MuramCalculator
- class PlasmaCalcs.hookups.muram.muram_calculator.MuramCalculator(*, dir='.', units='si', **kw_super)
Bases:
MuramEosLoader,MuramBasesLoader,MuramDirectLoader,MhdCalculatorPlasmaCalculator for Muram outputs.
dir: str
directory where files are located. Stored as self.dirname = os.path.abspath(dir).units: ‘si’ or ‘raw’units system for outputs of self. ‘raw’ for same as muram data, ‘si’ for SI units.‘cgs’ for cgs, but note cgs electromagnetic quantities are not yet implemented.Implementation here assumes Muram outputs are always in cgs, and that mu0_raw = 1;i.e. MhdUnitsManager.from_mhd_cgs(ucgs_l=1, ucgs_t=1, ucgs_r=1, mu0_raw=1)Methods
__call__(var, *args[, name, item, verbose])returns value of var from self.
__getitem__(snapi)sets self.snap, then returns self.
return state for pickling.
__init_subclass__(*[, dimension, dim_plural])called when subclassing DimensionHaver; sets some useful attributes related to dimension.
__iter__()equivalent to self.iter_snaps()
__len__()equivalent to len(self.snaps)
__setstate__(state)set state for pickling.
__setup_haver__(dim_cls, **kw_super)called by dim_cls.setup_haver(cls) when setting up cls so that it "has" dim_cls dimension.
angle_xy(A)return angle between +xhat and A, in the xy plane, in radians.
return unit vector u, given angle [radians] between +xhat and u in the xy plane.
apply_mask(arr[, masking])apply self.mask to arr, using self.masking to determine masking.
as_single_dimpoint([values, dims])return DimPoint with values for dims, but raise DimensionValueError if any value is_iterable_dim.
assert_single_fluid_mode([varname, mode])asserts that self is in single fluid mode; else crash.
assign_dim_coords(array, *dims[, skip])assign all dimensions in self as coords for array.
assign_maindims_coords(array)assign maindims dims and coords, based on self.get_maindims_coords() with slices=None.
attach_extra_coords(arr)attach any self.extra_coords to array arr but only if it is an xarray.DataArray or xarray.Dataset
check_pickle([x])checks that self (or, x, if provided) is pickleable, by pickling then unpickling.
chunker()gets Chunker based on the current values of self.chunks and self.slices.
cls_help([qstr, only, tree, modules, ...])prints str for help with quants.
cls_var_tree(var, *[, missing_ok])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
copy()returns a deep copy of self.
cross_component(A, B, x, *[, yz, missing_ok])return x component of A cross B, given A and B which have values for y and z 'component'.
return the components vectors need in order to find all cross product components in self.component_list
cross_product(A, B, *[, components])return cross product of vectors A and B, along dimension 'component'.
curl_component(v, x, *[, yz])return x component of curl(v).
current_n_dimpoints([dims])return number of points represented by current values of dims.
returns number of existing snaps, out of all snaps at self.snap.
dim_values([dims])return dict of current values for dimensions in self.
dims_apply(funcname, *args_func[, dims])apply funcname to each dimension in self, with args_func and kw_func.
dims_get(attr[, dims])return dict of {dim: getattr(self.dimensions[dim], attr) for dim in dims}.
directly_loadable_vars([snap])return tuple of directly loadable variables for this snap.
divergence(array[, components, _post_slices])return divergence of array.
dot_product(A, B)return dot product of vectors A and B, assuming vector components in the 'component' dimension.
enumerate_dimpoints([dims, all])iterate through values of dims, yielding (idx, DimPoint) pairs.
return list of existing snaps.
fftN(array[, dim, ds, slices])xarray_fftN with defaults for dim & slices determined by self.fft_dims, self.fft_slices.
fft_dims_for(array)return the dims over which to apply fft for this array.
gaussian_filter(array[, dim, sigma])xarray_gaussian_filter with defaults from self.blur_dims, self.blur_sigma.
get_0()0, as an xarray.
get_1()1, as an xarray.
get_B()magnetic field.
magnetic tension = (B dot grad) B / mu_0.
get_E()electric field.
get_E0S1(*[, _skappa, _E0n0])E0S1 = sum_s E0S1s, where E0S1s = (qs ns skappa_s / (1 + skappa_s^2)),
dataset containing 'E0S1' and 'E0S2'.
get_E0S1s(*[, _skappa, _E0n0])E0S1s = qs ns skappa_s / (1 + skappa_s^2).
get_E0S2(*[, _skappa, _E0n0])E0S2 = sum_s E0S2s, where E0S2s = (qs ns skappa_s^2/ (1 + skappa_s^2)),
get_E0S2s(*[, _skappa, _E0n0])E0S2s = qs ns skappa_s^2/ (1 + skappa_s^2).
get_E0_etaJ_perpB(*[, _E0S1, _E0S2])E0_perp_B = E0_etaJ_perpB + ..., where E0_etaJ_perpB = eta0_J * J_perp_B.
get_E0_hall(*[, _E0S1, _E0S2])E0_perp_B = E0_hall + ..., where E0_hall = eta0_hall * J x Bhat.
E0_un0_perpB = E0_etaJ_perpB + E0_hall
E0_un0_perpmodB = |E0_un0_perpB|.
E0_un0_perpmodB_min = minimum possible value of |E0_un0_perpB|, at each point.
E0_un0_perpmodB_simple = simple estimate of |E0_un0_perpB|, at each point.
get_E0n0(*, E0n0type)n0 for E0 calculations.
n type for E0 calculations.
speed determined from E_un0 and B: |E_un0 perp to B| / |B|.
E_un0 = electric field in the neutral frame, where u_n=0.
get_E_un0_perpmod_B(**kw_perpmod)E_un0_perpmod_B == |E_un0 perp to B| == magnitude of E, perp to B, in u_neutral=0 frame.
string telling method that will be used to get E_un0.
Eheat = Eheat_perp + Eheat_par.
get_Eheat_par(*[, _E_un0, _B, _Eheat_par_coeff])Eheat_par = Eheat_par_coeff * |E_par|^2.
Eheat_par = Eheat_par_coeff * |E_par|^2.
get_Eheat_perp(*[, _E_un0, _B, _Eheat_par_coeff])Eheat_perp = Eheat_perp_coeff * |E_perp|^2.
get_Eheat_perp_coeff(*[, _Eheat_par_coeff])Eheat_perp = Eheat_perp_coeff * |E_perp|^2.
zeroth order rate of heating of neutrals due to collisions with all charged species.
zeroth order rate of heating of neutrals due to collisions with s (self.fluid).
get_Epar()electric field, parallel to B.
electric field, perpendicular to B.
Lorentz force = q(E + u x B).
get_Gofnt(var, *[, _match])G(T,ne) from ChiantiPy and muse library for a given ion.
get_Gofnt_atmos(var, *[, _match])Interpolated G(T) with temperature, for a given ion.
get_Gofnt_em(var, *[, _match])Emission * G(T) for a given ion.
get_Gofnt_em_interp(var, *[, _match])Emission * G(T) for a given ion.
get_Gofnt_em_nointerp(var, *[, _match])Emission * G(T) for a given ion.
get_J()current density (without displacement current).
speed determined from J perp to B, and ne: |J_perp to B| / (ne * |qe|).
get_Jf()current density (associated with fluid).
get_P()Temperature.
pressure, from 'eosP' file.
pressure, from plugging r and e into eos tables (see self.tabin).
pressure (from ideal gas law?) P = (gamma - 1) * e
get_T()Temperature.
temperature, from 'eosT' file.
T_from_Eheat = T_n + Eheat.
T_from_Eheat_perp = T_n + Eheat_perp.
temperature, from plugging r and e into eos tables (see self.tabin).
temperature, assuming ideal gas law.
temperature of neutrals; T_n = T of SINGLE_FLUID.
get_Tapar(var, *[, _match])Tapar --> anisotropic temperature, parallel to B.
get_Taperp(var, *[, _match])Taperp --> anisotropic temperature, perpendicular to B.
temperature ("isotropic/maxwellian"), in energy units.
get__vdem_ignores_photosphere_var(var, *[, ...])_vdem_ignore_photosphere_var --> self(var) but possibly setting values at z<0 to 0,
get_abs(var, *[, _match])absolute value.
|electron charge|, in [self.units] units.
Absorption coefficient at wavelength=self.rcoords_wavelength_A,
get_amu()1 atomic mass unit, in [self.units] units.
get_angle_xy(var, *[, _match, _val0])angle between +xhat and var, in the xy plane, in radians.
get_angle_xy_to_hat(var, *[, _match, _val0])unit vector u, given angle [radians] between +xhat and u in the xy plane.
get_astats(var, *[, _match])return dataarray of stats for var, reporting stats along new dim: 'stat'.
get_behavior([keys])return value of self.behavior.
largest power of 2 subcycling allowed for each fluid in self.fluid.
largest subcycling allowed: best_subcycle = min_timescale / minf_timescale.
get_beta()plasma beta.
get_blur(var, *[, _match])gaussian_filter(var).
get_blurk(var, *[, _match])gaussian_filter(var), temporarily using self.blur_dims = ['k_x', 'k_y', 'k_z']
get_blurt(var, *[, _match])gaussian_filter(var), temporarily using self.blur_dims = ['snap']
{i} --> self(mem_var), where mem_var = self.parenthesis_memory_key_to_var[int(i)].
get_cache_var(var, *[, _match])get var, then save to cache.
return a previously-computed tfbi solution across EBspeed grid.
get_cached_var(var, *[, _match])get var from folder within self.cache_dirname.
get_caches_var(var, *[, _match])get var, possibly from folder within self.cache_dirname.
get_chianti_opa1d_table([tabname])Ionization state table from ChiantiPy.
get_compare_equals(var, *[, _match])self('A==B') --> boolean array: self('A') == self('B')
get_compare_greater_than(var, *[, _match])self('A>B') --> boolean array: self('A') > self('B')
get_compare_greater_than_or_equal(var, *[, ...])self('A>=B') --> boolean array: self('A') >= self('B')
get_compare_less_than(var, *[, _match])self('A<B') --> boolean array: self('A') < self('B')
get_compare_less_than_or_equal(var, *[, _match])self('A<=B') --> boolean array: self('A') <= self('B')
get_compare_not_equals(var, *[, _match])self('A!=B') --> boolean array: self('A') != self('B')
get_cross(var, *[, _match, _val0, _val1])cross product.
get_crosscrossdotself(var, *[, _match, ...])((A_cross_B)_cross_B)_dot_A.
sound speed.
sound speed squared.
get_curl(var, *[, _match])curl.
rate of heating of neutrals due to collisions with all charged species.
rate of heating of neutrals due to collisions with s (self.fluid).
temperature contribution to rate of heating of neutrals due to collisions with s.
dataset of contributions to rate of heating of neutrals due to collisions with s.
velocity contribution to rate of heating of neutrals due to collisions with s.
dataset of contributions to neutral heating rate, based on 'mean' turbulent values,
get_deg2rad(var, *[, _match])convert degrees to radians.
get_delta(var, *[, _match])perturbation.
get_deltafrac(var, *[, _match])perturbation.
get_derivative(var, *[, _match])derivative.
get_div(var, *[, _match])divergence.
get_divide(var, *[, _match])division.
get_dloi()dloi = coord spacing to use for integration as implied by self.loi.
get_dot(var, *[, _match, _val0, _val1])dot product.
get_dotgrad(var, *[, _match])dotgrad: u_dotgrad_B = (u dot grad) B = u_x dB/dx + u_y dB/dy + u_z dB/dz.
get_ds(var, *[, _match])dx (or dy, or dz) --> grid cell size along the x (or y, or z) axis.
spatial scale used when calculating timescales.
minimum spatial scale used when calculating timescales.
get_e()energy density.
Emission measure (EM) based on the selected emission mode (self.emiss_mode).
get_emiss_for_vdem_loi(*[, _T_loi])emiss_for_vdem_loi = emiss_loi, but with some adjustments for vdems:
Emission measure in cgs without TRAC correction.
Emission measure in cgs with TRAC correction.
internal energy (total, not density) per unit mass.
get_eps0()vacuum permittivity, in [self.units] units.
Debye length (of self.fluid), using T_from_Eheat_perp instead of T.
squared Debye length (of self.fluid), using Eheat_perp instead of T.
total Debye length for all fluids: sqrt(epsilon0 kB / sum_fluids(n q^2 / T)),
collisional mean free path, using eqperp_vtherm instead of vtherm.
thermal velocity, using T_from_Eheat_perp instead of T.
get_ertab_var(var, ustr)get var in self.units units from the eos tables, using r and e from self.
get_eta0_J(*[, _E0S1, _E0S2])E0_perp_B = eta0_J * J_perp_B + ..., where eta0_J = E0S1 * |B| / (E0S1^2 + E0S2^2).
get_eta0_hall(*[, _E0S1, _E0S2])E0_perp_B = eta0_hall J x Bhat + ..., where eta0_hall = - E0S2 * |B| / (E0S1^2 + E0S2^2)
get_exp(var, *[, _match])exponentiation.
get_fft(var, *[, _match])N-dimensional fft.
get_fft_with_dims(var, *[, _match])N-dimensional fft.
get_finite(var, *[, _match])var, masked with NaN wherever values are not finite.
get_first_dimpoint([dims, enumerate])return DimPoint taking the first value of each dim in self.dimensions.
get_float(var, *[, _match])any float, as an xarray.
adiabatic index.
get_grad(var, *[, _match])gradient.
get_gradvec(var, *[, _match])gradvec_u = du/dx, du/dy, du/dz, but listed along 'gradvec_component' dim,
get_growthfit(var, *[, _match])self('growthfit_var') --> linear regression along 't' coord, of ln|var|.
get_growthfitk(var, *[, _match])self('growthfitk_var') --> linear regression along 't' coord, of ln|radfft_var|.
get_growthk(var, *[, _match])self('growthk_var') --> exponential growth rate of radfft_var.
get_growthrate(var, *[, _match])self('growthrate_var') --> exponential growth rate of var.
(unsigned) gyrofrequency.
get_hat(var, *[, _match, _val0])unit vector in the direction of var.
get_ifft(var, *[, _match])N-dimensional ifft.
get_imag(var, *[, _match])imaginary part.
inelasticity for collisions between self.fluid and self.jfluid.
get_inf()infinity, as an xarray.
get_int(var, *[, _match])any integer, as an xarray.
ionization fraction.
get_kB()boltzmann constant, in [self.units] units.
(unsigned) kappa (magnetization parameter).
Debye length (of self.fluid).
squared Debye length (of self.fluid).
"total" Debye length; ldebye_subset = sqrt(epsilon0 kB / sum_fluids(n q^2 / (kB T)))
total Debye length for all fluids; ldebye_total = sqrt(epsilon0 kB / sum_fluids(n q^2 / (kB T)))
get_linregt(var, *[, _match])linear regression along 't' coord.
get_ln(var, *[, _match])log base e.
get_load_direct_maindims_var(var, *[, _match])load_var --> load maindims var directly (from files, cache, or setvars; see self.load_direct()).
get_log10(var, *[, _match])log base 10.
get_log2(var, *[, _match])log base 2.
get_logical_and(var, *[, _match])logical and.
get_logical_not(var, *[, _match])logical not.
get_logical_or(var, *[, _match])logical or.
get_loi_cumsum_var(var, *[, _match])loi_cumsum_var = var interpolated onto coordinates implied by self.loi,
get_los()return self.los as an array.
get_lowpass(var, *[, _match])lowpass filter across self.fft_dims; keep low frequencies, zero high frequencies.
get_m()abundance-weighted average fluid particle mass.
mass in atomic mass units.
mass, of a "single neutral particle".
return array of 0s, with dimensions and coords implied by self.maindims.
get_maindims_coord_xarrays([dim])return dict of {dim: xarray of coords for dim} for dim in self.maindims.
get_maindims_coords(*[, slices, coords_units])return dict of {dim: coords} for all dims in self.maindims, applying self.slices appropriately.
return dict of maindims coords' indices, based on self.slices.
get_maindims_dgrid(dim)return grid spacing associated with dim values (dim in self.maindims).
get_maindims_dim_coord(var, *[, _match])maindims_x_coord = array of x values and x coordinates.
get_maindims_dim_dgrid(var, *[, _match])maindims_x_dgrid == array of underlying grid spacing associated with x values.
get_maindims_dim_didx(var, *[, _match])maindims_x_didx == array of index spacing associated with x values,
get_maindims_dim_dslice(var, *[, _match])maindims_x_dslice == array of spacing between adjacent x values, accounting for self.slices.
get_maindims_dim_idx(var, *[, _match])maindims_x_idx == array of index associated with x values,
get_mask_var(var, *[, _match])mask_var --> masked version of self(var).
get_max(var, *[, _match])maximum.
get_mean(var, *[, _match])mean.
collisional mean free path.
get_mean_pm_std(var, *[, _match])return dataset of 'mean+std', 'mean', 'mean-std' for var.
get_meannormed(var, *[, _match])normalized by mean.
get_meant(var, *[, _match])mean-across-time of var.
get_median(var, *[, _match])median.
get_min(var, *[, _match])minimum.
minimum timescale across all timescales.
tells which timescale has the minimum value (across all timescales).
minimum timescale across all timescales and fluids.
tells which timescale has the minimum value (across all timescales and fluids).
get_minus(var, *[, _match])subtraction.
get_mod(var, *[, _match, _val0])magnitude of var.
get_mod2(var, *[, _match, _val0])magnitude squared of var.
get_moments(var, *[, _match])First three moments of a var, e.g., vdem or spectra.
get_n()number density.
number density of neutrals.
get_nan()NaN, as an xarray.
get_nandelta(var, *[, _match])perturbation.
get_nandeltafrac(var, *[, _match])perturbation.
get_nanmax(var, *[, _match])maximum.
get_nanmean(var, *[, _match])mean.
get_nanmedian(var, *[, _match])median.
get_nanmin(var, *[, _match])minimum.
get_nanrms(var, *[, _match])root mean square.
get_nanstd(var, *[, _match])standard deviation.
get_ncpu()returns ncpu, but if None, return multiprocessing.cpu_count() instead.
get_ne()electron number density.
electron number density, from 'eosne' file.
electron number density, from plugging r and e into eos tables (see self.tabin).
get_negation(var, *[, _match])negation.
ion-to-electron density ratio.
get_nmean(var, *[, _match])mean of var, weighted by n.
get_nq()charge density.
get_nstd(var, *[, _match])std of var, weighted by n.
get_nuns()collision frequency.
get_nusj()collision frequency.
get_nusn()collision frequency.
get_nusn_from_drift(var, *[, _match])nusn, calculated by assuming u satisfies momentum equation to zeroth order.
H opacity at self.rcoords_wavelength_A.
get_opac_h_he([wavelength])Opacities at wavelength=self.rcoords_wavelength_A.
HeI opacity at self.rcoords_wavelength_A.
HeII opacity at self.rcoords_wavelength_A.
get_p()momentum density.
get_parallel(var, *[, _match, _val0, _val1])A_par_B --> the component of A parallel to B.
get_parenthesis(var, *[, _match])parenthesis.
get_parmod(var, *[, _match, _val0, _val1])magnitude of the component of A parallel to B.
get_pc_uuid(*[, generate, default, return_meta])return the PlasmaCalcs uuid associated with dir=self.dirname.
get_perp(var, *[, _match, _val0, _val1])A_perp_B --> A after removing the component of A parallel to B.
get_perpmod(var, *[, _match, _val0, _val1])magnitude of A after removing the component of A parallel to B.
get_pi()pi.
get_plotter(name[, who])gets the Plotter associated with this name and who.
get_plotters([who, kind, name, all_whos, ...])return list of all plotters associated with these inputs.
get_plus(var, *[, _match])addition.
get_pmstd2werr(var, *[, _match])convert dataset with 'mean+std' and 'mean-std' into dataset with 'mean' and 'std'.
get_power(var, *[, _match])power.
get_prod(var, *[, _match])prod.
get_psi()psi = (1/(kappae * kappai)) == (nuen * nuin) / (gyrof_e * gyrof_i).
psi_i = (1/(kappae * kappai)) == (nuen * nuin) / (gyrof_e * gyrof_i).
get_pwl2_var(var, *[, _match])get pwl2_flatend fit to var across self.snap, evaluated at self.snap.
get_q()charge, of a "single particle".
get_r()mass density.
get_rad2deg(var, *[, _match])convert radians to degrees.
electron Pressure values for G(T) for fixed pressure, in [self.units] system,
log(electron number density) values for VDEMs and G(T,ne), with ne in [self.units] system,
log(Temperature) values used by some vars (e.g. vdems and G(T)), in [self.units] system,.
velocity (or, doppler shift) values used by some vars (e.g. vdems and spectra), in [self.units] system,.
get_real(var, *[, _match])real part.
get_rms(var, *[, _match])root mean square.
get_rmscomps(var, *[, _match])root mean squared of components.
rosenberg criterion for multiple ions: rosenberg_multi = (nusn_multi / wplasma_multi)^2.
collision frequency for rosenberg criterion with multiple ions.
plasma frequency for rosenberg criterion with multiple ions.
n such that rosenberg_qn == 1, for each fluid.
n / rosenberg_n.
Rosenberg criterion for quasineutrality, for each fluid: rosenberg_qn = (nusn / wplasma)^2.
get_safe_pow2_subcycle(*[, subcycle_safety])largest "safe" power of 2 subcycling allowed for each fluid in self.fluid.
get_sci_number(var, *[, _match])any number in scientific notation, as an xarray.
get_set_or_cached(var)returns var if found in self.setvars or self.cache, with compatible behavior_attrs.
signed gyrofrequency.
get_single_fluid_var(var, *[, _match])SF_{var} (or SINGLE_FLUID_{var}) --> {var}, definitely in single fluid mode.
signed kappa (magnetization parameter).
get_skappa_from_hall(var, *[, _match])signed kappa (magnetization parameter) that statisfies u_hall = u, in the E x B direction.
get_skappa_from_momE(var, *[, _match])signed kappa (magnetization parameter) that statisfies momentum equation in the E direction.
get_skappa_from_momExB(var, *[, _match])signed kappa (magnetization parameter) that statisfies momentum equation in the E x B direction.
get_skappa_from_pedersen(var, *[, _match])signed kappa (magnetization parameter) that statisfies u_pedersen = u, in the E direction.
get_slopet(var, *[, _match])slope calculated from linear regression along 't' coord.
get_sparmod(var, *[, _match, _val0, _val1])signed "magnitude" of the component of A parallel to B.
get_spectra(var, *[, _match])Synthetic spectra for a given ion.
get_sqrt(var, *[, _match])square root.
get_stats(var, *[, _match])return dataset of stats for var
get_std(var, *[, _match])standard deviation.
get_sum(var, *[, _match])sum.
get_surelin_var(var, *[, _match])values of var between (inclusive) t_surelin_min and t_surelin.
get_sureturb_var(var, *[, _match])values of var at or after t_sureturb.
time before which, values are definitely in the linear regime.
start time of "definitely linear regime".
time, after which, values are definitely in the turbulent regime.
time of turbulent onset.
get_t_turb_from_pwl2_var(var, *[, _match])t_turb from pwl2_flatend fit to var.
get_tau()Optical depth along line of integration (default: loi = line of sight),
get_tau_500([wavelength])Computes the tau scale from H-bf opacity alone 500 nm.
return a 1D grid of EBspeed values with constant logstep.
threshold EBspeed for TFBI to grow.
threshold E_un0_perpmag_B for TFBI to grow.
get_tfbi_all(**kw_get_vars)returns xarray.Dataset of values relevant to TFBI theory.
get_tfbi_extras(**kw_get_vars)returns xarray.Dataset of values relevant to TFBI theory but not necessary for inputs.
tfbi_fscale = n * kappa
tfbi_fscale_rel = tfbi_fscale(this fluid) / tfbi_fscale(electrons).
get_tfbi_inputs(**kw_get_vars)returns xarray.Dataset of values to input to the tfbi theory.
get_tfbi_omega(*[, kw_tfbi_solve])Thermal Farley Buneman Instability roots with largest imaginary part at each point in self.
get_tfbi_omega_ds(*[, kw_tfbi_solve])Thermal Farley Buneman Instability solution at each point in self.
return tfbi solution across EBspeed grid.
get_times(var, *[, _match])multiplication.
timescale from drift speed if possible, else from speed using E & B fields.
timescale from speed using E & B fields.
timescale from thermal velocity, using T_from_Eheat_perp instead of T.
timescale for cyclotron motion.
timescale for collisions with neutrals.
timescale from drift speed.
timescale from thermal velocity.
timescale from plasma oscillations.
all timescales (from self.TIMESCALE_VARS) as a dataset.
all timescales (from self.TIMESCALE_VARS) as a dataset, abbreviating names.
get_tturb_var(var, *[, _match])values of var at or after t_turb.
var used for t_turb '00' standard: caches_ln_std_blur_deltafrac_n,
get_turblindiff_var(var, *[, _match])meant_sureturb_var - meant_surelin_var.
get_turblindiffwerr_var(var, *[, _match])werrmeant_sureturb_var - werrmeant_surelin_var.
get_turblindivwerr_var(var, *[, _match])werrmeant_sureturb_var / werrmeant_surelin_var.
get_u()velocity.
get_u_EdotB(*[, _E, _B])EdotB drift velocity.
equilibrium velocity; solution to the momentum equation with collisions,
get_u_hall(*[, _E, _B])Hall drift velocity.
velocity of neutrals.
get_u_pedersen(*[, _E, _B])Pedersen drift velocity.
get_unwrapt_2pi_var(var, *[, _match])unwrapt_{A} --> unwrapped self(A) along 't', via np.unwrap with period=2*pi.
get_upar()velocity vector, parallel to B.
velocity vector, perpendicular to B.
Alfven speed.
Alfven speed squared.
get_var_at_max_of_ref(var, *[, _match])var_at_max_of_ref --> self(var) at argmax of self(ref),
get_var_at_min_of_ref(var, *[, _match])var_at_min_of_ref --> self(var) at argmin of self(ref),
get_var_loi(var, *[, _match])var_loi = var interpolated onto coordinates implied by self.loi.
get_var_los(var, *[, _match])var_los = var projected onto line of sight (as defined by self.los).
get_var_where_condition(var, *[, _match])var_where_condition --> self(var).where(self(condition)).
get_vars(vars, *args[, return_type, ...])returns values of vars from self.
get_vdem()VDEM (intergrated along an axis), as a function of temperature and velocity.
VDEM (intergrated along an axis), with interpolation (Matthias trick along T and u)
VDEM (intergrated along an axis), with interpolation (Matthias trick along T)
VDEM (intergrated along an axis), without interpolation.
get_vector_N(var, *[, _match])vector_n --> vector with n in each component.
thermal velocity.
thermal velocity including instrumental broadening.
thermal velocity for neutrals.
instrumental broadening for thermal velocity, in self.units system.
get_weighted_mean(weights_var, *[, _match])mean, weighted by weights.
get_weighted_std(weights_var, *[, _match])std, weighted by weights.
get_werr2pmstd(var, *[, _match])convert dataset with 'mean' and 'std' into dataset with 'mean+std', 'mean', 'mean-std'.
get_werradd(var, *[, _match])A_werradd_B = A + B, but result is a dataset with 'mean' and 'std'.
get_werrdiv(var, *[, _match])A_werrdiv_B = A / B, but result is a dataset with 'mean' and 'std'.
get_werrmean(var, *[, _match])dataset of 'mean' and 'std' of var.
get_werrmeant(var, *[, _match])dataset of 'mean' and 'std' of var, taking stats across time dimension.
get_werrmul(var, *[, _match])A_werrmul_B = A * B, but result is a dataset with 'mean' and 'std'.
get_werrsub(var, *[, _match])A_werrsub_B = A - B, but result is a dataset with 'mean' and 'std'.
get_where_condition_var(var, *[, _match])where_condition_var --> self(var).where(self(condition)).
"plasma frequency".
electron plasma frequency; Langmuir oscillations.
get_xhat()unit vector in the x direction.
get_xyz(var, *[, _match])x, y, and/or z components of var.
get_yhat()unit vector in the y direction.
get_zhat()unit vector in the z direction.
gradient(array[, components, _post_slices])return gradient of array as a single vector array.
has_var(var)return whether self can load var.
help([qstr, only, tree, modules, signature, ...])prints str for help with quants.
help_call_options([search])prints help for kw_call_options.
help_quants_str([qstr, only, tree, modules, ...])returns str for help with quants.
help_str([qstr, only])returns cls.help_quants_str(qstr=qstr, only=only, **kw).
ifftN(array[, dim, df, x0, ds])xarray_ifftN with defaults for dim determined by self.fft_dims.
ifft_dims_for(array)return dims over which to apply ifft for this array.
set self.snaps based on snap files in self.dirname.
interp_masked(array_or_var, bins[, dim, ...])Compute interpolation masks and normalization factors for a variable (e.g., "T")
iter_dimpoints([dims, all, restore, enumerate])iterate through values of dims, returning DimPoints and setting dim values during iteration.
kw_call_options(*[, sorted])returns list of kwarg names which can be used to set attrs self during self.__call__.
limb_vdem_pipeline(*[, iz0, snap, ...])Execute a VDEM pipeline for limb observations using ray draping geometry.
load_across_dims(loader, *args_loader[, ...])return loader(...), iterating & joining across each dimension.
load_across_dims_implied_by(var, loader, ...)return loader(...), iterating & joining across each dimension implied by var.
load_direct(var, *args, **kw)load var "directly", either from a file, self.setvars,
load_fromfile(fromfile_var, *args__None[, snap])return numpy array of fromfile_var, loaded directly from file.
load_input(fromfile_var, *args, **kw)load value of fromfile_var but when self.snap is INPUT_SNAP.
load_maindims_var(var, *args[, u, assign_labels])return var, formatted as an xarray with proper details for PlasmaCalcs.
load_maindims_var_across_dims(var[, dims, ...])load maindims var across these dims.
loi_cumsum(array, *[, do_interp, sort])return array interpolated onto coordinates implied by self.loi,
loi_interp(array)return array interpolated onto coordinates implied by self.loi.
lowpass(array[, dim, keep, keep_r])xarray_lowpass with defaults for dim & keep determined by self.fft_dims, self.lowpass_keep.
magnitude(A, *[, squared])return vector magnitude of A, assuming vector components along the dimension 'component'.
maintaining_attrs(*attrs, **attrs_as_flags)returns context manager which restores attrs of self to their original values, upon exit.
match_var(var, *[, check])match var from cls.KNOWN_VARS or cls.KNOWN_PATTERNS, or raise FormulaMissingError.
match_var_loading_dims(var, **kw_loading_dims)return dims for loading var across.
match_var_result_dims(var, **kw_result_dims)return dims which result of cls(var) will vary across.
match_var_result_size(var, *[, maindims])return size (number of elements) which self(var) will have.
match_var_tree([var])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
returns number of existing snaps.
pc_uuid_here(dir, *[, generate, default, ...])return the PlasmaCalcs uuid associated with this directory.
plot(name[, who, save, show, close])makes a single plot using the relevant plotter.
plot_check_nusn_from_drift(*[, u, drift, ...])plots PlasmaCalcs.timelines() for comparing nusn to nusn inferred from drifts.
polyfit(array_or_var, coord, degree[, window])polyfit along coord.
pop_dim_keys(kw)return ({key: kw.pop(key) for key in self.dimensions if key in kw}, kw).
quant_tree([var])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
return dict of defaults to use for ray_draping.
record_units(array)return array.assign_attrs(self.units_meta()).
register([registry, metrics, username])register this instance and these metrics to the registry.
return flat dict of input params to use in self.register().
rmscomps(A)return root mean squared of components of A.
save_plots([kind, who, name, all_whos, ...])saves all plots from plotters associated with these inputs.
set_E_un0_perpmod_B(value, **kw)set E_un0_perpmod_B to this value.
set_T_fromtable(value, **kw)set T_fromtable to this value.
set_attrs(**attrs)sets these attrs in self.
set_e(value, **kw)set e to this value.
set_eperm(value, **kw)set eperm to this value.
set_inelasticity(value, **kw)set inelasticity to this value, for this (self.fluid, self.jfluid) pair.
set_mask(mask)sets self.mask = mask, and increments self._mask_cache_state (if checks succeed).
set_mod_B(value, **kw)set mod_B to this value.
set_n(value, **kw)set n to this value.
set self.{key} = kw.pop(key) for each key in self.dimensions if key in kw.
set_r(value, **kw)set r to this value.
set self.t_turb & return t_turb from '00' standard: t_turb_from_pwl2_ln_std_blur_deltafrac_n,
set self.t_turb & return t_turb from '10' standard: t_turb_from_pwl2_ln_std_blur_deltafrac_n,
set_var(var, value[, behavior_attrs, ...])set var in self.
set_var_internal(var, value, behavior_attrs)set var in self.
set_vtherm(value, **kw)set thermal velocity, by setting T.
slice_maindims(array, **kw_xarray_isel)slice maindims of array using self.slices.
slicestr(*[, sep, keep_None])string representation of self.slices, for use in filenames, titles, etc.
snap_datetimestamp([snap, tz, as_str, sep])return (best-effort guess of) datetime when this snap was created or first written.
snap_filepath([snap])convert snap to full file path for this snap, i.e. to the Header.NNN file.
solve_tfbi_vs_EBspeed(*[, Mbytes_max, cache])solve tfbi across EBspeed grid from self('tfbi_EBspeed_grid').
returns a copy of self.slices, but calling interprets_fractional_indexing on all slices,
stat_dims_for(array)return the dims to apply statistics over, for this array.
store_mask(arr)equivalent: xarray_store_mask(arr, self.mask).
take_parallel_to(B, A)return the component of A parallel to B.
take_perp_to(B, A)return the component of A perpendicular to B.
tfbi_ds([ions, all, output_mask])returns Dataset of all the values needed & relevant to TFBI theory.
tfbi_mask(*[, kappae, ionfrac, kappai, set])set & return self.mask appropriate for TFBI.
tfbi_solver([ions])return TfbiSolver object for solving TFBI theory based on values in self.
title_with_slices([slices, sep, keep_None])return self.title with slicestr appended (after sep), if slicestr is not empty.
tree([var])return QuantTree of MatchedQuantity objects from matching var and all dependencies,
return dict(units=self.units).
unmask(arr, **kw_xarray_unmask)restore arr to the same shape as unmasked unstacked arrays.
unset_var(var[, behavior_attrs, missing_ok])remove var from self.setvars (but only at values stored with relevant behavior).
unset_var_internal(var, behavior_attrs[, ...])unset var from self.setvars.
using_at_call_depth(depth, **attrs_and_values)context manager for setting attrs_and_values but only while call_depth == depth.
using_at_next_call_depth(**attrs_and_values)context manager for setting attrs_and_values but only while call_depth == self.call_depth + 1
using_attrs([attrs_as_dict, _unset_sentinel])returns context manager which sets attrs of obj upon entry; restores original values upon exit.
using_first_dimpoint([dims])return context manager which sets dimensions to their first values (when called); restore original on exit.
vdem_pipeline(*[, los_dim, iz0, tg_percent, ...])Execute a standard VDEM (Velocity-Differential Emission Measure) analysis pipeline.
zeros_like_maindims(**kw_zeros_like)return array of all 0s like maindims var results (use ints to save space).
returns whether eos aux files (eosP, eosT, and eosne) exist for all snaps in self.
slice entries in dict using self.slices.
apply self.toplevel_scale_coords to arr, if nonempty, else return arr unchanged.
_array_compatible_with_current_behavior(array, *)returns whether array is compatible with current self.behavior.
assert that array is compatible with current self.behavior.
checks that array is not too big for caching.
_assert_is_maindim(dim)asserts dim in self.maindims; crash with DimensionKeyError if not.
_battrs_for_set_var_internal(behavior_attrs)returns behavior_attrs which will be used by set_var_internal, given these inputs.
_battrs_for_unset_var_internal(behavior_attrs)returns behavior_attrs which will be used by unset_var_internal, given these inputs.
_braced_int_dep(_var, groups)returns the 'dep' associated with this var for _get_braced_int_from_parenthesis_memory
_cache_dst(array_or_name)return abspath for cached array, given array (or name of array).
_call_hijacker(*args_super, **kw_super)returns False or name of hijacker method to use instead of self(var) call.
_call_loader0_at_dimpoint(dimpoint, loader0, ...)return self._call_loader_at_dimpoint(dimpoint, loader0, ...).
_call_loader_at_dimpoint(dimpoint, loader, ...)with self.using(**dimpoint): return loader(*args_loader, **kw_loader)
_call_postprocess(result, *, var[, name, item])postprocess result from self.__call__.
_call_postprocess_toplevel(result, *, var[, ...])additional postprocessing for self.__call__ when call_depth=1.
_call_preprocess(result, *, var)preprocessing during self.__call__.
check that all files in self.dirname are readable (checks recursively inside directories too).
default for self.cache_dirname.
default for how to handle "Equation of State" related variables (ne, T, P).
return default for ncoarse during self.load_across_dims.
return default for ncpu during self.load_across_dims.
returns default for print_freq.
return default value of self.tabin: erTabInputManager(self.tabinputfile, u=self.u).
return default for timeout during self.load_across_dims.
default title for self.
delete dst, if it exists, but first ensure it contains '_pc_caches' in the path.
returns correction factor to multiply derivatives by, for "coords_units != units" case.
default value for elements.
return dict of dimensions in self; {dimension name: Dimension object}
_get_ertab_var_raw(var)get var in 'raw' units, from the eos tables, using single-fluid r and e from self.
return dict of {'x': xcoords, 'y': ycoords, 'z': zcoords}.
returns self.get_maindims_coords() with tile_snaps applied appropriately.
_get_maybe_missing_var(var, *args[, ...])return value of var, or None if FormulaMissingError and missing_vars 'ignore' or 'warn'.
_get_stat_var(var, statfunc)returns result of applying statfunc to self(var), possibly one dimpoint at a time then joining results.
_get_stat_var_dimpoint_wise_false(var, statfunc)returns result of applying statfunc to self(var).
_get_stat_var_dimpoint_wise_true(var, statfunc)returns result of applying statfunc to self(var).
_get_statfunc_of_var(var, statfunc)load this stat, for self(var).
_get_with_chunks(var, *args_super, **kw_super)returns value of var, but chunking while loading, then merging chunked results.
_handle_typevar_nan(*[, errmsg])crash with TypevarNanError if self.typevar_crash_if_nan, else return 'nan'.
_help_matches(qstr, k, v)returns whether qstr matches k or v, and thus should be displayed during self.help(qstr).
returns dict of docstrings for specialized kw call options for self.
context manager for incrementing call_depth.
_load_across_dims_postprocess(arrs, dims, *, ...)postprocessing results from load_across_dims, after all tasks have been completed.
returns single numpy array (with the data from arrs, which is an array of arrays).
handles array broadcasting for _load_across_dims_postprocess.
_load_maindims_var_with_labels(var, *args, **kw)equivalent to self.load_maindims_var(var, *args, assign_labels=True, **kw)
_load_maindims_var_without_labels(var, ...)equivalent to self.load_maindims_var(var, *args, assign_labels=False, **kw)
return coord to use for integration, as implied by self.loi.
_loi_integration_dim(*[, signed])return dimension along which to integrate, as implied by self.loi.
return dict of arrays to interpolate onto, as implied by self.loi.
returns whether self.loi implies to do ray draping.
returns whether max supported n, in self.units unit system, is too big for float32.
function to get multi_slices dims, by default.
Called when self.fft_slices accessed but not yet set; create & return new FFTSlices.
_new_multi_slices(**kw)called when self.multi_slices accessed but not yet set; create & return new MultiSlices.
_parenthesis_converted_var(before, here, after)returns the var after converting it from var like '{before}({here}){after}'.
_parenthesis_dep(_var, groups)returns the 'dep' associated with this var for get_parenthesis.
pop all self.kw_call_options() from kw, returning dict of popped options.
return slices to apply before & after differentiation.
_print_or_warn(msg[, debug_thresh])if DEBUG>=debug_thresh, print msg.
_provided_val(var[, _val, _known_vals])returns the value of var, either from _known_vals or _val.
asserts self.current_n_component() == 1; raise ComponentValueError otherwise.
return metadata relevant to registering this run.
_registry_metrics(metrics)return dict of metrics' values relevant to registering this run with these metrics.
return list of contents to go in repr of self.
_slice_maindims_numpy(array, *[, h5])slice first len(maindims) dims of array, using self.slices.
return list of maindims which become scalars when hit by self.slices.
_special_dims_shifters(dimnames, _shift_special)return (dict for self.using(...), dict for result.isel(...)) to _shift_special_dims.
specialize popped kw_call_options, adjusting keys and/or values as needed,
returns expected abspath to file for storing tfbi solution across EBspeed grid.
returns [pre-current, post-current] snaps to tile along based on self.tile_snaps and self.snap.
if max n requires float64, upcast array to float64,
_var_for_load_fromfile(varname_internal)return var, suitably adjusted to pass into load_fromfile().
_vdem_multiply_then_sum_along(*arrays, dim)multiply arrays then sum along dim, without making big intermediate array.
Attributes
E0_NE0_MODE_OPTIONScontrols how to get ne when calculating E0.
EOS_MODE_OPTIONSE_UN0_MODE_OPTIONSmode for calculating E_un0, the electric field in the neutral frame (where u_n=0).
GOFNT_INTERP_MODE_OPTIONSGOFNT_MODE_OPTIONSKNOWN_PATTERNSKNOWN_PLOTTERSKNOWN_SETTERSKNOWN_VARSLOI_OPTIONSLOS_OPTIONSTFBI_EXTRASTFBI_VARSTIMESCALE_VARSUNIQUE_PLOTTERSVDEM_MODE_OPTIONSUNSET, None, or number
whether to assert self.masking != False and mask is not None, when getting values.
whether to assign self.behavior values as attrs of result when calling self.
max call_depth at which to assign_behavior_attrs to result,
whether to use include_xr=False if self.assign_behavior_attrs,
alias to self.component_dim.assign_coord_along
alias to self.component_dim.assign_coord
alias to self.snap_dim.assign_coord_along
alias to self.snap_dim.assign_coord
dict of {attr: self.attr} for attr in self.behavior_attrs.
list of attrs in self which control behavior of self.
alias to gaussian_filter
the dims over which to possibly apply blur (BlurLoader methods).
the default sigma to use for blurring calculations.
abspath to directory for containing cached values of this CachesLoader.
where to skip array-valued behavior attrs when caching arrays (to _pc_caches)
depth of the current call to self.
stores the value of call_depth, and helps to manage attrs dependent on call_depth value.
chunks for maindims when loading arrays.
cls_behavior_attrscls_metdata_attrsalias to self.component_dim.v
alias to self.component_dim.array_equals
component dimension for ComponentHaver.
alias to self.component_dim.is_iterable
alias to self.component_dim.list
alias to self.component_dim.get_type
alias to self.component_dim.values
None or str telling the current unit system for coordinates, e.g. 'si'.
str telling the current unit system for coordinates, e.g. 'si'.
alias to cross_product
alias to self.component_dim.current_n
alias to self.snap_dim.current_n
numpy dtype of each data array.
number of bytes in each data array.
ordering of data array axes: 'F' (Fortran) or 'C' (C order).
shape of each array of data stored in files.
array size (number of elements) of each data array.
datetime corresponding to roughly when this run was created.
bool or 'step'.
dict of dimensions in self; {dimension name: Dimension object}.
return dict of current values for dimensions in self.
abspath to directory containing data for this DirectLoader.
alias to divergence
alias to dot_product
value of 'drop' kwarg for any self('{var}_where_{condition}') calls.
ElementList of all elements in multifluid mixture assumed from single-fluid mhd.
string telling emission measure mode.
Emission Measure normalization factor.
whether to include opacity in emission measure (self('emiss')).
whether to include TRAC correction in emission measure (self('emiss')).
TRAC coefficient for emiss_trac calculation.
bool: whether self.load_fromfile is enabled during self.load_direct.
alias to self.component_dim.enumerate
alias to self.component_dim.enumerate_values
alias to self.snap_dim.enumerate
alias to self.snap_dim.enumerate_values
mode for "Equation of State" related variables (ne, T, P).
None or str telling the eos_mode for pressure, e.g. 'aux'.
alias to self.eos_mode_P if not None, else self.eos_mode.
None or str telling the eos_mode for temperature, e.g. 'aux'.
alias to self.eos_mode_T if not None, else self.eos_mode.
None or str telling the eos_mode for electron number density, e.g. 'aux'.
alias to self.eos_mode_ne if not None, else self.eos_mode.
dict of {coord_name: coord_value} to attach to outputs of self(var).
alias to fftN
the dims over which to possibly apply fft (FFTLoader methods).
alias to self.fft_slices.half
alias to self.fft_slices.keep
the dict of indexers to apply to all fft results from self, by default.
alias to self.fft_slices.step
alias to __call__
alias to get_maindims_coords
Abundance(?) to use for G(T) calculations.
Selects the emission measure x G(T) calculation mode.
Selects the G(T) calculation mode.
Wavelength range (as [min, max]) (in [Angstrom] units) to use for G(T) calculations.
alias to gradient
alias to self.gradvec_component_dim.v
gradvec_component_dimalias to self.gradvec_component_dim.values
alias to ifftN
whether self is in "single fluid mode".
alias to self.component_dim.iter
alias to self.component_dim.iter_values
alias to self.component_dim.iter_partition
alias to self.snap_dim.iter
alias to self.snap_dim.iter_values
alias to self.snap_dim.iter_partition
alias to self.component_dim.join_along
alias to self.snap_dim.join_along
known_patternknown_plotterknown_setterknown_varalias to los
Line Of Integration (dim, dict of arrays for interp), or "Lots Of Interpolation", if you prefer.
Tells whether to sort along the integration dimension before doing cumsum in self.loi_cumsum().
loi as 2-tuple of (integration axis, None or dict of arrays for interpolation).
units string (e.g., 'length') for loi interped coords,
loi_ustr, but returns self._loi_ustr_default if loi_ustr is UNSET
line of sight vector; used by self("var_los") pattern and any quantities which depend on it.
the default value for "keep" in self.lowpass.
maindims of MURAM data, i.e. ('x', 'y', 'z').
self.maindims_shape when self.slices=None
self.maindims_size when self.slices=None
self.maindims_sizes when self.slices=None
whether to immediately take means across maindims when loading arrays.
tuple of (len(self.get_maindims_coords()[dim]) for dim in self.maindims).
product of terms in self.maindims_shape.
dict of {dim: size of dim} for dim in self.maindims.
alias to maintaining_attrs
None or xarray.DataArray of bools,
how to apply self.mask to results at top level, if mask exists.
dict of metadata attributes and their values, excluding missing and ATTR_UNSET.
dict of metadata attributes and their values (value=ATTR_UNSET if missing).
alias to cls_metadata_attrs; set of all attrs which tell metadata,
dict of {key: slices dict}.
int or number between -1 < ikeep < 1
None or int
number of gigabytes across all files in self.dirname (and subdirectories).
number of megabytes across all files in self.dirname (and subdirectories).
number of bytes across all files in self.dirname (and subdirectories)
int
None or int
list of attrs in self which control behavior of self, but which are NOT in self.dimensions.
'abspath to directory containing plots/notes for a DirectLoader.
whether to store_mask during xarray_mask calls if self.masking.
return the global params shared by all snaps.
parenthesis_memoryPlasmaCalcs uuid (universally unique identifier) associated with self.dirname.
alias to self.polyfit_kw['boundary'].
alias to self.polyfit_kw['cov'].
alias to self.polyfit_kw['full'].
alias to self.polyfit_kw['keep_coord'].
kwargs to pass to self.polyfit(), other than array, coord, degree, and window.
polyfit_kw_key_aliasesalias to self.polyfit_kw['stddev'].
When polyfitting, tells window size to use for coarsening arrays before fitting.
None, or number (possibly negative or 0)
like self.print_freq, but converts UNSET to value based on self.verbose,
The RayDraping instance to use.
None, dict, or RayDraping instance defining RayDraping for ray draping problems.
self.ray_draping, but convert to RayDraping instance if needed.
electron Pressure [cgs units] values, used by some MhdRadiativeLoader vars.
log10(electron number density [cgs units]) values, used by some MhdRadiativeLoader vars.
log10(Temperature [K]) values used by some MhdRadiativeLoader vars.
velocity [km/s] (or, doppler shift) values, used by some MhdRadiativeLoader vars.
Wavelength (in [Angstrom] units) used by some MhdRadiativeLoader vars.
alias to set_var
alias to set_var
VarCache of vars set via self.set_var().
slices for maindims when loading arrays & during get_maindims_coords.
alias to self.snap_dim.v
alias to self.snap_dim.array_equals
snap dimension for SnapHaver.
alias to self.snap_dim.is_iterable
alias to self.snap_dim.list
alias to self.snap_dim.get_type
directory containing the snapshot files.
alias to self.snap_dim.values
the dims over which to possibly apply statistics (StatsLoader methods).
whether to apply stat calculations at each DimPoint, or after loading the full array.
fraction of t_turb which tells start time of "definitely linear regime".
fraction of t_turb which tells t_surelin.
None, or time of turbulent onset.
dict-like manager for Equation Of State tables; should include keys 'ne', 'T', 'P'.
abspath to tabinputfile (used when creating default self.tabin).
alias to self.component_dim.take
alias to self.component_dim.take_along
alias to self.snap_dim.take
alias to self.snap_dim.take_along
(logmin, logmax, logstep) for self('tfbi_EBspeed_grid'); log is base 10.
list of vars which might be needed for TFBI solver, but aren't always needed.
whether to assume elastic collisions in heating equation for TFBI theory.
threshold for confirming "yes there is tfbi growth predicted here", during self('tfbi_E_thresh').
instructions for tiling results from snaps, concatenating along a maindim.
None or int
title to help distinguish this calculator from others.
dict of {coord_name: coord_scaling} to apply to top-level outputs of self(var).
bool.
the current units manager for self.
abspath to directory containing plots/notes for a DirectLoader,
the current unit system for self.
alias to unset_var
alias to using_attrs
Specifies how the photosphere is treated in VDEM calculations.
(self.vdem_logT_min, self.rcoords_logT).
Minimum log10(temperature [K]) to include in VDEM calculations.
Tells which dimension to loop over during vdems.
tells which line of sight to integrate along for vdem calculations.
self.vdem_los, but if None convert to the explicit vdem_los to use.
Selects the velocity-differential emission measure (VDEM) calculation mode.
tells whether vdems should also vary across logD (electron number density) dimension,
instrumental broadening for thermal velocity, in SI units.
whether to require 'std' data var appear in at least 1 input for all werrmath operations.
alias to polyfit_window
- property E0_ne0_mode
controls how to get ne when calculating E0. See self.E0_NE0_MODE_OPTIONS for details.
- property E_un0_mode
mode for calculating E_un0, the electric field in the neutral frame (where u_n=0).
See self.E_UN0_MODE_OPTIONS for details on the various options.
- __call__(var, *args, name=UNSET, item=False, verbose=UNSET, **kw)
returns value of var from self.
result is probably an xarray.DataArray, but not guaranteed.var: str or iterable of strs.Name of the var(s) to load. E.g. ‘n’ for number density, or [‘n’, ‘u’] for number density & velocity.If multiple vars: returns an xarray.Dataset of all vars, via self.get_vars.Determine how to load each var, as follows:- (caching) if var in self.cache, with matching self.behavior_attrs, use value from cache.[TODO] - caching not yet implemented. May allow for better efficiency.- (setvars) if var in self.setvars, with matching self.behavior_attrs, use value from setvars.[TODO] - improve set_var functionality.set_var will allow user to apply PlasmaCalcs calculations to arbitrary values,not just values from one of the hookups. Useful for testing & quick calculations.- (KNOWN_VARS) if var in self.KNOWN_VARS,use the corresponding function to get it.- (KNOWN_PATTERNS) if var matches a pattern from self.KNOWN_PATTERNS,use the corresponding function to get it.- (direct) attempt to load var “directly”, via self.load_direct.load_direct will almost always end up loading values directly from a file (e.g., “data”).This may include converting var to fromfile_var, i.e. match file naming conventions,and/or dimensions being loaded. E.g. ‘b’ may become ‘bz’ when loading across ‘component’.Then, check if fromfile_var in setvars and cache, returning relevant value if found.Lastly, call self.load_fromfile(fromfile_var).Those are checked in the order listed.If none of those work, raise FormulaMissingError.name: UNSET, None, or strtry to set result.name = name.If can’t set result.name, but result.attrs exists, set result.attrs[‘name’] = name, instead.UNSET –> use name = var.item: boolif True, convert result to single value (e.g., python float) via result.item().This will cause crash if result is not a single value;it will also cause all metadata stored in the result to be lost.verbose: UNSET, bool, or intset self.verbose during this call to self.UNSET –> use self.verbose (unchanged)kw may additionally contain any keys from self.kw_call_options().if it does, pop those values, and temporarily set the corresponding attr.E.g.: self(‘n’, units=’si’, fluid=1)–> temporarily set units=’si’, fluid=1, while getting ‘n’.See self.help_call_options() for more details.[EFF] passes _match=re.fullmatch(pattern, var) to the getter function,if the match is from KNOWN_PATTERNS (but not if it is from KNOWN_VARS).misc note: if self._call_hijacker(…), instead return result from the corresponding method.e.g. if it returns “_get_with_chunks” then return self._get_with_chunks(var, …).Call hijacking occurs after setting behavior attrs (insidewith self.using(...):block)but before altering call depth (outsidewith self._increment_call_depth():block).
- __getitem__(snapi)
sets self.snap, then returns self.
Examples:self[4] –> self.snap = 4self[:5] –> self.snap = slice(0, 5)self[-1] –> self.snap = -1self[‘2’] –> self.snap = ‘2’self[self.snaps[7]] –> self.snap = self.snaps[7]self[[0,4,7,3]] –> self.snap = [0,4,7,3]Note this is ‘smart’ in the same way that setting self.snap is ‘smart’;will attempt self.snaps.get(snapi).See help(self.snaps.get) for more details.This enables “shorthand” syntax, e.g. self[3](‘n’) gets ‘n’ at self.snap=3.
- __getstate__()
return state for pickling. pickle default ignores class attr (parenthesis_memory) but we need it.
- classmethod __init_subclass__(*, dimension=None, dim_plural=None, **kw_super)
called when subclassing DimensionHaver; sets some useful attributes related to dimension.
dimension: str or None
name of dimension associated with this subclass.if None, no particular dimension associated with this subclass.dim_plural: str or Noneplural form of dimension. if None, use str(dimension)+’s’.Sets various attributes in cls:cls._dimension = dimension,cls._dim_plural = dim_plural,cls._dim_types = dict of all {dimension name: Dimension subclass} from cls and cls.__bases__(note - connecting self._dimension to this dict is not handled here;it is handled by __setup_haver__ called by Dimension.setup_haver)
- __iter__()
equivalent to self.iter_snaps()
- __len__()
equivalent to len(self.snaps)
- __setstate__(state)
set state for pickling. pickle default ignores class attr (parenthesis_memory) but we need it.
- classmethod __setup_haver__(dim_cls, **kw_super)
called by dim_cls.setup_haver(cls) when setting up cls so that it “has” dim_cls dimension.
- _all_eos_aux_files_exist()
returns whether eos aux files (eosP, eosT, and eosne) exist for all snaps in self.
- _apply_maindims_slices_to_dict(d)
slice entries in dict using self.slices. returns d. (Note: d will be directly altered.)
- _apply_toplevel_scale_coords(arr)
apply self.toplevel_scale_coords to arr, if nonempty, else return arr unchanged.
- _array_compatible_with_current_behavior(array, *, return_info=False)
returns whether array is compatible with current self.behavior.
Compatible if all of the following are true:
(1) All attrs appearing in array.attrs & self.behavior must be equal.E.g., if ‘units’ in both, need array.attrs[‘units’] == self.behavior[‘units’].(2) All attrs appearing in self.behavior.nondefault(include_xr=False) must appear in array.attrs.E.g., if ‘blur_sigma’ in self.behavior.nondefault(), need ‘blur_sigma’ in array.attrs.(3) [TODO] If self.behavior.nondefault(include_xr=’only’) has any values,they must match values saved to arrays in os.path.join(array.attrs[‘filepath’], ‘behavior_arrays’)E.g., if ‘tfbi_grid1_zeros’ appears, need self.behavior[‘tfbi_grid1_zeros’].equals(behavarr),where behavarr = xarray_load(… the array at ‘behavior_arrays/tfbi_grid1_zeros.pcxarr’))[TODO] currently, caching behavior array values is not implemented;see type(self).caches_behavior_skip_xr for details.(4) All appearing in array and self.behavior.dims must be equal.E.g., if ‘fluid’ in both, need array_equal(array[‘fluid’].values, self.behavior.dims[‘fluid’])(5) If array.attrs has ‘pc__version__’ and/or ‘pc__commit_hash’,they must match the current PlasmaCalcs version and commit hash, if known.return_info: boolwhether to instead return (result, reason of mismatch, key, array value, behavior value).(reason will be ‘version’, ‘attrs’, ‘dims’, or ‘array_attrs’)(if result is True, all other values are None)
- _assert_array_compatible_with_current_behavior(array)
assert that array is compatible with current self.behavior.
(if not, crash with CacheNotApplicableError)
- _assert_cache_array_not_too_big(array)
checks that array is not too big for caching. If too big, crash with MemorySizeError.
- _assert_is_maindim(dim)
asserts dim in self.maindims; crash with DimensionKeyError if not.
- _battrs_for_set_var_internal(behavior_attrs, forall=[], *, ukey=None)
returns behavior_attrs which will be used by set_var_internal, given these inputs.
see help(self.set_var_internal) for details.
- _battrs_for_unset_var_internal(behavior_attrs, forall=[], *, ukey=None)
returns behavior_attrs which will be used by unset_var_internal, given these inputs.
see help(self.unset_var_internal) for details.
- _braced_int_dep(_var, groups)
returns the ‘dep’ associated with this var for _get_braced_int_from_parenthesis_memory
- _cache_dst(array_or_name)
return abspath for cached array, given array (or name of array).
(if DataArray, uses array.name; if Dataset, must provide name as str instead.)result will include .pcxarr extension.if inferred name includes ‘/’, crash (and suggest to use ÷ character instead).
- _call_hijacker(*args_super, **kw_super)
returns False or name of hijacker method to use instead of self(var) call.
Here, returns ‘_get_with_chunks’ if self.chunks is nonempty, else super()._call_hijacker(…).
- _call_loader0_at_dimpoint(dimpoint, loader0, args_loader, *, nload, MBmax, **kw_loader)
return self._call_loader_at_dimpoint(dimpoint, loader0, …).
Also does memory size check based on nload and MBmax.intended for internal use only, inside load_across_dims.arr0 is handled differently from other arrays in order to do some checks.
- _call_loader_at_dimpoint(dimpoint, loader, args_loader, **kw_loader)
with self.using(**dimpoint): return loader(*args_loader, **kw_loader)
- _call_postprocess(result, *, var, name=UNSET, item=UNSET)
postprocess result from self.__call__. Called during self.__call__.
(self.call_depth inside here will tell depth of the current call; depth=1 for top level.)result: any value, probably an xarray.DataArrayresult from self.__call__, before postprocessing.var, name, item: UNSET or valuepassed directly from self.__call__.The implementation here does the following (subclasses might override / add to this):(A) call super()._call_postprocess(), which probably (if parent is QuantityLoader) does:(1) if self.verbose >= 4, print a message about getting var.(2) result = self.attach_extra_coords(result).(3) set result.name = name, or result.attrs[‘name’] = name, if possible.(4) if self.assign_behavior_attrs at this call depth, do so now.(5) if self.call_depth == 1, call self._call_postprocess_toplevel.(6) if item, convert result to single value via result.item().(B) if self._chunks_check0 is not None, crash if chunkdim is missing from result.dims.else, return result, unchanged.
- _call_postprocess_toplevel(result, *, var, name=UNSET, item=UNSET)
additional postprocessing for self.__call__ when call_depth=1.
called from self._call_postprocess, after doing other postprocessing, when call_depth=1.result: any value, probably an xarray.DataArrayresult from self.__call__, after other postprocessing.var, name, item: UNSET or valuepassed directly from self.__call__.Don’t need to handle these here because self._call_postprocess will handle it.The implementation here applies masking, if applicable.see help(type(self).mask)
- _call_preprocess(result, *, var)
preprocessing during self.__call__. Called during self.__call__.
(self.call_depth inside here will tell depth of the current call; depth=1 for top level.)result: any value, probably RESULT_MISSINGresult from self.__call__, before preprocessing. Usually RESULT_MISSING.var: strvar being loaded. Passed directly from self.__call__.The implementation here does the following (subclasses might override / add to this):(1) if self.verbose >= 2 or DEFAULTS.DEBUG >= 7, print a message about getting var.(2) return result, unchanged.If the returned result is anything other than RESULT_MISSING,self.__call__ will return it instead of loading var normally.
- _check_files_readable()
check that all files in self.dirname are readable (checks recursively inside directories too).
return number of files checked, number of files readable, and number of files not readable.print exceptions along the way if any files are not readable!
- _default_cache_dirname()
default for self.cache_dirname.
{self.dirname}/_pc_caches if self.dirname exists, else raise InputMissingError.
- _default_eos_mode()
default for how to handle “Equation of State” related variables (ne, T, P).
(provides default value for self.eos_mode.)result will be ‘aux’ if files for ‘eosT’, ‘eosP’, and ‘eosne’ exist for each snap,else ‘table’ if ‘tabparams.in’ file exists,else ‘ideal’.
- _default_ncoarse()
return default for ncoarse during self.load_across_dims. returns DEFAULTS.LOADING_NCOARSE
- _default_ncpu()
return default for ncpu during self.load_across_dims. returns DEFAULTS.LOADING_NCPU
- _default_print_freq()
returns default for print_freq. Here, returns UNSET; i.e., infer from self.verbose.
(See self.print_freq_explicit to get the actual value of print_freq.)
- _default_tabin()
return default value of self.tabin: erTabInputManager(self.tabinputfile, u=self.u).
- _default_timeout()
return default for timeout during self.load_across_dims. returns DEFAULTS.LOADING_TIMEOUT
- _default_title()
default title for self. Here, just returns os.path.basename(self.notes_dirname)
- _delete_cache_dst_if_exists(dst)
delete dst, if it exists, but first ensure it contains ‘_pc_caches’ in the path.
Never deletes files which don’t contain ‘_pc_caches’ in the path.
- _deriv_coords_units_correction(x)
returns correction factor to multiply derivatives by, for “coords_units != units” case.
E.g., for spatial derivatives (‘length’ units),if self.coords_units = ‘cgs’ while self.units = ‘si’,d(array)/dx will be 100 times smaller than it needs to be(e.g. x = [100,200,300] (cm) instead of [1,2,3] (m))so this method returns 100 in that case.x: str or list of str, coordinate name(s) for differentiation.all from ‘x’, ‘y’, ‘z’ –> self.u(‘length’, self.coords_units, convert_from=self.units)‘t’ –> self.u(‘time’, self.coords_units, convert_from=self.units)mixed (e.g. [‘x’, ‘t’]) –> crash.
- _get_default_elements()
default value for elements. here, just returns self.tabin.elements,
but raises a helpful error message if self.tabin not set.
- _get_dimensions_dict()
return dict of dimensions in self; {dimension name: Dimension object}
- _get_ertab_var_raw(var)
get var in ‘raw’ units, from the eos tables, using single-fluid r and e from self.
CAUTION: array values use [raw], but coords use [self.coords_units].see self.tabin.keys() for var options. gets value via interpolation.
- _get_maindims_coords_base()
return dict of {‘x’: xcoords, ‘y’: ycoords, ‘z’: zcoords}.
Results will be in self.coords_units (default: self.units) unit system.Ignores self.slices. See also: self.get_maindims_coords().
- _get_maindims_coords_tiled()
returns self.get_maindims_coords() with tile_snaps applied appropriately.
(self.get_maindims_coords() calls this function internally when self.tile_snaps != False).
- _get_maybe_missing_var(var, *args, missing_vars=UNSET, **kw)
return value of var, or None if FormulaMissingError and missing_vars ‘ignore’ or ‘warn’.
missing_vars: UNSET, ‘ignore’, ‘warn’, or ‘raise’what to do if any var causes FormulaMissingError.UNSET –> use self.missing_vars if it exists, else ‘raise’.‘ignore’ –> return None.‘warn’ –> return None, but also print a warning.‘raise’ –> raise FormulaMissingError.
- _get_stat_var(var, statfunc)
returns result of applying statfunc to self(var), possibly one dimpoint at a time then joining results.
see help(type(self).stats_dimpoint_wise) for details.
- _get_stat_var_dimpoint_wise_false(var, statfunc)
returns result of applying statfunc to self(var). (Used when self.stats_dimpoint_wise=False.)
- _get_stat_var_dimpoint_wise_true(var, statfunc, min_split=UNSET)
returns result of applying statfunc to self(var). (Used when self.stats_dimpoint_wise=True.)
min_split: UNSET or int[EFF] min length of dimension before actually applying dimpointwise stats along it.1 –> no minimum. If MemorySizeError when min_split > 1, try again but with min_split=1.UNSET –> use DEFAULTS.STATS_DIMPOINT_WISE_MIN_SPLIT.
- _get_statfunc_of_var(var, statfunc)
load this stat, for self(var).
- _get_with_chunks(var, *args_super, **kw_super)
returns value of var, but chunking while loading, then merging chunked results.
Result should be equivalent to self(var, chunks=None).CAUTION: derivatives may give wrong answers at chunk boundaries, unless deriv_before_slices=False
- _handle_typevar_nan(*, errmsg='')
crash with TypevarNanError if self.typevar_crash_if_nan, else return ‘nan’.
if crashing, use error message:errmsg + “nTo return ‘nan’ instead of crashing, set self.typevar_crash_if_nan=False.”
- classmethod _help_matches(qstr, k, v)
returns whether qstr matches k or v, and thus should be displayed during self.help(qstr).
qstr: str
the str to match; from self.help(qstr)k: varnamethe varname to test for matches.key from self.KNOWN_VARS.keys(), or key.str from self.KNOWN_PATTERNS.keys().v: LoadableQuantitythe LoadableQuantity to test for matches.value from self.KNOWN_VARS.values() or self.KNOWN_PATTERNS.values().matches if any of these are true:qstr == ‘’qstr in k.split(‘_’) # size limitation and split(‘_’) because, e.g. during help(‘n’),len(qstr)>=3 and qstr in k # want vars related to number density, not all vars with the letter ‘n’.qstr in module.split(‘.’) (where, module == v.get_f_module(cls))‘.’ in qstr and qstr in modulelen(qstr)>=3 and qstr in value from module.split(‘.’)len(qstr)>=3 and qstr in v.fnamere.fullmatch(k, qstr) # if k is a Patternotherwise, does not match.
- _help_specialized_kw_call_options()
returns dict of docstrings for specialized kw call options for self.
The implementation here just returns an empty dict, but subclass may override.
- _increment_call_depth()
context manager for incrementing call_depth.
use “with self._increment_call_depth():” inside of __call__, e.g.:
def __call__(self, *args, **kw):with self._increment_call_depth():# do stuff; possibly including calling self again.Equivalent to self.call_depth_manager.increment()
- _load_across_dims_postprocess(arrs, dims, *, it_dimnames, assign_coords, isel=None)
postprocessing results from load_across_dims, after all tasks have been completed.
i.e., after all arrays have been loaded, join them all together.
- _load_across_dims_postprocess__arrs_to_nparr(arr0, arrs)
returns single numpy array (with the data from arrs, which is an array of arrays).
- _load_across_dims_postprocess__broadcast_shapes(arr0, arrs, it_dimnames)
handles array broadcasting for _load_across_dims_postprocess.
returns (arr0, arrs), but with all arrs having the same shape as arr0. Crash if not possible.CAUTION: may edit arrs in-place.(Won’t edit individual arrays’ data; just arrs which contains the arrays.)NOTE: arr0 in result isn’t necessarily arrs.flat[0].arr0 in result is the “model array”, used to model coords & dims on.arr0 = first DataArray with size == max(size) across all arrays.E.g. if array shapes are [(), (), (7,1), (1,3), (7,3), (7,3) ()],then use arr0 = the first DataArray with shape (7,3).if neither array with shape (7,3) is a DataArray (i.e., has coords…)then crash instead (because we can’t properly assign coords to result.)it_dimnames: list of names of iterable dimensions; sometimes included in error message.
- _load_maindims_var_with_labels(var, *args, **kw)
equivalent to self.load_maindims_var(var, *args, assign_labels=True, **kw)
- _load_maindims_var_without_labels(var, *args, **kw)
equivalent to self.load_maindims_var(var, *args, assign_labels=False, **kw)
- _loi_integration_coord()
return coord to use for integration, as implied by self.loi.
Just like self._loi_integration_dim(), but if result ends with ‘_dim’, remove it.E.g. if _loi_integration_dim() == ‘grid_dim’, this returns ‘grid’.
- _loi_integration_dim(*, signed=False)
return dimension along which to integrate, as implied by self.loi.
Crash with InputMissingError if self.loi implies no integration.signed: boolwhether to start with ‘-’ to imply “cumsum in reverse order” inside loi_cumsum().E.g. ‘-z’ –> array.isel(z=slice(None,None,-1)).cumsum(‘z’) instead of array.cumsum(‘z’).
- _loi_interp_dict()
return dict of arrays to interpolate onto, as implied by self.loi.
result is None if self.loi implies “no interpolation”.Crash if invalid self.loi.
- _loi_is_ray_draping()
returns whether self.loi implies to do ray draping.
True if self.loi == ‘ray_draping’, or if self.loi == ‘los’ and los == ‘ray_draping’ or ‘-ray_draping’.
- _max_n_requires_float64()
returns whether max supported n, in self.units unit system, is too big for float32.
max supported n, in SI units, is DEFAULTS.MHD_MAX_SAFE_N_SIcrash with ValueError if max supported n is too big for float64 as well.without this check (and conversion to float64 if needed), some n values might become inf.
- _multi_slices_cls
alias of
MultiSlices
- _multi_slices_dims_default()
function to get multi_slices dims, by default.
Would love to use (lambda: self.maindims) instead of this function,however lambdas are not pickleable, thus incompatible with multiprocessing module.Providing this function allows the default multi_slices to still be pickleable.
- _new_fft_slices()
Called when self.fft_slices accessed but not yet set; create & return new FFTSlices.
- _new_multi_slices(**kw)
called when self.multi_slices accessed but not yet set; create & return new MultiSlices.
- classmethod _parenthesis_converted_var(before, here, after)
returns the var after converting it from var like ‘{before}({here}){after}’.
use same before & after, but use {i} instead of here.Looks like: f’{before}{{{key}}}{after}’ where key=int, unique to this var.
- _parenthesis_dep(_var, groups)
returns the ‘dep’ associated with this var for get_parenthesis.
- _pop_kw_call_options(kw)
pop all self.kw_call_options() from kw, returning dict of popped options.
- _pre_and_post_deriv_slices(x)
return slices to apply before & after differentiation. (result is a 2-tuple of dicts.)
x: str, or list of str.
only slices relevant to these dimensions will be adjusted.(e.g. there’s no need to touch ‘y’ slices during ddx.)Result depends primarily on self.deriv_before_slice.Note if self.deriv_before_slice=False, this method just returns (self.slices, {}).
- _print_or_warn(msg, debug_thresh=1)
if DEBUG>=debug_thresh, print msg. Else, warnings.warn(msg).
- _provided_val(var, _val=None, _known_vals={})
returns the value of var, either from _known_vals or _val.
if _val provided, return it; if ‘_{var}’ in _known_vals, return it;if both provided, crash with InputConflictError (unless they are the same object),else, return None.Can use this internally to avoid redundant recalculations. (See e.g. VectorArithmeticLoader)
- _radiative_assert_single_component()
asserts self.current_n_component() == 1; raise ComponentValueError otherwise.
The error message will be particularly helpful and give options for how to fix the error.
- _registry_metadata()
return metadata relevant to registering this run.
This includes all of self.metadata, along with calculator_type and pc_uuid.(Uses self.metadata not self.metadata_all; excludes any missing or ATTR_UNSET.)If self.pc_uuid does not exist, it will be created via self.get_pc_uuid().
- _registry_metrics(metrics)
return dict of metrics’ values relevant to registering this run with these metrics.
Strings in metrics will be converted to {key: self(key)} entries.e.g. metrics=[‘mean_T’] –> result is {‘mean_T’: self(‘mean_T’)}dicts will be used as-is.Result will be a dict of {key: (is_pc_quantity, value)} entries,with is_pc_quantity telling whether metric was computed via self(key),i.e. whether it was a string in the input metrics list.
- _repr_contents()
return list of contents to go in repr of self.
- _slice_maindims_numpy(array, *, h5=False)
slice first len(maindims) dims of array, using self.slices.
h5: bool
whether ‘array’ might be an h5py dataset.if True, handle negative step in the intuitive way;i.e. slice with positive step, to select the expected points, then reverse order.(This is necessary because h5 datasets crash when sliced by negative step…)
- _slices_which_scalarize()
return list of maindims which become scalars when hit by self.slices.
- _special_dims_shifters(dimnames, _shift_special)
return (dict for self.using(…), dict for result.isel(…)) to _shift_special_dims.
See docs of load_across_dims for more details.
- _specialized_kw_call_options(kw)
specialize popped kw_call_options, adjusting keys and/or values as needed,
to be suitable to pass to self.using(**kw).kw may be edited IN PLACE.Overriding this is discouraged, unless using property setters/getters is truly insufficient.If overriding this method, consider also overriding self._help_specialized_kw_call_options,to add documentation (inside self.help_call_options()) for any specialized kw call options.self.__call__ uses this method as follows:using=self._pop_kw_call_options(kw)using = self._specialize_using_kw_call_options(using)with self.using(**using):# <– majority of self.__call__ functionality goes here.The implementation here looks for any maindims in kw, using them to adjust relevant slices.Example: kw=dict(z=slice(100)) –> returns dict(slices={**self.slices, **{‘z’: slice(100)}})Example: kw=dict(y=9, slices=dict(x=8)) –> returns dict(slices=dict(x=8, y=9)).All other kwargs remain unchanged.
- _tfbi_vs_EBspeed_file()
returns expected abspath to file for storing tfbi solution across EBspeed grid.
Depends on current value of self.tfbi_EBspeed_grid_size.Does not check whether file exists already(might use this to find existing file, or to determine filepath for saving result.)Result is like:{self.unique_notes_dirname}/_pc_tfbi/EBspeed_{logmin:.4g}_{logmax:.4g}_{logstep:.4g}.pcxarr
- _tile_snaps_snaps()
returns [pre-current, post-current] snaps to tile along based on self.tile_snaps and self.snap.
(raise ValueError if self._tile_snaps is False, InputError if not exactly 1 ‘current’ snap indicator,or SnapValueError if self.snap_is_iterable())pre-current and post-current are (possibly empty) lists of Snap objects.
- _upcast_if_max_n_requires_float64(array)
if max n requires float64, upcast array to float64,
unless array’s dtype was already float64 or larger (in which case, just return array).see self._max_n_requires_float64 for details on when max n requires float64.
- _var_for_load_fromfile(varname_internal)
return var, suitably adjusted to pass into load_fromfile().
Here, follow the steps:(1) if self._loading_component, append self.component.E.g. ‘result_prim_b’ turns into ‘result_prim_bz’ when loading ‘z’ component.(2) convert result_prim_… via self._RESULT_PRIM_VAR_TO_FILEBASE, if applicable.E.g. ‘result_prim_bx’ becomes ‘result_prim_5’.
- _vdem_multiply_then_sum_along(*arrays, dim)
multiply arrays then sum along dim, without making big intermediate array.
Like xarray_multiply_then_sum_along, but uses vdem-relevant defaults from self.
- 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.)[Implementation currently just returns xarray_angle_xy(A)]
- 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.[Implementation currently just returns xarray_angle_xy_to_hat(A)]
- 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 dictvalues 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})
- property assert_masking
whether to assert self.masking != False and mask is not None, when getting values.
- assert_single_fluid_mode(varname='var', *, mode='getting')
asserts that self is in single fluid mode; else crash.
varname: strname of var to include in error message if crashing.mode: str, ‘getting’ or ‘setting’determines error type & error message if crashing.‘getting’ –> FluidValueError, with error message starting like:“{type(self)} getting {varname} requires self.in_single_fluid_mode…”‘setting’ –> SetvarNotImplementedError, with error message starting like:“var={varname}, when self not in_single_fluid_mode…”Use for operations which directly assume single fluid mode (e.g. get_r implementation here).Not necessary for operations which apply regardless of number of fluids,E.g. n = r / m for any number of fluids, and B is always independent of fluid.If unsure, err on the side of caution and use this function,to require multifluid subclass to explicitly handle the situation else crash.
- property assign_behavior_attrs
whether to assign self.behavior values as attrs of result when calling self.
False –> don’t use self.behavior code architecture to assign attrs.True –> equivalent to ‘nondefault’‘nondefault’ –> self.behavior.assign_nondefault_attrs(result)(for brevity, it does not assign behavior attrs with “default” value.)‘all’ –> self.behavior.assign_attrs(result).[EFF] only assigns attrs at call_depth >= self.assign_behavior_attrs_max_call_depth.(default: only assigns attrs at call_depth=1, i.e. at top level.
- property assign_behavior_attrs_max_call_depth
max call_depth at which to assign_behavior_attrs to result,
if self.assign_behavior_attrs indicates to assign behavior attrs.default 1, i.e. only assign if at top level.Use None to indicate “no max depth”.
- property assign_behavior_attrs_skip_xr
whether to use include_xr=False if self.assign_behavior_attrs,
during self.behavior.assign_nondefault_attrs.Use this if you want to assign behavior attrs EXCEPT array-valued behavior attrs.
- 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 selfassign only these dimensions as coords. (use all dimensions if len(dims)==0)skip: iterable of dimensions in selfdo not assign these dimensions as coords.
- assign_maindims_coords(array)
assign maindims dims and coords, based on self.get_maindims_coords() with slices=None.
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.(if self._slice_maindims_in_load_direct, actually uses self.slices instead of slices=None.)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 / mCannot be set directly; can only be manipulated via self.call_depth_manager.
- property call_depth_manager
stores the value of call_depth, and helps to manage attrs dependent on call_depth value.
- check_pickle(x=None)
checks that self (or, x, if provided) is pickleable, by pickling then unpickling.
Returns result of unpickling. Useful for debugging.
- chunker()
gets Chunker based on the current values of self.chunks and self.slices.
see help on MainDimensionsChunker, or help(type(self).chunks) for more details.
- property chunks
chunks for maindims when loading arrays.
E.g. chunks = dict(x=10, y_size=50)–> break x into 10 chunks total, and break y into chunks of size 50.(if y not divisible by 50, the last chunk will be smaller.)Can also provide a list of indexers for more low-level control,E.g. chunks = dict(x=[slice(0,50), 100, slice(800,900)])–> repeat calculation with x from 0 to 50, then 100th value, then 800 to 900.result will be a well-labeled xarray with x at those coordinates,here equivalent to result from slices=dict(x=[0,1,…,49,100,800,801,…,899])See help(self.chunker_cls) or help(self.chunker()) for more details.Notes:- mutually exclusive with providing slices of the same dims.E.g., cannot provide x chunk and x slice at the same time.- if provided, internally hijacks self.__call__ to do chunking instead,and inside of that will loop through calls to self with different slices.- only works for vars which keep the chunked axes.E.g., fails for self(‘mean_n’) since mean result doesn’t have maindims.
- classmethod cls_help(qstr=None, only=None, *, tree=None, modules=False, signature=False, doc=True, dense=False, print=True, **kw)
prints str for help with quants. Fails for any quants which depend on present values of a cls instance.
qstr: None or str
None –> tells info about this class & how to use this function.in particular, tells that quants are stored cls.KNOWN_VARS and cls.KNOWN_PATTERNS,and describes behavior of calling help with a string.str –> return str for help with all quants related to str.use empty str to get help for all quants.only: None or strIf provided, only get help for a subset of relevant quantities.None –> get help with all quantities related to qstr.‘VARS’ –> only get help with KNOWN_VARS.‘PATTERNS’ –> only get help with KNOWN_PATTERNS.‘TREE’ –> only get help with quantities in cls.cls_var_tree(str).‘EXACT’ –> only get help for the KNOWN_VAR exactly matching qstr.if provided when qstr is None, treat qstr as ‘’ instead.tree: None or boolHow much help to give for quantities in cls.cls_var_tree(qstr).False –> don’t even check cls.cls_var_tree(qstr).True –> help for all quantities in cls.cls_var_tree.None –> help for quantities in cls.cls_var_tree(qstr).flat_branches_until_vars()i.e. patterns & vars in tree but ignore any nodes with LoadableVar ancestors.e.g. qstr=’mean_mod_beta’ –> help with ‘mean_(.+)’, ‘mod_(.+)’, and ‘beta’,but no help with dependencies of ‘beta’ (‘q’, ‘mod_B’, ‘m’).modules: boolWhether to include modules in result.If True, result will be grouped into sections with modules written at top.signature: signature: boolwhether to include line with signature in help string.e.g. “help_str(f, *, module=True, signature=True, indent=None)”doc: doc: boolwhether to include lines with docstring in help string.e.g. “return str for help(f).” … and all the other docs in here.dense: boolWhether to reduce whitespace in result.E.g. True –> no newlines between functions. False –> one newline between functions.print: boolwhether to print the result. If False, return the result instead of printing.
- classmethod cls_var_tree(var, *, missing_ok=False)
return QuantTree of MatchedQuantity objects from matching var and all dependencies,
using self.KNOWN_VARS and self.KNOWN_PATTERNS when searching for matches.missing_ok: boolwhether to be lenient sometimes when missing details that would allow to fully determine deps.see help(MatchedQuantity.dep_vars) for more details.
- property component
alias to self.component_dim.v
- property component_array_equals
alias to self.component_dim.array_equals
- 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.DataArrayvectors to take cross product of.must include ‘component’ dimension including coordinates y and z.yz: None or iterable of two (int, str, or Component) objectsthe other two components; (x,y,z) should form a right-handed coordinate system.if not provided, infer from x.missing_ok: bool, default Falsewhether 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.[Implementation currently just returns xarray_cross_component(A, B, x, yz=yz, …)]
- cross_components_needed()
return the components vectors need in order to find all cross product components in self.component_list
e.g. if self.component == ‘x’, return (‘y’, ‘z’), because (A_cross_B)_x needs Ay, Az, By, Bz but not Ax, Bx.
- static cross_product(A, B, *, components=None)
return cross product of vectors A and B, along dimension ‘component’.
If A or B missing any components, treat them as 0.components: None or iterable of component specifiers (int, str, or Component)tells which components to get.None –> get all components (XYZ)e.g., (0, ‘z’) –> get component 0 and component ‘z’, i.e. X and Z.[Implementation currently just returns xarray_cross_product(A, B, components=components)]
- 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 Componenttells component to get. if int or str, use self.components to get corresponding Componentyz: None or iterable of two (int, str, or Component) objectsthe 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_snap
alias to self.snap_dim.current_n
- property data_array_dtype
numpy dtype of each data array. default is np.dtype(‘float32’).
Used by np.memmap during self.load_fromfile.
- property data_array_nbytes
number of bytes in each data array. (from data_array_size and data_array_dtype)
- property data_array_order
ordering of data array axes: ‘F’ (Fortran) or ‘C’ (C order). Default ‘F’.
- property data_array_shape
shape of each array of data stored in files. (‘N0’, ‘N1’, ‘N2’) from self.params.
Shape with (x, y, z) dimensions is some transposition of the result;transpose order stored in ‘layout.order’ file, see also self.params[‘order’].
- property data_array_size
array size (number of elements) of each data array. (from data_array_shape)
- property datetime_run
datetime corresponding to roughly when this run was created.
As isoformat string like: “YYYY-MM-DDTHH:MM:SS.ssssss+00:00” (UTC timezone).CAUTION: this is a best-effort estimate which may vary across operating systems.Result is from file system timestamp of first snapshot in self.existing_snaps() if any exist,else ATTR_UNSET.
- 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 iterableif 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 strsif 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 iterableif provided, only include these dimensions.See also: dims_apply
- directly_loadable_vars(snap=None)
return tuple of directly loadable variables for this snap.
snap: None, str, int, Snap, or iterable indicating multiple snaps.
None –> use self.snap.multiple snaps –> return result if all snaps have same result, else crash.
- property dirname
abspath to directory containing data for this DirectLoader.
- property div
alias to divergence
- static divergence(array, components=[Component('x', 0), Component('y', 1), Component('z', 2)], *, _post_slices=None)
return divergence of array.
The result will not have ‘components’ dimension.components: iterable of str or Component objectswhich components to include in the calculation.E.g., if components=[Component(‘x’, 0), Component(‘y’, 1)],then result = d(array)/dx + d(array)/dy.The derivative is taken along the corresponding dimension,e.g. d(array)/dy is xarray_differentiate(array, dim=’y’)._post_slices: None or dict of indexers[EFF] if provided, apply these indexers to results after taking each derivative,but before merging into the final array.Equivalently, could just result.isel(**_post_slices).But, indexing before merging can help avoid ever creating a large array.
- property dot
alias to dot_product
- static dot_product(A, B)
return dot product of vectors A and B, assuming vector components in the ‘component’ dimension.
[Implementation currently just returns xarray_dot_product(A,B)]
- 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 elements
ElementList of all elements in multifluid mixture assumed from single-fluid mhd.
Used to infer SINGLE_FLUID m.
- property emiss_mode
string telling emission measure mode.
Depends on (and can be used to set) emiss_trac and emiss_opa.‘notrac_noopa’ <–> emiss_trac=False, emiss_opa=False‘trac_noopa’ <–> emiss_trac=True, emiss_opa=False‘notrac_opa’ <–> emiss_trac=False, emiss_opa=True‘trac_opa’ <–> emiss_trac=True, emiss_opa=TrueSetting string sets emiss_trac and emiss_opa accordingly.Getting string returns result according to emiss_trac and emiss_opa.(Currently included for backwards compatibility, might be removed eventually.)
- property emiss_norm
Emission Measure normalization factor. Used in self(‘emiss’)
and related vars. emiss = unnormed_emiss / emiss_norm.
- property emiss_opa
whether to include opacity in emission measure (self(‘emiss’)).
- property emiss_trac
whether to include TRAC correction in emission measure (self(‘emiss’)).
- property emiss_trac_coeff
TRAC coefficient for emiss_trac calculation.
transition region using an adaptive conduction coefficient (Johnston et al. 2020).
- 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_snap
alias to self.snap_dim.enumerate
- property enumerate_snaps
alias to self.snap_dim.enumerate_values
- property eos_mode
mode for “Equation of State” related variables (ne, T, P).
see EOS_MODE_OPTIONS for details about available options.
- property eos_mode_P
None or str telling the eos_mode for pressure, e.g. ‘aux’.
None –> ignored; just use self.eos_mode. See help(type(self).eos_mode) for details.
- property eos_mode_P_explicit
alias to self.eos_mode_P if not None, else self.eos_mode.
Probably: internal methods use this, but user only uses eos_mode_P.
- property eos_mode_T
None or str telling the eos_mode for temperature, e.g. ‘aux’.
None –> ignored; just use self.eos_mode. See help(type(self).eos_mode) for details.
- property eos_mode_T_explicit
alias to self.eos_mode_T if not None, else self.eos_mode.
Probably: internal methods use this, but user only uses eos_mode_T.
- property eos_mode_ne
None or str telling the eos_mode for electron number density, e.g. ‘aux’.
None –> ignored; just use self.eos_mode. See help(type(self).eos_mode) for details.
- property eos_mode_ne_explicit
alias to self.eos_mode_ne if not None, else self.eos_mode.
Probably: internal methods use this, but user only uses eos_mode_ne.
- 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 strscoordinates(s) to take fft over.Can be pre-fft or post-fft names. (e.g. ‘x’, ‘freq_x’, ‘freqrad_x’, ‘k_x’)promote_dim(array, coord) for any non-dimension coordinates, as needed.None –> equivalent to array.dimsstr –> just this coordinate.iterable of strs –> just these coordinates.ds: None, number, or dict of {dim: d}spacing between elements of array (pre-transform), along each dim.if number, use the same value for all dims.if None, infer via array.coords[dim].diff(dim) for each dim(requires evenly-spaced coordinates in dim; spacing checked with np.allclose)rad: None or boolwhether 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: boolif True, return np.abs(result), instead.slices: dict or FFTSlicesinstructions for slicing the final result.Can provide {cname: indexer} instructing to slice post-fft dimensionassociated with cname, via indexer. (cname can be pre-fft or post-fft name.)These understand fractional indexing: can provide a fractional valuebetween -1 and 1, to use that fraction of the length along the relevant dimension.Can also providekeep,half,step, and/ormissing_slices, here (Or, as kwargs).(raise InputConflictError if any provided in both places and have conflicting values.)See those kwargs for more details.keep: None, True, dict, or number in 0 < keep <= 1implies 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 strsdimensions 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 1step to take along each dim.(ignored for any dimensions which already have a slice specified.)fractional value –> use fraction of length (e.g. 0.01 –> 1% of dim length), min |step|=1.negative –> reverses direction (and swaps start & stop for the slice)None –> equivalent to using step=1.dict –> different value in each dimension;keys can be pre-fft OR post-fft dimension names.UNSET –> use None.missing_slices: ‘ignore’, ‘warn’, or ‘raise’tells how to handle keys not matching any fft-related coordinate.‘ignore’ –> silently ignore these keys. This is the default.‘warn’ –> issue a warning.‘raise’ –> raise an error.UNSET –> use ‘ignore’additional kwargs passed to np.fft.fftn.returns result of fftn(…), shifted such that the 0-frequency is in the center,and with the relevant dimensions renamed as specified.
- property fft_dims
the dims over which to possibly apply fft (FFTLoader methods).
will only apply fft along these dims for an array if they actually appear in the array.None –> use self.maindims. (this is the default.)See also: self.fft_dims_for(array).
- fft_dims_for(array)
return the dims over which to apply fft for this array.
This is the intersection of self.fft_dims and array.dims.
- property fft_half
alias to self.fft_slices.half
- property fft_keep
alias to self.fft_slices.keep
- property fft_slices
the dict of indexers to apply to all fft results from self, by default.
keys can be a pre-fft or post-fft dimension name,e.g. ‘x’ or ‘freq_x’ both lead to slicing of the result’s ‘freq_x’ dimension.(note if rad=True it would be ‘k_x’ in the result, and ‘x’ would apply but not ‘freq_x’.)all other keys (not a pre-fft or post-fft dimension name) are ignored.values can be slice, int, iterable, or non-integer value between -1 and 1.fractional values are interpreted as a fraction of the length of the corresponding dimension,as per interprets_fractional_indexing. Negative fractions refer to distance from the end.e.g., dict(x=slice(-0.3, None, 0.01), y=0.8), where x and y correspond to length 1000,would be equivalent to dict(x=slice(-300, None, 10), y=800).Can also have special keys (which apply to all fft dims without a specifically-related key):keep: fraction of each dimension to keep,e.g. keep=0.4 with length=1000 would result in slice(300, 700),since that keeps 400 out of 1000 points, and is centered at 1000/2.half: dimension(s) along which to keep only the right half of the result.step: slice step. Can also be fractional to use fraction of dimension length.For more help on special keys, see help(self._fft_slices_cls) or help(FFTSlices)
- property fft_step
alias to self.fft_slices.step
- gaussian_filter(array, dim=UNSET, sigma=UNSET, **kw_xarray_gaussian_filter)
xarray_gaussian_filter with defaults from self.blur_dims, self.blur_sigma.
kwargs are passed to xarray_gaussian_filter.For convenience, docs for xarray_gaussian_filter are copied below:xarray_gaussian_filter_docs—————————returns array after applying scipy.ndimage.gaussian_filter to it.array: xarray.DataArray or Datasetfilters this array, or each data_var in a dataset.dim: None or str or iterable of strsdimensions to filter along.if None, filter along all dims.sigma: None, number, or iterable of numbersstandard 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: boolwhether 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 Muram)
- get_B_tension()
magnetic tension = (B dot grad) B / mu_0.
- get_E()
electric field.
[Not implemented for this class]
- get_E0S1(*, _skappa=None, _E0n0=None)
E0S1 = sum_s E0S1s, where E0S1s = (qs ns skappa_s / (1 + skappa_s^2)),
and the sum is across all charged fluids (from self.fluids).see help(self.get_E0_un0_perpB) for more details. Note: ne depends on self.E0_ne0_mode.[EFF] for efficiency, can provide _skappa and/or n (via _E0n0) 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))Note: ne depends on self.E0_ne0_mode.
- get_E0S1s(*, _skappa=None, _E0n0=None)
E0S1s = qs ns skappa_s / (1 + skappa_s^2).
See help(self.get_E0_un0_perpB) for more details. Note: ne depends on self.E0_ne0_mode.See also: self.get_E0S1() which sums across all charged fluids.[EFF] for efficiency, can provide _skappa and/or n (via _E0n0) if known(though, they must have ‘fluid’ coord matching self.fluid).
- get_E0S2(*, _skappa=None, _E0n0=None)
E0S2 = sum_s E0S2s, where E0S2s = (qs ns skappa_s^2/ (1 + skappa_s^2)),
and the sum is across all charged fluids (from self.fluids).see help(self.get_E0_un0_perpB) for more details. Note: ne depends on self.E0_ne0_mode.[EFF] for efficiency, can provide _skappa and/or n (via _E0n0) if known.
- get_E0S2s(*, _skappa=None, _E0n0=None)
E0S2s = qs ns skappa_s^2/ (1 + skappa_s^2).
See help(self.get_E0_un0_perpB) for more details. Note: ne depends on self.E0_ne0_mode.See also: self.get_E0S2() which sums across all charged fluids.[EFF] for efficiency, can provide _skappa and/or n (via _E0n0) if known(though, they must have ‘fluid’ coord matching self.fluid).
- get_E0_etaJ_perpB(*, _E0S1=None, _E0S2=None)
E0_perp_B = E0_etaJ_perpB + …, where E0_etaJ_perpB = eta0_J * J_perp_B.
see help(self.get_E0_un0_perpB_fromJ) for more details.
- get_E0_hall(*, _E0S1=None, _E0S2=None)
E0_perp_B = E0_hall + …, where E0_hall = eta0_hall * J x Bhat.
see help(self.get_E0_un0_perpB) for more details.
- get_E0_un0_perpB()
E0_un0_perpB = E0_etaJ_perpB + E0_hall
== eta0_J * J_perp_B + eta0_hall * J x Bhat== (E0S1 |B| J_perp_B + E0S2 B cross J) / (E0S1^2 + E0S2^2), whereE0S1 = sum_s (qs ns skappa_s / (1 + skappa_s^2)),E0S2 = sum_s (qs ns skappa_s^2/ (1 + skappa_s^2)),Note: ne depends on self.E0_ne0_mode.This is the electric field in the un=0 frame of reference, assuming:- zeroth order equilibrium velocities from multifluid equations,- including only collisions with neutrals,- considering only E (& J) perp to B; ignoring E0 (& J) parallel to B.
- get_E0_un0_perpmodB()
E0_un0_perpmodB = |E0_un0_perpB|.
Should be equivalent to self(‘mod_E0_un0_perpB’), aside from rounding errors.[EFF] the method here uses an algebraic simplification of the E0_un0_perpB formula:E0_un0_perpB == (E0S1 |B| J_perp_B + E0S2 B cross J) / (E0S1^2 + E0S2^2)–> (do some algebra, and utilizing J_perp_B dot B = 0) –>E0_un0_perpmodB = (|B| |J_perp_B|) / sqrt(E0S1^2 + E0S2^2)
- get_E0_un0_perpmodB_min()
E0_un0_perpmodB_min = minimum possible value of |E0_un0_perpB|, at each point.
E0_un0_perpmodB_min = (1/sqrt(2)) * |B| |J_perp_B| / (ne |qe|)Regardless of kappa (& nusn) values for electrons and ions, will always have:E0_un0_perpmodB >= E0_un0_perpmodB_min.Logic which proves this fact (below, using “K” as shorthand for “skappa”):E0_un0_perpmodB has sqrt(E0S1^2 + E0S2^2) in the denominator;–> when sqrt(E0S1^2 + E0S2^2) is largest, E0_un0_perpmodB will be smallest.sqrt(E0S1^2 + E0S2^2) is largest when |E0S1| and |E0S2| are both largest.(1) |E0S1| <= sum_s (|qs| ns |Ks| / (1 + Ks^2))(2) |E0S2| <= sum_s (qs ns Ks^2 / (1 + Ks^2))For ANY real K, the relevant quantities are bounded by:(i) 0 < |K| / (1 + K^2) <= 1/2(ii) 0 < K^2 / (1 + K^2) < 1which can be readily shown using introductory calculus:|K|/(1+K^2) has local extrema (derivative=0) only at K=1, where |K|/(1+K^2)=1/2;it tends to 0 when K->0; and it tends to 0 when K->inf.K^2/(1+K^2) has local extrema (derivative=0) only at K=0, where it equals 0;it tends to 0 when K->0; and it tends to 1 when K->inf.Applying (i) to expression (1) above yields:|E0S1| <= sum_s |qs| ns * 1/2Utilizing quasineutrality (sum_s qs ns = 0) and qe < 0 and qi > 0, provides:sum_s |qs| ns = ne |qe| + sum_i ni qi = 2 ne |qe|–> |E0S1| <= ne |qe|Meanwhile for expression (2), note that because qe < 0 and qi > 0,ne qe (Ke^2 / (1 + Ke^2)) has opposite the sign as sum_i ni qi Ki^2 / (1 + Ki^2),so the largest possible |E0S1| occurs when one of those two terms is as small as possible.Applying (ii) to each term, and quasineutrality to the second term, yields:|ne qe (Ke^2 / (1 + Ke^2))| < ne |qe||sum_i ni qi Ki^2 / (1 + Ki^2)| < sum_i ni qi = ne |qe|–> |E0S2| < ne |qe|Combining yields:sqrt(E0S1^2 + E0S2^2) < sqrt(2) ne |qe|Thus, we always have:(|B| |J_perp_B|) / sqrt(E0S1^2 + E0S2^2) >= (|B| |J_perp_B|) / (sqrt(2) * ne |qe|)i.e. E0_un0_perpmodB >= E0_un0_perpmodB_min.
- get_E0_un0_perpmodB_simple()
E0_un0_perpmodB_simple = simple estimate of |E0_un0_perpB|, at each point.
E0_un0_perpmodB_simple = (|B| |J_perp_B|) / (ne |qe|)This is a simple estimate of |E0_un0_perpB|, accurate when kappae>>1 and kappai<<1.
- get_E0n0(*, E0n0type)
n0 for E0 calculations. Electron result depends on self.E0_ne0_mode.
In ‘direct’ mode, just returns self(‘n’).In ‘QN’ mode, gives self(‘n’) for ions, but sum_i(qi ni)/|qe| for electrons.(When in ‘direct’ mode, E0n0type should be ‘n’ for all species.When in ‘QN’ mode, E0n0type will be ‘e’ for electrons, ‘n’ for ions.)
- get_E0n0type()
n type for E0 calculations. Depends on self.E0_ne0_mode.
In ‘direct’ mode, always ‘n’.In ‘QN’ mode, either ‘n’ (for ions) or ‘e’ (for electrons).
- get_EBspeed()
speed determined from E_un0 and B: |E_un0 perp to B| / |B|.
- get_E_un0()
E_un0 = electric field in the neutral frame, where u_n=0.
Result depends on self.E_un0_mode; see help(type(self).E_un0_mode) for details.
- get_E_un0_perpmod_B(**kw_perpmod)
E_un0_perpmod_B == |E_un0 perp to B| == magnitude of E, perp to B, in u_neutral=0 frame.
This is usually equivalent to using self.magnitude(self.take_perp_to(B, E_un0)),but if E_un0_mode = ‘E0_perpmodB’ will use more efficient method (self(‘E0_un0_perpmodB’)),and if E_un0_mode = ‘E0_perpmodB_min’ will use different method (self(‘E0_un0_perpmodB_min’)).kwargs are passed to self.get_perpmod, if applicable.
- get_E_un0_type()
string telling method that will be used to get E_un0. Based on self.E_un0_mode.
possible results include (but may be adjusted further by subclasses):‘nan’ <–> will crash. (e.g. this occurs if E_un0_mode = ‘E0_perpmodB_min’)‘E+unxB’ <–> self(‘E’) + self(‘u_neutral_cross_B’)‘E_u0’ <–> self(‘E_u0’)‘E+uxB’ <–> self(‘E’) + self(‘u_cross_B’)‘E’ <–> self(‘E’)‘E0_perpB’ <–> self(‘E0_un0_perpB’)
- get_Eheat()
Eheat = Eheat_perp + Eheat_par. total heating from electric field. Units of Kelvin.
From assuming u_n=0 and derivatives=0 in heating & momentum equations, which yields:
T_s = T_n + Eheat_perp + Eheat_par, whereEheat_perp = Eheat_perp_coeff * |E_perp|^2,Eheat_par = Eheat_par_coeff * |E_par|^2,E_perp = E(in u_n=0 frame) perp to B,E_par = E(in u_n=0 frame) parallel to B,Eheat_perp_coeff = (m_n / (3 kB)) (kappa_s^2 / B^2) * (1 / (1 + kappa_s^2)),Eheat_par_coeff = (m_n / (3 kB)) (kappa_s^2 / B^2).
- get_Eheat_par(*, _E_un0=None, _B=None, _Eheat_par_coeff=None)
Eheat_par = Eheat_par_coeff * |E_par|^2. heating parallel to B. Units of Kelvin.
see help(self.get_Eheat) for more details.[EFF] for efficiency, can provide _E_un0, _B and/or _Eheat_par_coeff if known.caution: if providing _E_un0 or _B, will assume any missing components are 0.
- get_Eheat_par_coeff()
Eheat_par = Eheat_par_coeff * |E_par|^2. for E heating parallel to B. Units of Kelvin.
see help(self.get_Eheat) for more details.
- get_Eheat_perp(*, _E_un0=None, _B=None, _Eheat_par_coeff=None)
Eheat_perp = Eheat_perp_coeff * |E_perp|^2. heating perp to B. Units of Kelvin.
see help(self.get_Eheat) for more details.[EFF] for efficiency, can provide _E_un0, _B and/or _Eheat_par_coeff if known.caution: if providing _E_un0 or _B, will assume any missing components are 0.
- get_Eheat_perp_coeff(*, _Eheat_par_coeff=None)
Eheat_perp = Eheat_perp_coeff * |E_perp|^2. for E heating perp to B. Units of Kelvin.
see help(self.get_Eheat) for more details.[EFF] for efficiency, can provide _Eheat_par_coeff if known.
- get_Eheat_perp_rate_n()
zeroth order rate of heating of neutrals due to collisions with all charged species.
Eheat_perp_rate_n = sum_s Eheat_perp_rate_n_s== sum_s 2 * nuns * Eheat_perp== sum_s 2 * (m_s / m_n) * (n_s / n_n) * nusn * Eheat_perp== sum_s (2 m_s / (3 kB)) * (n_s / n_n) * nusn * (kappa_s^2 / (1 + kappa_s^2)) * (|E_perp|^2 / |B|^2)Derived from plugging T_from_Eheat_perp and |u_drift| formulae into the neutral heating equation:dTn/dt + (2/3) T_n div(u_n) =sum_s (2 m_n / (m_n + m_s)) nu_{n,s} [(m_s / (3 kB)) |u_s - u_n|^2 + (T_s - T_n)]in the neutral reference frame (u_n=0),and using m_n n_n nu_{n,s} = m_s n_s nu_{s,n} which comes from conservation of momentum.
- get_Eheat_perp_rate_n_s()
zeroth order rate of heating of neutrals due to collisions with s (self.fluid).
Eheat_perp_rate_n_s = 2 * nuns * Eheat_perp== 2 * (m_s / m_n) * (n_s / n_n) * nusn * Eheat_perp== (2 m_s / (3 kB)) * (n_s / n_n) * nusn * (kappa_s^2 / (1 + kappa_s^2)) * (|E_perp|^2 / |B|^2)Derived from plugging T_from_Eheat_perp and |u_drift| formulae into the neutral heating equation:dTn/dt + (2/3) T_n div(u_n) =sum_s (2 m_n / (m_n + m_s)) nu_{n,s} [(m_s / (3 kB)) |u_s - u_n|^2 + (T_s - T_n)]in the neutral reference frame (u_n=0),and using m_n n_n nu_{n,s} = m_s n_s nu_{s,n} which comes from conservation of momentum.See also: Eheat_perp_rate_n
- get_Epar()
electric field, parallel to B. This is a full 3-vector.
Equivalent: self(‘E_par_B’) == (E dot Bhat) Bhat
- get_Eperp()
electric field, perpendicular to B. This is a full 3-vector.
Equivalent: self(‘E_perp_B’) == E - self(‘E_par_B’) == E - (E dot Bhat) Bhat
- get_F_lorentz()
Lorentz force = q(E + u x B).
- get_Gofnt(var, *, _match=None)
G(T,ne) from ChiantiPy and muse library for a given ion. E.g., GofT_fe_9_ion
Always in [cgs] (erg*cm^3/s/sr) regardless of self.units.ion string (like ‘fe_9’) is passed into muse.instr.utils.chianti_gofnt_linelist,via ionList = [ionstr]. See that function for more details about available ions.“returns G(T,ne) and spectral line properties, including wavelength and transition probabilities.”[TODO] what does that mean?CAUTION: directly adjusts the value of self.rcoords_wavelength_A, based on result.
- get_Gofnt_atmos(var, *, _match=None)
Interpolated G(T) with temperature, for a given ion.
Always in [cgs] (erg*cm^3/s/sr) regardless of self.units.For details about available ions, see muse.instr.utils.chianti_gofnt_linelist
- get_Gofnt_em(var, *, _match=None)
Emission * G(T) for a given ion. Results always in [cgs] (erg/cm^2/s/sr).
For details about available ions, see muse.instr.utils.chianti_gofnt_linelist
- get_Gofnt_em_interp(var, *, _match=None)
Emission * G(T) for a given ion. Results always in [cgs] (erg/cm^2/s/sr).
For details about available ions, see muse.instr.utils.chianti_gofnt_linelist
- get_Gofnt_em_nointerp(var, *, _match=None)
Emission * G(T) for a given ion. Results always in [cgs] (erg/cm^2/s/sr).
For details about available ions, see muse.instr.utils.chianti_gofnt_linelist
- get_J()
current density (without displacement current). J = curl(B) / mu0.
Per unit area, e.g. the SI units would be Amperes / meter^2.
- get_JBspeed()
speed determined from J perp to B, and ne: |J_perp to B| / (ne * |qe|).
- get_Jf()
current density (associated with fluid). Jf = (nq * u) = (charge density * velocity)
This is per unit area, e.g. the SI units would be Amperes / meter^2.(If self is not a FluidHaver, this will equal the total current density.)
- get_P()
Temperature. Depends on self.eos_mode; see help(type(self).eos_mode) for details
(To override eos_mode for just P, can set self.eos_mode_P instead.)‘ideal’ –> cannot get pressure. Crash with TypevarNanError.‘table’ –> P from plugging r and e into EOS lookup tables (see self.tabin).‘aux’ –> get directly from Muram aux files.[more options might be available (depending on subclass) – see self.EOS_MODE_OPTIONS.]
- get_P_aux()
pressure, from ‘eosP’ file.
- get_P_fromtable()
pressure, from plugging r and e into eos tables (see self.tabin).
- get_P_ideal()
pressure (from ideal gas law?) P = (gamma - 1) * e
[TODO] when is this relation actually true? is it ideal gas law, or something else?
- get_T()
Temperature. Depends on self.eos_mode; see help(type(self).eos_mode) for details
(To override eos_mode for just T, can set self.eos_mode_T instead.)‘ideal’ –> cannot get temperature. Crash with TypevarNanError.‘table’ –> T from plugging r and e into EOS lookup tables (see self.tabin).‘aux’ –> get directly from Muram aux files.[more options might be available (depending on subclass) – see self.EOS_MODE_OPTIONS.]
- get_T_aux()
temperature, from ‘eosT’ file.
- 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_fromtable()
temperature, from plugging r and e into eos tables (see self.tabin).
- get_T_ideal()
temperature, assuming ideal gas law. P = n kB T –> T = P / (n kB)
- get_T_neutral()
temperature of neutrals; T_n = T of SINGLE_FLUID.
(subclass might implement better T, but here assumes T_n equivalent to SF_T.)
- get_Tapar(var, *, _match=None)
Tapar –> anisotropic temperature, parallel to B. This is a full 3-vector.
Equivalent: self(‘Ta_par_B’) == (Ta dot Bhat) BhatAlso supports ‘Tajoulepar’ to get value in energy units; == ‘Tapar*kB’.
- get_Taperp(var, *, _match=None)
Taperp –> anisotropic temperature, perpendicular to B. This is a full 3-vector.
Equivalent: self(‘Ta_perp_B’) == Ta - self(‘Ta_par_B’) == Ta - (Ta dot Bhat) BhatAlso supports ‘Tajouleperp’ to get value in energy units; == ‘Taperp*kB’.
- get_Tjoule()
temperature (“isotropic/maxwellian”), in energy units. Tjoule = kB * T.
self(‘Tjoule’) == self(‘kB*T’) == kB * T. (If using SI units, result will be in Joules.)
- get__vdem_ignores_photosphere_var(var, *, _match=None)
_vdem_ignore_photosphere_var –> self(var) but possibly setting values at z<0 to 0,
depending on self.vdem_ignores_photosphere.
- 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_absorption_h_he()
Absorption coefficient at wavelength=self.rcoords_wavelength_A,
considering only H, HeI, and HeII contributions.Result is always in [cgs] units, regardless of self.units.See Anzer & Heinzel, 2005 for details.absorption_h_he = (opacity from h and he) * (single-fluid mass density) / grph,where grph = mean molecular mass (same unit system as other terms in expression).Assuming photopsheric abundances, grph is roughly 1.3 to 1.5 amu, depending onexact abundances model (but constant in space & time; it just depends on self.elements).
- 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 iterableif 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}.pcxarrCAUTION: 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_chianti_opa1d_table(tabname='chianti')
Ionization state table from ChiantiPy.
result is an xr.Dataset with data_vars ‘h’, ‘he’, ‘hei’,telling the H, HeI, and HeII ionization fractions, respectively.
- get_compare_equals(var, *, _match=None)
self(‘A==B’) –> boolean array: self(‘A’) == self(‘B’)
- get_compare_greater_than(var, *, _match=None)
self(‘A>B’) –> boolean array: self(‘A’) > self(‘B’)
- get_compare_greater_than_or_equal(var, *, _match=None)
self(‘A>=B’) –> boolean array: self(‘A’) >= self(‘B’)
- get_compare_less_than(var, *, _match=None)
self(‘A<B’) –> boolean array: self(‘A’) < self(‘B’)
- get_compare_less_than_or_equal(var, *, _match=None)
self(‘A<=B’) –> boolean array: self(‘A’) <= self(‘B’)
- get_compare_not_equals(var, *, _match=None)
self(‘A!=B’) –> boolean array: self(‘A’) != self(‘B’)
- get_cross(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
cross product. {A}_cross_{B} –> A cross B.
returned components are determined by self.component.(see also: the get_xyz pattern. E.g., {A}_cross_{B}_x –> x component of A cross B)[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘u_cross_E’, _u=u, _E=E) –> u cross E, using u and E which are already known.CAUTION: if providing values, include all self.cross_components_needed() components;missing components will be assumed to be 0.E.g. if providing u to calculate u_cross_E, but u doesn’t have x component, assumes u_x=0.can alternatively provide _val0 for A and/or _val1 for B.
- get_crosscrossdotself(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
((A_cross_B)_cross_B)_dot_A.
if vid, will internally do calculations based on vector identities instead:
(AxB)xB).A = (A.B)^2 - A^2 B^2[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘u_crosscrossdotself_B’, _u=u, _B=B) –> ((u cross B) cross B) dot u,using u and B which are already known.can alternatively provide _val0 for A and/or _val1 for B.if not providing cached values, will always use self.component=None internally,because result is a dot product so it shouldn’t depend on present self.component.
- get_csound()
sound speed. csound = sqrt(gamma * P / r)
- get_csound2()
sound speed squared. csound2 = gamma P / r.
- get_curl(var, *, _match=None)
curl. ‘curl_{var}’ –> curl(var), i.e. (du_z/dy - du_y/dz, du_x/dz - du_z/dx, du_y/dx - du_x/dy).
returned components are determined by self.component.(see also: the get_xyz pattern. E.g., curl_u_x –> x component of curl(u))if self.slices nonempty, self.deriv_before_slice controls whether slicing occurs before or after div.
- get_dTndt()
rate of heating of neutrals due to collisions with all charged species.
dTndt = sum_s dTndt_s== sum_s 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2 + (T_s - T_n)]
- get_dTndt_s()
rate of heating of neutrals due to collisions with s (self.fluid).
dTndt_s = 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2 + (T_s - T_n)]
- get_dTndt_s_T()
temperature contribution to rate of heating of neutrals due to collisions with s.
dTndt_s_T = 2 m_n / (m_n + m_s) * nuns * [(T_s - T_n)]
- get_dTndt_s_ds()
dataset of contributions to rate of heating of neutrals due to collisions with s.
dTndt_s = 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2 + (T_s - T_n)]Assumes u_n==0; else crash with QuantCalcError.result has keys:‘dTndt_u2’: 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2]‘dTndt_T’: 2 m_n / (m_n + m_s) * nuns * [(T_s - T_n)]
- get_dTndt_s_u2()
velocity contribution to rate of heating of neutrals due to collisions with s.
dTndt_s_u2 = 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2]
- get_dTndt_turb0_s_ds()
dataset of contributions to neutral heating rate, based on ‘mean’ turbulent values,
for each fluid (in self.fluid), due to collisions.Assumes u_n==0, and does not check.result has keys:‘dTndt_u2’: 2 m_n / (m_n + m_s) * nuns * [(m_s / (3 kB)) |u_s|^2]‘dTndt_T’: 2 m_n / (m_n + m_s) * nuns * [(T_s - T_n)]Except, use werrmeant_sureturb_u instead of u_s,and werrmeant_sureturb_T instead of T_sFor more accurate computation, consider self(‘werrmeant_sureturb_dTndt_s’)
- get_deg2rad(var, *, _match=None)
convert degrees to radians. deg2rad_{A} –> A * pi / 180.
self(‘deg2rad_var’) == np.deg2rad(self(‘var’))
- get_delta(var, *, _match=None)
perturbation. var - mean(var). Applied only along any self.stat_dims in array.
- get_deltafrac(var, *, _match=None)
perturbation. (var - mean(var)) / mean(var). Applied only along any self.stat_dims in array.
- get_derivative(var, *, _match=None)
derivative. dd{x}_{var} –> d{var}/d{x}.
self(var) must return an object with {x} in its coordinates.E.g. for x=’y’, self(var).coords[‘y’] are required.
- get_div(var, *, _match=None)
divergence. ‘div_{var}’ –> div(var), i.e. du_x/dx + du_y/dy + du_z/dz.
if component(s) is provided, only include that component(s) during the calculation.e.g. div_u__xy –> du_x/dx + du_y/dy.if self.slices nonempty, self.deriv_before_slice controls whether slicing occurs before or after div.
- get_divide(var, *, _match=None)
division. var0 / var1.
- get_dloi()
dloi = coord spacing to use for integration as implied by self.loi.
E.g. if self.loi implies integration along ‘x’ then this is basically dx(accounting for self.slices as needed; see also: self.get_maindims_dim_didx)Result’s values use self.units; coords use self.coords_units (default==self.units).(e.g., units=’cgs’, coord_units=’si’ –> values are in cgs, but coords are in SI.)See also: xarray_d_grid
- 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_dotgrad(var, *, _match=None)
dotgrad: u_dotgrad_B = (u dot grad) B = u_x dB/dx + u_y dB/dy + u_z dB/dz.
- get_ds(var, *, _match=None)
dx (or dy, or dz) –> grid cell size along the x (or y, or z) axis.
result is probably a 0D xr.DataArray.Caution: this is the “underlying grid cell spacing”, not numerically altered by self.slices.See also: self.get_maindims_dim_dslice(), which is more suitable if integrating.
- 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. (directly from Muram)
Per unit volume, e.g. the SI units would be Joules / meter^3.assumes single fluid mode, i.e. result corresponds to the single fluid from Muram.
- get_emiss()
Emission measure (EM) based on the selected emission mode (self.emiss_mode).
Depends on self.emiss_mode; see self.EMISS_MODE_OPTIONS for details.Result is always in cgs, regardless of self.units.
- get_emiss_for_vdem_loi(*, _T_loi=None)
emiss_for_vdem_loi = emiss_loi, but with some adjustments for vdems:
- ignores emiss contributions from very cold regions (log10(T) < self.vdem_logT_min).- depending on self.vdem_ignores_photosphere, might set to 0 below z=0[EFF] for efficiency, can provide _T_loi if known.
- get_emiss_notrac()
Emission measure in cgs without TRAC correction.
Result is always in [cgs], regardless of self.units.nh = r / (n_per_nh * mh)emiss_notrac = ne * nh / self.emiss_norm [1/cm^6]
- get_emiss_trac()
Emission measure in cgs with TRAC correction.
Result is always in [cgs], regardless of self.units.nh = r / (n_per_nh * mh)emiss_trac = ne * nh * trac_correction / normalizationself.emiss_trac_coeff tells the TRAC coefficient (default 3)
- get_eperm()
internal energy (total, not density) per unit mass. eperm = e / r.
- 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_ertab_var(var, ustr)
get var in self.units units from the eos tables, using r and e from self.
see self.tabin.keys() for var options. gets value via interpolation.ustr: strconvert result from raw to self.units by multiplying by self.u(ustr).
- get_eta0_J(*, _E0S1=None, _E0S2=None)
E0_perp_B = eta0_J * J_perp_B + …, where eta0_J = E0S1 * |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_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: boolwhether to return (idx, DimPoint) instead of just DimPoint.
- get_float(var, *, _match=None)
any float, as an xarray.
- get_gamma()
adiabatic index. Assumed to be 5/3.
- 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_gradvec(var, *, _match=None)
gradvec_u = du/dx, du/dy, du/dz, but listed along ‘gradvec_component’ dim,
since u already has ‘component’ dim.self.component controls which components of u will be included in result.self.gradvec_component controls which gradvec_components will be included in result.E.g. gradvec_component = [‘x’, ‘z’] –> only du/dx, du/dz, not du/dy.
- 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_inelasticity()
inelasticity for collisions between self.fluid and self.jfluid.
This affects the delta_sn factor in the heating equation,(see e.g. Dimant et al 2023, equation 1c).In general delta_sn = (1+inelasticity) * 2 m_s / (m_s + m_n),so inelasticity=0 for elastic collisions.The implementation here raises LoadingNotImplementedError,with instructions on how to set values directly.(Subclass with unambiguous inelasticity might also override this method.)
- get_inf()
infinity, as an xarray.
- get_int(var, *, _match=None)
any integer, as an xarray.
- get_ionfrac()
ionization fraction. ionfrac = ne / n (from single fluid).
Assumes quasineutrality, and that only once-ionized ions are relevant.
- 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_load_direct_maindims_var(var, *, _match=None)
load_var –> load maindims var directly (from files, cache, or setvars; see self.load_direct()).
var should be name of a directly loadable var (see self.directly_loadable_vars()).Output always uses ‘raw’ units, regardless of self.units,but coords are in self.coords_units (default: same as self.units).The data is loaded across snaps (according to self.snap) (and across maindims) but no other dims.This enables loading vars not yet implemented explicitly, e.g. for simulations with lots ofoptional aux outputs, those might not all be known by PlasmaCalcs,but the raw data can still be loaded into xarray format using this pattern.It also helps with debugging BasesLoader implementations (compare load_var with var from bases).
- 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_loi_cumsum_var(var, *, _match=None)
loi_cumsum_var = var interpolated onto coordinates implied by self.loi,
then cumulatively summed along line-of-integration dimension implied by self.loi.Internally calls self.loi_cumsum(val); can reliably use that method instead if desired.
- get_los()
return self.los as an array. (Probably xr.DataArray.)
Not necessarily unit vector(s); to guarantee magnitude==1, use self(‘hat_los’) instead.Crash if self.los is None, or if it is ‘component’ or ‘-component’ when current_n_component() > 1.see self.help(‘(.+)_los’), help(type(self).los), and self.LOS_OPTIONS for more details.[EFF] note: in case of ‘component’, ‘x’, ‘y’, ‘z’, or their negative counterparts,self(‘var_los’) pattern will not get self(‘los’) directly.(Though, those options are implemented here for consistency.)
- 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()
abundance-weighted average fluid particle mass.
m = self.elements.mtot() * (mass of 1 atomic mass unit).The “abundance-weighting” is as follows:m = sum_x(mx ax) / sum_x(ax), where ax = nx / nH, and x is any elem from self.elements.note: ax is related to abundance Ax via Ax = 12 + log10(ax).see help(self.elements.mtot) for more details, including a proof that mtot = rtot / ntot.(if self.elements does not exist, this method will crash with LoadingNotImplementedError)
- 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_maindims_0()
return array of 0s, with dimensions and coords implied by self.maindims.
To save space, the result’s dtype is int, by default.Equivalent: self.zeros_like_maindims()
- get_maindims_coord_xarrays(dim=None)
return dict of {dim: xarray of coords for dim} for dim in self.maindims.
x: None or str; if provided, return result[x] instead.Result’s values use self.units; coords use self.coords_units (default==self.units).(e.g., units=’cgs’, coord_units=’si’ –> values are in cgs, but coords are in SI.)
- get_maindims_coords(*, slices=UNSET, coords_units=UNSET)
return dict of {dim: coords} for all dims in self.maindims, applying self.slices appropriately.
E.g., {‘x’: xcoords, ‘y’: ycoords}, where xcoords and ycoords are numpy arrays.Results will be in self.coords_units (default: self.units) unit system.slices: UNSET, None, or dictif provided (i.e. not UNSET) use these slices instead of self.slices.equivalent to: with self.using(slices=slices): get_maindims_coords().E.g., slices = None (or dict()) –> full maindims coords, without any slicing.coords_units: UNSET, None, or strif provided (i.e. not UNSET) use coords_units = coords_units instead of self.coords_units.equivalent to: with self.using(coords_units=coords_units): get_maindims_coords().E.g., coords_units = ‘si’ –> maindims coords in ‘si’ regardless of self.coords_units.
- get_maindims_coords_idx()
return dict of maindims coords’ indices, based on self.slices.
E.g. if self.slices[‘x’] = slice(10, None, 4),then result[‘x’] = array([10, 14, 18, …]).Values in result are xarray.DataArrays,with dim = the maindim, coords = the maindim’s coord values.
- get_maindims_dgrid(dim)
return grid spacing associated with dim values (dim in self.maindims).
Result is a 1D xarray.DataArray, with coords according to self.get_maindims_coords()[dim].Result’s values use self.units; coords use self.coords_units (default==self.units).(e.g., units=’cgs’, coord_units=’si’ –> values are in cgs, but coords are in SI.)Caution: this is the “underlying grid cell size”, regardless of self.slices.E.g., slicing with slice(None,None,4) will NOT lead to 4 times larger result.For Muram, this value comes from self.params.
- get_maindims_dim_coord(var, *, _match=None)
maindims_x_coord = array of x values and x coordinates.
Equivalent: self.get_maindims_coord_xarrays()[x], self(‘maindims_0’)[x]x must be one of self.maindims.Result’s values use self.units; coords use self.coords_units (default==self.units).(e.g., units=’cgs’, coord_units=’si’ –> values are in cgs, but coords are in SI.)
- get_maindims_dim_dgrid(var, *, _match=None)
maindims_x_dgrid == array of underlying grid spacing associated with x values.
Result’s values use self.units; coords use self.coords_units (default==self.units).(e.g., units=’cgs’, coord_units=’si’ –> values are in cgs, but coords are in SI.)Caution: this is the underlying grid cell size, regardless of self.slices;Thus, this value is suitable for asking questions about the underlying grid,e.g. “what is the smallest wavelength the grid can support?”But it is NOT suitable for doing an integral across this dim, because, e.g.,setting self.slices[x]=slice(None,None,4) does NOT lead to 4 times larger result.For doing an integral, consider instead: self(‘maindims_{x}_dslice’)Equivalent: self.get_maindims_dgrid(x)
- get_maindims_dim_didx(var, *, _match=None)
maindims_x_didx == array of index spacing associated with x values,
based on self.slices. Only works if x in self.maindims.E.g. if slices[x]=slice(10, None, 4), then result values = [4, 4, 4, …].Equivalent: xarray_np_gradient(self(‘maindims_{x}_idx’), x)
- get_maindims_dim_dslice(var, *, _match=None)
maindims_x_dslice == array of spacing between adjacent x values, accounting for self.slices.
Result’s values use self.units; coords use self.coords_units (default==self.units).(e.g., units=’cgs’, coord_units=’si’ –> values are in cgs, but coords are in SI.)Thus, this value is suitable for doing an integral.E.g., self.slices[x]=slice(None,None,4) should make ~4 times larger result than slice(None).(only “roughly”, because the gradient accounts for adjacent values in the dgrid array.)For learning about the underlying grid, consider self(‘maindims_{x}_dgrid’) instead.Equivalent: maindims_x_dgrid * maindims_x_didx.
- get_maindims_dim_idx(var, *, _match=None)
maindims_x_idx == array of index associated with x values,
based on self.slices. Only works if x in self.maindims.E.g. if slices[x]=slice(10, None, 4), then result values = [10, 14, 18, …].Equivalent: self.get_maindims_coords_idx[‘x’]
- 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_moments(var, *, _match=None)
First three moments of a var, e.g., vdem or spectra.
I0 = (int(I du)) [erg/cm^2/s/sr]I1 = (int(I u du))/I0 [km/s]I2 = (int(I u^2 du))/I0-I1^2 [km/s]dim_moments_var –> self(var).pc.moments(dim=dim).e.g., vdop_moments_vdem –> self(‘vdem’).pc.moments(dim=’vdop’)result is a Dataset with data_vars ‘moment_0’, ‘moment_1’, ‘moment_2’.
- get_n()
number density. n = (r / m) = (mass density / mass)
(Note: for single-fluid, this excludes electron number density.)
- 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. Depends on self.eos_mode; see help(type(self).eos_mode) for details
(To override eos_mode for just ne, can set self.eos_mode_ne instead.)‘ideal’ –> cannot get ne. Crash with TypevarNanError.‘table’ –> ne from plugging r and e into EOS lookup tables (see self.tabin).‘aux’ –> get directly from Muram aux files.[more options might be available (depending on subclass) – see self.EOS_MODE_OPTIONS.]
- get_ne_aux()
electron number density, from ‘eosne’ file.
- get_ne_fromtable()
electron number density, from plugging r and e into eos tables (see self.tabin).
- get_negation(var, *, _match=None)
negation. -var.
- get_niefrac()
ion-to-electron density ratio. niefrac = ni / ne.
Result always corresponds to fluid=IONS, regardless of current self.fluid.
- get_nmean(var, *, _match=None)
mean of var, weighted by n. nmean = sum(var * n) / sum(n). n=self(‘n’).
Equivalent: ‘nmean_var’ <–> ‘weighted_n_mean_var’
- get_nq()
charge density. nq = (n * q) = (number density * charge)
- get_nstd(var, *, _match=None)
std of var, weighted by n. nstd = std(n*var)/mean(n), with n=self(‘n’).
- get_nuns()
collision frequency. for a single neutral particle to collide with any s.
nuns = nusn * (m / m_neutral) * (n / n_neutral).(from conservation of momentum, and summing collisional momentum transfer between species)
- get_nusj()
collision frequency. for a single particle of s to collide with any of j.
[Not implemented for this class]
- get_nusn()
collision frequency. for a single particle of s to collide with any neutral.
Computed as self(‘nusj’, jfluid=self.jfluids.get_neutral()).
- get_nusn_from_drift(var, *, _match=None)
nusn, calculated by assuming u satisfies momentum equation to zeroth order.
There are various options for how to solve for nusn, as explained below (see {drift}).All solutions use nusn = sgyrof / skappa, where skappa is determined viaskappa = self(‘skappa’+var[len(‘nusn’):]).E.g. ‘nusn_from_means_momExB’ –> use skappa = self(‘skappa_from_means_momExB’).The description below helps explain the various options.‘nusn_from_{means_}{u_}{drift}’E.g. ‘nusn_from_means_momExB’, ‘nusn_from_hall’, ‘nusn_from_means_moment1_momB’{means_} = ‘means_’ or ‘’.if ‘means_’, take means of vars: ‘sgyrof’, any vars relevant to the chosen {drift} option.{u_} = ‘’ or any other var then ‘_’.if provided, use this var instead of ‘u’ for velocity. (Doesn’t affect “u_neutral” though.){drift} = ‘momExB’, ‘momE’, ‘hall’, or ‘pedersen’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.‘pedersen’ –> get skappa from u_pedersen = u, in the E direction.
- get_opac_h()
H opacity at self.rcoords_wavelength_A.
See Anzer & Heinzel, 2005 for details.
- get_opac_h_he(wavelength=None)
Opacities at wavelength=self.rcoords_wavelength_A.
from hydrogen and helium bound free absorption (Anzer & Heinzel, 2005)
- get_opac_hei()
HeI opacity at self.rcoords_wavelength_A.
See Anzer & Heinzel, 2005 for details.
- get_opac_heii()
HeII opacity at self.rcoords_wavelength_A.
See Anzer & Heinzel, 2005 for details.
- get_p()
momentum density. p = (u * r) = (velocity * mass density).
- get_parallel(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
A_par_B –> the component of A parallel to B.
Equivalent to self.take_parallel_to(B, A) == (A dot Bhat) Bhat.see also: A_dot_hat_B, which is equivalent to mod_(A_par_B)[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘E_par_B’, _E=E, _B=B) –> E par to B, using E and B which are already known.can alternatively provide _val0 for A and/or _val1 for B.
- get_parenthesis(var, *, _match=None, **kw)
parenthesis. ‘{prefix}({here}){suffix}’, with no parenthesis inside {here}.
Ensures that {here} is interpreted as a single expression. Useful when combining operations.E.g. ‘sqrt_q/m’, with no parenthesis, has an ambiguous interpretation.‘sqrt_(q/m)’ unambiguously refers to “sqrt(ratio between q and m)”.‘(sqrt_q)/m’ unambiguously refers to “ratio between sqrt(q) and m”.The no-parenthesis interpretation is subject to change without warning, in future code updates.(You can always check the interpretation that is being used, via self.match_var_tree(var))
- get_parmod(var, *, _match=None, _val0=None, _val1=None, **_known_vals)
magnitude of the component of A parallel to B.
Equivalent to mod(A_par_B). Also equivalent to abs(A_dot_hat_B)[EFF] can provide known vals for A or B, to avoid recalculating them. (include leading underscores.)e.g. self(‘E_parmod_B’, _E=E, _B=B) –> |E par to B|, using E and B which are already known.can alternatively provide _val0 for A and/or _val1 for B.
- get_pc_uuid(*, generate=None, default=UNSET, return_meta=False)
return the PlasmaCalcs uuid associated with dir=self.dirname.
Equivalent to pc_uuid_here(self.dirname, …).(self.pc_uuid uses get_pc_uuid(generate=False, default=ATTR_UNSET).)pc_uuid_here docstring copied below for convenience:———————————————–return the PlasmaCalcs uuid associated with this directory.The uuid is intended to be a universally unique identifier;it is highly unlikely that any other uuid will ever match this one.This is especially useful for the .register() method and the registry.The uuid will be stored in a file named _pc_uuid.txt inside dir, which contains:# comment lines starting with ‘#’ explaining the purpose of the file# assignment lines below might also have # comments at end of lineuuid = “uuidstringwithouthyphens”generated_at = “YYYY-MM-DDTHH:MM:SS.ssssss+HH:MM” # when this uuid was generated# the file might also contain other assigments but likely will not;# other assignments will be ignored.dir: strpath to directory.generate: None, True, or Falsewhether to generate a new uuid (and create corresponding _pc_uuid.txt file)None –> as needed; only if _pc_uuid.txt does not already exist.True –> generate new uuid; crash if _pc_uuid.txt already exists.False –> return existing uuid; crash (or return default) if _pc_uuid.txt does not exist.default: UNSET or any objectif not UNSET, returndefaultif _pc_uuid.txt file does not exist and generate is False.Only used if generate is False.return_meta: boolwhether to instead return a dict containing all info from _pc_uuid.txt,including the metadata. If True, dict contains ‘uuid’ and all other keys from file.(Values evaluated via ast.literal_eval if possible, else kept as string.)When sharing runs across machines, keep the _pc_uuid.txt file,to allow PlasmaCalcs to identify it as “the same run” in multiple places.When copy-pasting a run as a starting point but wanting PlasmaCalcsto treat the new copied run as a different run, delete its _pc_uuid.txt file.
- 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 Plottername of the plotter to use, or a Plotter instance.who: UNSET, None, or strperson 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 strplotter 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: listexclude plotters with any of these people in plotter.who.skip_kinds: listexclude plotters with any of these kinds in plotter.kinds.min_cost: None or numberexclude plotters with cost < min_cost.None –> no minimum.max_cost: None or numberexclude plotters with cost > max_cost.None –> no maximum.sortby: None or ‘cost’tells how to sort the result (if returns==’plotters’).None –> keep in order they appear in self.UNIQUE_PLOTTERS.‘cost’ –> sort by plotter.cost values.returns: ‘plotters’, ‘names’, ‘who’, ‘kind’, or ‘kinds’‘plotters’ –> returns list of plotters‘names’ –> returns set of all names associated with at least 1 plotter in result.‘who’ –> returns set of all people associated with at least 1 plotter in result.‘kind’ or ‘kinds’ –> returns set of all kinds associated with at least 1 plotter in result.
- get_plus(var, *, _match=None)
addition. var0 + var1.
- get_pmstd2werr(var, *, _match=None)
convert dataset with ‘mean+std’ and ‘mean-std’ into dataset with ‘mean’ and ‘std’.
pmstd2werr_var will crash if self(var) doesn’t have ‘mean+std’ and ‘mean-std’ data vars.
- get_power(var, *, _match=None)
power. var0 ** var1.
- get_prod(var, *, _match=None)
prod. prod(var). Applied only along any self.stat_dims in array.
- get_psi()
psi = (1/(kappae * kappai)) == (nuen * nuin) / (gyrof_e * gyrof_i).
Commonly used in ionospheric Farley-Buneman instability analysis.psi is calculated using the formula above, for the single ion in self.fluids.self.fluids must contain exactly 1 ion and exactly 1 electron,else this method will crash with FluidValueError or FluidKeyError.equivalent to psi_i in the case of exactly 1 ion in self.fluid and self.fluids.
- get_psi_i()
psi_i = (1/(kappae * kappai)) == (nuen * nuin) / (gyrof_e * gyrof_i).
Commonly used in ionospheric Farley-Buneman instability analysis.psi_i gives the value of psi for each ion in self.fluid, using the formula above.fails with FluidValueError if current self.fluid includes any non-ions.fails with FluidKeyError if current self.fluid does not include any ions.see also: psi
- get_pwl2_var(var, *, _match=None)
get pwl2_flatend fit to var across self.snap, evaluated at self.snap.
(fail if self.snap is not a list of multiple snaps.)pwl2_flatend is a piecewise linear function with 2 pieces; final piece has slope=0.Equivalent: fitter=self(var).pc.pwl2_flatend_fitter(‘t’); fitter.fit(); fitter.eval()
- get_q()
charge, of a “single particle”. for protons, == +1 elementary charge.
[Not implemented for this class]
- get_r()
mass density. (directly from Muram)
assumes single fluid mode, i.e. result corresponds to the single fluid from Muram.
- get_rad2deg(var, *, _match=None)
convert radians to degrees. rad2deg_{A} –> A * 180 / pi.
self(‘rad2deg_var’) == np.rad2deg(self(‘var’))
- get_rcoords_Pe()
electron Pressure values for G(T) for fixed pressure, in [self.units] system,
along dimension ‘P’, with coords always in [cgs] units regardless of self.units.Determined by self.rcoords_Pe_cgs (which can be set directly), converted to [self.units].
- get_rcoords_logD()
log(electron number density) values for VDEMs and G(T,ne), with ne in [self.units] system,
along dimension ‘logD’, with coords always telling log10(ne [cgs]) regardless of self.units.Determined by self.rcoords_logD_cgs (which can be set directly), converted to [self.units].Getting self(‘rcoords_logD’) will crash if self.rcoords_logD_cgs is None, with a helpful error message.
- get_rcoords_logT()
log(Temperature) values used by some vars (e.g. vdems and G(T)), in [self.units] system,
along dimension ‘logT’, with coords always telling log(T [K]) regardless of self.units.Determined by self.rcoords_logT (which can be set directly), converted to [self.units].
- get_rcoords_vdop()
velocity (or, doppler shift) values used by some vars (e.g. vdems and spectra), in [self.units] system,
along dimension ‘vdop’, with coords always in km/s regardless of self.units.Determined by self.rcoords_vdop_kms (which can be set directly), converted to [self.units].
- get_real(var, *, _match=None)
real part. np.real(self(var))
- get_rms(var, *, _match=None)
root mean square. sqrt(mean(var**2)). Applied only along any self.stat_dims in array.
- get_rmscomps(var, *, _match=None)
root mean squared of components.
E.g., rmscomps_{A} –> sqrt((Ax^2 + Ay^2 + Az^2) / 3), if A has 3 components.
- get_rosenberg_multi()
rosenberg criterion for multiple ions: rosenberg_multi = (nusn_multi / wplasma_multi)^2.
quasineutrality is “reasonable” (during farley-buneman analysis) iff rosenberg_multi << 1.This criterion should be more accurate than using rosenberg_qn for each ion, separately.(Below uses ‘…’ to denote “terms independent of wplasma_i and nu_in”.)Rosenberg 1998 equation 17, derived from equation 14, assumed only 1 ion.However, equation 14 comes from 13, where wplasma_i and nu_in only appear as (Ai/wplasma_i^2).where Ai = omega * (omega + i nu_in) + … (see equation 15).equation 13 looks like: … + (Ai/wplasma_i^2) = 0From equation 4 I infer the dispersion relation with multiple ions will be like:… + sum_i (Ai/wplasma_i^2) = 0.Expanding this sum reveals that it can be expressed in the same algebraic form as with 1 ion:… + Am/wplasma_m^2 = 0, when:wplasma_m^2 = 1 / (1/wplasma_1^2 + 1/wplasma_2^2 + …),Am = omega * (omega + i nu_mn) + …nu_mn = nu1 * weight1 + nu2 * weight2 + … / (weight1 + weight2 + …),where weightj = wplasma_1^2 * wplasma_2^2 * … / wplasma_j^2.Thus, the remaining steps done by Rosenberg to derive the criterion should apply in the same way,and for multiple ions we can conclude the criterion is (nu_mn / wplasma_m)^2 << 1.Okay, actually, in practice, it’s probably not useful to use this…it mostly just selects the least-dense ion, due to the 1/wplasma^2 scaling.Also, the criterion means “instability gets dampened when collisions are faster than plasma oscillations”But for multiple ions, it’s really more like, the instability for THAT ion gets dampened…(Also, I think one of the assumptions in the paper probably fails when wplasma is small…)
- get_rosenberg_multi_nusn()
collision frequency for rosenberg criterion with multiple ions.
nusn_multi = nu1 * weight1 + nu2 * weight2 + … / (weight1 + weight2 + …),where weightj = wplasma_1^2 * wplasma_2^2 * … / wplasma_j^2.see rosenberg_multi for details.
- get_rosenberg_multi_wplasma()
plasma frequency for rosenberg criterion with multiple ions.
wplasma_multi^2 = 1 / (1 / wplasma1^2 + 1 / wplasma2^2 + …),with sum across all ions in self(‘wplasma’, fluids=None)see rosenberg_multi for details.
- get_rosenberg_n()
n such that rosenberg_qn == 1, for each fluid.
Equivalent: rosenberg_qn * n.To satisfy Rosenberg criterion, need rosenberg_qn << 1.rosenberg_qn = (nusn / wplasma)^2 = nusn^2 * m * eps0 / (n * q^2),which is proportional to 1 / n–> n is “good” if n >> rosenberg_n.Note: this also happens to be the solution to lmfp == ldebye…lmfp = (vtherm/nusn) = ((kB T / m)^0.5 / nusn) == (epsilon0 kB T / (n q^2))^0.5 = ldebye–> (nusn^-2 m^-1) == (epsilon0 n^-1 q^-2)–> n == epsilon0 nusn^2 m / q^2.
- get_rosenberg_n_margin()
n / rosenberg_n. margin of safety for rosenberg criterion. “safe” if margin is large.
- get_rosenberg_qn()
Rosenberg criterion for quasineutrality, for each fluid: rosenberg_qn = (nusn / wplasma)^2.
quasineutrality is “reasonable” (during farley-buneman analysis) iff rosenberg_qn << 1 for ions.(Intuitively: quasineutrality reasonable iff ‘collisions much slower than plasma oscillations’)If multiple ions, consider using self(‘rosenberg_multi’) instead of one criterion per ion.see Rosenberg 1998, equation 17, for details.
- get_safe_pow2_subcycle(*, subcycle_safety=UNSET)
largest “safe” power of 2 subcycling allowed for each fluid in self.fluid.
result = array of values like 2^N, with largest N such that result < best_subcycle / safety.(larger safety produces “safer” results. For safe_subcycle, just use best_subcycle / safety.)
- get_sci_number(var, *, _match=None)
any number in scientific notation, as an xarray.
- get_set_or_cached(var)
returns var if found in self.setvars or self.cache, with compatible behavior_attrs.
otherwise, raise CacheNotApplicableError.if var is found in self.setvars and has relevant, but not matching behavior_attrs,self.load_across_dims will be used to load the value.
- get_sgyrof()
signed gyrofrequency. sgyrof == q |B| / m == charge * |B| / mass. Negative when charge < 0.
- get_single_fluid_var(var, *, _match=None)
SF_{var} (or SINGLE_FLUID_{var}) –> {var}, definitely in single fluid mode.
crashes with FluidValueError if not self.in_single_fluid_mode.The implementation here just does self.assert_single_fluid_mode(),then returns self(var) (var from SF_var or SINGLE_FLUID_var string).Subclass might override to also set self.fluid = SINGLE_FLUID.
- get_skappa()
signed kappa (magnetization parameter). skappa = sgyrof / nusn. Negative when charge < 0.
skappa = gyrofrequency / collision frequency of self.fluid with neutrals.gyrofrequency == q * |B| / (mass * nusn).
- get_skappa_from_hall(var, *, _match=None)
signed kappa (magnetization parameter) that statisfies u_hall = u, in the E x B direction.
‘skappa_from_{means_}{u_}hall’E.g. ‘skappa_from_means_hall’, ‘skappa_from_hall’, ‘skappa_from_means_moment1_hall’{means_} = ‘means_’ or ‘’.if ‘means_’, take means of vars: ‘u’, ‘u_neutral’, ‘mod_B’, ‘E_cross_B’{u_} = ‘’ or any other var then ‘_’.if provided, use this var instead of ‘u’ for velocity. (Doesn’t affect “u_neutral” though.)E.g. eppic calculator might use ‘moment1’ here, as in ‘skappa_from_moment1_hall’.Algebraic solution:formula for u_hall (from solving momentum equation for u in the E x B direction):u_hall = (kappa**2 / (1 + kappa**2)) * (E x B) / |B|**2solving for kappa**2, assuming u instead of u_hall, yields:(u dot (E x B)) == (kappa**2 / (1 + kappa**2)) * (|E x B|**2 / |B|**2)A + A * kappa**2 - kappa**2 == 0, where A = (u dot (E x B)) / (|E x B|**2 / |B|**2)kappa**2 = A / (1 - A)–> skappa = +- sqrt(A / (1 - A)),There are two solutions; return solution with the same sign as self(‘q’) (i.e. fluid’s charge)
- get_skappa_from_momE(var, *, _match=None)
signed kappa (magnetization parameter) that statisfies momentum equation in the E direction.
‘skappa_from_{means_}{u_}momE’E.g. ‘skappa_from_means_momE’, ‘skappa_from_momE’, ‘skappa_from_means_moment1_momE’{means_} = ‘means_’ or ‘’.if ‘means_’, take means of vars: ‘u’, ‘u_neutral’, ‘mod_E’, ‘mod_B’, ‘E’, ‘E_cross_B’{u_} = ‘’ or any other var then ‘_’.if provided, use this var instead of ‘u’ for velocity. (Doesn’t affect “u_neutral” though.)E.g. eppic calculator might use ‘moment1’ here, as in ‘skappa_from_moment1_momE’.Algebraic solution:momentum equation, rearranged using skappa = q * |B| / (m * nusn):0 = q (E + u x B) - m * nusn * (u - u_neutral)0 = skappa (E + u x B) - |B| (u - u_neutral)dotting with E:0 = skappa (|E|^2 + (u x B) dot E) - |B| (u - u_neutral) dot E # note uxB.E == BxE.u == -ExB.u–> skappa = |B| (u - u_neutral) dot E / (|E|^2 - u dot (E x B))Note: results untrustworthy when kappa >> 1, since that involves dividing by a value close to 0.
- get_skappa_from_momExB(var, *, _match=None)
signed kappa (magnetization parameter) that statisfies momentum equation in the E x B direction.
‘skappa_from_{means_}{u_}momExB’E.g. ‘skappa_from_means_momExB’, ‘skappa_from_momExB’, ‘skappa_from_means_moment1_momExB’{means_} = ‘means_’ or ‘’.if ‘means_’, take means of vars: ‘u’, ‘u_neutral’, ‘mod_B’, ‘E_cross_B’, ‘u_cross_B’{u_} = ‘’ or any other var then ‘_’.if provided, use this var instead of ‘u’ for velocity. (Doesn’t affect “u_neutral” though.)E.g. eppic calculator might use ‘moment1’ here, as in ‘skappa_from_moment1_momExB’.Algebraic solution:momentum equation, rearranged using skappa = q * |B| / (m * nusn):0 = q (E + u x B) - m * nusn * (u - u_neutral)0 = skappa (E + u x B) - |B| (u - u_neutral)dotting with E x B:0 = skappa [(u x B) dot (E x B)] - |B| [(u - u_neutral) dot (E x B)]–> skappa = |B| [(u - u_neutral) dot (E x B)] / [(u x B) dot (E x B)]
- get_skappa_from_pedersen(var, *, _match=None)
signed kappa (magnetization parameter) that statisfies u_pedersen = u, in the E direction.
‘skappa_from_{means_}{u_}pedersen’E.g. ‘skappa_from_means_pedersen’, ‘skappa_from_pedersen’, ‘skappa_from_means_moment1_pedersen’{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_pedersen’.Algebraic solution:formula for u_pedersen (from solving momentum equation for u in the E direction):u_pedersen = (skappa / (1 + skappa**2)) * E / |B|solving for skappa, assuming u instead of u_pedersen, 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_spectra(var, *, _match=None)
Synthetic spectra for a given ion. Always in [cgs] units, regardless of self.units.
Units erg/cm^2/s/sr/AngsResult depends on self.rcoords_vdop_kms and self.rcoords_wavelength_A, which can be set directly.Result varies along the ‘vdop’ dimension which indicates doppler velocity (in km/s).[TODO] formula/details
- get_sqrt(var, *, _match=None)
square root. sqrt(var)
- get_stats(var, *, _match=None)
return dataset of stats for var
stats include: mean, std, min, max, median, rms.Applied only along any self.stat_dims in array.Incompatible with Dataset vars.Consider also: self(‘astats_var’), self(‘var’).pc.stats()
- get_std(var, *, _match=None)
standard deviation. std(var). Applied only along any self.stat_dims in array.
- get_sum(var, *, _match=None)
sum. sum(var). Applied only along any self.stat_dims in array.
- get_surelin_var(var, *, _match=None)
values of var between (inclusive) t_surelin_min and t_surelin. Mask all other values.
[TODO][EFF] wasted time computing values which will later be masked…
- get_sureturb_var(var, *, _match=None)
values of var at or after t_sureturb. Mask all values before t_sureturb.
[TODO][EFF] wasted time computing values which will later be masked…
- get_t_surelin()
time before which, values are definitely in the linear regime.
self(‘t_turb’) * self.surelin_quantile.
- get_t_surelin_min()
start time of “definitely linear regime”.
self(‘t_turb’) * self.surelin_min_quantile.
- get_t_sureturb()
time, after which, values are definitely in the turbulent regime.
Currently, just returns self(‘t_turb’).Eventually might implement some safety factor since t_turb might not be exact.
- get_t_turb()
time of turbulent onset. Equal to self.t_turb if set; Crash if not set.
(here always converts result to DataArray if not DataArray already.)
- get_t_turb_from_pwl2_var(var, *, _match=None)
t_turb from pwl2_flatend fit to var. Might want to do self.t_turb = result.
result depends on self.blur_sigma.Equivalent: fitter=self(‘var’).pc.pwl2_flatend_fitter(‘t’); fitter.fit(); fitter.get_xsat()Suggestion: t_turb_from_pwl2_ln_std_blur_deltafrac_n
- get_tau()
Optical depth along line of integration (default: loi = line of sight),
at wavelength=self.rcoords_wavelength_A, and considering only H, HeI, and HeII contributions.Result is always in [cgs] units, regardless of self.units.loi determined by self.loi (see help(type(self).loi) for details),when using self.los = self.vdem_los_explicit (see help(type(self).vdem_los) for details).tau(l) = integral(absorption * dl, from 0th l value to l); use self.loi instead of l.(in python terms, this is represented by a cumsum.)To reverse direction (i.e. “start from the other end”), edit self.loi or self.vdem_los.E.g. when self.loi=’los’, swapping from self.vdem_los=’-x’ to self.vdem_los=’x’ swaps direction.
- get_tau_500(wavelength=None)
Computes the tau scale from H-bf opacity alone 500 nm.
Assume all hydrogen to be neutral
- 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.Result also depends on self.tfbi_cond_vars,which will include ‘1+inelasticity’ if self.tfbi_elastic=True.Results depend on self.fluid. May want to call as self(‘tfbi_inputs’, fluid=CHARGED).
- get_tfbi_omega(*, kw_tfbi_solve={}, **kw_tfbi_solver)
Thermal Farley Buneman Instability roots with largest imaginary part at each point in self.
Equivalent: self.tfbi_solver(**kw_tfbi_solver).solve(**kw_solve)[‘omega’].Can provide kwargs, e.g. self(‘tfbi_omega’, ions=[‘H_II’, ‘C_II’], kw_tfbi_solve=dict(ncpu=1)).For more control, use self.tfbi_solver() directly.For even more control, use the pattern described in help(self.tfbi_solver_cls).Recommended: consider using ‘tfbi_omega_ds’ instead of ‘tfbi_omega’.‘tfbi_omega_ds’ gives the full Dataset of all values relevant to the solution.‘tfbi_omega’ just gives the DataArray of omega, which is harder to inspect later.
- get_tfbi_omega_ds(*, kw_tfbi_solve={}, **kw_tfbi_solver)
Thermal Farley Buneman Instability solution at each point in self.
Equivalent: self.tfbi_solver(**kw_tfbi_solver).solve(**kw_solve).Can provide kwargs, e.g. self(‘tfbi_omega_ds’, ions=[‘H_II’, ‘C_II’], kw_tfbi_solve=dict(ncpu=1)).For more control, use self.tfbi_solver() directly.For even more control, use the pattern described in help(self.tfbi_solver_cls).
- get_tfbi_vs_EBspeed()
return tfbi solution across EBspeed grid. Load saved result if it exists, else save result to file.
CAUTION: the implementation here might self.set(‘E_un0_perpmod_B’, self(‘mod_B’) * EBspeed)[TODO] avoid changing self.setvars… (or, at least, restore previous self.setvars afterwards.)CAUTION: the implementation here assumes self.tfbi_EBspeed_grid_size is enough to uniquely specify the result;e.g. if there is a different result at each snapshot of self, that will not be understood here.Equivalent: self.solve_tfbi_vs_EBspeed(cache=’caches’)
- get_times(var, *, _match=None)
multiplication. var0 * var1.
- get_timescale_EBdrift()
timescale from drift speed if possible, else from speed using E & B fields.
tries to return self(‘timescale_udrift’), but if that causes a QuantCalcError,use self(‘timescale_EBspeed’) instead.
- get_timescale_EBspeed()
timescale from speed using E & B fields. dsmin / (|E_un0 cross B| / |B|^2).
E_un0 (not E) because the derivation assumes neutral frame: u_neutral=0.note: to be more precise, use timescale_udrift instead.
- get_timescale_eqperp_vtherm()
timescale from thermal velocity, using T_from_Eheat_perp instead of T.
dsmin / eqperp_vtherm.
- get_timescale_gyrof()
timescale for cyclotron motion. 2 * pi / gyrof. (Hz, not rad/s)
gyrof = |q| |B| / m.
- get_timescale_nusn()
timescale for collisions with neutrals. 1 / nusn.
nusn = collision frequency of self.fluid with neutrals.
- get_timescale_udrift()
timescale from drift speed. dsmin / mod_u_drift.
note: to be less precise (but computationally cheaper), use timescale_EBspeed instead.
For electrons when kappae >> 1, timescale_EBspeed ~= timescale_udrift.When accounting for directionality, or kappae <~= 1, or non-electrons,timescale_EBspeed is always more conservative (i.e. smaller) than timescale_udrift.
- get_timescale_vtherm()
timescale from thermal velocity. dsmin / vthermal.
vthermal = sqrt(kB T / m).
- get_timescale_wplasma()
timescale from plasma oscillations. 2 * pi / wplasma. (Hz, not rad/s)
wplasma = sqrt(n q^2 / (m epsilon0)).
- get_timescales()
all timescales (from self.TIMESCALE_VARS) as a dataset.
Consider also: self(‘timescales_abbrv’)Useful patterns you might want to consider:self(‘timescales’, maindims_means=True) # timescales based on mean values onlyself(‘timescales’).min(‘fluid’) # minimum timescales across all fluidsself(‘timescales’).pc.minimum() # minimum timescale across all timescalesequivalent: self(‘min_timescale’)self(‘timescales’).min(‘fluid’).pc.minimum() # minimum timescale at each point.self(‘timescales’).pc.varmin() # name of timescale with minimum value at each point.# timescale variable names, sorted from min to max values.self(‘timescales’).to_dataarray().pc.sort_along(‘variable’)[‘variable’]
- get_timescales_abbrv()
all timescales (from self.TIMESCALE_VARS) as a dataset, abbreviating names.
abbreviates ‘timescale_var’ –> ‘var’.
- get_tturb_var(var, *, _match=None)
values of var at or after t_turb. Mask all values before t_turb.
[TODO][EFF] wasted time computing values which will later be masked…
- get_tturbvar00()
var used for t_turb ‘00’ standard: caches_ln_std_blur_deltafrac_n,
with fluid=electron, snap=None, blur_sigma=10.
- get_turblindiff_var(var, *, _match=None)
meant_sureturb_var - meant_surelin_var.
i.e., (time-averaged value in turbulent regime) minus (time-averaged value in linear regime).see also: werrturblindiff_var
- get_turblindiffwerr_var(var, *, _match=None)
werrmeant_sureturb_var - werrmeant_surelin_var.
i.e., (time-averaged value in turbulent regime) minus (time-averaged value in linear regime),but result is a Dataset with ‘mean’ and ‘std’ data_vars,with ‘std’ coming from “standard” error propagation formula assuming independent errors:std(A - B) = sqrt(std(A)**2 + std(B)**2).see also: turblindiff_var
- get_turblindivwerr_var(var, *, _match=None)
werrmeant_sureturb_var / werrmeant_surelin_var.
i.e., (time-averaged value in turbulent regime) divided by (time-averaged value in linear regime),but result is a Dataset with ‘mean’ and ‘std’ data_vars,with ‘std’ coming from “standard” error propagation formula assuming independent errors.
- get_u()
velocity. (directly from Muram)
assumes single fluid mode, i.e. result corresponds to the single fluid from Muram.
- 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 & pedersen 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_pedersen + 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_pedersen(*, _E=None, _B=None)
Pedersen drift velocity. u_pedersen = (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_loi(var, *, _match=None)
var_loi = var interpolated onto coordinates implied by self.loi.
Internally calls self.loi_interp(val) to do the interpolation (if any);can reliably use that method for same functionality as array_loi pattern, anywhere.Like all kwarg/attrs, can set loi beforehand, or as kwarg inside the call:self.loi = value; self(‘u_loi’) # option 1self(‘u_loi’, loi=value) # option 2
- get_var_los(var, *, _match=None)
var_los = var projected onto line of sight (as defined by self.los).
Equivalent: self(var) dot self(“hat_los”)Equivalent: self(f’{var}_sparmod_los’)See help(type(self).los) and self.LOS_OPTIONS for more details.Like all kwarg/attrs, can set los beforehand, or as kwarg inside the call:self.los = value; self(‘u_los’) # option 1self(‘u_los’, los=value) # option 2Internally, if doing projection, first does xarray_result_size_check(),to prevent accidental way-too-large result (threshold =10 GB by default),which can happen easily if self.los implies different dimensions than self(var).
- 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 strsNames of the vars to load. [‘n’, ‘u’] for number density & velocity.if any of these vars returns a return_type object, expand its keys,e.g. if ‘myDSvar’ returns dataset with ‘myvar1’, ‘myvar2’,then [‘n’, ‘myDSvar’] gives dataset with ‘n’, ‘myvar1’, ‘myvar2’.return_type: ‘dataset’ or ‘dict’if ‘dataset’, return result as xarray.Dataset.the data_var names will be the same as the var names.if ‘dict’, return result as dict of {var: value}.missing_vars: UNSET, ‘ignore’, ‘warn’, or ‘raise’what to do if any vars cause FormulaMissingError at any point in the error stack.UNSET –> use self.missing_vars if it exists, else ‘raise’.‘ignore’ –> ignore missing vars, and don’t include them in the result.‘warn’ –> ignore missing vars, but print a warning.‘raise’ –> raise FormulaMissingError if any vars are missing.additional args & kwargs are passed to self(…).
- get_vdem()
VDEM (intergrated along an axis), as a function of temperature and velocity.
IfResult depends on self.vdem_mode; see self.VDEM_MODE_OPTIONS for details.See also: self.interp_maskedRegardless of self.vdem_mode, the following always apply:temperature and velocity are determined by self.rcoords_logT and self.rcoords_vdop_kms,which can be set directly.Result is always in [cgs] units, regardless of self.units.(Result’s coords’ units will still be self.units, or self.coords_units if not None.)Might ignore photosphere, depending on self.vdem_ignores_photosphere;see help(type(self).vdem_ignores_photosphere) for details.Result is along line of sight corresponding to self.component (must be a single value).Can set via, e.g., self.component=’x’, or self(‘vdem_y’), or self(var, component=’z’).Ignores emiss contributions from very cold regions (log10(T) < self.vdem_logT_min).
- get_vdem_allinterp()
VDEM (intergrated along an axis), with interpolation (Matthias trick along T and u)
See self.help(‘vdem’) or help(self.get_vdem) for more details about vdems.Equivalent: self(‘vdem’, vdem_mode=’allinterp’).
- get_vdem_interp()
VDEM (intergrated along an axis), with interpolation (Matthias trick along T)
See self.help(‘vdem’) or help(self.get_vdem) for more details about vdems.Equivalent: self(‘vdem’, vdem_mode=’interp’).
- get_vdem_no_interp()
VDEM (intergrated along an axis), without interpolation.
See self.help(‘vdem’) or help(self.get_vdem) for more details about vdems.Equivalent: self(‘vdem’, vdem_mode=’nointerp’).
- get_vector_N(var, *, _match=None)
vector_n –> vector with n in each component. E.g. vector_0 –> vector with components (0,0,0).
result components determined by self.component.
- get_vtherm()
thermal velocity. vtherm = sqrt(kB T / m)
- get_vtherm_instr()
thermal velocity including instrumental broadening.
vtherm_instr = sqrt((kB T / m) + w_instrumental^2)w_instrumental can be set via self.w_instrumental_si = value.
- get_vtherm_n()
thermal velocity for neutrals. vtherm_n = sqrt(kB T_n / m_n)
- get_w_instrumental()
instrumental broadening for thermal velocity, in self.units system.
w_instrumental = self.w_instrumental_si, converted to self.units system.See also: vtherm_instr
- get_weighted_mean(weights_var, *, _match=None)
mean, weighted by weights. mean(weights*var)/mean(weights).
E.g. ‘weighted_n_mean_T’ –> mean(n * T) / mean(n).(see also: ‘nmean_[var]’, which is a shorthand for ‘weighted_n_mean_[var]’)Applied only along any self.stat_dims in array.
- get_weighted_std(weights_var, *, _match=None)
std, weighted by weights. std(weights*var)/mean(weights).
E.g. ‘weighted_n_std_mod_u’ –> std(n * mod_u) / mean(n).(see also: ‘nstd_[var]’, which is a shorthand for ‘weighted_n_std_[var]’)Applied only along any self.stat_dims in array.Currently, equivalent to self(‘(std_({weights}*{var}))/mean(weights)’)[TODO][EFF] internally, don’t compute weights twice…
- get_werr2pmstd(var, *, _match=None)
convert dataset with ‘mean’ and ‘std’ into dataset with ‘mean+std’, ‘mean’, ‘mean-std’.
werr2pmstd_var will crash if self(var) doesn’t have ‘mean’ and ‘std’ data vars.
- get_werradd(var, *, _match=None)
A_werradd_B = A + B, but result is a dataset with ‘mean’ and ‘std’.
Does not take any means or stds here, but if A or B has ‘std’ already,assumes independent errors and applies “error propagation” formula:mean(A + B) = mean(A) + mean(B)std(A + B) = sqrt(std(A)**2 + std(B)**2)(if A or B is DataArray, treat as ‘mean’. if missing ‘std’, assume 0.)
- get_werrdiv(var, *, _match=None)
A_werrdiv_B = A / B, but result is a dataset with ‘mean’ and ‘std’.
Does not take any means or stds here, but if A or B has ‘std’ already,assumes independent errors and applies “error propagation” formula:z = A / Bmean(z) = mean(A) / mean(B)std(z) = abs(mean(z)) * sqrt((std(A)/mean(A))**2 + (std(B)/mean(B))**2)(if A or B is DataArray, treat as ‘mean’. if missing ‘std’, assume 0.)
- get_werrmean(var, *, _match=None)
dataset of ‘mean’ and ‘std’ of var. Computed along self.stat_dims in array.
- get_werrmeant(var, *, _match=None)
dataset of ‘mean’ and ‘std’ of var, taking stats across time dimension.
self(werrmeant_var) –> self(var).werrmean(tdim), where tdim is the dim associated with time,(tdim default ‘snap’, but if ‘t’ coord associated with a dim, use that dim.)
- get_werrmul(var, *, _match=None)
A_werrmul_B = A * B, but result is a dataset with ‘mean’ and ‘std’.
Does not take any means or stds here, but if A or B has ‘std’ already,assumes independent errors and applies “error propagation” formula:z = A * Bmean(z) = mean(A) * mean(B)std(z) = abs(mean(z)) * sqrt((std(A)/mean(A))**2 + (std(B)/mean(B))**2)(if A or B is DataArray, treat as ‘mean’. if missing ‘std’, assume 0.)
- get_werrsub(var, *, _match=None)
A_werrsub_B = A - B, but result is a dataset with ‘mean’ and ‘std’.
Does not take any means or stds here, but if A or B has ‘std’ already,assumes independent errors and applies “error propagation” formula:mean(A - B) = mean(A) - mean(B)std(A - B) = sqrt(std(A)**2 + std(B)**2)(if A or B is DataArray, treat as ‘mean’. if missing ‘std’, assume 0.)
- get_where_condition_var(var, *, _match=None)
where_condition_var –> self(var).where(self(condition)).
Note: if var contains any underscores, must use parenthesis (like ‘where_condition_(var)’).The alias, self(‘var_where_condition’), does not have such a restriction.for ‘drop’ kwarg, in where(…, drop=…), use drop=self.drop_in_where.
- get_wplasma()
“plasma frequency”. wplasma = sqrt(n q^2 / (m epsilon0))
This is analogous to the “true” plasma frequency of Langmuir oscillations,which is calculated using the same formula but applied to electrons.wplasma is equivalent to wplasmae if self.fluid is electrons.
- get_wplasmae()
electron plasma frequency; Langmuir oscillations. wpe = sqrt(ne qe^2 / (me epsilon0))
- get_xhat()
unit vector in the x direction.
result components determined by self.component, e.g. xhat_x == 1; xhat_y == 0.
- get_xyz(var, *, _match=None)
x, y, and/or z components of var.
- get_yhat()
unit vector in the y direction.
result components determined by self.component, e.g. yhat_x == 0; yhat_y == 1.
- get_zhat()
unit vector in the z direction.
result components determined by self.component, e.g. zhat_x == 0; zhat_z == 1.
- property gofnt_abundance
Abundance(?) to use for G(T) calculations.
Passed directly to muse.instr.utils.chianti_gofnt_linelist via “abundance” kwarg.
- property gofnt_interp_mode
Selects the emission measure x G(T) calculation mode.
See self.GOFNT_INTERP_MODE_OPTIONS for options.
- property gofnt_mode
Selects the G(T) calculation mode. See self.GOFNT_MODE_OPTIONS for options.
- property gofnt_wavelength_range
Wavelength range (as [min, max]) (in [Angstrom] units) to use for G(T) calculations.
Passed directly to muse.instr.utils.chianti_gofnt_linelist via “wavelength_range” kwarg.
- property grad
alias to gradient
- static gradient(array, components=[Component('x', 0), Component('y', 1), Component('z', 2)], *, _post_slices=None)
return gradient of array as a single vector array.
The result will have ‘components’ dimension.components: iterable of str or Component objectswhich components to include in the result.result[‘component’][i] will be components[i],and result.isel(component=j) will be the derivative along str(components[j]).E.g., if components=[Component(‘x’, 0), Component(‘y’, 1)],then result[‘component’][1] == Component(‘y’, 1),and result.isel(component=1) = d(array)/dy.The derivative is taken along the corresponding dimension,e.g. d(array)/dy is xarray_differentiate(array, dim=’y’).Note that any components provided here but missing from array will become 0 in result.e.g., components=[x,y,z] but ‘z’ not in array –>np.all(result.isel(component=2) == 0)._post_slices: None or dict of indexers[EFF] if provided, apply these indexers to results after taking each derivative,but before merging into the final array.Equivalently, could just result.isel(**_post_slices).But, indexing before merging can help avoid ever creating a large array.
- property gradvec_component
alias to self.gradvec_component_dim.v
- property gradvec_components
alias to self.gradvec_component_dim.values
- has_var(var)
return whether self can load var. True if self.match_var(var) is found, else False.
Subclasses might override, to include checks for whether var can be loaded from data.[TODO] also check if var in self.cache or self.setvars.
- help(qstr=None, only=None, *, tree=None, modules=False, signature=False, doc=True, dense=False, print=True)
prints str for help with quants.
qstr: None or str
None –> tells info about this class & how to use this function.in particular, tells that quants are stored cls.KNOWN_VARS and cls.KNOWN_PATTERNS,and describes behavior of calling help with a string.str –> return str for help with all quants related to str.use empty str to get help for all quants.only: None or strIf provided, only get help for a subset of relevant quantities.None –> get help with all quantities related to qstr.‘VARS’ –> only get help with KNOWN_VARS.‘PATTERNS’ –> only get help with KNOWN_PATTERNS.‘TREE’ –> only get help with quantities in cls.cls_var_tree(str).‘EXACT’ –> only get help for the KNOWN_VAR exactly matching qstr.if provided when qstr is None, treat qstr as ‘’ instead.tree: None or boolHow much help to give for quantities in cls.cls_var_tree(qstr).False –> don’t even check cls.cls_var_tree(qstr).True –> help for all quantities in cls.cls_var_tree.None –> help for quantities in cls.cls_var_tree(qstr).flat_branches_until_vars()i.e. patterns & vars in tree but ignore any nodes with LoadableVar ancestors.e.g. qstr=’mean_mod_beta’ –> help with ‘mean_(.+)’, ‘mod_(.+)’, and ‘beta’,but no help with dependencies of ‘beta’ (‘q’, ‘mod_B’, ‘m’).modules: boolWhether to include modules in result.If True, result will be grouped into sections with modules written at top.signature: signature: boolwhether to include line with signature in help string.e.g. “help_str(f, *, module=True, signature=True, indent=None)”doc: doc: boolwhether to include lines with docstring in help string.e.g. “return str for help(f).” … and all the other docs in here.dense: boolWhether to reduce whitespace in result.E.g. True –> no newlines between functions. False –> one newline between functions.
- help_call_options(search=None)
prints help for kw_call_options.
if search is provided, only print help for keys containing search.
- classmethod help_quants_str(qstr=None, only=None, *, tree=None, modules=True, signature=False, doc=True, dense=False, _instance=None)
returns str for help with quants.
qstr: None or str
None –> tells info about this class & how to use this function.in particular, tells that quants are stored cls.KNOWN_VARS and cls.KNOWN_PATTERNS,and describes behavior of calling help with a string.str –> return str for help with all quants related to str.use empty str to get help for all quants.only: None or strIf provided, only get help for a subset of relevant quantities.None –> get help with all quantities related to qstr.‘VARS’ –> only get help with KNOWN_VARS.‘PATTERNS’ –> only get help with KNOWN_PATTERNS.‘TREE’ –> only get help with quantities in cls.cls_var_tree(str).‘EXACT’ –> only get help for the KNOWN_VAR exactly matching qstr.if provided when qstr is None, treat qstr as ‘’ instead.tree: None or boolHow much help to give for quantities in cls.cls_var_tree(qstr).False –> don’t even check cls.cls_var_tree(qstr).True –> help for all quantities in cls.cls_var_tree.None –> help for quantities in cls.cls_var_tree(qstr).flat_branches_until_vars()i.e. patterns & vars in tree but ignore any nodes with LoadableVar ancestors.e.g. qstr=’mean_mod_beta’ –> help with ‘mean_(.+)’, ‘mod_(.+)’, and ‘beta’,but no help with dependencies of ‘beta’ (‘q’, ‘mod_B’, ‘m’).modules: boolWhether to include modules in result.If True, result will be grouped into sections with modules written at top.signature: signature: boolwhether to include line with signature in help string.e.g. “help_str(f, *, module=True, signature=True, indent=None)”doc: doc: boolwhether to include lines with docstring in help string.e.g. “return str for help(f).” … and all the other docs in here.dense: boolWhether to reduce whitespace in result.E.g. True –> no newlines between functions. False –> one newline between functions._instance: None or QuantityLoader instanceif provided, use _instance.match_var_tree() instead of cls.cls_var_tree().
- classmethod help_str(qstr=None, only=None, **kw)
returns cls.help_quants_str(qstr=qstr, only=only, **kw).
cls.help() calls help_str.subclasses might overwrite help_str, but probably won’t touch help_quants_str.
- property 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 strscoordinates(s) of array to take ifft over.promote_dim(array, coord) for any non-dimension coordinates, as needed.None –> equivalent to array.dimsdf: 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 boolif 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; kwargdimmust 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 in_single_fluid_mode
whether self is in “single fluid mode”.
MhdCalculator is always in single-fluid mode… but subclass might not be.Some vars (bases especially) assume single-fluid mode, so it is good to check.E.g. this ensures multifluid subclasses don’t do weird things by accident.
- init_snaps()
set self.snaps based on snap files in self.dirname.
- interp_masked(array_or_var, bins, dim=None, *, mode='correct', return_weights=False)
Compute interpolation masks and normalization factors for a variable (e.g., “T”)
for use in DEM/VDEM binning with or without logarithmic scaling.Works just like the “static” method (not attached to this class),but with a few extra convenient features here:(1) first arg can be array (as in static method), OR a var.if it is a var (i.e., a str), use array=self(var)(2) dim does not need to be provided;if not provided, use dim=str(self.component).Docstring from “static” method copied below, for convenience.————————————————————-Array masked to bins, possibly with interpolation correction and normalization factors,for use in (Velocity) Differential Emission Measure ((V)DEM) binning.The result hasarraydims plusbinsdim, with values from 0 to 1.Conceptually - basically, this just tells whetherarrayoverlaps with each bin.E.g. result.isel(x=i, y=j, bindim=k) tells whether the (i,j)th x,y point overlaps with bin k.Actually - it may include an interpolation correction factor,accounting for adjacent cell values, and any jumps larger than bin widths.E.g. result.isel(x=i, bindim=k) tells how much of bin k is covered from the ith to (i+1)th x.Additionally - if return_weights, this method also returns xn, which can be applied to a value,to properly account for interpolation between adjacent cells.See Rempel et al. (2017) for details.(Note - Rempel+2017 formulas are slightly different than those here,because those formulas solve a slightly different problem.Testing those formulas here led to more numerical artifacts.)If binning multiple quantities (e.g., temperature and velocity), the canonical pattern to use is:mask1, xn = self.interp_masked(quantity1, bins1, return_weights=’exp’)mask2 = self.interp_masked(quantity2, bins2)mask3 = self.interp_masked(quantity3, bins3)… # etc. i.e., only the first call computes interpolation weights.emiss_interped = emiss * (1.0 - xn) + emiss.roll({x:1}) * xnNote - the result’s first value along dim may be unreliable (if non-periodic array),as it relies on array.roll({dim:1}).Parameters———-array : xarray.DataArrayvariable to be interp-masked. E.g., array of log10(temperature) values.bins : xarray.DataArray1D array of (evenly-spaced) bin centers (internally, assumes bin width = (bins[1]-bins[0])/2).dim : strapply the correction along this dimension of array.For VDEMS, this is the dimension along which the LOS integration will be performed.mode: ‘correct’ or ‘simple’tells how to compute the result.‘correct’ –> includes correction factor.‘simple’ –> exclude correction factor, just tells whether each point falls within each bin.Equivalent to: result = (bins - delta <= array) & (array < bins + delta),where delta = (bins[1] - bins[0]) / 2 == bin width.This can be much faster than mode=’correct’, but produces noisier results.(Also, only allowed if return_weights=False).return_weights : False, True, or ‘exp’whether to also return interpolation weights xn for each bin.False –> returns maskedTrue –> returns (masked, xn)‘exp’ –> returns (masked, xn) but compute xn using (10**value, 10**bins) not (value, bins).Returns——-masked : xarray.DataArrayarray of fn * overlaps, where overlaps = whether each cell overlaps with each bin,and fn = normalization factor for each bin, clipped to [0, 1].(Or, if mode==’simple’, this is just (bins - delta <= array) & (array < bins + delta).)xn : xarray.DataArrayInterpolation weight for each bin, with values clipped to [0, 1].(Only returned if return_weights.)
- 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: boolwhether 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: boolwhether to restore original dim values after iteration.enumerate: bool, default Falsewhether 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_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 join_components
alias to self.component_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)
- limb_vdem_pipeline(*, iz0=50, snap=None, tile_snaps=None, tile_snaps_fov=UNSET, fov_method='standard', Abox_x_NXEXT=0, Nx_times=1, Ny_times=1, Nz_times=1, Asph_theta=1.5707963267948966, Asph_phi=0, rays_debug_fov=False, rays_debug_all_tiles=False, tg_percent=0.1, dlogT=0.1, mintg_cut=4.6, maxtg_cut=7.7, tg_bins=60, ulos_bin=60, vel_percent=0.1, dvdop=10, minvel_cut=-3000, maxvel_cut=3000, emiss_norm=1e+27, modelname='', nslicer=46, zarr_version=2, dst='pc_limb_vdem_pipeline', author)
Execute a VDEM pipeline for limb observations using ray draping geometry.
This specialized pipeline performs VDEM analysis for solar limb observations where
the line-of-sight follows curved ray paths through the simulation domain. It usesray draping to simulate realistic observing geometries and supports tiling multiplesnapshots for extended spatial coverage.The pipeline handles large datasets by computing VDEM in slices, performs bothfull-disk and photosphere-cutoff analyses, and generates diagnostic plots withproper coordinate transformations for limb viewing geometry.Parameters———-iz0 : int, default=50Index along z-dimension marking the photosphere boundary. Used forphotosphere cutoff analysis.snap : int or None, optionalSnapshot number to analyze. If None, uses current snapshot.tile_snaps : array-like or None, optionalArray of snapshot indices to tile along x-dimension for extended coverage.E.g., [0, 1, 2, ‘current’] tiles three consecutive snapshots, before the current snapshot.(‘current’ or ‘here’ must appear in tile_snaps exactly once.)Note that the full (tiled) extent will be repeated periodically as needed to cover rays.None –> no tiling, equivalent to tile_snaps = [‘current’](i.e. the single current snapshot would be repeated periodically as needed).tile_snaps_fov: UNSET, None, or array-like, optionaldefault fov includes all rays needed to cover tile_snaps_fov.UNSET –> equivalent to tile_snaps_fov = tile_snaps.None –> no tiling, i.e. default fov only includes the rays needed to cover the current snap.E.g., to make FOV roughly “half-at-limb, half-on-disk”, and buffer with snap 0, could do:tile_snaps_fov = [‘current’, 0], tile_snaps = [‘current’, 0, 0, 0].fov_method : str, default=’standard’Field-of-view generation method. Options depend on ray draping implementation.Abox_x_NXEXT : float, default=0X-offset for ray draping box in units of simulation XEXT (domain extent).Allows shifting the observing geometry along x.Nx_times : float, default=1Multiplier for number of FOV pixels in x-direction relative to simulation Nx.Ny_times : float, default=1Multiplier for number of FOV pixels in y-direction relative to simulation Ny.Nz_times : float, default=1Multiplier for number of ray integration points relative to simulation Nz.Asph_theta : float, default=np.pi/2Spherical coordinate theta (colatitude) angle in radians for viewing geometry.pi/2 corresponds to equatorial view.Asph_phi : float, default=0Spherical coordinate phi (azimuthal) angle in radians for viewing geometry.rays_debug_fov: bool, default=Falseif enabled, halt immediately after producing plot showing ray paths through tile_snaps_fov box.rays_debug_all_tiles: bool, default=Falseif enabled, halt immediately after producing plot showing ray paths through tile_snaps box.This check occurs after rays_debug_fov; it is fast to produce both plots, soit is recommended to use this flag to double-check the rays look correct,before running full pipeline, especially for a large simulation.tg_percent : float, default=0.1Percentage threshold for automatic temperature range determination from histogram.dlogT : float, default=0.1Temperature bin width in log10(T [K]) units.mintg_cut : float or None, default=4.6Minimum log10(temperature [K]) cutoff. Overrides automatic determination.maxtg_cut : float or None, default=7.7Maximum log10(temperature [K]) cutoff. Overrides automatic determination.tg_bins : int, default=60Number of bins for temperature histogram analysis.ulos_bin : int, default=60Number of bins for velocity histogram analysis.vel_percent : float, default=0.1Percentage threshold for automatic velocity range determination from histogram.dvdop : float, default=10Velocity bin width in km/s.minvel_cut : float or None, default=-3000Minimum velocity cutoff in km/s. Overrides automatic determination.maxvel_cut : float or None, default=3000Maximum velocity cutoff in km/s. Overrides automatic determination.emiss_norm : float, default=1e27Emission measure normalization factor.modelname : str, default=’’Model identifier string used in output filenames.nslicer : int, default=46Number of slices for dividing FOV computation. Higher values reduce memoryusage but increase I/O overhead.zarr_version : int, default=2Zarr format version for output files (2 or 3).dst : str, default=’pc_limb_vdem_pipeline’Destination directory for output files.author : str, requiredAuthor name/identifier for output filenames and metadata.Returns——-vdem0 : xarray.DatasetProcessed VDEM dataset with limb observation coordinates and complete metadata.Contains ‘vdem’ data variable with dimensions (logT, vdop, x, y) where x and yrepresent FOV coordinates.Notes—–**Copy of self**: This pipeline uses self.copy() instead of using self directly,to avoid editing self in-place. Self will not be changed by this pipeline.**Temporary Directories**: This pipeline creates and DELETES temporary directories:- ‘_pc_temp_fov_lib_vdem/’: For storing partial VDEM computations- ‘_pc_temp_fov_lib_vdem_ph/’: For photosphere-cutoff VDEM computationsThese directories will be destroyed via shutil.rmtree() during pipeline execution.**Ray Draping Setup**: The pipeline configures ray draping with:- R0 = Solar radius (from DEFAULTS.PHYSICAL.CONSTANTS_SI)- T = 1 AU (observer distance)- Integration points scaled by Nz_times- FOV dimensions scaled by Nx_times- Spherical viewing angles (Asph_theta, Asph_phi)**Output Files**:- Temperature/velocity histograms:‘T_ulos_hist_{code}_{modelname}_{author}_{date}_{snap}.png’- VDEM moments (full):‘vdem_moment_{code}_{modelname}_{author}_{date}_{snap}.png’- VDEM moments (photosphere):‘vdem_moment_ph_{code}_{modelname}_{author}_{date}_{snap}.png’- VDEM Zarr dataset:‘vdem_{code}_{modelname}_limb_{author}_{date}_snaps_{tiles}.zarr’**Processing Steps**:1. Configure ray draping geometry with spherical coordinates2. Enable snapshot tiling if tile_snaps provided3. Compute histograms to determine optimal T and velocity ranges4. Compute VDEM in FOV slices to manage memory5. Merge slices and compute moments for full domain6. Repeat with photosphere cutoff (z < iz0-15)7. Generate diagnostic plots with proper scaling8. Save with complete metadata and coordinate attributesExamples——–>>> # Standard limb observation at solar equator>>> result = calc.limb_vdem_pipeline(… snap=100,… tile_snaps=[99, ‘current’, 101],… author=’scientist_name’… )>>> # High-resolution polar limb observation>>> result = calc.limb_vdem_pipeline(… Asph_phi=-np.pi/2, # North pole view… Nx_times=2, # Double resolution… dlogT=0.05, # Finer temperature bins… nslicer=92, # More slices for memory… author=’scientist_name’… )>>> # Limb observation with shifted viewpoint>>> result = calc.limb_vdem_pipeline(… Abox_x_NXEXT=0.5, # Shift by half domain width… Asph_phi=np.pi/4, # 45-degree azimuthal angle… author=’scientist_name’… )See Also——–vdem_pipeline : Standard VDEM pipeline without ray drapingget_vdem : Core VDEM computation methodray_draper : Ray draping geometry handler
- property line_of_sight
alias to los
- 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 objectsload 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 Nonewhether 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 callableif provided, use loader0 to get the first array, then use loader for the rest.Internally the first array’s .coords and .attrs are used to label the result;however all other arrays do not need to be converted to xarray._shift_special: UNSET or dict of (dimstr: list of special values)workaround to encourage loader0 to be called on a “usual” case, not a special case.if provided, and dimstr in dims, and d=self.dimensions[dimstr] has multiple values,with special_value first, and at least one non-special value later, theninternally rearrange dim values order before loading,then rearrange result back to original order (via indexing).E.g. _shift_special=dict(snap=[INPUT_SNAP]) –> apply loader0 to the first non-INPUT_SNAP,if there are any non-INPUT_SNAP snap values in snap, and ‘snap’ in dims.— MULTIPROCESSING STRATEGY OPTIONS (from self) —timeout: None or intmax 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^if self.timeout has not been set, use DEFAULTS.LOADING_TIMEOUT (default: None).ncpu: None or intmax 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.if self.ncpu has not been set, use DEFAULTS.LOADING_NCPU (default: 1).ncoarse: intif >1, group tasks into groups of size ncoarse before performing them.if self.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_FREQif self.print_freq has not been set, infer from self.verbose if it exists,else 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: strvariable 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 Nonewhether 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 1if 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, self.setvars,
or via self.load_input() if self.snap is INPUT_SNAP.Steps:1) attempt to get var from cache or self.setvars.[EFF] only tries this if we are not self._inside_quantity_loader_call_logic,to avoid redundant calls to self.get_set_or_cached.2) adjust var name if appropriate, via new_varname = self._var_for_load_fromfile(var).if new_varname != old varname, attempt to get new_varname from cache or setvars.3) if self.snap is INPUT_SNAP, return self.load_input(new_varname).4) super().load_direct(new_varname, *args, **kw),which calls self.load_fromfile(new_varname) (or crashes if self.enable_fromfile=False)
- load_fromfile(fromfile_var, *args__None, snap=None, **kw__None)
return numpy array of fromfile_var, loaded directly from file.
fromfile_var: str
the name of the variable to read, adjusted appropriately for loading fromfile.E.g. use ‘result_prim_5’ not ‘bx’, to get magnetic field x-component.See also: self._var_for_load_fromfile().snap: None, str, int, or Snapthe snapshot number to load. if None, use self.snap.
- load_input(fromfile_var, *args, **kw)
load value of fromfile_var but when self.snap is INPUT_SNAP.
[Not implemented for this subclass; loading direct when self.snap is INPUT_SNAP will crash](optional; subclass can override in order to implement INPUT_SNAP functionality.see EppicCalculator.load_input() for an example.)
- 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 None4) set result.attrs[‘units’] = self.units5) if self.maindims_means: take mean of result, across all maindims.6) use result = self._maindims_postprocess_callback(result), if possible.(Before those steps, first checks special cases:- if tile_snaps, load for each snap then concatenate results appropriately.- if using multi_slices, load for each slice then combine results into xarray.Dataset(or combine into dict instead if assign_labels=False).)u: None, value, or strunits factor for the result.None –> don’t do any units conversions.str –> multiply result by self.u(u)value –> multiply result by uassign_labels: boolwhether 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?)
- 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 strunits factor for the result.None –> don’t do any units conversions.str –> multiply result by self.u(u)value –> multiply result by u
- property loi
Line Of Integration (dim, dict of arrays for interp), or “Lots Of Interpolation”, if you prefer.
Used by self(“var_loi”) pattern (for the interpolation) and any quantities which integrate along a line.([TODO] move the integrate-along-a-line patterns here, e.g. from mhd_radiative_loader.)Can be any of the following:None –> no integrate-along-a-line (those methods will crash), and no interpolation.self(“var_loi”) == self(“var”).dict –> no integrate-along-a-line (those methods will crash), but can interpolate onto these arrays.self(“var_loi”) == self(“var”).interp(**self.loi)str –> special option (e.g. ‘los’ for “use behavior implied by self.los”)see self.LOI_OPTIONS for all special options.2-tuple –> (integration instructions, interpolation instructions)integration instructions can be None (as above) or str telling dim to integrate along.Note: if dim ends with ‘_dim’, assumes dim[:-4] tells coord values,e.g. x_dim implies integration along ‘x_dim’ but dx comes from ‘x’ coord,which is a useful pattern if ‘x’ coord depends on multiple dims.Note: if dim starts with ‘-’, assumes loi_cumsum should be evaluated in reverse order.Physically, this can affect things like optical depth.interpolation instructions can be None (as above) or dict (as above).(To supply kwargs to the interpolator, provide them in the dict.E.g.: dict(x=array(…), y=array(…), assume_sorted=True).Or, for clarity: dict(coords=(x=array(…), y=array(…)), assume_sorted=True).)
- loi_cumsum(array, *, do_interp=True, sort=UNSET)
return array interpolated onto coordinates implied by self.loi,
then cumulatively summed along line-of-integration dimension implied by self.loi.Cumulative sum is in forward order by default, but if loi integration dim starts with ‘-‘,instead reverse order, then cumsum, then reverse again to restore original order.do_interp: boolwhether to do the interpolation step (if any) implied by self.loi.(disable if providing array which is already the result of loi_interp().)sort: UNSET, bool, ‘ascending’, or ‘descending’if UNSET, use sort = self.loi_cumsum_sortTells whether to sort along the integration dimension before doing cumsum in self.loi_cumsum().(If sorting changes order, will not restore original order after cumsum operation,so operations relying on xarray coord matching would still work,but underlying data order will be different between result and original array.)True or ‘ascending’ –> sort in ascending order.‘descending’ –> sort in descending order.False –> do not sort.This check occurs before any reversing implied by self.loi.Example: self.loi_explicit[0] == ‘-z’, loi_cumsum_sort=True–> array.sortby(‘z’).isel(z=slice(None,None,-1)).cumsum(‘z’).isel(z=slice(None,None,-1))See help(type(self).loi) for more details.
- property loi_cumsum_sort
Tells whether to sort along the integration dimension before doing cumsum in self.loi_cumsum().
(If sorting changes order, will not restore original order after cumsum operation,so operations relying on xarray coord matching would still work,but underlying data order will be different between result and original array.)True or ‘ascending’ –> sort in ascending order.‘descending’ –> sort in descending order.False –> do not sort.This check occurs before any reversing implied by self.loi.Example: self.loi_explicit[0] == ‘-z’, loi_cumsum_sort=True–> array.sortby(‘z’).isel(z=slice(None,None,-1)).cumsum(‘z’).isel(z=slice(None,None,-1))
- property loi_explicit
loi as 2-tuple of (integration axis, None or dict of arrays for interpolation).
Getting loi_explicit will crash if no implied integration axis.If integration axis starts with ‘-’, it implies loi_cumsum() in reverse order.e.g. ‘-x’ is just like ‘x’ but any loi cumsums will be in reverse.Physically, this can affect quantities like optical depth.
- loi_interp(array)
return array interpolated onto coordinates implied by self.loi.
See help(type(self).loi) for more details.Returns array unchanged if self.loi implies no interpolation.
- property loi_ustr
units string (e.g., ‘length’) for loi interped coords,
in case self.units != self.coords_units, and loi not just along a maindim.Probably want to use ‘length’, but ‘length’ not assumed by LoiLoader,because maindims can technically represent anything, not just physical length.Subclass can alter default value used by editing _LOI_USTR_DEFAULT.(So, if subclass knows maindims and loi are lengths, it should set _LOI_USTR_DEFAULT=’length’)UNSET –> internally uses self._loi_ustr_default (default in LoiLoader: None. Subclass may override.)None –> if any units ambiguity (e.g. when getting dloi), crash.str –> use this string to get unit conversion factors as needed.e.g., umul = self.u(self.loi_ustr, units=self.units, convert_from=self.coords_units_explicit)dloi = xarray_d_grid(interped, xc) * umul # (when loi not in maindims)
- property loi_ustr_explicit
loi_ustr, but returns self._loi_ustr_default if loi_ustr is UNSET
- property los
line of sight vector; used by self(“var_los”) pattern and any quantities which depend on it. Can be:
None –> var_los will crash,str –> must be one of a few special strings (e.g. ‘x’ for XHAT, ‘-x’ for -XHAT);see self.LOS_OPTIONS for all special options.array –> xr.DataArray with ‘component’ dim representing line-of-sight vector(s).(Does not need to have magnitude 1; var_los will convert to unit vectors as needed.)To get array, use self(‘los’) (instead of something like self.los_explicit).
- 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 strscoordinates 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 <= 1fraction 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 <= 1radius 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 tokeep, 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 boolwhether to return np.real(ifft) instead of just ifft (which might have imaginary part)None –> infer from array. Use True if np.all(np.isreal(array)), else False.return_fft: boolwhether to return (result, masked fft) instead of just result.mainly intended for debugging purposes.
- property lowpass_keep
the default value for “keep” in self.lowpass. 0 < lowpass_keep <= 1.
Or, can be a dict of {dim: keep} pairs, to use different keep for different dims.To use keep_r instead of keep, call lowpass directly and enter keep_r there.
- static magnitude(A, *, squared=False)
return vector magnitude of A, assuming vector components along the dimension ‘component’.
squared: bool, default Falseif 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
maindims of MURAM data, i.e. (‘x’, ‘y’, ‘z’).
(currently only 3D MURAM data reading is implemented.)see MainDimensionsHaver for more maindims implementation details.
- 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.
- property maintaining
alias to maintaining_attrs
- maintaining_attrs(*attrs, **attrs_as_flags)
returns context manager which restores attrs of self to their original values, upon exit.
E.g. maintaining_attrs(obj, ‘attr1’, ‘attr2’, attr3=True, attr4=False)–> will restore upon exit, original values of obj.attr1, attr2, and attr3, but not attr4.
- property mask
None or xarray.DataArray of bools,
if self.masking, apply mask to results (with mask dims) at top-level (call_depth=1)(internal calls still do full calculations, so derivatives will still work.)applying mask means calling self.apply_mask(result);masking = True or ‘stacked’ –> xarray_mask(result, stack=True); i.e., drops all masked points.(and, result will have ‘_mask_stack’ dimension instead of mask.dims dimensions)masking = ‘simple’ –> xarray_mask(result, stack=False); i.e., masked points just replaced by nan.never applies mask if self.mask = None.setting self.mask = value is equivalent to calling self.set_mask(value).
- property masking
how to apply self.mask to results at top level, if mask exists.
True –> alias for ‘stacked’. This is the default.‘stacked’ –> apply stacked mask to self.stack(result), dropping masked points.‘simple’ –> apply mask to result, filling masked regions with np.nan.False –> do not apply mask, even if self.mask exists.
- classmethod match_var(var, *, check=['KNOWN_VARS', 'KNOWN_PATTERNS'])
match var from cls.KNOWN_VARS or cls.KNOWN_PATTERNS, or raise FormulaMissingError.
returns result=MatchedQuantity(var, loadable, _match=_match) where:
loadable is the LoadableQuantity associated with this var,_match is:None, if var in cls.KNOWN_VARS;re.fullmatch(pattern, var), if var matches any pattern in cls.KNOWN_PATTERNS.if var matches multiple patterns, only the first matching pattern is used.Uses MatchedVar if match from KNOWN_VARS, MatchedPattern if from KNOWN_PATTERNS.(note that both MatchedVar and MatchedPattern subclass MatchedQuantity.)check: str or list of str from [‘KNOWN_VARS’, ‘KNOWN_PATTERNS’]where to check for matches. Default is to check KNOWN_VARS and KNOWN_PATTERNS.E.g. to only check KNOWN_PATTERNS, use check=[‘KNOWN_PATTERNS’].loadable and _match can be retrieved via result.loadable and result._match.
- match_var_loading_dims(var, **kw_loading_dims)
return dims for loading var across.
Result will probably vary across these dims (but not guaranteed, if any dependency uses reduces_dims.)These are all Dimension dims, not maindims. (E.g. ‘fluid’ and ‘snap’, but not ‘x’, ‘y’, ‘z’).Equivalent: self.match_var_tree(var).loading_dims(**kw_loading_dims)
- match_var_result_dims(var, **kw_result_dims)
return dims which result of cls(var) will vary across.
These are all Dimension dims, not maindims. (E.g. ‘fluid’ and ‘snap’, but not ‘x’, ‘y’, ‘z’).Equivalent: cls.match_var_tree(var).result_dims(**kw_result_dims)
- match_var_result_size(var, *, maindims=True, **kw_result_dims)
return size (number of elements) which self(var) will have.
(Efficient; doesn’t actually get self(var).)Depends on current values of relevant dims. (E.g., self.fluid, not self.fluids)maindims: boolif True, include maindims_shape when calculating size.
- match_var_tree(var=UNSET, **kw_quant_tree_from_quantity_loader)
return QuantTree of MatchedQuantity objects from matching var and all dependencies,
using self.KNOWN_VARS and self.KNOWN_PATTERNS when searching for matches.var must be provided; var=UNSET will raise an error (helpful if tried calling this as a classmethod).See also: type(self).cls_var_tree, for the classmethod version of this function.Most of the time it is possible to get tree without any details from self,but sometimes not. e.g. when getting collision frequencies, self.fluid affects deps.additional kwargs will be passed to QuantTree.from_quantity_loader(…),which passes kwargs from self.kw_call_options() into self.using(**kw) while getting deps.
- matched_pattern_cls
alias of
MatchedPattern
- matched_var_cls
alias of
MatchedVar
- property metadata
dict of metadata attributes and their values, excluding missing and ATTR_UNSET.
See also: self.metadata_all.
- property metadata_all
dict of metadata attributes and their values (value=ATTR_UNSET if missing).
See also: self.metadata.
- property metadata_attrs
alias to cls_metadata_attrs; set of all attrs which tell metadata,
about this data source (simulation run / observation / other data source).E.g. metadata_attrs={‘dirname’, ‘datetime_run’}.
- 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 intNone –> 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 < 1index 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))
- property nGbytes
number of gigabytes across all files in self.dirname (and subdirectories).
== self.nbytes / 1024**3
- property nMbytes
number of megabytes across all files in self.dirname (and subdirectories).
== self.nbytes / 1024**2
- n_existing_snaps()
returns number of existing snaps. Equivalent to self.snap_dim.n_existing_for(self).
- property nbytes
number of bytes across all files in self.dirname (and subdirectories)
- property ncoarse
int
if >1, group tasks into groups of size ncoarse before performing them.
- property ncpu
None or int
max number of cpus to use for multiprocessing.None –> use multiprocessing.cpu_count()int –> use this value. if 0 or 1, do not use multiprocessing here.Note: will actually use min(ncpu, number of calls to be made);e.g. if ncpu=4 but len(arg_kw_tuples)=2, will only use 2 cpus.see also: self.get_ncpu() to read actual number of cpus when self.ncpu is None.
- property nondim_behavior_attrs
list of attrs in self which control behavior of self, but which are NOT in self.dimensions.
- property notes_dirname
‘abspath to directory containing plots/notes for a DirectLoader.
Might be the same directory as self.dirname, but doesn’t need to be;can explicitly set self.notes_dirname = value, if desired.If not set, use notes_dirname == self.dirname,unless self.dirname ends with one of the self._INDICATES_NOTES_DIRNAME options.E.g. dirname == ‘path/to/dir0’ –> notes_dirname == ‘path/to/dir0’.E.g. dirname == ‘path/to/dir1/_sim’ –> notes_dirname == ‘path/to/dir1’.E.g. dirname == ‘path/to/dir1/_check0’ –> notes_dirname == ‘path/to/dir1’.See also: self.unique_notes_dirname
- property output_mask
whether to store_mask during xarray_mask calls if self.masking.
False –> never store mask in resultsTrue –> always store mask in top-level results(all results will be xarray.Dataset objects with ‘_mask’ data_var)None –> only store mask in results which would have been Datasets anyways.
- property params
return the global params shared by all snaps.
Equivalent to self.snaps.params_global(recalc=False).
- property pc_uuid
PlasmaCalcs uuid (universally unique identifier) associated with self.dirname.
Returns value of existing uuid if possible, else ATTR_UNSET.See also: self.get_pc_uuid(), which will generate the uuid as needed.Equivalent to self.get_pc_uuid(generate=False, default=ATTR_UNSET).
- static pc_uuid_here(dir, *, generate=None, default=UNSET, return_meta=False)
return the PlasmaCalcs uuid associated with this directory.
The uuid is intended to be a universally unique identifier;
it is highly unlikely that any other uuid will ever match this one.This is especially useful for the .register() method and the registry.The uuid will be stored in a file named _pc_uuid.txt inside dir, which contains:# comment lines starting with ‘#’ explaining the purpose of the file# assignment lines below might also have # comments at end of lineuuid = “uuidstringwithouthyphens”generated_at = “YYYY-MM-DDTHH:MM:SS.ssssss+HH:MM” # when this uuid was generated# the file might also contain other assigments but likely will not;# other assignments will be ignored.dir: strpath to directory.generate: None, True, or Falsewhether to generate a new uuid (and create corresponding _pc_uuid.txt file)None –> as needed; only if _pc_uuid.txt does not already exist.True –> generate new uuid; crash if _pc_uuid.txt already exists.False –> return existing uuid; crash (or return default) if _pc_uuid.txt does not exist.default: UNSET or any objectif not UNSET, returndefaultif _pc_uuid.txt file does not exist and generate is False.Only used if generate is False.return_meta: boolwhether to instead return a dict containing all info from _pc_uuid.txt,including the metadata. If True, dict contains ‘uuid’ and all other keys from file.(Values evaluated via ast.literal_eval if possible, else kept as string.)When sharing runs across machines, keep the _pc_uuid.txt file,to allow PlasmaCalcs to identify it as “the same run” in multiple places.When copy-pasting a run as a starting point but wanting PlasmaCalcsto treat the new copied run as a different run, delete its _pc_uuid.txt file.
- 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 strperson 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: boolwhether 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: boolwhether 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 strsvar 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 strstells the way to infer skappa, and thus nusn. Options: ‘momExB’, ‘momE’, ‘hall’, ‘pedersen’.iterable of strs –> get multiple.cycle1: dict of listsparameters to use for matplotlib plotting if getting multiple u or drift.means: boolwhether 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: boolwhether 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: strcoordinate to polyfit along.If coord is not already a dimension, use array=promote_dim(array, coord).degree: intdegree of polynomial to fit.window: UNSET, None, or int.UNSET –> use self.polyfit_windowNone –> don’t use windowing; polyfit to the entire array along coord.int –> coarsen array along dim, using windows of this length,then polyfit in each window, then concat results along coord.Pass additional kwargs to xarray_coarsened_polyfit;also use self.polyfit_kw as defaults (for any kwargs not provided here).returns an xarray.DataSet which is the result of polyfit.
- property polyfit_boundary
alias to self.polyfit_kw[‘boundary’].
When polyfitting, tells how to handle boundaries when coarsening array.probably ‘exact’, ‘trim’, or ‘pad’.
- property polyfit_cov
alias to self.polyfit_kw[‘cov’].
When polyfitting, tells whether to also return the covariance matrix.only used if self.polyfit_full=False.
- property polyfit_full
alias to self.polyfit_kw[‘full’].
When polyfitting, tells whether to also return residuals, matrix rank and singular values.
- property polyfit_keep_coord
alias to self.polyfit_kw[‘keep_coord’].
When polyfitting, tells whether to keep some of the original coord values in result.probably ‘left’, ‘middle’, ‘right’, or False.
- property polyfit_kw
kwargs to pass to self.polyfit(), other than array, coord, degree, and window.
See polyfit_kw_key_aliases for a list of aliases to some of these kwargs, as attributes of self.getting self.polyfit_kw will also set keys to default values from aliases,e.g. polyfit_boundary has default of ‘trim’ –> if polyfit_kw[‘boundary’] not set, set it to ‘trim’.
- property polyfit_stddev
alias to self.polyfit_kw[‘stddev’].
When polyfitting, tells whether to also return the standard deviations of the coefficients.incompatible with self.polyfit_full=True.
- property polyfit_window
When polyfitting, tells window size to use for coarsening arrays before fitting.
E.g., polyfit_window=10 –> windows of length 10, polyfit in each window, concat results.
- pop_dim_keys(kw)
return ({key: kw.pop(key) for key in self.dimensions if key in kw}, kw).
- property print_freq
None, or number (possibly negative or 0)
>0 –> Minimum number of seconds between progress updates.=0 –> print every progress update.<0 –> never print progress updates.None –> use DEFAULTS.PROGRESS_UPDATES_PRINT_FREQ
- property print_freq_explicit
like self.print_freq, but converts UNSET to value based on self.verbose,
UNSET –> result depends on self.verbose:False or <=0 –> -1True or (>=1 and <5) –> None>=5 –> 0 (i.e. print every progress update)if self.verbose doesn’t exist –> Noneif result would be None, instead give DEFAULTS.PROGRESS_UPDATES_PRINT_FREQ.
- quant_tree(var=UNSET, **kw_quant_tree_from_quantity_loader)
return QuantTree of MatchedQuantity objects from matching var and all dependencies,
using self.KNOWN_VARS and self.KNOWN_PATTERNS when searching for matches.var must be provided; var=UNSET will raise an error (helpful if tried calling this as a classmethod).See also: type(self).cls_var_tree, for the classmethod version of this function.Most of the time it is possible to get tree without any details from self,but sometimes not. e.g. when getting collision frequencies, self.fluid affects deps.additional kwargs will be passed to QuantTree.from_quantity_loader(…),which passes kwargs from self.kw_call_options() into self.using(**kw) while getting deps.
- property ray_draper
The RayDraping instance to use. alias to self.ray_draping_explicit.
Use self.ray_draper to access the RayDraping instance implied by self.ray_draping,regardless of whether it is None, dict, or already a RayDraping instance.See help(type(self).ray_draping) for more details.
- property ray_draping
None, dict, or RayDraping instance defining RayDraping for ray draping problems.
Set kwargs here, then get the RayDraping instance via self.ray_draper. E.g.:self.ray_draping=dict(…) # <– set RayDraping kwargs as desiredself.ray_draper.rays(system=’box’) # <– ray paths in “box” systemNone –> quantities needing ray_draping will crash.dict –> will use RayDraping.from_dict({**self.ray_draping_defaults(), **ray_draping})(e.g., XEXT, YEXT, and ZEXT will come from self.maindims_coords() by default.)RayDraping –> will use that RayDraping instance directly.
- ray_draping_cls
alias of
RayDraping
- ray_draping_defaults()
return dict of defaults to use for ray_draping.
Asserts that set(self.maindims) == {‘x’, ‘y’, ‘z’}.XEXT, YEXT, ZEXT, X0, Y0 will be taken from self.maindims_coords()No other keys included here.For ZEXT, just does zmax, ignoring zmin, from self.maindims_coords()[‘z’].This maps z=0 to the sphere surface at R0. Rays will not pass through to z<0.(Internally, does still make the reasonable assertion: zmax>0)Workaround options if any of the behavior here is not desireable:option 1: set ray_draper = RayDraping(…) directly, with whatever kwargs you want,instead of the default ray_draper = RayDraping({**ray_draping_defaults, **ray_draping}).option 2: shift maindims coords upon loading.The easiest way to do this is probably to subclass your PlasmaCalculator,overriding _get_maindims_base to shift the z coords as desired,and possibly use a shifted R0 (which RayDraping always maps to z=0).
- property ray_draping_explicit
self.ray_draping, but convert to RayDraping instance if needed.
(crashes with InputMissingError if self.ray_draping is None.)
- property rcoords_Pe_cgs
electron Pressure [cgs units] values, used by some MhdRadiativeLoader vars.
E.g., used by G(T) when self.gofnt_mode==’pressure’.Can be a scalar, a 1D list or numpy array, or 1D xr.DataArray with dimension ‘Pe’.
- property rcoords_logD_cgs
log10(electron number density [cgs units]) values, used by some MhdRadiativeLoader vars.
E.g., used in vdems and used by G(T,ne) when self.gofnt_mode==’density’.Can be a scalar, a 1D list or numpy array, or 1D xr.DataArray with dimension ‘logD’.
- property rcoords_logT
log10(Temperature [K]) values used by some MhdRadiativeLoader vars.
E.g., used in VDEMs and in G(T) lookup tables.Can be a scalar, a 1D list or numpy array, or 1D xr.DataArray with dimension ‘logT’.Note: rcoords_logT minimum value can never be less than self.vdem_logT_min.(attempting to set bad value will cause crash & helpful error message.)
- property rcoords_vdop_kms
velocity [km/s] (or, doppler shift) values, used by some MhdRadiativeLoader vars.
E.g., used in VDEMs and in getting spectra.Can be a scalar, a 1D list or numpy array, or 1D xr.DataArray with dimension ‘vdop’.
- property rcoords_wavelength_A
Wavelength (in [Angstrom] units) used by some MhdRadiativeLoader vars.
E.g., used in get_spectra().[TODO] can it be a 1D list/array, or is it required to be a scalar?
- record_units(array)
return array.assign_attrs(self.units_meta()).
if array is not an xarray.DataArray, convert it first.
- register(registry=UNSET, *, metrics=[], username=UNSET)
register this instance and these metrics to the registry.
returns (registry.register() result, Registry object).(registry.register() result is a namedtuple of (run_id, history_id))registry: UNSET, None, Registry, or strRegistry –> use it directlyelse –> pass to self.registry_cls (probably Registry), which probably does:UNSET –> use registry implied by DEFAULTS.REGISTRY_LOCATION(if DEFAULTS.REGISTRY_LOCATION=None, use registry_location_default(),which is system-dependent, e.g. “~/.plasmacalcs/pc_registry.db” on Linux.)None –> use in-memory registry, equivalent to “:memory:”, does not edit any files.str –> filepath to registry database file.metrics: list of (str or dict) entriesmetrics to register (and possibly compute) for this instancestr –> compute this metric via self(metric)dict –> {key: value} to register directly, without computing via self(key)In case of conflict, later values override earlier ones,e.g. [{‘mykey’: 1}, {‘mykey’: 2}] registers ‘mykey’ with value 2.username: UNSET, None, or strUsername associated with this operation.UNSET –> get value from DEFAULTS.REGISTRY_USERNAME (default None).None –> no username provided. Only allowed for local databases.str –> username associated with this operation.Also, checks for consistency with registry.username ifregistryis a Registry object.
- registry_cls
alias of
Registry
- registry_params()
return flat dict of input params to use in self.register().
Basically self.params, but remove ‘dirname’ if present.(Allows ‘snap_s’ and ‘t’ to stay in case self has only 1 snap, that’s fine.)
- 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 strplotter 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: listexclude plotters with any of these people in plotter.who.skip_kinds: listexclude plotters with any of these kinds in plotter.kinds.min_cost: None or numberexclude plotters with cost < min_cost.None –> no minimum.max_cost: None or numberexclude plotters with cost > max_cost.None –> no maximum.For plotting:dst: strwhere 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 strwhether 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 strextra lines to put in the log “header”, if doing save_log.kw_save: dictkwargs to pass to plotter.save(…)bbox_inches: UNSET or any valueif provided, added to kw_save.dpi: UNSET or any valueif provided, added to kw_save.show: boolwhether 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: boolwhether 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: numberminimum 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_T_fromtable(value, **kw)
set T_fromtable to this value. T_fromtable = single fluid temperature, from er table.
Depends on the current value of r; if also setting r be sure to set r first.(internally, sets eperm such that T is the given value when doing lookups.)
- set_attrs(**attrs)
sets these attrs in self.
- set_e(value, **kw)
set e to this value. e = energy density.
- set_eperm(value, **kw)
set eperm to this value. eperm = internal energy per unit mass == e / r.
Depends on the current value of r; if also setting r be sure to set r first.
- set_inelasticity(value, **kw)
set inelasticity to this value, for this (self.fluid, self.jfluid) pair.
- 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_n(value, **kw)
set n to this value. n = number density == r / m.
- set_pop_dim_attrs(kw)
set self.{key} = kw.pop(key) for each key in self.dimensions if key in kw.
- set_r(value, **kw)
set r to this value. r = mass density.
- 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: strthe var to set in self.value: number, xarray, iterable or 1D array, array with shape matching self.maindims_shape.the value to set var to.number –> set var to this number.xarray –> set var to this xarray.[TODO](not yet implemented) iterable or 1D array –> set var to these values along dim=’testing’.[TODO](not yet implemented) array with shape matching self.maindims_shape –> set var to this array.behavior_attrs: None or listtells which attrs from self control behavior of the set var.The set var will only be retrieved when behavior_attrs of self are compatible.E.g. set_var(‘n’, [‘fluid’, ‘snap’]) –> saves ‘n’ in cache with current fluid & snap.Will only load ‘n’ if self.fluid and self.snap == cached fluid and snap for ‘n’.if var in self.KNOWN_SETTERS, cannot provide behavior_attrs here.else, use self.behavior_attrs if None.forall: list of stringsif provided, tells which attrs of self do NOT control the behavior of the set var.E.g. forall=[‘snap’] –> ‘snap’ will NOT be included in behavior_attrs.(anything in behavior_attrs AND forall will be removed from the final behavior_attrs)ukey: None or strif provided, tells string to give to UnitsManager when converting value’s units.When ukey is known, setting value in any unit system will enable to read it in all unit systems.E.g. set_var(‘n’, 1e10, …, ukey=’n’, units=’si’)–> self(‘n’, units=’raw’) == self(‘n’, units=’si’) * self.u(‘u’, ‘raw’, convert_from=’si’)if not provided, value will be associated with current unit system;attempted to read value in any other unit system will not used the cached value set here.E.g. set_var(‘u’, 1e10, …, units=’si’) # ukey not provided–> self(‘u’, units=’raw’) –> uses self’s other logic for getting ‘u’, not from setvars.note: if provided, ‘units’ will be added to behavior_attrs if not already in there.forced: bool, default Truehandles the case where self.KNOWN_SETTERS[var] doesn’t exist. In that case…True –> set var in self, anyway.False –> crash; raise FormulaMissingErroradditional kwargs, if provided, go to self.using(**kw) during the operation.returns list of set quantities.
- set_var_internal(var, value, behavior_attrs, forall=[], *, ukey=None)
set var in self. KNOWN_SETTERS functions may wish to use this method.
(KNOWN_SETTERS functions should NOT use self.set_var, to avoid recursion issue.)This function has the internal logic for self.set_var;set_var calls set_var_internal when self.KNOWN_SETTERS[var] not provided.var: strthe var to set in self.value: number, xarray, iterable or 1D array, array with shape matching self.maindims_shape.the value to set var to. See help(self.set_var) for more info.behavior_attrs: list of stringsthe behavior attrs relevant to setting this var;getting var only gives value when current behavior attrs values are compatible with the cached ones.forall: list of stringsif provided, tells which behavior attrs do NOT control the behavior of the set var.e.g. behavior_attrs=[‘snap’, ‘fluid’], forall=[‘snap’] –> use [‘fluid’], only.ukey: None or strif provided, tells string to give to UnitsManager when converting value’s units;when ukey is provided, can retrieve value in any unit system (probably ‘si’ or ‘raw’).when ukey not provided, if ‘units’ in used behavior attrs, can only retrieve value in that unit system.
- 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.Setting self.slices = None means “no slices” and will actually set self.slices to an empty dict().(self.slices = None –> (self.slices is None) == False, but (self.slices == dict()) == True.)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).
- 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 sliceskeep_None: bool, whether to keep slices with value None in the string.
- property snap
alias to self.snap_dim.v
- property snap_array_equals
alias to self.snap_dim.array_equals
- snap_datetimestamp(snap=None, *, tz='local', as_str=False, sep='_')
return (best-effort guess of) datetime when this snap was created or first written.
Result depends on system:
- macOS: real birth time- Windows: real creation time- Linux: falls back to modification time (st_mtime)snap: None, str, int, or Snapthe snapshot to load. if None, use self.snap.tz: ‘local’, ‘utc’, or datetime.tzinfo objecttimezone to convert result to. ‘local’ –> machine’s local timezone.‘utc’ –> standard/universal time (UTC) (“+00:00” if converted to str)as_str : boolwhether to instead return as isoformat string using sep: YYYY-MM-DD_HH:MM:SS.ssssss+HH:MMsep: stringseparator between date and time if as_str=True. (default ‘_’ shown in format above^)‘T’ is nice for more universal recognizability; ‘ ‘ too but slightly less universal.
- 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, i.e. to the Header.NNN file.
- 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.
Here, gives self.dirname, because Muram outputs are stored at top-level of directory.
- 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 numbermaxmimum 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 ifcacheimplies to load from existing cached file.)True –> use default: DEFAULTS.ADDONS.TFBI_EBSPEED_INPUTS_MBYTES_MAX (default: 0.1).False or None –> no maximumcache: ‘caches’, ‘cache’, ‘cached’, or Falsecontrols how & whether to handle cache the result.cached results go to self._tfbi_vs_EBspeed_file(); default:{self.unique_notes_dirname}/_pc_tfbi/EBspeed_{logmin:.4g}_{logmax:.4g}_{logstep:.4g}.pcxarrwhere logmin, logmax, logstep are from self.tfbi_EBspeed_grid_size‘caches’ –> read from saved file if it exists. Else, solve and save to file.‘cache’ –> solve and save to file. Saved file must not exist yet (else, crash).‘cached’ –> read from saved file. Saved file must exist (else, crash).False –> solve and return result, but do not save to file nor check if file exists.additional kwargs are passed to self.tfbi_solver().solve(**kw)
- 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 tabin
dict-like manager for Equation Of State tables; should include keys ‘ne’, ‘T’, ‘P’.
Each table=tabin[var] should have a table.interp(r=r, e=e) method,which returns value of var in ‘raw’ units, given values of r & e in ‘raw’ units.
- tabin_cls
alias of
erTabInputManager
- property tabinputfile
abspath to tabinputfile (used when creating default self.tabin).
return os.path.join(self.dirname, ‘tabparam.in’)
- property take_component
alias to self.component_dim.take
- property take_components
alias to self.component_dim.take_along
- static take_parallel_to(B, A)
return the component of A parallel to B. Equivalent: (A dot Bhat) Bhat.
Note that B is the first argument.[Implementation currently just returns xarray_take_parallel_to(B,A)]
- 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.[Implementation currently just returns xarray_take_perp_to(B,A)]
- 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_chunk_solver_cls
alias of
TfbiChunkSolver
- property tfbi_cond_vars
list of vars which might be needed for TFBI solver, but aren’t always needed.
For now, this is just: [] if self.tfbi_elastic=True else [‘1+inelasticity’].
- 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: boolwhether to include ‘tfbi_all’, or only ‘tfbi_inputs’.With only ‘tfbi_inputs’, the theory is still solvable, but harder to inspect later.output_mask: boolwhether to store_mask in results, if self.masking (and self.mask is not None)additional kwargs passed to self(…)
- property tfbi_elastic
whether to assume elastic collisions in heating equation for TFBI theory.
This affects the delta_sn factor (see e.g. Dimant et al 2023, equation 1c).In general, delta_sn = (1+inelasticity) * 2 m_s / (m_s + m_n),where inelasticity=0 for elastic collisions.
- 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 1lower 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 kappaeionfrac: None or numberupper 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=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 1upper 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: boolwhether 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, …).NOTE: if self.chunks is nonempty,will automatically use TfbiChunkSolver instead,but requires dst to be provided as kwarg, to avoid crash!docs for TfbiSolver copied below for convenience:————————————————-high-level interface for solving TFBI theory across many physical parameters.Call TfbiSolver to solve TFBI.Example:import PlasmaCalcs as pccc = pc.PlasmaCalculator(…) # <– your PlasmaCalculator of choicesolver = pc.TfbiSolver(cc)solution = solver() # alias: solver.solve()solution is an xarray.Dataset with all relevant quantities (see TfbiLoader.get_tfbi_all),and ‘omega’ telling roots with largest imaginary part.If you need more precise control over the solving process, use the pattern:import tfbi_theory as ttimport PlasmaCalcs as pccc = … # any PlasmaCalculator object from PlasmaCalcs.ds0 = cc.tfbi_ds()kp = tt.kPickerLowres(ds0)dsk = kp.get_ds() # copy of ds0, but with ds[‘k’] = k from kPicker.drel = tt.TfbiDisprelC.from_ds(dsk)dsR = drel.solve() # copy of dsk, but with ds[‘omega’] = solution to TFBI theory!Notes:if cc has more than ~4 ions, you will want to drop some or group them somehow.e.g. for MhdMultifluidCalculator, before calling tfbi_ds():cc.use_mix_heavy_ions(0.3, m_mean_mode=’density’)You can also pick ions directly during cc.tfbi_ds().e.g. for Bifrost chromosphere analysis, where n[He_II] < 1e-6 * ne, I use:cc.tfbi_ds(ions=[i for i in cc.fluids if i.q==1 and i!=’He_II’])After finishing solving, you might want to save the result,e.g. dsR.pc.save(‘filename’) saves result to ‘filename.pcxarr’;can load it later via pc.xarray_load(‘filename.pcxarr’).If you are solving across “many” points (e.g., more than ~5000),you might want to use chunking instead. see TfbiChunkSolver;also note cc.tfbi_solver(…) automatically uses TfbiChunkSolverif appropriate, i.e. if cc.chunks is set (where cc is a TfbiLoader).TfbiSolver internally stores self.cc, ds0, kp, dsk, drel, and dsR,as defined by the pattern above.cc: PlasmaCalculatorPlasmaCalculator 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()ions are determined when called, not during __init__.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.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 (e.g. >1000) points.‘mid’ –> tfbi_theory.kPickerMidres. Recommended if solving across a few (e.g. 10 to 100) points.‘high’ –> tfbi_theory.kPickerHighres. Recommended if solving at only 1 point.mod, lmod, ang: UNSET or dictpassed directly to kPicker if provided. Can specify k values other than the defaults.see help(self.kPicker_cls) for more details.tfbi_all: boolwhether 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 classtfbi_theory class to use for solving TFBI theory.None –> use self.drel_cls default: tt.TfbiDisprelCstr –> use getattr(tt, drel_cls) to get the class.
- tfbi_solver_cls
alias of
TfbiSolver
- property tile_snaps
instructions for tiling results from snaps, concatenating along a maindim.
False –> no tiling.(dim, snaps iterable) –> tile snaps along dim, concatenating along dim.Exactly 1 snap indicator must be None, ‘here’, or ‘current’ to indicate “the current snap”.E.g., (‘x’, [5, ‘current’, ‘snap100’]) –> results get stacked along x, like this:[results from 5th snap, results from current snap, results from snap with name==’snap100’]Coordinates will be shifted by appropriate offsets, too,with coords in ‘current’ matching maindims coords for current snap.
- 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) if self.notes_dirname == self.dirname,else basename(self.notes_dirname) + basename(self.dirname),except skip basename(self.dirname) if ‘_sim’.Examples of default behavior:‘/path/to/dir0’ –> ‘dir0’.‘/path/to/dir1/_sim’ –> ‘dir1’.‘/path/to/dir1/_check0’ –> ‘dir1_check0’.
- title_with_slices(slices=UNSET, *, sep=', ', keep_None=False)
return self.title with slicestr appended (after sep), if slicestr is not empty.
see self.slicestr() for more details.slices: None, dict, or UNSETslices to use instead of self.slices, if provided (i.e. not UNSET).(original slices will be restored after this operation)
- 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 unique_notes_dirname
abspath to directory containing plots/notes for a DirectLoader,
probably not shared by DirectLoaders corresponding to any other data.(E.g. ifMight be the same directory as self.dirname, but doesn’t need to be;can explicitly set self.notes_dirname = value, if desired.If not set, use unique_notes_dirname = self.dirname,unless dirname ends with one of the self._INDICATES_UNIQUE_NOTES_DIRNAME options.E.g. dirname == ‘path/to/dir0’ –> unique_notes_dirname == ‘path/to/dir0’.E.g. dirname == ‘path/to/dir1/_sim’ –> unique_notes_dirname == ‘path/to/dir1’.E.g. dirname == ‘path/to/dir1/_check0’ –> unique_notes_dirname == ‘path/to/dir1/_check0’.See also: self.notes_dirname
- property units
the current unit system for self. E.g., ‘si’. (this is an alias to self.u.units)
- units_meta()
return dict(units=self.units). 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 stringsonly remove cached values where self.behavior matches cached behavior for these attrs.if empty, remove all cached values for var, regardless of associated behavior.missing_ok: boolwhether it is okay for there to be zero matching cached values for var.raise CacheNotApplicableError if missing_ok=False when there are no matching cached values.additional kwargs, if provided, go to self.using(**kw) during the operation.return list of CachedQuantity objects which were removed from self.setvars.
- unset_var_internal(var, behavior_attrs, forall=[], *, ukey=None, missing_ok=True)
unset var from self.setvars.
KNOWN_SETTERS functions may wish to use this method, to unset dependent values.E.g. if u depends on n, and n is changed, may wish to unset the value of u.behavior_attrs: list of stringsthe behavior attrs relevant to setting this var.forall: list of stringsif provided, tells which behavior attrs to ignore when unsetting the var.ukey: None or stringif provided, ignore ‘units’ behavior attr when unsetting the var(due to assuming that ukey was provided when setting the var,hence that the set var could be retrieved in any units system)missing_ok: boolwhether it is okay for there to be zero matching cached values for var.raise CacheNotApplicableError if missing_ok=False when there are no matching cached values.return list of CachedQuantity objects which were removed from self.setvars.
- property using
alias to using_attrs
- using_at_call_depth(depth, **attrs_and_values)
context manager for setting attrs_and_values but only while call_depth == depth.
E.g.:
with self.using_at_call_depth(3, verbose=3):self(‘sgyrof’)# while self.call_depth == 3 inside of this ‘with’ block, uses self.verbose=3.# but everywhere else, uses original value of verbose.# assuming originally verbose=False (or unset), this example will print:| | (call_depth=2) get var=’q’| | (call_depth=2) get var=’mod_B’| | (call_depth=2) get var=’m’# compare this to simply using self.verbose=3, which would print:| (call_depth=1) get var=’sgyrof’| | (call_depth=2) get var=’q’| | (call_depth=2) get var=’mod_B’| | | (call_depth=3) get var=’B_dot_B’| | | | (call_depth=4) get var=’B_xyz’| | | | | (call_depth=5) get var=’B’| | (call_depth=2) get var=’m’Equivalent to self.call_depth_manager.using_obj_attrs_at(depth, **attrs_and_values)
- using_at_next_call_depth(**attrs_and_values)
context manager for setting attrs_and_values but only while call_depth == self.call_depth + 1
Equivalent to self.using_at_call_depth(self.call_depth + 1, **attrs_and_values).
(Also equivalent to self.call_depth_manager.using_obj_attrs_at_next(**attrs_and_values).)
- using_attrs(attrs_as_dict={}, _unset_sentinel=ATTR_UNSET, **attrs_and_values)
returns context manager which sets attrs of obj upon entry; restores original values upon exit.
_unset_sentinel: any value, default ATTR_UNSETupon entry, delete any attrs with value _unset_sentinel (compared via ‘is’).E.g. using_attrs(obj, _unset_sentinel=None, x=None) –> del obj.x upon entry.
- 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 vdem_ignores_photosphere
Specifies how the photosphere is treated in VDEM calculations.
Options include:‘z=0’ –> account for photosphere by ignoring all values at z < 0.False –> do not worry about photosphere.
- property vdem_logT
(self.vdem_logT_min, self.rcoords_logT).
Can set both at once via self.vdem_logT = (desired_min, desired_coords)
- property vdem_logT_min
Minimum log10(temperature [K]) to include in VDEM calculations.
some VDEMs ignore emiss contributions from very cold regions (T < self.vdem_logT_min).Note: vdem_logT_min can never be more than minimum value of self.rcoords_logT.(attempting to set bad value will cause crash & helpful error message.)
- property vdem_loopdim
Tells which dimension to loop over during vdems.
Passed as “loop” kwarg to xarray_multiply_then_sum_along. Docs for that parameter copied below:None, str, or (str, int, mode).Indicates looping instructions (if any) to use during xarray_multiply_then_sum_along.None –> no looping; simply multiply all arrays, then sum along dim.Conceptually simplest. But, internally builds unnecessarily large array,which might be larger than DEFAULTS.RESULT_ARRAY_GBYTES_MAX and thus trigger MemorySizeError.str –> loop over each point along the indicated dimension.If loop != dim, sum at each point and then concatenate final result.If loop == dim, keep a running sum during the loop; no need to concatenate final result.‘int’ or ‘sum’ –> equivalent to using loop == dim.(str, integer, mode) –> (loop dimension, chunk size, chunk size mode)loop over the indicated dimension in chunks of the indicated size,instead of only one point at a time. This is usually the most efficient option. Mode can be:‘GB’ –> size of chunk arrays in GB (approximately)E.g., (‘logT’, 5, ‘GB’) picks chunk size for logT such that each chunk is 5 GB or less.‘size’ –> number of points in the dimension.E.g., (‘x’, 5, ‘size’) does first 5 points along x, then next 5, etc.‘n’ –> number of chunks (roughly)E.g., (‘x’, 5, ‘n’) does first 1/5 of n points, then next 1/5, etc.Not guaranteed to be exactly 5 chunks, due to rounding.
- property vdem_los
tells which line of sight to integrate along for vdem calculations.
if None, vdems will use self.los if provided, else self._DEFAULT_VDEM_LOS (default: ‘-component’).(see self.LOS_OPTIONS for more details about the available shorthand options.Another option is to use an xr.DataArray with ‘component’ dimension.)The default (‘-component’) means the opposite direction implied by self.component,e.g. if self.component==’z’, then vdem_los is ‘-z’ (corresponding to pathswhich start at top of box and proceed downwards along z).Use self.vdem_los_explicit to get the actual value that will be used(filling in default or value from self.los as appropriate).
- property vdem_los_explicit
self.vdem_los, but if None convert to the explicit vdem_los to use.
- property vdem_mode
Selects the velocity-differential emission measure (VDEM) calculation mode.
See self.VDEM_MODE_OPTIONS for options.
- vdem_pipeline(*, los_dim='z', iz0=50, tg_percent=0.1, dlogT=0.1, mintg_cut=4.6, maxtg_cut=7.7, tg_bins=60, ulos_bin=60, vel_percent=0.1, dvdop=10, minvel_cut=-3000, maxvel_cut=3000, emiss_norm=1e+27, modelname='', zarr_version=2, chunks=256, ncpu=12, dst='pc_vdem_pipeline', author)
Execute a standard VDEM (Velocity-Differential Emission Measure) analysis pipeline.
This pipeline performs a complete VDEM analysis including:
1. Automatic determination of temperature and velocity ranges from data histograms2. Computation of VDEM with configurable binning3. Generation of moment plots (intensity, mean velocity, width)4. Photosphere region analysis with separate plots5. Saving results to Zarr format with complete metadataThe pipeline automatically determines optimal temperature and velocity bins based onhistogram analysis, applies user-specified cutoffs, computes VDEM along the specifiedline-of-sight dimension, and generates diagnostic plots.Parameters———-los_dim : str, default=’z’Line-of-sight dimension for VDEM integration (‘x’, ‘y’, or ‘z’).iz0 : int, default=50Index along z-dimension marking the photosphere boundary. Used to defineintegration limits and photosphere cutoff analysis.tg_percent : float, default=0.1Percentage threshold for automatic temperature range determination.Histogram bins with density > tg_percent% of maximum are included.dlogT : float, default=0.1Temperature bin width in log10(T [K]) units.mintg_cut : float or None, default=4.6Minimum log10(temperature [K]) cutoff. Overrides automatic determinationif specified.maxtg_cut : float or None, default=7.7Maximum log10(temperature [K]) cutoff. Overrides automatic determinationif specified.tg_bins : int, default=60Number of bins for temperature histogram analysis.ulos_bin : int, default=60Number of bins for velocity histogram analysis.vel_percent : float, default=0.1Percentage threshold for automatic velocity range determination.Histogram bins with density > vel_percent% of maximum are included.dvdop : float, default=10Velocity bin width in km/s.minvel_cut : float or None, default=-3000Minimum velocity cutoff in km/s. Overrides automatic determination if specified.maxvel_cut : float or None, default=3000Maximum velocity cutoff in km/s. Overrides automatic determination if specified.emiss_norm : float, default=1e27Emission measure normalization factor.modelname : str, default=’’Model identifier string used in output filenames.zarr_version : int, default=2Zarr format version for output files (2 or 3).chunks : int, default=256Chunk size for parallel computation along spatial dimensions.ncpu : int, default=12Number of CPU cores to use for parallel computation.dst : str, default=’pc_vdem_pipeline’Destination directory for output files.author : str, requiredAuthor name/identifier for output filenames and metadata.Returns——-vdem0 : xarray.DatasetProcessed VDEM dataset with coordinates and attributes set for the full domain.Contains ‘vdem’ data variable with dimensions (logT, vdop, x, y).Notes—–The pipeline generates the following outputs:- Temperature and velocity histogram plot:‘T_ulos_hist_{code}_{modelname}_{author}_{date}_{snap}.png’- VDEM moments plot (full domain):‘vdem_moment_{code}_{modelname}_{author}_{date}_{snap}.png’- VDEM moments plot (photosphere):‘vdem_moment_ph_{code}_{modelname}_{author}_{date}_{snap}.png’- VDEM Zarr dataset:‘vdem_{code}_{modelname}_los{los_dim}_{author}_{date}_{snap}.zarr’The pipeline automatically:- Sets units to CGS- Determines integration slice from iz0 to top of domain- Computes histograms to find optimal binning- Applies both automatic and manual cutoffs for T and velocity ranges- Computes VDEM with multiprocessing support- Generates moment plots with logarithmic scaling for intensity- Performs separate photosphere analysis (iz0 to iz0+5)- Adds complete history and metadata to outputExamples——–>>> # Standard VDEM pipeline with default settings>>> result = calc.vdem_pipeline(author=’scientist_name’)>>> # Custom temperature and velocity ranges>>> result = calc.vdem_pipeline(… mintg_cut=5.0,… maxtg_cut=7.0,… minvel_cut=-1000,… maxvel_cut=1000,… author=’scientist_name’… )>>> # High-resolution analysis with more CPU cores>>> result = calc.vdem_pipeline(… dlogT=0.05,… dvdop=5,… chunks=128,… ncpu=24,… author=’scientist_name’… )See Also——–limb_vdem_pipeline : Pipeline for limb observations with ray drapingget_vdem : Core VDEM computation method
- property vdem_varies_logD
tells whether vdems should also vary across logD (electron number density) dimension,
in addition to temperature (logT) and velocity (vdop) dimensions.Currently, equivalent to: (self.rcoords_logD_cgs is not None).(Eventually, might allow to edit this property directly, instead.)
- property w_instrumental_si
instrumental broadening for thermal velocity, in SI units.
vtherm_instr = sqrt((kB T / m) + self.w_instrumental_si^2)
- 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
- zeros_like_maindims(**kw_zeros_like)
return array of all 0s like maindims var results (use ints to save space).
Most users will find it sufficient to just load self.maindims_coords(),but zeros_like_maindims() is provided for more advanced abstractions,which rely on the fully-formed array, without caring about the actual values.(see, e.g., LoiLoader’s get_dloi().)Just like self.get_maindims_coords(), the result here depends on self.slices.kwargs go to np.zeros(). Default dtype is int, to save space.