ComponentHavingPlasmaCalculator
- class PlasmaCalcs.plasma_calculator.ComponentHavingPlasmaCalculator(*, component=None, components=[Component('x', 0), Component('y', 1), Component('z', 2)], **kw)
Bases:
ComponentHaver,DimensionlessPlasmaCalculator,VectorArithmeticLoader,VectorDerivativeLoaderDimensionlessPlasmaCalculator but with vector arithmetic and derivatives.
Not intended for direct instantiation. Instead, see options in the “hookups” subpackage,
or write your own hookup for a different type of input, following the examples there.Methods
__call__(var, *args[, name, item, verbose])returns value of var from self.
return state for pickling.
__init_subclass__(*[, dimension, dim_plural])called when subclassing DimensionHaver; sets some useful attributes related to dimension.
__setstate__(state)set state for pickling.
__setup_haver__(dim_cls, **kw_super)called by dim_cls.setup_haver(cls) when setting up cls so that it "has" dim_cls dimension.
angle_xy(A)return angle between +xhat and A, in the xy plane, in radians.
return unit vector u, given angle [radians] between +xhat and u in the xy plane.
apply_mask(arr[, masking])apply self.mask to arr, using self.masking to determine masking.
as_single_dimpoint([values, dims])return DimPoint with values for dims, but raise DimensionValueError if any value is_iterable_dim.
asserts self.quasineutral.
assign_dim_coords(array, *dims[, skip])assign all dimensions in self as coords for array.
attach_extra_coords(arr)attach any self.extra_coords to array arr but only if it is an xarray.DataArray or xarray.Dataset
check_pickle([x])checks that self (or, x, if provided) is pickleable, by pickling then unpickling.
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.
cross_component(A, B, x, *[, yz, missing_ok])return x component of A cross B, given A and B which have values for y and z 'component'.
return the components vectors need in order to find all cross product components in self.component_list
cross_product(A, B, *[, components])return cross product of vectors A and B, along dimension 'component'.
curl_component(v, x, *[, yz])return x component of curl(v).
current_n_dimpoints([dims])return number of points represented by current values of dims.
dim_values([dims])return dict of current values for dimensions in self.
dims_apply(funcname, *args_func[, dims])apply funcname to each dimension in self, with args_func and kw_func.
dims_get(attr[, dims])return dict of {dim: getattr(self.dimensions[dim], attr) for dim in dims}.
returns dict of {var: override} for all overrides of self which depend on behavior_attrs of self.
dot_product(A, B)return dot product of vectors A and B, assuming vector components along the dimension 'component'.
enumerate_dimpoints([dims, all])iterate through values of dims, yielding (idx, DimPoint) pairs.
fftN(array[, dim, ds, slices])xarray_fftN with defaults for dim & slices determined by self.fft_dims, self.fft_slices.
fft_dims_for(array)return the dims over which to apply fft for this array.
gaussian_filter(array[, dim, sigma])xarray_gaussian_filter with defaults from self.blur_dims, self.blur_sigma.
get_0()0, as an xarray.
get_1()1, as an xarray.
get_B()magnetic field.
get_E()electric field.
get_E0S1(*[, _skappa, _n])E0S1 = sum_s (qs ns skappa_s / (1 + skappa_s^2)),
dataset containing 'E0S1' and 'E0S2'.
get_E0S2(*[, _skappa, _n])E0S2 = sum_s (qs ns skappa_s^2/ (1 + skappa_s^2)),
get_E0_etaJ_perpB(*[, _E0S1, _E0S2])E0_perp_B = E0_etaJ_perpB + ..., where E0_etaJ_perpB = eta0_J * J_perp_B.
get_E0_hall(*[, _E0S1, _E0S2])E0_perp_B = E0_hall + ..., where E0_hall = eta0_hall * J x Bhat.
E0_un0_perpB = E0_etaJ_perpB + E0_hall
E0_un0_perpmodB = |E0_un0_perpB|.
E0_un0_perpmodB_min = minimum possible value of |E0_un0_perpB|, at each point.
E0_un0_perpmodB_simple = simple estimate of |E0_un0_perpB|, at each point.
speed determined from E_un0 and B: |E_un0 perp to B| / |B|.
E_un0 = electric field in the neutral frame, where u_n=0.
get_E_un0_perpmod_B(**kw_perpmod)E_un0_perpmod_B == |E_un0 perp to B| == magnitude of E, perp to B, in u_neutral=0 frame.
string telling method that will be used to get E_un0.
Eheat = Eheat_perp + Eheat_par.
get_Eheat_par(*[, _E_un0, _B, _Eheat_par_coeff])Eheat_par = Eheat_par_coeff * |E_par|^2.
Eheat_par = Eheat_par_coeff * |E_par|^2.
get_Eheat_perp(*[, _E_un0, _B, _Eheat_par_coeff])Eheat_perp = Eheat_perp_coeff * |E_perp|^2.
get_Eheat_perp_coeff(*[, _Eheat_par_coeff])Eheat_perp = Eheat_perp_coeff * |E_perp|^2.
zeroth order rate of heating of neutrals due to collisions with all charged species.
zeroth order rate of heating of neutrals due to collisions with s (self.fluid).
get_Epar()electric field, parallel to B.
electric field, perpendicular to B.
get_J()total current density.
speed determined from J perp to B, and ne: |J_perp to B| / (ne * |qe|).
get_Jf()current density (associated with fluid).
get_P()pressure ("isotropic/maxwellian").
get_T()temperature.
T_from_Eheat = T_n + Eheat.
T_from_Eheat_perp = T_n + Eheat_perp.
temperature of neutrals.
get_Tapar(var, *[, _match])Tapar --> anisotropic temperature, parallel to B.
get_Taperp(var, *[, _match])Taperp --> anisotropic temperature, perpendicular to B.
temperature ("isotropic/maxwellian"), in energy units.
get_abs(var, *[, _match])absolute value.
|electron charge|, in [self.units] units.
get_amu()1 atomic mass unit, in [self.units] units.
get_angle_xy(var, *[, _match, _val0])angle between +xhat and var, in the xy plane, in radians.
get_angle_xy_to_hat(var, *[, _match, _val0])unit vector u, given angle [radians] between +xhat and u in the xy plane.
get_astats(var, *[, _match])return dataarray of stats for var, reporting stats along new dim: 'stat'.
get_behavior([keys])return value of self.behavior.
largest power of 2 subcycling allowed for each fluid in self.fluid.
largest subcycling allowed: best_subcycle = min_timescale / minf_timescale.
get_beta()plasma beta.
get_blur(var, *[, _match])gaussian_filter(var).
get_blurk(var, *[, _match])gaussian_filter(var), temporarily using self.blur_dims = ['k_x', 'k_y', 'k_z']
get_blurt(var, *[, _match])gaussian_filter(var), temporarily using self.blur_dims = ['snap']
{i} --> self(mem_var), where mem_var = self.parenthesis_memory_key_to_var[int(i)].
get_cache_var(var, *[, _match])get var, then save to cache.
return a previously-computed tfbi solution across EBspeed grid.
get_cached_var(var, *[, _match])get var from folder within self.cache_dirname.
get_caches_var(var, *[, _match])get var, possibly from folder within self.cache_dirname.
get_compare_equals(var, *[, _match])self('A==B') --> boolean array: self('A') == self('B')
get_compare_greater_than(var, *[, _match])self('A>B') --> boolean array: self('A') > self('B')
get_compare_greater_than_or_equal(var, *[, ...])self('A>=B') --> boolean array: self('A') >= self('B')
get_compare_less_than(var, *[, _match])self('A<B') --> boolean array: self('A') < self('B')
get_compare_less_than_or_equal(var, *[, _match])self('A<=B') --> boolean array: self('A') <= self('B')
get_compare_not_equals(var, *[, _match])self('A!=B') --> boolean array: self('A') != self('B')
get_cross(var, *[, _match, _val0, _val1])cross product.
sound speed.
sound speed squared.
get_curl(var, *[, _match])curl.
rate of heating of neutrals due to collisions with all charged species.
rate of heating of neutrals due to collisions with s (self.fluid).
temperature contribution to rate of heating of neutrals due to collisions with s.
dataset of contributions to rate of heating of neutrals due to collisions with s.
velocity contribution to rate of heating of neutrals due to collisions with s.
dataset of contributions to neutral heating rate, based on 'mean' turbulent values,
get_deg2rad(var, *[, _match])convert degrees to radians.
get_delta(var, *[, _match])perturbation.
get_deltafrac(var, *[, _match])perturbation.
get_derivative(var, *[, _match])derivative.
get_div(var, *[, _match])divergence.
get_divide(var, *[, _match])division.
get_dot(var, *[, _match, _val0, _val1])dot product.
get_ds()vector(spatial scale), e.g. [dx, dy, dz].
spatial scale used when calculating timescales.
minimum spatial scale used when calculating timescales.
get_e()energy density.
get_eps0()vacuum permittivity, in [self.units] units.
Debye length (of self.fluid), using T_from_Eheat_perp instead of T.
squared Debye length (of self.fluid), using Eheat_perp instead of T.
total Debye length for all fluids: sqrt(epsilon0 kB / sum_fluids(n q^2 / T)),
collisional mean free path, using eqperp_vtherm instead of vtherm.
thermal velocity, using T_from_Eheat_perp instead of T.
get_eta0_J(*[, _E0S1, _E0S2])E0_perp_B = eta0_J * J_perp_B + ..., where eta0_J = E0S1 * |B| / (E0S1^2 + E0S2^2).
get_eta0_hall(*[, _E0S1, _E0S2])E0_perp_B = eta0_hall J x Bhat + ..., where eta0_hall = - E0S2 * |B| / (E0S1^2 + E0S2^2)
get_exp(var, *[, _match])exponentiation.
get_fft(var, *[, _match])N-dimensional fft.
get_fft_with_dims(var, *[, _match])N-dimensional fft.
get_finite(var, *[, _match])var, masked with NaN wherever values are not finite.
get_first_dimpoint([dims, enumerate])return DimPoint taking the first value of each dim in self.dimensions.
get_float(var, *[, _match])any float, as an xarray.
adiabatic index.
get_grad(var, *[, _match])gradient.
get_growthfit(var, *[, _match])self('growthfit_var') --> linear regression along 't' coord, of ln|var|.
get_growthfitk(var, *[, _match])self('growthfitk_var') --> linear regression along 't' coord, of ln|radfft_var|.
get_growthk(var, *[, _match])self('growthk_var') --> exponential growth rate of radfft_var.
get_growthrate(var, *[, _match])self('growthrate_var') --> exponential growth rate of var.
(unsigned) gyrofrequency.
get_hat(var, *[, _match, _val0])unit vector in the direction of var.
get_ifft(var, *[, _match])N-dimensional ifft.
get_imag(var, *[, _match])imaginary part.
get_inf()infinity, as an xarray.
get_int(var, *[, _match])any integer, as an xarray.
get_kB()boltzmann constant, in [self.units] units.
(unsigned) kappa (magnetization parameter).
Debye length (of self.fluid).
squared Debye length (of self.fluid).
"total" Debye length; ldebye_subset = sqrt(epsilon0 kB / sum_fluids(n q^2 / (kB T)))
total Debye length for all fluids; ldebye_total = sqrt(epsilon0 kB / sum_fluids(n q^2 / (kB T)))
get_linregt(var, *[, _match])linear regression along 't' coord.
get_ln(var, *[, _match])log base e.
get_log10(var, *[, _match])log base 10.
get_log2(var, *[, _match])log base 2.
get_logical_and(var, *[, _match])logical and.
get_logical_not(var, *[, _match])logical not.
get_logical_or(var, *[, _match])logical or.
get_lowpass(var, *[, _match])lowpass filter across self.fft_dims; keep low frequencies, zero high frequencies.
get_m()mass, of a "single particle".
mass in atomic mass units.
mass, of a "single neutral particle".
get_mask_var(var, *[, _match])mask_var --> masked version of self(var).
get_max(var, *[, _match])maximum.
get_mean(var, *[, _match])mean.
collisional mean free path.
get_mean_pm_std(var, *[, _match])return dataset of 'mean+std', 'mean', 'mean-std' for var.
get_meannormed(var, *[, _match])normalized by mean.
get_meant(var, *[, _match])mean-across-time of var.
get_median(var, *[, _match])median.
get_min(var, *[, _match])minimum.
minimum timescale across all timescales.
tells which timescale has the minimum value (across all timescales).
minimum timescale across all timescales and fluids.
tells which timescale has the minimum value (across all timescales and fluids).
get_minus(var, *[, _match])subtraction.
get_mod(var, *[, _match, _val0])magnitude of var.
get_mod2(var, *[, _match, _val0])magnitude squared of var.
get_n()number density.
number density of neutrals.
get_nan()NaN, as an xarray.
get_nandelta(var, *[, _match])perturbation.
get_nandeltafrac(var, *[, _match])perturbation.
get_nanmax(var, *[, _match])maximum.
get_nanmean(var, *[, _match])mean.
get_nanmedian(var, *[, _match])median.
get_nanmin(var, *[, _match])minimum.
get_nanrms(var, *[, _match])root mean square.
get_nanstd(var, *[, _match])standard deviation.
get_ncpu()returns ncpu, but if None, return multiprocessing.cpu_count() instead.
get_ne()electron number density.
get_negation(var, *[, _match])negation.
ion-to-electron density ratio.
get_nmean(var, *[, _match])mean of var, weighted by n.
get_nq()charge density.
get_nstd(var, *[, _match])std of var, weighted by n.
get_nuns()collision frequency.
get_nusj()collision frequency.
get_nusn()collision frequency.
get_nusn_from_drift(var, *[, _match])nusn, calculated by assuming u satisfies momentum equation to zeroth order.
get_p()momentum density.
get_parallel(var, *[, _match, _val0, _val1])A_par_B --> the component of A parallel to B.
get_parenthesis(var, *[, _match])parenthesis.
get_parmod(var, *[, _match, _val0, _val1])magnitude of the component of A parallel to B.
get_perp(var, *[, _match, _val0, _val1])A_perp_B --> A after removing the component of A parallel to B.
get_perpmod(var, *[, _match, _val0, _val1])magnitude of A after removing the component of A parallel to B.
get_pi()pi.
get_plotter(name[, who])gets the Plotter associated with this name and who.
get_plotters([who, kind, name, all_whos, ...])return list of all plotters associated with these inputs.
get_plus(var, *[, _match])addition.
get_pmstd2werr(var, *[, _match])convert dataset with 'mean+std' and 'mean-std' into dataset with 'mean' and 'std'.
get_power(var, *[, _match])power.
get_prod(var, *[, _match])prod.
get_pwl2_var(var, *[, _match])get pwl2_flatend fit to var across self.snap, evaluated at self.snap.
get_q()charge, of a "single particle".
get_r()mass density.
get_rad2deg(var, *[, _match])convert radians to degrees.
get_real(var, *[, _match])real part.
get_rms(var, *[, _match])root mean square.
get_rmscomps(var, *[, _match])root mean squared of components.
rosenberg criterion for multiple ions: rosenberg_multi = (nusn_multi / wplasma_multi)^2.
collision frequency for rosenberg criterion with multiple ions.
plasma frequency for rosenberg criterion with multiple ions.
n such that rosenberg_qn == 1, for each fluid.
n / rosenberg_n.
Rosenberg criterion for quasineutrality, for each fluid: rosenberg_qn = (nusn / wplasma)^2.
get_safe_pow2_subcycle(*[, subcycle_safety])largest "safe" power of 2 subcycling allowed for each fluid in self.fluid.
get_sci_number(var, *[, _match])any number in scientific notation, as an xarray.
get_set_or_cached(var)returns var if found in self.setvars or self.cache, with compatible behavior_attrs.
signed gyrofrequency.
signed kappa (magnetization parameter).
get_skappa_from_hall(var, *[, _match])signed kappa (magnetization parameter) that statisfies u_hall = u, in the E x B direction.
get_skappa_from_momE(var, *[, _match])signed kappa (magnetization parameter) that statisfies momentum equation in the E direction.
get_skappa_from_momExB(var, *[, _match])signed kappa (magnetization parameter) that statisfies momentum equation in the E x B direction.
get_skappa_from_pederson(var, *[, _match])signed kappa (magnetization parameter) that statisfies u_pederson = u, in the E direction.
get_slopet(var, *[, _match])slope calculated from linear regression along 't' coord.
get_sparmod(var, *[, _match, _val0, _val1])signed "magnitude" of the component of A parallel to B.
get_sqrt(var, *[, _match])square root.
get_stats(var, *[, _match])return dataset of stats for var
get_std(var, *[, _match])standard deviation.
get_sum(var, *[, _match])sum.
get_surelin_var(var, *[, _match])values of var between (inclusive) t_surelin_min and t_surelin.
get_sureturb_var(var, *[, _match])values of var at or after t_sureturb.
time before which, values are definitely in the linear regime.
start time of "definitely linear regime".
time, after which, values are definitely in the turbulent regime.
time of turbulent onset.
get_t_turb_from_pwl2_var(var, *[, _match])t_turb from pwl2_flatend fit to var.
return a 1D grid of EBspeed values with constant logstep.
threshold EBspeed for TFBI to grow.
threshold E_un0_perpmag_B for TFBI to grow.
get_tfbi_all(**kw_get_vars)returns xarray.Dataset of values relevant to TFBI theory.
get_tfbi_extras(**kw_get_vars)returns xarray.Dataset of values relevant to TFBI theory but not necessary for inputs.
tfbi_fscale = n * kappa
tfbi_fscale_rel = tfbi_fscale(this fluid) / tfbi_fscale(electrons).
get_tfbi_inputs(**kw_get_vars)returns xarray.Dataset of values to input to the tfbi theory.
get_tfbi_omega(*[, kw_tfbi_solve])Thermal Farley Buneman Instability roots with largest imaginary part at each point in self.
get_tfbi_omega_ds(*[, kw_tfbi_solve])Thermal Farley Buneman Instability solution at each point in self.
return tfbi solution across EBspeed grid.
get_times(var, *[, _match])multiplication.
timescale from drift speed if possible, else from speed using E & B fields.
timescale from speed using E & B fields.
timescale from thermal velocity, using T_from_Eheat_perp instead of T.
timescale for cyclotron motion.
timescale for collisions with neutrals.
timescale from drift speed.
timescale from thermal velocity.
timescale from plasma oscillations.
all timescales (from self.TIMESCALE_VARS) as a dataset.
all timescales (from self.TIMESCALE_VARS) as a dataset, abbreviating names.
get_tturb_var(var, *[, _match])values of var at or after t_turb.
var used for t_turb '00' standard: caches_ln_std_blur_deltafrac_n,
get_turblindiff_var(var, *[, _match])meant_sureturb_var - meant_surelin_var.
get_turblindiffwerr_var(var, *[, _match])werrmeant_sureturb_var - werrmeant_surelin_var.
get_turblindivwerr_var(var, *[, _match])werrmeant_sureturb_var / werrmeant_surelin_var.
get_u()velocity.
get_u_EdotB(*[, _E, _B])EdotB drift velocity.
equilibrium velocity; solution to the momentum equation with collisions,
get_u_hall(*[, _E, _B])Hall drift velocity.
velocity of neutrals.
get_u_pederson(*[, _E, _B])Pederson drift velocity.
get_unwrapt_2pi_var(var, *[, _match])unwrapt_{A} --> unwrapped self(A) along 't', via np.unwrap with period=2*pi.
get_upar()velocity vector, parallel to B.
velocity vector, perpendicular to B.
Alfven speed.
Alfven speed squared.
get_var_at_max_of_ref(var, *[, _match])var_at_max_of_ref --> self(var) at argmax of self(ref),
get_var_at_min_of_ref(var, *[, _match])var_at_min_of_ref --> self(var) at argmin of self(ref),
get_var_where_condition(var, *[, _match])var_where_condition --> self(var).where(self(condition)).
get_vars(vars, *args[, return_type, ...])returns values of vars from self.
get_vector_N(var, *[, _match])vector_n --> vector with n in each component.
thermal velocity.
thermal velocity for neutrals.
get_weighted_mean(weights_var, *[, _match])mean, weighted by weights.
get_weighted_std(weights_var, *[, _match])std, weighted by weights.
get_werr2pmstd(var, *[, _match])convert dataset with 'mean' and 'std' into dataset with 'mean+std', 'mean', 'mean-std'.
get_werradd(var, *[, _match])A_werradd_B = A + B, but result is a dataset with 'mean' and 'std'.
get_werrdiv(var, *[, _match])A_werrdiv_B = A / B, but result is a dataset with 'mean' and 'std'.
get_werrmean(var, *[, _match])dataset of 'mean' and 'std' of var.
get_werrmeant(var, *[, _match])dataset of 'mean' and 'std' of var, taking stats across time dimension.
get_werrmul(var, *[, _match])A_werrmul_B = A * B, but result is a dataset with 'mean' and 'std'.
get_werrsub(var, *[, _match])A_werrsub_B = A - B, but result is a dataset with 'mean' and 'std'.
get_where_condition_var(var, *[, _match])where_condition_var --> self(var).where(self(condition)).
"plasma frequency".
electron plasma frequency; Langmuir oscillations.
get_xhat()unit vector in the x direction.
get_xyz(var, *[, _match])x, y, and/or z components of var.
get_yhat()unit vector in the y direction.
get_zhat()unit vector in the z direction.
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).
ifftN(array[, dim, df, x0, ds])xarray_ifftN with defaults for dim determined by self.fft_dims.
ifft_dims_for(array)return dims over which to apply ifft for this array.
iter_dimpoints([dims, all, restore, enumerate])iterate through values of dims, returning DimPoints and setting dim values during iteration.
kw_call_options(*[, sorted])returns list of kwarg names which can be used to set attrs self during self.__call__.
load_across_dims(loader, *args_loader[, ...])return loader(...), iterating & joining across each dimension.
load_across_dims_implied_by(var, loader, ...)return loader(...), iterating & joining across each dimension implied by var.
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.
lowpass(array[, dim, keep, keep_r])xarray_lowpass with defaults for dim & keep determined by self.fft_dims, self.lowpass_keep.
magnitude(A, *[, squared])return vector magnitude of A, assuming vector components along the dimension 'component'.
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,
on_changed_quasineutral(*, old, new)called when self.quasineutral changes.
plot(name[, who, save, show, close])makes a single plot using the relevant plotter.
plot_check_nusn_from_drift(*[, u, drift, ...])plots PlasmaCalcs.timelines() for comparing nusn to nusn inferred from drifts.
polyfit(array_or_var, coord, degree[, window])polyfit along coord.
pop_dim_keys(kw)return ({key: kw.pop(key) for key in self.dimensions if key in kw}, kw).
quant_tree([var])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
record_units(array)return array.assign_attrs(self.units_meta()).
rmscomps(A)return root mean squared of components of A.
save_plots([kind, who, name, all_whos, ...])saves all plots from plotters associated with these inputs.
set_E_un0_perpmod_B(value, **kw)set E_un0_perpmod_B to this value.
set_attrs(**attrs)sets these attrs in self.
set_mask(mask)sets self.mask = mask, and increments self._mask_cache_state (if checks succeed).
set_mod_B(value, **kw)set mod_B to this value.
set self.{key} = kw.pop(key) for each key in self.dimensions if key in kw.
set self.t_turb & return t_turb from '00' standard: t_turb_from_pwl2_ln_std_blur_deltafrac_n,
set self.t_turb & return t_turb from '10' standard: t_turb_from_pwl2_ln_std_blur_deltafrac_n,
set_var(var, value[, behavior_attrs, ...])set var in self.
set_var_internal(var, value, behavior_attrs)set var in self.
set_vtherm(value, **kw)set thermal velocity, by setting T.
solve_tfbi_vs_EBspeed(*[, Mbytes_max, cache])solve tfbi across EBspeed grid from self('tfbi_EBspeed_grid').
stat_dims_for(array)return the dims to apply statistics over, for this array.
store_mask(arr)equivalent: xarray_store_mask(arr, self.mask).
take_parallel_to(B, A)return the component of A parallel to B.
take_perp_to(B, A)return the component of A perpendicular to B.
tfbi_ds([ions, all, output_mask])returns Dataset of all the values needed & relevant to TFBI theory.
tfbi_mask(*[, kappae, ionfrac, kappai, set])set & return self.mask appropriate for TFBI.
tfbi_solver([ions])return TfbiSolver object for solving TFBI theory based on values in self.
tree([var])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
return dict(units=self.units).
unmask(arr, **kw_xarray_unmask)restore arr to the same shape as unmasked unstacked arrays.
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.
using_first_dimpoint([dims])return context manager which sets dimensions to their first values (when called); restore original on exit.
apply self.toplevel_scale_coords to arr, if nonempty, else return arr unchanged.
_array_compatible_with_current_behavior(array, *)returns whether array is compatible with current self.behavior.
assert that array is compatible with current self.behavior.
checks that array is not too big for caching.
_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.
_braced_int_dep(_var, groups)returns the 'dep' associated with this var for _get_braced_int_from_parenthesis_memory
_cache_dst(array_or_name)return abspath for cached array, given array (or name of array).
_call_loader0_at_dimpoint(dimpoint, loader0, ...)return self._call_loader_at_dimpoint(dimpoint, loader0, ...).
_call_loader_at_dimpoint(dimpoint, loader, ...)with self.using(**dimpoint): return loader(*args_loader, **kw_loader)
_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.
default for self.cache_dirname.
return default for ncoarse during self.load_across_dims.
return default for ncpu during self.load_across_dims.
returns default for print_freq.
return default for timeout during self.load_across_dims.
delete dst, if it exists, but first ensure it contains '_pc_caches' in the path.
return dict of dimensions in self; {dimension name: Dimension object}
_get_maybe_missing_var(var, *args[, ...])return value of var, or None if FormulaMissingError and missing_vars 'ignore' or 'warn'.
_get_stat_var(var, statfunc)returns result of applying statfunc to self(var), possibly one dimpoint at a time then joining results.
_get_stat_var_dimpoint_wise_false(var, statfunc)returns result of applying statfunc to self(var).
_get_stat_var_dimpoint_wise_true(var, statfunc)returns result of applying statfunc to self(var).
_get_statfunc_of_var(var, statfunc)load this stat, for self(var).
_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).
context manager for incrementing call_depth.
_load_across_dims_postprocess(arrs, dims, *, ...)postprocessing results from load_across_dims, after all tasks have been completed.
returns single numpy array (with the data from arrs, which is an array of arrays).
handles array broadcasting for _load_across_dims_postprocess.
Called when self.fft_slices accessed but not yet set; create & return new FFTSlices.
_parenthesis_converted_var(before, here, after)returns the var after converting it from var like '{before}({here}){after}'.
_parenthesis_dep(_var, groups)returns the 'dep' associated with this var for get_parenthesis.
pop all self.kw_call_options() from kw, returning dict of popped options.
return slices to apply before & after differentiation.
_print_or_warn(msg[, debug_thresh])if DEBUG>=debug_thresh, print msg.
_provided_val(var[, _val, _known_vals])returns the value of var, either from _known_vals or _val.
return list of contents to go in repr of self.
_special_dims_shifters(dimnames, _shift_special)return (dict for self.using(...), dict for result.isel(...)) to _shift_special_dims.
returns expected abspath to file for storing tfbi solution across EBspeed grid.
Attributes
mode for calculating E_un0, the electric field in the neutral frame, where u_n=0.
KNOWN_PATTERNSKNOWN_PLOTTERSKNOWN_SETTERSKNOWN_VARSTFBI_EXTRASTFBI_VARSTIMESCALE_VARSUNIQUE_PLOTTERSUNSET, None, or number
whether to assert self.masking != False and mask is not None, when getting values.
whether 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,
alias to self.component_dim.assign_coord_along
alias to self.component_dim.assign_coord
dict of {attr: self.attr} for attr in self.behavior_attrs.
list of attrs in self which control behavior of self.
alias to gaussian_filter
the dims over which to possibly apply blur (BlurLoader methods).
the default sigma to use for blurring calculations.
abspath to directory for containing cached values of this CachesLoader.
where to skip array-valued behavior attrs when caching arrays (to _pc_caches)
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_attrsalias to self.component_dim.v
component dimension for ComponentHaver.
alias to self.component_dim.is_iterable
alias to self.component_dim.list
alias to self.component_dim.get_type
alias to self.component_dim.values
alias to cross_product
alias to self.component_dim.current_n
bool or 'step'.
dict of dimensions in self; {dimension name: Dimension object}.
return dict of current values for dimensions in self.
dict of {var: override} for all overrides of self which don't depend on behavior_attrs of self.
alias to dot_product
value of 'drop' kwarg for any self('{var}_where_{condition}') calls.
bool: whether self.load_fromfile is enabled during self.load_direct.
alias to self.component_dim.enumerate
alias to self.component_dim.enumerate_values
dict of {coord_name: coord_value} to attach to outputs of self(var).
alias to fftN
the dims over which to possibly apply fft (FFTLoader methods).
alias to self.fft_slices.half
alias to self.fft_slices.keep
the dict of indexers to apply to all fft results from self, by default.
alias to self.fft_slices.step
alias to __call__
alias to ifftN
alias to self.component_dim.iter
alias to self.component_dim.iter_values
alias to self.component_dim.iter_partition
alias to self.component_dim.join_along
known_patternknown_plotterknown_setterknown_varthe default value for "keep" in self.lowpass.
alias to maintaining_attrs
None or xarray.DataArray of bools,
how to apply self.mask to results at top level, if mask exists.
int
None or int
list of attrs in self which control behavior of self, but which are NOT in self.dimensions.
whether to store_mask during xarray_mask calls if self.masking.
parenthesis_memoryalias to self.polyfit_kw['boundary'].
alias to self.polyfit_kw['cov'].
alias to self.polyfit_kw['full'].
alias to self.polyfit_kw['keep_coord'].
kwargs to pass to self.polyfit(), other than array, coord, degree, and window.
polyfit_kw_key_aliasesalias to self.polyfit_kw['stddev'].
When polyfitting, tells window size to use for coarsening arrays before fitting.
None, or number (possibly negative or 0)
like self.print_freq, but converts UNSET to value based on self.verbose,
tells whether self is in quasineutral mode.
alias to set_var
alias to set_var
VarCache of vars set via self.set_var().
the dims over which to possibly apply statistics (StatsLoader methods).
whether to apply stat calculations at each DimPoint, or after loading the full array.
fraction of t_turb which tells start time of "definitely linear regime".
fraction of t_turb which tells t_surelin.
None, or time of turbulent onset.
alias to self.component_dim.take
alias to self.component_dim.take_along
(logmin, logmax, logstep) for self('tfbi_EBspeed_grid'); log is base 10.
threshold for confirming "yes there is tfbi growth predicted here", during self('tfbi_E_thresh').
None or int
dict of {coord_name: coord_scaling} to apply to top-level outputs of self(var).
bool.
the current units manager for self.
the current unit system for self.
alias to unset_var
alias to using_attrs
whether to require 'std' data var appear in at least 1 input for all werrmath operations.
alias to polyfit_window
- property E_un0_mode
mode for calculating E_un0, the electric field in the neutral frame, where u_n=0.
None, ‘un=u’, ‘un=0’, ‘E0_perpB’, ‘E0_perpmodB’, or ‘E0_perpmodB_min’.None –> E_un0 = E + u_n x B. (i.e., E & u_n in “lab frame” then transform to u_n=0 frame.)‘un=u’ –> E_un0 = E + u x B. (i.e., assume un==u; transform to the u=0 frame.)[EFF] if self.has_var(‘E_u0’), use E_un0 = self(‘E_u0’) directly, without getting u;assumes self(‘E_u0’) provides “E without the u x B contribution”.If E_u0 not available, this mode requires ‘u’ to not vary with fluid.‘un=0’ –> E_un0 = E. (i.e., assume un==0 already; no need to shift frames.)‘E0_perpB’ –> E_un0 = E0_un0_perpB. (i.e., E perp to B in u_n=0 frame,assuming zeroth order equilibrium velocities from multifluid equations,including only collisions with neutrals,and considering only E (& J) perp to B; ignoring E0 (& J) parallel to B.)‘E0_perpmodB’ –> |E_un0 perp to B| = E0_un0_perpmodB (== |E0_un0_perpB|). E_un0 = E0_un0_perpB.[EFF] equivalent to using E0_perpB, except that, when getting |E_un0 perp to B|,will use the more efficient formula for E0_un0_perpmodB.‘E0_perpmodB_min’ –> |E_un0 perp to B| = E0_un0_perpmodB_min. E_un0 = crash; cannot get E_un0 directly.(i.e., minimum possible value of |E_un0 perp to B|, regardless of collision frequencies;E0_un0_perpmodB_min = (1/sqrt(2)) * |B| |J_perp_B| / (ne |qe|).See help(self.get_E0_un0_perpmodB_min) for details.)
- __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”).However, there is one more chance for it to get intercepted: via direct_overrides.- (direct_overrides) if var in self.direct_overrides, attempts self.direct_overrides[var].The idea is to use direct_overrides when requiring alternate instructions forwhat would otherwise be a “base” var.E.g., ‘n’ may be a “base” var, but if quasineutral then ‘ne’ is not saved in a file;so, base_overrides[<key for density>] may tell how to get ‘ne’.Note: for overrides which depend on current state, use direct_overrides_dynamic.For overrides which are “always” implemented (not toggled by other things), use direct_overrides.- (fromfile) load_direct uses self.load_fromfile whenever direct_overrides is not applicable.Those are checked in the order listed.If none of those work, raise FormulaMissingError.
- name: UNSET, None, or str
- try to set result.name = name.UNSET –> use name = var.
- item: bool
- if 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 int
- set 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).
- __getstate__()
return state for pickling. pickle default ignores class attr (parenthesis_memory) but we need it.
- classmethod __init_subclass__(*, dimension=None, dim_plural=None, **kw_super)
called when subclassing DimensionHaver; sets some useful attributes related to dimension.
- dimension: str or None
- name of dimension associated with this subclass.if None, no particular dimension associated with this subclass.
- dim_plural: str or None
- plural form of dimension. if None, use str(dimension)+’s’.
Sets various attributes in cls:cls._dimension = dimension,cls._dim_plural = dim_plural,cls._dim_types = dict of all {dimension name: Dimension subclass} from cls and cls.__bases__(note - connecting self._dimension to this dict is not handled here;it is handled by __setup_haver__ called by Dimension.setup_haver)
- __setstate__(state)
set state for pickling. pickle default ignores class attr (parenthesis_memory) but we need it.
- classmethod __setup_haver__(dim_cls, **kw_super)
called by dim_cls.setup_haver(cls) when setting up cls so that it “has” dim_cls dimension.
- _apply_toplevel_scale_coords(arr)
apply self.toplevel_scale_coords to arr, if nonempty, else return arr unchanged.
- _array_compatible_with_current_behavior(array, *, return_info=False)
returns whether array is compatible with current self.behavior.
Compatible if all of the following are true:
(1) All attrs appearing in array.attrs & self.behavior must be equal.E.g., if ‘units’ in both, need array.attrs[‘units’] == self.behavior[‘units’].(2) All attrs appearing in self.behavior.nondefault(include_xr=False) must appear in array.attrs.E.g., if ‘blur_sigma’ in self.behavior.nondefault(), need ‘blur_sigma’ in array.attrs.(3) [TODO] If self.behavior.nondefault(include_xr=’only’) has any values,they must match values saved to arrays in os.path.join(array.attrs[‘filepath’], ‘behavior_arrays’)E.g., if ‘tfbi_grid1_zeros’ appears, need self.behavior[‘tfbi_grid1_zeros’].equals(behavarr),where behavarr = xarray_load(… the array at ‘behavior_arrays/tfbi_grid1_zeros.pcxarr’))[TODO] currently, caching behavior array values is not implemented;see type(self).caches_behavior_skip_xr for details.(4) All appearing in array and self.behavior.dims must be equal.E.g., if ‘fluid’ in both, need array_equal(array[‘fluid’].values, self.behavior.dims[‘fluid’])(5) If array.attrs has ‘pc__version__’ and/or ‘pc__commit_hash’,they must match the current PlasmaCalcs version and commit hash, if known.return_info: boolwhether to instead return (result, reason of mismatch, key, array value, behavior value).(reason will be ‘version’, ‘attrs’, ‘dims’, or ‘array_attrs’)(if result is True, all other values are None)
- _assert_array_compatible_with_current_behavior(array)
assert that array is compatible with current self.behavior.
(if not, crash with CacheNotApplicableError)
- _assert_cache_array_not_too_big(array)
checks that array is not too big for caching. If too big, crash with MemorySizeError.
- _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.
- _braced_int_dep(_var, groups)
returns the ‘dep’ associated with this var for _get_braced_int_from_parenthesis_memory
- _cache_dst(array_or_name)
return abspath for cached array, given array (or name of array).
(if DataArray, uses array.name; if Dataset, must provide name as str instead.)result will include .pcxarr extension.if inferred name includes ‘/’, crash (and suggest to use ÷ character instead).
- _call_loader0_at_dimpoint(dimpoint, loader0, args_loader, *, nload, MBmax, **kw_loader)
return self._call_loader_at_dimpoint(dimpoint, loader0, …).
Also does memory size check based on nload and MBmax.intended for internal use only, inside load_across_dims.arr0 is handled differently from other arrays in order to do some checks.
- _call_loader_at_dimpoint(dimpoint, loader, args_loader, **kw_loader)
with self.using(**dimpoint): return loader(*args_loader, **kw_loader)
- _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.DataArray
- result from self.__call__, before postprocessing.
- var, name, item: UNSET or value
- passed 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) if name was provided, set result.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.DataArray
- result from self.__call__, after other postprocessing.
- var, name, item: UNSET or value
- passed directly from self.__call__.Don’t need to handle these here because self._call_postprocess will handle it.
The implementation here applies masking, if applicable.see help(type(self).mask)
- _default_cache_dirname()
default for self.cache_dirname.
{self.dirname}/_pc_caches if self.dirname exists, else raise InputMissingError.
- _default_ncoarse()
return default for ncoarse during self.load_across_dims. returns DEFAULTS.LOADING_NCOARSE
- _default_ncpu()
return default for ncpu during self.load_across_dims. returns DEFAULTS.LOADING_NCPU
- _default_print_freq()
returns default for print_freq. Here, returns UNSET; i.e., infer from self.verbose.
(See self.print_freq_explicit to get the actual value of print_freq.)
- _default_timeout()
return default for timeout during self.load_across_dims. returns DEFAULTS.LOADING_TIMEOUT
- _delete_cache_dst_if_exists(dst)
delete dst, if it exists, but first ensure it contains ‘_pc_caches’ in the path.
Never deletes files which don’t contain ‘_pc_caches’ in the path.
- _get_dimensions_dict()
return dict of dimensions in self; {dimension name: Dimension object}
- _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.
- _get_stat_var(var, statfunc)
returns result of applying statfunc to self(var), possibly one dimpoint at a time then joining results.
see help(type(self).stats_dimpoint_wise) for details.
- _get_stat_var_dimpoint_wise_false(var, statfunc)
returns result of applying statfunc to self(var). (Used when self.stats_dimpoint_wise=False.)
- _get_stat_var_dimpoint_wise_true(var, statfunc, min_split=UNSET)
returns result of applying statfunc to self(var). (Used when self.stats_dimpoint_wise=True.)
- min_split: UNSET or int
- [EFF] min length of dimension before actually applying dimpointwise stats along it.1 –> no minimum. If MemorySizeError when min_split > 1, try again but with min_split=1.UNSET –> use DEFAULTS.STATS_DIMPOINT_WISE_MIN_SPLIT.
- _get_statfunc_of_var(var, statfunc)
load this stat, for self(var).
- _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: varname
- the varname to test for matches.key from self.KNOWN_VARS.keys(), or key.str from self.KNOWN_PATTERNS.keys().
- v: LoadableQuantity
- the 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.
- _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()
- _load_across_dims_postprocess(arrs, dims, *, it_dimnames, assign_coords, isel=None)
postprocessing results from load_across_dims, after all tasks have been completed.
i.e., after all arrays have been loaded, join them all together.
- _load_across_dims_postprocess__arrs_to_nparr(arr0, arrs)
returns single numpy array (with the data from arrs, which is an array of arrays).
- _load_across_dims_postprocess__broadcast_shapes(arr0, arrs, it_dimnames)
handles array broadcasting for _load_across_dims_postprocess.
returns (arr0, arrs), but with all arrs having the same shape as arr0. Crash if not possible.CAUTION: may edit arrs in-place.
(Won’t edit individual arrays’ data; just arrs which contains the arrays.)- NOTE: arr0 in result isn’t necessarily arrs.flat[0].
- arr0 in result is the “model array”, used to model coords & dims on.arr0 = first DataArray with size == max(size) across all arrays.E.g. if array shapes are [(), (), (7,1), (1,3), (7,3), (7,3) ()],then use arr0 = the first DataArray with shape (7,3).if neither array with shape (7,3) is a DataArray (i.e., has coords…)then crash instead (because we can’t properly assign coords to result.)
it_dimnames: list of names of iterable dimensions; sometimes included in error message.
- _new_fft_slices()
Called when self.fft_slices accessed but not yet set; create & return new FFTSlices.
- classmethod _parenthesis_converted_var(before, here, after)
returns the var after converting it from var like ‘{before}({here}){after}’.
use same before & after, but use {i} instead of here.Looks like: f’{before}{{{key}}}{after}’ where key=int, unique to this var.
- _parenthesis_dep(_var, groups)
returns the ‘dep’ associated with this var for get_parenthesis.
- _pop_kw_call_options(kw)
pop all self.kw_call_options() from kw, returning dict of popped options.
- _pre_and_post_deriv_slices(x)
return slices to apply before & after differentiation. (result is a 2-tuple of dicts.)
- x: str, or list of str.
- only slices relevant to these dimensions will be adjusted.(e.g. there’s no need to touch ‘y’ slices during ddx.)
Result depends primarily on self.deriv_before_slice.Note if self.deriv_before_slice=False, this method just returns (self.slices, {}).
- _print_or_warn(msg, debug_thresh=1)
if DEBUG>=debug_thresh, print msg. Else, warnings.warn(msg).
- _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)
- _repr_contents()
return list of contents to go in repr of self.
- _special_dims_shifters(dimnames, _shift_special)
return (dict for self.using(…), dict for result.isel(…)) to _shift_special_dims.
See docs of load_across_dims for more details.
- _tfbi_vs_EBspeed_file()
returns expected abspath to file for storing tfbi solution across EBspeed grid.
Depends on current value of self.tfbi_EBspeed_grid_size.Does not check whether file exists already(might use this to find existing file, or to determine filepath for saving result.)Result is like:{self.unique_notes_dirname}/_pc_tfbi/EBspeed_{logmin:.4g}_{logmax:.4g}_{logstep:.4g}.pcxarr
- static angle_xy(A)
return angle between +xhat and A, in the xy plane, in radians.
A should be a DataArray (or Dataset) with x and y in ‘component’ dimension.A can be any vector (does not need to be a unit vector, but it can be.)
- static angle_xy_to_hat(A)
return unit vector u, given angle [radians] between +xhat and u in the xy plane.
Equivalent: cos(A) * xhat + sin(A) * yhat.
- apply_mask(arr, masking=UNSET)
apply self.mask to arr, using self.masking to determine masking.
arr must have dims from self.mask.dims.- masking: UNSET, bool, ‘stacked’, or ‘simple’
- UNSET –> use self.masking.True –> alias for ‘stacked’‘stacked’ –> apply stacked mask to self.stack(arr), dropping masked points.‘simple’ –> apply mask to arr, filling masked regions with np.nan.
will crash with ValueError if masking corresponds to False, or if self.mask is None.
- property array_MBmax
UNSET, None, or number
maximum result size allowed, in Megabytes.will raise a MemorySizeError if result size would be larger than this.UNSET –> use DEFAULTS.ARRAY_MBYTES_MAX (default: 1000 MB).None –> no limit.Assumes that each result (at each dimpoint) will be the same size.
- as_single_dimpoint(values=None, *, dims=None, **values_as_kw)
return DimPoint with values for dims, but raise DimensionValueError if any value is_iterable_dim.
- values: None or dict
- values to use for the dimpoint.values will be joined with **values_as_kw; provided any of either will be equivalent.E.g. can use values={‘fluid’: ‘e’} or use fluid=’e’.if any are provided –> use values corresponding to self.{dim}=values[dim] for dim in dims.else –> use values of self.{dim} for dim in dims. (equivalent: self.dims_apply(‘_as_single’, dims=dims))
- dims: None or iterable of strs appearing in self.dimensions.keys()
- dimensions to include.None –> infer dimensions from keys of values (and values_as_kw).if no values were provided (values=None, and empty values_as_kw),use all dimensions from self.dimensions.keys().
additional kwargs provide other {dim: value} items.Examples:self.as_single_dimpoint() –> DimPoint({dim: self.{dim} for dim in self.dimensions})self.as_single_dimpoint({‘fluid’: ‘e’}) –> DimPoint({‘fluid’: ‘e’})self.as_single_dimpoint(fluid=’e’) –> DimPoint({‘fluid’: ‘e’})self.as_single_dimpoint({‘fluid’: ‘e’}, snap=0) –> DimPoint({‘fluid’: ‘e’, ‘snap’: 0})self.as_single_dimpoint(dims=[‘fluid’, ‘snap’]) –> DimPoint({‘fluid’: self.fluid, ‘snap’: self.snap})
- assert_QN()
asserts self.quasineutral. if not self._assert_QN, instead does not assert self.quasineutral.
- property assert_masking
whether to assert self.masking != False and mask is not None, when getting values.
- 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 detph”.
- 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.
- property assign_component_along
alias to self.component_dim.assign_coord_along
- property assign_component_coord
alias to self.component_dim.assign_coord
- assign_dim_coords(array, *dims, skip=[])
assign all dimensions in self as coords for array. (self.assign_{dim}_coord(array))
Assumes array is an xarray and does not have any dimensions in self.(array is not edited directly; returns result of assigning coords.)- dims: iterable of dimensions in self
- assign only these dimensions as coords. (use all dimensions if len(dims)==0)
- skip: iterable of dimensions in self
- do not assign these dimensions as coords.
- 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 blur
alias to gaussian_filter
- property blur_dims
the dims over which to possibly apply blur (BlurLoader methods).
will only blur along these dims for an array if they actually appear in the array.None –> use self.maindims. (this is the default.)
- property blur_sigma
the default sigma to use for blurring calculations.
None –> use DEFAULTS.GAUSSIAN_FILTER_SIGMA (default: 1.0)
- property cache_dirname
abspath to directory for containing cached values of this CachesLoader.
Default: {self.dirname}/_pc_caches if self.dirname exists, else raise InputMissingError. Caution: PlasmaCalcs may delete files with ‘_pc_caches’ in their path, without warning.
- property caches_behavior_skip_xr
where to skip array-valued behavior attrs when caching arrays (to _pc_caches)
and when checking compatibility with already-cached arrays (in _pc_caches).CAUTION: if True, might give subtly incorrect results if the relevant array-valued behavior attrs change.
Eventually, caching should save array-valued attrs too, but it’s trickier so this is a workaround for now.
- 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.
- check_pickle(x=None)
checks that self (or, x, if provided) is pickleable, by pickling then unpickling.
Returns result of unpickling. Useful for debugging.
- 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 str
- If 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 bool
- How 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: bool
- Whether to include modules in result.If True, result will be grouped into sections with modules written at top.
- signature: signature: bool
- whether to include line with signature in help string.e.g. “help_str(f, *, module=True, signature=True, indent=None)”
- doc: doc: bool
- whether to include lines with docstring in help string.e.g. “return str for help(f).” … and all the other docs in here.
- dense: bool
- Whether to reduce whitespace in result.E.g. True –> no newlines between functions. False –> one newline between functions.
- print: bool
- whether 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: bool
- whether to be lenient sometimes when missing details that would allow to fully determine deps.see help(MatchedQuantity.dep_vars) for more details.
- property component
alias to self.component_dim.v
- property component_dim
component dimension for ComponentHaver.
- component_dim_cls
alias of
ComponentDimension
- property component_is_iterable
alias to self.component_dim.is_iterable
- property component_list
alias to self.component_dim.list
- property component_type
alias to self.component_dim.get_type
- property components
alias to self.component_dim.values
- copy()
returns a deep copy of self.
[TODO] implement something less hacky than using the pickle module?
- property cross
alias to cross_product
- static cross_component(A, B, x, *, yz=None, missing_ok=False)
return x component of A cross B, given A and B which have values for y and z ‘component’.
- x: int, str, or Component
- tells component (of result) to get. if int or str, use XYZ.get(x)
- A, B: xarray.DataArray
- vectors to take cross product of.must include ‘component’ dimension including coordinates y and z.
- yz: None or iterable of two (int, str, or Component) objects
- the other two components; (x,y,z) should form a right-handed coordinate system.if not provided, infer from x.
- missing_ok: bool, default False
- whether it is okay for ‘component’ dimension to be missing y or z components, of A or B.if True, treat any missing components as 0.
- cross_components_needed()
return the components vectors need in order to find all cross product components in self.component_list
e.g. if self.component == ‘x’, return (‘y’, ‘z’), because (A_cross_B)_x needs Ay, Az, By, Bz but not Ax, Bx.
- static cross_product(A, B, *, components=None)
return cross product of vectors A and B, along dimension ‘component’.
If A or B missing any components, treat them as 0.- components: None or iterable of component specifiers (int, str, or Component)
- tells which components to get.None –> get all components (XYZ)e.g., (0, ‘z’) –> get component 0 and component ‘z’, i.e. X and Z.
- curl_component(v, x, *, yz=None)
return x component of curl(v).
- v: xarray.DataArray
- vector to take curl of.spatial derivatives will apply to dimensions (‘x’, ‘y’, ‘z’) (if they exist, else give 0).must include ‘components’ dimension including coordinates y and z.
- x: int, str, or Component
- tells component to get. if int or str, use self.components to get corresponding Component
- yz: None or iterable of two (int, str, or Component) objects
- the other two components; (x,y,z) should form a right-handed coordinate system.if not provided, infer from x.
- property current_n_component
alias to self.component_dim.current_n
- current_n_dimpoints(dims=None)
return number of points represented by current values of dims.
- dims: None or iterable of strs appearing in self.dimensions.keys()
- dimensions to consider. None –> use all dimensions.
E.g. current_n_dimpoints(self, dims=[‘fluid’, ‘snap’]) –> number of (fluid, snap) points;e.g. 3 fluids and 2 snaps –> 6 points.Note, for classes using maindims, maindims are not included in the number of dimpoints.Equivalent to len(list(self.iter_dimpoints(dims=dims, current=True)))
- property deriv_before_slice
bool or ‘step’. Whether to apply derivatives before any maindims slicing.
see help(type(self).slices) for slicing details.True –> get derivatives before applying slices.E.g. if slices=dict(x=slice(10, 30, 4)), getting ddx_var,would compute var across the entire domain, then ddx, then slice by x[10:30:4].This mode is most computationally expensive, but derivatives are trustworthy everywhere.‘step’ –> get derivatives before slicing step, but after slicing start & stop.E.g. if slices=dict(x=slice(10, 30, 4)), getting ddx_var,would compute var from x[10] to x[30], then ddx, then slice by x[::4].Note: if slicing by non-slice (e.g. x=5, or y=[0, 7, 10]), apply slicing afterwards.
This mode balances computational cost and trustworthiness;derivatives are trustworthy everywhere except near slices’ start & stop.False –> get derivatives after applying slices.E.g. if slices=dict(x=slice(10, 30, 4)), getting ddx_var,would compute var from x[10:30:4], then ddx.This mode is computationally cheapest, but derivatives are least trustworthy.
- dim_values(dims=None)
return dict of current values for dimensions in self.
- dims: None or iterable
- if provided, only include these dimensions.
Equivalent: DimRegion(self.dims_get(‘v’, dims=dims))
- property dimensions
dict of dimensions in self; {dimension name: Dimension object}.
e.g. {‘fluid’: self.fluid_dim, ‘snap’: self.snap_dim, …}.
- property dims
return dict of current values for dimensions in self. Equivalent: self.dim_values()
- dims_apply(funcname, *args_func, dims=None, **kw_func)
apply funcname to each dimension in self, with args_func and kw_func.
- dims: None or iterable of strs
- if provided, only apply to these dimensions.
See also: dims_get
- dims_get(attr, dims=None)
return dict of {dim: getattr(self.dimensions[dim], attr) for dim in dims}.
- dims: None or iterable
- if provided, only include these dimensions.
See also: dims_apply
- property direct_overrides
dict of {var: override} for all overrides of self which don’t depend on behavior_attrs of self.
For example, if user wants to set an override (or if setvars sets an override?), it will be here.See also: self.direct_overrides_dynamic().
- direct_overrides_dynamic()
returns dict of {var: override} for all overrides of self which depend on behavior_attrs of self.
- property dot
alias to dot_product
- static dot_product(A, B)
return dot product of vectors A and B, assuming vector components along the dimension ‘component’.
- property drop
value of ‘drop’ kwarg for any self(‘{var}_where_{condition}’) calls.
True –> drops points where condition is False. (See xarray.DataArray.where for details)False –> use nan where condition is False.- default: UNSET –> True if self(‘condition’) has ndim==1, else False.
- (easy when ndim==1 to drop nans, because condition is a 1D list of points.hard when ndim>=2. E.g. if mask (x,y)=(0,0) but not (0,1) and (1,0), can’t drop x=0 nor y=0…)
- 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 enumerate_component
alias to self.component_dim.enumerate
- property enumerate_components
alias to self.component_dim.enumerate_values
- enumerate_dimpoints(dims=None, *, all=False)
iterate through values of dims, yielding (idx, DimPoint) pairs.
idx is a dict of {dim: i} such that DimPoint values are {dim: dims[i] for dim,i in idx.items()}.Also, during iteration, set self.{dim} = value, as with self.iter_dim.Equivalent to self.iter_dimpoints(dims=dims, all=all, enumerate=True)
- 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 fft
alias to fftN
- fftN(array, dim=UNSET, ds=None, *, slices=UNSET, **kw_xarray_fftN)
xarray_fftN with defaults for dim & slices determined by self.fft_dims, self.fft_slices.
kwargs are passed to xarray_fftN. For convenience, docs for xarray_fftN are copied below.xarray_fftN docs—————-calculates fft(array) along N dimensions.shifts frequencies such that the 0-frequency is in the center.replaces result dimensions & coordinates appropriately, to indicate which dims were fft’d.- dim: None, str, or iterable of strs
- coordinates(s) to take fft over.Can be pre-fft or post-fft names. (e.g. ‘x’, ‘freq_x’, ‘freqrad_x’, ‘k_x’)promote_dim(array, coord) for any non-dimension coordinates, as needed.None –> equivalent to array.dimsstr –> just this coordinate.iterable of strs –> just these coordinates.
- ds: None, number, or dict of {dim: d}
- spacing between elements of array (pre-transform), along each dim.if number, use the same value for all dims.if None, infer via array.coords[dim].diff(dim) for each dim(requires evenly-spaced coordinates in dim; spacing checked with np.allclose)
- rad: None or bool
- whether to convert frequencies to “radians” by multiplying them by 2 * pi.E.g., for fft in space, rad=False gives 1/wavelength; rad=True gives wavenumber k.if None, infer from dim if any post-fft names provided, else default to False.
- abs: bool
- if True, return np.abs(result), instead.
- slices: dict or FFTSlices
- instructions for slicing the final result.Can provide {cname: indexer} instructing to slice post-fft dimensionassociated with cname, via indexer. (cname can be pre-fft or post-fft name.)These understand fractional indexing: can provide a fractional valuebetween -1 and 1, to use that fraction of the length along the relevant dimension.Can also provide
keep,half,step, and/ormissing_slices, here (Or, as kwargs).(raise InputConflictError if any provided in both places and have conflicting values.)See those kwargs for more details. - keep: None, True, dict, or number in 0 < keep <= 1
- implies the fraction of each dimension to keep.(ignored for any dimensions which already have a slice specified.)e.g. keep=0.4 with length=1000 would result in slice(300, 700),since that keeps 400 out of 1000 points, and is centered at 1000/2.None –> ignored.True –> use keep = DEFAULTS.FFT_KEEP (default: 0.4).dict –> different value in each dimension;keys can be pre-fft OR post-fft dimension names.UNSET –> use None.
- half: None, str, or iterable of strs
- dimensions along which to keep only the right half of the result.(ignored for any dimensions which already have a slice specified.)None –> ignored.str or iterable of strs –>can be pre-fft OR post-fft dimension name(s).Applied after keep, e.g. keep=0.4, length=1000, half=’x’ –> slice(500, 700) for x.UNSET –> use None.
- step: None, dict, int, or non-integer between -1 and 1
- step to take along each dim.(ignored for any dimensions which already have a slice specified.)fractional value –> use fraction of length (e.g. 0.01 –> 1% of dim length), min |step|=1.negative –> reverses direction (and swaps start & stop for the slice)None –> equivalent to using step=1.dict –> different value in each dimension;keys can be pre-fft OR post-fft dimension names.UNSET –> use None.
- missing_slices: ‘ignore’, ‘warn’, or ‘raise’
- tells how to handle keys not matching any fft-related coordinate.‘ignore’ –> silently ignore these keys. This is the default.‘warn’ –> issue a warning.‘raise’ –> raise an error.UNSET –> use ‘ignore’
additional kwargs passed to np.fft.fftn.returns result of fftn(…), shifted such that the 0-frequency is in the center,and with the relevant dimensions renamed as specified.
- property fft_dims
the dims over which to possibly apply fft (FFTLoader methods).
will only apply fft along these dims for an array if they actually appear in the array.None –> use self.maindims. (this is the default.)See also: self.fft_dims_for(array).
- fft_dims_for(array)
return the dims over which to apply fft for this array.
This is the intersection of self.fft_dims and array.dims.
- property fft_half
alias to self.fft_slices.half
- property fft_keep
alias to self.fft_slices.keep
- property fft_slices
the dict of indexers to apply to all fft results from self, by default.
keys can be a pre-fft or post-fft dimension name,e.g. ‘x’ or ‘freq_x’ both lead to slicing of the result’s ‘freq_x’ dimension.(note if rad=True it would be ‘k_x’ in the result, and ‘x’ would apply but not ‘freq_x’.)all other keys (not a pre-fft or post-fft dimension name) are ignored.values can be slice, int, iterable, or non-integer value between -1 and 1.fractional values are interpreted as a fraction of the length of the corresponding dimension,as per interprets_fractional_indexing. Negative fractions refer to distance from the end.e.g., dict(x=slice(-0.3, None, 0.01), y=0.8), where x and y correspond to length 1000,would be equivalent to dict(x=slice(-300, None, 10), y=800).Can also have special keys (which apply to all fft dims without a specifically-related key):- keep: fraction of each dimension to keep,
- e.g. keep=0.4 with length=1000 would result in slice(300, 700),since that keeps 400 out of 1000 points, and is centered at 1000/2.
half: dimension(s) along which to keep only the right half of the result. step: slice step. Can also be fractional to use fraction of dimension length.
For more help on special keys, see help(self._fft_slices_cls) or help(FFTSlices)
- property fft_step
alias to self.fft_slices.step
- gaussian_filter(array, dim=UNSET, sigma=UNSET, **kw_xarray_gaussian_filter)
xarray_gaussian_filter with defaults from self.blur_dims, self.blur_sigma.
kwargs are passed to xarray_gaussian_filter.For convenience, docs for xarray_gaussian_filter are copied below:xarray_gaussian_filter_docs—————————returns array after applying scipy.ndimage.gaussian_filter to it.- array: xarray.DataArray or Dataset
- filters this array, or each data_var in a dataset.
- dim: None or str or iterable of strs
- dimensions to filter along.if None, filter along all dims.
- sigma: None, number, or iterable of numbers
- standard deviation for Gaussian kernel.if iterable, must have same length as dim.if None, will use DEFAULTS.GAUSSIAN_FILTER_SIGMA (default: 1.0).
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.
additional kwargs go to scipy.ndimage.gaussian_filter.
- property get
alias to __call__
- get_0()
0, as an xarray. Code can also handle generic ints via self.get_int pattern.
- get_1()
1, as an xarray. Code can also handle generic ints via self.get_int pattern.
- get_B()
magnetic field.
[Not implemented for this class]
- get_E()
electric field.
[Not implemented for this class]
- get_E0S1(*, _skappa=None, _n=None)
E0S1 = sum_s (qs ns skappa_s / (1 + skappa_s^2)),
summed across all charged fluids (from self.fluids).see help(self.get_E0_un0_perpB) for more details.[EFF] for efficiency, can provide _skappa and/or _n if known.
- get_E0S1_and_S2()
dataset containing ‘E0S1’ and ‘E0S2’. Equivalent to self([‘E0S1’, ‘E0S2’]),
but more efficient (only computes skappa and n one time).E0S1 = sum_s (qs ns skappa_s / (1 + skappa_s^2))E0S2 = sum_s (qs ns skappa_s^2/ (1 + skappa_s^2))
- get_E0S2(*, _skappa=None, _n=None)
E0S2 = sum_s (qs ns skappa_s^2/ (1 + skappa_s^2)),
summed across all charged fluids (from self.fluids).see help(self.get_E0_un0_perpB) for more details.[EFF] for efficiency, can provide _skappa and/or _n if known.
- get_E0_etaJ_perpB(*, _E0S1=None, _E0S2=None)
E0_perp_B = E0_etaJ_perpB + …, where E0_etaJ_perpB = eta0_J * J_perp_B.
see help(self.get_E0_un0_perpB_fromJ) for more details.
- get_E0_hall(*, _E0S1=None, _E0S2=None)
E0_perp_B = E0_hall + …, where E0_hall = eta0_hall * J x Bhat.
see help(self.get_E0_un0_perpB) for more details.
- get_E0_un0_perpB()
E0_un0_perpB = E0_etaJ_perpB + E0_hall
== eta0_J * J_perp_B + eta0_hall * J x Bhat== (E0S1 |B| J_perp_B + E0S2 B cross J) / (E0S1^2 + E0S2^2), whereE0S1 = sum_s (qs ns skappa_s / (1 + skappa_s^2)),E0S2 = sum_s (qs ns skappa_s^2/ (1 + skappa_s^2)),This is the electric field in the un=0 frame of reference, assuming:- zeroth order equilibrium velocities from multifluid equations,- including only collisions with neutrals,- considering only E (& J) perp to B; ignoring E0 (& J) parallel to B.
- get_E0_un0_perpmodB()
E0_un0_perpmodB = |E0_un0_perpB|.
Should be equivalent to self(‘mod_E0_un0_perpB’), aside from rounding errors.[EFF] the method here uses an algebraic simplification of the E0_un0_perpB formula:E0_un0_perpB == (E0S1 |B| J_perp_B + E0S2 B cross J) / (E0S1^2 + E0S2^2)–> (do some algebra, and utilizing J_perp_B dot B = 0) –>E0_un0_perpmodB = (|B| |J_perp_B|) / sqrt(E0S1^2 + E0S2^2)
- get_E0_un0_perpmodB_min()
E0_un0_perpmodB_min = minimum possible value of |E0_un0_perpB|, at each point.
E0_un0_perpmodB_min = (1/sqrt(2)) * |B| |J_perp_B| / (ne |qe|)Regardless of kappa (& nusn) values for electrons and ions, will always have:E0_un0_perpmodB >= E0_un0_perpmodB_min.Logic which proves this fact (below, using “K” as shorthand for “skappa”):E0_un0_perpmodB has sqrt(E0S1^2 + E0S2^2) in the denominator;–> when sqrt(E0S1^2 + E0S2^2) is largest, E0_un0_perpmodB will be smallest.sqrt(E0S1^2 + E0S2^2) is largest when |E0S1| and |E0S2| are both largest.(1) |E0S1| <= sum_s (|qs| ns |Ks| / (1 + Ks^2))(2) |E0S2| <= sum_s (qs ns Ks^2 / (1 + Ks^2))For ANY real K, the relevant quantities are bounded by:(i) 0 < |K| / (1 + K^2) <= 1/2(ii) 0 < K^2 / (1 + K^2) < 1which can be readily shown using introductory calculus:|K|/(1+K^2) has local extrema (derivative=0) only at K=1, where |K|/(1+K^2)=1/2;it tends to 0 when K->0; and it tends to 0 when K->inf.K^2/(1+K^2) has local extrema (derivative=0) only at K=0, where it equals 0;it tends to 0 when K->0; and it tends to 1 when K->inf.Applying (i) to expression (1) above yields:|E0S1| <= sum_s |qs| ns * 1/2Utilizing quasineutrality (sum_s qs ns = 0) and qe < 0 and qi > 0, provides:sum_s |qs| ns = ne |qe| + sum_i ni qi = 2 ne |qe|–> |E0S1| <= ne |qe|Meanwhile for expression (2), note that because qe < 0 and qi > 0,ne qe (Ke^2 / (1 + Ke^2)) has opposite the sign as sum_i ni qi Ki^2 / (1 + Ki^2),so the largest possible |E0S1| occurs when one of those two terms is as small as possible.Applying (ii) to each term, and quasineutrality to the second term, yields:|ne qe (Ke^2 / (1 + Ke^2))| < ne |qe||sum_i ni qi Ki^2 / (1 + Ki^2)| < sum_i ni qi = ne |qe|–> |E0S2| < ne |qe|Combining yields:sqrt(E0S1^2 + E0S2^2) < sqrt(2) ne |qe|Thus, we always have:(|B| |J_perp_B|) / sqrt(E0S1^2 + E0S2^2) >= (|B| |J_perp_B|) / (sqrt(2) * ne |qe|)i.e. E0_un0_perpmodB >= E0_un0_perpmodB_min.
- get_E0_un0_perpmodB_simple()
E0_un0_perpmodB_simple = simple estimate of |E0_un0_perpB|, at each point.
E0_un0_perpmodB_simple = (|B| |J_perp_B|) / (ne |qe|)This is a simple estimate of |E0_un0_perpB|, accurate when kappae>>1 and kappai<<1.
- get_EBspeed()
speed determined from E_un0 and B: |E_un0 perp to B| / |B|.
- get_E_un0()
E_un0 = electric field in the neutral frame, where u_n=0.
Result depends on self.E_un0_mode; see help(type(self).E_un0_mode) for details.
- get_E_un0_perpmod_B(**kw_perpmod)
E_un0_perpmod_B == |E_un0 perp to B| == magnitude of E, perp to B, in u_neutral=0 frame.
This is usually equivalent to using self.magnitude(self.take_perp_to(B, E_un0)),but if E_un0_mode = ‘E0_perpmodB’ will use more efficient method (self(‘E0_un0_perpmodB’)),and if E_un0_mode = ‘E0_perpmodB_min’ will use different method (self(‘E0_un0_perpmodB_min’)).kwargs are passed to self.get_perpmod, if applicable.
- get_E_un0_type()
string telling method that will be used to get E_un0. Based on self.E_un0_mode.
possible results:‘nan’ <–> will crash. (e.g. this occurs if E_un0_mode = ‘E0_perpmodB_min’)‘E+unxB’ <–> self(‘E’) + self(‘u_neutral_cross_B’)‘E_u0’ <–> self(‘E_u0’)‘E+uxB’ <–> self(‘E’) + self(‘u_cross_B’)‘E’ <–> self(‘E’)‘E0_perpB’ <–> self(‘E0_un0_perpB’)
- get_Eheat()
Eheat = Eheat_perp + Eheat_par. total heating from electric field. Units of Kelvin.
From assuming u_n=0 and derivatives=0 in heating & momentum equations, which yields:
T_s = T_n + Eheat_perp + Eheat_par, whereEheat_perp = Eheat_perp_coeff * |E_perp|^2,Eheat_par = Eheat_par_coeff * |E_par|^2,E_perp = E(in u_n=0 frame) perp to B,E_par = E(in u_n=0 frame) parallel to B,Eheat_perp_coeff = (m_n / (3 kB)) (kappa_s^2 / B^2) * (1 / (1 + kappa_s^2)),Eheat_par_coeff = (m_n / (3 kB)) (kappa_s^2 / B^2).
- get_Eheat_par(*, _E_un0=None, _B=None, _Eheat_par_coeff=None)
Eheat_par = Eheat_par_coeff * |E_par|^2. heating parallel to B. Units of Kelvin.
see help(self.get_Eheat) for more details.[EFF] for efficiency, can provide _E_un0, _B and/or _Eheat_par_coeff if known.caution: if providing _E_un0 or _B, will assume any missing components are 0.
- get_Eheat_par_coeff()
Eheat_par = Eheat_par_coeff * |E_par|^2. for E heating parallel to B. Units of Kelvin.
see help(self.get_Eheat) for more details.
- get_Eheat_perp(*, _E_un0=None, _B=None, _Eheat_par_coeff=None)
Eheat_perp = Eheat_perp_coeff * |E_perp|^2. heating perp to B. Units of Kelvin.
see help(self.get_Eheat) for more details.[EFF] for efficiency, can provide _E_un0, _B and/or _Eheat_par_coeff if known.caution: if providing _E_un0 or _B, will assume any missing components are 0.
- get_Eheat_perp_coeff(*, _Eheat_par_coeff=None)
Eheat_perp = Eheat_perp_coeff * |E_perp|^2. for E heating perp to B. Units of Kelvin.
see help(self.get_Eheat) for more details.[EFF] for efficiency, can provide _Eheat_par_coeff if known.
- get_Eheat_perp_rate_n()
zeroth order rate of heating of neutrals due to collisions with all charged species.
Eheat_perp_rate_n = sum_s Eheat_perp_rate_n_s== sum_s 2 * nuns * Eheat_perp== sum_s 2 * (m_s / m_n) * (n_s / n_n) * nusn * Eheat_perp== sum_s (2 m_s / (3 kB)) * (n_s / n_n) * nusn * (kappa_s^2 / (1 + kappa_s^2)) * (|E_perp|^2 / |B|^2)Derived from plugging T_from_Eheat_perp and |u_drift| formulae into the neutral heating equation:dTn/dt + (2/3) T_n div(u_n) =sum_s (2 m_n / (m_n + m_s)) nu_{n,s} [(m_s / (3 kB)) |u_s - u_n|^2 + (T_s - T_n)]in the neutral reference frame (u_n=0),and using m_n n_n nu_{n,s} = m_s n_s nu_{s,n} which comes from conservation of momentum.
- get_Eheat_perp_rate_n_s()
zeroth order rate of heating of neutrals due to collisions with s (self.fluid).
Eheat_perp_rate_n_s = 2 * nuns * Eheat_perp== 2 * (m_s / m_n) * (n_s / n_n) * nusn * Eheat_perp== (2 m_s / (3 kB)) * (n_s / n_n) * nusn * (kappa_s^2 / (1 + kappa_s^2)) * (|E_perp|^2 / |B|^2)Derived from plugging T_from_Eheat_perp and |u_drift| formulae into the neutral heating equation:dTn/dt + (2/3) T_n div(u_n) =sum_s (2 m_n / (m_n + m_s)) nu_{n,s} [(m_s / (3 kB)) |u_s - u_n|^2 + (T_s - T_n)]in the neutral reference frame (u_n=0),and using m_n n_n nu_{n,s} = m_s n_s nu_{s,n} which comes from conservation of momentum.See also: Eheat_perp_rate_n
- get_Epar()
electric field, parallel to B. This is a full 3-vector.
Equivalent: self(‘E_par_B’) == (E dot Bhat) Bhat
- get_Eperp()
electric field, perpendicular to B. This is a full 3-vector.
Equivalent: self(‘E_perp_B’) == E - self(‘E_par_B’) == E - (E dot Bhat) Bhat
- get_J()
total current density. J = sum_across_fluids(n*q*u)
This is per unit area, e.g. the SI units would be Amperes / meter^2.
- get_JBspeed()
speed determined from J perp to B, and ne: |J_perp to B| / (ne * |qe|).
- 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 (“isotropic/maxwellian”). P = (n * Tjoule) = (number density * T [energy units])
- get_T()
temperature. “maxwellian” temperature (classical T in thermodynamics).
[Not implemented for this class]
- get_T_from_Eheat()
T_from_Eheat = T_n + Eheat. Units of Kelvin.
see help(self.get_Eheat) for more details.
- get_T_from_Eheat_perp()
T_from_Eheat_perp = T_n + Eheat_perp. Units of Kelvin.
see help(self.get_Eheat) for more details.
- get_T_neutral()
temperature of neutrals. “maxwellian” temperature (classical T in thermodynamics).
[Uses self.get_neutral(‘T’) if possible, else crash. Subclass may override.]
- get_Tapar(var, *, _match=None)
Tapar –> anisotropic temperature, parallel to B. This is a full 3-vector.
Equivalent: self(‘Ta_par_B’) == (Ta dot Bhat) BhatAlso supports ‘Tajoulepar’ to get value in energy units; == ‘Tapar*kB’.
- get_Taperp(var, *, _match=None)
Taperp –> anisotropic temperature, perpendicular to B. This is a full 3-vector.
Equivalent: self(‘Ta_perp_B’) == Ta - self(‘Ta_par_B’) == Ta - (Ta dot Bhat) BhatAlso supports ‘Tajouleperp’ to get value in energy units; == ‘Taperp*kB’.
- get_Tjoule()
temperature (“isotropic/maxwellian”), in energy units. Tjoule = kB * T.
If using SI units, result will be in Joules.
- get_abs(var, *, _match=None)
absolute value. abs(var)
- get_abs_qe()
|electron charge|, in [self.units] units. Equivalent to self.u(‘qe’).
abs to avoid any possible ambiguity, since electron charge itself is negative.
- get_amu()
1 atomic mass unit, in [self.units] units. Equivalent to self.u(‘amu’)
- get_angle_xy(var, *, _match=None, _val0=None, **_known_vals)
angle between +xhat and var, in the xy plane, in radians.
CAUTION: does not “unwrap”; all angles will be reported in the range -pi to pi.
See unwrapt2pi for example of unwrapping (see also: np.unwrap)angle_xy_{A} –> atan2(Ay, Ax).[EFF] can provide known val for A, to avoid recalculating it. (include leading underscore.)e.g. self(‘angle_xy_E’, _E=E) –> angle between +xhat and E, using E which is already known.
- get_angle_xy_to_hat(var, *, _match=None, _val0=None, **_known_vals)
unit vector u, given angle [radians] between +xhat and u in the xy plane.
angle_xy_to_hat_{A} –> cos(A) * xhat + sin(A) * yhat.
- get_astats(var, *, _match=None)
return dataarray of stats for var, reporting stats along new dim: ‘stat’.
stats include: mean, std, min, max, median, rms.Applied only along any self.stat_dims in array.Compatible with Dataset vars (without existing ‘stat’ coord or dim).The result excludes whichever dims the stats are being taken across,and adds the new dim ‘stat’ with the stats.Consider also: self(‘stats_var’), self(‘var’).pc.stats(to_da=’stat’)
- get_behavior(keys=None)
return value of self.behavior.
- keys: None or iterable
- if provided, only include these attrs.from nondim_behavior_attrs, or dims.
- get_best_pow2_subcycle()
largest power of 2 subcycling allowed for each fluid in self.fluid.
result = array of values like 2^N, with largest N such that result < best_subcycle.
- get_best_subcycle()
largest subcycling allowed: best_subcycle = min_timescale / minf_timescale.
min_timescale = min timescale for self.fluid, across all timescales.minf_timescale = min timescale across all fluids and all timescales.(when computing minf_timescale here, always use all self.fluids.)E.g. fluid=fluids=[‘e’,’H+’,’C+’], min_timescale=[1e-8, 1e-7, 5e-7]–> minf_timescale will be 1e-8, so result will be [1, 10, 50].
- get_beta()
plasma beta. beta = (pressure / magnetic pressure) = (P / (B^2 / (2 mu0)))
- get_blur(var, *, _match=None)
gaussian_filter(var). Applied along all self.blur_dims in array.
‘blur_var’ or ‘gaussian_filter_var’; both are equivalent.
- get_blurk(var, *, _match=None)
gaussian_filter(var), temporarily using self.blur_dims = [‘k_x’, ‘k_y’, ‘k_z’]
‘blurk_var’ or ‘gaussian_filterk_var’; both are equivalent.
- get_blurt(var, *, _match=None)
gaussian_filter(var), temporarily using self.blur_dims = [‘snap’]
‘blurt_var’ or ‘gaussian_filtert_var’; both are equivalent.
- get_braced_int_from_parenthesis_memory(var, *, _match=None)
{i} –> self(mem_var), where mem_var = self.parenthesis_memory_key_to_var[int(i)].
- get_cache_var(var, *, _match=None)
get var, then save to cache. returns value of var.
if cached result already exists, will overwrite it.if result is too big, crash with MemorySizeError.see also: caches_var, cached_var
- get_cached_tfbi_vs_EBspeed()
return a previously-computed tfbi solution across EBspeed grid.
Expects solution to live in _tfbi_vs_EBspeed_file(); default:{self.unique_notes_dirname}/_pc_tfbi/EBspeed_{logmin:.4g}_{logmax:.4g}_{logstep:.4g}.pcxarr- CAUTION: the implementation here assumes self.tfbi_EBspeed_grid_size is enough to uniquely specify the result;
- e.g. if there is a different result at each snapshot of self, that will not be understood here.
- get_cached_var(var, *, _match=None)
get var from folder within self.cache_dirname.
if not already cached, crash with CacheNotApplicableError.if previously cached, ensures attrs agree with self.behavior.nondefault(),and ensures dims agree with self.behavior.dims.see also: caches_var, cache_var
- get_caches_var(var, *, _match=None)
get var, possibly from folder within self.cache_dirname.
puts self.behavior.nondefault() as attrs of result.(caching not yet implemented for arrays with complicated nondefault behavior,e.g. will fail if trying to use caches_var syntax and masking at the same time.Workaround: separately call xarray_save and xarray_load, for results you care about.
Other workaround: use )if previously cached, check if applicable, i.e.whether attrs agree with self.behavior.nondefault(), and dims agree with self.behavior.dims.if applicable, then return cached result.else, destroy cache and proceed as if not already cached (see below).if not already cached, saves to {self.cache_dirname}/{var},unless result is too big (in which case, crash with MemorySizeError).“too big” [MB] == DEFAULTS.CACHE_ARRAY_MBYTES_MAX (default: 1)see also: cached_var, cache_var
- get_compare_equals(var, *, _match=None)
self(‘A==B’) –> boolean array: self(‘A’) == self(‘B’)
- get_compare_greater_than(var, *, _match=None)
self(‘A>B’) –> boolean array: self(‘A’) > self(‘B’)
- get_compare_greater_than_or_equal(var, *, _match=None)
self(‘A>=B’) –> boolean array: self(‘A’) >= self(‘B’)
- get_compare_less_than(var, *, _match=None)
self(‘A<B’) –> boolean array: self(‘A’) < self(‘B’)
- get_compare_less_than_or_equal(var, *, _match=None)
self(‘A<=B’) –> boolean array: self(‘A’) <= self(‘B’)
- get_compare_not_equals(var, *, _match=None)
self(‘A!=B’) –> boolean array: self(‘A’) != self(‘B’)
- get_cross(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
cross product. {A}_cross_{B} –> A cross B.
returned components are determined by self.component.(see also: the get_xyz pattern. E.g., {A}_cross_{B}_x –> x component of A cross B)[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘u_cross_E’, _u=u, _E=E) –> u cross E, using u and E which are already known.- CAUTION: if providing values, include all self.cross_components_needed() components;
- missing components will be assumed to be 0.
E.g. if providing u to calculate u_cross_E, but u doesn’t have x component, assumes u_x=0.can alternatively provide _val0 for A and/or _val1 for B.
- get_csound()
sound speed. csound = sqrt(gamma * P / r)
- get_csound2()
sound speed squared. csound2 = gamma P / r.
- get_curl(var, *, _match=None)
curl. ‘curl_{var}’ –> curl(var), i.e. (du_z/dy - du_y/dz, du_x/dz - du_z/dx, du_y/dx - du_x/dy).
returned components are determined by self.component.(see also: the get_xyz pattern. E.g., curl_u_x –> x component of curl(u))if self.slices nonempty, self.deriv_before_slice controls whether slicing occurs before or after div.
- get_dTndt()
rate of heating of neutrals due to collisions with all charged species.
dTndt = sum_s dTndt_s== sum_s 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2 + (T_s - T_n)]
- get_dTndt_s()
rate of heating of neutrals due to collisions with s (self.fluid).
dTndt_s = 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2 + (T_s - T_n)]
- get_dTndt_s_T()
temperature contribution to rate of heating of neutrals due to collisions with s.
dTndt_s_T = 2 m_n / (m_n + m_s) * nuns * [(T_s - T_n)]
- get_dTndt_s_ds()
dataset of contributions to rate of heating of neutrals due to collisions with s.
dTndt_s = 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2 + (T_s - T_n)]Assumes u_n==0; else crash with QuantCalcError.result has keys:‘dTndt_u2’: 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2]‘dTndt_T’: 2 m_n / (m_n + m_s) * nuns * [(T_s - T_n)]
- get_dTndt_s_u2()
velocity contribution to rate of heating of neutrals due to collisions with s.
dTndt_s_u2 = 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2]
- get_dTndt_turb0_s_ds()
dataset of contributions to neutral heating rate, based on ‘mean’ turbulent values,
for each fluid (in self.fluid), due to collisions.Assumes u_n==0, and does not check.result has keys:‘dTndt_u2’: 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2]‘dTndt_T’: 2 m_n / (m_n + m_s) * nuns * [(T_s - T_n)]Except, use werrmeant_sureturb_u instead of u_s,and werrmeant_sureturb_T instead of T_sFor more accurate computation, consider self(‘werrmeant_sureturb_dTndt_s’)
- get_deg2rad(var, *, _match=None)
convert degrees to radians. deg2rad_{A} –> A * pi / 180.
self(‘deg2rad_var’) == np.deg2rad(self(‘var’))
- get_delta(var, *, _match=None)
perturbation. var - mean(var). Applied only along any self.stat_dims in array.
- get_deltafrac(var, *, _match=None)
perturbation. (var - mean(var)) / mean(var). Applied only along any self.stat_dims in array.
- get_derivative(var, *, _match=None)
derivative. dd{x}_{var} –> d{var}/d{x}.
self(var) must return an object with {x} in its coordinates.E.g. for x=’y’, self(var).coords[‘y’] are required.
- get_div(var, *, _match=None)
divergence. ‘div_{var}’ –> div(var), i.e. du_x/dx + du_y/dy + du_z/dz.
if component(s) is provided, only include that component(s) during the calculation.e.g. div_u__xy –> du_x/dx + du_y/dy.if self.slices nonempty, self.deriv_before_slice controls whether slicing occurs before or after div.
- get_divide(var, *, _match=None)
division. var0 / var1.
- get_dot(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
dot product. {A}_dot_{B} –> A dot B.
if component(s) is provided, only include that component(s) during the calculation.e.g. A_dot_B__xy –> Ax * Bx + Ay * By.[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘u_dot_E’, _u=u, _E=E) –> u dot E, using u and E which are already known.if providing value as None, it will be treated as if value not provided.CAUTION: Not tested when simultaneously providing components such as A_dot_B__xy.
can alternatively provide _val0 for A and/or _val1 for B.
- get_ds()
vector(spatial scale), e.g. [dx, dy, dz]
[Not implemented for this class]
- get_ds_for_timescales()
spatial scale used when calculating timescales. vector(ds), e.g. [dx, dy, dz].
The method here just returns ds. Subclasses might overwrite if they use a different ds for timescales.
- get_dsmin_for_timescales()
minimum spatial scale used when calculating timescales.
min(ds_for_timescales) across components.
- get_e()
energy density. e = P / (gamma - 1) = pressure / (adiabatic index - 1)
- get_eps0()
vacuum permittivity, in [self.units] units. Equivalent to self.u(‘eps0’)
- get_eqperp_ldebye()
Debye length (of self.fluid), using T_from_Eheat_perp instead of T.
eqperp_ldebye = sqrt(epsilon0 kB T_from_Eheat_perp / (n q^2))
- get_eqperp_ldebye2()
squared Debye length (of self.fluid), using Eheat_perp instead of T.
eqperp_ldebye2 = epsilon0 kB T_from_Eheat_perp / (n q^2)
- get_eqperp_ldebye_total()
total Debye length for all fluids: sqrt(epsilon0 kB / sum_fluids(n q^2 / T)),
using T = T_from_Eheat_perp.Equivalent: sqrt( 1 / sum_fluids(1/eqperp_ldebye^2) )
- get_eqperp_mean_free_path()
collisional mean free path, using eqperp_vtherm instead of vtherm.
eqperp_lmfp = eqperp_vtherm / nusn
- get_eqperp_vtherm()
thermal velocity, using T_from_Eheat_perp instead of T.
eqperp_vtherm = sqrt(kB T_from_Eheat_perp / m)
- get_eta0_J(*, _E0S1=None, _E0S2=None)
E0_perp_B = eta0_J * J_perp_B + …, where eta0_J = E0S1 * |B| / (E0S1^2 + E0S2^2). note:
see help(self.get_E0_un0_perpB) for more details.[EFF] for efficiency, can provide _E0S1 and/or _E0S2 if known.
- get_eta0_hall(*, _E0S1=None, _E0S2=None)
E0_perp_B = eta0_hall J x Bhat + …, where eta0_hall = - E0S2 * |B| / (E0S1^2 + E0S2^2)
see help(self.get_E0_un0_perpB) for more details.[EFF] for efficiency, can provide _E0S1 and/or _E0S2 if known.
- get_exp(var, *, _match=None)
exponentiation. exp(var). Also known as e^var. See also: get_power
- get_fft(var, *, _match=None)
N-dimensional fft. fft(var). Applied along all fft_dims in array.
self.get(‘[rad]fft[N]_[var]’), where [rad]=’rad’ or ‘’, and [N]=any integer or ‘’E.g. ‘fft_var’, ‘radfft_var’, ‘fft1_var’, ‘fft2_var’, ‘radfft1_var’, ‘radfft2_var’.‘rad’ –> multiply result’s frequency coordinates by 2 * pi.(array values will be the same either way, but coordinates will be different.)N provided –> fft must be along exactly this many dimensions, else crash with DimensionError.E.g. N=2 means self(array) must have exactly 2 dims which are also in self.fft_dims.Feel free to separately self.fft_dims, or enter it as a kwarg via self(…, fft_dims=…).
- get_fft_with_dims(var, *, _match=None)
N-dimensional fft. fft(var). Applied along the indicated dims.
self.get(‘([rad]fft[dims]_[var]’), where [rad]=’rad’ or ‘’, and [dims]=any combination of xyzt.E.g. ‘fftx_var’, ‘fftt_var’, ‘fftyz_var’, ‘radfftxy_var’, ‘fftzyt_var’, ‘radfftyzt_var’.‘rad’ –> multiply result’s frequency coordinates by 2 * pi.(array values will be the same either way, but coordinates will be different.)
- get_finite(var, *, _match=None)
var, masked with NaN wherever values are not finite.
- get_first_dimpoint(dims=None, *, enumerate=False)
return DimPoint taking the first value of each dim in self.dimensions.
- dims: None or iterable of strs appearing in self.dimensions.keys()
- dimensions to include. None –> use all dimensions.
- enumerate: bool
- whether to return (idx, DimPoint) instead of just DimPoint.
- get_float(var, *, _match=None)
any float, as an xarray.
- get_gamma()
adiabatic index.
[Not implemented for this class]
- get_grad(var, *, _match=None)
gradient. ‘grad_{var}’ –> grad(var), i.e. (dn/dx, dn/dy, dn/dz).
returned components are determined by self.component.(see also: the get_xyz pattern. E.g., ‘grad_n_x’ –> x component of grad(n).to get grad of a vector’s component instead, use parentheses, e.g. ‘grad_(u_x)’)if self.slices nonempty, self.deriv_before_slice controls whether slicing occurs before or after div.
- get_growthfit(var, *, _match=None)
self(‘growthfit_var’) –> linear regression along ‘t’ coord, of ln|var|.
result[‘polyfit_coefficients’].sel(degree=1).drop_vars(‘degree’) gives the growth rate,
because growth rate = slope of natural log of |var| vs ‘t’.result might also contain other variables, depending on self.polyfit_kw;might want to use polyfit_stddev=True, polyfit_cov=True or polyfit_full=True to get more info.see help(type(self).polyfit_kw) for more options.
- get_growthfitk(var, *, _match=None)
self(‘growthfitk_var’) –> linear regression along ‘t’ coord, of ln|radfft_var|.
result[‘polyfit_coefficients’].sel(degree=1).drop_vars(‘degree’) gives the growth rate,
because growth rate = slope of natural log of |var| vs ‘t’.result might also contain other variables, depending on self.polyfit_kw;might want to use polyfit_stddev=True, polyfit_cov=True or polyfit_full=True to get more info.see help(type(self).polyfit_kw) for more options.Assumes, but does not check, that fft_dims are spatial, only.
- get_growthk(var, *, _match=None)
self(‘growthk_var’) –> exponential growth rate of radfft_var.
i.e. for each k, gives slope of ln|radfft_var| vs ‘t’.self(‘growthk_var’) == self(‘growthrate_radfft_var’).Accepts strings starting with ‘growth_vs_k_’ or ‘growthk_’.behavior affected by self.polyfit_kw; see help(type(self).polyfit_kw) for details.Assumes, but does not check, that fft_dims are spatial, only.
- get_growthrate(var, *, _match=None)
self(‘growthrate_var’) –> exponential growth rate of var. i.e., slope of ln|var| vs ‘t’.
self(‘growthrate_var’) == self(‘slopet_ln_abs_var’).behavior affected by self.polyfit_kw; see help(type(self).polyfit_kw) for details.
- get_gyrof()
(unsigned) gyrofrequency. gyrof == |sgyrof| == |q| |B| / m == |charge| * |B| / mass.
- get_hat(var, *, _match=None, _val0=None, **_known_vals)
unit vector in the direction of var. hat_{A} –> A / |A|.
returned components are determined by self.component.(e.g. when self.component==’x’, hat_A –> A_x / |A|.)[EFF] can provide known val for A, to avoid recalculating it. (include leading underscore.)e.g. self(‘hat_E’, _E=E) –> E / |E|, using E which is already known.can alternatively provide _val0 for A.
- get_ifft(var, *, _match=None)
N-dimensional ifft. ifft(var). Applied along all fft_dims in array.
self.get(‘ifft[N]_[var]’), where [N]=any integer or ‘’E.g. ‘ifft_var’, ‘ifft1_var’, ‘ifft2_var’.N provided –> ifft must be along exactly this many dimensions, else crash with DimensionError.E.g. N=2 means self(array) must have exactly 2 dims which are also in self.fft_dims.Feel free to separately self.fft_dims, or enter it as a kwarg via self(…, fft_dims=…).
- get_imag(var, *, _match=None)
imaginary part. np.imag(self(var))
- get_inf()
infinity, as an xarray.
- get_int(var, *, _match=None)
any integer, as an xarray.
- get_kB()
boltzmann constant, in [self.units] units. Equivalent to self.u(‘kB’)
- get_kappa()
(unsigned) kappa (magnetization parameter). kappa = |skappa| == |gyrof| / nusn.
kappa = |gyrofrequency| / collision frequency of self.fluid with neutrals.
- get_ldebye()
Debye length (of self.fluid). ldebye = sqrt(epsilon0 kB T / (n q^2))
- get_ldebye2()
squared Debye length (of self.fluid). ldebye2 = epsilon0 kB T / (n q^2)
- get_ldebye_subset()
“total” Debye length; ldebye_subset = sqrt(epsilon0 kB / sum_fluids(n q^2 / (kB T)))
sum is taken over the fluids in self.fluid.Equivalent: sqrt( 1 / sum_fluids(1/ldebye^2) )
- get_ldebye_total()
total Debye length for all fluids; ldebye_total = sqrt(epsilon0 kB / sum_fluids(n q^2 / (kB T)))
sum is taken over all the fluids in self.fluids.Equivalent: sqrt( 1 / sum_fluids(1/ldebye^2) )
- get_linregt(var, *, _match=None)
linear regression along ‘t’ coord. result is an xarray.DataSet including ‘polyfit_coefficients’.
Equivalent to self.polyfit(var, ‘t’, degree=1).behavior affected by self.polyfit_kw; see help(type(self).polyfit_kw) for details.
- get_ln(var, *, _match=None)
log base e. ln(var). (‘ln’ and ‘loge’ are aliases. Uses np.log; not np.log10.)
- get_log10(var, *, _match=None)
log base 10. log10(var)
- get_log2(var, *, _match=None)
log base 2. log2(var)
- get_logical_and(var, *, _match=None)
logical and. var0 and var1. Equivalent: self(var0) & self(var1)
- get_logical_not(var, *, _match=None)
logical not. not var. Equivalent: ~self(var)
- get_logical_or(var, *, _match=None)
logical or. var0 or var1. Equivalent: self(var0) | self(var1)
- get_lowpass(var, *, _match=None)
lowpass filter across self.fft_dims; keep low frequencies, zero high frequencies.
ifft(fft(self(var) * filter), where filter = 1 for low frequencies, 0 for high frequencies.fraction of each fft’d dimension to keep is determined by self.lowpass_keep.Default is DEFAULTS.LOWPASS_KEEP (default: 0.4).
- get_m()
mass, of a “single particle”. For protons, ~= +1 atomic mass unit.
[Not implemented for this class]
- get_m_amu()
mass in atomic mass units. Equivalent to self(‘m/amu’).
- 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_mask_var(var, *, _match=None)
mask_var –> masked version of self(var).
mask_var and stacked_mask_var = equivalent to self(var, masking=’stacked’).simple_mask_var = equivalent to self(var, masking=’simple’).
- get_max(var, *, _match=None)
maximum. max(var). Applied only along any self.stat_dims in array.
- get_mean(var, *, _match=None)
mean. mean(var). Applied only along any self.stat_dims in array.
- get_mean_free_path()
collisional mean free path. lmfp = vtherm / nusn = thermal velocity / collision frequency.
- get_mean_pm_std(var, *, _match=None)
return dataset of ‘mean+std’, ‘mean’, ‘mean-std’ for var.
Computed along any self.stat_dims in array.Equivalent: werr2pmstd_werrmean_var
- get_meannormed(var, *, _match=None)
normalized by mean. var / mean(var). Applied only along any self.stat_dims in array.
- get_meant(var, *, _match=None)
mean-across-time of var.
self(meant_var) –> self(var).mean(tdim), where tdim is the dim associated with time,(tdim default ‘snap’, but if ‘t’ coord associated with a dim, use that dim.)
- get_median(var, *, _match=None)
median. median(var). Applied only along any self.stat_dims in array.
- get_min(var, *, _match=None)
minimum. min(var). Applied only along any self.stat_dims in array.
- get_min_timescale()
minimum timescale across all timescales.
Equivalent: self(‘timescales’).pc.minimum()
- get_min_timescale_type()
tells which timescale has the minimum value (across all timescales).
Equivalent: self(‘timescales_abbrv’).pc.varmin()result is a string-valued array, values from self.TIMESCALE_VARS (removing ‘timescale_’ in names):‘wplasma’, ‘gyrof’, ‘nusn’, ‘vtherm’, ‘EBspeed’
- get_minf_timescale()
minimum timescale across all timescales and fluids.
Equivalent: self(‘timescales’).min(‘fluid’).pc.minimum()
- get_minf_timescale_type()
tells which timescale has the minimum value (across all timescales and fluids).
Equivalent: self(‘timescales_abbrv’).min(‘fluid’).pc.varmin()result is a string-valued array, values from self.TIMESCALE_VARS (removing ‘timescale_’ in names):‘wplasma’, ‘gyrof’, ‘nusn’, ‘vtherm’, ‘EBspeed’
- get_minus(var, *, _match=None)
subtraction. var0 - var1.
- get_mod(var, *, _match=None, _val0=None, **_known_vals)
magnitude of var. mod_{A} –> |A|. == sqrt(A dot A) == sqrt(Ax^2 + Ay^2 + Az^2).
alias: ‘mag_{A}’ is equivalent to ‘mod_{A}’
if component(s) is provided, only include that component(s) during the calculation.e.g. mod_A__xy –> sqrt(Ax^2 + Ay^2).[EFF] can provide known vals for {var} to avoid recalculating it. (include leading underscore.)e.g. self(‘mod_E’, _E=E) –> |E|, using E which is already known.CAUTION: Not tested when simultaneously providing components such as mod_A__xy.
can alternatively provide _val0 for A.
- get_mod2(var, *, _match=None, _val0=None, **_known_vals)
magnitude squared of var. mod2_{A} –> |A|^2. == A dot A == Ax^2 + Ay^2 + Az^2.
alias: ‘mag2_{A}’ is equivalent to ‘mod2_{A}’
if component(s) is provided, only include that component(s) during the calculation.e.g. mod2_A__xy –> Ax^2 + Ay^2.[EFF] can provide known vals for {var} to avoid recalculating it. (include leading underscore.)e.g. self(‘mod2_E’, _E=E) –> |E|**2, using E which is already known.CAUTION: Not tested when simultaneously providing components such as mod_A__xy.
can alternatively provide _val0 for A.
- get_n()
number density.
[Not implemented for this class]
- get_n_neutral()
number density of neutrals.
[Uses self.get_neutral(‘n’) if possible, else crash. Subclass may override.]
- get_nan()
NaN, as an xarray.
- get_nandelta(var, *, _match=None)
perturbation. var - mean(var), ignoring NaNs AND infs.
Applied only along any self.stat_dims in array.
- get_nandeltafrac(var, *, _match=None)
perturbation. (var - mean(var)) / mean(var), ignoring NaNs AND infs.
Applied only along any self.stat_dims in array.
- get_nanmax(var, *, _match=None)
maximum. max(var), ignoring NaNs AND infs. Applied only along any self.stat_dims in array.
- get_nanmean(var, *, _match=None)
mean. mean(var), ignoring NaNs AND infs. Applied only along any self.stat_dims in array.
- get_nanmedian(var, *, _match=None)
median. median(var), ignoring NaNs AND infs. Applied only along any self.stat_dims in array.
- get_nanmin(var, *, _match=None)
minimum. min(var), ignoring NaNs AND infs. Applied only along any self.stat_dims in array.
- get_nanrms(var, *, _match=None)
root mean square. sqrt(mean(var**2)), ignoring NaNs AND infs.
Applied only along any self.stat_dims in array.
- get_nanstd(var, *, _match=None)
standard deviation. std(var), ignoring NaNs AND infs. Applied only along any self.stat_dims in array.
- get_ncpu()
returns ncpu, but if None, return multiprocessing.cpu_count() instead.
(This is for convenience; using None will also work with any methods defined here.)
- get_ne()
electron number density. (ne qe) + sum_i (ni qi) = 0. (using qe < 0 convention)
- get_negation(var, *, _match=None)
negation. -var.
- get_niefrac()
ion-to-electron density ratio. niefrac = ni / ne.
Result always corresponds to fluid=IONS, regardless of current self.fluid.
- get_nmean(var, *, _match=None)
mean of var, weighted by n. nmean = sum(var * n) / sum(n). n=self(‘n’).
Equivalent: ‘nmean_var’ <–> ‘weighted_n_mean_var’
- get_nq()
charge density. nq = (n * q) = (number density * charge)
- get_nstd(var, *, _match=None)
std of var, weighted by n. nstd = std(n*var)/mean(n), with n=self(‘n’).
- 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_nusn_from_drift(var, *, _match=None)
nusn, calculated by assuming u satisfies momentum equation to zeroth order.
There are various options for how to solve for nusn, as explained below (see {drift}).All solutions use nusn = sgyrof / skappa, where skappa is determined viaskappa = self(‘skappa’+var[len(‘nusn’):]).E.g. ‘nusn_from_means_momExB’ –> use skappa = self(‘skappa_from_means_momExB’).The description below helps explain the various options.‘nusn_from_{means_}{u_}{drift}’E.g. ‘nusn_from_means_momExB’, ‘nusn_from_hall’, ‘nusn_from_means_moment1_momB’{means_} = ‘means_’ or ‘’.if ‘means_’, take means of vars: ‘sgyrof’, any vars relevant to the chosen {drift} option.{u_} = ‘’ or any other var then ‘_’.if provided, use this var instead of ‘u’ for velocity. (Doesn’t affect “u_neutral” though.){drift} = ‘momExB’, ‘momE’, ‘hall’, or ‘pederson’indicates how to solve for nusn. Use the similarly-named var when getting skappa.‘momExB’ –> get skappa from the momentum equation in the E x B direction.‘momE’ –> get skappa from the momentum equation in the E direction.‘hall’ –> get skappa from u_hall = u, in the E x B direction.‘pederson’ –> get skappa from u_pederson = u, in the E direction.
- get_p()
momentum density. p = (u * r) = (velocity * mass density).
- get_parallel(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
A_par_B –> the component of A parallel to B.
Equivalent to self.take_parallel_to(B, A) == (A dot Bhat) Bhat.see also: A_dot_hat_B, which is equivalent to mod_(A_par_B)[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘E_par_B’, _E=E, _B=B) –> E par to B, using E and B which are already known.can alternatively provide _val0 for A and/or _val1 for B.
- get_parenthesis(var, *, _match=None, **kw)
parenthesis. ‘{prefix}({here}){suffix}’, with no parenthesis inside {here}.
Ensures that {here} is interpreted as a single expression. Useful when combining operations.E.g. ‘sqrt_q/m’, with no parenthesis, has an ambiguous interpretation.‘sqrt_(q/m)’ unambiguously refers to “sqrt(ratio between q and m)”.‘(sqrt_q)/m’ unambiguously refers to “ratio between sqrt(q) and m”.The no-parenthesis interpretation is subject to change without warning, in future code updates.(You can always check the interpretation that is being used, via self.match_var_tree(var))
- get_parmod(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
magnitude of the component of A parallel to B.
Equivalent to mod(A_par_B). Also equivalent to abs(A_dot_hat_B)[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘E_parmod_B’, _E=E, _B=B) –> |E par to B|, using E and B which are already known.can alternatively provide _val0 for A and/or _val1 for B.
- get_perp(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
A_perp_B –> A after removing the component of A parallel to B.
Equivalent to self.take_perp_to(B, A) == A - (A dot Bhat) Bhat.[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘E_perp_B’, _E=E, _B=B) –> E perp to B, using E and B which are already known.can alternatively provide _val0 for A and/or _val1 for B.
- get_perpmod(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
magnitude of A after removing the component of A parallel to B.
Equivalent to mod(A_perp_B).[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘E_perpmod_B’, _E=E, _B=B) –> |E perp to B|, using E and B which are already known.can alternatively provide _val0 for A and/or _val1 for B.
- get_pi()
pi. numpy.pi. 3.1415…
- get_plotter(name, who=UNSET)
gets the Plotter associated with this name and who.
Roughly equivalent: self.KNOWN_PLOTTERS[(name, who)]- name: str or Plotter
- name of the plotter to use, or a Plotter instance.
- who: UNSET, None, or str
- person associated with the plotter.UNSET –> use the plotter with this name; crash if found multiple same-named plotters.
see also: self.get_plotters(), which is good if you don’t know ‘who’, or want multiple plotters.
- get_plotters(who=UNSET, kind=UNSET, *, name=None, all_whos=UNSET, all_kinds=UNSET, skip_who=[], skip_kinds=[], min_cost=None, max_cost=None, sortby=None, returns='plotters')
return list of all plotters associated with these inputs.
If called with no inputs, just returns a copy of self.UNIQUE_PLOTTERS.- who: UNSET, None, str, or list.
- person associated with the plotter.UNSET –> include plotters regardless of ‘who’.None –> require len(plotter.who) == 0.str –> require this name to be in plotter.who.list –> require at least one of these to be in plotter.who(or, if None in list, allow len(plotter.who)==0, too)
- kind: UNSET, str, or list.
- kind associated with the plotter.UNSET –> include plotters regardless of ‘kind’.str –> require this kind to be in plotter.kinds.list –> require at least one of these to be in plotter.kinds.
- name: None or str
- plotter name. E.g. ‘deltafrac_n’.None –> include all plotters regardless of ‘name’.
- all_whos: UNSET or list.
- include only plotters with ALL of these people in plotter.who.
- all_kinds: UNSET or str.
- include only plotters with ALL of these kinds in plotter.kinds.
- skip_who: list
- exclude plotters with any of these people in plotter.who.
- skip_kinds: list
- exclude plotters with any of these kinds in plotter.kinds.
- min_cost: None or number
- exclude plotters with cost < min_cost.None –> no minimum.
- max_cost: None or number
- exclude plotters with cost > max_cost.None –> no maximum.
- sortby: None or ‘cost’
- tells how to sort the result (if returns==’plotters’).None –> keep in order they appear in self.UNIQUE_PLOTTERS.‘cost’ –> sort by plotter.cost values.
returns: ‘plotters’, ‘names’, ‘who’, ‘kind’, or ‘kinds’‘plotters’ –> returns list of plotters‘names’ –> returns set of all names associated with at least 1 plotter in result.‘who’ –> returns set of all people associated with at least 1 plotter in result.‘kind’ or ‘kinds’ –> returns set of all kinds associated with at least 1 plotter in result.
- get_plus(var, *, _match=None)
addition. var0 + var1.
- get_pmstd2werr(var, *, _match=None)
convert dataset with ‘mean+std’ and ‘mean-std’ into dataset with ‘mean’ and ‘std’.
pmstd2werr_var will crash if self(var) doesn’t have ‘mean+std’ and ‘mean-std’ data vars.
- get_power(var, *, _match=None)
power. var0 ** var1.
- get_prod(var, *, _match=None)
prod. prod(var). Applied only along any self.stat_dims in array.
- get_pwl2_var(var, *, _match=None)
get pwl2_flatend fit to var across self.snap, evaluated at self.snap.
(fail if self.snap is not a list of multiple snaps.)pwl2_flatend is a piecewise linear function with 2 pieces; final piece has slope=0.Equivalent: fitter=self(var).pc.pwl2_flatend_fitter(‘t’); fitter.fit(); fitter.eval()
- get_q()
charge, of a “single particle”. for protons, == +1 elementary charge.
[Not implemented for this class]
- get_r()
mass density. r = (n * m) = (number density * mass)
- get_rad2deg(var, *, _match=None)
convert radians to degrees. rad2deg_{A} –> A * 180 / pi.
self(‘rad2deg_var’) == np.rad2deg(self(‘var’))
- get_real(var, *, _match=None)
real part. np.real(self(var))
- get_rms(var, *, _match=None)
root mean square. sqrt(mean(var**2)). Applied only along any self.stat_dims in array.
- get_rmscomps(var, *, _match=None)
root mean squared of components.
E.g., rmscomps_{A} –> sqrt((Ax^2 + Ay^2 + Az^2) / 3), if A has 3 components.
- get_rosenberg_multi()
rosenberg criterion for multiple ions: rosenberg_multi = (nusn_multi / wplasma_multi)^2.
quasineutrality is “reasonable” (during farley-buneman analysis) iff rosenberg_multi << 1.This criterion should be more accurate than using rosenberg_qn for each ion, separately.(Below uses ‘…’ to denote “terms independent of wplasma_i and nu_in”.)Rosenberg 1998 equation 17, derived from equation 14, assumed only 1 ion.However, equation 14 comes from 13, where wplasma_i and nu_in only appear as (Ai/wplasma_i^2).where Ai = omega * (omega + i nu_in) + … (see equation 15).equation 13 looks like: … + (Ai/wplasma_i^2) = 0From equation 4 I infer the dispersion relation with multiple ions will be like:… + sum_i (Ai/wplasma_i^2) = 0.Expanding this sum reveals that it can be expressed in the same algebraic form as with 1 ion:… + Am/wplasma_m^2 = 0, when:wplasma_m^2 = 1 / (1/wplasma_1^2 + 1/wplasma_2^2 + …),Am = omega * (omega + i nu_mn) + …nu_mn = nu1 * weight1 + nu2 * weight2 + … / (weight1 + weight2 + …),where weightj = wplasma_1^2 * wplasma_2^2 * … / wplasma_j^2.Thus, the remaining steps done by Rosenberg to derive the criterion should apply in the same way,and for multiple ions we can conclude the criterion is (nu_mn / wplasma_m)^2 << 1.Okay, actually, in practice, it’s probably not useful to use this…it mostly just selects the least-dense ion, due to the 1/wplasma^2 scaling.Also, the criterion means “instability gets dampened when collisions are faster than plasma oscillations”But for multiple ions, it’s really more like, the instability for THAT ion gets dampened…(Also, I think one of the assumptions in the paper probably fails when wplasma is small…)
- get_rosenberg_multi_nusn()
collision frequency for rosenberg criterion with multiple ions.
nusn_multi = nu1 * weight1 + nu2 * weight2 + … / (weight1 + weight2 + …),where weightj = wplasma_1^2 * wplasma_2^2 * … / wplasma_j^2.see rosenberg_multi for details.
- get_rosenberg_multi_wplasma()
plasma frequency for rosenberg criterion with multiple ions.
wplasma_multi^2 = 1 / (1 / wplasma1^2 + 1 / wplasma2^2 + …),with sum across all ions in self(‘wplasma’, fluids=None)see rosenberg_multi for details.
- get_rosenberg_n()
n such that rosenberg_qn == 1, for each fluid.
Equivalent: rosenberg_qn * n.To satisfy Rosenberg criterion, need rosenberg_qn << 1.rosenberg_qn = (nusn / wplasma)^2 = nusn^2 * m * eps0 / (n * q^2),which is proportional to 1 / n–> n is “good” if n >> rosenberg_n.- Note: this also happens to be the solution to lmfp == ldebye…
- lmfp = (vtherm/nusn) = ((kB T / m)^0.5 / nusn) == (epsilon0 kB T / (n q^2))^0.5 = ldebye–> (nusn^-2 m^-1) == (epsilon0 n^-1 q^-2)–> n == epsilon0 nusn^2 m / q^2.
- get_rosenberg_n_margin()
n / rosenberg_n. margin of safety for rosenberg criterion. “safe” if margin is large.
- get_rosenberg_qn()
Rosenberg criterion for quasineutrality, for each fluid: rosenberg_qn = (nusn / wplasma)^2.
quasineutrality is “reasonable” (during farley-buneman analysis) iff rosenberg_qn << 1 for ions.(Intuitively: quasineutrality reasonable iff ‘collisions much slower than plasma oscillations’)If multiple ions, consider using self(‘rosenberg_multi’) instead of one criterion per ion.see Rosenberg 1998, equation 17, for details.
- get_safe_pow2_subcycle(*, subcycle_safety=UNSET)
largest “safe” power of 2 subcycling allowed for each fluid in self.fluid.
result = array of values like 2^N, with largest N such that result < best_subcycle / safety.(larger safety produces “safer” results. For safe_subcycle, just use best_subcycle / safety.)
- get_sci_number(var, *, _match=None)
any number in scientific notation, as an xarray.
- 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_sgyrof()
signed gyrofrequency. sgyrof == q |B| / m == charge * |B| / mass. Negative when charge < 0.
- get_skappa()
signed kappa (magnetization parameter). skappa = sgyrof / nusn. Negative when charge < 0.
skappa = gyrofrequency / collision frequency of self.fluid with neutrals.gyrofrequency == q * |B| / (mass * nusn).
- get_skappa_from_hall(var, *, _match=None)
signed kappa (magnetization parameter) that statisfies u_hall = u, in the E x B direction.
‘skappa_from_{means_}{u_}hall’E.g. ‘skappa_from_means_hall’, ‘skappa_from_hall’, ‘skappa_from_means_moment1_hall’{means_} = ‘means_’ or ‘’.if ‘means_’, take means of vars: ‘u’, ‘u_neutral’, ‘mod_B’, ‘E_cross_B’{u_} = ‘’ or any other var then ‘_’.if provided, use this var instead of ‘u’ for velocity. (Doesn’t affect “u_neutral” though.)E.g. eppic calculator might use ‘moment1’ here, as in ‘skappa_from_moment1_hall’.Algebraic solution:formula for u_hall (from solving momentum equation for u in the E x B direction):u_hall = (kappa**2 / (1 + kappa**2)) * (E x B) / |B|**2solving for kappa**2, assuming u instead of u_hall, yields:(u dot (E x B)) == (kappa**2 / (1 + kappa**2)) * (|E x B|**2 / |B|**2)A + A * kappa**2 - kappa**2 == 0, where A = (u dot (E x B)) / (|E x B|**2 / |B|**2)kappa**2 = A / (1 - A)–> skappa = +- sqrt(A / (1 - A)),There are two solutions; return solution with the same sign as self(‘q’) (i.e. fluid’s charge)
- get_skappa_from_momE(var, *, _match=None)
signed kappa (magnetization parameter) that statisfies momentum equation in the E direction.
‘skappa_from_{means_}{u_}momE’E.g. ‘skappa_from_means_momE’, ‘skappa_from_momE’, ‘skappa_from_means_moment1_momE’{means_} = ‘means_’ or ‘’.if ‘means_’, take means of vars: ‘u’, ‘u_neutral’, ‘mod_E’, ‘mod_B’, ‘E’, ‘E_cross_B’{u_} = ‘’ or any other var then ‘_’.if provided, use this var instead of ‘u’ for velocity. (Doesn’t affect “u_neutral” though.)E.g. eppic calculator might use ‘moment1’ here, as in ‘skappa_from_moment1_momE’.Algebraic solution:momentum equation, rearranged using skappa = q * |B| / (m * nusn):0 = q (E + u x B) - m * nusn * (u - u_neutral)0 = skappa (E + u x B) - |B| (u - u_neutral)dotting with E:0 = skappa (|E|^2 + (u x B) dot E) - |B| (u - u_neutral) dot E # note uxB.E == BxE.u == -ExB.u–> skappa = |B| (u - u_neutral) dot E / (|E|^2 - u dot (E x B))Note: results untrustworthy when kappa >> 1, since that involves dividing by a value close to 0.
- get_skappa_from_momExB(var, *, _match=None)
signed kappa (magnetization parameter) that statisfies momentum equation in the E x B direction.
‘skappa_from_{means_}{u_}momExB’E.g. ‘skappa_from_means_momExB’, ‘skappa_from_momExB’, ‘skappa_from_means_moment1_momExB’{means_} = ‘means_’ or ‘’.if ‘means_’, take means of vars: ‘u’, ‘u_neutral’, ‘mod_B’, ‘E_cross_B’, ‘u_cross_B’{u_} = ‘’ or any other var then ‘_’.if provided, use this var instead of ‘u’ for velocity. (Doesn’t affect “u_neutral” though.)E.g. eppic calculator might use ‘moment1’ here, as in ‘skappa_from_moment1_momExB’.Algebraic solution:momentum equation, rearranged using skappa = q * |B| / (m * nusn):0 = q (E + u x B) - m * nusn * (u - u_neutral)0 = skappa (E + u x B) - |B| (u - u_neutral)dotting with E x B:0 = skappa [(u x B) dot (E x B)] - |B| [(u - u_neutral) dot (E x B)]–> skappa = |B| [(u - u_neutral) dot (E x B)] / [(u x B) dot (E x B)]
- get_skappa_from_pederson(var, *, _match=None)
signed kappa (magnetization parameter) that statisfies u_pederson = u, in the E direction.
‘skappa_from_{means_}{u_}pederson’E.g. ‘skappa_from_means_pederson’, ‘skappa_from_pederson’, ‘skappa_from_means_moment1_pederson’{means_} = ‘means_’ or ‘’.if ‘means_’, take means of vars: ‘u’, ‘u_neutral’, ‘mod_B’, ‘E’, ‘mod_E’,{u_} = ‘’ or any other var then ‘_’.if provided, use this var instead of ‘u’ for velocity. (Doesn’t affect “u_neutral” though.)E.g. eppic calculator might use ‘moment1’ here, as in ‘skappa_from_moment1_pederson’.Algebraic solution:formula for u_pederson (from solving momentum equation for u in the E direction):u_pederson = (skappa / (1 + skappa**2)) * E / |B|solving for skappa, assuming u instead of u_pederson, yields:(u dot E) == (skappa / (1 + skappa**2)) * (|E|**2 / |B|)A + A * skappa**2 - skappa == 0, where A = (u dot E) / (|E|**2 / |B|)skappa = (1 +- sqrt((-1)^2 - 4 * A * A)) / (2 * A),There are two solutions; the correct choice can be determined by using the momentum equation;the correct choice for the +- sign turns out to be: -sign(q) where q = self(‘q’) == fluid’s charge.Note: results untrustworthy when kappa >> 1, since that involves dividing by a value close to 0.
- get_slopet(var, *, _match=None)
slope calculated from linear regression along ‘t’ coord.
self(‘slopet_var’) == self(‘linregt_var)[‘polyfit_coefficients’].sel(degree=1).drop_vars(‘degree’)behavior affected by self.polyfit_kw; see help(type(self).polyfit_kw) for details.
- get_sparmod(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
signed “magnitude” of the component of A parallel to B.
Equivalent to A_dot_hat_B. Also abs(A_sparmod_B) is equivalent to mod(A_par_B).[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘E_parmod_B’, _E=E, _B=B) –> |E par to B|, using E and B which are already known.can alternatively provide _val0 for A and/or _val1 for B.
- get_sqrt(var, *, _match=None)
square root. sqrt(var)
- get_stats(var, *, _match=None)
return dataset of stats for var
stats include: mean, std, min, max, median, rms.Applied only along any self.stat_dims in array.Incompatible with Dataset vars.Consider also: self(‘astats_var’), self(‘var’).pc.stats()
- get_std(var, *, _match=None)
standard deviation. std(var). Applied only along any self.stat_dims in array.
- get_sum(var, *, _match=None)
sum. sum(var). Applied only along any self.stat_dims in array.
- get_surelin_var(var, *, _match=None)
values of var between (inclusive) t_surelin_min and t_surelin. Mask all other values.
[TODO][EFF] wasted time computing values which will later be masked…
- get_sureturb_var(var, *, _match=None)
values of var at or after t_sureturb. Mask all values before t_sureturb.
[TODO][EFF] wasted time computing values which will later be masked…
- get_t_surelin()
time before which, values are definitely in the linear regime.
self(‘t_turb’) * self.surelin_quantile.
- get_t_surelin_min()
start time of “definitely linear regime”.
self(‘t_turb’) * self.surelin_min_quantile.
- get_t_sureturb()
time, after which, values are definitely in the turbulent regime.
Currently, just returns self(‘t_turb’).Eventually might implement some safety factor since t_turb might not be exact.
- get_t_turb()
time of turbulent onset. Equal to self.t_turb if set; Crash if not set.
(here always converts result to DataArray if not DataArray already.)
- get_t_turb_from_pwl2_var(var, *, _match=None)
t_turb from pwl2_flatend fit to var. Might want to do self.t_turb = result.
result depends on self.blur_sigma.Equivalent: fitter=self(‘var’).pc.pwl2_flatend_fitter(‘t’); fitter.fit(); fitter.get_xsat()Suggestion: t_turb_from_pwl2_ln_std_blur_deltafrac_n
- get_tfbi_EBspeed_grid()
return a 1D grid of EBspeed values with constant logstep.
determines logmin, logmax, logstep (base 10) from self.tfbi_EBspeed_grid_size.result’s name & EBspeed grid dim is always ‘EBspeed’.
- get_tfbi_EBspeed_thresh()
threshold EBspeed for TFBI to grow. NaN if no growth predicted across the EBspeed grid considered.
Assumes user has already run self.solve_tfbi_vs_EBspeed().
If not, consider doing:copied = self.copy()copied.set_attrs(maindims_means=True, snap=0) # or some other way to downsample…copied.solve_tfbi_vs_EBspeed()equivalent to tfbi_vs_EBspeed.pc.min_coord_where(‘EBspeed’, tfbi_vs_EBspeed.it.growth_kmax()>0)
- get_tfbi_E_thresh()
threshold E_un0_perpmag_B for TFBI to grow. NaN if no growth predicted across the EBspeed grid considered.
Equivalent: self(‘tfbi_EBspeed_thresh’) * self(‘mod_B’).Assumes user has already run self.solve_tfbi_vs_EBspeed().See self.help(‘tfbi_EBspeed_thresh’) for more details.
- get_tfbi_all(**kw_get_vars)
returns xarray.Dataset of values relevant to TFBI theory.
This includes tfbi_inputs (required for theory) and tfbi_extras (optional)Results depend on self.fluid. May want to call as self(‘tfbi_all’, fluid=CHARGED).
- get_tfbi_extras(**kw_get_vars)
returns xarray.Dataset of values relevant to TFBI theory but not necessary for inputs.
Currently this just includes:‘eqperp_lmfp’: each fluid’s collisional mean free path at its “equilibrium” temperature,after considering zeroth order heating due to E_un0_perpmag_B.‘SF_n’: sum of number densities of all species (including neutrals)‘n’: number densities of each specie in self.fluid.‘n_n’: number density of neutral fluid.‘n*kappa’: number density times kappa.TFBI dispersion relation terms scale with n*kappa for each fluid,so this quantity roughly estimates the relative importance of each fluid.Results depend on self.fluid. May want to call as self(‘tfbi_extras’, fluid=CHARGED).
- get_tfbi_fscale()
tfbi_fscale = n * kappa
tfbi dispersion relation sums terms proportional to n * kappa, for each fluid.
- get_tfbi_fscale_rel()
tfbi_fscale_rel = tfbi_fscale(this fluid) / tfbi_fscale(electrons).
- get_tfbi_inputs(**kw_get_vars)
returns xarray.Dataset of values to input to the tfbi theory.
“global” scalars (no dependence on component nor fluid)‘mod_B’: |magnetic field|‘E_un0_perpmag_B’: |E_un0 perp to B|. E_un0 = electric field in u_neutral=0 frame.‘kB’: boltzmann constant. kB * T = temperature in energy units.‘T_n’: temperature of neutrals.‘m_n’: mass of neutrals.scalars which depend on fluid. Note: checks self.fluid, not self.fluids.‘m’: mass of all non-neutral fluids‘nusn’: collision frequency between fluid and neutrals.‘skappa’: signed magnetization parameter; q |B| / (m nusn)‘eqperp_ldebye’: each fluid’s debye length at its “equilibrium” temperature,after considering zeroth order heating due to E_un0_perpmag_B.Results depend on self.fluid. May want to call as self(‘tfbi_inputs’, fluid=CHARGED).
- get_tfbi_omega(*, kw_tfbi_solve={}, **kw_tfbi_solver)
Thermal Farley Buneman Instability roots with largest imaginary part at each point in self.
Equivalent: self.tfbi_solver(**kw_tfbi_solver).solve(**kw_solve)[‘omega’].Can provide kwargs, e.g. self(‘tfbi_omega’, ions=[‘H_II’, ‘C_II’], kw_tfbi_solve=dict(ncpu=1)).For more control, use self.tfbi_solver() directly.For even more control, use the pattern described in help(self.tfbi_solver_cls).- Recommended: consider using ‘tfbi_omega_ds’ instead of ‘tfbi_omega’.
- ‘tfbi_omega_ds’ gives the full Dataset of all values relevant to the solution.‘tfbi_omega’ just gives the DataArray of omega, which is harder to inspect later.
- get_tfbi_omega_ds(*, kw_tfbi_solve={}, **kw_tfbi_solver)
Thermal Farley Buneman Instability solution at each point in self.
Equivalent: self.tfbi_solver(**kw_tfbi_solver).solve(**kw_solve).Can provide kwargs, e.g. self(‘tfbi_omega_ds’, ions=[‘H_II’, ‘C_II’], kw_tfbi_solve=dict(ncpu=1)).For more control, use self.tfbi_solver() directly.For even more control, use the pattern described in help(self.tfbi_solver_cls).
- get_tfbi_vs_EBspeed()
return tfbi solution across EBspeed grid. Load saved result if it exists, else save result to file.
CAUTION: the implementation here might self.set(‘E_un0_perpmod_B’, self(‘mod_B’) * EBspeed)
[TODO] avoid changing self.setvars… (or, at least, restore previous self.setvars afterwards.)- CAUTION: the implementation here assumes self.tfbi_EBspeed_grid_size is enough to uniquely specify the result;
- e.g. if there is a different result at each snapshot of self, that will not be understood here.
Equivalent: self.solve_tfbi_vs_EBspeed(cache=’caches’)
- get_times(var, *, _match=None)
multiplication. var0 * var1.
- get_timescale_EBdrift()
timescale from drift speed if possible, else from speed using E & B fields.
tries to return self(‘timescale_udrift’), but if that causes a QuantCalcError,use self(‘timescale_EBspeed’) instead.
- get_timescale_EBspeed()
timescale from speed using E & B fields. dsmin / (|E_un0 cross B| / |B|^2).
E_un0 (not E) because the derivation assumes neutral frame: u_neutral=0.note: to be more precise, use timescale_udrift instead.
- get_timescale_eqperp_vtherm()
timescale from thermal velocity, using T_from_Eheat_perp instead of T.
dsmin / eqperp_vtherm.
- get_timescale_gyrof()
timescale for cyclotron motion. 2 * pi / gyrof. (Hz, not rad/s)
gyrof = |q| |B| / m.
- get_timescale_nusn()
timescale for collisions with neutrals. 1 / nusn.
nusn = collision frequency of self.fluid with neutrals.
- get_timescale_udrift()
timescale from drift speed. dsmin / mod_u_drift.
note: to be less precise (but computationally cheaper), use timescale_EBspeed instead.
For electrons when kappae >> 1, timescale_EBspeed ~= timescale_udrift.When accounting for directionality, or kappae <~= 1, or non-electrons,timescale_EBspeed is always more conservative (i.e. smaller) than timescale_udrift.
- get_timescale_vtherm()
timescale from thermal velocity. dsmin / vthermal.
vthermal = sqrt(kB T / m).
- get_timescale_wplasma()
timescale from plasma oscillations. 2 * pi / wplasma. (Hz, not rad/s)
wplasma = sqrt(n q^2 / (m epsilon0)).
- get_timescales()
all timescales (from self.TIMESCALE_VARS) as a dataset.
Consider also: self(‘timescales_abbrv’)Useful patterns you might want to consider:self(‘timescales’, maindims_means=True) # timescales based on mean values onlyself(‘timescales’).min(‘fluid’) # minimum timescales across all fluidsself(‘timescales’).pc.minimum() # minimum timescale across all timescalesequivalent: self(‘min_timescale’)self(‘timescales’).min(‘fluid’).pc.minimum() # minimum timescale at each point.self(‘timescales’).pc.varmin() # name of timescale with minimum value at each point.# timescale variable names, sorted from min to max values.self(‘timescales’).to_dataarray().pc.sort_along(‘variable’)[‘variable’]
- get_timescales_abbrv()
all timescales (from self.TIMESCALE_VARS) as a dataset, abbreviating names.
abbreviates ‘timescale_var’ –> ‘var’.
- get_tturb_var(var, *, _match=None)
values of var at or after t_turb. Mask all values before t_turb.
[TODO][EFF] wasted time computing values which will later be masked…
- get_tturbvar00()
var used for t_turb ‘00’ standard: caches_ln_std_blur_deltafrac_n,
with fluid=electron, snap=None, blur_sigma=10.
- get_turblindiff_var(var, *, _match=None)
meant_sureturb_var - meant_surelin_var.
i.e., (time-averaged value in turbulent regime) minus (time-averaged value in linear regime).see also: werrturblindiff_var
- get_turblindiffwerr_var(var, *, _match=None)
werrmeant_sureturb_var - werrmeant_surelin_var.
i.e., (time-averaged value in turbulent regime) minus (time-averaged value in linear regime),but result is a Dataset with ‘mean’ and ‘std’ data_vars,with ‘std’ coming from “standard” error propagation formula assuming independent errors:std(A - B) = sqrt(std(A)**2 + std(B)**2).see also: turblindiff_var
- get_turblindivwerr_var(var, *, _match=None)
werrmeant_sureturb_var / werrmeant_surelin_var.
i.e., (time-averaged value in turbulent regime) divided by (time-averaged value in linear regime),but result is a Dataset with ‘mean’ and ‘std’ data_vars,with ‘std’ coming from “standard” error propagation formula assuming independent errors.
- get_u()
velocity. vector quantity (result depends on self.component)
[Not implemented for this class]
- get_u_EdotB(*, _E=None, _B=None)
EdotB drift velocity. u_EdotB = (skappa**3 / (1 + skappa**2)) * (E_un0 dot B) B / |B|^3
(Commonly neglected, but comes from the same physical equation as hall & pederson drifts;from solving equilibrium momentum equation for u, when neglecting all derivatives.)[EFF] for efficiency, can provide E and/or B, if already known.
- get_u_drift()
equilibrium velocity; solution to the momentum equation with collisions,
assuming zero acceleration and zero spatial gradients.u_drift = u_hall + u_pederson + u_EdotB.
- get_u_hall(*, _E=None, _B=None)
Hall drift velocity. u_hall = (kappa**2 / (1 + kappa**2)) * (E_un0 x B) / |B|**2,
where kappa is the magnetization parameter, kappa = gyrof / nusn.[EFF] for efficiency, can provide E and/or B, if already known.
- 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_u_pederson(*, _E=None, _B=None)
Pederson drift velocity. u_pederson = (skappa / (1 + skappa**2)) * E_un0 / |B|,
where skappa is the (signed) magnetization parameter, skappa = q * |B| / (m * nusn).[EFF] for efficiency, can provide E and/or B, if already known.
- get_unwrapt_2pi_var(var, *, _match=None)
unwrapt_{A} –> unwrapped self(A) along ‘t’, via np.unwrap with period=2*pi.
- CAUTION: result at a given snapshot can vary depending on self.snap,
- (though, (result % 2*pi) will always be the same.)
E.g. self(‘unwrapt_angle_xy_E’) –> angle between +xhat and E, but unwrapped,so e.g. if results change from just above -pi to just below -pi,the values below -pi will actually be below -pi,instead of being reported as 2*pi + (value just below -pi).
- get_upar()
velocity vector, parallel to B. This is a full 3-vector.
Equivalent: self(‘u_par_B’) == (u dot Bhat) Bhat
- get_uperp()
velocity vector, perpendicular to B. This is a full 3-vector.
Equivalent: self(‘u_perp_B’) == u - self(‘u_par_B’) == u - (u dot Bhat) Bhat
- get_valfven()
Alfven speed. valfven = |B| / sqrt(mu0 * r)
- get_valfven2()
Alfven speed squared. valfven2 = |B|^2 / (mu0 * r)
- get_var_at_max_of_ref(var, *, _match=None)
var_at_max_of_ref –> self(var) at argmax of self(ref),
taking argmax across all dims in self(ref).For more precise control, consider directly using xarray_at_max_of.
- get_var_at_min_of_ref(var, *, _match=None)
var_at_min_of_ref –> self(var) at argmin of self(ref),
taking argmin across all dims in self(ref).For more precise control, consider directly using xarray_at_min_of.
- get_var_where_condition(var, *, _match=None)
var_where_condition –> self(var).where(self(condition)).
for ‘drop’ kwarg, in where(…, drop=…), use drop=self.drop.
- 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 strs
- Names 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.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(…).
- get_vector_N(var, *, _match=None)
vector_n –> vector with n in each component. E.g. vector_0 –> vector with components (0,0,0).
result components determined by self.component.
- get_vtherm()
thermal velocity. vtherm = sqrt(kB T / m)
- get_vtherm_n()
thermal velocity for neutrals. vtherm_n = sqrt(kB T_n / m_n)
- get_weighted_mean(weights_var, *, _match=None)
mean, weighted by weights. mean(weights*var)/mean(weights).
E.g. ‘weighted_n_mean_T’ –> mean(n * T) / mean(n).(see also: ‘nmean_[var]’, which is a shorthand for ‘weighted_n_mean_[var]’)Applied only along any self.stat_dims in array.
- get_weighted_std(weights_var, *, _match=None)
std, weighted by weights. std(weights*var)/mean(weights).
E.g. ‘weighted_n_std_mod_u’ –> std(n * mod_u) / mean(n).(see also: ‘nstd_[var]’, which is a shorthand for ‘weighted_n_std_[var]’)Applied only along any self.stat_dims in array.Currently, equivalent to self(‘(std_({weights}*{var}))/mean(weights)’)[TODO][EFF] internally, don’t compute weights twice…
- get_werr2pmstd(var, *, _match=None)
convert dataset with ‘mean’ and ‘std’ into dataset with ‘mean+std’, ‘mean’, ‘mean-std’.
werr2pmstd_var will crash if self(var) doesn’t have ‘mean’ and ‘std’ data vars.
- get_werradd(var, *, _match=None)
A_werradd_B = A + B, but result is a dataset with ‘mean’ and ‘std’.
Does not take any means or stds here, but if A or B has ‘std’ already,assumes independent errors and applies “error propagation” formula:mean(A + B) = mean(A) + mean(B)std(A + B) = sqrt(std(A)**2 + std(B)**2)(if A or B is DataArray, treat as ‘mean’. if missing ‘std’, assume 0.)
- get_werrdiv(var, *, _match=None)
A_werrdiv_B = A / B, but result is a dataset with ‘mean’ and ‘std’.
Does not take any means or stds here, but if A or B has ‘std’ already,assumes independent errors and applies “error propagation” formula:z = A / Bmean(z) = mean(A) / mean(B)std(z) = abs(mean(z)) * sqrt((std(A)/mean(A))**2 + (std(B)/mean(B))**2)(if A or B is DataArray, treat as ‘mean’. if missing ‘std’, assume 0.)
- get_werrmean(var, *, _match=None)
dataset of ‘mean’ and ‘std’ of var. Computed along self.stat_dims in array.
- get_werrmeant(var, *, _match=None)
dataset of ‘mean’ and ‘std’ of var, taking stats across time dimension.
self(werrmeant_var) –> self(var).werrmean(tdim), where tdim is the dim associated with time,(tdim default ‘snap’, but if ‘t’ coord associated with a dim, use that dim.)
- get_werrmul(var, *, _match=None)
A_werrmul_B = A * B, but result is a dataset with ‘mean’ and ‘std’.
Does not take any means or stds here, but if A or B has ‘std’ already,assumes independent errors and applies “error propagation” formula:z = A * Bmean(z) = mean(A) * mean(B)std(z) = abs(mean(z)) * sqrt((std(A)/mean(A))**2 + (std(B)/mean(B))**2)(if A or B is DataArray, treat as ‘mean’. if missing ‘std’, assume 0.)
- get_werrsub(var, *, _match=None)
A_werrsub_B = A - B, but result is a dataset with ‘mean’ and ‘std’.
Does not take any means or stds here, but if A or B has ‘std’ already,assumes independent errors and applies “error propagation” formula:mean(A - B) = mean(A) - mean(B)std(A - B) = sqrt(std(A)**2 + std(B)**2)(if A or B is DataArray, treat as ‘mean’. if missing ‘std’, assume 0.)
- get_where_condition_var(var, *, _match=None)
where_condition_var –> self(var).where(self(condition)).
- Note: if var contains any underscores, must use parenthesis (like ‘where_condition_(var)’).
- The alias, self(‘var_where_condition’), does not have such a restriction.
for ‘drop’ kwarg, in where(…, drop=…), use drop=self.drop_in_where.
- get_wplasma()
“plasma frequency”. wplasma = sqrt(n q^2 / (m epsilon0))
This is analogous to the “true” plasma frequency of Langmuir oscillations,which is calculated using the same formula but applied to electrons.wplasma is equivalent to wplasmae if self.fluid is electrons.
- get_wplasmae()
electron plasma frequency; Langmuir oscillations. wpe = sqrt(ne qe^2 / (me epsilon0))
- get_xhat()
unit vector in the x direction.
result components determined by self.component, e.g. xhat_x == 1; xhat_y == 0.
- get_xyz(var, *, _match=None)
x, y, and/or z components of var.
- get_yhat()
unit vector in the y direction.
result components determined by self.component, e.g. yhat_x == 0; yhat_y == 1.
- get_zhat()
unit vector in the z direction.
result components determined by self.component, e.g. zhat_x == 0; zhat_z == 1.
- 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 str
- If 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 bool
- How 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: bool
- Whether to include modules in result.If True, result will be grouped into sections with modules written at top.
- signature: signature: bool
- whether to include line with signature in help string.e.g. “help_str(f, *, module=True, signature=True, indent=None)”
- doc: doc: bool
- whether to include lines with docstring in help string.e.g. “return str for help(f).” … and all the other docs in here.
- dense: bool
- Whether 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 str
- If 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 bool
- How 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: bool
- Whether to include modules in result.If True, result will be grouped into sections with modules written at top.
- signature: signature: bool
- whether to include line with signature in help string.e.g. “help_str(f, *, module=True, signature=True, indent=None)”
- doc: doc: bool
- whether to include lines with docstring in help string.e.g. “return str for help(f).” … and all the other docs in here.
- dense: bool
- Whether to reduce whitespace in result.E.g. True –> no newlines between functions. False –> one newline between functions.
- _instance: None or QuantityLoader instance
- if 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 ifft
alias to ifftN
- ifftN(array, dim=UNSET, df=None, *, x0=0, ds=None, **kw_xarray_ifftN)
xarray_ifftN with defaults for dim determined by self.fft_dims.
kwargs are passed to xarray_ifftN. For convenience, docs for xarray_ifftN are copied below.xarray_ifftN docs—————–calculates ifft(array) along N dimensions.shifts positions such that the 0-position is in the center.replaces result dimensions & coordinates appropriately, to indicate which dims were ifft’d.For convenience, all coordinate names can be pre-fft OR post-fft names,e.g. ‘x’, ‘freq_x’, ‘freqrad_x’, or ‘k_x’.“post-fft” names look like ‘freq_dim’, ‘freqrad_dim’,or any value in DEFAULTS.FFT_FREQ_RAD_DIMNAMES.values(), e.g. ‘k_x’.- Caution: ifft(fft(arr)) == arr only approximately, due to floating point rounding errors.
- Can at least ensure coordinate alignment by providing ds during ifft(fft(arr), ds=…)
- dim: None, str, or iterable of strs
- coordinates(s) of array to take ifft over.promote_dim(array, coord) for any non-dimension coordinates, as needed.None –> equivalent to array.dims
- df: None, number, or dict of {dim: d}
- spacing between elements of array (in frequency-space).None –> infer from ds if provided, else infer from array.number –> use this as df for all dims.
- rad: None or bool
- if True, interpret frequency-spacing (df) like it is “in radians”,dividing it by 2 * pi before converting to position-space.None –> infer rad from names of the dims being ifft’d.
- ds: None, number, or dict of {dim: d}
- spacing between elements of result (in position-space), along dims from result.number –> use this as ds for all dims.None –> infer from df if provided, else infer from array.Note: provide ds to guarantee ifft(fft(arr)) == arr, exactly;otherwise position coords might include small rounding errors.
- x0: None, number, or dict of {dim: value}
- if provided, alter position-space coordinates by adding a constant offset,such that the 0’th position for each dim equals x0[dim].number –> apply the same number to all dims.iterable –> use these numbers; kwarg
dimmust also be provided as an iterable of strs.dict –> dict of {dim: x0} specifying the value associated with each dim
- ifft_dims_for(array)
return dims over which to apply ifft for this array.
This is the self.fft_dims which correspond to dims in array.dims,though not via exact match.E.g. ‘freq_x’ or ‘k_x’ in array.dims, if ‘x’ in fft_dims.
- property iter_component
alias to self.component_dim.iter
- property iter_components
alias to self.component_dim.iter_values
- property iter_components_partition
alias to self.component_dim.iter_partition
- iter_dimpoints(dims=None, *, all=False, restore=True, enumerate=False)
iterate through values of dims, returning DimPoints and setting dim values during iteration.
DimPoints are dicts of {dim: value} for dim in dims, where not is_iterable_dim(value).Also, during iteration, set self.{dim} = value, as with self.iter_dim.- dims: None or iterable of strs appearing in self.dimensions.keys()
- dimensions to consider. None –> use all dimensions.
- all: bool
- whether to iterate through all possible values, or only the current values.False –> iterate through current values (e.g., self.snap, self.fluid, …).similar to itertools.product(self.iter_snap(), self.iter_fluid(), …)True –> iterate through all possible values (e.g., self.snaps, self.fluid, …)similar to itertools.product(self.iter_snaps(), self.iter_fluids(), …)Equivalent to all=False if all dims are set to None, e.g. self.snap=None, …
- restore: bool
- whether to restore original dim values after iteration.
- enumerate: bool, default False
- whether to yield indices too, i.e. (idx, DimPoint) instead of just DimPoint.idx would be a dict of {dim: i} such that DimPoint values are {dim: dims[i] for dim,i in idx.items()}.
- property join_components
alias to self.component_dim.join_along
- 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_across_dims(loader, *args_loader, dims=[], assign_coords=None, loader0=None, _shift_special={}, **kw_loader)
return loader(…), iterating & joining across each dimension.
- loader: callable of (*args_loader, **kw_loader) -> xarray.DataArray.
- will call loader to get result values at each combination of dims values in self.(loader will probably depend on dims values from self.)
- dims: iterable of strs or Dimension objects
- load across these Dimensions.loads across the current values (when this method was called) of each dimension,not necessarily “all” values. (e.g., self.snap, not self.snaps)str values –> use self.dimensions[d] (where d is a str in dims).len(dims)==0 –> just return loader(var, *args_loader, **kw_loader).While loading, set dim.loading=True for each dim.
- assign_coords: None or bool, default None
- whether to dim.assign_coord for each result of loader, for each dimension.None –> assign coord only if dim.name not already in array.coords.
- loader0: None or callable
- if provided, use loader0 to get the first array, then use loader for the rest.Internally the first array’s .coords and .attrs are used to label the result;however all other arrays do not need to be converted to xarray.
- _shift_special: UNSET or dict of (dimstr: list of special values)
- workaround to encourage loader0 to be called on a “usual” case, not a special case.if provided, and dimstr in dims, and d=self.dimensions[dimstr] has multiple values,with special_value first, and at least one non-special value later, theninternally rearrange dim values order before loading,then rearrange result back to original order (via indexing).E.g. _shift_special=dict(snap=[INPUT_SNAP]) –> apply loader0 to the first non-INPUT_SNAP,if there are any non-INPUT_SNAP snap values in snap, and ‘snap’ in dims.
— MULTIPROCESSING STRATEGY OPTIONS (from self) —- timeout: None or int
- max duration, in seconds. Must be None or integer (due to limitations of signal.alarm method)None –> no time limit.Note: if time_limit is reached, will raise a TimeoutError and save the result so far.(in this case, any not-yet-calculated values will each be RESULT_MISSING.)# [TODO] make this happen, without making self un-picklable:in case of crash, results so far can be found in self._latest_load_tasks.Then possibly continued via:results = self._latest_load_tasks(…, reset=False, skip_done=True)result = self._load_across_dims_postprocess(results, dims, …)# [TODO] if crashing and resuming is common, make that easier to do^elf.timeout has not been set, use DEFAULTS.LOADING_TIMEOUT (default: None).
- ncpu: None or int
- max number of cpus to use for multiprocessing.None –> use multiprocessing.cpu_count()int –> use this value. if 0 or 1, do not use multiprocessing here.Note: will actually use min(ncpu, number of calls to be made);e.g. if ncpu=4 but len(arg_kw_tuples)=2, will only use 2 cpus.elf.ncpu has not been set, use DEFAULTS.LOADING_NCPU (default: 1).
- ncoarse: int
- if >1, group tasks into groups of size ncoarse before performing them.elf.ncoarse has not been set, use DEFAULTS.LOADING_NCOARSE (default: 1).
- print_freq: None, or number (possibly negative or 0)
- >0 –> Minimum number of seconds between progress updates.=0 –> print every progress update.<0 –> never print progress updates.None –> use DEFAULTS.PROGRESS_UPDATES_PRINT_FREQelf.print_freq has not been set, infer from self.verbose if it exists,use DEFAULTS.PROGRESS_UPDATES_PRINT_FREQ (default: 2).
additional args & kwargs are passed as loader(*args_loader, **kw_loader).
- load_across_dims_implied_by(var, loader, *args_loader, assign_coords=None, _min_split=1, **kw_loader)
return loader(…), iterating & joining across each dimension implied by var.
Equivalent to self.load_across_dims(loader, …, dims=self.match_var_loading_dims(var)).- var: str
- variable which implies dims to load across, via self.match_var_loading_dims(var).
- loader: callable of (*args_loader, **kw_loader) -> xarray.DataArray.
- will call loader to get result values at each combination of dims values in self.(loader will probably depend on dims values from self.)
- assign_coords: None or bool, default None
- whether to dim.assign_coord for each result of loader, for each dimension.None –> assign coord only if dim.name not already in array.coords.
- _min_split: int, default 1
- if an implied dim has current_n() < min_split, don’t load across it.1 –> no minimum.
additional args & kwargs are passed as loader(*args_loader, **kw_loader).
- load_direct(var, *args, **kw)
load var “directly”, from some source which is not known by the main part of PlasmaCalcs.
Attempt the following, returning the first successful attempt:- return self.direct_overrides[var](self, *args, **kw).- return self.direct_overrides_dynamic()[var](self, *args, **kw).- use self.load_fromfile.return the result (probably a numpy array, but not guaranteed).Examples:load Bx directly from a fileload n for H+, using a different module which somehow gives nH+(PlasmaCalcs doesn’t need to know where the value came from.)if used an override, instead of loading from file,set self._load_direct_used_override = var.Otherwise, set it to None.This might be used, e.g., to determine if the output came directly from a file or not.
- 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.
- lowpass(array, dim=UNSET, keep=UNSET, *, keep_r=UNSET, **kw_xarray_lowpass)
xarray_lowpass with defaults for dim & keep determined by self.fft_dims, self.lowpass_keep.
kwargs are passed to xarray_lowpass. For convenience, docs for xarray_lowpass are copied below.xarray_lowpass docs——————-return array after putting it through a lowpass filter using fft & ifft.This is equivalent to ifft(fft(array) * filter), where filter is 0 at all “large” frequency values.“large” is determined by keep & r; see below.- dim: None or iterable or strs
- coordinates to apply lowpass filter over. If None, use all array.dims.promote_dim(array, coord) for any non-dimension coordinates, as needed.
- keep: UNSET, True, dict, or number between 0 < keep <= 1
- fraction of frequencies to keep, along each dim.(Must provide this or keep_r but not both.)True –> use DEFAULTS.FFT_LOWPASS_KEEP.number –> use this value for all dims.
- keep_r: UNSET, True, or number between 0 < keep <= 1
- radius of N-sphere to keep in normalized frequency-space,normalized such that max(frequencies)==1 along each dim.All values outside of this N-sphere will be set to 0.Similar to
keep, but here use an N-sphere instead of an N-cube.(Must provide this or keep but not both.)True –> use DEFAULTS.FFT_LOWPASS_KEEP.[TODO] more options than just spherical? (e.g. ellipsoid) - ds: None, number, or dict of {dim: d}
- spacing between elements of array along each dim.number –> use the same value for all dims.None –> infer via array.coords[dim].diff(dim) for each dim(requires evenly-spaced coordinates in dim; spacing checked with np.allclose)
- real: None or bool
- whether to return np.real(ifft) instead of just ifft (which might have imaginary part)None –> infer from array. Use True if np.all(np.isreal(array)), else False.
return_fft: boolwhether to return (result, masked fft) instead of just result.mainly intended for debugging purposes.
- property lowpass_keep
the default value for “keep” in self.lowpass. 0 < lowpass_keep <= 1.
Or, can be a dict of {dim: keep} pairs, to use different keep for different dims.To use keep_r instead of keep, call lowpass directly and enter keep_r there.
- static magnitude(A, *, squared=False)
return vector magnitude of A, assuming vector components along the dimension ‘component’.
- squared: bool, default False
- if True, return |A|**2 instead of |A|.[EFF] to get |A|**2, when |A| is not needed,magnitude(A, squared=True) is more efficient than magnitude(A)**2
- 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.
- property mask
None or xarray.DataArray of bools,
if self.masking, apply mask to results (with mask dims) at top-level (call_depth=1)(internal calls still do full calculations, so derivatives will still work.)applying mask means calling self.apply_mask(result);masking = True or ‘stacked’ –> xarray_mask(result, stack=True); i.e., drops all masked points.(and, result will have ‘_mask_stack’ dimension instead of mask.dims dimensions)masking = ‘simple’ –> xarray_mask(result, stack=False); i.e., masked points just replaced by nan.never applies mask if self.mask = None.setting self.mask = value is equivalent to calling self.set_mask(value).
- property masking
how to apply self.mask to results at top level, if mask exists.
True –> alias for ‘stacked’. This is the default.‘stacked’ –> apply stacked mask to self.stack(result), dropping masked points.‘simple’ –> apply mask to result, filling masked regions with np.nan.False –> do not apply mask, even if self.mask exists.
- 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: bool
- if 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 ncoarse
int
if >1, group tasks into groups of size ncoarse before performing them.
- property ncpu
None or int
max number of cpus to use for multiprocessing.None –> use multiprocessing.cpu_count()int –> use this value. if 0 or 1, do not use multiprocessing here.- Note: will actually use min(ncpu, number of calls to be made);
- e.g. if ncpu=4 but len(arg_kw_tuples)=2, will only use 2 cpus.
see also: self.get_ncpu() to read actual number of cpus when self.ncpu is None.
- property nondim_behavior_attrs
list of attrs in self which control behavior of self, but which are NOT in self.dimensions.
- on_changed_quasineutral(*, old, new)
called when self.quasineutral changes.
default behavior: do nothing.
- property output_mask
whether to store_mask during xarray_mask calls if self.masking.
False –> never store mask in resultsTrue –> always store mask in top-level results(all results will be xarray.Dataset objects with ‘_mask’ data_var)None –> only store mask in results which would have been Datasets anyways.
- plot(name, who=UNSET, *, save=False, show=False, close=False, **kw_plotter)
makes a single plot using the relevant plotter.
- name: str or Plotter
- name of the plotter to use, or a Plotter instance.(if Plotter, use directly and ignore ‘who’ input.)
- who: UNSET, None, or str
- person associated with the plotter.UNSET –> use the plotter with this name; crash if found multiple same-named plotters.
- save: bool, str, or dict.
- whether to save figure after calling plotter.str –> filename=save.format(name=name, savename=savename), instead of default filename=name.dict –> pass to saver as kwargs. Use kwarg ‘dst’ to also provide filename.if plotter.ani, saver is movie_obj.ani(), else saver is plt.savefig().
- show: bool
- whether to plt.show() after making plot (and, after save).if show when ani==True, return movie_obj.ani() (so it will display in jupyter)
- close: bool
- whether to plt.show() after making plot (and, after save).if show when ani==True, return movie_obj.ani() (so it will display in jupyter)
additional kwargs go to plotter.plot(…)see also: self.get_plotters(), self.save_plots().
- plot_check_nusn_from_drift(*, u='u', drift='momExB', cycle1={'ls': ['-', '--', '-.', ':']}, means=True, log=True, **kw_timelines)
plots PlasmaCalcs.timelines() for comparing nusn to nusn inferred from drifts.
This is meant to be used as a quick check. Use this code as an example if you need more low-level control.- u: str or iterable of strs
- var to use for velocity. Might want something else, e.g. EppicCalculator might use u=’moment1’iterable of strs –> get multiple.
- drift: str or iterable of strs
- tells the way to infer skappa, and thus nusn. Options: ‘momExB’, ‘momE’, ‘hall’, ‘pederson’.iterable of strs –> get multiple.
- cycle1: dict of lists
- parameters to use for matplotlib plotting if getting multiple u or drift.
- means: bool
- whether to take means of lower-level vars while getting skappa.(e.g. use ‘skappa_from_means_momExB’ instead of ‘skappa_from_momExB’, if True.)
- log: bool
- whether to take log10 of the ratios (nusn_from_drift / nusn) before plotting.
returns plt.gcf().
- polyfit(array_or_var, coord, degree, window=UNSET, **kw)
polyfit along coord. Might coarsen array, polyfit in each window, and concat results.
- array_or_var: xarray.DataArray, or str
- array to polyfit.str –> use array=self(array_or_var). (Note; **kw will NOT go to self.get(array_or_var))
- coord: str
- coordinate to polyfit along.If coord is not already a dimension, use array=promote_dim(array, coord).
- degree: int
- degree of polynomial to fit.
- window: UNSET, None, or int.
- UNSET –> use self.polyfit_windowNone –> don’t use windowing; polyfit to the entire array along coord.int –> coarsen array along dim, using windows of this length,then polyfit in each window, then concat results along coord.
Pass additional kwargs to xarray_coarsened_polyfit;also use self.polyfit_kw as defaults (for any kwargs not provided here).returns an xarray.DataSet which is the result of polyfit.
- property polyfit_boundary
alias to self.polyfit_kw[‘boundary’].
When polyfitting, tells how to handle boundaries when coarsening array.probably ‘exact’, ‘trim’, or ‘pad’.
- property polyfit_cov
alias to self.polyfit_kw[‘cov’].
When polyfitting, tells whether to also return the covariance matrix.only used if self.polyfit_full=False.
- property polyfit_full
alias to self.polyfit_kw[‘full’].
When polyfitting, tells whether to also return residuals, matrix rank and singular values.
- property polyfit_keep_coord
alias to self.polyfit_kw[‘keep_coord’].
When polyfitting, tells whether to keep some of the original coord values in result.probably ‘left’, ‘middle’, ‘right’, or False.
- property polyfit_kw
kwargs to pass to self.polyfit(), other than array, coord, degree, and window.
See polyfit_kw_key_aliases for a list of aliases to some of these kwargs, as attributes of self.getting self.polyfit_kw will also set keys to default values from aliases,e.g. polyfit_boundary has default of ‘trim’ –> if polyfit_kw[‘boundary’] not set, set it to ‘trim’.
- property polyfit_stddev
alias to self.polyfit_kw[‘stddev’].
When polyfitting, tells whether to also return the standard deviations of the coefficients.incompatible with self.polyfit_full=True.
- property polyfit_window
When polyfitting, tells window size to use for coarsening arrays before fitting.
E.g., polyfit_window=10 –> windows of length 10, polyfit in each window, concat results.
- pop_dim_keys(kw)
return ({key: kw.pop(key) for key in self.dimensions if key in kw}, kw).
- property print_freq
None, or number (possibly negative or 0)
>0 –> Minimum number of seconds between progress updates.=0 –> print every progress update.<0 –> never print progress updates.None –> use DEFAULTS.PROGRESS_UPDATES_PRINT_FREQ
- property print_freq_explicit
like self.print_freq, but converts UNSET to value based on self.verbose,
UNSET –> result depends on self.verbose:False or <=0 –> -1True or (>=1 and <5) –> None>=5 –> 0 (i.e. print every progress update)if self.verbose doesn’t exist –> Noneif result would be None, instead give DEFAULTS.PROGRESS_UPDATES_PRINT_FREQ.
- 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 quasineutral
tells whether self is in quasineutral mode.
- record_units(array)
return array.assign_attrs(self.units_meta()).
if array is not an xarray.DataArray, convert it first.
- static rmscomps(A)
return root mean squared of components of A.
E.g., rmscomps(A) –> sqrt((Ax^2 + Ay^2 + Az^2) / 3), if A has 3 components.
- save_plots(kind=UNSET, who=UNSET, *, name=None, all_whos=UNSET, all_kinds=UNSET, skip_who=[], skip_kinds=[], min_cost=None, max_cost=None, dst='{savename}', save_log=True, log_extras=[], kw_save={}, bbox_inches=UNSET, dpi=UNSET, show=False, close=True, print_freq=0, **kw_plotter)
saves all plots from plotters associated with these inputs.
returns dict of {plotter: plotter result} for all plotters called.Consider checking self.get_plotters() first to learn which plotters will be included.For choosing which plotters to include:- kind: UNSET, str, or list.
- kind associated with the plotter.UNSET –> include plotters regardless of ‘kind’.str –> require this kind to be in plotter.kinds.list –> require at least one of these to be in plotter.kinds.
- who: UNSET, None, str, or list.
- person associated with the plotter.UNSET –> include plotters regardless of ‘who’.None –> require len(plotter.who) == 0.str –> require this name to be in plotter.who.list –> require at least one of these to be in plotter.who(or, if None in list, allow len(plotter.who)==0, too)
- name: None or str
- plotter name. E.g. ‘deltafrac_n’.None –> include all plotters regardless of ‘name’.
- all_whos: UNSET or list.
- include only plotters with ALL of these people in plotter.who.
- all_kinds: UNSET or str.
- include only plotters with ALL of these kinds in plotter.kinds.
- skip_who: list
- exclude plotters with any of these people in plotter.who.
- skip_kinds: list
- exclude plotters with any of these kinds in plotter.kinds.
- min_cost: None or number
- exclude plotters with cost < min_cost.None –> no minimum.
- max_cost: None or number
- exclude plotters with cost > max_cost.None –> no maximum.
For plotting:- dst: str
- where to save plots to. Hit by dst.format(name=plotter.name, savename=plotter.savename).if not abspath, save to os.path.join(self.unique_notes_dirname, dst) if possible,else save to dst within current directory.
- save_log: bool or str
- whether to save a log of plot progress to _save_plots_log.txt file.str –> save to this file name. If not abspath, put it in dir implied by dst (see above).The log tells current datetime, version info about PlasmaCalcs, and plot timing updates.
- log_extras: list of str
- extra lines to put in the log “header”, if doing save_log.
- kw_save: dict
- kwargs to pass to plotter.save(…)
- bbox_inches: UNSET or any value
- if provided, added to kw_save.
- dpi: UNSET or any value
- if provided, added to kw_save.
- show: bool
- whether to plt.show() after making plot (and, after save).if show when ani==True, return movie_obj.ani() (so it will display in jupyter)
- close: bool
- whether to plt.show() after making plot (and, after save).if show when ani==True, return movie_obj.ani() (so it will display in jupyter)
additional kwargs go to plotter.plot(…)Misc:- print_freq: number
- minimum seconds between printing progress updates.-1 –> never print; 0 –> always print.
see also: self.get_plotters(), self.plot().
- property set
alias to set_var
- set_E_un0_perpmod_B(value, **kw)
set E_un0_perpmod_B to this value. Also sets E_un0_perpmag_B.
- set_attrs(**attrs)
sets these attrs in self.
- set_mask(mask)
sets self.mask = mask, and increments self._mask_cache_state (if checks succeed).
Also does some checks:- mask is None or xarray.DataArray. If None, don’t do any other checks.Also may alter mask slightly:- discard non-dimension coords
- set_mod_B(value, **kw)
set mod_B to this value. Also sets mag_B, mod2_B, and mag2_B.
- set_pop_dim_attrs(kw)
set self.{key} = kw.pop(key) for each key in self.dimensions if key in kw.
- set_t_turb_00()
set self.t_turb & return t_turb from ‘00’ standard: t_turb_from_pwl2_ln_std_blur_deltafrac_n,
with fluid=electron, snap=None, blur_sigma=10.Drops ‘fluid’, ‘snap’, and ‘t’ coords from result.(internally, uses ‘caches_ln_std_blur_deltafrac_n’ with t_turb=None, to save time if recomputed later.)(00 standard should never change, it will always mean this!)
- set_t_turb_10()
set self.t_turb & return t_turb from ‘10’ standard: t_turb_from_pwl2_ln_std_blur_deltafrac_n,
for fluid=None, fitting across all snaps, and blur_sigma=10.Renames ‘fluid’ to ‘tturb_fluid’ in result. Drops ‘snap’ and ‘t’ coords from result.(internally, uses ‘caches_ln_std_blur_deltafrac_n’ with t_turb=None, to save time if recomputed later.)(10 standard should never change, it will always mean this!)
- 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: str
- the 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 list
- tells 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 strings
- if 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 str
- if 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 True
- handles the case where self.KNOWN_SETTERS[var] doesn’t exist. In that case…True –> set var in self, anyway.False –> crash; raise FormulaMissingError
additional 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: str
- the 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 strings
- the 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 strings
- if 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 str
- if 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.
- set_vtherm(value, **kw)
set thermal velocity, by setting T.
vtherm = sqrt(kB T / m) –> set T to (m vtherm^2 / kB).
- 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.
- solve_tfbi_vs_EBspeed(*, Mbytes_max=True, cache='caches', **kw_solve)
solve tfbi across EBspeed grid from self(‘tfbi_EBspeed_grid’).
CAUTION: the implementation here might self.set(‘E_un0_perpmod_B’, self(‘mod_B’) * EBspeed)
[TODO] avoid changing self.setvars… (or, at least, restore previous self.setvars afterwards.)Suggestion: use self.setvars.clear() after calling this function.
- Mbytes_max: bool or number
- maxmimum allowed data size [in MB] of self(‘tfbi_inputs’), before setting EBspeed grid.(helps prevent accidental requests to solve too many points at once.)(ignored if
cacheimplies to load from existing cached file.)True –> use default: DEFAULTS.ADDONS.TFBI_EBSPEED_INPUTS_MBYTES_MAX (default: 0.1).False or None –> no maximum - cache: ‘caches’, ‘cache’, ‘cached’, or False
- controls how & whether to handle cache the result.cached results go to self._tfbi_vs_EBspeed_file(); default:{self.unique_notes_dirname}/_pc_tfbi/EBspeed_{logmin:.4g}_{logmax:.4g}_{logstep:.4g}.pcxarrwhere logmin, logmax, logstep are from self.tfbi_EBspeed_grid_size‘caches’ –> read from saved file if it exists. Else, solve and save to file.‘cache’ –> solve and save to file. Saved file must not exist yet (else, crash).‘cached’ –> read from saved file. Saved file must exist (else, crash).False –> solve and return result, but do not save to file nor check if file exists.
additional kwargs are passed to self.tfbi_solver().solve(**kw)
- property stat_dims
the dims over which to possibly apply statistics (StatsLoader methods).
will only apply statics along these dims for an array if they actually appear in the array.None –> use self.maindims. (this is the default.)See also: self.stat_dims_for(array).
- stat_dims_for(array)
return the dims to apply statistics over, for this array.
Here, returns tuple of d from self.stat_dims if d in array.dims.
- property stats_dimpoint_wise
whether to apply stat calculations at each DimPoint, or after loading the full array.
[EFF] this setting is just for efficiency; it doesn’t affect results (when no MemorySizeError crash).True –> apply stat calculations to each array (at each DimPoint) before joining arrays.e.g., self(‘mean_n’) gets ‘mean_n’ at each fluid & snap, then joins results.False –> join arrays across all DimPoints before applying stat calculations.e.g., self(‘mean_n’) gets ‘n’ (which varies across fluid & snap), then takes mean.None –> if result.size will be > DEFAULTS.STATS_DIMPOINT_WISE_MIN_N / self.get_ncpu(), use True.otherwise try using False, then use True if MemorySizeError is raised.(True seems to be faster for large arrays but slower for small arrays.But also, when ncpu>1, loading across dimpoints is faster due to parallelization.)regardless of this setting, stat calculations are applied only along self.stat_dims(array).
- store_mask(arr)
equivalent: xarray_store_mask(arr, self.mask). Also equivalent: arr.pc.store_mask(self.mask)
- property surelin_min_quantile
fraction of t_turb which tells start time of “definitely linear regime”.
Use this to avoid including startup noise when computing linear properties.Example: t_turb=10, surelin_min_quantile=0.05 –> t_surelin=0.05*10 = 0.5.
- property surelin_quantile
fraction of t_turb which tells t_surelin.
t_turb tells when turbulence probably starts.t_surelin tells time before which, values are definitely in the linear regime.–> to compute linear properties consider only t < t_surelin.Example: t_turb=10, surelin_quantile=0.2 –> t_surelin=0.2*10 = 2.See also: surelin_min_quantile.
- property t_turb
None, or time of turbulent onset. some _turb quantities tell values only at t>=t_turb.
Can be set to a DataArray, to test multiple possibilities at once.Units should be self.units. Changing self.units afterwards will NOT auto-update t_turb.
- property take_component
alias to self.component_dim.take
- property take_components
alias to self.component_dim.take_along
- static take_parallel_to(B, A)
return the component of A parallel to B. Equivalent: (A dot Bhat) Bhat.
Note that B is the first argument.
- static take_perp_to(B, A)
return the component of A perpendicular to B. Equivalent: A - (A dot Bhat) Bhat.
Note that B is the first argument.
- property tfbi_EBspeed_grid_size
(logmin, logmax, logstep) for self(‘tfbi_EBspeed_grid’); log is base 10.
Default: DEFAULTS.ADDONS.TFBI_EBSPEED_LOGMIN, LOGMAX, LOGSTEP; (default: (3, 4, 0.01)).
- tfbi_ds(ions=None, *, all=True, output_mask=True, **kw_get_var)
returns Dataset of all the values needed & relevant to TFBI theory.
Equivalent: self(‘tfbi_all’, fluid=[electron, *ions], masking=True, …)- ions: None or specifier of multiple fluids (e.g. slice, or list of strs)
- list of ions to use. None –> self.fluids.ions()
- all: bool
- whether to include ‘tfbi_all’, or only ‘tfbi_inputs’.With only ‘tfbi_inputs’, the theory is still solvable, but harder to inspect later.
- output_mask: bool
- whether to store_mask in results, if self.masking (and self.mask is not None)
additional kwargs passed to self(…)
- property tfbi_growth_thresh
threshold for confirming “yes there is tfbi growth predicted here”, during self(‘tfbi_E_thresh’).
growth must be larger than (not equal to) this value, to confirm growth.0.0 is the theoretical threshold. A small positive value (e.g. 0.001) helps to avoid tiny errors.The default is DEFAULTS.ADDONS.TFBI_GROWTH_THRESH (default: 0.001).
- tfbi_mask(*, kappae=1, ionfrac=0.001, kappai=1, set=True)
set & return self.mask appropriate for TFBI.
- kappae: None or number, default 1
- lower limit for kappae; mask points with kappae smaller than this value.(kappae = |qe| |B| / (me nuen))Internally, loaded as ‘kappa’ with fluid=’e’.TFBI probably only matters when electrons are magnetized –> kappae >> 1.Applying TFBI theory to kappae masked points would still be fine,but will probably always say “instability doesn’t grow there”.None –> no mask on kappae
- ionfrac: None or number
- upper limit for ionfrac; mask points with ionfrac larger than this value.(ionfrac = ne / ntotal)Internally, loaded as ‘SF_ionfrac’ if available,else ne/(ne+n_neutral), with ne from self(‘n’, fluid=self.fluids.get_electron()).(Note: checked in Bifrost: SF_ionfrac uses SF_n = sum of element densities.SF_n does not include ne.The formula SF_ionfrac = ne/(ne+nn) uses ne as a proxy for sum(ni),which will be okay unless there are twice+ ionized species.)TFBI assumes weakly ionized.E_un0 also assumes weakly ionized, when self.assume_un=’u’.Applying TFBI theory to ionfrac masked points would be a big issue,as it could lead to many false positives,where physical effects not included in the theory damp out the TFBI.None –> no mask on ionfrac.
- kappai: None or number, default 1
- upper limit for min kappai; mask points with all kappai larger than this value.(kappai = |qi| |B| / (mi nuin))Internally, loaded as ‘kappa’ with fluid=ions, then take min across fluids.TFBI probably only matters when at least 1 ion species is demagnetized –> kappai < 1.Applying TFBI theory to kappai masked points would still be fine,but will probably always say “instability doesn’t grow there”.None –> no mask on kappai.
- set: bool
- whether to set self.mask = result.if False, only returns the result, without also setting self.mask.
- tfbi_solver(ions=None, **kw_solver)
return TfbiSolver object for solving TFBI theory based on values in self.
all inputs here get passed to TfbiSolver. Equivalent: TfbiSolver(self, …).docs for TfbiSolver copied below for convenience:————————————————-high-level interface for solving TFBI theory across many physical parameters.Call TfbiSolver to solve TFBI.Example:import PlasmaCalcs as pccc = pc.PlasmaCalculator(…) # <– your PlasmaCalculator of choicesolver = pc.TfbiSolver(cc)solution = solver() # alias: solver.solve()solution is an xarray.Dataset with all relevant quantities (see TfbiLoader.get_tfbi_all),and ‘omega’ telling roots with largest imaginary part.If you need more precise control over the solving process, use the pattern:import tfbi_theory as ttimport PlasmaCalcs as pccc = … # any PlasmaCalculator object from PlasmaCalcs.ds0 = cc.tfbi_ds()kp = tt.kPickerLowres(ds0)dsk = kp.get_ds() # copy of ds0, but with ds[‘k’] = k from kPicker.drel = tt.TfbiDisprelC.from_ds(dsk)dsR = drel.solve() # copy of dsk, but with ds[‘omega’] = solution to TFBI theory!TfbiSolver internally stores self.cc, ds0, kp, dsk, drel, and dsR,as defined by the pattern above.- cc: PlasmaCalculator
- PlasmaCalculator object used to load the data.Should be a TfbiLoader subclass. (PlasmaCalculator satisfies this by default,assuming successful import SymSolver and import tfbi_theory.)
- ions: None or specifier of multiple fluids (e.g. slice, or list of strs)
- None –> use cc.fluids.ions()print warning if this specifies more than DEFAULTS.ADDONS.TFBI_MAX_NUM_IONS ions(default: 5), because then solving will be slow and may be inaccurate.ions are determined when called, not during __init__.
- kres: ‘low’, ‘mid’, or ‘high’
- resolution in k-space. Tells which self.kPicker_cls to use.‘low’ –> tfbi_theory.kPickerLowres. Recommended if solving across many points.‘mid’ –> tfbi_theory.kPickerMidres. Recommended if solving across a few points.‘high’ –> tfbi_theory.kPickerHighres. Recommended if solving at only 1 point.
- mod, lmod, ang: UNSET or dict
- passed directly to kPicker if provided. Can specify k values other than the defaults.see help(self.kPicker_cls) for more details.
- tfbi_all: bool
- whether to compute all relevant tfbi vars, ds0 = cc(‘tfbi_all’).False –> compute only the necessary vars, ds0 = cc(‘tfbi_inputs’).
- drel_cls: None, str, or class
- tfbi_theory class to use for solving TFBI theory.None –> use self.drel_cls default: tt.TfbiDisprelCstr –> use getattr(tt, drel_cls) to get the class.
- tfbi_solver_cls
alias of
TfbiSolver
- property timeout
None or int
max duration, in seconds. Must be None or integer (due to limitations of signal.alarm method)None –> no time limit.- Note: if time_limit is reached, will raise a TimeoutError and save the result so far.
- (in this case, any not-yet-calculated values will each be RESULT_MISSING.)
- 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 u
the current units manager for self.
if not yet initialized, getting self.u will create (and store) a new UnitsManager().
- property units
the current unit system for self. E.g., ‘si’. (this is an alias to self.u.units)
- units_meta()
return dict(units=self.units).
- unmask(arr, **kw_xarray_unmask)
restore arr to the same shape as unmasked unstacked arrays. masked vals will still be np.nan.
Equivalent: xarray_unmask(arr) if arr has ‘_mask’ data_var, else xarray_unmask(arr, mask=self.mask)
- 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 strings
- only 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: bool
- whether 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 strings
- the behavior attrs relevant to setting this var.
- forall: list of strings
- if provided, tells which behavior attrs to ignore when unsetting the var.
- ukey: None or string
- if 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: bool
- whether 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_UNSET
- upon 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.
- using_first_dimpoint(dims=None)
return context manager which sets dimensions to their first values (when called); restore original on exit.
Useful for testing a single code at a single dimpoint without needing to set each dimension individually.- dims: None or iterable of strs appearing in self.dimensions.keys()
- dimensions to include. None –> use all dimensions.
- property werrmath_require_std
whether to require ‘std’ data var appear in at least 1 input for all werrmath operations.
E.g. if True and doing A_werradd_B but neither A nor B has ‘std’, crash with InputError.
- property window
alias to polyfit_window