leaspy.models

Submodules

Attributes

ModelType

Classes

BaseModel

Base model class from which all Leaspy models should inherit.

InitializationMethod

str(object='') -> str

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.

GenericModel

Generic model (temporary until AbstractModel is really abstract).

JointModel

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

LMEModel

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

McmcSaemCompatibleModel

Defines probabilistic models compatible with an MCMC SAEM estimation.

LinearModel

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

LogisticModel

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

RiemanianManifoldModel

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

ModelSettings

Used in Leaspy.load() to create a Leaspy class object from a json file.

SharedSpeedLogisticModel

Logistic model for multiple variables of interest, imposing same average

TimeReparametrizedModel

Contains the common attributes & methods of the multivariate models.

Functions

model_factory(name[, instance_name])

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

Package Contents

class BaseModel(name, **kwargs)

Bases: abc.ABC

Base model class from which all Leaspy models should inherit.

It defines the interface that a model should implement to be compatible with Leaspy.

Parameters:
namestr

The name of the model.

**kwargs

Hyperparameters of the model

Attributes:
namestr

The name of the model.

is_initializedbool

True``if the model is initialized, ``False otherwise.

featureslist of str

List of model features (None if not initialization).

dimensionint

Number of features.

Parameters:

name (str)

is_initialized: bool = False
name
property features: list[leaspy.utils.typing.FeatureType] | None
Return type:

Optional[list[leaspy.utils.typing.FeatureType]]

property dimension: int | None

The dimension of the model. If the private attribute is defined, then it takes precedence over the feature length. The associated setters are responsible for their coherence.

Return type:

Optional[int]

initialize(dataset=None, method=None)

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.

methodInitializationMethod, optional

A custom method to initialize the model

Parameters:
Return type:

None

abstractmethod save(path, **kwargs)

Save Leaspy object as json model parameter file.

Parameters:
pathstr

Path to store the model’s parameters.

**kwargs

Additional parameters for writing.

Parameters:

path (str)

Return type:

None

class InitializationMethod

Bases: str, enum.Enum

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

DEFAULT = 'default'
RANDOM = 'random'
class ConstantModel(name, **kwargs)

Bases: leaspy.models.generic.GenericModel

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.

**kwargs

Hyperparameters for the model. None supported for now.

Attributes:
namestr

The model’s name.

is_initializedbool

Always True (no true initialization needed for constant model).

featureslist of str

List of the model features. Unlike most models features will be determined at personalization only (because it does not needed any fit).

dimensionint

Number of features (read-only).

parametersdict

The model has no parameters: empty dictionary. The prediction_type parameter should be defined during personalization. Example:

>>> AlgorithmSettings('constant_prediction', prediction_type='last_known')
Parameters:

name (str)

See also

ConstantPredictionAlgorithm
is_initialized = True
compute_individual_trajectory(timepoints, individual_parameters)

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

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

Contains the age(s) of the subject.

individual_parametersdict [ str, Any]

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

Returns:
torch.Tensor

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

Parameters:
  • timepoints (Tensor)

  • individual_parameters (dict)

Return type:

Tensor

class ModelName

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'
model_factory(name, instance_name=None, **kwargs)

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

Parameters:
namestr or ModelName

The name of the model class to be instantiated.

instance_namestr, optional

The custom name of the instance to be created. If not provided, it will be the model class name.

**kwargs

Contains model’s hyper-parameters. Raise an error if the keyword is inappropriate for the given model’s name.

Returns:
BaseModel

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

Parameters:
Return type:

BaseModel

class GenericModel(name, **kwargs)

Bases: leaspy.models.base.BaseModel

Generic model (temporary until AbstractModel is really abstract).

TODO: change naming after AbstractModel was renamed?

Parameters:
namestr

The name of the model.

**kwargs

Hyperparameters of the model.

Attributes:
namestr

The name of the model.

is_initializedbool

True if the model is initialized, False otherwise.

featureslist of str

List of model features (None if not initialization).

dimensionint (read-only)

Number of features.

parametersdict

Contains internal parameters of the model.

Parameters:

name (str)

parameters: leaspy.utils.typing.KwargsType
get_hyperparameters(*, with_features=True, with_properties=True, default=None)

Get all model hyperparameters.

Parameters:
with_features, with_propertiesbool (default True)

Whether to include features and respectively all _properties (i.e. _dynamic_ hyperparameters) in the returned dictionary.

defaultAny

Default value is something is an hyperparameter is missing (should not!).

Returns:
:obj:`dict` { hyperparam_namestr -> hyperparam_valueAny }
Return type:

leaspy.utils.typing.KwargsType

hyperparameters_ok()

Check all model hyperparameters are ok.

Returns:
bool
Return type:

bool

load_parameters(parameters, *, list_converter=np.array)

Instantiate or update the model’s parameters.

Parameters:
parametersdict

Contains the model’s parameters.

list_convertercallable

The function to convert list objects.

Return type:

None

load_hyperparameters(hyperparameters, *, with_defaults=False)

Load model hyperparameters from a dict.

Parameters:
hyperparametersdict [ str, Any]

Contains the model’s hyperparameters.

with_defaultsbool (default False)

If True, it also resets hyperparameters that are part of the model but not included in hyperparameters to their default value.

Raises:
LeaspyModelInputError

If inconsistent hyperparameters.

Parameters:
  • hyperparameters (leaspy.utils.typing.KwargsType)

  • with_defaults (bool)

Return type:

None

save(path, **kwargs)

Save Leaspy object as JSON model parameter file.

Default save method: it can be overwritten in child class but should be generic…

Parameters:
pathstr

Path to store the model’s parameters.

**kwargs

Keyword arguments for json.dump method.

Parameters:

path (str)

Return type:

None

abstractmethod compute_individual_trajectory(timepoints, individual_parameters)

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

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

Contains the age(s) of the subject.

individual_parametersdict [ str, Any]

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

Returns:
torch.Tensor

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

Parameters:

individual_parameters (dict)

Return type:

Tensor

class JointModel(name, **kwargs)

Bases: leaspy.models.riemanian_manifold.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()

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)

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:

leaspy.utils.typing.KwargsType

put_individual_parameters(state, dataset)

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)

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:
  • individual_parameters (leaspy.utils.typing.DictParams)

  • skip_ips_checks (bool)

Return type:

Tensor

class LMEModel(name, **kwargs)

Bases: leaspy.models.generic.GenericModel

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? should inherit from AbstractModel. 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)

See also

LMEFitAlgorithm
LMEPersonalizeAlgorithm
dimension = 1

The dimension of the model. If the private attribute is defined, then it takes precedence over the feature length. The associated setters are responsible for their coherence.

compute_individual_trajectory(timepoints, individual_parameters)

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:

individual_parameters (dict)

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

Bases: leaspy.models.base.BaseModel

Defines probabilistic models compatible with an MCMC SAEM estimation.

Parameters:
namestr

The name of the model.

obs_modelsObservationModel or Iterable[ObservationModel]

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 of str

Names of the model features.

parametersdict

Contains the model’s parameters

obs_modelsTuple[ObservationModel, …]

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
tracked_variables: set[str]
track_variable(variable)
Parameters:

variable (leaspy.variables.specs.VariableName)

Return type:

None

track_variables(variables)
Parameters:

variables (Iterable[leaspy.variables.specs.VariableName])

Return type:

None

untrack_variable(variable)
Parameters:

variable (leaspy.variables.specs.VariableName)

Return type:

None

untrack_variables(variables)
Parameters:

variables (Iterable[leaspy.variables.specs.VariableName])

Return type:

None

property observation_model_names: list[str]
Return type:

list[str]

property state: State
Return type:

State

property dag: VariablesDAG
Return type:

VariablesDAG

property hyperparameters_names: tuple[leaspy.variables.specs.VariableName, Ellipsis]
Return type:

tuple[leaspy.variables.specs.VariableName, Ellipsis]

property parameters_names: tuple[leaspy.variables.specs.VariableName, Ellipsis]
Return type:

tuple[leaspy.variables.specs.VariableName, Ellipsis]

property population_variables_names: tuple[leaspy.variables.specs.VariableName, Ellipsis]
Return type:

tuple[leaspy.variables.specs.VariableName, Ellipsis]

property individual_variables_names: tuple[leaspy.variables.specs.VariableName, Ellipsis]
Return type:

tuple[leaspy.variables.specs.VariableName, Ellipsis]

property parameters: leaspy.utils.typing.DictParamsTorch

Dictionary of values for model parameters.

Return type:

leaspy.utils.typing.DictParamsTorch

property hyperparameters: leaspy.utils.typing.DictParamsTorch

Dictionary of values for model hyperparameters.

Return type:

leaspy.utils.typing.DictParamsTorch

has_observation_model_with_name(name)
Parameters:

name (str)

Return type:

bool

abstractmethod to_dict()

Export model as a dictionary ready for export.

Returns:
KwargsType

The model instance serialized as a dictionary.

Return type:

leaspy.utils.typing.KwargsType

save(path, **kwargs)

Save Leaspy object as json model parameter file.

TODO move logic upstream?

Parameters:
pathstr

Path to store the model’s parameters.

**kwargs

Keyword arguments for AbstractModel.to_dict() child method and json.dump function (default to indent=2).

Parameters:

path (str)

Return type:

None

load_parameters(parameters)

Instantiate or update the model’s parameters.

It assumes that all model hyperparameters are defined.

Parameters:
parametersdict [ str, Any ]

Contains the model’s parameters.

Parameters:

parameters (leaspy.utils.typing.KwargsType)

Return type:

None

compute_individual_trajectory(timepoints, individual_parameters, *, skip_ips_checks=False)

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_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:
  • individual_parameters (leaspy.utils.typing.DictParams)

  • skip_ips_checks (bool)

Return type:

Tensor

compute_prior_trajectory(timepoints, prior_type, *, n_individuals=None)

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

Parameters:
timepointstorch.Tensor [1, n_timepoints]
prior_typeLatentVariableInitType
n_individualsint, optional

The number of individuals.

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

The group-average values at given timepoints.

Parameters:
Return type:

leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float]

compute_mean_traj(timepoints)

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

Parameters:

timepoints (Tensor)

compute_mode_traj(timepoints)

Most typical individual trajectory.

Parameters:

timepoints (Tensor)

abstractmethod compute_jacobian_tensorized(state)

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), as well as: - timepoints : torch.Tensor of shape (n_individuals, n_timepoints)

Returns:
dict [ param_name: str, torch.Tensor ]

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

Parameters:

state (State)

Return type:

leaspy.utils.typing.DictParamsTorch

classmethod compute_sufficient_statistics(state)

Compute sufficient statistics from state.

Parameters:
stateState
Returns:
dict [ suff_stat: str, torch.Tensor]
Parameters:

state (State)

Return type:

leaspy.variables.specs.SuffStatsRW

classmethod update_parameters(state, sufficient_statistics, *, burn_in)

Update model parameters of the provided state.

Parameters:
stateState
sufficient_statisticsdict[suff_stat: str, torch.Tensor]
burn_inbool
Parameters:
  • state (State)

  • sufficient_statistics (leaspy.variables.specs.SuffStatsRO)

  • burn_in (bool)

Return type:

None

get_variables_specs()

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

initialize(dataset=None, method=None)

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.

methodInitializationMethod, optional

The initialization method to be used. Default=’default’.

Parameters:
Return type:

None

abstractmethod put_individual_parameters(state, dataset)
Parameters:
put_data_variables(state, dataset)

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

Parameters:
Return type:

None

reset_data_variables(state)

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

Parameters:

state (State)

Return type:

None

move_to_device(device)

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

Parameters:
devicetorch.device
Parameters:

device (device)

Return type:

None

class LinearModel(name, **kwargs)

Bases: LinearInitializationMixin, RiemanianManifoldModel

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

Parameters:

name (str)

get_variables_specs()

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

static metric(*, g)

Used to define the corresponding variable.

Parameters:

g (Tensor)

Return type:

Tensor

classmethod model_with_sources(*, rt, space_shifts, metric, v0, g)

Returns a model with sources.

Parameters:
Return type:

Tensor

class LogisticModel(name, **kwargs)

Bases: LogisticInitializationMixin, RiemanianManifoldModel

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

Parameters:

name (str)

get_variables_specs()

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

static metric(*, g)

Used to define the corresponding variable.

Parameters:

g (Tensor)

Return type:

Tensor

classmethod model_with_sources(*, rt, space_shifts, metric, v0, g)

Returns a model with sources.

Parameters:
  • rt (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • space_shifts (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • metric (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • v0 (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • g (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

Return type:

Tensor

class RiemanianManifoldModel(name, variables_to_track=None, **kwargs)

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:
  • name (str)

  • variables_to_track (Optional[Iterable[leaspy.variables.specs.VariableName]])

classmethod compute_sufficient_statistics(state)

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:

leaspy.variables.specs.SuffStatsRW

get_variables_specs()

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

static metric(*, g)
Abstractmethod:

Parameters:

g (Tensor)

Return type:

Tensor

classmethod model_no_sources(*, rt, metric, v0, g)

Returns a model without source. A bit dirty?

Parameters:

rt (Tensor)

Return type:

Tensor

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

Parameters:
Return type:

Tensor

class ModelSettings(path_to_model_settings_or_dict)

Used in Leaspy.load() to create a Leaspy 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

Raises:
LeaspyModelInputError
Parameters:

path_to_model_settings_or_dict (Union[str, dict])

name: str
parameters: leaspy.utils.typing.KwargsType
hyperparameters: leaspy.utils.typing.KwargsType
class SharedSpeedLogisticModel(name, **kwargs)

Bases: leaspy.models.riemanian_manifold.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)

Used to define the corresponding variable.

Parameters:

g_deltas_exp (Tensor)

Return type:

Tensor

static deltas_exp(*, deltas_padded)
Parameters:

deltas_padded (Tensor)

Return type:

Tensor

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

Tensor

static pad_deltas(*, deltas)

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

Parameters:

deltas (Tensor)

Return type:

Tensor

static denom(*, g_deltas_exp)
Parameters:

g_deltas_exp (Tensor)

Return type:

Tensor

static gamma_t0(*, denom)
Parameters:

denom (Tensor)

Return type:

Tensor

static g_metric(*, gamma_t0)
Parameters:

gamma_t0 (Tensor)

Return type:

Tensor

static collin_to_d_gamma_t0(*, deltas_exp, denom)
Parameters:
Return type:

Tensor

classmethod model_with_sources(*, rt, space_shifts, metric, deltas_padded, log_g)

Returns a model with sources.

Parameters:
  • rt (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • space_shifts (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • metric (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • deltas_padded (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • log_g (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

Return type:

Tensor

classmethod model_no_sources(*, rt, metric, deltas_padded, log_g)

Returns a model without source. A bit dirty?

Parameters:
  • rt (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • metric (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • deltas_padded (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • log_g (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

Return type:

Tensor

get_variables_specs()

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

class TimeReparametrizedModel(name, source_dimension=None, **kwargs)

Bases: leaspy.models.mcmc_saem_compatible.McmcSaemCompatibleModel

Contains the common attributes & methods of the multivariate models.

Parameters:
namestr

Name of the model.

**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 type:

Tensor

property tau_std: Tensor
Return type:

Tensor

property noise_std: Tensor
Return type:

Tensor

property sources_std: float
Return type:

float

property source_dimension: int | None
Return type:

Optional[int]

property has_sources: bool
Return type:

bool

static time_reparametrization(*, t, alpha, tau)

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).

Returns:
torch.Tensor of same shape as timepoints
Parameters:
  • t (leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float])

  • alpha (Tensor)

  • tau (Tensor)

Return type:

leaspy.utils.weighted_tensor.TensorOrWeightedTensor[float]

get_variables_specs()

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

put_individual_parameters(state, dataset)
Parameters:
to_dict(*, with_mixing_matrix=True)

Export Leaspy 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:

leaspy.utils.typing.KwargsType

abstractmethod compute_individual_ages_from_biomarker_values(value, individual_parameters, feature=None)

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:
  • value (Union[float, list[float]])

  • individual_parameters (leaspy.utils.typing.DictParams)

  • feature (Optional[leaspy.utils.typing.FeatureType])

Return type:

Tensor

abstractmethod compute_individual_ages_from_biomarker_values_tensorized(value, individual_parameters, feature)

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:
  • value (Tensor)

  • individual_parameters (leaspy.utils.typing.DictParamsTorch)

  • feature (Optional[leaspy.utils.typing.FeatureType])

Return type:

Tensor

ModelType