Coverage for python / lsst / scarlet / lite / io / component.py: 69%
31 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-26 08:40 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-04-26 08:40 +0000
1from __future__ import annotations
3from abc import ABC, abstractmethod
4from dataclasses import dataclass
5from typing import ClassVar
7import numpy as np
8from numpy.typing import DTypeLike
10from ..component import Component
11from ..observation import Observation
12from .utils import PersistenceError
14__all__ = ["ScarletComponentBaseData"]
17@dataclass(kw_only=True)
18class ScarletComponentBaseData(ABC):
19 """Base data for a scarlet component
21 Attributes
22 ----------
23 component_registry :
24 A registry of all known component types used for deserialization.
25 component_type :
26 The type of component being stored.
27 version :
28 The schema version of the exact data class.
29 """
31 component_registry: ClassVar[dict[str, type[ScarletComponentBaseData]]] = {}
32 component_type: str
33 version: str
35 @classmethod
36 def register(cls) -> None:
37 """Register a new component type"""
38 ScarletComponentBaseData.component_registry[cls.component_type] = cls
40 @abstractmethod
41 def to_component(self, observation: Observation) -> Component:
42 """Convert the storage data model into a scarlet Component
44 Parameters
45 ----------
46 observation :
47 The observation that the component is associated with
49 Returns
50 -------
51 component :
52 A scarlet component extracted from persisted data.
53 """
55 @abstractmethod
56 def as_dict(self) -> dict:
57 """Return the object encoded into a dict for JSON serialization
59 Returns
60 -------
61 result :
62 The object encoded as a JSON compatible dict
63 """
65 @staticmethod
66 def from_dict(data: dict, dtype: DTypeLike = np.float32) -> ScarletComponentBaseData:
67 """Reconstruct `ScarletComponentBaseData` from JSON compatible
68 dict.
70 Parameters
71 ----------
72 data :
73 Dictionary representation of the object
74 dtype :
75 Datatype of the resulting model.
77 Returns
78 -------
79 result :
80 The reconstructed object
81 """
82 component_type = data.get("component_type", "factorized")
83 # Fix legacy naming
84 if component_type == "component":
85 component_type = "cube"
86 if component_type not in ScarletComponentBaseData.component_registry:
87 raise PersistenceError(f"Unknown component type: {component_type}")
88 cls = ScarletComponentBaseData.component_registry[component_type]
89 return cls.from_dict(data, dtype=dtype)