def test_comparisons(): """ Test numpy ufunc comparison operators for unit consistency. """ from yt.units.yt_array import YTArray a1 = YTArray([1, 2, 3], 'cm') a2 = YTArray([2, 1, 3], 'cm') a3 = YTArray([.02, .01, .03], 'm') ops = (np.less, np.less_equal, np.greater, np.greater_equal, np.equal, np.not_equal) answers = ( [True, False, False], [True, False, True], [False, True, False], [False, True, True], [False, False, True], [True, True, False], ) for op, answer in zip(ops, answers): yield operate_and_compare, a1, a2, op, answer for op in ops: yield assert_raises, YTUfuncUnitError, op, a1, a3 for op, answer in zip(ops, answers): yield operate_and_compare, a1, a3.in_units('cm'), op, answer
def assert_allclose_units(actual, desired, rtol=1e-7, atol=0, **kwargs): """Raise an error if two objects are not equal up to desired tolerance This is a wrapper for :func:`numpy.testing.assert_allclose` that also verifies unit consistency Parameters ---------- actual : array-like Array obtained (possibly with attached units) desired : array-like Array to compare with (possibly with attached units) rtol : float, optional Relative tolerance, defaults to 1e-7 atol : float or quantity, optional Absolute tolerance. If units are attached, they must be consistent with the units of ``actual`` and ``desired``. If no units are attached, assumes the same units as ``desired``. Defaults to zero. Notes ----- Also accepts additional keyword arguments accepted by :func:`numpy.testing.assert_allclose`, see the documentation of that function for details. """ # Create a copy to ensure this function does not alter input arrays act = YTArray(actual) des = YTArray(desired) try: des = des.in_units(act.units) except UnitOperationError as e: raise AssertionError( "Units of actual (%s) and desired (%s) do not have " "equivalent dimensions" % (act.units, des.units)) from e rt = YTArray(rtol) if not rt.units.is_dimensionless: raise AssertionError( f"Units of rtol ({rt.units}) are not dimensionless") if not isinstance(atol, YTArray): at = YTQuantity(atol, des.units) try: at = at.in_units(act.units) except UnitOperationError as e: raise AssertionError("Units of atol (%s) and actual (%s) do not have " "equivalent dimensions" % (at.units, act.units)) from e # units have been validated, so we strip units before calling numpy # to avoid spurious errors act = act.value des = des.value rt = rt.value at = at.value return assert_allclose(act, des, rt, at, **kwargs)
def test_to_value(): a = YTArray([1.0, 2.0, 3.0], "kpc") assert_equal(a.to_value(), np.array([1.0, 2.0, 3.0])) assert_equal(a.to_value(), a.value) assert_equal(a.to_value("km"), a.in_units("km").value) b = YTQuantity(5.5, "Msun") assert_equal(b.to_value(), 5.5) assert_equal(b.to_value("g"), b.in_units("g").value)
def test_comparisons(): """ Test numpy ufunc comparison operators for unit consistency. """ from yt.units.yt_array import YTArray a1 = YTArray([1, 2, 3], 'cm') a2 = YTArray([2, 1, 3], 'cm') a3 = YTArray([.02, .01, .03], 'm') dimless = np.array([2,1,3]) ops = ( np.less, np.less_equal, np.greater, np.greater_equal, np.equal, np.not_equal ) answers = ( [True, False, False], [True, False, True], [False, True, False], [False, True, True], [False, False, True], [True, True, False], ) for op, answer in zip(ops, answers): operate_and_compare(a1, a2, op, answer) for op, answer in zip(ops, answers): operate_and_compare(a1, dimless, op, answer) for op, answer in zip(ops, answers): if LooseVersion(np.__version__) < LooseVersion('1.13.0'): assert_raises(YTUfuncUnitError, op, a1, a3) else: operate_and_compare(a1, a3, op, answer) for op, answer in zip(ops, answers): operate_and_compare(a1, a3.in_units('cm'), op, answer) # Check that comparisons with dimensionless quantities work in both directions. operate_and_compare(a3, dimless, np.less, [True, True, True]) operate_and_compare(dimless, a3, np.less, [False, False, False]) assert_equal(a1 < 2, [True, False, False]) assert_equal(a1 < 2, np.less(a1, 2)) assert_equal(2 < a1, [False, False, True]) assert_equal(2 < a1, np.less(2, a1))
def test_comparisons(): """ Test numpy ufunc comparison operators for unit consistency. """ from yt.units.yt_array import YTArray a1 = YTArray([1, 2, 3], 'cm') a2 = YTArray([2, 1, 3], 'cm') a3 = YTArray([.02, .01, .03], 'm') dimless = np.array([2, 1, 3]) ops = (np.less, np.less_equal, np.greater, np.greater_equal, np.equal, np.not_equal) answers = ( [True, False, False], [True, False, True], [False, True, False], [False, True, True], [False, False, True], [True, True, False], ) for op, answer in zip(ops, answers): yield operate_and_compare, a1, a2, op, answer for op, answer in zip(ops, answers): yield operate_and_compare, a1, dimless, op, answer for op in ops: yield assert_raises, YTUfuncUnitError, op, a1, a3 for op, answer in zip(ops, answers): yield operate_and_compare, a1, a3.in_units('cm'), op, answer # Check that comparisons with dimensionless quantities work in both directions. yield operate_and_compare, a3, dimless, np.less, [True, True, True] yield operate_and_compare, dimless, a3, np.less, [False, False, False] yield assert_equal, a1 < 2, [True, False, False] yield assert_equal, a1 < 2, np.less(a1, 2) yield assert_equal, 2 < a1, [False, False, True] yield assert_equal, 2 < a1, np.less(2, a1)
def test_comparisons(): """ Test numpy ufunc comparison operators for unit consistency. """ from yt.units.yt_array import YTArray a1 = YTArray([1, 2, 3], 'cm') a2 = YTArray([2, 1, 3], 'cm') a3 = YTArray([.02, .01, .03], 'm') ops = ( np.less, np.less_equal, np.greater, np.greater_equal, np.equal, np.not_equal ) answers = ( [True, False, False], [True, False, True], [False, True, False], [False, True, True], [False, False, True], [True, True, False], ) for op, answer in zip(ops, answers): yield operate_and_compare, a1, a2, op, answer for op in ops: yield assert_raises, YTUfuncUnitError, op, a1, a3 for op, answer in zip(ops, answers): yield operate_and_compare, a1, a3.in_units('cm'), op, answer
def z_from_t_analytic(my_time, hubble_constant=0.7, omega_matter=0.3, omega_lambda=0.7): """ Compute the redshift from time after the big bang. This is based on Enzo's CosmologyComputeExpansionFactor.C, but altered to use physical units. """ hubble_constant = YTQuantity(hubble_constant, "100*km/s/Mpc") omega_curvature = 1.0 - omega_matter - omega_lambda OMEGA_TOLERANCE = 1e-5 ETA_TOLERANCE = 1.0e-10 # Convert the time to Time * H0. if not isinstance(my_time, YTArray): my_time = YTArray(my_time, "s") t0 = (my_time.in_units("s") * hubble_constant.in_units("1/s")).to_ndarray() # For a flat universe with omega_matter = 1, it's easy. if np.fabs(omega_matter - 1) < OMEGA_TOLERANCE and omega_lambda < OMEGA_TOLERANCE: a = np.power(1.5 * t0, 2.0 / 3.0) # For omega_matter < 1 and omega_lambda == 0 see # Peebles 1993, eq. 13-3, 13-10. # Actually, this is a little tricky since we must solve an equation # of the form eta - np.sinh(eta) + x = 0.. elif omega_matter < 1 and omega_lambda < OMEGA_TOLERANCE: x = 2 * t0 * np.power(1.0 - omega_matter, 1.5) / omega_matter # Compute eta in a three step process, first from a third-order # Taylor expansion of the formula above, then use that in a fifth-order # approximation. Then finally, iterate on the formula itself, solving for # eta. This works well because parts 1 & 2 are an excellent approximation # when x is small and part 3 converges quickly when x is large. eta = np.power(6 * x, 1.0 / 3.0) # part 1 eta = np.power(120 * x / (20 + eta * eta), 1.0 / 3.0) # part 2 mask = np.ones(eta.size, dtype=bool) max_iter = 1000 for i in range(max_iter): # part 3 eta_old = eta[mask] eta[mask] = np.arcsinh(eta[mask] + x[mask]) mask[mask] = np.fabs(eta[mask] - eta_old) >= ETA_TOLERANCE if not mask.any(): break if i == max_iter - 1: raise RuntimeError("No convergence after %d iterations." % i) # Now use eta to compute the expansion factor (eq. 13-10, part 2). a = omega_matter / (2.0 * (1.0 - omega_matter)) * (np.cosh(eta) - 1.0) # For flat universe, with non-zero omega_lambda, see eq. 13-20. elif np.fabs(omega_curvature) < OMEGA_TOLERANCE and omega_lambda > OMEGA_TOLERANCE: a = np.power(omega_matter / (1 - omega_matter), 1.0 / 3.0) * np.power( np.sinh(1.5 * np.sqrt(1.0 - omega_matter) * t0), 2.0 / 3.0 ) else: raise NotImplementedError redshift = (1.0 / a) - 1.0 return redshift
# Calculate analytic Stroemgren radius alpha = 2.59e-13 # Recombination rate at T=1e4 K nH = 1e-3 # Hydrogen density lum = 5e48 # Ionizing photon luminosity trec = 1.0 / (alpha * nH) # Recombination time rs = ((3 * lum) / (4 * np.pi * alpha * nH**2))**(1.0 / 3) anyl_radius = rs * (1.0 - np.exp(-time / trec))**(1.0 / 3) #print("anyl_radius = ", anyl_radius) anyl_radius = YTArray(anyl_radius, 'cm') #print("anyl_radius = ", anyl_radius.to('kpc')) ratio = radius / anyl_radius error = np.abs(1 - ratio) imax = np.where(error == error.max())[0] p = plt.subplot(211) p.plot(time / Myr, radius.in_units('kpc'), 'ro') p.plot(time / Myr, anyl_radius.to('kpc'), 'k-') p.set_ylabel(r'$r_{\rm IF}$ (kpc)') p = plt.subplot(212) p.plot(time / Myr, ratio, 'k-') p.set_ylabel(r'$r_{\rm IF} / r_{\rm anyl}$') p.set_xlabel("Time (Myr)") plt.savefig("StroemgrenRadius.png") ######################################################################## # Some basic analysis on the final output ######################################################################## pf = yt.load("DD%4.4d/data%4.4d" % (last, last)) myfields = ["HI_kph", "Neutral_Fraction", "El_fraction"] pc = yt.SlicePlot(pf, 2, center=[0.5, 0.5, 1.0 / 64], fields=myfields)