autots.evaluator.tva package¶
Submodules¶
autots.evaluator.tva.decomposition module¶
NornDecomposer — Wraps TimeSeriesFeatureDetector for TVA decomposition.
In the spirit of structural weaving, this class decomposes time series into constituent threads (trend, seasonality, noise, etc.) for joint forecasting.
- class autots.evaluator.tva.decomposition.NornDecomposer(detector_params: dict | None = None, holiday_country=None, holiday_countries: dict | None = None)¶
Bases:
objectWraps TimeSeriesFeatureDetector to extract structured component DataFrames.
Produces trend, seasonality, holidays, level_shifts, anomalies, and noise as aligned DataFrames sharing the same index and columns as the input.
- Parameters:
detector_params – Dict of kwargs passed to TimeSeriesFeatureDetector.__init__.
- fit(df: DataFrame) NornDecomposer¶
Fit the feature detector on a wide DataFrame.
- Parameters:
df – Wide DataFrame with DatetimeIndex and one numeric column per series.
- Returns:
self
- get_components() dict¶
Extract decomposition components as DataFrames.
- Returns:
Dict with keys ‘trend’, ‘seasonality’, ‘holidays’, ‘level_shifts’, ‘anomalies’, ‘noise’. Each value is a DataFrame (T, N) aligned with the original input index and columns.
- get_features() dict¶
Return the full detected features dict from the underlying detector.
Includes changepoints, holiday impacts, anomaly records, etc. Useful for constructing priors or inspecting detection results.
- get_forecast_components(forecast_length: int) dict¶
Forward-project seasonality, holidays, level shifts, and trend.
Uses the detector’s built-in forecast method to project known deterministic components into the future.
- Parameters:
forecast_length – Number of future periods to project.
- Returns:
Dict with same keys as get_components(), each a DataFrame of shape (forecast_length, N).
autots.evaluator.tva.fusion module¶
Digital Twin Fusion — Component Recombination.
Reconstructs full forecasts by combining trend network output with seasonality, holidays, level shifts, and anomalies. Different variants (attention-weighted or additive) serve as the final weaving mechanism.
autots.evaluator.tva.losses module¶
TVA Loss Functions — The Allfather’s Judgment.
Six loss components that together enforce coherent, high-quality composite trends.
autots.evaluator.tva.priors module¶
YggdrasilPriors — Prior specification and encoding for the TVA graph.
Acts as the ‘world tree’ for the forecasting graph, connecting related time series across different domains through shared metadata.
- class autots.evaluator.tva.priors.SeriesMetadata(name: str, attribute_values: Dict[str, str] | None = None, hierarchy_path: list | None = None, history_periods: int = 0, metric_type: str | None = None, surface: str | None = None, geography: str | None = None)¶
Bases:
objectMetadata descriptor for a single time series.
- name¶
Series identifier matching DataFrame column name.
- Type:
str
- attribute_values¶
Arbitrary categorical metadata for the series.
- Type:
Dict[str, str]
- hierarchy_path¶
Ordered path from root to leaf (e.g. [‘global’, ‘NA’, ‘US’]).
- Type:
list | None
- history_periods¶
Number of observed time periods available.
- Type:
int
- attribute_values: Dict[str, str]¶
- property geography: str | None¶
- hierarchy_path: list | None¶
- history_periods: int = 0¶
- property metric_type: str | None¶
- name: str¶
- property surface: str | None¶
- class autots.evaluator.tva.priors.YggdrasilPriors(series_metadata: list | None = None, relationship_matrix: ndarray | None = None, prior_confidence: float = 0.3, detected_features: dict | None = None, trend_data: DataFrame | None = None, observed_history: Dict[str, int] | None = None, prior_construction_config: dict | None = None, causal_prior_construction_config: dict | None = None, series_names: list | None = None)¶
Bases:
objectConstructs prior adjacency matrices, metadata embeddings, and hierarchy matrices from series metadata. All methods return sensible defaults when metadata is absent, so TVA runs with or without priors.
- Parameters:
series_metadata – List of SeriesMetadata, one per series.
relationship_matrix – Optional (N, N) soft prior adjacency override.
prior_confidence – Weight of prior vs learned structure (0=ignore, 1=rigid).
- build_causal_prior_adjacency() ndarray | None¶
Construct a directed causal prior from decomposed trend components.
- build_hierarchy_matrix() ndarray¶
Build summing matrix S for hierarchical reconciliation.
S has shape (L, M) where L = total nodes (aggregates + bottom), M = number of bottom-level series. Compatible with mint_reconcile(S, y_all, W).
Returns identity if no hierarchy paths are specified.
- build_metadata_embeddings() ndarray¶
Build (N, D_meta) one-hot embedding matrix from categorical metadata.
Encodes arbitrary categorical metadata keys as concatenated one-hot vectors. Returns zeros if no metadata is available.
- build_prior_adjacency() ndarray | None¶
Backward-compatible alias for structural prior construction.
- build_structural_prior_adjacency() ndarray | None¶
Construct a soft structural prior from explicit, metadata, and event sources.
- get_anchor_mask(min_history: int) ndarray¶
Return boolean mask (N,) where True = series has enough history to be an anchor.
Anchors shape the core latent trend graph. Responders inherit composite trends but do not perturb the core geometry.
- get_series_names() list¶
Return ordered list of series names.
- property n_series¶
autots.evaluator.tva.reconciliation module¶
ReconciliationBridge — Bridge to AutoTS hierarchical reconciliation.
Thin adapter between TVA forecasts and the reconciliation functions in autots/tools/hierarchial.py (mint_reconcile, erm_reconcile, etc.).
- class autots.evaluator.tva.reconciliation.ReconciliationBridge(method: str = 'mint', covariance_method: str = 'ledoit_wolf')¶
Bases:
objectBridges TVA forecasts to hierarchical reconciliation methods.
Handles S matrix construction, covariance estimation, and method dispatch.
- Parameters:
method – Reconciliation method (‘mint’, ‘erm’, ‘iterative_mint’, ‘volatility_mint’). Default ‘mint’.
covariance_method – How to estimate W (‘ledoit_wolf’, ‘identity’, ‘sample’).
- reconcile(forecasts: DataFrame, S: ndarray, residuals: ndarray | None = None) DataFrame¶
Apply hierarchical reconciliation to forecast DataFrame.
- Parameters:
forecasts – (T, L) DataFrame with all hierarchy levels. Columns should be ordered: aggregate nodes first, then bottom nodes, matching the row order of S.
S – (L, M) summing matrix from YggdrasilPriors.build_hierarchy_matrix().
residuals – (T_hist, L) historical residuals for covariance estimation. If None, uses identity covariance.
- Returns:
Reconciled DataFrame with same shape and columns as input.
- reconcile_with_volatility(forecasts: DataFrame, S: ndarray, residuals: ndarray, cov_bottom: ndarray | None = None, volatility_method: str = 'variance', volatility_power: float = 1.0, alpha: float = 0.5) DataFrame¶
Volatility-weighted reconciliation for covariance-aware adjustment.
- Parameters:
forecasts – (T, L) DataFrame.
S – (L, M) summing matrix.
residuals – (T_hist, L) historical residuals.
cov_bottom – (M, M) bottom-level covariance. Estimated if None.
volatility_method – ‘variance’, ‘std’, or ‘cv’.
volatility_power – Power to raise volatility weights to.
alpha – Blend between standard W and volatility weights.
- Returns:
Reconciled DataFrame.
autots.evaluator.tva.scenario module¶
BifrostOptimizer — What-If Scenario Planning.
Freezes all network weights and optimizes a latent perturbation to satisfy user-specified constraints while minimizing disruption to the forecast.
- class autots.evaluator.tva.scenario.BifrostOptimizer(tva_model, n_steps: int = 50, lr: float = 0.01)¶
Bases:
objectInference-time optimizer for scenario planning / what-if analysis.
Freezes all network weights. Creates an optimizable perturbation in latent space and runs gradient descent to satisfy user constraints while minimizing total perturbation. The perturbation penalty is covariance-weighted: high-variance components absorb more of the adjustment, protecting high-confidence elements.
- Parameters:
tva_model – Fitted TVA instance.
n_steps – Number of optimization steps.
lr – Learning rate for the perturbation optimizer.
- apply_constraint(series_name: str, timestep: int, target_value: float) DataFrame¶
Pin a specific series at a specific timestep to a target value.
- Parameters:
series_name – Column name of the series to constrain.
timestep – Forecast timestep index (0-based).
target_value – Desired value at that timestep.
- Returns:
Adjusted forecast DataFrame for ALL series.
- apply_growth_constraint(series_name: str, growth_rate: float) DataFrame¶
Constrain a series to a specific growth rate over the forecast horizon.
- Parameters:
series_name – Column name.
growth_rate – Desired growth rate (e.g. 0.05 for 5% growth).
- Returns:
Adjusted forecast DataFrame.
- apply_hierarchical_adjustment(level_name: str, target_value: float, hierarchy_matrix: ndarray | None = None) DataFrame¶
Set an aggregate level to target_value and propagate down proportionally.
This is an adjustment (set to exactly target_value at every timestep), not a constraint (threshold/clamp that only fires when exceeded).
The delta between target_value and the current aggregate sum is distributed to constituent bottom-level series proportional to their current share of that aggregate. When the current aggregate is near zero, the delta is split equally across constituent series.
- Parameters:
level_name – Name of the aggregate node to adjust, matched against the last component of hierarchy path tuples (e.g. ‘global’, ‘NA’, ‘EU’). If multiple nodes share the same last component, the first (shallowest) match is used.
target_value – Desired flat aggregate value applied across all forecast timesteps. The constituent series are scaled so their sum equals this value at every step.
hierarchy_matrix – (L, M) summing matrix S. If None, built automatically from priors configured at fit time. Required when no series metadata was provided.
- Returns:
Adjusted forecast DataFrame (same shape as predict()), with constituent series modified so their aggregate sum equals target_value.
autots.evaluator.tva.structure module¶
Structure learning helpers for TVA.
This module keeps graph discovery, hierarchy discovery, export, and plotting separate from the forecast orchestration layer so new approaches can be swapped in without rewriting the TVA training loop.
- class autots.evaluator.tva.structure.GraphSnapshot(node_table: list, edge_table: list, adjacency_dense: ndarray, adjacency_thresholded: ndarray, assignment_matrices: list, topological_order: list, prior_adjacency: ndarray | None, is_acyclic: bool, cycle_score: float)¶
Bases:
objectSerializable export of learned TVA structure.
- adjacency_dense: ndarray¶
- adjacency_thresholded: ndarray¶
- assignment_matrices: list¶
- cycle_score: float¶
- edge_table: list¶
- is_acyclic: bool¶
- node_table: list¶
- prior_adjacency: ndarray | None¶
- to_dict() dict¶
- topological_order: list¶
- class autots.evaluator.tva.structure.StructureLearningConfig(enabled: bool = False, learn_hierarchy: bool = True, learn_dag: bool = True, max_levels: int = 3, pool_ratio: float = 0.5, min_nodes_per_level: int = 2, dag_penalty: float = 0.1, dag_warmup_epochs: float = 0.2, sparsity_weight: float = 0.01, assignment_entropy_weight: float = 0.01, assignment_full_rank_weight: float = 0.01, prior_tether_weight: float = 0.05, temporal_drift_weight: float = 0.0, threshold_for_export: float = 0.2)¶
Bases:
objectOpt-in configuration for TVA structure discovery.
- assignment_entropy_weight: float = 0.01¶
- assignment_full_rank_weight: float = 0.01¶
- dag_penalty: float = 0.1¶
- dag_warmup_epochs: float = 0.2¶
- derive_latent_sizes(n_anchor: int, fallback_sizes: list | None = None) list¶
Return deterministic latent widths from anchor count.
The returned list excludes the input anchor level and contains only derived latent widths ordered bottom-up.
- enabled: bool = False¶
- classmethod from_dict(config: dict | None = None) StructureLearningConfig¶
- learn_dag: bool = True¶
- learn_hierarchy: bool = True¶
- max_levels: int = 3¶
- min_nodes_per_level: int = 2¶
- pool_ratio: float = 0.5¶
- prior_tether_weight: float = 0.05¶
- sparsity_weight: float = 0.01¶
- structure_scale(epoch_index: int, total_epochs: int) float¶
- temporal_drift_weight: float = 0.0¶
- threshold_for_export: float = 0.2¶
- to_dict() dict¶
- warmup_start_epoch(total_epochs: int) int¶
- autots.evaluator.tva.structure.build_graph_snapshot(adjacency_dense: ndarray, assignment_matrices: list | None = None, threshold: float = 0.2, prior_adjacency: ndarray | None = None, anchor_names: list | None = None) GraphSnapshot¶
Create a serializable snapshot from TVA structure state.
- autots.evaluator.tva.structure.plot_graph_snapshot(snapshot: GraphSnapshot, view: str = 'dag', max_edges: int = 50, show_priors: bool = False, ax=None)¶
Render a TVA structure snapshot with matplotlib.
- autots.evaluator.tva.structure.topological_order_from_adjacency(adjacency: ndarray) list¶
Return a node ordering if the graph is acyclic, otherwise [].
autots.evaluator.tva.trend_network module¶
Composite Trend Network — The Sacred Timeline.
V1: Hierarchical Latent Trend Graph (deterministic structure). V2: Learned Directed Composite Graph (learned adjacency, adaptive prototypes).
The trend network operates only on isolated trend components, not raw series. It compresses per-series trends into a small set of shared composite prototypes and reconstructs per-series trend forecasts that are structurally consistent with those shared states.
autots.evaluator.tva.tva module¶
TVA — Time Variant Architecture.
Top-level orchestrator for the TVA forecasting graph. Ties together decomposition, priors, trend network, fusion, losses, reconciliation, and scenario planning into a single fit/predict interface.
Note a wrapper exists in /autots/models/tva_model.py for the AutoTS search integration.
Some reference papers: https://www.mdpi.com/2227-7390/13/20/3288 https://openreview.net/pdf?id=GYSG2vF6z5 https://arxiv.org/html/2409.10996v2 https://arxiv.org/html/2507.15119v2#S4 https://www.researchgate.net/profile/Jawad-Chowdhury-6/publication/379087074_CD-_NOTEAR[…]N0UGFnZSI6InB1YmxpY2F0aW9uIiwicGFnZSI6InB1YmxpY2F0aW9uIn19 https://openreview.net/pdf?id=80g3Yqlo1a https://openreview.net/pdf?id=WjDjem8mWE
- class autots.evaluator.tva.tva.TVA(detector_params: dict | None = None, trend_network: str = 'v2', fusion: str = 'attention', series_metadata: list | None = None, prior_adjacency: ndarray | None = None, prior_confidence: float = 0.3, causal_prior: ndarray | None = None, prior_construction_config: dict | None = None, causal_prior_construction_config: dict | None = None, d_token: int = 64, n_meso: int | str = 'auto', n_global: int | str = 'auto', n_prototypes: int | str = 'auto', n_heads: int = 4, epochs: int = 50, lr: float = 0.001, batch_size: int = 32, window_size: int = 91, forecast_horizon: int = 28, loss_weights: dict | None = None, reconciliation_method: str | None = None, min_anchor_history: int = 180, holiday_country=None, holiday_countries: dict | None = None, device: str = 'cpu', random_seed: int = 42, verbose: int = 1, prototype_assignment_method: str = 'cosine', prototype_assignment_temperature: float = 1.0, structure_learning_config: dict | None = None)¶
Bases:
objectTime Variant Architecture — end-to-end coherent forecasting graph.
The Common Operating Picture for time series. Produces structurally consistent forecasts across related series by routing all trends through shared composite prototypes. For all Time. Always.
- Parameters:
detector_params – Dict passed to TimeSeriesFeatureDetector.
trend_network – ‘v1’ (hierarchical latent) or ‘v2’ (learned directed).
fusion –
How stochastic components (trend, seasonality, holidays) are recombined before level shifts are added additively. ‘attention’ (default): DigitalTwinFusion — self-attention contextualizes
component embeddings; sigmoid gates independently fade each component in/out (gate in [0,1]) applied to the original values.
- ’direct’: DirectAttentionFusion — self-attention contextualizes component
embeddings; attended representations are projected directly to scalar contributions summed as a residual over the originals. More purely attention-driven; zero-init ensures pure-additive start.
’additive’: AdditiveFusion — plain sum, no learned parameters.
series_metadata – List of SeriesMetadata for prior construction.
prior_adjacency – (N, N) explicit prior adjacency matrix (optional).
prior_confidence – Weight of priors (0=ignore, 1=rigid).
causal_prior – Optional soft causal edge prior for V2 adjacency regularization.
prior_construction_config – Dict configuring automatic structural prior construction from event clusters and metadata. Defaults to blending detected changepoints/anomalies with metadata similarity ({‘sources’: [‘event’, ‘metadata’], …}). Pass {} to disable.
causal_prior_construction_config – Dict configuring automatic Granger-causal prior construction from decomposed trend components (requires statsmodels). Defaults to {‘max_lag’: 3, ‘min_history’: 90, ‘top_k’: 8, ‘alpha’: 0.05, ‘difference’: True}. Pass {} to disable.
d_token – Token/latent dimension.
n_meso – Number of meso latent nodes, or ‘auto’ (default) to set as 2 * n_global derived from N series.
n_global – Number of global latent nodes, or ‘auto’ (default) to set as max(2, ceil(sqrt(N_anchors))). Controls the DAG size.
n_prototypes – Number of prototype trend signatures, or ‘auto’ (default) to set as max(2, round(log2(N_anchors + 1))). Capped at 8.
n_heads – Attention heads.
epochs – Training epochs. Default 50 (needed for DAG warmup convergence).
lr – Learning rate.
batch_size – Training batch size.
window_size – Input trend window length.
forecast_horizon – Output forecast length.
loss_weights – Dict overriding loss component weights.
reconciliation_method – None, ‘mint’, ‘erm’, etc.
min_anchor_history – Minimum periods for a series to be an anchor.
device – ‘cpu’ or ‘cuda’.
random_seed – Reproducibility seed.
verbose – 0=silent, 1=progress bar, 2=per-epoch loss.
prototype_assignment_method – Prototype assignment method for bottleneck (‘cosine’, ‘l2’, ‘linear’). Defaults to ‘cosine’.
prototype_assignment_temperature – Temperature for prototype assignment logits.
structure_learning_config – Dict enabling DAG and dynamic hierarchy learning in the V2 trend network. Defaults to enabled with conservative penalties ({‘enabled’: True, ‘learn_hierarchy’: True, ‘learn_dag’: True, …}). Pass {‘enabled’: False} to disable.
- fit(df: DataFrame) TVA¶
Full TVA pipeline: decompose, build priors, train network.
- Parameters:
df – Wide DataFrame with DatetimeIndex and numeric columns.
- Returns:
self
- get_composite_trends() dict¶
Return learned composite/prototype trends for inspection.
- Returns:
Dict with ‘prototypes’ (K, D), ‘composite_trend’ (n_global, T_forecast), and ‘prototype_weights’ (N, K).
- get_graph() ndarray¶
Return the adjacency matrix (learned for V2, prior for V1).
- Returns:
(M, M) numpy array.
- get_graph_snapshot(threshold: float | None = None, include_priors: bool = True) dict¶
Return a serializable snapshot of the learned graph and hierarchy.
- plot_graph(view: str = 'dag', threshold: float | None = None, max_edges: int = 50, show_priors: bool = False, ax=None)¶
Plot the learned graph, hierarchy, or adjacency heatmap.
- predict(forecast_length: int | None = None) DataFrame¶
Generate forecasts for all series.
- Parameters:
forecast_length – Number of future periods. Defaults to forecast_horizon.
- Returns:
Wide DataFrame (forecast_length, N) with forecasted values.
- reconcile(forecasts: DataFrame | None = None) DataFrame¶
Apply hierarchical reconciliation if configured.
- Parameters:
forecasts – Forecast DataFrame. If None, generates fresh predictions.
- Returns:
Reconciled DataFrame.
- what_if(**constraints) DataFrame¶
Scenario planning via BifrostOptimizer.
- Parameters:
**constraints – Passed to BifrostOptimizer methods. Supported keys: - series_name, timestep, target_value -> apply_constraint - series_name, growth_rate -> apply_growth_constraint - level_name, target_value -> apply_hierarchical_constraint
- Returns:
Adjusted forecast DataFrame.
Module contents¶
TVA — Time-varying Vectorized Architecture.
A modular forecasting graph that produces structurally consistent forecasts across related time series via shared composite trend prototypes.
- class autots.evaluator.tva.GraphSnapshot(node_table: list, edge_table: list, adjacency_dense: ndarray, adjacency_thresholded: ndarray, assignment_matrices: list, topological_order: list, prior_adjacency: ndarray | None, is_acyclic: bool, cycle_score: float)¶
Bases:
objectSerializable export of learned TVA structure.
- adjacency_dense: ndarray¶
- adjacency_thresholded: ndarray¶
- assignment_matrices: list¶
- cycle_score: float¶
- edge_table: list¶
- is_acyclic: bool¶
- node_table: list¶
- prior_adjacency: ndarray | None¶
- to_dict() dict¶
- topological_order: list¶
- class autots.evaluator.tva.NornDecomposer(detector_params: dict | None = None, holiday_country=None, holiday_countries: dict | None = None)¶
Bases:
objectWraps TimeSeriesFeatureDetector to extract structured component DataFrames.
Produces trend, seasonality, holidays, level_shifts, anomalies, and noise as aligned DataFrames sharing the same index and columns as the input.
- Parameters:
detector_params – Dict of kwargs passed to TimeSeriesFeatureDetector.__init__.
- fit(df: DataFrame) NornDecomposer¶
Fit the feature detector on a wide DataFrame.
- Parameters:
df – Wide DataFrame with DatetimeIndex and one numeric column per series.
- Returns:
self
- get_components() dict¶
Extract decomposition components as DataFrames.
- Returns:
Dict with keys ‘trend’, ‘seasonality’, ‘holidays’, ‘level_shifts’, ‘anomalies’, ‘noise’. Each value is a DataFrame (T, N) aligned with the original input index and columns.
- get_features() dict¶
Return the full detected features dict from the underlying detector.
Includes changepoints, holiday impacts, anomaly records, etc. Useful for constructing priors or inspecting detection results.
- get_forecast_components(forecast_length: int) dict¶
Forward-project seasonality, holidays, level shifts, and trend.
Uses the detector’s built-in forecast method to project known deterministic components into the future.
- Parameters:
forecast_length – Number of future periods to project.
- Returns:
Dict with same keys as get_components(), each a DataFrame of shape (forecast_length, N).
- class autots.evaluator.tva.SeriesMetadata(name: str, attribute_values: Dict[str, str] | None = None, hierarchy_path: list | None = None, history_periods: int = 0, metric_type: str | None = None, surface: str | None = None, geography: str | None = None)¶
Bases:
objectMetadata descriptor for a single time series.
- name¶
Series identifier matching DataFrame column name.
- Type:
str
- attribute_values¶
Arbitrary categorical metadata for the series.
- Type:
Dict[str, str]
- hierarchy_path¶
Ordered path from root to leaf (e.g. [‘global’, ‘NA’, ‘US’]).
- Type:
list | None
- history_periods¶
Number of observed time periods available.
- Type:
int
- attribute_values: Dict[str, str]¶
- property geography: str | None¶
- hierarchy_path: list | None¶
- history_periods: int = 0¶
- property metric_type: str | None¶
- name: str¶
- property surface: str | None¶
- class autots.evaluator.tva.StructureLearningConfig(enabled: bool = False, learn_hierarchy: bool = True, learn_dag: bool = True, max_levels: int = 3, pool_ratio: float = 0.5, min_nodes_per_level: int = 2, dag_penalty: float = 0.1, dag_warmup_epochs: float = 0.2, sparsity_weight: float = 0.01, assignment_entropy_weight: float = 0.01, assignment_full_rank_weight: float = 0.01, prior_tether_weight: float = 0.05, temporal_drift_weight: float = 0.0, threshold_for_export: float = 0.2)¶
Bases:
objectOpt-in configuration for TVA structure discovery.
- assignment_entropy_weight: float = 0.01¶
- assignment_full_rank_weight: float = 0.01¶
- dag_penalty: float = 0.1¶
- dag_warmup_epochs: float = 0.2¶
- derive_latent_sizes(n_anchor: int, fallback_sizes: list | None = None) list¶
Return deterministic latent widths from anchor count.
The returned list excludes the input anchor level and contains only derived latent widths ordered bottom-up.
- enabled: bool = False¶
- classmethod from_dict(config: dict | None = None) StructureLearningConfig¶
- learn_dag: bool = True¶
- learn_hierarchy: bool = True¶
- max_levels: int = 3¶
- min_nodes_per_level: int = 2¶
- pool_ratio: float = 0.5¶
- prior_tether_weight: float = 0.05¶
- sparsity_weight: float = 0.01¶
- structure_scale(epoch_index: int, total_epochs: int) float¶
- temporal_drift_weight: float = 0.0¶
- threshold_for_export: float = 0.2¶
- to_dict() dict¶
- warmup_start_epoch(total_epochs: int) int¶
- class autots.evaluator.tva.TVA(detector_params: dict | None = None, trend_network: str = 'v2', fusion: str = 'attention', series_metadata: list | None = None, prior_adjacency: ndarray | None = None, prior_confidence: float = 0.3, causal_prior: ndarray | None = None, prior_construction_config: dict | None = None, causal_prior_construction_config: dict | None = None, d_token: int = 64, n_meso: int | str = 'auto', n_global: int | str = 'auto', n_prototypes: int | str = 'auto', n_heads: int = 4, epochs: int = 50, lr: float = 0.001, batch_size: int = 32, window_size: int = 91, forecast_horizon: int = 28, loss_weights: dict | None = None, reconciliation_method: str | None = None, min_anchor_history: int = 180, holiday_country=None, holiday_countries: dict | None = None, device: str = 'cpu', random_seed: int = 42, verbose: int = 1, prototype_assignment_method: str = 'cosine', prototype_assignment_temperature: float = 1.0, structure_learning_config: dict | None = None)¶
Bases:
objectTime Variant Architecture — end-to-end coherent forecasting graph.
The Common Operating Picture for time series. Produces structurally consistent forecasts across related series by routing all trends through shared composite prototypes. For all Time. Always.
- Parameters:
detector_params – Dict passed to TimeSeriesFeatureDetector.
trend_network – ‘v1’ (hierarchical latent) or ‘v2’ (learned directed).
fusion –
How stochastic components (trend, seasonality, holidays) are recombined before level shifts are added additively. ‘attention’ (default): DigitalTwinFusion — self-attention contextualizes
component embeddings; sigmoid gates independently fade each component in/out (gate in [0,1]) applied to the original values.
- ’direct’: DirectAttentionFusion — self-attention contextualizes component
embeddings; attended representations are projected directly to scalar contributions summed as a residual over the originals. More purely attention-driven; zero-init ensures pure-additive start.
’additive’: AdditiveFusion — plain sum, no learned parameters.
series_metadata – List of SeriesMetadata for prior construction.
prior_adjacency – (N, N) explicit prior adjacency matrix (optional).
prior_confidence – Weight of priors (0=ignore, 1=rigid).
causal_prior – Optional soft causal edge prior for V2 adjacency regularization.
prior_construction_config – Dict configuring automatic structural prior construction from event clusters and metadata. Defaults to blending detected changepoints/anomalies with metadata similarity ({‘sources’: [‘event’, ‘metadata’], …}). Pass {} to disable.
causal_prior_construction_config – Dict configuring automatic Granger-causal prior construction from decomposed trend components (requires statsmodels). Defaults to {‘max_lag’: 3, ‘min_history’: 90, ‘top_k’: 8, ‘alpha’: 0.05, ‘difference’: True}. Pass {} to disable.
d_token – Token/latent dimension.
n_meso – Number of meso latent nodes, or ‘auto’ (default) to set as 2 * n_global derived from N series.
n_global – Number of global latent nodes, or ‘auto’ (default) to set as max(2, ceil(sqrt(N_anchors))). Controls the DAG size.
n_prototypes – Number of prototype trend signatures, or ‘auto’ (default) to set as max(2, round(log2(N_anchors + 1))). Capped at 8.
n_heads – Attention heads.
epochs – Training epochs. Default 50 (needed for DAG warmup convergence).
lr – Learning rate.
batch_size – Training batch size.
window_size – Input trend window length.
forecast_horizon – Output forecast length.
loss_weights – Dict overriding loss component weights.
reconciliation_method – None, ‘mint’, ‘erm’, etc.
min_anchor_history – Minimum periods for a series to be an anchor.
device – ‘cpu’ or ‘cuda’.
random_seed – Reproducibility seed.
verbose – 0=silent, 1=progress bar, 2=per-epoch loss.
prototype_assignment_method – Prototype assignment method for bottleneck (‘cosine’, ‘l2’, ‘linear’). Defaults to ‘cosine’.
prototype_assignment_temperature – Temperature for prototype assignment logits.
structure_learning_config – Dict enabling DAG and dynamic hierarchy learning in the V2 trend network. Defaults to enabled with conservative penalties ({‘enabled’: True, ‘learn_hierarchy’: True, ‘learn_dag’: True, …}). Pass {‘enabled’: False} to disable.
- fit(df: DataFrame) TVA¶
Full TVA pipeline: decompose, build priors, train network.
- Parameters:
df – Wide DataFrame with DatetimeIndex and numeric columns.
- Returns:
self
- get_composite_trends() dict¶
Return learned composite/prototype trends for inspection.
- Returns:
Dict with ‘prototypes’ (K, D), ‘composite_trend’ (n_global, T_forecast), and ‘prototype_weights’ (N, K).
- get_graph() ndarray¶
Return the adjacency matrix (learned for V2, prior for V1).
- Returns:
(M, M) numpy array.
- get_graph_snapshot(threshold: float | None = None, include_priors: bool = True) dict¶
Return a serializable snapshot of the learned graph and hierarchy.
- plot_graph(view: str = 'dag', threshold: float | None = None, max_edges: int = 50, show_priors: bool = False, ax=None)¶
Plot the learned graph, hierarchy, or adjacency heatmap.
- predict(forecast_length: int | None = None) DataFrame¶
Generate forecasts for all series.
- Parameters:
forecast_length – Number of future periods. Defaults to forecast_horizon.
- Returns:
Wide DataFrame (forecast_length, N) with forecasted values.
- reconcile(forecasts: DataFrame | None = None) DataFrame¶
Apply hierarchical reconciliation if configured.
- Parameters:
forecasts – Forecast DataFrame. If None, generates fresh predictions.
- Returns:
Reconciled DataFrame.
- what_if(**constraints) DataFrame¶
Scenario planning via BifrostOptimizer.
- Parameters:
**constraints – Passed to BifrostOptimizer methods. Supported keys: - series_name, timestep, target_value -> apply_constraint - series_name, growth_rate -> apply_growth_constraint - level_name, target_value -> apply_hierarchical_constraint
- Returns:
Adjusted forecast DataFrame.
- class autots.evaluator.tva.YggdrasilPriors(series_metadata: list | None = None, relationship_matrix: ndarray | None = None, prior_confidence: float = 0.3, detected_features: dict | None = None, trend_data: DataFrame | None = None, observed_history: Dict[str, int] | None = None, prior_construction_config: dict | None = None, causal_prior_construction_config: dict | None = None, series_names: list | None = None)¶
Bases:
objectConstructs prior adjacency matrices, metadata embeddings, and hierarchy matrices from series metadata. All methods return sensible defaults when metadata is absent, so TVA runs with or without priors.
- Parameters:
series_metadata – List of SeriesMetadata, one per series.
relationship_matrix – Optional (N, N) soft prior adjacency override.
prior_confidence – Weight of prior vs learned structure (0=ignore, 1=rigid).
- build_causal_prior_adjacency() ndarray | None¶
Construct a directed causal prior from decomposed trend components.
- build_hierarchy_matrix() ndarray¶
Build summing matrix S for hierarchical reconciliation.
S has shape (L, M) where L = total nodes (aggregates + bottom), M = number of bottom-level series. Compatible with mint_reconcile(S, y_all, W).
Returns identity if no hierarchy paths are specified.
- build_metadata_embeddings() ndarray¶
Build (N, D_meta) one-hot embedding matrix from categorical metadata.
Encodes arbitrary categorical metadata keys as concatenated one-hot vectors. Returns zeros if no metadata is available.
- build_prior_adjacency() ndarray | None¶
Backward-compatible alias for structural prior construction.
- build_structural_prior_adjacency() ndarray | None¶
Construct a soft structural prior from explicit, metadata, and event sources.
- get_anchor_mask(min_history: int) ndarray¶
Return boolean mask (N,) where True = series has enough history to be an anchor.
Anchors shape the core latent trend graph. Responders inherit composite trends but do not perturb the core geometry.
- get_series_names() list¶
Return ordered list of series names.
- property n_series¶