Utilities#

class pylit.utils.NumpyArrayEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)#

Bases: JSONEncoder

Custom JSON encoder that converts NumPy arrays to lists.

default(obj)#

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return super().default(o)
pylit.utils.complete_detailed_balance(omega, D, beta)#

Extend the default model \(D(\omega)\) to satisfy the detailed balance.

Parameters:
  • omega (ndarray) – Array of non-negative discrete frequency axis.

  • D (ndarray) – The default model \(D(\omega)\) evaluated at omega.

  • beta (float) – Inverse temperature parameter \(\beta\)

Returns:

The completed omega and D values in terms of detailed balance.

Return type:

Tuple[np.ndarray, np.ndarray]

pylit.utils.diff_interval(tau1, tau0)#

Construct diffeomorphic transformations between two intervals.

Parameters:
  • tau1 (float64) – Upper bound of the target interval.

  • tau0 (float64) – Lower bound of the target interval.

Returns:

  • Forward mapping diffeomorphism psy(tau).

  • Inverse mapping diffeomorphism psy_inv(tau).

Return type:

Tuple[callable, callable]

pylit.utils.exp_std(omega, rho)#

Calculate the corrected sample variance for the input data array.

Parameters:
  • omega (ndarray) – The input data array of omega values.

  • rho (ndarray) – Density function values, must match the size of omega.

Returns:

  • mu: Expected value.

  • sigma: Standard deviation.

Return type:

Tuple[float, float]

pylit.utils.find_max_cutoff(array, cutoff)#

Find the first index after the global maximum where the array falls below a cutoff.

Parameters:
  • array (ndarray) – One-dimensional array of values.

  • cutoff (float) – Threshold value.

Returns:

Index of the first element smaller than the cutoff after the (global) maximum. Returns None if no such element is found.

pylit.utils.find_zero(array)#

Finds the index where the sign changes from negative to positive.

Parameters:

array (ndarray) – One-dimensional array of values.

Return type:

int

Returns:

Index i+1 such that arr[i] < 0 and arr[i+1] >= 0. Returns None if no sign change is found.

pylit.utils.generate_multi_index_set(dimension, degrees)#

Generate a set of multi-indices.

Parameters:
  • dimension (int) – Length of multi-indices.

  • degrees (List[int]) – Maximum degree in each dimension.

Return type:

ndarray

Returns:

Array of multi-indices, shape (n_combinations, dimension).

pylit.utils.import_xY(path)#

Load and preprocess data from a CSV file into x and Y arrays.

The first column is treated as the x-values, while the remaining columns are treated as Y-values. The data is sorted by x.

Parameters:

path (Path) – Path to the CSV file.

Returns:

  • x (1D array): Sorted x-values.

  • Y (2D array): Corresponding Y-values (transposed for row-wise access).

Return type:

Tuple[np.ndarray, np.ndarray]

Raises:

ValueError – If the file does not exist, is empty, or has invalid format.

pylit.utils.load_from_json(obj, filename)#

Load and reconstruct an object from JSON file.

Filters out any keys not present in the __init__ method of the target class.

Parameters:
  • obj – Class type to instantiate.

  • filename (Path) – Path to the JSON file.

Returns:

Instance of obj constructed with filtered attributes.

pylit.utils.moments(omega, rho, alphas)#

Compute statistical moments of a distribution.

Parameters:
  • omega (ndarray) – Array of discrete frequency axis.

  • rho (ndarray) – Density function values, must match the size of omega.

  • alphas (ndarray) – Powers for which to compute the moments.

Return type:

ndarray

Returns:

Array of computed moments.

pylit.utils.save_to_json(obj, filename)#

Serialize an object’s attributes to JSON and save to file.

NumPy arrays are converted to lists for compatibility.

Parameters:
  • obj – Object with a __dict__ attribute.

  • filename (Path) – Path to save the JSON file.

pylit.utils.to_string(obj)#

Create a human-readable string representation of an object and its attributes.

Handles special formatting for arrays, lists, floats, and dictionaries.

Parameters:

obj – Any object with attributes accessible via vars(obj).

Returns:

A string summarizing the object’s attributes.

Return type:

str