MuramMultifluidDensityLoader
- class PlasmaCalcs.hookups.muram.muram_multifluid_densities.MuramMultifluidDensityLoader
Bases:
MhdMultifluidDensityLoaderdensity quantities based on Muram single-fluid values, & inferred multifluid properties.
Methods
__call__(var, *args[, name, item, verbose])returns value of var from self.
assert_single_fluid_mode([varname, mode])asserts that self is in single fluid mode; else crash.
attach_extra_coords(arr)attach any self.extra_coords to array arr but only if it is an xarray.DataArray or xarray.Dataset
cls_help([qstr, only, tree, modules, ...])prints str for help with quants.
cls_var_tree(var, *[, missing_ok])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
copy()returns a deep copy of self.
get_B()magnetic field.
get_E()electric field.
electric field in the u_neutral=0 frame.
get_J()current density (without displacement current).
get_Jf()current density (associated with fluid).
get_P()pressure.
pressure, from plugging r and e into eos tables (see self.tabin).
pressure (from ideal gas law?) P = (gamma - 1) * e
get_T()temperature.
temperature, from plugging r and e into eos tables (see self.tabin).
temperature, assuming ideal gas law.
temperature of neutrals; T_n = T of SINGLE_FLUID.
temperature ("isotropic/maxwellian"), in energy units.
get_behavior([keys])return value of self.behavior.
get_ds()vector(spatial scale), e.g. [dx, dy, dz].
get_e()energy density.
internal energy (total, not density) per unit mass.
get_ertab_var(var, ustr)get var in self.units units from the eos tables, using r and e from self.
adiabatic index.
get_ionfrac(*, ionfrac_type)ionization fraction(s) of element(s) of self.fluid
ionization fraction based on self.radtab.
ionization fraction based on saha equation: ionfrac_saha = 1 / (1 + 1 / saha_n1n0)
ionfrac_type for self.fluid; affects 'ionfrac' result.
self.fluid element's first ionization energy.
electron thermal deBroglie wavelength.
get_m()average mass of fluid particle.
mass, of a "single neutral particle".
get_n(*, ntype)number density.
get_nI()number density of neutral species of element(s) of self.fluid.
get_nII()number density of once-ionized species of element(s) of self.fluid.
number density of once-ionized species of element(s) of self.fluid.
number density of once-ionized species of element(s) of self.fluid.
number density of neutral species of element(s) of self.fluid.
number density of neutral species of element(s) of self.fluid.
number density of self.fluid specie(s); from aux files values.
number density of element(s) for self.fluid.
n_from_ionfrac_charge__type for self.fluid, for inferring densities from ionization fraction.
sum of n for each ion in IonMixture.
number density of neutrals.
get_n_radtab(*, n_from_ionfrac_charge__type)number density self.fluid, based on self.radtab lookups of self('SF_T')
get_n_saha(*, n_from_ionfrac_charge__type)number density self.fluid, based on saha ionization.
get_ne()electron number density.
electron number density, assuming quasineutrality.
electron number density, from 'hionne' in aux.
electron number density, from plugging r and e into eos tables (see self.tabin).
ne_type.
neutral fraction(s) of element(s) of self.fluid.
neutral fraction based on self.radtab and self('SF_T').
neutral fraction based on saha ionization.
number density of element(s) for self.fluid, divided by total number density.
get_nq()charge density.
ntype of self.fluid.
get_nuns()collision frequency.
get_nusj()collision frequency.
get_nusn()collision frequency.
get_p()momentum density.
get_q()charge, of a "single particle".
get_r()mass density.
mass density of element(s) for self.fluid.
mass density of element(s) for self.fluid, divided by total mass density.
get_saha_factor_exp(*[, _T])exp(-xi / (kB * T)) for saha equation.
get_saha_factor_ldebroge(*[, _T])(2.0 / lde^3) for saha equation.
get_saha_factor_ldebroge_ne(*[, _T])(ldebroge_factor / ne) for saha equation.
ratio of self.fluid element's g (degeneracy of states) for g1 (ions) to g0 (neutrals).
(n1/n0) for an element, via saha equation:
get_set_or_cached(var)returns var if found in self.setvars or self.cache, with compatible behavior_attrs.
get_single_fluid_var(var, *[, _match])SF_{var} (or SINGLE_FLUID_{var}) --> {var}, definitely in single fluid mode.
get_u()velocity.
velocity of neutrals.
get_vars(vars, *args[, return_type, ...])returns values of vars from self.
has_var(var)return whether self can load var.
help([qstr, only, tree, modules, signature, ...])prints str for help with quants.
help_call_options([search])prints help for kw_call_options.
help_quants_str([qstr, only, tree, modules, ...])returns str for help with quants.
help_str([qstr, only])returns cls.help_quants_str(qstr=qstr, only=only, **kw).
kw_call_options(*[, sorted])returns list of kwarg names which can be used to set attrs self during self.__call__.
load_direct(var, *args, **kw)load var "directly", from some source which is not known by the main part of PlasmaCalcs.
load_fromfile(var, *args, **kw)load var directly from a file.
maintaining_attrs(*attrs, **attrs_as_flags)returns context manager which restores attrs of self to their original values, upon exit.
match_var(var, *[, check])match var from cls.KNOWN_VARS or cls.KNOWN_PATTERNS, or raise FormulaMissingError.
match_var_loading_dims(var, **kw_loading_dims)return dims for loading var across.
match_var_result_dims(var, **kw_result_dims)return dims which result of cls(var) will vary across.
match_var_result_size(var, *[, maindims])return size (number of elements) which self(var) will have.
match_var_tree([var])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
quant_tree([var])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
set_T_fromtable(value, **kw)set T_fromtable to this value.
set_e(value, **kw)set e to this value.
set_eperm(value, **kw)set eperm to this value.
set_n(value, **kw)set n to this value.
set_r(value, **kw)set r to this value.
set_var(var, value[, behavior_attrs, ...])set var in self.
set_var_internal(var, value, behavior_attrs)set var in self.
tree([var])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
unset_var(var[, behavior_attrs, missing_ok])remove var from self.setvars (but only at values stored with relevant behavior).
unset_var_internal(var, behavior_attrs[, ...])unset var from self.setvars.
using_at_call_depth(depth, **attrs_and_values)context manager for setting attrs_and_values but only while call_depth == depth.
using_at_next_call_depth(**attrs_and_values)context manager for setting attrs_and_values but only while call_depth == self.call_depth + 1
using_attrs([attrs_as_dict, _unset_sentinel])returns context manager which sets attrs of obj upon entry; restores original values upon exit.
apply self.toplevel_scale_coords to arr, if nonempty, else return arr unchanged.
return self.assign_fluid_coord(array, electron fluid).
_battrs_for_set_var_internal(behavior_attrs)returns behavior_attrs which will be used by set_var_internal, given these inputs.
_battrs_for_unset_var_internal(behavior_attrs)returns behavior_attrs which will be used by unset_var_internal, given these inputs.
_call_hijacker(var, *args__None, **kw__None)returns False or name of hijacker method to use instead of self(var) call.
_call_postprocess(result, *, var[, name, item])postprocess result from self.__call__.
_call_postprocess_toplevel(result, *, var[, ...])additional postprocessing for self.__call__ when call_depth=1.
_call_preprocess(result, *, var)preprocessing during self.__call__.
default value for self.eos_mode.
return default value of self.radtab: GenradTableManager.from_defaults().
return default value of self.tabin: erTabInputManager(self.tabinputfile, u=self.u).
default value for elements.
_get_ertab_var_raw(var)get var in 'raw' units, from the eos tables, using single-fluid r and e from self.
_get_maybe_missing_var(var, *args[, ...])return value of var, or None if FormulaMissingError and missing_vars 'ignore' or 'warn'.
_handle_typevar_nan(*[, errmsg])crash with TypevarNanError if self.typevar_crash_if_nan, else return 'nan'.
_help_matches(qstr, k, v)returns whether qstr matches k or v, and thus should be displayed during self.help(qstr).
returns dict of docstrings for specialized kw call options for self.
context manager for incrementing call_depth.
returns whether max supported n, in self.units unit system, is too big for float32.
pop all self.kw_call_options() from kw, returning dict of popped options.
_provided_val(var[, _val, _known_vals])returns the value of var, either from _known_vals or _val.
specialize popped kw_call_options, adjusting keys and/or values as needed,
if max n requires float64, upcast array to float64,
Attributes
EOS_MODE_OPTIONSIONFRAC_MODE_OPTIONSKNOWN_PATTERNSKNOWN_SETTERSKNOWN_VARSNE_MODE_OPTIONSNTYPE_TO_VARN_MODE_OPTIONSwhether to assign self.behavior values as attrs of result when calling self.
max call_depth at which to assign_behavior_attrs to result,
whether to use include_xr=False if self.assign_behavior_attrs,
dict of {attr: self.attr} for attr in self.behavior_attrs.
list of attrs in self which control behavior of self.
depth of the current call to self.
stores the value of call_depth, and helps to manage attrs dependent on call_depth value.
cls_behavior_attrsElementList of all elements in multifluid mixture assumed from single-fluid mhd.
bool: whether self.load_fromfile is enabled during self.load_direct.
mode for "Equation of State" related variables (ne, T, P).
dict of {coord_name: coord_value} to attach to outputs of self(var).
alias to __call__
whether self is in "single fluid mode".
mode for calculating self('ionfrac').
known_patternknown_setterknown_varalias to maintaining_attrs
str.
None or str.
explicit ne_mode: ne_mode if not None, else n_mode.
list of attrs in self which control behavior of self, but which are NOT in self.dimensions.
dict-like manager for Genrad tables.
alias to set_var
alias to set_var
VarCache of vars set via self.set_var().
dict-like manager for Equation Of State tables; should include keys 'ne', 'T', 'P'.
path to tabinputfile, used by self._default_tabin() to create self.tabin.
dict of {coord_name: coord_scaling} to apply to top-level outputs of self(var).
bool.
alias to unset_var
alias to using_attrs
- __call__(var, *args, name=UNSET, item=False, verbose=UNSET, **kw)
returns value of var from self.
result is probably an xarray.DataArray, but not guaranteed.var: str or iterable of strs.Name of the var(s) to load. E.g. ‘n’ for number density, or [‘n’, ‘u’] for number density & velocity.If multiple vars: returns an xarray.Dataset of all vars, via self.get_vars.Determine how to load each var, as follows:- (caching) if var in self.cache, with matching self.behavior_attrs, use value from cache.[TODO] - caching not yet implemented. May allow for better efficiency.- (setvars) if var in self.setvars, with matching self.behavior_attrs, use value from setvars.[TODO] - improve set_var functionality.set_var will allow user to apply PlasmaCalcs calculations to arbitrary values,not just values from one of the hookups. Useful for testing & quick calculations.- (KNOWN_VARS) if var in self.KNOWN_VARS,use the corresponding function to get it.- (KNOWN_PATTERNS) if var matches a pattern from self.KNOWN_PATTERNS,use the corresponding function to get it.- (direct) attempt to load var “directly”, via self.load_direct.load_direct will almost always end up loading values directly from a file (e.g., “data”).This may include converting var to fromfile_var, i.e. match file naming conventions,and/or dimensions being loaded. E.g. ‘b’ may become ‘bz’ when loading across ‘component’.Then, check if fromfile_var in setvars and cache, returning relevant value if found.Lastly, call self.load_fromfile(fromfile_var).Those are checked in the order listed.If none of those work, raise FormulaMissingError.name: UNSET, None, or strtry to set result.name = name.If can’t set result.name, but result.attrs exists, set result.attrs[‘name’] = name, instead.UNSET –> use name = var.item: boolif True, convert result to single value (e.g., python float) via result.item().This will cause crash if result is not a single value;it will also cause all metadata stored in the result to be lost.verbose: UNSET, bool, or intset self.verbose during this call to self.UNSET –> use self.verbose (unchanged)kw may additionally contain any keys from self.kw_call_options().if it does, pop those values, and temporarily set the corresponding attr.E.g.: self(‘n’, units=’si’, fluid=1)–> temporarily set units=’si’, fluid=1, while getting ‘n’.See self.help_call_options() for more details.[EFF] passes _match=re.fullmatch(pattern, var) to the getter function,if the match is from KNOWN_PATTERNS (but not if it is from KNOWN_VARS).misc note: if self._call_hijacker(…), instead return result from the corresponding method.e.g. if it returns “_get_with_chunks” then return self._get_with_chunks(var, …).Call hijacking occurs after setting behavior attrs (insidewith self.using(...):block)but before altering call depth (outsidewith self._increment_call_depth():block).
- _apply_toplevel_scale_coords(arr)
apply self.toplevel_scale_coords to arr, if nonempty, else return arr unchanged.
- _assign_electron_fluid_coord_if_unambiguous(array)
return self.assign_fluid_coord(array, electron fluid).
if self doesn’t have exactly 1 electron fluid, don’t assign coord.
- _battrs_for_set_var_internal(behavior_attrs, forall=[], *, ukey=None)
returns behavior_attrs which will be used by set_var_internal, given these inputs.
see help(self.set_var_internal) for details.
- _battrs_for_unset_var_internal(behavior_attrs, forall=[], *, ukey=None)
returns behavior_attrs which will be used by unset_var_internal, given these inputs.
see help(self.unset_var_internal) for details.
- _call_hijacker(var, *args__None, **kw__None)
returns False or name of hijacker method to use instead of self(var) call.
Here, just returns False, always. Subclass might override.
- _call_postprocess(result, *, var, name=UNSET, item=UNSET)
postprocess result from self.__call__. Called during self.__call__.
(self.call_depth inside here will tell depth of the current call; depth=1 for top level.)result: any value, probably an xarray.DataArrayresult from self.__call__, before postprocessing.var, name, item: UNSET or valuepassed directly from self.__call__.The implementation here does the following (subclasses might override / add to this):(1) if self.verbose >= 4, print a message about getting var.(2) result = self.attach_extra_coords(result).(3) set result.name = name, or result.attrs[‘name’] = name, if possible.(4) if self.assign_behavior_attrs at this call depth, do so now.(5) if self.call_depth == 1, call self._call_postprocess_toplevel.(6) if item, convert result to single value via result.item().
- _call_postprocess_toplevel(result, *, var, name=UNSET, item=UNSET)
additional postprocessing for self.__call__ when call_depth=1.
called from self._call_postprocess, after doing other postprocessing, when call_depth=1.result: any value, probably an xarray.DataArrayresult from self.__call__, after other postprocessing (exceptitem).var, name, item: UNSET or valuepassed directly from self.__call__.Don’t need to handle these here because self._call_postprocess will handle it.The implementation here does the following (subclasses might override / add to this):(1) self._apply_toplevel_scale_coords (does nothing if self.toplevel_scale_coords is empty)
- _call_preprocess(result, *, var)
preprocessing during self.__call__. Called during self.__call__.
(self.call_depth inside here will tell depth of the current call; depth=1 for top level.)result: any value, probably RESULT_MISSINGresult from self.__call__, before preprocessing. Usually RESULT_MISSING.var: strvar being loaded. Passed directly from self.__call__.The implementation here does the following (subclasses might override / add to this):(1) if self.verbose >= 2 or DEFAULTS.DEBUG >= 7, print a message about getting var.(2) return result, unchanged.If the returned result is anything other than RESULT_MISSING,self.__call__ will return it instead of loading var normally.
- _default_eos_mode()
default value for self.eos_mode. Here: ‘table’. Subclass might override.
- _default_radtab()
return default value of self.radtab: GenradTableManager.from_defaults().
- _default_tabin()
return default value of self.tabin: erTabInputManager(self.tabinputfile, u=self.u).
- _get_default_elements()
default value for elements. here, just returns self.tabin.elements,
but raises a helpful error message if self.tabin not set.
- _get_ertab_var_raw(var)
get var in ‘raw’ units, from the eos tables, using single-fluid r and e from self.
CAUTION: array values use [raw], but coords use [self.coords_units].see self.tabin.keys() for var options. gets value via interpolation.
- _get_maybe_missing_var(var, *args, missing_vars=UNSET, **kw)
return value of var, or None if FormulaMissingError and missing_vars ‘ignore’ or ‘warn’.
missing_vars: UNSET, ‘ignore’, ‘warn’, or ‘raise’what to do if any var causes FormulaMissingError.UNSET –> use self.missing_vars if it exists, else ‘raise’.‘ignore’ –> return None.‘warn’ –> return None, but also print a warning.‘raise’ –> raise FormulaMissingError.
- _handle_typevar_nan(*, errmsg='')
crash with TypevarNanError if self.typevar_crash_if_nan, else return ‘nan’.
if crashing, use error message:errmsg + “nTo return ‘nan’ instead of crashing, set self.typevar_crash_if_nan=False.”
- classmethod _help_matches(qstr, k, v)
returns whether qstr matches k or v, and thus should be displayed during self.help(qstr).
qstr: str
the str to match; from self.help(qstr)k: varnamethe varname to test for matches.key from self.KNOWN_VARS.keys(), or key.str from self.KNOWN_PATTERNS.keys().v: LoadableQuantitythe LoadableQuantity to test for matches.value from self.KNOWN_VARS.values() or self.KNOWN_PATTERNS.values().matches if any of these are true:qstr == ‘’qstr in k.split(‘_’) # size limitation and split(‘_’) because, e.g. during help(‘n’),len(qstr)>=3 and qstr in k # want vars related to number density, not all vars with the letter ‘n’.qstr in module.split(‘.’) (where, module == v.get_f_module(cls))‘.’ in qstr and qstr in modulelen(qstr)>=3 and qstr in value from module.split(‘.’)len(qstr)>=3 and qstr in v.fnamere.fullmatch(k, qstr) # if k is a Patternotherwise, does not match.
- _help_specialized_kw_call_options()
returns dict of docstrings for specialized kw call options for self.
The implementation here just returns an empty dict, but subclass may override.
- _increment_call_depth()
context manager for incrementing call_depth.
use “with self._increment_call_depth():” inside of __call__, e.g.:
def __call__(self, *args, **kw):with self._increment_call_depth():# do stuff; possibly including calling self again.Equivalent to self.call_depth_manager.increment()
- _max_n_requires_float64()
returns whether max supported n, in self.units unit system, is too big for float32.
max supported n, in SI units, is DEFAULTS.MHD_MAX_SAFE_N_SIcrash with ValueError if max supported n is too big for float64 as well.without this check (and conversion to float64 if needed), some n values might become inf.
- _pop_kw_call_options(kw)
pop all self.kw_call_options() from kw, returning dict of popped options.
- _provided_val(var, _val=None, _known_vals={})
returns the value of var, either from _known_vals or _val.
if _val provided, return it; if ‘_{var}’ in _known_vals, return it;if both provided, crash with InputConflictError (unless they are the same object),else, return None.Can use this internally to avoid redundant recalculations. (See e.g. VectorArithmeticLoader)
- _specialized_kw_call_options(kw)
specialize popped kw_call_options, adjusting keys and/or values as needed,
to be suitable to pass to self.using(**kw).kw may be edited IN PLACE.Overriding this is discouraged, unless using property setters/getters is truly insufficient.If overriding this method, consider also overriding self._help_specialized_kw_call_options,to add documentation (inside self.help_call_options()) for any specialized kw call options.self.__call__ uses this method as follows:using=self._pop_kw_call_options(kw)using = self._specialize_using_kw_call_options(using)with self.using(**using):# <– majority of self.__call__ functionality goes here.The implementation here just returns kw, unchanged.
- _upcast_if_max_n_requires_float64(array)
if max n requires float64, upcast array to float64,
unless array’s dtype was already float64 or larger (in which case, just return array).see self._max_n_requires_float64 for details on when max n requires float64.
- assert_single_fluid_mode(varname='var', *, mode='getting')
asserts that self is in single fluid mode; else crash.
varname: strname of var to include in error message if crashing.mode: str, ‘getting’ or ‘setting’determines error type & error message if crashing.‘getting’ –> FluidValueError, with error message starting like:“{type(self)} getting {varname} requires self.in_single_fluid_mode…”‘setting’ –> SetvarNotImplementedError, with error message starting like:“var={varname}, when self not in_single_fluid_mode…”Use for operations which directly assume single fluid mode (e.g. get_r implementation here).Not necessary for operations which apply regardless of number of fluids,E.g. n = r / m for any number of fluids, and B is always independent of fluid.If unsure, err on the side of caution and use this function,to require multifluid subclass to explicitly handle the situation else crash.
- property assign_behavior_attrs
whether to assign self.behavior values as attrs of result when calling self.
False –> don’t use self.behavior code architecture to assign attrs.True –> equivalent to ‘nondefault’‘nondefault’ –> self.behavior.assign_nondefault_attrs(result)(for brevity, it does not assign behavior attrs with “default” value.)‘all’ –> self.behavior.assign_attrs(result).[EFF] only assigns attrs at call_depth >= self.assign_behavior_attrs_max_call_depth.(default: only assigns attrs at call_depth=1, i.e. at top level.
- property assign_behavior_attrs_max_call_depth
max call_depth at which to assign_behavior_attrs to result,
if self.assign_behavior_attrs indicates to assign behavior attrs.default 1, i.e. only assign if at top level.Use None to indicate “no max depth”.
- property assign_behavior_attrs_skip_xr
whether to use include_xr=False if self.assign_behavior_attrs,
during self.behavior.assign_nondefault_attrs.Use this if you want to assign behavior attrs EXCEPT array-valued behavior attrs.
- attach_extra_coords(arr)
attach any self.extra_coords to array arr but only if it is an xarray.DataArray or xarray.Dataset
- property behavior
dict of {attr: self.attr} for attr in self.behavior_attrs. Note dims are separate;
dims go in behavior.dims. E.g. Behavior({‘units’:’si’,…}, dims={‘snap’:0,…}).
- property behavior_attrs
list of attrs in self which control behavior of self.
Here, returns self.cls_behavior_attrs.Subclasses could override if any behavior attrs are not known at the class-level,e.g. if MySubclass’s list of behavior attrs varies between instances of MySubclass.
- property call_depth
depth of the current call to self. depth = number of calls to self from within self.
E.g., call_depth while calculating gyrofrequency:
# call_depth == 0, for any code run here (outside any call to self).self(‘gyrof’)# call_depth == 1, for any code run here (inside ‘gyrof’ call but not inside deeper calls).q = self(‘q’)# call_depth == 2, for code inside ‘q’ call.mod_B = self(‘mod_B’)# call_depth == 2, for code inside ‘mod_B’ call.self(‘B’)# call_depth == 3, for code inside ‘B’ call.m = self(‘m’)# call_depth == 2, for code inside ‘m’ call.result = q * mod_B / mCannot be set directly; can only be manipulated via self.call_depth_manager.
- property call_depth_manager
stores the value of call_depth, and helps to manage attrs dependent on call_depth value.
- classmethod cls_help(qstr=None, only=None, *, tree=None, modules=False, signature=False, doc=True, dense=False, print=True, **kw)
prints str for help with quants. Fails for any quants which depend on present values of a cls instance.
qstr: None or str
None –> tells info about this class & how to use this function.in particular, tells that quants are stored cls.KNOWN_VARS and cls.KNOWN_PATTERNS,and describes behavior of calling help with a string.str –> return str for help with all quants related to str.use empty str to get help for all quants.only: None or strIf provided, only get help for a subset of relevant quantities.None –> get help with all quantities related to qstr.‘VARS’ –> only get help with KNOWN_VARS.‘PATTERNS’ –> only get help with KNOWN_PATTERNS.‘TREE’ –> only get help with quantities in cls.cls_var_tree(str).‘EXACT’ –> only get help for the KNOWN_VAR exactly matching qstr.if provided when qstr is None, treat qstr as ‘’ instead.tree: None or boolHow much help to give for quantities in cls.cls_var_tree(qstr).False –> don’t even check cls.cls_var_tree(qstr).True –> help for all quantities in cls.cls_var_tree.None –> help for quantities in cls.cls_var_tree(qstr).flat_branches_until_vars()i.e. patterns & vars in tree but ignore any nodes with LoadableVar ancestors.e.g. qstr=’mean_mod_beta’ –> help with ‘mean_(.+)’, ‘mod_(.+)’, and ‘beta’,but no help with dependencies of ‘beta’ (‘q’, ‘mod_B’, ‘m’).modules: boolWhether to include modules in result.If True, result will be grouped into sections with modules written at top.signature: signature: boolwhether to include line with signature in help string.e.g. “help_str(f, *, module=True, signature=True, indent=None)”doc: doc: boolwhether to include lines with docstring in help string.e.g. “return str for help(f).” … and all the other docs in here.dense: boolWhether to reduce whitespace in result.E.g. True –> no newlines between functions. False –> one newline between functions.print: boolwhether to print the result. If False, return the result instead of printing.
- classmethod cls_var_tree(var, *, missing_ok=False)
return QuantTree of MatchedQuantity objects from matching var and all dependencies,
using self.KNOWN_VARS and self.KNOWN_PATTERNS when searching for matches.missing_ok: boolwhether to be lenient sometimes when missing details that would allow to fully determine deps.see help(MatchedQuantity.dep_vars) for more details.
- copy()
returns a deep copy of self.
[TODO] implement something less hacky than using the pickle module?
- property elements
ElementList of all elements in multifluid mixture assumed from single-fluid mhd.
Used to infer SINGLE_FLUID m.
- property enable_fromfile
bool: whether self.load_fromfile is enabled during self.load_direct.
If False, raise QuantCalcError if load_direct can’t get value without load_fromfile().
- property eos_mode
mode for “Equation of State” related variables (ne, T, P).
see EOS_MODE_OPTIONS for details about available options.
- property extra_coords
dict of {coord_name: coord_value} to attach to outputs of self(var).
Useful if planning to join the output of self(var) with output from a different QuantityLoader.E.g. self.extra_coords={‘run’: ‘run 0’} and other.extra_coords={‘run’: ‘run 1’},then xr.concat([self(‘n’), other(‘n’)], ‘run’) gives ‘n’ from self AND other.(this is nice if self and other have same values for dims. Otherwise, might struggle.)
- property get
alias to __call__
- get_B()
magnetic field.
[Not implemented for this class]
- get_E()
electric field.
[Not implemented for this class]
- get_E_un0()
electric field in the u_neutral=0 frame.
Here, asserts all of self(‘u_n’)==0, then returns self(‘E’).if the assertion fails, raise NotImplementedError (expect subclass to handle it).
- get_J()
current density (without displacement current). J = curl(B) / mu0.
Per unit area, e.g. the SI units would be Amperes / meter^2.
- get_Jf()
current density (associated with fluid). Jf = (nq * u) = (charge density * velocity)
This is per unit area, e.g. the SI units would be Amperes / meter^2.(If self is not a FluidHaver, this will equal the total current density.)
- get_P()
pressure. Depends on self.eos_mode; see help(type(self).eos_mode) for details.
‘ideal’ –> P from ideal gas law: P_ideal = n kB T_ideal = (gamma - 1) e.‘table’ –> P from plugging r and e into EOS lookup tables (see self.tabin).[more options might be available (depending on subclass) – see self.EOS_MODE_OPTIONS.]
- get_P_fromtable()
pressure, from plugging r and e into eos tables (see self.tabin).
- get_P_ideal()
pressure (from ideal gas law?) P = (gamma - 1) * e
[TODO] when is this relation actually true? is it ideal gas law, or something else?
- get_T()
temperature. Depends on self.eos_mode; see help(type(self).eos_mode) for details.
‘ideal’ –> T from ideal gas law: P_ideal = n kB T_ideal –> T_ideal = P_ideal / (n kB).‘table’ –> T from plugging r and e into EOS lookup tables (see self.tabin).[more options might be available (depending on subclass) – see self.EOS_MODE_OPTIONS.]
- get_T_fromtable()
temperature, from plugging r and e into eos tables (see self.tabin).
- get_T_ideal()
temperature, assuming ideal gas law. P = n kB T –> T = P / (n kB)
- get_T_neutral()
temperature of neutrals; T_n = T of SINGLE_FLUID.
(subclass might implement better T, but here assumes T_n equivalent to SF_T.)
- get_Tjoule()
temperature (“isotropic/maxwellian”), in energy units. Tjoule = kB * T.
self(‘Tjoule’) == self(‘kB*T’) == kB * T. (If using SI units, result will be in Joules.)
- get_behavior(keys=None)
return value of self.behavior.
keys: None or iterableif provided, only include these attrs.from nondim_behavior_attrs, or dims.
- get_ds()
vector(spatial scale), e.g. [dx, dy, dz].
This is the spatial scale for the underlying grid(ignoring self.slices, even if self.slices exists).[Not implemented for this class]
- get_e()
energy density. e = P / (gamma - 1) = pressure / (adiabatic index - 1)
- get_eperm()
internal energy (total, not density) per unit mass. eperm = e / r.
- get_ertab_var(var, ustr)
get var in self.units units from the eos tables, using r and e from self.
see self.tabin.keys() for var options. gets value via interpolation.ustr: strconvert result from raw to self.units by multiplying by self.u(ustr).
- get_gamma()
adiabatic index.
[Not implemented for this class]
- get_ionfrac(*, ionfrac_type)
ionization fraction(s) of element(s) of self.fluid
if SINGLE_FLUID, return ne / n.where ne = electron number density, n = total number density for all elements, excluding electrons.assumes quasineutrality, and that only once-ionized ions are relevant –> sum_ions(nion) = ne.else if self.ionfrac_mode implies ‘n’, return n / n_elem.else if self.ionfrac_mode implies ‘saha’, return 1 / (1 + 1/saha_n1n0).else if self.ionfrac_mode implies ‘radtab’, return ionfrac based on self.radtab table lookup from self(‘T’)
- get_ionfrac_radtab()
ionization fraction based on self.radtab. ionfrac_radtab = 1 - neufrac_radtab.
crash if radtab not applicable to all fluids in self.fluid.
- get_ionfrac_saha()
ionization fraction based on saha equation: ionfrac_saha = 1 / (1 + 1 / saha_n1n0)
Equivalent: n1 / (n1 + n0), where n1 & n0 = number density for element’s ions (n1) & neutrals (n0).
assumes only once-ionized ions are relevant (i.e., n0 + n1 = element’s total number density).
- get_ionfrac_type()
ionfrac_type for self.fluid; affects ‘ionfrac’ result.
The output array values will each be one of:‘SINGLE_FLUID’ <–> ionfrac = ne / n.‘n’ <–> ionfrac from n / n_elem, and fluid must be an ion Specie.‘saha’ <–> ionfrac from saha equation‘radtab’ <–> ionfrac based on self.radtab table lookup‘nan’ <–> ionfrac not defined for this fluid
- get_ionize_energy()
self.fluid element’s first ionization energy.
- get_ldebroge()
electron thermal deBroglie wavelength.
lde^2 = hplanck^2 / (2 pi me kB T)
- get_m()
average mass of fluid particle.
if SINGLE_FLUID, m computed as abundance-weighted average mass:m = self.elements.mtot() * (mass of 1 atomic mass unit).The “abundance-weighting” is as follows:m = sum_x(mx ax) / sum_x(ax), where ax = nx / nH, and x is any elem from self.elements.note: ax is related to abundance Ax via Ax = 12 + log10(ax).see help(self.elements.mtot) for more details, including a proof that mtot = rtot / ntot.if Element or Specie, return fluid.m, converted from [amu] to self.units unit system.if IonMixture, depends on m_mean_mode:‘simple’ –> mean mass of all ions in ion mixture‘density’ –> density-weighted average mass of all ions in mixture.
- get_m_neutral()
mass, of a “single neutral particle”. For Hydrogen, ~= +1 atomic mass unit.
[Uses self.get_neutral(‘m’) if possible, else crash. Subclass may override.]
- get_n(*, ntype)
number density. Formula depends on fluid:
if SINGLE_FLUID, n = (r / m), from SINGLE_FLUID r & m.default m is the abundance-weighted average particle mass; see help(self.get_m) for details.if Element, n = (r / m), wherer is inferred from abundances combined with SINGLE_FLUID r, andm is element particle mass (fluid.m)if Specie, n depends on ntype, determined from self.n_mode (and self.ne_mode, if electron);see help(self.get_ntype) for details.
- get_nI()
number density of neutral species of element(s) of self.fluid. nI = n * neufrac == n * (1 - ionfrac)
see help(self.get_saha_n1n0) and help(self.get_ionfrac) for more details.assumes only once-ionized ions are relevant (ignore twice+ ionized ions).
- get_nII()
number density of once-ionized species of element(s) of self.fluid. nII = n * ionfrac
see help(self.get_ionfrac) for more details.
- get_nII_radtab()
number density of once-ionized species of element(s) of self.fluid. nII = n * ionfrac_radtab
- get_nII_saha()
number density of once-ionized species of element(s) of self.fluid. nII = n * ionfrac_saha
assumes only once-ionized ions are relevant (ignore twice+ ionized ions).
- get_nI_radtab()
number density of neutral species of element(s) of self.fluid. nI = n * neufrac_radtab
- get_nI_saha()
number density of neutral species of element(s) of self.fluid. nI = n * (1 - ionfrac_saha)
assumes only once-ionized ions are relevant (ignore twice+ ionized ions).
- get_n_aux()
number density of self.fluid specie(s); from aux files values.
Result depends on fluid:electron –> ‘eosne’other –> crash with FormulaMissingError.
- get_n_elem()
number density of element(s) for self.fluid. n_elem = nfrac_elem * SF_n.
- get_n_from_ionfrac_charge__type()
n_from_ionfrac_charge__type for self.fluid, for inferring densities from ionization fraction.
‘I’ <–> neutrals‘II’ <–> once-ionized ions‘III+’ <–> twice+ ionized ions‘nan’ <–> unknown charge, or electrons (getting ne from ionfrac not possible here).
- get_n_mixture()
sum of n for each ion in IonMixture.
- get_n_neutral()
number density of neutrals.
[Uses self.get_neutral(‘n’) if possible, else crash. Subclass may override.]
- get_n_radtab(*, n_from_ionfrac_charge__type)
number density self.fluid, based on self.radtab lookups of self(‘SF_T’)
result depends on n_from_ionfrac_charge__type, which is based on fluid.q.
- get_n_saha(*, n_from_ionfrac_charge__type)
number density self.fluid, based on saha ionization.
result depends on n_from_ionfrac_charge__type, which is based on fluid.q.
- get_ne()
electron number density. Result depends on self.ne_mode.
See self.NE_MODE_OPTIONS for details.
- get_ne_QN()
electron number density, assuming quasineutrality.
result is sum_i qi ni / |qe|, with sum across all ions i in self.fluids.(Comes from assuming sum_s qs ns = 0, with sum across all species s in self.fluids.)
- get_ne_aux()
electron number density, from ‘hionne’ in aux.
hionne in aux is stored in cgs units.
- get_ne_fromtable()
electron number density, from plugging r and e into eos tables (see self.tabin).
- get_ne_type()
ne_type. Result depends on self.ne_mode.
Possibilities include ‘table’, ‘QN_table’. See help(self.get_ntype) for details.
- get_neufrac()
neutral fraction(s) of element(s) of self.fluid. neufrac = 1 - ionfrac.
- get_neufrac_radtab()
neutral fraction based on self.radtab and self(‘SF_T’).
crash if radtab not applicable to all fluids in self.fluid.
- get_neufrac_saha()
neutral fraction based on saha ionization. neufrac_saha = 1 - ionfrac_saha.
- get_nfrac_elem()
number density of element(s) for self.fluid, divided by total number density.
- get_nq()
charge density. nq = (n * q) = (number density * charge)
- get_ntype()
ntype of self.fluid. Result depends on fluid as well as self.n_mode (and ne_mode if electron).
See self.N_MODE_OPTIONS and self.NE_MODE_OPTIONS for options.possible results (possible in parent class)‘SINGLE_FLUID’ <–> n for SINGLE_FLUID‘elem’ <–> n for Element‘saha’ <–> n from saha equation. (not available for electrons)‘table’ <–> n from EOS table. (only available for electrons)‘QN_table’ <–> n from sum of qi ni across self.fluids, with ne from table.possible results (possible here but not in parent class)‘aux’ <–> n from ‘eosne’ file. (only available for electrons)‘QN_aux’ <–> n from sum of qi ni across self.fluids, with ne from ‘eosne’ file.
- get_nuns()
collision frequency. for a single neutral particle to collide with any s.
nuns = nusn * (m / m_neutral) * (n / n_neutral).(from conservation of momentum, and summing collisional momentum transfer between species)
- get_nusj()
collision frequency. for a single particle of s to collide with any of j.
[Not implemented for this class]
- get_nusn()
collision frequency. for a single particle of s to collide with any neutral.
Computed as self(‘nusj’, jfluid=self.jfluids.get_neutral()).
- get_p()
momentum density. p = (u * r) = (velocity * mass density).
- get_q()
charge, of a “single particle”. for protons, == +1 elementary charge.
[Not implemented for this class]
- get_r()
mass density.
if SINGLE_FLUID, r directly from Bifrost;if Element, r inferred from SINGLE_FLUID r and abundances;if Species or IonMixture, r = n * m.
- get_r_elem()
mass density of element(s) for self.fluid. r_elem = rfrac_elem * SF_r.
- get_rfrac_elem()
mass density of element(s) for self.fluid, divided by total mass density.
- get_saha_factor_exp(*, _T=None)
exp(-xi / (kB * T)) for saha equation. (See help(self.get_saha_n1n0) for full saha equation.)
xi = first ionization energy.[EFF] for efficiency, can provide (single fluid) T if already known.
- get_saha_factor_ldebroge(*, _T=None)
(2.0 / lde^3) for saha equation. (See help(self.get_saha_n1n0) for full saha equation.)
[EFF] computed “efficiently”, i.e. combine all constants before including T contribution.[EFF] for efficiency, can provide (single fluid) T if already known.
- get_saha_factor_ldebroge_ne(*, _T=None)
(ldebroge_factor / ne) for saha equation. (See help(self.get_saha_n1n0) for full saha equation.)
[EFF] for efficiency, can provide (single fluid) T if already known.
- get_saha_g1g0()
ratio of self.fluid element’s g (degeneracy of states) for g1 (ions) to g0 (neutrals).
- get_saha_n1n0()
(n1/n0) for an element, via saha equation:
‘(n1/n0) = (1/ne) * (2.0 / lde^3) * (g1 / g0) * exp(-xi / (kB * T))where the terms are defined as follows:T : temperaturene: electron number densityn1: number density of element’s once-ionized ions.n0: number density of element’s neutrals.g1: “degeneracy of states” for element’s once-ionized ions.g0: “degeneracy of states” for element’s neutrals.xi: element’s first ionization energy.lde: electron thermal deBroglie wavelength:lde^2 = hplanck^2 / (2 pi me kB T)
- get_set_or_cached(var)
returns var if found in self.setvars or self.cache, with compatible behavior_attrs.
otherwise, raise CacheNotApplicableError.if var is found in self.setvars and has relevant, but not matching behavior_attrs,self.load_across_dims will be used to load the value.
- get_single_fluid_var(var, *, _match=None)
SF_{var} (or SINGLE_FLUID_{var}) –> {var}, definitely in single fluid mode.
crashes with FluidValueError if not self.in_single_fluid_mode.The implementation here just does self.assert_single_fluid_mode(),then returns self(var) (var from SF_var or SINGLE_FLUID_var string).Subclass might override to also set self.fluid = SINGLE_FLUID.
- get_u()
velocity. vector quantity (result depends on self.component)
[Not implemented for this class]
- get_u_neutral()
velocity of neutrals. vector quantity (result depends on self.component)
[Uses self.get_neutral(‘u’) if possible, else crash. Subclass may override.]
- get_vars(vars, *args, return_type='dataset', missing_vars=UNSET, **kw)
returns values of vars from self.
result is probably an xarray.Dataset, but not guaranteed; also depends on return_type.Equivalent to self(vars, *args, return_type=’dataset’, **kw).(Actually, self(vars, …) will call self.get_vars(vars, …).)vars: iterable of strsNames of the vars to load. [‘n’, ‘u’] for number density & velocity.if any of these vars returns a return_type object, expand its keys,e.g. if ‘myDSvar’ returns dataset with ‘myvar1’, ‘myvar2’,then [‘n’, ‘myDSvar’] gives dataset with ‘n’, ‘myvar1’, ‘myvar2’.return_type: ‘dataset’ or ‘dict’if ‘dataset’, return result as xarray.Dataset.the data_var names will be the same as the var names.if ‘dict’, return result as dict of {var: value}.missing_vars: UNSET, ‘ignore’, ‘warn’, or ‘raise’what to do if any vars cause FormulaMissingError at any point in the error stack.UNSET –> use self.missing_vars if it exists, else ‘raise’.‘ignore’ –> ignore missing vars, and don’t include them in the result.‘warn’ –> ignore missing vars, but print a warning.‘raise’ –> raise FormulaMissingError if any vars are missing.additional args & kwargs are passed to self(…).
- has_var(var)
return whether self can load var. True if self.match_var(var) is found, else False.
Subclasses might override, to include checks for whether var can be loaded from data.[TODO] also check if var in self.cache or self.setvars.
- help(qstr=None, only=None, *, tree=None, modules=False, signature=False, doc=True, dense=False, print=True)
prints str for help with quants.
qstr: None or str
None –> tells info about this class & how to use this function.in particular, tells that quants are stored cls.KNOWN_VARS and cls.KNOWN_PATTERNS,and describes behavior of calling help with a string.str –> return str for help with all quants related to str.use empty str to get help for all quants.only: None or strIf provided, only get help for a subset of relevant quantities.None –> get help with all quantities related to qstr.‘VARS’ –> only get help with KNOWN_VARS.‘PATTERNS’ –> only get help with KNOWN_PATTERNS.‘TREE’ –> only get help with quantities in cls.cls_var_tree(str).‘EXACT’ –> only get help for the KNOWN_VAR exactly matching qstr.if provided when qstr is None, treat qstr as ‘’ instead.tree: None or boolHow much help to give for quantities in cls.cls_var_tree(qstr).False –> don’t even check cls.cls_var_tree(qstr).True –> help for all quantities in cls.cls_var_tree.None –> help for quantities in cls.cls_var_tree(qstr).flat_branches_until_vars()i.e. patterns & vars in tree but ignore any nodes with LoadableVar ancestors.e.g. qstr=’mean_mod_beta’ –> help with ‘mean_(.+)’, ‘mod_(.+)’, and ‘beta’,but no help with dependencies of ‘beta’ (‘q’, ‘mod_B’, ‘m’).modules: boolWhether to include modules in result.If True, result will be grouped into sections with modules written at top.signature: signature: boolwhether to include line with signature in help string.e.g. “help_str(f, *, module=True, signature=True, indent=None)”doc: doc: boolwhether to include lines with docstring in help string.e.g. “return str for help(f).” … and all the other docs in here.dense: boolWhether to reduce whitespace in result.E.g. True –> no newlines between functions. False –> one newline between functions.
- help_call_options(search=None)
prints help for kw_call_options.
if search is provided, only print help for keys containing search.
- classmethod help_quants_str(qstr=None, only=None, *, tree=None, modules=True, signature=False, doc=True, dense=False, _instance=None)
returns str for help with quants.
qstr: None or str
None –> tells info about this class & how to use this function.in particular, tells that quants are stored cls.KNOWN_VARS and cls.KNOWN_PATTERNS,and describes behavior of calling help with a string.str –> return str for help with all quants related to str.use empty str to get help for all quants.only: None or strIf provided, only get help for a subset of relevant quantities.None –> get help with all quantities related to qstr.‘VARS’ –> only get help with KNOWN_VARS.‘PATTERNS’ –> only get help with KNOWN_PATTERNS.‘TREE’ –> only get help with quantities in cls.cls_var_tree(str).‘EXACT’ –> only get help for the KNOWN_VAR exactly matching qstr.if provided when qstr is None, treat qstr as ‘’ instead.tree: None or boolHow much help to give for quantities in cls.cls_var_tree(qstr).False –> don’t even check cls.cls_var_tree(qstr).True –> help for all quantities in cls.cls_var_tree.None –> help for quantities in cls.cls_var_tree(qstr).flat_branches_until_vars()i.e. patterns & vars in tree but ignore any nodes with LoadableVar ancestors.e.g. qstr=’mean_mod_beta’ –> help with ‘mean_(.+)’, ‘mod_(.+)’, and ‘beta’,but no help with dependencies of ‘beta’ (‘q’, ‘mod_B’, ‘m’).modules: boolWhether to include modules in result.If True, result will be grouped into sections with modules written at top.signature: signature: boolwhether to include line with signature in help string.e.g. “help_str(f, *, module=True, signature=True, indent=None)”doc: doc: boolwhether to include lines with docstring in help string.e.g. “return str for help(f).” … and all the other docs in here.dense: boolWhether to reduce whitespace in result.E.g. True –> no newlines between functions. False –> one newline between functions._instance: None or QuantityLoader instanceif provided, use _instance.match_var_tree() instead of cls.cls_var_tree().
- classmethod help_str(qstr=None, only=None, **kw)
returns cls.help_quants_str(qstr=qstr, only=only, **kw).
cls.help() calls help_str.subclasses might overwrite help_str, but probably won’t touch help_quants_str.
- property in_single_fluid_mode
whether self is in “single fluid mode”.
MhdCalculator is always in single-fluid mode… but subclass might not be.Some vars (bases especially) assume single-fluid mode, so it is good to check.E.g. this ensures multifluid subclasses don’t do weird things by accident.
- property ionfrac_mode
mode for calculating self(‘ionfrac’).
ignored when self.fluid is SINGLE_FLUID. See self.IONFRAC_MODE_OPTIONS for options.
- kw_call_options(*, sorted=True)
returns list of kwarg names which can be used to set attrs self during self.__call__.
(see self.__call__ for more details).Here, returns list(self.behavior_attrs) + list(self._extra_kw_for_quantity_loader_call)
- load_direct(var, *args, **kw)
load var “directly”, from some source which is not known by the main part of PlasmaCalcs.
The implementation here just returns self.load_fromfile() (or crashes if not self.enable_fromfile),but subclasses may override to include more checks. (see DirectLoader)(Here also sets self._load_direct_used_override = None to indicate no override was used,i.e. result is from load_fromfile, not from something like setvars nor cache.)return the result (probably a numpy array, but not guaranteed).
- load_fromfile(var, *args, **kw)
load var directly from a file. Other methods should usually use load_direct, instead.
the implementation here just raises LoadingNotImplementedError;subclasses should implement this method in order to load any values from files.
- property maintaining
alias to maintaining_attrs
- maintaining_attrs(*attrs, **attrs_as_flags)
returns context manager which restores attrs of self to their original values, upon exit.
E.g. maintaining_attrs(obj, ‘attr1’, ‘attr2’, attr3=True, attr4=False)–> will restore upon exit, original values of obj.attr1, attr2, and attr3, but not attr4.
- classmethod match_var(var, *, check=['KNOWN_VARS', 'KNOWN_PATTERNS'])
match var from cls.KNOWN_VARS or cls.KNOWN_PATTERNS, or raise FormulaMissingError.
returns result=MatchedQuantity(var, loadable, _match=_match) where:
loadable is the LoadableQuantity associated with this var,_match is:None, if var in cls.KNOWN_VARS;re.fullmatch(pattern, var), if var matches any pattern in cls.KNOWN_PATTERNS.if var matches multiple patterns, only the first matching pattern is used.Uses MatchedVar if match from KNOWN_VARS, MatchedPattern if from KNOWN_PATTERNS.(note that both MatchedVar and MatchedPattern subclass MatchedQuantity.)check: str or list of str from [‘KNOWN_VARS’, ‘KNOWN_PATTERNS’]where to check for matches. Default is to check KNOWN_VARS and KNOWN_PATTERNS.E.g. to only check KNOWN_PATTERNS, use check=[‘KNOWN_PATTERNS’].loadable and _match can be retrieved via result.loadable and result._match.
- match_var_loading_dims(var, **kw_loading_dims)
return dims for loading var across.
Result will probably vary across these dims (but not guaranteed, if any dependency uses reduces_dims.)These are all Dimension dims, not maindims. (E.g. ‘fluid’ and ‘snap’, but not ‘x’, ‘y’, ‘z’).Equivalent: self.match_var_tree(var).loading_dims(**kw_loading_dims)
- match_var_result_dims(var, **kw_result_dims)
return dims which result of cls(var) will vary across.
These are all Dimension dims, not maindims. (E.g. ‘fluid’ and ‘snap’, but not ‘x’, ‘y’, ‘z’).Equivalent: cls.match_var_tree(var).result_dims(**kw_result_dims)
- match_var_result_size(var, *, maindims=True, **kw_result_dims)
return size (number of elements) which self(var) will have.
(Efficient; doesn’t actually get self(var).)Depends on current values of relevant dims. (E.g., self.fluid, not self.fluids)maindims: boolif True, include maindims_shape when calculating size.
- match_var_tree(var=UNSET, **kw_quant_tree_from_quantity_loader)
return QuantTree of MatchedQuantity objects from matching var and all dependencies,
using self.KNOWN_VARS and self.KNOWN_PATTERNS when searching for matches.var must be provided; var=UNSET will raise an error (helpful if tried calling this as a classmethod).See also: type(self).cls_var_tree, for the classmethod version of this function.Most of the time it is possible to get tree without any details from self,but sometimes not. e.g. when getting collision frequencies, self.fluid affects deps.additional kwargs will be passed to QuantTree.from_quantity_loader(…),which passes kwargs from self.kw_call_options() into self.using(**kw) while getting deps.
- matched_pattern_cls
alias of
MatchedPattern
- matched_var_cls
alias of
MatchedVar
- property n_mode
str. mode for getting Specie densities. (ignored if fluid is SINGLE_FLUID or an Element)
see N_MODE_OPTIONS for details about available options.Note that you can always calculate n using a specific formula with the appropriate var,regardless of n_mode. E.g. n_saha will always load value from saha.Note: if ne_mode is not None, override n_mode with ne_mode when getting n for electrons.
- property ne_mode
None or str. mode for getting electron number density. See NE_MODE_OPTIONS for details.
Setting self.ne_mode = ‘__internal__’ will set ne_mode as if one layer deeper in the call;for many modes this just keeps ne_mode unchanged,but for QN modes this sets ne_mode to the internal value that will be used,e.g. if ne_mode was ‘QN_table’, setting ne_mode=’__internal__’ changes it to ne_mode=’table’.
- property ne_mode_explicit
explicit ne_mode: ne_mode if not None, else n_mode.
- property nondim_behavior_attrs
list of attrs in self which control behavior of self, but which are NOT in self.dimensions.
- quant_tree(var=UNSET, **kw_quant_tree_from_quantity_loader)
return QuantTree of MatchedQuantity objects from matching var and all dependencies,
using self.KNOWN_VARS and self.KNOWN_PATTERNS when searching for matches.var must be provided; var=UNSET will raise an error (helpful if tried calling this as a classmethod).See also: type(self).cls_var_tree, for the classmethod version of this function.Most of the time it is possible to get tree without any details from self,but sometimes not. e.g. when getting collision frequencies, self.fluid affects deps.additional kwargs will be passed to QuantTree.from_quantity_loader(…),which passes kwargs from self.kw_call_options() into self.using(**kw) while getting deps.
- property radtab
dict-like manager for Genrad tables.
Each table=radtab[var] should have a table.interp(values) method,which returns value of var given appropriate values.See table.invar for name of expected inputs.
- radtab_cls
alias of
GenradTableManager
- property set
alias to set_var
- set_T_fromtable(value, **kw)
set T_fromtable to this value. T_fromtable = single fluid temperature, from er table.
Depends on the current value of r; if also setting r be sure to set r first.(internally, sets eperm such that T is the given value when doing lookups.)
- set_e(value, **kw)
set e to this value. e = energy density.
- set_eperm(value, **kw)
set eperm to this value. eperm = internal energy per unit mass == e / r.
Depends on the current value of r; if also setting r be sure to set r first.
- set_n(value, **kw)
set n to this value. n = number density.
- set_r(value, **kw)
set r to this value. r = mass density.
- set_var(var, value, behavior_attrs=None, forall=[], *, ukey=None, forced=False, **kw_using)
set var in self. When later doing self(var) to get var, return the set value,
but only if self.behavior is compatible with the relevant parts of self.behavior when var was set.This function will use, if it exists:self.KNOWN_SETTERS[var](self, value, behavior_attrs, forall=forall)Otherwise, calls:self.set_var_internal(var, value, self.behavior_attrs, forall=forall)var: strthe var to set in self.value: number, xarray, iterable or 1D array, array with shape matching self.maindims_shape.the value to set var to.number –> set var to this number.xarray –> set var to this xarray.[TODO](not yet implemented) iterable or 1D array –> set var to these values along dim=’testing’.[TODO](not yet implemented) array with shape matching self.maindims_shape –> set var to this array.behavior_attrs: None or listtells which attrs from self control behavior of the set var.The set var will only be retrieved when behavior_attrs of self are compatible.E.g. set_var(‘n’, [‘fluid’, ‘snap’]) –> saves ‘n’ in cache with current fluid & snap.Will only load ‘n’ if self.fluid and self.snap == cached fluid and snap for ‘n’.if var in self.KNOWN_SETTERS, cannot provide behavior_attrs here.else, use self.behavior_attrs if None.forall: list of stringsif provided, tells which attrs of self do NOT control the behavior of the set var.E.g. forall=[‘snap’] –> ‘snap’ will NOT be included in behavior_attrs.(anything in behavior_attrs AND forall will be removed from the final behavior_attrs)ukey: None or strif provided, tells string to give to UnitsManager when converting value’s units.When ukey is known, setting value in any unit system will enable to read it in all unit systems.E.g. set_var(‘n’, 1e10, …, ukey=’n’, units=’si’)–> self(‘n’, units=’raw’) == self(‘n’, units=’si’) * self.u(‘u’, ‘raw’, convert_from=’si’)if not provided, value will be associated with current unit system;attempted to read value in any other unit system will not used the cached value set here.E.g. set_var(‘u’, 1e10, …, units=’si’) # ukey not provided–> self(‘u’, units=’raw’) –> uses self’s other logic for getting ‘u’, not from setvars.note: if provided, ‘units’ will be added to behavior_attrs if not already in there.forced: bool, default Truehandles the case where self.KNOWN_SETTERS[var] doesn’t exist. In that case…True –> set var in self, anyway.False –> crash; raise FormulaMissingErroradditional kwargs, if provided, go to self.using(**kw) during the operation.returns list of set quantities.
- set_var_internal(var, value, behavior_attrs, forall=[], *, ukey=None)
set var in self. KNOWN_SETTERS functions may wish to use this method.
(KNOWN_SETTERS functions should NOT use self.set_var, to avoid recursion issue.)This function has the internal logic for self.set_var;set_var calls set_var_internal when self.KNOWN_SETTERS[var] not provided.var: strthe var to set in self.value: number, xarray, iterable or 1D array, array with shape matching self.maindims_shape.the value to set var to. See help(self.set_var) for more info.behavior_attrs: list of stringsthe behavior attrs relevant to setting this var;getting var only gives value when current behavior attrs values are compatible with the cached ones.forall: list of stringsif provided, tells which behavior attrs do NOT control the behavior of the set var.e.g. behavior_attrs=[‘snap’, ‘fluid’], forall=[‘snap’] –> use [‘fluid’], only.ukey: None or strif provided, tells string to give to UnitsManager when converting value’s units;when ukey is provided, can retrieve value in any unit system (probably ‘si’ or ‘raw’).when ukey not provided, if ‘units’ in used behavior attrs, can only retrieve value in that unit system.
- property setvar
alias to set_var
- property setvars
VarCache of vars set via self.set_var(). Returns these values when appropriate,
i.e. whenever self.behavior is compatible with the behavior in the cache.To empty the cache, use self.setvars.clear() to empty the cache.
- property tabin
dict-like manager for Equation Of State tables; should include keys ‘ne’, ‘T’, ‘P’.
Each table=tabin[var] should have a table.interp(r=r, e=e) method,which returns value of var in ‘raw’ units, given values of r & e in ‘raw’ units.
- tabin_cls
alias of
erTabInputManager
- property tabinputfile
path to tabinputfile, used by self._default_tabin() to create self.tabin.
- property toplevel_scale_coords
dict of {coord_name: coord_scaling} to apply to top-level outputs of self(var).
(Never applies to internal calls of self(var), only applies at self.call_depth==1.)Useful if making plots and want to scale coords by some factor.E.g., self.toplevel_scale_coords = {‘t’: 1000} to convert s to ms.CAUTION: coord units labels will remain unaffected.
- tree(var=UNSET, **kw_quant_tree_from_quantity_loader)
return QuantTree of MatchedQuantity objects from matching var and all dependencies,
using self.KNOWN_VARS and self.KNOWN_PATTERNS when searching for matches.var must be provided; var=UNSET will raise an error (helpful if tried calling this as a classmethod).See also: type(self).cls_var_tree, for the classmethod version of this function.Most of the time it is possible to get tree without any details from self,but sometimes not. e.g. when getting collision frequencies, self.fluid affects deps.additional kwargs will be passed to QuantTree.from_quantity_loader(…),which passes kwargs from self.kw_call_options() into self.using(**kw) while getting deps.
- property typevar_crash_if_nan
bool. whether to crash methods if typevar output would be ‘nan’.
False –> return NaN when typevar gives ‘nan’, instead of crashing.“typevar” here refers to any var used for checking which formula to use, from various options,e.g. ‘ntype’ in MhdMultifluidLoader or ‘ionfrac_type’ in MhdIonizationLoader.The relevant methods can check if self.typevar_crash_if_nan before returning a ‘nan’ result.
- property unset
alias to unset_var
- unset_var(var, behavior_attrs=[], *, missing_ok=True, **kw_using)
remove var from self.setvars (but only at values stored with relevant behavior).
[TODO] define rules for which vars unset which other vars…e.g. for eppic right now, set_var(‘n’) sets ‘den’ but not ‘n’;unset_var(‘n’) unsets nothing… but should probably alias to unset_var(‘den’).behavior_attrs: list of stringsonly remove cached values where self.behavior matches cached behavior for these attrs.if empty, remove all cached values for var, regardless of associated behavior.missing_ok: boolwhether it is okay for there to be zero matching cached values for var.raise CacheNotApplicableError if missing_ok=False when there are no matching cached values.additional kwargs, if provided, go to self.using(**kw) during the operation.return list of CachedQuantity objects which were removed from self.setvars.
- unset_var_internal(var, behavior_attrs, forall=[], *, ukey=None, missing_ok=True)
unset var from self.setvars.
KNOWN_SETTERS functions may wish to use this method, to unset dependent values.E.g. if u depends on n, and n is changed, may wish to unset the value of u.behavior_attrs: list of stringsthe behavior attrs relevant to setting this var.forall: list of stringsif provided, tells which behavior attrs to ignore when unsetting the var.ukey: None or stringif provided, ignore ‘units’ behavior attr when unsetting the var(due to assuming that ukey was provided when setting the var,hence that the set var could be retrieved in any units system)missing_ok: boolwhether it is okay for there to be zero matching cached values for var.raise CacheNotApplicableError if missing_ok=False when there are no matching cached values.return list of CachedQuantity objects which were removed from self.setvars.
- property using
alias to using_attrs
- using_at_call_depth(depth, **attrs_and_values)
context manager for setting attrs_and_values but only while call_depth == depth.
E.g.:
with self.using_at_call_depth(3, verbose=3):self(‘sgyrof’)# while self.call_depth == 3 inside of this ‘with’ block, uses self.verbose=3.# but everywhere else, uses original value of verbose.# assuming originally verbose=False (or unset), this example will print:| | (call_depth=2) get var=’q’| | (call_depth=2) get var=’mod_B’| | (call_depth=2) get var=’m’# compare this to simply using self.verbose=3, which would print:| (call_depth=1) get var=’sgyrof’| | (call_depth=2) get var=’q’| | (call_depth=2) get var=’mod_B’| | | (call_depth=3) get var=’B_dot_B’| | | | (call_depth=4) get var=’B_xyz’| | | | | (call_depth=5) get var=’B’| | (call_depth=2) get var=’m’Equivalent to self.call_depth_manager.using_obj_attrs_at(depth, **attrs_and_values)
- using_at_next_call_depth(**attrs_and_values)
context manager for setting attrs_and_values but only while call_depth == self.call_depth + 1
Equivalent to self.using_at_call_depth(self.call_depth + 1, **attrs_and_values).
(Also equivalent to self.call_depth_manager.using_obj_attrs_at_next(**attrs_and_values).)
- using_attrs(attrs_as_dict={}, _unset_sentinel=ATTR_UNSET, **attrs_and_values)
returns context manager which sets attrs of obj upon entry; restores original values upon exit.
_unset_sentinel: any value, default ATTR_UNSETupon entry, delete any attrs with value _unset_sentinel (compared via ‘is’).E.g. using_attrs(obj, _unset_sentinel=None, x=None) –> del obj.x upon entry.