Source code for porereax.charge

"""
Module for sampling atomic charges.

The module provides :class:`ChargeSampler` to sample charge histograms of
specified atom structures.
"""

import numpy as np

from porereax.meta_sampler import _ATOM_SAMPLER_INIT_PARAMS, AtomSampler
from porereax.regions import Region
from porereax.utils import Substitution


[docs] @Substitution(params=_ATOM_SAMPLER_INIT_PARAMS) class ChargeSampler(AtomSampler): """ Sampler class for atomic charges. Parameters ---------- %(params)s range : tuple Range (min, max) for histogram sampling. """ def __init__( self, name_out: str, atoms: list, dimension: str, region: Region, process_id: int, atom_lib: dict, masses: dict, num_frames: int, box: np.ndarray, system_properties: dict | None, range: tuple, ): valid_dimensions = ["Histogram"] if not isinstance(dimension, str) or dimension not in valid_dimensions: raise ValueError(f"ChargeSampler does not support dimension {dimension}") if ( not isinstance(range, (list, tuple)) or len(range) != 2 or range[0] >= range[1] ): raise ValueError( "ChargeSampler requires a 'range' parameter as a list or " "tuple of two numbers (min, max) with min < max." ) self._min_range, self._max_range = range self._min_range = np.round(self._min_range * 1000) self._max_range = np.round(self._max_range * 1000) self._range = (self._min_range, self._max_range) self._num_bins = int(self._max_range - self._min_range) super().__init__( name_out, atoms, dimension, region, process_id, atom_lib, masses, num_frames, box, system_properties, ) self._input.update( { "num_bins": self._num_bins, "range": range, } ) # Setup data for identifier in self._molecules: hist, bin_edges = np.histogram([], bins=self._num_bins, range=self._range) self._data[identifier] = { "num_frames": 0, "num_atoms": 0, "mean_charge": 0.0, "hist": hist, "std": 0.0, "bin_edges": bin_edges, }
[docs] def sample( self, frame_id: int, molecule_mask: dict, molecule_bond_atoms: dict, bond_mask: dict, frame: object, bond_enum: object, positions_transformed: np.ndarray, ): charges = ( frame.particles.get("Charge").array if "Charge" in frame.particles else np.zeros(frame.particles.count) ) charges = np.round(charges * 1000) positions = frame.particles.positions.array position_mask = self._region(positions) for identifier in self._molecules: mol_mask = molecule_mask[identifier] & position_mask atom_charges = charges[mol_mask] hist, _ = np.histogram(atom_charges, bins=self._num_bins, range=self._range) self._data[identifier]["hist"] += hist self._data[identifier]["std"] += np.sum((atom_charges / 1000.0) ** 2) self._data[identifier]["num_frames"] += 1 self._data[identifier]["num_atoms"] += atom_charges.shape[0] self._data[identifier]["mean_charge"] += np.sum(atom_charges) / 1000.0
def _combine_identifier(self, identifier: str, data: dict) -> dict: num_frames = np.sum(data["num_frames"]) num_atoms = np.sum(data["num_atoms"]) bin_edges = data["bin_edges"][0] / 1000.0 # Compute mean and standard error of the mean (SEM) mean = np.sum(data["mean_charge"]) / num_atoms if num_atoms > 0 else np.nan worker_counts = np.array(data["num_atoms"]) worker_sums = np.array(data["mean_charge"]) valid_workers = worker_counts > 0 worker_means = worker_sums[valid_workers] / worker_counts[valid_workers] mean_std = ( np.std(worker_means, ddof=1) / np.sqrt(len(worker_means)) if len(worker_means) > 1 else np.nan ) # Normalise histogram and compute error on histogram bins hist = ( np.sum(data["hist"], axis=0) / num_frames if num_frames > 0 else np.zeros(self._num_bins) ) # mean counts per sampled frame worker_frames = np.array(data["num_frames"]) worker_hists = np.array(data["hist"]) / worker_frames[:, np.newaxis] hist_std = ( np.std(worker_hists, axis=0, ddof=1) / np.sqrt(len(worker_hists)) if len(worker_hists) > 1 else np.full(self._num_bins, np.nan) ) # Compute standard deviation of distribution std = np.sqrt( np.sum(data["std"]) / num_atoms - mean**2 if num_atoms > 0 else np.nan ) return { "num_frames": num_frames, "num_atoms": num_atoms, "mean": mean, "hist": hist, "std": std, "mean_std": mean_std, "hist_std": hist_std, "bin_edges": bin_edges, }