phenotypic.analysis.LinearSoftplus#

class phenotypic.analysis.LinearSoftplus(*, on: Annotated[str, _ColumnRefMarker('measurements')], groupby: Annotated[list[str], _ColumnRefMarker('measurements')], agg_func: Callable | str | list | dict | None = 'mean', n_jobs: int = 1, time_label: Annotated[str, _ColumnRefMarker('measurements')] = 'Metadata_Time', loss: Literal['linear', 'soft_l1', 'huber', 'cauchy', 'arctan'] = 'huber', f_scale: Annotated[float, Gt(gt=0), _PydanticGeneralMetadata(allow_inf_nan=False)] = 1.0, verbose: bool = False, stderr_label: str | None = None, s0_prior: Any = None, s0_prior_cv: float | None = None, s0_prior_sigma: float | None = None, s0_prior_groupby: list[str] | None = None, prune_saturated: bool = True)[source]#

Bases: _LinearSoftplusBase

Linear-with-softplus lag-phase growth fitter (no saturation).

Fits a 4-parameter linear post-lag growth model with a softplus lag transition:

\[s(t) = \frac{v}{\alpha}\, \ln\!\bigl(1 + e^{\alpha(t-\lambda)}\bigr) + s_0\]

Use this class when colonies are still in the linear-growth regime or when you want the saturation tail discarded as observation noise. For data with a clear carrying-capacity plateau, use DoubleSoftplus instead.

Pruning is ON by default — post-saturation timepoints are dropped from the fit so the linear regime is recovered cleanly. Disable with prune_saturated=False if your data is fully pre-saturation.

Attributes:
stderr_label (str | None): Column providing per-timepoint standard

errors used as weights in the fit. When None, the fit auto-derives a replicate-SE column during aggregation and a per-fit-group pooled point-level std (median across the n≥2 timepoints’ stds) that fills σ for any n=1 timepoints in the group. This keeps single-replicate rows from dominating the 1/σ² weighting — they get σ ≈ typical point noise instead of ε.

s0_prior (bool | float | str | None): Unified Gaussian-prior

source for s0. Dispatch (by type):

  • None or False → no prior (default).

  • True → ground on data: µ = median of self.on at the earliest observed timepoint within the effective group.

  • str → ground on named column: µ = median of data[s0_prior] at the earliest timepoint within the effective group.

  • positive float / int → scalar prior mean applied uniformly to every fit group.

s0_prior_cv (float | None): CV coefficient for the prior σ

(σ = cv × µ). Mutually exclusive with s0_prior_sigma. Defaults to None; if both s0_prior_cv and s0_prior_sigma are None and the prior is engaged, the helper applies CV=0.05 as a moderately informative default.

s0_prior_sigma (float | None): Absolute σ for the prior.

Mutually exclusive with s0_prior_cv. Use when the data scale makes a CV-based σ awkward (e.g. fractional / normalized data where µ < 1).

s0_prior_groupby (List[str] | None): Optional coarser grouping

(must be a subset of groupby) used for the per-group µ estimation on column-backed priors. When supplied, µ is pooled across replicate fits within each coarser group — an empirical-Bayes move appropriate when inoculation spread varies across conditions (e.g. per media). Only meaningful when s0_prior is True or a string.

prune_saturated (bool): Whether to drop post-saturation timepoints

before fitting. Defaults to True.

Note

``f_scale`` is unit-sensitive only on the unweighted fit path. The inherited f_scale (see ModelFitter) is the Huber/robust inlier–outlier threshold expressed in residual units, and those units depend on whether the fit is weighted:

  • Weighted (stderr_label set, or the default auto-derived replicate SEM when timepoints carry ≥2 replicates): residuals are divided by σ and are therefore dimensionless, so f_scale=1.0 means “one standard error” and is invariant to the units of on. No retuning is needed when the measurement scale changes.

  • Unweighted (no σ — e.g. single-replicate timepoints): residuals are in the native units of on, so f_scale is an absolute size threshold. If those units change (e.g. radius in px → mm, which shrinks residuals ~50×) f_scale must be rescaled to match, or the default robust loss="huber" never reaches its linear arm and silently degrades to ordinary least squares — losing all outlier suppression. loss="linear" ignores f_scale and is unaffected.

Category: LinearSoftplus#

Name

Description

Biology

v

The post-lag phase growth rate.

The post-lag phase growth rate using the target metric (usually radius)

s0

The initial value of the target metric

The initial size

lambda

The duration of the lag phase

alpha

lag phase transition sharpness

Methods

__init__

Create a new model by parsing and validating input data from keyword arguments.

analyze

Pre-broadcast helper columns, then delegate to the base pipeline.

construct

copy

Returns a copy of the model.

dash

Interactive Plotly version of show().

dict

from_orm

json

model_construct

Creates a new instance of the Model class with validated data.

model_copy

!!! abstract "Usage Documentation"

model_dump

!!! abstract "Usage Documentation"

model_dump_json

!!! abstract "Usage Documentation"

model_func

Linear-softplus growth curve, no saturation ceiling.

model_json_schema

Generates a JSON schema for a model class.

model_parametrized_name

Compute the class name for parametrizations of generic classes.

model_post_init

Build the inoculum-prior helper from the resolved fields.

model_rebuild

Try to rebuild the pydantic-core schema for the model.

model_validate

Validate a pydantic model instance.

model_validate_json

!!! abstract "Usage Documentation"

model_validate_strings

Validate the given object with string data against the Pydantic model.

parse_file

parse_obj

parse_raw

results

Return the most recent fit results produced by analyze().

schema

schema_json

show

Plot model predictions alongside measurements with optional filtering.

update_forward_refs

validate

Attributes

model_computed_fields

model_config

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_extra

Get extra fields set during validation.

model_fields

model_fields_set

Returns the set of fields that have been explicitly set on this model instance.

prune_saturated

stderr_label

s0_prior

s0_prior_cv

s0_prior_sigma

s0_prior_groupby

time_label

loss

f_scale

verbose

on

groupby

agg_func

n_jobs

Parameters:
prune_saturated: bool#
static model_func(t: np.ndarray | float, v: float, s0: float, lam: float, alpha: float) float | np.ndarray[source]#

Linear-softplus growth curve, no saturation ceiling.

\[s(t) = \frac{v}{\alpha}\, \ln\!\bigl(1 + e^{\alpha(t-\lambda)}\bigr) + s_0\]
Parameters:
  • t (np.ndarray | float) – Time (scalar or array).

  • v (float) – Post-lag growth rate.

  • s0 (float) – Initial size.

  • lam (float) – Lag duration.

  • alpha (float) – Lag transition sharpness.

Returns:

Predicted size at t; scalar when t is scalar, otherwise an array.

Return type:

float | np.ndarray

__copy__() Self#

Returns a shallow copy of the model.

Return type:

Self

__deepcopy__(memo: dict[int, Any] | None = None) Self#

Returns a deep copy of the model.

Parameters:

memo (dict[int, Any] | None)

Return type:

Self

classmethod __get_pydantic_json_schema__(core_schema: CoreSchema, handler: GetJsonSchemaHandler, /) JsonSchemaValue#

Hook into generating the model’s JSON schema.

Parameters:
  • core_schema (CoreSchema) – A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({‘type’: ‘nullable’, ‘schema’: current_schema}), or just call the handler with the original schema.

  • handler (GetJsonSchemaHandler) – Call into Pydantic’s internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

Returns:

A JSON schema, as a Python object.

Return type:

JsonSchemaValue

__init__(**data: Any) None#

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Parameters:

data (Any)

Return type:

None

__iter__() Generator[tuple[str, Any], None, None]#

So dict(model) works.

Return type:

Generator[tuple[str, Any], None, None]

__pretty__(fmt: Callable[[Any], Any], **kwargs: Any) Generator[Any]#

Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.

Parameters:
Return type:

Generator[Any]

classmethod __pydantic_init_subclass__(**kwargs: Any) None#

Populate field descriptions from the subclass docstring.

Runs once per concrete subclass after pydantic has built its model, copying parameter descriptions parsed from the Google-style Args: docstring block onto each field’s description slot.

Parameters:

**kwargs (Any) – Class-keyword arguments forwarded by pydantic.

Return type:

None

classmethod __pydantic_on_complete__() None#

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before [__pydantic_init_subclass__()][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using [model_rebuild()][pydantic.main.BaseModel.model_rebuild].

Return type:

None

__repr_name__() str#

Name of the instance’s class, used in __repr__.

Return type:

str

__repr_recursion__(object: Any) str#

Returns the string representation of a recursive object.

Parameters:

object (Any)

Return type:

str

__rich_repr__() RichReprResult#

Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.

Return type:

RichReprResult

analyze(data: pandas.DataFrame) pandas.DataFrame#

Pre-broadcast helper columns, then delegate to the base pipeline.

  • When stderr_label is None, a replicate-SEM column derived via groupby.transform("sem") so the weighted loss can downweight noisy timepoints automatically, plus a per-fit-group pooled point-level std column (f"{on}_std_pool") computed as the median of per- timepoint stds across the group’s n≥2 timepoints. The pool gives _resolve_y_stderr() a principled fallback σ for n=1 timepoints (σ ≈ typical point noise) instead of the vanishingly-small ε fill. Fit groups with zero multi- replicate timepoints produce NaN here and inherit the unweighted-residual fallback.

  • When the inoculum prior is column-based, a per-group median of inoc_size_label at the earliest observed timepoint is broadcast into a f"{label}_group_mean" column — the source of µ for the Gaussian prior on s0 (_InoculumPrior).

Each helper is constant within its effective group, so the base-class dict-style aggregation carries it through as a flat column without MultiIndex juggling.

Raises:

ValueError – If the inoculum prior is configured with an inoc_groupby that is not a subset of self.groupby, or references columns absent from data.

Parameters:

data (pandas.DataFrame)

Return type:

pandas.DataFrame

classmethod construct(_fields_set: set[str] | None = None, **values: Any) Self#
Parameters:
Return type:

Self

copy(*, include: AbstractSetIntStr | MappingIntStrAny | None = None, exclude: AbstractSetIntStr | MappingIntStrAny | None = None, update: Dict[str, Any] | None = None, deep: bool = False) Self#

Returns a copy of the model.

!!! warning “Deprecated”

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `

Parameters:
  • include (AbstractSetIntStr | MappingIntStrAny | None) – Optional set or mapping specifying which fields to include in the copied model.

  • exclude (AbstractSetIntStr | MappingIntStrAny | None) – Optional set or mapping specifying which fields to exclude in the copied model.

  • update (Dict[str, Any] | None) – Optional dictionary of field-value pairs to override field values in the copied model.

  • deep (bool) – If True, the values of fields that are Pydantic models will be deep-copied.

Returns:

A copy of the model with included, excluded and updated fields as specified.

Return type:

Self

dash(tmax: int | float | None = None, criteria: Dict[str, Any | List[Any]] | None = None, figsize=(6, 4), cmap: str | None = 'tab20', legend: bool | str = True, **kwargs) go.Figure#

Interactive Plotly version of show().

Hover tooltips are populated from _hover_fields so subclasses can expose whichever fitted parameters and metrics are most meaningful for their model.

Parameters:
  • legend (bool | str) – Controls legend rendering. True (default) renders the legend with one entry per groupby combination (joined with ", "). False hides the legend. A string must be one of self.groupby; groups sharing a value in that column share both color and a single legend entry.

  • tmax (int | float | None)

  • criteria (Dict[str, Union[Any, List[Any]]] | None)

  • cmap (str | None)

Raises:

ImportError – If plotly is not installed.

Return type:

go.Figure

dict(*, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False) Dict[str, Any]#
Parameters:
Return type:

Dict[str, Any]

classmethod from_orm(obj: Any) Self#
Parameters:

obj (Any)

Return type:

Self

json(*, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, by_alias: bool = False, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, encoder: Callable[[Any], Any] | None = PydanticUndefined, models_as_dict: bool = PydanticUndefined, **dumps_kwargs: Any) str#
Parameters:
Return type:

str

model_computed_fields = {}#
model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'validate_assignment': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod model_construct(_fields_set: set[str] | None = None, **values: Any) Self#

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

!!! note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.

Parameters:
  • _fields_set (set[str] | None) – A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

  • values (Any) – Trusted or pre-validated data dictionary.

Returns:

A new instance of the Model class with validated data.

Return type:

Self

model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) Self#
!!! abstract “Usage Documentation”

[model_copy](../concepts/models.md#model-copy)

Returns a copy of the model.

!!! note

The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:
  • update (Mapping[str, Any] | None) – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

  • deep (bool) – Set to True to make a deep copy of the model.

Returns:

New model instance.

Return type:

Self

model_dump(*, mode: Literal['json', 'python'] | str = 'python', include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False) dict[str, Any]#
!!! abstract “Usage Documentation”

[model_dump](../concepts/serialization.md#python-mode)

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:
  • mode (Literal['json', 'python'] | str) – The mode in which to_python should run. If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.

  • include (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None) – A set of fields to include in the output.

  • exclude (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None) – A set of fields to exclude from the output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to use the field’s alias in the dictionary key if defined.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (bool | Literal['none', 'warn', 'error']) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Callable[[Any], Any] | None) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Returns:

A dictionary representation of the model.

Return type:

dict[str, Any]

model_dump_json(*, indent: int | None = None, ensure_ascii: bool = False, include: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, exclude: set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None = None, context: Any | None = None, by_alias: bool | None = None, exclude_unset: bool = False, exclude_defaults: bool = False, exclude_none: bool = False, exclude_computed_fields: bool = False, round_trip: bool = False, warnings: bool | Literal['none', 'warn', 'error'] = True, fallback: Callable[[Any], Any] | None = None, serialize_as_any: bool = False) str#
!!! abstract “Usage Documentation”

[model_dump_json](../concepts/serialization.md#json-mode)

Generates a JSON representation of the model using Pydantic’s to_json method.

Parameters:
  • indent (int | None) – Indentation to use in the JSON output. If None is passed, the output will be compact.

  • ensure_ascii (bool) – If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

  • include (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None) – Field(s) to include in the JSON output.

  • exclude (set[int] | set[str] | Mapping[int, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | Mapping[str, set[int] | set[str] | Mapping[int, IncEx | bool] | Mapping[str, IncEx | bool] | bool] | None) – Field(s) to exclude from the JSON output.

  • context (Any | None) – Additional context to pass to the serializer.

  • by_alias (bool | None) – Whether to serialize using field aliases.

  • exclude_unset (bool) – Whether to exclude fields that have not been explicitly set.

  • exclude_defaults (bool) – Whether to exclude fields that are set to their default value.

  • exclude_none (bool) – Whether to exclude fields that have a value of None.

  • exclude_computed_fields (bool) – Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

  • round_trip (bool) – If True, dumped values should be valid as input for non-idempotent types such as Json[T].

  • warnings (bool | Literal['none', 'warn', 'error']) – How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors, “error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

  • fallback (Callable[[Any], Any] | None) – A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

  • serialize_as_any (bool) – Whether to serialize fields with duck-typing serialization behavior.

Returns:

A JSON string representation of the model.

Return type:

str

property model_extra: dict[str, Any] | None#

Get extra fields set during validation.

Returns:

A dictionary of extra fields, or None if config.extra is not set to “allow”.

model_fields = {'agg_func': FieldInfo(annotation=Union[Callable, str, list, dict, NoneType], required=False, default='mean'), 'f_scale': FieldInfo(annotation=float, required=False, default=1.0, description='Soft margin between inlier and outlier residuals handed to :func:`scipy.optimize.least_squares`. Only affects robust ``loss`` choices; ignored when ``loss="linear"``. Must be positive and finite.', metadata=[Gt(gt=0), _PydanticGeneralMetadata(allow_inf_nan=False)]), 'groupby': FieldInfo(annotation=list[str], required=True, metadata=[_ColumnRefMarker('measurements')]), 'loss': FieldInfo(annotation=Literal['linear', 'soft_l1', 'huber', 'cauchy', 'arctan'], required=False, default='huber', description='Loss calculation method passed through to :func:`scipy.optimize.least_squares`. Defaults to ``"huber"`` quadratic near zero and linear past ``f_scale``, so the fit behaves like standard least-squares on inliers but downweights rare large residuals (bubble artifacts, contamination spikes, mis-segmented timepoints). Pass ``"linear"`` to recover the classical unweighted-squared-residual loss, or ``"soft_l1"`` / ``"cauchy"`` / ``"arctan"`` for progressively more aggressive outlier suppression.'), 'n_jobs': FieldInfo(annotation=int, required=False, default=1, alias_priority=2, validation_alias=AliasChoices(choices=['n_jobs', 'num_workers'])), 'on': FieldInfo(annotation=str, required=True, metadata=[_ColumnRefMarker('measurements')]), 'prune_saturated': FieldInfo(annotation=bool, required=False, default=True, description='Whether to drop post-saturation timepoints before fitting. Defaults to ``True``. .. note:: **``f_scale`` is unit-sensitive only on the unweighted fit path.** The inherited ``f_scale`` (see :class:`ModelFitter`) is the Huber/robust inlier–outlier threshold expressed in *residual units*, and those units depend on whether the fit is weighted: - **Weighted** (``stderr_label`` set, or the default auto-derived replicate SEM when timepoints carry ≥2 replicates): residuals are divided by σ and are therefore dimensionless, so ``f_scale=1.0`` means "one standard error" and is invariant to the units of ``on``. No retuning is needed when the measurement scale changes. - **Unweighted** (no σ e.g. single-replicate timepoints): residuals are in the native units of ``on``, so ``f_scale`` is an absolute size threshold. If those units change (e.g. radius in px mm, which shrinks residuals ~50×) ``f_scale`` must be rescaled to match, or the default robust ``loss="huber"`` never reaches its linear arm and silently degrades to ordinary least squares losing all outlier suppression. ``loss="linear"`` ignores ``f_scale`` and is unaffected.'), 's0_prior': FieldInfo(annotation=Any, required=False, default=None, description='Unified Gaussian-prior source for ``s0``. Dispatch (by type): - ``None`` or ``False`` no prior (default). - ``True`` ground on data: ``µ`` = median of ``self.on`` at the earliest observed timepoint within the effective group. - ``str`` ground on named column: ``µ`` = median of ``data[s0_prior]`` at the earliest timepoint within the effective group. - positive ``float`` / ``int`` scalar prior mean applied uniformly to every fit group.'), 's0_prior_cv': FieldInfo(annotation=Union[float, NoneType], required=False, default=None, description='CV coefficient for the prior σ (``σ = cv × µ``). Mutually exclusive with ``s0_prior_sigma``. Defaults to ``None``; if both ``s0_prior_cv`` and ``s0_prior_sigma`` are ``None`` and the prior is engaged, the helper applies CV=0.05 as a moderately informative default.'), 's0_prior_groupby': FieldInfo(annotation=Union[list[str], NoneType], required=False, default=None, description='Optional coarser grouping (must be a subset of ``groupby``) used for the per-group ``µ`` estimation on column-backed priors. When supplied, ``µ`` is pooled across replicate fits within each coarser group an empirical-Bayes move appropriate when inoculation spread varies across conditions (e.g. per media). Only meaningful when ``s0_prior`` is ``True`` or a string.'), 's0_prior_sigma': FieldInfo(annotation=Union[float, NoneType], required=False, default=None, description='Absolute σ for the prior. Mutually exclusive with ``s0_prior_cv``. Use when the data scale makes a CV-based σ awkward (e.g. fractional / normalized data where ``µ < 1``).'), 'stderr_label': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, description="Column providing per-timepoint standard errors used as weights in the fit. When ``None``, the fit auto-derives a replicate-SE column during aggregation *and* a per-fit-group pooled point-level std (median across the n≥2 timepoints' stds) that fills σ for any n=1 timepoints in the group. This keeps single-replicate rows from dominating the 1/σ² weighting they get σ typical point noise instead of ε."), 'time_label': FieldInfo(annotation=str, required=False, default='Metadata_Time', description='Column name representing the independent variable (typically time).', metadata=[_ColumnRefMarker('measurements')]), 'verbose': FieldInfo(annotation=bool, required=False, default=False, description='Whether to print detailed optimizer output.')}#
property model_fields_set: set[str]#

Returns the set of fields that have been explicitly set on this model instance.

Returns:

A set of strings representing the fields that have been set,

i.e. that were not filled from defaults.

classmethod model_json_schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}', schema_generator: type[~pydantic.json_schema.GenerateJsonSchema] = <class 'pydantic.json_schema.GenerateJsonSchema'>, mode: ~typing.Literal['validation', 'serialization'] = 'validation', *, union_format: ~typing.Literal['any_of', 'primitive_type_array'] = 'any_of') dict[str, Any]#

Generates a JSON schema for a model class.

Parameters:
  • by_alias (bool) – Whether to use attribute aliases or not.

  • ref_template (str) – The reference template.

  • union_format (Literal['any_of', 'primitive_type_array']) –

    The format to use when combining schemas from unions together. Can be one of:

    keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.

  • schema_generator (type[GenerateJsonSchema]) – To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

  • mode (Literal['validation', 'serialization']) – The mode in which to generate the schema.

Returns:

The JSON schema for the given model class.

Return type:

dict[str, Any]

classmethod model_parametrized_name(params: tuple[type[Any], ...]) str#

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

params (tuple[type[Any], ...]) – Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

Returns:

String representing the new class where params are passed to cls as type variables.

Raises:

TypeError – Raised when trying to generate concrete names for non-generic models.

Return type:

str

model_post_init(_LinearSoftplusBase__context: Any) None#

Build the inoculum-prior helper from the resolved fields.

Runs after pydantic has validated every field. Constructing _InoculumPrior here preserves the original __init__-time validation: it raises TypeError for an unsupported s0_prior type and ValueError for a non-positive scalar, a mutually-exclusive σ pair, or an empty s0_prior_groupby list.

Parameters:
  • __context – Pydantic post-init context (unused).

  • _LinearSoftplusBase__context (Any)

Return type:

None

classmethod model_rebuild(*, force: bool = False, raise_errors: bool = True, _parent_namespace_depth: int = 2, _types_namespace: MappingNamespace | None = None) bool | None#

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:
  • force (bool) – Whether to force the rebuilding of the model schema, defaults to False.

  • raise_errors (bool) – Whether to raise errors, defaults to True.

  • _parent_namespace_depth (int) – The depth level of the parent namespace, defaults to 2.

  • _types_namespace (MappingNamespace | None) – The types namespace, defaults to None.

Returns:

Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.

Return type:

bool | None

classmethod model_validate(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, from_attributes: bool | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self#

Validate a pydantic model instance.

Parameters:
  • obj (Any) – The object to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Literal['allow', 'ignore', 'forbid'] | None) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • from_attributes (bool | None) – Whether to extract data from object attributes.

  • context (Any | None) – Additional context to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Raises:

ValidationError – If the object could not be validated.

Returns:

The validated model instance.

Return type:

Self

classmethod model_validate_json(json_data: str | bytes | bytearray, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self#
!!! abstract “Usage Documentation”

[JSON Parsing](../concepts/json.md#json-parsing)

Validate the given JSON data against the Pydantic model.

Parameters:
  • json_data (str | bytes | bytearray) – The JSON data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Literal['allow', 'ignore', 'forbid'] | None) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Returns:

The validated Pydantic model.

Raises:

ValidationError – If json_data is not a JSON string or the object could not be validated.

Return type:

Self

classmethod model_validate_strings(obj: Any, *, strict: bool | None = None, extra: Literal['allow', 'ignore', 'forbid'] | None = None, context: Any | None = None, by_alias: bool | None = None, by_name: bool | None = None) Self#

Validate the given object with string data against the Pydantic model.

Parameters:
  • obj (Any) – The object containing string data to validate.

  • strict (bool | None) – Whether to enforce types strictly.

  • extra (Literal['allow', 'ignore', 'forbid'] | None) – Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

  • context (Any | None) – Extra variables to pass to the validator.

  • by_alias (bool | None) – Whether to use the field’s alias when validating against the provided input data.

  • by_name (bool | None) – Whether to use the field’s name when validating against the provided input data.

Returns:

The validated Pydantic model.

Return type:

Self

classmethod parse_file(path: str | Path, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self#
Parameters:
  • path (str | Path)

  • content_type (str | None)

  • encoding (str)

  • proto (DeprecatedParseProtocol | None)

  • allow_pickle (bool)

Return type:

Self

classmethod parse_obj(obj: Any) Self#
Parameters:

obj (Any)

Return type:

Self

classmethod parse_raw(b: str | bytes, *, content_type: str | None = None, encoding: str = 'utf8', proto: DeprecatedParseProtocol | None = None, allow_pickle: bool = False) Self#
Parameters:
  • b (str | bytes)

  • content_type (str | None)

  • encoding (str)

  • proto (DeprecatedParseProtocol | None)

  • allow_pickle (bool)

Return type:

Self

results() pandas.DataFrame#

Return the most recent fit results produced by analyze().

Return type:

pandas.DataFrame

classmethod schema(by_alias: bool = True, ref_template: str = '#/$defs/{model}') Dict[str, Any]#
Parameters:
  • by_alias (bool)

  • ref_template (str)

Return type:

Dict[str, Any]

classmethod schema_json(*, by_alias: bool = True, ref_template: str = '#/$defs/{model}', **dumps_kwargs: Any) str#
Parameters:
  • by_alias (bool)

  • ref_template (str)

  • dumps_kwargs (Any)

Return type:

str

show(tmax: int | float | None = None, criteria: Dict[str, Any | List[Any]] | None = None, figsize=(6, 4), cmap: str | None = 'tab20', legend: bool | str = True, ax: plt.Axes | None = None, **kwargs) Tuple[plt.Figure, plt.Axes]#

Plot model predictions alongside measurements with optional filtering.

Parameters:
  • tmax (int | float | None) – Upper bound of the prediction curve. If None, uses the maximum observed time.

  • criteria (Dict[str, Union[Any, List[Any]]] | None) – Column/value filter applied to both fitted results and raw measurements before plotting.

  • figsize – Matplotlib figure size. Used only when ax is None.

  • cmap (str | None) – Matplotlib colormap name, a single color string, or None for matplotlib’s default color cycle.

  • legend (bool | str) – Controls legend rendering. True (default) renders the legend with one entry per groupby combination, labeled by the first groupby column. False hides the legend. A string must be one of self.groupby; groups sharing a value in that column share both color and a single legend entry. The legend is auto-removed if it is larger than the axes.

  • ax (plt.Axes | None) – Existing axes to draw into. A new figure is created when omitted.

  • **kwargs – Styling overrides — dpi, facecolor, edgecolor, line_width, marker_size, elinewidth, capsize, legend_loc, legend_fontsize, label.

Returns:

A (Figure, Axes) pair.

Return type:

Tuple[plt.Figure, plt.Axes]

classmethod update_forward_refs(**localns: Any) None#
Parameters:

localns (Any)

Return type:

None

classmethod validate(value: Any) Self#
Parameters:

value (Any)

Return type:

Self

stderr_label: str | None#
s0_prior: Any#
s0_prior_cv: float | None#
s0_prior_sigma: float | None#
s0_prior_groupby: list[str] | None#
time_label: ColumnRef#
loss: LossKind#
f_scale: float#
verbose: bool#
on: ColumnRef#
groupby: ColumnRefList#
agg_func: Callable | str | list | dict | None#
n_jobs: int#