PlasmaCalcs.tools.xarray_tools.xarray_accessors.pcAccessor
- class PlasmaCalcs.tools.xarray_tools.xarray_accessors.pcAccessor(xarray_obj)
Bases:
XarrayAccessoraccess attributes of DataArrays or Datasets e.g. xr.DataArray.pc.differentiate(…).This is the base class inherited by pcArrayAccessor and pcDatasetAccessor.When deciding where to attach a method, think:pcAccessor.register if it applies to DataArrays and Datasets the same way,pcAccessor.register(totype=’array’) if it applies to DataArrays only,pcAccessor.register(totype=’dataset’) if it applies to Datasets only.Example:@pcAccessor.registerdef my_method(xarray_object, arg1):print(arg1)print(xarray_obj)# –> can later do:xr.DataArray(data).pc.my_method(7) # prints 7 then prints DataArray(data).@pcAccessor.register(name=’my_method2’, totype=’array’)def xarray_my_method2(xarray_object):print(xarray_object * 10)# –> can later do:xr.DataArray(data).pc.my_method2() # prints DataArray(data).- __init__(xarray_obj)
Methods
__init__(xarray_obj)register(f_or_name, *[, aliases, totype, _name])register_attr(name, value, *[, totype])Attributes
access_typeaccess_type_to_clsaccessor_namealias_registryattrs_registryregistered_aliasesregistered_attrsregistered_methodsregistry- property agg
- alias to aggregate
- aggregate
- caller of function xarray_aggregate in module PlasmaCalcs.tools.xarray_tools.xarray_agg_statsxarray_aggregate(array, f, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw_agg_f)returns array aggregated along dim using f.
- f: callable or str
- dim: None, str, or iterable of strs
- apply operation along these dimensions
- keep: None, str, or iterable of strs
- apply operation along all except for these dimensions.(can provide keep or dim, but not both.)
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.
additional kwargs are passed to f.
- property ang
- alias to angle_xy
- property ang2hat
- alias to angle_xy_to_hat
- angle_xy
- caller of function angle_xy in module PlasmaCalcs.quantities.patterns.vector_arithmeticangle_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.)
- angle_xy_to_hat
- caller of function angle_xy_to_hat in module PlasmaCalcs.quantities.patterns.vector_arithmeticangle_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.
- property angxy
- alias to angle_xy
- property angxy2hat
- alias to angle_xy_to_hat
- as_array
- caller of function xarray_as_array in module PlasmaCalcs.tools.xarray_tools.xarray_miscxarray_as_array(array)return array if DataArray, else array[var] if array is Dataset with one var.if array is Dataset with multiple vars, crash with InputError.
- assign
- caller of function xarray_assign in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsxarray_assign(array, coords=None, attrs=None, *, name=UNSET, overwrite=None, expand_if_iterable=False)array.assign_coords(coords).assign_attrs(attrs).rename(name)
- coords: None or dict of {dim: coord}
- each coord must be “non-iterable”, as per is_iterable_dim(),unless expand_if_iterable=True.
- attrs: None or dict
- assign these attrs. dict of arbitrary values.
- name: UNSET, None, or str
- assign this name to the result, if provided.
- overwrite: None or bool
- whether to overwrite an existing value for coord in array.(note - array will never be altered here; only the result might be altered.)If any coord already in array.coords, behavior depends on overwrite:None –> crash with DimensionKeyError.True –> overwrite the coord using the new value.False –> return array, unchanged.
- expand_if_iterable: bool
- whether to expand_dims for any iterable coords,e.g. array.expand_dims(coords) for the relevant coords.
- at_max_of
- caller of function xarray_at_max_of in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_at_max_of(array, of, dim=None, *, promote_dims_if_needed=True)return array values at locations of maximum
of. Roughly: array.isel(of.argmax([dim])).But, here is nicer, in a few ways:(1) here doesn’t require array to have all dims in dim.E.g., if array has dims ‘x’, ‘kmod’, andofhas dims ‘kmod’, ‘kang’,and dim=[‘kmod’, ‘kang’], it will be handled in the intuitive way. Roughly:amax = of.argmax([‘kmod’, ‘kang’])result = array.isel(kmod=amax[‘kmod’])(2) here allows All-NaN slice inof.all-nan slices inofwill be filled with nan values in result.E.g., if dims=[‘d0’, ‘d1’],ofhas dims [‘d0’, ‘d1’, ‘nmul’, ‘fluid’],and of.isnull().all([‘d0’, ‘d1’]) when nmul index == 4 or 5, and fluid index == 2,then result.isel(nmul=[4,5], fluid=2) will be filled with nan values.- array: xarray.DataArray or xarray.Dataset
- array to get result values from.
- of: xarray.DataArray
- array to find maximum values in.
- dim: None, str, or list of str
- dim(s) along which to find the maximum values of
of.Takes the “simultaneous” maximum along all these dims, as per argmax(dims)None –> use of.dims.(if dim is a list with len==0, return array, unchanged.) - promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- at_min_of
- caller of function xarray_at_min_of in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_at_min_of(array, of, dim=None, *, promote_dims_if_needed=True)return array values at locations of minimum
of. Roughly: array.isel(of.argmin([dim])).But, here is nicer, in a few ways:(1) here doesn’t require array to have all dims in dim.E.g., if array has dims ‘x’, ‘kmod’, andofhas dims ‘kmod’, ‘kang’,and dim=[‘kmod’, ‘kang’], it will be handled in the intuitive way. Roughly:amin = of.argmin([‘kmod’, ‘kang’])result = array.isel(kmod=amin[‘kmod’])(2) here allows All-NaN slice inof.all-nan slices inofwill be filled with nan values in result.E.g., if dims=[‘d0’, ‘d1’],ofhas dims [‘d0’, ‘d1’, ‘nmul’, ‘fluid’],and of.isnull().all([‘d0’, ‘d1’]) when nmul index == 4 or 5, and fluid index == 2,then result.isel(nmul=[4,5], fluid=2) will be filled with nan values.- array: xarray.DataArray or xarray.Dataset
- array to get result values from.
- of: xarray.DataArray
- array to find minimum values in.
- dim: None, str, or list of str
- dim(s) along which to find the minimum values of
of.Takes the “simultaneous” minimum along all these dims, as per argmin(dims)None –> use of.dims.(if dim is a list with len==0, return array, unchanged.) - promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- property blur
- alias to gaussian_filter
- coarsened
- caller of function xarray_coarsened in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsxarray_coarsened(array, dim, window_len, dim_coarse=’window’, dim_fine=None, *, assign_coarse_coords=False, boundary=UNSET, side=UNSET, stride=UNSET, fill_value=UNSET, keep_attrs=UNSET)construct a coarsened version of array, where dim is coarsened by window_len,and becomes two dims: dim_coarse and dim_fine.Original dim coords will be associated with dim_coarse and dim_fine in the new array.
- dim: str
- dimension to coarsen.if a non-dimension coordinate, will attempt to promote it to a dimension (e.g. via swap_dims).
- window_len: int
- length of the window to coarsen over.
- dim_coarse: str, default ‘window’
- name of coarse dimension; the i’th value here corresponds to the i’th window.
- dim_fine: None or str
- name of fine dimension; the j’th value here corresponds to the j’th element within a window.if None, use ‘_’+dim, e.g. dim=’t’ –> dim_fine=’_t’.
- assign_coarse_coords: bool or coords
- coords to assign along the dim_coarse dimension.True –> use np.arange.False –> don’t assign coords.
- boundary, side: UNSET or value
- if provided (not UNSET), pass this value to coarsen().boundary should be ‘exact’, ‘trim’, or ‘pad’.side should be ‘left’ or ‘right’.
- stride, fill_value, keep_attrs: UNSET or value
- if provided (not UNSET), pass this value to construct().
docs for coarsen and construct are copied below, for convenience:xarray.DataArray.coarsen————————Coarsen object for DataArrays.Parameters———-- dimmapping of hashable to int, optional
- Mapping from the dimension name to the window size.
- boundary{“exact”, “trim”, “pad”}, default: “exact”
- If ‘exact’, a ValueError will be raised if dimension size is not amultiple of the window size. If ‘trim’, the excess entries aredropped. If ‘pad’, NA will be padded.
side : {“left”, “right”} or mapping of str to {“left”, “right”}, default: “left” coord_func : str or mapping of hashable to str, default: “mean”
function (name) that is applied to the coordinates,or a mapping from coordinate name to function (name).Returns——-core.rolling.DataArrayCoarsenxr.core.rolling.DataArrayRolling.construct——————————————Convert this Coarsen object to a DataArray or Dataset,where the coarsening dimension is split or reshaped to twonew dimensions.Parameters———-- window_dim: mapping
- A mapping from existing dimension name to new dimension names.The size of the second dimension will be the length of thecoarsening window.
- keep_attrs: bool, optional
- Preserve attributes if True
**window_dim_kwargs : {dim: new_name, …}The keyword arguments form of`window_dim`.Returns——-Dataset or DataArray with reshaped dimensions
- coarsened_polyfit
- caller of function xarray_coarsened_polyfit in module PlasmaCalcs.tools.xarray_tools.xarray_scixarray_coarsened_polyfit(array, coord, degree, window_len, *, dim_coarse=’window’, keep_coord=’middle’, assign_coarse_coords=True, boundary=UNSET, side=UNSET, stride=UNSET, fill_value=UNSET, keep_attrs=UNSET, **kw_polyfit)returns result of coarsening array, then polyfitting along the fine dimension, in each window.E.g., make windows of length 10 along ‘t’, then polyfit each window along ‘t’,then concat the results from each window, along dim_coarse (default: ‘window’).
- coord: str
- coordinate to polyfit along.
- degree: int
- degree of polynomial to fit.
- window_len: int or None
- length of window to coarsen over.None –> polyfit without coarsening; equivalent to window_len = len(array.coords[coord])
- dim_coarse: str, default ‘window’
- name of coarse dimension; the i’th value here corresponds to the i’th window.
- keep_coord: False or str in (‘left’, ‘right’, ‘middle’)
- along the dim_coarse dimension, also provide some of the original coord values.‘left’ –> provide the left-most value in each window.‘middle’ –> provide the middle value in each window.‘right’ –> provide the right-most value in each window.False –> don’t provide any of the original coord values.if not False, result will swap dims such that coord is a dimension instead of dim_coarse.
- assign_coarse_coords: bool or coords
- coords to assign along the dim_coarse dimension.True –> use np.arange.False –> don’t assign coords.
- boundary, side: UNSET or value
- if provided (not UNSET), pass this value to coarsen().
- stride, fill_value, keep_attrs: UNSET or value
- if provided (not UNSET), pass this value to construct().
additional **kw are passed to polyfit.Docs for xr.DataArray.polyfit copied below:——————————————-Least squares polynomial fit.This replicates the behaviour ofnumpy.polyfitbut differs by skippinginvalid values whenskipna = True.Parameters———-- dimHashable
- Coordinate along which to fit the polynomials.
- degint
- Degree of the fitting polynomial.
- skipnabool or None, optional
- If True, removes all invalid values before fitting each 1D slices of the array.Default is True if data is stored in a dask.array or if there is anyinvalid values, False otherwise.
- rcondfloat or None, optional
- Relative condition number to the fit.
- wHashable, array-like or None, optional
- Weights to apply to the y-coordinate of the sample points.Can be an array-like object or the name of a coordinate in the dataset.
- fullbool, default: False
- Whether to return the residuals, matrix rank and singular values in additionto the coefficients.
- covbool or “unscaled”, default: False
- Whether to return to the covariance matrix in addition to the coefficients.The matrix is not scaled if
cov='unscaled'.
Returns——-- polyfit_resultsDataset
- A single dataset which contains:polyfit_coefficientsThe coefficients of the best fit.polyfit_residualsThe residuals of the least-square computation (only included if
full=True).When the matrix rank is deficient, np.nan is returned.[dim]_matrix_rankThe effective rank of the scaled Vandermonde coefficient matrix (only included iffull=True)[dim]_singular_valueThe singular values of the scaled Vandermonde coefficient matrix (only included iffull=True)polyfit_covarianceThe covariance matrix of the polynomial coefficient estimates (only included iffull=Falseandcov=True)
See Also——–numpy.polyfitnumpy.polyvalxarray.polyvalDataArray.curvefit
- convert_types
- caller of function xarray_convert_types in module PlasmaCalcs.tools.xarray_tools.xarray_miscxarray_convert_types(array, oldtype_to_newtype)return copy of array or dataset, using var.astype(newtype) for any var with oldtype,for oldtype, newtype in oldtype_to_newtype.items().
- copy_kw
- caller of function xarray_copy_kw in module PlasmaCalcs.tools.xarray_tools.xarray_miscxarray_copy_kw(array, dims=None, *, name=None, array_to_dataset=False)return dict of info suitable for creating a similar array or dataset.result includes dims, coords, and attrs (unchanged, copied).
- dims: None, str, or iterable of str
- if provided, only include these dims (and related coords) in the result.Useful if only interested in some of the dims,e.g. if array has x,y,z,t dims but only want to mimic dims and coords from x,t.
- name: None, bool, or str
- whether to also include name in resultNone –> True if array has name, else FalseTrue –> name = array.name.str –> name = name.
- array_to_dataset: bool
- if True, result will be suitable for creating a Dataset based on the input DataArray.(Equivalent to using dims=[], name=False, and deleting ‘dims’ key from result.)
- property cross
- alias to cross_product
- cross_component
- caller of function cross_component in module PlasmaCalcs.quantities.patterns.vector_arithmeticcross_component(A, B, x, *, yz=None, missing_ok=False)return x component of A cross B, given A and B which have values for y and z ‘component’.
- x: int, str, or Component
- tells component (of result) to get. if int or str, use XYZ.get(x)
- A, B: xarray.DataArray
- vectors to take cross product of.must include ‘component’ dimension including coordinates y and z.
- yz: None or iterable of two (int, str, or Component) objects
- the other two components; (x,y,z) should form a right-handed coordinate system.if not provided, infer from x.
- missing_ok: bool, default False
- whether it is okay for ‘component’ dimension to be missing y or z components, of A or B.if True, treat any missing components as 0.
- cross_product
- caller of function cross_product in module PlasmaCalcs.quantities.patterns.vector_arithmeticcross_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.
- curve_eval
- caller of function xarray_curve_eval in module PlasmaCalcs.tools.xarray_tools.xarray_scixarray_curve_eval(params, f, xdata)evaluate a curve fit result (params) for this function at these xdata.[EFF] note: well-vectorized f could equivalently do:f(xdata, *params.transpose(‘param’, …))and that would probably be much faster, if it is an available option.
- params: xarray.DataArray or xarray.Dataset
- curve_fit result, or result[‘params’]. Must have ‘param’ dimension.if Dataset, will internally use params[‘params’].
- f: callable like f(x, param1, param2, …)
- function which was fit / to be evaluated.
- xdata: 1D xarray.DataArray
- x values at which to evaluate the fit.
- differentiate
- caller of function xarray_differentiate in module PlasmaCalcs.tools.xarray_tools.xarray_coordsdifferentiate array along coord, treating array like it is an xarray.DataArray.more lenient than xarray.DataArray.differentiate;returns 0 if can’t differentiate along coord (due to coord having size 1 or not existing.)
- keep_attrs: bool
- whether to copy attrs from array into the result. Default True.
requires that array.coords and array.differentiate exist, otherwise raises AttributeError.
- dims_coords
- caller of function xarray_dims_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_dims_coords(array, *, include_dims_as_coords=True)returns dict of {dim name: [coord name for all coords with this dim]}.result[()] will be list of all scalar coords (ndim=0 so no associated dims).coords associated with multiple dims will appear in multiple places in the result.
- include_dims_as_coords: bool
- whether to include dims as coord names in the result.Dims with no same-named coord will appear in appropriate place in result.
- property dir
- alias to unit_vector
- property direction
- alias to unit_vector
- property dirxy
- alias to angle_xy
- property dirxy2hat
- alias to angle_xy_to_hat
- property dot
- alias to dot_product
- dot_product
- caller of function dot_product in module PlasmaCalcs.quantities.patterns.vector_arithmeticdot_product(A, B)return dot product of vectors A and B, assuming vector components along the dimension ‘component’.
- ensure_dims
- caller of function xarray_ensure_dims in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsxarray_ensure_dims(array, coords, *, promote_dims_if_needed=True, missing_dims=’raise’, assert_1d=False, return_existing_dims=False)return array but ensure these coords are dimensions.
- coords: str or iterable of strings
- coords to ensure are dimensions.
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.0D coord –> array.expand_dims(coord)1D coord –> array.swap_dims(dict(dim=coord)) for associated dim2D+ coord –> crash with DimensionalityError.
- 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.
- assert_1d: bool, default False
- whether to assert that each of these coords is 1D (after promoting if needed).
- return_existing_dims: bool, default False
- True –> returns [array, set of dims (from input coords) which actually exist]probably only useful if missing_dims != ‘raise’.
- faceplot
- caller of class Faceplot in module PlasmaCalcs.plotting.faceplotclass Faceplot(PlasmaCalcs.plotting.movies.MoviePlotNode)| Faceplot(data, *, coords=None, t=None, ax=None, init_plot=True, add_colorbar=UNSET, add_labels=True, **kw_super)|| MoviePlotNode of a faceplot.| stores a FaceplotPlotElement, and updates it for each frame of the movie.| “faceplot” refers to 3 plots on 3 faces of a box in 3D.|| Troubleshooting colors? Try providing vmin, vmax, & levels, explicitly!|| data: dictlike with keys ‘x_y’, ‘x_z’, ‘y_z’, or an xarray.DataArray.| 2D arrays of data to plot on the faces. E.g. ‘x_z’ data goes on the x-z face.| xarray.DataArray –> infer faces via isel z=0, y=0, and x=0, respectively.| coords: None or dictlike with keys ‘x’, ‘y’, ‘z’| 1D coordinate arrays along each dimension.| If None, infer from data[‘x’], data[‘y’], data[‘z’].| t: None, str, or int| the array dimension which frames will index. E.g. ‘time’.| None –> infer it via infer_movie_dim(data[‘x_y’].dims, t).| str –> name of time dimension. And, data should be xarray object(s).| int –> index of time dimension. And, data should be dict of numpy arrays.|| init_plot: bool (default: True)| whether to call self.init_plot() immediately, during __init__.| (as a PlotSetting: tells the value of init_plot passed during __init__.)| False –> still must call self.init_plot() before using self(…) or self.updater(…)| (end-user will probably never use init_plot=False; it’s mostly for internal code.)| (might use False if creating MovieImage before defining the associated Axes.)|| add_colorbar: UNSET or bool (default: UNSET)| if provided, default for add_colorbar when making xarray plots.| add_labels: bool (default: True)| whether to add labels to xarray plots.|| title: UNSET, None, or str (default: UNSET)| title for a single axes/subplot. For xarrays, will title.format(**xarray_nondim_coords(array)).| (Note: plot_settings[‘title’] should always be the ‘base’ title, before title.format(…))| UNSET –> use array_at_current_frame._title_for_slice().| None –> do not add a title.| title_font: UNSET, None, or str (default: UNSET)| font for title, e.g. ‘serif’, ‘sans-serif’, or ‘monospace’| UNSET –> use DEFAULTS.PLOT.MOVIE_TITLE_FONT (default: monospace).| None –> use matplotlib default.| title_y: UNSET, None, or number (default: UNSET)| y position for title, in axes coordinates.| title_kw: UNSET, or dict (default: UNSET)| any additional kwargs for plt.title.||| To view or adjust plot settings in self, see self.plot_settings, or help(self.plot_settings).|| Method resolution order:| Faceplot| PlasmaCalcs.plotting.movies.MoviePlotNode| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| PlasmaCalcs.tools.trees.Tree| builtins.object|| Methods defined here:|| __init__(self, data, *, coords=None, t=None, ax=None, init_plot=True, add_colorbar=UNSET, add_labels=True, **kw_super)|| get_data_at_frame(self, frame)| returns dict-like of data at this frame, ready for plotting.|| get_nframes_here(self)| return the number of frames that could be in the movie, based on this node.|| init_plot(self)| plot for the first time. Save the FaceplotPlotElement at self.obj.|| plot_title(self)| adds title (as a MovieTextNode) on self.ax.| raise PlottingAmbiguityError if title already plotted| (this prevents having multiple title nodes).|| ———————————————————————-| Data descriptors defined here:|| ax| mpl_toolkits.mplot3d.axes3d.Axes3D where this Faceplot is plotted.|| fig| figure where this Faceplot is plotted.|| ———————————————————————-| Data and other attributes defined here:|| element_cls = <class ‘PlasmaCalcs.plotting.faceplot.FaceplotPlotElemen…| 3 plots on 3 faces of a box in 3D.| Faceplot.__init__ will make these plots.|| Troubleshooting colors? Try providing vmin, vmax, & levels, explicitly!|| coords: dictlike with keys ‘x’, ‘y’, ‘z’| 1D coordinate arrays along each dimension.| data: dictlike with keys ‘x_y’, ‘x_z’, ‘y_z’| 2D arrays of data to plot on the faces.| E.g. ‘x_z’ data will go on the x-z face.| ax: None or axes with 3d projection.| e.g. fig.add_subplot(1,1,1, projection=’3d’)| if None, use plt.gca() if current axes exist, else make new axes.|| Additional kwargs control settings for the plot:| faceplot_view_angle: UNSET, None, or 3-tuple of numbers (default: UNSET)| viewing angle for 3D faceplots, as (elevation, azimuth, roll).| UNSET –> use DEFAULTS.PLOT.FACEPLOT_VIEW_ANGLE (default: (-160, 30, 0)).| None –> use matplotlib defaults.| faceplot_edge_kwargs: UNSET, None, or dict (default: UNSET)| kwargs for edge lines in 3D faceplots.| UNSET –> use DEFAULTS.PLOT.FACEPLOT_EDGE_KWARGS (default: {‘color’: ‘0.4’, ‘linewidth’: 1, ‘zorder’: 1000.0}).| None –> don’t plot edge lines.| empty dict –> use matplotlib defaults.| faceplot_axes_zoom: UNSET or number>0 (default: UNSET)| zoom for faceplot axis. matplotlib default is zoom=1.| UNSET –> use DEFAULTS.PLOT.FACEPLOT_AXES_ZOOM (default: 1.0).| aspect3d: UNSET, None, str, 3-tuple of numbers, or 4-tuple of numbers (default: UNSET)| aspect ratio for 3D plots.| UNSET –> use DEFAULTS.PLOT.ASPECT3D (default: equal).| str –> ‘auto’ or ‘equal’| tuple of 3 numbers –> (x aspect, y aspect, z aspect)| tuple of 4 numbers –> (1, x multiplier, y multiplier, z multiplier);| multiplier multiplies aspect determined by data lengths.|| any of these kwargs for ax.contourf:| ‘vmin’, ‘vmax’, ‘levels’, ‘cmap’,|| any of these kwargs for ax.set:| ‘xlabel’, ‘ylabel’, ‘zlabel’, ‘xlim’, ‘ylim’, ‘zlim’,| ‘xticks’, ‘yticks’, ‘zticks’, ‘xticklabels’, ‘yticklabels’, ‘zticklabels’| Note the defaults for ‘xlabel’, ‘ylabel’, ‘zlabel’ will be ‘x’, ‘y’, ‘z’.|| add_colorbar: bool| whether to self.colorbar() during __init__.| colorbar_kw: unset or dict (default: UNSET)| any additional kwargs for plt.colorbar.|| These attrs of self will be created/updated during init (here, face=’x_y’, ‘x_z’, or ‘y_z’):| meshgrids: {face: {x: 2d array of x values at face} for x in face}| coord_lims: {x: [min, max] for x in ‘x’, ‘y’, ‘z’}| data_lims: {‘all’: [min, max], **{face: [min, max]} }| ax: the axes object to plot on; create if needed.| faces: {face: the mpl_toolkits.mplot3d.art3d.QuadContourSet3D plotted on this face}| edges: {x: the mpl_toolkits.mplot3d.art3d.Line3D plotted at x=0. x=’x’, ‘y’ or ‘z’}||| To view or adjust plot settings in self, see self.plot_settings, or help(self.plot_settings).||| ———————————————————————-| Methods inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| __call__(self, frame)| update the plot for the given frame. return iterable of all updated artists.| Defining __call__ in this way means self is compatible for direct use by FuncAnimation.|| returns FuncAnimation instance using self as func.| Use kwarg defaults from self.plot_settings, for any kwargs not provided here.|| fps: UNSET, None, or number (default: UNSET)| frames per second.| UNSET –> use DEFAULTS.PLOT.FPS (default: 30).| (Or use value from self.plot_settings, if provided.)| None –> use matplotlib defaults.| blit: UNSET, None, or bool (default: UNSET)| whether to use blitting.| UNSET –> use DEFAULTS.PLOT.BLIT (default: True).| (Or use value from self.plot_settings, if provided.)| if None, use matplotlib defaults.| frames: UNSET, None, int, iterable, or slice (default: UNSET)| passed to FuncAnimation. Tells number of frames or which frames to plot.| If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).| if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.| plt_close: bool| whether to plt.close() before returning the result.| This is useful in Jupyter, where commonly one cell might make a plot,| then call get_animator() to display movie in-line, but not plt.close().| In that case, plt_close=False would display animation & plot|| [TODO] use init_func kwarg to avoid calling self twice for frame 0?|| get_nframes(self)| return max of get_nframes_here() for self & all descendants of self.| If any node throws PlottingNframesUnknownError, pretend they said nframes=0.| If all nodes throw PlottingNframesUnknownError, raise the one from self.|| init_plots(self, *, plotted_ok=True)| init_plot for self & all descendants with non-None obj.| plotted_ok: bool| True –> skip node if node.plotted.| False –> call init_plot on all nodes with non-None obj.|| save the movie to filename.| RECOMMENDED:| first, self.save(…, frames=N), with small N (e.g. N=5), to test movie formatting.| Troubleshooting: if movie getting cut off,| try plt.subplots_adjust(bottom=0.2, left=0.2, right=0.8, top=0.8),| or even more extreme values if necessary. (0 is bottom/left edge; 1 is top/right edge.)|| frames: UNSET, None, int, iterable, or slice (default: UNSET)| passed to FuncAnimation. Tells number of frames or which frames to plot.| If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).| if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.| fps: UNSET, None, or number (default: UNSET)| frames per second.| UNSET –> use DEFAULTS.PLOT.FPS (default: 30).| (Or use value from self.plot_settings, if provided.)| None –> use matplotlib defaults.| blit: UNSET, None, or bool (default: UNSET)| whether to use blitting.| UNSET –> use DEFAULTS.PLOT.BLIT (default: True).| (Or use value from self.plot_settings, if provided.)| if None, use matplotlib defaults.|| additional kwargs passed to FuncAnimation() or FuncAnimation.save().| returns abspath of the saved movie.|| update_to_frame(self, frame)| update the plot for the given frame. set self.frame=frame.| also calls update_to_frame for all children.| return iterable of all updated artists.|| ———————————————————————-| Class methods inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| help() from builtins.type| prints a helpful message with examples for how to use this cls|| ———————————————————————-| Readonly properties inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| plotted| whether this node’s element has actually been plotted yet.| False before init_plot; True after. Always None if self.obj is None.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| ani| alias to get_animator|| frame| the currently-plotted frame|| frames| the frames that could be in the movie.| if set to None, will use self.get_nframes() instead.| if set to a slice, will use range(self.get_nframes())[frames] instead.|| plotted_data| the currently plotted data.|| ———————————————————————-| Class methods inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| appends note about using self.plot_settings, to cls.__doc__.| if “PlotSettings” or “plot_settings” appears in cls.__doc__, do NOT append this note;| assuming instead that this means the doc already mentions how to use plot_settings.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| __dict__| dictionary for instance variables (if defined)|| __weakref__| list of weak references to the object (if defined)|| ———————————————————————-| Methods inherited from PlasmaCalcs.tools.trees.Tree:|| __getitem__(self, i)| returns self.children[i]. If i is a tuple, index repeatedly, e.g. self[i[0]][i[1]][i[2]]…|| __iter__(self)| iterates over self.children.|| __repr__(self)| Return repr(self).|| add_child(self, child)| adds this child (a Tree) to self.children. Also, child.set_parent(self).| returns the added child.|| display(self, show_depth=None, max_depth=None, *, shorthand=None)| display self in html. Includes self.html() and DEFAULTS.TREE_CSS.| show_depth: None or int| max number of layers of tree to show by default (i.e. “not hidden” by default)| None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH| max_depth: None or int| max number of layers of tree to render (even if all layers are “not hidden”).| Anything deeper will not be converted to html string.| None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH| shorthand: None or bool| whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.| True –> use shorthand; replace that^ with: “((N, N, N)) …”| None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND|| enumerate_flat(self, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order,| yielding (index, node) pairs, such that self[index] == node.| Note that index will be a tuple with length == node.depth.| if include_self, yield self first, as: ((), self)).|| flat(self, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order.| if include_self, yield self first.|| flat_branches_until(self, branches_until, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order,| but stop looking at descendants on a branch as soon as branches_until(node).| E.g. self.flat_branches_until(lambda node: node.obj==7) will be similar to flat,| but won’t go to any descendants for any node with obj==7.|| if include self, yield self first, and check branches_until(self) before continuing.| otherwise, never check branches_until(self).|| html(self, show_depth=None, max_depth=None, *, shorthand=None)| returns html for displaying self and all of self’s children.| show_depth: None or int| max number of layers of tree to show by default (i.e. “not hidden” by default)| None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH| max_depth: None or int| max number of layers of tree to render (even if all layers are “not hidden”).| Anything deeper will not be converted to html string.| None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH| shorthand: None or bool| whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.| True –> use shorthand; replace that^ with: “((N, N, N)) …”| None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND|| make_child(self, obj)| makes a child of self, with obj as its stored object, and returns the child.|| make_children(self, objs)| make_child(obj) for obj in objs; returns the list of newly made children.|| set_parent(self, parent, *, _internal=False)| sets self.parent = parent. Also, parent.add_child(self), unless _internal=True.| Users should use self.parent = parent instead of calling set_parent directly.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.tools.trees.Tree:|| depth| number of layers above self. (parent, parent’s parents, etc.)| depth = 0 for the node with parent = None.|| height| number of layers below self. (children, children’s children, etc.)| height = 0 for a node with no children.|| parent| parent node of self. None if self is root.| When set to a value, calls self.set_parent(value),| which also updates tracking info appropriately, and updates parent’s children.|| parent_ref| stores parent value, but internally uses weakref to avoid circular references.| Users should always use self.parent instead.|| size| number of nodes in this tree. (here and below)| size = 1 for a node with no children.|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.tools.trees.Tree:|| DEFAULT_TREE_SHORTHAND = None|| DEFAULT_TREE_SHOW_DEPTH = None|| DEFAULT_TREE_SHOW_MAX_DEPTH = None
- fill_coords
- caller of function xarray_fill_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_fill_coords(array, dim=None, *, need=None)return copy of array with coords filled for indicated dims.(if all indicated dims have coords already, return original array, not a copy.)E.g. array with dim_1 length 50 but no coords–> result is just like array but has dim_1 coords = np.arange(50)
- dim: None, str, or iterable of strs
- dims for which to consider filling coords. None –> array.dims.
- need: None, str, or iterable of str or None
- coords which the result must contain.if any of these look like ‘{coord}_index’ or ‘log_{coord}’,create them via xarray_index_coords or xarray_log_coords.
- from_broadcastable
- caller of function xarray_from_broadcastable in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsxarray_from_broadcastable(array, broadcastable, *, dims=None, squeeze=True)return xarray from broadcastable values, using dims/coords/attrs from input.
- array: xarray.DataArray or xarray.Dataset
- read relevant dims, coords, and attrs from this array; copy to result.
- broadcastable: array (possibly numpy array) or dict of arrays
- result’s data comes from this array(s).single array –> result.data = array.dict of arrays –> result.data = array[v] for v in array. # [TODO] not yet implemented.
- dims: None or list of str
- list of dim names for broadcastable’s dims. len(dims) == broadcastable.ndim.None –> use array.dims.
- squeeze: bool
- whether to squeeze away dims with size 1 in broadcastable.True –> result.dims will only include dims with size > 1 in broadcastable.
- gaussian_filter
- caller of function xarray_gaussian_filter in module PlasmaCalcs.tools.xarray_tools.xarray_scixarray_gaussian_filter(array, dim=None, sigma=None, *, promote_dims_if_needed=True, missing_dims=’raise’, **kw_scipy_gaussian_filter)returns array after applying scipy.ndimage.gaussian_filter to it.
- array: xarray.DataArray or Dataset
- filters this array, or each data_var in a dataset.
- dim: None or str or iterable of strs
- dimensions to filter along.if None, filter along all dims.
- sigma: None, number, or iterable of numbers
- standard deviation for Gaussian kernel.if iterable, must have same length as dim.if None, will use DEFAULTS.GAUSSIAN_FILTER_SIGMA (default: 1.0).
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.
additional kwargs go to scipy.ndimage.gaussian_filter.
- get_dx_along
- caller of function xarray_get_dx_along in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_get_dx_along(array, coord, *, atol=0, rtol=1e-05, float_rounding=False)returns number equal to the diff along array.coords[coord], after checking that it is constant.result will be a single number, equal to array.coords[coord].diff(coord)[0].item().(Technically, also promotes coord to dim during calculations if coord was a non-dimension coordinate.)before returning result, ensure that np.allclose(array.diff(dim), atol=atol, rtol=rtol);if that fails, raise DimensionValueError.
- float_rounding: bool
- if True, re-create floating point result if it seems to be wrong by only a small amount,e.g. 0.20000000001 –> float(0.2); 0.39999999999 –> float(0.4); 0.123456781234 –> unchangedThis sometimes improves “exact” float comparisons, if float was input from a string.See tools.float_rounding for more details.
- has_mask
- caller of function xarray_has_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masksxarray_has_mask(array)returns whether an xarray object has a mask. I.e., has ‘_mask’ data_var.(Always False for DataArrays).
- property hat
- alias to unit_vector
- property hat2ang
- alias to angle_xy
- image
- caller of class XarrayImage in module PlasmaCalcs.plotting.imagesclass XarrayImage(PlasmaCalcs.plotting.movies.MoviePlotNode, PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin)| XarrayImage(array, t=None, *, x=None, y=None, ax=None, image_mode=’pcolormesh’, init_plot=True, add_colorbar=UNSET, add_labels=True, title=UNSET, **kw_super)|| MoviePlotNode of an xarray.DataArray.| stores an XarrayImagePlotElement & has methods for plotting & updating the image!| “image” refers to a matplotlib.cm.ScalarMappable object, e.g. the result of imshow or pcolormesh.|| array: xarray.DataArray, probably ndim=3; or xarray.Dataset with single data_var| the data to be plotted. if ndim=2, can still plot, but nothing to animate.| if xarray.Dataset, must have only one data_var; will create image of that data_var.| t: None or str| the array dimension which frames will index. E.g. ‘time’.| None -> infer from array & any other provided dimensions.| if provided but dimension not found, attempt xarray_promote_dim before crashing.| x, y: None or str| if provided, tells dimensions for the x, y plot axes.| None -> infer from array & any other provided dimensions.| if provided but dimension not found, attempt xarray_promote_dim before crashing.| ax: None or Axes| the attached mpl.axes.Axes object.| None –> will use self.ax=plt.gca() when getting self.ax for the first time.| image_mode: str (‘imshow’ or ‘pcolormesh’) (default: pcolormesh)| tells whether this image will be pcolormesh or imshow.| init_plot: bool (default: True)| whether to call self.init_plot() immediately, during __init__.| (as a PlotSetting: tells the value of init_plot passed during __init__.)| False –> still must call self.init_plot() before using self(…) or self.updater(…)| (end-user will probably never use init_plot=False; it’s mostly for internal code.)| (might use False if creating MovieImage before defining the associated Axes.)|| xmargin, ymargin, margin: None or number (greater than -0.5, probably close to 0.05) (default: None)| margin to use for x/y axis, as a fraction of the data interval for that axis.| None –> use matplotlib defaults| (e.g., plt.rcParams[“axes.xmargin”] or [“axes.ymargin”], or 0 if using imshow)| positive number –> pad around the data region, with this much whitespace.| E.g. 0.05 means adding 5% whitespace on each side.| Use this to zoom out.| negative number –> remove this much of the outer parts of the data region.| E.g. -0.2 means removing 20% space from each side.| Use this to zoom in.| For line plots, if also using
robust, ymargin will be applied to the robust y lims.| (margin-related params share the same docstring, but refer to:| ‘xmargin’: x-axis, ‘ymargin’: y-axis, ‘margin’: x and/or y-axis.)|| title: UNSET, None, or str (default: UNSET)| title for a single axes/subplot. For xarrays, will title.format(**xarray_nondim_coords(array)).| (Note: plot_settings[‘title’] should always be the ‘base’ title, before title.format(…))| UNSET –> use array_at_current_frame._title_for_slice().| None –> do not add a title.| title_font: UNSET, None, or str (default: UNSET)| font for title, e.g. ‘serif’, ‘sans-serif’, or ‘monospace’| UNSET –> use DEFAULTS.PLOT.MOVIE_TITLE_FONT (default: monospace).| None –> use matplotlib default.| title_y: UNSET, None, or number (default: UNSET)| y position for title, in axes coordinates.| title_kw: UNSET, or dict (default: UNSET)| any additional kwargs for plt.title.|| grid: UNSET, bool, or dict (default: UNSET)| whether to ax.grid() for each axes.| UNSET –> use rcParams[“axes.grid”].| True –> ax.grid(True) for all axes.| False –> ax.grid(False) for all axes.| dict –> ax.grid(**grid) for all axes.|| # [TODO] example||| To view or adjust plot settings in self, see self.plot_settings, or help(self.plot_settings).|| Method resolution order:| XarrayImage| PlasmaCalcs.plotting.movies.MoviePlotNode| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| PlasmaCalcs.tools.trees.Tree| PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin| builtins.object|| Methods defined here:|| __init__(self, array, t=None, *, x=None, y=None, ax=None, image_mode=’pcolormesh’, init_plot=True, add_colorbar=UNSET, add_labels=True, title=UNSET, **kw_super)|| get_data_at_frame(self, frame)| returns {‘array’: array at this frame}, properly transposed & ready for plotting.|| get_nframes_here(self)| return the number of frames that could be in the movie, based on this node.|| init_plot(self)| plot for the first time. Save the XarrayImagePlotElement at self.obj.|| plot_title(self)| adds title (as a MovieTextNode) on self.ax.| raise PlottingAmbiguityError if title already plotted| (this prevents having multiple title nodes).|| scatter_max(self, **kw_scatter)| plt.scatter() to draw a single marker, at the argmax of self.array.| [TODO] animatable, non-static marker (add as child node of self).| returns result of plt.scatter().|| scatter_min(self, **kw_scatter)| plt.scatter() to draw a single marker, at the argmin of self.array.| [TODO] animatable, non-static marker (add as child node of self).| returns result of plt.scatter().|| ———————————————————————-| Data descriptors defined here:|| ax| mpl.axes.Axes where this XarrayImage is plotted.|| fig| figure where this XarrayImage is plotted.|| ———————————————————————-| Data and other attributes defined here:|| element_cls = <class ‘PlasmaCalcs.plotting.images.XarrayImagePlotEleme…| image on an Axes, for an xarray.DataArray.| “image” refers to a matplotlib.cm.ScalarMappable object, e.g. the result of imshow or pcolormesh.|| array: xarray.DataArray, probably ndim=2.| the data to be plotted.| ax: None or Axes| the attached mpl.axes.Axes object.| None –> will use self.ax=plt.gca() when getting self.ax for the first time.| image_mode: str (‘imshow’ or ‘pcolormesh’) (default: pcolormesh)| tells whether this image will be pcolormesh or imshow.|| add_colorbar: UNSET or bool (default: UNSET)| if provided, default for add_colorbar when making xarray plots.| add_labels: bool (default: True)| whether to add labels to xarray plots.|| grid: UNSET, bool, or dict (default: UNSET)| whether to ax.grid() for each axes.| UNSET –> use rcParams[“axes.grid”].| True –> ax.grid(True) for all axes.| False –> ax.grid(False) for all axes.| dict –> ax.grid(**grid) for all axes.||| To view or adjust plot settings in self, see self.plot_settings, or help(self.plot_settings).||| plot_dims_attrs = {‘dims’: ‘_array_dims’, ‘t’: ‘t’, ‘t_necessary_if’: …|| ———————————————————————-| Methods inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| __call__(self, frame)| update the plot for the given frame. return iterable of all updated artists.| Defining __call__ in this way means self is compatible for direct use by FuncAnimation.|| returns FuncAnimation instance using self as func.| Use kwarg defaults from self.plot_settings, for any kwargs not provided here.|| fps: UNSET, None, or number (default: UNSET)| frames per second.| UNSET –> use DEFAULTS.PLOT.FPS (default: 30).| (Or use value from self.plot_settings, if provided.)| None –> use matplotlib defaults.| blit: UNSET, None, or bool (default: UNSET)| whether to use blitting.| UNSET –> use DEFAULTS.PLOT.BLIT (default: True).| (Or use value from self.plot_settings, if provided.)| if None, use matplotlib defaults.| frames: UNSET, None, int, iterable, or slice (default: UNSET)| passed to FuncAnimation. Tells number of frames or which frames to plot.| If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).| if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.| plt_close: bool| whether to plt.close() before returning the result.| This is useful in Jupyter, where commonly one cell might make a plot,| then call get_animator() to display movie in-line, but not plt.close().| In that case, plt_close=False would display animation & plot|| [TODO] use init_func kwarg to avoid calling self twice for frame 0?|| get_nframes(self)| return max of get_nframes_here() for self & all descendants of self.| If any node throws PlottingNframesUnknownError, pretend they said nframes=0.| If all nodes throw PlottingNframesUnknownError, raise the one from self.|| init_plots(self, *, plotted_ok=True)| init_plot for self & all descendants with non-None obj.| plotted_ok: bool| True –> skip node if node.plotted.| False –> call init_plot on all nodes with non-None obj.|| save the movie to filename.| RECOMMENDED:| first, self.save(…, frames=N), with small N (e.g. N=5), to test movie formatting.| Troubleshooting: if movie getting cut off,| try plt.subplots_adjust(bottom=0.2, left=0.2, right=0.8, top=0.8),| or even more extreme values if necessary. (0 is bottom/left edge; 1 is top/right edge.)|| frames: UNSET, None, int, iterable, or slice (default: UNSET)| passed to FuncAnimation. Tells number of frames or which frames to plot.| If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).| if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.| fps: UNSET, None, or number (default: UNSET)| frames per second.| UNSET –> use DEFAULTS.PLOT.FPS (default: 30).| (Or use value from self.plot_settings, if provided.)| None –> use matplotlib defaults.| blit: UNSET, None, or bool (default: UNSET)| whether to use blitting.| UNSET –> use DEFAULTS.PLOT.BLIT (default: True).| (Or use value from self.plot_settings, if provided.)| if None, use matplotlib defaults.|| additional kwargs passed to FuncAnimation() or FuncAnimation.save().| returns abspath of the saved movie.|| update_to_frame(self, frame)| update the plot for the given frame. set self.frame=frame.| also calls update_to_frame for all children.| return iterable of all updated artists.|| ———————————————————————-| Class methods inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| help() from builtins.type| prints a helpful message with examples for how to use this cls|| ———————————————————————-| Readonly properties inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| plotted| whether this node’s element has actually been plotted yet.| False before init_plot; True after. Always None if self.obj is None.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| ani| alias to get_animator|| frame| the currently-plotted frame|| frames| the frames that could be in the movie.| if set to None, will use self.get_nframes() instead.| if set to a slice, will use range(self.get_nframes())[frames] instead.|| plotted_data| the currently plotted data.|| ———————————————————————-| Class methods inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| appends note about using self.plot_settings, to cls.__doc__.| if “PlotSettings” or “plot_settings” appears in cls.__doc__, do NOT append this note;| assuming instead that this means the doc already mentions how to use plot_settings.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| __dict__| dictionary for instance variables (if defined)|| __weakref__| list of weak references to the object (if defined)|| ———————————————————————-| Methods inherited from PlasmaCalcs.tools.trees.Tree:|| __getitem__(self, i)| returns self.children[i]. If i is a tuple, index repeatedly, e.g. self[i[0]][i[1]][i[2]]…|| __iter__(self)| iterates over self.children.|| __repr__(self)| Return repr(self).|| add_child(self, child)| adds this child (a Tree) to self.children. Also, child.set_parent(self).| returns the added child.|| display(self, show_depth=None, max_depth=None, *, shorthand=None)| display self in html. Includes self.html() and DEFAULTS.TREE_CSS.| show_depth: None or int| max number of layers of tree to show by default (i.e. “not hidden” by default)| None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH| max_depth: None or int| max number of layers of tree to render (even if all layers are “not hidden”).| Anything deeper will not be converted to html string.| None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH| shorthand: None or bool| whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.| True –> use shorthand; replace that^ with: “((N, N, N)) …”| None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND|| enumerate_flat(self, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order,| yielding (index, node) pairs, such that self[index] == node.| Note that index will be a tuple with length == node.depth.| if include_self, yield self first, as: ((), self)).|| flat(self, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order.| if include_self, yield self first.|| flat_branches_until(self, branches_until, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order,| but stop looking at descendants on a branch as soon as branches_until(node).| E.g. self.flat_branches_until(lambda node: node.obj==7) will be similar to flat,| but won’t go to any descendants for any node with obj==7.|| if include self, yield self first, and check branches_until(self) before continuing.| otherwise, never check branches_until(self).|| html(self, show_depth=None, max_depth=None, *, shorthand=None)| returns html for displaying self and all of self’s children.| show_depth: None or int| max number of layers of tree to show by default (i.e. “not hidden” by default)| None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH| max_depth: None or int| max number of layers of tree to render (even if all layers are “not hidden”).| Anything deeper will not be converted to html string.| None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH| shorthand: None or bool| whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.| True –> use shorthand; replace that^ with: “((N, N, N)) …”| None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND|| make_child(self, obj)| makes a child of self, with obj as its stored object, and returns the child.|| make_children(self, objs)| make_child(obj) for obj in objs; returns the list of newly made children.|| set_parent(self, parent, *, _internal=False)| sets self.parent = parent. Also, parent.add_child(self), unless _internal=True.| Users should use self.parent = parent instead of calling set_parent directly.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.tools.trees.Tree:|| depth| number of layers above self. (parent, parent’s parents, etc.)| depth = 0 for the node with parent = None.|| height| number of layers below self. (children, children’s children, etc.)| height = 0 for a node with no children.|| parent| parent node of self. None if self is root.| When set to a value, calls self.set_parent(value),| which also updates tracking info appropriately, and updates parent’s children.|| parent_ref| stores parent value, but internally uses weakref to avoid circular references.| Users should always use self.parent instead.|| size| number of nodes in this tree. (here and below)| size = 1 for a node with no children.|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.tools.trees.Tree:|| DEFAULT_TREE_SHORTHAND = None|| DEFAULT_TREE_SHOW_DEPTH = None|| DEFAULT_TREE_SHOW_MAX_DEPTH = None|| ———————————————————————-| Methods inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| infer_xyt_dims(self, *, xy_fail_ok=False, t_fail_ok=True)| infers (x,y,t) dims from self.x, y, dim.| xy_fail_ok, t_fail_ok: bool| controls behavior when failing to infer a dim:| True –> return None for that dim| False –> raise PlottingAmbiguityError| t_fail_ok corresponds to t; xy_fail_ok corresponds to x,y.|| see also: DEFAULTS.PLOT.DIMS_INFER, plotting.infer_xyt_dims, infer_xy_dims, infer_movie_dim|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| t_plot_dim| the dimension which is actually used to index the movie’s frames (i.e. the “time axis”).| setting self.t_plot_dim=value also sets self.{plot_dims_attrs[‘t’]}=value.| getting self.t_plot_dim will get self.{plot_dims_attrs[‘t’]} if it is not None;| otherwise, infer from self.{plot_dims_attrs[‘dims’]}, self.{plot_dims_attrs[‘x’]}, and self.{plot_dims_attrs[‘y’]}| if self.{plot_dims_attrs[‘t_necessary_if’]}(), result might be None.|| x_plot_dim| the dimension which is actually used to index the plot’s x axis.| setting self.x_plot_dim=value also sets self.{plot_dims_attrs[‘x’]}=value.| getting self.x_plot_dim will get self.{plot_dims_attrs[‘x’]} if it is not None;| otherwise, infer from self.{plot_dims_attrs[‘dims’]}, self.{plot_dims_attrs[‘t’]}, and self.{plot_dims_attrs[‘y’]}.|| xy_plot_dims| (self.x_plot_dim, self.y_plot_dim)|| xyt_plot_dims| (self.x_plot_dim, self.y_plot_dim, self.t_plot_dim)|| y_plot_dim| the dimension which is actually used to index the plot’s y axis.| setting self.y_plot_dim=value also sets self.{plot_dims_attrs[‘y’]}=value.| getting self.y_plot_dim will get self.{plot_dims_attrs[‘y’]} if it is not None;| otherwise, infer from self.{plot_dims_attrs[‘dims’]}, self.{plot_dims_attrs[‘t’]}, and self.{plot_dims_attrs[‘x’]}.
- index_coords
- caller of function xarray_index_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_index_coords(array, coords=None, newname=’{coord}_index’, *, drop=False, promote=False, exist_ok=False, max_ndim=None)return copy of array with coord_index coords telling np.arange() for each coord.0D coords’ index will be 0 if provided explicitly in coords input, else ignored.1D coords’ index will be np.arange, e.g. coord_index[i] == i.2D+ coords’ index will be reshaped np.ndindex, such that coord_index[i,j] == (i,j).
- coords: None or iterable of strs
- if None, use all coords and dims which don’t already have coord_index.(e.g. ‘fluid’ –> make ‘fluid_index’, unless ‘fluid_index’ already exists.)
- newname: str
- string for new (index) coord names: newname.format(coord=coord).Default: ‘{coord}_index’. To keep original names, use ‘{coord}’
- drop: bool
- whether to drop original coords after creating coord_index coords.(e.g. ‘fluid’ –> drop ‘fluid’ after making ‘fluid_index’)
- promote: bool
- whether to promote all non-dim new index coords to dimensions.if True, xarray_promote_dim for all new index coords.
- exist_ok: bool
- whether it is okay if newname for coord (e.g. ‘fluid_index’) already exists.True –> replace existing coord with new coord_index.
- max_ndim: None or int
- if not None, skip any coords with ndim > max_ndim.E.g. max_ndim=1 prevents making indexes for coords with ndim>=2.
- isel
- caller of function xarray_isel in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_isel(array, indexers=None, *, promote_dims_if_needed=True, drop=False, missing_dims=’raise’, rounding=’round’, **indexers_as_kwargs)array.isel(…) which can also interpret fractional indexes between -1 and 1, and promotes non-dim coords.behaves just like xarray.DataArray.isel, but:- indexers also allow fractional indexes.- if any dim with index provided refers to a non-dimension coordinate, first promote it via swap_dims.- if any indexer has ‘iseler’ attr, use indexer.iseler(values) to determine indexes.In particular, for {cname: index}:- fractional indexes:if index is a slice, int, or iterable of ints, use it as is.if index contains any values between -1 and 1 (excluding -1, 0, and 1):treat that value as a fraction of L=len(array[cname]).E.g. 0.25 –> int(L * 0.25);-0.1 –> -int(L * 0.1).This is equivalent to interprets_fractional_indexing(index, L)- non-dimension coordinates:if cname is a non-dimension coordinate, use xarray_promote_dim(array, cname).
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
drop, missing_dims: passed to array.isel; see below for details. rounding: passed to interprets_fractional_indexing; see below for details.
xarray.DataArray.isel docs copied below:—————————————-str(object=’’) -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat will be decoded using the given encoding and error handler.Otherwise, returns the result of object.__str__() (if defined)or repr(object).encoding defaults to sys.getdefaultencoding().errors defaults to ‘strict’.interprets_fractional_indexing docs copied below:————————————————-interprets any fractional values, i.e. non-integers between -1 and 1.returns indexer in “canonical” form, no longer containing any fractional values.If indexer contains no fractional values, return indexer unchanged.- indexer: None, int, slice, iterable, or non-integer between -1 and 1.
- indexer to interpret; might contain fractional value(s), i.e. non-integers between -1 and 1.any fractional values will be converted to value*(L+1), then rounded to an integer.rounding method is determined by
rounding, unless indexer is a slice,in which case rounding for start & stop is handled differently.fractional values might appear in any of the following ways:- as an individual float, e.g. 0.3- as a float inside an iterable, e.g. [0, 0.25, 0.5, 0.75, 1]- as a float inside a slice, e.g. slice(0, -0.1, 0.02)“fractional” is tested via (-1 < value < 1) and (value != 0). - L: None or int
- length of the object being indexed. Required if any fractional values provided.None –> if any fractional values provided, raise InputMissingError.L must be >= 2. [TODO] handle L=1 case (have all fractional values imply 0).
- rounding: UNSET, ‘round’, ‘floor’, ‘ceil’ or ‘int’
- method to use for rounding fractional values to integers, except for slice.start or slice.stop.UNSET –> use DEFAULTS.FRACTIONAL_INDEX_ROUNDING (default: floor)‘round’ –> as per builtins.round(). round to nearest integer, ties toward even integers.‘int’ –> as per builtins.int(). round towards 0.‘floor’ –> as per math.floor(). round towards negative infinity.‘ceil’ –> as per math.ceil(). round towards positive infinity.
Rounding for slice.start and start.stop will ALWAYS include all indices between start*(L-1) and stop*(L-1)For positive (or None) step, this means: round all numbers toward +infinity.Examples (floats here are after multiplying input by L-1, e.g. 0.1 * 153 –> 15.3):slice(15.3, 29.2, 1) –> slice(16, 30, 1) # 15.3, [16, 17, …, 29], 29.2slice(-29.2, -15.3, 1) –> slice(-29, -15, 1) # -29.2, [-29, -28, …, -16], -15.3slice(15.3, -15.3, 1) –> slice(16, -15, 1) # 15.3, [16, 18, …, -17, -16], -15.3slice(-29.2, 100.1, 1) –> slice(-29, 101, 1) # -29.2, [-29, -28, …, 99, 100], 100.1For negative step, this means: round all numbers toward -infinity.Examples (floats here are after multiplying input by L-1, e.g. 0.1 * 153 –> 15.3):slice(29.2, 15.3, -1) –> slice(29, 15, -1) # 29.2, [29, 28, …, 17, 16], 15.3slice(-15.3, -29.2, -1) –> slice(-16, -30, -1) # -15.3, [-16, -17, …, -28, -29], -29.2slice(-15.3, 15.3, -1) –> slice(-16, 15, -1) # -15.3, [-16, -17, …, 16, 15], 15.3slice(100.1, -29.2, -1) –> slice(100, -30, -1) # 100.1, [100, 99, …, -28, -29], -29.2Rounding mode for slice.step is determined byrounding, applying to step*L (not L-1).however if this causes step=0, instead use step=1 or step=-1, based on sign of original step.— Examples —# [TODO] update these when considering N = L-1 is what is actually being multiplied.interprets_fractional_indexing(0.5, L=10) –> 5interprets_fractional_indexing(slice(0.2, 0.9, 0.1), L=10) –> slice(2, 9, 1)interprets_fractional_indexing([0.2, 0.5, -3, 8, 7, 0.9], L=10) –> [2, 5, -3, 8, 7, 9]interprets_fractional_indexing(0.23, L=10, rounding=’int’) –> 2interprets_fractional_indexing(0.23, L=10, rounding=’ceil’) –> 3
- lines
- caller of class XarrayLines in module PlasmaCalcs.plotting.linesclass XarrayLines(PlasmaCalcs.plotting.movies.MovieOrganizerNode)|| MovieOrganizerNode for organizing multiple XarrayLines.|| xarray: xarray.DataArray or xarray.Dataset| the array to plot lines from. Any number of dimensions is allowed.| if dataset, will be converted to array using to_array(dim=’variable’).| Note that dims other than t & x should be “not too long” otherwise plot will have lots of lines.| dims: None or list of str| dimensions to iterate over; plot one line per point in these dimensions.| E.g. dims = [‘fluid’, ‘component’] –> plot one line per fluid-component pair.| [TODO] improve formatting; currently uses default cycler for line properties,| but if using multiple dims it would be nicer to have a different cycler for each dim,| e.g. colors for fluid, linestyles for component.| None –> infer from array.dims, t, and x.| t: None or str| dimension name for the time axis (for movies).| None –> infer from the xarray coords. See also: DEFAULTS.PLOT.DIMS_INFER| If no time dimension (None provided & can’t infer), that’s okay, but animation will fail.| x: None or str| dimension name for the x axis.| None –> infer from the xarray coords. See also: DEFAULTS.PLOT.DIMS_INFER|| robust: {robust}| add_legend: bool| whether to plot a legend, by default.| label: {label}| UNSET –> ‘dim=val’ for each line, for each dim in dims, e.g. ‘fluid=e-, component=x’||| To view or adjust plot settings in self, see self.plot_settings, or help(self.plot_settings).|| Method resolution order:| XarrayLines| PlasmaCalcs.plotting.movies.MovieOrganizerNode| PlasmaCalcs.plotting.movies.EmptyMovieNode| PlasmaCalcs.plotting.movies.MoviePlotNode| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| PlasmaCalcs.tools.trees.Tree| builtins.object|| Methods defined here:||| init_plot(self)| plot for the first time: call init_plot on all nodes, and connect to tree.|| This is fundamentally different from MoviePlotNode.init_plot’s usual purpose,| since this is about calling init_plot on the nodes, not on self.obj.| [TODO] should this function be renamed, for clarity?|| plot_legend(self)| plot a legend! Plots to the right of the axes.| For more precise control of legend,| use add_legend=False during self.__init__,| and just call plt.legend() separately…|| Also fig.set_layout_engine(‘tight’) if layout engine was None;| otherwise the legend might get cut off at the edges.|| plot_title(self)| adds title (as a MovieTextNode) on self.ax.| raise PlottingAmbiguityError if title already plotted| (this prevents having multiple title nodes).|| ———————————————————————-| Readonly properties defined here:|| line0| first line; lines[0].|| ———————————————————————-| Data descriptors defined here:|| ax| mpl.axes.Axes where the lines are plotted.|| fig| figure where the lines are plotted.|| lines| alias to nodes|| ———————————————————————-| Methods inherited from PlasmaCalcs.plotting.movies.MovieOrganizerNode:|| __repr__(self)| Return repr(self).|| ———————————————————————-| Methods inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| __call__(self, frame)| update the plot for the given frame. return iterable of all updated artists.| Defining __call__ in this way means self is compatible for direct use by FuncAnimation.|| returns FuncAnimation instance using self as func.| Use kwarg defaults from self.plot_settings, for any kwargs not provided here.|| fps: UNSET, None, or number (default: UNSET)| frames per second.| UNSET –> use DEFAULTS.PLOT.FPS (default: 30).| (Or use value from self.plot_settings, if provided.)| None –> use matplotlib defaults.| blit: UNSET, None, or bool (default: UNSET)| whether to use blitting.| UNSET –> use DEFAULTS.PLOT.BLIT (default: True).| (Or use value from self.plot_settings, if provided.)| if None, use matplotlib defaults.| frames: UNSET, None, int, iterable, or slice (default: UNSET)| passed to FuncAnimation. Tells number of frames or which frames to plot.| If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).| if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.| plt_close: bool| whether to plt.close() before returning the result.| This is useful in Jupyter, where commonly one cell might make a plot,| then call get_animator() to display movie in-line, but not plt.close().| In that case, plt_close=False would display animation & plot|| [TODO] use init_func kwarg to avoid calling self twice for frame 0?|| get_data_at_frame(self, frame)| return dict of data for the given frame, to be used by the MoviePlotElement at self.obj.|| get_nframes(self)| return max of get_nframes_here() for self & all descendants of self.| If any node throws PlottingNframesUnknownError, pretend they said nframes=0.| If all nodes throw PlottingNframesUnknownError, raise the one from self.|| get_nframes_here(self)| return the number of frames that could be in the movie, based on this node.|| init_plots(self, *, plotted_ok=True)| init_plot for self & all descendants with non-None obj.| plotted_ok: bool| True –> skip node if node.plotted.| False –> call init_plot on all nodes with non-None obj.|| save the movie to filename.| RECOMMENDED:| first, self.save(…, frames=N), with small N (e.g. N=5), to test movie formatting.| Troubleshooting: if movie getting cut off,| try plt.subplots_adjust(bottom=0.2, left=0.2, right=0.8, top=0.8),| or even more extreme values if necessary. (0 is bottom/left edge; 1 is top/right edge.)|| frames: UNSET, None, int, iterable, or slice (default: UNSET)| passed to FuncAnimation. Tells number of frames or which frames to plot.| If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).| if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.| fps: UNSET, None, or number (default: UNSET)| frames per second.| UNSET –> use DEFAULTS.PLOT.FPS (default: 30).| (Or use value from self.plot_settings, if provided.)| None –> use matplotlib defaults.| blit: UNSET, None, or bool (default: UNSET)| whether to use blitting.| UNSET –> use DEFAULTS.PLOT.BLIT (default: True).| (Or use value from self.plot_settings, if provided.)| if None, use matplotlib defaults.|| additional kwargs passed to FuncAnimation() or FuncAnimation.save().| returns abspath of the saved movie.|| update_to_frame(self, frame)| update the plot for the given frame. set self.frame=frame.| also calls update_to_frame for all children.| return iterable of all updated artists.|| ———————————————————————-| Class methods inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| help() from builtins.type| prints a helpful message with examples for how to use this cls|| ———————————————————————-| Readonly properties inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| plotted| whether this node’s element has actually been plotted yet.| False before init_plot; True after. Always None if self.obj is None.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| ani| alias to get_animator|| frame| the currently-plotted frame|| frames| the frames that could be in the movie.| if set to None, will use self.get_nframes() instead.| if set to a slice, will use range(self.get_nframes())[frames] instead.|| plotted_data| the currently plotted data.|| ———————————————————————-| Class methods inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| appends note about using self.plot_settings, to cls.__doc__.| if “PlotSettings” or “plot_settings” appears in cls.__doc__, do NOT append this note;| assuming instead that this means the doc already mentions how to use plot_settings.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| __dict__| dictionary for instance variables (if defined)|| __weakref__| list of weak references to the object (if defined)|| ———————————————————————-| Methods inherited from PlasmaCalcs.tools.trees.Tree:|| __getitem__(self, i)| returns self.children[i]. If i is a tuple, index repeatedly, e.g. self[i[0]][i[1]][i[2]]…|| __iter__(self)| iterates over self.children.|| add_child(self, child)| adds this child (a Tree) to self.children. Also, child.set_parent(self).| returns the added child.|| display(self, show_depth=None, max_depth=None, *, shorthand=None)| display self in html. Includes self.html() and DEFAULTS.TREE_CSS.| show_depth: None or int| max number of layers of tree to show by default (i.e. “not hidden” by default)| None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH| max_depth: None or int| max number of layers of tree to render (even if all layers are “not hidden”).| Anything deeper will not be converted to html string.| None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH| shorthand: None or bool| whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.| True –> use shorthand; replace that^ with: “((N, N, N)) …”| None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND|| enumerate_flat(self, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order,| yielding (index, node) pairs, such that self[index] == node.| Note that index will be a tuple with length == node.depth.| if include_self, yield self first, as: ((), self)).|| flat(self, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order.| if include_self, yield self first.|| flat_branches_until(self, branches_until, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order,| but stop looking at descendants on a branch as soon as branches_until(node).| E.g. self.flat_branches_until(lambda node: node.obj==7) will be similar to flat,| but won’t go to any descendants for any node with obj==7.|| if include self, yield self first, and check branches_until(self) before continuing.| otherwise, never check branches_until(self).|| html(self, show_depth=None, max_depth=None, *, shorthand=None)| returns html for displaying self and all of self’s children.| show_depth: None or int| max number of layers of tree to show by default (i.e. “not hidden” by default)| None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH| max_depth: None or int| max number of layers of tree to render (even if all layers are “not hidden”).| Anything deeper will not be converted to html string.| None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH| shorthand: None or bool| whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.| True –> use shorthand; replace that^ with: “((N, N, N)) …”| None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND|| make_child(self, obj)| makes a child of self, with obj as its stored object, and returns the child.|| make_children(self, objs)| make_child(obj) for obj in objs; returns the list of newly made children.|| set_parent(self, parent, *, _internal=False)| sets self.parent = parent. Also, parent.add_child(self), unless _internal=True.| Users should use self.parent = parent instead of calling set_parent directly.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.tools.trees.Tree:|| depth| number of layers above self. (parent, parent’s parents, etc.)| depth = 0 for the node with parent = None.|| height| number of layers below self. (children, children’s children, etc.)| height = 0 for a node with no children.|| parent| parent node of self. None if self is root.| When set to a value, calls self.set_parent(value),| which also updates tracking info appropriately, and updates parent’s children.|| parent_ref| stores parent value, but internally uses weakref to avoid circular references.| Users should always use self.parent instead.|| size| number of nodes in this tree. (here and below)| size = 1 for a node with no children.|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.tools.trees.Tree:|| DEFAULT_TREE_SHORTHAND = None|| DEFAULT_TREE_SHOW_DEPTH = None|| DEFAULT_TREE_SHOW_MAX_DEPTH = None
- log_coords
- caller of function xarray_log_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_log_coords(array, coords=None, newname=’log_{coord}’, *, base=10, drop=True, promote=False)return copy of array with coords replaced by log coords (& renamed to log_coord)
- coords: None, str, or iterable of strs
- coords to replace with log. None –> all coords.
- newcoord: str
- string for new (logged) coord names: newcoord.format(coord=coord).Default: ‘log_{coord}’. To keep original names, use ‘{coord}’
- base: number or ‘e’
- log in this base. default 10.if not 10, result.assign_attrs({‘log_base’: base}).
- drop: bool
- whether to drop original coords’ values.True –> drop original coords.False –> add new coords but do not adjust original coords.
- promote: bool
- whether to promote all non-dim new log coords to dimensions.if True, xarray_promote_dim for all new log coords.
- property mag
- alias to magnitude
- magnitude
- caller of function magnitude in module PlasmaCalcs.quantities.patterns.vector_arithmeticmagnitude(A, *, squared=False)return vector magnitude of A, assuming vector components along the dimension ‘component’.
- squared: bool, default False
- if True, return |A|**2 instead of |A|.[EFF] to get |A|**2, when |A| is not needed,magnitude(A, squared=True) is more efficient than magnitude(A)**2
- map
- caller of function xarray_map in module PlasmaCalcs.tools.xarray_tools.xarray_indexingMainly useful if trying to apply f which expects unlabeled array & int axes inputs.E.g. numpy.mean can use axis kwarg as iterable of ints,but here can provide axis as a dim name str or list of dim names.Probably not super useful for mean, since xarray provides xr.mean,but may be useful for other functions e.g. scipy.ndimage.gaussian_filter,which might not have an existing equivalent in xarray.
- array: xarray.DataArray or Dataset
- apply f to this array, or each array in this Dataset
- f: callable
- axis, axes: None, str, or iterable of strs
- if provided, convert to axes positions in dataarray, and pass to f as int(s).Also promotes these coords to dims if necessary.
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.
- mask
- caller of function xarray_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masksxarray_mask(array, mask=None, stackdim=’_mask_stack’, *, stack=True, create_index=True, skip_arrays_without_mask_dims=True, store_mask=None, promote_dims_if_needed=True)mask an xarray object; result has non-nan values only where mask=False.By default, also stack along mask dimensions, and drop points where mask=True.
- array: xarray.DataArray or xarray.Dataset
- object to be masked.
- mask: None or xarray.DataArray
- mask to apply to array.None –> use array[‘_mask’] (and array must be a Dataset)
- stackdim: str, default ‘_mask_stack’
- result.dims[stackdim] has the mask dimensions stacked.
- stack: bool
- whether to stack result.if False, don’t stack, just use array.where(~mask). (~ means negation)
- create_index: bool
- whether to create a MultiIndex for stackdim in the result, if stack.
- skip_arrays_without_mask_dims: bool
- whether to apply mask to arrays without mask dims.if True, only arrays originally containing at least one mask dim will be masked.if False, all results will have mask dims (or stackdim) via array.where(~mask).
- store_mask: None or bool
- whether to store full mask as a data_var in result.None –> True if array is a Dataset, else FalseTrue –> result Dataset will have full mask in data_var ‘_mask’.If stack, mask dims replaced by ‘_mask_{d}’ for d in mask.dims,to avoid conflict with original mask dims’ coords in result.If input DataArray, first convert to Dataset with data_var array.name.False –> do not store mask in result.
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
crash with DimensionKeyError if any relevant dim (stackdim, ‘_mask’, ‘_mask_{d}’) already exists.
- max
- caller of function xarray_max in module PlasmaCalcs.tools.xarray_tools.xarray_agg_statsLike xarray max but first promotes dims if needed, and accepts ‘keep’ option.
- dim: None, str, or iterable of strs
- apply operation along these dimensions
- keep: None, str, or iterable of strs
- apply operation along all except for these dimensions.(can provide keep or dim, but not both.)
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.
additional kwargs are passed to array.max.
- mean
- caller of function xarray_mean in module PlasmaCalcs.tools.xarray_tools.xarray_agg_statsLike xarray mean but first promotes dims if needed, and accepts ‘keep’ option.
- dim: None, str, or iterable of strs
- apply operation along these dimensions
- keep: None, str, or iterable of strs
- apply operation along all except for these dimensions.(can provide keep or dim, but not both.)
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.
additional kwargs are passed to array.mean.
- median
- caller of function xarray_median in module PlasmaCalcs.tools.xarray_tools.xarray_agg_statsxarray_median(array, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw)Like xarray median but first promotes dims if needed, and accepts ‘keep’ option.
- dim: None, str, or iterable of strs
- apply operation along these dimensions
- keep: None, str, or iterable of strs
- apply operation along all except for these dimensions.(can provide keep or dim, but not both.)
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.
additional kwargs are passed to array.median.
- min
- caller of function xarray_min in module PlasmaCalcs.tools.xarray_tools.xarray_agg_statsLike xarray min but first promotes dims if needed, and accepts ‘keep’ option.
- dim: None, str, or iterable of strs
- apply operation along these dimensions
- keep: None, str, or iterable of strs
- apply operation along all except for these dimensions.(can provide keep or dim, but not both.)
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.
additional kwargs are passed to array.min.
- property mod
- alias to magnitude
- property nMbytes
- size of array in Mbytes
- nondim_coords
- caller of function xarray_nondim_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_nondim_coords(array, *, scalars_only=False, item=False, _sort=True)returns dict of {coord name: coord.values} for all non-dimension coords (not in array.dims).
- scalars_only: bool
- whether to only include coords with ndim==0.
- item: bool
- whether to use coord.item() for scalars.
- _sort: bool
- whether to sort, if any ‘{coord}_index’ coords appear consecutively,(when doing the default array.coords.items() order), sort those alphabetically.If their non-index counterparts also appear consecutively, sort those too.E.g. order: ‘C’, ‘A’, ‘B’, ‘other_index’, ‘D’, ‘C_index’, ‘A_index’, ‘D_index’, ‘B_index’, ‘E’,becomes: ‘A’, ‘B’, ‘C’, ‘other_index’, ‘D’, ‘A_index’, ‘B_index’, ‘C_index’, ‘D_index’, ‘E’.
- object_coords_to_str
- caller of function xarray_object_coords_to_str in module PlasmaCalcs.tools.xarray_tools.xarray_miscxarray_object_coords_to_str(array, *, maxlen=None, ndim_min=1)return copy of array with coords (of dtype=object) converted to string.
- maxlen: None or int>=5
- if int, truncate longer strings to this length-3, and add ‘…’ to end.
- ndim_min: int
- minimum number of dimensions for a coord to be converted.e.g. ndim_min=1 –> coords with ndim=0 will not be altered
- parallel
- caller of function parallel in module PlasmaCalcs.quantities.patterns.vector_arithmeticparallel(A, B)return the component of A parallel to B. Equivalent: (A dot Bhat) Bhat.
- property parmag
- alias to parmod
- parmod
- caller of function parmod in module PlasmaCalcs.quantities.patterns.vector_arithmeticparmod(A, B)return the magnitude of the component of A parallel to B. Equivalent: |(A dot Bhat) Bhat|
- perp
- caller of function perp in module PlasmaCalcs.quantities.patterns.vector_arithmeticperp(A, B)return the component of A perpendicular to B. Equivalent: A - (A dot Bhat) Bhat.
- property perpmag
- alias to perpmod
- perpmod
- caller of function perpmod in module PlasmaCalcs.quantities.patterns.vector_arithmeticperpmod(A, B)return the magnitude of the component of A perpendicular to B. Equivalent: |A - (A dot Bhat) Bhat|
- polyfit
- caller of function xarray_polyfit in module PlasmaCalcs.tools.xarray_tools.xarray_scixarray_polyfit(array, coord, degree, *, stddev=False, full=False, cov=False, eval=False, **kw_polyfit)returns array.polyfit(coord, degree, **kw_polyfit), after swapping coord to be a dimension, if needed.E.g. for an array with dimension ‘snap’ and associated non-dimension coordinate ‘t’,xarray_polyfit(array, ‘t’, 1) is equivalent to array.swap_dims(dict(snap=’t’)).polyfit(‘t’, 1).
- stddev: bool
- whether to also return the standard deviations of each coefficient in the fit.if True, assign the variable ‘polyfit_stddev’ = diagonal(polyfit_covariance)**0.5,mapping the diagonal (across ‘cov_i’, ‘cov_j’) to the dimension ‘degree’.if cov False when stddev True, do not keep_cov in the result.Not compatible with full=True.
- full: bool
- passed into polyfit; see below.
- cov: bool
- passed into polyfit; see below.Note: if stddev=True when cov=False, still use cov=True during array.polyfit,however then remove polyfit_covariance & polyfit_residuals from result.
- eval: bool
- whether to also return the fit, evaluated at array.coords[coord]if True, assign the variable ‘polyfit_eval’ = sum(coeff * coord**degree, ‘degree’).if stddev=True too, assign ‘polyfit_eval-stddev’ and ‘polyfit_eval+stddev’ too,using similar formula but using coeffs +/- stddev.
Docs for xr.DataArray.polyfit copied below:——————————————-Least squares polynomial fit.This replicates the behaviour ofnumpy.polyfitbut differs by skippinginvalid values whenskipna = True.Parameters———-- dimHashable
- Coordinate along which to fit the polynomials.
- degint
- Degree of the fitting polynomial.
- skipnabool or None, optional
- If True, removes all invalid values before fitting each 1D slices of the array.Default is True if data is stored in a dask.array or if there is anyinvalid values, False otherwise.
- rcondfloat or None, optional
- Relative condition number to the fit.
- wHashable, array-like or None, optional
- Weights to apply to the y-coordinate of the sample points.Can be an array-like object or the name of a coordinate in the dataset.
- fullbool, default: False
- Whether to return the residuals, matrix rank and singular values in additionto the coefficients.
- covbool or “unscaled”, default: False
- Whether to return to the covariance matrix in addition to the coefficients.The matrix is not scaled if
cov='unscaled'.
Returns——-- polyfit_resultsDataset
- A single dataset which contains:polyfit_coefficientsThe coefficients of the best fit.polyfit_residualsThe residuals of the least-square computation (only included if
full=True).When the matrix rank is deficient, np.nan is returned.[dim]_matrix_rankThe effective rank of the scaled Vandermonde coefficient matrix (only included iffull=True)[dim]_singular_valueThe singular values of the scaled Vandermonde coefficient matrix (only included iffull=True)polyfit_covarianceThe covariance matrix of the polynomial coefficient estimates (only included iffull=Falseandcov=True)
See Also——–numpy.polyfitnumpy.polyvalxarray.polyvalDataArray.curvefit
- promote_dim
- caller of function xarray_promote_dim in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsxarray_promote_dim(array, coord, *coords_as_args)Promote this coord (or these coords) to be a dimension, if it isn’t already.
- coord: str or iterable of strs
- name of coord(s) to promote.if already in array.dims, do nothing.if 0D, array.expand_dims(coord).(This occurs when coord has no associated dimension, in array.)if 1D, array.swap_dims(dict(dim=coord)),where dim is the dimension associated with coord.if 2D+, crash with DimensionalityError.
returns array, or a copy of array where coord is one of the dimensions.
- classmethod register(f_or_name, *, aliases=[], totype=UNSET, _name=None)
- (in general, use cls.accessor_name, not necessarily ‘pc’; ‘pc’ is for pcAccessor.)This ensures f can be accessed via xr.DataArray.pc.{name} or xr.Dataset.pc.{name}.pcAccessor.register –> available on both DataArrays and Datasets.pcArrayAccessor.register –> available on DataArrays only.pcDatasetAccessor.register –> available on Datasets only.
- f_or_name: str or callable
- str –> returns a function: f -> register(f, name=f_or_name)callable –> register this function then return it.will be registered at _name if provided, else at f.__name__.This enables this method to be used directly as a decorator, or as a decorator factory.
- aliases: list of str
- aliases for f. Create alias property for each of these.
- totype: UNSET, None, ‘array’, or ‘dataset’
- which type of xarray objects the registered method applies to.UNSET –> use cls.access_type.None –> methods apply to both DataArrays and Datasets.‘array’ –> methods apply to DataArrays only‘dataset’ –> methods apply to Datasets only.
- _name: str, optional
- name to register f at. If not provided, use f.__name__.Not intended to be provided directly.
Examples (using pcAccessor subclass for concreteness):@pcAccessor.registerdef my_method1(xarray_object, arg1):print(arg1)print(xarray_obj)xr.DataArray(data).pc.my_method1(7) # prints 7 then prints DataArray(data).xr.Dataset(data).pc.my_method1(5) # prints 5 then prints Dataset(data).@pcAccessor.register(name=’my_method2’, totype=’array’)def xarray_my_method2(xarray_object):print(xarray_object * 10)xr.DataArray(data).pc.my_method2() # prints 10*DataArray(data).xr.Dataset(data).pc.my_method2() # crashes; my_method2 not registered to datasets.
- classmethod register_attr(name, value, *, totype=UNSET)
- register cls.{name} = value, using a similar interface as cls.register.when totype is UNSET, this is equivalent to:cls.{name} = value; cls.attrs_registry[name] = (cls.access_type, value),when totype is provided, use cls=cls.access_type_to_cls[totype], instead.returns value, after doing setattr(cls, name, value)
- totype: UNSET, None, ‘array’, or ‘dataset’
- which type of xarray objects the registered attr applies to.UNSET –> use cls.access_type.None –> methods apply to both DataArrays and Datasets.‘array’ –> methods apply to DataArrays only‘dataset’ –> methods apply to Datasets only.
Examples (using pcAccessor subclass for concreteness):pcAccessor.register_attr(‘MY_CONSTANT1’, 7)pcAccessor.register_attr(‘MY_CONSTANT2’, 5, totype=’array’)pcAccessor.register_attr(‘nMbytes’, property(lambda self: self.obj.nbytes/1024**2))arr = xr.DataArray(some_data)ds = xr.Dataset(other_data)arr.pc.MY_CONSTANT1 # == 7ds.pc.MY_CONSTANT1 # == 7arr.pc.MY_CONSTANT2 # == 5ds.pc.MY_CONSTANT2 # crashes; MY_CONSTANT2 not registered to datasets.arr.pc.nMbytes # == DataArray(data).nbytes/1024**2ds.pc.nMbytes # == Dataset(data).nbytes/1024**2
- rename
- caller of function xarray_rename in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
- rms
- caller of function xarray_rms in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats(array**2).mean(dim, **kw)**0.5
- dim: None, str, or iterable of strs
- apply operation along these dimensions
- keep: None, str, or iterable of strs
- apply operation along all except for these dimensions.(can provide keep or dim, but not both.)
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.
- save
- caller of function xarray_save in module PlasmaCalcs.tools.xarray_tools.xarray_ioxarray_save(array, filename=None, *, exist_ok=False, add_meta=True, notes=None, reset_multi_index=True, engine=None, compress=None, encoding=None, **kw_to_netcdf)saves the array or dataset as filename.nc with a companion text file filename.txt.Both will be saved into a new directory named filename.pcxarr(“pcxarr” stands for “PlasmaCalcs xarray.DataArray or xarray.Dataset object”)
- array: xarray.DataArray or xarray.Dataset
- the array or dataset to save
- filename: None or str
- where to save the array. Extension “.pcxarr” will be added if not present.None –> infer filename=array.name, or “unnamed_array” if array.name is None.(actually: array.name.replace(‘/’, ‘÷’). To avoid interpreting division as directories.)if filename implies directories, those directories will be created, as per os.makedirs.
- exist_ok: bool, default False
- whether it’s okay if directory with the target name to already exist.False –> crash with FileExistsError if directory exists.True –> might overwrite files in that directory!
- add_meta: bool
- whether to array.assign_attrs(details about current version of PlasmaCalcs code)Those details include ‘pc__version__’, ‘pc__commit_hash’, and ‘datetime’.
- notes: None or object to convert to str
- if provided, also save a notes.txt file containing str(notes).Feel free to use this to write anything, e.g. describe what array means, in words.
- reset_multi_index: bool
- whether to array.reset_index(idx) for all MultiIndex idx, before saving.if True, also add info to array.attrs[‘reset_multi_index:{d}’ for reset d].if False, may crash with NotImplementedError if any MultiIndex present.
additional kwargs relate to internal strategy for to_netcdf:- engine: None or str (‘netcdf4’, ‘h5netcdf’, ‘scipy’)
- which engine to use for saving.None –> use _xarray_best_save_engine()(picks first available, from netcdf4 > h5netcdf > scipy)
- compress: None, bool, or dict
- whether to compress data when writing.None –> True if engine can do compression, else False.(‘scipy’ engine is not compatible with compression.)bool –> get dict from _xarray_engine_compression_defaults(engine)(crash with InputConflictError if engine can’t do compression.)(default {‘zlib’: True} for ‘netcdf4’ and ‘h5netcdf’)dict –> apply this strategy to each data variable.equivalent: encoding={var1: compress, var2: compress, …}
- encoding: None or dict
- dict of {var: {encoding options for var}} across data vars.determined automatically if provided compress.
returns abspath to filename.pcxarr directory where the array was saved.
- scale_coords
- caller of function xarray_scale_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsreturn copy of array with coords multiplied by scale.
- scale: None or dict of {coord: scale}
- dict –> multiply each coord by the corresponding number.None –> provide as kwargs (scale_as_kw) instead.
scale_as_kw: if scale is None, can provide scale dict as kwargs instead. missing_ok: bool
whether it is okay if some coords are missing (if yes, skip missing coords).
- search
- caller of function xarray_search in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_search(array, dim, value)return first index of value along dim(or coord. returns 0, not crash, if scalar coord which matches value.)Not efficient for large dims. For large sorted dims, see xarray.DataArray.searchsorted.crash with DimensionValueError if value not found in dim.
- sel
- caller of function xarray_sel in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_sel(array, indexers=None, *, promote_dims_if_needed=True, method=None, tolerance=None, drop=False, **indexers_as_kwargs)array.sel(…) but prioritize general applicability over efficiency:- promote non-dimension coordinate dims first if applicable- (if coord.dtype is object) check coord equality,e.g. 0==Fluid(‘e’, 0)==’e’, so could use Fluid(‘e’, 0), ‘e’, or 0 in sel.- can also use list, tuple, or 1D non-string iterable,e.g. [‘e’, 3, ‘Fe+’] to get multiple fluids.- can also use slice,e.g. slice(‘e’, ‘Fe+’, 2) to get every other fluid,starting from ‘e’, stopping before the first ‘Fe+’ match.- if indexer has ‘iseler’ attr, use indexer.iseler(values) to determine indexes.Assumes all indexing is for 1D dims. For indexing 2D+ dims, use xarray methods directly.
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- method: None or str
- method to use for inexact matches, for non-object dtype coords.
xarray.DataArray.sel docs copied below:—————————————-str(object=’’) -> strstr(bytes_or_buffer[, encoding[, errors]]) -> strCreate a new string object from the given object. If encoding orerrors is specified, then the object must expose a data bufferthat will be decoded using the given encoding and error handler.Otherwise, returns the result of object.__str__() (if defined)or repr(object).encoding defaults to sys.getdefaultencoding().errors defaults to ‘strict’.
- shift_coords
- caller of function xarray_shift_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsreturn copy of array with coords shifted by shift.
- shift: None or dict of {coord: shift}
- dict –> shift each coord by the corresponding number.None –> provide as kwargs (shift_as_kw) instead.
shift_as_kw: if shift is None, can provide shift dict as kwargs instead. missing_ok: bool
whether it is okay if some coords are missing (if yes, skip missing coords).
- std
- caller of function xarray_std in module PlasmaCalcs.tools.xarray_tools.xarray_agg_statsLike xarray std but first promotes dims if needed, and accepts ‘keep’ option.
- dim: None, str, or iterable of strs
- apply operation along these dimensions
- keep: None, str, or iterable of strs
- apply operation along all except for these dimensions.(can provide keep or dim, but not both.)
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.
additional kwargs are passed to array.std.
- store_mask
- caller of function xarray_store_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masksxarray_store_mask(array, mask)return Dataset like input but containing data_var ‘_mask’.crash with DimensionKeyError if ‘_mask’ already exists in input.if mask.dims not already in array.dims, rename mask dims d to ‘_mask_{d}’.(this will occur when storing mask in a stacked result,because the stacked result will have stackdim instead of mask dims.)
- array: xarray.DataArray or xarray.Dataset
- if DataArray, will be converted to Dataset with data_var array.name.
- str_coords
- caller of function xarray_str_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_str_coords(array, coords=None, newname=’str_{coord}’, *, drop=True, promote=False)return copy of array with coords replaced by str coords (& renamed to str_coord)E.g. array.pc.str_coords(‘fluid’) –> result[‘str_fluid’] == str(f) for f in array[‘fluid’]
- coords: None, str, or iterable of strs
- coords to replace with str. None –> all coords.
- newcoord: str
- string for new (converted-to-str) coord names: newcoord.format(coord=coord).Default: ‘str_{coord}’. To keep original names, use ‘{coord}’
- drop: bool
- whether to drop original coords’ values.True –> drop original coords.False –> add new coords but do not adjust original coords.
- promote: bool
- whether to promote all non-dim new str coords to dimensions.if True, xarray_promote_dim for all new str coords.
- subplots
- caller of class XarraySubplots in module PlasmaCalcs.plotting.subplots_extensionsclass XarraySubplots(MovieSubplots)| XarraySubplots(xarray, row=None, col=None, *, wrap=None, x=None, y=None, t=None, fig=None, vmin=None, vmax=None, robust=UNSET, share_vlims=False, title=UNSET, title_y=UNSET, suptitle=UNSET, suptitle_y=UNSET, aspect=UNSET, layout=UNSET, cax_mode=UNSET, axsize=UNSET, add_colorbars=True, **kw)|| grid of subplots from xarray data. Can be animated as a movie!|| xarray: xarray.DataArray or xarray.Dataset| the array to plot. up to 5D (row, col, x, y, t).| (Note that row & col dims should be “not too long” otherwise plot will be very large)| if dataset, up to 4D; will be converted to DataArray with new dim named ‘variable’.| internally, will store xarray_fill_coords(xarray) to utilize coordless dims’ indices in titles.| row: None or str| dimension to plot ACROSS rows.| None –> subplots will have ncols=1 (nothing varies across a row –> only 1 column).| E.g. if row==’fluid’, then the i’th COLUMN will be fluid i.| [TODO] infer row directly from xarray, somehow?| col: None or str| dimension to plot DOWN columns.| None –> subplots will have nrows=1 (nothing varies down a column –> only 1 row).| E.g. if col==’component’, then the j’th ROW will be component j.| wrap: None or int| wrap row or col dimension after this many images.| can only be provided if provided row or col but not both.| E.g. if row==’fluid’, wrap=4, and input has 10 fluids, will make rows of 4, 4, 2 images.| Any remaining “empty” plots will have their axes hidden.| x, y: None or str| dimension name for the x and y axes of an individual subplot.| None –> infer from the xarray coords. See also: DEFAULTS.PLOT.DIMS_INFER| t: None or str| dimension name for the time axis (for movies).| None –> infer from the xarray coords. See also: DEFAULTS.PLOT.DIMS_INFER|| vmin, vmax: None or value| if provided, use this value for vmin, vmax for all subplots,| and ignore share_vlims and robust.| share_vlims: bool or str (‘all’, ‘row’, ‘col’) (default: False)| whether to share vmin/vmax across ImageSubplots.| True –> use ‘all’| ‘all’ –> share vlims across all image subplots.| ‘row’ –> share vlims across each row of image subplots.| ‘col’ –> share vlims across each column of image subplots.| robust: UNSET, bool, or number between 0 and 50 (default: UNSET)| use np.percentile when determining vmin/vmax, if robust.| For imshow/image plots, this refers to colorbar lims; for line plots, this refers to y lims.| UNSET –> use DEFAULTS.PLOT.ROBUST (default: True).| False –> just use min and max of values, don’t use percentile.| True –> use DEFAULTS.PLOT.ROBUST_PERCENTILE (default: 2.0)| number –> use np.percentile with this percentile for vmin (and 100 - this percentile for vmax).|| additional kwargs go to other places [TODO][DOC] fill in the details.||| To view or adjust plot settings in self, see self.plot_settings, or help(self.plot_settings).|| Method resolution order:| XarraySubplots| MovieSubplots| PlasmaCalcs.plotting.movies.MovieOrganizerNode| PlasmaCalcs.plotting.movies.EmptyMovieNode| PlasmaCalcs.plotting.movies.MoviePlotNode| PlasmaCalcs.plotting.subplots.Subplots| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| PlasmaCalcs.tools.trees.Tree| builtins.object|| Methods defined here:|| __init__(self, xarray, row=None, col=None, *, wrap=None, x=None, y=None, t=None, fig=None, vmin=None, vmax=None, robust=UNSET, share_vlims=False, title=UNSET, title_y=UNSET, suptitle=UNSET, suptitle_y=UNSET, aspect=UNSET, layout=UNSET, cax_mode=UNSET, axsize=UNSET, add_colorbars=True, **kw)|| init_plot(self)| plot for the first time: call init_plot on all nodes,| and organize into a nice tree structure which can be indexed like an array.|| This is fundamentally different from MoviePlotNode.init_plot’s usual purpose,| since this is about calling init_plot on the nodes, not on self.obj.| [TODO] should this function be renamed, for clarity?|| plot_suptitle(self)| adds suptitle (as a MovieText node)| raise PlottingAmbiguityError if suptitle already plotted| (this prevents having multiple suptitle nodes).|| scatter_max(self, **kw_scatter)| plt.scatter() to draw a single marker in each subplot, at the argmax of each subplot’s array.| [TODO] animatable, non-static marker (as child nodes of each image in self)| Here just loops through each image in self.images, calling image.scatter_max().| returns np.array with same shape as self, containing the results of plt.scatter() calls.|| scatter_min(self, **kw_scatter)| plt.scatter() to draw a single marker in each subplot, at the argmin of each subplot’s array.| [TODO] animatable, non-static marker (as child nodes of each image in self)| Here just loops through each image in self.images, calling image.scatter_min().| returns np.array with same shape as self, containing the results of plt.scatter() calls.|| ———————————————————————-| Readonly properties defined here:|| image0| top-left image; images[0,0].|| isels| np.array (dtype=object) of (None or dict of index details), one for each subplot.| E.g. full_array.isel(self.isels[1,4]) == self.images[1,4].array.|| ———————————————————————-| Data descriptors defined here:|| images| alias to nodes|| t_plot_dim| alias to self.image0.t_plot_dim|| x_plot_dim| alias to self.image0.x_plot_dim|| y_plot_dim| alias to self.image0.y_plot_dim|| ———————————————————————-| Methods inherited from MovieSubplots:|| __getitem__(self, i)| returns self.children[i]. If i is a tuple, index repeatedly, e.g. self[i[0]][i[1]][i[2]]…|| __iter__(self)| iterates over self.children.|| ———————————————————————-| Data and other attributes inherited from MovieSubplots:|| DEFAULT_TREE_SHOW_DEPTH = 2|| ———————————————————————-| Methods inherited from PlasmaCalcs.plotting.movies.MovieOrganizerNode:|| __repr__(self)| Return repr(self).|| ———————————————————————-| Methods inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| __call__(self, frame)| update the plot for the given frame. return iterable of all updated artists.| Defining __call__ in this way means self is compatible for direct use by FuncAnimation.|| returns FuncAnimation instance using self as func.| Use kwarg defaults from self.plot_settings, for any kwargs not provided here.|| fps: UNSET, None, or number (default: UNSET)| frames per second.| UNSET –> use DEFAULTS.PLOT.FPS (default: 30).| (Or use value from self.plot_settings, if provided.)| None –> use matplotlib defaults.| blit: UNSET, None, or bool (default: UNSET)| whether to use blitting.| UNSET –> use DEFAULTS.PLOT.BLIT (default: True).| (Or use value from self.plot_settings, if provided.)| if None, use matplotlib defaults.| frames: UNSET, None, int, iterable, or slice (default: UNSET)| passed to FuncAnimation. Tells number of frames or which frames to plot.| If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).| if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.| plt_close: bool| whether to plt.close() before returning the result.| This is useful in Jupyter, where commonly one cell might make a plot,| then call get_animator() to display movie in-line, but not plt.close().| In that case, plt_close=False would display animation & plot|| [TODO] use init_func kwarg to avoid calling self twice for frame 0?|| get_data_at_frame(self, frame)| return dict of data for the given frame, to be used by the MoviePlotElement at self.obj.|| get_nframes(self)| return max of get_nframes_here() for self & all descendants of self.| If any node throws PlottingNframesUnknownError, pretend they said nframes=0.| If all nodes throw PlottingNframesUnknownError, raise the one from self.|| get_nframes_here(self)| return the number of frames that could be in the movie, based on this node.|| init_plots(self, *, plotted_ok=True)| init_plot for self & all descendants with non-None obj.| plotted_ok: bool| True –> skip node if node.plotted.| False –> call init_plot on all nodes with non-None obj.|| save the movie to filename.| RECOMMENDED:| first, self.save(…, frames=N), with small N (e.g. N=5), to test movie formatting.| Troubleshooting: if movie getting cut off,| try plt.subplots_adjust(bottom=0.2, left=0.2, right=0.8, top=0.8),| or even more extreme values if necessary. (0 is bottom/left edge; 1 is top/right edge.)|| frames: UNSET, None, int, iterable, or slice (default: UNSET)| passed to FuncAnimation. Tells number of frames or which frames to plot.| If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).| if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.| fps: UNSET, None, or number (default: UNSET)| frames per second.| UNSET –> use DEFAULTS.PLOT.FPS (default: 30).| (Or use value from self.plot_settings, if provided.)| None –> use matplotlib defaults.| blit: UNSET, None, or bool (default: UNSET)| whether to use blitting.| UNSET –> use DEFAULTS.PLOT.BLIT (default: True).| (Or use value from self.plot_settings, if provided.)| if None, use matplotlib defaults.|| additional kwargs passed to FuncAnimation() or FuncAnimation.save().| returns abspath of the saved movie.|| update_to_frame(self, frame)| update the plot for the given frame. set self.frame=frame.| also calls update_to_frame for all children.| return iterable of all updated artists.|| ———————————————————————-| Class methods inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| help() from builtins.type| prints a helpful message with examples for how to use this cls|| ———————————————————————-| Readonly properties inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| plotted| whether this node’s element has actually been plotted yet.| False before init_plot; True after. Always None if self.obj is None.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.movies.MoviePlotNode:|| ani| alias to get_animator|| fig| the Figure on which self is / will be plotted.|| frame| the currently-plotted frame|| frames| the frames that could be in the movie.| if set to None, will use self.get_nframes() instead.| if set to a slice, will use range(self.get_nframes())[frames] instead.|| plotted_data| the currently plotted data.|| ———————————————————————-| Methods inherited from PlasmaCalcs.plotting.subplots.Subplots:|| __len__(self)| return len(self.axs)|| apply_misc_formatting(self)| apply misc formatting according to self.plot_settings.|| ax_apply(self, f, *, sca=True)| return numpy array of f(ax) applied to each ax. result has dtype=object.| if sca, call plt.sca() before working on each ax.|| ax_images(self, *, fill_value=None)| return array of the image on each ax (or fill_value if no image on that ax).|| colorbars(self, mode=’auto’, **kw_colorbars_at)| create colorbars for each image in self.| mode: True, ‘auto’, ‘all’, ‘row’, slice, or tuple| tells where to create the colorbars.| True –> use mode=’auto’| ‘auto’ –> infer, by checking which images have equal im.get_clim() and im.cmap.| For rows where all image subplots have the same clim and cmap, mode=’row’| (unless the right-most in row has no image; then use mode=’all’).| ‘all’ –> each image gets its own colorbar.| ‘row’ –> each row gets its own colorbar, at the right-most image in the row.| slice or tuple –> self.colorbars_at(slice, …)|| # [TODO] add ‘col’ option, for horizontal colorbars at top of columns.| # [TODO] add ‘single’ option, for one tall colorbar on the right of figure.| # [TODO] make_shared_cax() which makes a tall colorbar with same height as multiple axes.|| colorbars_at(self, slice=None, *, sca=False, missing_ok=True, iter_ax=’all’, location=None, ticks_position=None, pad=None, size=None, kw_add_axes={}, **kw_colorbar)| create colorbars for each ax in self.iter_ax(slice), using self.colorbar(…).| slice: None, int, slice, or tuple| if provided, only include the axes from axs[slice].| when in this mode, (irow, icol) will still correspond to self.axs[(irow, icol)],| (not self.axs[slice][irow, icol]).| sca: bool| whether to set current axis to the last-created colorbar, after the operation is complete.| False –> afterwards, plt.gca() will be restored to what it was before this operation began.| missing_ok: bool| whether it is okay for some axs to not have a mappable.| iter_ax: ‘all’, ‘row’, or ‘col’| which axes to iterate over.| slice will be passed to the appropriate iter func. E.g. ‘row’ –> iter_row(slice, …)|| The remaining kwargs go to self.colorbar(…):| location: None, ‘right’, ‘left’, ‘top’, or ‘bottom’| location of colorbar relative to image.| None –> use DEFAULTS.PLOT.CAX_LOCATION (default: right)| ticks_position: None (default), ‘right’, ‘left’, ‘top’, or ‘bottom’| None -> ticks are on opposite side of colorbar from image.| string -> use this value to set ticks position.| pad: None or number (default 0.01)| padding between cax and ax, as a percentage of ax size.| None –> use DEFAULTS.PLOT.CAX_PAD (default: 0.01)| size: None or number (default 0.02)| size of colorbar, as a percentage of ax size.| None –> use DEFAULTS.PLOT.CAX_SIZE (default: 0.02)| kw_add_axes: dict| passed to make_cax(…, **kw_add_axes)… which passes it to plt.gcf().add_axes().|| colorbars_col(self, icol, **kw_colorbars_at)| create colorbars for each ax in column icol, using self.colorbars_at(…).| Equivalent to self.colorbars_at(icol, iter_ax=’col’, …)|| colorbars_row(self, irow, **kw_colorbars_at)| create colorbars for each ax in row irow, using self.colorbars_at(…).| Equivalent to self.colorbars_at(irow, iter_ax=’row’, …)|| ax.grid(…) on all axs|| hide_empty_axes(self)| hide axes (ax.set_visible(False)) without any data (check via ax.has_data())|| iter_ax(self, slice=None, *, sca=True, restore=True, skip=None)| iterate over axs, one at a time, yielding ((irow, icol), ax) for each ax.| slice: None, int, slice, or tuple| if provided, only include the axes from axs[slice].| when in this mode, (irow, icol) will still correspond to self.axs[(irow, icol)],| (not self.axs[slice][irow, icol]).| sca: bool| if True, call plt.sca(ax) before yielding each ax.| restore: bool| if True, restore original plt.gca() after iteration is stopped.| skip: None or callable of ((irow, icol), ax) –> bool| if provided, skip axes for which skip(irow, icol, ax) returns True.|| iterate over axs in column icol, yielding ((irow, icol), ax) for each ax. See also: self.iter_ax| icol: int or slice| column index(es) to iterate over. Can be negative int, e.g. -1 will be the rightmost column.| bool| if True, call plt.sca(ax) before yielding each ax.| bool| if True, restore original plt.gca() after iteration is stopped.|| iterate over axs in row irow, yielding ((irow, icol), ax) for each ax. See also: self.iter_ax| irow: int or slice| row index(es) to iterate over. Can be negative int, e.g. -1 will be the bottom row.| bool| if True, call plt.sca(ax) before yielding each ax.| bool| if True, restore original plt.gca() after iteration is stopped.|| remove_redundant_labels(self, which=[‘x’, ‘y’], *, ignore_empty=True)| remove labels which are redundant, e.g. ticklabels,| ylabels except in left col, xlabels except in bottom row.| if sharexlike=False or shareylike=False, will not remove the corresponding labels.|| if self.plot_settings[‘polar’], keep xticklabels (i.e. angles) on top row instead of bottom.|| which: iterable of str in (‘x’, ‘y’)| which labels to remove. Default: (‘x’, ‘y’)| ignore_empty: bool| whether to ignore empty axes (checked via ax.has_data())|| sca(self, irow, icol)| set current axis to self.axs[irow, icol]|| set_min_n_ticks(self, min_n_ticks=UNSET)| set_min_n_ticks on all axs.| Use min_n_ticks from self.plot_settings if not provided here.|| set_updater(self, irow, icol, updater)| set updater on ax[irow, icol] to updater|| subplots_adjust(self, **kw)| plt.subplots_adjust, using values from self.plot_settings by default.| Note: adjusts the parameters for self.fig, not necessarily plt.gcf().|| plt.subplots_adjust docs:| ————————-| <function subplots_adjust at 0x727be9461ee0>|| updaters(self, *, fill_value=None)| return array of updaters for each ax (or fill_value if no updater on that ax).|| set xlabel on relevant axs, or as supxlabel.| mode: None or str in (‘edge’, ‘all’, ‘sup’)| None –> use self.xlabel_mode| ‘edge’ –> only set xlabel on axs in bottom row| ‘all’ –> set xlabel on all axs.| ‘sup’ –> set xlabel on self.fig, as supxlabel.| only: bool, default True| if only, then also set xlabel to ‘’ on all other axes.| kwargs are passed to ax.set_xlabel or fig.supxlabel, as appropriate.|| set ylabel on relevant axs, or as supylabel.| mode: None or str in (‘edge’, ‘all’, ‘sup’)| None –> use self.xlabel_mode| ‘all’ –> set ylabel on all axs.| ‘sup’ –> set ylabel on self.fig, as supylabel.| only: bool, default True| if only, then also set ylabel to ‘’ on all other axes.| kwargs are passed to ax.set_ylabel or fig.supylabel, as appropriate.|| ———————————————————————-| Static methods inherited from PlasmaCalcs.plotting.subplots.Subplots:|| color_scheme_matches(im0, im1)| return whether color for im0 matches color scheme for im1|| colorbar(mappable=None, *, cax=None, ax=None, location=None, size=None, pad=None, **kw_colorbar_here)| create a colorbar, like plt.colorbar(), but using Colorbar class instead.| mappable: None or mpl.cm.ScalarMappable| the mappable for this colorbar.| if None, attempt to find it using find_mappable(ax=ax, im=mappable).| cax: None or axes object| the axes for this colorbar.| None –> use make_cax(…), or make cax using mpl_get_cax(…), depending on cax_mode.| kwargs for make_cax would be:| ax, location, sca, ticks_position, pad, size, **kw_add_axes.| cax_mode: UNSET, ‘mpl’, ‘pc’ (default: UNSET)| tells how to make a new axis for a colorbar if one was not provided.| UNSET –> use DEFAULTS.PLOT.CAX_MODE (default: mpl).| ‘mpl’ –> use matplotlib logic, the same exact logic as in plt.colorbar.| ‘pc’ –> use PlasmaCalcs logic; it looks better when using layout=’none’,| however ‘pc’ logic doesn’t play nicely with other layout options yet.| location: None, ‘right’, ‘left’, ‘top’, or ‘bottom’| location of colorbar relative to image.| None –> use DEFAULTS.PLOT.CAX_LOCATION (default: right)| also passed to super().__init__, so that orientation is set appropriately.|| The following are relevant if cax not provided, and using cax_mode=’mpl’:| sca: bool (default False)| whether to adjust the plt.gca() to cax.| False –> plt.gca() will be unchanged by this operation.| ticks_position: None (default), ‘right’, ‘left’, ‘top’, or ‘bottom’| None -> ticks are on opposite side of colorbar from image.| string -> use this value to set ticks position.| pad: None or number (default 0.01)| padding between cax and ax, as a percentage of ax size.| None –> use DEFAULTS.PLOT.CAX_PAD (default: 0.01)| size: None or number (default 0.02)| size of colorbar, as a percentage of ax size.| None –> use DEFAULTS.PLOT.CAX_SIZE (default: 0.02)| kw_add_axes: dict| passed to make_cax(…, **kw_add_axes)… which passes it to plt.gcf().add_axes().|| additional kwargs get passed to matplotlib.colorbar.Colorbar.__init__.|| find_mappable(ax=None, *, im=None)| return the relevant mappable. By default, return plt.gci().| if plt.gci() is None, instead attempt to find a mappable on plt.gca();| if there is exactly 1, return it, else raise PlottingError.| the error will be MappableNotFoundError if 0, else PlottingAmbiguityError.|| providing im uses im instead of plt.gci()| providing ax using ax instead of plt.gca() (only if didn’t provide im)|| ax: None or axes object| if provided, use ax.findobj to find mappable.| (cannot provide both ax and im)| if None, check plt.gci() first, then use findobj if that is also None.| im: None or mappable.| if provided, return it.| if None, attempt plt.gci(); returning it if that is not None|| subplots_figsize(nrows=1, ncols=1, axsize=None, *, left=None, right=None, bottom=None, top=None, wspace=None, hspace=None)| returns figsize to use for subplots so that every subplot has size axsize.| axsize: None, number, or (width, height)| size of a single subplot, in inches.| if None, use DEFAULTS.PLOT.SUBPLOTS_AXSIZE.| if number, use width=height=axsize.| left, right, bottom, top, wspace, hspace: None or number (probably between 0 and 1)| corresponding value that will be used during plt.subplots_adjust;| figsize must be adjust accordingly to account for whitespace between and around subplots.| None –> plt.rcParams[‘figure.subplot.left’], plt.rcParams[‘figure.subplot.right’], etc.| left, right, bottom, top: tell position of edge of subplots grid, as fraction of figure width / height.| wspace, hspace: tell width of padding between subplots, as fraction of axsize width / height.|| ———————————————————————-| Readonly properties inherited from PlasmaCalcs.plotting.subplots.Subplots:|| ax_idx| array of indices (irow, icol), with same shape as axs array, dtype=object|| ncols| number of columns in axs array.|| nrows| number of rows in axs array.|| shape| shape of axs array, as (nrows, ncols).|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.subplots.Subplots:|| axs| array of axes objects.|| cache_state| int, associated with cached results.|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.subplots.Subplots:|| axes_class = UNSET|| ———————————————————————-| Class methods inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| appends note about using self.plot_settings, to cls.__doc__.| if “PlotSettings” or “plot_settings” appears in cls.__doc__, do NOT append this note;| assuming instead that this means the doc already mentions how to use plot_settings.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| __dict__| dictionary for instance variables (if defined)|| __weakref__| list of weak references to the object (if defined)|| ———————————————————————-| Methods inherited from PlasmaCalcs.tools.trees.Tree:|| add_child(self, child)| adds this child (a Tree) to self.children. Also, child.set_parent(self).| returns the added child.|| display(self, show_depth=None, max_depth=None, *, shorthand=None)| display self in html. Includes self.html() and DEFAULTS.TREE_CSS.| show_depth: None or int| max number of layers of tree to show by default (i.e. “not hidden” by default)| None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH| max_depth: None or int| max number of layers of tree to render (even if all layers are “not hidden”).| Anything deeper will not be converted to html string.| None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH| shorthand: None or bool| whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.| True –> use shorthand; replace that^ with: “((N, N, N)) …”| None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND|| enumerate_flat(self, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order,| yielding (index, node) pairs, such that self[index] == node.| Note that index will be a tuple with length == node.depth.| if include_self, yield self first, as: ((), self)).|| flat(self, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order.| if include_self, yield self first.|| flat_branches_until(self, branches_until, *, include_self=False)| returns a generator which iterates over all of self’s descendants, in depth-first order,| but stop looking at descendants on a branch as soon as branches_until(node).| E.g. self.flat_branches_until(lambda node: node.obj==7) will be similar to flat,| but won’t go to any descendants for any node with obj==7.|| if include self, yield self first, and check branches_until(self) before continuing.| otherwise, never check branches_until(self).|| html(self, show_depth=None, max_depth=None, *, shorthand=None)| returns html for displaying self and all of self’s children.| show_depth: None or int| max number of layers of tree to show by default (i.e. “not hidden” by default)| None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH| max_depth: None or int| max number of layers of tree to render (even if all layers are “not hidden”).| Anything deeper will not be converted to html string.| None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH| shorthand: None or bool| whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.| True –> use shorthand; replace that^ with: “((N, N, N)) …”| None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND|| make_child(self, obj)| makes a child of self, with obj as its stored object, and returns the child.|| make_children(self, objs)| make_child(obj) for obj in objs; returns the list of newly made children.|| set_parent(self, parent, *, _internal=False)| sets self.parent = parent. Also, parent.add_child(self), unless _internal=True.| Users should use self.parent = parent instead of calling set_parent directly.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.tools.trees.Tree:|| depth| number of layers above self. (parent, parent’s parents, etc.)| depth = 0 for the node with parent = None.|| height| number of layers below self. (children, children’s children, etc.)| height = 0 for a node with no children.|| parent| parent node of self. None if self is root.| When set to a value, calls self.set_parent(value),| which also updates tracking info appropriately, and updates parent’s children.|| parent_ref| stores parent value, but internally uses weakref to avoid circular references.| Users should always use self.parent instead.|| size| number of nodes in this tree. (here and below)| size = 1 for a node with no children.|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.tools.trees.Tree:|| DEFAULT_TREE_SHORTHAND = None|| DEFAULT_TREE_SHOW_MAX_DEPTH = None
- sum
- caller of function xarray_sum in module PlasmaCalcs.tools.xarray_tools.xarray_agg_statsLike xarray sum but first promotes dims if needed, and accepts ‘keep’ option.
- dim: None, str, or iterable of strs
- apply operation along these dimensions
- keep: None, str, or iterable of strs
- apply operation along all except for these dimensions.(can provide keep or dim, but not both.)
- promote_dims_if_needed: bool
- whether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.
- missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)
- what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.
additional kwargs are passed to array.sum.
- take_along_dimensions
- caller of function take_along_dimensions in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionstake_along_dimensions(array, dimensions, **kw_isel)returns result of taking array along each of these dimensions, in order.result will be a numpy array with dtype=object, shape=(d0, d1, …),where di = len(array.coords[dimensions[i]]).each element of result will be an xarray.DataArray.any dimension can be None –> result shape will be 1 at that dimension, and nothing will be taken.E.g. take_along_dimensions(array, [None, ‘fluid’]) gives array of shape (1, len(fluids)).
- timelines
- caller of class XarrayTimelines in module PlasmaCalcs.plotting.xarray_timelinesclass XarrayTimelines(PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin)| XarrayTimelines(array, t=’t’, dims=None, *, werr=False, cycles=None, short_cycle_ok=False, dmax=UNSET, styles=None, plot=True, label=None, add_legend=True, legend_cols_align=True, legend_max_rows=20, skipna=False, robust=UNSET, ymargin=None, ybounds=None, xincrease=None, **kw_super)|| plotting lines vs time for an xarray.|| array: xarray.DataArray or xarray.Dataset| the array to plot.| Must have coord or dimension with name self.t (probably ‘t’ or ‘snap’).| if dataset, will be converted to DataArray with new dim named ‘variable’.| t: str| name for the time coordinate (to be plotted along the x axis).| if ‘snap’, use int(snap) for snap in array.coords[‘snap’].| if ‘snap_str’, use int(str(snap)) for snap in array.coords[‘snap’]| if looks like ‘{cname}_index’ or ‘log_{cname}’, and not in array yet,| but cname in array, array.pc.fill_coords() to infer the t coord to use.| if any other value, use array.coords[t].values.| if array.coords[t].dtype==object, convert to strs when plotting.| e.g. [Fluid(‘e’), Fluid(‘H+’)] –> ticks with ‘e’, ‘H+’.| dims: None or list-like of str/None objects.| the dimensions; plot one line for each combination of dimensions.| None –> infer, based on array and t.| list-like –> if any element is None, infer it based on the other dims.| werr: bool, ‘bar’, or ‘fill’| if array is a Dataset with ‘mean’ and ‘std’, use this to just plot mean, with error bars.| (else, werr=False is the only valid option.)| True –> equivalent to ‘bar’| ‘bar’ –> plt.errorbar| ‘fill’ –> plt.fill_between| Note: if using werr, can pass any kwargs here, (of plt.errorbar or plt.fill_between) for style.| E.g. capsize=5, elinewidth=3, capthick=5| cycles: None or list-like of dict/Cycler/None objects.| the styles to use for each dimension. Must have length >= len(dims).| E.g. cycles=[dict(color=[‘r’, ‘b’, ‘g’]), dict(linestyle=[‘-’, ‘–‘])]| –> dims[0] will cycle through colors; dims[1] will cycle through linestyles.| None –> use DEFAULTS.PLOT.TIMELINES_CYCLE0, and (if needed) DEFAULTS.PLOT.TIMELINES_CYCLE1.| (default: [None, {‘ls’: [‘-’, ‘–’, ‘:’, ‘-.’, (0, (3, 1, 1, 1, 1, 1))]}])| if len(dims) > 2, this will fail.| list-like –> if any element is None, use plt.rcParams[‘axes.prop_cycle’] for that dimension;| and cannot have more than 1 None cycle.| short_cycle_ok: bool| whether it is okay for cycles to be shorter than the number of points in that dimension.| dmax: UNSET, None, or int| maximum length of a timelines dimension before crashing (with TooManyPlottablesError).| This prevents accidentally asking to make plot with hundreds of lines or more,| e.g. if array has maindims in it due to forgetting to use ‘mean_’.| Not applied to self.t dimension, which can be any length,| since t goes along an axis instead of having 1 line for each.| UNSET –> self.dmax = DEFAULTS.PLOT.TIMELINES_DMAX (default: 10)| None –> no maximum. Use with caution.| int –> maximum length.| styles: None or list-like of dicts.| the styles to use for each line. i’th line will use styles[i].| if any value in styles dicts conflicts with cycles, use value from syles instead of cycle.| plot: bool| whether to call self.plot() immediately, during init.| label: None or str| if provided, prepend this value to all lines’ labels generated by this XarrayTimelines.| (If it doesn’t end with whitespace, add a single space. E.g. “myinfo” –> “myinfo “.)| Useful if plotting timelines on the same axes as other information.| add_legend: bool| whether to plot a legend, by default.| legend_cols_align: bool| whether to align legend cols such that one of the dims (the longest one), is the same in each row.| E.g. if True, and self.dims = [‘fluid’, ‘component’], with more fluids than components,| then ‘fluid’ will be the same across each row.| Only applied if len(self) > legend_max_rows > (number of rows when cols aligned)| legend_max_rows: None or int| maximum number of rows in the legend. Add legend columns if len(self) > legend_max_rows.| (For more precise control, make your own legend after plotting…)| None –> no maximum.| skipna: bool| whether to drop NaN values before plotting each line of values.| robust: UNSET, bool, or number between 0 and 50 (default: UNSET)| use np.percentile when determining vmin/vmax, if robust.| For imshow/image plots, this refers to colorbar lims; for line plots, this refers to y lims.| UNSET –> use DEFAULTS.PLOT.ROBUST (default: True).| False –> just use min and max of values, don’t use percentile.| True –> use DEFAULTS.PLOT.ROBUST_PERCENTILE (default: 2.0)| number –> use np.percentile with this percentile for vmin (and 100 - this percentile for vmax).| Will consider minimum vmin and maximum vmax across all lines, to avoid fully-hiding lines.| ymargin: None or number (greater than -0.5, probably close to 0.05) (default: None)| margin to use for x/y axis, as a fraction of the data interval for that axis.| None –> use matplotlib defaults| (e.g., plt.rcParams[“axes.xmargin”] or [“axes.ymargin”], or 0 if using imshow)| positive number –> pad around the data region, with this much whitespace.| E.g. 0.05 means adding 5% whitespace on each side.| Use this to zoom out.| negative number –> remove this much of the outer parts of the data region.| E.g. -0.2 means removing 20% space from each side.| Use this to zoom in.| For line plots, if also using
robust, ymargin will be applied to the robust y lims.| (margin-related params share the same docstring, but refer to:| ‘xmargin’: x-axis, ‘ymargin’: y-axis, ‘margin’: x and/or y-axis.)| ybounds: None, False, or 2-tuple/iterable of [max_ymin, min_ymax] (default: None)| tells the (maximum ymin, minimum ymax) when determining ylims.| None –> use the current ylims if current_axes_has_data(), else (None, None).| False –> equivalent to (None, None), i.e. ignore this setting.| E.g., overlaying multiple plots; plot 1 from -10 to 10, plot 2 from -5 to 15;| by default would use plot 2 ybounds=(-10, 10) –> final ylims of (-10, 15).| If provided plot 2 ybounds=(-7, 12), would instead have ylims of (-7, 15).| xincrease: None or bool| whether the x-axis should increase from left to right.| None –> False if monotonically nonincreasing. I.e., False if all(t[i+1] <= t[i]), else True.| (“if t values are obviously inverted, take it as a hint from user to do xincrease=False”)|| Additional kwargs go to super().__init__, and eventually to a plotting routine. Options include:| - self.plot_settings.get_mpl_kwargs(‘plt.legend’)| - self.plot_settings.get_mpl_kwargs(‘plt.plot’)| - self.plot_settings.get_mpl_kwargs(‘plt.errorbar’) # if werr=True or ‘bar’| - self.plot_settings.get_mpl_kwargs(‘plt.fill_between’) # if werr=’fill’|| (Note that any plot settings which also appear in cycles will use the cycles values,| e.g. if ‘linestyle’ appears in cycle but also in kwargs, use the cycle value instead.)|| — Examples —| import PlasmaCalcs as pc|| # basic usage:| array.pc.timelines() # make timelines plot with default settings.|| # alternative call signature:| pc.XarrayTimelines(array) # same result as above ^|| # specify cycle:| # for dims[0], use plt.rcParams[‘axes.prop_cycle’];| # for dims[1], use a gradient in alpha (instead of the default, which is different linestyles):| array.pc.timelines(cycles=[None, dict(alpha=np.linspace(1, 0.3, 10)])|| # use linewidth and linestyle in cycle for dims[1], use colors for dims[0]:| array.pc.timelines(cycles=[None, dict(linewidth=[5, 4, 3, 2], linestyle=[‘-’, ‘–’, ‘:’, ‘-.’])])|| # specify handlelength (for legend, ensure lines are long enough to see):| array.pc.timelines(handlelength=5)|| Method resolution order:| XarrayTimelines| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| builtins.object|| Methods defined here:|| __init__(self, array, t=’t’, dims=None, *, werr=False, cycles=None, short_cycle_ok=False, dmax=UNSET, styles=None, plot=True, label=None, add_legend=True, legend_cols_align=True, legend_max_rows=20, skipna=False, robust=UNSET, ymargin=None, ybounds=None, xincrease=None, **kw_super)|| __len__(self)| returns number lines which self would plot if plotted.|| add_labels(self)| add labels to plot, based on self.array.|| get_effective_data_interval(self, *, robust=UNSET)| returns (vmin, vmax) taken across all lines in self.| If robust, take min vmin(line) and max vmax(line) across all lines.|| robust: {robust}| If UNSET, use self.plot_settings.get(‘robust’). (if still UNSET, use behavior described above.)|| iter_dimpoints(self)| iterates through points across all dimensions.| Yields (dimsel, style) pairs, where:| dimsel = dict of {dim: (i of dim at this point)} for dim in self.dims| style = dict of {matplotlib kwarg: value} which are relevant at this point.|| legend(self, ncols=None)| plot the legend for the current plot, via plt.legend().| legend anchored to upper right corner of plot, outside the axes.| if self.legend_max_rows is not None:| put a limit on nrows.| if self.legend_cols_align is True:| align the columns such that (the longest) one of the dims is the same in each row.| Only applied if len(self) > legend_max_rows > (number of rows when cols aligned)| ncols: None or int| number of columns to use in the legend.| None –> picks a decent-looking value, based on self.legend_max_rows.|| For more precise legend control, use plt.legend() instead.|| plot(self, *, legend=UNSET, add_labels=True, robust=UNSET, ymargin=None, ybounds=UNSET, **kw_plot)| plot the lines vs time. Probably via plt.plot.| (if self.werr, might instead use plt.errorbar or plt.fill_between.)|| legend: UNSET or bool| whether to plt.legend().| UNSET –> use legend = self.add_legend (default: True)| note: if all labels are None or empty string, will never attempt to add legend.| add_labels: bool| whether to self.add_labels() to plot, based on self.array:| xlabel (self.t), and ylabel if known (self.array.name).| Also put units on those labels if self.array.attrs[‘units’] is provided.| robust: {robust}| If robust, take min vmin(line) and max vmax(line) across all lines.| If UNSET, use self.plot_settings.get(‘robust’). (if still UNSET, use behavior described above.)| ymargin: {ymargin}| If None, use self.plot_settings.get(‘ymargin’) instead.| ybounds: {ybounds}| if UNSET, use self.plot_settings.get(‘ybounds’) instead.|| set_ylim(self, *, robust=UNSET, ymargin=None, ybounds=UNSET)| sets plt.ylim() to a nice range for viewing all lines from self.| robust: {robust}| If robust, take min vmin(line) and max vmax(line) across all lines.| If UNSET, use self.plot_settings.get(‘robust’). (if still UNSET, use behavior described above.)| ymargin: {ymargin}| If None, use self.plot_settings.get(‘ymargin’) instead.| ybounds: {ybounds}| if UNSET, use self.plot_settings.get(‘ybounds’) instead.|| ———————————————————————-| Class methods inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| appends note about using self.plot_settings, to cls.__doc__.| if “PlotSettings” or “plot_settings” appears in cls.__doc__, do NOT append this note;| assuming instead that this means the doc already mentions how to use plot_settings.|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin:|| __dict__| dictionary for instance variables (if defined)|| __weakref__| list of weak references to the object (if defined)
- unit_vector
- caller of function unit_vector in module PlasmaCalcs.quantities.patterns.vector_arithmeticunit_vector(A)return a unit vector in the direction of A. Equivalent: A / |A|
- unmask
- caller of function xarray_unmask in module PlasmaCalcs.tools.xarray_tools.xarray_masksxarray_unmask(array, mask=None, stackdim=’_mask_stack’, *, store_mask=False, as_array=None, reindex=True, _upcast_bool=True)unmask (i.e., unstack) a masked (and stacked) xarray object.array.pc.unmask(mask) is equivalent to mask.pc.demask(array).See also: xarray_unmask_var, to get a single unmasked var from a Dataset.
- array: xarray.DataArray or xarray.Dataset
- object to unmask.
- mask: None or xarray.DataArray
- the (unstacked) mask. If None, use mask stored in array[‘_mask’] (and array must be a Dataset).
- stackdim: str, default ‘_mask_stack’
- dimension along which the mask stacking occurred.
- store_mask: None or bool
- whether to store full mask as a data_var in result.None –> True if result would otherwise be a Dataset, else FalseTrue –> result will be a Dataset with full mask in data_var ‘_mask’.False –> do not store mask in result.
- as_array: None or bool
- whether to ensure result is a DataArray.None –> True if result would be a Dataset with a single data_var, else False.True –> result will be a DataArray; crash if not possible(e.g. crash if output would have multiple vars, or if store_mask=True).False –> result will be a Dataset, unless input was a DataArray and store_mask=False.
- reindex: bool
- whether to result.reindex_like(mask). Highly recommended, but not required…
- _upcast_bool: bool
- whether to upcast dtype=bool array or data_vars to int8 before unstacking.when False, unstacking produces a dtype=object array due to the nans for missing values.(when True, unstacking makes dtype=float32, using 0 for False, 1 for True, nan for nan.)
In the simplest case (mask not None; array=non-boolean DataArray with MultiIndex in stackdim),this method behaves just like array.unstack(stackdim).reindex_like(mask).All the other stuff here helps to handle more complicated cases,e.g. Dataset containing mask, possibly without MultiIndex along stackdim.
- werradd
- caller of function xarray_werradd in module PlasmaCalcs.tools.xarray_tools.xarray_werr_statsxarray_werradd(A, B, *, require_std=True)returns dataset of ‘mean’ and ‘std’ for A + B, including error propagation.Assumes independent errors and applies the “standard” formula:mean(A + B) = mean(A) + mean(B)std(A + B) = sqrt(std(A)**2 + std(B)**2)
- A, B: xarray.Dataset or DataArray; B can also be any other value.
- Dataset –> mean = ds[‘mean’]; std = ds.get(‘std’, default=0).else –> assume it represents ‘mean’, with std=0.
- require_std: bool
- whether to require at least one of A or B to have ‘std’.if True and std missing from both, crash with InputError.
- werrdiv
- caller of function xarray_werrdiv in module PlasmaCalcs.tools.xarray_tools.xarray_werr_statsxarray_werrdiv(A, B, *, require_std=True)returns dataset of ‘mean’ and ‘std’ for A / B, including error propagation.Assumes independent errors and applies the “standard” 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)
- A, B: xarray.Dataset or DataArray; B can also be any other value.
- Dataset –> mean = ds[‘mean’]; std = ds.get(‘std’, default=0).else –> assume it represents ‘mean’, with std=0.
- require_std: bool
- whether to require at least one of A or B to have ‘std’.if True and std missing from both, crash with InputError.
- werrmul
- caller of function xarray_werrmul in module PlasmaCalcs.tools.xarray_tools.xarray_werr_statsxarray_werrmul(A, B, *, require_std=True)returns dataset of ‘mean’ and ‘std’ for A * B, including error propagation.Assumes independent errors and applies the “standard” 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)
- A, B: xarray.Dataset or DataArray; B can also be any other value.
- Dataset –> mean = ds[‘mean’]; std = ds.get(‘std’, default=0).else –> assume it represents ‘mean’, with std=0.
- require_std: bool
- whether to require at least one of A or B to have ‘std’.if True and std missing from both, crash with InputError.
- werrsub
- caller of function xarray_werrsub in module PlasmaCalcs.tools.xarray_tools.xarray_werr_statsxarray_werrsub(A, B, *, require_std=True)returns dataset of ‘mean’ and ‘std’ for A - B, including error propagation.Assumes independent errors and applies the “standard” formula:mean(A - B) = mean(A) - mean(B)std(A - B) = sqrt(std(A)**2 + std(B)**2)
- A, B: xarray.Dataset or DataArray; B can also be any other value.
- Dataset –> mean = ds[‘mean’]; std = ds.get(‘std’, default=0).else –> assume it represents ‘mean’, with std=0.
- require_std: bool
- whether to require at least one of A or B to have ‘std’.if True and std missing from both, crash with InputError.
- where
- caller of function xarray_where in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_where(array, cond, other=UNSET, *, drop=False, skip_if_no_matching_dims=True)like xarray’s builtin where, but return array unchanged if it has no dims matching cond.
- array: xarray.DataArray or xarray.Dataset
- array to apply condition to.
- cond: xarray.DataArray, xarray.Dataset, or callable
- Locations at which to preserve array’s values. Must have dtype=bool.callable –> replace with cond(array).
- other: UNSET, scalar, DataArray, Dataset, or callable, optional
- Value to use for locations in array where cond is False.By default, these locations are filled with NA.callable –> replace with other(array).UNSET –> do not pass this arg to xarray.where()
- drop: bool, default: False
- If True, coordinate labels that only correspond to False values ofthe condition are dropped from the result.
- skip_if_no_matching_dims: bool, default: True
- If True, return array unchanged if it has no dims matching cond.if Dataset, keep data_vars unchanged if they have no dims matching cond.If False, return array.where(cond, other=other, drop=drop) directly.
- where_finite
- caller of function xarray_where_finite in module PlasmaCalcs.tools.xarray_tools.xarray_miscxarray_where_finite(array)returns array, masked with NaNs anywhere that the values are not finite.