Skip to content

Models

limen_core.models

Core domain models used across the scoring engine and downstream services.

AggregateAssessment

Bases: BaseModel

AOI-level summary attached to the persisted risk_assessments row.

CellRiskRecord

Bases: BaseModel

One per-cell scoring result inside the assessment.

predisposition property

predisposition: float

Static susceptibility, whatever carries it for this hazard.

MonitoringContext

Bases: BaseModel

Carries everything the workflow learns about a single run.

with_update

with_update(**fields: Any) -> MonitoringContext

Return a copy with fields applied (pydantic-friendly).

RiskAnalysisDTO

Bases: BaseModel

Pydantic mirror of the RiskAnalyst structured output.

HazardType

Bases: StrEnum

Hazards Limen can score. Values match the SQL hazard_type enum.

CellFeatureBundle

Bases: _Frozen

Engine input — everything needed to score one cell at one moment.

ComponentBreakdown

Bases: HazardBreakdown

Landslide components + their normalised inputs, for auditability.

V1 ships five components (S/M/E/F/H, k always 0). V1.5 activates K on monitored cells and renormalises the others — but the same DTO shape carries both regimes so downstream consumers (ChatAgents, persistence, frontend) stay backwards-compatible.

The name is kept from before the hazard dimension existed: renaming it would touch every scoring consumer for no gain. Fase 2 adds FloodBreakdown and WildfireBreakdown alongside it.

DynamicInputs

Bases: _Frozen

Time-varying inputs needed by M / E / F components.

KinematicBreakdown

Bases: _Frozen

Sub-terms for the V1.5 K component (zero when no sensor coverage).

RainfallSeries

Bases: _Frozen

Hourly precipitation time-series used by Caine + API computations.

RiskLevel

Bases: StrEnum

Five-class classification used by the V1 engine.

Member names follow the project spec: None_ (Python's None is a reserved keyword, so a trailing underscore), Low, Moderate, High, VeryHigh. Values are the human-readable forms used in API responses and JSON dumps.

RiskScore

Bases: _Frozen, Generic[BreakdownT_co]

Engine output, parameterised by the hazard's breakdown shape.

Generic rather than pinned to :class:ComponentBreakdown so the landslide engine can return RiskScore[ComponentBreakdown] and its callers keep reading .breakdown.s with no cast and no narrowing, while a flood or wildfire engine returns its own breakdown through the same class.

SeismicHistoryEvent

Bases: _Frozen

One past seismic event relevant to a cell (within the lookback window).

StaticFactors

Bases: _Frozen

Per-cell static factors (mirror of cell_static_factors columns).

Every field is optional: when the underlying source isn't yet populated (DEM / CORINE / lithology pipelines land later), the engine must degrade — not crash.

SensorFeatures

Bases: BaseModel

Hourly aggregate read from sensor_features_hourly per cell.

has_kinematic_signal property

has_kinematic_signal: bool

True when at least one displacement-derived field is populated.

has_measured_meteo property

has_measured_meteo: bool

True when a measured rainfall/soil/piezometer reading is available.

limen_core.models.risk

Risk-domain DTOs.

These are the only types the deterministic engine reads from and writes to. They are intentionally side-effect-free Pydantic v2 models so:

  • the engine stays a pure function of its inputs;
  • assembling the bundle (DB queries, Open-Meteo / INGV / EFFIS fetches) is a separate concern that can be tested independently in Phase 4;
  • the V2 ML engine can be a drop-in by consuming the same CellFeatureBundle.

SensorFeatures

Bases: BaseModel

Hourly aggregate read from sensor_features_hourly per cell.

has_kinematic_signal property

has_kinematic_signal: bool

True when at least one displacement-derived field is populated.

has_measured_meteo property

has_measured_meteo: bool

True when a measured rainfall/soil/piezometer reading is available.

RiskLevel

Bases: StrEnum

Five-class classification used by the V1 engine.

Member names follow the project spec: None_ (Python's None is a reserved keyword, so a trailing underscore), Low, Moderate, High, VeryHigh. Values are the human-readable forms used in API responses and JSON dumps.

StaticFactors

Bases: _Frozen

Per-cell static factors (mirror of cell_static_factors columns).

Every field is optional: when the underlying source isn't yet populated (DEM / CORINE / lithology pipelines land later), the engine must degrade — not crash.

RainfallSample

Bases: _Frozen

One hourly rainfall observation (mm).

RainfallSeries

Bases: _Frozen

Hourly precipitation time-series used by Caine + API computations.

SeismicHistoryEvent

Bases: _Frozen

One past seismic event relevant to a cell (within the lookback window).

DynamicInputs

Bases: _Frozen

Time-varying inputs needed by M / E / F components.

CellFeatureBundle

Bases: _Frozen

Engine input — everything needed to score one cell at one moment.

EventoPioggia

Bases: _Frozen

L'evento di pioggia che la curva di Caine ha guardato, con le sue unità.

Serve a chi racconta il punteggio (#678): «145 mm in 7 ore contro una soglia di 2,4 mm/h» invece di «soglia superata sì/no». Non entra nel punteggio, che legge caine_excess.

KinematicBreakdown

Bases: _Frozen

Sub-terms for the V1.5 K component (zero when no sensor coverage).

FireWeatherState

Bases: _Frozen

La catena FWI di una cella in un giorno (Van Wagner 1987).

Input del motore incendio, non output: i tre codici ricorsivi vivono in fwi_state e attraversano i riavvii, e questa è la loro lettura del giorno insieme ai tre indici derivati.

HazardBreakdown

Bases: _Frozen

Base of every per-hazard breakdown.

Carries the discriminator plus three projections. Component names are hazard-specific by definition -- S/M/E/F/H/K describe how a slope fails and mean nothing for a wildfire -- so the base holds no components of its own; instead it declares the three questions every consumer that must work for any hazard actually asks. Each subclass answers them in its own terms, and no consumer grows a branch per danger.

components

components() -> dict[str, float]

Named drivers, for a narrative or a generic breakdown view.

Labels are the hazard's own: the briefing quotes the top three and must not have to know which danger it is describing.

factors_payload

factors_payload() -> dict[str, Any]

What goes into risk_assessments.factors.

Owned here rather than by the persistence executor so the stored shape follows the breakdown that produced it. The landslide payload is byte-identical to the one written before this method existed -- rows and the /api/cell/{id}/breakdown reader are untouched.

predisposition

predisposition() -> float

Static susceptibility in [0, 1] -- terrain, not weather.

The alert gate uses it to keep below-High alerts to cells that are actually predisposed ("moderate rain on a susceptible slope", not "moderate rain anywhere"). Every hazard has such a notion; which component carries it is the subclass's business.

measured

measured() -> bool

Whether the dynamic input this hazard needs actually arrived.

A degraded source gives a neutral result, and for a multiplicative engine the neutral result is zero -- indistinguishable, once it reaches a map, from a genuinely calm cell (#143). Only the breakdown knows the difference, because only the breakdown holds the raw signal, so it is the breakdown that answers.

The default is True: a hazard whose score stands on terrain alone is measured even when the weather is missing. The ones that need a live feed say so themselves.

segnali

segnali() -> dict[str, bool]

Which of the day's input signals arrived, by id (#484).

The finer-grained sibling of :meth:measured: «rain yes, river no» is measured, but on half of what the engine can read. Static inputs are not here -- whether a layer is loaded is a property of the cell, not of the run, and core/dati_di_base.py already says it. The default is no signals: the landslide breakdown does not record whether its weather arrived.

from_factors classmethod

from_factors(payload: dict[str, Any]) -> Self

Rebuild from a persisted factors blob.

The inverse of :meth:factors_payload. It exists as a method, not as a plain model_validate at the call site, because JSONB does not round-trip Python types: these models are strict=True, so a date comes back as a string and is refused. Each subclass restores what its own payload lost.

ComponentBreakdown

Bases: HazardBreakdown

Landslide components + their normalised inputs, for auditability.

V1 ships five components (S/M/E/F/H, k always 0). V1.5 activates K on monitored cells and renormalises the others — but the same DTO shape carries both regimes so downstream consumers (ChatAgents, persistence, frontend) stay backwards-compatible.

The name is kept from before the hazard dimension existed: renaming it would touch every scoring consumer for no gain. Fase 2 adds FloodBreakdown and WildfireBreakdown alongside it.

WildfireBreakdown

Bases: HazardBreakdown

Componenti del pericolo incendio (#61).

Nessuna sovrapposizione con ComponentBreakdown: fwi è meteo del giorno, fuel è copertura del suolo, slope è morfologia. Chiamarli S/M/E sarebbe una coincidenza di lettere, non di significato.

FloodBreakdown

Bases: HazardBreakdown

Componenti del pericolo alluvione (#63).

susceptibility è ciò che la cella è — dal mosaico idraulico ISPRA — e i due trigger sono i due modi in cui l'acqua ci arriva. Tenuti distinti, non sommati: sono mitigati da cose diverse, e un operatore deve sapere quale dei due sta guardando.

RiskScore

Bases: _Frozen, Generic[BreakdownT_co]

Engine output, parameterised by the hazard's breakdown shape.

Generic rather than pinned to :class:ComponentBreakdown so the landslide engine can return RiskScore[ComponentBreakdown] and its callers keep reading .breakdown.s with no cast and no narrowing, while a flood or wildfire engine returns its own breakdown through the same class.

breakdown_from_factors

breakdown_from_factors(hazard: HazardType, payload: dict[str, Any]) -> HazardBreakdown

Rebuild a breakdown from a persisted factors blob.

Dispatches to the hazard's own :meth:HazardBreakdown.from_factors, which restores whatever JSONB flattened. Callers that read historical rows are responsible for supplying defaults for keys a newer pipeline added -- :mod:limen.api.endpoints.risk does that for landslide.

segnali_da_factors

segnali_da_factors(hazard: HazardType, payload: dict[str, Any]) -> dict[str, bool]

:meth:HazardBreakdown.segnali of a persisted row (#484).

A row that does not read back as a breakdown (historical, another shape) does not say which signals it had: no signals beats invented ones.