lnPi data classes and routines (lnpidata)#
Classes:
|
Wrapper on lnPi lnPiArray |
|
Masked array like wrapper for lnPi data. |
- class lnpy.lnpidata.lnPiArray(lnz, data, state_kws=None, extra_kws=None, fill_value=nan, copy=None)[source]#
Bases:
MyAttrsMixinWrapper on lnPi lnPiArray
- Parameters:
lnz (
floator sequence offloat) – Value(s) oflnz(log of activity)data (array-like) – Value of lnPi. Number of dimensions should be same as
len(lnz). For single component,data[k1, ...]is the value of lnPi for k1, … particles.state_kws (
Mapping, optional) – ‘State’ variables. Common key/value pairs used by other methods:beta (float) : inverse temperature
volume (float) : volume
extra_kws (
Mapping,Optional) – Extra parameters. These are passed along to new objects without modification. Common key/value pairs:fill_value (scalar, default
nan) – Value to fill for masked elements.copy (
bool, optional) – If True, copy the data. If None or False, attempt to use view.
Methods:
pipe(func, *args, **kwargs)Apply numpy function to underlying data.
asdict()Convert object to dictionary.
assign(**kws)Alias to
new_like().new_like(**kws)Create a new object with optional parameters.
- assign(**kws)[source]#
Alias to
new_like().
- class lnpy.lnpidata.lnPiMasked(lnz, base, mask=None, copy=None)[source]#
Bases:
AccessorMixin,MyAttrsMixinMasked array like wrapper for lnPi data.
This is the basic data structure for storing the output from a single TMMC simulation.
- Parameters:
See also
Notes
Note that in most cases,
lnPiMaskedshould not be called directly. Rather, a constructor likefrom_data()should be used to construct the object.Note the the value of lnz is the value to reweight to.
Basic terminology:
T : temperature.
k : Boltzmann’s constant.
beta : Inverse temperature = 1/(k T).
mu : chemical potential.
lnz : log of activity = ln(z).
z : activity = beta * mu.
lnPi : log of macrostate distribution.
Methods:
from_data(data, lnz[, lnz_data, mask, ...])Create
lnPiMaskedobject from raw data.as_pure([keepdims])Iterator of pure component objects
filled([fill_value])Filled view or reweighted data
local_argmax(*args, **kwargs)Calculate index of maximum of masked data.
local_max(*args, **kwargs)Calculate index of maximum of masked data.
local_maxmask(*args, **kwargs)Calculate mask where
self.ma == self.local_max()edge_distance(ref, *args, **kwargs)Distance of local maximum value to nearest background point.
pipe(func, *args, **kwargs)Apply numpy function to underlying data, leaving other meta data unchanged.
pad([axes, ffill, bfill, limit])Pad nan values in underlying data to values
interpolate_na([axes, add_coords, method, ...])Interpolate
np.nanvalues.mask_nan()Return new object with nan values masked.
zeromax()Shift so that lnpi.max() == 0 on reference
reweight(lnz)Create new object at specified value of lnz
or_mask(mask)New object with logical or of self.mask and mask
and_mask(mask)New object with logical and of self.mask and mask
from_table(path, lnz[, state_kws, sep, ...])Create lnPi object from text file table with columns [n_0,...,n_ndim, lnpi]
from_dataarray(da[, state_as_attrs])Create a lnPi object from
xarray.DataArrayasdict()Convert object to dictionary.
assign(**kws)Alias to
new_like().decorate_accessor(name[, single_create])Register a property name to class of type accessor(self).
list_from_masks(masks[, convention])Create list of lnpis corresponding to masks[i]
new_like(**kws)Create a new object with optional parameters.
register_accessor(name, accessor[, ...])Register a property name to class of type accessor(self)
list_from_labels(labels[, features, ...])Create sequence of lnpis from labels array.
Attributes:
Type (dtype) of underling data
State variables.
Extra parameters.
Masked array view of data reweighted data
Reweighted data
Shape of lnPiArray
Alias to self.lnz
Accessor to self.state_kws['volume'].
Accessor to self.state_kws['beta'].
Matrix of distance from each element to a background (i.e., masked) point.
Accessor to
GrandCanonicalEnsemble.Accessor to
CanonicalEnsemble.- classmethod from_data(data, lnz, lnz_data=None, mask=None, state_kws=None, extra_kws=None, fill_value=None, copy=None)[source]#
Create
lnPiMaskedobject from raw data.
- as_pure(keepdims=False)[source]#
Iterator of pure component objects
- Parameters:
keepdims (
bool, defaultFalse) – IfTrue, keep the reduced dimensions (i.e., ndim is unchanged). Otherwise return 1d objects.- Yields:
lnpi_component (
lnPiMasked) – Pure component lnPiMasked
Example
>>> import numpy as np >>> import lnpy >>> ref = lnpy.lnPiMasked.from_data( ... data=np.arange(9).reshape(3, 3), lnz=[0, 2], lnz_data=[0, 2] ... ) >>> ref <lnPi(lnz=[0. 2.])> >>> ref.data array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> pures = list(ref.as_pure()) >>> pures[0] <lnPi(lnz=[0.])> >>> pures[0].data array([0, 3, 6]) >>> pures[1] <lnPi(lnz=[2.])> >>> pures[1].data array([0, 1, 2])
- property dtype#
Type (dtype) of underling data
- property state_kws#
State variables.
- property extra_kws#
Extra parameters.
- property ma#
Masked array view of data reweighted data
- property data#
Reweighted data
- property shape#
Shape of lnPiArray
- property betamu#
Alias to self.lnz
- property volume#
Accessor to self.state_kws[‘volume’].
- property beta#
Accessor to self.state_kws[‘beta’].
- local_argmax(*args, **kwargs)[source]#
Calculate index of maximum of masked data.
- Parameters:
*args – Positional arguments to argmax
**kwargs – Keyword arguments to argmax
- local_max(*args, **kwargs)[source]#
Calculate index of maximum of masked data.
- Parameters:
*args – Positional arguments to argmax
**kwargs – Keyword arguments to argmax
See also
- edge_distance_matrix[source]#
Matrix of distance from each element to a background (i.e., masked) point.
See also
- edge_distance(ref, *args, **kwargs)[source]#
Distance of local maximum value to nearest background point.
If edge_distance is too small, the value of properties calculated from this lnPi cannot be trusted. This usually is due to the data being reweighted to too high a value of lnz, or not sampled to sufficiently high values of N.
- pipe(func, *args, **kwargs)[source]#
Apply numpy function to underlying data, leaving other meta data unchanged.
- Parameters:
func (
callable()) – Function to apply to data. First argument must accept the data as a numpy array.*args, **kwargs – Extra positional and keyword arguments to
func.
- Returns:
lnPiMasked– New object with data transformed viafunc.
Example
Apply a gaussian filter to underlying data
>>> import numpy as np >>> data = np.random.default_rng(seed=0).random((3, 3)) >>> ref = lnPiMasked.from_data(data=data, lnz=[0.0, 0.0]) >>> ref <lnPi(lnz=[0. 0.])> >>> ref.data array([[0.637 , 0.2698, 0.041 ], [0.0165, 0.8133, 0.9128], [0.6066, 0.7295, 0.5436]])
Smooth data using gaussian filter
>>> from scipy.ndimage import gaussian_filter >>> smoothed = ref.pipe(gaussian_filter, mode="nearest", sigma=2) >>> smoothed # No change to metadata <lnPi(lnz=[0. 0.])> >>> smoothed.data array([[0.4638, 0.4249, 0.3835], [0.4928, 0.4792, 0.4608], [0.5297, 0.5303, 0.5245]])
- pad(axes=None, ffill=True, bfill=False, limit=None)[source]#
Pad nan values in underlying data to values
- Parameters:
fill_axes (
intor iterable ofint, optional) – Axes to apply operation over.limit (
int, defaultNone) – The maximum number of consecutive NaN values to forward fill. In other words, if there is a gap with more than this number of consecutive NaNs, it will only be partially filled. Must be greater than 0 or None for no limit.
- Returns:
out (
lnPiMasked) – Padded object. Note that final result is the average over all axes with specified back and forward fill.
- interpolate_na(axes=None, add_coords=False, method='linear', use_coordinate=False, **kwargs)[source]#
Interpolate
np.nanvalues.- Parameters:
fill_axes (
intor iterable ofint, optional) – Axes to apply operation over.add_coords (
bool, defaultFalse) – Some of the options require the underlyingDataArrayto have coordinates. Specifyadd_coords=Trueto enable these.method (
str, default"linear") – Seeinterpolate_na()use_coordinate (
bool, defaultFalse) – If True, use coordinates. If False, assume evenly spaced.**kwargs – Extra arguments to
interpolate_na()
- Returns:
out (
object) – Object with nan values filled.
See also
- classmethod from_table(path, lnz, state_kws=None, sep='\\s+', names=None, csv_kws=None, **kwargs)[source]#
Create lnPi object from text file table with columns [n_0,…,n_ndim, lnpi]
- Parameters:
path (path-like) – file object to be read
lnz (array-like) – \(\beta \mu\) for each component
state_kws (
dict, optional) – define state variables, like volume, betasep (
string, optional) – separator for file readcsv_kws (
dict, optional) – optional arguments to pandas.read_csv**kwargs – Passed to lnPi constructor
- classmethod from_dataarray(da, state_as_attrs=None, **kwargs)[source]#
Create a lnPi object from
xarray.DataArray- Parameters:
da (
DataArray) – DataArray containing the lnPi datastate_as_attrs (
bool, optional) – If True, get state_kws fromda.attrs.**kwargs – Extra arguments to
from_data()
- Returns:
See also
- assign(**kws)[source]#
Alias to
new_like().
- classmethod decorate_accessor(name, single_create=False)[source]#
Register a property name to class of type accessor(self).
Examples
>>> class parent(AccessorMixin): ... pass
>>> @parent.decorate_accessor("hello") ... class hello(AccessorMixin): ... def __init__(self, parent): ... self._parent = parent ... ... def there(self): ... return f"{type(self._parent)}"
>>> x = parent() >>> x.hello.there() "<class 'lnpy.extensions.parent'>"
- list_from_masks(masks, convention='image')[source]#
Create list of lnpis corresponding to masks[i]
- Parameters:
masks (sequence of
Noneorndarrayofbool) – Masks using “masked” convention. Where mask[i] is True, values are excluded for sample i.convention (
stringorbool) – Convention for mask. Allowable values are:- ‘image’ or TrueTrue values included, False values excluded.
This is the normal convention in
scipy.ndimage.
- ‘masked’ or False: False values are included, True values are excluded.
This is the convention in
numpy.ma
- Returns:
lnpis (
list) – list of lnpis corresponding to each mask
- new_like(**kws)[source]#
Create a new object with optional parameters.
- Parameters:
**kws – attribute, value pairs.
- classmethod register_accessor(name, accessor, single_create=False)[source]#
Register a property name to class of type accessor(self)
Examples
>>> class parent(AccessorMixin): ... pass >>> class hello(AccessorMixin): ... def __init__(self, parent): ... self._parent = parent ... ... def there(self): ... return f"{type(self._parent)}"
>>> parent.register_accessor("hello", hello) >>> x = parent() >>> x.hello.there() "<class 'lnpy.extensions.parent'>"
- list_from_labels(labels, features=None, include_boundary=False, check_features=True, **kwargs)[source]#
Create sequence of lnpis from labels array.
- Parameters:
labels (
ndarrayofint) – Each unique value i in labels indicates a mask. That islabels == iis a mask for feature i.features (sequence of
int) – If specified, extract only those locations wherelabels == featurefor all valuesfeature in features. That is, select a subset of unique label values.include_boundary (
bool) – if True, include boundary regions in output maskcheck_features (
bool) – if True, then make sure each feature is in labels**kwargs – Extra arguments to to
labels_to_masks()
- Returns:
outputs (
listoflnPiMasked)
- xge[source]#
Accessor to
GrandCanonicalEnsemble.
- xce[source]#
Accessor to
CanonicalEnsemble.