File: base.py

package info (click to toggle)
python-sigima 1.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,956 kB
  • sloc: python: 33,326; makefile: 3
file content (1037 lines) | stat: -rw-r--r-- 33,037 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.

"""
Base model classes for signals and images.
"""

# pylint: disable=invalid-name  # Allows short reference names like x, y, ...

from __future__ import annotations

import abc
import json
import re
import sys
from collections.abc import Generator
from copy import deepcopy
from typing import Any, Generic, Iterator, Type, TypeVar

import guidata.dataset as gds
import numpy as np
from numpy import ma

from sigima.config import _

if sys.version_info >= (3, 11):
    # Use Self from typing module in Python 3.11+
    from typing import Self
else:
    # Use Self from typing_extensions module in Python < 3.11
    from typing_extensions import Self

ROI_KEY = "_roi_"


def deepcopy_metadata(
    metadata: dict[str, Any],
    special_keys: set[str] | None = None,
    all_metadata: bool = False,
) -> dict[str, Any]:
    """Deepcopy metadata, except keys starting with "_" (private keys)
    with the exception of "_roi_" and "_ann_" keys.

    Args:
        metadata: Metadata dictionary to deepcopy.
        special_keys: Set of keys that should not be removed even if they
         start with "_".
        all_metadata: if True, copy all metadata, including private keys

    Returns:
        A new dictionary with deepcopied metadata, excluding private keys
        except those in `special_keys`.
    """
    if special_keys is None:
        special_keys = set([ROI_KEY])
    mdcopy = {}
    for key, value in metadata.items():
        if not key.startswith("_") or key in special_keys or all_metadata:
            mdcopy[key] = deepcopy(value)
    return mdcopy


class BaseProcParam(gds.DataSet):
    """Base class for processing parameters."""

    def apply_integer_range(self, vmin, vmax):  # pylint: disable=unused-argument
        """Do something in case of integer min-max range."""

    def apply_float_range(self, vmin, vmax):  # pylint: disable=unused-argument
        """Do something in case of float min-max range."""

    def set_from_datatype(self, dtype):
        """Set min/max range from NumPy datatype."""
        if np.issubdtype(dtype, np.integer):
            info = np.iinfo(dtype)
            self.apply_integer_range(info.min, info.max)
        else:
            info = np.finfo(dtype)
            self.apply_float_range(info.min, info.max)


class BaseRandomParam(BaseProcParam):
    """Random signal/image parameters."""

    seed = gds.IntItem(_("Seed"), default=1)


class UniformDistributionParam(BaseRandomParam):
    """Uniform-distribution signal/image parameters."""

    def apply_integer_range(self, vmin, vmax):
        """Do something in case of integer min-max range."""
        self.vmin, self.vmax = float(vmin), float(vmax)

    vmin = gds.FloatItem(
        "V<sub>min</sub>", default=-0.5, help=_("Uniform distribution lower bound")
    )
    vmax = gds.FloatItem(
        "V<sub>max</sub>", default=0.5, help=_("Uniform distribution higher bound")
    ).set_pos(col=1)

    def generate_title(self) -> str:
        """Generate a title based on current parameters."""
        return f"UniformRandom(vmin={self.vmin:g},vmax={self.vmax:g},seed={self.seed})"


class NormalDistributionParam(BaseRandomParam):
    """Normal-distribution signal/image parameters."""

    DEFAULT_RELATIVE_MU = 0.1
    DEFAULT_RELATIVE_SIGMA = 0.02

    def apply_integer_range(self, vmin, vmax):
        """Do something in case of integer min-max range."""
        delta = vmax - vmin
        self.mu = float(vmin + self.DEFAULT_RELATIVE_MU * delta)
        self.sigma = float(self.DEFAULT_RELATIVE_SIGMA * delta)

    mu = gds.FloatItem(
        "μ", default=DEFAULT_RELATIVE_MU, help=_("Normal distribution mean")
    )
    sigma = gds.FloatItem(
        "σ",
        default=DEFAULT_RELATIVE_SIGMA,
        min=0.0,
        help=_("Normal distribution standard deviation"),
    ).set_pos(col=1)

    def generate_title(self) -> str:
        """Generate a title based on current parameters."""
        return f"NormalRandom(μ={self.mu:g},σ={self.sigma:g},seed={self.seed})"


class PoissonDistributionParam(BaseRandomParam):
    """Base Poisson-distribution signal/image parameters."""

    DEFAULT_RELATIVE_LAMBDA = 0.1

    def apply_integer_range(self, vmin, vmax):
        """Adjust default λ based on integer min-max range."""
        positive_span = max(0.0, float(vmax) - max(0.0, float(vmin)))
        self.lam = float(max(self.DEFAULT_RELATIVE_LAMBDA * positive_span, 1.0))

    lam = gds.FloatItem(
        "λ",
        default=DEFAULT_RELATIVE_LAMBDA,
        min=0.0,
        help=_("Poisson distribution mean"),
    )

    def generate_title(self) -> str:
        """Generate a title based on current parameters."""
        return f"PoissonRandom(λ={self.lam:g},seed={self.seed})"


TypeObj = TypeVar("TypeObj", bound="BaseObj")
TypeROIParam = TypeVar("TypeROIParam", bound="BaseROIParam")
TypeSingleROI = TypeVar("TypeSingleROI", bound="BaseSingleROI")
TypeROI = TypeVar("TypeROI", bound="BaseROI")


class BaseObjMeta(abc.ABCMeta, gds.DataSetMeta):
    """Mixed metaclass to avoid conflicts"""


class NoDefaultOption:
    """Marker class for metadata option without default value"""


class BaseObj(Generic[TypeROI], metaclass=BaseObjMeta):
    """Object (signal/image) interface"""

    #: Class attribute that defines a string prefix used to uniquely identify instances
    #: of this class in metadata serialization. Each subclass should override this with
    #: a unique identifier (e.g., "s" for signals, "i" for images).
    #: This prefix is used as part of the key for storing and retrieving object-specific
    #: metadata, supporting type-based serialization and deserialization.
    PREFIX = ""  # This is overriden in children classes

    # This is overriden in children classes with a gds.DictItem instance:
    metadata: dict[str, Any] = {}
    annotations: str = ""

    #: Class attribute that defines a tuple of valid NumPy data types supported by this
    #: class. This is used to validate the data type of the object when it is set or
    #: modified and to ensure that the object can handle the data correctly.
    #: Subclasses should override this with a specific set of valid data types.
    VALID_DTYPES = (np.float64,)  # To be overriden in children classes

    def __init__(self):
        self.__roi_changed: bool | None = None
        self._maskdata_cache: np.ndarray | None = None
        self.__metadata_options_defaults: dict[str, Any] = {}
        self.__roi_cache: TypeROI | None = None

    @staticmethod
    @abc.abstractmethod
    def get_roi_class() -> Type[TypeROI]:
        """Return ROI class"""

    @property
    @abc.abstractmethod
    def data(self) -> np.ndarray | None:
        """Data"""

    @classmethod
    def get_valid_dtypenames(cls) -> list[str]:
        """Get valid data type names

        Returns:
            Valid data type names supported by this class
        """
        return [
            dtname
            for dtname in np.sctypeDict
            if isinstance(dtname, str)
            and dtname in (dtype.__name__ for dtype in cls.VALID_DTYPES)
        ]

    def check_data(self):
        """Check if data is valid, raise an exception if that's not the case

        Raises:
            TypeError: if data type is not supported
        """
        if self.data is not None:
            if self.data.dtype not in self.VALID_DTYPES:
                raise TypeError(f"Unsupported data type: {self.data.dtype}")

    def iterate_roi_indices(self) -> Generator[int | None, None, None]:
        """Iterate over object ROI indices (if there is no ROI, yield None)"""
        if self.roi is None:
            yield None
        else:
            yield from range(len(self.roi))

    @abc.abstractmethod
    def get_data(self, roi_index: int | None = None) -> np.ndarray:
        """
        Return original data (if ROI is not defined or `roi_index` is None),
        or ROI data (if both ROI and `roi_index` are defined).

        Args:
            roi_index: ROI index

        Returns:
            Data
        """

    @abc.abstractmethod
    def copy(
        self,
        title: str | None = None,
        dtype: np.dtype | None = None,
        all_metadata: bool = False,
    ) -> Self:
        """Copy object.

        Args:
            title: title
            dtype: data type
            all_metadata: if True, copy all metadata, otherwise only basic metadata

        Returns:
            Copied object
        """

    @abc.abstractmethod
    def set_data_type(self, dtype):
        """Change data type.

        Args:
            dtype: data type
        """

    @abc.abstractmethod
    def physical_to_indices(self, coords: list[float]) -> list[int]:
        """Convert coordinates from physical (real world) to indices

        Args:
            coords: coordinates

        Returns:
            Indices
        """

    @abc.abstractmethod
    def indices_to_physical(self, indices: list[int]) -> list[float]:
        """Convert coordinates from indices to physical (real world)

        Args:
            indices: indices

        Returns:
            Coordinates
        """

    def __roi_has_changed(self) -> bool:
        """Return True if ROI has changed since last call to this method.

        The first call to this method will return True if ROI has not yet been set,
        or if ROI has been set and has changed since the last call to this method.
        The next call to this method will always return False if ROI has not changed
        in the meantime.

        Returns:
            True if ROI has changed
        """
        if self.__roi_changed is None:
            self.__roi_changed = True
        returned_value = self.__roi_changed
        self.__roi_changed = False
        return returned_value

    @property
    def roi(self) -> TypeROI | None:
        """Return object regions of interest object.

        Returns:
            Regions of interest object
        """
        # If we have a cached ROI, return it
        if self.__roi_cache is not None:
            return self.__roi_cache

        # Otherwise, try to load from metadata
        roidata = self.metadata.get(ROI_KEY)
        if roidata is None:
            return None
        if not isinstance(roidata, dict):
            # Old or unsupported format: remove it
            self.metadata.pop(ROI_KEY)
            return None

        # Create ROI from metadata and cache it
        self.__roi_cache = self.get_roi_class().from_dict(roidata)
        return self.__roi_cache

    @roi.setter
    def roi(self, roi: TypeROI | None) -> None:
        """Set object regions of interest.

        Args:
            roi: regions of interest object
        """
        # Cache the ROI object
        self.__roi_cache = roi

        # Update metadata
        if roi is None:
            if ROI_KEY in self.metadata:
                self.metadata.pop(ROI_KEY)
        else:
            self.metadata[ROI_KEY] = roi.to_dict()
        self.__roi_changed = True

    @property
    def maskdata(self) -> np.ndarray | None:
        """Return masked data (areas outside defined regions of interest)

        Returns:
            Masked data
        """
        roi_changed = self.__roi_has_changed()
        if self.roi is None:
            if roi_changed:
                self._maskdata_cache = None
        elif roi_changed or self._maskdata_cache is None:
            self._maskdata_cache = self.roi.to_mask(self)
        return self._maskdata_cache

    def get_masked_view(self) -> ma.MaskedArray:
        """Return masked view for data

        Returns:
            Masked view
        """
        assert isinstance(self.data, np.ndarray)
        view = self.data.view(ma.MaskedArray)
        if self.maskdata is None:
            view.mask = np.isnan(self.data)
        else:
            view.mask = self.maskdata | np.isnan(self.data)
        return view

    def invalidate_maskdata_cache(self) -> None:
        """Invalidate mask data cache: force to rebuild it"""
        self._maskdata_cache = None

    def invalidate_roi_cache(self) -> None:
        """Invalidate ROI cache: force to reload it from metadata"""
        self.__roi_cache = None
        # Also invalidate mask data cache since ROI data might have changed
        self.invalidate_maskdata_cache()

    def sync_roi_to_metadata(self) -> None:
        """Synchronize the current ROI cache to metadata.

        This should be called after modifying the ROI object directly
        to ensure the changes are persisted in metadata.
        """
        if self.__roi_cache is not None:
            self.metadata[ROI_KEY] = self.__roi_cache.to_dict()
            self.__roi_changed = True
            # Also invalidate mask data cache since ROI has changed
            self.invalidate_maskdata_cache()

    def mark_roi_as_changed(self) -> None:
        """Mark the ROI as changed and invalidate dependent caches.

        This should be called after modifying the ROI object directly
        to ensure all dependent data (like mask cache) is properly invalidated.
        """
        self.__roi_changed = True
        self.invalidate_maskdata_cache()
        # Optionally sync to metadata immediately
        self.sync_roi_to_metadata()

    def update_metadata_from(self, other_metadata: dict[str, Any]) -> None:
        """Update metadata from another object's metadata (merge result shapes and
        annotations, and update the rest of the metadata).

        Args:
            other_metadata: other object metadata
        """
        self.metadata.update(other_metadata)
        # Invalidate ROI cache since metadata might have changed ROI data
        self.invalidate_roi_cache()

    # Method to set the default values of metadata options:
    def set_metadata_options_defaults(
        self, defaults: dict[str, Any], overwrite: bool = False
    ) -> None:
        """Set default values for metadata options

        A metadata option is a metadata entry starting with a double underscore.
        It is a way to store application-specific options in object metadata.

        .. note::

            This will not overwrite existing metadata options
            (unless `overwrite` is True).
            It will only set the default values for options that are not already set.*
            Use `reset_metadata_to_defaults` method to reset all metadata options
            to their default values.

        Args:
            defaults: dictionary of default values for metadata options
            overwrite: whether to overwrite existing metadata options (default: False)
        """
        self.__metadata_options_defaults.update(defaults)
        for key, value in defaults.items():
            self.set_metadata_option(key, value, overwrite)

    def get_metadata_options_defaults(self) -> dict[str, Any]:
        """Return default values for metadata options

        A metadata option is a metadata entry starting with a double underscore.
        It is a way to store application-specific options in object metadata.

        Returns:
            Dictionary of default values for metadata options
        """
        return self.__metadata_options_defaults

    def get_metadata_option(self, name: str, default: Any = NoDefaultOption) -> Any:
        """Return metadata option value

        A metadata option is a metadata entry starting with a double underscore.
        It is a way to store application-specific options in object metadata.

        Args:
            name: option name
            default: default value if option is not set (optional)

        Returns:
            Option value

        Raises:
            ValueError: if option name is invalid
        """
        if (
            default is not NoDefaultOption
            and name not in self.__metadata_options_defaults
        ):
            # If default is provided, store it in defaults
            # and set it as the option value
            self.__metadata_options_defaults[name] = default
            self.set_metadata_option(name, default, overwrite=False)
        try:
            value = self.metadata[f"__{name}"]
        except KeyError as exc:
            defaults = self.get_metadata_options_defaults()
            if name in defaults:
                value = defaults[name]
            else:
                raise ValueError(
                    f"Invalid metadata option name `{name}` "
                    f"(valid names: {', '.join(defaults.keys())})"
                ) from exc
        return value

    def set_metadata_option(
        self, name: str, value: Any, overwrite: bool = True
    ) -> None:
        """Set metadata option value

        A metadata option is a metadata entry starting with a double underscore.
        It is a way to store application-specific options in object metadata.

        Args:
            name: option name
            value: option value
            overwrite: whether to overwrite existing metadata options (default: True)

        Raises:
            ValueError: if option name is invalid
        """
        if overwrite or f"__{name}" not in self.metadata:
            self.metadata[f"__{name}"] = value

    def get_metadata_options(self) -> dict[str, Any]:
        """Return metadata options
        A metadata option is a metadata entry starting with a double underscore.

        Returns:
            Dictionary of metadata options (name: value)
        """
        options = {}
        for name, value in self.metadata.items():
            if name.startswith("__"):
                options[name[2:]] = value
        return options

    def reset_metadata_to_defaults(self) -> None:
        """Reset metadata to default values"""
        self.metadata = {}
        self.invalidate_roi_cache()
        defaults = self.get_metadata_options_defaults()
        for name, value in defaults.items():
            self.set_metadata_option(name, value)

    def save_attr_to_metadata(self, attrname: str, new_value: Any) -> None:
        """Save attribute to metadata

        Args:
            attrname: attribute name
            new_value: new value
        """
        value = getattr(self, attrname)
        if value:
            self.metadata[f"orig_{attrname}"] = value
        setattr(self, attrname, new_value)

    def restore_attr_from_metadata(self, attrname: str, default: Any) -> None:
        """Restore attribute from metadata

        Args:
            attrname: attribute name
            default: default value
        """
        value = self.metadata.pop(f"orig_{attrname}", default)
        setattr(self, attrname, value)

    # ------Annotation management methods

    def get_annotations(self) -> list[dict[str, Any]]:
        """Get annotations as a list of dictionaries.

        Returns:
            List of annotation dictionaries. Each dict contains application-specific
            annotation data. Returns empty list if no annotations exist.

        Notes:
            The annotation format is defined by the application layer. Sigima only
            provides storage and basic validation (valid JSON structure).

        Example:
            >>> obj.set_annotations([
            ...     {"type": "label", "x": 10, "y": 20, "text": "Peak"},
            ...     {"type": "rectangle", "x0": 0, "y0": 0, "x1": 100, "y1": 100}
            ... ])
            >>> annotations = obj.get_annotations()
            >>> len(annotations)
            2
        """
        if not self.annotations:
            return []
        try:
            data = json.loads(self.annotations)
            if isinstance(data, dict) and "annotations" in data:
                return data["annotations"]
            return []
        except (json.JSONDecodeError, TypeError):
            # Invalid JSON - return empty list
            return []

    def set_annotations(self, annotations: list[dict[str, Any]]) -> None:
        """Set annotations from a list of dictionaries.

        Args:
            annotations: List of annotation dictionaries

        Raises:
            TypeError: If annotations is not a list
            ValueError: If annotation items are not JSON-serializable

        Notes:
            Each annotation dictionary should be JSON-serializable.
            The internal storage format includes a version field for future migration.

        Example:
            >>> obj.set_annotations([{"type": "label", "text": "Test"}])
        """
        if not isinstance(annotations, list):
            raise TypeError(f"Annotations must be a list, got {type(annotations)}")

        # Validate JSON serializability
        try:
            # Store with version for future-proofing
            data = {"version": "1.0", "annotations": annotations}
            self.annotations = json.dumps(data, indent=2)
        except (TypeError, ValueError) as exc:
            raise ValueError(f"Annotations must be JSON-serializable: {exc}") from exc

    def add_annotation(self, annotation: dict[str, Any]) -> None:
        """Add a single annotation.

        Args:
            annotation: Annotation dictionary to add

        Example:
            >>> obj.add_annotation({"type": "circle", "x": 50, "y": 50, "r": 10})
        """
        current = self.get_annotations()
        current.append(annotation)
        self.set_annotations(current)

    def clear_annotations(self) -> None:
        """Remove all annotations.

        Example:
            >>> obj.clear_annotations()
            >>> obj.get_annotations()
            []
        """
        self.annotations = ""

    def has_annotations(self) -> bool:
        """Check if object has any annotations.

        Returns:
            True if annotations exist, False otherwise

        Example:
            >>> obj.has_annotations()
            False
            >>> obj.add_annotation({"type": "label"})
            >>> obj.has_annotations()
            True
        """
        return bool(self.get_annotations())


class BaseROIParamMeta(abc.ABCMeta, gds.DataSetMeta):
    """Mixed metaclass to avoid conflicts"""


class BaseROIParam(
    gds.DataSet,
    Generic[TypeObj, TypeSingleROI],  # type: ignore
    metaclass=BaseROIParamMeta,
):
    """Base class for ROI parameters"""

    @abc.abstractmethod
    def to_single_roi(self, obj: TypeObj) -> TypeSingleROI:
        """Convert parameters to single ROI

        Args:
            obj: object (signal/image)

        Returns:
            Single ROI
        """


class BaseSingleROI(Generic[TypeObj, TypeROIParam], abc.ABC):  # type: ignore
    """Base class for single ROI

    Args:
        coords: ROI edge (physical or pixel coordinates)
        indices: if True, coords are indices (pixels) instead of physical coordinates
        title: ROI title
    """

    def __init__(
        self,
        coords: np.ndarray | list[int] | list[float],
        indices: bool,
        title: str = "ROI",
    ) -> None:
        self.coords = np.array(coords, int if indices else float)
        self.indices = indices
        self.title = title
        self.check_coords()

    def __eq__(self, other: BaseSingleROI | None) -> bool:
        """Test equality with another single ROI"""
        if other is None:
            return False
        if not isinstance(other, BaseSingleROI):
            raise TypeError(f"Cannot compare {type(self)} with {type(other)}")
        return (
            np.array_equal(self.coords, other.coords) and self.indices == other.indices
        )

    def get_physical_coords(self, obj: TypeObj) -> list[float]:
        """Return physical coords

        Args:
            obj: object (signal/image)

        Returns:
            Physical coords
        """
        if self.indices:
            return obj.indices_to_physical(self.coords.tolist())
        return self.coords.tolist()

    def set_physical_coords(self, obj: TypeObj, coords: np.ndarray) -> None:
        """Set physical coords

        Args:
            obj: object (signal/image)
            coords: physical coords
        """
        if self.indices:
            self.coords = np.array(obj.physical_to_indices(coords.tolist()))
        else:
            self.coords = np.array(coords, float)

    def get_indices_coords(self, obj: TypeObj) -> list[int]:
        """Return indices coords

        Args:
            obj: object (signal/image)

        Returns:
            Indices coords
        """
        if self.indices:
            return self.coords.tolist()
        return obj.physical_to_indices(self.coords.tolist())

    def set_indices_coords(self, obj: TypeObj, coords: np.ndarray) -> None:
        """Set indices coords

        Args:
            obj: object (signal/image)
            coords: indices coords
        """
        if self.indices:
            self.coords = coords
        else:
            self.coords = np.array(obj.indices_to_physical(coords.tolist()))

    @abc.abstractmethod
    def check_coords(self) -> None:
        """Check if coords are valid

        Raises:
            ValueError: invalid coords
        """

    @abc.abstractmethod
    def to_mask(self, obj: TypeObj) -> np.ndarray:
        """Create mask from ROI

        Args:
            obj: signal or image object

        Returns:
            Mask (boolean array where True values are inside the ROI)
        """

    @abc.abstractmethod
    def to_param(self, obj: TypeObj, index: int) -> TypeROIParam:
        """Convert ROI to parameters

        Args:
            obj: object (signal/image), for physical-indices coordinates conversion
            index: ROI index
        """

    def to_dict(self) -> dict:
        """Convert ROI to dictionary

        Returns:
            Dictionary
        """
        return {
            "coords": self.coords,
            "indices": self.indices,
            "title": self.title,
            "type": type(self).__name__,
        }

    @classmethod
    def from_dict(cls: Type[TypeSingleROI], dictdata: dict) -> TypeSingleROI:
        """Convert dictionary to ROI

        Args:
            dictdata: dictionary

        Returns:
            ROI
        """
        return cls(dictdata["coords"], dictdata["indices"], dictdata["title"])


class BaseROI(Generic[TypeObj, TypeSingleROI, TypeROIParam], abc.ABC):  # type: ignore
    """Abstract base class for ROIs (Regions of Interest)

    Args:
        inverse: if True, ROI is outside the region of interest
    """

    #: Class attribute that defines a string prefix used for identifying ROI types
    #: in object metadata. This prefix is used when serializing and deserializing ROIs,
    #: allowing the system to determine the appropriate ROI class for reconstruction.
    #: Each ROI subclass should override this with a unique string identifier.
    PREFIX = ""  # This is overriden in children classes

    def __init__(self) -> None:
        self.single_rois: list[TypeSingleROI] = []

    @staticmethod
    @abc.abstractmethod
    def get_compatible_single_roi_classes() -> list[Type[BaseSingleROI]]:
        """Return compatible single ROI classes"""

    def __len__(self) -> int:
        """Return number of ROIs"""
        return len(self.single_rois)

    def __iter__(self) -> Iterator[TypeSingleROI]:
        """Iterate over single ROIs"""
        return iter(self.single_rois)

    def __eq__(self, other: BaseROI | None) -> bool:
        """Test equality with another ROI"""
        if other is None:
            return False
        if not isinstance(other, BaseROI):
            raise TypeError(f"Cannot compare {type(self)} with {type(other)}")
        return self.single_rois == other.single_rois

    def get_single_roi(self, index: int) -> TypeSingleROI:
        """Return single ROI at index

        Args:
            index: ROI index
        """
        return self.single_rois[index]

    def set_single_roi(self, index: int, roi: TypeSingleROI) -> None:
        """Set single ROI at index

        Args:
            index: ROI index
            roi: ROI to set
        """
        self.single_rois[index] = roi

    def get_single_roi_title(self, index: int) -> str:
        """Generate title for single ROI, based on its index, using either the
        ROI title or a default generic title as fallback.

        Args:
            index: ROI index
        """
        single_roi = self.get_single_roi(index)
        title = single_roi.title or get_generic_roi_title(index)
        return title

    def is_empty(self) -> bool:
        """Return True if no ROI is defined"""
        return len(self) == 0

    @classmethod
    def create(
        cls: Type[BaseROI], single_roi: TypeSingleROI
    ) -> BaseROI[TypeObj, TypeSingleROI, TypeROIParam]:
        """Create Regions of Interest object from a single ROI.

        Args:
            single_roi: single ROI

        Returns:
            Regions of Interest object
        """
        roi = cls()
        roi.add_roi(single_roi)
        return roi

    def copy(self) -> BaseROI[TypeObj, TypeSingleROI, TypeROIParam]:
        """Return a copy of ROIs"""
        return deepcopy(self)

    def empty(self) -> None:
        """Empty ROIs"""
        self.single_rois.clear()

    def combine_with(
        self, other: BaseROI[TypeObj, TypeSingleROI, TypeROIParam]
    ) -> BaseROI[TypeObj, TypeSingleROI, TypeROIParam]:
        """Combine ROIs with another ROI object, by merging single ROIs (and ignoring
        duplicate single ROIs) and returning a new combined ROI object.

        Args:
            other: other ROI object

        Returns:
            Combined ROIs object
        """
        if not isinstance(other, type(self)):
            raise TypeError(f"Cannot combine {type(self)} with {type(other)}")
        combined_roi = self.copy()
        for roi in other.single_rois:
            if all(s_roi != roi for s_roi in self.single_rois):
                combined_roi.single_rois.append(roi)
        return combined_roi

    def add_roi(
        self, roi: TypeSingleROI | BaseROI[TypeObj, TypeSingleROI, TypeROIParam]
    ) -> None:
        """Add ROI.

        Args:
            roi: ROI

        Raises:
            TypeError: if roi type is not supported (not a single ROI or a ROI)
            ValueError: if `inverse` values are incompatible
        """
        if isinstance(roi, BaseSingleROI):
            self.single_rois.append(roi)
        elif isinstance(roi, BaseROI):
            self.single_rois.extend(roi.single_rois)
        else:
            raise TypeError(f"Unsupported ROI type: {type(roi)}")

    @abc.abstractmethod
    def to_mask(self, obj: TypeObj) -> np.ndarray:
        """Create mask from ROI

        Args:
            obj: signal or image object

        Returns:
            Mask (boolean array where True values are inside the ROI)
        """

    def to_params(self, obj: TypeObj) -> list[TypeROIParam]:
        """Convert ROIs to a list of parameters

        Args:
            obj: object (signal/image), for physical to pixel conversion

        Returns:
            ROI parameters
        """
        return [iroi.to_param(obj, index=idx) for idx, iroi in enumerate(self)]

    @classmethod
    def from_params(
        cls: Type[BaseROI],
        obj: TypeObj,
        params: list[TypeROIParam],
    ) -> BaseROI[TypeObj, TypeSingleROI, TypeROIParam]:
        """Create ROIs from parameters

        Args:
            obj: object (signal/image)
            params: ROI parameters

        Returns:
            ROIs
        """
        roi = cls()
        for param in params:
            assert isinstance(param, BaseROIParam), "Invalid ROI parameter type"
            roi.add_roi(param.to_single_roi(obj))
        return roi

    def to_dict(self) -> dict:
        """Convert ROIs to dictionary

        Returns:
            Dictionary
        """
        return {
            "single_rois": [roi.to_dict() for roi in self.single_rois],
        }

    @classmethod
    def from_dict(cls: Type[TypeROI], dictdata: dict) -> TypeROI:
        """Convert dictionary to ROIs

        Args:
            dictdata: dictionary

        Returns:
            ROIs
        """
        instance = cls()
        if not all(key in dictdata for key in ["single_rois"]):
            raise ValueError("Invalid ROI: dictionary must contain 'single_rois' key")
        instance.single_rois = []
        for single_roi in dictdata["single_rois"]:
            for single_roi_class in instance.get_compatible_single_roi_classes():
                if single_roi["type"] == single_roi_class.__name__:
                    instance.single_rois.append(single_roi_class.from_dict(single_roi))
                    break
            else:
                raise ValueError(f"Unsupported single ROI type: {single_roi['type']}")
        return instance


GENERIC_ROI_TITLE_REGEXP = r"ROI(\d+)"


def get_generic_roi_title(index: int) -> None:
    """Return a generic title for the ROI"""
    title = f"ROI{index:02d}"
    assert re.match(GENERIC_ROI_TITLE_REGEXP, title)
    return title