PlasmaCalcs.hookups.ebysus.ebysus_calculator.EbysusCalculator

class PlasmaCalcs.hookups.ebysus.ebysus_calculator.EbysusCalculator(dd, *, collisions_mode='best', match_type='AUX', **kw_super)

Bases: EbysusBasesLoader, EbysusCollisionsLoader, EbysusEfieldLoader, EbysusTemperaturesLoader, MultifluidPlasmaCalculator

PlasmaCalculator for Ebysus.
The idea is to use EbysusData (from helita.sim.ebysus) to read files.
But hook everything up so that PlasmaCalcs does all the heavy-lifting.
dd should be an EbysusData object.
collisions_mode: str, default ‘best’
default mode for getting collision frequencies;
‘helita’ –> get collision frequencies directly from helita.
for more options/details, see help(type(self).collisions_mode).
match_type: ‘AUX’, ‘PHYSICS’, 1, 0, or None
1 or ‘AUX’ –> set dd.match_type = MATCH_AUX
0 or ‘PHYSICS’ –> set dd.match_type = MATCH_PHYSICS
None –> don’t adjust dd.match_type.
UNITS note: right now, units is fully managed by dd;
self.u(conversion) will always be 1 (e.g. self.u(‘l’) == self.u(‘m’) == … == 1);
self.units == ‘si’ –> dd.units_output == ‘si’;
self.units == ‘raw’ –> dd.units_output == ‘simu’.
[TODO] handle units via PlasmaCalcs instead of dd.
__init__(dd, *, collisions_mode='best', match_type='AUX', **kw_super)

Methods

__init__(dd, *[, collisions_mode, match_type])

angle_xy(A)

angle_xy_to_hat(A)

apply_mask(arr[, masking])

as_single_dimpoint([values, dims])

assert_QN()

assign_dim_coords(array, *dims[, skip])

assign_maindims_coords(array)

attach_extra_coords(arr)

check_pickle([x])

cls_help([qstr, only, tree, modules, ...])

cls_var_tree(var, *[, missing_ok])

copy()

cross_component(A, B, x, *[, yz, missing_ok])

cross_components_needed()

cross_product(A, B, *[, components])

curl_component(v, x, *[, yz])

current_n_dimpoints([dims])

current_n_existing_snaps()

dim_values([dims])

dims_apply(funcname, *args_func[, dims])

dims_get(attr[, dims])

direct_overrides_dynamic()

dot_product(A, B)

enumerate_dimpoints([dims, all])

existing_snaps()

fftN(array[, dim, ds, slices])

fft_dims_for(array)

gaussian_filter(array[, dim, sigma])

get_0()

get_1()

get_B()

get_E()

get_E0S1(*[, _skappa, _n])

get_E0S1_and_S2()

get_E0S2(*[, _skappa, _n])

get_E0_etaJ_perpB(*[, _E0S1, _E0S2])

get_E0_hall(*[, _E0S1, _E0S2])

get_E0_un0_perpB()

get_E0_un0_perpmodB()

get_E0_un0_perpmodB_min()

get_E0_un0_perpmodB_simple()

get_EBspeed()

get_E_bat(*[, _u_e])

get_E_helita()

get_E_mom(*[, _u_e])

get_E_momj(*[, _u_e])

get_E_terms()

get_E_un0()

get_E_un0_perpmod_B(**kw_perpmod)

get_E_un0_type()

get_E_uxB(*[, _u_e])

get_Eheat()

get_Eheat_par(*[, _E_un0, _B, _Eheat_par_coeff])

get_Eheat_par_coeff()

get_Eheat_perp(*[, _E_un0, _B, _Eheat_par_coeff])

get_Eheat_perp_coeff(*[, _Eheat_par_coeff])

get_Eheat_perp_rate_n()

get_Eheat_perp_rate_n_s()

get_Epar()

get_Eperp()

get_J()

get_JBspeed()

get_J_B()

get_J_ext()

get_J_helita()

get_Jf()

get_P()

get_T()

get_T_box()

get_T_from_Eheat()

get_T_from_Eheat_perp()

get_T_global(var, *[, _match])

get_T_global_correction(var, *[, _match])

get_T_neutral()

get_T_sj(*[, _m_s, _T_s, _m_j, _T_j])

get_Tapar(var, *[, _match])

get_Taperp(var, *[, _match])

get_Tjoule()

get__nusj_singlej(*, collision_type)

get_abs(var, *[, _match])

get_abs_qe()

get_amu()

get_angle_xy(var, *[, _match, _val0])

get_angle_xy_to_hat(var, *[, _match, _val0])

get_astats(var, *[, _match])

get_behavior([keys])

get_best_pow2_subcycle()

get_best_subcycle()

get_beta()

get_blur(var, *[, _match])

get_blurk(var, *[, _match])

get_blurt(var, *[, _match])

get_braced_int_from_parenthesis_memory(var, *)

get_cache_var(var, *[, _match])

get_cached_tfbi_vs_EBspeed()

get_cached_var(var, *[, _match])

get_caches_var(var, *[, _match])

get_collision_type()

get_collisions_cross_section()

get_collisions_crosstab(fluid1, fluid2, *[, ...])

get_collisions_crosstab_default_fluids()

get_compare_equals(var, *[, _match])

get_compare_greater_than(var, *[, _match])

get_compare_greater_than_or_equal(var, *[, ...])

get_compare_less_than(var, *[, _match])

get_compare_less_than_or_equal(var, *[, _match])

get_compare_not_equals(var, *[, _match])

get_coulomb_logarithm()

get_cross(var, *[, _match, _val0, _val1])

get_csound()

get_csound2()

get_curl(var, *[, _match])

get_dTndt()

get_dTndt_s()

get_dTndt_s_T()

get_dTndt_s_ds()

get_dTndt_s_u2()

get_dTndt_turb0_s_ds()

get_deg2rad(var, *[, _match])

get_delta(var, *[, _match])

get_delta_sj()

get_deltafrac(var, *[, _match])

get_derivative(var, *[, _match])

get_div(var, *[, _match])

get_divide(var, *[, _match])

get_dot(var, *[, _match, _val0, _val1])

get_ds()

get_ds_for_timescales()

get_dsmin_for_timescales()

get_e()

get_eps0()

get_eqperp_ldebye()

get_eqperp_ldebye2()

get_eqperp_ldebye_total()

get_eqperp_mean_free_path()

get_eqperp_vtherm()

get_eta0_J(*[, _E0S1, _E0S2])

get_eta0_hall(*[, _E0S1, _E0S2])

get_exp(var, *[, _match])

get_fft(var, *[, _match])

get_fft_with_dims(var, *[, _match])

get_finite(var, *[, _match])

get_first_dimpoint([dims, enumerate])

get_float(var, *[, _match])

get_gamma()

get_grad(var, *[, _match])

get_growthfit(var, *[, _match])

get_growthfitk(var, *[, _match])

get_growthk(var, *[, _match])

get_growthrate(var, *[, _match])

get_gyrof()

get_hat(var, *[, _match, _val0])

get_ifft(var, *[, _match])

get_imag(var, *[, _match])

get_inf()

get_init_fluids()

get_init_snaps()

get_int(var, *[, _match])

get_ionnefrac()

get_ionnefrac_significant()

get_ionnefrac_tiny()

get_kB()

get_kappa()

get_ldebye()

get_ldebye2()

get_ldebye_subset()

get_ldebye_total()

get_linregt(var, *[, _match])

get_ln(var, *[, _match])

get_log10(var, *[, _match])

get_log2(var, *[, _match])

get_logical_and(var, *[, _match])

get_logical_not(var, *[, _match])

get_logical_or(var, *[, _match])

get_lowpass(var, *[, _match])

get_m()

get_m_amu()

get_m_neutral()

get_m_sj(*[, _m_s, _m_j])

get_maindims_coords()

get_mask_var(var, *[, _match])

get_max(var, *[, _match])

get_mean(var, *[, _match])

get_mean_free_path()

get_mean_pm_std(var, *[, _match])

get_meannormed(var, *[, _match])

get_meant(var, *[, _match])

get_median(var, *[, _match])

get_min(var, *[, _match])

get_min_timescale()

get_min_timescale_type()

get_minf_timescale()

get_minf_timescale_type()

get_minus(var, *[, _match])

get_mod(var, *[, _match, _val0])

get_mod2(var, *[, _match, _val0])

get_n()

get_n_neutral()

get_nan()

get_nandelta(var, *[, _match])

get_nandeltafrac(var, *[, _match])

get_nanmax(var, *[, _match])

get_nanmean(var, *[, _match])

get_nanmedian(var, *[, _match])

get_nanmin(var, *[, _match])

get_nanrms(var, *[, _match])

get_nanstd(var, *[, _match])

get_ncpu()

get_ne()

get_negation(var, *[, _match])

get_neutral([var])

get_niefrac()

get_nmean(var, *[, _match])

get_nnefrac()

get_nnefrac_significant()

get_nnefrac_tiny()

get_nq()

get_nstd(var, *[, _match])

get_nuns()

get_nusj()

get_nusj_coulomb()

get_nusj_fromtable()

get_nusj_helita()

get_nusj_maxwell()

get_nusn()

get_nusn_from_drift(var, *[, _match])

get_p()

get_parallel(var, *[, _match, _val0, _val1])

get_parenthesis(var, *[, _match])

get_parmod(var, *[, _match, _val0, _val1])

get_perp(var, *[, _match, _val0, _val1])

get_perpmod(var, *[, _match, _val0, _val1])

get_pi()

get_plotter(name[, who])

get_plotters([who, kind, name, all_whos, ...])

get_plus(var, *[, _match])

get_pmstd2werr(var, *[, _match])

get_power(var, *[, _match])

get_pwl2_var(var, *[, _match])

get_q()

get_r()

get_rad2deg(var, *[, _match])

get_real(var, *[, _match])

get_rms(var, *[, _match])

get_rmscomps(var, *[, _match])

get_rosenberg_multi()

get_rosenberg_multi_nusn()

get_rosenberg_multi_wplasma()

get_rosenberg_n()

get_rosenberg_n_margin()

get_rosenberg_qn()

get_safe_pow2_subcycle(*[, subcycle_safety])

get_sci_number(var, *[, _match])

get_set_or_cached(var)

get_sgyrof()

get_skappa()

get_skappa_from_hall(var, *[, _match])

get_skappa_from_momE(var, *[, _match])

get_skappa_from_momExB(var, *[, _match])

get_skappa_from_pederson(var, *[, _match])

get_slopet(var, *[, _match])

get_sparmod(var, *[, _match, _val0, _val1])

get_sqrt(var, *[, _match])

get_stats(var, *[, _match])

get_std(var, *[, _match])

get_sum(var, *[, _match])

get_sum_fluid_var(var, *[, _match])

get_sum_fluids_var(var, *[, _match])

get_sum_ions_var(var, *[, _match])

get_sum_jfluid_var(var, *[, _match])

get_sum_jfluids_var(var, *[, _match])

get_sum_neutrals_var(var, *[, _match])

get_surelin_var(var, *[, _match])

get_sureturb_var(var, *[, _match])

get_t_surelin()

get_t_surelin_min()

get_t_sureturb()

get_t_turb()

get_t_turb_from_pwl2_var(var, *[, _match])

get_tfbi_EBspeed_grid()

get_tfbi_EBspeed_thresh()

get_tfbi_E_thresh()

get_tfbi_all(**kw_get_vars)

get_tfbi_extras(**kw_get_vars)

get_tfbi_fscale()

get_tfbi_fscale_rel()

get_tfbi_inputs(**kw_get_vars)

get_tfbi_omega(*[, kw_tfbi_solve])

get_tfbi_omega_ds(*[, kw_tfbi_solve])

get_tfbi_vs_EBspeed()

get_times(var, *[, _match])

get_timescale_EBdrift()

get_timescale_EBspeed()

get_timescale_eqperp_vtherm()

get_timescale_gyrof()

get_timescale_nusn()

get_timescale_udrift()

get_timescale_vtherm()

get_timescale_wplasma()

get_timescales()

get_timescales_abbrv()

get_tturb_var(var, *[, _match])

get_tturbvar00()

get_turblindiff_var(var, *[, _match])

get_turblindiffwerr_var(var, *[, _match])

get_turblindivwerr_var(var, *[, _match])

get_u()

get_u_EdotB(*[, _E, _B])

get_u_drift()

get_u_hall(*[, _E, _B])

get_u_neutral()

get_u_pederson(*[, _E, _B])

get_unwrapt_2pi_var(var, *[, _match])

get_upar()

get_uperp()

get_valfven()

get_valfven2()

get_var_at_max_of_ref(var, *[, _match])

get_var_at_min_of_ref(var, *[, _match])

get_var_where_condition(var, *[, _match])

get_vars(vars, *args[, return_type, ...])

get_vector_N(var, *[, _match])

get_vsqr()

get_vtherm()

get_vtherm_n()

get_weighted_mean(weights_var, *[, _match])

get_weighted_std(weights_var, *[, _match])

get_werr2pmstd(var, *[, _match])

get_werradd(var, *[, _match])

get_werrdiv(var, *[, _match])

get_werrmean(var, *[, _match])

get_werrmeant(var, *[, _match])

get_werrmul(var, *[, _match])

get_werrsub(var, *[, _match])

get_where_condition_var(var, *[, _match])

get_wplasma()

get_wplasmae()

get_xhat()

get_xyz(var, *[, _match])

get_yhat()

get_zhat()

getj(var, *args__get[, jfluid])

has_var(var)

help([qstr, only, tree, modules, signature, ...])

help_call_options([search])

help_quants_str([qstr, only, tree, modules, ...])

help_str([qstr, only])

ifftN(array[, dim, df, x0, ds])

ifft_dims_for(array)

iter_dimpoints([dims, all, restore, enumerate])

kw_call_options(*[, sorted])

load_across_dims(loader, *args_loader[, ...])

load_across_dims_implied_by(var, loader, ...)

load_direct(var, *args, **kw)

load_fromfile(ebysus_var, *args, **kw)

load_maindims_var(var, *args[, u, assign_labels])

load_maindims_var_across_dims(var[, dims, ...])

lowpass(array[, dim, keep, keep_r])

magnitude(A, *[, squared])

maindims_with_extent()

maindims_with_no_extent()

maintaining_attrs(*attrs, **attrs_as_flags)

match_dd_dims()

match_var(var, *[, check])

match_var_loading_dims(var, **kw_loading_dims)

match_var_result_dims(var, **kw_result_dims)

match_var_result_size(var, *[, maindims])

match_var_tree([var])

n_existing_snaps()

on_changed_quasineutral(*, old, new)

plot(name[, who, save, show, close])

plot_check_nusn_from_drift(*[, u, drift, ...])

polyfit(array_or_var, coord, degree[, window])

pop_dim_keys(kw)

quant_tree([var])

record_units(array)

rmscomps(A)

save_plots([kind, who, name, all_whos, ...])

set_E_un0_perpmod_B(value, **kw)

set_attrs(**attrs)

set_collisions_crosstab(fluid1, fluid2, ...)

set_collisions_crosstab_defaults([mode, ...])

set_mask(mask)

set_mod_B(value, **kw)

set_pop_dim_attrs(kw)

set_t_turb_00()

set_t_turb_10()

set_var(var, value[, behavior_attrs, ...])

set_var_internal(var, value, behavior_attrs)

set_vtherm(value, **kw)

slice_maindims(array, **kw_xarray_isel)

slicestr(*[, sep, keep_None])

snap_filepath([snap])

solve_tfbi_vs_EBspeed(*[, Mbytes_max, cache])

standardized_slices()

stat_dims_for(array)

store_mask(arr)

take_parallel_to(B, A)

take_perp_to(B, A)

tfbi_ds([ions, all, output_mask])

tfbi_mask(*[, kappae, ionfrac, kappai, set])

tfbi_solver([ions])

title_with_slices(*[, sep, keep_None])

tree([var])

units_meta()

unmask(arr, **kw_xarray_unmask)

unset_var(var[, behavior_attrs, missing_ok])

unset_var_internal(var, behavior_attrs[, ...])

using_at_call_depth(depth, **attrs_and_values)

using_at_next_call_depth(**attrs_and_values)

using_attrs([attrs_as_dict, _unset_sentinel])

using_first_dimpoint([dims])

Attributes

COLLISIONS_MODE_OPTIONS

COLLISION_TYPE_TO_VAR

CROSS_TABLE_DEFAULTS

E_un0_mode

KNOWN_PATTERNS

KNOWN_PLOTTERS

KNOWN_SETTERS

KNOWN_VARS

TFBI_EXTRAS

TFBI_VARS

TIMESCALE_VARS

UNIQUE_PLOTTERS

array_MBmax

assert_masking

assign_behavior_attrs

assign_behavior_attrs_max_call_depth

assign_behavior_attrs_skip_xr

assign_component_along

assign_component_coord

assign_fluid_along

assign_fluid_coord

assign_jfluid_along

assign_jfluid_coord

assign_snap_along

assign_snap_coord

behavior

behavior_attrs

blur

blur_dims

blur_sigma

cache_dirname

caches_behavior_skip_xr

call_depth

call_depth_manager

cls_behavior_attrs

collisions_cross_mapping

collisions_mode

component

component_dim

component_is_iterable

component_list

component_type

components

coords_units

coords_units_explicit

cross

current_n_component

current_n_fluid

current_n_jfluid

current_n_snap

deriv_before_slice

dimensions

dims

direct_overrides

dirname

dot

drop

enable_fromfile

enumerate_component

enumerate_components

enumerate_fluid

enumerate_fluids

enumerate_jfluid

enumerate_jfluids

enumerate_snap

enumerate_snaps

extra_coords

fft

fft_dims

fft_half

fft_keep

fft_slices

fft_step

flip_z_mesh

fluid

fluid_dim

fluid_is_iterable

fluid_list

fluid_type

fluids

get

get_space_coords

ifft

iter_component

iter_components

iter_components_partition

iter_fluid

iter_fluids

iter_fluids_partition

iter_jfluid

iter_jfluids

iter_jfluids_partition

iter_snap

iter_snaps

iter_snaps_partition

jfluid

jfluid_dim

jfluid_is_iterable

jfluid_list

jfluid_type

jfluids

join_components

join_fluids

join_jfluids

join_snaps

known_pattern

known_plotter

known_setter

known_var

lowpass_keep

maindims

maindims_full_shape

maindims_full_size

maindims_full_sizes

maindims_means

maindims_shape

maindims_size

maindims_sizes

maintaining

mask

masking

multi_slices

multi_slices_ikeep

multi_slices_ndim

ncoarse

ncpu

nnefrac_tiny_thresh

nondim_behavior_attrs

output_mask

parenthesis_memory

polyfit_boundary

polyfit_cov

polyfit_full

polyfit_keep_coord

polyfit_kw

polyfit_kw_key_aliases

polyfit_stddev

polyfit_window

print_freq

print_freq_explicit

quasineutral

set

setvar

setvars

slices

slicing

snap

snap_dim

snap_is_iterable

snap_list

snap_type

snapdir

snaps

stat_dims

stats_dimpoint_wise

surelin_min_quantile

surelin_quantile

t_turb

take_component

take_components

take_fluid

take_fluids

take_jfluid

take_jfluids

take_snap

take_snaps

tfbi_EBspeed_grid_size

tfbi_growth_thresh

timeout

title

toplevel_scale_coords

typevar_crash_if_nan

u

units

unset

using

werrmath_require_std

window

property CROSS_TABLE_DEFAULTS
dict of {shorthand: (filename, fc)} with shorthand useable in self.set_collisions_crosstab.
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.)
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.
property assign_fluid_along
alias to self.fluid_dim.assign_coord_along
property assign_fluid_coord
alias to self.fluid_dim.assign_coord
property assign_jfluid_along
alias to self.jfluid_dim.assign_coord_along
property assign_jfluid_coord
alias to self.jfluid_dim.assign_coord
assign_maindims_coords(array)
assign maindims dims and coords, based on self.get_maindims_coords() with slicing=False.
array must have same shape as implied by maindims and coords.
if array is 0D, just return a 0D xr.DataArray.
returns an xarray with proper details for PlasmaCalcs.
This function creates a new xarray based on array, and maindims & coords are >0 dimensional.
This is not like assign_{dim}_coord functions, which assign 0D coord to an existing xarray.
property assign_snap_along
alias to self.snap_dim.assign_coord_along
property assign_snap_coord
alias to self.snap_dim.assign_coord
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 / m
Cannot 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
None –> get help with all quantities related to qstr.
‘VARS’ or ‘vars’ –> only get help with KNOWN_VARS.
‘PATTERNS’ or ‘patterns’ –> only get help with KNOWN_PATTERNS.
‘TREE’ or ‘tree’ –> only get help with quantities in cls.cls_var_tree(str).
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 collisions_cross_mapping
the collisions cross sections mapping to use.
keys are (fluid1, fluid2) pairs; values are CrossTable objects.
see self.CROSS_TABLE_DEFAULTS for shorthand options for values.
for convenient methods to build the cross mapping, see:
self.set_collisions_crosstab, self.set_collisions_crosstab_defaults.
property collisions_mode
str, the collisions mode to use when getting nusj. See COLLISIONS_MODE_OPTIONS for details.
Note that you can always calculate collisions using a specific formula with the appropriate var,
regardless of collisions_mode; e.g., nusj_maxwell will always use maxwell formula.
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
property coords_units
None or str telling the current unit system for coordinates, e.g. ‘si’.
None –> “coords_units should match self.units”.
Value stored at self.u.alts.get(‘coords’, None)
See also: coords_units_explicit
property coords_units_explicit
str telling the current unit system for coordinates, e.g. ‘si’.
alias to self.coords_units if not None, else self.units.

equivalent: self.u.alts.get(‘coords’, self.units)

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.
cross_mapping_type

alias of CrossMapping

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)))
current_n_existing_snaps()
returns number of existing snaps, out of all snaps at self.snap.
Equivalent to self.snap_dim.current_n_existing_for(self).
property current_n_fluid
alias to self.fluid_dim.current_n
property current_n_jfluid
alias to self.jfluid_dim.current_n
property current_n_snap
alias to self.snap_dim.current_n
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 dirname
alias to self.dd.fdir
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 enumerate_fluid
alias to self.fluid_dim.enumerate
property enumerate_fluids
alias to self.fluid_dim.enumerate_values
property enumerate_jfluid
alias to self.jfluid_dim.enumerate
property enumerate_jfluids
alias to self.jfluid_dim.enumerate_values
property enumerate_snap
alias to self.snap_dim.enumerate
property enumerate_snaps
alias to self.snap_dim.enumerate_values
existing_snaps()
return list of existing snaps. Equivalent to self.snaps.existing_snaps(self).
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.dims
str –> 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 dimension
associated with cname, via indexer. (cname can be pre-fft or post-fft name.)
These understand fractional indexing: can provide a fractional value
between -1 and 1, to use that fraction of the length along the relevant dimension.
Can also provide keep, half, step, and/or missing_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
property flip_z_mesh
whether to flip (multiply by -1) the z mesh coordinates relative to meshfile.
When True, z<0 implies “below photosphere”, for solar simulations.
property fluid
alias to self.fluid_dim.v
property fluid_dim
fluid dimension for FluidHaver.
fluid_dim_cls

alias of FluidDimension

property fluid_is_iterable
alias to self.fluid_dim.is_iterable
property fluid_list
alias to self.fluid_dim.list
property fluid_type
alias to self.fluid_dim.get_type
property fluids
alias to self.fluid_dim.values
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. (directly from Ebysus)
get_E()
electric field. E = E_uxB + E_bat + E_mom
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), where
E0S1 = 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) < 1
which 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/2
Utilizing 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_bat(*, _u_e=None)
electric field battery contribution. E_bat == grad(P_e) / (ne qe)
get_E_helita()
electric field. (directly from helita)
get_E_mom(*, _u_e=UNSET)
electric field momentum contribution. E_mom == -1 * sum_j me ne nu_ej * (uj - ue) / (ne qe)

Equivalent: E_mom = sum(E_momj), where sum is taken across jfluids.

[EFF] for efficiency, can provide full u_e, if already known. (provide as _u_e)
(requires full ue, not just one component, since will do ue cross B.)
get_E_momj(*, _u_e=UNSET)
electric field momentum contribution due to jfluid.
E_momj == -1 * me ne nu_ej * (uj - ue) / (ne qe)
[EFF] for efficiency, can provide u_e if already known. (provide as _u_e)
(only used if _u_e.coords[‘component’] has the exact same values as self.component.)
get_E_terms()
xarray Dataset of the terms which contribute to E.
Dataset with ‘E_uxB’, ‘E_bat’, and ‘E_mom’ as data vars.
Suggestion: to quickly determine which E_terms are most important, consider using, e.g.:
self(‘mod_E_terms’).pc.stats(keep=’variable’) # for mod across all components
self(‘E_terms’, component=0).pc.stats(keep=’variable’) # for just component 0
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_E_uxB(*, _u_e=UNSET)
electric field u x B contribution. E_uxB == -1 * u_electron cross B
[EFF] for efficiency, can provide full u_e, if already known. (provide as _u_e)
(requires full ue, not just one component, since will do ue cross B.)
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, where
Eheat_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 == J_B + J_ext == curl(B) / mu0 + J_imposed.
get_JBspeed()
speed determined from J perp to B, and ne: |J_perp to B| / (ne * |qe|).
get_J_B()
current density from magnetic field (ignoring J_ext). J_B = curl(B) / mu0.
get_J_ext()
imposed current density; see ic_ix, ic_iy, ic_iz from Ebysus.
get_J_helita()
current density. (directly from Ebysus)
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. (directly from Ebysus).
“maxwellian” temperature (classical T in thermodynamics).
get_T_box()
temperature of the entire simulation box, as if full of particles,
and observed by something that could not resolve the individual cells.
Ignores Ta components for directions in which the box has no extent.
(E.g. 512x512x1 box –> ignore Tz.)
See self.help(‘rmscomps_nmean_Ta_global’) for more details.
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_global(var, *, _match=None)
quantity whose density-weighted mean is the global temperature,
when all particles across the box are considered, as if the system had particles in it.
Tjoule –> result will be in energy units.
T (not Ta) –> take rms of components of result, e.g. sqrt((Tx^2 + Ty^2 + Tz^2) / 3)
Tajoule_global = m * (vsqr - (nmean_u)^2)
== kB Ta + m*u^2 - m*(nmean_u)^2
Note that nmean(Ta_global) does NOT equal nmean(Ta). Instead:
nmean(kB Ta_global) = nmean(kB Ta) + m*nmean(u^2) - m*(nmean_u)^2
“DERIVATION” / EXPLANATION:
kB Ta = m * <(v - u)^2>, where u = <v>.
Simplifying yields kB Ta == m * (<v^2> - 2<v>u + u^2) == m * (<v^2> - u^2).
Note that taking an average across all particles is equivalent to a
density-weighted average across all cells, as density scales with number of particles.
(This doesn’t apply directly to T because particles don’t have individual values of T,
but it does apply to <v^2> and <v> because particles do have individual values of v.)
Using the equation above to infer T across all particles:
kB nmean_Ta_global = m * <v^2> - <v>^2,
where <v^2> are the means of cell values, taken across all particles:
–> kB nmean_Ta_global = m * (nmean(<v^2>_cell) - (nmean_u)^2)
Ta_global is defined as the quantity whose nmean satisfies the relationship above. i.e.:
kB Ta_global = m * <v^2>_cell - nmean_u^2
As described in get_vsqr, we can also infer <v^2> within a cell:
<v^2>_cell = (kB Ta_cell / m) + u_cell^2
If desired, these can be combined, to see:
kB Ta_global = kB Ta + m * (u_cell^2 - nmean_u^2)
get_T_global_correction(var, *, _match=None)
m*(u^2 - (nmean_u)^2) / kB
Ta_global_correction + Ta == Ta_global.
if Tajoule, don’t divide by kB (answer will be in energy units).
it T (not Ta), take rms of components.
see self.help(‘T_global’) for more detailed explanation.
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_T_sj(*, _m_s=UNSET, _T_s=UNSET, _m_j=UNSET, _T_j=UNSET)
mass-weighted temperature. T_sj = (m_s * T_j + m_j * T_s) / (m_s + m_j).
s = self.fluid; j = self.jfluid.
[EFF] for efficiency, can provide any of m_s, T_s, m_j, T_j, if already known.
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) Bhat | Also 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) Bhat | Also 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__nusj_singlej(*, collision_type)
_nusj_singlej = collision frequency between self.fluid and a single jfluid.
Implementation detail… may be removed later. Use self(‘nusj’) instead.
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_collision_type()
Similar to super().get_collision_type, but also allows ‘helita’ <–> do ‘helita’ collisions.
super().get_collision_type docs copied here for reference:
———————————————————-
<function CollisionsLoader.get_collision_type at 0x7d58e5bd4c10>
get_collisions_cross_section()
cross section between self.fluid and self.jfluid.
interpolates on self.collisions_cross_mapping based on mass-weighted temperature;
cross_table = collisions_cross_mapping[(fluid, jfluid)]
T_sj = (m_j * T_s + m_s * T_j) / (m_j + m_s)
result_si = cross_table(T_sj, input=’T’, output=’cross_si’)
result = result_si * self.u(‘area’) # convert to self.units unit system.
if collisions_cross_mapping[(fluid, jfluid)] is not found:
either return 0 (as an xarray), or raise QuantInfoMissingError,
depending on self.collisions_mode. see help(type(self).collisions_mode) for details.
get_collisions_crosstab(fluid1, fluid2, *, crossmap=None)
roughly, returns self.collisions_cross_mapping[(fluid1, fluid2)],
but, this is more convenient, because:
- fluid1 and fluid2 can be provided in shorthand.
can provide them as Fluid objects, ints, or strs.
crossmap: None or CrossMapping
if provided, get value from crossmap instead of from self.collisions_cross_mapping.
get_collisions_crosstab_default_fluids()
return dict of fluids from self which have any corresponding CROSS_TABLE_DEFAULTS.
keys will be e, H_I, H_II, He_I, He_II, He_III.
values will be Fluid objects (from self.fluids or self.jfluids)
checks multiple possible shorthand notations for each fluid:

e : fluids.get_electron(), jfluids.get_electron() H_I : ‘H_I’, ‘H I’, ‘H’ H_II : ‘H_II’, ‘H II’, ‘H+’ He_I : ‘He_I’, ‘He I’, ‘He’ He_II : ‘He_II’, ‘He II’, ‘He+’ He_III: ‘He_III’, ‘He III’, ‘He++’

if multiple matches found in any case, raise FluidValueError.
subclass could implement more sophisticated matching if needed;
the implementation here aims to be flexible, but crash if anything is ambiguous.
note: possible shorthands defined by self._COLLISIONS_CROSSTAB_DEFAULT_FLUIDS_ALIASES;
subclass might override that instead of this method, if just needing to alter shorthands.
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_coulomb_logarithm()
Coulomb logarithm, ln(Lambda). Used in coulomb collisions.
result = ln(Lambda) = 23.0 + 1.5 ln(Te [K] / 10^6) - 0.5 ln(ne [m^-3] / 10^12)
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_s
For 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_delta_sj()
kronecker delta function between self.fluid and self.jfluid.
1 where self.fluid == self.jfluid; 0 otherwise.
Useful e.g. to avoid counting collisions between the same species.
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]. Depends on self.component.
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.
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_init_fluids()
return dict of fluids, fluid, jfluids, jfluid for setting those attrs of self.
get_init_snaps()
return dict of snaps, snap for setting self.snaps & self.snap.
get_int(var, *, _match=None)
any integer, as an xarray.
get_ionnefrac()
ratio of n_ions / ne. Equivalent: self(‘nnefrac’, fluid=self.fluids.ions()).
get_ionnefrac_significant()
boolean array telling whether n_ions/ne >= self.nnefrac_tiny_thresh.

Equivalent: self(‘not_ionnefrac_tiny’)

get_ionnefrac_tiny()
boolean array telling whether n_ions/ne < self.nnefrac_tiny_thresh
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.
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_m_sj(*, _m_s=UNSET, _m_j=UNSET)
weighted mass. m_sj = m_s * m_j / (m_s + m_j).
s = self.fluid; j = self.jfluid.
[EFF] for efficiency, can provide m_s and/or m_j, if already known.
get_maindims_coords()
return dict of {‘x’: xcoords, ‘y’: ycoords, ‘z’: zcoords}, in dd.units_output units.
coords will be sliced according to self.slices.
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. n = (r / m) = (mass density / mass)
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_neutral(var=None, *args__get, **kw__get)
returns self(var), but for the neutral fluid.
if var is None, instead returns the neutral fluid itself.
if there is exactly 1 neutral fluid in self.fluids, returns self(var, fluid=neutral_fluid).
otherwise, if there is exactly 1 in self.jfluids, returns self.getj(var, jfluid=neutral_fluid).
otherwise (0 or 2+ neutral fluids), crash:
if 0 neutral fluids anywhere, raise FluidKeyError.
if 2+ neutral fluids, raise FluidValueError.
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_nnefrac()
ratio of number density to electron number density: n / ne.
get_nnefrac_significant()
boolean array telling whether n/ne >= self.nnefrac_tiny_thresh.

Equivalent: self(‘not_nnefrac_tiny’)

get_nnefrac_tiny()
boolean array telling whether n/ne < self.nnefrac_tiny_thresh
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.
“frequency for one particle of s (self.fluid) to collide with any of j (self.jfluid).”
Uses the appropriate formula based on self.collisions_mode, and self.fluid & self.jfluid.
get_nusj_coulomb()
coulomb collision frequency.
“frequency for one particle of s (self.fluid) to collide with any of j (self.jfluid).”
This is a good model for nusj when:
- s & j are both charged species.
nusj_coulomb = (1 Hz) * (1.7/20) * (ln(Lambda))
* (m_p/m_s) * (m_sj/m_p)^(1/2)
* (T_sj / Kelvin)^(-3/2)
* (q_s/q_e)^2 * (q_j/q_e)^2
* (n_j / (10^6 meters^-3)), where:
ln(Lambda) = Coulomb logarithm (see self.help(‘coulomb_logarithm’) for details)
n_j = number density of j (self.jfluid).
m_sj = weighted mass = m_s * m_j / (m_s + m_j)
T_sj = mass-weighted temperature = (m_s * T_j + m_j * T_s) / (m_s + m_j)
m_p = mass of proton
q_e = charge of electron
m_s, m_j = mass of s, j
T_s, T_j = temperature of s, j.
q_s, q_j = charge of s, j
get_nusj_fromtable()
collision frequency from a table.
“frequency for one particle of s (self.fluid) to collide with any of j (self.jfluid).”
Requires that the relevant CrossTable(s) are provided, in self.collisions_cross_mapping.
nusj_fromtable = n_j * (m_j / (m_s + m_j)) * C(T_sj) * sqrt(8 * kB * T_sj / (pi * m_sj)), where:
n_j = number density of j (self.jfluid)
m_sj = weighted mass = m_s * m_j / (m_s + m_j)
T_sj = mass-weighted temperature = (m_s * T_j + m_j * T_s) / (m_s + m_j)
m_s, m_j = mass of s, j
T_s, T_j = temperature of s, j
C(T_sj) = collisions_cross_section between s & j at temperature T_sj
kB = Boltzmann constant
get_nusj_helita()
collision frequency. (directly from Ebysus)
for a single particle of s (self.fluid) to collide with any of j (self.jfluid).
get_nusj_maxwell()
maxwell collision frequency.
“frequency for one particle of s (self.fluid) to collide with any of j (self.jfluid).”
This is a good model for nusj when:
- s or j is neutral hydrogen.
(assumed by the implementation here; could be improved in the future)
- the charged species is a heavy ion.
(collisions between [e-,H] and [H+,H] behave differently.)
nusj_maxwell = (1 Hz) * (1.95856) * n_j * sqrt(
(alpha_n * q_e^2 / eps0) * (m_j / (m_s * (m_s + m_j)))
), where:
n_j = number density of j [si units, i.e. meters^-3]
alpha_n = polarizability of neutral hydrogen. [si units, i.e. meters^3]
q_e = charge of electron. [si units, i.e. C]
eps0 = permittivity of free space; standard definition for eps0. [si units]
m_s, m_j = mass of s, j. [si units, i.e. kg]
(formula from Oppenheim+2020, Appendix A.)
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 via
skappa = 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. (directly from Ebysus)
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_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. (directly from Ebysus)
get_r()
mass density. (directly from Ebysus)
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) = 0
From 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|**2
solving 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.
property get_space_coords
alias to get_maindims_coords
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_sum_fluid_var(var, *, _match=None)
var summed across self.fluid. Equivalent: self(var).pc.sum(‘fluid’).
(if not self.fluid_is_iterable(), result numerically equivalent to self(var).)

aliases: sum_fluid_var or sum_s_var.

get_sum_fluids_var(var, *, _match=None)
var summed across self.fluids. Equivalent: self(var, fluid=None).pc.sum(‘fluid’).
get_sum_ions_var(var, *, _match=None)
var summed across all ions in self.fluids.

Equivalent: self(var, fluid=self.fluids.ions()).pc.sum(‘fluid’).

get_sum_jfluid_var(var, *, _match=None)
var summed across self.jfluid. Equivalent: self(var).pc.sum(‘jfluid’).
(if not self.jfluid_is_iterable(), result numerically equivalent to self(var).)

aliases: sum_jfluid_var or sum_j_var.

get_sum_jfluids_var(var, *, _match=None)
var summed across self.jfluids. Equivalent: self(var, jfluid=None).pc.sum(‘jfluid’).
get_sum_neutrals_var(var, *, _match=None)
var summed across all neutrals in self.fluids.

Equivalent: self(var, fluid=self.fluids.neutrals()).pc.sum(‘fluid’).

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 only
self(‘timescales’).min(‘fluid’) # minimum timescales across all fluids
self(‘timescales’).pc.minimum() # minimum timescale across all timescales

equivalent: 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. u = p / r = (momentum density / mass density)
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_vsqr()
Average particle v^2 amongst all particles in each grid cell,
as if the grid cell had particles in it (i.e., can be inferred even for fluid models).
vsqr = (kB Ta / m) + u^2
Ta = anisotropic temperatures. For Ebysus, use Ta == T.
Inferred from temperature & velocity in cell:
kB Ta = m * <(v - u)^2>, where u = <v>. This is the definition of Ta.
Here, the averaging is taken across many particles.
(T within a grid cell includes only the particles in the cell;
“global” T across many cells includes all particles in all those cells.)
Simplifying yields kB Ta == m * (<v^2> - 2<v>u + u^2) == m * (<v^2> - u^2).
Thus, it is possible to infer <v^2> within a cell from T aand u in that cell:
<v^2>_cell = (kB Ta_cell / m) + u_cell^2
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 / B
mean(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 * B
mean(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” for self.fluid. 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 when 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.
getj(var, *args__get, jfluid=UNSET, **kw__get)
returns self(var), but for jfluid instead of fluid.
jfluid: UNSET, None, or any jfluid specifier.
if provided, use this instead of self.jfluid.
Example:
m_s = self(‘m’)
with self.using(fluids=self.jfluids, fluid=self.jfluid):
m_j_0 = self(‘m’)
m_j_1 = self.getj(‘m’)
here, the values stored in the variables will be:
m_s = mass of self.fluid
m_j_0 = mass of self.jfluid. But, fluid dimension will be labeled ‘fluid’
m_j_1 = mass of self.jfluid. fluid dimension will be labeled ‘jfluid’.
additional args and kwargs are passed to self(var)
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
None –> get help with all quantities related to qstr.
‘VARS’ or ‘vars’ –> only get help with KNOWN_VARS.
‘PATTERNS’ or ‘patterns’ –> only get help with KNOWN_PATTERNS.
‘TREE’ or ‘tree’ –> only get help with quantities in cls.cls_var_tree(str).
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
None –> get help with all quantities related to qstr.
‘VARS’ or ‘vars’ –> only get help with KNOWN_VARS.
‘PATTERNS’ or ‘patterns’ –> only get help with KNOWN_PATTERNS.
‘TREE’ or ‘tree’ –> only get help with quantities in cls.cls_var_tree(str).
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 dim must 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 iter_fluid
alias to self.fluid_dim.iter
property iter_fluids
alias to self.fluid_dim.iter_values
property iter_fluids_partition
alias to self.fluid_dim.iter_partition
property iter_jfluid
alias to self.jfluid_dim.iter
property iter_jfluids
alias to self.jfluid_dim.iter_values
property iter_jfluids_partition
alias to self.jfluid_dim.iter_partition
property iter_snap
alias to self.snap_dim.iter
property iter_snaps
alias to self.snap_dim.iter_values
property iter_snaps_partition
alias to self.snap_dim.iter_partition
property jfluid
alias to self.jfluid_dim.v
property jfluid_dim
jfluid dimension for jFluidHaver.
jfluid_dim_cls

alias of jFluidDimension

property jfluid_is_iterable
alias to self.jfluid_dim.is_iterable
property jfluid_list
alias to self.jfluid_dim.list
property jfluid_type
alias to self.jfluid_dim.get_type
property jfluids
alias to self.jfluid_dim.values
property join_components
alias to self.component_dim.join_along
property join_fluids
alias to self.fluid_dim.join_along
property join_jfluids
alias to self.jfluid_dim.join_along
property join_snaps
alias to self.snap_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, then
internally 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_FREQ
elf.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”, either from a file or from self.direct_overrides.
first, add dimensions to var if appropriate, based on the currently-loading dimension(s).
E.g. ‘b’ turns into ‘bzc’ when loading ‘z’ component.
If there is is an override for that var, use it; otherwise load from file.
load_fromfile(ebysus_var, *args, **kw)
load ebysus_var directly from self.dd.
ebysus_var: str
the name of the variable to read. Should include all dimensions as appropriate.
E.g., use ‘bzc’, not ‘b’, to get magnetic field z component.
End-user should not need to worry about this function;
it’s mainly here for connecting the ebysus base vars for PlasmaCalcs appropriately.
load_maindims_var(var, *args, u=None, assign_labels=True, **kw)
return var, formatted as an xarray with proper details for PlasmaCalcs.
loading var should give an array with self.maindims as dimensions.
Also does these steps:
1) assign maindims coords via self.assign_maindims_coords().
2) slice array via self.slices.
3) convert units, if u is not None
4) set result.attrs[‘units’] = self.units
5) if self.maindims_means: take mean of result, across all maindims.
6) use result = self._maindims_postprocess_callback(result), if possible.
u: None, value, or str
units factor for the result.
None –> don’t do any units conversions.
str –> multiply result by self.u(u)
value –> multiply result by u
assign_labels: bool
whether to assign_maindims_coords and self.record_units.
Recommend to always use True, unless using this function internally.
(e.g. for load_maindims_var_across_dims, only use the first time, for efficiency.)
IGNORED if self.maindims_means.
Note:
If load_direct(var) uses an override or gets from cache or self.setvars,
skip steps 1,2,3,4
([TODO] Might need to reconsider this behavior?)
Note:
If self.multi_slices are provided, load_maindims_var for each slice,
then combine results into an xarray.Dataset.
if assign_labels=False, combine results into a dict instead.
load_maindims_var_across_dims(var, dims=None, *, skip=[], u=None, **kw)
load maindims var across these dims. Use all dims from self.dimensions if dims is None.
Only loads across the current value of these dims (e.g., self.fluid, not self.fluids).
(Can set current value to multiple values e.g. self.component = (‘x’, ‘y’).)
u: None, value, or str
units factor for the result.
None –> don’t do any units conversions.
str –> multiply result by self.u(u)
value –> multiply result by u
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: bool
whether 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 maindims_full_shape
self.maindims_shape when self.slices=None
property maindims_full_size
self.maindims_size when self.slices=None
property maindims_full_sizes
self.maindims_sizes when self.slices=None
property maindims_means
whether to immediately take means across maindims when loading arrays. (default False.)
True –> treat data across maindims as if it were the mean values, only.

Caution: this is different from taking means after doing calculations;

e.g., with maindims_means = True, ‘n*T’ –> mean(n)*mean(T), not mean(n*T).
property maindims_shape
tuple of (len(self.get_maindims_coords()[dim]) for dim in self.maindims).
Note, this should be sensitive to changes in self.slices. See also: self.maindims_full_shape.
property maindims_size
product of terms in self.maindims_shape.
Note, this should be sensitive to changes in self.slices. See also: self.maindims_full_size.
property maindims_sizes
dict of {dim: size of dim} for dim in self.maindims.
Note, this should be sensitive to changes in self.slices. See also: self.maindims_full_sizes.
maindims_with_extent()
return tuple of maindims with length > 1.
ebysus output is all technically 3D but some dims might have length 1 for 2D simulation.
It can be convenient to know which dims have extent / which do not.
maindims_with_no_extent()
return tuple of maindims with length == 1.
ebysus output is all technically 3D but some dims might have length 1 for 2D simulation.
It can be convenient to know which dims have extent / which do not.
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.
match_dd_dims()
matches self.snap, fluid, and jfluid to self.dd.snap, ifluid, and jfluid.
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 multi_slices
dict of {key: slices dict}.
When getting any vars across maindims, make a Dataset by applying each of these, separately.
If len(multi_slices)>0 then ignore self.slices.
Can also provide special keys ‘ndim’ and/or ‘ikeep’ to create special slices:
Example: if self.maindims=[‘x’, ‘y’, ‘z’], then self.multi_slices = dict(ndim=2, ikeep=0)
is equivalent to: self.multi_slices = dict(x_y=dict(z=0), x_z=dict(y=0), y_z=dict(x=0))
Details:

ndim: None or int

None –> ignore, and do not create special slices.
int –> create special slices to keep this many dims after applying each slice.
Example: MultiSlices(ndim=2) is shorthand for
“MultiSlices with one slices for every possible combination of keeping 2 dims”.
Example: MultiSlices(ndim=2, dims=[‘x’, ‘y’, ‘z’], ikeep=0) is equivalent to:
MultiSlices(keep_x_y=dict(z=0), keep_y_z=dict(x=0), keep_x_z=dict(y=0))
Example: MultiSlices(ndim=1, dims=[‘x’, ‘y’, ‘z’], ikeep=0) is equivalent to:
MultiSlices(keep_x=dict(y=0, z=0), keep_y=dict(x=0, z=0), keep_z=dict(x=0, y=0))

ikeep: int or number between -1 < ikeep < 1

index to take when picking a single value for sliced dimensions for special slices.
Default is 0, e.g. when slicing x, keep x[0].
int –> when slicing dim, keep dim[ikeep]. E.g. 10 –> keep x[10]
non-int between -1 and 1 –> multiply by length of dim to get index.
see interprets_fractional_indexing for more details.
Can also set these as attributes of self.multi_slices to achieve the same effect.
E.g. self.multi_slices.ndim = 2
property multi_slices_ikeep
int or number between -1 < ikeep < 1
index to take when picking a single value for sliced dimensions for special slices.
Default is 0, e.g. when slicing x, keep x[0].
int –> when slicing dim, keep dim[ikeep]. E.g. 10 –> keep x[10]
non-int between -1 and 1 –> multiply by length of dim to get index.
see interprets_fractional_indexing for more details.
property multi_slices_ndim
None or int
None –> ignore, and do not create special slices.
int –> create special slices to keep this many dims after applying each slice.
Example: MultiSlices(ndim=2) is shorthand for
“MultiSlices with one slices for every possible combination of keeping 2 dims”.
Example: MultiSlices(ndim=2, dims=[‘x’, ‘y’, ‘z’], ikeep=0) is equivalent to:
MultiSlices(keep_x_y=dict(z=0), keep_y_z=dict(x=0), keep_x_z=dict(y=0))
Example: MultiSlices(ndim=1, dims=[‘x’, ‘y’, ‘z’], ikeep=0) is equivalent to:
MultiSlices(keep_x=dict(y=0, z=0), keep_y=dict(x=0, z=0), keep_z=dict(x=0, y=0))
n_existing_snaps()
returns number of existing snaps. Equivalent to self.snap_dim.n_existing_for(self).
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 nnefrac_tiny_thresh
threshhold for where_nnefrac_tiny and where_nnefrac_significant.
tiny if n/ne < nnefrac_tiny_thresh, significant if n/ne >= nnefrac_tiny_thresh.
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 results
True –> 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_window
None –> 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 –> -1
True or (>=1 and <5) –> None
>=5 –> 0 (i.e. print every progress update)
if self.verbose doesn’t exist –> None
if 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.
quant_tree_cls

alias of QuantTree

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_collisions_crosstab(fluid1, fluid2, crosstab, *, crossmap=None)
roughly, does self.collisions_cross_mapping[(fluid1, fluid2)] = crosstab,
but this is a bit more convenient since it allows more shorthand options (see below)
fluid1, fluid2: int, str, or Fluid
the fluids to set the crosstab for.
Fluid –> use the provided value.
int or str –> infer the Fluid based on self.fluids.
crosstab: None, str, or CrossTable
None –> del self.collisions_cross_mapping[(fluid1, fluid2)], if possible.
else –> self.collisions_cross_mapping[(fluid1, fluid2)] = crosstab.
– CrossTable –> will use the provided value.
– str –> will use the CrossTable corresponding to this filename or key,
key from self.CROSS_TABLE_DEFAULTS.
Note: self.collisions_cross_mapping.smart=False can disable this.
crossmap: None or CrossMapping
if provided, set value in crossmap instead of in self.collisions_cross_mapping.
Example, these are all equivalent, if fluids[0]==’e’ and fluids[1]==’H II’:
self.set_collisions_crosstab(‘e’, ‘H II’, ‘e-h’)
self.set_collisions_crosstab(0, 1, ‘e-h-cross.txt’)
self.set_collisions_crosstab(self.fluids.get(‘e’), self.fluids.get(‘H II’),
CrossTable.from_file(‘e-h-cross.txt’))
self.collisions_cross_mapping[(self.fluids.get(0), self.fluids.get(1))] = ‘e-h’
set_collisions_crosstab_defaults(mode='bruno', *, crossmap=None)
set CROSS_TABLE_DEFAULTS cross sections for all relevant fluids in self.
e.g. if self has fluids e, H_I, H_II, He_II, would set:
crossmap[e, H_I] = ‘e-h’
crossmap[H_II, H_I] = ‘h-p’
crossmap[He_II, H_I] = ‘h-he’
crossmap[H_I, H_I] = ‘h-h’
if self has more relevant fluids, would set more crossmaps too.
see self.CROSS_TABLE_DEFAULTS for list of available defaults.
(note that order of keys doesn’t matter for crossmap since it’s a SymmetricPairMapping.)
mode: ‘bruno’ or ‘vranjes’
tells which defaults to use. (bruno is probably more accurate than vranjes.)
crossmap: None or CrossMapping
if provided, set values in crossmap instead of in self.collisions_cross_mapping.
gets relevant fluids from self.get_collisions_crosstab_default_fluids;
subclass may wish to override that method.
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.
slice_maindims(array, **kw_xarray_isel)
slice maindims of array using self.slices. See help(type(self).slices) for more details.
(if slices is an empty dict, return array, unchanged, without making a copy.)
Only slice dims which actually appear in array.
property slices
slices for maindims when loading arrays & during get_maindims_coords.
E.g. slices = dict(x=slice(0,50), y=7)
–> slice arrays along x & y, taking the first 50 x values, and only the 7th y value.
Notes:
- only applies slices along arrays which actually contain the related coordinates,
e.g. if z=10 appears in slice but loading an array with only x & y, won’t apply z=10 slice.
- supports fractional indexing, as per interprets_fractional_indexing.
Non-integer values between -1 and 1 can be used to infer to a fraction of the dimension length,
with negative values referring to a distance from the end, just like with integer indexing.
Example: dict(x=slice(-0.3, None, 0.01), y=0.8), where x and y each have length 1000
–> equivalent to dict(x=slice(-300, None, 10), y=800).
if self.slicing is False, self.slices will give an empty dict and cannot be set to any value!
however, the old value of self.slices will be remembered in case slicing is set to True later.
slicestr(*, sep=', ', keep_None=False)
string representation of self.slices, for use in filenames, titles, etc.
comma-separated, alphabetized, ignoring slice(None).
Supports single-indexes (e.g. x=5), slices (e.g. y=slice(0, 4)),
and fractional indexing (e.g. z=slice(0, 0.5, 0.01)),
though fractional indexing will be converted to ints.

sep: str, separator between slices keep_None: bool, whether to keep slices with value None in the string.

property slicing
whether to slice maindims when loading arrays & during get_maindims_coords.
if False, self.slices will return an empty dict.
property snap
alias to self.snap_dim.v
property snap_dim
snap dimension for SnapHaver.
snap_dim_cls

alias of SnapDimension

snap_filepath(snap=None)
convert snap to full file path for this snap. Subclass should implement.
snap: None, str, in, or Snap
the snapshot to load. if None, use self.snap.
property snap_is_iterable
alias to self.snap_dim.is_iterable
property snap_list
alias to self.snap_dim.list
property snap_type
alias to self.snap_dim.get_type
property snapdir
directory containing the snapshot files. Subclass should implement.
property snaps
alias to self.snap_dim.values
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 cache implies 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}.pcxarr
where 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)
standardized_slices()
returns a copy of self.slices, but calling interprets_fractional_indexing on all slices,
using lengths from self.maindims_full_sizes.
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
property take_fluid
alias to self.fluid_dim.take
property take_fluids
alias to self.fluid_dim.take_along
property take_jfluid
alias to self.jfluid_dim.take
property take_jfluids
alias to self.jfluid_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 take_snap
alias to self.snap_dim.take
property take_snaps
alias to self.snap_dim.take_along
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 pc
cc = pc.PlasmaCalculator(…) # <– your PlasmaCalculator of choice
solver = 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 tt
import PlasmaCalcs as pc
cc = … # 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.TfbiDisprelC
str –> 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 title
title to help distinguish this calculator from others.
E.g. might want to add self.title to plots. Default: os.path.basename(self.dirname).
title_with_slices(*, sep=', ', keep_None=False)
return self.title with slicestr appended (after sep), if slicestr is not empty.
see self.slicestr() for more details.
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
units, but also set dd.units_output when setting.
UNITS note: right now, units is fully managed by dd;
self.u(conversion) will always be 1 (e.g. self.u(‘l’) == self.u(‘m’) == … == 1);
self.units == ‘si’ –> dd.units_output == ‘si’;
self.units == ‘raw’ –> dd.units_output == ‘simu’.
units_meta()
return dict(units=self.units). Also include coords_units if different.
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