PathEnsemble

aimmd.PathEnsemble is a list/array-like collection of aimmd.Path objects with vectorized access, filtering by path type, projection, reporting, and reweighting into equilibrium observables.

class aimmd.PathEnsemble(*paths, find_shooting_indices=False, pipeline=(), verbose=True)[source]

Bases: PathEnsembleHelpers, PathEnsembleMagic, PathEnsembleProperties, PathEnsembleMethods, PathEnsemblePositions, PathEnsembleProject, PathEnsembleReweight, PathEnsembleIO, PathEnsembleReport

Collection of Path objects with vectorized operations.

A PathEnsemble is a container for paths used throughout AIMMD to represent:

  • shooting chains (ordered sequences of sampled paths),

  • selection pools (bounded candidate sets for shooting-point selection),

  • free-trajectory ensembles (collections of long unbiased trajectories),

  • merged or extracted ensembles used for analysis and training.

In addition to list-like behavior, PathEnsemble provides convenience methods that operate across all member paths, often in a vectorized / batched way:

  • compute per-frame quantities (states/descriptors/values) for the ensemble,

  • project values into bins and estimate densities,

  • reweight paths according to sampling schemes,

  • extract subsets by path type patterns or by end-state transitions,

  • merge paths into a single frame collection (for sweep shooting and reporting).

Representation An ensemble stores paths (typically in a list-like attribute such as _paths). Many performance-critical operations may operate directly on this internal structure.

Each path carries segment metadata and refers to trajectory files on disk. Ensemble methods therefore often interact with the global caches:

  • aimmd._config.MDA_CACHE for trajectory readers,

  • aimmd._config.NPY_CACHE for cached .npy arrays.

Typical usage in AIMMD Shooting The worker maintains a shooting chain as a PathEnsemble. New paths are appended via registration utilities. A separate PathEnsemble is used as the selection pool.

Training A PathEnsemble assembled from current chains and free trajectories is used to compute values and to fit the committor model. Projection and reweighting are performed on the ensemble to produce adaptive bins and densities.

Validation / sweep A merged ensemble (frame collection) is used to deterministically select frames and repeatedly shoot from them for brute-force committor estimation.

:param The constructor is aliased to PathEnsembleHelpers._init(). See that method: :param for the full signature and meaning of pathensemble initialization arguments.:

Notes

  • Many ensemble operations assume that per-path cached arrays (states, descriptors, values) exist or can be computed on demand, and that their frame ordering matches the path’s frame ordering.

  • Some methods intentionally mutate paths in place (e.g., attaching weights, updating cached attributes). This is acceptable in worker contexts where the ensemble is treated as a live view of the filesystem-backed run state.

Initialize the ensemble by normalizing all inputs into Path objects.

Parameters:
  • *paths – Any of the accepted inputs for aimmd.pathensemble.utils.get_paths().

  • find_shooting_indices (bool, default=False) – If True, pass shooting_index='find' into Path initialization.

  • pipeline (tuple, default=()) – Optional pipeline forwarded to Path initialization.

  • verbose (bool, default=True) – If True, display a progress bar over the loaded paths.

Notes

  • This method is aliased as PathEnsemble.__init__.

  • The initialization here is intentionally minimal: it only builds self._paths and leaves everything else to derived properties/methods.

property accepted

Array-like view of per-path acceptance flags. See Path.accepted.

Returns:

View over the Path attribute accepted.

Return type:

PathProperties

Notes

Setting this property does not write accepted directly. Instead it writes exclude_from (see setter below).

all(attribute)

Return a copy of self.

append(path)

Append a single Path.

Parameters:

path (aimmd.path.Path) – Path instance to append.

are_complete(states='ARB')

Vectorized wrapper around Path.is_complete.

Parameters:

states (str, default="ARB") – State alphabet / specification forwarded to Path.

Returns:

Boolean array of shape (n_paths,).

Return type:

numpy.ndarray, dtype=bool

are_excursions(states='ARB')

Vectorized wrapper around Path.is_excursion.

are_internal(states='ARB')

Vectorized wrapper around Path.is_internal.

are_transitions(states='ARB')

Vectorized wrapper around Path.is_transition.

backward(attribute)

Return the backward portion for each path in a PathEnsemble object.

The backward portion is the segment from the shooting point back to the initial end, with the shooting frame included. This method calls path.backward(attribute) for each path and returns the list of per-path results.

compute(*args, **kwargs)

Compute quantities on the merged path.

This is a thin wrapper around:

self.merge().compute(*args, **kwargs)

Notes

The comment in the original code suggests borrowing documentation from Path.compute. For user-facing docs, consult aimmd.path.Path.compute.

copy()

Deep-ish copy of the ensemble: copies each Path.

Returns:

New ensemble with path.copy() for each stored path.

Return type:

PathEnsemble

property exclude_from

Array-like view of exclude_from for every path. See Path.exclude_from.

Returns:

View over the Path attribute exclude_from.

Return type:

PathProperties

extend(paths)

Extend the ensemble with multiple paths.

Parameters:

paths (iterable of aimmd.path.Path) – Paths to append.

extract(*types)

Extract a sub-ensemble matching one or more type patterns.

Parameters:

*types – Patterns matched against Path.type using match_patterns.

If no types are provided, returns an empty PathEnsemble(). :type *types: str

Returns:

Selected paths as a new ensemble.

Return type:

PathEnsemble

factors(neighbors=10, norm=10, cutoff=1.0, sp_cutoff_min=None, sp_cutoff_max=None)

Convenience wrapper for reweighting factors.

This method calls reweight() in diagnostic-only mode (states='') and returns its first element.

Parameters:
Returns:

First element returned by reweight() (kept as-is).

Return type:

numpy.ndarray

Notes

In diagnostic-only mode, reweight() returns several arrays (factors, shooting values, extremes, …). This wrapper exposes only the first return element to preserve historical behavior.

final(attribute)

Final-point selector for the ensemble.

Calls path.final(attribute) for each path and returns one result per path. Container normalization follows the module-level policy.

property fname

Filename of the representative Path.

Returns:

path.fname if a representative path exists, otherwise ‘’.

Return type:

str

property fnames

Concatenated trajectory filenames of all paths.

Returns:

Concatenation of each path’s internal _fnames list.

Empty array if there are no paths. :rtype: numpy.ndarray

forward(attribute)

Return the forward portion for each path in a PathEnsemble object.

The forward portion is the segment from the shooting point to the final end, with the shooting frame included. This method calls path.forward(attribute) for each path and returns the list of per-path results.

frame(i)

Return a single frame addressed by a global index.

Parameters:

i (int) – Index into the concatenation of all path frames (using n_frames).

Returns:

The underlying representation of a frame as returned by Path.__getitem__.

Return type:

Any

Notes

Negative indices count from the end of the concatenated frame sequence.

from_files()

Force all paths to read their data from files (drop in-memory state).

Delegates to Path.from_files.

get(attribute, where='internal', verbose=False)

Internal bulk getter that delegates to each path.

Parameters:

attribute – Name of the per-path attribute to fetch through the Path internal API.

This is forwarded to path._get(attribute, *path._range(where)). :type attribute: str :param where: Range spec forwarded to each path’s _range(where) method. Typical values include (depending on Path implementation): “internal”, “all”, “forward”, “backward”, etc. :type where: str, default=”internal” :param verbose: If True, display a progress bar over the loaded paths. :type verbose: bool, default=False

Returns:

One element per path, each being the corresponding path’s _get(…)

result. :rtype: list

Notes

This is an internal routine used by PathEnsemble.__getattr__ to provide convenience “vectorized” attribute access. Many public properties return arrays instead; prefer them when you want stable NumPy types.

in_memory(attribute='reader')

Query whether each path currently holds a given attribute in memory.

Parameters:

attribute (str, default="reader") – Passed to Path.in_memory(attribute).

Return type:

numpy.ndarray, dtype=bool

index(path)

Return the index of a specific path (like list.index).

initial(attribute)

Initial-point selector for the ensemble.

Calls path.initial(attribute) for each path and returns one result per path. Container normalization follows the module-level policy.

internal(attribute)

Return the internal portion for each path in a PathEnsemble object.

Calls path.internal(attribute) for each path and returns the list of per-path results. The definition of “internal” is delegated to Path.

join()

Merge all paths into a single Path composed of concatenated file ranges.

Returns:

A new Path with _fnames, _first, _last representing the

concatenation of all trajectory segments across all paths. In-memory data will not be copied. :rtype: aimmd.path.Path

Warning

  • Only the first path’s shooting_index is propagated (if any paths exist).

  • Exclusion logic is simplified: if not all paths are accepted, the merged

path uses exclude_from = 0 (see code comment).

property lengths

Path lengths as stored.

Returns:

np.array([len(path) for path in self._paths]).

Return type:

numpy.ndarray

classmethod load(filename, find_shooting_indices=False, pipeline=())

Load a path ensemble from a text file.

Parameters:
  • filename (str or pathlib.Path) – Path to a file previously produced by save().

  • find_shooting_indices – Forwarded to PathEnsemble construction. See

aimmd.pathensemble.PathEnsemble.__init__(). :type find_shooting_indices: bool, default=False :param pipeline: Forwarded to PathEnsemble construction. See aimmd.pathensemble.PathEnsemble.__init__(). :type pipeline: tuple, default=()

Returns:

If called on the class, returns a new instance.

Return type:

PathEnsemble

Notes

If called on an instance, this method mutates the receiver by appending the loaded ensemble via self += instance and returns self.

max(attribute, source='values')

Return attribute at the maximum of source, one per path.

Delegates to path.max(attribute, source) for each path. See min() for the meaning of attribute and source.

max_backward(attribute, source='values')

Return attribute at the backward-portion maximum of source, per path.

See min_backward() for the meaning of the backward portion.

Delegates to path.max_backward(attribute, source).

max_forward(attribute, source='values')

Return attribute at the forward-portion maximum of source, per path.

See min_forward() for the meaning of the forward portion.

Delegates to path.max_forward(attribute, source).

merge()

Merge all paths into a single Path composed of merged file ranges.

Returns:

A new Path with _fnames, _first, _last representing the union of

all trajectory segments across all paths. :rtype: aimmd.path.Path

Warning

  • Only the first path’s shooting_index is propagated (if any paths exist).

  • Backward segments are converted to forward ranges.

  • In-memory data is lost because a new Path object is built manually.

  • Exclusion logic is simplified: if not all paths are accepted, the merged

path uses exclude_from = 0 (see code comment).

Notes

This method uses aimmd.core.utils.merge_ranges() per filename to merge local index ranges into a minimal set of intervals.

middle(attribute)

Middle-point selector for the ensemble.

Calls path.middle(attribute) for each path. The definition of “middle” is delegated entirely to Path.

min(attribute, source='values')

Return attribute at the minimum of source, one per path.

For each path, this delegates to path.min(attribute, source). The Path method defines how the minimum is located (based on source) and what is returned at that location (based on attribute).

Typical usage is:

  • source selects the scalar stream minimized along the path (often ‘values’).

  • attribute selects what is returned at the argmin location (e.g. frames, positions, descriptors, values).

Container normalization follows the module-level policy.

min_backward(attribute, source='values')

Return attribute at the backward-portion minimum of source, per path.

The backward portion is the part of the path running from the shooting point back to the initial end, with the shooting frame included. The exact slicing and indexing are defined by Path.

Delegates to path.min_backward(attribute, source).

min_forward(attribute, source='values')

Return attribute at the forward-portion minimum of source, per path.

The forward portion is the part of the path running from the shooting point to the final end, with the shooting frame included. The exact slicing and indexing are defined by Path.

Delegates to path.min_forward(attribute, source).

property n_files

Total number of trajectory files across all paths.

Returns:

Sum of len(path.files) over all paths.

Return type:

int

property n_frames

Effective number of frames per path, excluding boundary-state frames.

This property corrects the stored length of each path by removing boundary frames that correspond to end states, matching the ensemble convention used elsewhere in AIMMD.

For a path of length <= 1, the stored length is returned unchanged.

For longer paths, the correction depends on the Path state triplet path.type:

  • If states[0] != states[1] then the first frame is treated as an end-state boundary and is excluded from the effective count.

  • If states[1] != states[2] then the last frame is treated as an end-state boundary and is excluded from the effective count.

Returns:

Integer array of effective frame counts.

Return type:

numpy.ndarray

property n_paths

Number of paths in the ensemble (alias for len(self)).

property offsets

Cumulative frame offsets across paths.

Returns:

np.cumsum([len(path) for path in self.paths]).

Return type:

numpy.ndarray

property path

Representative Path for the ensemble.

The last Path in self._paths is scanned backwards and the first Path satisfying:

  • path._weight is truthy

  • path._exclude_from < 0

is returned. If no path matches, returns None.

Notes

This is primarily used to provide a stable fname even when the most recent paths are excluded or not yet weighted.

property paths

NumPy object array view of self._paths.

Returns:

Object array containing Path objects.

Return type:

numpy.ndarray

pop(i=None)

Remove and return a path (like list.pop).

Parameters:

i (int or None, default=None) – If None, pop the last element.

Return type:

aimmd.path.Path

print_report(*args, **kwargs)

Print the report text to a log file or stdout.

This is a convenience wrapper around report(). It prints only the text component (index 0 of the tuple returned by report()).

Notes

The current implementation references a variable log_file that is not defined in the function scope. In practice, callers likely intended to provide a log_file object via surrounding scope or to have this function retrieve it from kwargs. The implementation is kept as-is by design (documentation-only pass).

project(bins=[-inf, inf], key=None, weights=None, function=<function PathEnsembleProject.<lambda>>, source='values', where='internal', values_source='values', vmin=None, vmax=None, batch_size=4096, verbose=False)

Project per-frame data from an ensemble into an N-dimensional histogram.

Parameters:

bins – Bin edges for histogramming. If a single 1D iterable is provided,

it is treated as one-dimensional bins. If a list of iterables is provided, each element defines the bin edges for one dimension. :type bins: array_like or list[array_like], default=[-inf, +inf] :param key: Selection applied as np.arange(len(self))[key] to choose which paths contribute. Repeated indices are allowed and are accounted for by multiplying weights by their multiplicity. :type key: object, optional :param weights: Per-path weights overriding self.weights[indices]. If not provided, path ensemble weights are used (self.weights[key]). :type weights: array_like, optional :param function: Transformation applied to the raw per-frame data before binning. It must produce an array-like object with one row per frame. :type function: callable, default=lambda x: x :param source: Name of the per-frame stream extracted from Path via path._extract(k, source). If source == 'reader', per-segment inputs are wrapped with ChainReader before calling function. :type source: str, default=’values’ :param where: Portion of each path to include. The slicing rules are described in the module docstring. Typical values are ‘all’, ‘internal’, ‘forward’, ‘backward’. :type where: str, default=’internal’ :param values_source: Stream used to compute the value-range mask when vmin/vmax are provided. If it equals source, the already-extracted data are reused; otherwise the mask is computed from an independent extraction. :type values_source: str, default=’values’ :param vmin: If provided, apply an inclusion mask per frame:

  • both provided: keep frames with vmin <= values < vmax

  • only vmin: keep frames with values >= vmin (vmax = +inf)

  • only vmax: keep frames with values < vmax (vmin = -inf)

The mask is applied to the weights (frames outside range get weight 0). :type vmin: float, optional :param vmax: If provided, apply an inclusion mask per frame:

  • both provided: keep frames with vmin <= values < vmax

  • only vmin: keep frames with values >= vmin (vmax = +inf)

  • only vmax: keep frames with values < vmax (vmin = -inf)

The mask is applied to the weights (frames outside range get weight 0). :type vmax: float, optional :param batch_size: Maximum number of frames buffered before computing a partial histogram contribution. Larger values reduce overhead but increase memory usage. :type batch_size: int, default=4096 :param verbose: If True, show a tqdm progress bar. The progress bar tracks the number of frames processed (including frames skipped due to slicing). :type verbose: bool, default=False

Returns:

N-dimensional histogram of weighted counts.

Return type:

numpy.ndarray

Notes

Path selection and weighting:

  • Paths are selected via key, then unique indices and their counts (multiplicity) are computed.

  • Only accepted paths are kept (self.accepted).

  • Paths with NaN weights or zero weights are dropped.

  • The final per-path weight is multiplied by its multiplicity.

Missing data handling:

  • If path._extract(k, source) fails for a segment, that segment is skipped.

remove(path)

Remove a specific path (like list.remove).

report(bins=[], summary=True, values=None)

Create a human-readable report for the ensemble.

The report is returned as a formatted multi-line string. Optionally, a per-path histogram of values is computed and appended as aligned columns. The function also returns the per-path histogram matrix as a numeric array for programmatic use.

Parameters:

bins – Binning specification for histogram columns.

This implementation expects bins to be a sequence of bin edges. If an empty sequence is provided (or it becomes empty after coercion), histogram columns are omitted.

The docstring in the original code mentions “predefined values or n_bins, then call self.bins”, but this implementation currently only handles explicit bin edges. Any transformation from an integer number of bins to bin edges must therefore happen outside this method. :type bins: array-like or int, default=[] :param summary: If True, append a summary block at the end of the report, including:

  • total number of displayed paths,

  • total number of frames (sum of lengths),

  • a type-count table (counts and percentage per type),

  • and, if bins is provided, the aggregated histogram.

Parameters:

values – Per-path values used for histogramming. If None, uses self.values.

Expected structure is one entry per path, where each entry is a 1D array-like of per-frame scalars. :type values: sequence, optional

Returns:

(report_text, histograms)

report_text Formatted table as a single string.

histograms 2D float array with shape (n_paths, len(bins) - 1) if bins are provided, otherwise an empty array (or an array converted from an empty list). :rtype: (str, numpy.ndarray)

Notes

  • If the ensemble is empty, returns str(self) (as a string) without histogram output.

  • Path types are truncated to 3 characters and marked with a leading ‘*’ if all three characters are distinct. This is a display convention used to highlight “transitions” vs repeated-state paths.

  • The function uses path._fnames to display the list of trajectory segments contributing to each path.

report_shooting_results(states='ARB', sweep_size=0, alpha=0.95)

Print committor estimates from shooting results.

For each shooting point index i, the host method self.shooting_results(states, sweep_size) must yield a pair:

(n_to_states[0], n_to_states[-1])

interpreted as binomial counts of trajectories committed to the first and last state labels in states.

The output includes:

  • point index,

  • counts to the two terminal states,

  • mean committor and confidence interval,

  • logit(committor) and confidence interval in logit space.

Parameters:

states – State label string. Only the first and last characters are used as

the two terminal states in the printed table. :type states: str, default=’ARB’ :param sweep_size: Passed through to self.shooting_results. :type sweep_size: int, default=0 :param alpha: Confidence level used by aimmd.analysis.utils.binomial_mean_and_confidence_interval(). :type alpha: float, default=0.95

Notes

The logit transform diverges for p=0 or p=1. The confidence interval computation should therefore avoid returning exact 0/1 bounds or the resulting logit values will be ±inf.

reweight(states='ARB', free_threshold=50, theoretical_threshold=None, crossing_probability_cutoff=0.0, factors_neighbors=10, factors_norm=10, factors_cutoff=1.0, sp_cutoff_min=None, sp_cutoff_max=None, source='values')

Reweight an ensemble of paths.

Parameters:

states – State specification. Interpreted as a string and converted to upper

case. If at least three characters are provided, the first three are used as: s = states[0] (initial state) r = states[1] (reactive region) o = states[2] (final state) If fewer than three characters are provided, only r is used and s and o are set to the empty string. In that mode, the method returns diagnostic factors without performing directional reweighting (see “Just factors” return below). :type states: str, default=’ARB’ :param free_threshold: Threshold (in the extreme-value coordinate) used by compute_crossing_probability() to decide which events are treated as “free” crossings when estimating crossing probabilities. :type free_threshold: float, default=50 :param theoretical_threshold: Optional theoretical threshold forwarded to compute_crossing_probability(). If provided, it is used as an additional constraint on the crossing model. :type theoretical_threshold: float, optional :param crossing_probability_cutoff: Lower cutoff forwarded to compute_crossing_probability(). Crossing probabilities below this cutoff are suppressed. :type crossing_probability_cutoff: float, default=0. :param factors_neighbors: Neighborhood size used by compute_shooting_density() when estimating the local density at the shooting value. :type factors_neighbors: int, default=10 :param factors_norm: If non-zero, enable factor uniformization among shot excursions using uniformize_factors(). The value is passed as the norm argument to that function. :type factors_norm: int, default=10 :param factors_cutoff: Cutoff parameter forwarded to uniformize_factors(). :type factors_cutoff: float, default=1. :param sp_cutoff_min: Optional shooting-value cutoffs used to reclassify some shot paths as free. Shots with shooting values outside the interval [sp_cutoff_min, sp_cutoff_max] are treated as free excursions with special factors based on the count of internal frames beyond the cutoff. :type sp_cutoff_min: float, optional :param sp_cutoff_max: Optional shooting-value cutoffs used to reclassify some shot paths as free. Shots with shooting values outside the interval [sp_cutoff_min, sp_cutoff_max] are treated as free excursions with special factors based on the count of internal frames beyond the cutoff. :type sp_cutoff_max: float, optional :param source: Per-frame stream used by Path extractors. This is passed to Path methods such as shooting(source), internal(source), and attribute access via getattr(path, source). In typical usage, this is ‘values’ (the CV used for sampling), but it can be any Path-supported stream. :type source: str, default=’values’

Returns:

If s != o (directional reweighting mode), returns:

weights : numpy.ndarray, shape (len(self),) Per-path weights aligned with the ensemble order.

indices : numpy.ndarray Absolute indices of the excursion paths that were actually reweighted (linked to s via start or end), ordered according to the internal order returned by reweight_excursions().

factors : numpy.ndarray, shape (n_excursions,) Per-excursion correction factors (1 for free excursions, density corrected for shot excursions, and possibly uniformized).

shooting_values : numpy.ndarray, shape (n_excursions,) Per-excursion shooting values in the signed convention used by the current direction. Free excursions have their shooting value set to ±inf to separate them from shot trajectories.

extremes : numpy.ndarray, shape (n_excursions,) Per-excursion extreme values (signed by direction). For some free cases and certain transitions, extremes are set to +inf.

xP : numpy.ndarray Crossing probabilities associated with the extremes, as returned by compute_crossing_probability() / reweight_excursions().

f, m : numpy.ndarray Additional diagnostic arrays returned by reweight_excursions() (kept as-is; used for debugging/analysis).

If s == o (diagnostic-only mode), returns:

(weights, arange(len(self)), factors, shooting_values, extremes, zeros_like(extremes), factors, zeros_like(extremes))

where weights is all zeros and the remaining arrays describe the factor/extreme preprocessing performed on excursions. :rtype: tuple

Notes

Internal paths:

  • Internal segments (paths starting in r and going back to s) are assigned a uniform weight by default.

  • If an internal segment was “shot” (type marker indicates not r), its weight is scaled by 1 / n_frames and then renormalized.

  • Internal weights are normalized to sum to the excursion total weight (or 1 if excursion weights are all zero), and then inserted into the global weights vector.

Transition shot excursions:

  • Shot transition paths (from o to s) are divided by 2 to avoid double counting.

  • Factors are clipped to [1e-3, 1000] to avoid extreme weights.

sample(n_samples, weights=None, source='values', vmin=None, vmax=None)

Sample individual frames from the ensemble and return them as a Path, according to the path weights.

Parameters:
  • n_samples (int) – Number of frames to sample (with replacement).

  • weights – Per-path weights. If not provided, path ensemble weights

are used (self.weights). :type weights: array_like, optional :param source: Considered for getting frames between vmin and vmax :type source: str, default=’values’ :param vmin: If specified, do not get frames with value below vmin :type vmin: float, default=None :param vmax: If specified, do not get frames with value above vmax :type vmax: float, default=None

Returns:

A Path whose segments each correspond to a single selected frame

(each segment uses the original filename and a one-frame range). :rtype: aimmd.path.Path

Notes

This routine constructs a new Path manually (no initialization). The resulting Path uses per-frame ranges: _first[i] == _last[i].

save(fname)

Save the ensemble to a text file listing trajectory filenames.

Parameters:

fname (str or pathlib.Path) – Output file path.

Notes

  • Paths are written relative to the output file’s parent directory.

  • The written list is taken from aimmd.pathensemble.PathEnsembleProperties.fnames, i.e., the concatenation of all per-path segment filenames.

shooting(attribute)

Shooting-point selector for the ensemble.

Calls path.shooting(attribute) for each path and returns one result per path. Container normalization follows the module-level policy.

property shooting_indices

Array-like view of per-path shooting indices.

Returns:

View over the Path attribute shooting_index.

Return type:

PathProperties

shooting_results(states='ARB', sweep_size=0)

Aggregate shooting results over sweeps.

Parameters:
  • states (str, default="ARB") – State alphabet forwarded to Path.shooting_result.

  • sweep_size (int, default=0) – Size of the sweep block. If <= 0, defaults to len(self).

Returns:

For each sweep point, sums the (n_to_A, n_to_B)-like counters returned

by each path’s shooting_result(states). :rtype: numpy.ndarray, shape (sweep_size, 2)

Notes

Each path is assigned to the sweep point (validation frame) it was shot from: the frame index tagged on the trajectory by aimmd.path.utils.write_sweep_frame(), if present. Shots written by an older code path carry no tag and fall back to positional assignment i % sweep_size – which is exactly the frame the old strictly-sequential sweep shot, so legacy data is attributed correctly without modification.

split(verbose=False)

Split each path and flatten the resulting pieces into one ensemble.

Parameters:

verbose (bool, default=False) – If True, show a progress bar.

Returns:

New ensemble where each input path has been replaced by the pieces

produced by Path.split(). :rtype: PathEnsemble

Notes

This expects Path.split() to return a PathEnsemble-like object with a _paths attribute; this matches the current AIMMD design.

subsample(caps, states='ARB', rng=None)

Return a randomly down-sampled sub-ensemble with per-category caps.

This bounds the cost of an expensive per-round value pass (and the bins / reweighting that consume it) by keeping only a capped, uniformly drawn subset of paths in each category, while leaving the full ensemble for training. Selection is uniform within each category so the reweighting per-category renormalisation stays consistent; in-state-only paths carry zero reweight, so dropping them never biases the rate estimate.

Categories use the 4-character Path.type (initial, middle, final, shooting state). With states='ARB' (a=A, r=R, b=B):

  • shot excursions : middle == r and shooting == r,

  • free excursions : middle == r and shooting != r,

  • in-state paths : middle != r (grouped by the initial state).

Parameters:

caps – Validated Params.subsample_caps for this system. Recognised keys:

  • 'shot' / 'free' : max PATHS kept per direction-type

(oXdX, i.e. each of AA/AB/BA/BB capped independently),

  • 'in_state' : max FRAMES kept per state.

A missing key leaves that category uncapped. None/empty returns self unchanged. :type caps: dict or None :param states: Three-character state string (A, R, B). :type states: str, default ‘ARB’ :param rng: Source of randomness. A fresh default generator is used if None. :type rng: numpy.random.Generator or None

Returns:

A new ensemble (a real slice of self). Returns self if no cap

applies or the ensemble is empty. :rtype: PathEnsemble

to_memory()

Force all paths to load their data into memory.

Delegates to Path.to_memory.

property true_states

Cached ‘true_states’ array for the ensemble. See Path.true_states.

Returns:

Delegated to the host class via self._get('true_states').

Return type:

object

types(*patterns)

Return or filter the array of path type strings.

Parameters:

*patterns – If provided, return a boolean mask selecting types that match any of

these patterns (see match_patterns()). :type *patterns: str

Returns:

If no patterns: array of dtype ‘<U…’ with Path.type per path.

If patterns: boolean mask of shape (n_paths,). :rtype: numpy.ndarray

property weights

Array-like view of per-path weights. See Path.weight.

Returns:

View over the Path attribute weight.

Return type:

PathProperties