leaspy.models ============= .. py:module:: leaspy.models Submodules ---------- .. toctree:: :maxdepth: 1 /reference/api/leaspy/models/base/index /reference/api/leaspy/models/constant/index /reference/api/leaspy/models/factory/index /reference/api/leaspy/models/joint/index /reference/api/leaspy/models/linear/index /reference/api/leaspy/models/lme/index /reference/api/leaspy/models/logistic/index /reference/api/leaspy/models/mcmc_saem_compatible/index /reference/api/leaspy/models/mixture/index /reference/api/leaspy/models/obs_models/index /reference/api/leaspy/models/riemanian_manifold/index /reference/api/leaspy/models/settings/index /reference/api/leaspy/models/shared_speed_logistic/index /reference/api/leaspy/models/stateful/index /reference/api/leaspy/models/stateless/index /reference/api/leaspy/models/time_reparametrized/index /reference/api/leaspy/models/utilities/index /reference/api/leaspy/models/utils/index Classes ------- .. autoapisummary:: leaspy.models.BaseModel leaspy.models.ModelInterface leaspy.models.ConstantModel leaspy.models.ModelName leaspy.models.JointModel leaspy.models.LinearModel leaspy.models.LMEModel leaspy.models.LogisticModel leaspy.models.McmcSaemCompatibleModel leaspy.models.RiemanianManifoldModel leaspy.models.ModelSettings leaspy.models.SharedSpeedLogisticModel leaspy.models.StatefulModel leaspy.models.StatelessModel leaspy.models.TimeReparametrizedModel leaspy.models.LogisticMultivariateMixtureModel Functions --------- .. autoapisummary:: leaspy.models.model_factory Package Contents ---------------- .. py:class:: BaseModel(name, **kwargs) Bases: :py:obj:`ModelInterface` Base model class from which all ``Leaspy`` models should inherit. It implements the :class:`~leaspy.models.ModelInterface`. .. !! processed by numpydoc !! .. py:attribute:: initialization_method :type: InitializationMethod .. py:property:: name :type: str The name of the model. :Returns: :obj:`str` The name of the model. .. !! processed by numpydoc !! .. py:property:: is_initialized :type: bool True if the model is initialized, False otherwise. :Returns: :obj:`bool` True if the model is initialized, False otherwise. .. !! processed by numpydoc !! .. py:property:: features :type: Optional[list[leaspy.utils.typing.FeatureType]] List of model features (`None` if not initialization). :Returns: : :obj:`list` [:obj:`FeatureType`], optional The features of the model, or None if not initialized. .. !! processed by numpydoc !! .. py:property:: dimension :type: Optional[int] Number of features. :Returns: :obj:`int`, optional The dimension of the model, or None if not initialized. .. !! processed by numpydoc !! .. py:method:: initialize(dataset = None) Initialize the model given a :class:`~leaspy.io.data.dataset.Dataset` and an initialization method. After calling this method :attr:`is_initialized` should be ``True`` and model should be ready for use. :Parameters: **dataset** : :class:`~leaspy.io.data.dataset.Dataset`, optional The dataset we want to initialize from. .. !! processed by numpydoc !! .. py:method:: save(path, **kwargs) Save model as json model parameter file. :Parameters: **path** : :obj:`str` or :obj:`Path` The path to store the model's parameters. **\*\*kwargs** : :obj:`dict` Additional parameters for writing. :Raises: :exc:`.LeaspyModelInputError` If the model is not initialized. .. !! processed by numpydoc !! .. py:method:: to_dict(**kwargs) Export model as a dictionary ready for export. :Returns: :obj:`KwargsType` The model instance serialized as a dictionary. .. !! processed by numpydoc !! .. py:method:: load(path_to_model_settings) :classmethod: Load a model from a json model parameter file. :Parameters: **path_to_model_settings** : :obj:`str` or :obj:`Path` The path to the model's parameters file. :Returns: :class:`~leasp.models.base.BaseModel` An instance of the model loaded from the file. :Raises: :exc:`.LeaspyModelInputError` If the model settings file is not found or cannot be read. .. !! processed by numpydoc !! .. py:method:: load_parameters(parameters) :abstractmethod: Load model parameters from a dictionary. :Parameters: **parameters** : :obj:`KwargsType` The parameters to load into the model. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:method:: fit(data = None, algorithm = None, algorithm_settings = None, algorithm_settings_path = None, **kwargs) 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: **data** : :obj:`pd.DataFrame` or :class:`~leaspy.io.Data` or :class:`~leaspy.io.Dataset`, optional Contains the information of the individuals, in particular the time-points :math:`(t_{i,j})` and the observations :math:`(y_{i,j})`. **algorithm** : :obj:`str` or :class:`~leaspy.algo.base.AlgorithmName`, optional The name of the algorithm to use. Use this if you want to provide algorithm settings through kwargs. **algorithm_settings** : :class:`~leaspy.algo.AlgorithmSettings`, optional The algorithm settings to use. Use this if you want to customize algorithm settings through the :class:`~leaspy.algo.AlgorithmSettings` class. If provided, the fit will rely on these settings. **algorithm_settings_path** : :obj:`str` or :obj:`Path`, optional The path to the algorithm settings file. If provided, the settings from the file will be used instead of the settings provided. **\*\*kwargs** : :obj:`dict` Contains the algorithm's settings. .. !! processed by numpydoc !! .. py:method:: personalize(data = None, algorithm = None, algorithm_settings = None, algorithm_settings_path = None, **kwargs) Estimate individual parameters for each `ID` of a given dataset. These individual parameters correspond to the random-effects :math:`(z_{i,j})` of the mixed-effects model. :Parameters: **data** : :obj:`pd.DataFrame` or :class:`~leaspy.io.Data` or :class:`~leaspy.io.Dataset`, optional Contains the information of the individuals, in particular the time-points :math:`(t_{i,j})` and the observations :math:`(y_{i,j})`. **algorithm** : :obj:`str` or :class:`~leaspy.algo.base.AlgorithmName`, optional The name of the algorithm to use. **algorithm_settings** : :class:`~leaspy.algo.AlgorithmSettings`, optional The algorithm settings to use. Use this if you want to customize algorithm settings through the :class:`~leaspy.algo.AlgorithmSettings` class. If provided, the fit will rely on these settings. **algorithm_settings_path** : :obj:`str` or :obj:`Path`, optional The path to the algorithm settings file. If provided, the settings from the file will be used instead of the settings provided. **\*\*kwargs** : :obj:`dict` Contains the algorithm's settings. :Returns: :class:`~leaspy.io.outputs.IndividualParameters` Individual parameters computed. .. !! processed by numpydoc !! .. py:method:: estimate(timepoints, individual_parameters, *, to_dataframe = None) Return the model values for individuals characterized by their individual parameters :math:`z_i` at time-points :math:`(t_{i,j})_j`. :Parameters: **timepoints** : :obj:`pd.MultiIndex` or :obj:`dict` [:obj:`IDType`, :obj:`list` [:obj:`float`]] Contains, for each individual, the time-points to estimate. It can be a unique time-point or a list of time-points. **individual_parameters** : :class:`~leaspy.io.IndividualParameters` Corresponds to the individual parameters of individuals. **to_dataframe** : :obj:`bool`, 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_trajectory** : :obj:`pd.DataFrame` or :obj:`dict` [:obj:`IDType`, :obj:`np.ndarray`] Key: patient indices. Value: :class:`numpy.ndarray` of the estimated value, in the shape (number of timepoints, number of features) .. !! processed by numpydoc !! .. py:method:: compute_individual_trajectory(timepoints, individual_parameters) :abstractmethod: Compute the model values for an individual characterized by their individual parameters at given time-points. :Parameters: **timepoints** : :obj:`list` [:obj:`float`] The time-points at which to compute the model values. **individual_parameters** : :class:`~leaspy.io.IndividualParameters` The individual parameters of the individual. :Returns: :class:`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. .. !! processed by numpydoc !! .. py:method:: simulate(algorithm = None, algorithm_settings = None, algorithm_settings_path = None, **kwargs) 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: **algorithm** : :obj:`str` or :class:`~leaspy.algo.base.AlgorithmName`, optional The name of the algorithm to use. Use this if you want to provide algorithm settings through kwargs. **algorithm_settings** : :class:`~leaspy.algo.AlgorithmSettings`, optional The algorithm settings to use. Use this if you want to customize algorithm settings through the :class:`~leaspy.algo.AlgorithmSettings` class. If provided, the fit will rely on these settings. **algorithm_settings_path** : :obj:`str` or :obj:`Path`, optional The path to the algorithm settings file. If provided, the settings from the file will be used instead of the settings provided. **\*\*kwargs** : :obj:`dict` Contains the algorithm's settings. :Returns: **simulated_data** : :class:`~leaspy.io.outputs.result.Result` Contains the generated individual parameters & the corresponding generated scores. Returns empty Result if any required input is None. .. rubric:: 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. .. rubric:: 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 ) .. !! processed by numpydoc !! .. py:class:: ModelInterface Bases: :py:obj:`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. .. !! processed by numpydoc !! .. py:property:: name :type: str :abstractmethod: The name of the model. :Returns: :obj:`str` .. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:property:: is_initialized :type: bool :abstractmethod: True if the model is initialized, False otherwise. :Returns: :obj:`bool` .. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:property:: dimension :type: int :abstractmethod: Number of features. :Returns: :obj:`int` .. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:property:: features :type: list[leaspy.utils.typing.FeatureType] :abstractmethod: List of model features (`None` if not initialization). :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:property:: parameters :type: leaspy.utils.typing.DictParamsTorch :abstractmethod: Dictionary of values for model parameters. :Returns: :class:`~leaspy.utils.typing.DictParamsTorch` .. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:property:: hyperparameters :type: leaspy.utils.typing.DictParamsTorch :abstractmethod: Dictionary of values for model hyperparameters. :Returns: :class:`~leaspy.utils.typing.DictParamsTorch` .. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:method:: save(path, **kwargs) :abstractmethod: Save model as json model parameter file. :Parameters: **path** : :obj:`str` or :obj:`Path` The path to store the model's parameters. **\*\*kwargs** : :obj:`dict` Additional parameters for writing. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:method:: load(path_to_model_settings) :classmethod: :abstractmethod: Load a model from a json model parameter file. :Parameters: **path_to_model_settings** : :obj:`str` or :obj:`Path` The path to the model's parameters file. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:method:: fit(data = None, algorithm = None, algorithm_settings = None, algorithm_settings_path = None, **kwargs) :abstractmethod: Estimate the model's parameters :math:`\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 :class:`~leaspy.algo.AlgorithmSettings` 2. By providing a path to a serialized :class:`~leaspy.algo.AlgorithmSettings` 3. By providing the algorithm name and parameters directly If settings are provided in multiple ways, the order above will prevail. :Parameters: **data** : :obj:`pd.DataFrame` or :class:`~leaspy.io.Data` or :class:`~leaspy.io.Dataset`, optional Contains the information of the individuals, in particular the time-points :math:`(t_{i,j})` and the observations :math:`(y_{i,j})`. **algorithm** : :obj:`str` or :class:`~leaspy.algo.base.AlgorithmName`,optional The name of the algorithm to use. .. note:: Use this if you want to provide algorithm settings through kwargs. **algorithm_settings** : :class:`~leaspy.algo.AlgorithmSettings`, optional The algorithm settings to use. .. note:: Use this if you want to customize algorithm settings through the :class:`~leaspy.algo.AlgorithmSettings` class. If provided, the fit will rely on these settings. **algorithm_settings_path** : :obj:`str` or :obj:`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. **\*\*kwargs** : :obj:`dict` Contains the algorithm's settings. :Raises: NotImplementedError .. .. rubric:: 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] .. !! processed by numpydoc !! .. py:method:: personalize(data = None, algorithm = None, algorithm_settings = None, algorithm_settings_path = None, **kwargs) :abstractmethod: Estimate individual parameters for each `ID` of a given dataset. These individual parameters correspond to the random-effects :math:`(z_{i,j})` of the mixed-effects model. :Parameters: **data** : :obj:`pd.DataFrame` or :class:`~leaspy.io.Data` or :class:`~leaspy.io.Dataset`, optional Contains the information of the individuals, in particular the time-points :math:`(t_{i,j})` and the observations :math:`(y_{i,j})`. **algorithm** : :obj:`str` or :class:`~leaspy.algo.base.AlgorithmName`, optional The name of the algorithm to use. **algorithm_settings** : :class:`~leaspy.algo.AlgorithmSettings`, optional The algorithm settings to use. .. note:: Use this if you want to customize algorithm settings through the :class:`~leaspy.algo.AlgorithmSettings` class. If provided, the fit will rely on these settings. **algorithm_settings_path** : :obj:`str` or :obj:`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. **\*\*kwargs** : :obj:`dict` Contains the algorithm's settings. :Returns: **ips** : :class:`~leaspy.io.IndividualParameters` Individual parameters computed. :Raises: NotImplementedError .. .. rubric:: 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) .. !! processed by numpydoc !! .. py:method:: estimate(timepoints, individual_parameters, *, to_dataframe = None) :abstractmethod: Return the model values for individuals characterized by their individual parameters :math:`z_i` at time-points :math:`(t_{i,j})_j`. :Parameters: **timepoints** : :obj:`pd.MultiIndex` or :obj:`dict` [:obj:`IDType`, :obj:`list` [:obj:`float` ] ] Contains, for each individual, the time-points to estimate. It can be a unique time-point or a list of time-points. **individual_parameters** : :class:`~leaspy.io.IndividualParameters` Corresponds to the individual parameters of individuals. **to_dataframe** : :obj:`bool`, 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_trajectory** : :obj:`pd.MultiIndex` or :obj:`dict` [:obj:`IDType`, :obj:`list` [:obj:`float`]] Key: patient indices. Value: :class:`numpy.ndarray` of the estimated value, in the shape (number of timepoints, number of features) :Raises: NotImplementedError .. .. rubric:: 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) .. !! processed by numpydoc !! .. py:method:: simulate(individual_parameters, data = None, **kwargs) :abstractmethod: 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_parameters** : :class:`~leaspy.io.IndividualParameters` Individual parameters to use for the simulation. **data** : :obj:`pd.DataFrame` or :class:`~leaspy.io.Data` or :class:`~leaspy.io.Dataset` Data object. If None, returns empty Result. **\*\*kwargs** : :obj:`dict` Additional arguments for algorithm settings. :Returns: **simulated_data** : :class:`~leaspy.io.outputs.result.Result` Contains the generated individual parameters & the corresponding generated scores. Returns empty Result if any required input is None. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:class:: ConstantModel(name, **kwargs) Bases: :py:obj:`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 :term:`calibration`. It could predict: * ``last``: last value seen during calibration (even if ``NaN``). * ``last_known``: last non ``NaN`` value seen during :term:`calibration`. * ``max``: maximum (=worst) value seen during :term:`calibration`. * ``mean``: average of values seen during :term:`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: **name** : :obj:`str` The model's name. .. seealso:: :class:`~leaspy.algo.personalize.constant_prediction_algo.ConstantPredictionAlgorithm` .. .. !! processed by numpydoc !! .. py:property:: hyperparameters :type: leaspy.utils.typing.DictParamsTorch Dictionary of values for model hyperparameters. :Returns: :class:`~leaspy.utils.typing.DictParamsTorch` Dictionary of hyperparameters. .. !! processed by numpydoc !! .. py:method:: compute_individual_trajectory(timepoints, individual_parameters) Compute the individual trajectory based on the model's features and parameters. :Parameters: **timepoints** : :obj:`torch.Tensor` The time points at which to compute the trajectory. **individual_parameters** : :obj:`dict` Dictionary containing the individual's parameters, where keys are feature names. :Returns: :obj:`torch.Tensor` A tensor containing the computed trajectory for the individual. :Raises: :class:`~leaspy.exceptions.LeaspyModelInputError` If the model was not properly initialized or if features are not set. .. !! processed by numpydoc !! .. py:class:: ModelName Bases: :py:obj:`str`, :py:obj:`enum.Enum` The available models that users can instantiate in Leaspy. .. !! processed by numpydoc !! .. py:attribute:: JOINT :value: 'joint' .. py:attribute:: LOGISTIC :value: 'logistic' .. py:attribute:: LINEAR :value: 'linear' .. py:attribute:: SHARED_SPEED_LOGISTIC :value: 'shared_speed_logistic' .. py:attribute:: LME :value: 'lme' .. py:attribute:: CONSTANT :value: 'constant' .. py:attribute:: MIXTURE_LOGISTIC :value: 'mixture_logistic' .. py:function:: model_factory(name, instance_name = None, **kwargs) Return the model object corresponding to ``name`` arg with possible ``kwargs``. :Parameters: **name** : :obj:`str` 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_name** : :obj:`str`, 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: :class:`~leaspy.models.base.BaseModel` A child class object of :class:`~leaspy.models.base.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. .. !! processed by numpydoc !! .. py:class:: JointModel(name, **kwargs) Bases: :py:obj:`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: **name** : :obj:`str` The name of the model. **\*\*kwargs** Hyperparameters of the model (including `noise_model`) :Raises: :exc:`.LeaspyModelInputError` * If `name` is not one of allowed sub-type: 'univariate_linear' or 'univariate_logistic' * If hyperparameters are inconsistent .. !! processed by numpydoc !! .. py:attribute:: init_tolerance :type: float :value: 0.3 .. py:method:: 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. .. !! processed by numpydoc !! .. py:method:: 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_matrix** : :obj:`bool` If True the mixing matrix will be saved in the dictionary :Returns: KwargsType The model instance serialized as a dictionary. .. !! processed by numpydoc !! .. py:method:: put_individual_parameters(state, dataset) Initialise the individual parameters of the state thanks to the dataset. :Parameters: **state** : :class:`State` where all the variables of the model are stored **dataset** : :class:`Dataset` Where the individual data are stored :Returns: None .. .. !! processed by numpydoc !! .. py:method:: 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: **timepoints** : scalar or array_like[scalar] (:obj:`list`, :obj:`tuple`, :class:`numpy.ndarray`) Contains the age(s) of the subject. **individual_parameters** : :obj:`dict` Contains the individual parameters. Each individual parameter should be a scalar or array_like. **skip_ips_checks** : :obj:`bool` (default: ``False``) Flag to skip consistency/compatibility checks and tensorization of ``individual_parameters`` when it was done earlier (speed-up). :Returns: :class:`torch.Tensor` Contains the subject's scores computed at the given age(s) Shape of tensor is ``(1, n_tpts, n_features)``. :Raises: :exc:`.LeaspyModelInputError` If computation is tried on more than 1 individual. :exc:`.LeaspyIndividualParamsInputError` if invalid individual parameters. .. !! processed by numpydoc !! .. py:class:: LinearModel(name, **kwargs) Bases: :py:obj:`LinearInitializationMixin`, :py:obj:`leaspy.models.riemanian_manifold.RiemanianManifoldModel` Manifold model for multiple variables of interest (linear formulation). .. !! processed by numpydoc !! .. py:method:: get_variables_specs() 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. .. !! processed by numpydoc !! .. py:method:: metric(*, g) :staticmethod: Compute the metric tensor for the model. :Parameters: **g** : :class:`torch.Tensor` Input tensor with values of the population parameter `g` for each feature. :Returns: :class:`torch.Tensor` A tensor of ones with the same shape as `g`. .. !! processed by numpydoc !! .. py:method:: model_with_sources(*, rt, space_shifts, metric, v0, g) :classmethod: Return the model output when sources(spatial components) are present. :Parameters: **rt** : :class:`torch.Tensor` The reparametrized time. **space_shifts** : :class:`torch.Tensor` The values of the space-shifts **metric** : Any The metric tensor used for computing the spatial/temporal influence. **v0** : Any The values of the population parameter `v0` for each feature. **g** : Any The values of the population parameter `g` for each feature. :Returns: :class:`torch.Tensor` The model output with contribution from sources. .. !! processed by numpydoc !! .. py:class:: LMEModel(name, with_random_slope_age = True, **kwargs) Bases: :py:obj:`leaspy.models.stateless.StatelessModel` LMEModel is a benchmark model that fits and personalize a linear mixed-effects model. The model specification is the following: .. math:: y_{ij} = fixed_{intercept} + random_{intercept_i} + (fixed_{slopeAge} + random_{slopeAge_i}) * age_{ij} + \epsilon_{ij} with: * :math:`y_{ij}`: value of the feature of the i-th subject at his j-th visit, * :math:`age_{ij}`: age of the i-th subject at his j-th visit. * :math:`\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: **name** : :obj:`str` The model's name. **\*\*kwargs** Model hyperparameters: * with_random_slope_age : :obj:`bool` (default ``True``). :Attributes: **name** : :obj:`str` The model's name. **is_initialized** : :obj:`bool` ``True`` if the model is initialized, ``False`` otherwise. **with_random_slope_age** : :obj:`bool` (default ``True``) Has the LME a random slope for subject's age? Otherwise it only has a random intercept per subject. **features** : :obj:`list` of :obj:`str` List of the model features. .. warning:: LME has only one feature. **dimension** : :obj:`int` Will always be 1 (univariate). **parameters** : :obj:`dict` Contains the model parameters. In particular: * ``ages_mean`` : :obj:`float` Mean of ages (for normalization). * ``ages_std`` : :obj:`float` Std-dev of ages (for normalization). * ``fe_params`` : :class:`np.ndarray` of :obj:`float` Fixed effects. * ``cov_re`` : :class:`np.ndarray` Variance-covariance matrix of random-effects. * ``cov_re_unscaled_inv`` : :class:`np.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_std`` : :obj:`float` Std-dev of Gaussian noise. * ``bse_fe``, ``bse_re`` : :class:`np.ndarray` of :obj:`float` Standard errors on fixed-effects and random-effects respectively (not used in ``Leaspy``). .. seealso:: :class:`~leaspy.algo.others.lme_fit.LMEFitAlgorithm` .. :class:`~leaspy.algo.others.lme_personalize.LMEPersonalizeAlgorithm` .. .. !! processed by numpydoc !! .. py:attribute:: with_random_slope_age :value: True .. py:attribute:: dimension :value: 1 Number of features. :Returns: :obj:`int`, optional The dimension of the model, or None if not initialized. .. !! processed by numpydoc !! .. py:property:: hyperparameters :type: leaspy.utils.typing.DictParamsTorch Dictionary of values for model hyperparameters. .. !! processed by numpydoc !! .. py:method:: compute_individual_trajectory(timepoints, individual_parameters) Compute scores values at the given time-point(s) given a subject's individual parameters. :Parameters: **timepoints** : array-like of ages (not normalized) Timepoints to compute individual trajectory at. **individual_parameters** : :obj:`dict` Individual parameters: * random_intercept * random_slope_age (if ``with_random_slope_age == True``) :Returns: :class:`torch.Tensor` of :obj:`float` The individual trajectories. The shape of the tensor is ``(n_individuals == 1, n_tpts == len(timepoints), n_features == 1)``. .. !! processed by numpydoc !! .. py:class:: LogisticModel(name, **kwargs) Bases: :py:obj:`LogisticInitializationMixin`, :py:obj:`leaspy.models.riemanian_manifold.RiemanianManifoldModel` Manifold model for multiple variables of interest (logistic formulation). .. !! processed by numpydoc !! .. py:method:: get_variables_specs() 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. .. !! processed by numpydoc !! .. py:method:: metric(*, g) :staticmethod: Compute the metric tensor from input tensor `g`. This function calculates the metric as \((g + 1)^2 / g\) element-wise. :Parameters: **g** : :class:`torch.Tensor` Input tensor with values of the population parameter `g` for each feature. :Returns: :class:`torch.Tensor` The computed metric tensor, same shape as g(number of features) .. !! processed by numpydoc !! .. py:method:: model_with_sources(*, rt, space_shifts, metric, v0, g) :classmethod: Return the model output when sources(spatial components) are present. :Parameters: **rt** : TensorOrWeightedTensor[float] Tensor containing the reparametrized time. **space_shifts** : TensorOrWeightedTensor[float] Tensor containing the values of the space-shifts **metric** : TensorOrWeightedTensor[float] Tensor containing the metric tensor used for computing the spatial/temporal influence. **v0** : TensorOrWeightedTensor[float] Tensor containing the values of the population parameter `v0` for each feature. **g** : TensorOrWeightedTensor[float] Tensor containing the values of the population parameter `g` for each feature. :Returns: :class:`torch.Tensor` Weighted value tensor after applying sigmoid transformation, representing the model output with sources. .. !! processed by numpydoc !! .. py:class:: McmcSaemCompatibleModel(name, *, obs_models, fit_metrics = None, **kwargs) Bases: :py:obj:`leaspy.models.stateful.StatefulModel` Defines probabilistic models compatible with an MCMC SAEM estimation. :Parameters: **name** : :obj:`str` The name of the model. **obs_models** : :class:`~leaspy.models.obs_models` or :class:`~typing.Iterable` [:class:`~leaspy.models.obs_models`] The noise model for observations (keyword-only parameter). **fit_metrics** : :obj:`dict` Metrics that should be measured during the fit of the model and reported back to the user. **\*\*kwargs** Hyperparameters for the model :Attributes: **is_initialized** : :obj:`bool` Indicates if the model is initialized. **name** : :obj:`str` The model's name. **features** : :obj:`list` [:obj:`str`] Names of the model features. **parameters** : :obj:`dict` Contains the model's parameters **obs_models** : :obj:`tuple` [:class:`~leaspy.models.obs_models`, ...] The observation model(s) associated to the model. **fit_metrics** : :obj:`dict` Contains the metrics that are measured during the fit of the model and reported to the user. **_state** : :class:`~leaspy.variables.state.State` Private instance holding all values for model variables and their derived variables. .. !! processed by numpydoc !! .. py:attribute:: obs_models .. py:attribute:: fit_metrics :value: None .. py:property:: observation_model_names :type: list[str] Get the names of the observation models. :Returns: :obj:`list` [:obj:`str`] The names of the observation models. .. !! processed by numpydoc !! .. py:method:: has_observation_model_with_name(name) Check if the model has an observation model with the given name. :Parameters: **name** : :obj:`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. .. !! processed by numpydoc !! .. py:method:: to_dict(**kwargs) Export model as a dictionary ready for export. :Returns: :class:`~leaspy.utils.typing.KwargsType` The model instance serialized as a dictionary. .. !! processed by numpydoc !! .. py:method:: 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: **timepoints** : :obj:`scalar` or :obj:`array_like` [:obj:`scalar`] (:obj:`list`, :obj:`tuple`, :class:`numpy.ndarray`) Contains the age(s) of the subject. **individual_parameters** : :class:`~leaspy.utils.typing.DictParams` Contains the individual parameters. Each individual parameter should be a scalar or array_like. **skip_ips_checks** : :obj:`bool` (default: ``False``) Flag to skip consistency/compatibility checks and tensorization of ``individual_parameters`` when it was done earlier (speed-up). :Returns: :class:`torch.Tensor` Contains the subject's scores computed at the given age(s) Shape of tensor is ``(1, n_tpts, n_features)``. .. !! processed by numpydoc !! .. py:method:: compute_prior_trajectory(timepoints, prior_type, *, n_individuals = None) Compute trajectory of the model for prior mode or mean of individual parameters. :Parameters: **timepoints** : :obj:`torch.Tensor` [1, n_timepoints] Contains the timepoints (age(s) of the subject). **prior_type** : :class:`~leaspy.variables.specs.LatentVariableInitType` The type of prior to use for the individual parameters. **n_individuals** : :obj:`int`, optional The number of individuals. :Returns: :class:`torch.Tensor` [1, n_timepoints, dimension] The group-average values at given timepoints. :Raises: :exc:`.LeaspyModelInputError` If `n_individuals` is provided but not a positive integer, or if it is provided while `prior_type` is not `LatentVariableInitType.PRIOR_SAMPLES`. .. !! processed by numpydoc !! .. py:method:: compute_mean_traj(timepoints) Trajectory for average of individual parameters (not really meaningful for non-linear models). :Parameters: **timepoints** : :obj:`torch.Tensor` [1, n_timepoints] .. :Returns: :class:`torch.Tensor` [1, n_timepoints, dimension] The group-average values at given timepoints. .. !! processed by numpydoc !! .. py:method:: compute_mode_traj(timepoints) Most typical individual trajectory. :Parameters: **timepoints** : :obj:`torch.Tensor` [1, n_timepoints] .. :Returns: :class:`torch.Tensor` [1, n_timepoints, dimension] The group-average values at given timepoints. .. !! processed by numpydoc !! .. py:method:: compute_jacobian_tensorized(state) :abstractmethod: Compute the jacobian of the model w.r.t. each individual parameter, given the input state. This function aims to be used in :class:`.ScipyMinimize` to speed up optimization. :Parameters: **state** : :class:`~leaspy.variables.state.State` Instance holding values for all model variables (including latent individual variables) :Returns: :class:`~leaspy.utils.typing.DictParamsTorch` Tensors are of shape ``(n_individuals, n_timepoints, n_features, n_dims_param)``. :Raises: :exc:`NotImplementedError` .. .. !! processed by numpydoc !! .. py:method:: compute_sufficient_statistics(state) :classmethod: Compute sufficient statistics from state. :Parameters: **state** : :class:`~leaspy.variables.state.State` .. :Returns: :class:`~leaspy.variables.specs.SuffStatsRW` Contains the sufficient statistics computed from the state. .. !! processed by numpydoc !! .. py:method:: update_parameters(state, sufficient_statistics, *, burn_in) :classmethod: Update model parameters of the provided state. :Parameters: **cls** : :class:`~leaspy.models.mcmc_saem_compatible.McmcSaemCompatibleModel` Model class to which the parameters belong. **state** : :class:`~leaspy.variables.state.State` Instance holding values for all model variables (including latent individual variables) **sufficient_statistics** : :class:`~leaspy.variables.specs.SuffStatsRO` Contains the sufficient statistics computed from the state. **burn_in** : :obj:`bool` If True, the parameters are updated in a burn-in phase. .. !! processed by numpydoc !! .. py:method:: get_variables_specs() Get the specifications of the variables used in the model. :Returns: :class:`~leaspy.variables.specs.NamedVariables` Specifications of the variables used in the model, including timepoints and observation models. .. !! processed by numpydoc !! .. py:method:: put_individual_parameters(state, dataset) :abstractmethod: Put the individual parameters inside the provided state (in-place). :Raises: :exc:`NotImplementedError` .. .. !! processed by numpydoc !! .. py:method:: put_data_variables(state, dataset) Put all the needed data variables inside the provided state (in-place). :Parameters: **state** : :class:`~leaspy.variables.state.State` Instance holding values for all model variables (including latent individual variables), as well as: - timepoints : :class:`torch.Tensor` of shape (n_individuals, n_timepoints) **dataset** : :class:`~leaspy.io.data.dataset.Dataset` The dataset containing the data to be put in the state. .. !! processed by numpydoc !! .. py:method:: reset_data_variables(state) Reset all data variables inside the provided state (in-place). :Parameters: **state** : :class:`~leaspy.variables.state.State` Instance holding values for all model variables (including latent individual variables), as well as: - timepoints : :class:`torch.Tensor` of shape (n_individuals, n_timepoints) .. !! processed by numpydoc !! .. py:class:: RiemanianManifoldModel(name, variables_to_track = None, **kwargs) Bases: :py:obj:`leaspy.models.time_reparametrized.TimeReparametrizedModel` Manifold model for multiple variables of interest (logistic or linear formulation). :Parameters: **name** : :obj:`str` The name of the model. **\*\*kwargs** Hyperparameters of the model (including `noise_model`) :Raises: :exc:`.LeaspyModelInputError` * If hyperparameters are inconsistent .. !! processed by numpydoc !! .. py:method:: compute_sufficient_statistics(state) :classmethod: Compute the model's :term:`sufficient statistics`. :Parameters: **state** : :class:`.State` The state to pick values from. :Returns: SuffStatsRW The computed sufficient statistics. .. !! processed by numpydoc !! .. py:method:: get_variables_specs() 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. .. !! processed by numpydoc !! .. py:method:: metric(*, g) :staticmethod: :abstractmethod: .. py:method:: model_no_sources(*, rt, metric, v0, g) :classmethod: Return the model output when sources(spatial components) are not present. :Parameters: **rt** : :class:`torch.Tensor` The reparametrized time. **metric** : Any The metric tensor used for computing the spatial/temporal influence. **v0** : Any The values of the population parameter `v0` for each feature. **g** : Any The values of the population parameter `g` for each feature. :Returns: :class:`torch.Tensor` The model output without contribution from source shifts. .. rubric:: Notes This implementation delegates to `model_with_sources` with `space_shifts` set to a zero tensor of shape (1, 1), effectively removing source effects. .. !! processed by numpydoc !! .. py:method:: model_with_sources(*, rt, space_shifts, metric, v0, g) :classmethod: :abstractmethod: .. py:class:: ModelSettings(path_to_model_settings_or_dict) Used in models.base.load to create a model class object from a `json` file. :Parameters: **path_to_model_settings_or_dict** : :obj:`dict` or :obj:`str` * If a str: path to a json file containing model settings * If a dict: content of model settings :Attributes: **name** : :obj:`str` The model's name. **parameters** : :obj:`KwargsType` The model's parameters. **hyperparameters** : :obj:`KwargsType` The model's hyperparameters. :Raises: :exc:`.LeaspyModelInputError` If the provided settings are not valid or if the file cannot be read. .. !! processed by numpydoc !! .. py:attribute:: name :type: str .. py:attribute:: parameters :type: leaspy.utils.typing.KwargsType .. py:attribute:: hyperparameters :type: leaspy.utils.typing.KwargsType .. py:class:: SharedSpeedLogisticModel(name, **kwargs) Bases: :py:obj:`leaspy.models.logistic.LogisticInitializationMixin`, :py:obj:`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: **name** : :obj:`str` The name of the model. **\*\*kwargs** Hyperparameters of the model. .. !! processed by numpydoc !! .. py:method:: metric(*, g_deltas_exp) :staticmethod: Compute the metric term for the logistic model. This scaling term modulates the curvature of the logistic trajectory. :Parameters: **g_deltas_exp** : :class:`torch.Tensor` Product of slope and exp(-deltas). :Returns: :class:`torch.Tensor` Metric value, computed as: .. math:: \frac{(g \cdot e^{-\delta} + 1)^2}{g \cdot e^{-\delta}} .. !! processed by numpydoc !! .. py:method:: deltas_exp(*, deltas_padded) :staticmethod: Compute the exponential of the negative deltas. :Parameters: **deltas_padded** : :class:`torch.Tensor` Padded deltas. :Returns: :class:`torch.Tensor` Exponential of the negative deltas. .. !! processed by numpydoc !! .. py:method:: g_deltas_exp(*, g, deltas_exp) :staticmethod: .. py:method:: pad_deltas(*, deltas) :staticmethod: 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. .. !! processed by numpydoc !! .. py:method:: denom(*, g_deltas_exp) :staticmethod: Compute the denominator for the :math:`\gamma_{t_0}` calculation. .. !! processed by numpydoc !! .. py:method:: gamma_t0(*, denom) :staticmethod: Compute the :math:`\gamma_{t_0}` value, which is the inverse of the denominator. :Parameters: **denom** : :class:`torch.Tensor` Denominator term. :Returns: :class:`torch.Tensor` :math:`\gamma_{t_0}` value. .. !! processed by numpydoc !! .. py:method:: g_metric(*, gamma_t0) :staticmethod: Compute the g_metric value, which is the square of gamma_t0. :Parameters: **gamma_t0** : :class:`torch.Tensor` :math:`\gamma_{t_0}` value. :Returns: :class:`torch.Tensor` :math:`g_{metric}` value, computed as: .. math:: g\_metric = \frac{1}{(\gamma_{t0} \cdot (1 - \gamma_{t0}))^2} .. !! processed by numpydoc !! .. py:method:: collin_to_d_gamma_t0(*, deltas_exp, denom) :staticmethod: Compute the collinear term to d_gamma_t0. :Parameters: **deltas_exp** : :class:`torch.Tensor` Exponential of the negative deltas. **denom** : :class:`torch.Tensor` Denominator term. :Returns: :class:`torch.Tensor` Collinear term to d_gamma_t0 .. !! processed by numpydoc !! .. py:method:: model_with_sources(*, rt, space_shifts, metric, deltas_padded, log_g) :classmethod: Returns a model with sources. .. !! processed by numpydoc !! .. py:method:: model_no_sources(*, rt, metric, deltas_padded, log_g) :classmethod: Returns a model without sources. .. !! processed by numpydoc !! .. py:method:: get_variables_specs() Get the specifications of the variables used in the model. .. !! processed by numpydoc !! .. py:class:: StatefulModel(name, **kwargs) Bases: :py:obj:`leaspy.models.base.BaseModel` Stateful models have an internal :class:`~leaspy.variables.State` to handle parameters and variables. :Parameters: **name** : :obj:`str` The name of the model. :Attributes: **state** : :class:`~leaspy.variables.State` The internal state of the model, which contains the variables and their values. **tracked_variables** : :obj:`set` [:obj:`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. .. !! processed by numpydoc !! .. py:attribute:: tracked_variables :type: set[str] .. py:method:: track_variable(variable) Track a variable by its name. :Parameters: **variable** : :class:`~leaspy.variables.specs.VariableName` The name of the variable to track. This variable will be monitored for changes or updates. .. !! processed by numpydoc !! .. py:method:: track_variables(variables) Track multiple variables by their names. :Parameters: **variables** : :obj:`Iterable` [:class:`~leaspy.variables.specs.VariableName`] An iterable containing the names of the variables to track. Each variable will be monitored for changes or updates. .. !! processed by numpydoc !! .. py:method:: untrack_variable(variable) Untrack a variable by its name. :Parameters: **variable** : :class:`~leaspy.variables.specs.VariableName` The name of the variable to untrack. This variable will no longer be monitored for changes or updates. .. !! processed by numpydoc !! .. py:method:: untrack_variables(variables) Untrack multiple variables by their names. :Parameters: **variables** : :obj:`Iterable` [:class:`~leaspy.variables.specs.VariableName`] An iterable containing the names of the variables to untrack. Each variable will no longer be monitored for changes or updates. .. !! processed by numpydoc !! .. py:property:: state :type: leaspy.variables.state.State Get the internal state of the model. :Returns: **State** : :class:`~leaspy.variables.State` The internal state of the model, which contains the variables and their values. :Raises: :exc:`.LeaspyModelInputError` If the model's state is not initialized yet. .. !! processed by numpydoc !! .. py:property:: dag :type: leaspy.variables.dag.VariablesDAG Get the underlying DAG of the model's state. :Returns: : :class:`~leaspy.variables.dag.VariablesDAG` The directed acyclic graph (DAG) representing the model's variables and their relationships .. !! processed by numpydoc !! .. py:property:: hyperparameters_names :type: tuple[leaspy.variables.specs.VariableName, Ellipsis] Get the names of the model's hyperparameters. :Returns: : :obj:`tuple` [:class:`~leaspy.variables.specs.VariableName`, others...] A tuple containing the names of the model's hyperparameters. .. !! processed by numpydoc !! .. py:property:: parameters_names :type: tuple[leaspy.variables.specs.VariableName, Ellipsis] Get the names of the model's parameters. :Returns: : :obj:`tuple` [:class:`~leaspy.variables.specs.VariableName`, others...] A tuple containing the names of the model's parameters. .. !! processed by numpydoc !! .. py:property:: population_variables_names :type: tuple[leaspy.variables.specs.VariableName, Ellipsis] Get the names of the population latent variables. :Returns: : :obj:`tuple` [:class:`~leaspy.variables.specs.VariableName`, ...] A tuple containing the names of the population latent variables. .. !! processed by numpydoc !! .. py:property:: individual_variables_names :type: tuple[leaspy.variables.specs.VariableName, Ellipsis] Get the names of the individual latent variables. :Returns: : :obj:`tuple` [:class:`~leaspy.variables.specs.VariableName`, ...] A tuple containing the names of the individual latent variables. .. !! processed by numpydoc !! .. py:property:: parameters :type: leaspy.utils.typing.DictParamsTorch Dictionary of values for model parameters. :Returns: : :class:`~leaspy.utils.typing.DictParamsTorch` A dictionary mapping parameter names to their values (as tensors). .. !! processed by numpydoc !! .. py:property:: hyperparameters :type: leaspy.utils.typing.DictParamsTorch Dictionary of values for model hyperparameters. :Returns: : :class:`~leaspy.utils.typing.DictParamsTorch` A dictionary mapping hyperparameter names to their values (as tensors). .. !! processed by numpydoc !! .. py:method:: initialize(dataset = 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: **dataset** : :class:`~leaspy.io.data.dataset.Dataset`, optional Input dataset from which to initialize the model. .. !! processed by numpydoc !! .. py:method:: load_parameters(parameters) Instantiate or update the model's parameters. It assumes that all model hyperparameters are defined. :Parameters: **parameters** : :class:`~leaspy.utils.typing.KwargsType`] Contains the model's parameters. .. !! processed by numpydoc !! .. py:method:: get_variables_specs() :abstractmethod: Return the specifications of the variables (latent variables, derived variables, model 'parameters') that are part of the model. :Returns: **NamedVariables** : :class:`~leaspy.variables.specs.NamedVariables` The specifications of the model's variables. .. !! processed by numpydoc !! .. py:method:: move_to_device(device) Move a model and its relevant attributes to the specified :class:`torch.device`. :Parameters: **device** : :obj:`torch.device` The device to which the model and its attributes should be moved. .. !! processed by numpydoc !! .. py:class:: StatelessModel(name, **kwargs) Bases: :py:obj:`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: **name** : :obj:`str` The name of the model. .. !! processed by numpydoc !! .. py:property:: parameters Dictionary of values for model parameters. :Returns: :class:`~leaspy.utils.typing.DictParamsTorch` .. :Raises: NotImplementedError .. .. !! processed by numpydoc !! .. py:method:: load_parameters(parameters) Instantiate or update the model's parameters. :Parameters: **parameters** : :obj:`dict` Contains the model's parameters. .. !! processed by numpydoc !! .. py:class:: TimeReparametrizedModel(name, source_dimension = None, **kwargs) Bases: :py:obj:`leaspy.models.mcmc_saem_compatible.McmcSaemCompatibleModel` Contains the common attributes & methods of the multivariate time-reparametrized models. :Parameters: **name** : :obj:`str` Name of the model. **source_dimension** : Optional[:obj:`int`] Number of sources. Dimension of spatial components (default is None). **\*\*kwargs** Hyperparameters for the model (including `obs_models`). :Raises: :exc:`.LeaspyModelInputError` If inconsistent hyperparameters. .. !! processed by numpydoc !! .. py:property:: xi_std :type: torch.Tensor Return the standard deviation of xi as a tensor. .. !! processed by numpydoc !! .. py:property:: tau_std :type: torch.Tensor Return the standard deviation of tau as a tensor. .. !! processed by numpydoc !! .. py:property:: noise_std :type: torch.Tensor Return the standard deviation of the model as a tensor. .. !! processed by numpydoc !! .. py:property:: sources_std :type: float Return the standard deviation of sources as a float. .. !! processed by numpydoc !! .. py:property:: source_dimension :type: Optional[int] Return the number of the sources .. !! processed by numpydoc !! .. py:property:: has_sources :type: bool Indicates whether the model includes sources. :Returns: :obj:`bool` True if `source_dimension` is a positive integer. False otherwise. .. !! processed by numpydoc !! .. py:method:: time_reparametrization(*, t, alpha, tau) :staticmethod: Tensorized time reparametrization formula. .. warning:: Shapes of tensors must be compatible between them. :Parameters: **t** : :class:`torch.Tensor` Timepoints to reparametrize **alpha** : :class:`torch.Tensor` Acceleration factors of individual(s) **tau** : :class:`torch.Tensor` Time-shift(s) of individual(s) :Returns: :class:`torch.Tensor` Reparametrized time of same shape as `timepoints` .. !! processed by numpydoc !! .. py:method:: get_variables_specs() 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 .. !! processed by numpydoc !! .. py:method:: put_individual_parameters(state, dataset) Initialize individual latent parameters in the given state if not already set. :Parameters: **state** : State The current state object that holds all the variables **dataset** : Dataset Dataset used to initialize latent variables accordingly. .. !! processed by numpydoc !! .. py:method:: to_dict(*, with_mixing_matrix = True) Export model object as dictionary ready for :term:`JSON` saving. :Parameters: **with_mixing_matrix** : :obj:`bool` (default ``True``) Save the :term:`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. .. !! processed by numpydoc !! .. py:method:: compute_individual_ages_from_biomarker_values(value, individual_parameters, feature = None) :abstractmethod: 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 :term:`API` layer. :Parameters: **value** : scalar or array_like[scalar] (:obj:`list`, :obj:`tuple`, :class:`numpy.ndarray`) Contains the :term:`biomarker` value(s) of the subject. **individual_parameters** : :obj:`dict` Contains the individual parameters. Each individual parameter should be a scalar or array_like. **feature** : :obj:`str` (or None) Name of the considered :term:`biomarker`. .. note:: Optional for :class:`.UnivariateModel`, compulsory for :class:`.MultivariateModel`. :Returns: :class:`torch.Tensor` Contains the subject's ages computed at the given values(s). Shape of tensor is ``(1, n_values)``. :Raises: :exc:`.LeaspyModelInputError` If computation is tried on more than 1 individual. .. !! processed by numpydoc !! .. py:method:: compute_individual_ages_from_biomarker_values_tensorized(value, individual_parameters, feature) :abstractmethod: For one individual, compute age(s) at which the given features values are reached (given the subject's individual parameters), with tensorized inputs. :Parameters: **value** : :class:`torch.Tensor` of shape ``(1, n_values)`` Contains the :term:`biomarker` value(s) of the subject. **individual_parameters** : DictParamsTorch Contains the individual parameters. Each individual parameter should be a :class:`torch.Tensor`. **feature** : :obj:`str` (or None) Name of the considered :term:`biomarker`. .. note:: Optional for :class:`.UnivariateModel`, compulsory for :class:`.MultivariateModel`. :Returns: :class:`torch.Tensor` Contains the subject's ages computed at the given values(s). Shape of tensor is ``(n_values, 1)``. .. !! processed by numpydoc !! .. py:class:: LogisticMultivariateMixtureModel(name, **kwargs) Bases: :py:obj:`LogisticMixtureInitializationMixin`, :py:obj:`RiemanianManifoldMixtureModel` Mixture Manifold model for multiple variables of interest (logistic formulation). .. !! processed by numpydoc !! .. py:method:: get_variables_specs() 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. These include `ModelParameter`, `Hyperparameter`, `PopulationLatentVariable`, and `LinkedVariable` instances. .. !! processed by numpydoc !! .. py:method:: metric(*, g) :staticmethod: Compute the metric tensor from input tensor `g`. This function calculates the metric as \((g + 1)^2 / g\) element-wise. :Parameters: **g** : :class:`torch.Tensor` Input tensor with values of the population parameter `g` for each feature. :Returns: :class:`torch.Tensor` The computed metric tensor, same shape as g(number of features) .. !! processed by numpydoc !! .. py:method:: model_with_sources(*, rt, space_shifts, metric, v0, g) :classmethod: Return the model output when sources(spatial components) are present. :Parameters: **rt** : :class:`~leaspy.utils.weighted_tensor.TensorOrWeightedTensor` [:obj:`float`] Tensor containing the reparametrized time. **space_shifts** : :class:`~leaspy.utils.weighted_tensor.TensorOrWeightedTensor` [:obj:`float`] Tensor containing the values of the space-shifts **metric** : :class:`~leaspy.utils.weighted_tensor.TensorOrWeightedTensor` [:obj:`float`] Tensor containing the metric tensor used for computing the spatial/temporal influence. **v0** : :class:`~leaspy.utils.weighted_tensor.TensorOrWeightedTensor` [:obj:`float`] Tensor containing the values of the population parameter `v0` for each feature. **g** : :class:`~leaspy.utils.weighted_tensor.TensorOrWeightedTensor` [:obj:`float`] Tensor containing the values of the population parameter `g` for each feature. :Returns: :class:`torch.Tensor` Weighted value tensor after applying sigmoid transformation, representing the model output with sources. .. !! processed by numpydoc !!