lnPi data classes and routines (lnpidata)#

Classes:

lnPiArray(lnz, data[, state_kws, extra_kws, ...])

Wrapper on lnPi lnPiArray

lnPiMasked(lnz, base[, mask, copy])

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: MyAttrsMixin

Wrapper on lnPi lnPiArray

Parameters:
  • lnz (float or sequence of float) – Value(s) of lnz (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.

pipe(func, *args, **kwargs)[source]#

Apply numpy function to underlying data.

asdict()[source]#

Convert object to dictionary.

assign(**kws)[source]#

Alias to new_like().

new_like(**kws)[source]#

Create a new object with optional parameters.

Parameters:

**kwsattribute, value pairs.

class lnpy.lnpidata.lnPiMasked(lnz, base, mask=None, copy=None)[source]#

Bases: AccessorMixin, MyAttrsMixin

Masked array like wrapper for lnPi data.

This is the basic data structure for storing the output from a single TMMC simulation.

Parameters:
  • lnz (float or sequence of float) – Value(s) of lnz (log of activity)

  • base (object) – lnPi data object.

  • mask (None or ndarray of bool) – Mask using “masked” convention. Where mask is True, values are excluded.

  • copy (bool, optional) – If True, copy the data. If None or False, attempt to use view.

Notes

Note that in most cases, lnPiMasked should not be called directly. Rather, a constructor like from_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 lnPiMasked object 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.nan values.

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.DataArray

asdict()

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:

dtype

Type (dtype) of underling data

state_kws

State variables.

extra_kws

Extra parameters.

ma

Masked array view of data reweighted data

data

Reweighted data

shape

Shape of lnPiArray

betamu

Alias to self.lnz

volume

Accessor to self.state_kws['volume'].

beta

Accessor to self.state_kws['beta'].

edge_distance_matrix

Matrix of distance from each element to a background (i.e., masked) point.

xge

Accessor to GrandCanonicalEnsemble.

xce

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 lnPiMasked object from raw data.

Parameters:
  • lnz (float or sequence of float) – Value of lnz to reweight data to.

  • lnz_data (float or sequence of float, optional) – Value of lnz at which data was collected. Defaults to lnz.

  • {data}

  • {mask_masked}

  • {state_kws}

  • {extra_kws}

  • {fill_value}

  • {copy}

Returns:

out (lnPiMasked)

as_pure(keepdims=False)[source]#

Iterator of pure component objects

Parameters:

keepdims (bool, default False) – If True, 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

filled(fill_value=None)[source]#

Filled view or 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

local_maxmask(*args, **kwargs)[source]#

Calculate mask where self.ma == self.local_max()

edge_distance_matrix[source]#

Matrix of distance from each element to a background (i.e., masked) point.

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 via func.

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 (int or iterable of int, optional) – Axes to apply operation over.

  • ffill (bool, default True) – Do forward filling

  • bfill (bool, default False) – Do back filling

  • limit (int, default None) – 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.nan values.

Parameters:
  • fill_axes (int or iterable of int, optional) – Axes to apply operation over.

  • add_coords (bool, default False) – Some of the options require the underlying DataArray to have coordinates. Specify add_coords=True to enable these.

  • method (str, default "linear") – See interpolate_na()

  • use_coordinate (bool, default False) – 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

interpolate_na

mask_nan()[source]#

Return new object with nan values masked.

zeromax()[source]#

Shift so that lnpi.max() == 0 on reference

reweight(lnz)[source]#

Create new object at specified value of lnz

or_mask(mask)[source]#

New object with logical or of self.mask and mask

and_mask(mask)[source]#

New object with logical and of self.mask and mask

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, beta

  • sep (string, optional) – separator for file read

  • names (sequence of str)

  • csv_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 data

  • state_as_attrs (bool, optional) – If True, get state_kws from da.attrs.

  • **kwargs – Extra arguments to from_data()

Returns:

lnPiMasked

See also

from_data()

asdict()[source]#

Convert object to dictionary.

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 None or ndarray of bool) – Masks using “masked” convention. Where mask[i] is True, values are excluded for sample i.

  • convention (string or bool) – 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:

**kwsattribute, 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 (ndarray of int) – Each unique value i in labels indicates a mask. That is labels == i is a mask for feature i.

  • features (sequence of int) – If specified, extract only those locations where labels == feature for all values feature in features. That is, select a subset of unique label values.

  • include_boundary (bool) – if True, include boundary regions in output mask

  • check_features (bool) – if True, then make sure each feature is in labels

  • **kwargs – Extra arguments to to labels_to_masks()

Returns:

outputs (list of lnPiMasked)

xge[source]#

Accessor to GrandCanonicalEnsemble.

xce[source]#

Accessor to CanonicalEnsemble.