<commit_before># Licensed under a 3-clause BSD style license - see LICENSE.rst

import sys
import tempfile

import pytest
import numpy as np

from astropy.cosmology import core, funcs, realizations
from astropy.cosmology.realizations import Planck13, Planck15, Planck18, WMAP5, WMAP7, WMAP9
from astropy.units import allclose
from astropy import units as u
from astropy.utils.exceptions import AstropyUserWarning
from astropy.utils.compat.optional_deps import HAS_SCIPY  # noqa


@pytest.mark.skipif('not HAS_SCIPY')
def test_z_at_value():
    # These are tests of expected values, and hence have less precision
    # than the roundtrip tests below (test_z_at_value_roundtrip);
    # here we have to worry about the cosmological calculations
    # giving slightly different values on different architectures,
    # there we are checking internal consistency on the same architecture
    # and so can be more demanding
    z_at_value = funcs.z_at_value
    cosmo = Planck13
    assert allclose(z_at_value(cosmo.age, 2 * u.Gyr), 3.19812268, rtol=1e-6)
    assert allclose(z_at_value(cosmo.lookback_time, 7 * u.Gyr), 0.795198375, rtol=1e-6)
    assert allclose(z_at_value(cosmo.distmod, 46 * u.mag), 1.991389168, rtol=1e-6)
    assert allclose(z_at_value(cosmo.luminosity_distance, 1e4 * u.Mpc), 1.36857907, rtol=1e-6)
    assert allclose(z_at_value(cosmo.luminosity_distance, 26.037193804 * u.Gpc, ztol=1e-10),
                    3, rtol=1e-9)
    assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500*u.Mpc, zmax=2),
                    0.681277696, rtol=1e-6)
    assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500*u.Mpc, zmin=2.5),
                    3.7914908, rtol=1e-6)

    # test behavior when the solution is outside z limits (should
    # raise a CosmologyError)
    with pytest.raises(core.CosmologyError):
        with pytest.warns(AstropyUserWarning, match=r'fval is not bracketed'):
            z_at_value(cosmo.angular_diameter_distance, 1500*u.Mpc, zmax=0.5)

    with pytest.raises(core.CosmologyError):
        with pytest.warns(AstropyUserWarning, match=r'fval is not bracketed'):
            z_at_value(cosmo.angular_diameter_distance, 1500*u.Mpc, zmin=4.)

    # Test the "verbose" flag. Since this uses "print", ned to mod stdout
    original_stdout = sys.stdout
    with tempfile.NamedTemporaryFile(mode="w") as f:
        try:  # protect stdout with a "finally"
            sys.stdout = f # Change the standard output to the tempfile
        except Exception:  # error normally
            raise
        else:
            resx = z_at_value(cosmo.age, 2 * u.Gyr, verbose=True)
        finally:
            sys.stdout = original_stdout # reset the standard output

        f.flush()  # move print from buffer to file
        with open(f.name) as ff:  # read file
            assert str(resx) in ff.read()  # test that "verbose" prints res


@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('method', ['Brent', 'Golden', 'Bounded'])
def test_z_at_value_bracketed(method):
    """
    Test 2 solutions for angular diameter distance by not constraining zmin, zmax,
    but setting `bracket` on the appropriate side of the turning point z.
    Setting zmin / zmax should override `bracket`.<commit_msg>adapt to Windows I/O issues on open files<commit_after># Licensed under a 3-clause BSD style license - see LICENSE.rst

import sys
import tempfile

import pytest
import numpy as np

from astropy.cosmology import core, funcs, realizations
from astropy.cosmology.realizations import Planck13, Planck15, Planck18, WMAP5, WMAP7, WMAP9
from astropy.units import allclose
from astropy import units as u
from astropy.utils.exceptions import AstropyUserWarning
from astropy.utils.compat.optional_deps import HAS_SCIPY  # noqa


@pytest.mark.skipif('not HAS_SCIPY')
def test_z_at_value():
    # These are tests of expected values, and hence have less precision
    # than the roundtrip tests below (test_z_at_value_roundtrip);
    # here we have to worry about the cosmological calculations
    # giving slightly different values on different architectures,
    # there we are checking internal consistency on the same architecture
    # and so can be more demanding
    z_at_value = funcs.z_at_value
    cosmo = Planck13
    assert allclose(z_at_value(cosmo.age, 2 * u.Gyr), 3.19812268, rtol=1e-6)
    assert allclose(z_at_value(cosmo.lookback_time, 7 * u.Gyr), 0.795198375, rtol=1e-6)
    assert allclose(z_at_value(cosmo.distmod, 46 * u.mag), 1.991389168, rtol=1e-6)
    assert allclose(z_at_value(cosmo.luminosity_distance, 1e4 * u.Mpc), 1.36857907, rtol=1e-6)
    assert allclose(z_at_value(cosmo.luminosity_distance, 26.037193804 * u.Gpc, ztol=1e-10),
                    3, rtol=1e-9)
    assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500*u.Mpc, zmax=2),
                    0.681277696, rtol=1e-6)
    assert allclose(z_at_value(cosmo.angular_diameter_distance, 1500*u.Mpc, zmin=2.5),
                    3.7914908, rtol=1e-6)

    # test behavior when the solution is outside z limits (should
    # raise a CosmologyError)
    with pytest.raises(core.CosmologyError):
        with pytest.warns(AstropyUserWarning, match=r'fval is not bracketed'):
            z_at_value(cosmo.angular_diameter_distance, 1500*u.Mpc, zmax=0.5)

    with pytest.raises(core.CosmologyError):
        with pytest.warns(AstropyUserWarning, match=r'fval is not bracketed'):
            z_at_value(cosmo.angular_diameter_distance, 1500*u.Mpc, zmin=4.)

    # Test the "verbose" flag. Since this uses "print", ned to mod stdout
    # Windows has issues with reading from opened NamedTemporaryFiles,
    # so this test is run inside a NamedTemporaryDirectory with normal files.
    original_stdout = sys.stdout
    with tempfile.TemporaryDirectory() as d:
        fname = d + "/tempfile.txt"
        with open(fname, "w") as f:
            try:  # protect stdout with a "finally"
                sys.stdout = f # Change the standard output to the tempfile
            except Exception:  # error normally
                raise
            else:
                resx = z_at_value(cosmo.age, 2 * u.Gyr, verbose=True)
            finally:
                sys.stdout = original_stdout # reset the standard output

        with open(fname, "r") as f:  # read file
            assert str(resx) in f.read()  # test that "verbose" prints res


@pytest.mark.skipif('not HAS_SCIPY')
@pytest.mark.parametrize('method', ['Brent', 'Golden', 'Bounded'])
def test_z_at_value_bracketed(method):
    """
    Test 2 solutions for angular diameter distance by not constraining zmin, zmax,
    but setting `bracket` on the appropriate side of the turning point z.
    Setting zmin / zmax should override `bracket`.
{'fraction_non_alphanumeric': 0.08814364148983529, 'fraction_numerical': 0.037691052084879065, 'mean_word_length': 3.351194318915429, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '113454', 'n_tokens_mistral': 2410, 'n_tokens_neox': 2194, 'n_words': 627}