leaspy.models

Submodules

Classes

BaseModel

Base model class from which all Leaspy models should inherit.

ModelInterface

This is the public interface for Leaspy models.

ConstantModel

ConstantModel` is a benchmark model that predicts constant values (no matter what the patient's ages are).

ModelName

The available models that users can instantiate in Leaspy.

JointModel

Joint model for multiple repeated measures (logistic) and multiple competing events.

LinearModel

Manifold model for multiple variables of interest (linear formulation).

LMEModel

LMEModel is a benchmark model that fits and personalize a linear mixed-effects model.

LogisticModel

Manifold model for multiple variables of interest (logistic formulation).

McmcSaemCompatibleModel

Defines probabilistic models compatible with an MCMC SAEM estimation.

RiemanianManifoldModel

Manifold model for multiple variables of interest (logistic or linear formulation).

ModelSettings

Used in models.base.load to create a model class object from a json file.

SharedSpeedLogisticModel

Logistic model for multiple variables of interest, imposing same average

StatefulModel

Stateful models have an internal State to handle parameters and variables.

StatelessModel

Stateless model do not use an internal state to keep track of variables.

TimeReparametrizedModel

Contains the common attributes & methods of the multivariate time-reparametrized models.

LogisticMultivariateMixtureModel

Mixture Manifold model for multiple variables of interest (logistic formulation).

Functions

model_factory(name[, instance_name])

Return the model object corresponding to name arg with possible kwargs.

Package Contents

class BaseModel(name, **kwargs)[source]

Bases: ModelInterface

Base model class from which all Leaspy models should inherit.

It implements the ModelInterface.

Parameters:

name (str)

dataset_info
training_info
initialization_method: InitializationMethod
property name: str

The name of the model.

Returns:
str

The name of the model.

Return type:

str

property is_initialized: bool

True if the model is initialized, False otherwise.

Returns:
bool

True if the model is initialized, False otherwise.

Return type:

bool

property features: list[FeatureType] | None

List of model features (None if not initialization).

Returns:
: list [FeatureType], optional

The features of the model, or None if not initialized.

Return type:

Optional[list[FeatureType]]

property dimension: int | None

Number of features.

Returns:
int, optional

The dimension of the model, or None if not initialized.

Return type:

Optional[int]

initialize(dataset=None)[source]

Initialize the model given a Dataset and an initialization method.

After calling this method is_initialized should be True and model should be ready for use.

Parameters:
datasetDataset, optional

The dataset we want to initialize from.

Parameters:

dataset (Optional[Dataset])

Return type:

None

save(path, **kwargs)[source]

Save model as json model parameter file.

Parameters:
pathstr or Path

The path to store the model’s parameters.

**kwargsdict

Additional parameters for writing.

Raises:
LeaspyModelInputError

If the model is not initialized.

Parameters:

path (Union[str, Path])

Return type:

None

to_dict(**kwargs)[source]

Export model as a dictionary ready for export.

Returns:
KwargsType

The model instance serialized as a dictionary.

Return type:

KwargsType

classmethod load(path_to_model_settings)[source]

Load a model from a json model parameter file.

Parameters:
path_to_model_settingsstr or Path

The path to the model’s parameters file.

Returns:
BaseModel

An instance of the model loaded from the file.

Raises:
LeaspyModelInputError

If the model settings file is not found or cannot be read.

Parameters:

path_to_model_settings (Union[str, Path])

abstractmethod load_parameters(parameters)[source]

Load model parameters from a dictionary.

Parameters:
parametersKwargsType

The parameters to load into the model.

Raises:
NotImplementedError
Parameters:

parameters (KwargsType)

Return type:

None

fit(data=None, algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]

Estimate the model’s parameters for a given dataset and a given algorithm. These model’s parameters correspond to the fixed-effects of the mixed-effects model.

Parameters:
datapd.DataFrame or Data or Dataset, optional

Contains the information of the individuals, in particular the time-points \((t_{i,j})\) and the observations \((y_{i,j})\).

algorithmstr or AlgorithmName, optional

The name of the algorithm to use. Use this if you want to provide algorithm settings through kwargs.

algorithm_settingsAlgorithmSettings, optional

The algorithm settings to use. Use this if you want to customize algorithm settings through the AlgorithmSettings class. If provided, the fit will rely on these settings.

algorithm_settings_pathstr or Path, optional

The path to the algorithm settings file. If provided, the settings from the file will be used instead of the settings provided.

**kwargsdict

Contains the algorithm’s settings.

Parameters:
info()[source]

Print detailed information about the model configuration and training dataset.

Return type:

None

summary()[source]

Generate a structured summary of the model.

When called directly (e.g., model.summary()), prints a formatted summary. When stored in a variable, provides programmatic access to model attributes.

Returns:
Summary

A structured summary object.

Raises:
LeaspyModelInputError

If the model is not initialized or has no parameters.

Return type:

Summary

Examples

>>> model.summary()           # Prints the summary
>>> s = model.summary()       # Store to access attributes
>>> s.nll                     # Get specific value
>>> s.help()                  # Show available attributes
personalize(data=None, algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]

Estimate individual parameters for each ID of a given dataset. These individual parameters correspond to the random-effects \((z_{i,j})\) of the mixed-effects model.

Parameters:
datapd.DataFrame or Data or Dataset, optional

Contains the information of the individuals, in particular the time-points \((t_{i,j})\) and the observations \((y_{i,j})\).

algorithmstr or AlgorithmName, optional

The name of the algorithm to use.

algorithm_settingsAlgorithmSettings, optional

The algorithm settings to use. Use this if you want to customize algorithm settings through the AlgorithmSettings class. If provided, the fit will rely on these settings.

algorithm_settings_pathstr or Path, optional

The path to the algorithm settings file. If provided, the settings from the file will be used instead of the settings provided.

**kwargsdict

Contains the algorithm’s settings.

Returns:
IndividualParameters

Individual parameters computed.

Parameters:
Return type:

IndividualParameters

estimate(timepoints, individual_parameters, *, to_dataframe=None)[source]

Return the model values for individuals characterized by their individual parameters \(z_i\) at time-points \((t_{i,j})_j\).

Parameters:
timepointspd.MultiIndex or dict [IDType, list [float]]

Contains, for each individual, the time-points to estimate. It can be a unique time-point or a list of time-points.

individual_parametersIndividualParameters

Corresponds to the individual parameters of individuals.

to_dataframebool, optional

Whether to output a dataframe of estimations? If None: default is to be True if and only if timepoints is a pandas.MultiIndex

Returns:
individual_trajectorypd.DataFrame or dict [IDType, np.ndarray]

Key: patient indices. Value: numpy.ndarray of the estimated value, in the shape (number of timepoints, number of features)

Parameters:
Return type:

Union[DataFrame, dict[IDType, ndarray]]

abstractmethod compute_individual_trajectory(timepoints, individual_parameters)[source]

Compute the model values for an individual characterized by their individual parameters at given time-points. Parameters ———- timepoints : list [float]

The time-points at which to compute the model values.

individual_parametersIndividualParameters

The individual parameters of the individual.

Returns:
torch.Tensor

The computed model values for the individual at the given time-points.

Raises:
NotImplementedError

If the method is not implemented in the subclass.

Parameters:
Return type:

Tensor

simulate(algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]

Run the simulation pipeline using a leaspy model.

This method simulates longitudinal data using the given leaspy model. It performs the following steps: - Retrieves individual parameters (IP) from fixed effects of the model. - Loads the specified Leaspy model. - Generates visit ages (timepoints) for each individual (based on specifications in visits_type) - Simulates observations at those visit ages. - Packages the result into a Result object, including simulated data, individual parameters, and the model’s noise standard deviation.

Parameters:
algorithmstr or AlgorithmName, optional

The name of the algorithm to use. Use this if you want to provide algorithm settings through kwargs.

algorithm_settingsAlgorithmSettings, optional

The algorithm settings to use. Use this if you want to customize algorithm settings through the AlgorithmSettings class. If provided, the fit will rely on these settings.

algorithm_settings_pathstr or Path, optional

The path to the algorithm settings file. If provided, the settings from the file will be used instead of the settings provided.

**kwargsdict

Contains the algorithm’s settings.

Returns:
simulated_dataResult

Contains the generated individual parameters & the corresponding generated scores. Returns empty Result if any required input is None.

Parameters:

Notes

To generate a new subject, first we estimate the joined distribution of the individual parameters and the reparametrized baseline ages. Then, we randomly pick a new point from this distribution, which define the individual parameters & baseline age of our new subjects. Then, we generate the timepoints following the baseline age. Then, from the model and the generated timepoints and individual parameters, we compute the corresponding values estimations. Then, we add some noise to these estimations, which is the same noise-model as the one from your model by default. But, you may customize it by setting the noise keyword.

Examples

Use a calibrated model & individual parameters to simulate new subjects similar to the ones you have:

>>> from leaspy.models import LogisticModel
>>> from leaspy.io.data import Data
>>> from leaspy.datasets import load_dataset, load_leaspy_instance, load_individual_parameters
>>> putamen_df = load_dataset("parkinson-putamen-train_and_test")
>>> data = Data.from_dataframe(putamen_df.xs('train', level='SPLIT'))
>>> leaspy_logistic = load_leaspy_instance("parkinson-putamen-train")
>>> visits_params = {'patient_number':200,
         'visit_type': "random",
         'first_visit_mean' : 0.,
         'first_visit_std' : 0.4,
         'time_follow_up_mean' : 11,
         'time_follow_up_std' : 0.5,
         'distance_visit_mean' : 2/12,
         'distance_visit_std' : 0.75/12,
         'min_spacing_between_visits': 1/365
        }
>>> simulated_data = model.simulate( algorithm="simulate", features=["MDS1_total", "MDS2_total", "MDS3_off_total", 'SCOPA_total','MOCA_total','REM_total','PUTAMEN_R','PUTAMEN_L','CAUDATE_R','CAUDATE_L'],visit_parameters= visits_params  )
class ModelInterface[source]

Bases: abc.ABC

This is the public interface for Leaspy models. It defines the methods and properties that all models should implement. It is not meant to be instantiated directly, but rather to be inherited by concrete model classes.

property name: str
Abstractmethod:

Return type:

str

The name of the model.

Returns:
str
Raises:
NotImplementedError
Return type:

str

property is_initialized: bool
Abstractmethod:

Return type:

bool

True if the model is initialized, False otherwise.

Returns:
bool
Raises:
NotImplementedError
Return type:

bool

property dimension: int
Abstractmethod:

Return type:

int

Number of features.

Returns:
int
Raises:
NotImplementedError
Return type:

int

property features: list[FeatureType]
Abstractmethod:

Return type:

list[FeatureType]

List of model features (None if not initialization).

Raises:
NotImplementedError
Return type:

list[FeatureType]

property parameters: DictParamsTorch
Abstractmethod:

Return type:

DictParamsTorch

Dictionary of values for model parameters.

Returns:
DictParamsTorch
Raises:
NotImplementedError
Return type:

DictParamsTorch

property hyperparameters: DictParamsTorch
Abstractmethod:

Return type:

DictParamsTorch

Dictionary of values for model hyperparameters.

Returns:
DictParamsTorch
Raises:
NotImplementedError
Return type:

DictParamsTorch

abstractmethod save(path, **kwargs)[source]

Save model as json model parameter file.

Parameters:
pathstr or Path

The path to store the model’s parameters.

**kwargsdict

Additional parameters for writing.

Raises:
NotImplementedError
Parameters:

path (Union[str, Path])

Return type:

None

classmethod load(path_to_model_settings)[source]
Abstractmethod:

Parameters:

path_to_model_settings (Union[str, Path])

Load a model from a json model parameter file.

Parameters:
path_to_model_settingsstr or Path

The path to the model’s parameters file.

Raises:
NotImplementedError
Parameters:

path_to_model_settings (Union[str, Path])

abstractmethod fit(data=None, algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]

Estimate the model’s parameters \(\theta\) for a given dataset and a given algorithm.

These model’s parameters correspond to the fixed-effects of the mixed-effects model.

There are three ways to provide parameters to the fitting algorithm:

  1. By providing an instance of AlgorithmSettings

  2. By providing a path to a serialized AlgorithmSettings

  3. By providing the algorithm name and parameters directly

If settings are provided in multiple ways, the order above will prevail.

Parameters:
datapd.DataFrame or Data or Dataset, optional

Contains the information of the individuals, in particular the time-points \((t_{i,j})\) and the observations \((y_{i,j})\).

algorithmstr or AlgorithmName,optional

The name of the algorithm to use.

Note

Use this if you want to provide algorithm settings through kwargs.

algorithm_settingsAlgorithmSettings, optional

The algorithm settings to use.

Note

Use this if you want to customize algorithm settings through the AlgorithmSettings class. If provided, the fit will rely on these settings.

algorithm_settings_pathstr or Path, optional

The path to the algorithm settings file.

Note

If provided, the settings from the file will be used instead of the settings provided through kwarsg.

**kwargsdict

Contains the algorithm’s settings.

Raises:
NotImplementedError
Parameters:

Examples

Fit a logistic model on a longitudinal dataset, display the group parameters

>>> from leaspy.models import LogisticModel
>>> from leaspy.datasets import load_dataset
>>> putamen_df = load_dataset("parkinson-putamen")
>>> model = LogisticModel(name="test-model-logistic")
>>> model.fit(putamen_df, "mcmc_saem", seed=0, print_periodicity=50)
>>> print(model)
=== MODEL ===
betas_mean : []
log_g_mean : [-0.8394]
log_v0_mean : [-3.7930]
noise_std : 0.021183
tau_mean : [64.6920]
tau_std : [10.0864]
xi_std : [0.5232]
abstractmethod personalize(data=None, algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]

Estimate individual parameters for each ID of a given dataset.

These individual parameters correspond to the random-effects \((z_{i,j})\) of the mixed-effects model.

Parameters:
datapd.DataFrame or Data or Dataset, optional

Contains the information of the individuals, in particular the time-points \((t_{i,j})\) and the observations \((y_{i,j})\).

algorithmstr or AlgorithmName, optional

The name of the algorithm to use.

algorithm_settingsAlgorithmSettings, optional

The algorithm settings to use.

Note

Use this if you want to customize algorithm settings through the AlgorithmSettings class. If provided, the fit will rely on these settings.

algorithm_settings_pathstr or Path, optional

The path to the algorithm settings file.

Note

If provided, the settings from the file will be used instead of the settings provided.

**kwargsdict

Contains the algorithm’s settings.

Returns:
ipsIndividualParameters

Individual parameters computed.

Raises:
NotImplementedError
Parameters:
Return type:

IndividualParameters

Examples

Compute the individual parameters for a given longitudinal dataset and calibrated model, then display the histogram of the log-acceleration:

>>> from leaspy.datasets import load_model, load_dataset
>>> model = load_model("parkinson-putamen")
>>> putamen_df = load_dataset("parkinson-putamen")
>>> individual_parameters = model.personalize(putamen_df, "scipy_minimize", seed=0)
abstractmethod estimate(timepoints, individual_parameters, *, to_dataframe=None)[source]

Return the model values for individuals characterized by their individual parameters \(z_i\) at time-points \((t_{i,j})_j\).

Parameters:
timepointspd.MultiIndex or dict [IDType, list [float ] ]

Contains, for each individual, the time-points to estimate. It can be a unique time-point or a list of time-points.

individual_parametersIndividualParameters

Corresponds to the individual parameters of individuals.

to_dataframebool, optional

Whether to output a dataframe of estimations? If None: default is to be True if and only if timepoints is a pandas.MultiIndex

Returns:
individual_trajectorypd.MultiIndex or dict [IDType, list [float]]

Key: patient indices. Value: numpy.ndarray of the estimated value, in the shape (number of timepoints, number of features)

Raises:
NotImplementedError
Parameters:
Return type:

Union[DataFrame, dict[IDType, ndarray]]

Examples

Given the individual parameters of two subjects, estimate the features of the first at 70, 74 and 80 years old and at 71 and 72 years old for the second.

>>> from leaspy.datasets import load_model, load_individual_parameters, load_dataset
>>> model = load_model("parkinson-putamen")
>>> individual_parameters = load_individual_parameters("parkinson-putamen")
>>> df_train = load_dataset("parkinson-putamen-train_and_test").xs("train", level="SPLIT")
>>> timepoints = {'GS-001': (70, 74, 80), 'GS-002': (71, 72)}
>>> estimations = model.estimate(timepoints, individual_parameters)
abstractmethod simulate(individual_parameters, data=None, **kwargs)[source]
Run the simulation pipeline using a leaspy model.

This method simulates longitudinal data using the given leaspy model. It performs the following steps: - Retrieves individual parameters (IP) from fixed effects of the model. - Loads the specified Leaspy model. - Generates visit ages (timepoints) for each individual (based on specifications

in visits_type).

  • Simulates observations at those visit ages.

  • Packages the result into a Result object, including simulated data, individual parameters, and the model’s noise standard deviation.

Parameters:
individual_parametersIndividualParameters

Individual parameters to use for the simulation.

datapd.DataFrame or Data or Dataset

Data object. If None, returns empty Result.

**kwargs : dict raise NotImplementedError

` Additional arguments for algorithm settings.
Returns:
simulated_dataResult

Contains the generated individual parameters & the corresponding generated scores. Returns empty Result if any required input is None.

Raises:
NotImplementedError
Parameters:
class ConstantModel(name, **kwargs)[source]

Bases: leaspy.models.stateless.StatelessModel

ConstantModel` is a benchmark model that predicts constant values (no matter what the patient’s ages are).

These constant values depend on the algorithm setting and the patient’s values provided during calibration.

It could predict:
  • last: last value seen during calibration (even if NaN).

  • last_known: last non NaN value seen during calibration.

  • max: maximum (=worst) value seen during calibration.

  • mean: average of values seen during calibration.

Warning

Depending on features, the last_known / max value may correspond to different visits.

Warning

For a given feature, value will be NaN if and only if all values for this feature were NaN.

Parameters:
namestr

The model’s name.

Parameters:

name (str)

property hyperparameters: DictParamsTorch

Dictionary of values for model hyperparameters.

Returns:
DictParamsTorch

Dictionary of hyperparameters.

Return type:

DictParamsTorch

compute_individual_trajectory(timepoints, individual_parameters)[source]

Compute the individual trajectory based on the model’s features and parameters.

Parameters:
timepointstorch.Tensor

The time points at which to compute the trajectory.

individual_parametersdict

Dictionary containing the individual’s parameters, where keys are feature names.

Returns:
torch.Tensor

A tensor containing the computed trajectory for the individual.

Raises:
LeaspyModelInputError

If the model was not properly initialized or if features are not set.

Parameters:
  • timepoints (Tensor)

  • individual_parameters (dict)

Return type:

Tensor

class ModelName[source]

Bases: str, enum.Enum

The available models that users can instantiate in Leaspy.

JOINT = 'joint'
LOGISTIC = 'logistic'
LINEAR = 'linear'
SHARED_SPEED_LOGISTIC = 'shared_speed_logistic'
LME = 'lme'
CONSTANT = 'constant'
MIXTURE_LOGISTIC = 'mixture_logistic'
model_factory(name, instance_name=None, **kwargs)[source]

Return the model object corresponding to name arg with possible kwargs.

Parameters:
namestr or ModelName
The name of the model class to be instantiated. Valid options include:
  • "joint"

  • "logistic"

  • "linear"

  • "shared_speed_logistic"

  • "lme"

  • "constant"

  • "mixture_logistic"

instance_namestr, optional

A custom name for the model instance. If not provided, the model’s name will be used as the instance name.

**kwargs

Additional keyword arguments corresponding to the model’s hyperparameters. These must be valid for the specified model, or an error will be raised.

Returns:
BaseModel

A child class object of models.BaseModel class object determined by name.

Raises:
ValueError

If an invalid model name is provided or the model cannot be instantiated with the provided arguments.

Parameters:
Return type:

BaseModel

class JointModel(name, **kwargs)[source]

Bases: leaspy.models.logistic.LogisticModel

Joint model for multiple repeated measures (logistic) and multiple competing events. The model implemented is associated to this [publication](https://arxiv.org/abs/2501.08960) on arxiv.

Parameters:
namestr

The name of the model.

**kwargs

Hyperparameters of the model (including noise_model)

Raises:
LeaspyModelInputError
  • If name is not one of allowed sub-type: ‘univariate_linear’ or ‘univariate_logistic’

  • If hyperparameters are inconsistent

Parameters:

name (str)

init_tolerance: float = 0.3
get_variables_specs()[source]

Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.

Returns:
NamedVariables

The specifications of the model’s variables.

Return type:

NamedVariables

to_dict(*, with_mixing_matrix=True)[source]

Export model as a dictionary ready for export. Add the number of events compare to the multivariate output

Parameters:
with_mixing_matrixbool

If True the mixing matrix will be saved in the dictionary

Returns:
KwargsType

The model instance serialized as a dictionary.

Parameters:

with_mixing_matrix (bool)

Return type:

KwargsType

put_individual_parameters(state, dataset)[source]

Initialise the individual parameters of the state thanks to the dataset.

Parameters:
stateState

where all the variables of the model are stored

datasetDataset

Where the individual data are stored

Returns:
None
Parameters:
compute_individual_trajectory(timepoints, individual_parameters, *, skip_ips_checks=False)[source]

This method computes the individual trajectory of a patient for given timepoint(s) using his/her individual parameters (random effects). For the longitudinal sub-model:

  • Compute longitudinal values

For the event sub-model:
  • only one event: return the survival rate corrected by the probability of the first time point of the prediction assuming that the patient was alive,

  • more than one event: return the Cumulative Incidence function corrected by the probability of the first time point of the prediction assuming that the patient was alive.

Nota: model uses its current internal state.

Parameters:
timepointsscalar or array_like[scalar] (list, tuple, numpy.ndarray)

Contains the age(s) of the subject.

individual_parametersdict

Contains the individual parameters. Each individual parameter should be a scalar or array_like.

skip_ips_checksbool (default: False)

Flag to skip consistency/compatibility checks and tensorization of individual_parameters when it was done earlier (speed-up).

Returns:
torch.Tensor

Contains the subject’s scores computed at the given age(s) Shape of tensor is (1, n_tpts, n_features).

Raises:
LeaspyModelInputError

If computation is tried on more than 1 individual.

LeaspyIndividualParamsInputError

if invalid individual parameters.

Parameters:
Return type:

Tensor

class LinearModel(name, **kwargs)[source]

Bases: LinearInitializationMixin, leaspy.models.riemanian_manifold.RiemanianManifoldModel

Manifold model for multiple variables of interest (linear formulation).

Parameters:

name (str)

get_variables_specs()[source]

Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.

Returns:
:class:`~leaspy.variables.specs.NamedVariables

A dictionary-like object mapping variable names to their specifications.

Return type:

NamedVariables

static metric(*, g)[source]

Compute the metric tensor for the model.

Parameters:
gtorch.Tensor

Input tensor with values of the population parameter g for each feature.

Returns:
torch.Tensor

A tensor of ones with the same shape as g.

Parameters:

g (Tensor)

Return type:

Tensor

classmethod model_with_sources(*, rt, space_shifts, metric, v0, g)[source]

Return the model output when sources(spatial components) are present.

Parameters:
rttorch.Tensor

The reparametrized time.

space_shiftstorch.Tensor

The values of the space-shifts

metricAny

The metric tensor used for computing the spatial/temporal influence.

v0Any

The values of the population parameter v0 for each feature.

gAny

The values of the population parameter g for each feature.

Returns:
torch.Tensor

The model output with contribution from sources.

Parameters:
Return type:

Tensor

class LMEModel(name, with_random_slope_age=True, **kwargs)[source]

Bases: leaspy.models.stateless.StatelessModel

LMEModel is a benchmark model that fits and personalize a linear mixed-effects model.

The model specification is the following:

\[y_{ij} = fixed_{intercept} + random_{intercept_i} + (fixed_{slopeAge} + random_{slopeAge_i}) * age_{ij} + \epsilon_{ij}\]
with:
  • \(y_{ij}\): value of the feature of the i-th subject at his j-th visit,

  • \(age_{ij}\): age of the i-th subject at his j-th visit.

  • \(\epsilon_{ij}\): residual Gaussian noise (independent between visits)

Warning

This model must be fitted on one feature only (univariate model).

TODO? add some covariates in this very simple model.

Parameters:
namestr

The model’s name.

**kwargs
Model hyperparameters:
  • with_random_slope_age : bool (default True).

Attributes:
namestr

The model’s name.

is_initializedbool

True if the model is initialized, False otherwise.

with_random_slope_agebool (default True)

Has the LME a random slope for subject’s age? Otherwise it only has a random intercept per subject.

featureslist of str

List of the model features.

Warning

LME has only one feature.

dimensionint

Will always be 1 (univariate).

parametersdict
Contains the model parameters. In particular:
  • ages_meanfloat

    Mean of ages (for normalization).

  • ages_stdfloat

    Std-dev of ages (for normalization).

  • fe_paramsnp.ndarray of float

    Fixed effects.

  • cov_renp.ndarray

    Variance-covariance matrix of random-effects.

  • cov_re_unscaled_invnp.ndarray

    Inverse of unscaled (= divided by variance of noise) variance-covariance matrix of random-effects. This matrix is used for personalization to new subjects.

  • noise_stdfloat

    Std-dev of Gaussian noise.

  • bse_fe, bse_renp.ndarray of float

    Standard errors on fixed-effects and random-effects respectively (not used in Leaspy).

Parameters:
  • name (str)

  • with_random_slope_age (Optional[bool])

See also

LMEFitAlgorithm
LMEPersonalizeAlgorithm
with_random_slope_age = True
dimension = 1

Number of features.

Returns:
int, optional

The dimension of the model, or None if not initialized.

property hyperparameters: DictParamsTorch

Dictionary of values for model hyperparameters.

Return type:

DictParamsTorch

compute_individual_trajectory(timepoints, individual_parameters)[source]

Compute scores values at the given time-point(s) given a subject’s individual parameters.

Parameters:
timepointsarray-like of ages (not normalized)

Timepoints to compute individual trajectory at.

individual_parametersdict
Individual parameters:
  • random_intercept

  • random_slope_age (if with_random_slope_age == True)

Returns:
torch.Tensor of float

The individual trajectories. The shape of the tensor is (n_individuals == 1, n_tpts == len(timepoints), n_features == 1).

Parameters:
Return type:

Tensor

class LogisticModel(name, **kwargs)[source]

Bases: LogisticInitializationMixin, leaspy.models.riemanian_manifold.RiemanianManifoldModel

Manifold model for multiple variables of interest (logistic formulation).

Parameters:

name (str)

get_variables_specs()[source]

Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.

Returns:
NamedVariables

A dictionary-like object mapping variable names to their specifications.

Return type:

NamedVariables

static metric(*, g)[source]

Compute the metric tensor from input tensor g. This function calculates the metric as ((g + 1)^2 / g) element-wise.

Parameters:
gt torch.Tensor

Input tensor with values of the population parameter g for each feature.

Returns:
torch.Tensor

The computed metric tensor, same shape as g(number of features)

Parameters:

g (Tensor)

Return type:

Tensor

classmethod model_with_sources(*, rt, space_shifts, metric, v0, g)[source]

Return the model output when sources(spatial components) are present.

Parameters:
rtTensorOrWeightedTensor[float]

Tensor containing the reparametrized time.

space_shiftsTensorOrWeightedTensor[float]

Tensor containing the values of the space-shifts

metricTensorOrWeightedTensor[float]

Tensor containing the metric tensor used for computing the spatial/temporal influence.

v0TensorOrWeightedTensor[float]

Tensor containing the values of the population parameter v0 for each feature.

gTensorOrWeightedTensor[float]

Tensor containing the values of the population parameter g for each feature.

Returns:
torch.Tensor

Weighted value tensor after applying sigmoid transformation, representing the model output with sources.

Parameters:
Return type:

Tensor

class McmcSaemCompatibleModel(name, *, obs_models, fit_metrics=None, **kwargs)[source]

Bases: leaspy.models.stateful.StatefulModel

Defines probabilistic models compatible with an MCMC SAEM estimation.

Parameters:
namestr

The name of the model.

obs_modelsobs_models or Iterable [obs_models]

The noise model for observations (keyword-only parameter).

fit_metricsdict

Metrics that should be measured during the fit of the model and reported back to the user.

**kwargs

Hyperparameters for the model

Attributes:
is_initializedbool

Indicates if the model is initialized.

namestr

The model’s name.

featureslist [str]

Names of the model features.

parametersdict

Contains the model’s parameters

obs_modelstuple [obs_models, …]

The observation model(s) associated to the model.

fit_metricsdict

Contains the metrics that are measured during the fit of the model and reported to the user.

_stateState

Private instance holding all values for model variables and their derived variables.

Parameters:
obs_models
fit_metrics = None
property observation_model_names: list[str]

Get the names of the observation models.

Returns:
list [str]

The names of the observation models.

Return type:

list[str]

has_observation_model_with_name(name)[source]

Check if the model has an observation model with the given name. Parameters ———- name : str

The name of the observation model to check.

Returns:
bool:

True if the model has an observation model with the given name, False otherwise.

Parameters:

name (str)

Return type:

bool

to_dict(**kwargs)[source]

Export model as a dictionary ready for export.

Returns:
KwargsType

The model instance serialized as a dictionary.

Return type:

KwargsType

compute_individual_trajectory(timepoints, individual_parameters, *, skip_ips_checks=False)[source]

Compute scores values at the given time-point(s) given a subject’s individual parameters.

Note

The model uses its current internal state.

Parameters:
timepointsscalar or array_like [scalar] (list, tuple, numpy.ndarray)

Contains the age(s) of the subject.

individual_parametersDictParams

Contains the individual parameters. Each individual parameter should be a scalar or array_like.

skip_ips_checksbool (default: False)

Flag to skip consistency/compatibility checks and tensorization of individual_parameters when it was done earlier (speed-up).

Returns:
torch.Tensor

Contains the subject’s scores computed at the given age(s) Shape of tensor is (1, n_tpts, n_features).

Parameters:
Return type:

Tensor

compute_prior_trajectory(timepoints, prior_type, *, n_individuals=None)[source]

Compute trajectory of the model for prior mode or mean of individual parameters.

Parameters:
timepointstorch.Tensor [1, n_timepoints]

Contains the timepoints (age(s) of the subject).

prior_typeLatentVariableInitType

The type of prior to use for the individual parameters.

n_individualsint, optional

The number of individuals.

Returns:
torch.Tensor [1, n_timepoints, dimension]

The group-average values at given timepoints.

Raises:
LeaspyModelInputError

If n_individuals is provided but not a positive integer, or if it is provided while prior_type is not LatentVariableInitType.PRIOR_SAMPLES.

Parameters:
Return type:

TensorOrWeightedTensor[float]

compute_mean_traj(timepoints)[source]

Trajectory for average of individual parameters (not really meaningful for non-linear models).

Parameters:
timepointstorch.Tensor [1, n_timepoints]
Returns:
torch.Tensor [1, n_timepoints, dimension]

The group-average values at given timepoints.

Parameters:

timepoints (Tensor)

Return type:

TensorOrWeightedTensor[float]

compute_mode_traj(timepoints)[source]

Most typical individual trajectory.

Parameters:
timepointstorch.Tensor [1, n_timepoints]
Returns:
torch.Tensor [1, n_timepoints, dimension]

The group-average values at given timepoints.

Parameters:

timepoints (Tensor)

Return type:

TensorOrWeightedTensor[float]

abstractmethod compute_jacobian_tensorized(state)[source]

Compute the jacobian of the model w.r.t. each individual parameter, given the input state.

This function aims to be used in ScipyMinimize to speed up optimization.

Parameters:
stateState

Instance holding values for all model variables (including latent individual variables)

Returns:
DictParamsTorch

Tensors are of shape (n_individuals, n_timepoints, n_features, n_dims_param).

Raises:
NotImplementedError
Parameters:

state (State)

Return type:

DictParamsTorch

classmethod compute_sufficient_statistics(state)[source]

Compute sufficient statistics from state.

Parameters:
stateState
Returns:
SuffStatsRW

Contains the sufficient statistics computed from the state.

Parameters:

state (State)

Return type:

SuffStatsRW

classmethod update_parameters(state, sufficient_statistics, *, burn_in)[source]

Update model parameters of the provided state.

Parameters:
clsMcmcSaemCompatibleModel

Model class to which the parameters belong.

stateState

Instance holding values for all model variables (including latent individual variables)

sufficient_statisticsSuffStatsRO

Contains the sufficient statistics computed from the state.

burn_inbool

If True, the parameters are updated in a burn-in phase.

Parameters:
Return type:

None

get_variables_specs()[source]

Get the specifications of the variables used in the model.

Returns:
NamedVariables

Specifications of the variables used in the model, including timepoints and observation models.

Return type:

NamedVariables

abstractmethod put_individual_parameters(state, dataset)[source]

Put the individual parameters inside the provided state (in-place).

Raises:
NotImplementedError
Parameters:
put_data_variables(state, dataset)[source]

Put all the needed data variables inside the provided state (in-place).

Parameters:
stateState

Instance holding values for all model variables (including latent individual variables), as well as: - timepoints : torch.Tensor of shape (n_individuals, n_timepoints)

datasetDataset

The dataset containing the data to be put in the state.

Parameters:
Return type:

None

reset_data_variables(state)[source]

Reset all data variables inside the provided state (in-place).

Parameters:
stateState

Instance holding values for all model variables (including latent individual variables), as well as: - timepoints : torch.Tensor of shape (n_individuals, n_timepoints)

Parameters:

state (State)

Return type:

None

class RiemanianManifoldModel(name, variables_to_track=None, **kwargs)[source]

Bases: leaspy.models.time_reparametrized.TimeReparametrizedModel

Manifold model for multiple variables of interest (logistic or linear formulation).

Parameters:
namestr

The name of the model.

**kwargs

Hyperparameters of the model (including noise_model)

Raises:
LeaspyModelInputError
  • If hyperparameters are inconsistent

Parameters:
classmethod compute_sufficient_statistics(state)[source]

Compute the model’s sufficient statistics.

Parameters:
stateState

The state to pick values from.

Returns:
SuffStatsRW

The computed sufficient statistics.

Parameters:

state (State)

Return type:

SuffStatsRW

get_variables_specs()[source]

Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.

Returns:
NamedVariables

A dictionary-like object mapping variable names to their specifications. These include ModelParameter, Hyperparameter, PopulationLatentVariable, and LinkedVariable instances.

Return type:

NamedVariables

static metric(*, g)[source]
Abstractmethod:

Parameters:

g (Tensor)

Return type:

Tensor

classmethod model_no_sources(*, rt, metric, v0, g)[source]

Return the model output when sources(spatial components) are not present.

Parameters:
rttorch.Tensor

The reparametrized time.

metricAny

The metric tensor used for computing the spatial/temporal influence.

v0Any

The values of the population parameter v0 for each feature.

gAny

The values of the population parameter g for each feature.

Returns:
torch.Tensor

The model output without contribution from source shifts.

Parameters:

rt (Tensor)

Return type:

Tensor

Notes

This implementation delegates to model_with_sources with space_shifts set to a zero tensor of shape (1, 1), effectively removing source effects.

classmethod model_with_sources(*, rt, space_shifts, metric, v0, g)[source]
Abstractmethod:

Parameters:
Return type:

Tensor

class ModelSettings(path_to_model_settings_or_dict)[source]

Used in models.base.load to create a model class object from a json file.

Parameters:
path_to_model_settings_or_dictdict or str
  • If a str: path to a json file containing model settings

  • If a dict: content of model settings

Attributes:
namestr

The model’s name.

parametersKwargsType

The model’s parameters.

hyperparametersKwargsType

The model’s hyperparameters.

Raises:
LeaspyModelInputError

If the provided settings are not valid or if the file cannot be read.

Parameters:

path_to_model_settings_or_dict (Union[str, dict])

name: str
parameters: KwargsType
dataset_info: dict
training_info: dict
hyperparameters: KwargsType
class SharedSpeedLogisticModel(name, **kwargs)[source]

Bases: leaspy.models.logistic.LogisticInitializationMixin, leaspy.models.time_reparametrized.TimeReparametrizedModel

Logistic model for multiple variables of interest, imposing same average evolution pace for all variables (logistic curves are only time-shifted).

Parameters:
namestr

The name of the model.

**kwargs

Hyperparameters of the model.

Parameters:

name (str)

static metric(*, g_deltas_exp)[source]

Compute the metric term for the logistic model.

This scaling term modulates the curvature of the logistic trajectory.

Parameters:
g_deltas_exptorch.Tensor

Product of slope and exp(-deltas).

Returns:
torch.Tensor
Metric value, computed as:
\[\frac{(g \cdot e^{-\delta} + 1)^2}{g \cdot e^{-\delta}}\]
Parameters:

g_deltas_exp (Tensor)

Return type:

Tensor

static deltas_exp(*, deltas_padded)[source]

Compute the exponential of the negative deltas.

Parameters:

deltas_padded (torch.Tensor): Padded deltas.

Returns:

torch.Tensor: Exponential of the negative deltas.

Parameters:

deltas_padded (Tensor)

Return type:

Tensor

static g_deltas_exp(*, g, deltas_exp)[source]
Parameters:
Return type:

Tensor

static pad_deltas(*, deltas)[source]

Prepend deltas with a zero as delta_1 is set to zero in the equations. .

Parameters:

deltas (torch.Tensor): Deltas tensor.

Returns:

torch.Tensor: Padded deltas tensor.

Parameters:

deltas (Tensor)

Return type:

Tensor

static denom(*, g_deltas_exp)[source]

Compute the denominator for the \(\gamma_{t_0}\) calculation.

Parameters:

g_deltas_exp (Tensor)

Return type:

Tensor

static gamma_t0(*, denom)[source]

Compute the \(\gamma_{t_0}\) value, which is the inverse of the denominator.

Parameters:
denomtorch.Tensor

Denominator term.

Returns:
torch.Tensor

\(\gamma_{t_0}\) value.

Parameters:

denom (Tensor)

Return type:

Tensor

static g_metric(*, gamma_t0)[source]

Compute the g_metric value, which is the square of gamma_t0.

Parameters:
gamma_t0torch.Tensor

\(\gamma_{t_0}\) value.

Returns:
torch.Tensor
\(g_{metric}\) value, computed as:
\[g\_metric = \frac{1}{(\gamma_{t0} \cdot (1 - \gamma_{t0}))^2}\]
Parameters:

gamma_t0 (Tensor)

Return type:

Tensor

static collin_to_d_gamma_t0(*, deltas_exp, denom)[source]

Compute the collinear term to d_gamma_t0.

Parameters:
deltas_exptorch.Tensor

Exponential of the negative deltas.

denomtorch.Tensor

Denominator term.

Returns:
torch.Tensor

Collinear term to d_gamma_t0

Parameters:
Return type:

Tensor

classmethod model_with_sources(*, rt, space_shifts, metric, deltas_padded, log_g)[source]

Returns a model with sources.

Parameters:
Return type:

Tensor

classmethod model_no_sources(*, rt, metric, deltas_padded, log_g)[source]

Returns a model without sources.

Parameters:
Return type:

Tensor

get_variables_specs()[source]

Get the specifications of the variables used in the model.

Return type:

NamedVariables

class StatefulModel(name, **kwargs)[source]

Bases: leaspy.models.base.BaseModel

Stateful models have an internal State to handle parameters and variables.

Parameters:
namestr

The name of the model.

Attributes:
stateState

The internal state of the model, which contains the variables and their values.

tracked_variablesset [str]

Set of variable names that are tracked by the model. These variables are not necessarily part of the model’s state but are monitored for changes or updates. This can include variables that are relevant for the model’s operation but not directly stored in the state.

Parameters:

name (str)

tracked_variables: set[str]
track_variable(variable)[source]

Track a variable by its name.

Parameters

variableVariableName

The name of the variable to track. This variable will be monitored for changes or updates.

Parameters:

variable (VariableName)

Return type:

None

track_variables(variables)[source]

Track multiple variables by their names.

Parameters:
variablesIterable [VariableName]

An iterable containing the names of the variables to track. Each variable will be monitored for changes or updates.

Parameters:

variables (Iterable[VariableName])

Return type:

None

untrack_variable(variable)[source]

Untrack a variable by its name.

Parameters

variableVariableName

The name of the variable to untrack. This variable will no longer be monitored for changes or updates.

Parameters:

variable (VariableName)

Return type:

None

untrack_variables(variables)[source]

Untrack multiple variables by their names.

Parameters:
variablesIterable [VariableName]

An iterable containing the names of the variables to untrack. Each variable will no longer be monitored for changes or updates.

Parameters:

variables (Iterable[VariableName])

Return type:

None

property state: State

Get the internal state of the model.

Returns:
StateState

The internal state of the model, which contains the variables and their values.

Raises:
LeaspyModelInputError

If the model’s state is not initialized yet.

Return type:

State

property dag: VariablesDAG

Get the underlying DAG of the model’s state.

Returns:
: VariablesDAG

The directed acyclic graph (DAG) representing the model’s variables and their relationships

Return type:

VariablesDAG

property hyperparameters_names: tuple[VariableName, Ellipsis]

Get the names of the model’s hyperparameters.

Returns:
: tuple [VariableName, others…]

A tuple containing the names of the model’s hyperparameters.

Return type:

tuple[VariableName, Ellipsis]

property parameters_names: tuple[VariableName, Ellipsis]

Get the names of the model’s parameters.

Returns:
: tuple [VariableName, others…]

A tuple containing the names of the model’s parameters.

Return type:

tuple[VariableName, Ellipsis]

property population_variables_names: tuple[VariableName, Ellipsis]

Get the names of the population latent variables.

Returns:
: tuple [VariableName, …]

A tuple containing the names of the population latent variables.

Return type:

tuple[VariableName, Ellipsis]

property individual_variables_names: tuple[VariableName, Ellipsis]

Get the names of the individual latent variables.

Returns:
: tuple [VariableName, …]

A tuple containing the names of the individual latent variables.

Return type:

tuple[VariableName, Ellipsis]

property parameters: DictParamsTorch

Dictionary of values for model parameters.

Returns:
: DictParamsTorch

A dictionary mapping parameter names to their values (as tensors).

Return type:

DictParamsTorch

property hyperparameters: DictParamsTorch

Dictionary of values for model hyperparameters.

Returns:
: DictParamsTorch

A dictionary mapping hyperparameter names to their values (as tensors).

Return type:

DictParamsTorch

initialize(dataset=None)[source]

Overloads base model initialization (in particular to handle internal model State).

<!> We do not put data variables in internal model state at this stage (done in algorithm)

Parameters:
datasetDataset, optional

Input dataset from which to initialize the model.

Parameters:

dataset (Optional[Dataset])

Return type:

None

load_parameters(parameters)[source]

Instantiate or update the model’s parameters.

It assumes that all model hyperparameters are defined.

Parameters:
parametersKwargsType]

Contains the model’s parameters.

Parameters:

parameters (KwargsType)

Return type:

None

abstractmethod get_variables_specs()[source]

Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.

Returns:
NamedVariablesNamedVariables

The specifications of the model’s variables.

Return type:

NamedVariables

move_to_device(device)[source]

Move a model and its relevant attributes to the specified torch.device.

Parameters:
devicetorch.device

The device to which the model and its attributes should be moved.

Parameters:

device (device)

Return type:

None

class StatelessModel(name, **kwargs)[source]

Bases: leaspy.models.base.BaseModel

Stateless model do not use an internal state to keep track of variables.

Parameters are stored in an internal dictionary.

Parameters:
namestr

The name of the model.

Parameters:

name (str)

property parameters

Dictionary of values for model parameters.

Returns:
DictParamsTorch
Raises:
NotImplementedError
load_parameters(parameters)[source]

Instantiate or update the model’s parameters.

Parameters:
parametersdict

Contains the model’s parameters.

Parameters:

parameters (KwargsType)

Return type:

None

class TimeReparametrizedModel(name, source_dimension=None, **kwargs)[source]

Bases: leaspy.models.mcmc_saem_compatible.McmcSaemCompatibleModel

Contains the common attributes & methods of the multivariate time-reparametrized models.

Parameters:
namestr

Name of the model.

source_dimensionOptional[int]

Number of sources. Dimension of spatial components (default is None).

**kwargs

Hyperparameters for the model (including obs_models).

Raises:
LeaspyModelInputError

If inconsistent hyperparameters.

Parameters:
  • name (str)

  • source_dimension (Optional[int])

property xi_std: Tensor

Return the standard deviation of xi as a tensor.

Return type:

Tensor

property tau_std: Tensor

Return the standard deviation of tau as a tensor.

Return type:

Tensor

property noise_std: Tensor

Return the standard deviation of the model as a tensor.

Return type:

Tensor

property sources_std: float

Return the standard deviation of sources as a float.

Return type:

float

property source_dimension: int | None

Return the number of the sources

Return type:

Optional[int]

property has_sources: bool

Indicates whether the model includes sources.

Returns:
bool

True if source_dimension is a positive integer. False otherwise.

Return type:

bool

static time_reparametrization(*, t, alpha, tau)[source]

Tensorized time reparametrization formula.

Warning

Shapes of tensors must be compatible between them.

Parameters:
ttorch.Tensor

Timepoints to reparametrize

alphatorch.Tensor

Acceleration factors of individual(s)

tautorch.Tensor

Time-shift(s) of individual(s)

Returns:
torch.Tensor

Reparametrized time of same shape as timepoints

Parameters:
Return type:

TensorOrWeightedTensor[float]

get_variables_specs()[source]

Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.

Returns:
NamedVariables

A dictionary-like object containing specifications for the variables

Return type:

NamedVariables

put_individual_parameters(state, dataset)[source]

Initialize individual latent parameters in the given state if not already set.

Parameters:
stateState

The current state object that holds all the variables

datasetDataset

Dataset used to initialize latent variables accordingly.

Parameters:
to_dict(*, with_mixing_matrix=True)[source]

Export model object as dictionary ready for JSON saving.

Parameters:
with_mixing_matrixbool (default True)

Save the mixing matrix in the exported file in its ‘parameters’ section.

Warning

It is not a real parameter and its value will be overwritten at model loading (orthonormal basis is recomputed from other “true” parameters and mixing matrix is then deduced from this orthonormal basis and the betas)! It was integrated historically because it is used for convenience in browser webtool and only there…

Returns:
KwargsType

The object as a dictionary.

Parameters:

with_mixing_matrix (bool)

Return type:

KwargsType

abstractmethod compute_individual_ages_from_biomarker_values(value, individual_parameters, feature=None)[source]

For one individual, compute age(s) at which the given features values are reached (given the subject’s individual parameters).

Consistency checks are done in the main API layer.

Parameters:
valuescalar or array_like[scalar] (list, tuple, numpy.ndarray)

Contains the biomarker value(s) of the subject.

individual_parametersdict

Contains the individual parameters. Each individual parameter should be a scalar or array_like.

featurestr (or None)

Name of the considered biomarker.

Note

Optional for UnivariateModel, compulsory for MultivariateModel.

Returns:
torch.Tensor

Contains the subject’s ages computed at the given values(s). Shape of tensor is (1, n_values).

Raises:
LeaspyModelInputError

If computation is tried on more than 1 individual.

Parameters:
Return type:

Tensor

abstractmethod compute_individual_ages_from_biomarker_values_tensorized(value, individual_parameters, feature)[source]

For one individual, compute age(s) at which the given features values are reached (given the subject’s individual parameters), with tensorized inputs.

Parameters:
valuetorch.Tensor of shape (1, n_values)

Contains the biomarker value(s) of the subject.

individual_parametersDictParamsTorch

Contains the individual parameters. Each individual parameter should be a torch.Tensor.

featurestr (or None)

Name of the considered biomarker.

Note

Optional for UnivariateModel, compulsory for MultivariateModel.

Returns:
torch.Tensor

Contains the subject’s ages computed at the given values(s). Shape of tensor is (n_values, 1).

Parameters:
Return type:

Tensor

class LogisticMultivariateMixtureModel(name, **kwargs)[source]

Bases: LogisticMixtureInitializationMixin, RiemanianManifoldMixtureModel

Mixture Manifold model for multiple variables of interest (logistic formulation).

Parameters:

name (str)

get_variables_specs()[source]

Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.

Returns:
NamedVariables

A dictionary-like object mapping variable names to their specifications. These include ModelParameter, Hyperparameter, PopulationLatentVariable, and LinkedVariable instances.

Return type:

NamedVariables

static metric(*, g)[source]

Compute the metric tensor from input tensor g. This function calculates the metric as ((g + 1)^2 / g) element-wise.

Parameters:
gt torch.Tensor

Input tensor with values of the population parameter g for each feature.

Returns:
torch.Tensor

The computed metric tensor, same shape as g(number of features)

Parameters:

g (Tensor)

Return type:

Tensor

classmethod model_with_sources(*, rt, space_shifts, metric, v0, g)[source]

Return the model output when sources(spatial components) are present.

Parameters:
rtTensorOrWeightedTensor`[:obj:`float]

Tensor containing the reparametrized time.

space_shifts~leaspy.uitls.weighted_tensor._weighted_tensor.TensorOrWeightedTensor`[:obj:`float]

Tensor containing the values of the space-shifts

metric :`~leaspy.uitls.weighted_tensor._weighted_tensor.TensorOrWeightedTensor`[:obj:`float`]

Tensor containing the metric tensor used for computing the spatial/temporal influence.

v0~leaspy.uitls.weighted_tensor._weighted_tensor.TensorOrWeightedTensor`[:obj:`float]

Tensor containing the values of the population parameter v0 for each feature.

g~leaspy.uitls.weighted_tensor._weighted_tensor.TensorOrWeightedTensor`[:obj:`float]

Tensor containing the values of the population parameter g for each feature.

Returns:
torch.Tensor

Weighted value tensor after applying sigmoid transformation, representing the model output with sources.

Parameters:
Return type:

Tensor