flowtorch.analysis
flowtorch.analysis.svd
Classes and functions wrapping around torch.linalg.svd.
- class flowtorch.analysis.svd.PODSubspaceDependencyResult(similarity: Tensor, ranks: Tensor, sequence_fractions: Tensor, snapshot_strides: Tensor, n_snapshots: Tensor, optimal_ranks: Tensor, reference_optimal_rank: int)[source]
Bases:
NamedTupleResults of a POD subspace data-dependency sweep.
similarityhas shape(n_fractions, n_strides, n_ranks). Then_snapshotsandoptimal_rankstensors have shape(n_fractions, n_strides).- n_snapshots: Tensor
Alias for field number 4
- optimal_ranks: Tensor
Alias for field number 5
- ranks: Tensor
Alias for field number 1
- reference_optimal_rank: int
Alias for field number 6
- sequence_fractions: Tensor
Alias for field number 2
- similarity: Tensor
Alias for field number 0
- snapshot_strides: Tensor
Alias for field number 3
- class flowtorch.analysis.svd.SVD(data_matrix: Tensor | StateVectorSource, rank: int | None = None, mode: str = 'auto', weight: Tensor | None = None, *, subtract_mean: bool = False, spatial_batch_size: int | None = None, execution: DistributedExecution | None = None, memory_budget_bytes: int | None = None, prefetch_chunks: bool = False, basis_storage: str = 'disk', basis_directory: str | PathLike[str] | None = None)[source]
Bases:
ProvenanceMixinCompute and analyze the SVD of a data matrix.
Examples
>>> import torch as pt >>> from flowtorch.analysis import SVD >>> data = pt.rand((400, 5), dtype=pt.float32) >>> svd = SVD(data, rank=100) >>> print(svd) SVD of a 400x5 data matrix Selected/optimal rank: 5/2 data type: torch.float32 (4b) truncated SVD size: 7.9297Kb >>> svd.s_rel tensor([9.9969e+01, 3.0860e-02, 3.0581e-04, 7.8097e-05, 3.2241e-05]) >>> svd.s_cum tensor([ 99.9687, 99.9996, 99.9999, 100.0000, 100.0000]) >>> svd.U.shape torch.Size([400, 5])
A
StateVectorSourceselects the out-of-core TSQR path. The same call is spatially distributed when an initializedDistributedExecutionis supplied:source = DataloaderStateVectorSource( loader, (FieldSpec("U", (3,)), FieldSpec("p")), normalization={"U": u_ref, "p": p_ref}, ) svd = SVD( source, rank=20, subtract_mean=True, spatial_batch_size=100_000, execution=execution, # omit for shared-memory execution ) for spatial_slice, fields in svd.U.iter_chunks(split=True): consume(fields["U"], fields["p"])
- property U: Any
Physical left-singular vectors.
For a weighted decomposition, these modes are orthonormal in the weighted inner product,
U.conj().T @ W @ U = I.- Returns:
physical left-singular vectors truncated to specified rank
- Return type:
pt.Tensor
- property U_weighted: Tensor | StateVectorResult
Euclidean-orthonormal left-singular vectors.
For a weighted decomposition, this is
W**0.5 @ U. Without a weight, it is identical toU.- Returns:
left-singular vectors in weighted coordinates
- Return type:
pt.Tensor
- property V: Tensor
Truncated matrix of right-singular vectors.
- Returns:
right-singular vectors truncated at specified rank
- Return type:
pt.Tensor
- property basis_storage: str | None
Local TSQR basis storage mode, or None for a tensor decomposition.
- decode(coefficients: Tensor) Tensor | StateVectorResult[source]
Expand arbitrary POD coefficients into the physical state space.
- encode(state: Tensor | StateVectorSource) Tensor[source]
Project one or more physical states onto the retained POD modes.
Centering and the weighted inner product used to compute the SVD are applied consistently. Source-backed projections are reduced across the configured process group, so every rank receives the same modal coefficients.
- classmethod load(path: str | PathLike[str], *, source: StateVectorSource | None = None, execution: DistributedExecution | None = None, map_location: Any = 'cpu', spatial_batch_size: int | None = None, prefetch_chunks: bool | None = None, basis_storage: str = 'disk', basis_directory: str | PathLike[str] | None = None) SVD[source]
Restore self-contained factors without accessing original snapshots.
Source-backed directory checkpoints restore using the same rank count.
sourceis optional and, when supplied, only validates the layout.basis_storageselects memory or owned temporary disk storage.
- property maximum_rank: int | None
Requested TSQR rank ceiling; None selects the rank automatically.
- property mean: Tensor | StateVectorResult | None
Temporal mean retained by a centered decomposition.
- property mode: str
SVD compute path
- Returns:
can be ‘svd’ or ‘evd’
- Return type:
str
- property opt_rank: int
Optimal truncation rank according to singular value hard threshold.
- Returns:
optimal rank
- Return type:
int
- property rank: int
Truncation rank.
- Returns:
truncation rank
- Return type:
int
- reconstruct(rank: int | None = None) Any[source]
Reconstruct the data matrix for a given rank.
- Parameters:
rank (int, optional) – rank used to compute a truncated reconstruction
- Returns:
reconstruction of the input data matrix
- Return type:
pt.Tensor
- property required_memory: int
Compute the memory size in bytes of the truncated SVD.
- Returns:
persistent factor tensor bytes (local for TSQR), excluding disk arrays, filesystem cache, and temporary workspace
- Return type:
int
- property s: Tensor
Truncated singular values.
- Returns:
singular values truncated to specified rank
- Return type:
pt.Tensor
- property s_cum: Tensor
Relative cumulative contribution of singular values.
- Returns:
relative cumulative contribution given in percent
- Return type:
pt.Tensor
- property s_full: Tensor
All singular values of economy SVD.
- Returns:
singular values (not truncated)
- Return type:
pt.Tensor
- property s_rel: Tensor
Relative truncated singular values.
- Returns:
contribution of singular values to their sum; given in percent
- Return type:
pt.Tensor
- save(path: str | PathLike[str]) None[source]
Save self-contained factors, including the retained physical basis.
Tensor decompositions use one torch file. Source-backed decompositions use a new directory with metadata and one chunk-file shard per rank. Distributed saves are collective and require a shared filesystem. Existing checkpoint directories are never overwritten.
- update(new_source: StateVectorSource) SVD[source]
Append snapshots using stored local modes, including mean corrections.
Explicit source-backed ranks are ceilings. Intermediate truncation is approximate and may differ from truncating a single full factorization. The initial spatial size is reused, reduced only if the current memory estimate requires it. Updates never run timing trials. Old snapshots are never read. The new batch is staged once in owned chunk storage and remains available only for the duration of the update.
- property weight: Tensor | None
Expanded raw diagonal inner-product weight.
- Returns:
expanded weight, or
Nonefor the Euclidean inner product- Return type:
Union[pt.Tensor, None]
- flowtorch.analysis.svd.pod_subspace_data_dependency(data_matrix: Tensor, ranks: int | Sequence[int] | Tensor | None = None, sequence_fractions: Sequence[float] = (0.5, 0.6, 0.7, 0.8, 0.9, 1.0), snapshot_strides: Sequence[int] = (1, 2, 3, 4), weight: Tensor | None = None, subtract_mean: bool = True, mode: str = 'auto') PODSubspaceDependencyResult[source]
Measure POD-subspace dependency on sequence length and sampling.
The POD of the complete sequence at snapshot stride one is used as the reference. For every sequence fraction
pand snapshot striden, the sampled matrix isdata_matrix[:, :floor(p*N):n]. Its leading POD subspaces are compared with the reference usingsubspace_similarity().If
ranksis omitted, all ranks up to the automatically selected rank of the reference SVD are evaluated, subject to the rank supported by the smallest sampled matrix. Automatic ranks of all sampled matrices are returned as diagnostics but do not alter the common comparison ranks.similarityin the returned result has shape(n_fractions, n_strides, n_ranks). A stridencorresponds to an effective sampling intervaln*dtif the original snapshots are spaced bydt.- Parameters:
data_matrix (pt.Tensor) – state-by-snapshot data matrix
ranks (Union[int, Sequence[int], pt.Tensor, None], optional) – positive, strictly increasing comparison ranks; defaults to all feasible ranks up to the reference SVD’s automatic rank
sequence_fractions (Sequence[float], optional) – fractions of the sequence retained before subsampling
snapshot_strides (Sequence[int], optional) – positive snapshot strides
weight (pt.Tensor, optional) – positive diagonal spatial weight used for the POD inner product
subtract_mean (bool, optional) – subtract the temporal mean independently from every sampled matrix, defaults to
Truemode (str, optional) – SVD compute mode passed to
SVD, defaults to"auto"
- Raises:
ValueError – for invalid data, sweep coordinates, or ranks
- Returns:
dependency sweep and rank diagnostics
- Return type:
- flowtorch.analysis.svd.subspace_similarity(first_modes: Tensor, second_modes: Tensor, ranks: int | Sequence[int] | Tensor | None = None, weight: Tensor | None = None) Tensor[source]
Compare nested subspaces spanned by two columnwise mode sets.
For each requested rank
r, the returned normalized projection overlap is\[S_r = \frac{1}{r}\lVert Q_{1,r}^* Q_{2,r}\rVert_F^2 = \frac{1}{r}\sum_{i=1}^r \cos^2(\theta_i),\]where
Qare orthonormal bases andthetaare the principal angles. The score lies in[0, 1]and is invariant to sign, phase, ordering, and rotations within either rank-rsubspace. Whenweightis provided, the bases are constructed in the corresponding diagonal weighted inner product.If
ranksis omitted, similarities for every available rank are returned. The result is always one-dimensional, including when a single integer rank is supplied.- Parameters:
first_modes (pt.Tensor) – first columnwise mode set
second_modes (pt.Tensor) – second columnwise mode set
ranks (Union[int, Sequence[int], pt.Tensor, None], optional) – positive, strictly increasing subspace ranks; defaults to all available ranks
weight (pt.Tensor, optional) – positive diagonal spatial weight
- Raises:
ValueError – for incompatible modes, ranks, or weights
- Returns:
normalized similarity for every requested rank
- Return type:
pt.Tensor
flowtorch.analysis.state_vector
Lazy construction and decomposition outputs for physical state vectors.
- class flowtorch.analysis.state_vector.CompositeStateVectorSource(sources: Sequence[StateVectorSource])[source]
Bases:
StateVectorSourceAppend-compatible view over consecutive state-vector sources.
- property layout: StateVectorLayout
- property n_snapshots: int
- class flowtorch.analysis.state_vector.DataloaderStateVectorSource(loader: Dataloader, fields: Sequence[FieldSpec], times: Sequence[str] | None = None, normalization: str | Mapping[str, float] | None = None, spatial_weight: WeightSource | None = None, device: str | pt.device = 'cpu')[source]
Bases:
StateVectorSourceBuild state-vector chunks lazily from a flowTorch dataloader.
Each physical field has one normalization factor, regardless of how many scalar components it contains. For example, all three velocity components use
u_refwhile pressure usesp_ref:fields = ( FieldSpec("U", component_shape=(3,), component_names=("u", "v", "w")), FieldSpec("p"), ) source = DataloaderStateVectorSource( loader, fields, times=loader.write_times, normalization={"U": u_ref, "p": p_ref}, spatial_weight=loader.weights, )
Passing
normalization="rms"fits one weighted fluctuation RMS per field during the first SVD. Snapshot and spatial slices are requested from the dataloader only when a decomposition or result chunk needs them.- fit_normalization(spatial_slice: slice, spatial_batch_size: int, snapshot_batch_size: int, execution: Any = None) None[source]
Fit deferred normalization, if any.
- property layout: StateVectorLayout
- property n_snapshots: int
- property normalization_fitted: bool
- read_cpu(spatial_slice: slice, snapshot_slice: slice) Tensor[source]
Pack source data on the host, deferring transfer to the consumer.
- read_weight_cpu(spatial_slice: slice) Tensor | None[source]
Host weight preparation hook for prefetched chunks.
- restore_normalization(factors: Mapping[str, float]) None[source]
Restore frozen factors without rescanning snapshots.
- property times: tuple[str, ...]
- with_times(times: Sequence[str]) DataloaderStateVectorSource[source]
Create a compatible source for newly appended times.
- class flowtorch.analysis.state_vector.FieldSpec(name: str, component_shape: tuple[int, ...] = (), component_names: tuple[str, ...] = ())[source]
Bases:
objectDescribe one physical field in a flat state vector.
Component dimensions must trail the common spatial dimensions. All spatial values of one component are stored contiguously before the next component.
>>> velocity = FieldSpec("U", component_shape=(3,), component_names=("u", "v", "w")) >>> pressure = FieldSpec("p")
- component_names: tuple[str, ...] = ()
- component_shape: tuple[int, ...] = ()
- property n_components: int
Number of scalar components in the field.
- name: str
- class flowtorch.analysis.state_vector.StateVectorLayout(fields: Sequence[FieldSpec], spatial_shape: Sequence[int], normalization_factors: Mapping[str, float] | None = None)[source]
Bases:
objectPack and restore fields using a stable component-major layout.
- property normalization_factors: dict[str, float]
- pack(values: Mapping[str, Tensor], *, spatial_shape: Sequence[int] | None = None, normalize: bool = True) Tensor[source]
Concatenate scalar components into state-by-snapshot form.
- property signature: tuple[Any, ...]
Metadata used to validate compatible sources.
- property spatial_shape: tuple[int, ...]
- split(state: Tensor, *, spatial_shape: Sequence[int] | None = None, denormalize: bool = True) dict[str, Tensor][source]
Restore physical field and component dimensions from a flat state.
- property state_size: int
- with_normalization(factors: Mapping[str, float]) StateVectorLayout[source]
- class flowtorch.analysis.state_vector.StateVectorResult(layout: StateVectorLayout, local_spatial_slice: slice, trailing_shape: Sequence[int], producer: Callable[[slice], Tensor], spatial_batch_size: int, execution: Any = None)[source]
Bases:
objectLazy local spatial result with optional field reconstruction.
Flat chunks remain normalized. Set
split=Trueto obtain denormalized physical fields with their original component dimensions:for spatial_slice, fields in svd.U.iter_chunks(split=True): velocity_modes = fields["U"] pressure_modes = fields["p"]
Distributed results remain local unless
gather()is called collectively on every rank.- gather(split: bool = False, root_rank: int | None = None) Tensor | dict[str, Tensor] | None[source]
Materialize local chunks and gather complete CPU fields on one rank.
- property global_shape: tuple[int, ...]
- class flowtorch.analysis.state_vector.StateVectorSource[source]
Bases:
ProvenanceMixin,ABCRandom-access, spatially chunked source of flat state vectors.
- property device: device | None
Declared consumer device, when the source has one.
- fit_normalization(spatial_slice: slice, spatial_batch_size: int, snapshot_batch_size: int, execution: Any = None) None[source]
Fit deferred normalization, if any.
- iter_chunks(spatial_slice: slice, spatial_batch_size: int, snapshot_slice: slice | None = None, *, prefetch: bool = False) Generator[tuple[slice, Tensor, Tensor | None], None, None][source]
Read one spatial chunk ahead in CPU RAM, without device transfers.
The iterator owns its preparation thread, not the source. Close it when stopping early. Legacy GPU-only readers use synchronous iteration.
- abstract property layout: StateVectorLayout
- abstract property n_snapshots: int
- read_cpu(spatial_slice: slice, snapshot_slice: slice) Tensor[source]
CPU preparation hook; GPU-only custom readers stay synchronous.
Override this method to enable CPU prefetch for GPU-returning sources. The default preserves existing readers and does not move data devices.
- read_weight_cpu(spatial_slice: slice) Tensor | None[source]
Host weight preparation hook for prefetched chunks.
- restore_normalization(factors: Mapping[str, float]) None[source]
Restore checkpoint normalization or reject incompatible factors.
- property spatial_shape: tuple[int, ...]
flowtorch.analysis.dft
Windowed Fourier modes and POD-compressed Fourier analysis.
Spectra contain total spatially weighted bin energy, rather than spatially averaged squared FFT magnitudes. Real spectra include one-sided energy factors.
- class flowtorch.analysis.dft.DFT(data_matrix: Tensor, dt: float, nfft: int | None = None, window: str = 'boxcar', device: str = 'cpu', *, weight: Tensor | None = None, subtract_mean: bool = True)[source]
Bases:
ProvenanceMixinCompute Fourier modes of a spatial-by-temporal tensor.
Modes have unit norm in the supplied spatial inner product. Null modes are zero.
amplitudeis bin energy, not the square root of energy. Centered analyses omit DC from the public spectrum, but preserve the window-induced DC internally for inverse-FFT reconstruction.- property amplitude: Tensor
Total weighted bin energy, corrected for window energy.
For boxcar, summing all bins gives the temporal mean of the weighted squared state norm. Centered analyses omit DC; non-boxcar tapering can create DC even after centering, so the exposed sum then excludes it.
- property eigvals: Tensor
Single energy branch, shaped like the AMSPOD spectrum.
- property frequency: Tensor
FFT frequencies; DC is exposed only when centering is disabled.
- get_mode(f_idx: int) Tensor | StateVectorResult[source]
Return a single normalized physical Fourier mode.
- mode_reconstruction(f_idx: int, dt: float | None = None, N: int | None = None) Tensor | StateVectorResult[source]
Animate a unit-norm mode over one period (25 samples by default).
This is harmonic animation, not the amplitude-scaled inverse-FFT contribution. DC uses the original time step, as in PAMSPOD.
- property modes: Tensor | StateVectorResult
Weighted unit-norm physical modes; unresolved bins are zero.
- partial_reconstruction(mode_indices: Set[int] | int, include_mean: bool = False) Tensor | StateVectorResult[source]
Inverse FFT of selected public bins at the original sampling times.
For centered data, internal DC is always retained to preserve taper DC.
include_meanrestores the mean only if centering was enabled. Window division amplifies errors where the taper is small; zero-window samples cannot be recovered. Hamming has nonzero endpoints and is more stable to invert. Real-input reconstruction includes conjugate partners.
- property reconstruction: Tensor | StateVectorResult
Inverse FFT using all bins and the retained mean.
- show_mode_similarity(reference_timescale: float | None = None, ax: Any = None, **kwargs: Any)[source]
Plot the frequency-by-frequency weighted mode similarities.
- show_spectrum(n_show: int = 1, show_sum: bool = False, reference_timescale: float | None = None, energy_density: bool = False, normalize_energy: bool = False, ax: Any = None, **kwargs: Any)[source]
Plot bin energy or density using the shared SPOD spectrum helper.
- property spectral_density: Tensor
Bin energy per Hz, using spacing
1 / (nfft * dt).
- top_modes(n: int = 10, f_min: float = -inf, f_max: float = inf, *, spacing: Literal['log', 'linear'] = 'log') Tensor[source]
Select the strongest bin per frequency segment, as in PAMSPOD.
ncounts segments, not global peaks. Log spacing excludes DC and supports negative frequencies. The upper frequency bound is exclusive.
- class flowtorch.analysis.dft.PDFT(data_matrix: Tensor | StateVectorSource, dt: float, rank: int | None = None, nfft: int | None = None, window: str = 'boxcar', device: str = 'cpu', *, weight: Tensor | None = None, subtract_mean: bool = True, prefetch_chunks: bool = False, spatial_batch_size: int | None = None, execution: DistributedExecution | None = None)[source]
Bases:
DFTFourier analysis in a retained, optionally weighted POD subspace.
SVD centers before fitting the POD basis. Lazy sources use SVD’s batched and optionally distributed computation; physical results remain lazy.
- classmethod from_svd(svd: SVD, dt: float, nfft: int | None = None, window: str = 'boxcar', device: str = 'cpu') PDFT[source]
Reuse SVD factors, centering and weights without reading snapshots.
Rebuild PDFT after updating the supplied SVD: spectral results are computed at construction and do not automatically track factor changes.
- get_mode(f_idx: int) Tensor | StateVectorResult[source]
Project only one Fourier mode to physical coordinates.
- mode_reconstruction(f_idx: int, dt: float | None = None, N: int | None = None) Tensor | StateVectorResult[source]
Project a unit-norm harmonic animation to physical space.
- property modes: Tensor | StateVectorResult
Weighted unit-norm Fourier modes in physical coordinates.
- partial_reconstruction(mode_indices: Set[int] | int, include_mean: bool = False) Tensor | StateVectorResult[source]
Inverse-FFT reconstruction in physical space, optionally restoring mean.
flowtorch.analysis.mssa
Implementation of multivariate singular spectrum analysis (MSSA).
The MSSA may be used as a preprocessing tool to reduce noise in time series data. For large state vectors, the memory requirements due to time delay embedding can be reduced by projecting the data onto a truncated POD basis before performing MSSA. This variant is referred to as projected MSSA (PMSSA). The implementation is based on the work of Ohmichi et al.
- class flowtorch.analysis.mssa.MSSA(data_matrix: Tensor, window_size: int = None, rank: int = None)[source]
Bases:
ProvenanceMixinMultivariate singular spectrum analysis (MSSA).
Examples
>>> import torch as pt >>> from flowtorch.analysis import MSSA >>> dm = pt.rand((10, 100)) >>> mssa = MSSA(dm, rank=20) >>> rec = mssa.reconstruction >>> err = mssa.reconstruction_error.norm() / dm.norm()
- property delay: int
- property reconstruction: Tensor
Compute reconstruction of the original data matrix.
In the rank-r approximation of the Hankel matrix, multiple instances of individual snapshots are reconstructed. To reconstruct the original data matrix, averaging over the anti-diagonals is performed.
- Returns:
rank-r reconstruction of the original data matrix
- Return type:
pt.Tensor
- property reconstruction_error: Tensor
Compute elementwise reconstruction error.
- Returns:
reconstruction error with one value for each element in the data matrix
- Return type:
pt.Tensor
- property svd: SVD
SVD of the Hankel matrix.
- Returns:
truncated SVD of the Hankel matrix
- Return type:
- property window_size: int
- class flowtorch.analysis.mssa.PMSSA(data_matrix: Tensor, window_size: int = None, rank: int = None)[source]
Bases:
MSSAProjected multivariate singular spectrum analysis (PMSSA).
Examples
>>> import torch as pt >>> from flowtorch.analysis import PMSSA >>> dm = pt.rand((1000, 200)) >>> pmssa = PMSSA(dm, rank=20) >>> rec = pmssa.reconstruction >>> err = pmssa.reconstruction_error.norm() / dm.norm()
- property reconstruction: Tensor
Compute reconstruction error in the original basis
- Returns:
reconstruction of the original data matrix
- Return type:
pt.Tensor
- property reconstruction_error: Tensor
Compute elementwise reconstruction error.
flowtorch.analysis.dmd
Classes and functions to compute the dynamic mode decomposition (DMD) of a data matrix.
- class flowtorch.analysis.dmd.DMD(data_matrix: Tensor | List[Tensor], dt: float, rank: int | None = None, unitary: bool = False, optimal: bool = False, tlsq: bool = False, forward_backward: bool | dict = False)[source]
Bases:
objectWrapper class implementing multiple DMD versions.
Examples
>>> from flowtorch import DATASETS >>> from flowtorch.data import FOAMDataloader >>> from flowtorch.analysis import DMD >>> path = DATASETS["of_cavity_binary"] >>> loader = FOAMDataloader(path) >>> data_matrix = loader.load_snapshot("p", loader.write_times) >>> dmd = DMD(data_matrix, dt=0.1, rank=3) >>> dmd.frequency tensor([0., 5., 0.]) >>> dmd.growth_rate tensor([-2.3842e-06, -4.2345e+01, -1.8552e+01]) >>> dmd.amplitude tensor([10.5635+0.j, -0.0616+0.j, -0.0537+0.j])
- property amplitude: List[Tensor] | Tensor
- property dft_properties: Tuple[float, float, float]
- property dynamics: List[Tensor] | Tensor
- property eigvals: Tensor
- property eigvals_cont: Tensor
- property eigvecs: Tensor
- property fb_log: dict | None
- property frequency: Tensor
- property growth_rate: Tensor
- property integral_contribution: List[Tensor] | Tensor
Integral contribution of individual modes according to J. Kou et al. 2017.
- property modes: Tensor
- property operator: Tensor
- partial_reconstruction(mode_indices: Set[int]) List[Tensor] | Tensor[source]
Reconstruct data matrix with limited number of modes.
- Parameters:
mode_indices (Set[int]) – mode indices to keep
- Returns:
reconstructed data matrix
- Return type:
pt.Tensor
- predict(initial_condition: Tensor, n_steps: int) Tensor[source]
Predict evolution over N steps starting from user-defined initial conditions.
- Parameters:
initial_condition (pt.Tensor) – initial state vector
n_steps (int) – number of steps to predict
- Returns:
predicted evolution, including the initial state (N+1 states are returned)
- Return type:
pt.Tensor
- property projection_error: Tensor
Compute the difference between Y and AX.
- Returns:
projection error
- Return type:
pt.Tensor
- property reconstruction: List[Tensor] | Tensor
Reconstruct an approximation of the original data matrix.
- Returns:
reconstructed data matrix
- Return type:
pt.Tensor
- property reconstruction_error: List[Tensor] | Tensor
Compute the reconstruction error.
- Returns:
difference between reconstruction and data matrix
- Return type:
pt.Tensor
- property required_memory: int
Compute the memory size in bytes of the DMD.
- Returns:
cumulative size of SVD, eigen values/vectors, and DMD modes in bytes
- Return type:
int
- property tlsq_error: Tuple[Tensor, Tensor]
Compute the noise in X and Y.
- Returns:
noise in X and Y
- Return type:
Tuple[pt.Tensor, pt.Tensor]
- top_modes(n: int = 10, integral: bool = False, f_min: float = -inf, f_max: float = inf) Tensor[source]
Get the indices of the first n most important modes.
Note that the conjugate complex modes for real data matrices are not filtered out by default. However, by setting the lower frequency threshold to a positive number, only modes with positive imaginary part are considered.
- Parameters:
n (int) – number of indices to return; defaults to 10
integral (bool, optional) – if True, the modes are sorted according to their integral contribution; defaults to False
f_min (float, optional) – consider only modes with a frequency larger or equal to f_min; defaults to -inf
f_max (float, optional) – consider only modes with a frequency smaller than f_max; defaults to -inf
- Returns:
indices of top n modes sorted by amplitude or integral contribution
- Return type:
pt.Tensor
flowtorch.analysis.hodmd
Implementation of the higher-order DMD (HODMD).
- class flowtorch.analysis.hodmd.HODMD(data_matrix: Tensor, dt: float, delay: int | None = None, rank_dr: int | None = None, **dmd_options: Any)[source]
Bases:
DMDHigher-order dynamic mode decomposition (HODMD).
For the theoretical background, refer to Clainche and Vega. The HODMD wraps around the standard DMD by adding an initial dimensionality reduction step and an enrichment of the data matrix with delays. To reconstruct snapshots and modes in the original space, a few properties of the base class are overwritten. Examples
>>> from flowtorch.analysis import HODMD >>> dmd = HODMD(data_matrix, dt) set time delay explicitly to 5 time levels >>> dmd = HODMD(data_matrix, dt, delay=5) set the rank for the initial dimensionality reduction >>> dmd = HODMD(data_matrix, dt, delay=5, rank_dr=100) use optimal mode coefficients >>> dmd = HODMD(data_matrix, dt, delay=5, rank_dr=100, optimal=True)
- property delay: int
- property dynamics: Tensor
Get mode dynamics for the original data matrix.
- Returns:
mode dynamics for the original snapshot sequence
- Return type:
pt.Tensor
- property modes: Tensor
Get DMD modes in the input space.
As suggested by Clainche and Vega, only the first set of modes corresponding to the first r rows of the reduced DMD modes are kept (r is the dimension after the initial dimensionality reduction).
- Returns:
DMD modes in the input space
- Return type:
pt.Tensor
- predict(initial_condition: Tensor, n_steps: int) Tensor[source]
Predict evolution over N steps starting from user-defined initial conditions.
The prediction is performed as follows: 1) the initial conditions are projected on the first r POD modes 2) the time delay embedding is computed in the reduced space 3) the prediction is computed in the reduced space 4) the first r rows of the prediction are reconstructed
- Parameters:
initial_condition (pt.Tensor) – initial sequence of state vectors without time delay embedding; for d delays and a state vector of size M, the initial conditions should be given as a M x d matrix sorted such that the most recent state is contained in the last column
n_steps (int) – number of future steps to predict
- Returns:
predicted states; due to the structure of the linear operator some states are predicted multiple times; only the first M rows of the reconstruction are returned
- Return type:
pt.Tensor
- property projection_error: Tensor
Compute the difference between Y and AX.
- Returns:
projection error
- Return type:
pt.Tensor
- property reconstruction: Tensor
Compute reconstruction of original data matrix.
Due to the time delays, some states are contained multiple times in a reconstruction. Only the first occurrence of a state is kept when looping over the rows in steps of size r (rank).
- Returns:
reconstruction of original data matrix
- Return type:
pt.Tensor
- property reconstruction_error: Tensor
Compute the point-wise reconstruction error.
Due to the time delay, not all snapshots from the input data matrix are reconstructed, so the error is only computed for the available reconstructed snapshots
- Returns:
reconstruction error
- Return type:
pt.Tensor
- property tlsq_error: Tuple[Tensor, Tensor]
Compute the noise in X and Y.
- Returns:
noise in X and Y
- Return type:
Tuple[pt.Tensor, pt.Tensor]
flowtorch.analysis.optdmd
Optimized DMD via gradient descent and backpropagation.
- class flowtorch.analysis.optdmd.OptDMD(*dmd_args, **dmd_kwargs)[source]
Bases:
ModuleOptimized DMD based on backpropagation and gradient descent.
For a detailed description of this DMD variant, refer to Weiner and Semaan (2023).
Examples
>>> import torch as pt >>> from flowtorch.analysis import OptDMD >>> dm = pt.rand((200, 100)) >>> dmd = DMD(dm, dt=1.0) >>> dmd.train(stopping_options={'patience' : 80, 'checkpoint' : 'best_model.pt'}) >>> dmd.load_state_dict(pt.load('best_model.pt')) >>> train_loss = dmd.log['train_loss'] >>> val_loss = dmd.log['val_loss']
- property amplitude: Tensor
- property dynamics: Tensor
- property eigvals: Tensor
- property eigvals_cont: Tensor
- property eigvecs: Tensor
- forward(time_indices: Tensor) Tensor[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- property frequency: Tensor
- property growth_rate: Tensor
- property integral_contribution: Tensor
- property log: dict
- property modes: Tensor
- predict(initial_condition: Tensor, n_steps: int) Tensor[source]
Predict evolution over N steps starting from user-defined initial conditions.
- Parameters:
initial_condition (pt.Tensor) – initial state vector
n_steps (int) – number of steps to predict
- Returns:
predicted evolution including the initial state (N+1 states are returned)
- Return type:
pt.Tensor
- property reconstruction: Tensor
- property reconstruction_error: Tensor
- top_modes(n: int = 10, integral: bool = False, f_min: float = -inf, f_max: float = inf) Tensor[source]
- train(epochs: int = 1000, lr: float = 0.001, batch_size: int = None, train_size: int | float = 0.75, val_size: int | float = 0.25, loss_function: Callable = <function fro_loss>, scheduler_options: dict = {}, stopping_options: dict = {}, loss_key: str = 'val_loss')[source]
Optimize modes and dynamics based on gradient descent.
- Parameters:
epochs (int, optional) – number of training iterations, defaults to 1000
lr (float, optional) – initial learning rate, defaults to 1.0e-3
batch_size (int, optional) – batch size for batch training, defaults to None
train_size (Union[int, float], optional) – fraction or number of snapshots to use for training; defaults to 0.75
val_size (Union[int, float], optional) – fraction or number of snapshots to use for validation; defaults to 0.25
loss_function (Callable, optional) – user-defined loss function, e.g., to add sparsity promotion, defaults to fro_loss
scheduler_options (dict, optional) – options passed to learning rate scheduler; refer to PyTorch’s ReduceLROnPlateau documentation; defaults to {}
stopping_options (dict, optional) – options to modify early stopping behavior; refer to the EarlyStopping class; defaults to {}
loss_key (str, optional) – key of loss value based on which the learning rate schedule and early stopping criteria are evaluated; can be ‘train_loss’, ‘val_loss’, or ‘full_loss’; defaults to “val_loss”
- flowtorch.analysis.optdmd.fro_loss(label: Tensor, prediction: Tensor, eigvecs: Tensor, eigvals: Tensor) Tensor[source]
Compute the Frobenius norm of the prediction error.
Note: in contrast to the default norm function in PyTorch, the norm is normalized by the number of elements in the prediction tensor.
Note: the argument list is more generic than necessary for this loss function; the eigenvectors and eigenvalues may be used for regularization or to enforce physical constraints in more advanced loss functions.
- Parameters:
label (pt.Tensor) – ground truth
prediction (pt.Tensor) – predictions
- Returns:
L2 norm normalized by number of elements
- Return type:
pt.Tensor
flowtorch.analysis.hooptdmd
Higher-order optimized DMD version.
- class flowtorch.analysis.hooptdmd.HOOptDMD(data_matrix: Tensor, dt: float, delay: int = 1, rank_dr: int = None, **dmd_options: dict)[source]
Bases:
OptDMDOptimized DMD extended with data projection and time delay embedding.
- Parameters:
OptDMD (flowtorch.analysis.OptDMD) – Optimized DMD base class
- property dynamics: Tensor
- property modes
- predict(initial_condition: Tensor, n_steps: int) Tensor[source]
Predict evolution over N steps starting from user-defined initial conditions.
The prediction is performed as follows: 1) the initial conditions are projected on the first r POD modes 2) the time delay embedding is computed in the reduced space 3) the prediction is computed in the reduced space 4) the first r rows of the prediction are reconstructed
- Parameters:
initial_condition (pt.Tensor) – initial sequence of state vectors without time delay embedding; for d delays and a state vector of size M, the initial conditions should be given as a M x d matrix sorted such that the most recent state is contained in the last column
n_steps (int) – number of future steps to predict
- Returns:
predicted states; due to the structure of the linear operator some states are predicted multiple times; only the first M rows of the reconstruction are returned
- Return type:
pt.Tensor
- property reconstruction: Tensor
- property reconstruction_error: Tensor
flowtorch.analysis.linear_control
Implementation of a linear dynamics model with control inputs.
- class flowtorch.analysis.linear_control.LinearControlModel(data_matrix: Tensor, control_inputs: Tensor, dt: float)[source]
Bases:
Module- property A: Tensor
- property B: Tensor
- property amplitude: Tensor
- property dft_properties: Tuple[float, float, float]
- property dynamics: Tensor
- property eigvals: Tensor
- property eigvals_cont: Tensor
- property eigvecs: Tensor
- property forced_dynamics: Tensor
- forward(x0: Tensor, noise_idx: Tensor, c: Tensor, backward: bool) Tensor[source]
Predict a batch of controlled trajectories.
abbreviations B - batch size M - state vector size S - number of control inputs N - trajectory length without initial condition
- Parameters:
x0 (pt.Tensor) – batch of initial states of size B X M forward: x0 corresponds to state at time step 0 backward: x0 corresponds to state at time step N
noise_idx (pt.Tensor) – noise indices of size B corresponding to x0
c (pt.Tensor) – batch of control inputs of size B x S X N-1 forward: control time indices [0, 1, …, N-1] with x0 at 0 backward: control time indices [N-1, N-2, …, 0] with x0 at N
backward (bool) – True for rollouts backward in time
- Returns:
batch of trajectory predictions of size B x M x N
- Return type:
pt.Tensor
- property frequency: Tensor
- property growth_rate: Tensor
- property modes: Tensor
- predict(initial_condition: Tensor, control_inputs: Tensor) Tensor[source]
Predict trajectory for given initial condition and control inputs.
M - size of state vector S - number of control inputs N - number of prediction steps
- Parameters:
initial_condition (pt.Tensor) – initial state vector of size M
control_inputs (pt.Tensor) – control inputs of size S x N-1
- Raises:
ValueError – for non-matching initial conditions or control inputs
- Returns:
predicted trajectory of size N (including initial condition)
- Return type:
pt.Tensor
- property projection_error: Tensor
- property reconstruction: Tensor
- property reconstruction_error: Tensor
- train(epochs: int = 1000, batch_size: int | None = None, loss_function: Callable | None = None, split_options: dict = {}, scheduler_options: dict = {}, stopping_options: dict = {}, optimizer: Type[Optimizer] = <class 'torch.optim.adamw.AdamW'>, optimizer_options: dict = {}, loss_key: str = 'full_loss', device: str = 'cpu') None[source]
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Args:
- mode (bool): whether to set training mode (
True) or evaluation mode (
False). Default:True.
- mode (bool): whether to set training mode (
- Returns:
Module: self
- property unforced_dynamics: Tensor
flowtorch.analysis.linear_model
Implements a linear model of the form y = Ax.
- class flowtorch.analysis.linear_model.LinearModel(dm: Tensor | List[Tensor], dt: float, decompose_operator: bool = False, rank: int | None = None, init_forward_backward: bool = True, sigma_filter: None | float = None)[source]
Bases:
Module- property A: Tensor
- property amplitude: List[Tensor]
- property dynamics: List[Tensor]
- property eigvals: Tensor
- property eigvals_cont: Tensor
- property eigvecs: Tensor
- forward(x: Tensor, noise_idx: Tensor, n_steps: int, backward: bool) Tensor[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- property frequency: Tensor
- property growth_rate: Tensor
- property integral_contribution: List[Tensor]
- load_state_dict(*args, **kwargs)[source]
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dictunlessget_swap_module_params_on_conversion()isTrue.- Args:
- state_dict (dict): a dict containing parameters and
persistent buffers.
- strict (bool, optional): whether to strictly enforce that the keys
in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:True- assign (bool, optional): When set to
False, the properties of the tensors in the current module are preserved whereas setting it to
Truepreserves properties of the Tensors in the state dict. The only exception is therequires_gradfield ofParameterfor which the value from the module is preserved. Default:False
- Returns:
NamedTuplewithmissing_keysandunexpected_keysfields:missing_keysis a list of str containing any keys that are expectedby this module but missing from the provided
state_dict.
unexpected_keysis a list of str containing the keys that are notexpected by this module but present in the provided
state_dict.
- Note:
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- property log: dict
- property noise: Tuple[Tensor]
- property reconstruction: List[Tensor]
- property reconstruction_error: List[Tensor]
- top_modes(n: int = 10, integral: bool = False, f_min: float = -inf, f_max: float = inf) Tensor[source]
- train(epochs: int = 1000, batch_size: int | None = None, loss_function: Callable | None = None, split_options: dict = {}, scheduler_options: dict = {}, stopping_options: dict = {}, optimizer: Type[Optimizer] = <class 'torch.optim.adamw.AdamW'>, optimizer_options: dict = {}, loss_key: str = 'full_loss', device: str = 'cpu') None[source]
Set the module in training mode.
This has an effect only on certain modules. See the documentation of particular modules for details of their behaviors in training/evaluation mode, i.e., whether they are affected, e.g.
Dropout,BatchNorm, etc.- Args:
- mode (bool): whether to set training mode (
True) or evaluation mode (
False). Default:True.
- mode (bool): whether to set training mode (
- Returns:
Module: self
flowtorch.analysis.periodogram
Periodogram estimation techniques for scalar signals.
- class flowtorch.analysis.periodogram.AMPS(signal: Tensor, dt: float, nfft: int | None = None, adaptive: bool = True, max_tapers: int = 50, tolerance: float = 1e-05, subtract_mean: bool = True, verbose: bool = False)[source]
Bases:
ProvenanceMixinAdaptive multi-taper power spectrum estimation.
This class is a version of AMSPOD (adaptive multi-taper spectral POD) adjusted for scalar signals. The result is an estimate of the signal’s power spectrum, similar to Welch’s method. However, multiple realizations are estimated using sin-tapers rather than signal blocks (Welch). The main references for this implementation are:
Yeung, B. C. Y., Schmidt, O. T.: Adaptive spectral proper orthogonal decomposition of broadband-tonal flows, Theor. Comput. Fluid Dyn. 38, 355-374, 2024, DOI 10.1007/s00162-024-00695-0
Riedel, K. S., Sidorenko, A.: Minimum bias multiple taper spectral estimation, IEEE transactions of Signal Processing 43, 188-195, 1995, DOI 10.1109/78.365298
- property frequency: Tensor
DFT bin frequencies.
For real-valued input data, only positive frequencies are returned.
- Returns:
DFT bin frequencies
- Return type:
pt.Tensor
- property half_bandwidth: float | Tensor
Resulting sin-taper half-bandwidth.
The half-bandwidth quantifies the effective frequency resolution. A larger bandwidth leads to a greater smoothing of the spectrum. The effect of smoothing is lower variance (of the eigenvalues) but also poorer frequency resolution.
- Returns:
constant half-bandwidth if the number of windows is constant; otherwise, one half-bandwidth per frequency bin
- Return type:
Union[float, pt.Tensor]
- property log: dict
Log data stored throughout the computation.
- Returns:
dictionary with various useful logs
- Return type:
dict
- property residual: Tensor | None
Residual of the leading mode during adaptive refinement.
- Returns:
residual computed as
abs(power[k+1] - power[k]) / power[k+1]; since the number of tapers varies per bin, a tensor of size n_freq x (n_tapers - 2) is filled with NANs, and then the residuals are overwritten if available; (n_tapers - 2) is a consequence of the minimum number of tapers (2) and the residual being computed from the power change between two consecutive taper values, so in the first iteration, there is no sensible value to compare to- Return type:
pt.Tensor
- show_residual(reference_timescale: float | None = None, ax: Any = None, **kwargs: Any)[source]
Plot the adaptive power-estimate convergence residual.
For AMPS,
ris the change in the logarithmic power estimate at consecutive taper counts. Residuals are available only when adaptive taper selection was enabled.- Parameters:
reference_timescale (float, optional) – reference time used to plot Strouhal number
ax (matplotlib.axes.Axes, optional) – existing Matplotlib axes
kwargs – additional arguments for
plot_adaptive_residual
- Raises:
RuntimeError – if adaptive taper selection was disabled
- Returns:
modifiable Matplotlib figure and axes
- Return type:
Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
- property spectral_density: Tensor
Frequency-normalized spectral power estimate.
- Returns:
power spectral density
- Return type:
pt.Tensor
- property spectral_power: Tensor
Power estimate for all frequency bins.
The estimate is obtained by averaging the squared amplitudes. A correction for one-sided spectra is included.
- Returns:
spectral power estimate
- Return type:
pt.Tensor
- top_power(n: int = 1, f_min: float = -inf, f_max: float = inf) Tensor[source]
Get the indices of the first n frequency bins with the highest power.
- Parameters:
n (int) – number of indices to return; defaults to 1
f_min (float, optional) – consider only bins with a frequency larger or equal to f_min; defaults to -inf
f_max (float, optional) – consider only bins with a frequency smaller than f_max; defaults to -inf
- Returns:
indices of top n frequency bins sorted by spectral power
- Return type:
pt.Tensor
flowtorch.analysis.psp_explorer
Module with classes and functions to explore and analyse iPSP data.
- class flowtorch.analysis.psp_explorer.PSPExplorer(file_path: str)[source]
Bases:
objectExplore iPSP data interactively.
- interact(zone: str, field_name: str, times: list, mask: bool = True, width: int = 1024, every: int = 5, cmin: float = -2, cmax: float = 0.5) Figure[source]
Show selected snapshots of an iPSP file as interactive surface plot.
- Parameters:
zone (str) – name of the zone to display
field_name (str) – name of the field to display
times (list) – list of time instances to show
mask (bool, optional) – if True, the data is masked using the mask provided in the iPSP dataset, defaults to True
width (int, optional) – width of the plot, defaults to 1024
every (int, optional) – plot only every nth point, defaults to 5
cmin (float, optional) – lower bound for color range, defaults to -2
cmax (float, optional) – upper bound for color range, defaults to 0.5
- Returns:
interactive iPSP surface plot
- Return type:
go.Figure
- property loader: PSPDataloader
Get the PSPdataloader instance used to access data.
This property allows accessing the loader’s metadata via the explorer without having to create a new loader instance.
- Returns:
PSP dataloader instance
- Return type:
- mean(zone: str, field_name: str, times: list, mask: bool = True, width: int = 1024, every=5, cmin: float = -2, cmax: float = 0.5) Figure[source]
Show temporal mean of an iPSP file as interactive surface plot.
- Parameters:
zone (str) – name of the zone to display
field_name (str) – name of the field to display
times (list) – snapshot times over which to compute the mean
mask (bool, optional) – if True, the data is masked using the mask provided in the iPSP dataset, defaults to True
width (int, optional) – width of the plot, defaults to 1024
every (int, optional) – use only every nth point for plotting, defaults to 5
cmin (float, optional) – lower bound for color range, defaults to -2
cmax (float, optional) – upper bound for color range, defaults to 0.5
- Returns:
interactive iPSP surface plot showing the temporal mean
- Return type:
go.Figure
- std(zone: str, field_name: str, times: list, mask: bool = True, width: int = 1024, every=5, cmin: float = 0, cmax: float = 0.5) Figure[source]
Show temporal standard deviation as interactive surface plot.
- Parameters:
zone (str) – name of the zone to display
field_name (str) – name of the field to display
times (list) – snapshot times over which to compute the standard deviation
mask (bool, optional) – if True, the data is masked using the mask provided in the iPSP dataset, defaults to True
width (int, optional) – width of the plot, defaults to 1024
every (int, optional) – use only every nth point for plotting, defaults to 5
cmin (float, optional) – lower bound for color range, defaults to -2
cmax (float, optional) – upper bound for color range, defaults to 0.5
- Returns:
interactive iPSP surface plot
- Return type:
go.Figure
flowtorch.analysis.spod
PyTorch implementation of adaptive multi-taper SPOD.
The adaptive multi-taper spectral proper orthogonal decomposition (AMSPOD) uses a frequency-variable number of sine-tapers per bin. The main references are:
- Yeung, B. C. Y., Schmidt, O. T.: Adaptive spectral proper orthogonal decomposition
of broadband-tonal flows, Theor. Comput. Fluid Dyn. 38, 355-374, 2024, DOI 10.1007/s00162-024-00695-0
- Matlab implementation by the original authors available at:
https://github.com/SpectralPOD/spod_matlab/blob/master/spod_adapt.m
Compared to the original implementation, multiple realizations of the DFT are generated only by multiple tapers. There is no additional subdivision into overlapping blocks. Moreover, the compressed version is implemented as a lightweight derived class wrapping around the AMSPOD, termed PAMSPOD.
- class flowtorch.analysis.spod.AMSPOD(data_matrix: Tensor, dt: float, nfft: int | None = None, adaptive: bool = True, max_tapers: int = 50, tolerance: float = 1e-05, weight: Tensor | None = None, subtract_mean: bool = True, keep_n_modes: int = 3, device: str = 'cpu', verbose: bool = False)[source]
Bases:
ProvenanceMixinClass to manage AMSPOD computation without compression.
- property eigvals: Tensor
Eigenvalues of the cross-spectral density realizations.
the absolute value of each eigenvalue is returned
for real input data, all eigenvalues are doubled, except for zero and Nyquist frequencies to account for the energy content of the negative part of the spectrum
- Returns:
absolute value of eigenvalues accounting for one-sided spectra
- Return type:
pt.Tensor
- property frequency: Tensor
SPOD bin frequencies.
For real-valued input data, only positive frequencies are returned.
- Returns:
SPOD bin frequencies
- Return type:
pt.Tensor
- property half_bandwidth: float | Tensor
Resulting sin-taper half-bandwidth.
The half-bandwidth quantifies the effective frequency resolution. A larger bandwidth leads to a greater smoothing of the spectrum. The effect of smoothing is lower variance (of the eigenvalues) but also poorer effective frequency resolution.
- Returns:
constant half-bandwidth if the number of windows is constant; otherwise, one half-bandwidth per frequency bin
- Return type:
Union[float, pt.Tensor]
- property log: dict
Log data stored throughout the computation.
- Returns:
dictionary with various useful logs
- Return type:
dict
- mode_reconstruction(f_idx: int, eig_idx: int = 0, dt: float | None = None, N: int | None = None) Tensor[source]
Compute a time-domain reconstruction based on a single mode.
The mode is selected based on the frequency bin and the eigenbasis index. Note that the size of the eigenbasis may vary across frequency bins if adaptive=True. By default, one period is reconstructed at 25 equally spaced time values, including both period boundaries. For the zero-frequency mode, the original time step is used instead.
- Parameters:
f_idx (int) – frequency bin index
eig_idx (int, optional) – index of eigenvector-eigenvalue pair; defaults to 0, i.e., the most dominant mode at the selected frequency
dt (Union[float, None], optional) – optional reconstruction time step; defaults to None (distribute the time values over one period)
N (Union[int, None], optional) – optional number of time values; defaults to None (use 25)
- Raises:
ValueError – for invalid frequency bins
ValueError – for invalid eigenbasis index
ValueError – if the corresponding mode was not saved due to keep_n_modes
- Returns:
reconstruction based on a single mode
- Return type:
pt.Tensor
- mode_similarity(first_mode_idx: int = 0, second_mode_idx: int = 0) Tensor[source]
Compare two SPOD mode branches across all frequency bins.
Entry
(i, j)of the returned tensor is the normalized, absolute weighted inner product betweenfirst_mode_idxat frequency biniandsecond_mode_idxat frequency binj. Consequently, the result has shape(n_frequency, n_frequency). For equal mode indices it is symmetric, with a unit diagonal wherever the mode is available.AMSPOD modes are compared in the spatial inner product supplied at construction. PAMSPOD inherits this implementation and compares its reduced modes directly, which is equivalent to the weighted full-space product within the retained POD subspace.
Similarities involving a mode unavailable at an adaptive frequency bin are returned as NAN.
- Parameters:
first_mode_idx (int, optional) – mode index used along the first matrix axis, defaults to 0
second_mode_idx (int, optional) – mode index used along the second matrix axis, defaults to 0
- Raises:
ValueError – if either mode index is invalid or was not retained
- Returns:
frequency-by-frequency mode similarity matrix
- Return type:
pt.Tensor
- property modes: Tensor
Leading eigenvectors (modes) of the cross spectral density realizations.
- Returns:
user-defined number of eigenvectors; see keep_n_modes
- Return type:
pt.Tensor
- partial_reconstruction(f_min: int | float, f_max: int | float, n_modes: int = 1, start_idx: int = 0, n_snapshots: int = 100, add_mean: bool = False) Tensor[source]
Reconstruct snapshots from a subset of frequency bins and modes.
If both frequency limits are integers, they are interpreted as frequency-bin indices. Otherwise, they are interpreted as physical frequency values and all bins within the inclusive range are selected. The reconstruction is formed from the SPOD modes and their temporal coefficients. If fewer modes are available than requested, the number is reduced according to
temporal_coefficients().- Parameters:
f_min (Union[int, float]) – first frequency-bin index or minimum frequency to include
f_max (Union[int, float]) – last frequency-bin index or maximum frequency to include
n_modes (int, optional) – maximum number of leading modes to include per frequency bin; defaults to 1
start_idx (int, optional) – index of the first snapshot to reconstruct; defaults to 0
n_snapshots (int, optional) – maximum number of snapshots to reconstruct; defaults to 100
add_mean (bool, optional) – add the temporal mean if it was subtracted during the SPOD computation; defaults to False
- Raises:
ValueError – for invalid frequency-bin or snapshot indices
ValueError – if
n_modesorn_snapshotsis smaller than one
- Returns:
partial reconstruction arranged as
(n_spatial_points, n_reconstructed_snapshots)- Return type:
pt.Tensor
- property residual: Tensor | None
Residual of the leading mode during adaptive refinement.
- Returns:
residual computed as
abs(1 - mode_similarity); since the number of tapers varies per bin, a tensor of size n_freq x (n_tapers - 2) is filled with NANs, and then the residuals are overwritten if available; (n_tapers - 2) is a consequence of the minimum number of tapers (2) and the residual being computed from the mode similarity between two consecutive taper values, so in the first iteration, there is no sensible similarity- Return type:
pt.Tensor
- show_mode_similarity(first_mode_idx: int = 0, second_mode_idx: int = 0, reference_timescale: float | None = None, ax: Any = None, **kwargs: Any)[source]
Plot mode similarity across the SPOD frequency spectrum.
Symmetric matrices are shown as their lower triangle including the diagonal by default. Plot behavior can be changed with the
triangleargument accepted byflowtorch.visualization.plot_mode_similarity().- Parameters:
first_mode_idx (int, optional) – mode index used along the horizontal axis, defaults to 0
second_mode_idx (int, optional) – mode index used along the vertical axis, defaults to 0
reference_timescale (float, optional) – reference time used to plot Strouhal number
ax (matplotlib.axes.Axes, optional) – existing Matplotlib axes
kwargs – additional arguments for
plot_mode_similarity
- Returns:
modifiable Matplotlib figure and axes
- Return type:
Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
- show_residual(reference_timescale: float | None = None, ax: Any = None, **kwargs: Any)[source]
Plot the adaptive leading-mode convergence residual.
For AMSPOD,
ris the absolute difference between one and the leading-mode similarity at consecutive taper counts. Residuals are available only when adaptive taper selection was enabled.- Parameters:
reference_timescale (float, optional) – reference time used to plot Strouhal number
ax (matplotlib.axes.Axes, optional) – existing Matplotlib axes
kwargs – additional arguments for
plot_adaptive_residual
- Raises:
RuntimeError – if adaptive taper selection was disabled
- Returns:
modifiable Matplotlib figure and axes
- Return type:
Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
- show_spectrum(n_show: int = 3, show_sum: bool = True, reference_timescale: float | None = None, energy_density: bool = False, normalize_energy: bool = False, ax: Any = None, **kwargs: Any)[source]
Plot the SPOD eigenvalue spectrum and its half-bandwidth.
This convenience method passes
frequency,eigvals, andhalf_bandwidthtoflowtorch.visualization.plot_spod_spectrum(). The returned figure and axes remain fully modifiable.- Parameters:
n_show (int, optional) – maximum number of leading eigenvalues, defaults to 3
show_sum (bool, optional) – plot the sum over all eigenvalues, defaults to
Truereference_timescale (float, optional) – reference time used to plot against Strouhal number
energy_density (bool, optional) – convert bin energy to density in the displayed horizontal coordinate, defaults to
Falsenormalize_energy (bool, optional) – divide by the total resolved spectral energy, defaults to
Falseax (matplotlib.axes.Axes, optional) – existing Matplotlib axes
kwargs – additional arguments for
plot_spod_spectrum
- Returns:
modifiable Matplotlib figure and axes
- Return type:
Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
- show_time_coefficients(n_modes: int = 1, reference_timescale: float | None = None, ax: Any = None, **kwargs: Any)[source]
Plot the L2 amplitude of the SPOD temporal coefficients.
Temporal coefficients are computed by oblique projection before they are passed with
frequencyand the sampling times toflowtorch.visualization.plot_spod_time_coefficients(). Computing the coefficients can be substantially more expensive than plotting the eigenvalue spectrum.- Parameters:
n_modes (int, optional) – number of leading modes included per frequency, defaults to 1
reference_timescale (float, optional) – common scale for nondimensional time and frequency
ax (matplotlib.axes.Axes, optional) – existing Matplotlib axes
kwargs – additional arguments for
plot_spod_time_coefficients
- Returns:
modifiable Matplotlib figure and axes
- Return type:
Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
- temporal_coefficients(n_modes: int = 1) Tensor[source]
Compute SPOD time coefficients by oblique projection.
The leading
n_modesfrom all frequency bins are collected in a single non-orthogonal basis. The coefficients are obtained with the weighted oblique projection described in frequency-time SPOD analysis, i.e. by solving the normal equations for the weighted spatial modes. See Nekkanti, A. and Schmidt, O. T., “Frequency-time analysis, low-rank reconstruction and denoising of turbulent flows using SPOD”, Journal of Fluid Mechanics, 926, A26, 2021, https://doi.org/10.1017/jfm.2021.681.- Parameters:
n_modes (int, optional) – number of leading modes per frequency bin used in the projection; if larger than
keep_n_modesor, for adaptive SPOD, larger than the minimum number of available modes per bin, the value is reduced with a warning; defaults to 1- Raises:
ValueError – if
n_modesis smaller than one- Returns:
temporal coefficients arranged as
(n_frequency, n_modes, n_snapshots)- Return type:
pt.Tensor
- top_modes(n: int = 10, eig_idx: int | str = 0, f_min: float = -inf, f_max: float = inf, spacing: Literal['log', 'linear'] = 'log') Tensor[source]
Get the indices of dominant modes in frequency segments.
Segments can be equally spaced on a logarithmic or linear frequency coordinate. Negative frequencies are supported for both choices. Log spacing uses a signed logarithmic coordinate and omits the zero-frequency bin because it has no logarithmic representation. Linear spacing includes the zero-frequency bin when it is within the requested frequency range.
- Parameters:
n (int) – number of segments into which to divide the frequency range; defaults to 10
eig_idx (Union[int, str], optional) – eigenvalue index according to which to rank the modes; if
eig_idx="sum", the sum of all eigenvalues in a bin is used; for adaptive SPOD, the index is limited to the minimum number of tapers across all bins; defaults to 0f_min (float, optional) – consider only modes with a frequency larger or equal to f_min; defaults to -inf
f_max (float, optional) – consider only modes with a frequency smaller than f_max; defaults to inf
spacing (Literal["log", "linear"], optional) – distribute segment boundaries logarithmically or linearly in frequency; defaults to
"log"
- Raises:
ValueError – if
spacingis neither"log"nor"linear"- Returns:
frequency-bin index corresponding to the largest eigenvalue in each non-empty frequency segment
- Return type:
pt.Tensor
- class flowtorch.analysis.spod.PAMSPOD(data_matrix: Tensor | StateVectorSource, dt: float, nfft: int | None = None, adaptive: bool = True, max_tapers: int = 50, tolerance: float = 1e-05, weight: Tensor | None = None, subtract_mean: bool = True, keep_n_modes: int = 3, device: str = 'cpu', verbose: bool = False, rank: int | None = None, spatial_batch_size: int | None = None, execution: DistributedExecution | None = None, prefetch_chunks: bool = False)[source]
Bases:
AMSPODPerform AMSPOD on POD time coefficients.
Tensor inputs retain the original in-memory behavior. Passing a
StateVectorSourceuses the same spatially batched and optionally distributed SVD interface:spod = PAMSPOD( source, dt=0.001, rank=40, spatial_batch_size=100_000, execution=execution, ) for spatial_slice, fields in spod.get_mode(5).iter_chunks(split=True): velocity_mode = fields["U"]
- classmethod from_svd(svd: SVD, dt: float, nfft: int | None = None, adaptive: bool = True, max_tapers: int = 50, tolerance: float = 1e-05, keep_n_modes: int = 3, device: str = 'cpu', verbose: bool = False) PAMSPOD[source]
Construct PAMSPOD from an existing serial or distributed SVD.
The SVD’s temporal factors, centering, normalization, state layout, and spatial partition are reused without loading physical snapshots.
This avoids another SVD and does not read the physical snapshots while constructing PAMSPOD:
svd = SVD(source, rank=20, subtract_mean=True, execution=execution) spod = PAMSPOD.from_svd(svd, dt=0.001, keep_n_modes=3)
- get_mode(f_idx: int, mode_idx: int = 0) Tensor | StateVectorResult[source]
Get mode/eigenvector of prescribed frequency bin and mode index.
- Parameters:
f_idx (int) – index of the frequency bin
mode_idx (int, optional) – index of the sorted modes per frequency bin, defaults to 0
- Returns:
mode in full state space
- Return type:
pt.Tensor
- mode_reconstruction(f_idx: int, eig_idx: int = 0, dt: float | None = None, N: int | None = None) Tensor | StateVectorResult[source]
Compute time-domain reconstruction based on a single mode.
This method wraps around the corresponding method of the base class and projects the reconstruction back to the full state space.
- Parameters:
f_idx (int) – frequency bin index
eig_idx (int, optional) – index of eigenvector-eigenvalue pair; defaults to 0, i.e., the most dominant mode at the selected frequency
dt (Union[float, None], optional) – optional reconstruction time step; defaults to None (distribute the time values over one period)
N (Union[int, None], optional) – optional number of time values; defaults to None (use 25)
- Returns:
reconstruction based on a single mode
- Return type:
pt.Tensor
- property modes: Tensor | StateVectorResult
Project modes back to the original physical space.
- Returns:
SPOD modes in full state space
- Return type:
pt.Tensor
- partial_reconstruction(f_min: int | float, f_max: int | float, n_modes: int = 1, start_idx: int = 0, n_snapshots: int = 100, add_mean: bool = False) Tensor | StateVectorResult[source]
Reconstruct snapshots in full space from selected bins and modes.
See
AMSPOD.partial_reconstruction()for the argument definitions.- Returns:
partial reconstruction in the original state space
- Return type:
pt.Tensor
- flowtorch.analysis.spod.mode_similarity(first_modes: Tensor, second_modes: Tensor) Tensor[source]
Compute normalized similarities between two sets of modes.
Modes are arranged columnwise, with tensors of shape
(n_state, n_modes). The returned matrix contains the absolute normalized inner products\[\rho_{ij} = \frac{|\phi_i^*\psi_j|} {\|\phi_i\|_2\|\psi_j\|_2},\]and therefore has shape
(n_first_modes, n_second_modes). The absolute value makes the result invariant to the sign or complex phase of either mode. To compute similarities in a weighted inner product, multiply both mode sets by the square root of the weights before calling this function.Similarities involving zero-norm or non-finite modes are returned as NAN.
- Parameters:
first_modes (pt.Tensor) – first columnwise set of modes
second_modes (pt.Tensor) – second columnwise set of modes
- Raises:
ValueError – if either input is not two-dimensional, the state dimensions differ, or the tensors are on different devices
- Returns:
pairwise normalized mode similarities
- Return type:
pt.Tensor
flowtorch.analysis.propagation
Propagation quantities inferred from complex harmonic spatial modes.
- flowtorch.analysis.propagation.curvilinear_surface_phase_velocity(modes: Tensor, frequencies: float | Tensor, x: Tensor, y: Tensor, z: Tensor | None = None, amplitude_threshold: float = 0.05, min_wavenumber: float = 0.0, smoothing_sigma: float | Tuple[float, float] | None = None, smoothing_mode: str = 'reflect', smoothing_truncate: float = 3.0, edge_order: int = 2, metric_tolerance: float = 1e-12) Tensor[source]
Infer local phase velocity on a structured curvilinear surface.
A single complex mode has shape
(nx, ny). Multiple modes have shape(nx, ny, n_modes)and must be accompanied by a one-dimensional frequency tensor containing exactly one frequency per mode. A scalar frequency is accepted only for a single mode.For a mode \(\phi=a+ib=A\exp(i\theta)\), the phase gradient is
\[\nabla\theta = \frac{a\nabla b-b\nabla a}{a^2+b^2}.\]Assuming time dependence \(\exp(i 2\pi f t)\), the local phase velocity normal to the phase fronts is
\[\boldsymbol{c}_p = -2\pi f \frac{\nabla\theta}{\lVert\nabla\theta\rVert^2}.\]The result has shape
(nx, ny, 2)for a planar grid and(nx, ny, 3)for a surface embedded usingz. For multiple modes, the mode axis precedes the final vector-component axis. The result is a surface-tangential normal phase velocity, not a material or group velocity, and this function does not support three-dimensional volume grids.Real and imaginary parts are smoothed consistently before differentiation. Locations with weak modal amplitude, insufficient wavenumber, singular grid metrics, or non-finite intermediate values are filled with NAN.
- Parameters:
modes (pt.Tensor) – one complex mode with shape
(nx, ny)or multiple modes with shape(nx, ny, n_modes)frequencies (float or pt.Tensor) – scalar nonzero frequency for a single mode or one nonzero frequency per mode with shape
(n_modes,)x (pt.Tensor) – first Cartesian coordinate on the structured surface
y (pt.Tensor) – second Cartesian coordinate on the structured surface
z (pt.Tensor, optional) – optional third Cartesian coordinate of an embedded surface
amplitude_threshold (float, optional) – mask amplitudes below this fraction of each mode’s maximum amplitude; defaults to 0.05
min_wavenumber (float, optional) – mask phase-gradient magnitudes no larger than this value; defaults to 0
smoothing_sigma (float or Tuple[float, float], optional) – Gaussian width in grid-index units, applied to real and imaginary parts before differentiation
smoothing_mode (str, optional) – Gaussian boundary mode;
"reflect","replicate", or"circular"smoothing_truncate (float, optional) – Gaussian kernel radius in multiples of sigma
edge_order (int, optional) – finite-difference boundary accuracy, either 1 or 2
metric_tolerance (float, optional) – relative threshold for singular grid metrics
- Raises:
ValueError – for invalid mode, frequency, grid, or option inputs
- Returns:
local phase-velocity vectors
- Return type:
pt.Tensor
flowtorch.analysis.statistics
Batched statistics and trend analysis for snapshot sequences.
- class flowtorch.analysis.statistics.DistributedExecution(process_group: Any | None = None, root_rank: int = 0)[source]
Bases:
NamedTupleSelect collective execution for a statistics call.
The caller must initialize
torch.distributedbefore invoking a collective statistics operation.root_rankis relative to the selected process group and is the only rank that receives a result. The collective implementation is compatible with Gloo, NCCL, and MPI process groups.- process_group: Any | None
Alias for field number 0
- root_rank: int
Alias for field number 1
- class flowtorch.analysis.statistics.HistogramResult(histogram: Tensor, bin_edges: Tensor)[source]
Bases:
NamedTupleSpatiotemporal histogram values and bin edges.
- bin_edges: Tensor
Alias for field number 1
- histogram: Tensor
Alias for field number 0
- class flowtorch.analysis.statistics.LinearTrendResult(slope: Tensor, intercept: Tensor, r_squared: Tensor, normalized_change: Tensor, n_snapshots: int)[source]
Bases:
NamedTupleSpatial fields describing a least-squares linear temporal trend.
- intercept: Tensor
Alias for field number 1
- n_snapshots: int
Alias for field number 4
- normalized_change: Tensor
Alias for field number 3
- r_squared: Tensor
Alias for field number 2
- slope: Tensor
Alias for field number 0
- class flowtorch.analysis.statistics.MomentDependencyResult(fractions: Tensor, n_snapshots: Tensor, reduced_moments: Tensor, field_difference_norms: Tensor, final_fields: MomentFields, intermediate_fields: MomentFields | None)[source]
Bases:
NamedTupleFraction-dependent moments and consecutive spatial differences.
reduced_momentshas shape(n_fractions, 4)in the order given byMOMENT_NAMES.field_difference_normshas shape(n_fractions - 1, 4)and compares each fraction with its predecessor.- field_difference_norms: Tensor
Alias for field number 3
- final_fields: MomentFields
Alias for field number 4
- fractions: Tensor
Alias for field number 0
- intermediate_fields: MomentFields | None
Alias for field number 5
- n_snapshots: Tensor
Alias for field number 1
- reduced_moments: Tensor
Alias for field number 2
- class flowtorch.analysis.statistics.MomentFields(mean: Tensor, variance: Tensor, skewness: Tensor, kurtosis: Tensor)[source]
Bases:
NamedTupleMean, population variance, skewness, and Pearson kurtosis fields.
- kurtosis: Tensor
Alias for field number 3
- mean: Tensor
Alias for field number 0
- skewness: Tensor
Alias for field number 2
- variance: Tensor
Alias for field number 1
- class flowtorch.analysis.statistics.RunningMoments(snapshot_dim: int = -1, accumulator_dtype: dtype | None = None)[source]
Bases:
ProvenanceMixinAccumulate the first four moments from batches of snapshots.
Batches are combined using stable parallel central-moment formulas. The retained state consists of a count, mean, and the unnormalized central moments M2, M3, and M4.
- property count: int
Number of accumulated snapshots.
- finalize() MomentFields[source]
Return the four conventional moment fields.
- merge(other: RunningMoments) None[source]
Merge another compatible accumulator into this instance.
- class flowtorch.analysis.statistics.SnapshotStatisticsResult(moments: MomentFields | None, moment_dependency: MomentDependencyResult | None, trend: LinearTrendResult | None, spatial_statistics: SpatialStatisticsResult | None, histogram: HistogramResult | None)[source]
Bases:
NamedTupleResults produced by
snapshot_statistics().Fields excluded through
computeareNone. Requesting dependency statistics also populatesmomentsfrom the dependency’s final fields.- histogram: HistogramResult | None
Alias for field number 4
- moment_dependency: MomentDependencyResult | None
Alias for field number 1
- moments: MomentFields | None
Alias for field number 0
- spatial_statistics: SpatialStatisticsResult | None
Alias for field number 3
- trend: LinearTrendResult | None
Alias for field number 2
- class flowtorch.analysis.statistics.SpatialStatisticsResult(minimum: Tensor, maximum: Tensor, mean: Tensor, quantiles: Tensor, quantile_levels: Tensor)[source]
Bases:
NamedTupleSpatially reduced statistics for every snapshot.
minimum,maximum, andmeanhave shape(n_snapshots,).quantileshas shape(n_quantiles, n_snapshots)and follows the probabilities stored inquantile_levels.- maximum: Tensor
Alias for field number 1
- mean: Tensor
Alias for field number 2
- minimum: Tensor
Alias for field number 0
- quantile_levels: Tensor
Alias for field number 4
- quantiles: Tensor
Alias for field number 3
- flowtorch.analysis.statistics.detect_linear_trend(result: LinearTrendResult, min_normalized_change: float, min_r_squared: float = 0.5) Tensor[source]
Classify trends using explicit effect-size and fit thresholds.
- Parameters:
result (LinearTrendResult) – output of
linear_trend()min_normalized_change (float) – minimum absolute fitted total change in temporal standard deviations
min_r_squared (float, optional) – minimum explained variance, defaults to 0.5
- Returns:
boolean spatial trend mask
- Return type:
pt.Tensor
- flowtorch.analysis.statistics.linear_trend(source: Tensor | Callable[[int, int], Tensor], n_snapshots: int | None = None, time: Tensor | Sequence[float] | None = None, batch_size: int = 32, snapshot_dim: int = -1, accumulator_dtype: dtype | None = None, spatial_mask: Tensor | None = None, execution: DistributedExecution | None = None) LinearTrendResult | None[source]
Fit a batched linear temporal trend at every spatial location.
normalized_changeis the fitted change across the complete time span divided by the temporal population standard deviation. Masked locations are returned asNaN. A callable source follows the same indexedsource(start, stop)contract asmoment_data_dependency().Global time values are sliced with the distributed snapshot ranges:
result = linear_trend( source, n_snapshots=100_000, time=time, execution=DistributedExecution(root_rank=0), ) if result is not None: mask = detect_linear_trend(result, 1.0)
- Parameters:
source (Union[pt.Tensor, Callable[[int, int], pt.Tensor]]) – snapshot tensor or indexed batch callable
n_snapshots (int, optional) – total count required for a callable source
time (Union[pt.Tensor, Sequence[float]], optional) – strictly increasing snapshot times; indices are the default
batch_size (int, optional) – maximum snapshots loaded together, defaults to 32
snapshot_dim (int, optional) – dimension containing snapshots, defaults to
-1accumulator_dtype (pt.dtype, optional) – optional floating-point accumulation dtype
spatial_mask (pt.Tensor, optional) – boolean mask selecting spatial locations
execution (DistributedExecution, optional) – optional collective execution policy
- Returns:
spatial fields describing the linear fit
- Return type:
- flowtorch.analysis.statistics.moment_data_dependency(source: Tensor | Callable[[int, int], Tensor], n_snapshots: int | None = None, fractions: Sequence[float] = (0.25, 0.5, 0.75, 1.0), batch_size: int = 32, snapshot_dim: int = -1, spatial_weight: Tensor | None = None, spatial_mask: Tensor | None = None, spatial_reduction: Literal['mean', 'rms'] = 'mean', keep_intermediate_fields: bool = False, accumulator_dtype: dtype | None = None, execution: DistributedExecution | None = None) MomentDependencyResult | None[source]
Compute fraction-dependent moments in one forward batched pass.
Every checkpoint field is reduced spatially. Weighted spatial L2 norms monitor field changes between consecutive fractions. Only the final fields are retained unless
keep_intermediate_fieldsis enabled. Masked field locations remain in the output asNaNbut do not enter any reduction. A callable source accepts integerstartandstopindices and returns the corresponding snapshot batch.Distributed fractions refer to prefixes of the global snapshot sequence:
result = moment_data_dependency( source, n_snapshots=100_000, fractions=(0.25, 0.5, 0.75, 1.0), execution=DistributedExecution(root_rank=0), )
- Parameters:
source (Union[pt.Tensor, Callable[[int, int], pt.Tensor]]) – snapshot tensor or indexed batch callable
n_snapshots (int, optional) – total count required for a callable source
fractions (Sequence[float], optional) – increasing data fractions ending in 1.0
batch_size (int, optional) – maximum snapshots loaded together, defaults to 32
snapshot_dim (int, optional) – dimension containing snapshots, defaults to
-1spatial_weight (pt.Tensor, optional) – non-negative spatial integration weights
spatial_mask (pt.Tensor, optional) – boolean mask selecting spatial locations
spatial_reduction (str, optional) – weighted
"mean"or"rms"keep_intermediate_fields (bool, optional) – retain all non-final checkpoint fields
accumulator_dtype (pt.dtype, optional) – optional floating-point accumulation dtype
execution (DistributedExecution, optional) – optional collective execution policy
- Returns:
reduced moments, consecutive difference norms, and fields
- Return type:
- flowtorch.analysis.statistics.snapshot_statistics(source: Tensor | Callable[[int, int], Tensor], n_snapshots: int | None = None, *, time: Tensor | Sequence[float] | None = None, fractions: Sequence[float] = (0.25, 0.5, 0.75, 1.0), quantiles: Sequence[float] = (0.05, 0.1, 0.25, 0.5, 0.75, 0.95), histogram_bins: int | Sequence[float] | Tensor = 50, histogram_range: Sequence[float] | None = None, batch_size: int = 32, snapshot_dim: int = -1, spatial_weight: Tensor | None = None, spatial_mask: Tensor | None = None, spatial_reduction: Literal['mean', 'rms'] = 'mean', keep_intermediate_fields: bool = False, density: bool = False, accumulator_dtype: dtype | None = None, compute: Sequence[str] = ('moments', 'dependency', 'trend', 'spatial', 'histogram'), execution: DistributedExecution | None = None) SnapshotStatisticsResult | None[source]
Compute selected snapshot statistics through a shared batch stream.
With explicit histogram edges or
histogram_range, every enabled statistic consumes the same loaded batch and the source is traversed once. An exact automatically ranged histogram requires one additional pass that updates only histogram counts.spatial_maskrestricts every collector to its true locations. Spatial field outputs retain their original shape and containNaNoutside the mask. Non-finite data outside the mask is ignored.Distributed execution partitions globally indexed snapshots among the selected process-group ranks. Only
execution.root_rankreturns a result. For example, after initializingtorch.distributed:execution = DistributedExecution(root_rank=0) result = snapshot_statistics( source, n_snapshots=100_000, batch_size=16, histogram_range=(-5.0, 5.0), execution=execution, ) if result is not None: print(result.moments.mean)
- Parameters:
source – snapshot tensor or globally indexed batch callable
n_snapshots – total snapshot count required for a callable source
time – strictly increasing global snapshot times
fractions – increasing dependency fractions ending in 1.0
quantiles – increasing spatial quantile probabilities
histogram_bins – histogram bin count or explicit edges
histogram_range – optional range for integer histogram bins
batch_size – maximum snapshots loaded by each rank at once
snapshot_dim – dimension containing snapshots
spatial_weight – non-negative spatial weights
spatial_mask – boolean mask selecting spatial locations
spatial_reduction – dependency reduction,
"mean"or"rms"keep_intermediate_fields – retain dependency checkpoint fields
density – normalize histogram counts to a density
accumulator_dtype – optional moment and trend accumulation dtype
compute – selected statistics; all are enabled by default
execution – optional collective execution policy
- Returns:
selected results on the serial or distributed root process
- flowtorch.analysis.statistics.spatial_statistics(source: Tensor | Callable[[int, int], Tensor], n_snapshots: int | None = None, quantiles: Sequence[float] = (0.05, 0.1, 0.25, 0.5, 0.75, 0.95), batch_size: int = 32, snapshot_dim: int = -1, spatial_weight: Tensor | None = None, spatial_mask: Tensor | None = None, execution: DistributedExecution | None = None) SpatialStatisticsResult | None[source]
Compute weighted spatial statistics for every snapshot in batches.
Quantiles use linear interpolation over weighted sample midpoints
\[p_i = \frac{\sum_{j \leq i} w_j - w_i/2}{\sum_j w_j}.\]Values outside the midpoint range are clamped to the spatial minimum or maximum. Locations with zero weight or a false spatial mask do not contribute to any statistic. A callable source follows the indexed
source(start, stop)contract ofmoment_data_dependency().In a distributed run, the callback remains globally indexed and only the configured root receives the concatenated time series:
result = spatial_statistics( source, n_snapshots=100_000, execution=DistributedExecution(root_rank=0), )
- Parameters:
source (Union[pt.Tensor, Callable[[int, int], pt.Tensor]]) – snapshot tensor or indexed batch callable
n_snapshots (int, optional) – total count required for a callable source
quantiles (Sequence[float], optional) – increasing probabilities in
[0, 1]batch_size (int, optional) – maximum snapshots loaded together, defaults to 32
snapshot_dim (int, optional) – dimension containing snapshots, defaults to
-1spatial_weight (pt.Tensor, optional) – non-negative spatial weights
spatial_mask (pt.Tensor, optional) – boolean mask selecting spatial locations
execution (DistributedExecution, optional) – optional collective execution policy
- Returns:
spatial statistic time series
- Return type:
- flowtorch.analysis.statistics.spatiotemporal_histogram(source: Tensor | Callable[[int, int], Tensor], n_snapshots: int | None = None, bins: int | Sequence[float] | Tensor = 50, value_range: Sequence[float] | None = None, batch_size: int = 32, snapshot_dim: int = -1, spatial_weight: Tensor | None = None, spatial_mask: Tensor | None = None, density: bool = False, execution: DistributedExecution | None = None) HistogramResult | None[source]
Compute a histogram reduced across space and time in batches.
Every snapshot has equal temporal weight. If
spatial_weightis given, the weight of each spatial location is applied once per snapshot. Locations with zero weight or a false spatial mask are excluded. Counts are returned by default. Withdensity=True, bin values are normalized so that\[\sum_i h_i \Delta x_i = 1.\]Integer bins with no
value_rangerequire two batched passes over the source: one to discover the exact global range and one to accumulate the histogram. Explicit edges or a value range require only one pass. Bins are left-inclusive and right-exclusive, except for the final bin, which also includes its upper edge.For distributed execution, all ranks call the function and only the root receives the global histogram:
result = spatiotemporal_histogram( source, n_snapshots=100_000, bins=50, value_range=(-5.0, 5.0), execution=DistributedExecution(root_rank=0), )
- Parameters:
source (Union[pt.Tensor, Callable[[int, int], pt.Tensor]]) – snapshot tensor or indexed batch callable
n_snapshots (int, optional) – total count required for a callable source
bins (Union[int, Sequence[float], pt.Tensor], optional) – positive bin count or strictly increasing edges, defaults to 50
value_range (Sequence[float], optional) – minimum and maximum for integer bins
batch_size (int, optional) – maximum snapshots loaded together, defaults to 32
snapshot_dim (int, optional) – dimension containing snapshots, defaults to
-1spatial_weight (pt.Tensor, optional) – non-negative spatial weights
spatial_mask (pt.Tensor, optional) – boolean mask selecting spatial locations
density (bool, optional) – normalize by total weight and bin width, defaults to False
execution (DistributedExecution, optional) – optional collective execution policy
- Returns:
histogram values and bin edges
- Return type:
- flowtorch.analysis.statistics.statistical_moments(data: Tensor | Callable[[int, int], Tensor], snapshot_dim: int = -1, batch_size: int = 32, accumulator_dtype: dtype | None = None, *, n_snapshots: int | None = None, spatial_mask: Tensor | None = None, execution: DistributedExecution | None = None) MomentFields | None[source]
Compute mean, variance, skewness, and kurtosis in batches.
A spatial mask preserves the field shape and fills excluded locations with
NaN. Non-finite snapshot values are permitted only outside the mask.A distributed call uses the same interface:
result = statistical_moments( source, n_snapshots=100_000, execution=DistributedExecution(root_rank=0), ) if result is not None: print(result.variance)
- Parameters:
data (Union[pt.Tensor, Callable[[int, int], pt.Tensor]]) – snapshot tensor or globally indexed batch callable
snapshot_dim (int, optional) – dimension containing snapshots, defaults to
-1batch_size (int, optional) – maximum snapshots processed together, defaults to 32
accumulator_dtype (pt.dtype, optional) – optional floating-point accumulation dtype
n_snapshots (int, optional) – global count required for a callable source
spatial_mask (pt.Tensor, optional) – boolean mask selecting spatial locations
execution (DistributedExecution, optional) – optional collective execution policy
- Returns:
four spatial moment fields
- Return type:
flowtorch.analysis.utils
Common functionality shared by multiple analysis tools.
- class flowtorch.analysis.utils.EarlyStopping(patience: int = 40, min_delta: float = 0.0001, checkpoint: str | None = None, model: Module | None = None)[source]
Bases:
objectProvide stopping control for iterative optimization tasks.