예제 #1
0
def test_z_and_a(modeling_data, cosmo_init):
    """ Unit tests abstract class z and a methdods """

    cosmo = theo.Cosmology()

    z = np.linspace(0.0, 10.0, 1000)

    assert_raises(ValueError, cosmo._get_a_from_z, z - 1.0)

    a = cosmo._get_a_from_z(z)

    assert_raises(ValueError, cosmo._get_z_from_a, a * 2.0)

    z_cpy = cosmo._get_z_from_a(a)

    assert_allclose(z_cpy, z, **TOLERANCE)

    a_cpy = cosmo._get_a_from_z(z_cpy)

    assert_allclose(a_cpy, a, **TOLERANCE)

    # Convert from a to z - scalar, list, ndarray
    assert_allclose(cosmo._get_a_from_z(0.5), 2. / 3., **TOLERANCE)
    assert_allclose(cosmo._get_a_from_z([0.1, 0.2, 0.3, 0.4]),
                    [10. / 11., 5. / 6., 10. / 13., 5. / 7.], **TOLERANCE)
    assert_allclose(cosmo._get_a_from_z(np.array([0.1, 0.2, 0.3, 0.4])),
                    np.array([10. / 11., 5. / 6., 10. / 13., 5. / 7.]),
                    **TOLERANCE)

    # Convert from z to a - scalar, list, ndarray
    assert_allclose(cosmo._get_z_from_a(2. / 3.), 0.5, **TOLERANCE)
    assert_allclose(
        cosmo._get_z_from_a([10. / 11., 5. / 6., 10. / 13., 5. / 7.]),
        [0.1, 0.2, 0.3, 0.4], **TOLERANCE)
    assert_allclose(
        cosmo._get_z_from_a(np.array([10. / 11., 5. / 6.,
                                      10. / 13., 5. / 7.])),
        np.array([0.1, 0.2, 0.3, 0.4]), **TOLERANCE)

    # Some potential corner-cases for the two funcs
    assert_allclose(cosmo._get_a_from_z(np.array([0.0, 1300.])),
                    np.array([1.0, 1. / 1301.]), **TOLERANCE)
    assert_allclose(cosmo._get_z_from_a(np.array([1.0, 1. / 1301.])),
                    np.array([0.0, 1300.]), **TOLERANCE)

    # Test for exceptions when outside of domains
    assert_raises(ValueError, cosmo._get_a_from_z, -5.0)
    assert_raises(ValueError, cosmo._get_a_from_z, [-5.0, 5.0])
    assert_raises(ValueError, cosmo._get_a_from_z, np.array([-5.0, 5.0]))
    assert_raises(ValueError, cosmo._get_z_from_a, 5.0)
    assert_raises(ValueError, cosmo._get_z_from_a, [-5.0, 5.0])
    assert_raises(ValueError, cosmo._get_z_from_a, np.array([-5.0, 5.0]))

    # Convert from a to z to a (and vice versa)
    testval = 0.5
    assert_allclose(cosmo._get_a_from_z(cosmo._get_z_from_a(testval)), testval,
                    **TOLERANCE)
    assert_allclose(cosmo._get_z_from_a(cosmo._get_a_from_z(testval)), testval,
                    **TOLERANCE)
예제 #2
0
def test_cosmo_basic(modeling_data, cosmo_init):
    """ Unit tests abstract class z and a methdods """
    reltol = modeling_data['cosmo_reltol']
    cosmo = theo.Cosmology(**cosmo_init)
    # Test get_<PAR>(z)
    Omega_m0 = cosmo['Omega_m0']
    assert_allclose(cosmo.get_Omega_m(0.0), Omega_m0, **TOLERANCE)
    assert_allclose(cosmo.get_E2Omega_m(0.0), Omega_m0, **TOLERANCE)
    # Test getting all parameters
    for param in ("Omega_m0", "Omega_b0", "Omega_dm0", "Omega_k0", 'h', 'H0'):
        cosmo[param]
    # Test params values
    for param in cosmo_init.keys():
        assert_allclose(cosmo_init[param], cosmo[param], **TOLERANCE)
    # Test for NumCosmo
    if cosmo.backend == 'nc':
        for param in ("Omega_b0", "Omega_dm0", "Omega_k0", 'h', 'H0'):
            cosmo[param] *= 1.01
        assert_raises(ValueError, cosmo._set_param, "nonexistent", 0.0)
        # Initializing a cosmology from a dist argument
        theo.Cosmology(dist=cosmo.dist)
    else:
        assert_raises(NotImplementedError, cosmo._set_param, "nonexistent",
                      0.0)
    # Test missing parameter
    assert_raises(ValueError, cosmo._get_param, "nonexistent")
    # Test da(z) = da12(0, z)
    z = np.linspace(0.0, 10.0, 1000)
    assert_allclose(cosmo.eval_da(z), cosmo.eval_da_z1z2(0.0, z), rtol=8.0e-15)
    assert_allclose(cosmo.eval_da_z1z2(0.0, z),
                    cosmo.eval_da_z1z2(0.0, z),
                    rtol=8.0e-15)
    # Test da(a1, a1)
    cosmo, testcase = load_validation_config()
    assert_allclose(cosmo.eval_da_a1a2(testcase['aexp_cluster']),
                    testcase['dl'], reltol)
    assert_allclose(cosmo.eval_da_a1a2(testcase['aexp_source']),
                    testcase['ds'], reltol)
    assert_allclose(
        cosmo.eval_da_a1a2(testcase['aexp_source'], testcase['aexp_cluster']),
        testcase['dsl'], reltol)

    # Test initializing cosmo
    test_cosmo = theo.Cosmology(be_cosmo=cosmo.be_cosmo)
예제 #3
0
def test_convert_rad_to_mpc():
    """ Test conversion between physical and angular units and vice-versa. """
    # Set some default values if I want them
    redshift = 0.25
    cosmo = theo.Cosmology(H0=70.0, Omega_dm0=0.3 - 0.045, Omega_b0=0.045)
    # Test basic conversions each way
    _rad2mpc_helper(0.003, redshift, cosmo, do_inverse=False)
    _rad2mpc_helper(1.0, redshift, cosmo, do_inverse=True)
    # Convert back and forth and make sure I get the same answer
    midtest = cosmo.rad2mpc(0.003, redshift)
    assert_allclose(cosmo.mpc2rad(midtest, redshift), 0.003, **TOLERANCE)
    # Test some different redshifts
    for onez in [0.1, 0.25, 0.5, 1.0, 2.0, 3.0]:
        _rad2mpc_helper(0.33, onez, cosmo, do_inverse=False)
        _rad2mpc_helper(1.0, onez, cosmo, do_inverse=True)
    # Test some different H0
    for oneh0 in [30., 50., 67.3, 74.7, 100.]:
        _rad2mpc_helper(0.33,
                        0.5,
                        theo.Cosmology(H0=oneh0,
                                       Omega_dm0=0.3 - 0.045,
                                       Omega_b0=0.045),
                        do_inverse=False)
        _rad2mpc_helper(1.0,
                        0.5,
                        theo.Cosmology(H0=oneh0,
                                       Omega_dm0=0.3 - 0.045,
                                       Omega_b0=0.045),
                        do_inverse=True)
    # Test some different Omega_M
    for oneomm in [0.1, 0.3, 0.5, 1.0]:
        _rad2mpc_helper(0.33,
                        0.5,
                        theo.Cosmology(H0=70.0,
                                       Omega_dm0=oneomm - 0.045,
                                       Omega_b0=0.045),
                        do_inverse=False)
        _rad2mpc_helper(1.0,
                        0.5,
                        theo.Cosmology(H0=70.0,
                                       Omega_dm0=oneomm - 0.045,
                                       Omega_b0=0.045),
                        do_inverse=True)
예제 #4
0
def load_validation_config():
    """ Loads values precomputed by numcosmo for comparison """
    numcosmo_path = 'tests/data/numcosmo/'
    with open(numcosmo_path + 'config.json', 'r') as fin:
        testcase = json.load(fin)
    numcosmo_profile = np.genfromtxt(numcosmo_path + 'radial_profiles.txt',
                                     names=True)
    # Cosmology
    cosmo = theo.Cosmology(H0=testcase['cosmo_H0'],
                           Omega_dm0=testcase['cosmo_Odm0'],
                           Omega_b0=testcase['cosmo_Ob0'])
    return cosmo, testcase
예제 #5
0
def load_validation_config():
    """ Loads values precomputed by numcosmo for comparison """
    numcosmo_path = 'tests/data/numcosmo/'
    with open(numcosmo_path+'config.json', 'r') as fin:
        testcase = json.load(fin)
    numcosmo_profile = np.genfromtxt(numcosmo_path+'radial_profiles.txt', names=True)

    # Physical Constants
    CLMM_SIGMAC_PCST = compute_sigmac_physical_constant(clc.CLIGHT_KMS.value,
                                                        clc.GNEWT.value,
                                                        clc.SOLAR_MASS.value,
                                                        clc.PC_TO_METER.value)
    testcase_SIGMAC_PCST = compute_sigmac_physical_constant(testcase['lightspeed[km/s]'],
                                                            testcase['G[m3/km.s2]'],
                                                            testcase['Msun[kg]'],
                                                            testcase['pc_to_m'])

    # Cosmology
    cosmo = theo.Cosmology(H0=testcase['cosmo_H0'], Omega_dm0=testcase['cosmo_Odm0'], Omega_b0=testcase['cosmo_Ob0'])

    # Sets of parameters to be used by multiple functions
    RHO_PARAMS = {
        'r3d': np.array(numcosmo_profile['r3d']),
        'mdelta':testcase['cluster_mass'],
        'cdelta':testcase['cluster_concentration'],
        'z_cl':testcase['z_cluster'],
        }
    SIGMA_PARAMS = {
        'r_proj': np.array(numcosmo_profile['r3d']),
        'mdelta':testcase['cluster_mass'],
        'cdelta':testcase['cluster_concentration'],
        'z_cl':testcase['z_cluster'],
        'delta_mdef':testcase['mass_Delta'],
        'halo_profile_model':testcase['density_profile_parametrization'],
        }
    GAMMA_PARAMS = {
        'r_proj': np.array(numcosmo_profile['r3d']),
        'mdelta': testcase['cluster_mass'],
        'cdelta': testcase['cluster_concentration'],
        'z_cluster': testcase['z_cluster'],
        'z_source': testcase['z_source'],
        'delta_mdef': testcase['mass_Delta'],
        'halo_profile_model': testcase['density_profile_parametrization'],
        'z_src_model': 'single_plane',
        }
    return {'TEST_CASE': testcase, 'z_source': testcase['z_source'],
            'cosmo': cosmo,
            'cosmo_pars': {k.replace('cosmo_', ''): v for k, v in testcase.items() if 'cosmo_' in k},
            'RHO_PARAMS': RHO_PARAMS, 'SIGMA_PARAMS': SIGMA_PARAMS, 'GAMMA_PARAMS': GAMMA_PARAMS,
            'numcosmo_profiles': numcosmo_profile, 'TEST_CASE_SIGMAC_PCST': testcase_SIGMAC_PCST,
            'CLMM_SIGMAC_PCST': CLMM_SIGMAC_PCST}
예제 #6
0
def helper_profiles(func):
    """ A helper function to repeat a set of unit tests on several functions
    that expect the same inputs.

    Tests the following functions: get_3d_density, predict_surface_density,
                                   predict_excess_surface_density

    Tests that the functions:
    1. Throw an error if an invalid profile model is passed
    2. Test each default parameter to ensure that the defaults are not changed.
    """
    # Make some base objects
    r3d = np.logspace(-2, 2, 100)
    mdelta = 1.0e15
    cdelta = 4.0
    z_cl = 0.2
    cclcosmo = theo.Cosmology(Omega_dm0=0.25, Omega_b0=0.05)

    # Fail vals
    assert_raises(ValueError, func, r3d, 0, cdelta, z_cl, cclcosmo, 200)
    assert_raises(ValueError, func, r3d, mdelta, 0, z_cl, cclcosmo, 200)
    # r<0
    assert_raises(ValueError, func, -1, mdelta, cdelta, z_cl, cclcosmo, 200)
    # r=0
    assert_raises(ValueError, func, 0, mdelta, cdelta, z_cl, cclcosmo, 200)
    # other profiles models are passed
    assert_raises(ValueError, func, r3d, mdelta, cdelta, z_cl, cclcosmo, 200, 'bleh')

    # Test defaults

    defaulttruth = func(r3d, mdelta, cdelta, z_cl, cclcosmo)
    assert_allclose(func(r3d, mdelta, cdelta, z_cl, cclcosmo, delta_mdef=200),
                    defaulttruth, **TOLERANCE)
    assert_allclose(func(r3d, mdelta, cdelta, z_cl, cclcosmo, halo_profile_model='nfw'),
                    defaulttruth, **TOLERANCE)
    assert_allclose(func(r3d, mdelta, cdelta, z_cl, cclcosmo, massdef='mean'),
                    defaulttruth, **TOLERANCE)
    # Test case fix
    assert_allclose(func(r3d, mdelta, cdelta, z_cl, cclcosmo, halo_profile_model='NFW'),
                    defaulttruth, **TOLERANCE)
    assert_allclose(func(r3d, mdelta, cdelta, z_cl, cclcosmo, massdef='MEAN'),
                    defaulttruth, **TOLERANCE)
예제 #7
0
def helper_physics_functions(func):
    """ A helper function to repeat a set of unit tests on several functions
    that expect the same inputs.

    Tests the following functions: predict_tangential_shear, predict_convergence,
                                   predict_reduced_tangential_shear

    Tests that the functions:
    1. Test each default parameter to ensure that the defaults are not changed.
    2. Test that exceptions are thrown for unsupported zsource models and profiles
    """
    # Make some base objects
    rproj = np.logspace(-2, 2, 100)
    mdelta = 1.0e15
    cdelta = 4.0
    z_cl = 0.2
    z_src = 0.45
    cosmo = theo.Cosmology(Omega_dm0=0.25, Omega_b0=0.05, H0=70.0)

    # Test defaults

    defaulttruth = func(rproj, mdelta, cdelta, z_cl, z_src, cosmo, delta_mdef=200,
                        halo_profile_model='nfw', z_src_model='single_plane')
    assert_allclose(func(rproj, mdelta, cdelta, z_cl, z_src, cosmo, halo_profile_model='nfw',
                         z_src_model='single_plane'), defaulttruth, **TOLERANCE)
    assert_allclose(func(rproj, mdelta, cdelta, z_cl, z_src, cosmo, delta_mdef=200,
                         z_src_model='single_plane'), defaulttruth, **TOLERANCE)
    assert_allclose(func(rproj, mdelta, cdelta, z_cl, z_src, cosmo, delta_mdef=200,
                         halo_profile_model='nfw'), defaulttruth, **TOLERANCE)

    # Test for exception on unsupported z_src_model and halo profiles
    assert_raises(ValueError, func, rproj, mdelta, cdelta, z_cl, z_src, cosmo,
        delta_mdef=200, halo_profile_model='blah', massdef='mean', z_src_model='single_plane')
    assert_raises(ValueError, func, rproj, mdelta, cdelta, z_cl, z_src, cosmo,
        delta_mdef=200, halo_profile_model='nfw', massdef='blah', z_src_model='single_plane')
    assert_raises(ValueError, func, rproj, mdelta, cdelta, z_cl, z_src, cosmo,
        delta_mdef=200, halo_profile_model='nfw', massdef='mean', z_src_model='blah')
예제 #8
0
def test_convert_units():
    """ Test the wrapper function to convert units. Corner cases should be tested in the
    individual functions. This function should test one case for all supported conversions
    and the error handling.
    """
    # Make an astropy cosmology object for testing
    #   cosmo = FlatLambdaCDM(H0=70., Om0=0.3)
    cosmo = md.Cosmology(H0=70.0, Omega_dm0=0.3 - 0.045, Omega_b0=0.045)

    # Test that each unit is supported
    utils.convert_units(1.0, 'radians', 'degrees')
    utils.convert_units(1.0, 'arcmin', 'arcsec')
    utils.convert_units(1.0, 'Mpc', 'kpc')
    utils.convert_units(1.0, 'Mpc', 'kpc')

    # Error checking
    assert_raises(ValueError, utils.convert_units, 1.0, 'radians', 'CRAZY')
    assert_raises(ValueError, utils.convert_units, 1.0, 'CRAZY', 'radians')
    assert_raises(TypeError, utils.convert_units, 1.0, 'arcsec', 'Mpc')
    assert_raises(TypeError, utils.convert_units, 1.0, 'arcsec', 'Mpc', None,
                  cosmo)
    assert_raises(TypeError, utils.convert_units, 1.0, 'arcsec', 'Mpc', 0.5,
                  None)
    assert_raises(ValueError, utils.convert_units, 1.0, 'arcsec', 'Mpc', -0.5,
                  cosmo)

    # Test cases to make sure angular -> angular is fitting together
    assert_allclose(utils.convert_units(np.pi, 'radians', 'degrees'), 180.,
                    **TOLERANCE)
    assert_allclose(utils.convert_units(180.0, 'degrees', 'radians'), np.pi,
                    **TOLERANCE)
    assert_allclose(utils.convert_units(1.0, 'degrees', 'arcmin'), 60.,
                    **TOLERANCE)
    assert_allclose(utils.convert_units(1.0, 'degrees', 'arcsec'), 3600.,
                    **TOLERANCE)

    # Test cases to make sure physical -> physical is fitting together
    assert_allclose(utils.convert_units(1.0, 'Mpc', 'kpc'), 1.0e3, **TOLERANCE)
    assert_allclose(utils.convert_units(1000., 'kpc', 'Mpc'), 1.0, **TOLERANCE)
    assert_allclose(utils.convert_units(1.0, 'Mpc', 'pc'), 1.0e6, **TOLERANCE)

    # Test conversion from angular to physical
    # Using astropy, circular now but this will be fine since we are going to be
    # swapping to CCL soon and then its kosher
    r_arcmin, redshift = 20.0, 0.5
    d_a = cosmo.eval_da(redshift) * 1.e3  #kpc
    truth = r_arcmin * (1.0 / 60.0) * (np.pi / 180.0) * d_a
    assert_allclose(
        utils.convert_units(r_arcmin, 'arcmin', 'kpc', redshift, cosmo), truth,
        **TOLERANCE)

    # Test conversion both ways between angular and physical units
    # Using astropy, circular now but this will be fine since we are going to be
    # swapping to CCL soon and then its kosher
    r_kpc, redshift = 20.0, 0.5
    #    d_a = cosmo.angular_diameter_distance(redshift).to('kpc').value
    d_a = cosmo.eval_da(redshift) * 1.e3  #kpc
    truth = r_kpc * (1.0 / d_a) * (180. / np.pi) * 60.
    assert_allclose(
        utils.convert_units(r_kpc, 'kpc', 'arcmin', redshift, cosmo), truth,
        **TOLERANCE)