Source code for utils.observables

"""
Physics-related utility functions for calculating thermodynamic observables and correlations.
"""
from __future__ import annotations

import logging
from typing import Any, NamedTuple, Protocol

import numpy as np
from scipy.integrate import cumulative_trapezoid

from utils.equilibration import (
    convergence_equilibrate_two_start,
    ordered_start_seed,
    select_measurement_simulation,
)


class _Sim(Protocol):
    """Structural type for any MonteCarloSimulation; avoids a models/ → utils/ import."""

    spins: np.ndarray | None

    def step(self) -> None: ...

    def calculate_correlation_function(self) -> tuple[np.ndarray, np.ndarray]: ...

    def get_spin_field(self) -> np.ndarray: ...


[docs] def derived_thermo_estimate( *, series: np.ndarray, temperature: float, L: int, observable: str ) -> float: """Compute a fluctuation-based derived observable from a time series. Single authoritative implementation of the fluctuation-dissipation formulas, shared by :func:`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 ------- float The derived observable value. Raises ------ ValueError If ``observable`` is not ``'chi'`` or ``'cv'``. """ N = float(L * L) variance = float(np.var(series)) if observable == 'chi': return float(N * variance / temperature) if observable == 'cv': return float(N * variance / (temperature**2)) raise ValueError(f"observable must be one of 'chi' or 'cv', got {observable!r}")
[docs] def calculate_thermodynamics( *, mags: np.ndarray, engs: np.ndarray, T: float, L: int ) -> tuple[float, float, float, float]: """ 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 ------- tuple[float, float, float, float] A tuple of (avg_mag, avg_eng, susceptibility, specific_heat). Raises ------ ValueError If ``T`` is not positive or ``L`` is not a positive integer. """ if T <= 0.0: raise ValueError(f'T must be positive (T > 0), got {T}') if not isinstance(L, (int, np.integer)) or L < 1: raise ValueError(f'L must be a positive integer, got {L!r}') avg_mag = float(np.mean(mags)) avg_eng = float(np.mean(engs)) susceptibility = derived_thermo_estimate(series=mags, temperature=T, L=L, observable='chi') specific_heat = derived_thermo_estimate(series=engs, temperature=T, L=L, observable='cv') return avg_mag, avg_eng, susceptibility, specific_heat
[docs] def calculate_entropy( *, temperatures: np.ndarray, specific_heat: np.ndarray, s_ref: float = 0.0, ) -> np.ndarray: """ 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 ------- np.ndarray 1-D array of entropy values, one per temperature, in the original unsorted order of ``temperatures``. Raises ------ ValueError If arrays differ in length, contain fewer than 2 points, or include non-positive temperatures. """ temperatures = np.asarray(temperatures, dtype=np.float64) specific_heat = np.asarray(specific_heat, dtype=np.float64) if temperatures.shape != specific_heat.shape: raise ValueError( f'temperatures and specific_heat must have the same shape, ' f'got {temperatures.shape} and {specific_heat.shape}' ) if temperatures.size < 2: raise ValueError('Need at least 2 temperature points for integration') if np.any(temperatures <= 0.0): raise ValueError('All temperatures must be positive') # Sort ascending; remember original order to restore later. sort_idx = np.argsort(temperatures) t_sorted = temperatures[sort_idx] cv_sorted = specific_heat[sort_idx] # Integrand: C(T) / T integrand = cv_sorted / t_sorted # Cumulative integral from T_1 (lowest) to each T_i. partial = cumulative_trapezoid(integrand, t_sorted) # Prepend 0 for the first (lowest-T) point. partial = np.concatenate(([0.0], partial)) # S(T) = s_ref - (total_integral - partial_integral_up_to_T) total = partial[-1] entropy_sorted = s_ref - (total - partial) # Restore original ordering. entropy: np.ndarray = np.empty_like(entropy_sorted) entropy[sort_idx] = entropy_sorted return entropy
[docs] def get_averaged_correlation( *, sim: _Sim, total_steps: int, sample_interval: int ) -> tuple[np.ndarray, np.ndarray]: """ 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. """ if sample_interval < 1: raise ValueError(f'sample_interval must be >= 1, got {sample_interval}') if total_steps < 0: raise ValueError(f'total_steps must be non-negative, got {total_steps}') G_r_avg: np.ndarray | None = None count = 0 r: np.ndarray = np.array([]) for i in range(total_steps): sim.step() if i % sample_interval == 0: r, G_r = sim.calculate_correlation_function() if G_r_avg is None: G_r_avg = np.zeros_like(G_r) G_r_avg += G_r count += 1 if G_r_avg is not None and count > 0: G_r_avg /= count else: # Fallback if no samples were taken r, G_r_dummy = sim.calculate_correlation_function() G_r_avg = np.zeros_like(G_r_dummy) return r, G_r_avg
[docs] def 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: logging.Logger | None = None, detect_stuck: bool = False, ) -> tuple[np.ndarray, np.ndarray]: """ 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. """ if logger is not None: logger.debug(f'Equilibrating at T={temp:.3f} (L={size}, seed={seed})...') sim_r = model_cls( size=size, temp=temp, update='checkerboard', init_state='random', seed=seed, **model_kwargs, ) sim_o = model_cls( size=size, temp=temp, update='checkerboard', init_state='ordered', seed=ordered_start_seed(seed=seed), **model_kwargs, ) outcome = convergence_equilibrate_two_start( sim_random=sim_r, sim_ordered=sim_o, chunk_size=eq_probe, max_steps=eq_max, detect_stuck=detect_stuck, ) if not outcome.certified: # Neither start is known to have relaxed, so G(r) is not measured. if logger is not None: logger.warning( f'T={temp:.3f}: no convergence in {eq_max} steps; storing NaN for G(r)' ) r, _ = sim_r.calculate_correlation_function() return r, np.full(r.shape, np.nan) sim_meas = select_measurement_simulation( outcome=outcome, sim_random=sim_r, sim_ordered=sim_o, ) if logger is not None: logger.debug(f'Measuring correlations at T={temp:.3f}...') return get_averaged_correlation( sim=sim_meas, total_steps=meas_steps, sample_interval=interval, )
[docs] class CorrelationPoint(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, typing.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). """ 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
[docs] def measure_correlation_point( point: CorrelationPoint, ) -> tuple[str, np.ndarray, np.ndarray]: """ 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 ------- tuple[str, numpy.ndarray, numpy.ndarray] 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``. """ logger = logging.getLogger('vibespin') r, G = simulate_equilibrium_correlation( model_cls=point.model_cls, model_kwargs=point.model_kwargs, size=point.size, temp=point.temperature, seed=point.seed, eq_probe=point.eq_probe, eq_max=point.eq_max, meas_steps=point.meas_steps, interval=point.interval, logger=logger, detect_stuck=point.detect_stuck, ) return point.label, r, G
def _fit_window( *, r: np.ndarray, G: np.ndarray, r_min: int, r_max: int | None, ) -> tuple[np.ndarray, np.ndarray]: """ Select the distances a decay fit may use. The upper end defaults to L/4. Beyond that the periodic images of a site are closer than the nominal distance suggests, so G(r) flattens for a reason that has nothing to do with the decay being fitted. Values at or below zero are dropped because both fits work in log space. Parameters ---------- r : numpy.ndarray Radial distances, running out to L/2. G : numpy.ndarray Correlation values at those distances. r_min : int Smallest distance to fit, excluding the lattice-scale points where the asymptotic form does not hold yet. r_max : int or None Largest distance to fit, or None for L/4. Returns ------- tuple[numpy.ndarray, numpy.ndarray] The distances and correlation values inside the window. """ if len(r) == 0: return np.array([]), np.array([]) upper = float(r[-1]) / 2.0 if r_max is None else float(r_max) mask = (r >= r_min) & (r <= upper) & (G > 1e-10) & np.isfinite(G) return r[mask], G[mask]
[docs] def fit_correlation_length( *, r: np.ndarray, G: np.ndarray, r_min: int = 2, r_max: int | None = None, ) -> float: """ 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 ------- float The correlation length xi, or NaN when fewer than two usable points remain, the fit fails, or the fitted slope is not negative. """ r_fit, G_fit = _fit_window(r=r, G=G, r_min=r_min, r_max=r_max) if len(r_fit) < 2: return float('nan') try: slope, _ = np.polyfit(r_fit, np.log(G_fit), 1) except (np.linalg.LinAlgError, ValueError): return float('nan') if not np.isfinite(slope) or slope >= 0.0: return float('nan') return float(-1.0 / slope)
[docs] def fit_correlation_exponent( *, r: np.ndarray, G: np.ndarray, r_min: int = 2, r_max: int | None = None, ) -> float: """ 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 ------- float The exponent eta, or NaN when fewer than two usable points remain or the fit fails. """ r_fit, G_fit = _fit_window(r=r, G=G, r_min=r_min, r_max=r_max) if len(r_fit) < 2: return float('nan') try: slope, _ = np.polyfit(np.log(r_fit), np.log(G_fit), 1) except (np.linalg.LinAlgError, ValueError): return float('nan') if not np.isfinite(slope): return float('nan') return float(-slope)
[docs] def radial_average_sk(*, spins: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Compute the circularly averaged structure factor :math:`S(|k|)`. Bins :math:`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. """ N = spins.shape[0] if spins.ndim == 3: # Vector spins (XY/Clock) sx, sy = spins[..., 0], spins[..., 1] Sk_raw = ( np.abs(np.fft.fft2(sx.astype(float))) ** 2 + np.abs(np.fft.fft2(sy.astype(float))) ** 2 ) else: # Scalar spins (Ising) Sk_raw = np.abs(np.fft.fft2(spins.astype(float))) ** 2 Sk = np.fft.fftshift(Sk_raw) / (N * N) cx = N // 2 iy, ix = np.indices((N, N)) r_int = np.sqrt((ix - cx) ** 2 + (iy - cx) ** 2).astype(int) # Average within each annular bin up to the Nyquist radius r_max = cx mask = r_int <= r_max tbin = np.bincount(r_int[mask].ravel(), Sk[mask].ravel()) nbin = np.bincount(r_int[mask].ravel()) S_radial = np.where(nbin > 0, tbin / nbin, 0.0) # Convert bin index → |k| in reciprocal lattice units (2π/N per bin) k_vals = np.arange(len(S_radial)) * (2.0 * np.pi / N) return k_vals, S_radial
[docs] def pair_correlation_x(*, spins: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """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). """ N = spins.shape[0] if spins.ndim == 3: # Vector spins (XY/Clock) sx, sy = spins[..., 0].astype(float), spins[..., 1].astype(float) Fx = np.fft.rfft(sx, axis=1) Fy = np.fft.rfft(sy, axis=1) autocorr = np.fft.irfft(np.abs(Fx) ** 2 + np.abs(Fy) ** 2, n=N, axis=1) else: # Scalar spins (Ising) s = spins.astype(float) F = np.fft.rfft(s, axis=1) autocorr = np.fft.irfft(np.abs(F) ** 2, n=N, axis=1) # Average over rows and normalise by N G_full = np.mean(autocorr, axis=0) / N r_half = N // 2 + 1 r_vals = np.arange(r_half) G = G_full[:r_half] if G[0] != 0.0: G = G / G[0] return r_vals, G
[docs] def correlation_length_1e(*, r: np.ndarray, G: np.ndarray) -> float: """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 ------- float The interpolated 1/e crossing radius, or NaN if no crossing exists. """ inv_e = 1.0 / np.e below = np.where(np.asarray(G) < inv_e)[0] if len(below) == 0: return float('nan') idx = int(below[0]) if idx == 0: return float(r[0]) r0, r1 = float(r[idx - 1]), float(r[idx]) g0, g1 = float(G[idx - 1]), float(G[idx]) return r0 + (inv_e - g0) * (r1 - r0) / (g1 - g0)
[docs] def connected_correlation_length( *, sim: _Sim, meas_steps: int, sample_interval: int ) -> float: """ 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 ------- float Connected correlation length in lattice units, or NaN if the averaged function never drops below 1/e within half the lattice. Raises ------ ValueError If no sample falls inside ``meas_steps``. """ if sample_interval < 1 or meas_steps < sample_interval: raise ValueError( f'meas_steps={meas_steps} yields no sample at interval {sample_interval}.' ) G_sum: np.ndarray | None = None r_vals = np.empty(0) n_samples = 0 for step in range(1, meas_steps + 1): sim.step() if step % sample_interval == 0: field = np.asarray(sim.get_spin_field(), dtype=float) mean = field.mean(axis=(0, 1)) r_vals, G = pair_correlation_x(spins=field - mean) G_sum = G if G_sum is None else G_sum + G n_samples += 1 if G_sum is None: raise RuntimeError('No correlation sample was accumulated despite a valid interval.') G_avg = G_sum / n_samples if G_avg[0] == 0.0: return float('nan') return correlation_length_1e(r=r_vals, G=G_avg / G_avg[0])
[docs] def compute_kinetics_metrics(*, sim: _Sim) -> dict[str, float]: """ Calculate common kinetics metrics (R_sk, xi) for a simulation state. Parameters ---------- sim : _Sim MonteCarloSimulation instance. Returns ------- dict[str, float] Dictionary containing 'R_sk' and 'xi'. """ if sim.spins is None: return {'R_sk': 0.0, 'xi': 0.0} # 1. R_sk from structure factor first moment spin_field = sim.get_spin_field() kvals, S_radial = radial_average_sk(spins=spin_field) S_k = S_radial[1:] K_k = kvals[1:] denom = float(np.sum(K_k * S_k)) R_sk = (2.0 * np.pi * float(np.sum(S_k) / denom)) if denom != 0 else 0.0 # 2. xi from G(r) 1/e decay; no crossing means the correlation extends # beyond the accessible range, so fall back to the largest distance. r_vals, G = pair_correlation_x(spins=spin_field) xi = correlation_length_1e(r=r_vals, G=G) if not np.isfinite(xi): xi = float(r_vals[-1]) return {'R_sk': R_sk, 'xi': xi}