API Reference
Package modules
Data
Methods to load and preprocess shell and astrophysical data from HDF5 files used in Doppleriann. Supports merging datasets, handling planetary signal injections, and generating shell-level inputs.
- doppleriann.data.data_loader.load_shell_astro_datah5(pis=[0.1, 1.0], periods=[20], use_mask=False, spec_type='act', use_residuals=False, use_temp=True, data_dir='data/shells/', dataset_name='default', selected_idx=None, remove_ds=False, remove_ds_val=5.0, remove_ds_period=100)
Load and merge multiple HDF5 shell datasets into full training arrays.
Each file corresponds to a specific planetary injection setup, defined by a Doppler semi-amplitude (PI) and orbital period (P).
- Parameters:
pis (list of float) – List of Doppler semi-amplitude values (m/s) to include. Examples: [0.1, 1.0].
periods (list of float) – List of orbital periods (days) for which data is loaded.
use_mask (bool, optional) – Whether to multiply shell data by the density matrix (default False).
spec_type (str, optional) – Spectrum type identifier (act, or, sim) (default “act”).
use_residuals (bool, optional) – Subtract mean shell value to compute residuals (default False).
use_temp (bool, optional) – Use temperature shells (True) or flux shells (False) (default True).
data_dir (str, optional) – Directory containing the HDF5 files (default “data/shells/”).
dataset_name (str, optional) – Direct filename to load instead of looping through PI/period (default “default”).
selected_idx (list or ndarray, optional) – Specific indexes of spectra to select (default None).
remove_ds (bool, optional) – Whether to remove the Doppler-shift component using a reference dataset (default False).
remove_ds_val (float, optional) – Reference Doppler amplitude (m/s) for removal (default 5.0).
remove_ds_period (float, optional) – Reference period (days) for removal dataset (default 100).
- Returns:
shell_data_full (ndarray) – Combined shell data array (N, H, W).
astro_data_full (ndarray) – Corresponding astrophysical quantities.
density_data_full (ndarray) – Density maps for each shell.
grad_data_full (ndarray) – Gradient maps for each shell.
wave_data_full (ndarray) – Wavelength maps for each shell.
- doppleriann.data.data_loader.load_shell_astro_datah5_random(use_mask=False, spec_type='act', use_residuals=False, use_temp=True, data_dir='data/shellsHiddenRandom/', selected_idx=None, remove_ds=False, remove_ds_val=5.0, remove_ds_period=100, min_ds=0.0, max_ds=inf, n_size=None)
Load a random subset of HDF5 shell datasets for stochastic training.
- Parameters:
use_mask (bool, optional) – Whether to multiply shell data by the density matrix (default False).
spec_type (str, optional) – Spectrum type identifier (act, or, sim) (default “act”).
use_residuals (bool, optional) – Subtract mean shell value to compute residuals (default False).
use_temp (bool, optional) – Use temperature shells (True) or flux shells (False) (default True).
data_dir (str, optional) – Directory containing the HDF5 files (default “data/shellsHiddenRandom/”).
selected_idx (list or ndarray, optional) – Specific indexes of spectra to select (default None).
remove_ds (bool, optional) – Whether to remove the Doppler-shift component using a reference dataset (default False).
remove_ds_val (float, optional) – Reference Doppler amplitude (m/s) for removal (default 5.0).
remove_ds_period (float, optional) – Reference period (days) for removal dataset (default 100).
min_ds (float, optional) – Minimum Doppler shift (m/s) for inclusion (default 0.0).
max_ds (float, optional) – Maximum Doppler shift (m/s) for inclusion (default np.inf).
n_size (int, optional) – Number of random files to load (default None).
- Returns:
shell_data_full (ndarray) – Combined shell data array (N, H, W).
astro_data_full (ndarray) – Corresponding astrophysical quantities.
density_data_full (ndarray) – Density maps for each shell.
grad_data_full (ndarray) – Gradient maps for each shell.
wave_data_full (ndarray) – Wavelength maps for each shell.
- doppleriann.data.data_loader.load_hdf5_data(file_name, key)
Load a specific dataset from an HDF5 file.
- doppleriann.data.data_loader.load_and_process_file(file_name, use_residuals=True, use_mask=False, selected_idx=None)
Load shell and astrophysical datasets from an HDF5 file.
Compatible with both legacy (Pandas .to_hdf) and modern (h5py) DopplerIANN formats.
Scaling utilities for DopplerIANN shell data.
Includes Min-Max, Standard, and Masked Standard scalers for 3D datasets (e.g., spectral shells or image-like data cubes).
- class doppleriann.data.scalers.MinMaxScaler3D(feature_range=(0, 1))
Bases:
objectScales each pixel independently across all shells using min-max normalization.
- fit(X)
Compute min and max per pixel position across all shells.
- Parameters:
X (ndarray of shape (N, H, W)) – Input data array.
- Returns:
self – Fitted scaler instance.
- Return type:
- transform(X)
Scale each pixel independently using stored min and max values.
- Parameters:
X (ndarray of shape (N, H, W)) – Input data array to scale.
- Returns:
X_scaled – Scaled data array.
- Return type:
ndarray
- fit_transform(X)
Fit and transform the input data in one step.
- inverse_transform(X_scaled)
Reverse the scaling transformation.
- Parameters:
X_scaled (ndarray of shape (N, H, W)) – Scaled data array to revert.
- Returns:
X_orig – Original (unscaled) data array.
- Return type:
ndarray
- class doppleriann.data.scalers.StandardScaler3D
Bases:
objectStandardizes 3D data by removing the mean and scaling to unit variance. Useful for shell datasets and other image-like structures.
- fit(X)
Compute the mean and standard deviation across all samples.
- Parameters:
X (ndarray of shape (N, H, W)) – Input data array.
- Returns:
self – Fitted scaler instance.
- Return type:
- transform(X)
Apply standardization to the dataset.
- Parameters:
X (ndarray of shape (N, H, W)) – Input data array.
- Returns:
X_scaled – Standardized data array.
- Return type:
ndarray
- fit_transform(X)
Fit and transform the input data in one step.
- inverse_transform(X_scaled)
Reverse the standardization process.
- Parameters:
X_scaled (ndarray of shape (N, H, W)) – Standardized data array.
- Returns:
X_orig – Original data array restored from standardized form.
- Return type:
ndarray
- class doppleriann.data.scalers.MaskedStandardScaler3D
Bases:
objectStandardizes 3D arrays while preserving zeros (masked normalization). Zeros are treated as missing data and excluded from mean/std computation.
- fit(X)
Compute mean and standard deviation while ignoring zero values.
- Parameters:
X (ndarray of shape (N, H, W)) – Input data array with possible zero-masked elements.
- Returns:
self – Fitted scaler instance.
- Return type:
- transform(X)
Apply standardization while preserving zero-masked elements.
- Parameters:
X (ndarray of shape (N, H, W)) – Input data array with zeros representing masked elements.
- Returns:
X_norm – Standardized data array with zeros preserved.
- Return type:
ndarray
- fit_transform(X)
Fit the scaler and apply the transformation in one step.
- Parameters:
X (ndarray of shape (N, H, W)) – Input data array.
- Returns:
X_norm – Standardized data array.
- Return type:
ndarray
- inverse_transform(X_scaled)
Reverse the standardization, restoring original scale and preserving zeros.
- Parameters:
X_scaled (ndarray of shape (N, H, W)) – Standardized data array.
- Returns:
X_orig – Original data array with zero-mask preserved.
- Return type:
ndarray
Injects a hidden planetary signal into provided flux and/or temperature spectra time series.
- Parameters:
waves_obs (np.ndarray) – Wavelength array used to build SpectrumData.
dates (np.ndarray) – Observation Julian dates.
spec_vals_flux (np.ndarray, optional) – Flux and temperature spectra arrays (2D). At least one must be provided.
spec_vals_temp (np.ndarray, optional) – Flux and temperature spectra arrays (2D). At least one must be provided.
spec_type (str) – Spectrum type tag (e.g., ‘act’).
ds_amplitude (float, optional) – Doppler semi-amplitude (m/s).
period_range (tuple, optional) – Range of orbital periods to choose randomly from.
save_to (str or None, optional) – Directory path to save results. If None, results are only returned.
- Returns:
- {
“inj_flux”: ndarray or None, “inj_temp”: ndarray or None, “flux_master”: ndarray or None, “temp_master”: ndarray or None, “params”: {“phase_offset”: float, “ds”: float, “period”: float}
}
- Return type:
dict
- doppleriann.data.shell_generation.generate_data(num_it, spec_flux, spec_temp, spec_flux_master, spec_temp_master, flux_err_val, temp_err_val, waves_obs, dates, data_dir, doppler_shift_range=(0.1, 2.0), n_reso=9, spec_type='act', random_shifts=True, period=None, doppler_shift=None, phase_offset=None)
Generate synthetic datasets (flux + temperature) with random or controlled Doppler injections and their corresponding shell diagrams.
- Parameters:
num_it (int) – Iteration index (for file naming).
spec_flux (np.ndarray) – Input spectra arrays (flux and temperature).
spec_temp (np.ndarray) – Input spectra arrays (flux and temperature).
spec_flux_master (np.ndarray) – Corresponding master (reference) spectra.
spec_temp_master (np.ndarray) – Corresponding master (reference) spectra.
flux_err_val (np.ndarray) – Per-pixel uncertainties for flux and temperature.
temp_err_val (np.ndarray) – Per-pixel uncertainties for flux and temperature.
waves_obs (np.ndarray) – Observed wavelengths array.
dates (np.ndarray) – Julian dates for each observation.
data_dir (str) – Directory where generated .h5 files will be stored.
doppler_shift_range (tuple(float, float)) – Min and max Doppler shift amplitudes [m/s].
n_reso (int) – Shell resolution.
spec_type (str) – Spectrum type identifier (e.g., ‘act’).
random_shifts (bool, default=True) – If True, apply random Doppler shifts per spectrum (randomized amplitudes and phases). If False, inject a single coherent sinusoidal planetary signal.
period (float, optional) – Orbital period in days (required if random_shifts=False).
doppler_shift (float, optional) – Semi-amplitude [m/s] (required if random_shifts=False).
phase_offset (float, optional) – Initial orbital phase (optional, random if not provided).
Networks
DopplerIANN Networks Module - Base Classes
2025 by Isidro Gomez-Vargas (isidro.gomezvargas@unige.ch) ———————————————————- This module defines the foundational classes for all neural network architectures in DopplerIANN, including supervised models (e.g., CNNs, MLPs) and variational autoencoders (VAEs). It provides shared functionality for dropout handling, Monte Carlo uncertainty estimation, and model loading.
- class doppleriann.networks.base_networks.SuperVAE(latent_dim, dropout=0.2, actfn='tanh', mcdropout=True)
Bases:
objectBase class for Variational Autoencoders (VAEs).
Provides shared functionality for VAE subclasses, including Monte Carlo dropout prediction and model loading with DopplerIANN’s custom TensorFlow layers.
- Parameters:
latent_dim (int) – Dimensionality of the latent representation.
dropout (float, optional) – Dropout rate applied to network layers (default is 0.2).
actfn (str, optional) – Activation function used in layers (default is ‘tanh’).
mcdropout (bool, optional) – Enables Monte Carlo Dropout during inference (default is True).
- mcdo_predict(testset, encoder, decoder, mc_dropout_num=50)
Perform Monte Carlo Dropout predictions for a VAE.
Runs multiple stochastic forward passes through the encoder and decoder to estimate predictive uncertainty.
- Parameters:
testset (array-like) – Input data to perform stochastic predictions on.
encoder (tf.keras.Model) – Encoder part of the VAE.
decoder (tf.keras.Model) – Decoder part of the VAE.
mc_dropout_num (int, optional) – Number of Monte Carlo passes to perform (default is 50).
- Returns:
Dictionary containing means and standard deviations of encoded and decoded predictions: {
’mean_encoder’: np.ndarray, ‘std_encoder’: np.ndarray, ‘mean’: np.ndarray, ‘std’: np.ndarray
}
- Return type:
dict
- load_model(model_name)
Load a trained VAE model with DopplerIANN custom layers.
- Parameters:
model_name (str) – Path to the saved model file.
- Returns:
Loaded TensorFlow model.
- Return type:
tf.keras.Model
- model_tf()
Abstract method to build the TensorFlow model.
Subclasses must implement this method to define the encoder, decoder, and full VAE architecture.
- class doppleriann.networks.base_networks.SupervisedNET(deep=None, actfn='relu', dropout=0.2, mcdropout=True)
Bases:
objectBase class for supervised neural networks (MLPs, CNNs, etc.).
Provides shared initialization, dropout management, and Monte Carlo Dropout prediction methods for regression or classification networks.
- Parameters:
deep (list of int, optional) – Defines the number of neurons in each dense layer (default [100, 100, 100]).
actfn (str, optional) – Activation function for layers (default is ‘relu’).
dropout (float, optional) – Dropout rate applied to layers (default is 0.2).
mcdropout (bool, optional) – Enables Monte Carlo Dropout for uncertainty estimation (default is True).
- mcdo_predict(testset, model, mc_dropout_num=50)
Perform Monte Carlo Dropout predictions for supervised models.
- Parameters:
testset (array-like) – Input dataset for prediction.
model (tf.keras.Model) – Trained Keras model with dropout layers.
mc_dropout_num (int, optional) – Number of stochastic forward passes (default is 50).
- Returns:
Dictionary containing mean and standard deviation of predictions: {
’mean’: np.ndarray, ‘std’: np.ndarray
}
- Return type:
dict
- load_model(model_name)
Load a trained supervised model with custom DopplerIANN layers.
- Parameters:
model_name (str) – Path to the saved model file.
- Returns:
Loaded TensorFlow model.
- Return type:
tf.keras.Model
- model_tf()
Abstract method to build the TensorFlow model.
Subclasses must implement this method to define their specific supervised architecture.
DopplerIANN Networks Module - Custom TensorFlow Layers
2025 by Isidro Gomez-Vargas (isidro.gomezvargas@unige.ch) ——————————————————- Collection of custom TensorFlow/Keras layers and helper functions used in DopplerIANN for neural network regularization, uncertainty quantification (Monte Carlo dropout), and variational autoencoders.
- class doppleriann.networks.net_blocks.MCDropout(*args, **kwargs)
Bases:
LayerMonte Carlo Dropout layer.
Enables dropout to remain active during inference, allowing stochastic forward passes for uncertainty estimation and Bayesian approximation.
- Parameters:
rate (float) – Dropout rate (probability of dropping a unit).
is_disabled (bool, optional) – If True, disables dropout completely (default is False).
noise_shape (tuple, optional) – Shape of the dropout noise mask (default is None).
name (str, optional) – Name of the layer.
**kwargs (dict) – Additional arguments passed to the Keras Layer base class.
- call(inputs: Tensor, training: bool = None) Tensor
Apply dropout during both training and inference (if not disabled).
- Parameters:
inputs (tf.Tensor) – Input tensor to apply dropout on.
training (bool, optional) – Whether the layer is currently in training mode.
- Returns:
Tensor after dropout or unmodified input if disabled.
- Return type:
tf.Tensor
- get_config() dict
Returns the configuration of the layer for serialization.
- class doppleriann.networks.net_blocks.KLDivergenceLayer(*args, **kwargs)
Bases:
LayerCustom layer that computes and adds the KL divergence loss term.
Used in Variational Autoencoders (VAEs) to regularize the latent space.
- Parameters:
beta (float, optional) – Scaling factor for the KL divergence loss (default is 1.0).
- call(inputs)
Compute the KL divergence and add it as a model loss.
- Parameters:
inputs (list of tf.Tensor) – [z_mean, z_log_sigma] from the encoder.
- Returns:
The mean latent vector (z_mean) for downstream processing.
- Return type:
tf.Tensor
- class doppleriann.networks.net_blocks.ReconstructionLossLayer(*args, **kwargs)
Bases:
LayerCustom layer to compute and add a reconstruction (MSE) loss term.
Typically used in autoencoders or VAEs to penalize the difference between input and reconstructed output.
- call(inputs)
Compute the mean squared reconstruction loss.
- Parameters:
inputs (list of tf.Tensor) – [x_true, x_pred] - ground truth and reconstructed tensors.
- Returns:
The predicted tensor (x_pred), passed through unchanged.
- Return type:
tf.Tensor
- class doppleriann.networks.net_blocks.Resize1DTensorLayer(*args, **kwargs)
Bases:
LayerCustom layer that resizes a 1D tensor using bilinear interpolation.
Useful for upsampling feature sequences in 1D convolutional models.
- call(inputs)
Resize the temporal dimension of a 1D tensor.
- Parameters:
inputs (tf.Tensor) – Input tensor of shape (batch, time, channels).
- Returns:
Resized tensor with temporal dimension = target_len.
- Return type:
tf.Tensor
- get_config()
Return configuration for serialization.
- class doppleriann.networks.net_blocks.L1LatentRegularization(*args, **kwargs)
Bases:
LayerApplies L1 regularization directly to latent variables in VAEs.
- Parameters:
l1_lambda (float, optional) – Regularization coefficient (default is 1e-3).
- call(z)
Add L1 regularization loss term on the latent vector.
- Parameters:
z (tf.Tensor) – Latent representation tensor.
- Returns:
The same latent tensor, passed through unchanged.
- Return type:
tf.Tensor
- doppleriann.networks.net_blocks.resize_1d_tensor(t, target_len)
Resize a 1D tensor along its temporal dimension.
- Parameters:
t (tf.Tensor) – Input tensor of shape (batch, time, channels).
target_len (int) – Target temporal length after resizing.
- Returns:
Resized tensor with new temporal length.
- Return type:
tf.Tensor
- doppleriann.networks.net_blocks.sampling(args)
Reparameterization trick for VAEs.
Samples from a normal distribution using the mean and log-variance.
- Parameters:
args (list of tf.Tensor) – [z_mean, z_log_sigma] from encoder output.
- Returns:
Sampled latent vector.
- Return type:
tf.Tensor
DopplerIANN Networks Module - Autoencoders
2025 by Isidro Gomez-Vargas (isidro.gomezvargas@unige.ch) ———————————————————- Variable 1D Convolutional Variational Autoencoder (VAE) and Autoencoder architectures for shell-based or spectral inputs.
- class doppleriann.networks.aes.VaeCNN1D(n_inputs, conv_layers=None, dense_layers=None, **kwargs)
Bases:
SuperVAEFlexible 1D Convolutional Variational Autoencoder (VAE).
This model allows dynamic configuration of convolutional and dense layers for 1D shell-based or spectral representations.
- Parameters:
n_inputs (int) – Length of the 1D input vector (e.g., number of spectral bins).
conv_layers (list of tuple, optional) – List specifying (filters, kernel_size) for convolutional layers. Default is [(128, 5), (256, 5)].
dense_layers (list of int, optional) – List specifying fully connected layer sizes. Default is [512, 256].
**kwargs (dict) – Additional arguments for the parent SuperVAE class.
- Returns:
(vae, encoder, decoder) TensorFlow Keras models.
- Return type:
tuple
- model_tf()
Builds the flexible 1D CNN VAE model dynamically based on user-defined layers.
- class doppleriann.networks.aes.AeCNN1D(n_inputs, conv_layers=None, dense_layers=None, **kwargs)
Bases:
SupervisedNETFlexible 1D Convolutional Autoencoder.
This model provides a convolutional autoencoder architecture with L1 regularization for sparse latent representations.
- Parameters:
n_inputs (int) – Length of the flattened input vector.
conv_layers (list of tuple, optional) – List of (filters, kernel_size) for convolutional layers. Default is [(128, 5), (256, 5)].
dense_layers (list of int, optional) – Sizes of fully connected layers. Default is [512, 256].
**kwargs (dict) – Additional parameters passed to SupervisedNET.
- Returns:
(autoencoder, encoder, decoder) TensorFlow Keras models.
- Return type:
tuple
- model_tf()
Build the flexible 1D CNN Autoencoder architecture.
DopplerIANN Networks Module - CNN Architectures
2025 by Isidro Gomez-Vargas (isidro.gomezvargas@unige.ch) ———————————————————- 1D and 2D Convolutional Neural Networks (CNNs) for regression and supervised learning tasks using shell-based or spectral representations.
- class doppleriann.networks.cnns.ShellCNN1D(input_shape, n_outputs, learning_rate=0.001, conv_layers=None, dense_layers=None, **kwargs)
Bases:
SupervisedNETFlexible 1D Convolutional Neural Network (CNN) for supervised regression tasks.
This model dynamically constructs 1D convolutional and dense layers for processing shell-based or spectral inputs.
- Parameters:
input_shape (tuple) – Shape of the 1D input data.
n_outputs (int) – Number of output values (e.g., RV, FWHM, activity index).
learning_rate (float, optional) – Learning rate for the optimizer (default: 0.001).
conv_layers (list of tuple, optional) – List of (filters, kernel_size) for each convolutional layer. Default is [(128, 5), (256, 5)].
dense_layers (list of int, optional) – List specifying neuron counts for fully connected layers. Default is [512, 256].
**kwargs (dict) – Additional arguments for SupervisedNET.
- model_tf()
Build and return a 1D CNN model dynamically based on user-defined architecture.
- class doppleriann.networks.cnns.ShellCNN1DDual(input_shape, n_outputs, learning_rate=0.001, conv_layers=None, dense_layers=None, **kwargs)
Bases:
SupervisedNETDual-input 1D Convolutional Neural Network (CNN).
This architecture processes two separate 1D shell-based inputs through parallel convolutional branches and merges their extracted features before regression.
- Parameters:
input_shape (tuple) – Shape of each individual 1D input array.
n_outputs (int) – Number of output regression values.
learning_rate (float, optional) – Learning rate for the optimizer (default: 0.001).
conv_layers (list of tuple, optional) – List of (filters, kernel_size) defining Conv1D layers. Default is [(128, 5), (256, 5)].
dense_layers (list of int, optional) – Number of neurons in fully connected layers (default: [512, 256]).
**kwargs (dict) – Additional keyword arguments for SupervisedNET.
- model_tf()
Builds and compiles a 1D CNN model with two input branches.
- class doppleriann.networks.cnns.ShellCNN2Channel(input_shape, n_outputs, learning_rate=0.001, conv_layers=None, dense_layers=None, **kwargs)
Bases:
SupervisedNETEarly-fusion 2D CNN that processes two shell matrices as a single 2-channel input.
This approach stacks two shell representations (e.g., flux and temperature) as separate channels within a single 2D input tensor.
- Parameters:
input_shape (tuple) – Input shape including channels (e.g., (9, 9, 2)).
n_outputs (int) – Number of output regression targets (e.g., RV and DS).
learning_rate (float, optional) – Optimizer learning rate (default: 0.001).
conv_layers (list of tuple, optional) – List of (filters, kernel_size) for Conv2D layers. Default is [(128, 3), (256, 3)].
dense_layers (list of int, optional) – Fully connected layer sizes. Default is [512, 256].
**kwargs (dict) – Additional arguments for SupervisedNET.
- model_tf()
Build and return a 2-channel early-fusion Conv2D regression model.
- class doppleriann.networks.cnns.ShellCNN2D(input_shape, n_outputs, learning_rate=0.001, conv_layers=None, dense_layers=None, **kwargs)
Bases:
SupervisedNETFlexible 2D Convolutional Neural Network (CNN) for regression tasks.
- Parameters:
input_shape (tuple) – Shape of the 2D input matrix.
n_outputs (int) – Number of regression outputs.
learning_rate (float, optional) – Optimizer learning rate (default: 0.001).
conv_layers (list of tuple, optional) – List specifying (filters, kernel_size) for Conv2D layers. Default is [(128, 5), (256, 5)].
dense_layers (list of int, optional) – List of neuron counts for dense layers. Default is [512, 256].
**kwargs (dict) – Additional arguments passed to SupervisedNET.
- model_tf()
Build and return a flexible 2D CNN regression model.
DopplerIANN Networks Module - Conditional VAEs
2025 by Isidro Gomez-Vargas (isidro.gomezvargas@unige.ch) ———————————————————- Conditional 1D Convolutional Variational Autoencoder (CVAE) for shell-based or spectral representations conditioned on astrophysical or auxiliary parameters.
- class doppleriann.networks.cvae.CondVaeCNN1D(n_inputs, n_conditions, conv_layers=None, dense_layers=None, **kwargs)
Bases:
SuperVAEConditional 1D Convolutional Variational Autoencoder (CVAE).
This model learns a latent representation of 1D shell-based or spectral data while conditioning on auxiliary physical variables (e.g., stellar activity indices, RVs, or other metadata).
- Parameters:
n_inputs (int) – Number of input features (e.g., number of wavelength bins).
n_conditions (int) – Number of auxiliary conditioning variables.
conv_layers (list of tuple, optional) – Convolutional layer configuration, each tuple as (filters, kernel_size). Default is [(128, 5), (256, 5)].
dense_layers (list of int, optional) – Dense layer configuration for encoder and decoder. Default is [512, 256].
**kwargs (dict) – Additional keyword arguments passed to SuperVAE.
- model_tf()
Build and return the full Conditional VAE model (encoder, decoder, and CVAE).
DopplerIANN Networks Module - Kolmogorov-Arnold Networks (KAN)
2025 by Isidro Gomez-Vargas (isidro.gomezvargas@unige.ch) ———————————————————- Kolmogorov-Arnold Network (KAN) implementation for shell-based or spectral inputs, using spline-like nonlinearities for flexible, interpretable regression modeling.
- class doppleriann.networks.kann.KAN(n_inputs, n_outputs, deep=None, actfn='tanh', dropout=0.2, mcdropout=True, **kwargs)
Bases:
SupervisedNETKolmogorov–Arnold Network (KAN) Spectrum Feedforward Neural Network.
A feedforward neural network that approximates continuous mappings using univariate spline-based activation functions, inspired by the Kolmogorov–Arnold representation theorem.
- Parameters:
n_inputs (int) – Number of input features (e.g., number of wavelength bins).
n_outputs (int) – Number of outputs (e.g., target regression values).
deep (list of int, optional) – Number of neurons in each hidden layer. Default is [50, 50].
actfn (str, optional) – Standard activation function for dense layers (default: ‘tanh’).
dropout (float, optional) – Dropout rate between layers. Default is 0.2.
mcdropout (bool, optional) – Whether to use Monte Carlo Dropout for Bayesian sampling. Default is True.
**kwargs (dict) – Additional arguments passed to SupervisedNET.
- univariate_activation(x)
Custom activation function using cubic UnivariateSpline interpolation.
Each layer applies a smooth, spline-based nonlinearity over the neuron outputs, enabling flexible functional approximations with interpretable mappings.
- Parameters:
x (tf.Tensor) – Input tensor to apply the spline-based activation.
- Returns:
Tensor with spline-based nonlinear transformation applied.
- Return type:
tf.Tensor
- model_tf()
Builds and compiles the SpecKAN model.
DopplerIANN Networks Module - Multilayer Perceptron (MLP)
2025 by Isidro Gomez-Vargas (isidro.gomezvargas@unige.ch) ———————————————————- Feedforward Multilayer Perceptron (MLP) architectures for supervised regression or classification tasks using shell- based or spectral inputs.
- class doppleriann.networks.mlp.MLP(n_inputs, n_outputs, **kwargs)
Bases:
SupervisedNETFeedforward Multilayer Perceptron (MLP) for supervised tasks.
A flexible fully-connected neural network suitable for regression or classification using shell representations, spectra, or derived astrophysical data.
- Parameters:
n_inputs (int) – Number of input features (e.g., flattened shell size or spectral bins).
n_outputs (int) – Number of outputs (e.g., RV, BIS, or other scalar targets).
**kwargs (dict) – Additional arguments for the parent SupervisedNET class, such as dropout rate, activation function, and architecture depth.
- model_tf()
Abstract method to build the TensorFlow model.
Subclasses must implement this method to define their specific supervised architecture.
Physics
Cross-Correlation Function (CCF) tools for stellar spectra analysis. Includes CCF template generation, Doppler shift computation, and activity indicator extraction (RV, FWHM, BIS).
- class doppleriann.physics.CCFcalculator.CCFcalculator(wrapper=True, wavelimits=(4000.0, 6500.0), ccf_windows=10000, ccf_size=125.0, map_fn=<class 'map'>)
Bases:
objectCalculates cross-correlation functions (CCFs) from stellar spectra using a line mask template.
- Parameters:
wrapper (bool, optional) – If True, runs in Python mode only. If False, uses compiled C++ code for BIS fitting.
wavelimits (tuple, optional) – Lower and upper wavelength limits (default: 4000.0 - 6500.0 A).
ccf_windows (int, optional) – Velocity range for the CCF (default: 10000 m/s).
ccf_size (float, optional) – Step size in velocity space for the CCF (default: 125 m/s).
map_fn (function, optional) – Map function (default: Python built-in map).
- calculate_CCF_1(velocity_array, wavelength, wavelength_line, weight_line, wavelength_extend)
Builds a CCF mask template by shifting spectral lines across a velocity grid.
- Parameters:
velocity_array (ndarray) – Array of velocity values (m/s).
wavelength (ndarray) – Base wavelength grid.
wavelength_line (ndarray) – Mask line wavelengths.
weight_line (ndarray) – Mask line weights.
wavelength_extend (ndarray) – Extended wavelength grid for interpolation.
- Returns:
mask_template – 2D CCF mask array.
- Return type:
ndarray
- calculate_CCF_2(spectrum)
Computes the CCF by correlating an observed spectrum with the precomputed mask template.
- Parameters:
spectrum (ndarray) – Observed stellar spectrum on the defined wavelength grid.
- Returns:
CCF – Computed cross-correlation function.
- Return type:
ndarray
- Delta_wavelength(v, wavelength0)
Converts a velocity shift into a wavelength difference using the relativistic Doppler formula.
- Parameters:
v (float) – Velocity shift (m/s).
wavelength0 (float) – Reference wavelength.
- Returns:
delta_wavelength – Wavelength difference corresponding to the velocity shift.
- Return type:
float
- calc_mask(wavelength_extend, wavelength_line_shift, weight_line, begin_wave, mask_width=820, hole_width=0)
Constructs a line mask shifted in wavelength space for each velocity step.
- Parameters:
wavelength_extend (ndarray) – Extended wavelength grid.
wavelength_line_shift (ndarray) – Doppler-shifted line wavelengths.
weight_line (ndarray) – Mask line weights.
begin_wave (float) – Starting wavelength of the extended grid.
mask_width (float, optional) – Width of mask regions (default: 820 m/s converted to wavelength units).
hole_width (float, optional) – Optional hole width for mask gaps.
- Returns:
mask – 1D array containing the generated CCF mask.
- Return type:
ndarray
- ccf_calculator(spectra, waves)
Computes the Cross-Correlation Function (CCF) for an input spectrum.
- Parameters:
spectra (ndarray) – Input stellar spectrum.
waves (ndarray) – Wavelength grid of the input spectrum.
- Returns:
If wrapper is True –
- ccf_datandarray
Array containing velocity and CCF values.
- ccf_errorndarray
Estimated errors for the CCF.
If wrapper is False – ccf_data : ndarray ccf_error : ndarray span_harps : float
Line bisector inverse slope (BIS).
- vrad_harpsfloat
Measured radial velocity.
- vrad_errfloat
Radial velocity uncertainty.
- fwhm_harpsfloat
Full width at half maximum of the CCF.
- fwhm_errfloat
Uncertainty of FWHM.
- doppleriann.physics.CCFcalculator.astro_data(X, wave_cols, wrapper=True)
Extracts radial velocity (RV), FWHM, BIS, and their uncertainties from a set of spectra.
- Parameters:
X (ndarray) – Input spectra array (n_samples, n_wavelengths).
wave_cols (ndarray) – Wavelength grid for the spectra.
wrapper (bool, optional) – Whether to use the Python-only mode (default: True).
- Returns:
astro_array –
- Array of shape (N, 5):
column 0: radial velocity (RV)
column 1: RV error
column 2: FWHM
column 3: FWHM error
column 4: BIS (bisector span)
- Return type:
ndarray
Collection of tools to manipulate shell representations of stellar spectra. Includes methods for planetary signal injection, removal, and extraction of Doppler-orthogonal components (shape shells).
- doppleriann.physics.shell_utils.inject_planet_at_shell_level(shell_stats, dates, doppler_shift_amplitude, period_days, reference_date, c, randomize_phase=True)
Injects a planetary signal at the shell level, considering the orbital period and observation dates.
- Parameters:
shell_stats (dict) – Dictionary containing shell data and gradients. Must include: - ‘shell_df’: 2D DataFrame of the base shell. - ‘mean_grad_map’: 2D array of mean gradients per bin. - ‘mean_wave_map’: 2D array of mean wavelengths per bin.
dates (ndarray) – Observation times (Julian dates) corresponding to each shell.
doppler_shift_amplitude (float) – Semi-amplitude of the injected Doppler shift in m/s.
period_days (float) – Orbital period of the planetary signal in days.
reference_date (float) – Reference Julian date for phase calculation.
c (float) – Speed of light in m/s (typically 299792458).
randomize_phase (bool, optional) – Whether to introduce a random phase offset (default is True).
- Returns:
injected_shells (list of pd.DataFrame) – List of shells with injected planetary signals, one per observation date.
phase_values (ndarray) – Phase values used for each injection, in radians.
- doppleriann.physics.shell_utils.remove_planet_signal_shell_level(shell_stats, dates, doppler_shift_amplitude, period_days, reference_date, c)
Removes a previously injected planetary signal from shell-level data.
- Parameters:
shell_stats (dict) – Dictionary containing shell-level quantities: - ‘shell_df’: 2D DataFrame of the injected shell. - ‘mean_grad_map’: 2D array of mean gradients per bin. - ‘mean_wave_map’: 2D array of mean wavelengths per bin.
dates (ndarray) – Observation times (Julian dates) corresponding to each shell.
doppler_shift_amplitude (float) – Semi-amplitude of the injected Doppler shift in m/s.
period_days (float) – Orbital period of the planetary signal in days.
reference_date (float) – Reference Julian date used in the injection.
c (float) – Speed of light in m/s (typically 299792458).
- Returns:
cleaned_shells – List of shells with the injected planetary signal removed, one per observation date.
- Return type:
list of pd.DataFrame
- doppleriann.physics.shell_utils.extract_shape_shell(shell_obs, shell_dop)
Extracts the “shape shell” component by projecting an observed shell onto a Doppler shell and subtracting the Doppler-aligned component.
This isolates the residual (activity-related) part of the shell representation, orthogonal to the Doppler-induced deformation.
- Parameters:
shell_obs (ndarray or pd.DataFrame) – Shell data for the observed spectrum.
shell_dop (ndarray or pd.DataFrame) – Shell data for the Doppler-shifted (reference) spectrum.
- Returns:
shell_shape_df – 2D shell representation of the shape shell, representing Doppler-orthogonal features.
- Return type:
pd.DataFrame
Tools to transform and process stellar spectra for DopplerIANN. Includes methods to generate shell representations, apply Doppler shifts, mask the spectra, or get the temperature given the flux through interpolation.
- class doppleriann.physics.spec_transform.SpectrumData(wavelengths)
Bases:
objectClass providing spectral transformation utilities such as shell representation generation, Doppler shift injection, and spectral filtering.
- Parameters:
wavelengths (array-like) – Array of wavelength values (in Angstroms or nanometers) corresponding to the input spectra.
- shell_diagram(spec_input, master_spec, spec_err, n_reso, scale_factor=1.0, num_limits_factor=0.0)
Generate a shell representation of the spectrum based on gradients and flux values.
- Parameters:
spec_input (array) – Input observed spectrum.
master_spec (array) – Reference or master spectrum.
spec_err (array) – Spectrum uncertainties or noise estimates.
n_reso (int) – Resolution of the shell map (number of bins along each axis).
scale_factor (float, optional) – Scaling factor for the velocity gradient (default 1.0).
num_limits_factor (float, optional) – Minimum fraction of valid points per bin (default 0.0).
- Returns:
shell_stats –
- Dictionary containing:
- shell_dfpd.DataFrame
2D shell map of mean flux residuals.
- density_mapnp.ndarray
Density weighting map.
- mean_grad_mapnp.ndarray
Mean gradient per bin.
- mean_wave_mapnp.ndarray
Mean wavelength per bin.
- Return type:
dict
- planet_inj(full_spec_data, dates, doppler_shift_amplitude, period_days=20.0, reference_date=None, phase_offset=0)
Injects a planetary signal by applying a Doppler shift to the spectral time series given a period and semi amplitude.
- Parameters:
full_spec_data (ndarray of shape (N, M)) – The full spectral time series (N spectra × M wavelengths).
dates (ndarray of shape (N,)) – Observation times in Julian dates.
doppler_shift_amplitude (float) – Semi-amplitude of the Doppler shift in m/s.
period_days (float, optional) – Orbital period in days. Default is 20.
reference_date (float, optional) – Reference Julian date for phase calculation. If None, uses the first date.
phase_offset (float, optional) – Phase offset in radians applied to the sinusoidal signal. Default is 0.
- Returns:
injected_spectra (ndarray of shape (N, M)) – Spectra after applying Doppler shifts (planet injection).
modulated_doppler_shifts (ndarray of shape (N,)) – Doppler shifts applied to each spectrum, in m/s.
phase_values (ndarray of shape (N,)) – Phase values used to compute the Doppler shifts.
- inject_random_doppler_shifts(full_spec_data, doppler_shift_range=(0.05, 0.2), seed=None)
Apply random Doppler shifts to each spectrum independently.
- Parameters:
full_spec_data (ndarray) – Spectral time series (N spectra x M wavelengths).
doppler_shift_range (tuple of float, optional) – Min and max Doppler shifts (m/s).
seed (int or None, optional) – Random seed for reproducibility.
- Returns:
injected_spectra (ndarray) – Spectra after random Doppler shifts.
doppler_shifts (ndarray) – Applied Doppler shifts in m/s.
phases_dummy (ndarray) – Placeholder zero phases (for compatibility).
- kitcat_filtering_mask(full_spec_data, mask_dir='data/mask_kitcatkitcat_CCF_mask_Sun.npz')
Apply a spectral mask based on the KITCAT CCF line mask.
- Parameters:
full_spec_data (ndarray) – Input spectra to be filtered.
mask_dir (str) – Path to the KITCAT CCF mask file (.npz).
- Returns:
filtered_flux_dataset (ndarray) – Spectra after applying the line mask.
filtered_index (ndarray) – Indices of wavelengths that passed the mask filter.
- doppleriann.physics.spec_transform.interp_temp_given_flux(target_flux, master_flux, temp_values)
Interpolate temperature values corresponding to target fluxes, restricted to monotonic segments of the reference flux array.
- Parameters:
target_flux (ndarray) – Target flux values for interpolation.
master_flux (ndarray) – Reference flux array (must contain monotonic chunks).
temp_values (ndarray) – Temperature values corresponding to master_flux.
- Returns:
interpolated_temp (ndarray) – Interpolated temperature values.
accepted_idx (ndarray of bool) – Boolean array indicating successfully interpolated points.
DopplerIANN Physics — Signal Utilities
2025 by Isidro Gomez-Vargas (isidro.gomezvargas@unige.ch) ——————————————————-
Collection of signal-processing tools for analyzing radial velocity (RV) time series, including long-term trend removal, periodogram analysis, and phase recovery methods.
Functions include: - Sinusoidal modeling - Polynomial detrending - Periodogram generation (GLS) - Iterative removal of strongest periodic signals - Phase offset recovery and diagnostic plots ——————————————————-
- doppleriann.physics.signal_utils.sinusoidal_model(x, A, T, phi, C)
Sinusoidal model function: A * sin(2πx/T + φ) + C
- Parameters:
x (array_like) – Input time or phase values.
A (float) – Amplitude of the sine wave.
T (float) – Period of the signal.
phi (float) – Phase offset (radians).
C (float) – Constant offset.
- Returns:
Evaluated sinusoidal function values.
- Return type:
ndarray
- doppleriann.physics.signal_utils.long_term_remover(times, time_series, degree=3)
Removes long-term trends in a time series via polynomial fitting.
- Parameters:
times (array_like) – Observation times.
time_series (array_like) – Measured values (e.g., RVs).
degree (int, optional) – Degree of the polynomial trend to remove (default: 3). If 0, no detrending is applied.
- Returns:
Detrended time series (original minus fitted trend).
- Return type:
ndarray
- doppleriann.physics.signal_utils.remove_strongest_signals(rvs, time, err, n_remove)
Iteratively remove the strongest periodic signals from an RV time series using the Generalized Lomb-Scargle (GLS) periodogram.
- Parameters:
rvs (array_like) – Radial velocity values.
time (array_like) – Observation times (days).
err (array_like) – Measurement uncertainties.
n_remove (int) – Number of strongest signals to iteratively remove.
- Returns:
Residuals after signal removal.
- Return type:
ndarray
- doppleriann.physics.signal_utils.recover_phase_offset(dates, phase_values, period_days, reference_date=None)
Recover the relative phase offset between injected and observed signals.
- Parameters:
dates (array_like) – Observation dates.
phase_values (array_like) – Injected or recovered phase values (radians).
period_days (float) – Signal period in days.
reference_date (float, optional) – Reference date for phase zero. Defaults to the first date.
- Returns:
Circular mean phase offset in fractional phase units [0, 1].
- Return type:
float
- doppleriann.physics.signal_utils.circ_dist_cycles(a, b)
- doppleriann.physics.signal_utils.periodogram(rvs, time, err=None, fap=0.1, min_period=5, max_period=2000)
Compute a Generalized Lomb-Scargle (GLS) periodogram for radial velocity data.
- Parameters:
rvs (array_like) – Radial velocity measurements.
time (array_like) – Observation times (days).
err (array_like, optional) – Measurement uncertainties. Defaults to None.
fap (float, optional) – False alarm probability threshold (default: 0.1).
min_period (float, optional) – Minimum period to search (days).
max_period (float, optional) – Maximum period to search (days).
- Returns:
(clp, plevels) - clp : pyPeriod.Gls object containing periodogram results. - plevels : float, false-alarm probability threshold.
- Return type:
tuple
- doppleriann.physics.signal_utils.generate_periodogram_test(**kwargs)
Generate and optionally plot GLS periodograms for real vs predicted data.
- Parameters:
**kwargs (dict) –
- real_rvarray_like
Original radial velocities.
- pred_rvarray_like
Predicted radial velocities.
- pred_dsarray_like
Predicted Doppler shifts or derived signal.
- datesarray_like
Observation dates.
- prefix_namestr, optional
Prefix for output plot filenames.
- shell_type_strstr, optional
Optional tag for labeling.
- spec_typestr, optional
Spectrum type (default: ‘solar’).
- ds_sizefloat, optional
Doppler shift amplitude for annotation.
- periodfloat, optional
Injected period (days).
- min_period, max_periodfloat, optional
Period range for GLS computation.
- fapfloat, optional
False alarm probability (default: 0.1).
- plotbool, optional
If True, plot periodograms.
- savefigbool, optional
If True, save plots to output_dir.
- Returns:
Dictionary containing: - fig : matplotlib Figure (if plot=True) - clp_rv_real : GLS for real RVs - clp_rv_pred : GLS for predicted RVs - clp_ds_pred : GLS for predicted DS
- Return type:
dict
- doppleriann.physics.signal_utils.prior_transform(u)
Transform unit-cube parameters into physical model parameters for sinusoidal fitting.
- Parameters:
u (array_like of shape (4,)) – Uniform random variables in [0, 1].
- Returns:
(A, T, phi, C) - A : float, amplitude (0-50) - T : float, period (1-200) - phi : float, phase (-pi to pi) - C : float, constant offset (-10 to 10)
- Return type:
tuple
Utils
- doppleriann.utils.logger_config.setup_logging()