Exemplo n.º 1
0
    def test_plot_influence(self):
        infl = self.res.get_influence()
        fig = influence_plot(self.res)
        assert_equal(isinstance(fig, plt.Figure), True)
        # test that we have the correct criterion for sizes #3103
        try:
            sizes = fig.axes[0].get_children()[0]._sizes
            ex = sm.add_constant(infl.cooks_distance[0])
            ssr = sm.OLS(sizes, ex).fit().ssr
            assert_array_less(ssr, 1e-12)
        except AttributeError:
            import warnings
            warnings.warn('test not compatible with matplotlib version')
        plt.close(fig)

        fig = influence_plot(self.res, criterion='DFFITS')
        assert_equal(isinstance(fig, plt.Figure), True)
        try:
            sizes = fig.axes[0].get_children()[0]._sizes
            ex = sm.add_constant(np.abs(infl.dffits[0]))
            ssr = sm.OLS(sizes, ex).fit().ssr
            assert_array_less(ssr, 1e-12)
        except AttributeError:
            pass
        plt.close(fig)

        assert_raises(ValueError,
                      influence_plot,
                      self.res,
                      criterion='unknown')
Exemplo n.º 2
0
def test_growth(cosmo=None):
    if cosmo is None:
        cosmo = cosmo_wmap_5()
    print "Comparing growth factor with calculations from http://icosmo.org/"

    # load external distance calculations
    # z D
    growth_file = os.path.dirname(os.path.abspath(__file__))
    growth_file = os.path.join(growth_file, 'icosmo_testdata', 'growth.txt')
    ic_growth = numpy.loadtxt(growth_file)

    z = ic_growth[:,0]

    cp_growth = cp.fgrowth(z, cosmo['omega_M_0'])

    label = r"$D(z)$"
    pylab.figure()
    pylab.plot(z, ic_growth[:,1], 
               label=label + ' IC', ls=':')
    pylab.plot(z, cp_growth, label=label + ' perturbation.py', ls='-')
    pylab.legend(loc='best')

    pylab.figure()
    diff = (ic_growth[:,1] - cp_growth) / ic_growth[:,1]

    maxdiff = numpy.max(numpy.abs(diff))
    print "Maximum fraction difference in %s is %e." % (label,
                                                        maxdiff)
    pylab.plot(z,
               diff, 
               label=label, ls='-')
    pylab.legend(loc='best')

    ntest.assert_array_less(numpy.abs(diff), 5e-3)
    def test_plot_influence(self, close_figures):
        infl = self.res.get_influence()
        fig = influence_plot(self.res)
        assert_equal(isinstance(fig, plt.Figure), True)
        # test that we have the correct criterion for sizes #3103
        try:
            sizes = fig.axes[0].get_children()[0]._sizes
            ex = sm.add_constant(infl.cooks_distance[0])
            ssr = sm.OLS(sizes, ex).fit().ssr
            assert_array_less(ssr, 1e-12)
        except AttributeError:
            import warnings
            warnings.warn('test not compatible with matplotlib version')

        fig = influence_plot(self.res, criterion='DFFITS')
        assert_equal(isinstance(fig, plt.Figure), True)
        try:
            sizes = fig.axes[0].get_children()[0]._sizes
            ex = sm.add_constant(np.abs(infl.dffits[0]))
            ssr = sm.OLS(sizes, ex).fit().ssr
            assert_array_less(ssr, 1e-12)
        except AttributeError:
            pass

        assert_raises(ValueError, influence_plot, self.res, criterion='unknown')
Exemplo n.º 4
0
def test_age():
    """Test integrated age against analytical age."""
    z = numpy.arange(0, 10.0, 0.05)

    cosmo = {}
    cosmo['omega_M_0'] = numpy.array([[0.99],[0.01],[0.3]])
    cosmo['omega_lambda_0'] = 1. - cosmo['omega_M_0']
    cosmo['h'] = 0.7
    cd.set_omega_k_0(cosmo)

    linestyle = ['-', ':', '--']

    gyr = 1e9 * cc.yr_s

    tl = cd.lookback_time(z, **cosmo)
    age = cd.age(z, **cosmo)
    age_ana = cd.age_flat(z, **cosmo)

    pylab.figure(figsize=(6,6))
    for i in range(len(linestyle)):
        pylab.plot(z, (tl/gyr)[i], ls=linestyle[i], color='0.5')
        pylab.plot(z, (age/gyr)[i], ls=linestyle[i], color='r')
        pylab.plot(z, (age_ana/gyr)[i], ls=linestyle[i], color='k')
    pylab.xlabel("redshift z")
    pylab.ylabel(r"age $t_L/$Gyr")

    pylab.figure(figsize=(6,6))
    for i in range(len(linestyle)):
        pylab.plot(z, ((age - age_ana)/age_ana)[i], ls=linestyle[i], 
                   color='k')
        # Make sure errors are small:
        ntest.assert_array_less((numpy.abs((age - age_ana)/age_ana)[i]),
                                3e-13)
    pylab.xlabel("redshift z")
    pylab.ylabel(r"age: (integral - analytical)/analytical")
Exemplo n.º 5
0
def test_attenuation(fiber_layout):
    """Should fail if the output power not less than initial pulse."""
    outputs = fiber_layout(gssn_1_ch, True, False, False, False, False, False)
    in_temporal_power = outputs[0]
    out_temporal_power = outputs[4]
    for i in range(len(out_temporal_power)):
        assert_array_less(out_temporal_power[i], in_temporal_power)
Exemplo n.º 6
0
def test_GBL_tau_inst():
    """Test match between analytical and numerical tau with instant
    reionization.

    Also makes a plot reproducing figure 1 of arXiv:astro-ph/9812125v3.
    """
    dz = 0.05
    z = numpy.arange(0., 80. + 1.5 * dz, dz)

    # Fully ionized H and He
    x_ionH = 1.0
    x_ionHe = 2.0

    cosmo = {}
    cosmo['omega_M_0'] = numpy.array([[0.3], [0.6], [1.0]])
    cosmo['omega_lambda_0'] = 1. - cosmo['omega_M_0']
    cosmo['h'] = 0.65
    cosmo['omega_b_0'] = 0.02 / cosmo['h']**2.
    cosmo['Y_He'] = 0.24
    cd.set_omega_k_0(cosmo)

    tau_inst = cr.optical_depth_instant(z,
                                        x_ionH=x_ionH,
                                        x_ionHe=x_ionHe,
                                        **cosmo)
    tau_int = cr.integrate_optical_depth(x_ionH, x_ionHe, z, **cosmo)

    linestyle = ['-', ':', '--']

    pylab.figure()
    pylab.subplot(2, 1, 1)
    pylab.title("Compare to GB&L fig. 1 (astro-ph/9812125v3.)")
    for i in range(len(linestyle)):
        pylab.plot(z, tau_inst[i], ls=linestyle[i], color='b')
        pylab.plot(z, tau_int[i], ls=linestyle[i], color='r')

    pylab.xlim(0, 80)
    pylab.ylim(0, 1)
    pylab.xlabel(r"$\mathrm{z_{ion}}$")
    pylab.ylabel(r"$\tau$")

    pylab.subplot(2, 1, 2)
    for i in range(len(linestyle)):
        pylab.plot(z,
                   1.e4 * (tau_int[i] - tau_inst[i]) / tau_inst[i],
                   ls=linestyle[i],
                   color='k')
        diff = (tau_int[i] - tau_inst[i]) / tau_inst[i]
        diff[numpy.isnan(diff)] = 0.0
        print("max fractional error in num. int. = %.3g" %
              numpy.max(numpy.abs(diff)))
        ntest.assert_array_less(numpy.abs(diff),
                                numpy.zeros(diff.shape) + 2.e-4)

    pylab.xlim(0, 40)
    pylab.xlabel(r"$\mathrm{z_{ion}}$")
    pylab.ylabel(r"$\mathrm{10^4 \times (num.\tau - ana.\tau)/ana.\tau}$")
def test_GBL_tau_inst():
    """Test match between analytical and numerical tau with instant
    reionization.

    Also makes a plot reproducing figure 1 of arXiv:astro-ph/9812125v3.
    """
    dz = 0.05
    z = numpy.arange(0., 80. + 1.5*dz, dz)

    # Fully ionized H and He
    x_ionH = 1.0
    x_ionHe = 2.0

    cosmo = {}
    cosmo['omega_M_0'] = numpy.array([[0.3],[0.6],[1.0]])
    cosmo['omega_lambda_0'] = 1. - cosmo['omega_M_0']
    cosmo['h'] = 0.65
    cosmo['omega_b_0'] = 0.02 / cosmo['h']**2.
    cosmo['Y_He'] = 0.24
    cd.set_omega_k_0(cosmo)

    tau_inst = cr.optical_depth_instant(z, x_ionH=x_ionH, x_ionHe=x_ionHe, 
                                        **cosmo)
    tau_int = cr.integrate_optical_depth(x_ionH, x_ionHe, z, **cosmo)

    linestyle = ['-', ':', '--']
    
    pylab.figure()
    pylab.subplot(2,1,1)
    pylab.title("Compare to GB&L fig. 1 (astro-ph/9812125v3.)")
    for i in range(len(linestyle)):
        pylab.plot(z, tau_inst[i], ls=linestyle[i], color='b')
        pylab.plot(z, tau_int[i], ls=linestyle[i], color='r')

    pylab.xlim(0,80)
    pylab.ylim(0,1)
    pylab.xlabel(r"$\mathrm{z_{ion}}$")
    pylab.ylabel(r"$\tau$")
    
    pylab.subplot(2,1,2)
    for i in range(len(linestyle)):
        pylab.plot(z, 
                   1.e4 * (tau_int[i] - tau_inst[i])/tau_inst[i], 
                   ls=linestyle[i], color='k')
        diff = (tau_int[i] - tau_inst[i]) / tau_inst[i]
        diff[numpy.isnan(diff)] = 0.0
        print ("max fractional error in num. int. = %.3g" % 
               numpy.max(numpy.abs(diff))
               )
        ntest.assert_array_less(numpy.abs(diff), 
                                numpy.zeros(diff.shape) + 2.e-4)

    pylab.xlim(0,40)
    pylab.xlabel(r"$\mathrm{z_{ion}}$")
    pylab.ylabel(r"$\mathrm{10^4 \times (num.\tau - ana.\tau)/ana.\tau}$")
Exemplo n.º 8
0
def test_kwta_presentation():
    """Tests one kwta presentation to half of the units, followed by
    another presentation to the second half."""
    s = InputSample(8, 8, [[1] * 8] * 4 + [[0] * 8] * 4)
    kwta_presentation(Tns.p2, Tns.p1, s, 2)
    assert get_current_time() == 2
    rates = get_rate_encoder(Tns.p1).get_rates()
    assert_array_less(rates[4:8], rates[0:4])
    s = InputSample(8, 8, [[0] * 8] * 4 + [[1] * 8] * 4)
    kwta_presentation(Tns.p2, Tns.p1, s, 2)
    assert get_current_time() == 4
    rates = get_rate_encoder(Tns.p1).get_rates()
    assert_array_less(rates[0:4], rates[4:8])
Exemplo n.º 9
0
def test_kwta_presentation():
    """Tests one kwta presentation to half of the units, followed by
    another presentation to the second half."""
    s = InputSample(8, 8, [[1] * 8] * 4 + [[0] * 8] * 4)
    kwta_presentation(Tns.p2, Tns.p1, s, 2)
    assert get_current_time() == 2
    rates = get_rate_encoder(Tns.p1).get_rates()
    assert_array_less(rates[4:8], rates[0:4])
    s = InputSample(8, 8, [[0] * 8] * 4 + [[1] * 8] * 4)
    kwta_presentation(Tns.p2, Tns.p1, s, 2)
    assert get_current_time() == 4
    rates = get_rate_encoder(Tns.p1).get_rates()
    assert_array_less(rates[0:4], rates[4:8])
Exemplo n.º 10
0
def test_conversion(lifetime_function):
    """Tests conversion of mass into lifetime and back. Note that this
    test is not passed right now because of the numerical
    discontinuties in the lifetime functions where their different
    segments meet up."""
    print lifetime_function.__name__
    import numpy.testing.utils as ntest
    mass = numpy.arange(0., 200., 0.1)
    time_from_mass = lifetime_function(mass)
    mass_from_time_func = \
                       mass_from_main_sequence_life_function(lifetime_function)
    mass_from_time_from_mass = mass_from_time_func(time_from_mass)

    frac_diff = (mass_from_time_from_mass-mass)/mass

    pylab.subplot(221)
    pylab.plot(mass, mass_from_time_from_mass)

    pylab.subplot(222)
    pylab.plot(mass, time_from_mass, label=lifetime_function.__name__)
    pylab.yscale('log')
    pylab.legend(loc='best')

    pylab.subplot(223)
    pylab.plot(mass, frac_diff)

    goodmask = numpy.ones(len(time_from_mass), dtype=numpy.bool)
    if hasattr(lifetime_function, 'minlife'):
        goodmask[time_from_mass <= lifetime_function.minlife] = False
    if hasattr(lifetime_function, 'maxlife'):
        goodmask[time_from_mass >= lifetime_function.maxlife] = False

    goodmask[numpy.logical_not(numpy.isfinite(time_from_mass))] = False

    print "Max frac. diff: ",
    print numpy.nanmax(numpy.abs(frac_diff[goodmask]))
    print "SKIPPING TEST THAT FAILS!!!!"
    if (False):
        threshold = 1e-9
        ntest.assert_array_less(numpy.abs(frac_diff[goodmask]),
                                threshold * numpy.ones(len(frac_diff[goodmask])),
                                err_msg='Error in mass recovery exceeds %s' %
                                threshold)
        print 'Mass recovery discrepency is below %s' % threshold
Exemplo n.º 11
0
def test_age():
    """Test integrated age against analytical age."""
    z = numpy.arange(0, 10.0, 0.05)

    cosmo = {}
    cosmo['omega_M_0'] = numpy.array([[0.99], [0.01], [0.3]])
    cosmo['omega_lambda_0'] = 1. - cosmo['omega_M_0']
    cosmo['h'] = 0.7
    cd.set_omega_k_0(cosmo)

    linestyle = ['-', ':', '--']

    gyr = 1e9 * cc.yr_s

    tl = cd.lookback_time(z, **cosmo)
    age = cd.age(z, **cosmo)
    age_ana = cd.age_flat(z, **cosmo)

    pylab.figure(figsize=(6, 6))
    for i in range(len(linestyle)):
        pylab.plot(z, (tl / gyr)[i], ls=linestyle[i], color='0.5')
        pylab.plot(z, (age / gyr)[i], ls=linestyle[i], color='r')
        pylab.plot(z, (age_ana / gyr)[i], ls=linestyle[i], color='k')
    pylab.xlabel("redshift z")
    pylab.ylabel(r"age $t_L/$Gyr")

    pylab.figure(figsize=(6, 6))
    for i in range(len(linestyle)):
        pylab.plot(z, ((age - age_ana) / age_ana)[i],
                   ls=linestyle[i],
                   color='k')
        # Make sure errors are small:
        ntest.assert_array_less((numpy.abs((age - age_ana) / age_ana)[i]),
                                3e-13)
    pylab.xlabel("redshift z")
    pylab.ylabel(r"age: (integral - analytical)/analytical")
Exemplo n.º 12
0
def test_interplay_dispersion_and_spm():
    """Should fail if (i) fwhm of temporal output powers for small
    N square number is greater than fwhm of initial pulse or (ii)
    fwhm of temporal output powers for big N square number is
    greater than initial fwhm in case of positive GVD and smaller
    than initial fwhm in case of negative GVD.

    Notes
    -----
    Test case::

    gssn ___ fiber

    """
    # Environment creation
    domain = Domain()
    lt = Layout(domain)
    dtime = domain.dtime
    fwhms_pos_gvd = []
    fwhms_neg_gvd = []
    time_pos_gvd = []
    time_neg_gvd = []
    nlse_method = "ssfm_symmetric"
    # Make sure to have a positive GVD to pass the test
    gssn = Gaussian(channels=1, peak_power=[1.0], center_lambda=[1030.])
    flag = True
    for i in range(1, 5):
        if (i == 4):
            flag = False
        fiber = Fiber(length=1.0,
                      nlse_method=nlse_method,
                      alpha=[0.46],
                      gamma=2.0,
                      nl_approx=flag,
                      ATT=False,
                      DISP=True,
                      SPM=True,
                      SS=False,
                      RS=False,
                      steps=1000,
                      save=True,
                      approx_type=i,
                      beta=[1e5, 1e3, 20.0])
        lt.add_link(gssn[0], fiber[0])
        lt.run(gssn)
        lt.reset()
        time_pos_gvd.append(fiber[1][0].time)
        fwhms_pos_gvd.append(fwhm(temporal_power(fiber[1][0].channels), dtime))
    flag = True
    for i in range(1, 5):
        if (i == 4):
            flag = False
        fiber = Fiber(length=1.0,
                      nlse_method=nlse_method,
                      alpha=[0.46],
                      gamma=2.0,
                      nl_approx=flag,
                      ATT=False,
                      DISP=True,
                      SPM=True,
                      SS=False,
                      RS=False,
                      steps=1000,
                      save=True,
                      approx_type=i,
                      beta=[1e5, 1e3, -20.0])
        lt.add_link(gssn[0], fiber[0])
        lt.run(gssn)
        lt.reset()
        time_neg_gvd.append(fiber[1][0].time)
        fwhms_neg_gvd.append(fwhm(temporal_power(fiber[1][0].channels), dtime))
    fwhm_temporal_gssn = fwhm(temporal_power(gssn[0][0].channels), dtime)
    time_gssn = gssn[0][0].time
    # Testing
    for i in range(len(fwhms_neg_gvd)):
        assert_array_less(time_gssn, time_pos_gvd[i])
        assert_array_less(time_gssn, time_neg_gvd[i])
        assert fwhm_temporal_gssn[0] < fwhms_pos_gvd[i][0]
        assert fwhms_neg_gvd[i][0] < fwhm_temporal_gssn[0]
Exemplo n.º 13
0
def assert_cosine_similarity(x, y, atol=1e-6):
    x_normalized = normalize_vector_to_unit_length(x)
    y_normalized = normalize_vector_to_unit_length(y)
    distance = 1 - np.abs(vector_H_vector(x_normalized, y_normalized))**2
    assert_array_less(distance, atol)