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).Methods
register(f_or_name, *[, aliases, totype, _name])attaches method which applies f(self.obj, *args, **kw) to xr.DataArray.pc.{name}, then returns f.
register_attr(name, value, *[, totype])register cls.{name} = value, using a similar interface as cls.register.
Attributes
access_typeaccess_type_to_clsaccessor_namealias to aggregate
caller of function xarray_aggregate in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
alias_registryalias to angle_xy
alias to angle_xy_to_hat
caller of function angle_xy in module PlasmaCalcs.quantities.patterns.vector_arithmetic
caller of function angle_xy_to_hat in module PlasmaCalcs.quantities.patterns.vector_arithmetic
alias to angle_xy
alias to angle_xy_to_hat
caller of function xarray_argsort in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_as_array in module PlasmaCalcs.tools.xarray_tools.xarray_misc
caller of function xarray_assign in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_assign_self_as_coord in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_at_max_of in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_at_min_of in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
attrs_registryalias to gaussian_filter
caller of function xarray_broadcastable_array in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_closeness in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_cmax in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_cmin in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_coarsened in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_coarsened_polyfit in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of class XarrayContour in module PlasmaCalcs.plotting.contours
caller of function xarray_convert_types in module PlasmaCalcs.tools.xarray_tools.xarray_misc
caller of function xarray_coords_dims in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_copy_kw in module PlasmaCalcs.tools.xarray_tools.xarray_misc
alias to cross_product
caller of function cross_component in module PlasmaCalcs.quantities.patterns.vector_arithmetic
caller of function cross_product in module PlasmaCalcs.quantities.patterns.vector_arithmetic
caller of function xarray_curve_eval in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_curve_fit in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_curvigrad3D in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_d_grid in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_demask_from_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masks
caller of function xarray_demote_index_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_differentiate in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_dims_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
alias to unit_vector
alias to unit_vector
alias to angle_xy
alias to angle_xy_to_hat
alias to divergence
caller of function divergence in module PlasmaCalcs.quantities.patterns.vector_derivatives
alias to dot_product
caller of function dot_product in module PlasmaCalcs.quantities.patterns.vector_arithmetic
caller of function xarray_dtype_object_to_str in module PlasmaCalcs.tools.xarray_tools.xarray_misc
caller of function xarray_ensure_dims in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of class Faceplot in module PlasmaCalcs.plotting.faceplot
caller of function xarray_faces_3D in module PlasmaCalcs.plotting.faceplot
alias to fftN
caller of function xarray_fftN in module PlasmaCalcs.tools.fft_tools.xarray_fft
caller of function xarray_fill_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_from_broadcastable in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_gamera_egg_pad in module PlasmaCalcs.hookups.mage.gamera.gamera_egg_loader
caller of function xarray_gamera_eggify in module PlasmaCalcs.hookups.mage.gamera.gamera_egg_loader
caller of function xarray_gaussian_filter in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_get_dx_along in module PlasmaCalcs.tools.xarray_tools.xarray_coords
alias to gradient
caller of function gradient in module PlasmaCalcs.quantities.patterns.vector_derivatives
caller of function xarray_has_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masks
alias to unit_vector
alias to angle_xy
alias to ifftN
caller of function xarray_ifftN in module PlasmaCalcs.tools.fft_tools.xarray_fft
caller of class XarrayImage in module PlasmaCalcs.plotting.images
caller of function xarray_index_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_interp_inverse in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function interp_masked in module PlasmaCalcs.mhd.mhd_radiative_loader
caller of function xarray_is_sorted in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_isel in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_isel_for_interp1D in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_jacobian in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_join_xyz in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
alias to join_xyz
caller of class XarrayLimsPatch in module PlasmaCalcs.plotting.patches
caller of class XarrayLine in module PlasmaCalcs.plotting.lines
caller of function xarray_line_fit in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of class XarrayLineFitter in module PlasmaCalcs.tools.xarray_tools.xarray_sci
alias to line_fit
caller of class XarrayLines in module PlasmaCalcs.plotting.lines
caller of function xarray_log_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_lowpass in module PlasmaCalcs.tools.fft_tools.xarray_fft
alias to magnitude
caller of function xarray_magnitude in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
caller of function xarray_map in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masks
caller of function xarray_max in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
caller of function xarray_max_coord_where in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_max_dim_sizes in module PlasmaCalcs.tools.xarray_tools.xarray_size_check
caller of function xarray_mean in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
caller of function xarray_mean_pm_std in module PlasmaCalcs.tools.xarray_tools.xarray_werr_stats
caller of function xarray_median in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
caller of function xarray_merge_from in module PlasmaCalcs.tools.xarray_tools.xarray_misc
caller of function xarray_min in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
caller of function xarray_min_coord_where in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
alias to magnitude
caller of function xarray_mod_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_moments in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_multiply_then_sum_along in module PlasmaCalcs.tools.xarray_tools.xarray_size_check
size of array in Mbytes
caller of function xarray_nondim_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of function xarray_np_gradient in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_object_coords_to_str in module PlasmaCalcs.tools.xarray_tools.xarray_misc
alias to parallel
caller of function parallel in module PlasmaCalcs.quantities.patterns.vector_arithmetic
alias to parmod
caller of function parmod in module PlasmaCalcs.quantities.patterns.vector_arithmetic
caller of function perp in module PlasmaCalcs.quantities.patterns.vector_arithmetic
alias to perpmod
caller of function perpmod in module PlasmaCalcs.quantities.patterns.vector_arithmetic
caller of function xarray_polyfit in module PlasmaCalcs.tools.xarray_tools.xarray_sci
caller of function xarray_predict_result_size in module PlasmaCalcs.tools.xarray_tools.xarray_size_check
caller of function xarray_prod in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
caller of function xarray_promote_dim in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_promote_index_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of class XarrayRectanglePatch in module PlasmaCalcs.plotting.patches
registered_aliasesregistered_attrsregistered_methodsregistrycaller of function xarray_rename in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_result_size_check in module PlasmaCalcs.tools.xarray_tools.xarray_size_check
caller of function xarray_rms in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
caller of function xarray_rmscomps in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
caller of function xarray_save in module PlasmaCalcs.tools.xarray_tools.xarray_io
caller of function xarray_scale_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of class XarrayScatter in module PlasmaCalcs.plotting.scatter
caller of function xarray_scatter_max in module PlasmaCalcs.plotting.scatter
caller of function xarray_scatter_min in module PlasmaCalcs.plotting.scatter
caller of function xarray_scatter_where in module PlasmaCalcs.plotting.scatter
caller of function xarray_search in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_sel in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_shift_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
total number of elements in the DataArray.
caller of function xarray_sort_array_along in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_squeeze in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_squeeze_close in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_stats in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
caller of function xarray_std in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
caller of function xarray_store_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masks
caller of function xarray_str_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
caller of class XarraySubplots in module PlasmaCalcs.plotting.subplots_extensions
caller of function xarray_sum in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
caller of function xarray_suptitle_plot_node in module PlasmaCalcs.plotting.labels
caller of function take_along_dimensions in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
caller of function xarray_take_xyz in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
caller of class XarrayText in module PlasmaCalcs.plotting.labels
caller of class XarrayTimelines in module PlasmaCalcs.plotting.xarray_timelines
caller of function xarray_title_plot_node in module PlasmaCalcs.plotting.labels
caller of function xarray_unit_vector in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
caller of function xarray_unmask in module PlasmaCalcs.tools.xarray_tools.xarray_masks
caller of function xarray_werradd in module PlasmaCalcs.tools.xarray_tools.xarray_werr_stats
caller of function xarray_werrdiv in module PlasmaCalcs.tools.xarray_tools.xarray_werr_stats
caller of function xarray_werrmean in module PlasmaCalcs.tools.xarray_tools.xarray_werr_stats
caller of function xarray_werrmul in module PlasmaCalcs.tools.xarray_tools.xarray_werr_stats
caller of function xarray_werrsub in module PlasmaCalcs.tools.xarray_tools.xarray_werr_stats
caller of function xarray_where in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
caller of function xarray_where_finite in module PlasmaCalcs.tools.xarray_tools.xarray_misc
caller of function xarray_with_data in module PlasmaCalcs.tools.xarray_tools.xarray_misc
caller of function xarray_wrapped_interp1D in module PlasmaCalcs.tools.xarray_tools.xarray_sci
- property agg
alias to aggregate
- aggregate
caller of function xarray_aggregate in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
xarray_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 strfunction to aggregate along dim. E.g. xarray.DataArray.sum, or ‘mean’.Call signature should be like: f(array, dim, **kw).str –> will call getattr(array, f)(dim, **kw).dim: None, str, or iterable of strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.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_arithmetic
angle_xy(A)
return angle between +xhat and A, in the xy plane, in radians.A should be a DataArray (or Dataset) with x and y in ‘component’ dimension.A can be any vector (does not need to be a unit vector, but it can be.)[Implementation currently just returns xarray_angle_xy(A)]
- angle_xy_to_hat
caller of function angle_xy_to_hat in module PlasmaCalcs.quantities.patterns.vector_arithmetic
angle_xy_to_hat(A)
return unit vector u, given angle [radians] between +xhat and u in the xy plane.Equivalent: cos(A) * xhat + sin(A) * yhat.[Implementation currently just returns xarray_angle_xy_to_hat(A)]
- 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_indexing
xarray_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.DataArrayarray to argsort.dim: strdimension along which to sort.newname: strresult dim will be replaced by newname.format(dim=dim). Default: ‘{dim}_sort’.ascending: boolresult sorted in ascending order if True, descending if False.nkeep: None or intnumber 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: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.squeeze: boolwhether 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_misc
xarray_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_dimensions
xarray_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 dictassign these attrs. dict of arbitrary values.name: UNSET, None, or strassign this name to the result, if provided.overwrite: None or boolwhether 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: boolwhether 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_coords
xarray_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_indexing
xarray_at_max_of(array, of, dim=None, *, promote_dims_if_needed=True)
return array values at locations of maximumof. 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.Datasetarray to get result values from.of: xarray.DataArrayarray to find maximum values in.dim: None, str, or list of strdim(s) along which to find the maximum values ofof.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: boolwhether 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_indexing
xarray_at_min_of(array, of, dim=None, *, promote_dims_if_needed=True)
return array values at locations of minimumof. 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.Datasetarray to get result values from.of: xarray.DataArrayarray to find minimum values in.dim: None, str, or list of strdim(s) along which to find the minimum values ofof.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: boolwhether 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_dimensions
xarray_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 strresult 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_dimensions
xarray_closeness(array, dim=None)
computes “closeness” along each dim: (array.isel(dim=0)/array).std()(Special case: if array.isel(dim=0) is all 0s, closeness=0 if array is all 0, else inf.)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 strsif provided, only consider these dims.See also: xarray_squeeze_close
- cmax
caller of function xarray_cmax in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
xarray_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.DataArrayarray to find max value in.coord: strcoord along which to find max.promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.see also: xarray_max_coord_where
- cmin
caller of function xarray_cmin in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
xarray_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.DataArrayarray to find minimum value in.coord: strcoord along which to find min.promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.see also: xarray_min_coord_where
- coarsened
caller of function xarray_coarsened in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
xarray_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: strdimension to coarsen.if a non-dimension coordinate, will attempt to promote it to a dimension (e.g. via swap_dims).window_len: intlength 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 strname 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 coordscoords to assign along the dim_coarse dimension.True –> use np.arange.False –> don’t assign coords.boundary, side: UNSET or valueif 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 valueif 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———-dim : mapping of hashable to int, optionalMapping 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: mappingA 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, optionalPreserve 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_sci
xarray_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: strcoordinate to polyfit along.degree: intdegree of polynomial to fit.window_len: int or Nonelength 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 coordscoords to assign along the dim_coarse dimension.True –> use np.arange.False –> don’t assign coords.boundary, side: UNSET or valueif provided (not UNSET), pass this value to coarsen().stride, fill_value, keep_attrs: UNSET or valueif 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———-dim : HashableCoordinate along which to fit the polynomials.deg : intDegree of the fitting polynomial.skipna : bool or None, optionalIf 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.rcond : float or None, optionalRelative condition number to the fit.w : Hashable, array-like or None, optionalWeights 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.full : bool, default: FalseWhether to return the residuals, matrix rank and singular values in additionto the coefficients.cov : bool or “unscaled”, default: FalseWhether to return to the covariance matrix in addition to the coefficients.The matrix is not scaled ifcov='unscaled'.Returns——-polyfit_results : DatasetA single dataset which contains:polyfit_coefficientsThe coefficients of the best fit.polyfit_residualsThe residuals of the least-square computation (only included iffull=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.contours
class 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 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.)|| 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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| PLOT_DIMS_EXPECTING = UNSET|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- convert_types
caller of function xarray_convert_types in module PlasmaCalcs.tools.xarray_tools.xarray_misc
xarray_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().
- coords_dims
caller of function xarray_coords_dims in module PlasmaCalcs.tools.xarray_tools.xarray_coords
xarray_coords_dims(array, *, include_dims_as_coords=True, include_coordless_dims=False)
returns dict of {coord name: [dim name for all dims associated with this coord]}.coords with no associated dims will appear in result with value [].coords associated with multiple dims will have multiple dim names in value list.include_dims_as_coords: boolwhether to include dims as coord names in the result.E.g., if array.coords has coord ‘x’ with dim ‘x’,include_dims_as_coords tells whether result should include {‘x’: [‘x’]}.include_coordless_dims: boolwhether to include dims with no associated coords in the result (at the end).E.g., if array has dim ‘x’ but no coord ‘x’,include_coordless_dims tells whether result should include {‘x’: [‘x’]}.(In this case, the implied coord values are just np.arange(array.sizes[‘x’]).)
- copy_kw
caller of function xarray_copy_kw in module PlasmaCalcs.tools.xarray_tools.xarray_misc
xarray_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 strif 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 strwhether to also include name in resultNone –> True if array has name, else FalseTrue –> name = array.name.str –> name = name.array_to_dataset: boolif 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_arithmetic
cross_component(A, B, x, *, yz=None, missing_ok=False)
return x component of A cross B, given A and B which have values for y and z ‘component’.x: int, str, or Componenttells component (of result) to get. if int or str, use XYZ.get(x)A, B: xarray.DataArrayvectors to take cross product of.must include ‘component’ dimension including coordinates y and z.yz: None or iterable of two (int, str, or Component) objectsthe other two components; (x,y,z) should form a right-handed coordinate system.if not provided, infer from x.missing_ok: bool, default Falsewhether it is okay for ‘component’ dimension to be missing y or z components, of A or B.if True, treat any missing components as 0.[Implementation currently just returns xarray_cross_component(A, B, x, yz=yz, …)]
- cross_product
caller of function cross_product in module PlasmaCalcs.quantities.patterns.vector_arithmetic
cross_product(A, B, *, components=None)
return cross product of vectors A and B, along dimension ‘component’.If A or B missing any components, treat them as 0.components: None or iterable of component specifiers (int, str, or Component)tells which components to get.None –> get all components (XYZ)e.g., (0, ‘z’) –> get component 0 and component ‘z’, i.e. X and Z.[Implementation currently just returns xarray_cross_product(A, B, components=components)]
- curve_eval
caller of function xarray_curve_eval in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_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.Datasetcurve_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.DataArrayx values at which to evaluate the fit.stddev: boolwhether to instead return Dataset with data_vars ‘eval+std’, ‘eval’, and ‘eval-std’,telling f(xdata, *(params+std)), f(xdata, *params), and f(xdata, *(params-std)).Fails if params is not a Dataset with ‘stddev’ data_var.
- curve_fit
caller of function xarray_curve_fit in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_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 Datasetdata to fit.Currently, Dataset allowed only if it has ‘mean’ and ‘std’ data_vars, whenstddev=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: strdim to fit along.f: callable like f(x, param1, param2, …)function to fit.stddev: boolwhether to include data_var ‘stddev’ telling standard deviation of the fit.werr_samples: intnumber 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 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 0np.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: boolwhether 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 strnames 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. 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.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 scipy.optimize.curve_fit.returns xarray.Dataset with data_vars:params: iterable along ‘param’ dimension of the parameters of the fit.e.g. call f with f(x, *result[‘params’].values) if 1D array.e.g. f(x, *result[‘params’].isel(fluid=0).values) if 2D array.stddev: standard deviation of each parameter’s fit.
- curvigrad3D
caller of function xarray_curvigrad3D in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_curvigrad3D(array, x=None, xyz=(‘x’, ‘y’, ‘z’))
return d(array)/dx, for curvilinear coordinates in 3D,i.e. where x, y, z might each be up to 3D arrays instead of 1D.For example, might have x varying across underlying dimensions i, j, k,while y varies across only i, j and z varies across only j, k.Or, maybe all three of them vary across i, j, and k.array: xarray.DataArray or Datasetarray to be differentiated.Must contain x, y, z coords, each of which can be up to 3D,and which together share some set of up to 3 underlying dimensions.x: None, str, or iterable of str.tells which coord(s) to differentiate with respect to.str –> result will be d(array)/dx.None –> equivalent to using x=xyziterable of str –> result is a Dataset with data_vars dd{x[0]}, dd{x[1]}, dd{x[2]}.(e.g., x=(‘x’, ‘y’) –> result has data_vars ‘ddx’ and ‘ddy’.)Ifarraywas already a Dataset, result is a dict with those keys instead.xyz: iterable of 3 strings, default (‘x’, ‘y’, ‘z’)tells which 3 coords form a basis for the curvilinear coordinates.Even if only getting ‘x’ derivative, the result can depend on ‘y’ and ‘z’due to the Jacobian. Really, it is because, what does “d/dx” really mean?It means “derivative when moving along x BUT not moving along y and z”.With that framing, it is clear that d/dx depends, in general, on howthe underlying grid varies with all three variables.
- d_grid
caller of function xarray_d_grid in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_d_grid(array, coord)
return the gradient of array[coord], along dim=coord if possible, else along ‘{coord}_dim’.Example (which demonstrates the motivation for this function):minvals = pc.xr1d([1,2,3], ‘mindim’)maxvals = pc.xr1d([5,7], ‘maxdim’)grid = pc.xarray_grid(min=minvals, max=maxvals, N=10, name=’grid’)# grid has sizes {‘mindim’: 3, ‘maxdim’: 2, ‘grid_dim’: 10}, and coord ‘grid’ telling values.# if grid is part of some physical formula leading to a meaningful value, e.g.:meaningful_value = grid * 10# then it might be useful to know d(grid), the spacing of ‘grid’ along ‘grid_dim’.# But, for a dimension-agnostic approach, it is important to note that a simpler grid,# like: simple_grid = pc.xarray_grid(min=1, max=7, N=10, name=’grid’)# would only have ‘grid’ and not ‘grid_dim’.# Using xarray_d_grid handles both cases properly, in one line:d_grid = xarray_d_grid(meaningful_value, ‘grid’)# or, equivalently, either of the following:d_grid = xarray_d_grid(grid, ‘grid’) # equivalent resultd_grid = xarray_d_grid(meaningful_value[‘grid’], ‘grid’) # also equivalent
- demask
caller of function xarray_demask_from_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masks
xarray_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.DataArraythe (unstacked) mask.array: xarray.DataArray or xarray.Datasetobject to unmask.stackdim: str, default ‘_mask_stack’dimension along which the mask stacking occurred.store_mask: None or boolwhether 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 boolwhether 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: boolwhether to result.reindex_like(mask). Highly recommended, but not required…_upcast_bool: boolwhether 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_coords
xarray_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 strcoords (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_coords
xarray_differentiate(array, coord, *, chain=False, keep_attrs=True, **kw__differentiate)
differentiate 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.)- if ndim(coord)>1, differentiate using chain rule!chain: ‘grid’, ‘naive’, or Falsewhether and how to apply chain rule whenever ndim(coord)>1.‘grid’ –> apply chain rule but keeping only the term for ‘{coord}_dim’:dA/dc = (dA/d(c_dim))*(d(c_dim)/dc)This is useful if you want “take partial derivative along coord_dim,but respecting the actual step size along coord”.For example, if you have an array of rays, one at each FOVx and FOVy,and ray_s = distance along each ray, generated from xarray_grid(),then ray_s might be 1D (e.g. xarray_grid(min=0, step=5, N=100, name=’ray_s’),or it might be 3D (e.g. xarray_grid(min=start, max=stop, N=100, name=’ray_s’),with start and stop both being 2D with dims FOVx and FOVy.)If it is 1D, array will have ‘ray_s’ dimension only, with appropriate coords.If it is 3D, array will have ‘ray_s’ coord, and ‘ray_s_dim’ dimension.To take derivative “along each ray, respecting step size”, can simply do:xarray_differentiate(array, ‘ray_s’, chain=’grid’),instead of needing to handle each case separately.‘naive’ –> apply full NAIVE chain rule (which gives WRONG answers):dA/dc = (dA/d(dim0))*(d(dim0)/dc) + (dA/d(dim1))*(d(dim1)/dc) + …where dim0, dim1, … are the dimensions of array[coord].That part is technically correct.But, the naive part is the following:assume d(dimN)/dc = 1/(dc/d(dimN)) if coord actually varies with dimN, else 0.This is WRONG in general; the Jacobian needs to be used instead,except for in very particular cases.[TODO] - implement jacobian in generic case, make chain=’jacob’ option?False –> never use chain rule; crash if ndim(coord)>1.keep_attrs: boolwhether 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_coords
xarray_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: boolwhether 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 div
alias to divergence
- divergence
caller of function divergence in module PlasmaCalcs.quantities.patterns.vector_derivatives
divergence(array, components=ComponentList(Component(‘x’, 0), Component(‘y’, 1), Component(‘z’, 2)), *, _post_slices=None)
return divergence of array.The result will not have ‘components’ dimension.components: iterable of str or Component objectswhich components to include in the calculation.E.g., if components=[Component(‘x’, 0), Component(‘y’, 1)],then result = d(array)/dx + d(array)/dy.The derivative is taken along the corresponding dimension,e.g. d(array)/dy is xarray_differentiate(array, dim=’y’)._post_slices: None or dict of indexers[EFF] if provided, apply these indexers to results after taking each derivative,but before merging into the final array.Equivalently, could just result.isel(**_post_slices).But, indexing before merging can help avoid ever creating a large array.
- property dot
alias to dot_product
- dot_product
caller of function dot_product in module PlasmaCalcs.quantities.patterns.vector_arithmetic
dot_product(A, B)
return dot product of vectors A and B, assuming vector components in the ‘component’ dimension.[Implementation currently just returns xarray_dot_product(A,B)]
- dtype_object_to_str
caller of function xarray_dtype_object_to_str in module PlasmaCalcs.tools.xarray_tools.xarray_misc
xarray_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_dimensions
xarray_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 stringscoords to ensure are dimensions.promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.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 Falsewhether to assert that each of these coords is 1D (after promoting if needed).return_existing_dims: bool, default FalseTrue –> 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.faceplot
class Faceplot(PlasmaCalcs.plotting.movies.MoviePlotNode, PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin)
| Faceplot(data, *, 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 DataArrays of data to plot on the faces. E.g. ‘x_z’ data goes on the x-z face.| xarray.DataArray –> 3D array; infer faces via isel z=0, y=0, and x=0, respectively.| t: None, False, or str| coord (1D) which frames will index. E.g. ‘time’.| None –> infer automatically from data[‘x_y’] array| False –> do not use time dimension; result cannot be animated.|| 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| PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin| builtins.object|| Methods defined here:|| __init__(self, data, *, 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:|| PLOT_DIMS_EXPECTING = ‘faceplot’|| 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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- faces_3D
caller of function xarray_faces_3D in module PlasmaCalcs.plotting.faceplot
xarray_faces_3D(array, ikeep=0, *, dims=(‘x’, ‘y’, ‘z’))
infer the faces (at 0th index of dims) of a 3D xarray.DataArray.ikeep: intselect 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 strthe 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_fft
xarray_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 strscoordinates(s) to take fft over.Can be pre-fft or post-fft names. (e.g. ‘x’, ‘freq_x’, ‘freqrad_x’, ‘k_x’)promote_dim(array, coord) for any non-dimension coordinates, as needed.None –> equivalent to array.dimsstr –> just this coordinate.iterable of strs –> just these coordinates.ds: None, number, or dict of {dim: d}spacing between elements of array (pre-transform), along each dim.if number, use the same value for all dims.if None, infer via array.coords[dim].diff(dim) for each dim(requires evenly-spaced coordinates in dim; spacing checked with np.allclose)rad: None or boolwhether to convert frequencies to “radians” by multiplying them by 2 * pi.E.g., for fft in space, rad=False gives 1/wavelength; rad=True gives wavenumber k.if None, infer from dim if any post-fft names provided, else default to False.abs: boolif True, return np.abs(result), instead.slices: dict or FFTSlicesinstructions for slicing the final result.Can provide {cname: indexer} instructing to slice post-fft dimensionassociated with cname, via indexer. (cname can be pre-fft or post-fft name.)These understand fractional indexing: can provide a fractional valuebetween -1 and 1, to use that fraction of the length along the relevant dimension.Can also providekeep,half,step, and/ormissing_slices, here (Or, as kwargs).(raise InputConflictError if any provided in both places and have conflicting values.)See those kwargs for more details.keep: None, True, dict, or number in 0 < keep <= 1implies the fraction of each dimension to keep.(ignored for any dimensions which already have a slice specified.)e.g. keep=0.4 with length=1000 would result in slice(300, 700),since that keeps 400 out of 1000 points, and is centered at 1000/2.None –> ignored.True –> use keep = DEFAULTS.FFT_KEEP (default: 0.4).dict –> different value in each dimension;keys can be pre-fft OR post-fft dimension names.UNSET –> use None.half: None, str, or iterable of strsdimensions along which to keep only the right half of the result.(ignored for any dimensions which already have a slice specified.)None –> ignored.str or iterable of strs –>can be pre-fft OR post-fft dimension name(s).Applied after keep, e.g. keep=0.4, length=1000, half=’x’ –> slice(500, 700) for x.UNSET –> use None.step: None, dict, int, or non-integer between -1 and 1step to take along each dim.(ignored for any dimensions which already have a slice specified.)fractional value –> use fraction of length (e.g. 0.01 –> 1% of dim length), min |step|=1.negative –> reverses direction (and swaps start & stop for the slice)None –> equivalent to using step=1.dict –> different value in each dimension;keys can be pre-fft OR post-fft dimension names.UNSET –> use None.missing_slices: ‘ignore’, ‘warn’, or ‘raise’tells how to handle keys not matching any fft-related coordinate.‘ignore’ –> silently ignore these keys. This is the default.‘warn’ –> issue a warning.‘raise’ –> raise an error.UNSET –> use ‘ignore’additional kwargs passed to np.fft.fftn.returns result of fftn(…), shifted such that the 0-frequency is in the center,and with the relevant dimensions renamed as specified.
- fill_coords
caller of function xarray_fill_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
xarray_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 strsdims for which to consider filling coords. None –> array.dims.need: None, str, or iterable of str or Nonecoords 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_dimensions
xarray_from_broadcastable(array, broadcastable, *, dims=None, squeeze=True)
return xarray from broadcastable values, using dims/coords/attrs from input.array: xarray.DataArray or xarray.Datasetread relevant dims, coords, and attrs from this array; copy to result.broadcastable: array (possibly numpy array) or dict of arraysresult’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 strlist of dim names for broadcastable’s dims. len(dims) == broadcastable.ndim.None –> use array.dims.squeeze: boolwhether to squeeze away dims with size 1 in broadcastable.True –> result.dims will only include dims with size > 1 in broadcastable.
- gamera_egg_pad
caller of function xarray_gamera_egg_pad in module PlasmaCalcs.hookups.mage.gamera.gamera_egg_loader
xarray_gamera_egg_pad(egg)
pads gamera egg along k, setting things up appropriately for interpolation.This is necessary because the “edges” of the egg (k[0] and k[-1]) areactually adjacent to each other in physical space,but not adjacent along k, and the period is pi not 2 pi,so various things need factors of -1 or need to be flipped.The result includes a copy of k[-1] before k[0], and a copy of k[0] after k[-1],but with both copies altered as follows:- alter eggzimuth by -pi for k[-1] copy, +pi for k[0] copy- set k coords to -1 for k[-1] copy, and max(k)+1 for k[0] copy- “flip” data with respect to j (along j: copy=copy[::-1].assign_coords(j=copy[j]))- multiply eggY by -1egg must have the full array in j (or be sliced by step, possibly,but not be sliced by start or stop; that would cause bad interpolation results.)
- gamera_eggify
caller of function xarray_gamera_eggify in module PlasmaCalcs.hookups.mage.gamera.gamera_egg_loader
xarray_gamera_eggify(array, Nk=None, *, Nj=None, squeeze=True, is_full=False, nok_ok=False)
eggify gamera array by stiching together the top (k<Nk//2) and bottom (k>=Nk//2) halves,connecting them at constant azimuth mod pi, attaching more j values appropriately.array: xarray.DataArray or Dataset with ‘j’ and ‘k’ dimsMust have k symmetric around Nk//2,i.e. for all k0<Nk//2 in array[‘k’], k0+Nk//2 in array as well.Nk: int or Nonefull size of k dimension in original grid (array might be only a slice of grid).if None and is_full=True, infer from array.sizes[‘k’].Nj: int or Nonefull size of j dimension in original grid (array might be only a slice of grid)if None and is_full=True, infer from array.sizes[‘j’].squeeze: boolwhether to squeeze k dimension (isel(k=0)) if there is only 1 k value in result.is_full: boolwhether to infer Nk and Nj from array[‘k’] and array[‘j’] sizes, respectively.if False, Nk and Nj must be provided explicitly.(Only use is_full=True if you know array contains the full, unsliced grid.)nok_ok: boolwhether it is okay if array has no ‘k’ dim.(If array has no ‘k’ dim, then just do the j and eggY processing.)More detailed explanation:————————–“Egg” is a cute name for the full grid shape in x, y, z coords.At fixed k (fixed azimuth) it looks like half an egg in the x-y and x-z planes too.(in x-y it looks more circular, since that is looking at the nose.)For k < Nk//2, it is the “top half”, and for k >= Nk//2 it is the “bottom half”.That is because the azimuth was varied from -pi to pi,instead of being limited to [0, pi].(Nk == self.maindims_full_sizes[‘k’])So, eggifying just means stiching together the top and bottom halves,i.e. the k < Nk//2 and k >= Nk//2 regions,and connecting them in the j axis instead of the k axis.(result k values will all be k < Nk//2.)Note: probably avoid using y and z coordinates when plotting egg data;instead strongly consider putting the eggY coordinate as the y axis.eggY will be set to eggY = sign * rcyl, wherercyl = cylidrical radius (sqrt(y^2 + z^2))sign = +1 for points originally from the “top half”, -1 otherwise.Note that sign(eggY) does not always equal sign(y)!The full result has:- half as many points in k, and twice as many points in j.- (bottom_half_region j values) == 2 * Nj - (top_half_region j values)(this makes sense when input grid j increases from nose to tailin both top and bottom regions. For continuity, after stitching,we want j to increase from nose to tail (top half) thenj in bottom half should go from tail to nose.)- coordinate ‘eggzimuth’, renamed from ‘azimuth’ if it existed,with values converted to be between 0 and pi (“top half region”).- coordinate ‘eggY’ if coordinate ‘rcyl’ exists and does not depend on k.to show image of egg, it is good to use x for x axis, eggY for y axis.
- gaussian_filter
caller of function xarray_gaussian_filter in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_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 Datasetfilters this array, or each data_var in a dataset.dim: None or str or iterable of strsdimensions to filter along.if None, filter along all dims.sigma: None, number, or iterable of numbersstandard deviation for Gaussian kernel.if iterable, must have same length as dim.if None, will use DEFAULTS.GAUSSIAN_FILTER_SIGMA (default: 1.0).promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.additional kwargs go to scipy.ndimage.gaussian_filter.
- get_dx_along
caller of function xarray_get_dx_along in module PlasmaCalcs.tools.xarray_tools.xarray_coords
xarray_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: boolif 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.
- property grad
alias to gradient
- gradient
caller of function gradient in module PlasmaCalcs.quantities.patterns.vector_derivatives
gradient(array, components=ComponentList(Component(‘x’, 0), Component(‘y’, 1), Component(‘z’, 2)), *, _post_slices=None)
return gradient of array as a single vector array.The result will have ‘components’ dimension.components: iterable of str or Component objectswhich components to include in the result.result[‘component’][i] will be components[i],and result.isel(component=j) will be the derivative along str(components[j]).E.g., if components=[Component(‘x’, 0), Component(‘y’, 1)],then result[‘component’][1] == Component(‘y’, 1),and result.isel(component=1) = d(array)/dy.The derivative is taken along the corresponding dimension,e.g. d(array)/dy is xarray_differentiate(array, dim=’y’).Note that any components provided here but missing from array will become 0 in result.e.g., components=[x,y,z] but ‘z’ not in array –>np.all(result.isel(component=2) == 0)._post_slices: None or dict of indexers[EFF] if provided, apply these indexers to results after taking each derivative,but before merging into the final array.Equivalently, could just result.isel(**_post_slices).But, indexing before merging can help avoid ever creating a large array.
- has_mask
caller of function xarray_has_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masks
xarray_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_fft
xarray_ifftN(array, dim=None, df=None, *, rad=None, pos_dims=None, ds=None, x0=0, **kw_np_ifftn)
calculates ifft(array) along N dimensions.shifts positions such that the 0-position is in the center.replaces result dimensions & coordinates appropriately, to indicate which dims were ifft’d.For convenience, all coordinate names can be pre-fft OR post-fft names,e.g. ‘x’, ‘freq_x’, ‘freqrad_x’, or ‘k_x’.“post-fft” names look like ‘freq_dim’, ‘freqrad_dim’,or any value in DEFAULTS.FFT_FREQ_RAD_DIMNAMES.values(), e.g. ‘k_x’.Caution: ifft(fft(arr)) == arr only approximately, due to floating point rounding errors.Can at least ensure coordinate alignment by providing ds during ifft(fft(arr), ds=…)dim: None, str, or iterable of strscoordinates(s) of array to take ifft over.promote_dim(array, coord) for any non-dimension coordinates, as needed.None –> equivalent to array.dimsdf: None, number, or dict of {dim: d}spacing between elements of array (in frequency-space).None –> infer from ds if provided, else infer from array.number –> use this as df for all dims.rad: None or boolif True, interpret frequency-spacing (df) like it is “in radians”,dividing it by 2 * pi before converting to position-space.None –> infer rad from names of the dims being ifft’d.ds: None, number, or dict of {dim: d}spacing between elements of result (in position-space), along dims from result.number –> use this as ds for all dims.None –> infer from df if provided, else infer from array.Note: provide ds to guarantee ifft(fft(arr)) == arr, exactly;otherwise position coords might include small rounding errors.x0: None, number, or dict of {dim: value}if provided, alter position-space coordinates by adding a constant offset,such that the 0’th position for each dim equals x0[dim].number –> apply the same number to all dims.iterable –> use these numbers; kwargdimmust also be provided as an iterable of strs.dict –> dict of {dim: x0} specifying the value associated with each dim
- image
caller of class XarrayImage in module PlasmaCalcs.plotting.images
class XarrayImage(PlasmaCalcs.plotting.movies.MoviePlotNode, PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin)
| XarrayImage(array, x=None, y=None, t=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 or xarray.Dataset with single data_var, with ndim=2 or 3.| the data to be plotted. animatable if ndim=3.| if xarray.Dataset with only one data_var, will create image of that data_var.| x, y: None or str| the array coords (each can be at most 2D) for the x, y plot axes.| None –> infer; see PlotDimsInferrer or self.plot_dims for more details.| t: None, False, or str| the array coord (1D) which frames will index. E.g. ‘time’.| None –> infer it; see PlotDimsInferrer or self.plot_dims for more details.| False –> do not use time dimension; result cannot be animated.| 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 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.)|| 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, x=None, y=None, t=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)| default style: {**DEFAULTS.PLOT.SCATTER_STYLE, **DEFAULTS.PLOT.SCATTER_MAX}| 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)| default style: {**DEFAULTS.PLOT.SCATTER_STYLE, **DEFAULTS.PLOT.SCATTER_MIN}| 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:|| PLOT_DIMS_EXPECTING = ‘image’|| 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.| x, y: None or str| if provided, tells coords for x and y axes. Passed directly to array.plot.pcolormesh or .imshow.| 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).||| ———————————————————————-| 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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- index_coords
caller of function xarray_index_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
xarray_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 strsif 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: strstring for new (index) coord names: newname.format(coord=coord).Default: ‘{coord}_index’. To keep original names, use ‘{coord}’drop: boolwhether to drop original coords after creating coord_index coords.(e.g. ‘fluid’ –> drop ‘fluid’ after making ‘fluid_index’)promote: boolwhether to promote all non-dim new index coords to dimensions.if True, xarray_promote_dim for all new index coords.exist_ok: boolwhether 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 intif 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_sci
xarray_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.See below for even more examples.[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.DataArraymust have non-None array.name.interpto: None or dictdictionary of {var: value or 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.Note: the array of values for [TODO]output: None or strname for the result variable.None –> use the key from array.dims which is missing from interpto (after xarray_ensure_dims).promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.assume_sorted: None or boolwhether 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 boolwhether 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 strmethod to pass to xarray.interp for all interpolations.if None, use xarray.interp method default.kw_interp: None or dictif 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.— More Examples —# This array should make it easier to understand, follow, and predict results:tt = pc.xrrange(5, ‘tens’)oo = pc.xrrange(10, ‘ones’)arr = (10 * tt + oo).rename(‘n’)# arr looks like: [[0, 10, …, 40], [1, 11, …, 41], …, [9, 19, …, 49]].pc.xarray_interp_inverse(arr, tens=1, n=17) == 7arr.pc.interp_inverse(tens=1, n=17) == 7 # more convenient syntax thanks to pcAccessor.# more exact matches:arr.pc.interp_inverse(tens=2, n=23) == 3 # n=23, tens=2 –> ones=3arr.pc.interp_inverse(n=20, tens=2) == 0 # n=20, tens=2 –> ones=0arr.pc.interp_inverse(n=18, ones=8) == 1 # n=18, ones=8 –> tens=1arr.pc.interp_inverse(n=29, ones=9) == 2 # n=29, ones=9 –> tens=2# inexact matches:arr.pc.interp_inverse(n=15, ones=0) == 1.5 # ones=0 –> tens needs 0.5arr.pc.interp_inverse(n=27, ones=3) == 2.4arr.pc.interp_inverse(n=23.5, tens=2) == 3.5arr.pc.interp_inverse(n=27, tens=2.5) == 2# unreachable array values (n) gives nanarr.pc.interp_inverse(n=27, tens=3) –> NaN # ones can’t compensate# out of bounds input coords (ones or tens) raises DimensionValueError (regardless of n)arr.pc.interp_inverse(n=27, ones=10) –> crash with DimensionValueErrorarr.pc.interp_inverse(n=11, ones=-1) –> crash with DimensionValueError# coords can be arrays (output will be an xarray; shown here as a list.)arr.pc.interp_inverse(ones=[7, 2], n=27)–> xr.DataArray([2.0, 2.5], name=’tens’, dims=[‘ones’], coords=dict(ones=[7, 2], n=27))arr.pc.interp_inverse(tens=[2,3], n=27)–> xr.DataArray([7.0, nan], name=’ones’, dims=[‘tens’], coords=dict(tens=[2, 3], n=27))# arr.name var can be an array:arr.pc.interp_inverse(ones=5, n=[20, 25, 30, 36])–> xr.DataArray([1.5, 2, 2.5, 3.1], name=’tens’, dims=[‘n’],coords=dict(ones=5, n=[20, 25, 30, 36]))# both can be arrays:arr.pc.interp_inverse(ones=[0, 7, 9], n=[27, 29])–> xr.DataArray([[2.7, 2.9], [2.0, 2.2], [1.8, 2.0]], name=’tens’, dims=[‘ones’, ‘n’],coords=dict(ones=[0, 7, 9], n=[27, 29]))# inputs can also be well-labeled; relevant info will be maintained:ones = xr.DataArray([7, 2], name=’customname’, dims=[‘x’], coords=dict(x=[100, 200]))arr.pc.interp_inverse(ones=ones, n=27)–> xr.DataArray([2.0, 2.5], name=’tens’, dims=[‘x’],coords=dict(ones=(‘x’, [7, 2]), n=27, x=[100, 200]))
- interp_masked
caller of function interp_masked in module PlasmaCalcs.mhd.mhd_radiative_loader
interp_masked(array, bins, dim, *, mode=’correct’, return_weights=False)
Array masked to bins, possibly with interpolation correction and normalization factors,for use in (Velocity) Differential Emission Measure ((V)DEM) binning.The result hasarraydims plusbinsdim, with values from 0 to 1.Conceptually - basically, this just tells whetherarrayoverlaps with each bin.E.g. result.isel(x=i, y=j, bindim=k) tells whether the (i,j)th x,y point overlaps with bin k.Actually - it may include an interpolation correction factor,accounting for adjacent cell values, and any jumps larger than bin widths.E.g. result.isel(x=i, bindim=k) tells how much of bin k is covered from the ith to (i+1)th x.Additionally - if return_weights, this method also returns xn, which can be applied to a value,to properly account for interpolation between adjacent cells.See Rempel et al. (2017) for details.(Note - Rempel+2017 formulas are slightly different than those here,because those formulas solve a slightly different problem.Testing those formulas here led to more numerical artifacts.)If binning multiple quantities (e.g., temperature and velocity), the canonical pattern to use is:mask1, xn = self.interp_masked(quantity1, bins1, return_weights=’exp’)mask2 = self.interp_masked(quantity2, bins2)mask3 = self.interp_masked(quantity3, bins3)… # etc. i.e., only the first call computes interpolation weights.emiss_interped = emiss * (1.0 - xn) + emiss.roll({x:1}) * xnNote - the result’s first value along dim may be unreliable (if non-periodic array),as it relies on array.roll({dim:1}).Parameters———-array : xarray.DataArrayvariable to be interp-masked. E.g., array of log10(temperature) values.bins : xarray.DataArray1D array of (evenly-spaced) bin centers (internally, assumes bin width = (bins[1]-bins[0])/2).dim : strapply the correction along this dimension of array.For VDEMS, this is the dimension along which the LOS integration will be performed.mode: ‘correct’ or ‘simple’tells how to compute the result.‘correct’ –> includes correction factor.‘simple’ –> exclude correction factor, just tells whether each point falls within each bin.Equivalent to: result = (bins - delta <= array) & (array < bins + delta),where delta = (bins[1] - bins[0]) / 2 == bin width.This can be much faster than mode=’correct’, but produces noisier results.(Also, only allowed if return_weights=False).return_weights : False, True, or ‘exp’whether to also return interpolation weights xn for each bin.False –> returns maskedTrue –> returns (masked, xn)‘exp’ –> returns (masked, xn) but compute xn using (10**value, 10**bins) not (value, bins).Returns——-masked : xarray.DataArrayarray of fn * overlaps, where overlaps = whether each cell overlaps with each bin,and fn = normalization factor for each bin, clipped to [0, 1].(Or, if mode==’simple’, this is just (bins - delta <= array) & (array < bins + delta).)xn : xarray.DataArrayInterpolation weight for each bin, with values clipped to [0, 1].(Only returned if return_weights.)
- is_sorted
caller of function xarray_is_sorted in module PlasmaCalcs.tools.xarray_tools.xarray_coords
xarray_is_sorted(array, *, increasing=True)
returns whether array is sorted; array must be 1D.increasing: boolTrue –> 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_indexing
xarray_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: boolwhether 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 byrounding, 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 intlength 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
- isel_for_interp1D
caller of function xarray_isel_for_interp1D in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_isel_for_interp1D(array, values, *, edges=False)
return minimal indices for array.isel(dim=…) that still allow interp to these values.Calling this is wholly unnecessary if the full array is already in-memory.But, it can be very useful if the original array is on disk and large,but loading array values along this single dim is easy,and we know that we only care about the interpolated result.E.g., array=x, values=10–> returns indices for [largest x less than 10, smallest x more than 10].E.g., array=y, values=[7,12]–> returns indices for [largest y less than 7, smallest y more than 7,largest y less than 12, smallest y more than 12].array: 1D xarray.DataArraymust have exactly 1 dimension.values: number or iterable of numbersvalues to be interpolated to.edges: boolwhether to allow indices outside the array size, i.e. -1 and len(array).if False (default), crash if any results are -1 or len(array)
- jacobian
caller of function xarray_jacobian in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_jacobian(array, coords, dims)
return the jacobian of array with respect to these coords and dims.This is the grid of derivatives:d(c0)/d(d0) d(c0)/d(d1) …d(c1)/d(d0) d(c1)/d(d1) ……coords: iterable of str; order matters.dims: iterable of str; order matters.Assumes coords’ dims are all in dims,and that each dim in dims appears in at least one of the coords’ dims.[TODO] output xarray with extra dims, instead of a list of lists…
- join_xyz
caller of function xarray_join_xyz in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
xarray_join_xyz(x, y, z, *, _basis=UNSET)
return vector with components x, y, z along ‘component’ dimension.(Call as xarray_join_xyz(x, y, z), or x.pc.join_yz(y,z), or x.pc.join_xyz(y,z))Result has ‘component’ coord with values ‘x’, ‘y’, ‘z’(or Component objects representing ‘x’, ‘y’, ‘z’, depending on _basis.)x, y, z: xarray.DataArray or Dataset objectsvector components to use._basis: UNSET or BasisXYZtells basis from which to infer X, Y, Z component labels.UNSET –> default to xarray_vectors._BASIS
- property join_yz
alias to join_xyz
- lims_patch
caller of class XarrayLimsPatch in module PlasmaCalcs.plotting.patches
class 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 patch params to be plotted.| if ndim=0, can still plot, but cannot animate.| 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.)| t: None, False, or str| the array coord (1D) which frames will index. E.g. ‘time’.| None –> infer it; see PlotDimsInferrer or self.plot_dims for more details.| False –> do not use time dimension; result cannot be animated.| 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| PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin| 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.|| ———————————————————————-| Data and other attributes inherited from XarrayPatch:|| PLOT_DIMS_EXPECTING = ‘just_maybe_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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- line
caller of class XarrayLine in module PlasmaCalcs.plotting.lines
class XarrayLine(PlasmaCalcs.plotting.movies.MoviePlotNode, PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin)
| XarrayLine(array, x=None, t=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.| x: None or str| the array coord (1D) for plot x axis.| None –> infer it; see PlotDimsInferrer or self.plot_dims for more details.| t: None, False, or str| the array coord (1D) which frames will index. E.g. ‘time’.| None –> infer it; see PlotDimsInferrer or self.plot_dims for more details.| False –> do not use time dimension; result cannot be animated.| 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 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.)| aspect: UNSET, None, str, or number (default: UNSET)| aspect ratio for each Axes, by default.| UNSET –> use DEFAULTS.PLOT.ASPECT (default: equal_or_auto).| None –> use matplotlib defaults; do not otherwise adjust aspect.| str –> ‘equal’, ‘auto’, or ‘equal_or_auto’.| ‘equal’ and ‘auto’ get passed directly to matplotlib; ‘equal’ is equivalent to aspect=1.| ‘equal_or_auto’ tries to pick ‘equal’, but uses ‘auto’ if aspect is too far from 1,| i.e. if max(data_aspect, 1/data_aspect) < aspect_ratio_max| (default: DEFAULTS.PLOT.ASPECT_RATIO_MAX=20)| 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| PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin| builtins.object|| Methods defined here:|| __init__(self, array, x=None, t=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.|| ———————————————————————-| Data and other attributes defined here:|| PLOT_DIMS_EXPECTING = ‘line’|| 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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- line_fit
caller of function xarray_line_fit in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_line_fit(array, dim, *, pnames=UNSET, pbounds=UNSET, **kw_curve_fitter)
returns result of xarray_curve_fit with f a line:f(x, slope, intercept) = slope * x + intercept.array: xarray.DataArray or Datasetdata to fit.Currently, Dataset allowed only if it has ‘mean’ and ‘std’ data_vars, whenstddev=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: strdim to fit along.stddev: boolwhether to include data_var ‘stddev’ telling standard deviation of the fit.werr_samples: intnumber 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 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 0np.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: boolwhether 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 strnames 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. 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 pbounds = Nonebounds: 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 XarrayCurveFitter, then xarray_curve_fit, then scipy.optimize.curve_fit.
- line_fitter
caller of class XarrayLineFitter in module PlasmaCalcs.tools.xarray_tools.xarray_sci
class 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, whenstddev=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’,| telling f(xdata, *(params+std)), f(xdata, *params), and f(xdata, *(params-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.lines
class XarrayLines(PlasmaCalcs.plotting.movies.MovieOrganizerNode, PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin)
| 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| the array coords (1D) 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 it; see PlotDimsInferrer or self.plot_dims for more details.| This gets passed to “others” in PlotDimsInferrer.| t: None or str| the array coord (1D) which frames will index. E.g. ‘time’.| None –> infer it; see PlotDimsInferrer or self.plot_dims for more details.| If no time dimension (None provided & can’t infer), that’s okay, but animation will fail.| x: None or str| the array coord (1D) for plot x axis.| None –> infer it; see PlotDimsInferrer or self.plot_dims for more details.| 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| PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin| 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|| ———————————————————————-| Data and other attributes defined here:|| PLOT_DIMS_EXPECTING = ‘lines’|| ———————————————————————-| 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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- log_coords
caller of function xarray_log_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
xarray_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 strscoords to replace with log. None –> all coords.newcoord: strstring 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: boolwhether to drop original coords’ values.True –> drop original coords.False –> add new coords but do not adjust original coords.promote: boolwhether 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_fft
xarray_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 strscoordinates to apply lowpass filter over. If None, use all array.dims.promote_dim(array, coord) for any non-dimension coordinates, as needed.keep: UNSET, True, dict, or number between 0 < keep <= 1fraction of frequencies to keep, along each dim.(Must provide this or keep_r but not both.)True –> use DEFAULTS.FFT_LOWPASS_KEEP.number –> use this value for all dims.keep_r: UNSET, True, or number between 0 < keep <= 1radius of N-sphere to keep in normalized frequency-space,normalized such that max(frequencies)==1 along each dim.All values outside of this N-sphere will be set to 0.Similar tokeep, but here use an N-sphere instead of an N-cube.(Must provide this or keep but not both.)True –> use DEFAULTS.FFT_LOWPASS_KEEP.[TODO] more options than just spherical? (e.g. ellipsoid)ds: None, number, or dict of {dim: d}spacing between elements of array along each dim.number –> use the same value for all dims.None –> infer via array.coords[dim].diff(dim) for each dim(requires evenly-spaced coordinates in dim; spacing checked with np.allclose)real: None or boolwhether to return np.real(ifft) instead of just ifft (which might have imaginary part)None –> infer from array. Use True if np.all(np.isreal(array)), else False.return_fft: boolwhether to return (result, masked fft) instead of just result.mainly intended for debugging purposes.
- property mag
alias to magnitude
- magnitude
caller of function xarray_magnitude in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
xarray_magnitude(A, *, squared=False)
return vector magnitude of A, assuming vector components along the dimension ‘component’.squared: bool, default Falseif True, return |A|**2 instead of |A|.[EFF] to get |A|**2, when |A| is not needed,magnitude(A, squared=True) is more efficient than magnitude(A)**2
- map
caller of function xarray_map in module PlasmaCalcs.tools.xarray_tools.xarray_indexing
xarray_map(array, f, *args_f, axis=None, axes=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw_f)
func(array, *args_f, **kw_f), but axis/axes can be provided as strings!Mainly 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 Datasetapply f to this array, or each array in this Datasetf: callablewill be called as f(array, *args_f, **kw_f),possibly will also be passed a value for axis or axes, if provided hereaxis, axes: None, str, or iterable of strsif 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: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.
- mask
caller of function xarray_mask in module PlasmaCalcs.tools.xarray_tools.xarray_masks
xarray_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.Datasetobject to be masked.mask: None or xarray.DataArraymask 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: boolwhether to stack result.if False, don’t stack, just use array.where(~mask). (~ means negation)create_index: boolwhether to create a MultiIndex for stackdim in the result, if stack.skip_arrays_without_mask_dims: boolwhether 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 boolwhether 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: boolwhether 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_stats
xarray_max(array, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw)
Like xarray max but first promotes dims if needed, and accepts ‘keep’ option.dim: None, str, or iterable of strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.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_indexing
xarray_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.DataArrayarray to find maximum value in.coord: strcoord whose maximum value will appear in the result.Must correspond with a single dimension of array.where: xarray.DataArray or callablelocations 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: boolwhether 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).
- max_dim_sizes
caller of function xarray_max_dim_sizes in module PlasmaCalcs.tools.xarray_tools.xarray_size_check
xarray_max_dim_sizes(array, *more_arrays, assert_broadcastable=False)
return dict of {dim: max size across all arrays} for all dims in any of the arrays.assert_broadcastable: boolwhether to raise DimensionValueError if any dim has different sizes in different arrays(other than size=1, which is considered broadcastable to any other size.)[TODO] more lenient definition which checks shared coordinates instead.
- mean
caller of function xarray_mean in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
xarray_mean(array, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw)
Like xarray mean but first promotes dims if needed, and accepts ‘keep’ option.dim: None, str, or iterable of strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.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_stats
xarray_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 strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.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_stats
xarray_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 strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.additional kwargs are passed to array.median.
- merge
caller of function xarray_merge_from in module PlasmaCalcs.tools.xarray_tools.xarray_misc
xarray_merge_from(array, other_arrays, *, ngroup=UNSET, verbose=True, **kw_xarray_merge)
xr.merge() this xarray object (DataArray or Dataset) with other xarray objects.Internally, uses xarray_merge which might be a bit more efficient than xr.merge().xarray_merge docs copied below for convenience:———————————————–xr.merge() these xarray objects (probably DataArrays or Datasets),but maybe slightly more efficiently than just using xr.merge() directly.Also, has slightly more convenient default behaviors:- by default, allow name=None on inputs (treat all inputs with None name as same name)- by default, if all inputs are DataArray with same name, output DataArray not Dataset.ngroup: int>=2, None, or UNSET[EFF] max number of arrays per xr.merge() call.(Final results should be unaffected by ngroup, just affects internal strategy.)UNSET –> use DEFAULTS.XARRAY_MERGE_NGROUP (default: 16).None –> merge all arrays in a single xr.merge() call.int>=2 –> merge arrays in groups of size ngroup, then merge the merged groups.(This can be much faster than ngroup=None; see xarray_merge for details.)verbose: bool or intwhether to print progress updates. (Ignored if N <= ngroup.)0: never print progress updates1: print updates every DEFAULTS.PROGRESS_UPDATES_PRINT_FREQ seconds (default: 2)2: print updates every file.missing_name_ok: boolwhether to allow name=None as a valid name for input arrays.True –> treat all inputs with name=None as having the same name (None).(if result is a Dataset this can lead to a key in result being None.)to_ds: Nonewhether result should be a Dataset.None –> DataArray if and only if all inputs are DataArrays with same name.True –> always return Dataset.False –> always return a DataArray (crash if any inputs are not DataArrays with same name)._updater: None or ProgressUpdaterif provided, use this (instead of a new ProgressUpdater) to print updates, ignoringverbose.— Timing notes: —Tt seems like merging more than ~16 arrays at once can cause significant slowdowns,when compared to merging groups of 16, then merging those results.Tests with xarray 2024.7.0, Python 3.9.13, with subsets of 256 arrays totaling roughly 2 GB:64 arrays with N=None –> ~42 seconds | N=2 –> ~16s | N=4, 8, 16 –> ~12s128 arrays with N=None –> (didn’t test it) | N=16 –> ~30 seconds256 arrays with N=None –> crashed due to memory errors | N=16 –> ~102 seconds
- min
caller of function xarray_min in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
xarray_min(array, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw)
Like xarray min but first promotes dims if needed, and accepts ‘keep’ option.dim: None, str, or iterable of strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.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_indexing
xarray_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.DataArrayarray to find minimum value in.coord: strcoord whose minimum value will appear in the result.Must correspond with a single dimension of array.where: xarray.DataArray or callablelocations 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: boolwhether 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_coords
xarray_mod_coords(array, mod=None, *, missing_ok=True, modshift=0, **mod_as_kw)
return copy of array with coords modded (via np.mod) bymod.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: valueshift 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: boolwhether it is okay if some coords are missing (if yes, skip missing coords).
- moments
caller of function xarray_moments in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_moments(array, dim=None)
returns Dataset of the “normalized” moments of array along dim,with data_vars ‘moment_0’, ‘moment_1’, ‘moment_2’, wheremoment_0 = sum(array) along dimmoment_1 = sum(array * x) / moment_0moment_2 = (sum(array * x**2) / moment_0) - moment_1**2array: xarray.DataArraydim: str or Nonedimension along which to compute the moments.if None, array must be 1D, and uses dim = array.dims[0].
- multiply_then_sum_along
caller of function xarray_multiply_then_sum_along in module PlasmaCalcs.tools.xarray_tools.xarray_size_check
xarray_multiply_then_sum_along(array, *more_arrays, dim, loop=(‘int’, 0.45, ‘GB’), errmsg=None)
returns result of product of arrays then .sum(dim=dim).Numerically equivalent to (arr0 * arr1 * …).sum(dim=dim).But, internally does extra checks, and can be more efficient for large arrays:- ensures intermediate steps and final result never lead to “way too large” array,i.e. never bigger than DEFAULTS.RESULT_ARRAY_GBYTES_MAX.If it would be too big, crash with helpful MemorySizeError, instead.- may loop over a dimension, depending onloop, to avoid creating large intermediate arrays.array, more_arrays: xarray.DataArray objectsthe arrays to be multiplieddim: strthe dimension to sum along after multiplying.(ignored if not present in any of the arrays.)loop: None, str, or (str, int, mode).Indicates looping instructions (if any) to use during xarray_multiply_then_sum_along.None –> no looping; simply multiply all arrays, then sum along dim.Conceptually simplest. But, internally builds unnecessarily large array,which might be larger than DEFAULTS.RESULT_ARRAY_GBYTES_MAX and thus trigger MemorySizeError.str –> loop over each point along the indicated dimension.If loop != dim, sum at each point and then concatenate final result.If loop == dim, keep a running sum during the loop; no need to concatenate final result.‘int’ or ‘sum’ –> equivalent to using loop == dim.(str, integer, mode) –> (loop dimension, chunk size, chunk size mode)loop over the indicated dimension in chunks of the indicated size,instead of only one point at a time. This is usually the most efficient option. Mode can be:‘GB’ –> size of chunk arrays in GB (approximately)E.g., (‘logT’, 5, ‘GB’) picks chunk size for logT such that each chunk is 5 GB or less.‘size’ –> number of points in the dimension.E.g., (‘x’, 5, ‘size’) does first 5 points along x, then next 5, etc.‘n’ –> number of chunks (roughly)E.g., (‘x’, 5, ‘n’) does first 1/5 of n points, then next 1/5, etc.Not guaranteed to be exactly 5 chunks, due to rounding.errmsg: None or strerror message to use if the predicted size of any intermediate array is too big.Will be hit by .format(nGB=nGB, GBmax=GBmax, dimsizes=(dict of predicted sizes of result dims)).None –> make reasonably informative default error message.
- property nMbytes
size of array in Mbytes
- nondim_coords
caller of function xarray_nondim_coords in module PlasmaCalcs.tools.xarray_tools.xarray_coords
xarray_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: boolwhether to only include coords with ndim==0.item: boolwhether to use coord.item() for scalars._sort: boolwhether 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’.
- np_gradient
caller of function xarray_np_gradient in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_np_gradient(array, dim)
return the np.gradient of array along dim, without incorporating coordinates into the math.xarray.differentiate provides the same results if coordinate is not provided for dim,or if coordinate == np.arange(array.sizes[dim]).Equivalent: xarray_map(array, np.gradient, axis=dim)
- object_coords_to_str
caller of function xarray_object_coords_to_str in module PlasmaCalcs.tools.xarray_tools.xarray_misc
xarray_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>=5if int, truncate longer strings to this length-3, and add ‘…’ to end.ndim_min: intminimum number of dimensions for a coord to be converted.e.g. ndim_min=1 –> coords with ndim=0 will not be altered
- property par
alias to parallel
- parallel
caller of function parallel in module PlasmaCalcs.quantities.patterns.vector_arithmetic
parallel(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_arithmetic
parmod(A, B, *, signed=False)
return the magnitude of the component of A parallel to B. Equivalent: |(A dot Bhat) Bhat|signed: bool; whether to return signed result instead, i.e. (A dot Bhat), without taking abs.
- perp
caller of function perp in module PlasmaCalcs.quantities.patterns.vector_arithmetic
perp(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_arithmetic
perpmod(A, B)
return 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_sci
xarray_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: boolwhether 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: boolpassed into polyfit; see below.cov: boolpassed 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: boolwhether 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———-dim : HashableCoordinate along which to fit the polynomials.deg : intDegree of the fitting polynomial.skipna : bool or None, optionalIf 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.rcond : float or None, optionalRelative condition number to the fit.w : Hashable, array-like or None, optionalWeights 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.full : bool, default: FalseWhether to return the residuals, matrix rank and singular values in additionto the coefficients.cov : bool or “unscaled”, default: FalseWhether to return to the covariance matrix in addition to the coefficients.The matrix is not scaled ifcov='unscaled'.Returns——-polyfit_results : DatasetA single dataset which contains:polyfit_coefficientsThe coefficients of the best fit.polyfit_residualsThe residuals of the least-square computation (only included iffull=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
- predict_result_size
caller of function xarray_predict_result_size in module PlasmaCalcs.tools.xarray_tools.xarray_size_check
xarray_predict_result_size(array, *more_arrays, units=’items’)
return prediction of how large the product of these xarray objects would be.(or, any other math operation which broadcasts operations in the standard way..)units: strtells the units of the result (default: ‘items’). Options:‘items’ –> number of items (elements) in the joined array.‘bytes’, ‘kB’, ‘MB’, ‘GB’ –> memory size of the data in joined array.(based on each array’s dtype.itemsize and number of items.)
- prod
caller of function xarray_prod in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
xarray_prod(array, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw)
Like xarray prod but first promotes dims if needed, and accepts ‘keep’ option.dim: None, str, or iterable of strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.additional kwargs are passed to array.prod.
- promote_dim
caller of function xarray_promote_dim in module PlasmaCalcs.tools.xarray_tools.xarray_dimensions
xarray_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 strsname 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_coords
xarray_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 strcoords (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.patches
class 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 patch params to be plotted.| if ndim=0, can still plot, but cannot 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, False, or str| the array coord (1D) which frames will index. E.g. ‘time’.| None –> infer it; see PlotDimsInferrer or self.plot_dims for more details.| False –> do not use time dimension; result cannot be animated.| 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| PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin| 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 bytransform; 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.|| ———————————————————————-| Data and other attributes inherited from XarrayPatch:|| PLOT_DIMS_EXPECTING = ‘just_maybe_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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- classmethod register(f_or_name, *, aliases=[], totype=UNSET, _name=None)
attaches method which applies f(self.obj, *args, **kw) to xr.DataArray.pc.{name}, then returns f.
(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 callablestr –> 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 straliases 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, optionalname 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
xarray_rename(array, names=None, **more_names)
return array.rename(names, **more_names), but skip any names not found in array.coords.names should be a dict, if provided.
- result_size_check
caller of function xarray_result_size_check in module PlasmaCalcs.tools.xarray_tools.xarray_size_check
xarray_result_size_check(array, *more_arrays, GBmax=UNSET, safety=1, errmsg=None)
ensure that the result of combining these xarrays (e.g., via product) is not too large.Too large if safety * predicted_size_GB > GBmaxGBmax: UNSET, None, or numbermaximum size allowed, in Gigabytes.UNSET –> use DEFAULTS.RESULT_ARRAY_GBYTES_MAXNone –> no limit (equivalent to “skip this check”)safety: numbersafety factor; safety * predicted_size_GB is the actual limit.smaller is “safer” (effectively reduces limit)errmsg: None or strerror message to use if the size is too large.will be formatted with .format(nGB=nGB, GBmax=GBmax, safety=safety,dimsizes=(dict of predicted sizes of result dims)).raises MemorySizeError if array is too large.
- rms
caller of function xarray_rms in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
xarray_rms(array, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw)
(array**2).mean(dim, **kw)**0.5dim: None, str, or iterable of strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.
- rmscomps
caller of function xarray_rmscomps in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
xarray_rmscomps(A)
return root mean squared of components of A.E.g., rmscomps(A) –> sqrt((Ax^2 + Ay^2 + Az^2) / 3), if A has 3 components.
- save
caller of function xarray_save in module PlasmaCalcs.tools.xarray_tools.xarray_io
xarray_save(array, filename=None, *, exist_ok=False, add_code_snapshot_info=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.Datasetthe array or dataset to savefilename: None or strwhere 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 Falsewhether 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_code_snapshot_info: bool or dictwhether to array.assign_attrs(details about current version of PlasmaCalcs code)Those details include ‘pc__version__’, ‘pc__commit_hash’, and ‘datetime’.If dict, pass kwargs to code_snapshot_info(). E.g. dict(default=’_undefined_’)notes: None or object to convert to strif 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: boolwhether 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: boolwhether 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: boolwhether 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 dictwhether 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 dictdict 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_coords
xarray_scale_coords(array, scale=None, *, missing_ok=True, **scale_as_kw)
return 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: boolwhether it is okay if some coords are missing (if yes, skip missing coords).
- scatter
caller of class XarrayScatter in module PlasmaCalcs.plotting.scatter
class XarrayScatter(PlasmaCalcs.plotting.movies.MoviePlotNode, PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin)
| XarrayScatter(array, t=None, *, x=None, ax=None, init_plot=True, label=UNSET, **kw_super)|| 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.| Or, consider using XarrayLines instead, with ls=’’.| [TODO] add a class (or just a function?) to handle this sort of thing automatically.| ndim == 0 is allowed (to plot a single point) only if x is provided explicitly| and x in array.coords already, and t is None or False.| t: None, False, or str| the array coord (1D) which frames will index. E.g. ‘time’.| None –> infer it; see PlotDimsInferrer or self.plot_dims for more details.| False –> do not use time dimension; result cannot be animated.| x: None or str| the array coord (1D) for plot x axis.| None –> infer it; see PlotDimsInferrer or self.plot_dims for more details.| 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 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.)|| 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| PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin| builtins.object|| Methods defined here:|| __init__(self, array, t=None, *, x=None, ax=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 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.|| ———————————————————————-| Data and other attributes defined here:|| PLOT_DIMS_EXPECTING = ‘line’|| 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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- scatter_max
caller of function xarray_scatter_max in module PlasmaCalcs.plotting.scatter
xarray_scatter_max(array, x, y, *, t=None, **kw_scatter)
use XarrayScatter to plt.scatter() a single marker, at the argmax of array.default style: {**DEFAULTS.PLOT.SCATTER_STYLE, **DEFAULTS.PLOT.SCATTER_MAX}array: xarray.DataArrayarray whose max will be marked.x: strcoordinate to use for x-axis values.y: strcoordinate to use for y-axis values.t: None or strcoordinate 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
xarray_scatter_min(array, x, y, *, t=None, **kw_scatter)
use XarrayScatter to plt.scatter() a single marker, at the argmin of array.default style: {**DEFAULTS.PLOT.SCATTER_STYLE, **DEFAULTS.PLOT.SCATTER_MIN}array: xarray.DataArrayarray whose min will be marked.x: strcoordinate to use for x-axis values.y: strcoordinate to use for y-axis values.t: None or strcoordinate 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.scatter
xarray_scatter_where(arr, condition=None, *, x, y, t=None, **kw_scatter)
use XarrayScatter to plt.scatter() markers wherever arr==True.Roughly equivalent: arr[y].where(arr).pc.scatter(x=x, t=t, **kw_scatter)arr: xarray.DataArrayarray of bools, or array to be provided to condition if condition is callable.condition: None, array of bools, or callableNone –> 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: strcoordinate to use for x-axis values.y: strcoordinate to use for y-axis values.t: None or strcoordinate 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_indexing
xarray_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_indexing
xarray_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: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.method: None or strmethod 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_coords
xarray_shift_coords(array, shift=None, *, missing_ok=True, **shift_as_kw)
return 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: boolwhether 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_indexing
xarray_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.DataArrayarray to sort.dim: strdimension along which to sort.newname: strresult dim will be replaced by newname.format(dim=dim). Default: ‘{dim}_sort’.ascending: boolresult sorted in ascending order if True, descending if False.nkeep: None or intnumber 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: boolwhether 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: boolwhether 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: strname to use for original dim’s coord values if store_original=True. Default: ‘{dim}_orig’.promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.squeeze_argsort: boolwhether 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_dimensions
xarray_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 strsif provided, only consider dropping these dims.keep: None, str, or list of strsif provided, do not consider dropping these dims.(can provide dim or keep, but not both.)drop: boolwhether 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_dimensions
xarray_squeeze_close(array, dim=None, tol=0.001, *, closeness_as=’coords’, 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.(Special case: if array.isel(dim=0) is all 0s, closeness=0 if array is all 0, else inf.)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 strsif provided, only consider dropping these dims.tol: numberdrops dim with tol >= (array.isel(dim=0)/array).std().Use tol=0 to only drop dims with exactly 0 variation along them,i.e., only dims with all(array.isel(dim=0) == array).closeness_as: ‘coords’, ‘attrs’, or Nonewhere to put information about closeness == pre-squeeze variation along each dim,for each dim dropped. (closeness = array.isel(dim=0)/array).std())(smaller is closer.) (always 0 for dims of size 1.)‘coords’ –> put info in result.coords‘attrs’ –> put info in result.attrsNone –> do not include closeness values in the result.closeness_name: str, default ‘closeness_{dim}’name for closeness info (seecloseness_asabove for details).keep: None, str, or list of strsif provided, do not consider dropping these dims.(can provide dim or keep, but not both.)drop: boolwhether 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_stats
xarray_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.Datasetthe 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 strsapply operation along these dimensionsstats: 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 strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.if not ‘raise’, any missing dims will be skipped.to_da: None, bool, or strwhether to return DataArray instead of Dataset.None –> True ifarrayis 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_stats
xarray_std(array, dim=None, *, keep=None, promote_dims_if_needed=True, missing_dims=’raise’, **kw)
Like xarray std but first promotes dims if needed, and accepts ‘keep’ option.dim: None, str, or iterable of strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.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_masks
xarray_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.Datasetif 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_coords
xarray_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 strscoords to replace with str. None –> all coords.newcoord: strstring for new (converted-to-str) coord names: newcoord.format(coord=coord).Default: ‘str_{coord}’. To keep original names, use ‘{coord}’drop: boolwhether to drop original coords’ values.True –> drop original coords.False –> add new coords but do not adjust original coords.promote: boolwhether to promote all non-dim new str coords to dimensions.if True, xarray_promote_dim for all new str coords.missing_ok: boolwhether it is okay for some providedcoordsto be missing from array.coords.
- subplots
caller of class XarraySubplots in module PlasmaCalcs.plotting.subplots_extensions
class XarraySubplots(MovieSubplots, PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin)
| XarraySubplots(array, 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 array data. Can be animated as a movie!|| array: 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(array) to utilize coordless dims’ indices in titles.| row: None, False, or str| coord (1D) to plot ACROSS rows. E.g. row=’fluid’ –> i’th COLUMN is fluid i.| None –> infer automatically from array. row will be inferred before column.| False –> do not use row dimension; result has ncols=1 (unless using wrap).| col: None, False, or str| coord (1D) to plot DOWN columns. E.g. col=’component’ –> j’th ROW is component j.| None –> infer automatically from array.| False –> do not use col dimension; result has nrows=1 (unless using wrap).| 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| x and y axes’ coords for each subplot (each can be at most 2D within each subplot)| None –> infer from the array coords. See also: DEFAULTS.PLOT.DIMS_INFER| t: None, False, or str| coord (1D) dimension name for the time axis (for movies).| None –> infer from the array coords. See also: DEFAULTS.PLOT.DIMS_INFER| False –> do not use time dimension; result cannot be animated.|| 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_or_auto).| None –> use matplotlib defaults; do not otherwise adjust aspect.| str –> ‘equal’, ‘auto’, or ‘equal_or_auto’.| ‘equal’ and ‘auto’ get passed directly to matplotlib; ‘equal’ is equivalent to aspect=1.| ‘equal_or_auto’ tries to pick ‘equal’, but uses ‘auto’ if aspect is too far from 1,| i.e. if max(data_aspect, 1/data_aspect) < aspect_ratio_max| (default: DEFAULTS.PLOT.ASPECT_RATIO_MAX=20)| 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’] unlessfontfamilyspecified 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| PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin| builtins.object|| Methods defined here:|| __init__(self, array, 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).| default style: {**DEFAULTS.PLOT.SCATTER_STYLE, **DEFAULTS.PLOT.SCATTER_MAX}| 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).| default style: {**DEFAULTS.PLOT.SCATTER_STYLE, **DEFAULTS.PLOT.SCATTER_MAX}| 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.plot_dims.t_coord 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|| ———————————————————————-| Data and other attributes defined here:|| PLOT_DIMS_EXPECTING = ‘image_subplots’|| ———————————————————————-| 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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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’, …)|| grid(self, *args_grid, **kw_grid)| 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.)|| iter_col(self, icol, *, sca=True, restore=True, **kw_iter_ax)| 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.)|| iter_row(self, irow, *, sca=True, restore=True, **kw_iter_ax)| 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 0x755d5c390b80>|| updaters(self, *, fill_value=None)| return array of updaters for each ax (or fill_value if no updater on that ax).|| xlabel(self, xlabel, mode=None, *, only=True, **kw)| 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.|| ylabel(self, ylabel, mode=None, *, only=True, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- sum
caller of function xarray_sum in module PlasmaCalcs.tools.xarray_tools.xarray_agg_stats
xarray_sum(array, dim=None, *, keep=None, skipna=False, promote_dims_if_needed=True, missing_dims=’raise’, **kw)
Like xarray sum but first promotes dims if needed, and accepts ‘keep’ option.dim: None, str, or iterable of strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)skipna: boolwhether to skip NaNs. Unlike xarray’s builtin sum(), the default here is False.False –> NaNs in input produce NaNs in same locations in output,e.g. [[1,nan,2],[3,4,5]] summing along dim 0 becomes [4, nan, 7].True –> equivalent to replacing all NaNs with 0 before summing.e.g. [[1,nan,2],[3,4,5]] summing along dim 0 becomes [4, 4, 7].promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.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.labels
xarray_suptitle_plot_node(array, base_text=UNSET, t=None, *, fig=None, parent=None, **kw)
create 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 strthe 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 strthe array dimension which frames will index. E.g. ‘time’.None –> infer it from array coords.parent: None or MoviePlotNodeif 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_dimensions
take_along_dimensions(array, dimensions, *, atleast_1d=False, **kw_isel)
returns result of taking array along each of these dimensions, in order.result will be a numpy array with dtype=object, shape=(d0, d1, …),where di = len(array.coords[dimensions[i]]).each element of result will be an xarray.DataArray.any dimension can be None –> result shape will be 1 at that dimension, and nothing will be taken.E.g. take_along_dimensions(array, [None, ‘fluid’]) gives array of shape (1, len(fluids)).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.
- take_xyz
caller of function xarray_take_xyz in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
xarray_take_xyz(A, *, drop=False, as_dict=False)
return [Ax, Ay, Az] from selecting ‘x’, ‘y’, ‘z’ along ‘component’ dimension.Crashes if any components are missing.drop: boolwhether to drop x, y, z ‘component’ coord from results.as_dict: boolif True, return dict(x=Ax, y=Ay, z=Az) instead of list [Ax, Ay, Az].
- text
caller of class XarrayText in module PlasmaCalcs.plotting.labels
class XarrayText(MovieText, PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin)
| XarrayText(array, txt, t=None, *, base_text=None, **kw_super)|| 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 from array coords.| 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 PlotDimsInferrer 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| PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin| builtins.object|| Methods defined here:|| __init__(self, array, txt, t=None, *, base_text=None, **kw_super)|| 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).|| ———————————————————————-| Data and other attributes defined here:|| PLOT_DIMS_EXPECTING = ‘get_maybe_t’|| ———————————————————————-| 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.|| get_animator(self, *, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)| 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(self, filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)| 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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).|| has_node_where(self, condition, *, include_self=False)| returns True if any node in self or descendants satisfies condition(node).| if include_self, check self as well.|| 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|| ———————————————————————-| Data descriptors inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims| PlotDimsInferrer for this plotting object.| Created from plot_dims_inputs and PLOT_DIMS_EXPECTING.| See help(self.plot_dims_inferrer_cls) for more details.|| plot_dims_inputs| inputs for creating self.plot_dims.| (Internally actually uses PlotDimsInferrer._translate_inputs(plot_dims_inputs);| provide _skip_translation=True to skip the normal translation rules.)|| ———————————————————————-| Data and other attributes inherited from PlasmaCalcs.plotting.plot_tools.plot_dims.PlotDimsMixin:|| plot_dims_inferrer_cls = <class ‘PlasmaCalcs.plotting.plot_tools.plot_…| manages inferring dims (or maybe 2D+ coords!) to use for plotting.|| Parameters below, followed by explanation of non-str options.| Note that explicitly-provided selections can be implicitly-creatable;| e.g. ‘log_x’ or ‘x_index’ from ‘x’. All options (for any d in coords) are:| ‘log_d’ –> log10 of d’s values| ‘d_index’ –> np.arange(array.sizes[d]) if 1D, else array of tuples telling ndindex.| ‘str_d’ –> str(v) for v in d’s values. (E.g. useful if d has object values)|| coords_or_array: UNSET, xarray.DataArray or Dataset, list of str, or dict of (str or list of str)| xarray.DataArray or other way to indicate all possible dims and 1D+ coords.| Order matters only as a last resort for inferring a dim from otherwise-equal-priority coords.| UNSET –> providecoordsorarrayinstead.| DataArray or Dataset –> coords = xarray_coords_dims(array, include_coordless_dims=True)| list of str –> list of dim names.| dict –> mapping from coord/dim or list of dims associated with coord/dim.| (for key d which is already a dim, value should just be [d].)| coords: UNSET, list of str, or dict of (str or list of str)| same as coords_or_array, but only for coords.| UNSET –> providearrayorcoords_or_arrayinstead.| array: UNSET or xarray.DataArray or Dataset| same as coords_or_array, but only for array.| UNSET –> providecoordsorcoords_or_arrayinstead.| xy_2D_ok: bool| whether to allow x and y to correspond to 2D coordinates, instead of dims.| False –> x and y must correspond to 1D coords or dims.| x, y: ATTR_UNSET, UNSET, False, None, or str| coords or dims for x and y axes of the plot.| x, y must be 1D or 2D (e.g. for pcolormesh) within each subplot (i.e. after removing row & col dims).| row, col: ATTR_UNSET, UNSET, False, None, or str| dims to iterate over across subplot rows / down subplot columns.| row, col must be 1D.| row = dim to plot ACROSS rows, e.g. if row=’fluid’ then i’th column is i’th fluid.| col = dim to plot DOWN columns, e.g. if col=’component’ then i’th row is i’th component.| t: UNSET, False, None, or str| dim for time dimension of the plot (frames of a movie).| t must be 1D.| others: ATTR_UNSET, UNSET, False, None, or list of strs| other dims (or coordinates) to use for plotting, which may be used by other kinds of routines.| e.g., might put others=[‘line_number’] for a line plot with multiple lines.| each coord in others must be 1D (for now).| expecting: UNSET or str| shorthand to specify whether x, y, row, col, and other(s) should default to False or to None,| if they are not provided (i.e. if they are still the default of ATTR_UNSET).| For all options, see cls.EXPECTING_OPTIONS. Examples include:| ‘image’ –> x=y=None, row=col=False, others=False| ‘image_subplots’ –> x=y=None, row=col=UNSET, others=False| ‘get_maybe_t’ –> x=y=row=col=False, others=UNSET| ‘lines’ –> x=None, y=False, row=col=False, others=UNSET| _prioritize_row_if_small: False or (True or int, dict of dim sizes)| whether to prioritize inferring ‘row’ before ‘t’ if both would otherwise have the same priority level| (i.e. both UNSET or both None) and inferred row would be “small” in size.| “small” determined by int if input, else DEFAULTS.PLOT.SUBPLOTS_MAX_NROWS_NCOLS.| This rule is applied at a late stage of the inferring process,| (after trying to infer x, y, and checking for DIMS_INFER[‘t’])| so it might apply only rarely. If a known behavior is desired, just set t or row explicitly.| DIMS_INFER: UNSET or dict of (str: list of str)| mapping from dim name to list of coords/dims to check for inferring that dim.| UNSET –> use DEFAULTS.PLOT.DIMS_INFER. (See defaults.py for more info.)|| The following non-str options are available for x, y, t, row, and col:| ATTR_UNSET –> default must be implied byexpectingkwarg, else crash.| (not available for t; t cannot be ATTR_UNSET.)| UNSET –> only attempt to infer and use this dim for plotting if needed,| i.e. if there are extra unaccounted-for dims after inferring other dims.| False –> do not use this dim for plotting, and do not attempt to infer this dim.| (e.g., if not doing subplots, then row and col should be False.)| None –> dim not specified, but desired, and must be inferred.| (for x, y, t, row, col, this increases priority of inferring, compared to UNSET;| internally will attempt to fill any None before any UNSET.| However, forothers, the priority is not increased;| even others=None will only be filled after all other dims are inferred.| Setting others=None just means to crash if len(others)==0 at the end.)
- timelines
caller of class XarrayTimelines in module PlasmaCalcs.plotting.xarray_timelines
class 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.| Currently, this is highly specialized for this particular purpose,| including some convenient functionality not yet implemented for XarrayLines,| partly because XarrayTimelines is not trying to be animatable.| [TODO] maybe generalize and combine XarrayLines and XarrayTimelines?| XarrayTimelines could probably be a (mostly-)thin wrapper around XarrayLines.|| 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’| ifarrayis 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:|| __init_subclass__(*args_super, **kw) from builtins.type| 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.labels
xarray_title_plot_node(array, base_text=UNSET, t=None, *, ax=None, parent=None, **kw)
create 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 strthe 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 strthe array dimension which frames will index. E.g. ‘time’.None –> infer it from array coords.parent: None or MoviePlotNodeif 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 xarray_unit_vector in module PlasmaCalcs.tools.xarray_tools.xarray_vectors
xarray_unit_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_masks
xarray_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.Datasetobject to unmask.mask: None or xarray.DataArraythe (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 boolwhether 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 boolwhether 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: boolwhether to result.reindex_like(mask). Highly recommended, but not required…_upcast_bool: boolwhether 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_stats
xarray_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: boolwhether 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_stats
xarray_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: boolwhether 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_stats
xarray_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 strsapply operation along these dimensionskeep: None, str, or iterable of strsapply operation along all except for these dimensions.(can provide keep or dim, but not both.)promote_dims_if_needed: boolwhether to promote non-dimension coords to dimensions.if False, raise DimensionKeyError if any relevant coord is not already a dimension.missing_dims: str in (‘ignore’, ‘warn’, ‘raise’)what to do if any coord is not found:‘ignore’ –> do nothing.‘warn’ –> raise a warning.‘raise’ –> raise DimensionKeyError.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_stats
xarray_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: boolwhether 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_stats
xarray_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: boolwhether 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_indexing
xarray_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.Datasetarray to apply condition to.cond: xarray.DataArray, xarray.Dataset, or callableLocations at which to preserve array’s values. Must have dtype=bool.callable –> replace with cond(array).other: UNSET, scalar, DataArray, Dataset, or callable, optionalValue 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: FalseIf True, coordinate labels that only correspond to False values ofthe condition are dropped from the result.skip_if_no_matching_dims: bool, default: TrueIf 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_misc
xarray_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_misc
xarray_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 strif 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 strwhether to also include name in resultNone –> True if array has name, else FalseTrue –> name = array.name.str –> name = name.
- wrapped_interp1D
caller of function xarray_wrapped_interp1D in module PlasmaCalcs.tools.xarray_tools.xarray_sci
xarray_wrapped_interp1D(array, dim, values, *, wrap, demote=True, method=’linear’, **kw_interp)
return array interpolated to values, along dim, assuming wrap-around at wrap.For example: array[‘theta’] = 10, 30, 50, …, 350; dim=’theta’, wrap=360,values=xr.DataArray([0, 5, 20, 355], dim=’myangles’), method=’linear’ –>result[‘myangles’] == [0, 5, 20, 355], with values across myangles being:result.isel(myangles=0) = 0.5*arr.isel(theta=-1) + 0.5*arr.isel(theta=0)result.isel(myangles=1) = 0.25*arr.isel(theta=-1) + 0.75*arr.isel(theta=0)result.isel(myangles=2) = 0.5*arr.isel(theta=0) + 0.5*arr.isel(theta=1)result.isel(myangles=3) = 0.75*arr.isel(theta=-1) + 0.25*arr.isel(theta=0)(e.g., the 0 degrees value is halfway between the 10 degrees and 350 degrees value,instead of being nan or some extrapolation from purely the 10 degrees value).array: xarray.DataArraythe array to be interpolated; any number of dims is fine.dim: strthe dimension to interpolate along.(or, can provide a 1D coordinate, and will automatically infer the implied dim.)values: xarray.DataArray (any number of dims) or single valuetells values to interp to.wrap: numberthe wrap-around value for dim.demote: boolif provided dim= 1D coord (which is not a dimension) and result would vary along dim,this tells whether to demote coord back to coord at the end,i.e. whether to promote dim to a dimension.e.g., maybe array varies across ‘i’ dim, with ‘theta’ coord along ‘i’,and you want to interpolate based on ‘theta’ but keep ‘i’ as the dim afterward,then use demote=True. To make result instead have ‘theta’ as dim, use demote=False.method: ‘linear’ or any other method to provide to xarray.interp(not yet implemented, must use ‘linear’.Other methods might require additional padding, or less padding;that can be implemented later if needed.)additional kwargs get passed to xarray.interp.