PlasmaCalcs.tools.xarray_tools.xarray_accessors.pcArrayAccessor
- class PlasmaCalcs.tools.xarray_tools.xarray_accessors.pcArrayAccessor(xarray_obj)
Bases:
pcAccessoraccess attributes of DataArrays e.g. xr.DataArray.pc.differentiate(…).for more help see help(xr.DataArray.pc).- __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
- argsort
- caller of function xarray_argsort in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_argsort(array, dim, newname=’{dim}_sort’, *, ascending=True, nkeep=None, promote_dims_if_needed=True, squeeze=True, kind=None)argsort for xarray.DataArray; returns indexes along dim which would sort array along dim.Drops original coords along dim, because the output along dim is now the indexes;result[i] corresponds to coord value array[dim][result[i]], not array[dim][i].Good examples to consider (where result=xarray_argsort(array, dim)):(1) sortarr = array.isel(dim=result) to get sorted array,which will have dim as a multidimensional coordinate with same dims as argsort result,and values telling original values of dim, sorted appropriately.(2) sortarr = array.isel(dim=result.isel(newdim=slice(0, N)) to get sorted array,similar to example (1), but only keeping first N lowest values(or N highest values if ascending=False when getting argsort result).
- array: xarray.DataArray
- array to argsort.
- dim: str
- dimension along which to sort.
- newname: str
- result dim will be replaced by newname.format(dim=dim). Default: ‘{dim}_sort’.
- ascending: bool
- result sorted in ascending order if True, descending if False.
- nkeep: None or int
- number of sorted values to keep. E.g. nkeep=2 –> keep only the first 2 values.equivalent to using result.isel(newdim=(0, nkeep)), where newdim=newname.format(dim=dim).
- 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.
- squeeze: bool
- whether to drop redundant dims for argsort result.This means any dims with np.all(array==array.isel(dim=0)). (This includes dims with len=1.)
- kind: None or str from {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}
- sorting algorithm. Passed directly to numpy.argsort; see help(numpy.argsort) for details.
- 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.
- assign_self_as_coord
- caller of function xarray_assign_self_as_coord in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_assign_self_as_coord(array)return copy of array with coord named array.name, equal to array values.
Equivalent: array.assign_coords({array.name: array})
- 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
- broadcastable
- caller of function xarray_broadcastable_array in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsxarray_broadcastable_array(array, dims)return broadcastable version of array, standardizing dims to the list provided.missing dims will be expanded to size 1. result dims will be put in this order.
- dims: list of str
- result will have all these dims, in this order, with size 1 if not present in array.if any array.dims not present in dims, raise DimensionKeyError.
- closeness
- caller of function xarray_closeness in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsxarray_closeness(array, dim=None)computes “closeness” along each dim: (array.isel(dim=0)/array).std()Result is a dataset with one scalar data_var telling closeness of each dim.
- Note: the std() is always taken across ALL dims of the array.
- [TODO] allow to keep some dims?
- dim: None, str, or list of strs
- if provided, only consider these dims.
See also: xarray_squeeze_close
- cmax
- caller of function xarray_cmax in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_cmax(array, coord, where=UNSET, *, promote_dims_if_needed=True)return (array of) coord value(s) at array.argmax(dim=dim associated with coord).coord must be a dimension, or associated with a single 1D dimension.
- array: xarray.DataArray
- array to find max value in.
- coord: str
- coord along which to find max.
- 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.
see also: xarray_max_coord_where
- cmin
- caller of function xarray_cmin in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_cmin(array, coord, where=UNSET, *, promote_dims_if_needed=True)return (array of) coord value(s) at array.argmin(dim=dim associated with coord).coord must be a dimension, or associated with a single 1D dimension.
- array: xarray.DataArray
- array to find minimum value in.
- coord: str
- coord along which to find min.
- 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.
see also: xarray_min_coord_where
- 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
- contour
- caller of class XarrayContour in module PlasmaCalcs.plotting.contoursclass XarrayContour(PlasmaCalcs.plotting.movies.MoviePlotNode, PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin)| XarrayContour(array, t=None, *, x=None, y=None, ax=None, blur=None, init_plot=True, label=UNSET, **kw_super)|| MoviePlotNode of contours.| stores an XarrayContourPlotElement & has methods for plotting & updating the plot.| “contour” refers to a matplotlib.contour.QuadContourSet object, e.g. the result of plt.contour.|| Troubleshooting jagged contours? Try using blur=1 or larger!|| array: xarray.DataArray, probably ndim=3.| the data to be plotted. if ndim=2, can still plot, but nothing to animate.| t: None or str| the array dimension which frames will index. E.g. ‘time’.| None -> infer from array & any other provided dimensions.| x, y: None or str| if provided, tells dimensions for the x, y plot axes.| None -> infer from array & any other provided dimensions.| 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.| blur: None or number| if non-None, apply gaussian filter to array before storing it;| use sigma=blur, and only blur along x_plot_dim & y_plot_dim.| e.g. equivalent to arr.pc.blur([‘x’, ‘y’], sigma=blur).pc.contour(…, blur=None)| This is useful if the contours are too jagged / noisy!|| 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.)|| label: UNSET or str (default: UNSET)| label for this plot element, to be included in a legend.| For xarrays, will label.format(**xarray_nondim_coords(array)).| legend_handle_kw: UNSET or dict (default: UNSET)| any additional kwargs to use when creating legend handles.|| 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() if XarrayImage (or other single-array plot).| use XarraySubplotTitlesInferer.infer_title() if XarraySubplots (or other multi-array plot).| 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:| XarrayContour| 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, blur=None, init_plot=True, label=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 XarrayContourPlotElement 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.axes.Axes where this Contour is plotted.|| fig| figure where this Contour is plotted.|| handle| creates legend handle to use for this Contour.|| ———————————————————————-| Data and other attributes defined here:|| element_cls = <class ‘PlasmaCalcs.plotting.contours.XarrayContourPlotE…| plot contours of 2D data.|| array: xarray.DataArray, probably ndim=2.| the data to be plotted.| add_colorbar: UNSET or bool (default: UNSET)| if provided, default for add_colorbar when making xarray plots.| colorbar_linewidth: UNSET, None, int, list-like, or 2-tuple of None/int. (default: UNSET)| linewidth for lines in contour colorbar.| UNSET –> use DEFAULTS.PLOT.COLORBAR_LINEWIDTH (default: (4, None)).| None –> use same width as contour lines.| int or list-like –> use this as the linewidth| (as per matplotlib.collections.LineCollection.set(linewidth=…))| tuple –> defines (min, max) linewidths; use None for no bound.| E.g. (4, None) says “for thinner lines use 4; others same as contour lines”.| colorbar_linestyle: UNSET, None, or str (default: UNSET)| linestyle for lines in contour colorbar.| UNSET –> use DEFAULTS.PLOT.COLORBAR_LINESTYLE (default: None).| None –> use same style as contour lines.| colorbar_lines_set: UNSET, or dict (default: UNSET)| any additional attrs to set for contour colorbar lines,| via cbar.ax.get_children()[1].set(…)| label: UNSET or str (default: UNSET)| label for this plot element, to be included in a legend.| For xarrays, will label.format(**xarray_nondim_coords(array)).| UNSET –> no label.| legend_handle_kw: UNSET or dict (default: UNSET)| any additional kwargs to use when creating legend handles.|| contourf: bool (default: False)| whether to use filled contours (i.e., plt.contourf) or not (i.e., plt.contour).||| 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’]}.
- 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, *, stddev=False)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.
- stddev: bool
- curve_fit
- caller of function xarray_curve_fit in module PlasmaCalcs.tools.xarray_tools.xarray_scixarray_curve_fit(array, f, dim, *, stddev=True, werr_samples=1000, werr_seed=0, promote_dims_if_needed=True, pnames=None, pbounds=None, bounds=UNSET, **kw_curve_fit)scipy.optimize.curve_fit(f, xdata=array[dim], ydata=array).Except, iterate over all other dims in array.E.g. arr.curve_fit(‘t’, f) for arr with ‘t’ and ‘fluid’ dims–> result reduces ‘t’ dim but retains ‘fluid’ dim.
- array: xarray.DataArray or Dataset
- data to fit.Currently, Dataset allowed only if it has ‘mean’ and ‘std’ data_vars, when
stddev=True,in which case will sample the implied gaussians (via np.random.normal),N=``werr_samples`` times, performing N fits to f,reporting the mean and stddev of each fit param across all N fits, andignoring scipy standard deviation info about params from each individual fit. - dim: str
- dim to fit along.
- f: callable like f(x, param1, param2, …)
- function to fit.
- stddev: bool
- whether to include data_var ‘stddev’ telling standard deviation of the fit.
- werr_samples: int
- number of fits to do if
arrayis a Dataset with ‘mean’ and ‘std’ vars, whenstddev=True,in which case result will tell mean and stddev of each fit param across all N fits,and ignore scipy standard deviation info about params from each individual fit.(Implemented this because default scipy linear least squares fitting with errorbarsjust weights each point’s important by inverse of error bar,which highly favors points with small errors.That default does NOT correspond to the results of “repeating the experiment” N times,where “the experiment” is gathering data then fitting,and then asking “what is the mean and stddev of fit params across all N experiments?”.However, using werr_samples DOES correspond to “repeating the experiment” N times.) - werr_seed: None or any object, default 0
np.random.seed(werr_seed)beforehand, if doing werr_samples (with Datasetarray).Default 0 ensures reproducible results.None –> don’t call np.random.seed beforehand. Will give different results each time.- 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.
- pnames: None or list of str
- names of params. If provided, ‘param’ coord will be assigned these names.
- pbounds: None or list of [None, callable, or 2-tuple of value, None, or callable]
- bounds for each parameter. Provide
pboundsorbounds, but not both.None –> no bounds provided.Each bound can be:callable –> call as bound(array, dim) (after doing array.pc.ensure_dims(dim)).None –> use (-np.inf, np.inf).2-tuple –> (lower, upper).callable –> use lower(array, dim) / upper(array, dim)None –> use -np.inf / np.inf. - bounds: UNSET or (list of lower bounds, list of upper bounds)
- bounds, formatted as expected by scipy curve_fit.Provide
pboundsorbounds, but not both.
additional kwargs go to scipy.optimize.curve_fit.returns xarray.Dataset with data_vars:
- demask
- caller of function xarray_demask_from_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masksxarray_demask_from_mask(mask, array, stackdim=’_mask_stack’, *, store_mask=False, as_array=None, reindex=True, _upcast_bool=True)unmask (i.e., unstack) a masked (and stacked) xarray object, using this mask.Equivalent to xarray_unmask(array, mask=mask, …)
- mask: xarray.DataArray
- the (unstacked) mask.
- array: xarray.DataArray or xarray.Dataset
- object to unmask.
- 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.)
- demote_index_coords
- caller of function xarray_demote_index_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_demote_index_coords(array, coords=None)demote ‘{cname}_index’ dims to coords by promoting ‘{cname}’ coords to dim instead.Skips index dims for which associated ‘{cname}’ coord does not exist.
- coords: None, str, or list of str
- coords (with or without ‘_index’ suffix) to consider demoting to dims.None –> all index coords.str –> treat as list of 1 element.
- 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’.
- dtype_object_to_str
- caller of function xarray_dtype_object_to_str in module PlasmaCalcs.tools.xarray_tools.xarray_miscxarray_dtype_object_to_str(array)convert array with dtype=object to dtype=str, by doing str(x) for every x in array.
- 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() if XarrayImage (or other single-array plot).| use XarraySubplotTitlesInferer.infer_title() if XarraySubplots (or other multi-array plot).| 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
- faces_3D
- caller of function xarray_faces_3D in module PlasmaCalcs.plotting.faceplotxarray_faces_3D(array, ikeep=0, *, dims=(‘x’, ‘y’, ‘z’))infer the faces (at 0th index of dims) of a 3D xarray.DataArray.
- ikeep: int
- select ikeep’th value in the removed-dimension for each face.E.g. if ikeep=0: x_y=array.isel(z=0), x_z=array.isel(y=0), and y_z=array.isel(x=0).
- dims: 3-tuple of str
- the names of the dimensions for the x, y, and z faces.also affects resulting data var names,e.g. dims=’abc’ –> result will have ‘a_b’ instead of ‘x_y’.
returns xarray.Dataset with data vars x_y, x_z, y_z.
- property fft
- alias to fftN
- fftN
- caller of function xarray_fftN in module PlasmaCalcs.tools.fft_tools.xarray_fftxarray_fftN(array, dim=None, ds=None, *, rad=None, abs=False, slices={}, keep=UNSET, half=UNSET, step=UNSET, missing_slices=UNSET, **kw_np_fftn)calculates fft(array) along N dimensions.shifts frequencies such that the 0-frequency is in the center.replaces result dimensions & coordinates appropriately, to indicate which dims were fft’d.
- dim: None, str, or iterable of strs
- coordinates(s) to take fft over.Can be pre-fft or post-fft names. (e.g. ‘x’, ‘freq_x’, ‘freqrad_x’, ‘k_x’)promote_dim(array, coord) for any non-dimension coordinates, as needed.None –> equivalent to array.dimsstr –> just this coordinate.iterable of strs –> just these coordinates.
- ds: None, number, or dict of {dim: d}
- spacing between elements of array (pre-transform), along each dim.if number, use the same value for all dims.if None, infer via array.coords[dim].diff(dim) for each dim(requires evenly-spaced coordinates in dim; spacing checked with np.allclose)
- rad: None or bool
- whether to convert frequencies to “radians” by multiplying them by 2 * pi.E.g., for fft in space, rad=False gives 1/wavelength; rad=True gives wavenumber k.if None, infer from dim if any post-fft names provided, else default to False.
- abs: bool
- if True, return np.abs(result), instead.
- slices: dict or FFTSlices
- instructions for slicing the final result.Can provide {cname: indexer} instructing to slice post-fft dimensionassociated with cname, via indexer. (cname can be pre-fft or post-fft name.)These understand fractional indexing: can provide a fractional valuebetween -1 and 1, to use that fraction of the length along the relevant dimension.Can also provide
keep,half,step, and/ormissing_slices, here (Or, as kwargs).(raise InputConflictError if any provided in both places and have conflicting values.)See those kwargs for more details. - keep: None, True, dict, or number in 0 < keep <= 1
- implies the fraction of each dimension to keep.(ignored for any dimensions which already have a slice specified.)e.g. keep=0.4 with length=1000 would result in slice(300, 700),since that keeps 400 out of 1000 points, and is centered at 1000/2.None –> ignored.True –> use keep = DEFAULTS.FFT_KEEP (default: 0.4).dict –> different value in each dimension;keys can be pre-fft OR post-fft dimension names.UNSET –> use None.
- half: None, str, or iterable of strs
- dimensions along which to keep only the right half of the result.(ignored for any dimensions which already have a slice specified.)None –> ignored.str or iterable of strs –>can be pre-fft OR post-fft dimension name(s).Applied after keep, e.g. keep=0.4, length=1000, half=’x’ –> slice(500, 700) for x.UNSET –> use None.
- step: None, dict, int, or non-integer between -1 and 1
- step to take along each dim.(ignored for any dimensions which already have a slice specified.)fractional value –> use fraction of length (e.g. 0.01 –> 1% of dim length), min |step|=1.negative –> reverses direction (and swaps start & stop for the slice)None –> equivalent to using step=1.dict –> different value in each dimension;keys can be pre-fft OR post-fft dimension names.UNSET –> use None.
- missing_slices: ‘ignore’, ‘warn’, or ‘raise’
- tells how to handle keys not matching any fft-related coordinate.‘ignore’ –> silently ignore these keys. This is the default.‘warn’ –> issue a warning.‘raise’ –> raise an error.UNSET –> use ‘ignore’
additional kwargs passed to np.fft.fftn.returns result of fftn(…), shifted such that the 0-frequency is in the center,and with the relevant dimensions renamed as specified.
- 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’, ‘log_{coord}’, or ‘str_{coord}’,create them via xarray_index_coords, xarray_log_coords, or xarray_str_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
- property ifft
- alias to ifftN
- ifftN
- caller of function xarray_ifftN in module PlasmaCalcs.tools.fft_tools.xarray_fftcalculates ifft(array) along N dimensions.shifts positions such that the 0-position is in the center.replaces result dimensions & coordinates appropriately, to indicate which dims were ifft’d.For convenience, all coordinate names can be pre-fft OR post-fft names,e.g. ‘x’, ‘freq_x’, ‘freqrad_x’, or ‘k_x’.“post-fft” names look like ‘freq_dim’, ‘freqrad_dim’,or any value in DEFAULTS.FFT_FREQ_RAD_DIMNAMES.values(), e.g. ‘k_x’.
- Caution: ifft(fft(arr)) == arr only approximately, due to floating point rounding errors.
- Can at least ensure coordinate alignment by providing ds during ifft(fft(arr), ds=…)
- dim: None, str, or iterable of strs
- coordinates(s) of array to take ifft over.promote_dim(array, coord) for any non-dimension coordinates, as needed.None –> equivalent to array.dims
- df: None, number, or dict of {dim: d}
- spacing between elements of array (in frequency-space).None –> infer from ds if provided, else infer from array.number –> use this as df for all dims.
- rad: None or bool
- if True, interpret frequency-spacing (df) like it is “in radians”,dividing it by 2 * pi before converting to position-space.None –> infer rad from names of the dims being ifft’d.
- ds: None, number, or dict of {dim: d}
- spacing between elements of result (in position-space), along dims from result.number –> use this as ds for all dims.None –> infer from df if provided, else infer from array.Note: provide ds to guarantee ifft(fft(arr)) == arr, exactly;otherwise position coords might include small rounding errors.
- x0: None, number, or dict of {dim: value}
- if provided, alter position-space coordinates by adding a constant offset,such that the 0’th position for each dim equals x0[dim].number –> apply the same number to all dims.iterable –> use these numbers; kwarg
dimmust also be provided as an iterable of strs.dict –> dict of {dim: x0} specifying the value associated with each dim
- 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() if XarrayImage (or other single-array plot).| use XarraySubplotTitlesInferer.infer_title() if XarraySubplots (or other multi-array plot).| 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)| use XarrayScatter to plt.scatter() a single marker, at the argmax of self.array.| animatable (e.g. different max for each frame); does self.add_child(scatter result)| returns XarrayScatter object (which got added as child of self).|| see also: xarray_scatter_max (or, array.pc.scatter_max)|| scatter_min(self, **kw_scatter)| use XarrayScatter to plt.scatter() a single marker, at the argmin of self.array.| animatable (e.g. different min for each frame); does self.add_child(scatter result)| returns XarrayScatter object (which got added as child of self).|| see also: xarray_scatter_min (or, array.pc.scatter_min)|| scatter_where(self, condition, **kw_scatter)| use XarrayScatter to plt.scatter() markers where condition is True.| animatable (e.g. different condition for each frame); does self.add_child(scatter result)| returns XarrayScatter object (which got added as child of self).|| condition: callable or DataArray of bools| callable –> use condition(self.array)| DataArray –> ignore self.array entirely.|| For x, y, t plot dims, uses self.x_plot_dim, self.y_plot_dim, self.t_plot_dim.|| see also: xarray_scatter_where (or, array.pc.scatter_where)|| Example:| xim = array.pc.image(…)| xim.scatter_where(lambda arr: arr > 7.5) # marker at all points where arr > 7.5| xim.save(filename) # save animation to filename (if xim.t_plot_dim is not None)|| ———————————————————————-| Data descriptors defined here:|| ax| mpl.axes.Axes where this XarrayImage is plotted, or None if not plotted.|| cbar| the mpl.colorbar.Colorbar of this XarrayImage.| None if image not plotted.| False if image plotted but does not have an associated colorbar.|| fig| figure where this XarrayImage is plotted, or None if not plotted.|| im| mpl.cm.ScalarMappable object of this XarrayImage, or None if not 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.|| min_n_ticks: UNSET, None, int, or 2-tuple of ints (default: UNSET)| minimum number of ticks to use on plot axes, e.g. x & y axes.| UNSET –> use DEFAULTS.PLOT.MIN_N_TICKS (default: 3).| None –> use matplotlib default (probably 2).| int –> use this number of ticks.| tuple –> provides (min for x, min for y).| min_n_ticks_cbar: UNSET, None, int, or 2-tuple of ints (default: UNSET)| minimum number of ticks to use on colorbars.| UNSET –> use DEFAULTS.PLOT.MIN_N_TICKS_CBAR (default: 3).| None –> use matplotlib default (probably 2).| int –> use this number of ticks.| tuple –> provides (min for horizontal cbars, min for vertical cbars).|| 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.
- interp_inverse
- caller of function xarray_interp_inverse in module PlasmaCalcs.tools.xarray_tools.xarray_scixarray_interp_inverse(array, interpto=None, output=None, *, promote_dims_if_needed=True, assume_sorted=None, assume_sorted_values=None, method=None, kw_interp=None, **interpto_as_kw)interpolate a DataArray but using the array values as one of the interpolation variables;the result is the array of the unused interpolation coordinate.Example: if array has dims {‘x’, ‘y’} and name ‘T’, and interpto specifies ‘x’ and ‘T’,then result will be a DataArray with dims {‘x’, ‘T’} and values for ‘y’.Special case: if interpto specifications are single values,the result will be scalar along that key instead of a dimension,e.g. if interpto[‘x’] = 7 (as a opposed to a 1D array like [1,2,3]),then result would have coordinate ‘x’=7 but not have an ‘x’ dimension.[EFF] note: inefficient if choosing many values along vars other than array.name.each result value along those vars corresponds to its own interp call.The internal steps are roughly:(1) array.interp(all interpto vars except array.name)(2) array.assign_coords({array.name: array})(3) for each index along all interpto vars except array.name:tmp = array.isel(index).interp({array.name: interpto[array.name]})result[index] = tmp[output var][TODO] still need to implement step 3 for 3D+ arrays instead of only 2D or less.
- array: xarray.DataArray
- must have non-None array.name.
- interpto: None or dict
- dictionary of {var: value or 1D array of values} to interpolate to.Keys must correspond to array.name, and coords for all except 1 dim of array.None –> provide interpto dict as kwargs to this function.
- output: None or str
- name for the result variable.None –> use the key from array.dims which is missing from interpto (after xarray_ensure_dims).
- 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.
- assume_sorted: None or bool
- whether to assume_sorted during step (1),i.e. during the initial interp for all interpto vars except array.nameNone –> assume_sorted if xarray_is_sorted.True –> assume_sorted without checking. CAUTION: only do this if you’re 100% sure!False –> don’t assume sorted. May be noticeably slower for large arrays.
- assume_sorted_values: None or bool
- whether to assume_sorted during step (3),i.e. during the interp using array.name as a coordinate.None –> assume_sorted if xarray_is_sorted. check at each index in step 3;if False multiple times in a row, stop checking and just assume False.True –> assume_sorted without checking. CAUTION: only do this if you’re 100% sure!False –> don’t assume sorted. May be noticeably slower for large arrays.
- method: None or str
- method to pass to xarray.interp for all interpolations.if None, use xarray.interp method default.
- kw_interp: None or dict
- if provided, pass these kwargs to all calls of xarray.interp.These will eventually go to the internal interpolator method e.g. from scipy.
interpto_as_kw: optionally, provide interpto dict as kwargs to this function.
- is_sorted
- caller of function xarray_is_sorted in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_is_sorted(array, *, increasing=True)returns whether array is sorted; array must be 1D.
- increasing: bool
- True –> check for increasing order. vals[i] <= vals[i+1]False –> check for decreasing order. vals[i] >= vals [i+1]
- 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
- lims_patch
- caller of class XarrayLimsPatch in module PlasmaCalcs.plotting.patchesclass XarrayLimsPatch(XarrayRectanglePatch)| XarrayLimsPatch(ds, t=None, ax=None, init_plot=True, **kw_super)|| MoviePlotNode of 2D rectangle, from xmin, xmax, ymin, ymax, instead of x0, y0, width, height.| stores a LimsPatchPlotElement and has methods for plotting & updating it.|| ds: xarray.Dataset, probably 0D or 1D.| xarray Dataset containing the rectangle params to be plotted.| must contain (‘xmin’ and ‘xmax’) and/or (‘ymin’ and ‘ymax’).| units determined by
transform; default ‘data’ units.| if xlims not provided, transform[0] must allow ‘axes’ units (will put 0 to 1, i.e. fill horizontally)| if ylims not provided, transform[1] must allow ‘axes’ units (will put 0 to 1, i.e. fill vertically)| (if transform restricted above but not input directly,| default to ‘axes’ units where necessary, and ‘data’ units elsewhere.)| t: None or str| the array dimension which frames will index. E.g. ‘time’.| None –> infer from ds.dims. (if ds is 1D, use t=ds.dims[0]).| 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.| transform: UNSET, ‘data’, ‘axes’, 2-tuple of (‘data’ or ‘axes’), or Transform object (default: UNSET)| indicate coordinate system to use for x and y inputs.| single string –> x and y both in this coordinate system.| tuple –> xy[0] tells x system; xy[1] tells y system.| ‘data’ coords means input values match data values.| ‘axes’ coords means input values correspond to distance across axis:| for x: left=0, right=1.| for y: bottom=0, top=1.|| 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.)| label: UNSET or str (default: UNSET)| label for this plot element, to be included in a legend.| For xarrays, will label.format(**xarray_nondim_coords(array)).|| additional kwargs can contain constant rectangle params with same key as in matplotlib,| but only if not provided in ds. E.g. ‘edgecolor’, but only if no ds[‘edgecolor’].| additional kwargs can also be any other PlotSettings.|| See also: XarrayRectanglePatch|| Example:| ds = xr.Dataset(dict(xmin=2.5, xmax=3.7))| ds.pc.lims_patch(hatch=’//’, edgecolor=’red’, linewidth=0, facecolor=’none’)| # produces a red hatched pattern between xmin=2.5 and xmax=3.7, with no outline and no fill,| # extending from bottom to top of the axes.|| ds = xr.Dataset(dict(ymin=0.5, ymax=0.7), transform=’axes’)| ds.pc.lims_patch(alpha=0.5)| # produces a translucent rectangle between 50% and 70% of the way up the axes,| # extending from left to right of the axes.|| xx = pc.xr1d([2.5, 2.6, 2.7, 2.8, 2.9, 3.0], name=’grid’)| ds = xr.Dataset(dict(xmin=xx, xmax=3.7))| rect = ds.pc.lims_patch()| rect.ani() # or, xrect.save() to save to file instead of viewing in-line in Jupyter| # produces an animation of rectangle gradually getting thinner (across 6 animation frames),| # spanning from x=2.5 to x=3.7 at first, but x=3.0 to x=3.7 by the end of the animation.| # note: to attach this animation to an already existing PlasmaCalcs animation,| # e.g. xim=arr.image(), just add this MoviePlotNode to the tree, e.g. xim.add_child(rect).|| Method resolution order:| XarrayLimsPatch| XarrayRectanglePatch| XarrayPatch| PlasmaCalcs.plotting.movies.MoviePlotNode| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| PlasmaCalcs.tools.trees.Tree| builtins.object|| Data and other attributes defined here:|| element_cls = <class ‘PlasmaCalcs.plotting.patches.LimsPatchPlotElemen…| plot a rectangle patch, from xmin, xmax, ymin, ymax, instead of x0, y0, width, height.|| params: dict| dict of any rectangle patch related parameters.| must contain (‘xmin’ and ‘xmax’) and/or (‘ymin’ and ‘ymax’).| units determined bytransform; default ‘data’ units.| if xlims not provided, transform[0] must allow ‘axes’ units (will put 0 to 1, i.e. fill horizontally)| if ylims not provided, transform[1] must allow ‘axes’ units (will put 0 to 1, i.e. fill vertically)| (if transform restricted above but not input directly,| default to ‘axes’ units where necessary, and ‘data’ units elsewhere.)| transform: UNSET, ‘data’, ‘axes’, 2-tuple of (‘data’ or ‘axes’), or Transform object (default: UNSET)| indicate coordinate system to use for x and y inputs.| single string –> x and y both in this coordinate system.| tuple –> xy[0] tells x system; xy[1] tells y system.| ‘data’ coords means input values match data values.| ‘axes’ coords means input values correspond to distance across axis:| for x: left=0, right=1.| for y: bottom=0, top=1.|| See also: XarrayLimsPatch, RectanglePatchPlotElement||| To view or adjust plot settings in self, see self.plot_settings, or help(self.plot_settings).||| ———————————————————————-| Data and other attributes inherited from XarrayRectanglePatch:|| PATCH_SETTINGS_LOOKUP = ‘pc.RectanglePatchPlotElement’|| ———————————————————————-| Methods inherited from XarrayPatch:|| __init__(self, ds, t=None, ax=None, init_plot=True, **kw_super)| Initialize self. See help(type(self)) for accurate signature.|| get_data_at_frame(self, frame)| returns {‘params’: params at this frame}.|| 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 PatchPlotElement in self.obj.|| ———————————————————————-| Data descriptors inherited from XarrayPatch:|| ax| mpl.axes.Axes where this XarrayPatch is plotted, or None if not plotted.|| fig| mpl.figure.Figure where this XarrayPatch is plotted, or None if not plotted.|| legend_handle| alias to self.obj.legend_handle;| method which returns a Patch suitable for use as a handle in a legend.| (implied handles are sometimes okay, but this is useful to increase hatch density if using hatches.)|| patch| mpl.patches.Patch object of this XarrayPatch, or None if not plotted.|| t_plot_dim| alias to t|| ———————————————————————-| 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
- line
- caller of class XarrayLine in module PlasmaCalcs.plotting.linesclass XarrayLine(PlasmaCalcs.plotting.movies.MoviePlotNode)| XarrayLine(array, t=None, *, x=None, ax=None, init_plot=True, label=UNSET, aspect=None, **kw_super)|| MoviePlotNode of line.| stores an XarrayLinePlotElement & has methods for plotting & updating the plot.| “line” refers to a matplotlib.lines.Line2D object, e.g. the result of plt.plot.|| array: xarray.DataArray, probably ndim=2.| the data to be plotted. if ndim=1, can still plot, but nothing to animate.| t: None or str| the array dimension which frames will index. E.g. ‘time’.| None -> infer from array & any other provided dimensions.| x: None or str| if provided, tells dimensions for the x plot axes.| None -> infer from array & any other provided dimensions.| 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.|| 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.)|| label: UNSET or str (default: UNSET)| label for this plot element, to be included in a legend.| For xarrays, will label.format(**xarray_nondim_coords(array)).|| 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.)| aspect: UNSET, None, str, or number (default: UNSET)| aspect ratio for each Axes, by default.| UNSET –> use DEFAULTS.PLOT.ASPECT (default: equal).| None –> use matplotlib defaults.| str –> use ‘equal’, or ‘auto’. Note that ‘equal’ is equivalent to using aspect=1.| number –> height scaling / width scaling.| E.g. aspect=2 –> 1 data unit of height is twice long as 1 data unit of width.|| 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() if XarrayImage (or other single-array plot).| use XarraySubplotTitlesInferer.infer_title() if XarraySubplots (or other multi-array plot).| 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:| XarrayLine| PlasmaCalcs.plotting.movies.MoviePlotNode| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| PlasmaCalcs.tools.trees.Tree| builtins.object|| Methods defined here:|| __init__(self, array, t=None, *, x=None, ax=None, init_plot=True, label=UNSET, aspect=None, **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 ContourPlotElement 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.axes.Axes where this XarrayLine is plotted, or None if not plotted.|| fig| figure where this XarrayLine is plotted, or None if not plotted.|| t_plot_dim| alias to t|| ———————————————————————-| Data and other attributes defined here:|| element_cls = <class ‘PlasmaCalcs.plotting.lines.XarrayLinePlotElement…| plot line of 1D data.|| array: xarray.DataArray, probably ndim=1.| the data to be plotted.| coords with ndim>0, dtype=object will be converted to strings suitable for ticklabels.| label: UNSET or str (default: UNSET)| label for this plot element, to be included in a legend.| For xarrays, will label.format(**xarray_nondim_coords(array)).||| 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
- line_fit
- caller of function xarray_line_fit in module PlasmaCalcs.tools.xarray_tools.xarray_scireturns result of xarray_curve_fit with f a line:f(x, slope, intercept) = slope * x + intercept.
- array: xarray.DataArray or Dataset
- data to fit.Currently, Dataset allowed only if it has ‘mean’ and ‘std’ data_vars, when
stddev=True,in which case will sample the implied gaussians (via np.random.normal),N=``werr_samples`` times, performing N fits to f,reporting the mean and stddev of each fit param across all N fits, andignoring scipy standard deviation info about params from each individual fit. - dim: str
- dim to fit along.
- stddev: bool
- whether to include data_var ‘stddev’ telling standard deviation of the fit.
- werr_samples: int
- number of fits to do if
arrayis a Dataset with ‘mean’ and ‘std’ vars, whenstddev=True,in which case result will tell mean and stddev of each fit param across all N fits,and ignore scipy standard deviation info about params from each individual fit.(Implemented this because default scipy linear least squares fitting with errorbarsjust weights each point’s important by inverse of error bar,which highly favors points with small errors.That default does NOT correspond to the results of “repeating the experiment” N times,where “the experiment” is gathering data then fitting,and then asking “what is the mean and stddev of fit params across all N experiments?”.However, using werr_samples DOES correspond to “repeating the experiment” N times.) - werr_seed: None or any object, default 0
np.random.seed(werr_seed)beforehand, if doing werr_samples (with Datasetarray).Default 0 ensures reproducible results.None –> don’t call np.random.seed beforehand. Will give different results each time.- 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.
- pnames: UNSET or None or list of str
- names of params. If provided, ‘param’ coord will be assigned these names.UNSET –> use pnames = [‘slope’, ‘intercept’]
- pbounds: UNSET or None or list of [None, callable, or 2-tuple of value, None, or callable]
- bounds for each parameter. Provide
pboundsorbounds, but not both.None –> no bounds provided.Each bound can be:callable –> call as bound(array, dim) (after doing array.pc.ensure_dims(dim)).None –> use (-np.inf, np.inf).2-tuple –> (lower, upper).callable –> use lower(array, dim) / upper(array, dim)None –> use -np.inf / np.inf.UNSET –> use pbounds = None - bounds: UNSET or (list of lower bounds, list of upper bounds)
- bounds, formatted as expected by scipy curve_fit.Provide
pboundsorbounds, but not both.
additional kwargs go to XarrayCurveFitter, then xarray_curve_fit, then scipy.optimize.curve_fit.
- line_fitter
- caller of class XarrayLineFitter in module PlasmaCalcs.tools.xarray_tools.xarray_sciclass XarrayLineFitter(XarrayCurveFitter)| XarrayLineFitter(array, dim, *, promote_dims_if_needed=True, pnames=UNSET, pbounds=UNSET, bounds=UNSET, **kw_curve_fit)|| XarrayCurveFitter with f a line: f(x, slope, intercept) = slope * x + intercept.|| array: xarray.DataArray or Dataset| data to fit.| Currently, Dataset allowed only if it has ‘mean’ and ‘std’ data_vars, when
stddev=True,| in which case will sample the implied gaussians (via np.random.normal),| N=``werr_samples`` times, performing N fits to f,| reporting the mean and stddev of each fit param across all N fits, and| ignoring scipy standard deviation info about params from each individual fit.| dim: str| dim to fit along.| stddev: bool| whether to include data_var ‘stddev’ telling standard deviation of the fit.| (Internally, stored inside self.kw_curve_fit)| werr_samples: int| number of fits to do ifarrayis a Dataset with ‘mean’ and ‘std’ vars, whenstddev=True,| in which case result will tell mean and stddev of each fit param across all N fits,| and ignore scipy standard deviation info about params from each individual fit.| (Implemented this because default scipy linear least squares fitting with errorbars| just weights each point’s important by inverse of error bar,| which highly favors points with small errors.| That default does NOT correspond to the results of “repeating the experiment” N times,| where “the experiment” is gathering data then fitting,| and then asking “what is the mean and stddev of fit params across all N experiments?”.| However, using werr_samples DOES correspond to “repeating the experiment” N times.)| (Internally, stored inside self.kw_curve_fit)| werr_seed: None or any object, default 0|np.random.seed(werr_seed)beforehand, if doing werr_samples (with Datasetarray).| Default 0 ensures reproducible results.| None –> don’t call np.random.seed beforehand. Will give different results each time.| (Internally, stored inside self.kw_curve_fit)| 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.| pnames: UNSET or None or list of str| names of params. If provided, ‘param’ coord will be assigned these names.| UNSET –> use cls.pnames (default: None)| pbounds: UNSET or None or list of [None, callable, or 2-tuple of value, None, or callable]| bounds for each parameter. Providepboundsorbounds, but not both.| None –> no bounds provided.| Each bound can be:| callable –> call as bound(array, dim) (after doing array.pc.ensure_dims(dim)).| None –> use (-np.inf, np.inf).| 2-tuple –> (lower, upper).| callable –> use lower(array, dim) / upper(array, dim)| None –> use -np.inf / np.inf.| UNSET –> use cls.pbounds (default: None)| bounds: UNSET or (list of lower bounds, list of upper bounds)| bounds, formatted as expected by scipy curve_fit.| Providepboundsorbounds, but not both.|| additional kwargs go to xarray_curve_fit, then scipy.optimize.curve_fit.|| Method resolution order:| XarrayLineFitter| XarrayCurveFitter| builtins.object|| Static methods defined here:|| f(x, slope, intercept)| function to fit: just a simple line. f(x, slope, intercept) = slope * x + intercept.|| ———————————————————————-| Data and other attributes defined here:|| pnames = [‘slope’, ‘intercept’]|| ———————————————————————-| Methods inherited from XarrayCurveFitter:|| __init__(self, array, dim, *, promote_dims_if_needed=True, pnames=UNSET, pbounds=UNSET, bounds=UNSET, **kw_curve_fit)| Initialize self. See help(type(self)) for accurate signature.|| __repr__(self)| Return repr(self).|| eval(self, xdata=UNSET, params=UNSET, stddev=False)| evaluate curve fit result (params) at these xdata.| Equivalent: xarray_curve_eval(params, self.f, xdata)|| xdata: UNSET, 1D xarray.DataArray, or other 1D array-like| x values at which to evaluate the fit.| UNSET –> use self.xdata.| non-xarray 1D array-like –> convert to 1D DataArray via xr1d(xdata, self.dim)| params: UNSET or values of params from a fit.| UNSET –> use self.fitted| stddev: bool| whether to instead return Dataset with data_vars ‘eval+std’, ‘eval’, and ‘eval-std’,| Fails if params is not a Dataset with ‘stddev’ data_var.|| [EFF] note: if self.f is well-vectorized, it is equivalent (when stddev=False) and faster to do:| self.f(xdata, *params.transpose(‘param’, …))|| fit(self, *, stddev=UNSET)| curve_fit to ydata = self.array, xdata = self.array[self.dim].| Remembers result in self.fitted. Returns self.fitted.|| stddev: UNSET or bool| whether to include data_var ‘stddev’ telling standard deviation of the fit.| UNSET –> use value from self.kw_curve_fit, else default of xarray_curve_fit.|| ———————————————————————-| Readonly properties inherited from XarrayCurveFitter:|| params| alias to self.fitted[‘params’], the params from latest call to self.fit.| crash with helpful message if self.fitted doesn’t exist.|| xdata| alias to self.array[self.dim]|| ———————————————————————-| Data descriptors inherited from XarrayCurveFitter:|| __dict__| dictionary for instance variables (if defined)|| __weakref__| list of weak references to the object (if defined)|| fitted| result of latest call to self.fit().| None if never called self.fit(), or if crashed before finishing self.fit().|| ———————————————————————-| Data and other attributes inherited from XarrayCurveFitter:|| pbounds = None
- property linear_fit
- alias to line_fit
- lines
- caller of class XarrayLines in module PlasmaCalcs.plotting.linesclass XarrayLines(PlasmaCalcs.plotting.movies.MovieOrganizerNode)| XarrayLines(array, dims=None, t=None, *, x=None, ax=None, add_legend=True, label=UNSET, cstyles=None, cstyles_default=False, **kw)|| MovieOrganizerNode for organizing multiple XarrayLines.|| array: 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 , str, 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 array 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 array coords. See also: DEFAULTS.PLOT.DIMS_INFER| cstyles: None or dict of {{coordname: dict or list of tuples of (val, dict of kwargs for XarrayLine)}}| if provided, pass these dicts to individual lines with corresponding scalar val for coord.| use tuples of values to test equality instead of indexing a dict.| E.g., styles={{‘fluid’: [(‘e’, dict(ls=’–‘)), (‘H_II’, dict(color=’blue’))]}}| would ensure dashed line when arr[‘fluid’]==’e’, blue line when arr[‘fluid’]==’H_II’,| and have no effect whenever arr[‘fluid’] is not scalar, doesn’t exist, or isn’t ‘e’ or ‘H_II’.| cstyles_default: bool| tells how to handle conflict between kwargs from cstyles and kwargs passed directly to self.| True –> treat cstyles as ‘defaults’; kwargs from self override kwargs from cstyles.| False –> kwargs from cstyles take precedence.|| robust: {robust}| ymargin: {ymargin}| 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__(self, array, dims=None, t=None, *, x=None, ax=None, add_legend=True, label=UNSET, cstyles=None, cstyles_default=False, **kw)|| 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.
- lowpass
- caller of function xarray_lowpass in module PlasmaCalcs.tools.fft_tools.xarray_fftxarray_lowpass(array, dim=None, keep=UNSET, *, keep_r=UNSET, ds=None, real=None, return_fft=False)return array after putting it through a lowpass filter using fft & ifft.This is equivalent to ifft(fft(array) * filter), where filter is 0 at all “large” frequency values.“large” is determined by keep & r; see below.
- dim: None or iterable or strs
- coordinates to apply lowpass filter over. If None, use all array.dims.promote_dim(array, coord) for any non-dimension coordinates, as needed.
- keep: UNSET, True, dict, or number between 0 < keep <= 1
- fraction of frequencies to keep, along each dim.(Must provide this or keep_r but not both.)True –> use DEFAULTS.FFT_LOWPASS_KEEP.number –> use this value for all dims.
- keep_r: UNSET, True, or number between 0 < keep <= 1
- radius of N-sphere to keep in normalized frequency-space,normalized such that max(frequencies)==1 along each dim.All values outside of this N-sphere will be set to 0.Similar to
keep, but here use an N-sphere instead of an N-cube.(Must provide this or keep but not both.)True –> use DEFAULTS.FFT_LOWPASS_KEEP.[TODO] more options than just spherical? (e.g. ellipsoid) - ds: None, number, or dict of {dim: d}
- spacing between elements of array along each dim.number –> use the same value for all dims.None –> infer via array.coords[dim].diff(dim) for each dim(requires evenly-spaced coordinates in dim; spacing checked with np.allclose)
- real: None or bool
- whether to return np.real(ifft) instead of just ifft (which might have imaginary part)None –> infer from array. Use True if np.all(np.isreal(array)), else False.
- return_fft: bool
- whether to return (result, masked fft) instead of just result.mainly intended for debugging purposes.
- property 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.
- max_coord_where
- caller of function xarray_max_coord_where in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_max_coord_where(array, coord, where, *, promote_dims_if_needed=True)return (array of) maximum value(s) of coord, where condition is True.
- array: xarray.DataArray
- array to find maximum value in.
- coord: str
- coord whose maximum value will appear in the result.Must correspond with a single dimension of array.
- where: xarray.DataArray or callable
- locations at which to consider values of coord.callable –> use where=where(array)(will promote coord to dim first, if coord not dim yet.)
- 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.
Example:xarray_max_coord_where(growth, ‘kmod’, lambda arr: arr>0)# returns the maximum value(s) of kmod across all regions where growth>0.# (result has no ‘kmod’ dim, but does retain any other dims from array.)Compare to xarray_cmax(growth.where(growth>0), ‘kmod’),which tells the value of kmod at the location of max growth (where growth>0)(but not necessarily the maximum kmod across all regions with growth>0).
- 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.
- mean_pm_std
- caller of function xarray_mean_pm_std in module PlasmaCalcs.tools.xarray_tools.xarray_werr_statsxarray_mean_pm_std(array, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw)returns Dataset of ‘mean+std’, ‘mean’, ‘mean-std’ for array.
- 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 and std.Can provide skipna=True/False to skip NaNs or not; default True for float dtypes.
- 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.
- min_coord_where
- caller of function xarray_min_coord_where in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_min_coord_where(array, coord, where, *, promote_dims_if_needed=True)return (array of) minimum value(s) of coord, where condition is True.
- array: xarray.DataArray
- array to find minimum value in.
- coord: str
- coord whose minimum value will appear in the result.Must correspond with a single dimension of array.
- where: xarray.DataArray or callable
- locations at which to consider values of coord.callable –> use where=where(array)(will promote coord to dim first, if coord not dim yet.)
- 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.
Example:xarray_min_coord_where(growth, ‘E’, lambda arr: arr>0)# returns the minimum value(s) of E across all regions where growth>0.# (result has no ‘E’ dim, but does retain any other dims from array.)Compare to xarray_cmin(growth.where(growth>0), ‘E’),which tells the value of E at the location of minimum growth (where growth>0)(but not necessarily the minimum E across all regions with growth>0).
- property mod
- alias to magnitude
- mod_coords
- caller of function xarray_mod_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsreturn copy of array with coords modded (via np.mod) by
mod.- mod: None or dict of {coord: mod}
- dict –> mod each coord by the corresponding number.None –> provide as kwargs (mod_as_kw) instead.
mod_as_kw: if mod is None, can provide mod dict as kwargs instead. modshift: value
shift each coord by modshift before modding, then -modshift after modding.E.g. if modshift=90, mod=180, then modded coord = np.mod(coord+90, 180)-90.- missing_ok: bool
- whether it is okay if some coords are missing (if yes, skip missing coords).
- 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.
- promote_index_coords
- caller of function xarray_promote_index_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coordsxarray_promote_index_coords(array, coords=None)promote to dims all ‘{cname}_index’ coords for which ‘{cname}’ is associated with a 1D dim.
- coords: None, str, or list of str
- coords (with or without ‘_index’ suffix) to consider promoting to dims.None –> all index coords.str –> treat as list of 1 element.
- rectangle_patch
- caller of class XarrayRectanglePatch in module PlasmaCalcs.plotting.patchesclass XarrayRectanglePatch(XarrayPatch)| XarrayRectanglePatch(ds, t=None, ax=None, init_plot=True, **kw_super)|| MoviePlotNode of 2D rectangle.| stores a RectanglePatchPlotElement and has methods for plotting & updating it.|| ds: xarray.Dataset, probably 0D or 1D.| xarray Dataset containing the rectangle params to be plotted.| if ndim=0, can still plot, but nothing to animate.| rectangle params are ‘x0’, ‘y0’, ‘width’, ‘height’.| (x0 and y0 point to lower left corner unless negative width or height.| units determined by transform; default data units.)| t: None or str| the array dimension which frames will index. E.g. ‘time’.| None –> infer from ds.dims. (if ds is 1D, use t=ds.dims[0]).| 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.| transform: UNSET, ‘data’, ‘axes’, 2-tuple of (‘data’ or ‘axes’), or Transform object (default: UNSET)| indicate coordinate system to use for x and y inputs.| single string –> x and y both in this coordinate system.| tuple –> xy[0] tells x system; xy[1] tells y system.| ‘data’ coords means input values match data values.| ‘axes’ coords means input values correspond to distance across axis:| for x: left=0, right=1.| for y: bottom=0, top=1.|| 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.)| label: UNSET or str (default: UNSET)| label for this plot element, to be included in a legend.| For xarrays, will label.format(**xarray_nondim_coords(array)).|| additional kwargs can contain constant rectangle params with same key as in matplotlib,| but only if not provided in ds. E.g. ‘edgecolor’, but only if no ds[‘edgecolor’].| additional kwargs can also be any other PlotSettings.|| See also: XarrayLimsPatch|| Method resolution order:| XarrayRectanglePatch| XarrayPatch| PlasmaCalcs.plotting.movies.MoviePlotNode| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| PlasmaCalcs.tools.trees.Tree| builtins.object|| Data and other attributes defined here:|| PATCH_SETTINGS_LOOKUP = ‘pc.RectanglePatchPlotElement’|| element_cls = <class ‘PlasmaCalcs.plotting.patches.RectanglePatchPlotE…| plot a rectangle patch.|| params: dict| dict of any rectangle patch related parameters.| must contain ‘x0’ and ‘y0’.| rectangle params are ‘x0’, ‘y0’, ‘width’, ‘height’.| (x0 and y0 point to lower left corner unless negative width or height.| units determined by
transform; default data units.)| transform: UNSET, ‘data’, ‘axes’, 2-tuple of (‘data’ or ‘axes’), or Transform object (default: UNSET)| indicate coordinate system to use for x and y inputs.| single string –> x and y both in this coordinate system.| tuple –> xy[0] tells x system; xy[1] tells y system.| ‘data’ coords means input values match data values.| ‘axes’ coords means input values correspond to distance across axis:| for x: left=0, right=1.| for y: bottom=0, top=1.|| ‘height’ and ‘width’ may either be specified viaparamsor as additional kwargs.| Additional kwargs can be any patch params (with same key as in matplotlib) or PlotSettings.| E.g. ‘angle’, ‘facecolor’, ‘hatch’.|| See also: XarrayRectanglePatch, LimsPatchPlotElement||| ———————————————————————-| Methods inherited from XarrayPatch:|| __init__(self, ds, t=None, ax=None, init_plot=True, **kw_super)| Initialize self. See help(type(self)) for accurate signature.|| get_data_at_frame(self, frame)| returns {‘params’: params at this frame}.|| 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 PatchPlotElement in self.obj.|| ———————————————————————-| Data descriptors inherited from XarrayPatch:|| ax| mpl.axes.Axes where this XarrayPatch is plotted, or None if not plotted.|| fig| mpl.figure.Figure where this XarrayPatch is plotted, or None if not plotted.|| legend_handle| alias to self.obj.legend_handle;| method which returns a Patch suitable for use as a handle in a legend.| (implied handles are sometimes okay, but this is useful to increase hatch density if using hatches.)|| patch| mpl.patches.Patch object of this XarrayPatch, or None if not plotted.|| t_plot_dim| alias to t|| ———————————————————————-| 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
- 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, expand_dict_attrs=True, stringify_bool_attrs=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.
- expand_dict_attrs: bool
- whether to expand dict-valued attributes into separate attributes,with names like “__dictattr_{origattrname}__{dictkey}__”.(netcdf doesn’t allow saving dict-valued attributes.)(will be applied before stringify_bool_attrs.)
- stringify_bool_attrs: bool
- whether to replace bool-valued attributes’ values with “__bool=True__” or “__bool=False__”.(netcdf doesn’t like saving bool-valued attributes.)(xarray_load will automatically convert these back into bools.)
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).
- scatter
- caller of class XarrayScatter in module PlasmaCalcs.plotting.scatterclass XarrayScatter(PlasmaCalcs.plotting.movies.MoviePlotNode)|| MoviePlotNode of scatter.| stores a ScatterPlotElement & has methods for plotting & updating the plot.| “scatter” refers to a matplotlib.collections.PathCollection object, e.g. the result of plt.scatter.|| array: xarray.DataArray, probably ndim=2.| the data to be plotted. if ndim=1, can still plot, but nothing to animate.| For ndim >= 3, consider manually iterating over the 3rd+ dim(s),| putting multing scatter plots onto the same axes,| making a movie=MovieOrganizerNode() and doing movie.add_child(s) for each plot.| [TODO] add a class (or just a function?) to handle this sort of thing automatically.| t: None or str| the array dimension which frames will index. E.g. ‘time’.| None -> infer from array & any other provided dimensions.| x: None or str| if provided, tells dimensions for the x plot axes.| None -> infer from array & any other provided dimensions.| 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.|| 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.)| label: UNSET or str (default: UNSET)| label for this plot element, to be included in a legend.| For xarrays, will label.format(**xarray_nondim_coords(array)).|| 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() if XarrayImage (or other single-array plot).| use XarraySubplotTitlesInferer.infer_title() if XarraySubplots (or other multi-array plot).| 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:| XarrayScatter| PlasmaCalcs.plotting.movies.MoviePlotNode| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| PlasmaCalcs.tools.trees.Tree| builtins.object|| Methods defined here:||| 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 ScatterPlotElement 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.axes.Axes where this XarrayScatter is plotted, or None if not plotted.|| fig| figure where this XarrayScatter is plotted, or None if not plotted.|| legend_handle| alias to self.obj.legend_handle;| method which returns a Line2D object suitable for use as a handle in a legend.| (implied handles are sometimes okay, but this is useful in case self is sometimes all-nan.)|| scatter| mpl.collections.PathCollection object of this XarrayScatter, or None if not plotted.|| t_plot_dim| alias to t|| ———————————————————————-| Data and other attributes defined here:|| element_cls = <class ‘PlasmaCalcs.plotting.scatter.ScatterPlotElement’…| scatter plot.|| array: xarray.DataArray, probably ndim=1.| the data to be plotted.| if ndim != 1, must providex; all other dims will be stacked.| x: None or str| the coordinate to use for x-axis values.| None –> if array ndim==1, use the (first 1D) coord associated with the 1 dim,| (or just use the dim itself, if no such associated coord).| if array ndim!=1, crash with PlottingAmbiguityError.|| aliases, provide at most one of each pair:| s, markersize:sfrom plt.scatter. size of markers.| facecolors, facecolor:facecolorsfrom plt.scatter. Color of marker faces in plot.| edgecolors, edgecolor:edgecolorsfrom plt.scatter. Color of marker edges in plot.| linewidths, linewidth:linewidthsfrom plt.scatter. Width of marker edges in plot.|| label: UNSET or str (default: UNSET)| label for this plot element, to be included in a legend.| For xarrays, will label.format(**xarray_nondim_coords(array)).| 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 usingrobust, 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.)||| 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
- scatter_max
- caller of function xarray_scatter_max in module PlasmaCalcs.plotting.scatter
- array: xarray.DataArray
- array whose max will be marked.
- x: str
- coordinate to use for x-axis values.
- y: str
- coordinate to use for y-axis values.
- t: None or str
- coordinate to use for “time” (iterate across movie frames).None –> probably can’t animate; might show all points in 1 frame.
[TODO] optionally infer x, y, t automatically if not provided directly.additional kwargs go to XarrayScatterreturns XarrayScatter object.
- scatter_min
- caller of function xarray_scatter_min in module PlasmaCalcs.plotting.scatter
- array: xarray.DataArray
- array whose min will be marked.
- x: str
- coordinate to use for x-axis values.
- y: str
- coordinate to use for y-axis values.
- t: None or str
- coordinate to use for “time” (iterate across movie frames).None –> probably can’t animate; might show all points in 1 frame.
[TODO] optionally infer x, y, t automatically if not provided directly.additional kwargs go to XarrayScatterreturns XarrayScatter object.
- scatter_where
- caller of function xarray_scatter_where in module PlasmaCalcs.plotting.scatteruse XarrayScatter to plt.scatter() markers wherever arr==True.Roughly equivalent: arr[y].where(arr).pc.scatter(x=x, t=t, **kw_scatter)
- arr: xarray.DataArray
- array of bools, or array to be provided to condition if condition is callable.
- condition: None, array of bools, or callable
- None –> use condition =
arr, andarrmust be array of bools.array –> ignore arr entirely.conditionmust be array of bools.callable –> use condition = condition(arr), which must return array of bools. - x: str
- coordinate to use for x-axis values.
- y: str
- coordinate to use for y-axis values.
- t: None or str
- coordinate to use for “time” (iterate across movie frames).None –> probably can’t animate; might show all points in 1 frame.
[TODO] optionally infer x, y, t automatically if not provided directly.additional kwargs go to XarrayScatterreturns XarrayScatter object.
- 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).
- property size
- total number of elements in the DataArray. Equivalent to array.size.Provided for consistent interface for DataArray or Dataset size: use obj.pc.size.
- sort_along
- caller of function xarray_sort_array_along in module PlasmaCalcs.tools.xarray_tools.xarray_indexingxarray_sort_array_along(array, dim, newname=’{dim}_sort’, *, ascending=True, nkeep=None, index=False, store_original=False, newname_original=’{dim}_orig’, promote_dims_if_needed=True, squeeze_argsort=True, kind=None)returns array, sorted along dim.
- array: xarray.DataArray
- array to sort.
- dim: str
- dimension along which to sort.
- newname: str
- result dim will be replaced by newname.format(dim=dim). Default: ‘{dim}_sort’.
- ascending: bool
- result sorted in ascending order if True, descending if False.
- nkeep: None or int
- number of sorted values to keep. E.g. nkeep=2 –> keep only the first 2 values.equivalent to using result.isel(newdim=(0, nkeep)), where newdim=newname.format(dim=dim).
- index: bool
- whether to use indexes for result’s dim coord values, instead of original coord values.Either way, the relevant coord is multidimensional, varying across all array.dims except dim.True –> result[‘{dim}_index’] will be the indexes along original dimFalse –> result[dim] will be the original coord values.
- store_original: bool
- whether to store original dim’s coord values in result.True –> result will be a Dataset with data_vars array.name and ‘{dim}_orig’;result[array.name] = sorted values (dims=array.dims but replace dim with newname.format(dim=dim))result[‘{dim}_orig’] = original values of dim (dims=’{dim}_orig’)False –> result will be a DataArray which does not track original dim’s coord values separately.
- newname_original: str
- name to use for original dim’s coord values if store_original=True. Default: ‘{dim}_orig’.
- 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.
- squeeze_argsort: bool
- whether to drop redundant dims for argsort result.This means any dims with np.all(array==array.isel(dim=0)). (This includes dims with len=1.)
- kind: None or str from {‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}
- sorting algorithm. Passed directly to numpy.argsort; see help(numpy.argsort) for details.
- squeeze
- caller of function xarray_squeeze in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsxarray_squeeze(array, dim=None, *, keep=None, drop=True)return array but drop redundant dims.dims are redundant if np.all(array==array.isel(dim=0)).This is a more aggressive version of array.squeeze():all dims with size 1 are trivially redundant and will be dropped;but here, additionally, all dims which are redundant in any way will be dropped.
- dim: None, str, or list of strs
- if provided, only consider dropping these dims.
- keep: None, str, or list of strs
- if provided, do not consider dropping these dims.(can provide dim or keep, but not both.)
- drop: bool
- whether to drop coord for size-1 redundant dims.if False, will keep scalar coord for size-1 redundant dims.
E.g. [[0,1,2],[0,1,2]] –> [0,1,2]. (But, as xarray, so result remains well-labeled.)
- squeeze_close
- caller of function xarray_squeeze_close in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsxarray_squeeze_close(array, dim=None, tol=0.001, *, closeness_name=’closeness_{dim}’, keep=None, drop=True)return array but drop redundant dims, with an tolerance when checking equality.dims are redundant if all values are close along that dim.Closeness check here is: (array.isel(dim=0)/array).std() < tol.For each removed dim:result will just use array.isel(dim=0).result will add coord ‘closeness_{dim}’ == std(array.isel(dim=0)/array).This is a much more aggressive version of array.squeeze():all dims with size 1 are trivially redundant and will be dropped;but here, additionally, all dims which are redundant in any way will be dropped.
NOTE: performs all closeness checks before dropping any dims.
- dim: None, str, or list of strs
- if provided, only consider dropping these dims.
- tol: number
- drops dim with tol > (array.isel(dim=0)/array).std().
- closeness_name: None or str, default ‘closeness_{dim}’
- add new coord with this name, with value == (array.isel(dim=0)/array).std(),for each dim dropped. (smaller is closer.) (always 0 for dims of size 1.)(closeness_{dim} value tells the pre-squeeze variation along that dim.)None –> do not add this coord.
- keep: None, str, or list of strs
- if provided, do not consider dropping these dims.(can provide dim or keep, but not both.)
- drop: bool
- whether to drop coord for size-1 redundant dims.if False, will keep scalar coord for size-1 redundant dims.
See also: xarray_closeness
- stats
- caller of function xarray_stats in module PlasmaCalcs.tools.xarray_tools.xarray_agg_statsxarray_stats(array, dim=None, stats=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, to_da=None, **kw)returns Dataset of stats for array: min, mean, median, max, std, rms.
- array: xarray.DataArray or xarray.Dataset
- the array (or dataset) from which to compute stats.if dataset, compute separate stats for each data var,and result will be a dataset with ‘stat’ dim;equivalent to doing xarray_stats for each data_var, with ``to_da``=’stat’.
- dim: None, str, or iterable of strs
- apply operation along these dimensions
- stats: None or iterable of str from (‘min’, ‘mean’, ‘median’, ‘max’, ‘std’, ‘rms’)
- which stats to compute & include in the result.None –> equivalent to stats=[‘min’, ‘mean’, ‘median’, ‘max’, ‘std’, ‘rms’].
- 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.
- to_da: None, bool, or str
- whether to return DataArray instead of Dataset.None –> True if
arrayis a Dataset, else False.False –> result is a Dataset with stats as data vars.(incompatible with inputarraybeing a Dataset)True –> equivalent to to_da=’stat’.str –> stats reported along this dimension (must not already exist inarray).result type is the same type as input (DataArray or Dataset).
additional kwargs are passed to array.min, mean, median, max, and std.Can provide skipna=True/False to skip NaNs or not; default True for float dtypes.
- 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, missing_ok=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.
- missing_ok: bool
- whether it is okay for some provided
coordsto be missing from array.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, rtitle=UNSET, ttitle=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, scalar value, or array-like| if provided, tells value for vmin, vmax for all subplots, ignoring share_vlims and robust.| if providing only one, still use share_vlims and robust for the other| (e.g. if provided vmax but vmin=None, use share_vlims and robust when deciding on vmin).| if array-like vmin, use vmin=vmin[i][j] for plot in i’th row and j’th column. Similar for vmax.| (doesn’t squeeze. e.g., if only 1 row exists, because row=None, then use vmin[0][j])| (if non-None wrap, vlims shape should correspond to the shape after wrapping.)| (use None limit to instead use share_vlims and robust for that subplot.| E.g. vmin=[[0, 2, None]], share_vlims=’row’, robust=10, for subplots with 1 row, 3 cols,| will use vmin=0 for first plot, 2 for second plot,| and vmin=10th percenticle across all values in all three plots, for the third plot.)| 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).|| axsize: UNSET, number, or (width, height) in inches (default: UNSET)| size of a single subplot, in inches.| UNSET –> use DEFAULTS.PLOT.SUBPLOTS_AXSIZE (default: (2, 2)).| number –> use width = height = axsize.| mutually exclusive with figsize, cannot provide both.| aspect: UNSET, None, str, or number (default: UNSET)| aspect ratio for each Axes, by default.| UNSET –> use DEFAULTS.PLOT.ASPECT (default: equal).| None –> use matplotlib defaults.| str –> use ‘equal’, or ‘auto’. Note that ‘equal’ is equivalent to using aspect=1.| number –> height scaling / width scaling.| E.g. aspect=2 –> 1 data unit of height is twice long as 1 data unit of width.| layout: UNSET, None, or str (default: UNSET)| layout for subplots, by default.| Suggestion: use layout=’compressed’, make_cax=’mpl’, and tweak wspace & hspace,| OR use layout=’none’, make_cax=’pc’, and tweak suptitle_y, left, top, and bottom.| UNSET –> use DEFAULTS.PLOT.LAYOUT (default: compressed).| None –> use matplotlib defaults.| str –> should be ‘constrained’, ‘compressed’, ‘tight’, or ‘none’.|| suptitle: UNSET, None, or str (default: UNSET)| suptitle for a single axes/subplot. For xarrays, will suptitle.format(**xarray_nondim_coords(array)).| (Note: plot_settings[‘suptitle’] should always be the ‘base’ suptitle, before suptitle.format(…))| UNSET –> use self.default_suptitle. For XarraySubplots this includes information about t_plot_dim.| None –> use no suptitle.| (Note - self.plot_settings[‘suptitle’] will always be the ‘base’ suptitle, before applying suptitle_format.)| suptitle_y: UNSET, None, or number (default: UNSET)| y position for suptitle, in figure coordinates.| suptitle_font: UNSET, None, or str (default: UNSET)| font for suptitle, e.g. ‘serif’, ‘sans-serif’, or ‘monospace’| UNSET –> use DEFAULTS.PLOT.MOVIE_TITLE_FONT (default: monospace).| None –> use matplotlib default.| suptitle_kw: UNSET, or dict (default: UNSET)| any additional kwargs for plt.suptitle.| suptitle_width: UNSET, None, or number (default: UNSET)| suggested width [number of characters] for suptitle;| default routines might make multiline suptitle to avoid going longer than this.| UNSET –> use DEFAULTS.PLOT.SUPTITLE_WIDTH (default: 40).| None –> no maximum width.|| 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() if XarrayImage (or other single-array plot).| use XarraySubplotTitlesInferer.infer_title() if XarraySubplots (or other multi-array plot).| 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.| subplot_title_width: UNSET, None, or number (default: UNSET)| suggested width [number of characters] for subplot titles;| default title routines might make multiline title if title would be longer than this.| UNSET –> use DEFAULTS.PLOT.SUBPLOT_TITLE_WIDTH (default: 20).| None –> no maximum width.|| rtitle: UNSET or str (default: UNSET)| rightmost-column ‘title’ to put only on righthand side of subplots on the rightmost column.| For xarrays, will rtitle.format(**xarray_nondim_coords(array)).| Note: rtitles created via PlasmaCalcs’ plot_note(), which uses plt.annotate, not plt.ylabel().| UNSET –> do not add rtitle.| rtitle_kw: UNSET, or dict (default: UNSET)| any additional kwargs for plot_note() when making rtitle.| (note: includes font=plot_settings[‘title_font’] unless
fontfamilyspecified in rtitle_kw.)| (note: to specify location, uselocorxyin axes coords or as str; see plot_note() for details.)| UNSET –> use DEFAULTS.PLOT.RTITLE_KW (default: {‘rotation’: 270, ‘loc’: ‘outside center right’, ‘fontsize’: ‘large’}).| ttitle: UNSET or str (default: UNSET)| topmost-row title to put only on subplots in the top row.| For xarrays, will ttitle.format(**xarray_nondim_coords(array)).| Mutually exclusive with providingtitle, and overrides default titles if provided.| UNSET –> do not add ttitle.| ttitle_kw: UNSET, or dict (default: UNSET)| any additional kwargs for plt.title when making ttitle.| (note: includes font=plot_settings[‘title_font’] unlessfontfamilyspecified in ttitle_kw.)| UNSET –> use DEFAULTS.PLOT.TTITLE_KW (default: {}).| None –> use no title.|| 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.| colorbar_kw: unset or dict (default: UNSET)| any additional kwargs for plt.colorbar.| add_colorbars: UNSET, bool, or str (default: True)| whether to add colorbars during init_plot, for ImageSubplots.| str –> use self.colorbars(mode=add_colorbars). E.g. ‘auto’, ‘all’, ‘row’.|| 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, rtitle=UNSET, ttitle=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_rtitles(self)| adds rtitles (as MovieText node objects) via plot_note() on right-hand-side of right-most images.| (only if self.plot_settings[‘rtitle’] is not UNSET.)|| plot_suptitle(self)| adds suptitle (as a MovieText node)| raise PlottingAmbiguityError if suptitle already plotted| (this prevents having multiple suptitle nodes).|| rightmost_images(self, *, as_idx=False, missing_ok: True)| list of rightmost existing image (i.e., non-None) in each row.| as_idx: bool| whether to return indices of images within self.images, instead of image objects.| missing_ok: bool| whether it is okay for some row to have no images (result will be None in those rows).|| scatter_max(self, **kw_scatter)| use XarrayScatter to plt.scatter() a marker at argmax of each subplot image’s array.| animatable (e.g. different max for each frame); for each image, image.add_child(scatter result).| returns np.array with same shape as self, containing the results of XarrayScatter calls.|| scatter_min(self, **kw_scatter)| use XarrayScatter to plt.scatter() a marker at argmin of each subplot image’s array.| animatable (e.g. different max for each frame); for each image, image.add_child(scatter result).| returns np.array with same shape as self, containing the results of XarrayScatter calls.|| scatter_where(self, condition, **kw_scatter)| use XarrayScatter to plt.scatter() markers where condition is True.| animatable (e.g. different max for each frame); for each image, image.add_child(scatter result).|| condition: callable or DataArray of bools| callable –> use condition(arr) for each image in self, where arr=image.array.| DataArray –> use condition.isel(ii) for each image in self,| where ii is the corresponding dict of indices from self.isels.|| returns np.array with same shape as self, containing the results of XarrayScatter calls.|| Example:| xsubs = array.pc.image(…)| xsubs.scatter_where(lambda arr: arr > 7.5) # markers at all values larger than 7.5| xsubs.save(filename) # save animation to filename (if xsubs.t_plot_dim is not None)|| ———————————————————————-| 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_cbars(self, *, no_image=None, no_cbar=False)| return array of colorbars associated with images on each ax.| for ax with no image, value will beno_image(default None).| for ax with image but no colorbar, value will beno_cbar(default False).|| 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.|| iter_cbars(self)| iterate across axs, yielding ((irow, icol), cbar) for each ax with a colorbar.| (axs without colorbars will be skipped.)|| 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.|| iter_images(self)| iterate across axs, yielding ((irow, icol), image) for each ax with an image.| (axs without image will be skipped.)|| 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 0x7d58dfc869d0>|| 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|| cbars| list of colorbars appearing on any ax across self.| equivalent: [cbar for ((irow, icol), cbar) in self.iter_cbars()]|| 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.
- suptitle
- caller of function xarray_suptitle_plot_node in module PlasmaCalcs.plotting.labelscreate a MoviePlotNode for a suptitle associated with an xarray.DataArray.
- array: xarray.DataArray, probably ndim=3.
- the full DataArray which will be plotted throughout the movie.internally, store xarray_fill_coords(array), so that coordless dims’ indices can be used.e.g. if “dim0” is a dimension with no coords, will use np.arange(dim0.size).
- base_text: UNSET or str
- the base text string, to be formatted by array at each frame.UNSET –> will use array._title_for_slice() for array at each frame.str –> will be formatted by xarray_nondim_coords(array at frame).E.g., base_text=’fluid={{fluid}}, time={{t:.2e}} seconds’.
- t: None or str
- the array dimension which frames will index. E.g. ‘time’.None –> infer it via infer_movie_dim(array.dims, t)
- parent: None or MoviePlotNode
- if provided, the parent of this node. None -> this node has no parent.
- suptitle_font: UNSET, None, or str (default: UNSET)
- font for suptitle, e.g. ‘serif’, ‘sans-serif’, or ‘monospace’UNSET –> use DEFAULTS.PLOT.MOVIE_TITLE_FONT (default: monospace).None –> use matplotlib default.
- suptitle_y: UNSET, None, or number (default: UNSET)
- y position for suptitle, in figure coordinates.
- suptitle_kw: UNSET, or dict (default: UNSET)
- any additional kwargs for plt.suptitle.
- text_kw: UNSET, None, or dict (default: UNSET)
- any additional kwargs for text, e.g. text_kw=dict(fontweight=bold).Applied to titles too, but individual kw can be overridden by title settings.[TODO] ability to enter unambiguous text_kw directly, e.g. fontweight.
Additional kwargs go directly to plt.suptitle()
- take_along_dimensions
- caller of function take_along_dimensions in module PlasmaCalcs.tools.xarray_tools.xarray_dimensionsreturns 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)).if dimensions is an empty list:result will be a scalar numpy array with result[()] =
array,unless atleast_1d=True; then result has shape (1,) and result[0] =array.
- text
- caller of class XarrayText in module PlasmaCalcs.plotting.labelsclass XarrayText(MovieText)|| MoviePlotNode managing text associated with an xarray.DataArray.|| txt: Text object| e.g., the result of plt.text(…) or plt.title(…)| array: xarray.DataArray, probably ndim=3.| the full DataArray which will be plotted throughout the movie.| internally, store xarray_fill_coords(array), so that coordless dims’ indices can be used.| e.g. if “dim0” is a dimension with no coords, will use np.arange(dim0.size).| t: None or str| the array dimension which frames will index. E.g. ‘time’.| None –> infer it via infer_movie_dim(array.dims, t)| base_text: None, UNSET or str| the base text string, to be formatted by array at each frame.| UNSET –> will use array._title_for_slice() for array at each frame.| str –> will be formatted by xarray_nondim_coords(array at frame).| E.g., base_text=’fluid={{fluid}}, time={{t:.2e}} seconds’.| if None, infer from txt.|| — Examples —| # simple example:| import PlasmaCalcs as pc| array = … # some array having fluid & t coords…| txt = plt.text(0, 7, ‘{fluid}, t={t:.2e}’) # text at x=0, y=7 in data coords.| xtext = pc.XarrayText(array, txt, t=’t’)| xtext.save(‘text_movie.mp4’)|| # slightly more complex: start like above, but attach to existing MoviePlotNode instead:| xim = array.pc.image()| xim.add_child(xtext, arr)| xim.save(‘image_and_text_movie.mp4’) # movie of image & text, both updating in time!|| # one more notable option: instead of txt = plt.text(…),| # could do txt = plt.title(…), plt.suptitle(…) or similar option.| # also, if infer_movie_dim can figure out t, don’t need to provide it explicitly:| xtext = pc.XarrayText(array, plt.title(‘{fluid}, t={t:.2e}’))|| # finally, note that this can be accessed from array, e.g.:| xtext = array.pc.text(plt.title(‘{fluid}, t={t:.2e}’))||| To view or adjust plot settings in self, see self.plot_settings, or help(self.plot_settings).|| Method resolution order:| XarrayText| MovieText| PlasmaCalcs.plotting.movies.MoviePlotNode| PlasmaCalcs.plotting.plot_settings.PlotSettingsMixin| PlasmaCalcs.tools.trees.Tree| builtins.object|| Methods defined here:||| frame_to_text(self, frame)| return the text string at this frame|| get_nframes_here(self)| returns number of frames that could be in this movie, based on this node.| 0 if self never updates (i.e., self.t is None).|| ———————————————————————-| Methods inherited from MovieText:|| get_data_at_frame(self, frame)| returns {‘text’: text string for this frame}.|| init_plot(self)| plot for the first time. Save the TitlePlotElement at self.obj.|| ———————————————————————-| Readonly properties inherited from MovieText:|| text| the text string stored in self.obj; use self.update_to_frame to update it.|| ———————————————————————-| Data descriptors inherited from MovieText:|| ax| mpl.axes.Axes where this MovieText is plotted.|| fig| figure where this MovieText is plotted.|| ———————————————————————-| Data and other attributes inherited from MovieText:|| element_cls = <class ‘PlasmaCalcs.plotting.labels.TextPlotElement’>| MoviePlotElement for Text object. see MovieText for updating text over time.|| txt: Text object| e.g., the result of plt.text(…) or plt.title(…)||| 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
- 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, fill_center=None, cycles=None, short_cycle_ok=False, dmax=UNSET, styles=None, plot=True, label=None, custom_labels=None, add_legend=True, legend_cols_align=True, legend_max_rows=20, skipna=False, robust=UNSET, ymargin=None, ybounds=None, xincrease=None, cstyles=None, cstyles_default=False, **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
arrayis a Dataset with info about mean and std, use this to make plot with error bars.| (else, werr=False is the only valid option.)| True –> equivalent to ‘bar’| ‘bar’ –> plt.errorbar. Expectarrayto have ‘mean’ and ‘std’ data_vars.| ‘fill’ –> plt.fill_between. Expectarrayto have one of the following pairs of data vars:| (‘mean’ and ‘std’, ‘mean+std’ and ‘mean-std’, ‘eval+std’ and ‘eval-std’)| 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| fill_center: None, bool, or dict| if True or provided, and werr=’fill’ and array has ‘mean’ (or ‘eval’) data_var, also make timeline at center,| using kwargs from __init__ but overwriting some things for the internal call to timelines():| anything provided in fill_center; werr=False, fill_center=False; alpha=1.| (The alpha=1 prevents fill_center from appearing transparent if alpha<1 in __init__.)| 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, False, 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.| False –> use label=’’ for all lines.| custom_labels: None or str| if provided, use this label instead oflabel+ dim info;| will be passed dict of nondim coord values for each line.| E.g. custom_labels=’u_{fluid},{component}’ –> ‘u_H+,x’ when fluid=’H+’ and component=’x’.| 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 usingrobust, 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”)| cstyles: None or dict of {coordname: dict or list of tuples of (val, dict of kwargs for a line)}| if provided, pass these dicts to individual lines with corresponding scalar val for coord.| use tuples of values to test equality instead of indexing a dict.| E.g., styles={‘fluid’: [(‘e’, dict(ls=’–‘)), (‘H_II’, dict(color=’blue’))]}| would ensure dashed line when arr[‘fluid’]==’e’, blue line when arr[‘fluid’]==’H_II’,| and have no effect whenever arr[‘fluid’] is not scalar, doesn’t exist, or isn’t ‘e’ or ‘H_II’.| cstyles_default: bool| tells how to handle conflict between kwargs from cstyles and other kwargs.| True –> treat cstyles as ‘defaults’; kwargs from other sources override kwargs from cstyles.| False –> kwargs from cstyles take precedence.|| 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, fill_center=None, cycles=None, short_cycle_ok=False, dmax=UNSET, styles=None, plot=True, label=None, custom_labels=None, add_legend=True, legend_cols_align=True, legend_max_rows=20, skipna=False, robust=UNSET, ymargin=None, ybounds=None, xincrease=None, cstyles=None, cstyles_default=False, **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: 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).| 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.| only includes relevant cstyles if not self.cstyles_default.|| 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: 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).| 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: 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 usingrobust, 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.)| If None, use self.plot_settings.get(‘ymargin’) instead.| 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).| 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)
- title
- caller of function xarray_title_plot_node in module PlasmaCalcs.plotting.labelscreate a MoviePlotNode for a title associated with an xarray.DataArray.
- array: xarray.DataArray, probably ndim=3.
- the full DataArray which will be plotted throughout the movie.internally, store xarray_fill_coords(array), so that coordless dims’ indices can be used.e.g. if “dim0” is a dimension with no coords, will use np.arange(dim0.size).
- base_text: UNSET or str
- the base text string, to be formatted by array at each frame.UNSET –> will use array._title_for_slice() for array at each frame.str –> will be formatted by xarray_nondim_coords(array at frame).E.g., base_text=’fluid={{fluid}}, time={{t:.2e}} seconds’.
- t: None or str
- the array dimension which frames will index. E.g. ‘time’.None –> infer it via infer_movie_dim(array.dims, t)
- parent: None or MoviePlotNode
- if provided, the parent of this node. None -> this node has no parent.
- 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.
- text_kw: UNSET, None, or dict (default: UNSET)
- any additional kwargs for text, e.g. text_kw=dict(fontweight=bold).Applied to titles too, but individual kw can be overridden by title settings.[TODO] ability to enter unambiguous text_kw directly, e.g. fontweight.
Additional kwargs go directly to plt.title()
- 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.
- werrmean
- caller of function xarray_werrmean in module PlasmaCalcs.tools.xarray_tools.xarray_werr_statsxarray_werrmean(array, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw)returns Dataset of ‘mean’ and ‘std’ for array.
Equivalent: xarray_stats(array, stats=[‘mean’, ‘std’], …)
- 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 and std.Can provide skipna=True/False to skip NaNs or not; default True for float dtypes.see also: xarray_werradd, xarray_werrsub, xarray_werrmul, xarray_werrdiv.Example:ds = arr.pc.werrmean().pc.werradd(arr2.pc.werrmean())ds[‘mean’] == arr.mean() + arr2.mean(),ds[‘std’] == sqrt(arr.std()**2 + arr2.std()**2)
- 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.
- with_data
- caller of function xarray_with_data in module PlasmaCalcs.tools.xarray_tools.xarray_miscxarray_with_data(xarray, data, dims=None, *, name=None)return data as an xr.DataArray with dims, coords, name, and attrs copied from xarray.Similar to DataArray.copy(data=data), but here allows a bit more control.
- 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.