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
sigima/client/utils.py ADDED
@@ -0,0 +1,90 @@
1
+ # Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
2
+
3
+ """
4
+ Sigima Client Utilities
5
+ -----------------------
6
+
7
+ Common utilities shared between client remote control and stub server modules.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib
13
+ from io import BytesIO
14
+ from xmlrpc.client import Binary
15
+
16
+ import guidata.dataset as gds
17
+ import numpy as np
18
+ from guidata.io import JSONReader, JSONWriter
19
+
20
+ # pylint: disable=duplicate-code
21
+
22
+
23
+ def array_to_rpcbinary(data: np.ndarray) -> Binary:
24
+ """Convert NumPy array to XML-RPC Binary object, with shape and dtype.
25
+
26
+ The array is converted to a binary string using NumPy's native binary
27
+ format.
28
+
29
+ Args:
30
+ data: NumPy array to convert
31
+
32
+ Returns:
33
+ XML-RPC Binary object
34
+ """
35
+ dbytes = BytesIO()
36
+ np.save(dbytes, data, allow_pickle=False)
37
+ return Binary(dbytes.getvalue())
38
+
39
+
40
+ def rpcbinary_to_array(binary: Binary) -> np.ndarray:
41
+ """Convert XML-RPC binary to NumPy array.
42
+
43
+ Args:
44
+ binary: XML-RPC Binary object
45
+
46
+ Returns:
47
+ NumPy array
48
+ """
49
+ dbytes = BytesIO(binary.data)
50
+ return np.load(dbytes, allow_pickle=False)
51
+
52
+
53
+ def dataset_to_rpcjson(param: gds.DataSet) -> list[str]:
54
+ """Convert guidata DataSet to XML-RPC compatible JSON data.
55
+
56
+ The JSON data is a list of three elements:
57
+
58
+ - The first element is the module name of the DataSet class
59
+ - The second element is the class name of the DataSet class
60
+ - The third element is the JSON data of the DataSet instance
61
+
62
+ Args:
63
+ param: guidata DataSet to convert
64
+
65
+ Returns:
66
+ XML-RPC compatible JSON data (3-element list)
67
+ """
68
+ writer = JSONWriter()
69
+ param.serialize(writer)
70
+ param_json = writer.get_json()
71
+ klass = param.__class__
72
+ return [klass.__module__, klass.__name__, param_json]
73
+
74
+
75
+ def rpcjson_to_dataset(param_data: list[str]) -> gds.DataSet:
76
+ """Convert XML-RPC compatible JSON data to guidata DataSet.
77
+
78
+ Args:
79
+ param_data: XML-RPC compatible JSON data (3-element list)
80
+
81
+ Returns:
82
+ guidata DataSet
83
+ """
84
+ param_module, param_clsname, param_json = param_data
85
+ mod = importlib.__import__(param_module, fromlist=[param_clsname])
86
+ klass = getattr(mod, param_clsname)
87
+ param: gds.DataSet = klass()
88
+ reader = JSONReader(param_json)
89
+ param.deserialize(reader)
90
+ return param
sigima/config.py ADDED
@@ -0,0 +1,444 @@
1
+ # Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
2
+
3
+ """
4
+ Configuration (:mod:`sigima.config`)
5
+ -------------------------------------
6
+
7
+ The :mod:`sigima.config` module provides a way to manage configuration options for the
8
+ `sigima` library, as well as to handle translations and data paths, and other
9
+ configuration-related tasks.
10
+
11
+ It allows users to set and retrieve options that affect the behavior of the library,
12
+ such as whether to keep results of computations or not. The options are handled as
13
+ in-memory objects with default values provided, and can be temporarily overridden using
14
+ a context manager.
15
+
16
+ Typical usage:
17
+
18
+ .. code-block:: python
19
+
20
+ from sigima.config import options
21
+
22
+ # Get an option
23
+ value = options.fft_shift_enabled.get(default=True)
24
+
25
+ # Set an option
26
+ options.fft_shift_enabled.set(False)
27
+
28
+ # Temporarily override an option
29
+ with options.fft_shift_enabled.context(True):
30
+ ...
31
+
32
+ The following table lists the available options:
33
+
34
+ .. options-table::
35
+
36
+ .. note::
37
+
38
+ The options are stored in an environment variable in JSON format, allowing for
39
+ synchronization with external configurations or other processes that may need to
40
+ read or modify the options. The environment variable name is defined by
41
+ :attr:`sigima.config.OptionsContainer.ENV_VAR`. This is especially useful for
42
+ applications such as DataLab (where the `sigima` library is used as a core
43
+ component) as computations may be run in separate processes.
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ import json
49
+ import os
50
+ from contextlib import contextmanager
51
+ from typing import Any, Generator
52
+
53
+ from guidata import configtools
54
+
55
+ # Translation and data path configuration
56
+ MOD_NAME = "sigima"
57
+ _ = configtools.get_translation(MOD_NAME)
58
+ DATAPATH = configtools.get_module_data_path(MOD_NAME, "data")
59
+
60
+
61
+ class OptionField:
62
+ """A configurable option field with get/set/context interface.
63
+
64
+ Args:
65
+ container: Options container instance to which this option belongs.
66
+ name: Name of the option (used for introspection or errors).
67
+ default: Default value of the option.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ container: OptionsContainer,
73
+ name: str,
74
+ default: Any,
75
+ description: str = "",
76
+ ) -> None:
77
+ self._container = container
78
+ self.name = name
79
+ self.check(default) # Validate the default value
80
+ self._value = default
81
+ self.description = description
82
+
83
+ def check(self, value: Any) -> None: # pylint: disable=unused-argument
84
+ """Check if the value is valid for this option.
85
+
86
+ Args:
87
+ value: The value to check.
88
+
89
+ Raises:
90
+ ValueError: If the value is not valid.
91
+ """
92
+ # This method can be overridden in subclasses for specific validation
93
+
94
+ def get(self, sync_env: bool = True) -> Any:
95
+ """Return the current value of the option.
96
+
97
+ Args:
98
+ sync_env: Whether to ensure the environment variable is synchronized
99
+ with the current value.
100
+
101
+ Returns:
102
+ The current value of the option.
103
+ """
104
+ if sync_env:
105
+ self._container.ensure_loaded_from_env()
106
+ return self._value
107
+
108
+ def set(self, value: Any, sync_env: bool = True) -> None:
109
+ """Set the value of the option.
110
+
111
+ Args:
112
+ value: The new value to assign.
113
+ sync_env: Whether to synchronize the environment variable.
114
+ """
115
+ self.check(value) # Validate the new value
116
+ self._value = value
117
+ if sync_env:
118
+ self._container.sync_env()
119
+
120
+ def context(self, temp_value: Any) -> Generator[None, None, None]:
121
+ """Temporarily override the option within a context.
122
+
123
+ Args:
124
+ temp_value: Temporary value to use within the context.
125
+
126
+ Yields:
127
+ None. Restores the original value upon exit.
128
+ """
129
+
130
+ @contextmanager
131
+ def _ctx():
132
+ old_value = self._value
133
+ self.set(temp_value)
134
+ try:
135
+ yield
136
+ finally:
137
+ self.set(old_value)
138
+
139
+ return _ctx()
140
+
141
+
142
+ class TypedOptionField(OptionField):
143
+ """A configurable option field with type checking.
144
+
145
+ Args:
146
+ container: Options container instance to which this option belongs.
147
+ name: Name of the option (used for introspection or errors).
148
+ default: Default value of the option.
149
+ expected_type: Expected type of the option value.
150
+ description: Description of the option.
151
+ """
152
+
153
+ def __init__(
154
+ self,
155
+ container: OptionsContainer,
156
+ name: str,
157
+ default: Any,
158
+ expected_type: type,
159
+ description: str = "",
160
+ ) -> None:
161
+ self.expected_type = expected_type
162
+ super().__init__(container, name, default, description)
163
+
164
+ def check(self, value: Any) -> None:
165
+ """Check if the value is of the expected type.
166
+
167
+ Args:
168
+ value: The value to check.
169
+
170
+ Raises:
171
+ ValueError: If the value is not of the expected type.
172
+ """
173
+ if not isinstance(value, self.expected_type):
174
+ raise ValueError(
175
+ f"Expected {self.expected_type.__name__}, got {type(value).__name__}"
176
+ )
177
+
178
+
179
+ class ImageIOOptionField(OptionField):
180
+ """A configurable option field for image I/O formats.
181
+
182
+ .. note::
183
+
184
+ This option is specifically for image I/O formats and expects a tuple of
185
+ tuples (or list of lists) of strings representing the formats,
186
+ similar to the following:
187
+
188
+ ... code-block:: python
189
+
190
+ imageio_formats = (
191
+ ("*.gel", "Opticks GEL"),
192
+ ("*.spe", "Princeton Instruments SPE"),
193
+ ("*.ndpi", "Hamamatsu Slide Scanner NDPI"),
194
+ ("*.rec", "PCO Camera REC"),
195
+ )
196
+
197
+ Args:
198
+ container: Options container instance to which this option belongs.
199
+ name: Name of the option (used for introspection or errors).
200
+ default: Default value of the option.
201
+ description: Description of the option.
202
+ """
203
+
204
+ def check(
205
+ self,
206
+ value: list[list[str, str]]
207
+ | list[tuple[str, str]]
208
+ | tuple[tuple[str, str]]
209
+ | tuple[list[str, str]],
210
+ ) -> None:
211
+ """Check if the value is a valid image I/O format.
212
+
213
+ Args:
214
+ value: The value to check.
215
+
216
+ Raises:
217
+ ValueError: If the value is not a valid image I/O format.
218
+ """
219
+ if not isinstance(value, (tuple, list)) or not all(
220
+ isinstance(item, (tuple, list)) and len(item) == 2 for item in value
221
+ ):
222
+ raise ValueError(
223
+ "Expected a tuple of tuples with two elements each "
224
+ "(format, description)"
225
+ )
226
+ for item in value:
227
+ if not isinstance(item[0], str) or not isinstance(item[1], str):
228
+ raise ValueError(
229
+ "Each item must be a tuple of (format, description) as strings"
230
+ )
231
+
232
+ def set(self, value: Any, sync_env: bool = True) -> None:
233
+ """Set the value of the option.
234
+
235
+ Args:
236
+ value: The new value to assign.
237
+ sync_env: Whether to synchronize the environment variable.
238
+ """
239
+ super().set(value, sync_env)
240
+ # pylint: disable=cyclic-import
241
+ # pylint: disable=import-outside-toplevel
242
+ from sigima.io.image import formats
243
+
244
+ # Generate image I/O format classes based on the new value
245
+ # This allows dynamic loading of formats based on the configuration
246
+ formats.generate_imageio_format_classes(value)
247
+
248
+
249
+ IMAGEIO_FORMATS = (
250
+ ("*.gel", "Opticks GEL"),
251
+ ("*.spe", "Princeton Instruments SPE"),
252
+ ("*.ndpi", "Hamamatsu Slide Scanner NDPI"),
253
+ ("*.rec", "PCO Camera REC"),
254
+ ) # Default image I/O formats
255
+
256
+
257
+ class OptionsContainer:
258
+ """Container for all configurable options in the `sigima` library.
259
+
260
+ Options are exposed as attributes with `.get()`, `.set()` and `.context()` methods.
261
+ """
262
+
263
+ #: Environment variable name for options in JSON format
264
+ # This is used to synchronize options with external configurations or with
265
+ # separate processes that may need to read or modify the options.
266
+ ENV_VAR = "SIGIMA_OPTIONS_JSON"
267
+
268
+ @classmethod
269
+ def set_env(cls, value: str) -> None:
270
+ """Set the environment variable with the given JSON string.
271
+
272
+ Args:
273
+ value: A JSON string representation of the options to set.
274
+ """
275
+ os.environ[cls.ENV_VAR] = value
276
+
277
+ @classmethod
278
+ def get_env(cls) -> str:
279
+ """Get the current value of the environment variable.
280
+
281
+ Returns:
282
+ The JSON string representation of the options from the environment variable.
283
+ """
284
+ return os.environ.get(cls.ENV_VAR, "{}")
285
+
286
+ def __init__(self) -> None:
287
+ self.fft_shift_enabled = TypedOptionField(
288
+ self,
289
+ "fft_shift_enabled",
290
+ default=True,
291
+ expected_type=bool,
292
+ description=_(
293
+ "If True, the FFT operations will apply a shift to the zero frequency "
294
+ "component to the center of the spectrum. This is useful for "
295
+ "visualizing frequency components in a more intuitive way."
296
+ ),
297
+ )
298
+ self.auto_normalize_kernel = TypedOptionField(
299
+ self,
300
+ "auto_normalize_kernel",
301
+ default=False,
302
+ expected_type=bool,
303
+ description=_(
304
+ "If True, convolution kernels will be automatically normalized to "
305
+ "sum to 1.0 before convolution. This ensures that the output signal "
306
+ "or image has the same overall magnitude as the input when using "
307
+ "smoothing kernels. Set to False to preserve the mathematical "
308
+ "properties of the original kernel."
309
+ ),
310
+ )
311
+ self.imageio_formats = ImageIOOptionField(
312
+ self,
313
+ "imageio_formats",
314
+ default=IMAGEIO_FORMATS,
315
+ description=_(
316
+ """List of supported image I/O formats. Each format is a tuple of
317
+ ``(file_extension, description)``.
318
+
319
+ The ``sigima`` library supports any image format that can be read by the ``imageio``
320
+ library, provided that the associated plugin(s) are installed (see `imageio
321
+ documentation <https://imageio.readthedocs.io/en/stable/formats/index.html>`_)
322
+ and that the output NumPy array data type and shape are supported by ``sigima``.
323
+
324
+ To add a new file format, you may use the ``imageio_formats`` option to specify
325
+ additional formats. Each entry should be a tuple of (file extension, description).
326
+ """
327
+ ),
328
+ )
329
+ # Add new options here
330
+
331
+ def describe_all(self) -> None:
332
+ """Print the name, value, and description of all options."""
333
+ for name in vars(self):
334
+ opt = getattr(self, name)
335
+ if isinstance(opt, OptionField):
336
+ print(f"{name} = {opt.get()} # {opt.description}")
337
+
338
+ def generate_rst_doc(self) -> str:
339
+ """Generate reStructuredText documentation for all options.
340
+
341
+ Returns:
342
+ A string containing the reStructuredText documentation.
343
+ """
344
+ doc = """.. list-table::
345
+ :header-rows: 1
346
+ :align: left
347
+
348
+ * - Name
349
+ - Default Value
350
+ - Description
351
+ """
352
+ for name in vars(self):
353
+ opt = getattr(self, name)
354
+ if isinstance(opt, OptionField):
355
+ # Process description to work within table cells
356
+ description = opt.description.strip()
357
+ # For table cells, we need to indent continuation lines properly
358
+ # and handle multi-line content correctly
359
+ description_lines = description.split("\n")
360
+ if len(description_lines) > 1:
361
+ # Multi-line descriptions need special handling in RST tables
362
+ processed_lines = [description_lines[0]] # First line
363
+ for line in description_lines[1:]:
364
+ if line.strip(): # Non-empty lines
365
+ processed_lines.append(" " + line.strip())
366
+ else: # Empty lines
367
+ processed_lines.append("")
368
+ description = "\n".join(processed_lines)
369
+
370
+ # Get the value and format it nicely
371
+ value = repr(opt.get(sync_env=False))
372
+ if len(value) > 200: # Truncate very long values
373
+ value = value[:197] + "..."
374
+
375
+ doc += f" * - ``{name}``\n"
376
+ doc += f" - ``{value}``\n"
377
+ doc += f" - {description}\n"
378
+ return doc
379
+
380
+ def ensure_loaded_from_env(self) -> None:
381
+ """Lazy-load from JSON env var on first access."""
382
+ value = self.get_env()
383
+ try:
384
+ values = json.loads(value)
385
+ self.from_dict(values)
386
+ except Exception as exc: # pylint: disable=broad-except
387
+ # If loading fails, we just log a warning and continue with defaults
388
+ print(f"[sigima] Warning: failed to load options from env: {exc}")
389
+
390
+ def to_env_json(self) -> str:
391
+ """Return the current options as a JSON string for environment variable.
392
+
393
+ Returns:
394
+ A JSON string representation of the current options.
395
+ """
396
+ return json.dumps(self.to_dict())
397
+
398
+ def sync_env(self) -> None:
399
+ """Update env var with current option values."""
400
+ self.set_env(self.to_env_json())
401
+
402
+ def to_dict(self) -> dict[str, Any]:
403
+ """Return the current option values as a dictionary.
404
+
405
+ Returns:
406
+ A dictionary with option names as keys and their current values.
407
+ """
408
+ return {
409
+ name: getattr(self, name).get(sync_env=False)
410
+ for name in vars(self)
411
+ if isinstance(getattr(self, name), OptionField)
412
+ }
413
+
414
+ def from_dict(self, values: dict[str, Any]) -> None:
415
+ """Set option values from a dictionary.
416
+
417
+ Args:
418
+ values: A dictionary with option names as keys and their new values.
419
+ """
420
+ for name, value in values.items():
421
+ if hasattr(self, name):
422
+ opt = getattr(self, name)
423
+ if isinstance(opt, OptionField):
424
+ opt.set(value, sync_env=False)
425
+ self.sync_env()
426
+
427
+
428
+ #: Global instance of the options container
429
+ options = OptionsContainer()
430
+
431
+ # Generate OPTIONS_RST at module load time after options is created
432
+ # This avoids circular import issues since everything is already loaded
433
+ OPTIONS_RST = options.generate_rst_doc()
434
+
435
+
436
+ def __getattr__(name: str):
437
+ """Handle lazy evaluation of module-level attributes.
438
+
439
+ This provides backward compatibility for any code that might access OPTIONS_RST.
440
+ """
441
+ if name == "OPTIONS_RST":
442
+ # Return the global variable if it exists, otherwise generate it
443
+ return globals().get("OPTIONS_RST", options.generate_rst_doc())
444
+ raise AttributeError(f"module '{__name__}' has no attribute '{name}'")