def test_allclose_isclose(): a = [1, 2] * u.m b = [101, 201] * u.cm delta = 2 * u.cm assert u.allclose(a, b, atol=delta) assert np.all(u.isclose(a, b, atol=delta)) c = [90, 200] * u.cm assert not u.allclose(a, c) assert not np.all(u.isclose(a, c))
def __eq__(self, other): try: if self.ionic_symbol != other.ionic_symbol: return False ionic_fraction_within_tolerance = np.isclose( self.ionic_fraction, other.ionic_fraction, rtol=1e-15, ) number_density_within_tolerance = u.isclose( self.number_density, other.number_density, rtol=1e-15, ) return all([ ionic_fraction_within_tolerance, number_density_within_tolerance ]) except Exception as exc: raise TypeError( "Unable to ascertain equality between the following objects:\n" f" {self}\n" f" {other}") from exc
def test_u_comoving(self): """test u in the reference frame comoving with the blob""" assert u.isclose( 8.88373221e-10 * u.Unit("erg / cm3"), cmb_test.u(blob_test), atol=0 * u.Unit("erg / cm3"), rtol=1e-3, )
def test_u(self): """test u in the stationary reference frame""" assert u.isclose( 6.67945605e-12 * u.Unit("erg / cm3"), CMB_Z_1.u(), atol=0 * u.Unit("erg / cm3"), rtol=1e-3, )
def test_known1(self): """ Tests Fermi_integral for expected value. """ methodVal = _chemical_potential_interp(self.n_e, self.T) testTrue = u.isclose(methodVal, self.True1, rtol=1e-16, atol=0.0) errStr = f"Chemical potential value should be {self.True1} and not {methodVal}." assert testTrue, errStr
def test_redden(self): s = Star() s._description = 'Test star spectrum' S = SpectralGradient(14 * u.percent / hundred_nm, wave0=0.55 * u.um) s_r = s.redden(S) assert u.isclose(s_r(0.65 * u.um), 1.14 * u.W / (u.m**2 * u.um)) assert s_r.description == 'Test star spectrum reddened by {} at {}'. \ format(14 * u.percent / hundred_nm, 0.55 * u.um)
def test_particle_mass_equivalent_args(arg1, kwargs1, arg2, kwargs2, expected): """Test that `particle_mass` returns equivalent results for equivalent positional and keyword arguments.""" result1 = particle_mass(arg1, **kwargs1) result2 = particle_mass(arg2, **kwargs2) assert u.isclose(result1, result2), ( f"particle_mass({repr(arg1)}, **{kwargs1}) = {repr(result1)}, whereas " f"particle_mass({repr(arg2)}, **{kwargs2}) = {repr(result2)}. " f"These results are not equivalent as expected.") if expected is not None: assert u.isclose(result1, result2) and u.isclose(result2, expected), ( f"particle_mass({repr(arg1)}, **{kwargs1}) = {repr(result1)} and " f"particle_mass({repr(arg2)}, **{kwargs2}) = {repr(result2)}, but " f"these results are not equal to {repr(expected)} as expected.")
def test_u_comoving(self): """test u in the reference frame comoving with the blob""" assert u.isclose( 8.88373221e-10 * u.Unit("erg / cm3"), CMB_Z_1.u(PWL_BLOB), atol=0 * u.Unit("erg / cm3"), rtol=1e-3, )
def test_wobble_regions_finder(): center = SkyCoord(83.6333313, 21.51444435, unit="deg", frame="icrs") source_angle = 35 * u.deg on_region = CircleSkyRegion( center=center, radius=0.15 * u.deg, ) pointing = on_region.center.directional_offset_by( separation=0.4 * u.deg, position_angle=180 * u.deg + source_angle, ) assert u.isclose(pointing.position_angle(on_region.center).to(u.deg), source_angle, rtol=0.05) n_off_regions = 3 finder = WobbleRegionsFinder(n_off_regions) regions, _ = finder.run(on_region, pointing) assert len(regions) == 3 for i, off_region in enumerate(regions, start=1): assert u.isclose(pointing.separation(off_region.center), 0.4 * u.deg) expected = source_angle + 360 * u.deg * i / (n_off_regions + 1) assert u.isclose( pointing.position_angle(off_region.center).to(u.deg), expected.to(u.deg), rtol=0.001, ) # test with exclusion region pos = pointing.directional_offset_by( separation=0.4 * u.deg, position_angle=source_angle + 90 * u.deg, ) exclusion_region = CircleSkyRegion(pos, Angle(0.2, "deg")) geom = WcsGeom.create(skydir=pos, binsz=0.01, width=10.0) exclusion_mask = ~geom.region_mask([exclusion_region]) finder = WobbleRegionsFinder(n_off_regions) regions, _ = finder.run(on_region, pointing, exclusion_mask) assert len(regions) == 2
def test_from_norm_at_gamma_1(self): """test the intialisation of the powerlaw from the normalisation at gamma = 1""" norm = 1e-13 * u.Unit("cm-3") pwl = PowerLaw.from_norm_at_gamma_1(norm=norm, p=p_test, gamma_min=1, gamma_max=gamma_max_test) assert u.isclose(norm, pwl(1), atol=0 * u.Unit("cm-3"), rtol=1e-2)
def test_init(self): themis = HG12_Pen16(7.121 * u.mag, 0.68, radius=100 * u.km, wfb='V') assert themis._unit == 'mag' assert u.isclose(themis.radius, 100*u.km) assert isinstance(themis.H, Parameter) assert np.isclose(themis.H.value, 7.121) assert isinstance(themis.G12, Parameter) assert np.isclose(themis.G12.value, 0.68) assert themis.wfb == 'V'
def test_init(self): # initialize with numbers ceres = HG(3.34 * u.mag, 0.12, radius=480 * u.km, wfb='V') assert u.isclose(ceres.radius, 480 * u.km) assert isinstance(ceres.H, Parameter) assert np.isclose(ceres.H.value, 3.34) assert isinstance(ceres.G, Parameter) assert np.isclose(ceres.G.value, 0.12) assert ceres.wfb == 'V'
def test_customized_particles(cls, kwargs, attr, expected): """Test the attributes of dimensionless and custom particles.""" instance = cls(**kwargs) value = getattr(instance, attr) if not u.isclose(value, expected, equal_nan=True): pytest.fail( f"{call_string(cls, kwargs=kwargs)}.{attr} should return a value " f"of {expected}, but instead returned a value of {value}.")
def testTisserand(self): """ test tisserand method""" halley = Orbit.from_dict(HALLEY) jupiter = Orbit.from_dict(JUPITER) assert u.isclose(halley.tisserand(jupiter), u.Quantity(-0.61659744)) comets = Orbit.from_dict(COMETS) assert u.allclose(comets.tisserand(jupiter), u.Quantity([2.82130706, 2.79709686]))
def test_oo_propagate(self): """ test oo_propagate method""" orbit = Orbit.from_horizons('Ceres') epoch = Time(Time.now().jd + 100, format='jd', scale='utc') future_orbit = Orbit.from_horizons('Ceres', epochs=Time(epoch, format='jd', scale='utc').tdb) oo_orbit = orbit.oo_propagate(epoch) elements = ['a', 'e', 'i', 'Omega', 'w', 'M'] assert all([u.isclose(oo_orbit[k][0], future_orbit[k][0]) for k in elements]) assert u.isclose(oo_orbit['epoch'][0].utc.jd, future_orbit['epoch'][0].utc.jd) assert oo_orbit['epoch'].scale == 'utc'
def test_init(self): ceres = HG(3.34, 0.12, radius=480 * u.km, M_sun=-26.74) if LooseVersion(astropy.__version__) >= req_ver: assert u.isclose(ceres.radius, 480 * u.km) assert np.isclose(ceres.M_sun, -26.74) assert isinstance(ceres.H, Parameter) assert np.isclose(ceres.H.value, 3.34) assert isinstance(ceres.G, Parameter) assert np.isclose(ceres.G.value, 0.12)
def test_T(self): R_tilde = 10 R = 10 * R_G phi_expected = 0.225 # Eq. 64 [Dermer2009] T_expected = np.power( 3 * G * M_BH * M_DOT / (8 * np.pi * np.power(R, 3) * sigma_sb), 1 / 4).to("K") assert u.isclose(DISK.T(R_tilde), T_expected, atol=0 * u.K, rtol=1e-2)
def test_ref(self): linphase = LinearPhaseFunc(5, 2.29, radius=300) pha_test = np.linspace(0, np.pi, 10) ref_test = np.array([ 1.59389035e-02, 7.63333149e-03, 3.65569373e-03, 1.75075544e-03, 8.38457717e-04, 4.01547427e-04, 1.92305864e-04, 9.20975780e-05, 4.41066314e-05, 2.11231932e-05 ]) ref_norm_test = np.array([ 1., 0.47891196, 0.22935666, 0.10984165, 0.05260448, 0.02519291, 0.01206519, 0.00577816, 0.00276723, 0.00132526 ]) eph = linphase.to_ref(pha_test, append_results=True) assert np.isclose(eph['ref'], ref_test).all() assert np.isclose(eph['alpha'], pha_test).all() assert set(eph.field_names) == {'alpha', 'ref'} eph_norm = linphase.to_ref(pha_test, normalized=0, append_results=True) assert np.isclose(eph_norm['ref'], ref_norm_test).all() assert np.isclose(eph_norm['alpha'], pha_test).all() assert set(eph_norm.field_names) == {'alpha', 'ref'} linphase = LinearPhaseFunc(5 * u.mag, 0.04 * u.mag / u.deg, radius=300) pha_test = np.linspace(0, 180, 10) * u.deg eph = linphase.to_ref(pha_test, append_results=True) ref_test = np.array([ 1.59389035e-02, 7.62883887e-03, 3.65139185e-03, 1.74766602e-03, 8.36485548e-04, 4.00367155e-04, 1.91627768e-04, 9.17188165e-05, 4.38993856e-05, 2.10115670e-05 ]) / u.sr ref_norm_test = np.array([ 1., 0.47863009, 0.22908677, 0.10964782, 0.05248075, 0.02511886, 0.01202264, 0.0057544, 0.00275423, 0.00131826 ]) * u.dimensionless_unscaled if LooseVersion(astropy.__version__) >= req_ver: assert u.isclose(eph['ref'], ref_test).all() assert u.isclose(eph['alpha'], pha_test).all() assert set(eph.field_names) == {'alpha', 'ref'} eph_norm = linphase.to_ref(pha_test, normalized=0 * u.deg, append_results=True) if LooseVersion(astropy.__version__) >= req_ver: assert u.isclose(eph_norm['ref'], ref_norm_test).all() assert u.isclose(eph_norm['alpha'], pha_test).all() assert set(eph_norm.field_names) == {'alpha', 'ref'}
def test_Wigner_Seitz_radius(): """ Checks Wigner-Seitz radius for a known value. """ n_e = 1e23 * u.cm**-3 radiusTrue = 1.3365046175719772e-10 * u.m radiusMeth = Wigner_Seitz_radius(n_e) testTrue = u.isclose(radiusMeth, radiusTrue, rtol=1e-5) errStr = f"Error in Wigner_Seitz_radius(), got {radiusMeth}, should be {radiusTrue}" assert testTrue, errStr
def test_with_toy(): np.random.seed(42) geom = CameraGeometry.from_name('LSTCam') width = 0.03 * u.m length = 0.15 * u.m intensity = 500 xs = u.Quantity([0.5, 0.5, -0.5, -0.5], u.m) ys = u.Quantity([0.5, -0.5, 0.5, -0.5], u.m) psis = Angle([-90, -45, 0, 45, 90], unit='deg') for x, y in zip(xs, ys): for psi in psis: # make a toymodel shower model model = toymodel.Gaussian( x=x, y=y, width=width, length=length, psi=psi, ) image, signal, noise = model.generate_image( geom, intensity=intensity, nsb_level_pe=5, ) result = hillas_parameters(geom, signal) assert u.isclose(result.x, x, rtol=0.1) assert u.isclose(result.y, y, rtol=0.1) assert u.isclose(result.width, width, rtol=0.1) assert u.isclose(result.length, length, rtol=0.1) assert ((result.psi.to_value(u.deg) == approx(psi.deg, abs=2)) or abs(result.psi.to_value(u.deg) - psi.deg) == approx( 180.0, abs=2)) assert signal.sum() == result.intensity
def test_init(self): themis = HG12_Pen16(7.121 * u.mag, 0.68, radius=100 * u.km, wfb='V') assert themis._unit == 'mag' if LooseVersion(astropy.__version__) >= req_ver: assert u.isclose(themis.radius, 100 * u.km) assert isinstance(themis.H, Parameter) assert np.isclose(themis.H.value, 7.121) assert isinstance(themis.G12, Parameter) assert np.isclose(themis.G12.value, 0.68) assert themis.wfb == 'V'
def test_correlation_function_ellipticity(self): """Test correlation function calculation.""" expected_r = 4.395319409351799 * u.arcmin expected_xip = 0.001867305310370419 expected_xip_err = 0.0005348912968829396 cat = self.load_data() matches = GroupView.build(cat) ra = matches.aggregate(averageRaFromCat) * u.radian dec = matches.aggregate(averageDecFromCat) * u.radian e1_res = matches.aggregate(medianEllipticity1ResidualsFromCat) e2_res = matches.aggregate(medianEllipticity2ResidualsFromCat) result = correlation_function_ellipticity(ra, dec, e1_res, e2_res) self.assertTrue(u.isclose(np.mean(result[0]), expected_r)) self.assertTrue(u.isclose(np.mean(result[1]), expected_xip)) self.assertTrue(u.isclose(np.mean(result[2]), expected_xip_err))
def test_init(self): themis = HG12(7.121, 0.68, radius=100 * u.km, M_sun=-26.74) assert themis._unit == 'mag' if LooseVersion(astropy.__version__) >= req_ver: assert u.isclose(themis.radius, 100 * u.km) assert np.isclose(themis.M_sun, -26.74) assert isinstance(themis.H, Parameter) assert np.isclose(themis.H.value, 7.121) assert isinstance(themis.G12, Parameter) assert np.isclose(themis.G12.value, 0.68)
def test_telescope_separation(): from ctapipe.coordinates import TelescopeFrame telescope_pointing = SkyCoord(alt=70 * u.deg, az=0 * u.deg, frame=AltAz()) telescope_frame = TelescopeFrame(telescope_pointing=telescope_pointing) tel1 = SkyCoord(fov_lon=0 * u.deg, fov_lat=0 * u.deg, frame=telescope_frame) tel2 = SkyCoord(fov_lon=0 * u.deg, fov_lat=1 * u.deg, frame=telescope_frame) assert u.isclose(tel1.separation(tel2), 1 * u.deg)
def test_root_mean_square_particle(use_rms_charge, use_rms_mass): """ Test that ``ParticleList.average_particle`` returns the mean or root mean square of the charge and mass, as appropriate. """ particle_list = ParticleList(["p+", "e-"]) average_particle = particle_list.average_particle( use_rms_charge=use_rms_charge, use_rms_mass=use_rms_mass ) expected_average_charge = (1 if use_rms_charge else 0) * proton.charge assert u.isclose(average_particle.charge, expected_average_charge, rtol=1e-14) if use_rms_mass: expected_average_mass = np.sqrt((proton.mass**2 + electron.mass**2) / 2) else: expected_average_mass = (proton.mass + electron.mass) / 2 assert u.isclose(average_particle.mass, expected_average_mass, atol=1e-35 * u.kg)
def test_fail1(self): """ Tests if test_known1() would fail if we slightly adjusted the value comparison by some quantity close to numerical error. """ fail1 = self.True1 + 1e-15 methodVal = _chemical_potential_interp(self.n_e, self.T) testTrue = not u.isclose(methodVal, fail1, rtol=1e-16, atol=0.0) errStr = (f"Chemical potential value test gives {methodVal} " f"and should not be equal to {fail1}.") assert testTrue, errStr
def test_timescales(self): """ test with input in UTC scale """ orbit = Orbit.from_dict(CERES) orbit['epoch'] = orbit['epoch'].utc # transform to cart and back cart_orbit = orbit.oo_transform('CART') kep_orbit = cart_orbit.oo_transform('KEP') elements = ['a', 'e', 'i', 'Omega', 'w', 'M'] assert all([u.isclose(orbit[k][0], kep_orbit[k][0]) for k in elements]) assert u.isclose(orbit['epoch'][0].utc.jd, kep_orbit['epoch'][0].utc.jd) # transform to com and back com_orbit = orbit.oo_transform('COM') kep_orbit = com_orbit.oo_transform('KEP') assert all([u.isclose(orbit[k][0], kep_orbit[k][0]) for k in elements]) assert u.isclose(orbit['epoch'][0].utc.jd, kep_orbit['epoch'][0].utc.jd) assert kep_orbit['epoch'].scale == 'utc'
def test_Particle_class(arg, kwargs, expected_dict): """ Test that `~plasmapy.particles.Particle` objects for different subatomic particles, elements, isotopes, and ions return the expected properties. Provide a detailed error message that lists all of the inconsistencies with the expected results. """ call = call_string(Particle, arg, kwargs) errmsg = "" try: particle = Particle(arg, **kwargs) except Exception as exc: raise AtomicError(f"Problem creating {call}") from exc for key in expected_dict.keys(): expected = expected_dict[key] if inspect.isclass(expected) and issubclass(expected, Exception): # Exceptions are expected to be raised when accessing certain # attributes for some particles. For example, accessing a # neutrino's mass should raise a MissingAtomicDataError since # only upper limits of neutrino masses are presently available. # If expected_dict[key] is an exception, then check to make # sure that this exception is raised. try: with pytest.raises(expected): exec(f"particle.{key}") except pytest.fail.Exception: errmsg += f"\n{call}[{key}] does not raise {expected}." except Exception: errmsg += ( f"\n{call}[{key}] does not raise {expected} but " f"raises a different exception." ) else: try: result = eval(f"particle.{key}") assert result == expected or u.isclose(result, expected) except AssertionError: errmsg += ( f"\n{call}.{key} returns {result} instead " f"of the expected value of {expected}." ) except Exception: errmsg += f"\n{call}.{key} raises an unexpected exception." if len(errmsg) > 0: raise Exception(f"Problems with {call}:{errmsg}")
def test_stream_reader_defaults(self, raw, nstream): # Test not passing a sample rate and samples per frame to reader # (can't test reading, since the sample file is tiny). default_frame_rate = (100/6/2**22)*u.MHz with gsb.open(SAMPLE_PHASED_HEADER, 'rs', raw=raw) as fh_r: assert fh_r.sample_shape[-1] == 512 assert fh_r.payload_nbytes == 2**22 assert fh_r.samples_per_frame == nstream * 2**12 # 2**22 / 1024 assert u.isclose(fh_r.sample_rate, fh_r.samples_per_frame*default_frame_rate, rtol=2**-52)
def test_table_interpolation(): from pyirf.spectral import TableInterpolationSpectrum # log log energy = [1, 10, 100] * u.TeV flux = [50, 5, 0.5] / (u.GeV * u.m**2 * u.sr * u.s) spectrum = TableInterpolationSpectrum(energy, flux) assert u.isclose(spectrum(5 * u.TeV), 10 / (u.GeV * u.m**2 * u.sr * u.s)) # lin lin energy = [1, 2, 3] * u.TeV flux = [10, 8, 6] / (u.GeV * u.m**2 * u.sr * u.s) spectrum = TableInterpolationSpectrum(energy, flux, log_energy=False, log_flux=False) assert u.isclose(spectrum(1.5 * u.TeV), 9 / (u.GeV * u.m**2 * u.sr * u.s))
def test_from_normalised_energy_density(self): """test the intialisation of the power law from the total particle energy density""" u_e = 3e-4 * u.Unit("erg cm-3") pwl = PowerLaw.from_normalised_energy_density(u_e=u_e, p=p_test, gamma_min=gamma_min_test, gamma_max=gamma_max_test) # calculate u_e u_e_calc = mec2 * pwl.integral( gamma_low=gamma_min_test, gamma_up=gamma_max_test, gamma_power=1) assert u.isclose(u_e, u_e_calc, atol=0 * u.Unit("erg cm-3"), rtol=1e-2)
def test_allclose_isclose_default(a, b): assert u.allclose(a, b) assert np.all(u.isclose(a, b))