vibespin.utils package

Submodules

utils.efficiency_runner module

Shared machinery for the Wolff-versus-Metropolis efficiency comparison.

The comparison asks the same question of every model here: at a given temperature, how many statistically independent configurations per second of wall-clock time does a local update deliver, and how many does the cluster update deliver? Nothing in that measurement is model-specific except the simulation class and where the interesting temperature window lies, so the worker, the figure, and the argument surface live here and each model script supplies only its own physics.

Comparing raw autocorrelation times across the two algorithms would be meaningless, because one Wolff step touches a cluster and one Metropolis sweep touches the whole lattice. The Wolff run therefore records one sample every round(L^2 / <C>) cluster flips, roughly one lattice sweep of work, so that both algorithms receive the same measurement budget in sweep units; giving both the same number of raw steps would leave Wolff with a few sweeps of work in the paramagnet, where clusters hold a handful of spins. tau_wolff is stored in cluster flips as before, and the work-normalised time multiplies it by the mean cluster fraction, putting both algorithms on a lattice-sweep footing; the independent-samples-per-second figure sidesteps the question entirely by measuring against the clock.

class utils.efficiency_runner.EfficiencyPoint(temp_idx: int, seed_idx: int, temperature: float, size: int, eq_probe_steps: int, eq_max_steps: int, meas_steps: int, model_cls: type, model_kwargs: dict[str, Any], detect_stuck: bool = False)[source]

Bases: NamedTuple

Typed worker payload for one (temperature, seed) efficiency measurement.

Parameters:
  • temp_idx (int) – Index of this temperature in the sweep grid.

  • seed_idx (int) – Replica index within the seed ensemble for this temperature.

  • temperature (float) – Simulation temperature T.

  • size (int) – Linear lattice dimension L.

  • eq_probe_steps (int) – Chunk size for the two-start convergence check.

  • eq_max_steps (int) – Hard cap on equilibration steps.

  • meas_steps (int) – Timed measurement steps per algorithm.

  • model_cls (type) – Simulation class to instantiate. It must be importable under its qualified name so that it survives the multiprocessing pickle.

  • model_kwargs (dict[str, Any]) – Extra constructor arguments beyond size, temperature, update, start, and seed.

  • detect_stuck (bool) – Enable quasi-steady stuck detection for both equilibrations; set only below the ordering temperature of a model with metastable domain states (default False).

detect_stuck: bool

Alias for field number 9

eq_max_steps: int

Alias for field number 5

eq_probe_steps: int

Alias for field number 4

meas_steps: int

Alias for field number 6

model_cls: type

Alias for field number 7

model_kwargs: dict[str, Any]

Alias for field number 8

seed_idx: int

Alias for field number 1

size: int

Alias for field number 3

temp_idx: int

Alias for field number 0

temperature: float

Alias for field number 2

utils.efficiency_runner.add_wolff_efficiency_arguments(*, parser: ArgumentParser, size: int, t_min: float, t_max: float, output_dir: str) → None[source]

Add the argument surface shared by the per-model efficiency scripts.

Parameters:
  • parser (argparse.ArgumentParser) – Parser to extend.

  • size (int) – Default linear lattice size L.

  • t_min (float) – Default lower end of the temperature window.

  • t_max (float) – Default upper end of the temperature window.

  • output_dir (str) – Default directory for the NPZ file and the figure.

Returns:

The parser is modified in place.

Return type:

None

utils.efficiency_runner.measure_efficiency_point(point: EfficiencyPoint) → dict[str, float][source]

Measure local-update and cluster-update efficiency at one grid point.

Both algorithms start from their own independently equilibrated state, so that neither inherits the other’s correlations. Metropolis records one sample per sweep; Wolff records one sample every round(L^2 / <C>) cluster flips, so both receive the same budget in sweep units.

Parameters:

point (EfficiencyPoint) – Payload describing the measurement.

Returns:

Grid indices, temperature, the measured quantities, and the converged_metro and converged_wolff flags. An algorithm whose two starts did not converge within eq_max_steps is not measured, and its quantities are NaN.

Return type:

dict[str, float]

utils.efficiency_runner.plot_efficiency(*, temperatures: ndarray, summaries: dict[str, dict[str, ndarray]], title: str, directory: str, transitions: dict[str, float] | None) → None[source]

Produce and save the four-panel efficiency comparison figure.

Parameters:
  • temperatures (numpy.ndarray) – Sorted temperature grid.

  • summaries (dict[str, dict[str, numpy.ndarray]]) – Median and band for each plotted quantity, keyed by tau_metro_norm, tau_wolff_norm, iss_metro, iss_wolff, mean_cluster_frac, chi_metro, and chi_wolff.

  • title (str) – Figure suptitle.

  • directory (str) – Output directory for the saved PNG.

  • transitions (dict[str, float] or None) – Vertical reference lines to draw in every panel, keyed by legend label, or None to omit them.

Returns:

The figure is written to wolff_efficiency.png in directory.

Return type:

None

utils.efficiency_runner.run_wolff_efficiency(*, args: Namespace, model_cls: type, model_kwargs: dict[str, Any], model_label: str, transitions: dict[str, float] | None, stuck_below: float | None = None) → None[source]

Run the efficiency comparison and write its NPZ file and figure.

Parameters:
  • args (argparse.Namespace) – Arguments parsed from a parser extended by add_wolff_efficiency_arguments.

  • model_cls (type) – Simulation class to compare the two update schemes on.

  • model_kwargs (dict[str, Any]) – Extra constructor arguments beyond size, temperature, update, start, and seed.

  • model_label (str) – Model name for the figure title and the NPZ metadata.

  • transitions (dict[str, float] or None) – Temperatures to mark in every panel, keyed by legend label, or None to omit the markers. The first by label is drawn dashed, the rest dotted.

  • stuck_below (float or None) – Temperature below which stuck detection is enabled, i.e. the ordering temperature of a model with metastable domain states. None disables stuck detection everywhere.

Returns:

Results are written to args.output_dir.

Return type:

None

utils.equilibration module

Equilibration algorithms for Monte Carlo simulations.

Provides adaptive and two-start convergence equilibration routines, together with the underlying relaxation-time estimation and quasi-steady-state detection helpers that support them. These algorithms were previously split between utils.system (equilibrate functions) and utils.analysis (relaxation diagnostic helpers), which required a lazy cross-import to avoid circular dependencies. Unifying them here eliminates that workaround.

utils.equilibration.ORDERED_START_SEED_OFFSET = 500

Offset between the seed of a random start and that of its ordered partner. The per-sweep RNG streams depend only on (seed, step), so two starts built with one seed draw identical random numbers and their traces become correlated, which weakens the cross-band test that assumes independent runs. The offset sits inside the 1000-seed block that derive_point_seed reserves for one replica, clear of the small seed + 1 and seed + 2 sub-streams callers derive.

class utils.equilibration.TwoStartOutcome(total_steps: int, converged: bool, stuck: bool)[source]

Bases: NamedTuple

Result of a two-start equilibration.

Parameters:
  • total_steps (int) – MC steps run by each of the two simulations.

  • converged (bool) – Whether the mutual cross-band criterion was met, i.e. both starts reached the same stationary state.

  • stuck (bool) – Whether the run stopped on a quasi-steady stuck state: the ordered start had settled while the random start stayed stranded on a metastable plateau. Only the ordered start is then a valid measurement source.

property certified: bool

Whether a measurement on this pair is valid.

True after convergence or after a stuck exit. A stuck exit can only occur where the caller enabled detect_stuck, which callers do only where a stuck state is accepted. A run that reached max_steps is not certified: neither start is known to have relaxed, and callers store NaN for the point instead of measuring it.

converged: bool

Alias for field number 1

stuck: bool

Alias for field number 2

total_steps: int

Alias for field number 0

utils.equilibration.adaptive_equilibrate(sim: _Sim, *, min_steps: int, probe_steps: int = 500, factor: float = 50.0, max_steps: int = 200000) → int[source]

Equilibrate a simulation adaptively, extending the burn-in until the probe window covers factor integrated autocorrelation times.

After the mandatory min_steps burn-in, the function repeatedly runs a probe_steps measurement via sim.run() and computes tau_int from the resulting magnetization series. If probe_steps >= factor * tau_int, the probe spans enough correlation times for the initial state to be forgotten and equilibration is declared complete. Otherwise the probe has advanced the system state and the loop continues. In the ordered phase the magnetization series has zero variance; this is treated as full equilibration and the function returns immediately.

Parameters:
  • sim (_Sim) – Any simulation object implementing equilibrate and run.

  • min_steps (int) – Mandatory burn-in passed to sim.equilibrate before probing.

  • probe_steps (int) – MC steps per probe run (default 500).

  • factor (float) – Required ratio probe_steps / tau_int (default 50.0).

  • max_steps (int) – Hard cap on total steps to prevent unbounded runtime near criticality (default 200 000).

Returns:

Total number of MC steps run (burn-in + probes).

Return type:

int

Raises:

ValueError – If the adaptive-equilibration parameters are invalid.

utils.equilibration.convergence_equilibrate(*, sim_random: _Sim, sim_ordered: _Sim, chunk_size: int = 500, max_steps: int = 200000, qs_sigma_threshold: float = 0.05, qs_min_steps: int = 1500, **kwargs: Any) → int[source]

Equilibrate two simulations (random- and ordered-start) until they converge.

Uses estimate_relaxation_time_two_start to detect convergence via the mutual cross-band criterion: each smoothed trajectory must enter and sustain a band defined by the other trajectory’s tail statistics. A sigma floor prevents false positives when one trace is nearly flat. This is more robust than one-start adaptive methods for complex energy landscapes.

Parameters:
  • sim_random (_Sim) – Simulation instance started from a random state.

  • sim_ordered (_Sim) – Simulation instance started from an ordered state.

  • chunk_size (int) – Number of steps to run between convergence checks.

  • max_steps (int) – Hard cap on total steps.

  • qs_sigma_threshold (float) – Tail-std threshold used to detect a quasi-steady, non-converged stuck state and exit early.

  • qs_min_steps (int) – Minimum accumulated steps before stuck detection is allowed to fire. Ensures tail statistics are computed from enough data to be reliable, preventing false positives when traces have not yet had time to settle.

  • **kwargs (Any) – Passed to estimate_relaxation_time_two_start (k, smooth_window, dwell_window, min_fraction_inside, sigma_floor, etc.).

Returns:

Total number of MC steps run per simulation.

Return type:

int

utils.equilibration.convergence_equilibrate_two_start(*, sim_random: _Sim, sim_ordered: _Sim, chunk_size: int = 500, max_steps: int = 200000, qs_sigma_threshold: float = 0.05, qs_min_steps: int = 1500, detect_stuck: bool = False, **kwargs: Any) → TwoStartOutcome[source]

Equilibrate a random-start and an ordered-start simulation side by side.

The two runs advance in chunks until their smoothed magnetization traces pass the mutual cross-band criterion of estimate_relaxation_time_two_start, until the quasi-steady stuck detector fires, or until max_steps is reached. Unlike convergence_equilibrate_with_status the result keeps a stuck exit apart from genuine convergence, so callers can measure on the start that is actually valid (see select_measurement_simulation).

Parameters:
  • sim_random (_Sim) – Simulation instance started from a random state.

  • sim_ordered (_Sim) – Simulation instance started from an ordered state. It should carry a different seed from sim_random (see ordered_start_seed).

  • chunk_size (int) – Number of steps to run between convergence checks.

  • max_steps (int) – Hard cap on total steps.

  • qs_sigma_threshold (float) – Tail-std threshold used to detect a quasi-steady stuck state.

  • qs_min_steps (int) – Minimum accumulated steps before stuck detection may fire.

  • detect_stuck (bool) – Whether a quasi-steady stuck state ends the run early (default False). The detector cannot tell a stranded random start from one that is still relaxing slowly, which is common near a transition and for the XY model below T_BKT, so it is opt-in: enable it only in the ordered phase of a model with metastable domain states, where measuring the ordered start after a stuck exit is valid.

  • **kwargs (Any) – Passed to estimate_relaxation_time_two_start (k, smooth_window, dwell_window, min_fraction_inside, sigma_floor, etc.).

Returns:

Steps run, convergence flag, and stuck flag. At most one flag is set.

Return type:

TwoStartOutcome

utils.equilibration.convergence_equilibrate_with_status(*, sim_random: _Sim, sim_ordered: _Sim, chunk_size: int = 500, max_steps: int = 200000, qs_sigma_threshold: float = 0.05, qs_min_steps: int = 1500, qs_allow_stuck: bool = False, **kwargs: Any) → tuple[int, bool][source]

Equilibrate two simulations and report whether convergence was reached.

Uses estimate_relaxation_time_two_start to detect convergence via the mutual cross-band criterion: each smoothed trajectory must enter and sustain a band defined by the other trajectory’s tail statistics. A sigma floor prevents false positives when one trace is nearly flat. This variant returns both the total number of MC steps executed and a boolean convergence flag.

The boolean cannot tell an accepted stuck state from genuine convergence; after an accepted stuck state only the ordered start is a valid measurement source. Callers that measure should use convergence_equilibrate_two_start with select_measurement_simulation instead.

Parameters:
  • sim_random (_Sim) – Simulation instance started from a random state.

  • sim_ordered (_Sim) – Simulation instance started from an ordered state.

  • chunk_size (int) – Number of steps to run between convergence checks.

  • max_steps (int) – Hard cap on total steps.

  • qs_sigma_threshold (float) – Tail-std threshold used to detect a quasi-steady, non-converged stuck state and exit early.

  • qs_min_steps (int) – Minimum accumulated steps before stuck detection is allowed to fire. Ensures tail statistics are computed from enough data to be reliable, preventing false positives when traces have not yet had time to settle.

  • qs_allow_stuck (bool) – If True, detecting a quasi-steady stuck state (where the ordered trace is stable but the random trace is stranded) is treated as a successful equilibration. Useful for Ising sweeps where random-start domain-wall trapping is physically expected.

  • **kwargs (Any) – Passed to estimate_relaxation_time_two_start (k, smooth_window, dwell_window, min_fraction_inside, sigma_floor, etc.).

Returns:

Tuple (total_steps, converged).

Return type:

tuple[int, bool]

utils.equilibration.estimate_relaxation_time_two_start(*, trace_random: ndarray, trace_ordered: ndarray, k: float = 1.0, smooth_window: int = 60, dwell_window: int = 60, min_fraction_inside: float = 0.85, sigma_floor: float = 0.02, skip_validation: bool = False) → int[source]

Estimate thermalization time from convergence of random- and ordered-start traces.

Compares a trajectory started from a random spin configuration against one started from a fully ordered configuration. Returns the first step at which both smoothed traces pass a mutual cross-band test sustained over a dwell window.

The criterion is asymmetric in the correct physical sense: the smoothed random-start trace must lie within k standard deviations of the ordered-start tail mean, and the ordered-start trace must simultaneously lie within k standard deviations of the random-start tail mean. Tail statistics are computed from the second half of each smoothed trace independently. A sigma_floor prevents band collapse when one trace is nearly variance-free (e.g. in the deep ordered phase near T=0).

Parameters:
  • trace_random (np.ndarray) – 1-D magnetization trace from a random initial state.

  • trace_ordered (np.ndarray) – 1-D magnetization trace from an ordered initial state.

  • k (float) – Half-width of each convergence band in units of the respective tail standard deviation. Larger values are more permissive.

  • smooth_window (int) – Window length (steps) for the moving-average smoother.

  • dwell_window (int) – Window length (steps) for the sustained-convergence test.

  • min_fraction_inside (float) – Fraction of steps within dwell_window that must satisfy the mutual cross-band condition to declare convergence.

  • sigma_floor (float) – Minimum allowed standard deviation for each tail, preventing band collapse when a trajectory is nearly flat.

  • skip_validation (bool) – If True, skip np.asarray and finite-prefix checks.

Returns:

Estimated relaxation time as a 0-indexed position in the original input traces (i.e. a sweep count minus one). The first index at which both smoothed traces have been mutually inside each other’s band for dwell_window steps is mapped back to the corresponding raw-trace position as hits[0] + smooth_window - 1. Returns n (full trace length) if no convergence is detected, or 0 for very short traces.

Return type:

int

utils.equilibration.ordered_start_seed(*, seed: int | None) → int | None[source]

Return the seed for the ordered-start partner of a seeded random start.

Parameters:

seed (int or None) – Seed of the random-start simulation. None (unseeded) is passed through unchanged.

Returns:

seed + ORDERED_START_SEED_OFFSET, or None for an unseeded run.

Return type:

int or None

Raises:

ValueError – If the partner seed would leave the 32-bit generator range.

utils.equilibration.prepare_equilibrated_simulation(*, model_cls: type, model_kwargs: dict[str, Any], size: int, temp: float, seed: int | None, chunk_size: int, max_steps: int, update: str = 'checkerboard', **kwargs: Any) → tuple[Any, TwoStartOutcome][source]

Build a two-start pair, equilibrate it, and return the start to measure.

The random start receives seed and the ordered start ordered_start_seed(seed=seed), so the two runs draw independent random numbers. After equilibration the random start is returned when the pair converged, and the ordered start otherwise (see select_measurement_simulation). When the run hit max_steps, outcome.certified is False and the caller should record NaN for the point rather than measure the returned simulation.

Parameters:
  • model_cls (type) – Simulation class to instantiate.

  • model_kwargs (dict[str, Any]) – Constructor arguments beyond size, temperature, update, start, and seed.

  • size (int) – Linear lattice size L.

  • temp (float) – Simulation temperature T.

  • seed (int or None) – Seed of the random start; None leaves both starts unseeded.

  • chunk_size (int) – Steps between convergence checks.

  • max_steps (int) – Hard cap on equilibration steps.

  • update (str) – Update scheme for both starts (default 'checkerboard').

  • **kwargs (Any) – Passed to convergence_equilibrate_two_start, for example detect_stuck=True in the ordered phase of a model with metastable domain states.

Returns:

The simulation to measure and the equilibration outcome.

Return type:

tuple[Any, TwoStartOutcome]

utils.equilibration.select_measurement_simulation(*, outcome: TwoStartOutcome, sim_random: SimT, sim_ordered: SimT) → SimT[source]

Choose which start of an equilibrated pair to measure.

The random start is used only when the two starts converged to the same state. After a stuck exit the random start sits on a metastable plateau, so the ordered start is returned. After hitting the step cap the ordered start is returned as well, but neither start is certified (outcome.certified is False) and callers must not measure it.

Parameters:
  • outcome (TwoStartOutcome) – Result of convergence_equilibrate_two_start.

  • sim_random (simulation) – Random-start simulation.

  • sim_ordered (simulation) – Ordered-start simulation.

Returns:

sim_random if the pair converged, otherwise sim_ordered.

Return type:

simulation

utils.evolution_helpers module

Shared infrastructure for ordering evolution visualisation scripts.

Provides the snapshot loop and figure generation shared by the Ising, XY, and Clock ordering-evolution scripts.

utils.evolution_helpers.run_ordering_evolution(*, model_cls: type, model_kwargs: dict[str, Any], capture_vorticity: bool, title: str, size: int, temp: float, step_targets: list[int], output_dir: str, logger: Logger | None = None) → None[source]

Run an ordering evolution simulation and save the multi-panel figure.

Quenches the model to temp, advances to each step in step_targets, captures spin configurations and correlation functions, optionally captures vorticity maps, and writes the figure to output_dir.

Parameters:
  • model_cls (type) – Simulation class to instantiate (e.g. XYSimulation).

  • model_kwargs (dict[str, Any]) – Extra keyword arguments forwarded to the constructor beyond size, temp, and update='random'.

  • capture_vorticity (bool) – Whether to record vorticity maps at each snapshot. Pass True for vector-spin models (XY, Clock) and False for scalar models (Ising). Controls is_vector in the output figure.

  • title (str) – Figure-level suptitle.

  • size (int) – Linear lattice size L.

  • temp (float) – Quench temperature T.

  • step_targets (list[int]) – MC step counts at which to capture snapshots. Need not be sorted; the function sorts them internally.

  • output_dir (str) – Directory in which to write the output figure.

  • logger (logging.Logger, optional) – Logger to use; creates a module-level logger if not provided.

utils.exceptions module

Project-specific exception types for analysis and runtime failures.

exception utils.exceptions.NumericalAnalysisError[source]

Bases: VibeSpinError, RuntimeError

Base class for mathematically undefined or failed analysis results.

exception utils.exceptions.VibeSpinError[source]

Bases: Exception

Base class for project-specific exceptions.

exception utils.exceptions.ZeroVarianceAutocorrelationError[source]

Bases: NumericalAnalysisError

Raised when autocorrelation is undefined because the series variance is zero.

utils.kinetics_helpers module

Shared infrastructure for ordering kinetics analysis scripts.

Provides the simulation loop, power-law fitting, and result plotting shared by the Ising, XY, and Clock ordering-kinetics scripts. The compute_mean_intercept_length function is also placed here as a reusable domain-size estimator for scalar-spin models.

utils.kinetics_helpers.compute_mean_intercept_length(*, sim: Any) → float[source]

Estimate domain size via the stereological mean intercept length (MIL).

Counts domain-wall crossings along every row and column of the lattice, including the periodic wrap-around crossing, then divides the total line length by the crossing count to obtain the mean intercept length.

Parameters:

sim (Any) – A simulation instance with a spins attribute (an integer-sign array) and a size property giving the linear lattice dimension.

Returns:

Estimated domain size in lattice units. Returns float(size) when there are no domain walls (fully ordered state).

Return type:

float

utils.kinetics_helpers.run_ordering_kinetics(*, model_cls: type, model_kwargs: dict[str, Any], third_metric_fn: Callable[[Any], float], third_metric_label: str, title: str, left_title: str, right_title: str, size: int, temp: float, max_steps: int, samples: int, fit_min: int, output_dir: str, y_label: str = 'Characteristic Length Scale $L(t)$ (lattice units)', logger: Logger | None = None, npz_path: str | None = None, n_seeds: int = 1, base_seed: int = 42) → None[source]

Run an ordering kinetics simulation and save the two-panel kinetics figure.

Quenches the model to temp, steps forward to each of samples logarithmically spaced targets up to max_steps, measures growth scales and a model-specific third metric, fits power laws, and writes the figure to output_dir.

When n_seeds > 1, the simulation is repeated for an ensemble of seeds. The median trajectory is used for fitting and plotting, and per-seed arrays together with IQR-based error bars are saved to the NPZ file.

Parameters:
  • model_cls (type) – Simulation class to instantiate (e.g. IsingSimulation).

  • model_kwargs (dict[str, Any]) – Extra keyword arguments forwarded to the constructor beyond size, temp, and update='random'.

  • third_metric_fn (Callable[[Any], float]) – Called with the live simulation instance at each measurement step; returns a scalar third metric (e.g. vortex density or MIL).

  • third_metric_label (str) – Y-axis label for the third-metric panel.

  • title (str) – Figure-level suptitle.

  • left_title (str) – Title for the left (growth-scale) subplot.

  • right_title (str) – Title for the right (third-metric) subplot.

  • size (int) – Linear lattice size L.

  • temp (float) – Quench temperature T.

  • max_steps (int) – Total MC steps to run.

  • samples (int) – Number of logarithmically spaced measurement points.

  • fit_min (int) – Minimum MC step used for power-law fitting.

  • output_dir (str) – Directory in which to write the output figure.

  • y_label (str, optional) – Y-axis label for the growth-scale panel.

  • logger (logging.Logger, optional) – Logger to use; creates a module-level logger if not provided.

  • npz_path (str, optional) – If given, save the kinetics data arrays to this .npz file for notebook consumption.

  • n_seeds (int, optional) – Number of independent seeds to run. Defaults to 1 (legacy single-trajectory behavior).

  • base_seed (int, optional) – Starting seed; seeds are base_seed, base_seed+1, ....

utils.observables module

Physics-related utility functions for calculating thermodynamic observables and correlations.

class utils.observables.CorrelationPoint(label: str, temperature: float, model_cls: type, model_kwargs: dict[str, Any], size: int, seed: int, eq_probe: int, eq_max: int, meas_steps: int, interval: int, detect_stuck: bool = False)[source]

Bases: NamedTuple

Typed worker payload for one temperature of a correlation comparison.

Parameters:
  • label (str) – Name of the phase this temperature represents, carried through so the caller can match results back to the temperature that produced them without relying on the order the pool returns them in.

  • temperature (float) – Simulation temperature T.

  • model_cls (type) – Simulation class to instantiate. It must be importable under its qualified name so that it survives the multiprocessing pickle.

  • model_kwargs (dict[str, Any]) – Extra constructor arguments beyond size, temperature, update, start, and seed.

  • size (int) – Linear lattice size L.

  • seed (int) – Random seed of the random start; the ordered start uses ordered_start_seed(seed=seed).

  • eq_probe (int) – Chunk size for convergence equilibration probes.

  • eq_max (int) – Maximum equilibration steps.

  • meas_steps (int) – Measurement steps after equilibration.

  • interval (int) – Spacing between correlation samples during measurement.

  • detect_stuck (bool) – Forwarded to simulate_equilibrium_correlation (default False).

detect_stuck: bool

Alias for field number 10

eq_max: int

Alias for field number 7

eq_probe: int

Alias for field number 6

interval: int

Alias for field number 9

label: str

Alias for field number 0

meas_steps: int

Alias for field number 8

model_cls: type

Alias for field number 2

model_kwargs: dict[str, Any]

Alias for field number 3

seed: int

Alias for field number 5

size: int

Alias for field number 4

temperature: float

Alias for field number 1

utils.observables.calculate_entropy(*, temperatures: ndarray, specific_heat: ndarray, s_ref: float = 0.0) → ndarray[source]

Compute entropy by integrating specific heat over a temperature sweep.

Integrates C(T)/T from high temperature downward so that S(T_max) = s_ref and S(T) = s_ref - integral from T to T_max of C/T dT’. This avoids the C/T divergence near T = 0 and anchors the result at the high-temperature limit where the entropy is analytically known.

Parameters:
  • temperatures (np.ndarray) – 1-D array of temperature values. Need not be sorted.

  • specific_heat (np.ndarray) – Specific heat C_v at each temperature (same length).

  • s_ref (float) – Reference entropy at the highest temperature. Pass 0.0 for relative entropy or np.log(q) (per site, in units of k_B) for absolute entropy of a q-state model.

Returns:

1-D array of entropy values, one per temperature, in the original unsorted order of temperatures.

Return type:

np.ndarray

Raises:

ValueError – If arrays differ in length, contain fewer than 2 points, or include non-positive temperatures.

utils.observables.calculate_thermodynamics(*, mags: ndarray, engs: ndarray, T: float, L: int) → tuple[float, float, float, float][source]

Calculate average magnetization, energy, susceptibility, and specific heat.

Parameters:
  • mags (np.ndarray) – Array of magnetization measurements.

  • engs (np.ndarray) – Array of energy measurements.

  • T (float) – Temperature.

  • L (int) – Linear lattice size.

Returns:

A tuple of (avg_mag, avg_eng, susceptibility, specific_heat).

Return type:

tuple[float, float, float, float]

Raises:

ValueError – If T is not positive or L is not a positive integer.

utils.observables.compute_kinetics_metrics(*, sim: _Sim) → dict[str, float][source]

Calculate common kinetics metrics (R_sk, xi) for a simulation state.

Parameters:

sim (_Sim) – MonteCarloSimulation instance.

Returns:

Dictionary containing ‘R_sk’ and ‘xi’.

Return type:

dict[str, float]

utils.observables.connected_correlation_length(*, sim: _Sim, meas_steps: int, sample_interval: int) → float[source]

Measure the equilibrium correlation length from the connected correlation.

The simulation is advanced meas_steps sweeps, and every sample_interval sweeps the lattice-axis pair correlation of the spin field is accumulated after subtracting the configuration’s mean spin. The 1/e crossing of the averaged, normalised function is returned. Subtracting the mean matters below the ordering temperature: the disconnected function plateaus at m^2 and never falls below 1/e, so a 1/e criterion applied to it returns the largest distance available instead of a correlation length.

Parameters:
  • sim (_Sim) – Equilibrated simulation; it is advanced in place.

  • meas_steps (int) – Number of sweeps to run.

  • sample_interval (int) – Sweeps between two samples.

Returns:

Connected correlation length in lattice units, or NaN if the averaged function never drops below 1/e within half the lattice.

Return type:

float

Raises:

ValueError – If no sample falls inside meas_steps.

utils.observables.correlation_length_1e(*, r: ndarray, G: ndarray) → float[source]

Estimate the correlation length as the 1/e crossing of G(r).

Linearly interpolates between the last point above 1/e and the first point below it. Returns r[0] when the very first point is already below 1/e, and NaN when G never drops below 1/e within the given range (callers decide the appropriate fallback for their context).

Parameters:
  • r (np.ndarray) – Radial distances (monotonically increasing).

  • G (np.ndarray) – Correlation values G(r), normalised so G(0) = 1.

Returns:

The interpolated 1/e crossing radius, or NaN if no crossing exists.

Return type:

float

utils.observables.derived_thermo_estimate(*, series: ndarray, temperature: float, L: int, observable: str) → float[source]

Compute a fluctuation-based derived observable from a time series.

Single authoritative implementation of the fluctuation-dissipation formulas, shared by calculate_thermodynamics() and the uncertainty summarizers in utils.statistics.

Parameters:
  • series (np.ndarray) – 1-D time series (magnetization for 'chi', energy per site for 'cv').

  • temperature (float) – Temperature T of the measurement.

  • L (int) – Linear lattice size.

  • observable (str) – 'chi' (susceptibility, N Var(M)/T) or 'cv' (specific heat, N Var(E)/T^2).

Returns:

The derived observable value.

Return type:

float

Raises:

ValueError – If observable is not 'chi' or 'cv'.

utils.observables.fit_correlation_exponent(*, r: ndarray, G: ndarray, r_min: int = 2, r_max: int | None = None) → float[source]

Fit the anomalous dimension of an algebraically decaying G(r).

A straight line through log G against log r has slope -eta, so this is the right estimator where power-law decay is expected: at the critical point of the Ising model, where eta is exactly 1/4, and throughout the quasi-ordered phase of the XY and clock models, where spin-wave theory predicts eta = T / (2 pi J).

Parameters:
  • r (numpy.ndarray) – Radial distances.

  • G (numpy.ndarray) – Correlation values.

  • r_min (int, optional) – Smallest distance to fit.

  • r_max (int or None, optional) – Largest distance to fit, or None for L/4.

Returns:

The exponent eta, or NaN when fewer than two usable points remain or the fit fails.

Return type:

float

utils.observables.fit_correlation_length(*, r: ndarray, G: ndarray, r_min: int = 2, r_max: int | None = None) → float[source]

Fit the correlation length of an exponentially decaying G(r).

A straight line through log G against r has slope -1/xi, so this is the right estimator only where exponential decay is the expected form, which means above the transition. Applying it inside a critical or quasi-ordered phase returns a number, but that number describes nothing.

Parameters:
  • r (numpy.ndarray) – Radial distances.

  • G (numpy.ndarray) – Correlation values.

  • r_min (int, optional) – Smallest distance to fit.

  • r_max (int or None, optional) – Largest distance to fit, or None for L/4.

Returns:

The correlation length xi, or NaN when fewer than two usable points remain, the fit fails, or the fitted slope is not negative.

Return type:

float

utils.observables.get_averaged_correlation(*, sim: _Sim, total_steps: int, sample_interval: int) → tuple[ndarray, ndarray][source]

Run simulation and average the correlation function over multiple configurations.

Parameters:
  • sim (_Sim) – An instance of MonteCarloSimulation.

  • total_steps (int) – Total number of MC steps to run.

  • sample_interval (int) – Interval between correlation samples. Must be ≥ 1.

Returns:

  • r (np.ndarray) – Radial distances.

  • G_r_avg (np.ndarray) – Averaged correlation values.

Raises:

ValueError – If sample_interval is less than 1 or total_steps is negative.

utils.observables.measure_correlation_point(point: CorrelationPoint) → tuple[str, ndarray, ndarray][source]

Worker: equilibrate and measure G(r) at one temperature.

This exists as a module-level function taking a single argument so that it can be handed to parallel_sweep, which pickles the worker and its payload across processes.

Parameters:

point (CorrelationPoint) – Payload describing the measurement.

Returns:

The point’s label, the radial distances, and the averaged G(r), which is all NaN when the two starts did not converge within eq_max.

Return type:

tuple[str, numpy.ndarray, numpy.ndarray]

utils.observables.pair_correlation_x(*, spins: ndarray) → tuple[ndarray, ndarray][source]

Compute the real-space spin-spin pair correlation G(r) along x.

Uses the Wiener-Khinchin theorem: the autocorrelation of each row is the inverse FFT of the row’s power spectrum. Results are averaged over all rows (y positions) and normalised so G(0) = 1.

Parameters:

spins (np.ndarray) – (N, N) or (N, N, 2) spin array.

Returns:

  • r_vals (np.ndarray) – Lag distances r = 0 … N//2 in lattice units.

  • G (np.ndarray) – Normalised pair correlation G(r) / G(0).

utils.observables.radial_average_sk(*, spins: ndarray) → tuple[ndarray, ndarray][source]

Compute the circularly averaged structure factor \(S(|k|)\).

Bins \(S(k)\) by integer pixel radius from the DC centre of the shifted FFT, then averages within each annular bin.

Parameters:

spins (np.ndarray) – (N, N) or (N, N, 2) spin array.

Returns:

  • k_vals (np.ndarray) – Wavevector magnitudes in units of 2π/N (reciprocal lattice).

  • S_radial (np.ndarray) – Mean S(k) value for each annular bin.

utils.observables.simulate_equilibrium_correlation(*, model_cls: type, model_kwargs: dict[str, Any], size: int, temp: float, seed: int, eq_probe: int, eq_max: int, meas_steps: int, interval: int, logger: Logger | None = None, detect_stuck: bool = False) → tuple[ndarray, ndarray][source]

Equilibrate a model and measure its averaged correlation function.

Runs two-start convergence equilibration (random start vs. ordered start, checkerboard updates) to avoid initialization bias, then averages the correlation function over meas_steps Monte Carlo steps, sampling every interval steps. When convergence is not reached within eq_max steps, the point is not measured and G(r) is returned as NaN.

Parameters:
  • model_cls (type) – Simulation class to instantiate (e.g. IsingSimulation).

  • model_kwargs (dict[str, Any]) – Extra keyword arguments forwarded to the model constructor beyond size, temp, update, init_state, and seed (e.g. {'q': 6} for the clock model).

  • size (int) – Linear lattice size L.

  • temp (float) – Temperature for the measurement.

  • seed (int) – Random seed of the random start; the ordered start uses ordered_start_seed(seed=seed).

  • eq_probe (int) – Chunk size for convergence equilibration probes.

  • eq_max (int) – Maximum equilibration steps.

  • meas_steps (int) – Measurement steps after equilibration.

  • interval (int) – Spacing between correlation samples during measurement.

  • logger (logging.Logger | None) – Optional logger for progress and fallback messages.

  • detect_stuck (bool) – Enable quasi-steady stuck detection, so that a random start stranded in a domain state ends the run and the ordered start is measured. Set it only in the ordered phase of a model with metastable domain states (default False).

Returns:

  • r (np.ndarray) – Radial distances.

  • G_r_avg (np.ndarray) – Averaged correlation values G(r), all NaN when the two starts did not converge within eq_max steps.

utils.plotting module

Domain plotting and file-output helpers for VibeSpin simulations.

Groups the filesystem output helpers (save_plot(), ensure_results_dir()) together with the domain-specific visualisation functions. Keeping visualisation logic here leaves utils.system a pure infrastructure module (logging, parallelism) with no matplotlib dependency.

utils.plotting.ensure_results_dir(*, directory: str = 'results') → str[source]

Ensure the results directory exists.

Parameters:

directory (str) – Name of the directory to create.

Returns:

The path to the directory.

Return type:

str

utils.plotting.plot_ordering_evolution(*, targets: Sequence[int], snapshots: Sequence[ndarray], gr_data: Sequence[tuple[ndarray, ndarray]], vorticity_data: Sequence[ndarray] | None, title: str, filename: str, directory: str, is_vector: bool = False) → None[source]

Generate and save a multi-row figure showing order evolution over time.

Row 0: Spin configurations (binary for Ising, HSV for XY/Clock). Row 1: Circularly-averaged structure factor \(S(|k|)\) or vorticity maps. Row 2: Radially averaged correlation functions G(r) with xi estimates.

Parameters:
  • targets (Sequence[int]) – List of MC steps for each snapshot.

  • snapshots (Sequence[np.ndarray]) – List of spin arrays.

  • gr_data (Sequence[tuple[np.ndarray, np.ndarray]]) – List of (r, G) tuples.

  • vorticity_data (Sequence[np.ndarray] | None) – Optional list of vorticity arrays.

  • title (str) – Figure-level suptitle.

  • filename (str) – Output filename.

  • directory (str) – Output directory.

  • is_vector (bool) – Whether the spins are 2D vectors (True) or scalars (False).

utils.plotting.plot_ordering_evolution_snapshots(*, targets: Sequence[int], snapshots: Sequence[ndarray], gr_data: Sequence[tuple[ndarray, ndarray]], sk_data: Sequence[tuple[ndarray, ndarray]], size: int, temp: float) → tuple[Figure, ndarray, list[float]][source]

Build a 3-row diagnostic grid of ordering-evolution snapshots.

Row 1 shows binary spin matrices, row 2 the structure factor \(S(|k|)\) on log-log axes, and row 3 the spatial correlation function G(r) with the 1/e crossing (correlation length xi) annotated.

Unlike plot_ordering_evolution(), this helper returns the figure instead of writing it to disk, so notebooks can render the grid inline.

Parameters:
  • targets (Sequence[int]) – Target Monte Carlo sweep counts, one per column.

  • snapshots (Sequence[np.ndarray]) – Spin matrices, one per target.

  • gr_data (Sequence[tuple[np.ndarray, np.ndarray]]) – Correlation data (r, G(r)), one per target.

  • sk_data (Sequence[tuple[np.ndarray, np.ndarray]]) – Structure-factor data (k, S(|k|)), one per target.

  • size (int) – Lattice size L, used in the suptitle.

  • temp (float) – Quench temperature, used in the suptitle.

Returns:

  • fig (plt.Figure) – The figure holding the grid.

  • axes (np.ndarray) – The (3, n_targets) axes grid.

  • xi_values (list[float]) – Correlation length per target; NaN where G(r) never crosses 1/e.

utils.plotting.plot_ordering_kinetics(*, t: ndarray, R_sk: ndarray, R_xi: ndarray, third_metric: ndarray | None, third_metric_label: str | None, exponents: dict[str, float | None], prefactors: dict[str, float | None], fit_mask: ndarray, title: str, filename: str, directory: str, y_label: str = 'Characteristic Length Scale $L(t)$ (lattice units)', left_title: str = 'Domain Coarsening', right_title: str = 'Defect/Boundary Evolution') → None[source]

Generate and save a 2-panel figure showing ordering kinetics.

Left Panel: Growth of length scales R_sk and xi. Right Panel: Growth/Decay of a third metric (Vortex density or MIL).

Parameters:
  • t (np.ndarray) – Time array (Monte Carlo sweeps).

  • R_sk (np.ndarray) – Domain size from structure factor.

  • R_xi (np.ndarray) – Correlation length from G(r).

  • third_metric (np.ndarray | None) – Optional third metric array.

  • third_metric_label (str | None) – Label for the third metric.

  • exponents (dict[str, float | None]) – Dict of fitted exponents.

  • prefactors (dict[str, float | None]) – Dict of fitted prefactors.

  • fit_mask (np.ndarray) – Mask used for fitting.

  • title (str) – Figure-level suptitle.

  • filename (str) – Output filename.

  • directory (str) – Output directory.

  • y_label (str) – Y-axis label for the left panel.

  • left_title (str) – Title for the left subplot.

  • right_title (str) – Title for the right subplot.

utils.plotting.plot_temperature_sweep(*, temperatures: ndarray, avg_m: Sequence[float], avg_e: Sequence[float], susc: Sequence[float], spec_h: Sequence[float], title: str, filename: str, directory: str, avg_m_err: ndarray | Sequence[float] | None = None, avg_e_err: ndarray | Sequence[float] | None = None, susc_err: ndarray | Sequence[float] | None = None, spec_h_err: ndarray | Sequence[float] | None = None, entropy: ndarray | Sequence[float] | None = None, entropy_err: ndarray | Sequence[float] | None = None, entropy_ci_low: ndarray | Sequence[float] | None = None, entropy_ci_high: ndarray | Sequence[float] | None = None, tau_int: ndarray | Sequence[float] | None = None, tau_int_ci_low: ndarray | Sequence[float] | None = None, tau_int_ci_high: ndarray | Sequence[float] | None = None, tau_unstable_flag: ndarray | Sequence[float] | None = None, low_effective_sample_flag: ndarray | Sequence[float] | None = None, diagnostics_note: str | None = None, run_metadata_note: str | None = None, quality_summary: Mapping[str, int | float] | None = None, transition_temperatures: dict[str, float] | None = None, transition_window: tuple[float, float] | None = None, entropy_reference: tuple[str, float] | None = None, annotate_peaks: bool = True, min_visible_rel_error: float = 0.01, mark_invalid_uncertainty: bool = True) → None[source]

Generate and save a standardized temperature sweep plot.

Displays magnetization, energy, susceptibility, and specific heat as functions of temperature in a dedicated thermodynamics figure. When entropy or tau_int are provided a companion diagnostics figure is saved alongside the main figure.

Parameters:
  • temperatures (np.ndarray) – Array of temperature values (x-axis).

  • avg_m (Sequence[float]) – Average absolute magnetization per temperature point.

  • avg_e (Sequence[float]) – Average energy per temperature point.

  • susc (Sequence[float]) – Magnetic susceptibility per temperature point.

  • spec_h (Sequence[float]) – Specific heat per temperature point.

  • title (str) – Figure-level suptitle string (e.g. ‘2D Ising Model: Temperature Sweep (L=50)’).

  • filename (str) – Output filename passed to save_plot() (e.g. ‘temperature_sweep.png’).

  • directory (str) – Output directory passed to save_plot() (e.g. ‘results/ising’).

  • entropy (np.ndarray | Sequence[float] | None) – Optional entropy per temperature point.

  • entropy_err (np.ndarray | Sequence[float] | None) – Optional symmetric uncertainty for entropy.

  • entropy_ci_low (np.ndarray | Sequence[float] | None) – Optional lower confidence band for entropy.

  • entropy_ci_high (np.ndarray | Sequence[float] | None) – Optional upper confidence band for entropy.

  • tau_int (np.ndarray | Sequence[float] | None) – Optional integrated autocorrelation time per temperature point. Reveals critical slowing down as a peak near T_c.

  • tau_int_ci_low (np.ndarray | Sequence[float] | None) – Optional lower confidence band for tau_int.

  • tau_int_ci_high (np.ndarray | Sequence[float] | None) – Optional upper confidence band for tau_int.

  • tau_unstable_flag (np.ndarray | Sequence[float] | None) – Optional per-temperature mask flagging unstable tau_int intervals.

  • low_effective_sample_flag (np.ndarray | Sequence[float] | None) – Optional per-temperature mask identifying points with low effective sample size.

  • diagnostics_note (str | None) – Optional text shown on diagnostics figure summarizing uncertainty quality metrics.

  • run_metadata_note (str | None) – Optional concise metadata line for the diagnostics header (for example lattice size, seeds, confidence level, method).

  • quality_summary (Mapping[str, int | float] | None) – Optional dictionary containing quality counts. Expected keys are total_points, well_conditioned_count, low_effective_count, unstable_interval_count, and undefined_count.

  • transition_temperatures (dict[str, float] | None) – Optional mapping of transition-marker labels to temperatures rendered as vertical dashed guide lines.

  • transition_window (tuple[float, float] | None) – Optional (low, high) temperature window highlighted with a light background band.

  • entropy_reference (tuple[str, float] | None) – Optional (label, value) rendered as a horizontal reference on the entropy diagnostics panel.

  • annotate_peaks (bool) – If True, annotate peak temperatures for susceptibility, specific heat, and tau_int when present.

  • min_visible_rel_error (float) – Minimum relative error bar size used for visibility when finite uncertainties are extremely small.

  • mark_invalid_uncertainty (bool) – If True, points with non-finite uncertainty are marked with x markers and a legend label.

utils.plotting.save_plot(*, filename: str, directory: str = 'results', tight_layout: bool = True, fig: Figure | None = None, close: bool = False) → None[source]

Save a matplotlib figure to the results directory.

Parameters:
  • filename (str) – Name of the output file (e.g., ‘plot.png’).

  • directory (str) – Output directory name.

  • tight_layout (bool) – Whether to apply tight_layout() before saving.

  • fig (plt.Figure | None) – Figure to save. Defaults to the current figure; passing it explicitly removes the dependence on pyplot’s global state and is required for correctness when several figures are open.

  • close (bool) – Whether to close the figure after saving. Long-running sweeps otherwise accumulate open figures in pyplot’s global registry.

utils.statistics module

Statistical estimators and uncertainty schemas for Monte Carlo time series: blocking analysis, autocorrelation, replicate and seed-ensemble aggregation.

utils.statistics.blocking_error(*, time_series: ndarray, min_block_size: int = 2, max_block_size: int | None = None) → dict[str, float][source]

Estimate standard error using standard blocking/binning analysis.

Any series containing NaN values (e.g. from failed measurements) yields the all-NaN result dict: a partially NaN series would otherwise poison the block means and produce a meaningless plateau selection.

Parameters:
  • time_series (np.ndarray) – 1-D time series of at least 2 samples.

  • min_block_size (int) – Smallest block size to test (>= 2).

  • max_block_size (int | None) – Largest block size to test; defaults to half the series length.

Returns:

Dict with keys stderr (plateau-selected standard error), stderr_naive, block_size, n_blocks, and tau_int_from_blocking.

Return type:

dict[str, float]

utils.statistics.calculate_autocorr(*, time_series: ndarray, max_lag: int | None = None, window_constant: float = 6.0) → tuple[ndarray, float][source]

Compute the normalized autocorrelation function and integrated autocorrelation time.

Uses an FFT-based estimator for C(t): zero-pads to 2N, computes the power spectrum, IFFTs, and normalizes by variance and the number of pairs at each lag. Applies the Madras-Sokal automatic windowing rule to stop integration at the lag W where W = window_constant * tau_int, preventing the estimator from accumulating noise at large lags.

Parameters:
  • time_series (np.ndarray) – 1-D array of sequential measurements (e.g. magnetization).

  • max_lag (int | None) – Maximum lag to compute. Defaults to len(time_series) // 2.

  • window_constant (float) – Multiplier for the Madras-Sokal window (default 6.0).

Returns:

A tuple (C_t, tau_int) where C_t is the normalized autocorrelation array truncated at the window endpoint, and tau_int is the integrated autocorrelation time (scalar).

Return type:

tuple[np.ndarray, float]

Raises:
utils.statistics.estimate_effective_sample_size(*, time_series: ndarray, tau_int: float | None = None) → float[source]

Estimate effective sample size from integrated autocorrelation time.

Parameters:
  • time_series (np.ndarray) – 1-D time series of at least 2 samples.

  • tau_int (float | None) – Optional precomputed integrated autocorrelation time; when omitted it is estimated from the series. Must be positive when provided.

Returns:

N_eff = N / (2 tau_int), clipped to [1, N]; NaN when tau_int is undefined, non-finite, or non-positive.

Return type:

float

utils.statistics.estimate_tau_int_or_nan(*, time_series: ndarray) → float[source]

Return the integrated autocorrelation time, or NaN when undefined.

Wraps calculate_autocorr with the standard zero-variance fallback so callers can precompute tau_int once and share it between the primary and derived summarizers instead of recomputing the FFT per summarizer.

utils.statistics.power_fit(*, t_arr: ndarray, y_arr: ndarray, mask: ndarray) → tuple[float, float] | tuple[None, None][source]

Fit a power law y = prefactor * t^exponent via log-log linear regression.

Parameters:
  • t_arr (np.ndarray) – Independent variable array (e.g., time or length scale); only positive values are used in the fit.

  • y_arr (np.ndarray) – Dependent variable array; only positive values are used in the fit.

  • mask (np.ndarray) – Boolean mask selecting the subset of points to include.

Returns:

  • exponent – Fitted power-law exponent, or None if fewer than 3 valid points.

  • prefactor – Fitted prefactor, or None if fewer than 3 valid points.

utils.statistics.summarize_asymmetric_replicate_uncertainty(*, samples: ndarray, confidence: float = 0.68) → dict[str, float][source]

Summarize 1-D replicate samples with asymmetric percentile intervals.

Parameters:
  • samples (np.ndarray) – 1-D replicate values; NaN entries are ignored.

  • confidence (float) – Two-sided confidence level for the percentile band.

Returns:

Dict with value (median), asymmetric ci_low/ci_high, the symmetric err (half band width) plus err_low/err_high offsets, samples, and nan_or_undefined_count.

Return type:

dict[str, float]

utils.statistics.summarize_derived_observable(*, magnetization_series: ndarray | None = None, energy_series: ndarray | None = None, temperature: float, L: int, observable: str, method: str = 'blocking', confidence: float = 0.68, bootstrap_resamples: int = 0, rng_seed: int = 0, blocking: dict[str, float] | None = None, tau_int: float | None = None) → dict[str, float][source]

Summarize derived observables (chi, Cv) with uncertainty estimates.

rng_seed seeds the block-bootstrap resampling (default 0, matching the previously hardcoded stream). blocking and tau_int accept precomputed results for the base series, as in summarize_primary_observable.

Parameters:
  • magnetization_series (np.ndarray | None) – Base series for observable='chi'.

  • energy_series (np.ndarray | None) – Base series for observable='cv'.

  • temperature (float) – Measurement temperature (> 0).

  • L (int) – Linear lattice size.

  • observable (str) – 'chi' or 'cv'.

  • method (str) – 'blocking' (default) or 'bootstrap'.

  • confidence (float) – Two-sided confidence level for the CI bounds.

  • bootstrap_resamples (int) – Resample count; required > 0 for bootstrap.

  • rng_seed (int) – Seed for the block-bootstrap RNG.

  • blocking (dict[str, float] | None) – Optional precomputed blocking_error result dict.

  • tau_int (float | None) – Optional precomputed integrated autocorrelation time.

Returns:

Dict with the standard uncertainty-schema fields value, err, ci_low, ci_high, tau_int, n_eff, and samples.

Return type:

dict[str, float]

utils.statistics.summarize_entropy_observable(*, temperatures: ndarray, specific_heat_samples: ndarray, confidence: float = 0.68, s_ref: float = 0.0, specific_heat_err: ndarray | None = None, method: str = 'bootstrap', bootstrap_resamples: int = 400, rng_seed: int = 0) → dict[str, ndarray][source]

Summarize entropy from replicate specific-heat curves.

Each replicate column is converted to an entropy curve via calculate_entropy(), then uncertainty is computed either via replicate spread (blocking-like) or bootstrap over replicate curves. For a single finite replicate, uncertainty is reported as NaN unless specific_heat_err is provided, in which case entropy uncertainty is propagated from pointwise specific-heat errors.

utils.statistics.summarize_primary_observable(*, time_series: ndarray, confidence: float = 0.68, blocking: dict[str, float] | None = None, tau_int: float | None = None) → dict[str, float][source]

Summarize a primary observable with blocking-based uncertainty.

blocking and tau_int accept precomputed results from blocking_error and estimate_tau_int_or_nan on the same series, so a caller that also summarizes a derived observable of that series does not pay for the blocking scan and autocorrelation FFT twice. When omitted they are computed here. A passed tau_int may be NaN (undefined).

Parameters:
  • time_series (np.ndarray) – 1-D time series of at least 2 samples.

  • confidence (float) – Two-sided confidence level for the CI bounds.

  • blocking (dict[str, float] | None) – Optional precomputed blocking_error result dict.

  • tau_int (float | None) – Optional precomputed integrated autocorrelation time.

Returns:

Dict with the standard uncertainty-schema fields value, err, ci_low, ci_high, tau_int, n_eff, and samples.

Return type:

dict[str, float]

utils.statistics.summarize_replicate_samples(*, samples: ndarray, confidence: float = 0.68) → dict[str, ndarray | float][source]

Summarize replicate samples using NaN-safe median and percentile bands.

Parameters:
  • samples (np.ndarray) – Replicate values, either 1-D (one grid point) or 2-D with shape (n_points, n_replicates).

  • confidence (float) – Two-sided confidence level; the band spans the alpha and 1 - alpha quantiles with alpha = (1 - confidence) / 2.

Returns:

Dict with value (median), err (half the band width), ci_low, ci_high, samples (replicate count), and nan_or_undefined_count.

Return type:

dict[str, np.ndarray | float]

utils.statistics.summarize_seed_ensemble(*, values: ndarray, within_seed_errors: ndarray, confidence: float = 0.68) → dict[str, float][source]

Aggregate per-seed estimates into one mean with its standard error.

With two or more finite seeds the error is the standard error of the seed mean, sqrt(Var_between / n_seeds), with a Student-t interval on n_seeds - 1 degrees of freedom. The spread of independent seed estimates already contains each seed’s own statistical noise, so adding the within-seed variance again would count it twice (for independent seeds the reported error was too large by a factor near sqrt(2)). With a single seed the within-seed error is the only information and is used directly. Both components are still reported for diagnostics.

Parameters:
  • values (np.ndarray) – Per-seed point estimates.

  • within_seed_errors (np.ndarray) – Per-seed standard errors from blocking.

  • confidence (float) – Two-sided confidence level for the CI bounds.

Returns:

value, err, ci_low, ci_high, between_seed_component, within_seed_component, samples, and nan_or_undefined_count.

Return type:

dict[str, float]

utils.sweep_helpers module

Shared infrastructure for per-temperature Monte Carlo sweep workers.

This module provides the two-layer decomposition used by all three model temperature sweeps (Ising, XY, Clock).

simulate_at_temperature owns equilibration and raw measurement. compute_thermo_observables owns statistical summarization. simulate_thermo_point chains both layers and is the worker function passed to parallel_sweep.

Post-processing helpers build_uncertainty_bundle and build_quality_flags aggregate per-seed results over a full temperature axis and are also shared here, eliminating identical copies that previously lived in each sweep script.

class utils.sweep_helpers.RawThermoData(temperature_index: int, seed_index: int, equilibrated_flag: float, equilibration_steps: float, temperature: float, size: int, mags_arr: np.ndarray | None, engs_arr: np.ndarray | None)[source]

Bases: NamedTuple

Raw simulation output from one (temperature, seed) equilibration + measurement.

Parameters:
  • temperature_index (int) – Index of this temperature in the sweep’s temperature array.

  • seed_index (int) – Replica index within the multi-seed ensemble for this temperature.

  • equilibrated_flag (float) – 1.0 if equilibration converged, 0.0 otherwise.

  • equilibration_steps (float) – Total equilibration steps taken (for diagnostics).

  • temperature (float) – Temperature at which the simulation was run.

  • size (int) – Linear lattice dimension L.

  • mags_arr (np.ndarray or None) – Magnetisation time series of length meas_steps. None when equilibration did not converge.

  • engs_arr (np.ndarray or None) – Energy per site time series of length meas_steps. None when equilibration did not converge.

engs_arr: ndarray | None

Alias for field number 7

equilibrated_flag: float

Alias for field number 2

equilibration_steps: float

Alias for field number 3

mags_arr: ndarray | None

Alias for field number 6

seed_index: int

Alias for field number 1

size: int

Alias for field number 5

temperature: float

Alias for field number 4

temperature_index: int

Alias for field number 0

utils.sweep_helpers.SEED_POINT_STRIDE = 4000000

Size of the seed block one grid point owns.

utils.sweep_helpers.SEED_REPLICAS_PER_STREAM = 1000

Replicas a single stream can hold. The sweeps allow ten attempts per requested replica, so this covers --n-seeds 100.

utils.sweep_helpers.SEED_REPLICA_STRIDE = 1000

Spacing between the base seeds of two replicas at the same grid point and stream. Callers derive short sub-streams by small addition, such as the seed + 1 and seed + 2 runs of the efficiency worker, so a replica needs room around its base rather than the next integer.

utils.sweep_helpers.SEED_STREAMS_PER_POINT = 4

Independent algorithm streams a grid point can hold, such as the separate Metropolis and Wolff streams that measure_z runs at the same point.

utils.sweep_helpers.SEED_STREAM_STRIDE = 1000000

Size of the seed block one stream owns within a grid point.

utils.sweep_helpers.SUMMARY_FIELDS: tuple[str, ...] = ('value', 'err', 'ci_low', 'ci_high', 'tau_int', 'n_eff', 'samples')

Fields of a summarize_primary_observable result, as read by build_single_run_schema. A worker that skips an unequilibrated point returns dict.fromkeys(SUMMARY_FIELDS, nan).

class utils.sweep_helpers.ThermoPoint(temperature: float, size: int, meas_steps: int, eq_probe_steps: int, eq_max_steps: int, eq_qs_sigma_threshold: float, eq_qs_min_steps: int, qs_allow_stuck: bool, prefer_ordered_start: bool, temperature_index: int, seed_index: int, seed: int, model_cls: type, model_kwargs: dict[str, Any], confidence: float, derived_method: str, bootstrap_resamples: int)[source]

Bases: NamedTuple

Typed worker payload for one (temperature, seed) point in a sweep.

Parameters:
  • temperature (float) – Simulation temperature T.

  • size (int) – Linear lattice dimension L.

  • meas_steps (int) – Number of Monte Carlo sweeps to record after equilibration.

  • eq_probe_steps (int) – Chunk size passed to convergence_equilibrate_two_start.

  • eq_max_steps (int) – Hard cap on total equilibration steps.

  • eq_qs_sigma_threshold (float) – Tail-std threshold for quasi-steady stuck-state detection.

  • eq_qs_min_steps (int) – Minimum steps before stuck detection is allowed to fire.

  • qs_allow_stuck (bool) – If True, stuck detection is active and a quasi-steady stuck state counts as convergence, measured on the ordered start (Ising and the discrete clock model at low T). If False, stuck detection is off and the pair runs until it converges or reaches eq_max_steps.

  • prefer_ordered_start (bool) – Retained for payload compatibility; it no longer changes the result. The ordered start is measured whenever the random start was stranded in an accepted stuck state, and the former magnetisation-gap heuristic this flag controlled is removed.

  • temperature_index (int) – Index of this temperature in the sweep’s temperature array.

  • seed_index (int) – Replica index within the multi-seed ensemble for this temperature.

  • seed (int) – RNG seed of the random-start simulation; the ordered start uses ordered_start_seed(seed=seed) so the two runs are independent.

  • model_cls (type) – Simulation class to instantiate (e.g. IsingSimulation). Must be importable by its qualified name so it survives multiprocessing pickle.

  • model_kwargs (dict[str, Any]) – Extra keyword arguments forwarded to the model constructor beyond size, temp, init_state, and seed. Empty dict for Ising and XY; carries {'q': q, 'A': aniso} for Clock.

  • confidence (float) – Two-sided confidence level for uncertainty intervals (0 < c < 1).

  • derived_method (str) – Uncertainty method for susceptibility and specific heat ('blocking' or 'bootstrap').

  • bootstrap_resamples (int) – Bootstrap resamples used when derived_method='bootstrap'.

bootstrap_resamples: int

Alias for field number 16

confidence: float

Alias for field number 14

derived_method: str

Alias for field number 15

eq_max_steps: int

Alias for field number 4

eq_probe_steps: int

Alias for field number 3

eq_qs_min_steps: int

Alias for field number 6

eq_qs_sigma_threshold: float

Alias for field number 5

meas_steps: int

Alias for field number 2

model_cls: type

Alias for field number 12

model_kwargs: dict[str, Any]

Alias for field number 13

prefer_ordered_start: bool

Alias for field number 8

qs_allow_stuck: bool

Alias for field number 7

seed: int

Alias for field number 11

seed_index: int

Alias for field number 10

size: int

Alias for field number 1

temperature: float

Alias for field number 0

temperature_index: int

Alias for field number 9

utils.sweep_helpers.build_quality_flags(*, tau_int: ndarray, ci_low: ndarray, ci_high: ndarray, n_eff: ndarray, min_effective_samples: float, max_tau_relative_width: float) → dict[str, ndarray][source]

Build per-temperature diagnostic flags for uncertainty quality.

Parameters:
  • tau_int (np.ndarray) – Shape (n_temps,). Integrated autocorrelation time estimates.

  • ci_low (np.ndarray) – Shape (n_temps,). Lower CI bound on tau_int.

  • ci_high (np.ndarray) – Shape (n_temps,). Upper CI bound on tau_int.

  • n_eff (np.ndarray) – Shape (n_temps,). Effective sample size estimates.

  • min_effective_samples (float) – Threshold below which a point is flagged as low-N_eff.

  • max_tau_relative_width (float) – CI-width-to-tau ratio above which the tau estimate is considered unstable.

Returns:

Keys: 'undefined_autocorr_flag', 'low_effective_sample_flag', 'tau_interval_unstable_flag'. All uint8 arrays of length n_temps.

Return type:

dict[str, np.ndarray]

utils.sweep_helpers.build_single_run_schema(*, prefix: str, summaries: list[dict[str, float]], uncertainty_method: str, confidence: float) → dict[str, Any][source]

Assemble the standard NPZ uncertainty schema for single-run sweeps.

Scripts that run one simulation per grid point and summarize each with summarize_primary_observable (or an equivalent dict) use this to write the per-observable fields and metadata required by AGENTS.md section 8 without re-implementing the layout.

Parameters:
  • prefix (str) – Observable name used as the key prefix, e.g. 'helicity_modulus'.

  • summaries (list[dict[str, float]]) – One summary per grid point with value, err, ci_low, ci_high, tau_int, and n_eff.

  • uncertainty_method (str) – Label stored as uncertainty_method.

  • confidence (float) – Confidence level the intervals were built for.

Returns:

<prefix>_value, _err, _ci_low, _ci_high, _tau_int, _n_eff (shape (n_points,)), <prefix>_samples (shape (n_points, 1), the single run’s point estimate), and the metadata uncertainty_method, confidence_level, n_seeds, bootstrap_resamples, and nan_or_undefined_count.

Return type:

dict[str, Any]

utils.sweep_helpers.build_uncertainty_bundle(*, values_by_seed: ndarray, errors_by_seed: ndarray, tau_by_seed: ndarray, n_eff_by_seed: ndarray, confidence: float, ci_low_by_seed: ndarray | None = None, ci_high_by_seed: ndarray | None = None) → dict[str, ndarray][source]

Aggregate per-seed results for one observable across a temperature axis.

For multi-seed sweeps, applies hierarchical seed-ensemble aggregation via summarize_seed_ensemble. Falls back to direct single-seed blocking results when only one seed is available.

Parameters:
  • values_by_seed (np.ndarray) – Shape (n_temps, n_seeds). Per-seed point estimates.

  • errors_by_seed (np.ndarray) – Shape (n_temps, n_seeds). Per-seed within-seed uncertainties.

  • tau_by_seed (np.ndarray) – Shape (n_temps, n_seeds). Per-seed integrated autocorrelation times.

  • n_eff_by_seed (np.ndarray) – Shape (n_temps, n_seeds). Per-seed effective sample sizes.

  • confidence (float) – Two-sided confidence level for the returned CI bounds.

  • ci_low_by_seed (np.ndarray or None) – Shape (n_temps, n_seeds). Per-seed interval bounds from the summarizers. Used for single-seed sweeps and for temperatures where only one seed has a finite value, whose intervals then keep the Student-t width of the blocking estimate; without them the bounds are a Gaussian multiple of the error.

  • ci_high_by_seed (np.ndarray or None) – Shape (n_temps, n_seeds). Per-seed interval bounds from the summarizers. Used for single-seed sweeps and for temperatures where only one seed has a finite value, whose intervals then keep the Student-t width of the blocking estimate; without them the bounds are a Gaussian multiple of the error.

Returns:

Keys: 'value', 'err', 'ci_low', 'ci_high', 'tau_int', 'n_eff', 'samples'. All arrays have length n_temps except 'samples' which has shape (n_temps, n_seeds).

Return type:

dict[str, np.ndarray]

utils.sweep_helpers.compute_thermo_observables(raw: RawThermoData, point: ThermoPoint) → dict[str, float][source]

Compute blocked/summarized thermodynamic observables from raw time series.

Takes the raw output of simulate_at_temperature and applies autocorrelation-aware blocking (primary observables) and variance-based summarization (derived observables) to produce the standard per-point result dictionary.

Parameters:
  • raw (RawThermoData) – Raw time series from simulate_at_temperature.

  • point (ThermoPoint) – Originating worker payload; provides temperature, size, and statistical configuration (confidence, derived_method, bootstrap_resamples).

Returns:

Keys: temperature_index, seed_index, equilibrated_flag, equilibration_steps, and — when equilibrated — avg_m_*, avg_e_*, susc_*, spec_h_* with suffixes _value, _err, _tau_int, _n_eff.

Return type:

dict[str, float]

utils.sweep_helpers.derive_point_seed(*, temperature_index: int, seed_index: int, stream_index: int = 0) → int[source]

Derive a deterministic RNG seed for one sweep grid point.

The three indices address three nested blocks: a grid point owns SEED_POINT_STRIDE seeds, a stream within it owns SEED_STREAM_STRIDE, and a replica within that owns SEED_REPLICA_STRIDE, leaving room for the sub-streams callers derive by small addition. Because each index scales its own block rather than being added into a shared range, two different index triples cannot produce the same seed, and an index that would leave its block is rejected rather than silently reusing a neighbour’s seeds.

Parameters:
  • temperature_index (int) – Index of the outer sweep axis (temperature or lattice-size grid).

  • seed_index (int) – Replica index within the seed ensemble for this grid point.

  • stream_index (int) – Index of the independent seed stream at this grid point, used where one point runs more than one algorithm; measure_z gives its Wolff runs a different stream from its Metropolis runs (default 0).

Returns:

The seed addressed by the three indices.

Return type:

int

Raises:

ValueError – If any index is negative or outside the capacity of its block, or if the resulting seed exceeds the 32-bit range the generators accept.

utils.sweep_helpers.simulate_at_temperature(point: ThermoPoint) → RawThermoData[source]

Run equilibration and measurement for one (temperature, seed) point.

Creates a random-start and an ordered-start simulation with independent seeds, runs two-start convergence equilibration, then records meas_steps sweeps on the start that is valid: the random start after genuine convergence, the ordered start after an accepted stuck state. Returns raw magnetisation and energy time series for downstream statistical processing.

Parameters:

point (ThermoPoint) – Fully configured worker payload.

Returns:

Raw time series; mags_arr and engs_arr are None when equilibration did not converge.

Return type:

RawThermoData

utils.sweep_helpers.simulate_thermo_point(point: ThermoPoint) → dict[str, float][source]

Run a full (equilibration + measurement + summarization) point.

Thin wrapper over simulate_at_temperature followed by compute_thermo_observables. This is the function passed as worker_func to parallel_sweep in temperature-sweep scripts.

Parameters:

point (ThermoPoint) – Fully configured worker payload.

Returns:

Standard per-point result dictionary; see compute_thermo_observables for the full key set.

Return type:

dict[str, float]

utils.sweep_helpers.validate_sweep_uncertainty_args(*, confidence_level: float, max_undefined_fraction: float, min_effective_samples: float, max_tau_relative_width: float, derived_uncertainty_method: str, derived_bootstrap_resamples: int, n_seeds: int) → None[source]

Validate the shared uncertainty-related CLI arguments of sweep scripts.

Centralized here so that the Ising, XY, and Clock temperature sweeps reject invalid inputs identically instead of failing deep inside worker statistics after simulations have already started.

Parameters:
  • confidence_level (float) – Two-sided confidence level; must satisfy 0 < c < 1.

  • max_undefined_fraction (float) – Strict-mode threshold; must satisfy 0 <= f <= 1.

  • min_effective_samples (float) – Quality-flag threshold; must be >= 0.

  • max_tau_relative_width (float) – Quality-flag threshold; must be >= 0.

  • derived_uncertainty_method (str) – Method name for derived observables; bootstrap requires resamples.

  • derived_bootstrap_resamples (int) – Bootstrap resample count; must be > 0 when the method is bootstrap.

  • n_seeds (int) – Target converged seed replicas; must be >= 1.

Raises:

ValueError – If any argument is outside its documented range.

utils.sweep_runner module

Shared command-line surface and orchestration for the temperature sweeps.

The Ising, XY, and Clock sweeps differ only in the model they instantiate, the lattice and temperature window they default to, the transition overlay they draw, and whether they prefer an ordered start below a known critical temperature. Everything between those choices, the argument surface, the seed-retry collection loop, the uncertainty bundles, the NPZ schema, and the figure, is identical and lives here, so that a change to the uncertainty schema reaches all three models at once instead of drifting between them.

utils.sweep_runner.add_temperature_sweep_arguments(*, parser: ArgumentParser, size: int, t_min: float, t_max: float, t_points: int, eq_max_steps: int, meas_steps: int, output_dir: str, transition_help: str) → None[source]

Add the argument surface shared by all three temperature sweeps.

Parameters:
  • parser (argparse.ArgumentParser) – Parser to extend. Model-specific arguments such as the clock state count are added by the caller, before or after this call.

  • size (int) – Default linear lattice size L for this model.

  • t_min (float) – Default lower end of the temperature window.

  • t_max (float) – Default upper end of the temperature window.

  • t_points (int) – Default number of temperature points.

  • eq_max_steps (int) – Default hard cap on equilibration steps. The vector models need a far higher cap than Ising because their relaxation is slower.

  • meas_steps (int) – Default number of measurement sweeps per point.

  • output_dir (str) – Default directory for the NPZ file and the figure.

  • transition_help (str) – Model-specific help text for --transition-preset, which names the overlay that auto draws.

Returns:

The parser is modified in place.

Return type:

None

utils.sweep_runner.run_temperature_sweep(*, args: Namespace, model_cls: type, model_kwargs: dict[str, Any], model_label: str, plot_title: str, metadata_note: str, transition_temperatures: dict[str, float] | None, variant_note: str = '', ordered_start_below: float | None = None) → None[source]

Execute a temperature sweep and write its NPZ file and figure.

Parameters:
  • args (argparse.Namespace) – Arguments parsed from a parser extended by add_temperature_sweep_arguments.

  • model_cls (type) – Simulation class to instantiate for every point. It must be importable under its qualified name so that it survives the multiprocessing pickle.

  • model_kwargs (dict[str, Any]) – Extra constructor arguments beyond size, temperature, start, and seed.

  • model_label (str) – Model name used in log messages, for example 'Ising'.

  • plot_title (str) – Title of the thermodynamics figure.

  • metadata_note (str) – Run provenance line printed under the figure.

  • transition_temperatures (dict[str, float] or None) – Vertical overlays to draw, already resolved against --transition-preset by the caller, since which overlay is meaningful depends on the model.

  • variant_note (str, optional) – Extra model configuration to mention in the opening log line, for example the clock variant and anisotropy.

  • ordered_start_below (float, optional) – Temperature under which a quasi-steady stuck state counts as converged and the ordered start may replace the random one. Set it to the critical temperature for models with true long-range order below it; leave it None where the low-temperature phase has none.

Returns:

Results are written to args.output_dir.

Return type:

None

Raises:

RuntimeError – If no temperature produced a converged replica, or if strict uncertainty mode is on and too many points have undefined autocorrelation.

utils.system module

Technical infrastructure for logging, parallel execution, and CLI argument parsing.

utils.system.parallel_sweep(*, worker_func: Callable[[Any], Any], params: Iterable[Any], num_processes: int | None = None) → list[Any][source]

Run a parallel sweep over a set of parameters using a worker function. Uses multiprocessing.Pool and tqdm for progress tracking.

Parameters:
  • worker_func (Callable[[Any], Any]) – Function to execute in parallel.

  • params (Iterable[Any]) – Iterable of parameters to pass to the worker function.

  • num_processes (int | None) – Number of processes to use. Defaults to CPU count.

Returns:

List of results from the worker function.

Return type:

list[Any]

utils.system.parse_args_compat(*, parser: ArgumentParser) → Namespace[source]

Parse CLI args with compatibility for parser wrappers used by some runners.

utils.system.setup_logging(*, level: int = 20, log_file: str | None = None) → Logger[source]

Configure project-wide logging.

Parameters:
  • level (int) – Logging level (e.g., logging.INFO).

  • log_file (str | None) – Optional path to a file to save logs to.

Returns:

The configured logger instance.

Return type:

logging.Logger

Module contents

Public API for VibeSpin utility and analysis functions.

The export list mirrors the utilities that scripts and notebooks actually consume, so it can serve as an accurate overview of the public surface. Submodule imports (utils.statistics, utils.observables, …) remain the canonical access path.

exception utils.NumericalAnalysisError[source]

Bases: VibeSpinError, RuntimeError

Base class for mathematically undefined or failed analysis results.

class utils.TwoStartOutcome(total_steps: int, converged: bool, stuck: bool)[source]

Bases: NamedTuple

Result of a two-start equilibration.

Parameters:
  • total_steps (int) – MC steps run by each of the two simulations.

  • converged (bool) – Whether the mutual cross-band criterion was met, i.e. both starts reached the same stationary state.

  • stuck (bool) – Whether the run stopped on a quasi-steady stuck state: the ordered start had settled while the random start stayed stranded on a metastable plateau. Only the ordered start is then a valid measurement source.

property certified: bool

Whether a measurement on this pair is valid.

True after convergence or after a stuck exit. A stuck exit can only occur where the caller enabled detect_stuck, which callers do only where a stuck state is accepted. A run that reached max_steps is not certified: neither start is known to have relaxed, and callers store NaN for the point instead of measuring it.

converged: bool

Alias for field number 1

stuck: bool

Alias for field number 2

total_steps: int

Alias for field number 0

exception utils.VibeSpinError[source]

Bases: Exception

Base class for project-specific exceptions.

exception utils.ZeroVarianceAutocorrelationError[source]

Bases: NumericalAnalysisError

Raised when autocorrelation is undefined because the series variance is zero.

utils.adaptive_equilibrate(sim: _Sim, *, min_steps: int, probe_steps: int = 500, factor: float = 50.0, max_steps: int = 200000) → int[source]

Equilibrate a simulation adaptively, extending the burn-in until the probe window covers factor integrated autocorrelation times.

After the mandatory min_steps burn-in, the function repeatedly runs a probe_steps measurement via sim.run() and computes tau_int from the resulting magnetization series. If probe_steps >= factor * tau_int, the probe spans enough correlation times for the initial state to be forgotten and equilibration is declared complete. Otherwise the probe has advanced the system state and the loop continues. In the ordered phase the magnetization series has zero variance; this is treated as full equilibration and the function returns immediately.

Parameters:
  • sim (_Sim) – Any simulation object implementing equilibrate and run.

  • min_steps (int) – Mandatory burn-in passed to sim.equilibrate before probing.

  • probe_steps (int) – MC steps per probe run (default 500).

  • factor (float) – Required ratio probe_steps / tau_int (default 50.0).

  • max_steps (int) – Hard cap on total steps to prevent unbounded runtime near criticality (default 200 000).

Returns:

Total number of MC steps run (burn-in + probes).

Return type:

int

Raises:

ValueError – If the adaptive-equilibration parameters are invalid.

utils.blocking_error(*, time_series: ndarray, min_block_size: int = 2, max_block_size: int | None = None) → dict[str, float][source]

Estimate standard error using standard blocking/binning analysis.

Any series containing NaN values (e.g. from failed measurements) yields the all-NaN result dict: a partially NaN series would otherwise poison the block means and produce a meaningless plateau selection.

Parameters:
  • time_series (np.ndarray) – 1-D time series of at least 2 samples.

  • min_block_size (int) – Smallest block size to test (>= 2).

  • max_block_size (int | None) – Largest block size to test; defaults to half the series length.

Returns:

Dict with keys stderr (plateau-selected standard error), stderr_naive, block_size, n_blocks, and tau_int_from_blocking.

Return type:

dict[str, float]

utils.calculate_autocorr(*, time_series: ndarray, max_lag: int | None = None, window_constant: float = 6.0) → tuple[ndarray, float][source]

Compute the normalized autocorrelation function and integrated autocorrelation time.

Uses an FFT-based estimator for C(t): zero-pads to 2N, computes the power spectrum, IFFTs, and normalizes by variance and the number of pairs at each lag. Applies the Madras-Sokal automatic windowing rule to stop integration at the lag W where W = window_constant * tau_int, preventing the estimator from accumulating noise at large lags.

Parameters:
  • time_series (np.ndarray) – 1-D array of sequential measurements (e.g. magnetization).

  • max_lag (int | None) – Maximum lag to compute. Defaults to len(time_series) // 2.

  • window_constant (float) – Multiplier for the Madras-Sokal window (default 6.0).

Returns:

A tuple (C_t, tau_int) where C_t is the normalized autocorrelation array truncated at the window endpoint, and tau_int is the integrated autocorrelation time (scalar).

Return type:

tuple[np.ndarray, float]

Raises:
utils.calculate_entropy(*, temperatures: ndarray, specific_heat: ndarray, s_ref: float = 0.0) → ndarray[source]

Compute entropy by integrating specific heat over a temperature sweep.

Integrates C(T)/T from high temperature downward so that S(T_max) = s_ref and S(T) = s_ref - integral from T to T_max of C/T dT’. This avoids the C/T divergence near T = 0 and anchors the result at the high-temperature limit where the entropy is analytically known.

Parameters:
  • temperatures (np.ndarray) – 1-D array of temperature values. Need not be sorted.

  • specific_heat (np.ndarray) – Specific heat C_v at each temperature (same length).

  • s_ref (float) – Reference entropy at the highest temperature. Pass 0.0 for relative entropy or np.log(q) (per site, in units of k_B) for absolute entropy of a q-state model.

Returns:

1-D array of entropy values, one per temperature, in the original unsorted order of temperatures.

Return type:

np.ndarray

Raises:

ValueError – If arrays differ in length, contain fewer than 2 points, or include non-positive temperatures.

utils.calculate_thermodynamics(*, mags: ndarray, engs: ndarray, T: float, L: int) → tuple[float, float, float, float][source]

Calculate average magnetization, energy, susceptibility, and specific heat.

Parameters:
  • mags (np.ndarray) – Array of magnetization measurements.

  • engs (np.ndarray) – Array of energy measurements.

  • T (float) – Temperature.

  • L (int) – Linear lattice size.

Returns:

A tuple of (avg_mag, avg_eng, susceptibility, specific_heat).

Return type:

tuple[float, float, float, float]

Raises:

ValueError – If T is not positive or L is not a positive integer.

utils.connected_correlation_length(*, sim: _Sim, meas_steps: int, sample_interval: int) → float[source]

Measure the equilibrium correlation length from the connected correlation.

The simulation is advanced meas_steps sweeps, and every sample_interval sweeps the lattice-axis pair correlation of the spin field is accumulated after subtracting the configuration’s mean spin. The 1/e crossing of the averaged, normalised function is returned. Subtracting the mean matters below the ordering temperature: the disconnected function plateaus at m^2 and never falls below 1/e, so a 1/e criterion applied to it returns the largest distance available instead of a correlation length.

Parameters:
  • sim (_Sim) – Equilibrated simulation; it is advanced in place.

  • meas_steps (int) – Number of sweeps to run.

  • sample_interval (int) – Sweeps between two samples.

Returns:

Connected correlation length in lattice units, or NaN if the averaged function never drops below 1/e within half the lattice.

Return type:

float

Raises:

ValueError – If no sample falls inside meas_steps.

utils.convergence_equilibrate(*, sim_random: _Sim, sim_ordered: _Sim, chunk_size: int = 500, max_steps: int = 200000, qs_sigma_threshold: float = 0.05, qs_min_steps: int = 1500, **kwargs: Any) → int[source]

Equilibrate two simulations (random- and ordered-start) until they converge.

Uses estimate_relaxation_time_two_start to detect convergence via the mutual cross-band criterion: each smoothed trajectory must enter and sustain a band defined by the other trajectory’s tail statistics. A sigma floor prevents false positives when one trace is nearly flat. This is more robust than one-start adaptive methods for complex energy landscapes.

Parameters:
  • sim_random (_Sim) – Simulation instance started from a random state.

  • sim_ordered (_Sim) – Simulation instance started from an ordered state.

  • chunk_size (int) – Number of steps to run between convergence checks.

  • max_steps (int) – Hard cap on total steps.

  • qs_sigma_threshold (float) – Tail-std threshold used to detect a quasi-steady, non-converged stuck state and exit early.

  • qs_min_steps (int) – Minimum accumulated steps before stuck detection is allowed to fire. Ensures tail statistics are computed from enough data to be reliable, preventing false positives when traces have not yet had time to settle.

  • **kwargs (Any) – Passed to estimate_relaxation_time_two_start (k, smooth_window, dwell_window, min_fraction_inside, sigma_floor, etc.).

Returns:

Total number of MC steps run per simulation.

Return type:

int

utils.convergence_equilibrate_two_start(*, sim_random: _Sim, sim_ordered: _Sim, chunk_size: int = 500, max_steps: int = 200000, qs_sigma_threshold: float = 0.05, qs_min_steps: int = 1500, detect_stuck: bool = False, **kwargs: Any) → TwoStartOutcome[source]

Equilibrate a random-start and an ordered-start simulation side by side.

The two runs advance in chunks until their smoothed magnetization traces pass the mutual cross-band criterion of estimate_relaxation_time_two_start, until the quasi-steady stuck detector fires, or until max_steps is reached. Unlike convergence_equilibrate_with_status the result keeps a stuck exit apart from genuine convergence, so callers can measure on the start that is actually valid (see select_measurement_simulation).

Parameters:
  • sim_random (_Sim) – Simulation instance started from a random state.

  • sim_ordered (_Sim) – Simulation instance started from an ordered state. It should carry a different seed from sim_random (see ordered_start_seed).

  • chunk_size (int) – Number of steps to run between convergence checks.

  • max_steps (int) – Hard cap on total steps.

  • qs_sigma_threshold (float) – Tail-std threshold used to detect a quasi-steady stuck state.

  • qs_min_steps (int) – Minimum accumulated steps before stuck detection may fire.

  • detect_stuck (bool) – Whether a quasi-steady stuck state ends the run early (default False). The detector cannot tell a stranded random start from one that is still relaxing slowly, which is common near a transition and for the XY model below T_BKT, so it is opt-in: enable it only in the ordered phase of a model with metastable domain states, where measuring the ordered start after a stuck exit is valid.

  • **kwargs (Any) – Passed to estimate_relaxation_time_two_start (k, smooth_window, dwell_window, min_fraction_inside, sigma_floor, etc.).

Returns:

Steps run, convergence flag, and stuck flag. At most one flag is set.

Return type:

TwoStartOutcome

utils.convergence_equilibrate_with_status(*, sim_random: _Sim, sim_ordered: _Sim, chunk_size: int = 500, max_steps: int = 200000, qs_sigma_threshold: float = 0.05, qs_min_steps: int = 1500, qs_allow_stuck: bool = False, **kwargs: Any) → tuple[int, bool][source]

Equilibrate two simulations and report whether convergence was reached.

Uses estimate_relaxation_time_two_start to detect convergence via the mutual cross-band criterion: each smoothed trajectory must enter and sustain a band defined by the other trajectory’s tail statistics. A sigma floor prevents false positives when one trace is nearly flat. This variant returns both the total number of MC steps executed and a boolean convergence flag.

The boolean cannot tell an accepted stuck state from genuine convergence; after an accepted stuck state only the ordered start is a valid measurement source. Callers that measure should use convergence_equilibrate_two_start with select_measurement_simulation instead.

Parameters:
  • sim_random (_Sim) – Simulation instance started from a random state.

  • sim_ordered (_Sim) – Simulation instance started from an ordered state.

  • chunk_size (int) – Number of steps to run between convergence checks.

  • max_steps (int) – Hard cap on total steps.

  • qs_sigma_threshold (float) – Tail-std threshold used to detect a quasi-steady, non-converged stuck state and exit early.

  • qs_min_steps (int) – Minimum accumulated steps before stuck detection is allowed to fire. Ensures tail statistics are computed from enough data to be reliable, preventing false positives when traces have not yet had time to settle.

  • qs_allow_stuck (bool) – If True, detecting a quasi-steady stuck state (where the ordered trace is stable but the random trace is stranded) is treated as a successful equilibration. Useful for Ising sweeps where random-start domain-wall trapping is physically expected.

  • **kwargs (Any) – Passed to estimate_relaxation_time_two_start (k, smooth_window, dwell_window, min_fraction_inside, sigma_floor, etc.).

Returns:

Tuple (total_steps, converged).

Return type:

tuple[int, bool]

utils.correlation_length_1e(*, r: ndarray, G: ndarray) → float[source]

Estimate the correlation length as the 1/e crossing of G(r).

Linearly interpolates between the last point above 1/e and the first point below it. Returns r[0] when the very first point is already below 1/e, and NaN when G never drops below 1/e within the given range (callers decide the appropriate fallback for their context).

Parameters:
  • r (np.ndarray) – Radial distances (monotonically increasing).

  • G (np.ndarray) – Correlation values G(r), normalised so G(0) = 1.

Returns:

The interpolated 1/e crossing radius, or NaN if no crossing exists.

Return type:

float

utils.derive_point_seed(*, temperature_index: int, seed_index: int, stream_index: int = 0) → int[source]

Derive a deterministic RNG seed for one sweep grid point.

The three indices address three nested blocks: a grid point owns SEED_POINT_STRIDE seeds, a stream within it owns SEED_STREAM_STRIDE, and a replica within that owns SEED_REPLICA_STRIDE, leaving room for the sub-streams callers derive by small addition. Because each index scales its own block rather than being added into a shared range, two different index triples cannot produce the same seed, and an index that would leave its block is rejected rather than silently reusing a neighbour’s seeds.

Parameters:
  • temperature_index (int) – Index of the outer sweep axis (temperature or lattice-size grid).

  • seed_index (int) – Replica index within the seed ensemble for this grid point.

  • stream_index (int) – Index of the independent seed stream at this grid point, used where one point runs more than one algorithm; measure_z gives its Wolff runs a different stream from its Metropolis runs (default 0).

Returns:

The seed addressed by the three indices.

Return type:

int

Raises:

ValueError – If any index is negative or outside the capacity of its block, or if the resulting seed exceeds the 32-bit range the generators accept.

utils.derived_thermo_estimate(*, series: ndarray, temperature: float, L: int, observable: str) → float[source]

Compute a fluctuation-based derived observable from a time series.

Single authoritative implementation of the fluctuation-dissipation formulas, shared by calculate_thermodynamics() and the uncertainty summarizers in utils.statistics.

Parameters:
  • series (np.ndarray) – 1-D time series (magnetization for 'chi', energy per site for 'cv').

  • temperature (float) – Temperature T of the measurement.

  • L (int) – Linear lattice size.

  • observable (str) – 'chi' (susceptibility, N Var(M)/T) or 'cv' (specific heat, N Var(E)/T^2).

Returns:

The derived observable value.

Return type:

float

Raises:

ValueError – If observable is not 'chi' or 'cv'.

utils.estimate_effective_sample_size(*, time_series: ndarray, tau_int: float | None = None) → float[source]

Estimate effective sample size from integrated autocorrelation time.

Parameters:
  • time_series (np.ndarray) – 1-D time series of at least 2 samples.

  • tau_int (float | None) – Optional precomputed integrated autocorrelation time; when omitted it is estimated from the series. Must be positive when provided.

Returns:

N_eff = N / (2 tau_int), clipped to [1, N]; NaN when tau_int is undefined, non-finite, or non-positive.

Return type:

float

utils.estimate_relaxation_time_two_start(*, trace_random: ndarray, trace_ordered: ndarray, k: float = 1.0, smooth_window: int = 60, dwell_window: int = 60, min_fraction_inside: float = 0.85, sigma_floor: float = 0.02, skip_validation: bool = False) → int[source]

Estimate thermalization time from convergence of random- and ordered-start traces.

Compares a trajectory started from a random spin configuration against one started from a fully ordered configuration. Returns the first step at which both smoothed traces pass a mutual cross-band test sustained over a dwell window.

The criterion is asymmetric in the correct physical sense: the smoothed random-start trace must lie within k standard deviations of the ordered-start tail mean, and the ordered-start trace must simultaneously lie within k standard deviations of the random-start tail mean. Tail statistics are computed from the second half of each smoothed trace independently. A sigma_floor prevents band collapse when one trace is nearly variance-free (e.g. in the deep ordered phase near T=0).

Parameters:
  • trace_random (np.ndarray) – 1-D magnetization trace from a random initial state.

  • trace_ordered (np.ndarray) – 1-D magnetization trace from an ordered initial state.

  • k (float) – Half-width of each convergence band in units of the respective tail standard deviation. Larger values are more permissive.

  • smooth_window (int) – Window length (steps) for the moving-average smoother.

  • dwell_window (int) – Window length (steps) for the sustained-convergence test.

  • min_fraction_inside (float) – Fraction of steps within dwell_window that must satisfy the mutual cross-band condition to declare convergence.

  • sigma_floor (float) – Minimum allowed standard deviation for each tail, preventing band collapse when a trajectory is nearly flat.

  • skip_validation (bool) – If True, skip np.asarray and finite-prefix checks.

Returns:

Estimated relaxation time as a 0-indexed position in the original input traces (i.e. a sweep count minus one). The first index at which both smoothed traces have been mutually inside each other’s band for dwell_window steps is mapped back to the corresponding raw-trace position as hits[0] + smooth_window - 1. Returns n (full trace length) if no convergence is detected, or 0 for very short traces.

Return type:

int

utils.estimate_tau_int_or_nan(*, time_series: ndarray) → float[source]

Return the integrated autocorrelation time, or NaN when undefined.

Wraps calculate_autocorr with the standard zero-variance fallback so callers can precompute tau_int once and share it between the primary and derived summarizers instead of recomputing the FFT per summarizer.

utils.get_averaged_correlation(*, sim: _Sim, total_steps: int, sample_interval: int) → tuple[ndarray, ndarray][source]

Run simulation and average the correlation function over multiple configurations.

Parameters:
  • sim (_Sim) – An instance of MonteCarloSimulation.

  • total_steps (int) – Total number of MC steps to run.

  • sample_interval (int) – Interval between correlation samples. Must be ≥ 1.

Returns:

  • r (np.ndarray) – Radial distances.

  • G_r_avg (np.ndarray) – Averaged correlation values.

Raises:

ValueError – If sample_interval is less than 1 or total_steps is negative.

utils.ordered_start_seed(*, seed: int | None) → int | None[source]

Return the seed for the ordered-start partner of a seeded random start.

Parameters:

seed (int or None) – Seed of the random-start simulation. None (unseeded) is passed through unchanged.

Returns:

seed + ORDERED_START_SEED_OFFSET, or None for an unseeded run.

Return type:

int or None

Raises:

ValueError – If the partner seed would leave the 32-bit generator range.

utils.pair_correlation_x(*, spins: ndarray) → tuple[ndarray, ndarray][source]

Compute the real-space spin-spin pair correlation G(r) along x.

Uses the Wiener-Khinchin theorem: the autocorrelation of each row is the inverse FFT of the row’s power spectrum. Results are averaged over all rows (y positions) and normalised so G(0) = 1.

Parameters:

spins (np.ndarray) – (N, N) or (N, N, 2) spin array.

Returns:

  • r_vals (np.ndarray) – Lag distances r = 0 … N//2 in lattice units.

  • G (np.ndarray) – Normalised pair correlation G(r) / G(0).

utils.parallel_sweep(*, worker_func: Callable[[Any], Any], params: Iterable[Any], num_processes: int | None = None) → list[Any][source]

Run a parallel sweep over a set of parameters using a worker function. Uses multiprocessing.Pool and tqdm for progress tracking.

Parameters:
  • worker_func (Callable[[Any], Any]) – Function to execute in parallel.

  • params (Iterable[Any]) – Iterable of parameters to pass to the worker function.

  • num_processes (int | None) – Number of processes to use. Defaults to CPU count.

Returns:

List of results from the worker function.

Return type:

list[Any]

utils.parse_args_compat(*, parser: ArgumentParser) → Namespace[source]

Parse CLI args with compatibility for parser wrappers used by some runners.

utils.power_fit(*, t_arr: ndarray, y_arr: ndarray, mask: ndarray) → tuple[float, float] | tuple[None, None][source]

Fit a power law y = prefactor * t^exponent via log-log linear regression.

Parameters:
  • t_arr (np.ndarray) – Independent variable array (e.g., time or length scale); only positive values are used in the fit.

  • y_arr (np.ndarray) – Dependent variable array; only positive values are used in the fit.

  • mask (np.ndarray) – Boolean mask selecting the subset of points to include.

Returns:

  • exponent – Fitted power-law exponent, or None if fewer than 3 valid points.

  • prefactor – Fitted prefactor, or None if fewer than 3 valid points.

utils.prepare_equilibrated_simulation(*, model_cls: type, model_kwargs: dict[str, Any], size: int, temp: float, seed: int | None, chunk_size: int, max_steps: int, update: str = 'checkerboard', **kwargs: Any) → tuple[Any, TwoStartOutcome][source]

Build a two-start pair, equilibrate it, and return the start to measure.

The random start receives seed and the ordered start ordered_start_seed(seed=seed), so the two runs draw independent random numbers. After equilibration the random start is returned when the pair converged, and the ordered start otherwise (see select_measurement_simulation). When the run hit max_steps, outcome.certified is False and the caller should record NaN for the point rather than measure the returned simulation.

Parameters:
  • model_cls (type) – Simulation class to instantiate.

  • model_kwargs (dict[str, Any]) – Constructor arguments beyond size, temperature, update, start, and seed.

  • size (int) – Linear lattice size L.

  • temp (float) – Simulation temperature T.

  • seed (int or None) – Seed of the random start; None leaves both starts unseeded.

  • chunk_size (int) – Steps between convergence checks.

  • max_steps (int) – Hard cap on equilibration steps.

  • update (str) – Update scheme for both starts (default 'checkerboard').

  • **kwargs (Any) – Passed to convergence_equilibrate_two_start, for example detect_stuck=True in the ordered phase of a model with metastable domain states.

Returns:

The simulation to measure and the equilibration outcome.

Return type:

tuple[Any, TwoStartOutcome]

utils.radial_average_sk(*, spins: ndarray) → tuple[ndarray, ndarray][source]

Compute the circularly averaged structure factor \(S(|k|)\).

Bins \(S(k)\) by integer pixel radius from the DC centre of the shifted FFT, then averages within each annular bin.

Parameters:

spins (np.ndarray) – (N, N) or (N, N, 2) spin array.

Returns:

  • k_vals (np.ndarray) – Wavevector magnitudes in units of 2π/N (reciprocal lattice).

  • S_radial (np.ndarray) – Mean S(k) value for each annular bin.

utils.select_measurement_simulation(*, outcome: TwoStartOutcome, sim_random: SimT, sim_ordered: SimT) → SimT[source]

Choose which start of an equilibrated pair to measure.

The random start is used only when the two starts converged to the same state. After a stuck exit the random start sits on a metastable plateau, so the ordered start is returned. After hitting the step cap the ordered start is returned as well, but neither start is certified (outcome.certified is False) and callers must not measure it.

Parameters:
  • outcome (TwoStartOutcome) – Result of convergence_equilibrate_two_start.

  • sim_random (simulation) – Random-start simulation.

  • sim_ordered (simulation) – Ordered-start simulation.

Returns:

sim_random if the pair converged, otherwise sim_ordered.

Return type:

simulation

utils.setup_logging(*, level: int = 20, log_file: str | None = None) → Logger[source]

Configure project-wide logging.

Parameters:
  • level (int) – Logging level (e.g., logging.INFO).

  • log_file (str | None) – Optional path to a file to save logs to.

Returns:

The configured logger instance.

Return type:

logging.Logger

utils.simulate_equilibrium_correlation(*, model_cls: type, model_kwargs: dict[str, Any], size: int, temp: float, seed: int, eq_probe: int, eq_max: int, meas_steps: int, interval: int, logger: Logger | None = None, detect_stuck: bool = False) → tuple[ndarray, ndarray][source]

Equilibrate a model and measure its averaged correlation function.

Runs two-start convergence equilibration (random start vs. ordered start, checkerboard updates) to avoid initialization bias, then averages the correlation function over meas_steps Monte Carlo steps, sampling every interval steps. When convergence is not reached within eq_max steps, the point is not measured and G(r) is returned as NaN.

Parameters:
  • model_cls (type) – Simulation class to instantiate (e.g. IsingSimulation).

  • model_kwargs (dict[str, Any]) – Extra keyword arguments forwarded to the model constructor beyond size, temp, update, init_state, and seed (e.g. {'q': 6} for the clock model).

  • size (int) – Linear lattice size L.

  • temp (float) – Temperature for the measurement.

  • seed (int) – Random seed of the random start; the ordered start uses ordered_start_seed(seed=seed).

  • eq_probe (int) – Chunk size for convergence equilibration probes.

  • eq_max (int) – Maximum equilibration steps.

  • meas_steps (int) – Measurement steps after equilibration.

  • interval (int) – Spacing between correlation samples during measurement.

  • logger (logging.Logger | None) – Optional logger for progress and fallback messages.

  • detect_stuck (bool) – Enable quasi-steady stuck detection, so that a random start stranded in a domain state ends the run and the ordered start is measured. Set it only in the ordered phase of a model with metastable domain states (default False).

Returns:

  • r (np.ndarray) – Radial distances.

  • G_r_avg (np.ndarray) – Averaged correlation values G(r), all NaN when the two starts did not converge within eq_max steps.

utils.summarize_asymmetric_replicate_uncertainty(*, samples: ndarray, confidence: float = 0.68) → dict[str, float][source]

Summarize 1-D replicate samples with asymmetric percentile intervals.

Parameters:
  • samples (np.ndarray) – 1-D replicate values; NaN entries are ignored.

  • confidence (float) – Two-sided confidence level for the percentile band.

Returns:

Dict with value (median), asymmetric ci_low/ci_high, the symmetric err (half band width) plus err_low/err_high offsets, samples, and nan_or_undefined_count.

Return type:

dict[str, float]

utils.summarize_derived_observable(*, magnetization_series: ndarray | None = None, energy_series: ndarray | None = None, temperature: float, L: int, observable: str, method: str = 'blocking', confidence: float = 0.68, bootstrap_resamples: int = 0, rng_seed: int = 0, blocking: dict[str, float] | None = None, tau_int: float | None = None) → dict[str, float][source]

Summarize derived observables (chi, Cv) with uncertainty estimates.

rng_seed seeds the block-bootstrap resampling (default 0, matching the previously hardcoded stream). blocking and tau_int accept precomputed results for the base series, as in summarize_primary_observable.

Parameters:
  • magnetization_series (np.ndarray | None) – Base series for observable='chi'.

  • energy_series (np.ndarray | None) – Base series for observable='cv'.

  • temperature (float) – Measurement temperature (> 0).

  • L (int) – Linear lattice size.

  • observable (str) – 'chi' or 'cv'.

  • method (str) – 'blocking' (default) or 'bootstrap'.

  • confidence (float) – Two-sided confidence level for the CI bounds.

  • bootstrap_resamples (int) – Resample count; required > 0 for bootstrap.

  • rng_seed (int) – Seed for the block-bootstrap RNG.

  • blocking (dict[str, float] | None) – Optional precomputed blocking_error result dict.

  • tau_int (float | None) – Optional precomputed integrated autocorrelation time.

Returns:

Dict with the standard uncertainty-schema fields value, err, ci_low, ci_high, tau_int, n_eff, and samples.

Return type:

dict[str, float]

utils.summarize_entropy_observable(*, temperatures: ndarray, specific_heat_samples: ndarray, confidence: float = 0.68, s_ref: float = 0.0, specific_heat_err: ndarray | None = None, method: str = 'bootstrap', bootstrap_resamples: int = 400, rng_seed: int = 0) → dict[str, ndarray][source]

Summarize entropy from replicate specific-heat curves.

Each replicate column is converted to an entropy curve via calculate_entropy(), then uncertainty is computed either via replicate spread (blocking-like) or bootstrap over replicate curves. For a single finite replicate, uncertainty is reported as NaN unless specific_heat_err is provided, in which case entropy uncertainty is propagated from pointwise specific-heat errors.

utils.summarize_primary_observable(*, time_series: ndarray, confidence: float = 0.68, blocking: dict[str, float] | None = None, tau_int: float | None = None) → dict[str, float][source]

Summarize a primary observable with blocking-based uncertainty.

blocking and tau_int accept precomputed results from blocking_error and estimate_tau_int_or_nan on the same series, so a caller that also summarizes a derived observable of that series does not pay for the blocking scan and autocorrelation FFT twice. When omitted they are computed here. A passed tau_int may be NaN (undefined).

Parameters:
  • time_series (np.ndarray) – 1-D time series of at least 2 samples.

  • confidence (float) – Two-sided confidence level for the CI bounds.

  • blocking (dict[str, float] | None) – Optional precomputed blocking_error result dict.

  • tau_int (float | None) – Optional precomputed integrated autocorrelation time.

Returns:

Dict with the standard uncertainty-schema fields value, err, ci_low, ci_high, tau_int, n_eff, and samples.

Return type:

dict[str, float]

utils.summarize_replicate_samples(*, samples: ndarray, confidence: float = 0.68) → dict[str, ndarray | float][source]

Summarize replicate samples using NaN-safe median and percentile bands.

Parameters:
  • samples (np.ndarray) – Replicate values, either 1-D (one grid point) or 2-D with shape (n_points, n_replicates).

  • confidence (float) – Two-sided confidence level; the band spans the alpha and 1 - alpha quantiles with alpha = (1 - confidence) / 2.

Returns:

Dict with value (median), err (half the band width), ci_low, ci_high, samples (replicate count), and nan_or_undefined_count.

Return type:

dict[str, np.ndarray | float]

utils.summarize_seed_ensemble(*, values: ndarray, within_seed_errors: ndarray, confidence: float = 0.68) → dict[str, float][source]

Aggregate per-seed estimates into one mean with its standard error.

With two or more finite seeds the error is the standard error of the seed mean, sqrt(Var_between / n_seeds), with a Student-t interval on n_seeds - 1 degrees of freedom. The spread of independent seed estimates already contains each seed’s own statistical noise, so adding the within-seed variance again would count it twice (for independent seeds the reported error was too large by a factor near sqrt(2)). With a single seed the within-seed error is the only information and is used directly. Both components are still reported for diagnostics.

Parameters:
  • values (np.ndarray) – Per-seed point estimates.

  • within_seed_errors (np.ndarray) – Per-seed standard errors from blocking.

  • confidence (float) – Two-sided confidence level for the CI bounds.

Returns:

value, err, ci_low, ci_high, between_seed_component, within_seed_component, samples, and nan_or_undefined_count.

Return type:

dict[str, float]

utils.validate_sweep_uncertainty_args(*, confidence_level: float, max_undefined_fraction: float, min_effective_samples: float, max_tau_relative_width: float, derived_uncertainty_method: str, derived_bootstrap_resamples: int, n_seeds: int) → None[source]

Validate the shared uncertainty-related CLI arguments of sweep scripts.

Centralized here so that the Ising, XY, and Clock temperature sweeps reject invalid inputs identically instead of failing deep inside worker statistics after simulations have already started.

Parameters:
  • confidence_level (float) – Two-sided confidence level; must satisfy 0 < c < 1.

  • max_undefined_fraction (float) – Strict-mode threshold; must satisfy 0 <= f <= 1.

  • min_effective_samples (float) – Quality-flag threshold; must be >= 0.

  • max_tau_relative_width (float) – Quality-flag threshold; must be >= 0.

  • derived_uncertainty_method (str) – Method name for derived observables; bootstrap requires resamples.

  • derived_bootstrap_resamples (int) – Bootstrap resample count; must be > 0 when the method is bootstrap.

  • n_seeds (int) – Target converged seed replicas; must be >= 1.

Raises:

ValueError – If any argument is outside its documented range.