DictOfSimilar

class PlasmaCalcs.tools.iterables.DictOfSimilar

Bases: dict

dict of similar objects with similar attributes.

similar attributes list stored in SIMILAR_ATTRS.
In many ways, simply broadcasts operations to all values in the dict.
See self.to_ds(), to_da(), and to_xr() for helpful methods to convert result to xarray objects
(These are defined in xarray_tools and bound to the DictOfSimilar class there).

Methods

__add__(other)

self + other.

__call__(*args[, dos_verbose])

call obj(*args, **kw) for each object in self.

__floordiv__(other)

self // other.

__getattr__(attr)

self.getattrs(attr) if attr in SIMILAR_ATTRS.

__getitem__(i)

self[i[0]].getitems(i[1]) if i tuple and i[0] in SIMILAR_ATTRS.

__mod__(other)

self % other.

__mul__(other)

self * other.

__neg__()

-self.

__pos__()

+self.

__pow__(other)

self ** other.

__radd__(other)

other + self.

__rfloordiv__(other)

other // self.

__rmod__(other)

other % self.

__rmul__(other)

other * self.

__rpow__(other)

other ** self.

__rsub__(other)

other - self.

__rtruediv__(other)

other / self.

__setattr__(attr, value)

self.setattrs(attr, value) if attr in SIMILAR_ATTRS, otherwise super().__setattr__.

__setitem__(i, value)

self.setitems(i[1], value) if i tuple and i[0] in SIMILAR_ATTRS.

__str__()

like repr but never abbreviate.

__sub__(other)

self - other.

__truediv__(other)

self / other.

apply(func, *args, **kw)

return func(obj, *args, **kw) for each object in self.

callattrs(attr, *args[, dos_verbose])

call obj.attr(*args, **kw) for each object in self.

clear()

copy()

fromkeys([value])

Create a new dictionary with keys from iterable and values set to value.

get(key[, default])

Return the value for key if key is in the dictionary, else default.

getattrs(attr[, default])

get obj.attr for each object in self.

getitems(i)

get obj[i] for each object in self.

items()

keys()

pop(k[,d])

If key is not found, default is returned if given, otherwise KeyError is raised

popitem()

Remove and return a (key, value) pair as a 2-tuple.

setattrs(attr, value)

set obj.attr = value for each object in self.

setdefault(key[, default])

Insert key with a value of default if key is not in the dictionary.

setitems(i, value)

set obj[i] = value for each object in self.

subset([keep, drop])

return DictOfSimilar like self but with only a subset of the keys from self.

to_da([dim, ds, da_dim, var, drop_coords, ...])

return DataArray based on values in self.

to_ds([da_dim, var, drop_coords, ...])

return Dataset based on values in self.

to_xr([dim, da_dim, var, drop_coords, ...])

return xarray.DataArray or Dataset, stacking values in self along the new dimension.

update([E, ]**F)

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]

values()

_math_op(other, op)

apply op to self and other.

_new(*args, **kw)

return a new DictOfSimilar of the same type as self.

_updater(dos_verbose, *[, wait])

return ProgressUpdater with print_freq appropriate for dos_verbose.

Attributes

REPR_ITEM_MAXLEN

SIMILAR_ATTRS

ca

alias to callattrs

cls_new

do

alias to apply

ga

alias to getattrs

gi

alias to getitems

sa

alias to setattrs

si

alias to setitems

__add__(other)

self + other. At each key if other is a dict, else apply to each value in self.

__call__(*args, dos_verbose=True, **kw)

call obj(*args, **kw) for each object in self.

dos_verbose: bool or number
whether to print progress updates from DictOfSimilar while looping.
False or <=0 –> no updates
True –> updates every 5 seconds
>=2 and <5 –> updates every 2 seconds
>=5 –> updates every loop iteration
__floordiv__(other)

self // other. At each key if other is a dict, else apply to each value in self.

__getattr__(attr)

self.getattrs(attr) if attr in SIMILAR_ATTRS. Else raise AttributeError.

(Only invoked when object.__getattr__(self, attr) fails.)
__getitem__(i)

self[i[0]].getitems(i[1]) if i tuple and i[0] in SIMILAR_ATTRS.

(e.g. self[‘snap’, 0] returns self[‘snap’].getitems(0)
otherwise, try super().__getitem__.
if that fails, try to return list(self.values())[i]
(e.g., self[3] will return 3rd object, unless 3 in self.keys())
__mod__(other)

self % other. At each key if other is a dict, else apply to each value in self.

__mul__(other)

self * other. At each key if other is a dict, else apply to each value in self.

__neg__()

-self. Apply to each value in self.

__pos__()

+self. Apply to each value in self.

__pow__(other)

self ** other. At each key if other is a dict, else apply to each value in self.

__radd__(other)

other + self. At each key if other is a dict, else apply to each value in self.

__rfloordiv__(other)

other // self. At each key if other is a dict, else apply to each value in self.

__rmod__(other)

other % self. At each key if other is a dict, else apply to each value in self.

__rmul__(other)

other * self. At each key if other is a dict, else apply to each value in self.

__rpow__(other)

other ** self. At each key if other is a dict, else apply to each value in self.

__rsub__(other)

other - self. At each key if other is a dict, else apply to each value in self.

__rtruediv__(other)

other / self. At each key if other is a dict, else apply to each value in self.

__setattr__(attr, value)

self.setattrs(attr, value) if attr in SIMILAR_ATTRS, otherwise super().__setattr__.

__setitem__(i, value)

self.setitems(i[1], value) if i tuple and i[0] in SIMILAR_ATTRS. otherwise super().__setitem__.

__str__()

like repr but never abbreviate. Also, use str of objs.

__sub__(other)

self - other. At each key if other is a dict, else apply to each value in self.

__truediv__(other)

self / other. At each key if other is a dict, else apply to each value in self.

_math_op(other, op)

apply op to self and other. If other is a dict, apply op to self[k] and other[k] for each k.

Otherwise, apply op to each value in self and other.
_new(*args, **kw)

return a new DictOfSimilar of the same type as self.

_updater(dos_verbose, *, wait=True)

return ProgressUpdater with print_freq appropriate for dos_verbose.

dos_verbose: bool or number
whether to print progress updates from DictOfSimilar while looping.
False or <=0 –> no updates
True –> updates every 5 seconds
>=2 and <5 –> updates every 2 seconds
>=5 –> updates every loop iteration
apply(func, *args, **kw)

return func(obj, *args, **kw) for each object in self.

property ca

alias to callattrs

callattrs(attr, *args, dos_verbose=False, **kw)

call obj.attr(*args, **kw) for each object in self.

dos_verbose: bool or number
whether to print progress updates from DictOfSimilar while looping.
False or <=0 –> no updates
True –> updates every 5 seconds
>=2 and <5 –> updates every 2 seconds
>=5 –> updates every loop iteration
clear() None.  Remove all items from D.
copy() a shallow copy of D
property do

alias to apply

fromkeys(value=None, /)

Create a new dictionary with keys from iterable and values set to value.

property ga

alias to getattrs

get(key, default=None, /)

Return the value for key if key is in the dictionary, else default.

getattrs(attr, default=UNSET)

get obj.attr for each object in self.

getitems(i)

get obj[i] for each object in self.

property gi

alias to getitems

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, default is returned if given, otherwise KeyError is raised

popitem()

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order.

Raises KeyError if the dict is empty.
property sa

alias to setattrs

setattrs(attr, value)

set obj.attr = value for each object in self.

setdefault(key, default=None, /)

Insert key with a value of default if key is not in the dictionary.

Return the value for key if key is in the dictionary, else default.

setitems(i, value)

set obj[i] = value for each object in self.

property si

alias to setitems

subset(keep=None, *, drop=None)

return DictOfSimilar like self but with only a subset of the keys from self.

keep: None, iterable, or callable

None –> no restrictions from keep
iterable –> only keep self[k] for k in keep.
callable –> only keep (k,v) from self.items() if keep(k, v).
drop: None, iterable, or callable
None –> no restrictions from drop
iterable –> drop self[k] for k in drop.
callable –> drop (k,v) from self.items() if drop(k, v).
If any conflict between drop and keep, drop takes priority.
(E.g. if ‘key1’ in keep and in drop, it will be dropped, not kept.)
to_da(dim='variable', *, ds=False, da_dim=None, var=None, drop_coords=False, str_coords=False, item=False, errors_ok=False, **kw_to_ds)

return DataArray based on values in self.

The default behavior of this method is equivalent to:
return xr.Dataset(self).to_dataarray(dim=dim)
The other inputs enable to do some processing steps on self.values first.
If passing any inputs other than dim and ds, self.to_da(dim, **kw) is equivalent to:
return self.to_ds(**kw).to_dataarray(dim=dim)
dim: str
name of new dimension, across which to stack the data_vars from the dataset.
ds: bool
whether to convert result back into a Dataset.
shorthand for the pattern:
self.to_ds(dim, da_dim=’dadim’, **kw).to_dataset(‘dadim’)
Useful e.g. if self.values are datasets already,
and the goal is to end up with a Dataset just like each value in self,
but with the result also having the new dim dimension (with size==len(self))
if True, cannot also provide da_dim, and internally uses da_dim=’__da_dim_internal__’
Docs for to_ds() copied below, for convenience:
———————————————–
error indicating an issue with binding; see tools.binding.
to_ds(da_dim=None, *, var=None, drop_coords=False, str_coords=False, item=False, errors_ok=False)

return Dataset based on values in self.

The default behavior of this method is equivalent to:
return xr.Dataset(self)
The main reason to use to_ds is to do common processing steps on the values first.
No processing steps will be attempted by default.
Providing inputs can enable various steps, in this order:
(1) replace values with value[var]
(2) convert values to DataArray via value.to_dataarray(da_dim)
(3) drop some coords from each value
(4) convert values’ coords to strings via xarray_str_coords
(5) convert values to scalars via value.item()
Input options described below.
var: None, str, or iterable of str.
if provided, will get value[var] for each value in self.
da_dim: None or str
if provided, will call value.to_dataarray(da_dim) for each value in self.
drop_coords: bool, str, or list of strs
whether to call value.drop_vars(…) for each value in self.
True –> value.drop_vars(value.coods)
str or list of strs –> value.drop_vars(drop_coords)
str_coords: bool, str, or list of strs
whether to call xarray_str_coords on each value in self.
True –> converts all coords’ values to strs.
str or list of strs –> xarray_str_coords(value, str_coords, promote=True)
item: bool
whether to call value.item() for each value in self.
errors_ok: bool
whether to ignore simple errors during processing.
if True:
var non-None but value not dict or Dataset –> skip this step.
da_dim non-None but values are not Datasets –> skip this step.
drop_coords –> value.drop_vars(drop_coords, errors=’ignore’).
str_coords –> xarray_str_coords(value, str_coords, missing_ok=True).
item but value.item() fails with ValueError or AttributeError –> skip this step.
Example:
mc = pc.MultiCalculator(…)
dos = mc(‘mean_n’, snap=7) # depends on ‘fluid’ dim, but also has ‘snap’ and ‘t’ coords.
n_vals = dos.to_ds(str_coords=’fluid’, drop_coords=(‘snap’, ‘t’))
# str_coords=’fluid’ because ‘fluid’ might be different objects for each calculator
# drop_coords=(‘snap’, ‘t’) because ‘snap’ and ‘t’ info won’t necessarily agree across all calculators.
to_xr(dim='variable', da_dim=None, *, var=None, drop_coords=False, str_coords=False, item=False, errors_ok=False, **kw_to_ds)

return xarray.DataArray or Dataset, stacking values in self along the new dimension.

This is shorthand for self.to_da() or self.to_ds()
(depending on da_dim and whether self.values are already xarray.Dataset objects).
dim: str
the new dimension, along which to stack values from self.
da_dim: None or str
if provided, will call value.to_dataarray(da_dim) for each value in self.
If da_dim provided or if there are no Dataset values in self,
result will be a DataArray, as per self.to_da(dim, ds=False, da_dim=da_dim, **kw).
Otherwise, if all self.values are Datasets,
result will be a Dataset, as per self.to_da(dim, ds=True, da_dim=None).
Otherwise (only some values are Datasets, and da_dim not provided),
crash with InputError.
The remaining kwargs go to self.to_ds() (see help(self.to_ds) for details):
var: None, str, or iterable of str.
if provided, will get value[var] for each value in self.
drop_coords: bool, str, or list of strs
whether to call value.drop_vars(…) for each value in self.
str_coords: bool, str, or list of strs
whether to call xarray_str_coords on each value in self.
item: bool
whether to call value.item() for each value in self.
errors_ok: bool
whether to ignore simple errors during processing.
update([E, ]**F) None.  Update D from dict/iterable E and F.

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]

If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
values() an object providing a view on D's values