[yt-svn] commit/yt: jzuhone: Merged in ngoldbaum/yt (pull request #1728)
commits-noreply at bitbucket.org
commits-noreply at bitbucket.org
Wed Sep 9 17:12:04 PDT 2015
1 new commit in yt:
https://bitbucket.org/yt_analysis/yt/commits/47da0c1a0142/
Changeset: 47da0c1a0142
Branch: yt
User: jzuhone
Date: 2015-09-10 00:11:51+00:00
Summary: Merged in ngoldbaum/yt (pull request #1728)
Unit improvements
Affected #: 10 files
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/frontends/enzo/simulation_handling.py
--- a/yt/frontends/enzo/simulation_handling.py
+++ b/yt/frontends/enzo/simulation_handling.py
@@ -77,7 +77,7 @@
def _set_units(self):
self.unit_registry = UnitRegistry()
- self.unit_registry.lut["code_time"] = (1.0, dimensions.time)
+ self.unit_registry.add("code_time", 1.0, dimensions.time)
if self.cosmological_simulation:
# Instantiate EnzoCosmology object for units and time conversions.
self.cosmology = \
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/frontends/fits/data_structures.py
--- a/yt/frontends/fits/data_structures.py
+++ b/yt/frontends/fits/data_structures.py
@@ -420,7 +420,7 @@
Generates the conversion to various physical _units based on the parameter file
"""
default_length_units = [u for u,v in default_unit_symbol_lut.items()
- if str(v[-1]) == "(length)"]
+ if str(v[1]) == "(length)"]
more_length_units = []
for unit in default_length_units:
if unit in prefixable_units:
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/units/__init__.py
--- a/yt/units/__init__.py
+++ b/yt/units/__init__.py
@@ -1,1 +1,17 @@
-from yt.units.unit_symbols import *
+from yt.units import unit_symbols
+from yt.utilities import physical_constants
+
+from yt.units.yt_array import YTQuantity
+
+
+# function to only import quantities into this namespace
+# we go through the trouble of doing this instead of "import *"
+# to avoid including extraneous variables (e.g. floating point
+# constants used to *construct* a physical constant) in this namespace
+def import_quantities(module, global_namespace):
+ for key, value in module.__dict__.items():
+ if isinstance(value, YTQuantity):
+ global_namespace[key] = value
+
+import_quantities(unit_symbols, globals())
+import_quantities(physical_constants, globals())
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/units/tests/test_units.py
--- a/yt/units/tests/test_units.py
+++ b/yt/units/tests/test_units.py
@@ -15,16 +15,16 @@
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
-import nose
import numpy as np
from numpy.testing import \
assert_array_almost_equal_nulp, \
- assert_raises
+ assert_raises, assert_equal
from nose.tools import assert_true
import operator
from sympy import Symbol
from yt.testing import \
- fake_random_ds, assert_allclose_units
+ fake_random_ds, assert_allclose_units, \
+ assert_almost_equal
# dimensions
from yt.units.dimensions import \
@@ -84,6 +84,9 @@
yield assert_true, u2.base_value == 1
yield assert_true, u2.dimensions == 1
+ yield assert_equal, u1.latex_repr, ''
+ yield assert_equal, u2.latex_repr, ''
+
#
# Start init tests
#
@@ -450,3 +453,14 @@
assert_raises(InvalidUnitOperation, operator.mul, u1, u2)
assert_raises(InvalidUnitOperation, operator.truediv, u1, u2)
+
+def test_comoving_labels():
+ ds = fake_random_ds(64, nprocs=1)
+
+ # create a fake comoving unit
+ ds.unit_registry.add('pccm', ds.unit_registry.lut['pc'][0]/(1+2), length,
+ "\\rm{pc}/(1+z)")
+
+ test_unit = Unit('Mpccm', registry=ds.unit_registry)
+ assert_almost_equal(test_unit.base_value, cm_per_mpc/3)
+ assert_equal(test_unit.latex_repr, r'\rm{Mpc}/(1+z)')
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/units/tests/test_ytarray.py
--- a/yt/units/tests/test_ytarray.py
+++ b/yt/units/tests/test_ytarray.py
@@ -679,6 +679,8 @@
assert_array_equal(ret1, npret1)
assert_array_equal(ret2, npret2)
+ elif ufunc is np.invert:
+ assert_raises(TypeError, ufunc, a)
else:
# There shouldn't be any untested ufuncs.
assert_true(False)
@@ -697,6 +699,10 @@
elif a.units != b.units:
assert_raises(YTUnitOperationError, ufunc, a, b)
return
+ if ufunc in (np.bitwise_and, np.bitwise_or, np.bitwise_xor,
+ np.left_shift, np.right_shift, np.ldexp):
+ assert_raises(TypeError, ufunc, a, b)
+ return
ret = ufunc(a, b, out=out)
@@ -732,8 +738,10 @@
a = YTArray([.3, .4, .5], 'cm')
b = YTArray([.1, .2, .3], 'dimensionless')
c = np.array(b)
+ d = YTArray([1., 2., 3.], 'g')
yield binary_ufunc_comparison, ufunc, a, b
yield binary_ufunc_comparison, ufunc, a, c
+ assert_raises(YTUnitOperationError, ufunc, a, d)
continue
a = YTArray([.3, .4, .5], 'cm')
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/units/unit_lookup_table.py
--- a/yt/units/unit_lookup_table.py
+++ b/yt/units/unit_lookup_table.py
@@ -19,9 +19,9 @@
sec_per_min, temp_sun_kelvin, luminosity_sun_ergs_per_sec, \
metallicity_sun, erg_per_eV, amu_grams, mass_electron_grams, \
cm_per_ang, jansky_cgs, mass_jupiter_grams, mass_earth_grams, \
- boltzmann_constant_erg_per_K, kelvin_per_rankine, \
- speed_of_light_cm_per_s, planck_length_cm, planck_charge_esu, \
- planck_energy_erg, planck_mass_grams, planck_temperature_K, planck_time_s
+ kelvin_per_rankine, speed_of_light_cm_per_s, planck_length_cm, \
+ planck_charge_esu, planck_energy_erg, planck_mass_grams, \
+ planck_temperature_K, planck_time_s
import numpy as np
# Lookup a unit symbol with the symbol string, and provide a tuple with the
@@ -29,135 +29,115 @@
default_unit_symbol_lut = {
# base
- "g": (1.0, dimensions.mass),
- #"cm": (1.0, length, r"\rm{cm}"), # duplicate with meter below...
- "s": (1.0, dimensions.time),
- "K": (1.0, dimensions.temperature),
- "radian": (1.0, dimensions.angle),
+ "g": (1.0, dimensions.mass, 0.0, r"\rm{g}"),
+ "s": (1.0, dimensions.time, 0.0, r"\rm{s}"),
+ "K": (1.0, dimensions.temperature, 0.0, r"\rm{K}"),
+ "radian": (1.0, dimensions.angle, 0.0, r"\rm{radian}"),
# other cgs
- "dyne": (1.0, dimensions.force),
- "erg": (1.0, dimensions.energy),
- "esu": (1.0, dimensions.charge_cgs),
- "gauss": (1.0, dimensions.magnetic_field_cgs),
- "degC": (1.0, dimensions.temperature, -273.15),
- "statA": (1.0, dimensions.current_cgs),
- "statV": (1.0, dimensions.electric_potential_cgs),
- "statohm": (1.0, dimensions.resistance_cgs),
+ "dyne": (1.0, dimensions.force, 0.0, r"\rm{dyn}"),
+ "erg": (1.0, dimensions.energy, 0.0, r"\rm{erg}"),
+ "esu": (1.0, dimensions.charge_cgs, 0.0, r"\rm{esu}"),
+ "gauss": (1.0, dimensions.magnetic_field_cgs, 0.0, r"\rm{G}"),
+ "degC": (1.0, dimensions.temperature, -273.15, r"^\circ\rm{C}"),
+ "statA": (1.0, dimensions.current_cgs, 0.0, r"\rm{statA}"),
+ "statV": (1.0, dimensions.electric_potential_cgs, 0.0, r"\rm{statV}"),
+ "statohm": (1.0, dimensions.resistance_cgs, 0.0, r"\rm{statohm}"),
# some SI
- "m": (1.0e2, dimensions.length),
- "J": (1.0e7, dimensions.energy),
- "W": (1.0e7, dimensions.power),
- "Hz": (1.0, dimensions.rate),
- "N": (1.0e5, dimensions.force),
- "C": (1.0, dimensions.charge_mks),
- "A": (1.0, dimensions.current_mks),
- "T": (1000.0, dimensions.magnetic_field_mks),
- "Pa": (10.0, dimensions.pressure),
- "V": (1.0e7, dimensions.electric_potential_mks),
- "ohm": (1.0e7, dimensions.resistance_mks),
+ "m": (1.0e2, dimensions.length, 0.0, r"\rm{m}"),
+ "J": (1.0e7, dimensions.energy, 0.0, r"\rm{J}"),
+ "W": (1.0e7, dimensions.power, 0.0, r"\rm{W}"),
+ "Hz": (1.0, dimensions.rate, 0.0, r"\rm{Hz}"),
+ "N": (1.0e5, dimensions.force, 0.0, r"\rm{N}"),
+ "C": (1.0, dimensions.charge_mks, 0.0, r"\rm{C}"),
+ "A": (1.0, dimensions.current_mks, 0.0, r"\rm{A}"),
+ "T": (1000.0, dimensions.magnetic_field_mks, 0.0, r"\rm{T}"),
+ "Pa": (10.0, dimensions.pressure, 0.0, r"\rm{Pa}"),
+ "V": (1.0e7, dimensions.electric_potential_mks, 0.0, r"\rm{V}"),
+ "ohm": (1.0e7, dimensions.resistance_mks, 0.0, r"\Omega"),
# Imperial units
- "ft": (30.48, dimensions.length),
- "mile": (160934, dimensions.length),
- "degF": (kelvin_per_rankine, dimensions.temperature, -459.67),
- "R": (kelvin_per_rankine, dimensions.temperature),
+ "ft": (30.48, dimensions.length, 0.0, r"\rm{ft}"),
+ "mile": (160934, dimensions.length, 0.0, r"\rm{mile}"),
+ "degF": (kelvin_per_rankine, dimensions.temperature, -459.67,
+ "^\circ\rm{F}"),
+ "R": (kelvin_per_rankine, dimensions.temperature, 0.0, r"^\circ\rm{R}"),
# dimensionless stuff
- "h": (1.0, dimensions.dimensionless), # needs to be added for rho_crit_now
- "dimensionless": (1.0, dimensions.dimensionless),
+ "h": (1.0, dimensions.dimensionless, 0.0, r"h"), # needs to be added for rho_crit_now
+ "dimensionless": (1.0, dimensions.dimensionless, 0.0, r""),
# times
- "min": (sec_per_min, dimensions.time),
- "hr": (sec_per_hr, dimensions.time),
- "day": (sec_per_day, dimensions.time),
- "yr": (sec_per_year, dimensions.time),
+ "min": (sec_per_min, dimensions.time, 0.0, r"\rm{min}"),
+ "hr": (sec_per_hr, dimensions.time, 0.0, r"\rm{hr}"),
+ "day": (sec_per_day, dimensions.time, 0.0, r"\rm{d}"),
+ "yr": (sec_per_year, dimensions.time, 0.0, r"\rm{yr}"),
# Velocities
- "c": (speed_of_light_cm_per_s, dimensions.velocity),
+ "c": (speed_of_light_cm_per_s, dimensions.velocity, 0.0, r"\rm{c}"),
# Solar units
- "Msun": (mass_sun_grams, dimensions.mass),
- "msun": (mass_sun_grams, dimensions.mass),
- "Rsun": (cm_per_rsun, dimensions.length),
- "rsun": (cm_per_rsun, dimensions.length),
- "Lsun": (luminosity_sun_ergs_per_sec, dimensions.power),
- "Tsun": (temp_sun_kelvin, dimensions.temperature),
- "Zsun": (metallicity_sun, dimensions.dimensionless),
- "Mjup": (mass_jupiter_grams, dimensions.mass),
- "Mearth": (mass_earth_grams, dimensions.mass),
+ "Msun": (mass_sun_grams, dimensions.mass, 0.0, r"M_\odot"),
+ "msun": (mass_sun_grams, dimensions.mass, 0.0, r"M_\odot"),
+ "Rsun": (cm_per_rsun, dimensions.length, 0.0, r"R_\odot"),
+ "rsun": (cm_per_rsun, dimensions.length, 0.0, r"R_\odot"),
+ "Lsun": (luminosity_sun_ergs_per_sec, dimensions.power, 0.0, r"L_\odot"),
+ "Tsun": (temp_sun_kelvin, dimensions.temperature, 0.0, r"T_\odot"),
+ "Zsun": (metallicity_sun, dimensions.dimensionless, 0.0, r"Z_\odot"),
+ "Mjup": (mass_jupiter_grams, dimensions.mass, 0.0, r"M_{\rm{Jup}"),
+ "Mearth": (mass_earth_grams, dimensions.mass, 0.0, r"M_\oplus"),
# astro distances
- "AU": (cm_per_au, dimensions.length),
- "au": (cm_per_au, dimensions.length),
- "ly": (cm_per_ly, dimensions.length),
- "pc": (cm_per_pc, dimensions.length),
+ "AU": (cm_per_au, dimensions.length, 0.0, r"\rm{AU}"),
+ "au": (cm_per_au, dimensions.length, 0.0, r"\rm{AU}"),
+ "ly": (cm_per_ly, dimensions.length, 0.0, r"\rm{ly}"),
+ "pc": (cm_per_pc, dimensions.length, 0.0, r"\rm{pc}"),
# angles
- "degree": (np.pi/180., dimensions.angle), # degrees
- "arcmin": (np.pi/10800., dimensions.angle), # arcminutes
- "arcsec": (np.pi/648000., dimensions.angle), # arcseconds
- "mas": (np.pi/648000000., dimensions.angle), # millarcseconds
- "hourangle": (np.pi/12., dimensions.angle), # hour angle
- "steradian": (1.0, dimensions.solid_angle),
+ "degree": (np.pi/180., dimensions.angle, 0.0, r"\rm{deg}"), # degrees
+ "arcmin": (np.pi/10800., dimensions.angle, 0.0,
+ r"\rm{arcmin}"), # arcminutes
+ "arcsec": (np.pi/648000., dimensions.angle, 0.0,
+ r"\rm{arcsec}"), # arcseconds
+ "mas": (np.pi/648000000., dimensions.angle, 0.0,
+ r"\rm{mas}"), # millarcseconds
+ "hourangle": (np.pi/12., dimensions.angle, 0.0, r"\rm{HA}"), # hour angle
+ "steradian": (1.0, dimensions.solid_angle, 0.0, r"\rm{sr}"),
# misc
- "eV": (erg_per_eV, dimensions.energy),
- "amu": (amu_grams, dimensions.mass),
- "angstrom": (cm_per_ang, dimensions.length),
- "Jy": (jansky_cgs, dimensions.specific_flux),
- "counts": (1.0, dimensions.dimensionless),
- "photons": (1.0, dimensions.dimensionless),
- "me": (mass_electron_grams, dimensions.mass),
+ "eV": (erg_per_eV, dimensions.energy, 0.0, r"\rm{eV}"),
+ "amu": (amu_grams, dimensions.mass, 0.0, r"\rm{amu}"),
+ "angstrom": (cm_per_ang, dimensions.length, 0.0, r"\AA"),
+ "Jy": (jansky_cgs, dimensions.specific_flux, 0.0, r"\rm{Jy}"),
+ "counts": (1.0, dimensions.dimensionless, 0.0, r"\rm{counts}"),
+ "photons": (1.0, dimensions.dimensionless, 0.0, r"\rm{photons}"),
+ "me": (mass_electron_grams, dimensions.mass, 0.0, r"m_e"),
# for AstroPy compatibility
- "solMass": (mass_sun_grams, dimensions.mass),
- "solRad": (cm_per_rsun, dimensions.length),
- "solLum": (luminosity_sun_ergs_per_sec, dimensions.power),
- "dyn": (1.0, dimensions.force),
- "sr": (1.0, dimensions.solid_angle),
- "rad": (1.0, dimensions.solid_angle),
- "deg": (np.pi/180., dimensions.angle),
- "Fr": (1.0, dimensions.charge_cgs),
- "G": (1.0, dimensions.magnetic_field_cgs),
- "d": (1.0, dimensions.time),
- "Angstrom": (cm_per_ang, dimensions.length),
- "statC": (1.0, dimensions.charge_cgs),
-
+ "solMass": (mass_sun_grams, dimensions.mass, 0.0, r"M_\odot"),
+ "solRad": (cm_per_rsun, dimensions.length, 0.0, r"R_\odot"),
+ "solLum": (luminosity_sun_ergs_per_sec, dimensions.power, 0.0, r"L_\odot"),
+ "dyn": (1.0, dimensions.force, 0.0, r"\rm{dyn}"),
+ "sr": (1.0, dimensions.solid_angle, 0.0, r"\rm{sr}"),
+ "rad": (1.0, dimensions.solid_angle, 0.0, r"\rm{rad}"),
+ "deg": (np.pi/180., dimensions.angle, 0.0, r"\rm{deg}"),
+ "Fr": (1.0, dimensions.charge_cgs, 0.0, r"\rm{Fr}"),
+ "G": (1.0, dimensions.magnetic_field_cgs, 0.0, r"\rm{G}"),
+ "d": (1.0, dimensions.time, 0.0, r"\rm{d}"),
+ "Angstrom": (cm_per_ang, dimensions.length, 0.0, r"\AA"),
+ "statC": (1.0, dimensions.charge_cgs, 0.0, r"\rm{statC}"),
+
# Planck units
- "m_pl": (planck_mass_grams, dimensions.mass),
- "l_pl": (planck_length_cm, dimensions.length),
- "t_pl": (planck_time_s, dimensions.time),
- "T_pl": (planck_temperature_K, dimensions.temperature),
- "q_pl": (planck_charge_esu, dimensions.charge_cgs),
- "E_pl": (planck_energy_erg, dimensions.energy),
+ "m_pl": (planck_mass_grams, dimensions.mass, 0.0, r"m_{\rm{P}}"),
+ "l_pl": (planck_length_cm, dimensions.length, 0.0, r"\ell_\rm{P}"),
+ "t_pl": (planck_time_s, dimensions.time, 0.0, r"r_{\rm{P}}"),
+ "T_pl": (planck_temperature_K, dimensions.temperature, 0.0, r"T_{\rm{P}}"),
+ "q_pl": (planck_charge_esu, dimensions.charge_cgs, 0.0, r"q_{\rm{P}}"),
+ "E_pl": (planck_energy_erg, dimensions.energy, 0.0, r"E_{\rm{P}}"),
}
-# Add LaTeX representations for units with trivial representations.
-latex_symbol_lut = {
- "unitary" : r"",
- "dimensionless" : r"",
- "code_length" : r"\rm{code}\ \rm{length}",
- "code_time" : r"\rm{code}\ \rm{time}",
- "code_mass" : r"\rm{code}\ \rm{mass}",
- "code_temperature" : r"\rm{code}\ \rm{temperature}",
- "code_metallicity" : r"\rm{code}\ \rm{metallicity}",
- "code_velocity" : r"\rm{code}\ \rm{velocity}",
- "code_magnetic" : r"\rm{code}\ \rm{magnetic}",
- "Msun" : r"\rm{M}_\odot",
- "msun" : r"\rm{M}_\odot",
- "Rsun" : r"\rm{R}_\odot",
- "rsun" : r"\rm{R}_\odot",
- "Lsun" : r"\rm{L}_\odot",
- "Tsun" : r"\rm{T}_\odot",
- "Zsun" : r"\rm{Z}_\odot",
-}
-for key in default_unit_symbol_lut:
- if key not in latex_symbol_lut:
- latex_symbol_lut[key] = r"\rm{" + key + r"}"
-
# This dictionary formatting from magnitude package, credit to Juan Reyero.
unit_prefixes = {
'Y': 1e24, # yotta
@@ -181,7 +161,7 @@
}
latex_prefixes = {
- "u" : "\\mu",
+ "u": r"\mu",
}
prefixable_units = (
@@ -216,22 +196,22 @@
)
yt_base_units = {
- dimensions.mass:'g',
- dimensions.length:'cm',
- dimensions.time:'s',
- dimensions.temperature:'K',
- dimensions.angle:'radian',
- dimensions.current_mks:'A',
+ dimensions.mass: 'g',
+ dimensions.length: 'cm',
+ dimensions.time: 's',
+ dimensions.temperature: 'K',
+ dimensions.angle: 'radian',
+ dimensions.current_mks: 'A',
}
cgs_base_units = yt_base_units.copy()
cgs_base_units.pop(dimensions.current_mks)
mks_base_units = {
- dimensions.mass:'kg',
- dimensions.length:'m',
- dimensions.time:'s',
- dimensions.temperature:'K',
- dimensions.angle:'radian',
- dimensions.current_mks:'A',
+ dimensions.mass: 'kg',
+ dimensions.length: 'm',
+ dimensions.time: 's',
+ dimensions.temperature: 'K',
+ dimensions.angle: 'radian',
+ dimensions.current_mks: 'A',
}
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/units/unit_object.py
--- a/yt/units/unit_object.py
+++ b/yt/units/unit_object.py
@@ -26,8 +26,7 @@
base_dimensions, temperature, \
dimensionless, current_mks
from yt.units.unit_lookup_table import \
- latex_symbol_lut, unit_prefixes, \
- prefixable_units, cgs_base_units, \
+ unit_prefixes, prefixable_units, cgs_base_units, \
mks_base_units, latex_prefixes, yt_base_units
from yt.units.unit_registry import UnitRegistry
from yt.utilities.exceptions import YTUnitsNotReducible
@@ -103,6 +102,17 @@
return result
+def get_latex_representation(expr, registry):
+ symbol_table = {}
+ for ex in expr.free_symbols:
+ symbol_table[ex] = registry.lut[str(ex)][3]
+ latex_repr = latex(expr, symbol_names=symbol_table, mul_symbol="dot",
+ fold_frac_powers=True, fold_short_frac=True)
+ if latex_repr == '1':
+ return ''
+ else:
+ return latex_repr
+
unit_text_transform = (auto_positive_symbol, rationalize, auto_number)
class Unit(Expr):
@@ -119,10 +129,10 @@
# Extra attributes
__slots__ = ["expr", "is_atomic", "base_value", "base_offset", "dimensions",
- "registry"]
+ "registry", "latex_repr"]
def __new__(cls, unit_expr=sympy_one, base_value=None, base_offset=0.0,
- dimensions=None, registry=None, **assumptions):
+ dimensions=None, registry=None, latex_repr=None, **assumptions):
"""
Create a new unit. May be an atomic unit (like a gram) or combinations
of atomic units (like g / cm**3).
@@ -133,15 +143,20 @@
The symbolic unit expression.
base_value : float
The unit's value in yt's base units.
+ base_offset : float
+ The offset necessary to normalize temperature units to a common
+ zero point.
dimensions : sympy.core.expr.Expr
A sympy expression representing the dimensionality of this unit.
It must contain only mass, length, time, temperature and angle
symbols.
- base_offset : float
- The offset necessary to normalize temperature units to a common
- zero point.
registry : UnitRegistry object
The unit registry we use to interpret unit symbols.
+ latex_repr : string
+ A string to render the unit as LaTeX
+
+ Additional keyword arguments are passed as assumptions to the Sympy Expr
+ initializer
"""
# Simplest case. If user passes a Unit object, just use the expr.
@@ -199,13 +214,19 @@
# check that dimensions is valid
if dimensions is not None:
validate_dimensions(dimensions)
+ if latex_repr is None:
+ latex_repr = r"\rm{" + str(unit_expr).replace('_', '\ ') + "}"
else:
# lookup the unit symbols
unit_data = _get_unit_data_from_expr(unit_expr, registry.lut)
base_value = unit_data[0]
dimensions = unit_data[1]
- if len(unit_data) == 3:
+ if len(unit_data) > 2:
base_offset = unit_data[2]
+ latex_repr = unit_data[3]
+ else:
+ base_offset = 0.0
+ latex_repr = get_latex_representation(unit_expr, registry)
# Create obj with superclass construct.
obj = Expr.__new__(cls, **assumptions)
@@ -216,9 +237,10 @@
obj.base_value = base_value
obj.base_offset = base_offset
obj.dimensions = dimensions
+ obj.latex_repr = latex_repr
obj.registry = registry
- if unit_key:
+ if unit_key is not None:
registry.unit_objs[unit_key] = obj
# Return `obj` so __init__ can handle it.
@@ -411,12 +433,8 @@
return get_conversion_factor(self, other_units)
def latex_representation(self):
- symbol_table = {}
- for ex in self.expr.free_symbols:
- symbol_table[ex] = latex_symbol_lut[str(ex)]
- return latex(self.expr, symbol_names=symbol_table,
- mul_symbol="dot", fold_frac_powers=True,
- fold_short_frac=True)
+ return self.latex_repr
+
#
# Unit manipulation functions
#
@@ -526,27 +544,42 @@
# the first character could be a prefix, check the rest of the symbol
symbol_wo_prefix = symbol_str[1:]
- if symbol_wo_prefix in unit_symbol_lut and symbol_wo_prefix in prefixable_units:
+ unit_is_si_prefixable = (symbol_wo_prefix in unit_symbol_lut and
+ symbol_wo_prefix in prefixable_units)
+
+ if unit_is_si_prefixable is True:
# lookup successful, it's a symbol with a prefix
unit_data = unit_symbol_lut[symbol_wo_prefix]
prefix_value = unit_prefixes[possible_prefix]
- if symbol_str not in latex_symbol_lut:
- if possible_prefix in latex_prefixes:
- sstr = symbol_str.replace(possible_prefix,
- '{'+latex_prefixes[possible_prefix]+'}')
+ if possible_prefix in latex_prefixes:
+ latex_repr = symbol_str.replace(
+ possible_prefix, '{'+latex_prefixes[possible_prefix]+'}')
+ else:
+ # Need to add some special handling for comoving units
+ # this is fine for now, but it wouldn't work for a general
+ # unit that has an arbitrary LaTeX representation
+ if symbol_wo_prefix != 'cm' and symbol_wo_prefix.endswith('cm'):
+ sub_symbol_wo_prefix = symbol_wo_prefix[:-2]
+ sub_symbol_str = symbol_str[:-2]
else:
- sstr = symbol_str
- latex_symbol_lut[symbol_str] = \
- latex_symbol_lut[symbol_wo_prefix].replace(
- '{'+symbol_wo_prefix+'}', '{'+sstr+'}')
+ sub_symbol_wo_prefix = symbol_wo_prefix
+ sub_symbol_str = symbol_str
+ latex_repr = unit_data[3].replace(
+ '{' + sub_symbol_wo_prefix + '}', '{' + sub_symbol_str + '}')
- # don't forget to account for the prefix value!
- return (unit_data[0] * prefix_value, unit_data[1])
+ # Leave offset and dimensions the same, but adjust scale factor and
+ # LaTeX representation
+ ret = (unit_data[0] * prefix_value, unit_data[1], unit_data[2],
+ latex_repr)
+
+ unit_symbol_lut[symbol_str] = ret
+
+ return ret
# no dice
- raise UnitParseError("Could not find unit symbol '%s' in the provided " \
- "symbols." % symbol_str)
+ raise UnitParseError("Could not find unit symbol '%s' in the table of "
+ "known symbols." % symbol_str)
def validate_dimensions(dimensions):
if isinstance(dimensions, Mul):
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/units/unit_registry.py
--- a/yt/units/unit_registry.py
+++ b/yt/units/unit_registry.py
@@ -13,7 +13,7 @@
#-----------------------------------------------------------------------------
from yt.units.unit_lookup_table import \
- default_unit_symbol_lut, latex_symbol_lut
+ default_unit_symbol_lut
class SymbolNotFoundError(Exception):
pass
@@ -39,7 +39,7 @@
def __contains__(self, item):
return item in self.lut
- def add(self, symbol, base_value, dimensions, tex_repr=None):
+ def add(self, symbol, base_value, dimensions, tex_repr=None, offset=None):
"""
Add a symbol to this registry.
@@ -48,18 +48,25 @@
# Validate
if not isinstance(base_value, float):
- raise UnitParseError("base_value must be a float, got a %s."
- % type(base_value))
+ raise UnitParseError("base_value (%s) must be a float, got a %s."
+ % (base_value, type(base_value)))
+
+ if offset is not None:
+ if not isinstance(offset, float):
+ raise UnitParseError(
+ "offset value (%s) must be a float, got a %s."
+ % (offset, type(offset)))
+ else:
+ offset = 0.0
validate_dimensions(dimensions)
- # Add to symbol lut
if tex_repr is None:
- tex_repr = "\\rm{" + symbol + "}"
- latex_symbol_lut.setdefault(symbol, tex_repr)
+ # make educated guess that will look nice in most cases
+ tex_repr = r"\rm{" + symbol + "}"
# Add to lut
- self.lut.update({symbol: (base_value, dimensions)})
+ self.lut.update({symbol: (base_value, dimensions, offset, tex_repr)})
def remove(self, symbol):
"""
@@ -86,7 +93,8 @@
if hasattr(base_value, "in_base"):
base_value = float(base_value.in_base().value)
- self.lut[symbol] = (base_value, self.lut[symbol][1])
+
+ self.lut[symbol] = (base_value, ) + self.lut[symbol][1:]
def keys(self):
"""
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/units/yt_array.py
--- a/yt/units/yt_array.py
+++ b/yt/units/yt_array.py
@@ -19,14 +19,15 @@
from functools import wraps
from numpy import \
add, subtract, multiply, divide, logaddexp, logaddexp2, true_divide, \
- floor_divide, negative, power, remainder, mod, fmod, absolute, rint, \
+ floor_divide, negative, power, remainder, mod, absolute, rint, \
sign, conj, exp, exp2, log, log2, log10, expm1, log1p, sqrt, square, \
reciprocal, ones_like, sin, cos, tan, arcsin, arccos, arctan, arctan2, \
hypot, sinh, cosh, tanh, arcsinh, arccosh, arctanh, deg2rad, rad2deg, \
+ bitwise_and, bitwise_or, bitwise_xor, invert, left_shift, right_shift, \
greater, greater_equal, less, less_equal, not_equal, equal, logical_and, \
- logical_or, logical_xor, logical_not, maximum, minimum, isreal, iscomplex, \
- isfinite, isinf, isnan, signbit, copysign, nextafter, modf, frexp, \
- floor, ceil, trunc, fmax, fmin, fabs
+ logical_or, logical_xor, logical_not, maximum, minimum, fmax, fmin, \
+ isreal, iscomplex, isfinite, isinf, isnan, signbit, copysign, nextafter, \
+ modf, ldexp, frexp, fmod, floor, ceil, trunc, fabs
from yt.units.unit_object import Unit, UnitParseError
from yt.units.unit_registry import UnitRegistry
@@ -38,7 +39,9 @@
from numbers import Number as numeric_type
from yt.utilities.on_demand_imports import _astropy
from sympy import Rational
-from yt.units.unit_lookup_table import unit_prefixes, prefixable_units
+from yt.units.unit_lookup_table import \
+ unit_prefixes, prefixable_units, \
+ default_unit_symbol_lut
from yt.units.equivalencies import equivalence_registry
from yt.utilities.logger import ytLogger as mylog
@@ -94,6 +97,14 @@
def comparison_unit(unit1, unit2):
return None
+def invert_units(unit):
+ raise TypeError(
+ "Bit-twiddling operators are not defined for YTArray instances")
+
+def bitop_units(unit1, unit2):
+ raise TypeError(
+ "Bit-twiddling operators are not defined for YTArray instances")
+
def coerce_iterable_units(input_object):
if isinstance(input_object, np.ndarray):
return input_object
@@ -150,15 +161,16 @@
negative, absolute, rint, ones_like, sign, conj, exp, exp2, log, log2,
log10, expm1, log1p, sqrt, square, reciprocal, sin, cos, tan, arcsin,
arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh, deg2rad,
- rad2deg, logical_not, isreal, iscomplex, isfinite, isinf, isnan,
+ rad2deg, invert, logical_not, isreal, iscomplex, isfinite, isinf, isnan,
signbit, floor, ceil, trunc, modf, frexp, fabs
)
binary_operators = (
add, subtract, multiply, divide, logaddexp, logaddexp2, true_divide, power,
- remainder, mod, arctan2, hypot, greater, greater_equal, less, less_equal,
+ remainder, mod, arctan2, hypot, bitwise_and, bitwise_or, bitwise_xor,
+ left_shift, right_shift, greater, greater_equal, less, less_equal,
not_equal, equal, logical_and, logical_or, logical_xor, maximum, minimum,
- fmax, fmin, copysign, nextafter, fmod,
+ fmax, fmin, copysign, nextafter, ldexp, fmod,
)
class YTArray(np.ndarray):
@@ -272,6 +284,12 @@
hypot: preserve_units,
deg2rad: return_without_unit,
rad2deg: return_without_unit,
+ bitwise_and: bitop_units,
+ bitwise_or: bitop_units,
+ bitwise_xor: bitop_units,
+ invert: invert_units,
+ left_shift: bitop_units,
+ right_shift: bitop_units,
greater: comparison_unit,
greater_equal: comparison_unit,
less: comparison_unit,
@@ -295,6 +313,7 @@
copysign: passthrough_unit,
nextafter: preserve_units,
modf: passthrough_unit,
+ ldexp: bitop_units,
frexp: return_without_unit,
floor: passthrough_unit,
ceil: passthrough_unit,
@@ -479,6 +498,14 @@
return new_array
+ def to(self, units):
+ """
+ An alias for YTArray.in_units().
+
+ See the docstrings of that function for details.
+ """
+ return self.in_units(units)
+
def in_base(self):
"""
Creates a copy of this array with the data in the equivalent base units,
@@ -1104,6 +1131,12 @@
"""
super(YTArray, self).__setstate__(state[1:])
unit, lut = state[0]
+ # need to fix up the lut if the pickle was saved prior to PR #1728
+ # when the pickle format changed
+ if len(lut['m']) == 2:
+ lut.update(default_unit_symbol_lut)
+ for k, v in [(k, v) for k, v in lut.items() if len(v) == 2]:
+ lut[k] = v + (0.0, r'\rm{' + k.replace('_', '\ ') + '}')
registry = UnitRegistry(lut=lut, add_default_symbols=False)
self.units = Unit(unit, registry=registry)
diff -r 415b19e3578b9ad05adab2b94edded8ec57d9ede -r 47da0c1a0142b30d6ff793f84090761fca977f67 yt/utilities/physical_constants.py
--- a/yt/utilities/physical_constants.py
+++ b/yt/utilities/physical_constants.py
@@ -3,58 +3,102 @@
from math import pi
mass_electron_cgs = YTQuantity(mass_electron_grams, 'g')
-amu_cgs = YTQuantity(amu_grams, 'g')
+mass_electron = mass_electron_cgs
+me = mass_electron_cgs
+
+amu_cgs = YTQuantity(amu_grams, 'g')
+amu = amu_cgs
+Na = 1 / amu_cgs
+
mass_hydrogen_cgs = 1.007947*amu_cgs
+mass_hydrogen = mass_hydrogen_cgs
+mp = mass_hydrogen_cgs
+mh = mp
# Velocities
speed_of_light_cgs = YTQuantity(speed_of_light_cm_per_s, 'cm/s')
+speed_of_light = speed_of_light_cgs
+clight = speed_of_light_cgs
+c = speed_of_light_cgs
# Cross Sections
# 8*pi/3 (alpha*hbar*c/(2*pi))**2
cross_section_thompson_cgs = YTQuantity(6.65245854533e-25, 'cm**2')
+cross_section_thompson = cross_section_thompson_cgs
+thompson_cross_section = cross_section_thompson_cgs
+sigma_thompson = cross_section_thompson_cgs
# Charge
charge_proton_cgs = YTQuantity(4.8032056e-10, 'esu')
+charge_proton = charge_proton_cgs
+proton_charge = charge_proton_cgs
elementary_charge = charge_proton_cgs
+qp = charge_proton_cgs
# Physical Constants
boltzmann_constant_cgs = YTQuantity(boltzmann_constant_erg_per_K, 'erg/K')
-gravitational_constant_cgs = YTQuantity(6.67384e-8, 'cm**3/g/s**2')
-planck_constant_cgs = YTQuantity(6.62606957e-27, 'erg*s')
+boltzmann_constant = boltzmann_constant_cgs
+kboltz = boltzmann_constant_cgs
+kb = kboltz
+
+gravitational_constant_cgs = YTQuantity(6.67384e-8, 'cm**3/g/s**2')
+gravitational_constant = gravitational_constant_cgs
+G = gravitational_constant_cgs
+
+planck_constant_cgs = YTQuantity(6.62606957e-27, 'erg*s')
+planck_constant = planck_constant_cgs
+hcgs = planck_constant_cgs
+hbar = 0.5*hcgs/pi
+
stefan_boltzmann_constant_cgs = YTQuantity(5.670373e-5, 'erg/cm**2/s**1/K**4')
-Tcmb = YTQuantity(2.726, 'K') # Current CMB temperature
+stefan_boltzmann_constant = stefan_boltzmann_constant_cgs
+
+Tcmb = YTQuantity(2.726, 'K') # Current CMB temperature
+CMB_temperature = Tcmb
# Solar System
mass_sun_cgs = YTQuantity(mass_sun_grams, 'g')
+mass_sun = mass_sun_cgs
+solar_mass = mass_sun_cgs
+msun = mass_sun_cgs
# Standish, E.M. (1995) "Report of the IAU WGAS Sub-Group on Numerical Standards",
# in Highlights of Astronomy (I. Appenzeller, ed.), Table 1,
# Kluwer Academic Publishers, Dordrecht.
# REMARK: following masses include whole systems (planet + moons)
mass_jupiter_cgs = YTQuantity(mass_jupiter_grams, 'g')
+mass_jupiter = mass_jupiter_cgs
+jupiter_mas = mass_jupiter_cgs
+
mass_mercury_cgs = YTQuantity(mass_mercury_grams, 'g')
+mass_mercury = mass_mercury_cgs
+mercury_mass = mass_mercury_cgs
+
mass_venus_cgs = YTQuantity(mass_venus_grams, 'g')
+mass_venus = mass_venus_cgs
+venus_mass = mass_venus_cgs
+
mass_earth_cgs = YTQuantity(mass_earth_grams, 'g')
+mass_earth = mass_earth_cgs
+earth_mass = mass_earth_cgs
+mearth = mass_earth_cgs
+
mass_mars_cgs = YTQuantity(mass_mars_grams, 'g')
+mass_mars = mass_mars_cgs
+mars_mass = mass_mars_cgs
+
mass_saturn_cgs = YTQuantity(mass_saturn_grams, 'g')
+mass_saturn = mass_saturn_cgs
+saturn_mass = mass_saturn_cgs
+
mass_uranus_cgs = YTQuantity(mass_uranus_grams, 'g')
+mass_uranus = mass_uranus_cgs
+uranus_mass = mass_uranus_cgs
+
mass_neptune_cgs = YTQuantity(mass_neptune_grams, 'g')
+mass_neptune = mass_neptune_cgs
+neptune_mass = mass_neptune_cgs
-#Short cuts
-G = gravitational_constant_cgs
-me = mass_electron_cgs
-mp = mass_hydrogen_cgs
-qp = charge_proton_cgs
-mh = mp
-clight = speed_of_light_cgs
-speed_of_light = speed_of_light_cgs
-kboltz = boltzmann_constant_cgs
-kb = kboltz
-hcgs = planck_constant_cgs
-hbar = 0.5*hcgs/pi
-sigma_thompson = cross_section_thompson_cgs
-Na = 1 / amu_cgs
-
-#Planck units
+# Planck units
m_pl = planck_mass = YTQuantity(planck_mass_grams, "g")
l_pl = planck_length = YTQuantity(planck_length_cm, "cm")
t_pl = planck_time = YTQuantity(planck_time_s, "s")
@@ -62,5 +106,6 @@
q_pl = planck_charge = YTQuantity(planck_charge_esu, "esu")
T_pl = planck_temperature = YTQuantity(planck_temperature_K, "K")
+# MKS E&M units
mu_0 = YTQuantity(4.0e-7*pi, "N/A**2")
eps_0 = (1.0/(clight.in_mks()**2*mu_0)).in_units("C**2/N/m**2")
Repository URL: https://bitbucket.org/yt_analysis/yt/
--
This is a commit notification from bitbucket.org. You are receiving
this because you have the service enabled, addressing the recipient of
this email.
More information about the yt-svn
mailing list