sigima 0.0.1.dev0__py3-none-any.whl → 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. sigima/__init__.py +142 -2
  2. sigima/client/__init__.py +105 -0
  3. sigima/client/base.py +780 -0
  4. sigima/client/remote.py +469 -0
  5. sigima/client/stub.py +814 -0
  6. sigima/client/utils.py +90 -0
  7. sigima/config.py +444 -0
  8. sigima/data/logo/Sigima.svg +135 -0
  9. sigima/data/tests/annotations.json +798 -0
  10. sigima/data/tests/curve_fitting/exponential_fit.txt +511 -0
  11. sigima/data/tests/curve_fitting/gaussian_fit.txt +100 -0
  12. sigima/data/tests/curve_fitting/piecewiseexponential_fit.txt +1022 -0
  13. sigima/data/tests/curve_fitting/polynomial_fit.txt +100 -0
  14. sigima/data/tests/curve_fitting/twohalfgaussian_fit.txt +1000 -0
  15. sigima/data/tests/curve_formats/bandwidth.txt +201 -0
  16. sigima/data/tests/curve_formats/boxcar.npy +0 -0
  17. sigima/data/tests/curve_formats/datetime.txt +1001 -0
  18. sigima/data/tests/curve_formats/dynamic_parameters.txt +4000 -0
  19. sigima/data/tests/curve_formats/fw1e2.txt +301 -0
  20. sigima/data/tests/curve_formats/fwhm.txt +319 -0
  21. sigima/data/tests/curve_formats/multiple_curves.csv +29 -0
  22. sigima/data/tests/curve_formats/noised_saw.mat +0 -0
  23. sigima/data/tests/curve_formats/oscilloscope.csv +111 -0
  24. sigima/data/tests/curve_formats/other/other2/recursive2.txt +5 -0
  25. sigima/data/tests/curve_formats/other/recursive1.txt +5 -0
  26. sigima/data/tests/curve_formats/paracetamol.npy +0 -0
  27. sigima/data/tests/curve_formats/paracetamol.txt +1010 -0
  28. sigima/data/tests/curve_formats/paracetamol_dx_dy.csv +1000 -0
  29. sigima/data/tests/curve_formats/paracetamol_dy.csv +1001 -0
  30. sigima/data/tests/curve_formats/pulse1.npy +0 -0
  31. sigima/data/tests/curve_formats/pulse2.npy +0 -0
  32. sigima/data/tests/curve_formats/simple.txt +5 -0
  33. sigima/data/tests/curve_formats/spectrum.mca +2139 -0
  34. sigima/data/tests/curve_formats/square2.npy +0 -0
  35. sigima/data/tests/curve_formats/step.npy +0 -0
  36. sigima/data/tests/fabry-perot1.jpg +0 -0
  37. sigima/data/tests/fabry-perot2.jpg +0 -0
  38. sigima/data/tests/flower.npy +0 -0
  39. sigima/data/tests/image_formats/NF 180338201.scor-data +11003 -0
  40. sigima/data/tests/image_formats/binary_image.npy +0 -0
  41. sigima/data/tests/image_formats/binary_image.png +0 -0
  42. sigima/data/tests/image_formats/centroid_test.npy +0 -0
  43. sigima/data/tests/image_formats/coordinated_text/complex_image.txt +10011 -0
  44. sigima/data/tests/image_formats/coordinated_text/complex_ref_image.txt +10010 -0
  45. sigima/data/tests/image_formats/coordinated_text/image.txt +15 -0
  46. sigima/data/tests/image_formats/coordinated_text/image2.txt +14 -0
  47. sigima/data/tests/image_formats/coordinated_text/image_no_unit_no_label.txt +14 -0
  48. sigima/data/tests/image_formats/coordinated_text/image_with_nan.txt +15 -0
  49. sigima/data/tests/image_formats/coordinated_text/image_with_unit.txt +14 -0
  50. sigima/data/tests/image_formats/fiber.csv +480 -0
  51. sigima/data/tests/image_formats/fiber.jpg +0 -0
  52. sigima/data/tests/image_formats/fiber.png +0 -0
  53. sigima/data/tests/image_formats/fiber.txt +480 -0
  54. sigima/data/tests/image_formats/gaussian_spot_with_noise.npy +0 -0
  55. sigima/data/tests/image_formats/mr-brain.dcm +0 -0
  56. sigima/data/tests/image_formats/noised_gaussian.mat +0 -0
  57. sigima/data/tests/image_formats/sif_reader/nd_lum_image_no_glue.sif +0 -0
  58. sigima/data/tests/image_formats/sif_reader/raman1.sif +0 -0
  59. sigima/data/tests/image_formats/tiling.txt +10 -0
  60. sigima/data/tests/image_formats/uint16.tiff +0 -0
  61. sigima/data/tests/image_formats/uint8.tiff +0 -0
  62. sigima/data/tests/laser_beam/TEM00_z_13.jpg +0 -0
  63. sigima/data/tests/laser_beam/TEM00_z_18.jpg +0 -0
  64. sigima/data/tests/laser_beam/TEM00_z_23.jpg +0 -0
  65. sigima/data/tests/laser_beam/TEM00_z_30.jpg +0 -0
  66. sigima/data/tests/laser_beam/TEM00_z_35.jpg +0 -0
  67. sigima/data/tests/laser_beam/TEM00_z_40.jpg +0 -0
  68. sigima/data/tests/laser_beam/TEM00_z_45.jpg +0 -0
  69. sigima/data/tests/laser_beam/TEM00_z_50.jpg +0 -0
  70. sigima/data/tests/laser_beam/TEM00_z_55.jpg +0 -0
  71. sigima/data/tests/laser_beam/TEM00_z_60.jpg +0 -0
  72. sigima/data/tests/laser_beam/TEM00_z_65.jpg +0 -0
  73. sigima/data/tests/laser_beam/TEM00_z_70.jpg +0 -0
  74. sigima/data/tests/laser_beam/TEM00_z_75.jpg +0 -0
  75. sigima/data/tests/laser_beam/TEM00_z_80.jpg +0 -0
  76. sigima/enums.py +195 -0
  77. sigima/io/__init__.py +123 -0
  78. sigima/io/base.py +311 -0
  79. sigima/io/common/__init__.py +5 -0
  80. sigima/io/common/basename.py +164 -0
  81. sigima/io/common/converters.py +189 -0
  82. sigima/io/common/objmeta.py +181 -0
  83. sigima/io/common/textreader.py +58 -0
  84. sigima/io/convenience.py +157 -0
  85. sigima/io/enums.py +17 -0
  86. sigima/io/ftlab.py +395 -0
  87. sigima/io/image/__init__.py +9 -0
  88. sigima/io/image/base.py +177 -0
  89. sigima/io/image/formats.py +1016 -0
  90. sigima/io/image/funcs.py +414 -0
  91. sigima/io/signal/__init__.py +9 -0
  92. sigima/io/signal/base.py +129 -0
  93. sigima/io/signal/formats.py +290 -0
  94. sigima/io/signal/funcs.py +723 -0
  95. sigima/objects/__init__.py +260 -0
  96. sigima/objects/base.py +937 -0
  97. sigima/objects/image/__init__.py +88 -0
  98. sigima/objects/image/creation.py +556 -0
  99. sigima/objects/image/object.py +524 -0
  100. sigima/objects/image/roi.py +904 -0
  101. sigima/objects/scalar/__init__.py +57 -0
  102. sigima/objects/scalar/common.py +215 -0
  103. sigima/objects/scalar/geometry.py +502 -0
  104. sigima/objects/scalar/table.py +784 -0
  105. sigima/objects/shape.py +290 -0
  106. sigima/objects/signal/__init__.py +133 -0
  107. sigima/objects/signal/constants.py +27 -0
  108. sigima/objects/signal/creation.py +1428 -0
  109. sigima/objects/signal/object.py +444 -0
  110. sigima/objects/signal/roi.py +274 -0
  111. sigima/params.py +405 -0
  112. sigima/proc/__init__.py +96 -0
  113. sigima/proc/base.py +381 -0
  114. sigima/proc/decorator.py +330 -0
  115. sigima/proc/image/__init__.py +513 -0
  116. sigima/proc/image/arithmetic.py +335 -0
  117. sigima/proc/image/base.py +260 -0
  118. sigima/proc/image/detection.py +519 -0
  119. sigima/proc/image/edges.py +329 -0
  120. sigima/proc/image/exposure.py +406 -0
  121. sigima/proc/image/extraction.py +458 -0
  122. sigima/proc/image/filtering.py +219 -0
  123. sigima/proc/image/fourier.py +147 -0
  124. sigima/proc/image/geometry.py +661 -0
  125. sigima/proc/image/mathops.py +340 -0
  126. sigima/proc/image/measurement.py +195 -0
  127. sigima/proc/image/morphology.py +155 -0
  128. sigima/proc/image/noise.py +107 -0
  129. sigima/proc/image/preprocessing.py +182 -0
  130. sigima/proc/image/restoration.py +235 -0
  131. sigima/proc/image/threshold.py +217 -0
  132. sigima/proc/image/transformations.py +393 -0
  133. sigima/proc/signal/__init__.py +376 -0
  134. sigima/proc/signal/analysis.py +206 -0
  135. sigima/proc/signal/arithmetic.py +551 -0
  136. sigima/proc/signal/base.py +262 -0
  137. sigima/proc/signal/extraction.py +60 -0
  138. sigima/proc/signal/features.py +310 -0
  139. sigima/proc/signal/filtering.py +484 -0
  140. sigima/proc/signal/fitting.py +276 -0
  141. sigima/proc/signal/fourier.py +259 -0
  142. sigima/proc/signal/mathops.py +420 -0
  143. sigima/proc/signal/processing.py +580 -0
  144. sigima/proc/signal/stability.py +175 -0
  145. sigima/proc/title_formatting.py +227 -0
  146. sigima/proc/validation.py +272 -0
  147. sigima/tests/__init__.py +7 -0
  148. sigima/tests/common/__init__.py +0 -0
  149. sigima/tests/common/arithmeticparam_unit_test.py +26 -0
  150. sigima/tests/common/basename_unit_test.py +126 -0
  151. sigima/tests/common/client_unit_test.py +412 -0
  152. sigima/tests/common/converters_unit_test.py +77 -0
  153. sigima/tests/common/decorator_unit_test.py +176 -0
  154. sigima/tests/common/examples_unit_test.py +104 -0
  155. sigima/tests/common/kernel_normalization_unit_test.py +242 -0
  156. sigima/tests/common/roi_basic_unit_test.py +73 -0
  157. sigima/tests/common/roi_geometry_unit_test.py +171 -0
  158. sigima/tests/common/scalar_builder_unit_test.py +142 -0
  159. sigima/tests/common/scalar_unit_test.py +991 -0
  160. sigima/tests/common/shape_unit_test.py +183 -0
  161. sigima/tests/common/stat_unit_test.py +138 -0
  162. sigima/tests/common/title_formatting_unit_test.py +338 -0
  163. sigima/tests/common/tools_coordinates_unit_test.py +60 -0
  164. sigima/tests/common/transformations_unit_test.py +178 -0
  165. sigima/tests/common/validation_unit_test.py +205 -0
  166. sigima/tests/conftest.py +129 -0
  167. sigima/tests/data.py +998 -0
  168. sigima/tests/env.py +280 -0
  169. sigima/tests/guiutils.py +163 -0
  170. sigima/tests/helpers.py +532 -0
  171. sigima/tests/image/__init__.py +28 -0
  172. sigima/tests/image/binning_unit_test.py +128 -0
  173. sigima/tests/image/blob_detection_unit_test.py +312 -0
  174. sigima/tests/image/centroid_unit_test.py +170 -0
  175. sigima/tests/image/check_2d_array_unit_test.py +63 -0
  176. sigima/tests/image/contour_unit_test.py +172 -0
  177. sigima/tests/image/convolution_unit_test.py +178 -0
  178. sigima/tests/image/datatype_unit_test.py +67 -0
  179. sigima/tests/image/edges_unit_test.py +155 -0
  180. sigima/tests/image/enclosingcircle_unit_test.py +88 -0
  181. sigima/tests/image/exposure_unit_test.py +223 -0
  182. sigima/tests/image/fft2d_unit_test.py +189 -0
  183. sigima/tests/image/filtering_unit_test.py +166 -0
  184. sigima/tests/image/geometry_unit_test.py +654 -0
  185. sigima/tests/image/hough_circle_unit_test.py +147 -0
  186. sigima/tests/image/imageobj_unit_test.py +737 -0
  187. sigima/tests/image/morphology_unit_test.py +71 -0
  188. sigima/tests/image/noise_unit_test.py +57 -0
  189. sigima/tests/image/offset_correction_unit_test.py +72 -0
  190. sigima/tests/image/operation_unit_test.py +518 -0
  191. sigima/tests/image/peak2d_limits_unit_test.py +41 -0
  192. sigima/tests/image/peak2d_unit_test.py +133 -0
  193. sigima/tests/image/profile_unit_test.py +159 -0
  194. sigima/tests/image/projections_unit_test.py +121 -0
  195. sigima/tests/image/restoration_unit_test.py +141 -0
  196. sigima/tests/image/roi2dparam_unit_test.py +53 -0
  197. sigima/tests/image/roi_advanced_unit_test.py +588 -0
  198. sigima/tests/image/roi_grid_unit_test.py +279 -0
  199. sigima/tests/image/spectrum2d_unit_test.py +40 -0
  200. sigima/tests/image/threshold_unit_test.py +91 -0
  201. sigima/tests/io/__init__.py +0 -0
  202. sigima/tests/io/addnewformat_unit_test.py +125 -0
  203. sigima/tests/io/convenience_funcs_unit_test.py +470 -0
  204. sigima/tests/io/coordinated_text_format_unit_test.py +495 -0
  205. sigima/tests/io/datetime_csv_unit_test.py +198 -0
  206. sigima/tests/io/imageio_formats_test.py +41 -0
  207. sigima/tests/io/ioregistry_unit_test.py +69 -0
  208. sigima/tests/io/objmeta_unit_test.py +87 -0
  209. sigima/tests/io/readobj_unit_test.py +130 -0
  210. sigima/tests/io/readwriteobj_unit_test.py +67 -0
  211. sigima/tests/signal/__init__.py +0 -0
  212. sigima/tests/signal/analysis_unit_test.py +135 -0
  213. sigima/tests/signal/check_1d_arrays_unit_test.py +169 -0
  214. sigima/tests/signal/convolution_unit_test.py +404 -0
  215. sigima/tests/signal/datetime_unit_test.py +176 -0
  216. sigima/tests/signal/fft1d_unit_test.py +303 -0
  217. sigima/tests/signal/filters_unit_test.py +403 -0
  218. sigima/tests/signal/fitting_unit_test.py +929 -0
  219. sigima/tests/signal/fwhm_unit_test.py +111 -0
  220. sigima/tests/signal/noise_unit_test.py +128 -0
  221. sigima/tests/signal/offset_correction_unit_test.py +34 -0
  222. sigima/tests/signal/operation_unit_test.py +489 -0
  223. sigima/tests/signal/peakdetection_unit_test.py +145 -0
  224. sigima/tests/signal/processing_unit_test.py +657 -0
  225. sigima/tests/signal/pulse/__init__.py +112 -0
  226. sigima/tests/signal/pulse/crossing_times_unit_test.py +123 -0
  227. sigima/tests/signal/pulse/plateau_detection_unit_test.py +102 -0
  228. sigima/tests/signal/pulse/pulse_unit_test.py +1824 -0
  229. sigima/tests/signal/roi_advanced_unit_test.py +392 -0
  230. sigima/tests/signal/signalobj_unit_test.py +603 -0
  231. sigima/tests/signal/stability_unit_test.py +431 -0
  232. sigima/tests/signal/uncertainty_unit_test.py +611 -0
  233. sigima/tests/vistools.py +1030 -0
  234. sigima/tools/__init__.py +59 -0
  235. sigima/tools/checks.py +290 -0
  236. sigima/tools/coordinates.py +308 -0
  237. sigima/tools/datatypes.py +26 -0
  238. sigima/tools/image/__init__.py +97 -0
  239. sigima/tools/image/detection.py +451 -0
  240. sigima/tools/image/exposure.py +77 -0
  241. sigima/tools/image/extraction.py +48 -0
  242. sigima/tools/image/fourier.py +260 -0
  243. sigima/tools/image/geometry.py +190 -0
  244. sigima/tools/image/preprocessing.py +165 -0
  245. sigima/tools/signal/__init__.py +86 -0
  246. sigima/tools/signal/dynamic.py +254 -0
  247. sigima/tools/signal/features.py +135 -0
  248. sigima/tools/signal/filtering.py +171 -0
  249. sigima/tools/signal/fitting.py +1171 -0
  250. sigima/tools/signal/fourier.py +466 -0
  251. sigima/tools/signal/interpolation.py +70 -0
  252. sigima/tools/signal/peakdetection.py +126 -0
  253. sigima/tools/signal/pulse.py +1626 -0
  254. sigima/tools/signal/scaling.py +50 -0
  255. sigima/tools/signal/stability.py +258 -0
  256. sigima/tools/signal/windowing.py +90 -0
  257. sigima/worker.py +79 -0
  258. sigima-1.0.0.dist-info/METADATA +233 -0
  259. sigima-1.0.0.dist-info/RECORD +262 -0
  260. {sigima-0.0.1.dev0.dist-info → sigima-1.0.0.dist-info}/licenses/LICENSE +29 -29
  261. sigima-0.0.1.dev0.dist-info/METADATA +0 -60
  262. sigima-0.0.1.dev0.dist-info/RECORD +0 -6
  263. {sigima-0.0.1.dev0.dist-info → sigima-1.0.0.dist-info}/WHEEL +0 -0
  264. {sigima-0.0.1.dev0.dist-info → sigima-1.0.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,784 @@
1
+ # Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
2
+
3
+ """
4
+ Table results
5
+ =============
6
+
7
+ Table results are compute-friendly result containers for scalar table outputs.
8
+
9
+ This module defines the `TableResult` class and related utilities:
10
+
11
+ - `TableResult`: table of scalar metrics
12
+ - `TableResultBuilder`: builder for TableResult with fluent interface
13
+ - Utility functions for table operations (concatenation, filtering, etc.)
14
+
15
+ Each result object is a simple data container with no behavior or methods:
16
+
17
+ - It contains the result of a 1-to-0 processing function
18
+ (e.g. `sigima.proc.signal.fwhm()`), i.e. a computation function that takes a signal
19
+ or image object (`SignalObj` or `ImageObj`) as input and produces a scalar output.
20
+
21
+ - The result may consist of multiple rows, each corresponding to a different ROI.
22
+
23
+ .. note::
24
+
25
+ No UI/HTML, no DataLab-specific metadata here. Adapters/formatters live in
26
+ DataLab. These classes are JSON-friendly via `to_dict()`/`from_dict()`.
27
+
28
+ Conventions
29
+ -----------
30
+
31
+ Conventions regarding ROI indexing:
32
+
33
+ - `NO_ROI = -1` sentinel is used for "full image / no ROI" rows.
34
+ - Per-ROI rows use non-negative indices (0-based).
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import dataclasses
40
+ import enum
41
+ import inspect
42
+ import os
43
+ from typing import TYPE_CHECKING, Any, Callable, Iterable, Mapping, Sequence
44
+
45
+ import numpy as np
46
+ import pandas as pd
47
+
48
+ from sigima.objects.scalar.common import (
49
+ NO_ROI,
50
+ DataFrameManager,
51
+ DisplayPreferencesManager,
52
+ ResultHtmlGenerator,
53
+ )
54
+
55
+ if TYPE_CHECKING:
56
+ from sigima.objects import ImageObj, SignalObj
57
+
58
+
59
+ class TableKind(str, enum.Enum):
60
+ """Types of table results."""
61
+
62
+ STATISTICS = "statistics"
63
+ PULSE_FEATURES = "pulse_features"
64
+ CUSTOM = "results"
65
+
66
+ @classmethod
67
+ def values(cls) -> list[str]:
68
+ """Return all table kind values."""
69
+ return [e.value for e in cls]
70
+
71
+
72
+ @dataclasses.dataclass(frozen=True)
73
+ class TableResult:
74
+ """Table of scalar results, optionally per-ROI.
75
+
76
+ Args:
77
+ title: Human-readable title for this table of results.
78
+ kind: Type of table result (e.g., TableKind.PULSE_FEATURES,
79
+ TableKind.STATISTICS). Default is TableKind.CUSTOM.
80
+ headers: Column names (one per metric).
81
+ data: 2-D list of shape (N, len(headers)) with scalar values.
82
+ roi_indices: Optional list (N,) mapping rows to ROI indices.
83
+ Use NO_ROI (-1) for the "full image / no ROI" row.
84
+ attrs: Optional algorithmic context (e.g. thresholds, method variant).
85
+
86
+ Raises:
87
+ ValueError: If dimensions are inconsistent or fields are invalid.
88
+
89
+ Notes:
90
+ - No UI/presentation concerns, no persistence schema here.
91
+ - Use DataLab-side adapters to store results in metadata if needed.
92
+ """
93
+
94
+ title: str
95
+ kind: TableKind | str = TableKind.CUSTOM
96
+ headers: Sequence[str] = dataclasses.field(default_factory=list)
97
+ data: list[list] = dataclasses.field(default_factory=list)
98
+ roi_indices: list[int] | None = None
99
+ attrs: dict[str, object] = dataclasses.field(default_factory=dict)
100
+
101
+ def __post_init__(self) -> None:
102
+ """Validate fields after initialization."""
103
+ if isinstance(self.kind, str):
104
+ try:
105
+ object.__setattr__(self, "kind", TableKind(self.kind))
106
+ except ValueError:
107
+ pass # Allow custom string values that are not in the enum
108
+ if not isinstance(self.title, str) or not self.title:
109
+ raise ValueError("title must be a non-empty string")
110
+ if not isinstance(self.headers, (list, tuple)) or not all(
111
+ isinstance(c, str) for c in self.headers
112
+ ):
113
+ raise ValueError("names must be a sequence of strings")
114
+ if not isinstance(self.data, list):
115
+ raise ValueError("data must be a list of lists")
116
+ if self.data and not isinstance(self.data[0], list):
117
+ raise ValueError("data must be a list of lists")
118
+ if self.data and len(self.data[0]) != len(self.headers):
119
+ raise ValueError("data columns must match names length")
120
+ if self.roi_indices is not None:
121
+ if not isinstance(self.roi_indices, list):
122
+ raise ValueError("roi_indices must be a list if provided")
123
+ if self.roi_indices and isinstance(self.roi_indices[0], list):
124
+ raise ValueError("roi_indices must be a list if provided")
125
+ if len(self.roi_indices) != len(self.data):
126
+ raise ValueError("roi_indices length must match number of data rows")
127
+
128
+ @property
129
+ def name(self) -> str:
130
+ """Get the unique identifier name for this scalar table result.
131
+
132
+ Returns:
133
+ The string value of the kind attribute, which serves as a unique
134
+ name identifier for this scalar table result type.
135
+ """
136
+ if isinstance(self.kind, TableKind):
137
+ return self.kind.value
138
+ return self.kind
139
+
140
+ def __str__(self) -> str:
141
+ """Return a string representation of the TableResult."""
142
+ df = self.to_dataframe()
143
+ text = f"TableResult(title={self.title}, kind={self.kind}, shape={df.shape})"
144
+ text += os.linesep * 2
145
+ text += str(df)
146
+ return text
147
+
148
+ # -------- Factory methods --------
149
+
150
+ @classmethod
151
+ def from_rows(
152
+ cls,
153
+ title: str,
154
+ headers: Sequence[str],
155
+ rows: list[list],
156
+ roi_indices: list[int] | None = None,
157
+ *,
158
+ kind: TableKind | str = TableKind.CUSTOM,
159
+ attrs: dict[str, object] | None = None,
160
+ ) -> TableResult:
161
+ """Create a TableResult from raw data.
162
+
163
+ Args:
164
+ title: Human-readable title for this table of results.
165
+ headers: Column names (one per metric).
166
+ rows: 2-D list of lists of shape (N, len(headers)) with values.
167
+ roi_indices: Optional list (N,) mapping rows to ROI indices.
168
+ Use NO_ROI (-1) for the "full image / no ROI" row.
169
+ kind: Type of table result (e.g., TableKind.PULSE_FEATURES).
170
+ attrs: Optional algorithmic context (e.g. thresholds, method variant).
171
+
172
+ Returns:
173
+ A TableResult instance.
174
+ """
175
+ return cls(
176
+ title,
177
+ kind,
178
+ headers,
179
+ rows,
180
+ roi_indices,
181
+ {} if attrs is None else dict(attrs),
182
+ )
183
+
184
+ # -------- JSON-friendly (de)serialization (no DataLab metadata coupling) -----
185
+
186
+ def to_dict(self) -> dict:
187
+ """Convert the TableResult to a dictionary."""
188
+ return {
189
+ "schema": 1,
190
+ "title": self.title,
191
+ "kind": self.kind.value if isinstance(self.kind, TableKind) else self.kind,
192
+ "names": list(self.headers),
193
+ "data": self.data,
194
+ "roi_indices": self.roi_indices,
195
+ "attrs": dict(self.attrs) if self.attrs else {},
196
+ }
197
+
198
+ @staticmethod
199
+ def from_dict(d: dict) -> TableResult:
200
+ """Convert a dictionary to a TableResult."""
201
+ return TableResult(
202
+ title=d["title"],
203
+ kind=d.get("kind", TableKind.CUSTOM),
204
+ headers=list(d["names"]),
205
+ data=d["data"],
206
+ roi_indices=d.get("roi_indices"),
207
+ attrs=dict(d.get("attrs", {})),
208
+ )
209
+
210
+ # -------- Pandas DataFrame interop --------
211
+
212
+ def to_dataframe(self, visible_only: bool = False):
213
+ """Convert the result to a pandas DataFrame.
214
+
215
+ Args:
216
+ visible_only: If True, include only visible headers based on display
217
+ preferences. Default is False.
218
+
219
+ Returns:
220
+ DataFrame with an optional 'roi_index' column.
221
+ If visible_only is True, only columns with visible headers are included.
222
+ """
223
+ df = pd.DataFrame(self.data, columns=self.headers)
224
+
225
+ # Add roi_index column if present
226
+ if self.roi_indices is not None:
227
+ df.insert(0, "roi_index", self.roi_indices)
228
+
229
+ # Filter to visible columns if requested
230
+ if visible_only:
231
+ visible_headers = self.get_visible_headers()
232
+ df = DataFrameManager.apply_visible_only_filter(df, visible_headers)
233
+
234
+ return df
235
+
236
+ def get_display_preferences(self) -> dict[str, bool]:
237
+ """Get display preferences for metrics.
238
+
239
+ Returns:
240
+ Dictionary mapping header names to visibility (True=visible, False=hidden).
241
+ By default, all metrics are visible unless specified in attrs.
242
+ """
243
+ return DisplayPreferencesManager.get_display_preferences(
244
+ self, self.headers, "hidden_metrics"
245
+ )
246
+
247
+ def set_display_preferences(self, preferences: dict[str, bool]) -> None:
248
+ """Set display preferences for metrics.
249
+
250
+ Args:
251
+ preferences: Dictionary mapping header names to visibility
252
+ (True=visible, False=hidden)
253
+ """
254
+ DisplayPreferencesManager.set_display_preferences(
255
+ self, preferences, self.headers, "hidden_metrics"
256
+ )
257
+
258
+ def get_visible_headers(self) -> list[str]:
259
+ """Get list of currently visible headers based on display preferences.
260
+
261
+ Returns:
262
+ List of header names that should be displayed
263
+ """
264
+ return DisplayPreferencesManager.get_visible_headers(
265
+ self, self.headers, "hidden_metrics"
266
+ )
267
+
268
+ @classmethod
269
+ def from_dataframe(
270
+ cls,
271
+ df,
272
+ title: str,
273
+ kind: TableKind | str = TableKind.CUSTOM,
274
+ attrs: dict = None,
275
+ ) -> TableResult:
276
+ """Create a TableResult from a pandas DataFrame.
277
+
278
+ Args:
279
+ df: pandas DataFrame. If 'roi_index' column is present, it is used
280
+ for roi_indices.
281
+ title: Title for the TableResult.
282
+ kind: Type of table result (e.g., TableKind.PULSE_FEATURES).
283
+ attrs: Optional dictionary of attributes.
284
+
285
+ Returns:
286
+ TableResult instance.
287
+ """
288
+ if not isinstance(df, pd.DataFrame):
289
+ raise TypeError("df must be a pandas DataFrame")
290
+ cols = list(df.columns)
291
+ if "roi_index" in cols:
292
+ roi_indices = df["roi_index"].tolist()
293
+ names = [c for c in cols if c != "roi_index"]
294
+ data = df[names].values.tolist()
295
+ else:
296
+ roi_indices = None
297
+ names = cols
298
+ data = df.values.tolist()
299
+ if attrs is None:
300
+ attrs = {}
301
+ return cls(
302
+ title=title,
303
+ kind=kind,
304
+ headers=names,
305
+ data=data,
306
+ roi_indices=roi_indices,
307
+ attrs=attrs,
308
+ )
309
+
310
+ # -------- User-oriented methods --------
311
+
312
+ def col(self, name: str) -> list:
313
+ """Return the column vector by name (raises KeyError if missing).
314
+
315
+ Args:
316
+ name: The name of the column to retrieve.
317
+
318
+ Returns:
319
+ A list containing the column data.
320
+ """
321
+ try:
322
+ j = list(self.headers).index(name)
323
+ except ValueError as exc:
324
+ raise KeyError(name) from exc
325
+ return [row[j] for row in self.data]
326
+
327
+ def __getitem__(self, name: str) -> list:
328
+ """Shorthand for col(name)."""
329
+ return self.col(name)
330
+
331
+ def __contains__(self, name: str) -> bool:
332
+ """Check if a column name exists in the table.
333
+
334
+ Args:
335
+ name: The name of the column to check.
336
+
337
+ Returns:
338
+ True if the column exists, False otherwise.
339
+ """
340
+ return name in self.headers
341
+
342
+ def __len__(self) -> int:
343
+ """Return the number of names in the table."""
344
+ return len(self.headers)
345
+
346
+ def value(self, name: str, roi: int | None = None) -> float:
347
+ """Return a single scalar by column name and ROI.
348
+
349
+ Args:
350
+ name: The name of the column to retrieve.
351
+ roi: The region of interest (ROI) to filter by (optional).
352
+ Use None for NO_ROI row.
353
+
354
+ Returns:
355
+ A single scalar value from the specified column and ROI.
356
+ """
357
+ vec = self.col(name)
358
+ if self.roi_indices is None:
359
+ # single row (common in 'full image' stats)
360
+ if len(vec) != 1:
361
+ raise ValueError(
362
+ "Ambiguous selection: multiple rows but no ROI indices"
363
+ )
364
+ return vec[0]
365
+ target = NO_ROI if roi is None else int(roi)
366
+ matching_indices = [
367
+ i for i, roi_idx in enumerate(self.roi_indices) if roi_idx == target
368
+ ]
369
+ if not matching_indices:
370
+ raise KeyError(f"No row for ROI={target}")
371
+ if len(matching_indices) != 1:
372
+ raise ValueError(
373
+ f"Ambiguous selection: {len(matching_indices)} rows for ROI={target}"
374
+ )
375
+ return vec[matching_indices[0]]
376
+
377
+ def as_dict(self, roi: int | None = None) -> dict[str, Any]:
378
+ """Return a {column -> value} mapping for one row (ROI or full image).
379
+
380
+ Args:
381
+ roi: The region of interest (ROI) to filter by (optional).
382
+ Use None for NO_ROI row.
383
+
384
+ Returns:
385
+ A dictionary mapping column names to their corresponding values.
386
+ """
387
+ if self.roi_indices is None:
388
+ if len(self.data) != 1:
389
+ raise ValueError(
390
+ "Ambiguous selection: multiple rows but no ROI indices"
391
+ )
392
+ row = self.data[0]
393
+ else:
394
+ target = NO_ROI if roi is None else int(roi)
395
+ matching_indices = [
396
+ i for i, roi_idx in enumerate(self.roi_indices) if roi_idx == target
397
+ ]
398
+ if not matching_indices:
399
+ raise KeyError(f"No row for ROI={target}")
400
+ if len(matching_indices) != 1:
401
+ raise ValueError(
402
+ f"Ambiguous selection: {len(matching_indices)} rows for "
403
+ f"ROI={target}"
404
+ )
405
+ row = self.data[matching_indices[0]]
406
+ return {name: row[j] for j, name in enumerate(self.headers)}
407
+
408
+ def to_html(
409
+ self,
410
+ obj: SignalObj | ImageObj,
411
+ visible_only: bool = True,
412
+ transpose_single_row: bool = True,
413
+ **kwargs,
414
+ ) -> str:
415
+ """Convert the result to HTML format.
416
+
417
+ Args:
418
+ obj: SignalObj or ImageObj for ROI title extraction
419
+ visible_only: If True, include only visible headers based on display
420
+ preferences. Default is False.
421
+ transpose_single_row: If True, transpose when there's only one row
422
+ **kwargs: Additional arguments passed to DataFrame.to_html()
423
+
424
+ Returns:
425
+ HTML representation of the result
426
+ """
427
+ return ResultHtmlGenerator.generate_html(
428
+ self, obj, visible_only, transpose_single_row, **kwargs
429
+ )
430
+
431
+ # -------- Convenience methods for table type identification --------
432
+
433
+ def is_statistics(self) -> bool:
434
+ """Check if this is a statistics table."""
435
+ return self.kind == TableKind.STATISTICS
436
+
437
+ def is_pulse_features(self) -> bool:
438
+ """Check if this is a pulse features table."""
439
+ return self.kind == TableKind.PULSE_FEATURES
440
+
441
+ def is_custom(self) -> bool:
442
+ """Check if this is a custom table."""
443
+ return self.kind == TableKind.CUSTOM
444
+
445
+
446
+ class TableResultBuilder:
447
+ """Builder for TableResult with fluent interface.
448
+
449
+ Args:
450
+ title: The title of the table.
451
+ kind: The type of table result.
452
+ """
453
+
454
+ def __init__(self, title: str, kind: TableKind | str = TableKind.CUSTOM) -> None:
455
+ self.title = title
456
+ self.kind = kind
457
+
458
+ # We define either a list of column functions, or a single global function
459
+ # that returns a dataclass instance with float/int fields.
460
+ self.column_funcs: list[tuple[Callable, str]] = []
461
+ self.global_func: Callable | None = None
462
+
463
+ self._hidden_columns: set[str] = set()
464
+
465
+ def set_global_function(self, func: Callable) -> None:
466
+ """Set a global function that returns a dataclass with float/int fields.
467
+
468
+ Args:
469
+ func: The function to compute the dataclass instance.
470
+ """
471
+ assert not self.column_funcs, "Cannot mix global and per-column functions"
472
+ assert isinstance(func, Callable), "Global function must be callable"
473
+ # Check function signature:
474
+ sig = inspect.signature(func)
475
+ if len(sig.parameters) < 1:
476
+ raise ValueError(
477
+ "Global function must accept at least one argument (xydata tuple)"
478
+ )
479
+ firstparam = list(sig.parameters.values())[0]
480
+ if (
481
+ firstparam.annotation is not sig.empty
482
+ and firstparam.annotation != "tuple[np.ndarray, np.ndarray]"
483
+ ):
484
+ raise ValueError(
485
+ "Global function must accept a (np.ndarray, np.ndarray) tuple"
486
+ )
487
+ # Check return type
488
+ if sig.return_annotation is not sig.empty:
489
+ ret_type = sig.return_annotation
490
+ if not dataclasses.is_dataclass(ret_type):
491
+ raise ValueError("Global function must return a dataclass")
492
+ self.global_func = func
493
+
494
+ def add(self, func: Callable, name: str) -> None:
495
+ """Add a column function to the table.
496
+
497
+ Args:
498
+ func: The function to compute the column values.
499
+ name: The name of the column.
500
+ """
501
+ assert self.global_func is None, "Cannot mix global and per-column functions"
502
+ assert isinstance(name, str) and name, "Column name must be a non-empty string"
503
+ assert isinstance(func, Callable), "Column function must be callable"
504
+ # Check function signature:
505
+ sig = inspect.signature(func)
506
+ if len(sig.parameters) < 1:
507
+ raise ValueError(
508
+ f"Column function '{name}' must accept at least one argument"
509
+ )
510
+ first_param = list(sig.parameters.values())[0]
511
+ if (
512
+ first_param.annotation is not sig.empty
513
+ and first_param.annotation != "np.ndarray"
514
+ ):
515
+ raise ValueError(f"Column function '{name}' must accept a np.ndarray")
516
+ # Check return type
517
+ if sig.return_annotation is not sig.empty and sig.return_annotation not in (
518
+ "float",
519
+ "int",
520
+ ):
521
+ raise ValueError(f"Column function '{name}' must return a float or int")
522
+ self.column_funcs.append((name, func))
523
+
524
+ def hide_columns(self, names: list[str]) -> TableResultBuilder:
525
+ """Mark multiple columns as hidden in the display.
526
+
527
+ Args:
528
+ names: List of column names to hide.
529
+
530
+ Returns:
531
+ Self for method chaining.
532
+ """
533
+ self._hidden_columns.update(names)
534
+ return self
535
+
536
+ @staticmethod
537
+ def __check_value(value) -> float | str:
538
+ """Check and convert a value to float or str.
539
+
540
+ Args:
541
+ value: The value to check.
542
+
543
+ Returns:
544
+ The value converted to float or str.
545
+
546
+ Raises:
547
+ ValueError: If the value is not convertible to float or str.
548
+ """
549
+ try:
550
+ value = float(value)
551
+ except ValueError as exc:
552
+ if not isinstance(value, str):
553
+ raise ValueError(f"Unexpected non-numeric value: {value!r}") from exc
554
+ return value
555
+
556
+ def __compute_row_from_column_funcs(self, data: np.ndarray) -> list:
557
+ """Compute a single row using the column functions.
558
+
559
+ Args:
560
+ data: The input data array.
561
+
562
+ Returns:
563
+ A list of computed values for the row.
564
+ """
565
+ row_data = []
566
+ for _name, func in self.column_funcs:
567
+ value = func(data)
568
+ value = self.__check_value(value)
569
+ row_data.append(value)
570
+ return row_data
571
+
572
+ def __compute_row_from_dataclass(self, result) -> tuple[list, list]:
573
+ """Compute a single row using the global function's dataclass result.
574
+
575
+ Args:
576
+ result: The dataclass instance returned by the global function.
577
+
578
+ Returns:
579
+ A tuple of (row_data, names).
580
+ """
581
+ row_data = []
582
+ names = []
583
+ if not dataclasses.is_dataclass(result):
584
+ raise ValueError("Global function must return a dataclass instance")
585
+ for field in dataclasses.fields(result):
586
+ value = getattr(result, field.name)
587
+ if isinstance(value, (int, float, np.floating, np.integer, enum.Enum, str)):
588
+ value = self.__check_value(value)
589
+ else:
590
+ value = None
591
+ row_data.append(value)
592
+ names.append(field.name)
593
+ return row_data, names
594
+
595
+ def compute(self, obj: SignalObj | ImageObj) -> TableResult:
596
+ """Extract data from the image or signal object and compute the table.
597
+
598
+ Args:
599
+ obj: The image or signal object to extract data from.
600
+
601
+ Returns:
602
+ A TableResult object containing the extracted data.
603
+ """
604
+ names = [name for name, _ in self.column_funcs]
605
+ roi_indices = list(obj.iterate_roi_indices())
606
+ if roi_indices[0] is not None:
607
+ roi_indices.insert(0, None)
608
+ rows = []
609
+ roi_idx = []
610
+ for i_roi in roi_indices:
611
+ data = obj.get_data(i_roi)
612
+ row_data = []
613
+ if self.column_funcs:
614
+ row_data = self.__compute_row_from_column_funcs(data)
615
+ elif self.global_func:
616
+ result = self.global_func(data)
617
+ row_data, names = self.__compute_row_from_dataclass(result)
618
+ rows.append(row_data)
619
+ roi_idx.append(NO_ROI if i_roi is None else int(i_roi))
620
+
621
+ # Remove columns with all None and/or NaN values
622
+ if rows and names:
623
+ valid_cols = []
624
+ for j, name in enumerate(names):
625
+ col_values = [row[j] for row in rows]
626
+ if any(
627
+ v is not None and not (isinstance(v, float) and np.isnan(v))
628
+ for v in col_values
629
+ ):
630
+ valid_cols.append(j)
631
+ if len(valid_cols) < len(names):
632
+ names = [names[j] for j in valid_cols]
633
+ rows = [[row[j] for j in valid_cols] for row in rows]
634
+
635
+ result = TableResult.from_rows(
636
+ title=self.title,
637
+ headers=names,
638
+ rows=rows,
639
+ roi_indices=roi_idx,
640
+ kind=self.kind,
641
+ )
642
+
643
+ # Apply display preferences
644
+ if self._hidden_columns:
645
+ hidden_prefs = {name: name not in self._hidden_columns for name in names}
646
+ result.set_display_preferences(hidden_prefs)
647
+
648
+ return result
649
+
650
+
651
+ # ===========================
652
+ # Table utility functions
653
+ # ===========================
654
+
655
+
656
+ def calc_table_from_data(
657
+ title: str,
658
+ data: np.ndarray,
659
+ labeledfuncs: Mapping[str, Callable[[np.ndarray], float]],
660
+ roi_masks: list[np.ndarray] | None = None,
661
+ kind: TableKind | str = TableKind.CUSTOM,
662
+ attrs: dict[str, object] | None = None,
663
+ ) -> TableResult:
664
+ """Run scalar metrics on a full array or per-ROI masks and return a TableResult.
665
+
666
+ Args:
667
+ title: Result title.
668
+ data: N-D array consumed by metric functions.
669
+ labeledfuncs: Mapping of {label: func}, where func(data_or_masked) -> float.
670
+ roi_masks: Optional list of boolean masks (same shape as data). If provided,
671
+ results are computed per mask; otherwise a single full-image row is returned.
672
+ kind: Type of table result (e.g., TableKind.PULSE_FEATURES).
673
+ attrs: Optional algorithmic context.
674
+
675
+ Returns:
676
+ TableResult with rows per ROI mask (or one row if `roi_masks` is None).
677
+ `roi_indices` will be the mask indices (0..M-1) or NO_ROI for the
678
+ single row.
679
+ """
680
+ names = list(labeledfuncs.keys())
681
+ funcs = list(labeledfuncs.values())
682
+
683
+ if roi_masks:
684
+ rows = []
685
+ roi_idx = []
686
+ for i, m in enumerate(roi_masks):
687
+ sub = data[m] if (isinstance(m, np.ndarray) and m.dtype == bool) else data
688
+ rows.append([float(f(sub)) for f in funcs])
689
+ roi_idx.append(i)
690
+ return TableResult(
691
+ title=title,
692
+ kind=kind,
693
+ headers=names,
694
+ data=rows,
695
+ roi_indices=roi_idx,
696
+ attrs={} if attrs is None else dict(attrs),
697
+ )
698
+
699
+ # No ROI: single row with NO_ROI sentinel
700
+ row = [float(f(data)) for f in funcs]
701
+ return TableResult(
702
+ title=title,
703
+ kind=kind,
704
+ headers=names,
705
+ data=[row],
706
+ roi_indices=[NO_ROI],
707
+ attrs={} if attrs is None else dict(attrs),
708
+ )
709
+
710
+
711
+ def concat_tables(title: str, items: Iterable[TableResult]) -> TableResult:
712
+ """Concatenate multiple TableResult objects with identical names.
713
+
714
+ Args:
715
+ title: Title for the concatenated result.
716
+ items: Iterable of TableResult objects to concatenate.
717
+
718
+ Returns:
719
+ TableResult with concatenated data and updated metadata.
720
+ """
721
+ items = list(items)
722
+ if not items:
723
+ return TableResult(title=title, headers=[], data=[])
724
+ first = items[0]
725
+ cols = list(first.headers)
726
+ kind = first.kind
727
+ for it in items[1:]:
728
+ if list(it.headers) != cols:
729
+ raise ValueError(
730
+ "All TableResult objects must share the same names to concatenate"
731
+ )
732
+ if it.kind != kind:
733
+ kind = TableKind.CUSTOM # Default to CUSTOM if kinds don't match
734
+ data = []
735
+ for it in items:
736
+ data.extend(it.data)
737
+ if any(it.roi_indices is not None for it in items):
738
+ roi = []
739
+ for it in items:
740
+ if it.roi_indices is not None:
741
+ roi.extend(it.roi_indices)
742
+ else:
743
+ roi.extend([NO_ROI] * len(it.data))
744
+ else:
745
+ roi = None
746
+ return TableResult(title=title, kind=kind, headers=cols, data=data, roi_indices=roi)
747
+
748
+
749
+ def filter_table_by_roi(res: TableResult, roi: int | None) -> TableResult:
750
+ """Filter rows by ROI index. If roi is None, keeps NO_ROI rows.
751
+
752
+ Args:
753
+ res: The TableResult to filter.
754
+ roi: The ROI index to filter by, or None to keep all.
755
+
756
+ Returns:
757
+ A filtered TableResult.
758
+ """
759
+ if res.roi_indices is None:
760
+ # No ROI info: either keep all or none depending on request
761
+ keep_all = roi in (None, NO_ROI)
762
+ data = res.data if keep_all else []
763
+ indices = None if keep_all else []
764
+ return TableResult(
765
+ title=res.title,
766
+ headers=list(res.headers),
767
+ data=data,
768
+ roi_indices=indices,
769
+ attrs=dict(res.attrs),
770
+ )
771
+ target = NO_ROI if roi is None else int(roi)
772
+ filtered_data = []
773
+ filtered_indices = []
774
+ for i, roi_idx in enumerate(res.roi_indices):
775
+ if roi_idx == target:
776
+ filtered_data.append(res.data[i])
777
+ filtered_indices.append(roi_idx)
778
+ return TableResult(
779
+ title=res.title,
780
+ headers=list(res.headers),
781
+ data=filtered_data,
782
+ roi_indices=filtered_indices,
783
+ attrs=dict(res.attrs),
784
+ )