API Reference

Welcome to the fusionlab-learn API reference. This section provides detailed specifications for the public functions, classes, and modules included in the package.


Transformer Models (fusionlab.nn.transformers)

Implementations of pure-transformer and Temporal Fusion Transformer architectures.

TimeSeriesTransformer

A standard Transformer model for multi-horizon time series forecasting.

TemporalFusionTransformer

TemporalFusionTransformer model implementation for multi-horizon forecasting, with optional static, past, and future inputs.

TFT

Temporal Fusion Transformer (TFT) required static, dynamic(past) and future inputs.

DummyTFT

DummyTFT: Simplified TFT variant using only Static and Dynamic inputs.

Fusion-Attentive Models (fusionlab.nn.models)

Core implementations of the Hybrid-Attentive Fusion and its variants.

BaseAttentive

Base Attentive Model.

HALNet

Hybrid Attentive LSTM Network (HAL-Net).

XTFT

Extreme Temporal Fusion Transformer (XTFT) model for complex time series forecasting.

SuperXTFT

SuperXTFT: An enhanced version of XTFT with Variable Selection Networks (VSNs) and integrated Gate → Add & Norm → GRN pipeline in attention layers.

Physic-Informed Models (fusionlab.nn.pinn)

Fusion models that integrate physical laws into the training process.

TransFlowSubsNet

Transient Ground-Water–Driven Subsidence Network

PIHALNet

Physics-Informed Hybrid Attentive-based LSTM Network (PIHALNet).

PiHALNet

Physics-Informed Hybrid Attentive LSTM Network (PiHALNet).

PiTGWFlow

Physics-Informed Transient Groundwater Flow.


Core Neural Network Components (fusionlab.nn.components)

Reusable building blocks for feature selection, sequence processing, attention, and output generation used within the forecasting models.

GatedResidualNetwork

Gated Residual Network applying transformations with optional context.

VariableSelectionNetwork

Applies GRN to each variable and learns importance weights.

PositionalEncoding

Injects positional information into an input tensor.

StaticEnrichmentLayer

Static Enrichment Layer for combining static and temporal features [1].

LearnedNormalization

Learned Normalization layer that learns mean and standard deviation parameters for normalizing input features.

PositionwiseFeedForward

Implements the Position-wise Feed-Forward Network (FFN) layer.

Sequence Processing Components (fusionlab.nn.components)

Components primarily focused on processing temporal sequences.

MultiScaleLSTM

MultiScaleLSTM layer applying multiple LSTMs at different sampling scales and concatenating their outputs [1].

DynamicTimeWindow

DynamicTimeWindow layer that slices the last max_window_size steps from the input sequence.

aggregate_multiscale

Aggregate multi-scale LSTM outputs using specified temporal fusion strategy.

aggregate_multiscale_on_3d

Aggregate multi-scale LSTM outputs using a specified strategy.

aggregate_time_window_output

Aggregates time window output features based on the specified

create_causal_mask

Creates a causal attention mask of shape [1,1,seq_len,seq_len] where mask[0,0,i,j] = 1.0 if j > i else 0.0.

Attention Mechanisms (fusionlab.nn.components)

Various attention layers used in Fusion Model architectures.

TemporalAttentionLayer

Temporal Attention Layer conditioning query with context.

CrossAttention

CrossAttention layer that attends one source sequence to another [1].

HierarchicalAttention

Hierarchical Attention layer that processes short-term and long-term sequences separately using multi-head attention, then combines their outputs [1].

MemoryAugmentedAttention

Memory-Augmented Attention layer that uses a learned memory matrix to enhance temporal representation [1].

MultiResolutionAttentionFusion

MultiResolutionAttentionFusion layer applying multi-head attention fusion over features [1].

ExplainableAttention

ExplainableAttention layer that returns attention scores from multi-head attention [1].

Embedding & Output Components (fusionlab.nn.components)

Layers for input embedding and generating final model outputs.

MultiModalEmbedding

MultiModalEmbedding layer for embedding multiple input modalities into a common feature space and concatenating them along the last dimension.

MultiDecoder

MultiDecoder for multi-horizon forecasting [1].

QuantileDistributionModeling

QuantileDistributionModeling layer projects deterministic outputs into quantile predictions [1].


Losses (fusionlab.nn.components & fusionlab.nn.losses)

Losses tailored for time series forecasting and anomaly detection.

Loss Components (fusionlab.nn.components)

These classes implement composite or parameterized loss behaviors.

AdaptiveQuantileLoss

Adaptive Quantile Loss layer that computes quantile loss for given quantiles [1].

AnomalyLoss

Anomaly Loss layer computing mean squared anomaly scores.

MultiObjectiveLoss

Multi-Objective Loss layer combining quantile loss and anomaly loss [1].

Loss Functions** (fusionlab.nn.losses)

Pure functions for computing scalar losses on predictions.

combined_quantile_loss

prediction_based_loss

Create a combined prediction + anomaly loss function for prediction-based strategy.

combined_total_loss

Create a total loss that adds quantile loss + anomaly loss.

objective_loss

Create a multi-objective Keras loss function that wraps a MultiObjectiveLoss layer, optionally including anomaly scores.

quantile_loss

Quantile (Pinball) Loss Function for Quantile Regression.

quantile_loss_multi

Multi-Quantile (Pinball) Loss Function for Quantile Regression.

anomaly_loss

Compute the anomaly loss based on given anomaly scores and a


Anomaly Detection (fusionlab.nn.anomaly_detection)

Components specifically designed for anomaly detection tasks.

LSTMAutoencoderAnomaly

LSTM Autoencoder for time series reconstruction-based anomaly

SequenceAnomalyScoreLayer

Computes an anomaly score from input features using a Multi-Layer

PredictionErrorAnomalyScore

Calculates an anomaly score based on prediction error between


Hyperparameter Tuning (fusionlab.nn.forecast_tuner)

Utilities for optimizing model hyperparameters using Keras Tuner.

HydroTuner

A robust and flexible hyperparameter tuner for hydrogeological PINN models.

HALTuner

A Keras Tuner for hyperparameter optimization of the HALNet model.

XTFTTuner

Keras‑Tuner wrapper dedicated to Extreme Temporal Fusion Transformer families (XTFT, SuperXTFT).

TFTTuner

Hyper‑parameter optimiser for Temporal Fusion Transformer (TFT) architectures – both the stricter TFT and the flexible TemporalFusionTransformer ('tft_flex').

PiHALTuner

Hyperparameter tuner for the PIHALNet model, which jointly predicts land subsidence and groundwater level (GWL) via a physics-informed neural network (PINN) framework.

xtft_tuner

Fine-tunes XTFT, SuperXTFT, or TFT (stricter) models.

tft_tuner

Fine-tunes TemporalFusionTransformer (flexible via model_name='tft_flex')


Neural Network Utilities (fusionlab.nn.utils)

Utilities specifically for preparing data for or interacting with neural network models.

create_sequences

Create input sequences and corresponding targets for time series forecasting.

split_static_dynamic

Split sequences into static and dynamic inputs for the model.

reshape_xtft_data

Reshapes time series data into rolling sequences for models like

compute_forecast_horizon

Compute the forecast horizon for time series forecasting models.

prepare_spatial_future_data

Prepare future static and dynamic inputs for making predictions.

compute_anomaly_scores

Compute anomaly scores for given true targets using various methods.

generate_forecast

Generate forecast using the XTFT model.

generate_forecast_with

Generate forecasts using a pre-trained XTFT model based on the forecast horizon.

forecast_single_step

Generate a single-step forecast using the XTFT model.

forecast_multi_step

Generate a multi-step forecast using the XTFT model.

step_to_long

Convert a multi-step forecast DataFrame from wide to long format.

format_predictions

Formats model predictions into a structured pandas DataFrame.

format_predictions_to_dataframe

Deprecated alias for format_predictions.

prepare_model_inputs

Prepares a list of input tensors for a model's call method.

format_pihalnet_predictions

Formats PIHALNet predictions into a structured pandas DataFrame.

prepare_pinn_data_sequences

Reshapes and prepares time-series data into sequences for PINN models.

format_pinn_predictions

Formats PINN model predictions into a structured pandas DataFrame.


PINN Parameter Descriptors (fusionlab.params)

Classes for specifying how physical coefficients in PINN models should be handled, allowing them to be defined as fixed constants or as learnable parameters to be discovered during training.

LearnableK

Learnable Hydraulic Conductivity (K).

LearnableSs

Learnable Specific Storage (Ss).

LearnableQ

Learnable Source/Sink term (Q).

LearnableC

Indicates that the PINN’s physical coefficient \(C\) should be learned (trainable).

FixedC

Non-trainable, constant \(C\).

DisabledC

Disable physics – \(C\) is ignored.

resolve_physical_param

Normalise a physical-parameter descriptor.


Metrics (fusionlab.metrics)

A collection of metrics for evaluating forecast accuracy, calibration, sharpness, and stability, particularly suited for probabilistic and time-series forecasting.

coverage_score

Compute the coverage score of prediction intervals.

continuous_ranked_probability_score

Compute the sample-based Continuous Ranked Probability Score (CRPS).

mean_interval_width_score

Compute the Mean Interval Width (sharpness) of prediction intervals.

prediction_stability_score

Compute the Prediction Stability Score (PSS).

quantile_calibration_error

Compute Quantile Calibration Error (QCE).

theils_u_score

Compute Theil's U Statistic.

time_weighted_accuracy_score

Compute the Time-Weighted Accuracy (TWA) score.

time_weighted_interval_score

Compute the Time-Weighted Interval Score (TWIS).

time_weighted_mean_absolute_error

Compute the Time-Weighted Mean Absolute Error (TW-MAE).

weighted_interval_score

Compute the Weighted Interval Score (WIS).


Visualization (fusionlab.plot)

A suite of plotting functions for visualizing time-series forecasts—enabling easy comparison of predictions with actual observations and detailed inspection of results at each forecast step or over specified horizons.

Visual‑metric helpers (fusionlab.plot.evaluation)

A curated set of plotting utilities that turn the raw numbers returned by fusionlab.metrics into clear, publication‑quality figures. They cover point‑forecast accuracy, interval sharpness & coverage, ensemble calibration, temporal stability, and more – all tailored to time‑series / probabilistic‑forecast workflows.

plot_coverage

Visualise prediction‑interval coverage in two ways:

plot_crps

Visualise the Continuous Ranked Probability Score (CRPS) for ensemble forecasts.

plot_forecast_comparison

Compare forecasts to ground‑truth on a temporal or spatial canvas.

plot_mean_interval_width

Visualise Mean Interval Width (MIW) – a simple sharpness measure equal to the average distance between lower and upper prediction‐ interval bounds.

plot_metric_over_horizon

Plot one or several error metrics as a function of forecast step.

plot_metric_radar

Visualise a chosen error metric per segment on a radar chart.

plot_prediction_stability

Visualise the Prediction Stability Score (PSS) — the average absolute change between successive time steps in a forecast trajectory.

plot_quantile_calibration

Visualise Quantile Calibration Error (QCE).

plot_theils_u_score

Visualise Theil’s U statistic.

plot_time_weighted_metric

Visualise time‑weighted error / accuracy metrics (MAE, classification accuracy, or interval‑based scores) as either

plot_weighted_interval_score

Visualise Weighted Interval Score (WIS).

Quick‑look forecast helpers (fusionlab.plot.forecast)

Light‑weight plotting utilities that turn a long‑format forecast DataFrame (as returned by :func:fusionlab.nn.utils.format_predictions_to_dataframe) into clear, side‑by‑side figures for rapid inspection.

forecast_view

Generates and displays spatial forecast visualizations.

plot_forecasts

Visualizes model forecasts from a structured DataFrame.

plot_forecast_by_step

Plots forecast data, organizing subplots by forecast step.

visualize_forecasts

Visualize forecast results and actual test data for one or more evaluation periods.


Data Processing Utilities (fusionlab.utils)

A grab-bag of utilities for cleaning, reshaping, and enriching raw time-series or spatial measurements before they enter the modelling pipeline

Preprocessing helpers (fusionlab.utils)

A collection of helpers for data manipulation, feature engineering, and preparing data for models.

nan_ops

Perform operations on NaN values within data structures, handling both primary data and optional witness data based on specified parameters.

widen_temporal_columns

Convert a long PIHALNet prediction table into a wide format where each temporal slice becomes a dedicated column.

pivot_forecast_dataframe

Transforms a long-format forecast DataFrame to a wide format.

create_spatial_clusters

Cluster 2D spatial data in df using <algorithm> and optionally plot the results.

spatial_sampling

Sample spatial data intelligently to represent the distribution

augment_series_features

Augments specified feature columns in a time series DataFrame by adding noise.

generate_dummy_pinn_data

Generate dummy PINN data dictionary with specified or default ranges.

augment_spatiotemporal_data

Applies temporal interpolation and/or feature augmentation to a spatiotemporal DataFrame.

mask_by_reference

Masks (replaces) values in columns other than the reference column for rows in which the reference column matches (or is closest to) the specified value(s).

fetch_joblib_data

Dynamically load data from a joblib-saved dictionary with flexible key access.

save_job

Quick save your job using 'joblib' or persistent Python pickle module.

Time Series Utilities (fusionlab.utils.ts_utils)

General utilities for time series data processing, analysis, and feature engineering.

ts_validator

Validate and preprocess time series data, ensuring the presence of a properly formatted datetime column or index.

to_dt

Converts a given DataFrame's column or index to datetime format using pandas' to_datetime functionality.

filter_by_period

Filter a DataFrame based on the provided evaluation periods.

ts_engineering

Perform feature engineering on a time series to create relevant predictors for machine learning models.

create_lag_features

Generate lag features for a time series to capture temporal dependencies.

trend_analysis

Perform trend analysis on a given time series, combining a stationarity test and a linear trend detection.

trend_ops

Perform transformations on a time series (e.g., removing upward/downward trends or applying differencing) based on automatically detected trends.

decompose_ts

Decompose a time series into trend, seasonal, and residual components while keeping the other features intact.

get_decomposition_method

Infer the suitable decomposition method for a given time series, based on certain heuristics or user preferences.

infer_decomposition_method

Determine the best decomposition approach for a time series, offering two modes:

ts_corr_analysis

Perform correlation analysis on a time series dataset, including autocorrelation (ACF), partial autocorrelation (PACF), and cross-correlation with external features.

transform_stationarity

Perform stationarity transformations on a time series dataset by applying differencing, variance stabilization, or detrending.

ts_split

Perform a time-based split on a time series dataset for either a simple train-test partition or cross-validation.

ts_outlier_detector

Detect outliers in a time series using either Z-Score or Interquartile Range (IQR).

select_and_reduce_features

Perform feature selection or dimensionality reduction on a dataset, using either correlation-based filtering or Principal Component Analysis (PCA).


Datasets (fusionlab.datasets)

Utilities for loading included sample datasets and generating synthetic time series data for testing and demonstration.

Loading Functions (fusionlab.datasets)

fetch_zhongshan_data

Fetch the Zhongshan land subsidence dataset (sampled 2000 points).

fetch_nansha_data

Fetch the sampled Nansha land subsidence dataset (2000 points).

load_processed_subsidence_data

Loads, preprocesses, and optionally sequences landslide datasets.

load_subsidence_pinn_data

Load and preprocess subsidence‐focused PINN data for Zhongshan or Nansha.

make_multi_feature_time_series

Generate multi-variate time series with static, dynamic, and future features.

make_quantile_prediction_data

Generate synthetic actuals and corresponding quantile predictions.

make_anomaly_data

Generate sequence data with injected anomalies.

make_trend_seasonal_data

Generate synthetic time series with specified trend and seasonality.

make_multivariate_target_data

Generate multi-series data with multiple related target variables.


Command-Line Tools (fusionlab.tools)

High-level applications for common workflows. For usage details, see the Command-Line Tools guide.

References