def test_multiplication(): """ Multiply two units. """ msun_cgs = mass_sun_grams pc_cgs = cm_per_pc # Create symbols msun_sym = Symbol("Msun", positive=True) pc_sym = Symbol("pc", positive=True) s_sym = Symbol("s", positive=True) # Create units u1 = Unit("Msun") u2 = Unit("pc") # Mul operation u3 = u1 * u2 assert_true(u3.expr == msun_sym * pc_sym) assert_allclose_units(u3.base_value, msun_cgs * pc_cgs, 1e-12) assert_true(u3.dimensions == mass * length) # Pow and Mul operations u4 = Unit("pc**2") u5 = Unit("Msun * s") u6 = u4 * u5 assert_true(u6.expr == pc_sym**2 * msun_sym * s_sym) assert_allclose_units(u6.base_value, pc_cgs**2 * msun_cgs, 1e-12) assert_true(u6.dimensions == length**2 * mass * time)
def test_create_new_symbol(): """ Create unit with unknown symbol. """ u1 = Unit("abc", base_value=42, dimensions=(mass/time)) yield assert_true, u1.expr == Symbol("abc", positive=True) yield assert_true, u1.base_value == 42 yield assert_true, u1.dimensions == mass / time u1 = Unit("abc", base_value=42, dimensions=length**3) yield assert_true, u1.expr == Symbol("abc", positive=True) yield assert_true, u1.base_value == 42 yield assert_true, u1.dimensions == length**3 u1 = Unit("abc", base_value=42, dimensions=length*(mass*length)) yield assert_true, u1.expr == Symbol("abc", positive=True) yield assert_true, u1.base_value == 42 yield assert_true, u1.dimensions == length**2*mass assert_raises(UnitParseError, Unit, 'abc', base_value=42, dimensions=length**length) assert_raises(UnitParseError, Unit, 'abc', base_value=42, dimensions=length**(length*length)) assert_raises(UnitParseError, Unit, 'abc', base_value=42, dimensions=length-mass) assert_raises(UnitParseError, Unit, 'abc', base_value=42, dimensions=length+mass)
def test_base_equivalent(): """ Check base equivalent of a unit. """ Msun_cgs = mass_sun_grams Mpc_cgs = cm_per_mpc u1 = Unit("Msun * Mpc**-3") u2 = Unit("g * cm**-3") u3 = u1.get_base_equivalent() assert_true(u2.expr == u3.expr) assert_true(u2 == u3) assert_allclose_units(u1.base_value, Msun_cgs / Mpc_cgs**3, 1e-12) assert_true(u2.base_value == 1) assert_true(u3.base_value == 1) mass_density = mass / length**3 assert_true(u1.dimensions == mass_density) assert_true(u2.dimensions == mass_density) assert_true(u3.dimensions == mass_density) assert_allclose_units( get_conversion_factor(u1, u3)[0], Msun_cgs / Mpc_cgs**3, 1e-12)
def get_label(self, projected=False): """ Return a data label for the given field, including units. """ name = self.name[1] if self.display_name is not None: name = self.display_name # Start with the field name data_label = r"$\rm{%s}" % name # Grab the correct units if projected: raise NotImplementedError else: if self.ds is not None: units = Unit(self.units, registry=self.ds.unit_registry) else: units = Unit(self.units) # Add unit label if not units.is_dimensionless: data_label += r"\ \ (%s)" % (units.latex_representation()) data_label += r"$" return data_label
def test_create_from_expr(): """ Create units from sympy Exprs and check attributes. """ pc_cgs = cm_per_pc yr_cgs = sec_per_year # Symbol expr s1 = Symbol("pc", positive=True) s2 = Symbol("yr", positive=True) # Mul expr s3 = s1 * s2 # Pow expr s4 = s1**2 * s2**(-1) u1 = Unit(s1) u2 = Unit(s2) u3 = Unit(s3) u4 = Unit(s4) assert_true(u1.expr == s1) assert_true(u2.expr == s2) assert_true(u3.expr == s3) assert_true(u4.expr == s4) assert_allclose_units(u1.base_value, pc_cgs, 1e-12) assert_allclose_units(u2.base_value, yr_cgs, 1e-12) assert_allclose_units(u3.base_value, pc_cgs * yr_cgs, 1e-12) assert_allclose_units(u4.base_value, pc_cgs**2 / yr_cgs, 1e-12) assert_true(u1.dimensions == length) assert_true(u2.dimensions == time) assert_true(u3.dimensions == length * time) assert_true(u4.dimensions == length**2 / time)
def test_cgs_equivalent(): """ Check cgs equivalent of a unit. """ Msun_cgs = mass_sun_grams Mpc_cgs = cm_per_mpc u1 = Unit("Msun * Mpc**-3") u2 = Unit("g * cm**-3") u3 = u1.get_cgs_equivalent() yield assert_true, u2.expr == u3.expr yield assert_true, u2 == u3 yield assert_allclose, u1.cgs_value, Msun_cgs / Mpc_cgs**3, 1e-12 yield assert_true, u2.cgs_value == 1 yield assert_true, u3.cgs_value == 1 mass_density = mass / length**3 yield assert_true, u1.dimensions == mass_density yield assert_true, u2.dimensions == mass_density yield assert_true, u3.dimensions == mass_density yield assert_allclose, get_conversion_factor(u1, u3)[0], \ Msun_cgs / Mpc_cgs**3, 1e-12
def test_create_new_symbol(): """ Create unit with unknown symbol. """ u1 = Unit("abc", cgs_value=42, dimensions=(mass/time)) yield assert_true, u1.expr == Symbol("abc", positive=True) yield assert_true, u1.cgs_value == 42 yield assert_true, u1.dimensions == mass / time u1 = Unit("abc", cgs_value=42, dimensions=length**3) yield assert_true, u1.expr == Symbol("abc", positive=True) yield assert_true, u1.cgs_value == 42 yield assert_true, u1.dimensions == length**3 u1 = Unit("abc", cgs_value=42, dimensions=length*(mass*length)) yield assert_true, u1.expr == Symbol("abc", positive=True) yield assert_true, u1.cgs_value == 42 yield assert_true, u1.dimensions == length**2*mass yield assert_raises, UnitParseError, Unit, 'abc', \ {'cgs_value':42, 'dimensions':length**length} yield assert_raises, UnitParseError, Unit, 'abc', \ {'cgs_value':42, 'dimensions':length**(length*length)} yield assert_raises, UnitParseError, Unit, 'abc', \ {'cgs_value':42, 'dimensions':length-mass} yield assert_raises, UnitParseError, Unit, 'abc', \ {'cgs_value':42, 'dimensions':length+mass}
def _get_axes_unit_labels(self, unit_x, unit_y): axes_unit_labels = ['', ''] comoving = False hinv = False for i, un in enumerate((unit_x, unit_y)): unn = None if hasattr(self.data_source, 'axis'): if hasattr(self.ds.coordinates, "image_units"): # This *forces* an override unn = self.ds.coordinates.image_units[ self.data_source.axis][i] elif hasattr(self.ds.coordinates, "default_unit_label"): axax = getattr(self.ds.coordinates, "%s_axis" % ("xy"[i]))[self.data_source.axis] unn = self.ds.coordinates.default_unit_label.get( axax, None) if unn is not None: axes_unit_labels[i] = r'\ \ \left(' + unn + r'\right)' continue # Use sympy to factor h out of the unit. In this context 'un' # is a string, so we call the Unit constructor. expr = Unit(un, registry=self.ds.unit_registry).expr h_expr = Unit('h', registry=self.ds.unit_registry).expr # See http://docs.sympy.org/latest/modules/core.html#sympy.core.expr.Expr h_power = expr.as_coeff_exponent(h_expr)[1] # un is now the original unit, but with h factored out. un = str(expr * h_expr**(-1 * h_power)) un_unit = Unit(un, registry=self.ds.unit_registry) cm = Unit('cm').expr if str(un).endswith('cm') and cm not in un_unit.expr.atoms(): comoving = True un = un[:-2] # no length units besides code_length end in h so this is safe if h_power == -1: hinv = True elif h_power != 0: # It doesn't make sense to scale a position by anything # other than h**-1 raise RuntimeError if un not in ['1', 'u', 'unitary']: if un in formatted_length_unit_names: un = formatted_length_unit_names[un] else: un = Unit(un, registry=self.ds.unit_registry) un = un.latex_representation() if hinv: un = un + '\,h^{-1}' if comoving: un = un + '\,(1+z)^{-1}' pp = un[0] if pp in latex_prefixes: symbol_wo_prefix = un[1:] if symbol_wo_prefix in prefixable_units: un = un.replace(pp, "{" + latex_prefixes[pp] + "}", 1) axes_unit_labels[i] = '\ \ (' + un + ')' return axes_unit_labels
def test_equality(): """ Check unit equality with different symbols, but same dimensions and base_value. """ u1 = Unit("km * s**-1") u2 = Unit("m * ms**-1") assert_true(u1 == u2)
def test_unit_systems(): goofy_unit_system = UnitSystem("goofy", "ly", "lbm", "hr", temperature_unit="R", angle_unit="arcsec", current_mks_unit="mA") assert goofy_unit_system["temperature"] == Unit("R") assert goofy_unit_system[dimensions.solid_angle] == Unit("arcsec**2") assert goofy_unit_system["energy"] == Unit("lbm*ly**2/hr**2") goofy_unit_system["energy"] = "eV" assert goofy_unit_system["energy"] == Unit("eV") assert goofy_unit_system["magnetic_field_mks"] == Unit("lbm/(hr**2*mA)") assert "goofy" in unit_system_registry
def test_unit_conversions(): """ Test operations that convert to different units or cast to ndarray """ from yt.units.yt_array import YTQuantity from yt.units.unit_object import Unit km = YTQuantity(1, 'km') km_in_cm = km.in_units('cm') cm_unit = Unit('cm') kpc_unit = Unit('kpc') 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_view = km.ndarray_view() km.convert_to_units('cm') assert_true(km_view.base is km.base) 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') assert_true(km_view.base is km.base) 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 __new__(cls, input_array, input_units=None, registry=None, dtype=None): if dtype is None: dtype = getattr(input_array, 'dtype', np.float64) if input_array is NotImplemented: return input_array if registry is None and isinstance(input_units, (str, bytes)): 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: if registry is None: pass else: input_array.units.registry = registry elif isinstance(input_units, Unit): input_array.units = input_units else: input_array.units = Unit(input_units, registry=registry) return input_array elif isinstance(input_array, np.ndarray): pass elif iterable(input_array) and input_array: if isinstance(input_array[0], YTArray): return YTArray(np.array(input_array, dtype=dtype), input_array[0].units) # Input array is an already formed ndarray instance # We first cast to be our class type obj = np.asarray(input_array, dtype=dtype).view(cls) # Check units type if input_units is None: # Nothing provided. Make dimensionless... units = Unit() elif isinstance(input_units, Unit): units = input_units else: # units kwarg set, but it's not a Unit object. # don't handle all the cases here, let the Unit class handle if # it's a str. units = Unit(input_units, registry=registry) # Attach the units obj.units = units return obj
def test_creation_from_ytarray(): u1 = Unit(electrostatic_unit) assert_equal(str(u1), 'esu') assert_equal(u1, Unit('esu')) assert_equal(u1, electrostatic_unit.units) u2 = Unit(elementary_charge) assert_equal(str(u2), '4.8032056e-10*esu') assert_equal(u2, Unit('4.8032056e-10*esu')) assert_equal(u1, elementary_charge.units) assert_equal((u1 / u2).base_value, electrostatic_unit / elementary_charge) assert_raises(UnitParseError, Unit, [1, 2, 3] * elementary_charge)
def test_string_representation(): """ Check unit string representation. """ pc = Unit("pc") Myr = Unit("Myr") speed = pc / Myr dimensionless = Unit() assert_true(str(pc) == "pc") assert_true(str(Myr) == "Myr") assert_true(str(speed) == "pc/Myr") assert_true(repr(speed) == "pc/Myr") assert_true(str(dimensionless) == "dimensionless")
def _sanitize_min_max_units(amin, amax, finfo, registry): # returns a copy of amin and amax, converted to finfo's output units umin = getattr(amin, 'units', None) umax = getattr(amax, 'units', None) if umin is None: umin = Unit(finfo.output_units, registry=registry) rmin = YTQuantity(amin, umin) else: rmin = amin.in_units(finfo.output_units) if umax is None: umax = Unit(finfo.output_units, registry=registry) rmax = YTQuantity(amax, umax) else: rmax = amax.in_units(finfo.output_units) return rmin, rmax
def test_slice(): fns = [] grid_eps = np.finfo(np.float64).eps for nprocs in [8, 1]: # We want to test both 1 proc and 8 procs, to make sure that # parallelism isn't broken ds = fake_random_ds(64, nprocs=nprocs) dims = ds.domain_dimensions xn, yn, zn = ds.domain_dimensions dx = ds.arr(1.0 / (ds.domain_dimensions * 2), 'code_length') xi, yi, zi = ds.domain_left_edge + dx xf, yf, zf = ds.domain_right_edge - dx coords = np.mgrid[xi:xf:xn * 1j, yi:yf:yn * 1j, zi:zf:zn * 1j] uc = [np.unique(c) for c in coords] slc_pos = 0.5 # Some simple slice tests with single grids for ax, an in enumerate("xyz"): xax = ds.coordinates.x_axis[ax] yax = ds.coordinates.y_axis[ax] for wf in ["density", None]: slc = ds.slice(ax, slc_pos) shifted_slc = ds.slice(ax, slc_pos + grid_eps) yield assert_equal, slc["ones"].sum(), slc["ones"].size yield assert_equal, slc["ones"].min(), 1.0 yield assert_equal, slc["ones"].max(), 1.0 yield assert_equal, np.unique(slc["px"]), uc[xax] yield assert_equal, np.unique(slc["py"]), uc[yax] yield assert_equal, np.unique(slc["pdx"]), 0.5 / dims[xax] yield assert_equal, np.unique(slc["pdy"]), 0.5 / dims[yax] pw = slc.to_pw(fields='density') for p in pw.plots.values(): tmpfd, tmpname = tempfile.mkstemp(suffix='.png') os.close(tmpfd) p.save(name=tmpname) fns.append(tmpname) frb = slc.to_frb((1.0, 'unitary'), 64) shifted_frb = shifted_slc.to_frb((1.0, 'unitary'), 64) for slc_field in ['ones', 'density']: fi = ds._get_field_info(slc_field) yield assert_equal, frb[slc_field].info['data_source'], \ slc.__str__() yield assert_equal, frb[slc_field].info['axis'], \ ax yield assert_equal, frb[slc_field].info['field'], \ slc_field yield assert_equal, frb[slc_field].units, \ Unit(fi.units) yield assert_equal, frb[slc_field].info['xlim'], \ frb.bounds[:2] yield assert_equal, frb[slc_field].info['ylim'], \ frb.bounds[2:] yield assert_equal, frb[slc_field].info['center'], \ slc.center yield assert_equal, frb[slc_field].info['coord'], \ slc_pos yield assert_equal, frb[slc_field], \ shifted_frb[slc_field] # wf == None yield assert_equal, wf, None teardown_func(fns)
def test_cutting_plane(): fns = [] for nprocs in [8, 1]: # We want to test both 1 proc and 8 procs, to make sure that # parallelism isn't broken ds = fake_random_ds(64, nprocs=nprocs) center = [0.5, 0.5, 0.5] normal = [1, 1, 1] cut = ds.cutting(normal, center) assert_equal(cut["ones"].sum(), cut["ones"].size) assert_equal(cut["ones"].min(), 1.0) assert_equal(cut["ones"].max(), 1.0) pw = cut.to_pw(fields='density') for p in pw.plots.values(): tmpfd, tmpname = tempfile.mkstemp(suffix='.png') os.close(tmpfd) p.save(name=tmpname) fns.append(tmpname) for width in [(1.0, 'unitary'), 1.0, ds.quan(0.5, 'code_length')]: frb = cut.to_frb(width, 64) for cut_field in ['ones', 'density']: fi = ds._get_field_info("unknown", cut_field) assert_equal(frb[cut_field].info['data_source'], cut.__str__()) assert_equal(frb[cut_field].info['axis'], 4) assert_equal(frb[cut_field].info['field'], cut_field) assert_equal(frb[cut_field].units, Unit(fi.units)) assert_equal(frb[cut_field].info['xlim'], frb.bounds[:2]) assert_equal(frb[cut_field].info['ylim'], frb.bounds[2:]) assert_equal(frb[cut_field].info['length_to_cm'], ds.length_unit.in_cgs()) assert_equal(frb[cut_field].info['center'], cut.center) teardown_func(fns)
def test_cutting_plane(): fns = [] for nprocs in [8, 1]: # We want to test both 1 proc and 8 procs, to make sure that # parallelism isn't broken ds = fake_random_ds(64, nprocs=nprocs) center = [0.5, 0.5, 0.5] normal = [1, 1, 1] cut = ds.cutting(normal, center) assert_equal(cut["ones"].sum(), cut["ones"].size) assert_equal(cut["ones"].min(), 1.0) assert_equal(cut["ones"].max(), 1.0) pw = cut.to_pw(fields="density") for p in pw.plots.values(): tmpfd, tmpname = tempfile.mkstemp(suffix=".png") os.close(tmpfd) p.save(name=tmpname) fns.append(tmpname) for width in [(1.0, "unitary"), 1.0, ds.quan(0.5, "code_length")]: frb = cut.to_frb(width, 64) for cut_field in ["ones", "density"]: fi = ds._get_field_info("unknown", cut_field) data = frb[cut_field] assert_equal(data.info["data_source"], cut.__str__()) assert_equal(data.info["axis"], 4) assert_equal(data.info["field"], cut_field) assert_equal(data.units, Unit(fi.units)) assert_equal(data.info["xlim"], frb.bounds[:2]) assert_equal(data.info["ylim"], frb.bounds[2:]) assert_equal(data.info["length_to_cm"], ds.length_unit.in_cgs()) assert_equal(data.info["center"], cut.center) teardown_func(fns)
def test_create_with_duplicate_dimensions(): """ Create units with overlapping dimensions. Ex: km/Mpc. """ u1 = Unit("erg * s**-1") u2 = Unit("km/s/Mpc") km_cgs = cm_per_km Mpc_cgs = cm_per_mpc assert_true(u1.base_value == 1) assert_true(u1.dimensions == power) assert_allclose_units(u2.base_value, km_cgs / Mpc_cgs, 1e-12) assert_true(u2.dimensions == rate)
def test_create_with_duplicate_dimensions(): """ Create units with overlapping dimensions. Ex: km/Mpc. """ u1 = Unit("erg * s**-1") u2 = Unit("km/s/Mpc") km_cgs = cm_per_km Mpc_cgs = cm_per_mpc yield assert_true, u1.cgs_value == 1 yield assert_true, u1.dimensions == power yield assert_allclose, u2.cgs_value, km_cgs / Mpc_cgs, 1e-12 yield assert_true, u2.dimensions == rate
def __getitem__(self, key): if isinstance(key, string_types): key = getattr(dimensions, key) um = self.units_map if key not in um or um[key].dimensions is not key: units = _get_system_unit_string(key, self.units_map) self.units_map[key] = Unit(units, registry=self.registry) return self.units_map[key]
def _set_code_unit_attributes(self): """ Generates the conversion to various physical _units based on the parameter file """ # This should be improved. h5f = h5py.File(self.parameter_filename, mode="r") for field_name in h5f["/field_types"]: current_field = h5f[f"/field_types/{field_name}"] if "field_to_cgs" in current_field.attrs: field_conv = current_field.attrs["field_to_cgs"] self.field_units[field_name] = just_one(field_conv) elif "field_units" in current_field.attrs: field_units = current_field.attrs["field_units"] if isinstance(field_units, str): current_field_units = current_field.attrs["field_units"] else: current_field_units = just_one( current_field.attrs["field_units"]) self.field_units[field_name] = current_field_units.decode( "utf8") else: self.field_units[field_name] = "" if "dataset_units" in h5f: for unit_name in h5f["/dataset_units"]: current_unit = h5f[f"/dataset_units/{unit_name}"] value = current_unit[()] unit = current_unit.attrs["unit"] # need to convert to a Unit object and check dimensions # because unit can be things like # 'dimensionless/dimensionless**3' so naive string # comparisons are insufficient unit = Unit(unit, registry=self.unit_registry) if unit_name.endswith( "_unit") and unit.dimensions is sympy_one: # Catch code units and if they are dimensionless, # assign CGS units. setdefaultattr will catch code units # which have already been set via units_override. un = unit_name[:-5] un = un.replace("magnetic", "magnetic_field_cgs", 1) unit = unit_system_registry["cgs"][un] setdefaultattr(self, unit_name, self.quan(value, unit)) setdefaultattr(self, unit_name, self.quan(value, unit)) if unit_name in h5f["/field_types"]: if unit_name in self.field_units: mylog.warning( "'field_units' was overridden by 'dataset_units/%s'", unit_name, ) self.field_units[unit_name] = str(unit) else: setdefaultattr(self, "length_unit", self.quan(1.0, "cm")) setdefaultattr(self, "mass_unit", self.quan(1.0, "g")) setdefaultattr(self, "time_unit", self.quan(1.0, "s")) h5f.close()
def test_dimensionless(): """ Create dimensionless unit and check attributes. """ u1 = Unit() yield assert_true, u1.is_dimensionless yield assert_true, u1.expr == 1 yield assert_true, u1.cgs_value == 1 yield assert_true, u1.dimensions == 1 u2 = Unit("") yield assert_true, u2.is_dimensionless yield assert_true, u2.expr == 1 yield assert_true, u2.cgs_value == 1 yield assert_true, u2.dimensions == 1
def alias( self, alias_name, original_name, units=None, deprecate: Optional[Tuple[str, str]] = None, ): """ Alias one field to another field. Parameters ---------- alias_name : Tuple[str] The new field name. original_name : Tuple[str] The field to be aliased. units : str A plain text string encoding the unit. Powers must be in python syntax (** instead of ^). If set to "auto" the units will be inferred from the return value of the field function. deprecate : Tuple[str], optional If this is set, then the tuple contains two string version numbers: the first marking the version when the field was deprecated, and the second marking when the field will be removed. """ if original_name not in self: return if units is None: # We default to CGS here, but in principle, this can be pluggable # as well. u = Unit(self[original_name].units, registry=self.ds.unit_registry) if u.dimensions is not dimensionless: units = str(self.ds.unit_system[u.dimensions]) else: units = self[original_name].units self.field_aliases[alias_name] = original_name function = TranslationFunc(original_name) if deprecate is not None: self.add_deprecated_field( alias_name, function=function, sampling_type=self[original_name].sampling_type, display_name=self[original_name].display_name, units=units, since=deprecate[0], removal=deprecate[1], ret_name=original_name, ) else: self.add_field( alias_name, function=function, sampling_type=self[original_name].sampling_type, display_name=self[original_name].display_name, units=units, )
def setup_particle_fields(self, ptype, ftype='gas', num_neighbors=64): skip_output_units = () for f, (units, aliases, dn) in sorted(self.known_particle_fields): units = self.ds.field_units.get((ptype, f), units) if (f in aliases or ptype not in self.ds.particle_types_raw) and \ units not in skip_output_units: u = Unit(units, registry=self.ds.unit_registry) output_units = str(u.get_cgs_equivalent()) else: output_units = units if (ptype, f) not in self.field_list: continue self.add_output_field((ptype, f), units=units, particle_type=True, display_name=dn, output_units=output_units, take_log=False) for alias in aliases: self.alias((ptype, alias), (ptype, f), units=output_units) # We'll either have particle_position or particle_position_[xyz] if (ptype, "particle_position") in self.field_list or \ (ptype, "particle_position") in self.field_aliases: particle_scalar_functions(ptype, "particle_position", "particle_velocity", self) else: # We need to check to make sure that there's a "known field" that # overlaps with one of the vector fields. For instance, if we are # in the Stream frontend, and we have a set of scalar position # fields, they will overlap with -- and be overridden by -- the # "known" vector field that the frontend creates. So the easiest # thing to do is to simply remove the on-disk field (which doesn't # exist) and replace it with a derived field. if (ptype, "particle_position") in self and \ self[ptype, "particle_position"]._function == NullFunc: self.pop((ptype, "particle_position")) particle_vector_functions( ptype, ["particle_position_%s" % ax for ax in 'xyz'], ["particle_velocity_%s" % ax for ax in 'xyz'], self) particle_deposition_functions(ptype, "particle_position", "particle_mass", self) standard_particle_fields(self, ptype) # Now we check for any leftover particle fields for field in sorted(self.field_list): if field in self: continue if not isinstance(field, tuple): raise RuntimeError if field[0] not in self.ds.particle_types: continue self.add_output_field(field, units=self.ds.field_units.get(field, ""), particle_type=True) self.setup_smoothed_fields(ptype, num_neighbors=num_neighbors, ftype=ftype)
def __setstate__(self, state): """Pickle setstate method This is called inside pickle.read() and restores the unit data from the metadata extracted in __reduce__ and then serialized by pickle. """ super(YTArray, self).__setstate__(state[1:]) unit, lut = state[0] registry = UnitRegistry(lut=lut, add_default_symbols=False) self.units = Unit(unit, registry=registry)
def __getitem__(self, item): if item in self.data: return self.data[item] mylog.info("Making a fixed resolutuion buffer of (%s) %d by %d" % \ (item, self.buff_size[0], self.buff_size[1])) dd = self.data_source width = self.ds.arr((self.bounds[1] - self.bounds[0], self.bounds[3] - self.bounds[2], self.bounds[5] - self.bounds[4])) buff = off_axis_projection(dd.ds, dd.center, dd.normal_vector, width, dd.resolution, item, weight=dd.weight_field, volume=dd.volume, no_ghost=dd.no_ghost, interpolated=dd.interpolated, north_vector=dd.north_vector) units = Unit(dd.ds.field_info[item].units, registry=dd.ds.unit_registry) if dd.weight_field is None: units *= Unit('cm', registry=dd.ds.unit_registry) ia = ImageArray(buff.swapaxes(0,1), input_units=units, info=self._get_info(item)) self[item] = ia return ia
def test_slice(pf): fns = [] grid_eps = np.finfo(np.float64).eps for nprocs in [8, 1]: # We want to test both 1 proc and 8 procs, to make sure that # parallelism isn't broken ds = fake_random_ds(64, nprocs=nprocs) dims = ds.domain_dimensions xn, yn, zn = ds.domain_dimensions dx = ds.arr(1.0 / (ds.domain_dimensions * 2), "code_length") xi, yi, zi = ds.domain_left_edge + dx xf, yf, zf = ds.domain_right_edge - dx coords = np.mgrid[xi:xf:xn * 1j, yi:yf:yn * 1j, zi:zf:zn * 1j] uc = [np.unique(c) for c in coords] slc_pos = 0.5 # Some simple slice tests with single grids for ax, an in enumerate("xyz"): xax = ds.coordinates.x_axis[ax] yax = ds.coordinates.y_axis[ax] for wf in ["density", None]: slc = ds.slice(ax, slc_pos) shifted_slc = ds.slice(ax, slc_pos + grid_eps) assert_equal(slc["ones"].sum(), slc["ones"].size) assert_equal(slc["ones"].min(), 1.0) assert_equal(slc["ones"].max(), 1.0) assert_equal(np.unique(slc["px"]), uc[xax]) assert_equal(np.unique(slc["py"]), uc[yax]) assert_equal(np.unique(slc["pdx"]), 0.5 / dims[xax]) assert_equal(np.unique(slc["pdy"]), 0.5 / dims[yax]) pw = slc.to_pw(fields="density") for p in pw.plots.values(): tmpfd, tmpname = tempfile.mkstemp(suffix=".png") os.close(tmpfd) p.save(name=tmpname) fns.append(tmpname) for width in [(1.0, "unitary"), 1.0, ds.quan(0.5, "code_length")]: frb = slc.to_frb((1.0, "unitary"), 64) shifted_frb = shifted_slc.to_frb((1.0, "unitary"), 64) for slc_field in ["ones", "density"]: fi = ds._get_field_info(slc_field) assert_equal(frb[slc_field].info["data_source"], slc.__str__()) assert_equal(frb[slc_field].info["axis"], ax) assert_equal(frb[slc_field].info["field"], slc_field) assert_equal(frb[slc_field].units, Unit(fi.units)) assert_equal(frb[slc_field].info["xlim"], frb.bounds[:2]) assert_equal(frb[slc_field].info["ylim"], frb.bounds[2:]) assert_equal(frb[slc_field].info["center"], slc.center) assert_equal(frb[slc_field].info["coord"], slc_pos) assert_equal(frb[slc_field], shifted_frb[slc_field]) assert_equal(wf, None) teardown_func(fns)
def _sanitize_dimensions(self, item): field = self.data_source._determine_fields(item)[0] finfo = self.data_source.ds.field_info[field] dimensions = Unit( finfo.units, registry=self.data_source.ds.unit_registry).dimensions if dimensions not in self.known_dimensions: self.known_dimensions[dimensions] = item ret_item = item else: ret_item = self.known_dimensions[dimensions] return ret_item
def setup_magnetic_field_aliases(registry, ds_ftype, ds_fields, ftype="gas"): r""" This routine sets up special aliases between dataset-specific magnetic fields and the default magnetic fields in yt so that unit conversions between different unit systems can be handled properly. This is only called from the `setup_fluid_fields` method of a frontend's :class:`FieldInfoContainer` instance. Parameters ---------- registry : :class:`FieldInfoContainer` The field registry that these definitions will be installed into. ds_ftype : string The field type for the fields we're going to alias, e.g. "flash", "enzo", "athena", etc. ds_fields : list of strings The fields that will be aliased. ftype : string, optional The resulting field type of the fields. Default "gas". Examples -------- >>> class PlutoFieldInfo(ChomboFieldInfo): ... def setup_fluid_fields(self): ... from yt.fields.magnetic_field import \ ... setup_magnetic_field_aliases ... setup_magnetic_field_aliases(self, "chombo", ["bx%s" % ax for ax in [1,2,3]]) """ unit_system = registry.ds.unit_system ds_fields = [(ds_ftype, fd) for fd in ds_fields] if ds_fields[0] not in registry: return from_units = Unit(registry[ds_fields[0]].units, registry=registry.ds.unit_registry) if dimensions.current_mks in unit_system.base_units: to_units = unit_system["magnetic_field_mks"] equiv = "SI" else: to_units = unit_system["magnetic_field_cgs"] equiv = "CGS" if from_units.dimensions == to_units.dimensions: convert = lambda x: x.in_units(to_units) else: convert = lambda x: x.to_equivalent(to_units, equiv) def mag_field(fd): def _mag_field(field, data): return convert(data[fd]) return _mag_field for ax, fd in zip(registry.ds.coordinates.axis_order, ds_fields): registry.add_field((ftype, "magnetic_field_%s" % ax), sampling_type="cell", function=mag_field(fd), units=unit_system[to_units.dimensions])