[yt-svn] commit/yt: 12 new changesets
commits-noreply at bitbucket.org
commits-noreply at bitbucket.org
Mon Apr 14 12:08:17 PDT 2014
12 new commits in yt:
https://bitbucket.org/yt_analysis/yt/commits/6c5d709d1334/
Changeset: 6c5d709d1334
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-09 23:13:06
Summary: Adding mks conversions.
Affected #: 4 files
diff -r 794b2beb2c48272fed16de10daa07975309b950f -r 6c5d709d1334100499fc229e36015c3514a03362 yt/units/tests/test_ytarray.py
--- a/yt/units/tests/test_ytarray.py
+++ b/yt/units/tests/test_ytarray.py
@@ -325,23 +325,44 @@
yield assert_equal, km_in_cm, km
yield assert_equal, km_in_cm.in_cgs(), 1e5
+ yield assert_equal, km_in_cm.in_mks(), 1e3
yield assert_equal, km_in_cm.units, cm_unit
km.convert_to_units('cm')
yield assert_equal, km, YTQuantity(1, 'km')
yield assert_equal, km.in_cgs(), 1e5
+ yield assert_equal, km.in_mks(), 1e3
yield assert_equal, km.units, cm_unit
km.convert_to_units('kpc')
yield assert_array_almost_equal_nulp, km, YTQuantity(1, 'km')
yield assert_array_almost_equal_nulp, km.in_cgs(), YTQuantity(1e5, 'cm')
+ yield assert_array_almost_equal_nulp, km.in_mks(), YTQuantity(1e3, 'm')
yield assert_equal, km.units, kpc_unit
yield assert_isinstance, km.to_ndarray(), np.ndarray
yield assert_isinstance, km.ndarray_view(), np.ndarray
+ dyne = YTQuantity(1.0, 'dyne')
+
+ yield assert_equal, dyne.in_cgs(), dyne
+ yield assert_equal, dyne.in_cgs(), 1.0
+ yield assert_equal, dyne.in_mks(), dyne
+ yield assert_equal, dyne.in_mks(), 1e-5
+ yield assert_equal, str(dyne.in_mks().units), 'kg*m/s**2'
+ yield assert_equal, str(dyne.in_cgs().units), 'cm*g/s**2'
+
+ em3 = YTQuantity(1.0, 'erg/m**3')
+
+ yield assert_equal, em3.in_cgs(), em3
+ yield assert_equal, em3.in_cgs(), 1e-6
+ yield assert_equal, em3.in_mks(), em3
+ yield assert_equal, em3.in_mks(), 1e-7
+ yield assert_equal, str(em3.in_mks().units), 'kg/(m*s**2)'
+ yield assert_equal, str(em3.in_cgs().units), 'g/(cm*s**2)'
+
def test_yt_array_yt_quantity_ops():
"""
diff -r 794b2beb2c48272fed16de10daa07975309b950f -r 6c5d709d1334100499fc229e36015c3514a03362 yt/units/unit_lookup_table.py
--- a/yt/units/unit_lookup_table.py
+++ b/yt/units/unit_lookup_table.py
@@ -172,3 +172,11 @@
dimensions.temperature:'K',
dimensions.angle:'radian',
}
+
+mks_base_units = {
+ dimensions.mass:'kg',
+ dimensions.length:'m',
+ dimensions.time:'s',
+ dimensions.temperature:'K',
+ dimensions.angle:'radian',
+}
diff -r 794b2beb2c48272fed16de10daa07975309b950f -r 6c5d709d1334100499fc229e36015c3514a03362 yt/units/unit_object.py
--- a/yt/units/unit_object.py
+++ b/yt/units/unit_object.py
@@ -24,7 +24,8 @@
from yt.units import dimensions as dimensions_mod
from yt.units.unit_lookup_table import \
latex_symbol_lut, unit_prefixes, \
- prefixable_units, cgs_base_units
+ prefixable_units, cgs_base_units, \
+ mks_base_units
from yt.units.unit_registry import UnitRegistry
import copy
@@ -317,24 +318,34 @@
return False
return True
- # @todo: might be a simpler/smarter sympy way to do this...
+ def _get_system_equivalent(self, base_units):
+ # The dimensions of a unit object is the product of the base dimensions.
+ # Use sympy to factor the dimensions into base CGS unit symbols.
+ units = []
+ my_dims = self.dimensions.expand()
+ for dim in base_units:
+ unit_string = base_units[dim]
+ power_string = "**(%s)" % my_dims.as_coeff_exponent(dim)[1]
+ units.append("".join([unit_string, power_string]))
+ units_string = " * ".join(units)
+
+ return Unit(units_string, cgs_value=self.get_conversion_factor(units_string),
+ dimensions=self.dimensions, registry=self.registry)
+
+
def get_cgs_equivalent(self):
"""
Create and return dimensionally-equivalent cgs units.
"""
- # The dimensions of a unit object is the product of the base dimensions.
- # Use sympy to factor the dimensions into base CGS unit symbols.
- cgs_units = []
- my_dims = self.dimensions.expand()
- for dim in cgs_base_units:
- unit_string = cgs_base_units[dim]
- power_string = "**(%s)" % my_dims.as_coeff_exponent(dim)[1]
- cgs_units.append("".join([unit_string, power_string]))
- cgs_units_string = " * ".join(cgs_units)
+ return self._get_system_equivalent(cgs_base_units)
- return Unit(cgs_units_string, cgs_value=1.0,
- dimensions=self.dimensions, registry=self.registry)
+ def get_mks_equivalent(self):
+ """
+ Create and return dimensionally-equivalent mks units.
+
+ """
+ return self._get_system_equivalent(mks_base_units)
def get_conversion_factor(self, other_units):
return get_conversion_factor(self, other_units)
diff -r 794b2beb2c48272fed16de10daa07975309b950f -r 6c5d709d1334100499fc229e36015c3514a03362 yt/units/yt_array.py
--- a/yt/units/yt_array.py
+++ b/yt/units/yt_array.py
@@ -342,6 +342,13 @@
"""
return self.convert_to_units(self.units.get_cgs_equivalent())
+ def convert_to_mks(self):
+ """
+ Convert the array and units to the equivalent mks units.
+
+ """
+ return self.convert_to_units(self.units.get_mks_equivalent())
+
def in_units(self, units):
"""
Creates a copy of this array with the data in the supplied units, and
@@ -372,11 +379,23 @@
Returns
-------
- Quantity object with data converted to cgs and cgs units.
+ Quantity object with data converted to cgs units.
"""
return self.in_units(self.units.get_cgs_equivalent())
+ def in_mks(self):
+ """
+ Creates a copy of this array with the data in the equivalent mks units,
+ and returns it.
+
+ Returns
+ -------
+ Quantity object with data converted to mks units.
+
+ """
+ return self.in_units(self.units.get_mks_equivalent())
+
def ndarray_view(self):
"""
Returns a view into the array, but as an ndarray rather than ytarray.
https://bitbucket.org/yt_analysis/yt/commits/1aea5ba8236c/
Changeset: 1aea5ba8236c
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-10 07:41:27
Summary: Removing code units from the default symbol lut. Fixing everywhere that used this construction.
Affected #: 22 files
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/data_objects/construction_data_containers.py
--- a/yt/data_objects/construction_data_containers.py
+++ b/yt/data_objects/construction_data_containers.py
@@ -336,7 +336,8 @@
input_units=input_units,
registry=self.pf.unit_registry)
if self.weight_field is None:
- if Unit(units).is_code_unit and input_units != units:
+ u_obj = Unit(units, registry=self.pf.unit_registry)
+ if u_obj.is_code_unit and input_units != units:
if units is '':
final_unit = "code_length"
else:
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/data_objects/profiles.py
--- a/yt/data_objects/profiles.py
+++ b/yt/data_objects/profiles.py
@@ -782,11 +782,13 @@
The name of the new unit.
"""
if field in self.field_units:
- self.field_units[field] = Unit(new_unit)
+ self.field_units[field] = \
+ Unit(new_unit, registry=self.pf.unit_registry)
else:
fd = self.field_map[field]
if fd in self.field_units:
- self.field_units[fd] = Unit(new_unit)
+ self.field_units[fd] = \
+ Unit(new_unit, registry=self.pf.unit_registry)
else:
raise KeyError("%s not in profile!" % (field))
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/data_objects/selection_data_containers.py
--- a/yt/data_objects/selection_data_containers.py
+++ b/yt/data_objects/selection_data_containers.py
@@ -458,12 +458,12 @@
"""
if iterable(width):
assert_valid_width_tuple(width)
- width = YTQuantity(width[0], width[1])
+ width = self.pf.quan(width[0], width[1])
if height is None:
height = width
elif iterable(height):
assert_valid_width_tuple(height)
- height = YTQuantity(height[0], height[1])
+ height = self.pf.quan(height[0], height[1])
if not iterable(resolution):
resolution = (resolution, resolution)
from yt.visualization.fixed_resolution import ObliqueFixedResolutionBuffer
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/data_objects/static_output.py
--- a/yt/data_objects/static_output.py
+++ b/yt/data_objects/static_output.py
@@ -176,6 +176,7 @@
self._create_unit_registry()
self._parse_parameter_file()
+ self.set_units()
self._setup_coordinate_handler()
# Because we need an instantiated class to check the pf's existence in
@@ -187,7 +188,6 @@
pass
self.print_key_parameters()
- self.set_units()
self._set_derived_attrs()
self._setup_classes()
@@ -632,7 +632,7 @@
DW = np.zeros(3)
else:
DW = self.arr(self.domain_right_edge - self.domain_left_edge, "code_length")
- self.unit_registry.modify("unitary", DW.max())
+ self.unit_registry.add("unitary", float(DW.max()), DW.units.dimensions)
_arr = None
@property
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/data_objects/tests/test_projection.py
--- a/yt/data_objects/tests/test_projection.py
+++ b/yt/data_objects/tests/test_projection.py
@@ -56,7 +56,8 @@
proj_field
field_unit = Unit(fi.units)
if wf is not None:
- yield assert_equal, frb[proj_field].units, Unit(field_unit)
+ yield assert_equal, frb[proj_field].units, \
+ Unit(field_unit, registry=pf.unit_registry)
else:
if frb[proj_field].units.is_code_unit:
proj_unit = "code_length"
@@ -64,7 +65,8 @@
proj_unit = "cm"
if field_unit != '' and field_unit != Unit():
proj_unit = "({0}) * {1}".format(field_unit, proj_unit)
- yield assert_equal, frb[proj_field].units, Unit(proj_unit)
+ yield assert_equal, frb[proj_field].units, \
+ Unit(proj_unit, registry=pf.unit_registry)
yield assert_equal, frb[proj_field].info['xlim'], \
frb.bounds[:2]
yield assert_equal, frb[proj_field].info['ylim'], \
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/fields/field_detector.py
--- a/yt/fields/field_detector.py
+++ b/yt/fields/field_detector.py
@@ -178,12 +178,12 @@
def get_field_parameter(self, param, default = None):
self.requested_parameters.append(param)
if param in ['bulk_velocity', 'center', 'normal']:
- return YTArray(np.random.random(3) * 1e-2, self.fp_units[param])
+ return self.pf.arr(np.random.random(3) * 1e-2, self.fp_units[param])
elif param in ['axis']:
return 0
elif param.startswith("cp_"):
ax = param[3]
- rv = YTArray((0.0, 0.0, 0.0), self.fp_units[param])
+ rv = self.pf.arr((0.0, 0.0, 0.0), self.fp_units[param])
rv['xyz'.index(ax)] = 1.0
return rv
elif param == "fof_groups":
@@ -197,7 +197,7 @@
id = 1
def apply_units(self, arr, units):
- return YTArray(arr, input_units = units)
+ return self.pf.arr(arr, input_units = units)
def has_field_parameter(self, param):
return True
@@ -211,7 +211,7 @@
fc.shape = (self.nd*self.nd*self.nd, 3)
else:
fc = fc.transpose()
- return YTArray(fc, input_units = "code_length")
+ return self.pf.arr(fc, input_units = "code_length")
@property
def icoords(self):
@@ -236,5 +236,5 @@
fw = np.ones((self.nd**3, 3), dtype="float64") / self.nd
if not self.flat:
fw.shape = (self.nd, self.nd, self.nd, 3)
- return YTArray(fw, input_units = "code_length")
+ return self.pf.arr(fw, input_units = "code_length")
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/fields/field_info_container.py
--- a/yt/fields/field_info_container.py
+++ b/yt/fields/field_info_container.py
@@ -20,7 +20,8 @@
from numbers import Number as numeric_type
from yt.funcs import mylog, only_on_root
-from yt.units.unit_object import Unit
+from yt.units.unit_object import \
+ Unit, UnitParseError
from yt.units.yt_array import YTArray
from .derived_field import \
DerivedField, \
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/frontends/athena/data_structures.py
--- a/yt/frontends/athena/data_structures.py
+++ b/yt/frontends/athena/data_structures.py
@@ -384,6 +384,9 @@
self.magnetic_unit = np.sqrt(4*np.pi * self.mass_unit /
(self.time_unit**2 * self.length_unit))
self.magnetic_unit.convert_to_units("gauss")
+
+ def set_code_units(self):
+ super(self, AthenaDataset).set_code_units()
self.unit_registry.modify("code_magnetic", self.magnetic_unit)
def _parse_parameter_file(self):
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/frontends/boxlib/data_structures.py
--- a/yt/frontends/boxlib/data_structures.py
+++ b/yt/frontends/boxlib/data_structures.py
@@ -32,9 +32,6 @@
mpc_conversion, sec_conversion
from yt.utilities.parallel_tools.parallel_analysis_interface import \
parallel_root_only
-from yt.units.yt_array import \
- YTArray, \
- YTQuantity
from yt.utilities.lib.misc_utilities import \
get_box_grids_level
from yt.geometry.selection_routines import \
@@ -600,10 +597,10 @@
self._setup2d()
def _set_code_unit_attributes(self):
- self.length_unit = YTQuantity(1.0, "cm")
- self.mass_unit = YTQuantity(1.0, "g")
- self.time_unit = YTQuantity(1.0, "s")
- self.velocity_unit = YTQuantity(1.0, "cm/s")
+ self.length_unit = self.quan(1.0, "cm")
+ self.mass_unit = self.quan(1.0, "g")
+ self.time_unit = self.quan(1.0, "s")
+ self.velocity_unit = self.quan(1.0, "cm/s")
def _setup1d(self):
# self._index_class = BoxlibHierarchy1D
@@ -866,8 +863,7 @@
self.particle_types_raw = self.particle_types
def _set_code_unit_attributes(self):
- self.mass_unit = YTQuantity(1.0, "Msun")
- self.time_unit = YTQuantity(1.0 / 3.08568025e19, "s")
- self.length_unit = YTQuantity(1.0 / (1 + self.current_redshift),
- "mpc")
+ self.mass_unit = self.quan(1.0, "Msun")
+ self.time_unit = self.quan(1.0 / 3.08568025e19, "s")
+ self.length_unit = self.quan(1.0 / (1 + self.current_redshift), "Mpc")
self.velocity_unit = self.length_unit / self.time_unit
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/frontends/chombo/data_structures.py
--- a/yt/frontends/chombo/data_structures.py
+++ b/yt/frontends/chombo/data_structures.py
@@ -43,9 +43,6 @@
mpc_conversion, sec_conversion
from yt.utilities.parallel_tools.parallel_analysis_interface import \
parallel_root_only
-from yt.units.yt_array import \
- YTArray, \
- YTQuantity
from yt.utilities.lib.misc_utilities import \
get_box_grids_level
from yt.utilities.io_handler import \
@@ -225,10 +222,10 @@
self._handle.close()
def _set_code_unit_attributes(self):
- self.length_unit = YTQuantity(1.0, "cm")
- self.mass_unit = YTQuantity(1.0, "g")
- self.time_unit = YTQuantity(1.0, "s")
- self.velocity_unit = YTQuantity(1.0, "cm/s")
+ self.length_unit = self.quan(1.0, "cm")
+ self.mass_unit = self.quan(1.0, "g")
+ self.time_unit = self.quan(1.0, "s")
+ self.velocity_unit = self.quan(1.0, "cm/s")
def _localize(self, f, default):
if f is None:
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/frontends/enzo/data_structures.py
--- a/yt/frontends/enzo/data_structures.py
+++ b/yt/frontends/enzo/data_structures.py
@@ -868,7 +868,7 @@
self.unit_registry.modify("code_time", self.time_unit)
self.unit_registry.modify("code_velocity", self.velocity_unit)
DW = self.arr(self.domain_right_edge - self.domain_left_edge, "code_length")
- self.unit_registry.modify("unitary", DW.max())
+ self.unit_registry.add("unitary", float(DW.max()), DW.units.dimensions)
def cosmology_get_units(self):
"""
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/frontends/flash/data_structures.py
--- a/yt/frontends/flash/data_structures.py
+++ b/yt/frontends/flash/data_structures.py
@@ -34,7 +34,6 @@
io_registry
from yt.utilities.physical_constants import cm_per_mpc
from .fields import FLASHFieldInfo
-from yt.units.yt_array import YTQuantity
class FLASHGrid(AMRGridPatch):
_id_offset = 1
@@ -225,20 +224,19 @@
else:
length_factor = 1.0
temperature_factor = 1.0
- self.magnetic_unit = YTQuantity(b_factor, "gauss")
- self.length_unit = YTQuantity(length_factor, "cm")
- self.mass_unit = YTQuantity(1.0, "g")
- self.time_unit = YTQuantity(1.0, "s")
- self.velocity_unit = YTQuantity(1.0, "cm/s")
- self.temperature_unit = YTQuantity(temperature_factor, "K")
+ self.magnetic_unit = self.quan(b_factor, "gauss")
+ self.length_unit = self.quan(length_factor, "cm")
+ self.mass_unit = self.quan(1.0, "g")
+ self.time_unit = self.quan(1.0, "s")
+ self.velocity_unit = self.quan(1.0, "cm/s")
+ self.temperature_unit = self.quan(temperature_factor, "K")
# Still need to deal with:
#self.conversion_factors['temp'] = (1.0 + self.current_redshift)**-2.0
def set_code_units(self):
super(FLASHDataset, self).set_code_units()
- from yt.units.dimensions import dimensionless
self.unit_registry.modify("code_temperature",
- self.temperature_unit.value)
+ self.temperature_unit.value)
def _find_parameter(self, ptype, pname, scalar = False):
nn = "/%s %s" % (ptype,
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/frontends/flash/fields.py
--- a/yt/frontends/flash/fields.py
+++ b/yt/frontends/flash/fields.py
@@ -43,8 +43,6 @@
erg_units = "code_mass * (code_length/code_time)**2"
rho_units = "code_mass / code_length**3"
-Na_code = Na.in_units("1/code_mass")
-
class FLASHFieldInfo(FieldInfoContainer):
known_other_fields = (
("velx", ("code_length/code_time", ["velocity_x"], None)),
@@ -145,10 +143,12 @@
units="erg/g")
## Derived FLASH Fields
def _nele(field, data):
+ Na_code = data.pf.quan(Na, '1/code_mass')
return data["flash","dens"]*data["flash","ye"]*Na_code
self.add_field(('flash','nele'), function=_nele, units="code_length**-3")
self.add_field(('flash','edens'), function=_nele, units="code_length**-3")
def _nion(field, data):
+ Na_code = data.pf.quan(Na, '1/code_mass')
return data["flash","dens"]*data["flash","sumy"]*Na_code
self.add_field(('flash','nion'), function=_nion, units="code_length**-3")
def _abar(field, data):
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/frontends/ramses/data_structures.py
--- a/yt/frontends/ramses/data_structures.py
+++ b/yt/frontends/ramses/data_structures.py
@@ -29,7 +29,6 @@
from yt.data_objects.octree_subset import \
OctreeSubset
-from yt.units.yt_array import YTQuantity
from .definitions import ramses_header, field_aliases
from yt.utilities.lib.misc_utilities import \
get_box_grids_level
@@ -472,10 +471,10 @@
magnetic_unit = np.sqrt(4*np.pi * mass_unit /
(time_unit**2 * length_unit))
- self.magnetic_unit = YTQuantity(magnetic_unit, "gauss")
- self.length_unit = YTQuantity(length_unit, "cm")
- self.mass_unit = YTQuantity(mass_unit, "g")
- self.time_unit = YTQuantity(time_unit, "s")
+ self.magnetic_unit = self.quan(magnetic_unit, "gauss")
+ self.length_unit = self.quan(length_unit, "cm")
+ self.mass_unit = self.quan(mass_unit, "g")
+ self.time_unit = self.quan(time_unit, "s")
self.velocity_unit = self.length_unit / self.time_unit
def _parse_parameter_file(self):
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/geometry/tests/test_particle_octree.py
--- a/yt/geometry/tests/test_particle_octree.py
+++ b/yt/geometry/tests/test_particle_octree.py
@@ -9,6 +9,8 @@
from yt.utilities.lib.geometry_utils import get_morton_indices
from yt.frontends.stream.api import load_particles
from yt.geometry.selection_routines import RegionSelector, AlwaysSelector
+from yt.units.unit_registry import UnitRegistry
+import yt.units.dimensions as dimensions
import yt.data_objects.api
import time, os
@@ -127,22 +129,26 @@
domain_left_edge = None
domain_right_edge = None
domain_width = None
+ unit_registry = UnitRegistry()
+ unit_registry.add('code_length', 1.0, dimensions.length)
periodicity = (False, False, False)
class FakeRegion:
def __init__(self, nfiles):
self.pf = FakePF()
- self.pf.domain_left_edge = YTArray([0.0, 0.0, 0.0], "code_length")
- self.pf.domain_right_edge = YTArray([nfiles, nfiles, nfiles], "code_length")
+ self.pf.domain_left_edge = YTArray([0.0, 0.0, 0.0], "code_length",
+ registry=self.pf.unit_registry)
+ self.pf.domain_right_edge = YTArray([nfiles, nfiles, nfiles], "code_length",
+ registry=self.pf.unit_registry)
self.pf.domain_width = self.pf.domain_right_edge - \
self.pf.domain_left_edge
self.nfiles = nfiles
def set_edges(self, file_id):
self.left_edge = YTArray([file_id + 0.1, 0.0, 0.0],
- "code_length")
+ 'code_length', registry=self.pf.unit_registry)
self.right_edge = YTArray([file_id+1 - 0.1, self.nfiles, self.nfiles],
- "code_length")
+ 'code_length', registry=self.pf.unit_registry)
def test_particle_regions():
np.random.seed(int(0x4d3d3d3))
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/units/tests/test_units.py
--- a/yt/units/tests/test_units.py
+++ b/yt/units/tests/test_units.py
@@ -21,6 +21,7 @@
assert_allclose, assert_raises
from nose.tools import assert_true
from sympy import Symbol
+from yt.testing import fake_random_pf
# dimensions
from yt.units.dimensions import \
@@ -420,11 +421,12 @@
Msun_cgs / Mpc_cgs**3, 1e-12
def test_is_code_unit():
- u1 = Unit('code_mass')
- u2 = Unit('code_mass/code_length')
- u3 = Unit('code_velocity*code_mass**2')
- u4 = Unit('code_time*code_mass**0.5')
- u5 = Unit('code_mass*g')
+ pf = fake_random_pf(64, nprocs=1)
+ u1 = Unit('code_mass', registry=pf.unit_registry)
+ u2 = Unit('code_mass/code_length', registry=pf.unit_registry)
+ u3 = Unit('code_velocity*code_mass**2', registry=pf.unit_registry)
+ u4 = Unit('code_time*code_mass**0.5', registry=pf.unit_registry)
+ u5 = Unit('code_mass*g', registry=pf.unit_registry)
u6 = Unit('g/cm**3')
yield assert_true, u1.is_code_unit
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/units/unit_lookup_table.py
--- a/yt/units/unit_lookup_table.py
+++ b/yt/units/unit_lookup_table.py
@@ -32,17 +32,6 @@
"K": (1.0, dimensions.temperature),
"radian": (1.0, dimensions.angle),
- # "code" units, default to CGS conversion.
- # These default values are overridden in the code frontends
- "code_length" : (1.0, dimensions.length),
- "unitary" : (1.0, dimensions.length),
- "code_mass" : (1.0, dimensions.mass),
- "code_time" : (1.0, dimensions.time),
- "code_velocity" : (1.0, dimensions.velocity),
- "code_magnetic" : (1.0, dimensions.magnetic_field),
- "code_temperature" : (1.0, dimensions.temperature),
- "code_metallicity" : (1.0, dimensions.dimensionless),
-
# other cgs
"dyne": (1.0, dimensions.force),
"erg": (1.0, dimensions.energy),
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/units/unit_object.py
--- a/yt/units/unit_object.py
+++ b/yt/units/unit_object.py
@@ -137,7 +137,7 @@
"""
# Simplest case. If user passes a Unit object, just use the expr.
unit_key = None
- if isinstance(unit_expr, str):
+ if isinstance(unit_expr, basestring):
if registry and unit_expr in registry.unit_objs:
return registry.unit_objs[unit_expr]
else:
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/units/yt_array.py
--- a/yt/units/yt_array.py
+++ b/yt/units/yt_array.py
@@ -14,7 +14,6 @@
#-----------------------------------------------------------------------------
import copy
-
import numpy as np
from functools import wraps
@@ -29,7 +28,7 @@
isfinite, isinf, isnan, signbit, copysign, nextafter, modf, frexp, \
floor, ceil, trunc, fmax, fmin
-from yt.units.unit_object import Unit
+from yt.units.unit_object import Unit, UnitParseError
from yt.units.unit_registry import UnitRegistry
from yt.units.dimensions import dimensionless
from yt.utilities.exceptions import \
@@ -241,9 +240,19 @@
def __new__(cls, input_array, input_units=None, registry=None, dtype=np.float64):
if input_array is NotImplemented:
return input_array
+ if registry is None and isinstance(input_units, basestring):
+ if input_units.startswith('code_'):
+ raise UnitParseError(
+ "Code units used without referring to a dataset. \n"
+ "Perhaps you meant to do something like this instead: \n"
+ "ds.arr(%s, \"%s\")" % (input_array, input_units)
+ )
if isinstance(input_array, YTArray):
if input_units is None:
- pass
+ if registry is None:
+ pass
+ else:
+ input_array.units.registry = registry
elif isinstance(input_units, Unit):
input_array.units = input_units
else:
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/utilities/tests/test_selectors.py
--- a/yt/utilities/tests/test_selectors.py
+++ b/yt/utilities/tests/test_selectors.py
@@ -24,7 +24,7 @@
data = pf.sphere(center, 0.25)
# WARNING: this value has not be externally verified
dd = pf.h.all_data()
- dd.set_field_parameter("center", YTArray(center, 'code_length'))
+ dd.set_field_parameter("center", pf.arr(center, 'code_length'))
n_outside = (dd["radius"] >= 0.25).sum()
assert_equal(data["radius"].size + n_outside, dd["radius"].size)
@@ -55,7 +55,7 @@
data.get_data()
dd = pf.h.all_data()
- dd.set_field_parameter("center", YTArray(center, "code_length"))
+ dd.set_field_parameter("center", pf.arr(center, "code_length"))
n_outside = (dd["radius"] >= ratios[0]).sum()
assert_equal(data["radius"].size + n_outside, dd["radius"].size)
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/visualization/plot_window.py
--- a/yt/visualization/plot_window.py
+++ b/yt/visualization/plot_window.py
@@ -91,7 +91,7 @@
return (pf.quan(width[0], 'code_length'),
pf.quan(width[1], 'code_length'))
elif isinstance(width[0], YTQuantity) and isinstance(width[1], YTQuantity):
- return width
+ return (pf.quan(width[0]), pf.quan(width[1]))
else:
assert_valid_width_tuple(width)
# If width and unit are both valid width tuples, we
@@ -150,7 +150,7 @@
else:
raise RuntimeError('center keyword \"%s\" not recognized' % center)
elif isinstance(center, YTArray):
- pass
+ return pf.arr(center)
elif iterable(center):
if iterable(center[0]) and isinstance(center[1], basestring):
center = pf.arr(center[0], center[1])
@@ -791,7 +791,8 @@
colorbar_label = image.info['label']
# Determine the units of the data
- units = Unit(self._frb[f].units).latex_representation()
+ units = Unit(self._frb[f].units, registry=self.pf.unit_registry)
+ units = units.latex_representation()
if units is None or units == '':
pass
diff -r 6c5d709d1334100499fc229e36015c3514a03362 -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 yt/visualization/tests/test_plotwindow.py
--- a/yt/visualization/tests/test_plotwindow.py
+++ b/yt/visualization/tests/test_plotwindow.py
@@ -103,39 +103,39 @@
WIDTH_SPECS = {
# Width choices map to xlim, ylim, width, axes_unit_name 4-tuples
None : (
- (YTQuantity(0, 'code_length'), YTQuantity(1, 'code_length')),
- (YTQuantity(0, 'code_length'), YTQuantity(1, 'code_length')),
- (YTQuantity(1, 'code_length'), YTQuantity(1, 'code_length')),
+ ((0, 'code_length'), (1, 'code_length')),
+ ((0, 'code_length'), (1, 'code_length')),
+ ((1, 'code_length'), (1, 'code_length')),
None,
),
0.2 : (
- (YTQuantity(0.4, 'code_length'), YTQuantity(0.6, 'code_length')),
- (YTQuantity(0.4, 'code_length'), YTQuantity(0.6, 'code_length')),
- (YTQuantity(0.2, 'code_length'), YTQuantity(0.2, 'code_length')),
+ ((0.4, 'code_length'), (0.6, 'code_length')),
+ ((0.4, 'code_length'), (0.6, 'code_length')),
+ ((0.2, 'code_length'), (0.2, 'code_length')),
None,
),
(0.4, 0.3) : (
- (YTQuantity(0.3, 'code_length'), YTQuantity(0.7, 'code_length')),
- (YTQuantity(0.35, 'code_length'), YTQuantity(0.65, 'code_length')),
- (YTQuantity(0.4, 'code_length'), YTQuantity(0.3, 'code_length')),
+ ((0.3, 'code_length'), (0.7, 'code_length')),
+ ((0.35, 'code_length'), (0.65, 'code_length')),
+ ((0.4, 'code_length'), (0.3, 'code_length')),
None,
),
(1.2, 'cm') : (
- (YTQuantity(-0.1, 'code_length'), YTQuantity(1.1, 'code_length')),
- (YTQuantity(-0.1, 'code_length'), YTQuantity(1.1, 'code_length')),
- (YTQuantity(1.2, 'code_length'), YTQuantity(1.2, 'code_length')),
+ ((-0.1, 'code_length'), (1.1, 'code_length')),
+ ((-0.1, 'code_length'), (1.1, 'code_length')),
+ ((1.2, 'code_length'), (1.2, 'code_length')),
('cm', 'cm'),
),
((1.2, 'cm'), (2.0, 'cm')) : (
- (YTQuantity(-0.1, 'code_length'), YTQuantity(1.1, 'code_length')),
- (YTQuantity(-0.5, 'code_length'), YTQuantity(1.5, 'code_length')),
- (YTQuantity(1.2, 'code_length'), YTQuantity(2.0, 'code_length')),
+ ((-0.1, 'code_length'), (1.1, 'code_length')),
+ ((-0.5, 'code_length'), (1.5, 'code_length')),
+ ((1.2, 'code_length'), (2.0, 'code_length')),
('cm', 'cm'),
),
((1.2, 'cm'), (0.02, 'm')) : (
- (YTQuantity(-0.1, 'code_length'), YTQuantity(1.1, 'code_length')),
- (YTQuantity(-0.5, 'code_length'), YTQuantity(1.5, 'code_length')),
- (YTQuantity(1.2, 'code_length'), YTQuantity(2.0, 'code_length')),
+ ((-0.1, 'code_length'), (1.1, 'code_length')),
+ ((-0.5, 'code_length'), (1.5, 'code_length')),
+ ((1.2, 'code_length'), (2.0, 'code_length')),
('cm', 'm'),
),
}
@@ -300,6 +300,11 @@
def test_creation_with_width(self, width):
xlim, ylim, pwidth, aun = WIDTH_SPECS[width]
plot = self.projections_w[width]
+
+ xlim = [plot.pf.quan(el[0], el[1]) for el in xlim]
+ ylim = [plot.pf.quan(el[0], el[1]) for el in ylim]
+ pwidth = [plot.pf.quan(el[0], el[1]) for el in pwidth]
+
[assert_array_almost_equal(px, x, 14) for px, x in zip(plot.xlim, xlim)]
[assert_array_almost_equal(py, y, 14) for py, y in zip(plot.ylim, ylim)]
[assert_array_almost_equal(pw, w, 14) for pw, w in zip(plot.width, pwidth)]
https://bitbucket.org/yt_analysis/yt/commits/0c291753812c/
Changeset: 0c291753812c
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-10 07:57:38
Summary: Reverting some unnecessary changes to field_info_container.
Affected #: 1 file
diff -r 1aea5ba8236cb53fb986466af25ecb61bddb8021 -r 0c291753812c8e50b326d51de182e0dae0c91962 yt/fields/field_info_container.py
--- a/yt/fields/field_info_container.py
+++ b/yt/fields/field_info_container.py
@@ -20,8 +20,7 @@
from numbers import Number as numeric_type
from yt.funcs import mylog, only_on_root
-from yt.units.unit_object import \
- Unit, UnitParseError
+from yt.units.unit_object import Unit
from yt.units.yt_array import YTArray
from .derived_field import \
DerivedField, \
https://bitbucket.org/yt_analysis/yt/commits/99dce508200d/
Changeset: 99dce508200d
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-10 08:37:16
Summary: Fixing a bug in the SPH frontend.
Affected #: 1 file
diff -r 0c291753812c8e50b326d51de182e0dae0c91962 -r 99dce508200d00ba77194d4ee0b4f71839ccc90d yt/frontends/sph/io.py
--- a/yt/frontends/sph/io.py
+++ b/yt/frontends/sph/io.py
@@ -563,10 +563,12 @@
for ax in 'xyz':
mi = pp["Coordinates"][ax].min()
ma = pp["Coordinates"][ax].max()
- outlier = YTArray(np.max(np.abs((mi,ma))), 'code_length')
+ outlier = self.arr(np.max(np.abs((mi,ma))), 'code_length')
if outlier > pf.domain_right_edge or -outlier < pf.domain_left_edge:
- pf.domain_left_edge = -1.01*outlier # scale these up so the domain is slightly
- pf.domain_right_edge = 1.01*outlier # larger than the most distant particle position
+ # scale these up so the domain is slightly
+ # larger than the most distant particle position
+ pf.domain_left_edge = -1.01*outlier
+ pf.domain_right_edge = 1.01*outlier
ind += c
pf.domain_left_edge = np.ones(3)*pf.domain_left_edge
pf.domain_right_edge = np.ones(3)*pf.domain_right_edge
https://bitbucket.org/yt_analysis/yt/commits/c0ff5788441a/
Changeset: c0ff5788441a
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-10 09:57:42
Summary: Refactoring unit setting in the dataset initializer.
Affected #: 1 file
diff -r 99dce508200d00ba77194d4ee0b4f71839ccc90d -r c0ff5788441ac057944ef4d78bc95f51c3404594 yt/data_objects/static_output.py
--- a/yt/data_objects/static_output.py
+++ b/yt/data_objects/static_output.py
@@ -200,10 +200,6 @@
self.domain_width = self.domain_right_edge - self.domain_left_edge
if not isinstance(self.current_time, YTQuantity):
self.current_time = self.quan(self.current_time, "code_time")
- # need to do this if current_time was set before units were set
- elif self.current_time.units.registry.lut["code_time"] != \
- self.unit_registry.lut["code_time"]:
- self.current_time.units.registry = self.unit_registry
for attr in ("center", "width", "left_edge", "right_edge"):
n = "domain_%s" % attr
v = getattr(self, n)
@@ -568,12 +564,12 @@
def _create_unit_registry(self):
self.unit_registry = UnitRegistry()
import yt.units.dimensions as dimensions
- self.unit_registry.lut["code_length"] = (1.0, dimensions.length)
- self.unit_registry.lut["code_mass"] = (1.0, dimensions.mass)
- self.unit_registry.lut["code_time"] = (1.0, dimensions.time)
- self.unit_registry.lut["code_magnetic"] = (1.0, dimensions.magnetic_field)
- self.unit_registry.lut["code_temperature"] = (1.0, dimensions.temperature)
- self.unit_registry.lut["code_velocity"] = (1.0, dimensions.velocity)
+ self.unit_registry.add("code_length", 1.0, dimensions.length)
+ self.unit_registry.add("code_mass", 1.0, dimensions.mass)
+ self.unit_registry.add("code_time", 1.0, dimensions.time)
+ self.unit_registry.add("code_magnetic", 1.0, dimensions.magnetic_field)
+ self.unit_registry.add("code_temperature", 1.0, dimensions.temperature)
+ self.unit_registry.add("code_velocity", 1.0, dimensions.velocity)
def set_units(self):
"""
https://bitbucket.org/yt_analysis/yt/commits/990f3de43313/
Changeset: 990f3de43313
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-13 17:56:56
Summary: Updating the way length units are set in the SZ tests.
h/t to Kacper Kowalik for debugging this.
Affected #: 1 file
diff -r c0ff5788441ac057944ef4d78bc95f51c3404594 -r 990f3de433137ec57c6087b9250cedfe78ff2ff5 yt/analysis_modules/sunyaev_zeldovich/tests/test_projection.py
--- a/yt/analysis_modules/sunyaev_zeldovich/tests/test_projection.py
+++ b/yt/analysis_modules/sunyaev_zeldovich/tests/test_projection.py
@@ -86,12 +86,12 @@
data["velocity_y"] = (np.zeros(ddims), "cm/s")
data["velocity_z"] = (velz, "cm/s")
- bbox = np.array([[-0.5,0.5],[-0.5,0.5],[-0.5,0.5]])
+ L = 2 * R * cm_per_kpc
+ bbox = np.array([[-0.5,0.5],[-0.5,0.5],[-0.5,0.5]]) * L
- L = 2*R*cm_per_kpc
dl = L/nz
- pf = load_uniform_grid(data, ddims, length_unit=L, bbox=bbox)
+ pf = load_uniform_grid(data, ddims, length_unit='cm', bbox=bbox)
pf.h
return pf
https://bitbucket.org/yt_analysis/yt/commits/494243492f6d/
Changeset: 494243492f6d
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-14 00:24:49
Summary: Ensure the callback tests all clean up after themselves.
Affected #: 1 file
diff -r 990f3de433137ec57c6087b9250cedfe78ff2ff5 -r 494243492f6db11c803a9226491548fe08a01856 yt/visualization/tests/test_callbacks.py
--- a/yt/visualization/tests/test_callbacks.py
+++ b/yt/visualization/tests/test_callbacks.py
@@ -74,7 +74,7 @@
p = SlicePlot(pf, "x", "density")
p.annotate_velocity(factor=8, scale=0.5, scale_units="inches",
normalize = True)
- p.save()
+ p.save(prefix)
def test_magnetic_callback():
with _cleanup_fname() as prefix:
@@ -91,7 +91,7 @@
p = SlicePlot(pf, "x", "density")
p.annotate_magnetic_field(factor=8, scale=0.5,
scale_units="inches", normalize = True)
- p.save()
+ p.save(prefix)
def test_quiver_callback():
with _cleanup_fname() as prefix:
@@ -113,7 +113,7 @@
scale_units="inches", normalize = True,
bv_x = 0.5 * u.cm / u.s,
bv_y = 0.5 * u.cm / u.s)
- p.save()
+ p.save(prefix)
def test_contour_callback():
with _cleanup_fname() as prefix:
@@ -134,7 +134,7 @@
take_log=False, clim=(0.4, 0.6),
plot_args={'lw':2.0}, label=True,
label_args={'text-size':'x-large'})
- p.save()
+ p.save(prefix)
p = SlicePlot(pf, "x", "density")
s2 = pf.slice(0, 0.2)
@@ -143,7 +143,7 @@
plot_args={'lw':2.0}, label=True,
label_args={'text-size':'x-large'},
data_source=s2)
- p.save()
+ p.save(prefix)
def test_grids_callback():
with _cleanup_fname() as prefix:
https://bitbucket.org/yt_analysis/yt/commits/c04a525bd774/
Changeset: c04a525bd774
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-14 00:25:43
Summary: Refactoring the cgs/mks conversion functions. Adding is_cgs and is_mks properties.
Affected #: 1 file
diff -r 494243492f6db11c803a9226491548fe08a01856 -r c04a525bd77447d43562a585d7c2bd6626f5425b yt/units/unit_object.py
--- a/yt/units/unit_object.py
+++ b/yt/units/unit_object.py
@@ -318,7 +318,25 @@
return False
return True
- def _get_system_equivalent(self, base_units):
+ @property
+ def is_cgs(self):
+ for atom in self.expr.atoms():
+ if str(atom) in cgs_base_units.values() or atom.is_Number:
+ pass
+ else:
+ return False
+ return True
+
+ @property
+ def is_mks(self):
+ for atom in self.expr.atoms():
+ if str(atom) in mks_base_units.values() or atom.is_Number:
+ pass
+ else:
+ return False
+ return True
+
+ def _get_system_unit_string(self, base_units):
# The dimensions of a unit object is the product of the base dimensions.
# Use sympy to factor the dimensions into base CGS unit symbols.
units = []
@@ -327,10 +345,7 @@
unit_string = base_units[dim]
power_string = "**(%s)" % my_dims.as_coeff_exponent(dim)[1]
units.append("".join([unit_string, power_string]))
- units_string = " * ".join(units)
-
- return Unit(units_string, cgs_value=self.get_conversion_factor(units_string),
- dimensions=self.dimensions, registry=self.registry)
+ return " * ".join(units)
def get_cgs_equivalent(self):
@@ -338,14 +353,20 @@
Create and return dimensionally-equivalent cgs units.
"""
- return self._get_system_equivalent(cgs_base_units)
+ units_string = self._get_system_unit_string(cgs_base_units)
+ return Unit(units_string, cgs_value=1.0,
+ dimensions=self.dimensions, registry=self.registry)
def get_mks_equivalent(self):
"""
Create and return dimensionally-equivalent mks units.
"""
- return self._get_system_equivalent(mks_base_units)
+ units_string = self._get_system_unit_string(mks_base_units)
+ cgs_value = (get_conversion_factor(self, self.get_cgs_equivalent()) /
+ get_conversion_factor(self, units_string))
+ return Unit(units_string, cgs_value=cgs_value,
+ dimensions=self.dimensions, registry=self.registry)
def get_conversion_factor(self, other_units):
return get_conversion_factor(self, other_units)
https://bitbucket.org/yt_analysis/yt/commits/ec0321b41a6f/
Changeset: ec0321b41a6f
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-14 00:30:46
Summary: Merging with the tip of mainline.
Affected #: 5 files
diff -r c04a525bd77447d43562a585d7c2bd6626f5425b -r ec0321b41a6f4798e69770f4e2ca079ef138db41 yt/fields/field_info_container.py
--- a/yt/fields/field_info_container.py
+++ b/yt/fields/field_info_container.py
@@ -161,6 +161,8 @@
:class:`~yt.data_objects.api.DerivedField`.
"""
+ override = kwargs.pop("force_override", False)
+ if not override and name in self: return
if function is None:
def create_function(function):
self[name] = DerivedField(name, function, **kwargs)
diff -r c04a525bd77447d43562a585d7c2bd6626f5425b -r ec0321b41a6f4798e69770f4e2ca079ef138db41 yt/frontends/boxlib/data_structures.py
--- a/yt/frontends/boxlib/data_structures.py
+++ b/yt/frontends/boxlib/data_structures.py
@@ -42,7 +42,9 @@
cm_per_mpc
from .fields import \
- BoxlibFieldInfo
+ BoxlibFieldInfo, \
+ MaestroFieldInfo
+
from .io import IOHandlerBoxlib
# This is what we use to find scientific notation that might include d's
# instead of e's.
@@ -454,21 +456,7 @@
elif param == "castro.use_comoving":
vals = self.cosmological_simulation = int(vals)
else:
- # Now we guess some things about the parameter and its type
- v = vals.split()[0] # Just in case there are multiple; we'll go
- # back afterward to using vals.
- try:
- float(v.upper().replace("D","E"))
- except:
- pcast = str
- else:
- syms = (".", "D+", "D-", "E+", "E-")
- if any(sym in v.upper() for sym in syms for v in vals.split()):
- pcast = float
- else:
- pcast = int
- vals = [pcast(v) for v in vals.split()]
- if len(vals) == 1: vals = vals[0]
+ vals = _guess_pcast(vals)
self.parameters[param] = vals
if getattr(self, "cosmological_simulation", 0) == 1:
@@ -756,6 +744,8 @@
class MaestroDataset(BoxlibDataset):
+ _field_info_class = MaestroFieldInfo
+
@classmethod
def _is_valid(cls, *args, **kwargs):
# fill our args
@@ -772,6 +762,19 @@
if any("maestro" in line.lower() for line in lines): return True
return False
+ def _parse_parameter_file(self):
+ super(MaestroDataset, self)._parse_parameter_file()
+ jobinfo_filename = os.path.join(self.output_dir, "job_info")
+ line = ""
+ with open(jobinfo_filename, "r") as f:
+ while not line.startswith(" [*] indicates overridden default"):
+ line = f.next()
+ for line in f:
+ p, v = (_.strip() for _ in line[4:].split("="))
+ if len(v) == 0:
+ self.parameters[p] = ""
+ else:
+ self.parameters[p] = _guess_pcast(v)
class NyxHierarchy(BoxlibHierarchy):
@@ -867,3 +870,23 @@
self.time_unit = self.quan(1.0 / 3.08568025e19, "s")
self.length_unit = self.quan(1.0 / (1 + self.current_redshift), "Mpc")
self.velocity_unit = self.length_unit / self.time_unit
+
+def _guess_pcast(vals):
+ # Now we guess some things about the parameter and its type
+ v = vals.split()[0] # Just in case there are multiple; we'll go
+ # back afterward to using vals.
+ try:
+ float(v.upper().replace("D","E"))
+ except:
+ pcast = str
+ if v in ("F", "T"):
+ pcast = bool
+ else:
+ syms = (".", "D+", "D-", "E+", "E-")
+ if any(sym in v.upper() for sym in syms for v in vals.split()):
+ pcast = float
+ else:
+ pcast = int
+ vals = [pcast(v) for v in vals.split()]
+ if len(vals) == 1: vals = vals[0]
+ return vals
diff -r c04a525bd77447d43562a585d7c2bd6626f5425b -r ec0321b41a6f4798e69770f4e2ca079ef138db41 yt/frontends/boxlib/fields.py
--- a/yt/frontends/boxlib/fields.py
+++ b/yt/frontends/boxlib/fields.py
@@ -14,11 +14,16 @@
#-----------------------------------------------------------------------------
import numpy as np
+import string
from yt.utilities.physical_constants import \
mh, boltzmann_constant_cgs, amu_cgs
from yt.fields.field_info_container import \
FieldInfoContainer
+from yt.fields.species_fields import \
+ add_species_field_by_fraction
+from yt.utilities.chemical_formulas import \
+ ChemicalFormula
rho_units = "code_mass / code_length**3"
mom_units = "code_mass / (code_time * code_length**2)"
@@ -108,3 +113,90 @@
self.add_field(("gas", "velocity_%s" % ax),
function = _get_vel(ax),
units = "cm/s")
+
+class MaestroFieldInfo(FieldInfoContainer):
+
+ known_other_fields = (
+ ("density", ("g/cm**3", ["density"], None)),
+ ("x_vel", ("cm/s", ["velocity_x"], None)),
+ ("y_vel", ("cm/s", ["velocity_y"], None)),
+ ("z_vel", ("cm/s", ["velocity_z"], None)),
+ ("magvel", ("cm/s", ["velocity_magnitude"], None)),
+ ("tfromp", ("K", [], None)),
+ ("tfromh", ("K", [], None)),
+ ("Machnumber", ("", ["mach_number"], None)),
+ ("S", ("1/s", [], None)),
+ ("ad_excess", ("", [], "Adiabatic Excess")),
+ ("deltaT", ("", [], None)),
+ ("deltagamma", ("", [], None)),
+ ("deltap", ("", [], None)),
+ ("divw0", ("1/s", [], None)),
+ # Specific entropy
+ ("entropy", ("erg/(g*K)", ["entropy"], None)),
+ ("entropypert", ("", [], None)),
+ ("enucdot", ("ergs/(g*s)", [], None)),
+ ("gpi_x", ("dyne/cm**3", [], None)), # Perturbational pressure grad
+ ("gpi_y", ("dyne/cm**3", [], None)),
+ ("gpi_z", ("dyne/cm**3", [], None)),
+ ("h", ("erg/g", [], "Specific Enthalpy")),
+ ("h0", ("erg/g", [], "Base State Specific Enthalpy")),
+ # Momentum cannot be computed because we need to include base and
+ # full state.
+ ("momentum", ("g*cm/s", ["momentum_magnitude"], None)),
+ ("p0", ("erg/cm**3", [], None)),
+ ("p0pluspi", ("erg/cm**3", [], None)),
+ ("pi", ("erg/cm**3", [], None)),
+ ("pioverp0", ("", [], None)),
+ # Base state density
+ ("rho0", ("g/cm**3", [], None)),
+ ("rhoh", ("erg/cm**3", ["enthalpy_density"], None)),
+ # Base state enthalpy density
+ ("rhoh0", ("erg/cm**3", [], None)),
+ ("rhohpert", ("erg/cm**3", [], None)),
+ ("rhopert", ("g/cm**3", [], None)),
+ ("soundspeed", ("cm/s", ["sound_speed"], None)),
+ ("sponge", ("", [], None)),
+ ("tpert", ("K", [], None)),
+ # Again, base state -- so we can't compute ourselves.
+ ("vort", ("1/s", ["vorticity_magnitude"], None)),
+ # Base state
+ ("w0_x", ("cm/s", [], None)),
+ ("w0_y", ("cm/s", [], None)),
+ ("w0_z", ("cm/s", [], None)),
+ )
+
+ def setup_fluid_fields(self):
+ # Add omegadots, units of 1/s
+ if self.pf.parameters["use_tfromp"]:
+ self.alias(("gas", "temperature"), ("boxlib", "tfromp"),
+ units = "K")
+ else:
+ self.alias(("gas", "temperature"), ("boxlib", "tfromh"),
+ units = "K")
+
+ for _, field in self.pf.field_list:
+ if field.startswith("X("):
+ # We have a fraction
+ nice_name = field[2:-1]
+ self.alias(("gas", "%s_fraction" % nice_name), ("boxlib", field),
+ units = "")
+ def _create_density_func(field_name):
+ def _func(field, data):
+ return data[field_name] * data["gas", "density"]
+ return _func
+ func = _create_density_func(("gas", "%s_fraction" % nice_name))
+ self.add_field(name = ("gas", "%s_density" % nice_name),
+ function = func,
+ units = "g/cm**3")
+ # We know this will either have one letter, or two.
+ if field[3] in string.letters:
+ element, weight = field[2:4], field[4:-1]
+ else:
+ element, weight = field[2:3], field[3:-1]
+ weight = int(weight)
+ # Here we can, later, add number density.
+ if field.startswith("omegadot("):
+ nice_name = field[9:-1]
+ self.add_output_field(("boxlib", field), units = "1/s")
+ self.alias(("gas", "%s_creation_rate" % nice_name),
+ ("boxlib", field), units = "1/s")
diff -r c04a525bd77447d43562a585d7c2bd6626f5425b -r ec0321b41a6f4798e69770f4e2ca079ef138db41 yt/frontends/sph/data_structures.py
--- a/yt/frontends/sph/data_structures.py
+++ b/yt/frontends/sph/data_structures.py
@@ -563,6 +563,7 @@
@classmethod
def _is_valid(self, *args, **kwargs):
+ return False
field_dtypes = kwargs.get("field_dtypes", {})
return TipsyDataset._validate_header(args[0], field_dtypes)[0]
diff -r c04a525bd77447d43562a585d7c2bd6626f5425b -r ec0321b41a6f4798e69770f4e2ca079ef138db41 yt/visualization/volume_rendering/camera.py
--- a/yt/visualization/volume_rendering/camera.py
+++ b/yt/visualization/volume_rendering/camera.py
@@ -294,8 +294,9 @@
order += [0, 4, 1, 5, 2, 6, 3, 7]
vertices = np.empty([corners.shape[2]*2*12,3])
+ vertices = self.pf.arr(vertices, "code_length")
for i in xrange(3):
- vertices[:,i] = corners[order,i,:].ravel(order='F')
+ vertices[:,i] = corners[order,i,...].ravel(order='F')
px, py, dz = self.project_to_plane(vertices, res=im.shape[:2])
@@ -477,8 +478,9 @@
order += [0, 4, 1, 5, 2, 6, 3, 7]
vertices = np.empty([24,3])
+ vertices = self.pf.arr(vertices, "code_length")
for i in xrange(3):
- vertices[:,i] = corners[order,i,:].ravel(order='F')
+ vertices[:,i] = corners[order,i,...].ravel(order='F')
px, py, dz = self.project_to_plane(vertices, res=im.shape[:2])
https://bitbucket.org/yt_analysis/yt/commits/d59369fab508/
Changeset: d59369fab508
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-14 02:08:30
Summary: Adding documentation for MKS conversions. Cleaning up units docs a bit.
Affected #: 3 files
diff -r ec0321b41a6f4798e69770f4e2ca079ef138db41 -r d59369fab5084db2b1a01ccdf1a60b6108359e30 doc/source/analyzing/units/1)_Symbolic_Units.ipynb
--- a/doc/source/analyzing/units/1)_Symbolic_Units.ipynb
+++ b/doc/source/analyzing/units/1)_Symbolic_Units.ipynb
@@ -1,7 +1,7 @@
{
"metadata": {
"name": "",
- "signature": "sha256:52f186664831f5290b31ec433114927b9771e224bd79d0c82dd3d9a8d9c09bf6"
+ "signature": "sha256:5d881061b9e82bd9df5d3598983c8ddc5fbec35e3bf7ae4524430dc558e27489"
},
"nbformat": 3,
"nbformat_minor": 0,
@@ -307,7 +307,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "For convenience, `unit_quantity` is also available via `uq` and `unit_array` is available via `ua`:"
+ "For convenience, `unit_quantity` is also available via `uq` and `unit_array` is available via `ua`. You can use these arrays to create dummy arrays with the same units as another array - this is sometimes easier than manually creating a new array or quantity."
]
},
{
@@ -402,11 +402,13 @@
"\n",
"print a/b\n",
"print (a/b).in_cgs()\n",
+ "print (a/b).in_mks()\n",
"print (a/b).in_units('km/s')\n",
"print ''\n",
"\n",
"print a*b\n",
- "print (a*b).in_cgs()"
+ "print (a*b).in_cgs()\n",
+ "print (a*b).in_mks()"
],
"language": "python",
"metadata": {},
@@ -433,7 +435,10 @@
"from yt.utilities.physical_constants import G, kboltz\n",
"\n",
"print \"Newton's constant: \", G\n",
- "print \"Boltzmann constant: \", kboltz"
+ "print \"Newton's constant in MKS: \", G.in_mks(), \"\\n\"\n",
+ "\n",
+ "print \"Boltzmann constant: \", kboltz\n",
+ "print \"Boltzmann constant in MKS: \", kboltz.in_mks()"
],
"language": "python",
"metadata": {},
diff -r ec0321b41a6f4798e69770f4e2ca079ef138db41 -r d59369fab5084db2b1a01ccdf1a60b6108359e30 doc/source/analyzing/units/2)_Data_Selection_and_fields.ipynb
--- a/doc/source/analyzing/units/2)_Data_Selection_and_fields.ipynb
+++ b/doc/source/analyzing/units/2)_Data_Selection_and_fields.ipynb
@@ -1,7 +1,7 @@
{
"metadata": {
"name": "",
- "signature": "sha256:8e1a5db9e3869bcf761ff39c5a95d21458b7c4205f00da3d3f973d398422a466"
+ "signature": "sha256:9e7ac626b3609cf5f3fb2d4ebc6e027ed923ab1c22f0acc212e42fc7535e3205"
},
"nbformat": 3,
"nbformat_minor": 0,
@@ -73,6 +73,7 @@
"mass = dd['cell_mass']\n",
"\n",
"print \"Cell Masses in CGS: \\n\", mass, \"\\n\"\n",
+ "print \"Cell Masses in MKS: \\n\", mass.in_mks(), \"\\n\"\n",
"print \"Cell Masses in Solar Masses: \\n\", mass.in_units('Msun'), \"\\n\"\n",
"print \"Cell Masses in code units: \\n\", mass.in_units('code_mass'), \"\\n\""
],
@@ -87,6 +88,7 @@
"dx = dd['dx']\n",
"print \"Cell dx in code units: \\n\", dx, \"\\n\"\n",
"print \"Cell dx in centimeters: \\n\", dx.in_cgs(), \"\\n\"\n",
+ "print \"Cell dx in meters: \\n\", dx.in_units('m'), \"\\n\"\n",
"print \"Cell dx in megaparsecs: \\n\", dx.in_units('Mpc'), \"\\n\""
],
"language": "python",
@@ -109,8 +111,10 @@
"\n",
"* `in_units`\n",
"* `in_cgs`\n",
+ "* `in_mks`\n",
"* `convert_to_units`\n",
- "* `convert_to_cgs`"
+ "* `convert_to_cgs`\n",
+ "* `convert_to_mks`"
]
},
{
@@ -134,15 +138,16 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The second, `in_cgs`, returns a copy of the array converted into the base units of yt's CGS unit system:"
+ "`in_cgs` and `in_mks` return a copy of the array converted CGS and MKS units, respectively:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
- "print (dd['pressure']/dd['density'])\n",
- "print (dd['pressure']/dd['density']).in_cgs()"
+ "print (dd['pressure'])\n",
+ "print (dd['pressure']).in_cgs()\n",
+ "print (dd['pressure']).in_mks()"
],
"language": "python",
"metadata": {},
diff -r ec0321b41a6f4798e69770f4e2ca079ef138db41 -r d59369fab5084db2b1a01ccdf1a60b6108359e30 doc/source/analyzing/units/3)_Comoving_units_and_code_units.ipynb
--- a/doc/source/analyzing/units/3)_Comoving_units_and_code_units.ipynb
+++ b/doc/source/analyzing/units/3)_Comoving_units_and_code_units.ipynb
@@ -1,7 +1,7 @@
{
"metadata": {
"name": "",
- "signature": "sha256:a07224c25b1d938bc1014b6d9d09c1a2392912f21b821b07615e65302677ef9b"
+ "signature": "sha256:242d7005d45a82744713bfe6389e49d47f39b524d1e7fcbf5ceb2e65dc473e68"
},
"nbformat": 3,
"nbformat_minor": 0,
@@ -20,77 +20,6 @@
"level": 3,
"metadata": {},
"source": [
- "The unit registry"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "When a dataset is loaded, we attempt to detect and assign conversion factors from the internal simulation coordinate system and the physical CGS system. These conversion factors are stored in a `unit_registry` along with conversion factors to the other known unit symbols:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "from yt.mods import *\n",
- "\n",
- "ds = load('Enzo_64/DD0043/data0043')\n",
- "\n",
- "ds.unit_registry"
- ],
- "language": "python",
- "metadata": {},
- "outputs": []
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "ds.unit_registry.lut"
- ],
- "language": "python",
- "metadata": {},
- "outputs": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "It is not necessary to specify a unit registry when creating a new `YTArray` or `YTQuantity` since `yt` ships with a default unit registry:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "from yt.units.unit_object import default_unit_registry as reg\n",
- "\n",
- "unit_names = reg.lut.keys()\n",
- "unit_names.sort()\n",
- "\n",
- "# Print out the first 10 unit names\n",
- "for i in range(10):\n",
- " print unit_names[i], reg.lut[unit_names[i]]"
- ],
- "language": "python",
- "metadata": {},
- "outputs": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Each entry in the lookup table is the string name of a base unit and a tuple containing the CGS conversion factor and dimensions of the unit symbol."
- ]
- },
- {
- "cell_type": "heading",
- "level": 3,
- "metadata": {},
- "source": [
"Code units"
]
},
@@ -98,25 +27,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Some of the most interesting unit symbols are the ones for \"code\" units:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "code_unit_names = [un for un in unit_names if 'code_' in un]\n",
- "\n",
- "print code_unit_names"
- ],
- "language": "python",
- "metadata": {},
- "outputs": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
"Let's take a look at a cosmological enzo dataset to play with converting between physical units and code units:"
]
},
@@ -132,13 +42,22 @@
"outputs": []
},
{
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The conversion factors between Enzo's internal unit system and the physical CGS system are stored in the dataset's `unit_registry` object. Code units have names like `code_length` and `code_time`. Let's take a look at the names of all of the code units, along with their CGS conversion factors for this cosmological enzo dataset:"
+ ]
+ },
+ {
"cell_type": "code",
"collapsed": false,
"input": [
"reg = ds.unit_registry\n",
"\n",
- "for un in code_unit_names:\n",
- " print un, reg.lut[un]"
+ "for un in reg.keys():\n",
+ " if un.startswith('code_'):\n",
+ " fmt_tup = (un, reg.lut[un][0], reg.lut[un][1])\n",
+ " print \"Unit name: {:<15}\\nCGS conversion: {:<15}\\nDimensions: {:<15}\\n\".format(*fmt_tup)"
],
"language": "python",
"metadata": {},
@@ -295,6 +214,95 @@
"language": "python",
"metadata": {},
"outputs": []
+ },
+ {
+ "cell_type": "heading",
+ "level": 3,
+ "metadata": {},
+ "source": [
+ "The unit registry"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When you create a `YTArray` without referring to a unit registry, `yt` uses the default unit registry, which does not include code units or comoving units."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "a = YTQuantity(3, 'cm')\n",
+ "\n",
+ "print a.units.registry.keys()"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When a dataset is loaded, `yt` infers conversion factors from the internal simulation unit system to the CGS unit system. These conversion factors are stored in a `unit_registry` along with conversion factors to the other known unit symbols. For the cosmological Enzo dataset we loaded earlier, we can see there are a number of additional unit symbols not defined in the default unit lookup table:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "print sorted([k for k in ds.unit_registry.keys() if k not in a.units.registry.keys()])"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since code units do not appear in the default unit symbol lookup table, one must explicitly refer to a unit registry when creating a `YTArray` to be able to convert to the unit system of a simulation."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To make this as clean as possible, there are array and quantity-creating convenience functions attached to the `Dataset` object:\n",
+ "\n",
+ "* `ds.arr()`\n",
+ "* `ds.quan()`\n",
+ "\n",
+ "These functions make it straightforward to create arrays and quantities that can be converted to code units or comoving units. For example:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "a = ds.quan(3, 'code_length')\n",
+ "\n",
+ "print a\n",
+ "print a.in_cgs()\n",
+ "print a.in_units('Mpccm/h')"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "b = ds.arr([3, 4, 5], 'Mpccm/h')\n",
+ "print b\n",
+ "print b.in_cgs()"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": []
}
],
"metadata": {}
https://bitbucket.org/yt_analysis/yt/commits/242ec87c903d/
Changeset: 242ec87c903d
Branch: yt-3.0
User: ngoldbaum
Date: 2014-04-14 02:10:24
Summary: Removing is_cgs and is_mks since they are unneeded and use a dubious algorithm.
Affected #: 1 file
diff -r d59369fab5084db2b1a01ccdf1a60b6108359e30 -r 242ec87c903d5ad09e41f3c8bc9e30f9c14830e8 yt/units/unit_object.py
--- a/yt/units/unit_object.py
+++ b/yt/units/unit_object.py
@@ -318,24 +318,6 @@
return False
return True
- @property
- def is_cgs(self):
- for atom in self.expr.atoms():
- if str(atom) in cgs_base_units.values() or atom.is_Number:
- pass
- else:
- return False
- return True
-
- @property
- def is_mks(self):
- for atom in self.expr.atoms():
- if str(atom) in mks_base_units.values() or atom.is_Number:
- pass
- else:
- return False
- return True
-
def _get_system_unit_string(self, base_units):
# The dimensions of a unit object is the product of the base dimensions.
# Use sympy to factor the dimensions into base CGS unit symbols.
https://bitbucket.org/yt_analysis/yt/commits/eaf23ee4fc06/
Changeset: eaf23ee4fc06
Branch: yt-3.0
User: MatthewTurk
Date: 2014-04-14 21:08:08
Summary: Merged in ngoldbaum/yt/yt-3.0 (pull request #807)
Units updates: code units and MKS conversions
Affected #: 29 files
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 doc/source/analyzing/units/1)_Symbolic_Units.ipynb
--- a/doc/source/analyzing/units/1)_Symbolic_Units.ipynb
+++ b/doc/source/analyzing/units/1)_Symbolic_Units.ipynb
@@ -1,7 +1,7 @@
{
"metadata": {
"name": "",
- "signature": "sha256:52f186664831f5290b31ec433114927b9771e224bd79d0c82dd3d9a8d9c09bf6"
+ "signature": "sha256:5d881061b9e82bd9df5d3598983c8ddc5fbec35e3bf7ae4524430dc558e27489"
},
"nbformat": 3,
"nbformat_minor": 0,
@@ -307,7 +307,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "For convenience, `unit_quantity` is also available via `uq` and `unit_array` is available via `ua`:"
+ "For convenience, `unit_quantity` is also available via `uq` and `unit_array` is available via `ua`. You can use these arrays to create dummy arrays with the same units as another array - this is sometimes easier than manually creating a new array or quantity."
]
},
{
@@ -402,11 +402,13 @@
"\n",
"print a/b\n",
"print (a/b).in_cgs()\n",
+ "print (a/b).in_mks()\n",
"print (a/b).in_units('km/s')\n",
"print ''\n",
"\n",
"print a*b\n",
- "print (a*b).in_cgs()"
+ "print (a*b).in_cgs()\n",
+ "print (a*b).in_mks()"
],
"language": "python",
"metadata": {},
@@ -433,7 +435,10 @@
"from yt.utilities.physical_constants import G, kboltz\n",
"\n",
"print \"Newton's constant: \", G\n",
- "print \"Boltzmann constant: \", kboltz"
+ "print \"Newton's constant in MKS: \", G.in_mks(), \"\\n\"\n",
+ "\n",
+ "print \"Boltzmann constant: \", kboltz\n",
+ "print \"Boltzmann constant in MKS: \", kboltz.in_mks()"
],
"language": "python",
"metadata": {},
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 doc/source/analyzing/units/2)_Data_Selection_and_fields.ipynb
--- a/doc/source/analyzing/units/2)_Data_Selection_and_fields.ipynb
+++ b/doc/source/analyzing/units/2)_Data_Selection_and_fields.ipynb
@@ -1,7 +1,7 @@
{
"metadata": {
"name": "",
- "signature": "sha256:8e1a5db9e3869bcf761ff39c5a95d21458b7c4205f00da3d3f973d398422a466"
+ "signature": "sha256:9e7ac626b3609cf5f3fb2d4ebc6e027ed923ab1c22f0acc212e42fc7535e3205"
},
"nbformat": 3,
"nbformat_minor": 0,
@@ -73,6 +73,7 @@
"mass = dd['cell_mass']\n",
"\n",
"print \"Cell Masses in CGS: \\n\", mass, \"\\n\"\n",
+ "print \"Cell Masses in MKS: \\n\", mass.in_mks(), \"\\n\"\n",
"print \"Cell Masses in Solar Masses: \\n\", mass.in_units('Msun'), \"\\n\"\n",
"print \"Cell Masses in code units: \\n\", mass.in_units('code_mass'), \"\\n\""
],
@@ -87,6 +88,7 @@
"dx = dd['dx']\n",
"print \"Cell dx in code units: \\n\", dx, \"\\n\"\n",
"print \"Cell dx in centimeters: \\n\", dx.in_cgs(), \"\\n\"\n",
+ "print \"Cell dx in meters: \\n\", dx.in_units('m'), \"\\n\"\n",
"print \"Cell dx in megaparsecs: \\n\", dx.in_units('Mpc'), \"\\n\""
],
"language": "python",
@@ -109,8 +111,10 @@
"\n",
"* `in_units`\n",
"* `in_cgs`\n",
+ "* `in_mks`\n",
"* `convert_to_units`\n",
- "* `convert_to_cgs`"
+ "* `convert_to_cgs`\n",
+ "* `convert_to_mks`"
]
},
{
@@ -134,15 +138,16 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "The second, `in_cgs`, returns a copy of the array converted into the base units of yt's CGS unit system:"
+ "`in_cgs` and `in_mks` return a copy of the array converted CGS and MKS units, respectively:"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
- "print (dd['pressure']/dd['density'])\n",
- "print (dd['pressure']/dd['density']).in_cgs()"
+ "print (dd['pressure'])\n",
+ "print (dd['pressure']).in_cgs()\n",
+ "print (dd['pressure']).in_mks()"
],
"language": "python",
"metadata": {},
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 doc/source/analyzing/units/3)_Comoving_units_and_code_units.ipynb
--- a/doc/source/analyzing/units/3)_Comoving_units_and_code_units.ipynb
+++ b/doc/source/analyzing/units/3)_Comoving_units_and_code_units.ipynb
@@ -1,7 +1,7 @@
{
"metadata": {
"name": "",
- "signature": "sha256:a07224c25b1d938bc1014b6d9d09c1a2392912f21b821b07615e65302677ef9b"
+ "signature": "sha256:242d7005d45a82744713bfe6389e49d47f39b524d1e7fcbf5ceb2e65dc473e68"
},
"nbformat": 3,
"nbformat_minor": 0,
@@ -20,77 +20,6 @@
"level": 3,
"metadata": {},
"source": [
- "The unit registry"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "When a dataset is loaded, we attempt to detect and assign conversion factors from the internal simulation coordinate system and the physical CGS system. These conversion factors are stored in a `unit_registry` along with conversion factors to the other known unit symbols:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "from yt.mods import *\n",
- "\n",
- "ds = load('Enzo_64/DD0043/data0043')\n",
- "\n",
- "ds.unit_registry"
- ],
- "language": "python",
- "metadata": {},
- "outputs": []
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "ds.unit_registry.lut"
- ],
- "language": "python",
- "metadata": {},
- "outputs": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "\n",
- "It is not necessary to specify a unit registry when creating a new `YTArray` or `YTQuantity` since `yt` ships with a default unit registry:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "from yt.units.unit_object import default_unit_registry as reg\n",
- "\n",
- "unit_names = reg.lut.keys()\n",
- "unit_names.sort()\n",
- "\n",
- "# Print out the first 10 unit names\n",
- "for i in range(10):\n",
- " print unit_names[i], reg.lut[unit_names[i]]"
- ],
- "language": "python",
- "metadata": {},
- "outputs": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Each entry in the lookup table is the string name of a base unit and a tuple containing the CGS conversion factor and dimensions of the unit symbol."
- ]
- },
- {
- "cell_type": "heading",
- "level": 3,
- "metadata": {},
- "source": [
"Code units"
]
},
@@ -98,25 +27,6 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Some of the most interesting unit symbols are the ones for \"code\" units:"
- ]
- },
- {
- "cell_type": "code",
- "collapsed": false,
- "input": [
- "code_unit_names = [un for un in unit_names if 'code_' in un]\n",
- "\n",
- "print code_unit_names"
- ],
- "language": "python",
- "metadata": {},
- "outputs": []
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
"Let's take a look at a cosmological enzo dataset to play with converting between physical units and code units:"
]
},
@@ -132,13 +42,22 @@
"outputs": []
},
{
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The conversion factors between Enzo's internal unit system and the physical CGS system are stored in the dataset's `unit_registry` object. Code units have names like `code_length` and `code_time`. Let's take a look at the names of all of the code units, along with their CGS conversion factors for this cosmological enzo dataset:"
+ ]
+ },
+ {
"cell_type": "code",
"collapsed": false,
"input": [
"reg = ds.unit_registry\n",
"\n",
- "for un in code_unit_names:\n",
- " print un, reg.lut[un]"
+ "for un in reg.keys():\n",
+ " if un.startswith('code_'):\n",
+ " fmt_tup = (un, reg.lut[un][0], reg.lut[un][1])\n",
+ " print \"Unit name: {:<15}\\nCGS conversion: {:<15}\\nDimensions: {:<15}\\n\".format(*fmt_tup)"
],
"language": "python",
"metadata": {},
@@ -295,6 +214,95 @@
"language": "python",
"metadata": {},
"outputs": []
+ },
+ {
+ "cell_type": "heading",
+ "level": 3,
+ "metadata": {},
+ "source": [
+ "The unit registry"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When you create a `YTArray` without referring to a unit registry, `yt` uses the default unit registry, which does not include code units or comoving units."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "a = YTQuantity(3, 'cm')\n",
+ "\n",
+ "print a.units.registry.keys()"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When a dataset is loaded, `yt` infers conversion factors from the internal simulation unit system to the CGS unit system. These conversion factors are stored in a `unit_registry` along with conversion factors to the other known unit symbols. For the cosmological Enzo dataset we loaded earlier, we can see there are a number of additional unit symbols not defined in the default unit lookup table:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "print sorted([k for k in ds.unit_registry.keys() if k not in a.units.registry.keys()])"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": []
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Since code units do not appear in the default unit symbol lookup table, one must explicitly refer to a unit registry when creating a `YTArray` to be able to convert to the unit system of a simulation."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To make this as clean as possible, there are array and quantity-creating convenience functions attached to the `Dataset` object:\n",
+ "\n",
+ "* `ds.arr()`\n",
+ "* `ds.quan()`\n",
+ "\n",
+ "These functions make it straightforward to create arrays and quantities that can be converted to code units or comoving units. For example:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "a = ds.quan(3, 'code_length')\n",
+ "\n",
+ "print a\n",
+ "print a.in_cgs()\n",
+ "print a.in_units('Mpccm/h')"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": []
+ },
+ {
+ "cell_type": "code",
+ "collapsed": false,
+ "input": [
+ "b = ds.arr([3, 4, 5], 'Mpccm/h')\n",
+ "print b\n",
+ "print b.in_cgs()"
+ ],
+ "language": "python",
+ "metadata": {},
+ "outputs": []
}
],
"metadata": {}
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/analysis_modules/sunyaev_zeldovich/tests/test_projection.py
--- a/yt/analysis_modules/sunyaev_zeldovich/tests/test_projection.py
+++ b/yt/analysis_modules/sunyaev_zeldovich/tests/test_projection.py
@@ -86,12 +86,12 @@
data["velocity_y"] = (np.zeros(ddims), "cm/s")
data["velocity_z"] = (velz, "cm/s")
- bbox = np.array([[-0.5,0.5],[-0.5,0.5],[-0.5,0.5]])
+ L = 2 * R * cm_per_kpc
+ bbox = np.array([[-0.5,0.5],[-0.5,0.5],[-0.5,0.5]]) * L
- L = 2*R*cm_per_kpc
dl = L/nz
- pf = load_uniform_grid(data, ddims, length_unit=L, bbox=bbox)
+ pf = load_uniform_grid(data, ddims, length_unit='cm', bbox=bbox)
pf.h
return pf
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/data_objects/construction_data_containers.py
--- a/yt/data_objects/construction_data_containers.py
+++ b/yt/data_objects/construction_data_containers.py
@@ -336,7 +336,8 @@
input_units=input_units,
registry=self.pf.unit_registry)
if self.weight_field is None:
- if Unit(units).is_code_unit and input_units != units:
+ u_obj = Unit(units, registry=self.pf.unit_registry)
+ if u_obj.is_code_unit and input_units != units:
if units is '':
final_unit = "code_length"
else:
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/data_objects/profiles.py
--- a/yt/data_objects/profiles.py
+++ b/yt/data_objects/profiles.py
@@ -783,11 +783,13 @@
The name of the new unit.
"""
if field in self.field_units:
- self.field_units[field] = Unit(new_unit)
+ self.field_units[field] = \
+ Unit(new_unit, registry=self.pf.unit_registry)
else:
fd = self.field_map[field]
if fd in self.field_units:
- self.field_units[fd] = Unit(new_unit)
+ self.field_units[fd] = \
+ Unit(new_unit, registry=self.pf.unit_registry)
else:
raise KeyError("%s not in profile!" % (field))
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/data_objects/selection_data_containers.py
--- a/yt/data_objects/selection_data_containers.py
+++ b/yt/data_objects/selection_data_containers.py
@@ -458,12 +458,12 @@
"""
if iterable(width):
assert_valid_width_tuple(width)
- width = YTQuantity(width[0], width[1])
+ width = self.pf.quan(width[0], width[1])
if height is None:
height = width
elif iterable(height):
assert_valid_width_tuple(height)
- height = YTQuantity(height[0], height[1])
+ height = self.pf.quan(height[0], height[1])
if not iterable(resolution):
resolution = (resolution, resolution)
from yt.visualization.fixed_resolution import ObliqueFixedResolutionBuffer
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/data_objects/static_output.py
--- a/yt/data_objects/static_output.py
+++ b/yt/data_objects/static_output.py
@@ -176,6 +176,7 @@
self._create_unit_registry()
self._parse_parameter_file()
+ self.set_units()
self._setup_coordinate_handler()
# Because we need an instantiated class to check the pf's existence in
@@ -187,7 +188,6 @@
pass
self.print_key_parameters()
- self.set_units()
self._set_derived_attrs()
self._setup_classes()
@@ -200,10 +200,6 @@
self.domain_width = self.domain_right_edge - self.domain_left_edge
if not isinstance(self.current_time, YTQuantity):
self.current_time = self.quan(self.current_time, "code_time")
- # need to do this if current_time was set before units were set
- elif self.current_time.units.registry.lut["code_time"] != \
- self.unit_registry.lut["code_time"]:
- self.current_time.units.registry = self.unit_registry
for attr in ("center", "width", "left_edge", "right_edge"):
n = "domain_%s" % attr
v = getattr(self, n)
@@ -568,12 +564,12 @@
def _create_unit_registry(self):
self.unit_registry = UnitRegistry()
import yt.units.dimensions as dimensions
- self.unit_registry.lut["code_length"] = (1.0, dimensions.length)
- self.unit_registry.lut["code_mass"] = (1.0, dimensions.mass)
- self.unit_registry.lut["code_time"] = (1.0, dimensions.time)
- self.unit_registry.lut["code_magnetic"] = (1.0, dimensions.magnetic_field)
- self.unit_registry.lut["code_temperature"] = (1.0, dimensions.temperature)
- self.unit_registry.lut["code_velocity"] = (1.0, dimensions.velocity)
+ self.unit_registry.add("code_length", 1.0, dimensions.length)
+ self.unit_registry.add("code_mass", 1.0, dimensions.mass)
+ self.unit_registry.add("code_time", 1.0, dimensions.time)
+ self.unit_registry.add("code_magnetic", 1.0, dimensions.magnetic_field)
+ self.unit_registry.add("code_temperature", 1.0, dimensions.temperature)
+ self.unit_registry.add("code_velocity", 1.0, dimensions.velocity)
def set_units(self):
"""
@@ -632,7 +628,7 @@
DW = np.zeros(3)
else:
DW = self.arr(self.domain_right_edge - self.domain_left_edge, "code_length")
- self.unit_registry.modify("unitary", DW.max())
+ self.unit_registry.add("unitary", float(DW.max()), DW.units.dimensions)
_arr = None
@property
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/data_objects/tests/test_projection.py
--- a/yt/data_objects/tests/test_projection.py
+++ b/yt/data_objects/tests/test_projection.py
@@ -56,7 +56,8 @@
proj_field
field_unit = Unit(fi.units)
if wf is not None:
- yield assert_equal, frb[proj_field].units, Unit(field_unit)
+ yield assert_equal, frb[proj_field].units, \
+ Unit(field_unit, registry=pf.unit_registry)
else:
if frb[proj_field].units.is_code_unit:
proj_unit = "code_length"
@@ -64,7 +65,8 @@
proj_unit = "cm"
if field_unit != '' and field_unit != Unit():
proj_unit = "({0}) * {1}".format(field_unit, proj_unit)
- yield assert_equal, frb[proj_field].units, Unit(proj_unit)
+ yield assert_equal, frb[proj_field].units, \
+ Unit(proj_unit, registry=pf.unit_registry)
yield assert_equal, frb[proj_field].info['xlim'], \
frb.bounds[:2]
yield assert_equal, frb[proj_field].info['ylim'], \
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/fields/field_detector.py
--- a/yt/fields/field_detector.py
+++ b/yt/fields/field_detector.py
@@ -178,12 +178,12 @@
def get_field_parameter(self, param, default = None):
self.requested_parameters.append(param)
if param in ['bulk_velocity', 'center', 'normal']:
- return YTArray(np.random.random(3) * 1e-2, self.fp_units[param])
+ return self.pf.arr(np.random.random(3) * 1e-2, self.fp_units[param])
elif param in ['axis']:
return 0
elif param.startswith("cp_"):
ax = param[3]
- rv = YTArray((0.0, 0.0, 0.0), self.fp_units[param])
+ rv = self.pf.arr((0.0, 0.0, 0.0), self.fp_units[param])
rv['xyz'.index(ax)] = 1.0
return rv
elif param == "fof_groups":
@@ -197,7 +197,7 @@
id = 1
def apply_units(self, arr, units):
- return YTArray(arr, input_units = units)
+ return self.pf.arr(arr, input_units = units)
def has_field_parameter(self, param):
return True
@@ -211,7 +211,7 @@
fc.shape = (self.nd*self.nd*self.nd, 3)
else:
fc = fc.transpose()
- return YTArray(fc, input_units = "code_length")
+ return self.pf.arr(fc, input_units = "code_length")
@property
def icoords(self):
@@ -236,5 +236,5 @@
fw = np.ones((self.nd**3, 3), dtype="float64") / self.nd
if not self.flat:
fw.shape = (self.nd, self.nd, self.nd, 3)
- return YTArray(fw, input_units = "code_length")
+ return self.pf.arr(fw, input_units = "code_length")
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/frontends/athena/data_structures.py
--- a/yt/frontends/athena/data_structures.py
+++ b/yt/frontends/athena/data_structures.py
@@ -384,6 +384,9 @@
self.magnetic_unit = np.sqrt(4*np.pi * self.mass_unit /
(self.time_unit**2 * self.length_unit))
self.magnetic_unit.convert_to_units("gauss")
+
+ def set_code_units(self):
+ super(self, AthenaDataset).set_code_units()
self.unit_registry.modify("code_magnetic", self.magnetic_unit)
def _parse_parameter_file(self):
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/frontends/boxlib/data_structures.py
--- a/yt/frontends/boxlib/data_structures.py
+++ b/yt/frontends/boxlib/data_structures.py
@@ -32,9 +32,6 @@
mpc_conversion, sec_conversion
from yt.utilities.parallel_tools.parallel_analysis_interface import \
parallel_root_only
-from yt.units.yt_array import \
- YTArray, \
- YTQuantity
from yt.utilities.lib.misc_utilities import \
get_box_grids_level
from yt.geometry.selection_routines import \
@@ -588,10 +585,10 @@
self._setup2d()
def _set_code_unit_attributes(self):
- self.length_unit = YTQuantity(1.0, "cm")
- self.mass_unit = YTQuantity(1.0, "g")
- self.time_unit = YTQuantity(1.0, "s")
- self.velocity_unit = YTQuantity(1.0, "cm/s")
+ self.length_unit = self.quan(1.0, "cm")
+ self.mass_unit = self.quan(1.0, "g")
+ self.time_unit = self.quan(1.0, "s")
+ self.velocity_unit = self.quan(1.0, "cm/s")
def _setup1d(self):
# self._index_class = BoxlibHierarchy1D
@@ -883,10 +880,9 @@
self.particle_types_raw = self.particle_types
def _set_code_unit_attributes(self):
- self.mass_unit = YTQuantity(1.0, "Msun")
- self.time_unit = YTQuantity(1.0 / 3.08568025e19, "s")
- self.length_unit = YTQuantity(1.0 / (1 + self.current_redshift),
- "mpc")
+ self.mass_unit = self.quan(1.0, "Msun")
+ self.time_unit = self.quan(1.0 / 3.08568025e19, "s")
+ self.length_unit = self.quan(1.0 / (1 + self.current_redshift), "Mpc")
self.velocity_unit = self.length_unit / self.time_unit
def _guess_pcast(vals):
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/frontends/chombo/data_structures.py
--- a/yt/frontends/chombo/data_structures.py
+++ b/yt/frontends/chombo/data_structures.py
@@ -43,9 +43,6 @@
mpc_conversion, sec_conversion
from yt.utilities.parallel_tools.parallel_analysis_interface import \
parallel_root_only
-from yt.units.yt_array import \
- YTArray, \
- YTQuantity
from yt.utilities.lib.misc_utilities import \
get_box_grids_level
from yt.utilities.io_handler import \
@@ -225,10 +222,10 @@
self._handle.close()
def _set_code_unit_attributes(self):
- self.length_unit = YTQuantity(1.0, "cm")
- self.mass_unit = YTQuantity(1.0, "g")
- self.time_unit = YTQuantity(1.0, "s")
- self.velocity_unit = YTQuantity(1.0, "cm/s")
+ self.length_unit = self.quan(1.0, "cm")
+ self.mass_unit = self.quan(1.0, "g")
+ self.time_unit = self.quan(1.0, "s")
+ self.velocity_unit = self.quan(1.0, "cm/s")
def _localize(self, f, default):
if f is None:
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/frontends/enzo/data_structures.py
--- a/yt/frontends/enzo/data_structures.py
+++ b/yt/frontends/enzo/data_structures.py
@@ -868,7 +868,7 @@
self.unit_registry.modify("code_time", self.time_unit)
self.unit_registry.modify("code_velocity", self.velocity_unit)
DW = self.arr(self.domain_right_edge - self.domain_left_edge, "code_length")
- self.unit_registry.modify("unitary", DW.max())
+ self.unit_registry.add("unitary", float(DW.max()), DW.units.dimensions)
def cosmology_get_units(self):
"""
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/frontends/flash/data_structures.py
--- a/yt/frontends/flash/data_structures.py
+++ b/yt/frontends/flash/data_structures.py
@@ -34,7 +34,6 @@
io_registry
from yt.utilities.physical_constants import cm_per_mpc
from .fields import FLASHFieldInfo
-from yt.units.yt_array import YTQuantity
class FLASHGrid(AMRGridPatch):
_id_offset = 1
@@ -225,20 +224,19 @@
else:
length_factor = 1.0
temperature_factor = 1.0
- self.magnetic_unit = YTQuantity(b_factor, "gauss")
- self.length_unit = YTQuantity(length_factor, "cm")
- self.mass_unit = YTQuantity(1.0, "g")
- self.time_unit = YTQuantity(1.0, "s")
- self.velocity_unit = YTQuantity(1.0, "cm/s")
- self.temperature_unit = YTQuantity(temperature_factor, "K")
+ self.magnetic_unit = self.quan(b_factor, "gauss")
+ self.length_unit = self.quan(length_factor, "cm")
+ self.mass_unit = self.quan(1.0, "g")
+ self.time_unit = self.quan(1.0, "s")
+ self.velocity_unit = self.quan(1.0, "cm/s")
+ self.temperature_unit = self.quan(temperature_factor, "K")
# Still need to deal with:
#self.conversion_factors['temp'] = (1.0 + self.current_redshift)**-2.0
def set_code_units(self):
super(FLASHDataset, self).set_code_units()
- from yt.units.dimensions import dimensionless
self.unit_registry.modify("code_temperature",
- self.temperature_unit.value)
+ self.temperature_unit.value)
def _find_parameter(self, ptype, pname, scalar = False):
nn = "/%s %s" % (ptype,
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/frontends/flash/fields.py
--- a/yt/frontends/flash/fields.py
+++ b/yt/frontends/flash/fields.py
@@ -43,8 +43,6 @@
erg_units = "code_mass * (code_length/code_time)**2"
rho_units = "code_mass / code_length**3"
-Na_code = Na.in_units("1/code_mass")
-
class FLASHFieldInfo(FieldInfoContainer):
known_other_fields = (
("velx", ("code_length/code_time", ["velocity_x"], None)),
@@ -145,10 +143,12 @@
units="erg/g")
## Derived FLASH Fields
def _nele(field, data):
+ Na_code = data.pf.quan(Na, '1/code_mass')
return data["flash","dens"]*data["flash","ye"]*Na_code
self.add_field(('flash','nele'), function=_nele, units="code_length**-3")
self.add_field(('flash','edens'), function=_nele, units="code_length**-3")
def _nion(field, data):
+ Na_code = data.pf.quan(Na, '1/code_mass')
return data["flash","dens"]*data["flash","sumy"]*Na_code
self.add_field(('flash','nion'), function=_nion, units="code_length**-3")
def _abar(field, data):
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/frontends/ramses/data_structures.py
--- a/yt/frontends/ramses/data_structures.py
+++ b/yt/frontends/ramses/data_structures.py
@@ -29,7 +29,6 @@
from yt.data_objects.octree_subset import \
OctreeSubset
-from yt.units.yt_array import YTQuantity
from .definitions import ramses_header, field_aliases
from yt.utilities.lib.misc_utilities import \
get_box_grids_level
@@ -472,10 +471,10 @@
magnetic_unit = np.sqrt(4*np.pi * mass_unit /
(time_unit**2 * length_unit))
- self.magnetic_unit = YTQuantity(magnetic_unit, "gauss")
- self.length_unit = YTQuantity(length_unit, "cm")
- self.mass_unit = YTQuantity(mass_unit, "g")
- self.time_unit = YTQuantity(time_unit, "s")
+ self.magnetic_unit = self.quan(magnetic_unit, "gauss")
+ self.length_unit = self.quan(length_unit, "cm")
+ self.mass_unit = self.quan(mass_unit, "g")
+ self.time_unit = self.quan(time_unit, "s")
self.velocity_unit = self.length_unit / self.time_unit
def _parse_parameter_file(self):
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/frontends/sph/io.py
--- a/yt/frontends/sph/io.py
+++ b/yt/frontends/sph/io.py
@@ -563,10 +563,12 @@
for ax in 'xyz':
mi = pp["Coordinates"][ax].min()
ma = pp["Coordinates"][ax].max()
- outlier = YTArray(np.max(np.abs((mi,ma))), 'code_length')
+ outlier = self.arr(np.max(np.abs((mi,ma))), 'code_length')
if outlier > pf.domain_right_edge or -outlier < pf.domain_left_edge:
- pf.domain_left_edge = -1.01*outlier # scale these up so the domain is slightly
- pf.domain_right_edge = 1.01*outlier # larger than the most distant particle position
+ # scale these up so the domain is slightly
+ # larger than the most distant particle position
+ pf.domain_left_edge = -1.01*outlier
+ pf.domain_right_edge = 1.01*outlier
ind += c
pf.domain_left_edge = np.ones(3)*pf.domain_left_edge
pf.domain_right_edge = np.ones(3)*pf.domain_right_edge
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/geometry/tests/test_particle_octree.py
--- a/yt/geometry/tests/test_particle_octree.py
+++ b/yt/geometry/tests/test_particle_octree.py
@@ -9,6 +9,8 @@
from yt.utilities.lib.geometry_utils import get_morton_indices
from yt.frontends.stream.api import load_particles
from yt.geometry.selection_routines import RegionSelector, AlwaysSelector
+from yt.units.unit_registry import UnitRegistry
+import yt.units.dimensions as dimensions
import yt.data_objects.api
import time, os
@@ -127,22 +129,26 @@
domain_left_edge = None
domain_right_edge = None
domain_width = None
+ unit_registry = UnitRegistry()
+ unit_registry.add('code_length', 1.0, dimensions.length)
periodicity = (False, False, False)
class FakeRegion:
def __init__(self, nfiles):
self.pf = FakePF()
- self.pf.domain_left_edge = YTArray([0.0, 0.0, 0.0], "code_length")
- self.pf.domain_right_edge = YTArray([nfiles, nfiles, nfiles], "code_length")
+ self.pf.domain_left_edge = YTArray([0.0, 0.0, 0.0], "code_length",
+ registry=self.pf.unit_registry)
+ self.pf.domain_right_edge = YTArray([nfiles, nfiles, nfiles], "code_length",
+ registry=self.pf.unit_registry)
self.pf.domain_width = self.pf.domain_right_edge - \
self.pf.domain_left_edge
self.nfiles = nfiles
def set_edges(self, file_id):
self.left_edge = YTArray([file_id + 0.1, 0.0, 0.0],
- "code_length")
+ 'code_length', registry=self.pf.unit_registry)
self.right_edge = YTArray([file_id+1 - 0.1, self.nfiles, self.nfiles],
- "code_length")
+ 'code_length', registry=self.pf.unit_registry)
def test_particle_regions():
np.random.seed(int(0x4d3d3d3))
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/units/tests/test_units.py
--- a/yt/units/tests/test_units.py
+++ b/yt/units/tests/test_units.py
@@ -21,6 +21,7 @@
assert_allclose, assert_raises
from nose.tools import assert_true
from sympy import Symbol
+from yt.testing import fake_random_pf
# dimensions
from yt.units.dimensions import \
@@ -420,11 +421,12 @@
Msun_cgs / Mpc_cgs**3, 1e-12
def test_is_code_unit():
- u1 = Unit('code_mass')
- u2 = Unit('code_mass/code_length')
- u3 = Unit('code_velocity*code_mass**2')
- u4 = Unit('code_time*code_mass**0.5')
- u5 = Unit('code_mass*g')
+ pf = fake_random_pf(64, nprocs=1)
+ u1 = Unit('code_mass', registry=pf.unit_registry)
+ u2 = Unit('code_mass/code_length', registry=pf.unit_registry)
+ u3 = Unit('code_velocity*code_mass**2', registry=pf.unit_registry)
+ u4 = Unit('code_time*code_mass**0.5', registry=pf.unit_registry)
+ u5 = Unit('code_mass*g', registry=pf.unit_registry)
u6 = Unit('g/cm**3')
yield assert_true, u1.is_code_unit
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/units/tests/test_ytarray.py
--- a/yt/units/tests/test_ytarray.py
+++ b/yt/units/tests/test_ytarray.py
@@ -325,23 +325,44 @@
yield assert_equal, km_in_cm, km
yield assert_equal, km_in_cm.in_cgs(), 1e5
+ yield assert_equal, km_in_cm.in_mks(), 1e3
yield assert_equal, km_in_cm.units, cm_unit
km.convert_to_units('cm')
yield assert_equal, km, YTQuantity(1, 'km')
yield assert_equal, km.in_cgs(), 1e5
+ yield assert_equal, km.in_mks(), 1e3
yield assert_equal, km.units, cm_unit
km.convert_to_units('kpc')
yield assert_array_almost_equal_nulp, km, YTQuantity(1, 'km')
yield assert_array_almost_equal_nulp, km.in_cgs(), YTQuantity(1e5, 'cm')
+ yield assert_array_almost_equal_nulp, km.in_mks(), YTQuantity(1e3, 'm')
yield assert_equal, km.units, kpc_unit
yield assert_isinstance, km.to_ndarray(), np.ndarray
yield assert_isinstance, km.ndarray_view(), np.ndarray
+ dyne = YTQuantity(1.0, 'dyne')
+
+ yield assert_equal, dyne.in_cgs(), dyne
+ yield assert_equal, dyne.in_cgs(), 1.0
+ yield assert_equal, dyne.in_mks(), dyne
+ yield assert_equal, dyne.in_mks(), 1e-5
+ yield assert_equal, str(dyne.in_mks().units), 'kg*m/s**2'
+ yield assert_equal, str(dyne.in_cgs().units), 'cm*g/s**2'
+
+ em3 = YTQuantity(1.0, 'erg/m**3')
+
+ yield assert_equal, em3.in_cgs(), em3
+ yield assert_equal, em3.in_cgs(), 1e-6
+ yield assert_equal, em3.in_mks(), em3
+ yield assert_equal, em3.in_mks(), 1e-7
+ yield assert_equal, str(em3.in_mks().units), 'kg/(m*s**2)'
+ yield assert_equal, str(em3.in_cgs().units), 'g/(cm*s**2)'
+
def test_yt_array_yt_quantity_ops():
"""
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/units/unit_lookup_table.py
--- a/yt/units/unit_lookup_table.py
+++ b/yt/units/unit_lookup_table.py
@@ -32,17 +32,6 @@
"K": (1.0, dimensions.temperature),
"radian": (1.0, dimensions.angle),
- # "code" units, default to CGS conversion.
- # These default values are overridden in the code frontends
- "code_length" : (1.0, dimensions.length),
- "unitary" : (1.0, dimensions.length),
- "code_mass" : (1.0, dimensions.mass),
- "code_time" : (1.0, dimensions.time),
- "code_velocity" : (1.0, dimensions.velocity),
- "code_magnetic" : (1.0, dimensions.magnetic_field),
- "code_temperature" : (1.0, dimensions.temperature),
- "code_metallicity" : (1.0, dimensions.dimensionless),
-
# other cgs
"dyne": (1.0, dimensions.force),
"erg": (1.0, dimensions.energy),
@@ -172,3 +161,11 @@
dimensions.temperature:'K',
dimensions.angle:'radian',
}
+
+mks_base_units = {
+ dimensions.mass:'kg',
+ dimensions.length:'m',
+ dimensions.time:'s',
+ dimensions.temperature:'K',
+ dimensions.angle:'radian',
+}
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/units/unit_object.py
--- a/yt/units/unit_object.py
+++ b/yt/units/unit_object.py
@@ -24,7 +24,8 @@
from yt.units import dimensions as dimensions_mod
from yt.units.unit_lookup_table import \
latex_symbol_lut, unit_prefixes, \
- prefixable_units, cgs_base_units
+ prefixable_units, cgs_base_units, \
+ mks_base_units
from yt.units.unit_registry import UnitRegistry
import copy
@@ -136,7 +137,7 @@
"""
# Simplest case. If user passes a Unit object, just use the expr.
unit_key = None
- if isinstance(unit_expr, str):
+ if isinstance(unit_expr, basestring):
if registry and unit_expr in registry.unit_objs:
return registry.unit_objs[unit_expr]
else:
@@ -317,23 +318,36 @@
return False
return True
- # @todo: might be a simpler/smarter sympy way to do this...
+ def _get_system_unit_string(self, base_units):
+ # The dimensions of a unit object is the product of the base dimensions.
+ # Use sympy to factor the dimensions into base CGS unit symbols.
+ units = []
+ my_dims = self.dimensions.expand()
+ for dim in base_units:
+ unit_string = base_units[dim]
+ power_string = "**(%s)" % my_dims.as_coeff_exponent(dim)[1]
+ units.append("".join([unit_string, power_string]))
+ return " * ".join(units)
+
+
def get_cgs_equivalent(self):
"""
Create and return dimensionally-equivalent cgs units.
"""
- # The dimensions of a unit object is the product of the base dimensions.
- # Use sympy to factor the dimensions into base CGS unit symbols.
- cgs_units = []
- my_dims = self.dimensions.expand()
- for dim in cgs_base_units:
- unit_string = cgs_base_units[dim]
- power_string = "**(%s)" % my_dims.as_coeff_exponent(dim)[1]
- cgs_units.append("".join([unit_string, power_string]))
- cgs_units_string = " * ".join(cgs_units)
+ units_string = self._get_system_unit_string(cgs_base_units)
+ return Unit(units_string, cgs_value=1.0,
+ dimensions=self.dimensions, registry=self.registry)
- return Unit(cgs_units_string, cgs_value=1.0,
+ def get_mks_equivalent(self):
+ """
+ Create and return dimensionally-equivalent mks units.
+
+ """
+ units_string = self._get_system_unit_string(mks_base_units)
+ cgs_value = (get_conversion_factor(self, self.get_cgs_equivalent()) /
+ get_conversion_factor(self, units_string))
+ return Unit(units_string, cgs_value=cgs_value,
dimensions=self.dimensions, registry=self.registry)
def get_conversion_factor(self, other_units):
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/units/yt_array.py
--- a/yt/units/yt_array.py
+++ b/yt/units/yt_array.py
@@ -14,7 +14,6 @@
#-----------------------------------------------------------------------------
import copy
-
import numpy as np
from functools import wraps
@@ -29,7 +28,7 @@
isfinite, isinf, isnan, signbit, copysign, nextafter, modf, frexp, \
floor, ceil, trunc, fmax, fmin
-from yt.units.unit_object import Unit
+from yt.units.unit_object import Unit, UnitParseError
from yt.units.unit_registry import UnitRegistry
from yt.units.dimensions import dimensionless
from yt.utilities.exceptions import \
@@ -241,9 +240,19 @@
def __new__(cls, input_array, input_units=None, registry=None, dtype=np.float64):
if input_array is NotImplemented:
return input_array
+ if registry is None and isinstance(input_units, basestring):
+ if input_units.startswith('code_'):
+ raise UnitParseError(
+ "Code units used without referring to a dataset. \n"
+ "Perhaps you meant to do something like this instead: \n"
+ "ds.arr(%s, \"%s\")" % (input_array, input_units)
+ )
if isinstance(input_array, YTArray):
if input_units is None:
- pass
+ if registry is None:
+ pass
+ else:
+ input_array.units.registry = registry
elif isinstance(input_units, Unit):
input_array.units = input_units
else:
@@ -342,6 +351,13 @@
"""
return self.convert_to_units(self.units.get_cgs_equivalent())
+ def convert_to_mks(self):
+ """
+ Convert the array and units to the equivalent mks units.
+
+ """
+ return self.convert_to_units(self.units.get_mks_equivalent())
+
def in_units(self, units):
"""
Creates a copy of this array with the data in the supplied units, and
@@ -372,11 +388,23 @@
Returns
-------
- Quantity object with data converted to cgs and cgs units.
+ Quantity object with data converted to cgs units.
"""
return self.in_units(self.units.get_cgs_equivalent())
+ def in_mks(self):
+ """
+ Creates a copy of this array with the data in the equivalent mks units,
+ and returns it.
+
+ Returns
+ -------
+ Quantity object with data converted to mks units.
+
+ """
+ return self.in_units(self.units.get_mks_equivalent())
+
def ndarray_view(self):
"""
Returns a view into the array, but as an ndarray rather than ytarray.
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/utilities/tests/test_selectors.py
--- a/yt/utilities/tests/test_selectors.py
+++ b/yt/utilities/tests/test_selectors.py
@@ -24,7 +24,7 @@
data = pf.sphere(center, 0.25)
# WARNING: this value has not be externally verified
dd = pf.h.all_data()
- dd.set_field_parameter("center", YTArray(center, 'code_length'))
+ dd.set_field_parameter("center", pf.arr(center, 'code_length'))
n_outside = (dd["radius"] >= 0.25).sum()
assert_equal(data["radius"].size + n_outside, dd["radius"].size)
@@ -55,7 +55,7 @@
data.get_data()
dd = pf.h.all_data()
- dd.set_field_parameter("center", YTArray(center, "code_length"))
+ dd.set_field_parameter("center", pf.arr(center, "code_length"))
n_outside = (dd["radius"] >= ratios[0]).sum()
assert_equal(data["radius"].size + n_outside, dd["radius"].size)
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/visualization/plot_window.py
--- a/yt/visualization/plot_window.py
+++ b/yt/visualization/plot_window.py
@@ -91,7 +91,7 @@
return (pf.quan(width[0], 'code_length'),
pf.quan(width[1], 'code_length'))
elif isinstance(width[0], YTQuantity) and isinstance(width[1], YTQuantity):
- return width
+ return (pf.quan(width[0]), pf.quan(width[1]))
else:
assert_valid_width_tuple(width)
# If width and unit are both valid width tuples, we
@@ -150,7 +150,7 @@
else:
raise RuntimeError('center keyword \"%s\" not recognized' % center)
elif isinstance(center, YTArray):
- pass
+ return pf.arr(center)
elif iterable(center):
if iterable(center[0]) and isinstance(center[1], basestring):
center = pf.arr(center[0], center[1])
@@ -791,7 +791,8 @@
colorbar_label = image.info['label']
# Determine the units of the data
- units = Unit(self._frb[f].units).latex_representation()
+ units = Unit(self._frb[f].units, registry=self.pf.unit_registry)
+ units = units.latex_representation()
if units is None or units == '':
pass
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/visualization/tests/test_callbacks.py
--- a/yt/visualization/tests/test_callbacks.py
+++ b/yt/visualization/tests/test_callbacks.py
@@ -74,7 +74,7 @@
p = SlicePlot(pf, "x", "density")
p.annotate_velocity(factor=8, scale=0.5, scale_units="inches",
normalize = True)
- p.save()
+ p.save(prefix)
def test_magnetic_callback():
with _cleanup_fname() as prefix:
@@ -91,7 +91,7 @@
p = SlicePlot(pf, "x", "density")
p.annotate_magnetic_field(factor=8, scale=0.5,
scale_units="inches", normalize = True)
- p.save()
+ p.save(prefix)
def test_quiver_callback():
with _cleanup_fname() as prefix:
@@ -113,7 +113,7 @@
scale_units="inches", normalize = True,
bv_x = 0.5 * u.cm / u.s,
bv_y = 0.5 * u.cm / u.s)
- p.save()
+ p.save(prefix)
def test_contour_callback():
with _cleanup_fname() as prefix:
@@ -134,7 +134,7 @@
take_log=False, clim=(0.4, 0.6),
plot_args={'lw':2.0}, label=True,
label_args={'text-size':'x-large'})
- p.save()
+ p.save(prefix)
p = SlicePlot(pf, "x", "density")
s2 = pf.slice(0, 0.2)
@@ -143,7 +143,7 @@
plot_args={'lw':2.0}, label=True,
label_args={'text-size':'x-large'},
data_source=s2)
- p.save()
+ p.save(prefix)
def test_grids_callback():
with _cleanup_fname() as prefix:
diff -r 47cca121fc80b321c75546cfc39673e1b0feb366 -r eaf23ee4fc06dfd795eab718ef0ff39ab3fb6cb9 yt/visualization/tests/test_plotwindow.py
--- a/yt/visualization/tests/test_plotwindow.py
+++ b/yt/visualization/tests/test_plotwindow.py
@@ -103,39 +103,39 @@
WIDTH_SPECS = {
# Width choices map to xlim, ylim, width, axes_unit_name 4-tuples
None : (
- (YTQuantity(0, 'code_length'), YTQuantity(1, 'code_length')),
- (YTQuantity(0, 'code_length'), YTQuantity(1, 'code_length')),
- (YTQuantity(1, 'code_length'), YTQuantity(1, 'code_length')),
+ ((0, 'code_length'), (1, 'code_length')),
+ ((0, 'code_length'), (1, 'code_length')),
+ ((1, 'code_length'), (1, 'code_length')),
None,
),
0.2 : (
- (YTQuantity(0.4, 'code_length'), YTQuantity(0.6, 'code_length')),
- (YTQuantity(0.4, 'code_length'), YTQuantity(0.6, 'code_length')),
- (YTQuantity(0.2, 'code_length'), YTQuantity(0.2, 'code_length')),
+ ((0.4, 'code_length'), (0.6, 'code_length')),
+ ((0.4, 'code_length'), (0.6, 'code_length')),
+ ((0.2, 'code_length'), (0.2, 'code_length')),
None,
),
(0.4, 0.3) : (
- (YTQuantity(0.3, 'code_length'), YTQuantity(0.7, 'code_length')),
- (YTQuantity(0.35, 'code_length'), YTQuantity(0.65, 'code_length')),
- (YTQuantity(0.4, 'code_length'), YTQuantity(0.3, 'code_length')),
+ ((0.3, 'code_length'), (0.7, 'code_length')),
+ ((0.35, 'code_length'), (0.65, 'code_length')),
+ ((0.4, 'code_length'), (0.3, 'code_length')),
None,
),
(1.2, 'cm') : (
- (YTQuantity(-0.1, 'code_length'), YTQuantity(1.1, 'code_length')),
- (YTQuantity(-0.1, 'code_length'), YTQuantity(1.1, 'code_length')),
- (YTQuantity(1.2, 'code_length'), YTQuantity(1.2, 'code_length')),
+ ((-0.1, 'code_length'), (1.1, 'code_length')),
+ ((-0.1, 'code_length'), (1.1, 'code_length')),
+ ((1.2, 'code_length'), (1.2, 'code_length')),
('cm', 'cm'),
),
((1.2, 'cm'), (2.0, 'cm')) : (
- (YTQuantity(-0.1, 'code_length'), YTQuantity(1.1, 'code_length')),
- (YTQuantity(-0.5, 'code_length'), YTQuantity(1.5, 'code_length')),
- (YTQuantity(1.2, 'code_length'), YTQuantity(2.0, 'code_length')),
+ ((-0.1, 'code_length'), (1.1, 'code_length')),
+ ((-0.5, 'code_length'), (1.5, 'code_length')),
+ ((1.2, 'code_length'), (2.0, 'code_length')),
('cm', 'cm'),
),
((1.2, 'cm'), (0.02, 'm')) : (
- (YTQuantity(-0.1, 'code_length'), YTQuantity(1.1, 'code_length')),
- (YTQuantity(-0.5, 'code_length'), YTQuantity(1.5, 'code_length')),
- (YTQuantity(1.2, 'code_length'), YTQuantity(2.0, 'code_length')),
+ ((-0.1, 'code_length'), (1.1, 'code_length')),
+ ((-0.5, 'code_length'), (1.5, 'code_length')),
+ ((1.2, 'code_length'), (2.0, 'code_length')),
('cm', 'm'),
),
}
@@ -300,6 +300,11 @@
def test_creation_with_width(self, width):
xlim, ylim, pwidth, aun = WIDTH_SPECS[width]
plot = self.projections_w[width]
+
+ xlim = [plot.pf.quan(el[0], el[1]) for el in xlim]
+ ylim = [plot.pf.quan(el[0], el[1]) for el in ylim]
+ pwidth = [plot.pf.quan(el[0], el[1]) for el in pwidth]
+
[assert_array_almost_equal(px, x, 14) for px, x in zip(plot.xlim, xlim)]
[assert_array_almost_equal(py, y, 14) for py, y in zip(plot.ylim, ylim)]
[assert_array_almost_equal(pw, w, 14) for pw, w in zip(plot.width, pwidth)]
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