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,1626 @@
1
+ # Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
2
+
3
+ """
4
+ .. Pulse analysis (see parent package :mod:`sigima.tools.signal`)
5
+ """
6
+
7
+ # pylint: disable=invalid-name # Allows short reference names like x, y, ...
8
+
9
+ from __future__ import annotations
10
+
11
+ import abc
12
+ import warnings
13
+ from dataclasses import dataclass
14
+ from typing import Literal
15
+
16
+ import numpy as np
17
+ import scipy.ndimage
18
+ import scipy.optimize # type: ignore
19
+ import scipy.special
20
+
21
+ from sigima.enums import SignalShape
22
+ from sigima.tools.checks import check_1d_arrays
23
+ from sigima.tools.signal import features, filtering, peakdetection
24
+
25
+
26
+ class PulseFitModel(abc.ABC):
27
+ """Base class for 1D pulse fit models"""
28
+
29
+ @classmethod
30
+ @abc.abstractmethod
31
+ def func(cls, x, amp, sigma, x0, y0):
32
+ """Return fitting function"""
33
+
34
+ # pylint: disable=unused-argument
35
+ @classmethod
36
+ def get_amp_from_amplitude(cls, amplitude, sigma):
37
+ """Return amp from function amplitude and sigma"""
38
+ return amplitude
39
+
40
+ @classmethod
41
+ def amplitude(cls, amp, sigma):
42
+ """Return function amplitude"""
43
+ return cls.func(0, amp, sigma, 0, 0)
44
+
45
+ @classmethod
46
+ @abc.abstractmethod
47
+ def fwhm(cls, amp, sigma):
48
+ """Return function FWHM"""
49
+
50
+ @classmethod
51
+ def half_max_segment(cls, amp, sigma, x0, y0):
52
+ """Return segment coordinates for y=half-maximum intersection"""
53
+ hwhm = 0.5 * cls.fwhm(amp, sigma)
54
+ yhm = 0.5 * cls.amplitude(amp, sigma) + y0
55
+ return x0 - hwhm, yhm, x0 + hwhm, yhm
56
+
57
+
58
+ class GaussianModel(PulseFitModel):
59
+ """1-dimensional Gaussian fit model"""
60
+
61
+ @classmethod
62
+ def func(cls, x, amp, sigma, x0, y0):
63
+ """Return fitting function"""
64
+ return (
65
+ amp / (sigma * np.sqrt(2 * np.pi)) * np.exp(-0.5 * ((x - x0) / sigma) ** 2)
66
+ + y0
67
+ )
68
+
69
+ @classmethod
70
+ def get_amp_from_amplitude(cls, amplitude, sigma):
71
+ """Return amp from function amplitude and sigma"""
72
+ return amplitude * (sigma * np.sqrt(2 * np.pi))
73
+
74
+ @classmethod
75
+ def amplitude(cls, amp, sigma):
76
+ """Return function amplitude"""
77
+ return amp / (sigma * np.sqrt(2 * np.pi))
78
+
79
+ @classmethod
80
+ def fwhm(cls, amp, sigma):
81
+ """Return function FWHM"""
82
+ return 2 * sigma * np.sqrt(2 * np.log(2))
83
+
84
+
85
+ class LorentzianModel(PulseFitModel):
86
+ """1-dimensional Lorentzian fit model"""
87
+
88
+ @classmethod
89
+ def func(cls, x, amp, sigma, x0, y0):
90
+ """Return fitting function"""
91
+ return (amp / (sigma * np.pi)) / (1 + ((x - x0) / sigma) ** 2) + y0
92
+
93
+ @classmethod
94
+ def get_amp_from_amplitude(cls, amplitude, sigma):
95
+ """Return amp from function amplitude and sigma"""
96
+ return amplitude * (sigma * np.pi)
97
+
98
+ @classmethod
99
+ def amplitude(cls, amp, sigma):
100
+ """Return function amplitude"""
101
+ return amp / (sigma * np.pi)
102
+
103
+ @classmethod
104
+ def fwhm(cls, amp, sigma):
105
+ """Return function FWHM"""
106
+ return 2 * sigma
107
+
108
+
109
+ class VoigtModel(PulseFitModel):
110
+ """1-dimensional Voigt fit model"""
111
+
112
+ @classmethod
113
+ def func(cls, x, amp, sigma, x0, y0):
114
+ """Return fitting function"""
115
+ # pylint: disable=no-member
116
+ z = (x - x0 + 1j * sigma) / (sigma * np.sqrt(2.0))
117
+ return y0 + amp * scipy.special.wofz(z).real / (sigma * np.sqrt(2 * np.pi))
118
+
119
+ @classmethod
120
+ def fwhm(cls, amp, sigma):
121
+ """Return function FWHM"""
122
+ wg = GaussianModel.fwhm(amp, sigma)
123
+ wl = LorentzianModel.fwhm(amp, sigma)
124
+ return 0.5346 * wl + np.sqrt(0.2166 * wl**2 + wg**2)
125
+
126
+
127
+ # MARK: Pulse analysis -----------------------------------------------------------------
128
+
129
+
130
+ class PulseAnalysisError(Exception):
131
+ """Base exception for pulse analysis errors."""
132
+
133
+
134
+ class InvalidSignalError(PulseAnalysisError):
135
+ """Raised when signal data is invalid or insufficient."""
136
+
137
+
138
+ class PolarityDetectionError(PulseAnalysisError):
139
+ """Raised when polarity cannot be determined."""
140
+
141
+
142
+ def heuristically_recognize_shape(
143
+ x: np.ndarray,
144
+ y: np.ndarray,
145
+ start_range: tuple[float, float] | None = None,
146
+ end_range: tuple[float, float] | None = None,
147
+ step_threshold_ratio: float = 0.5,
148
+ ) -> SignalShape:
149
+ """
150
+ Heuristically determine the shape of the signal: 'step' or 'square'.
151
+
152
+ Args:
153
+ x: 1D array of x values (e.g., time or position).
154
+ y: 1D array of y values corresponding to x.
155
+ start_range: Range for the start baseline.
156
+ end_range: Range for the end baseline.
157
+ step_threshold_ratio: Threshold ratio to distinguish step from square pulse.
158
+ If step amplitude > threshold_ratio * total_amplitude, classify as step.
159
+
160
+ Returns:
161
+ Signal shape, either SignalShape.STEP or SignalShape.SQUARE.
162
+
163
+ Raises:
164
+ InvalidSignalError: If signal data is invalid.
165
+ """
166
+ if x.size != y.size:
167
+ raise InvalidSignalError("x and y arrays must have the same length")
168
+ if x.size < 3:
169
+ raise InvalidSignalError("Signal must have at least 3 data points")
170
+
171
+ # if ranges are None, use the first and last points
172
+ if start_range is None:
173
+ start_range = (x[0], x[0])
174
+ if end_range is None:
175
+ end_range = (x[-1], x[-1])
176
+
177
+ step_amplitude = get_amplitude(
178
+ x, y, start_range, end_range, signal_shape=SignalShape.STEP
179
+ )
180
+ total_amplitude = np.max(y) - np.min(y)
181
+
182
+ if total_amplitude == 0:
183
+ raise InvalidSignalError("Signal has zero amplitude")
184
+
185
+ if np.abs(step_amplitude) > np.abs(step_threshold_ratio * total_amplitude):
186
+ signal_shape = SignalShape.STEP
187
+ else:
188
+ signal_shape = SignalShape.SQUARE
189
+
190
+ return signal_shape
191
+
192
+
193
+ def _detect_square_polarity(
194
+ x: np.ndarray,
195
+ y: np.ndarray,
196
+ start_range: tuple[float, float] | None = None,
197
+ end_range: tuple[float, float] | None = None,
198
+ plateau_range: tuple[float, float] | None = None,
199
+ y_start: float | None = None,
200
+ y_end: float | None = None,
201
+ ) -> int:
202
+ """Detect the polarity of a square pulse in a signal based on baseline regions.
203
+
204
+ Args:
205
+ x: The array of x-values (typically time or sample indices).
206
+ y: The array of y-values (signal amplitudes) corresponding to `x`.
207
+ start_range: The x range for the initial baseline (before the pulse).
208
+ end_range: The x range for the final baseline (after the pulse).
209
+ plateau_range: The x range for the plateau region, if applicable.
210
+ If None, uses the reduced y-values.
211
+ y_start: The y value of the baseline at the start of the pulse.
212
+ y_end: The y value of the baseline at the end of the pulse.
213
+
214
+ Returns:
215
+ 1 if the pulse is positive, -1 if negative, or 0 if indeterminate.
216
+ """
217
+ if start_range is None:
218
+ start_range = (x[0], x[0])
219
+ if end_range is None:
220
+ end_range = (x[-1], x[-1])
221
+
222
+ # reduce x and y outside the base level
223
+ y_red = y[np.logical_and(x >= start_range[1], x <= end_range[0])]
224
+ if len(y_red) == 0:
225
+ return 0
226
+
227
+ if plateau_range is None:
228
+ max_y = np.max(y_red)
229
+ min_y = np.min(y_red)
230
+ else:
231
+ max_y = min_y = get_range_mean_y(x, y, plateau_range)
232
+ positive_score = negative_score = 0
233
+
234
+ y_start = get_range_mean_y(x, y, start_range) if y_start is None else y_start
235
+ y_end = get_range_mean_y(x, y, end_range) if y_end is None else y_end
236
+
237
+ if max_y > y_start and max_y > y_end:
238
+ positive_score = (max_y - y_start) ** 2 + (max_y - y_end) ** 2
239
+ if min_y < y_start and min_y < y_end:
240
+ negative_score = (min_y - y_start) ** 2 + (min_y - y_end) ** 2
241
+ return int(np.sign(positive_score - negative_score))
242
+
243
+
244
+ def detect_polarity(
245
+ x: np.ndarray,
246
+ y: np.ndarray,
247
+ start_range: tuple[float, float] | None = None,
248
+ end_range: tuple[float, float] | None = None,
249
+ plateau_range: tuple[float, float] | None = None,
250
+ signal_shape: SignalShape | None = None,
251
+ fraction: float = 0.05,
252
+ ) -> int:
253
+ """Get step curve polarity.
254
+
255
+ Args:
256
+ x: Array of x-values (abscisse).
257
+ y: Array of y-values (ordinate).
258
+ start_range: Range for the start baseline.
259
+ end_range: Range for the end baseline.
260
+ plateau_range: Range for the plateau.
261
+ signal_shape: Shape of the signal.
262
+ fraction: Fraction of the x-range to use for baseline and plateau calculations.
263
+
264
+ Returns:
265
+ Polarity of the step (1 for positive, -1 for negative).
266
+
267
+ Raises:
268
+ PolarityDetectionError: If polarity cannot be determined.
269
+ ValueError: If signal shape is unknown.
270
+ """
271
+ if start_range is None:
272
+ start_range = get_start_range(x, fraction)
273
+ if end_range is None:
274
+ end_range = get_end_range(x, fraction)
275
+
276
+ if signal_shape is None:
277
+ signal_shape = heuristically_recognize_shape(x, y, start_range, end_range)
278
+
279
+ y_start = get_range_mean_y(x, y, start_range)
280
+ y_end = get_range_mean_y(x, y, end_range)
281
+
282
+ if signal_shape == SignalShape.STEP:
283
+ if y_start < y_end:
284
+ return 1
285
+ if y_start > y_end:
286
+ return -1
287
+
288
+ raise PolarityDetectionError(
289
+ "Polarity could not be determined. Check signal data and baseline ranges."
290
+ )
291
+ if signal_shape == SignalShape.SQUARE:
292
+ # Try square polarity detection first
293
+ try:
294
+ return _detect_square_polarity(
295
+ x,
296
+ y,
297
+ start_range,
298
+ end_range,
299
+ plateau_range,
300
+ y_start,
301
+ y_end,
302
+ )
303
+ except (PolarityDetectionError, IndexError, ValueError) as exc:
304
+ # If square detection fails, try Gaussian-like approach
305
+ # This handles Gaussian signals that are misclassified as SQUARE
306
+ baseline_mean = (y_start + y_end) / 2
307
+ max_y = np.max(y)
308
+ min_y = np.min(y)
309
+ peak_value = (
310
+ max_y if max_y - baseline_mean > baseline_mean - min_y else min_y
311
+ )
312
+
313
+ if peak_value > baseline_mean:
314
+ return 1
315
+ if peak_value < baseline_mean:
316
+ return -1
317
+ raise PolarityDetectionError(
318
+ "Polarity could not be determined. Check signal data and "
319
+ "baseline ranges."
320
+ ) from exc
321
+
322
+ raise ValueError(
323
+ f"\nUnknown signal shape '{signal_shape}'. Use 'step' or 'square'."
324
+ )
325
+
326
+
327
+ def get_start_range(x: np.ndarray, fraction: float = 0.05) -> tuple[float, float]:
328
+ """Get start range based on fraction of x-range.
329
+
330
+ Args:
331
+ x: 1D array of x values.
332
+ fraction: Fraction of the x-range to use for the start range.
333
+
334
+ Returns:
335
+ Tuple representing the start range (min, max).
336
+ """
337
+ x_fraction = fraction * (x[-1] - x[0])
338
+ return (x[0], x[0] + x_fraction)
339
+
340
+
341
+ def get_end_range(x: np.ndarray, fraction: float = 0.05) -> tuple[float, float]:
342
+ """Get end range based on fraction of x-range.
343
+
344
+ Args:
345
+ x: 1D array of x values.
346
+ fraction: Fraction of the x-range to use for the end range.
347
+
348
+ Returns:
349
+ Tuple representing the end range (min, max).
350
+ """
351
+ x_fraction = fraction * (x[-1] - x[0])
352
+ return (x[-1] - x_fraction, x[-1])
353
+
354
+
355
+ def get_plateau_range(
356
+ x: np.ndarray,
357
+ y: np.ndarray,
358
+ polarity: int,
359
+ fraction: float = 0.05,
360
+ start_range: tuple[float, float] | None = None,
361
+ end_range: tuple[float, float] | None = None,
362
+ ) -> tuple[float, float]:
363
+ """Get plateau range around the max y-value based on fraction of x-range.
364
+
365
+ The plateau is identified as the longest continuous region with values >= 90% of
366
+ the maximum, constrained to be after the start baseline and before the end baseline.
367
+ This ensures the plateau is detected in the correct temporal region of the signal,
368
+ avoiding isolated spikes.
369
+
370
+ Args:
371
+ x: 1D array of x values.
372
+ y: 1D array of y values.
373
+ polarity: Polarity of the signal (1 for positive, -1 for negative).
374
+ fraction: Fraction of the x-range to use for the plateau range.
375
+ start_range: Start baseline range (optional, for constraining search).
376
+ end_range: End baseline range (optional, for constraining search).
377
+
378
+ Returns:
379
+ Tuple representing the plateau range (min, max).
380
+ """
381
+ # Get baseline ranges if not provided
382
+ if start_range is None:
383
+ start_range = get_start_range(x, fraction)
384
+ if end_range is None:
385
+ end_range = get_end_range(x, fraction)
386
+
387
+ # Constrain search to region between end of start baseline and start of end baseline
388
+ # This avoids the circular dependency with find_crossing_at_ratio
389
+ mask = (x > start_range[1]) & (x < end_range[0])
390
+
391
+ # Apply polarity correction
392
+ y_polarity_corrected = y if polarity == 1 else np.max(y) - y
393
+
394
+ # Find points >= 90% of maximum within the constrained region
395
+ # (lower threshold for plateau)
396
+ y_masked = y_polarity_corrected[mask]
397
+ if len(y_masked) == 0:
398
+ # Fallback: use full signal if constrained region is empty
399
+ y_masked = y_polarity_corrected
400
+ mask = np.ones_like(x, dtype=bool)
401
+
402
+ # Use 90% threshold to capture the full plateau, not just the peak
403
+ threshold = 0.9 * np.max(y_masked)
404
+ above_threshold = y_masked >= threshold
405
+
406
+ # Find the longest continuous region above threshold
407
+ # This identifies the plateau, not isolated spikes
408
+ changes = np.diff(np.concatenate(([False], above_threshold, [False])).astype(int))
409
+ start_indices = np.where(changes == 1)[0]
410
+ end_indices = np.where(changes == -1)[0]
411
+
412
+ if len(start_indices) == 0:
413
+ # Fallback: if no regions found, use the maximum point
414
+ max_idx = np.argmax(y_masked)
415
+ x_fraction = fraction * (x[-1] - x[0])
416
+ x_masked = x[mask]
417
+ x_center = x_masked[max_idx]
418
+ return (x_center - 0.5 * x_fraction, x_center + 0.5 * x_fraction)
419
+
420
+ # Find the longest continuous region
421
+ region_lengths = end_indices - start_indices
422
+ longest_region_idx = np.argmax(region_lengths)
423
+ plateau_start_idx = start_indices[longest_region_idx]
424
+ plateau_end_idx = end_indices[longest_region_idx] - 1 # -1 because end is exclusive
425
+
426
+ x_masked = x[mask]
427
+ return (x_masked[plateau_start_idx], x_masked[plateau_end_idx])
428
+
429
+
430
+ def get_range_mean_y(
431
+ x: np.ndarray,
432
+ y: np.ndarray,
433
+ value_range: tuple[float, float],
434
+ ) -> float:
435
+ """Get mean y-value in a given x-range.
436
+
437
+ Args:
438
+ x: 1D array of x values.
439
+ y: 1D array of y values.
440
+ value_range: Tuple representing the x-range (min, max).
441
+
442
+ Returns:
443
+ Mean y-value in the specified x-range, or NaN if no points in range.
444
+ """
445
+ y_range = y[np.logical_and(x >= value_range[0], x <= value_range[1])]
446
+ if len(y_range) == 0:
447
+ return np.nan
448
+ return float(np.mean(y_range))
449
+
450
+
451
+ @check_1d_arrays(x_sorted=True)
452
+ def get_amplitude(
453
+ x: np.ndarray,
454
+ y: np.ndarray,
455
+ start_range: tuple[float, float] | None = None,
456
+ end_range: tuple[float, float] | None = None,
457
+ plateau_range: tuple[float, float] | None = None,
458
+ signal_shape: SignalShape | str | None = None,
459
+ fraction: float = 0.05,
460
+ ) -> float:
461
+ """Get curve amplitude.
462
+
463
+ Args:
464
+ x: 1D array of x values.
465
+ y: 1D array of y values.
466
+ start_range: Range for the start baseline.
467
+ end_range: Range for the end baseline.
468
+ plateau_range: Range for the plateau.
469
+ signal_shape: Shape of the signal.
470
+ fraction: Fraction of the x-range to use for baseline and plateau calculations
471
+ if start, end, or plateau are None.
472
+
473
+ Returns:
474
+ Amplitude of the step.
475
+ """
476
+ if signal_shape is None:
477
+ signal_shape = heuristically_recognize_shape(x, y, start_range, end_range)
478
+
479
+ if start_range is None:
480
+ start_range = get_start_range(x, fraction)
481
+ if end_range is None:
482
+ end_range = get_end_range(x, fraction)
483
+
484
+ if signal_shape == SignalShape.STEP:
485
+ min_level = get_range_mean_y(x, y, start_range)
486
+ max_level = get_range_mean_y(x, y, end_range)
487
+ elif signal_shape == SignalShape.SQUARE:
488
+ try:
489
+ polarity = detect_polarity(
490
+ x, y, start_range, end_range, signal_shape=signal_shape
491
+ )
492
+ except PolarityDetectionError:
493
+ # If polarity cannot be determined, use total amplitude
494
+ return np.max(y) - np.min(y)
495
+
496
+ if plateau_range is None:
497
+ plateau_range = get_plateau_range(
498
+ x, y, polarity, fraction, start_range, end_range
499
+ )
500
+
501
+ # reverse y if polarity is negative
502
+ y_positive = y * polarity
503
+ # compute base level
504
+ min_level = get_range_mean_y(x, y_positive, start_range)
505
+ max_level = get_range_mean_y(x, y_positive, plateau_range)
506
+ else:
507
+ raise ValueError("Unknown signal type. Use 'step' or 'square'.")
508
+
509
+ return np.abs(min_level - max_level)
510
+
511
+
512
+ @check_1d_arrays(x_sorted=True)
513
+ def find_crossing_at_ratio(
514
+ x: np.ndarray,
515
+ y: np.ndarray,
516
+ ratio: float = 0.1,
517
+ start_range: tuple[float, float] | None = None,
518
+ end_range: tuple[float, float] | None = None,
519
+ signal_shape: SignalShape | str | None = None,
520
+ fraction: float = 0.05,
521
+ warn_multiple_crossings: bool = False,
522
+ ) -> float | None:
523
+ """Find the x-value at which the signal crosses a specified fractional amplitude.
524
+
525
+ Calculates the x-value at which a normalized step signal crosses a specified
526
+ fractional amplitude.
527
+
528
+ This function normalizes the input signal `y` relative to the baseline level defined
529
+ by `start` and the amplitude between `start` and `end`. It accounts for the
530
+ polarity of the step (rising or falling) and then finds the x-position where the
531
+ normalized signal crosses the specified `ratio` fraction of the step height.
532
+
533
+ Args:
534
+ x: 1D array of x values (e.g., time).
535
+ y: 1D array of y values corresponding to `x`.
536
+ ratio: The fractional amplitude (between 0 and 1) at which to find the
537
+ crossing time. For example, 0.5 corresponds to the half-maximum crossing.
538
+ start_range: Tuple defining the start baseline region (initial plateau).
539
+ end_range: Tuple defining the end baseline region (final plateau).
540
+ signal_shape: Shape of the signal. If None, it will be heuristically
541
+ determined.
542
+ fraction: Fraction of the x-range to use for baseline calculations if
543
+ start_range or end_range are None.
544
+ warn_multiple_crossings: If True, a warning is issued when multiple crossings
545
+ are found.
546
+
547
+ Returns:
548
+ The x-value where the normalized signal crosses the specified fractional
549
+ amplitude.
550
+
551
+ Raises:
552
+ ValueError: If `ratio` is not between 0 and 1.
553
+ InvalidSignalError: If the signal is invalid or if polarity cannot be
554
+ determined.
555
+ """
556
+ # pylint: disable=too-many-return-statements
557
+ if not 0 <= ratio <= 1:
558
+ raise ValueError("ratio must be between 0 and 1")
559
+ if signal_shape is None:
560
+ signal_shape = heuristically_recognize_shape(x, y, start_range, end_range)
561
+ try:
562
+ polarity = detect_polarity(
563
+ x,
564
+ y,
565
+ start_range,
566
+ end_range,
567
+ signal_shape=signal_shape,
568
+ )
569
+ except PolarityDetectionError as exc:
570
+ raise InvalidSignalError(f"Cannot determine crossing time: {exc}") from exc
571
+ amplitude = get_amplitude(
572
+ x, y, start_range, end_range, signal_shape=signal_shape, fraction=fraction
573
+ )
574
+ y_positive = y * polarity
575
+ if start_range is None:
576
+ start_range = get_start_range(x, fraction)
577
+ if end_range is None:
578
+ end_range = get_end_range(x, fraction)
579
+ y_start = get_range_mean_y(x, y_positive, start_range)
580
+ if amplitude == 0.0:
581
+ return None
582
+ y_norm = (y_positive - y_start) / amplitude
583
+
584
+ # Constrain search to the rise/fall edge region (between baselines)
585
+ # This prevents finding spurious crossings in the baseline regions
586
+ mask = (x > start_range[1]) & (x < end_range[0])
587
+ x_search = x[mask]
588
+ y_norm_search = y_norm[mask]
589
+
590
+ if len(x_search) == 0:
591
+ return None
592
+
593
+ # Special handling for low ratios (0% to 10%):
594
+ # For these, we need to avoid finding crossings in the baseline noise.
595
+ # Strategy: Find the 10% crossing first, then search backwards to find
596
+ # the requested crossing point near the actual rise edge.
597
+ if ratio < 0.1:
598
+ try:
599
+ # First find the 10% crossing point as a reference
600
+ roots_10pct = features.find_x_values_at_y(x_search, y_norm_search, 0.1)
601
+ if len(roots_10pct) > 0:
602
+ x_10pct = roots_10pct[0]
603
+ # Now search for the requested ratio only in the region
604
+ # leading up to the 10% crossing
605
+ mask_near_edge = x_search <= x_10pct
606
+ x_near_edge = x_search[mask_near_edge]
607
+ y_norm_near_edge = y_norm_search[mask_near_edge]
608
+ roots = features.find_x_values_at_y(
609
+ x_near_edge, y_norm_near_edge, ratio
610
+ )
611
+ # Return the crossing closest to the 10% point
612
+ if len(roots) > 0:
613
+ return roots[-1] # Last crossing before 10% point
614
+ except ValueError:
615
+ pass
616
+ # Fallback to regular search if 10% crossing not found
617
+ try:
618
+ roots = features.find_x_values_at_y(x_search, y_norm_search, ratio)
619
+ except ValueError:
620
+ return None
621
+ else:
622
+ # For higher ratios, regular search works fine
623
+ try:
624
+ roots = features.find_x_values_at_y(x_search, y_norm_search, ratio)
625
+ except ValueError:
626
+ return None
627
+
628
+ if len(roots) == 0:
629
+ return None
630
+ if len(roots) > 1 and warn_multiple_crossings:
631
+ warnings.warn(
632
+ f"Multiple crossing points found at ratio {ratio}. "
633
+ f"Returning first at x={roots[0]:.6f}"
634
+ )
635
+ return roots[0]
636
+
637
+
638
+ def _find_gaussian_crossing_times(
639
+ x: np.ndarray,
640
+ y: np.ndarray,
641
+ start_ratio: float,
642
+ stop_ratio: float,
643
+ start_range: tuple[float, float],
644
+ end_range: tuple[float, float],
645
+ ) -> tuple[float, float] | None:
646
+ """Find crossing times for Gaussian signals with proper handling of multiple
647
+ crossings.
648
+
649
+ For Gaussian signals, we want:
650
+ - Left side crossing at start_ratio
651
+ - Right side crossing at stop_ratio
652
+
653
+ This gives a meaningful "rise time" across the Gaussian peak.
654
+
655
+ Returns:
656
+ Tuple of (start_time, stop_time) or None if calculation fails.
657
+ """
658
+ try:
659
+ # Get signal properties
660
+ signal_shape = heuristically_recognize_shape(x, y, start_range, end_range)
661
+ polarity = detect_polarity(
662
+ x, y, start_range, end_range, signal_shape=signal_shape
663
+ )
664
+ amplitude = get_amplitude(
665
+ x, y, start_range, end_range, signal_shape=signal_shape
666
+ )
667
+
668
+ y_positive = y * polarity
669
+ y_start = get_range_mean_y(x, y_positive, start_range)
670
+
671
+ if amplitude == 0.0:
672
+ return None
673
+
674
+ y_norm = (y_positive - y_start) / amplitude
675
+
676
+ # Find all crossing points
677
+ start_roots = features.find_x_values_at_y(x, y_norm, start_ratio)
678
+ stop_roots = features.find_x_values_at_y(x, y_norm, stop_ratio)
679
+
680
+ # For true Gaussian signals, we expect exactly 2 crossings per ratio
681
+ # (left and right sides). However, for truncated signals (e.g., in
682
+ # extract_pulse_features), we might only see 1 crossing (left side only).
683
+ if len(start_roots) == 1 and len(stop_roots) == 1:
684
+ # Truncated Gaussian (left side only) - use these crossings directly
685
+ start_time = start_roots[0]
686
+ stop_time = stop_roots[0]
687
+ return (start_time, stop_time)
688
+ if len(start_roots) != 2 or len(stop_roots) != 2:
689
+ # Not a clean Gaussian-style signal
690
+ return None
691
+
692
+ # Additional check: Gaussian signals should be roughly symmetric
693
+ # Square signals often have asymmetric crossing patterns
694
+ center_x = (x[0] + x[-1]) / 2
695
+ start_center = (start_roots[0] + start_roots[1]) / 2
696
+ stop_center = (stop_roots[0] + stop_roots[1]) / 2
697
+
698
+ # If crossings are very asymmetric or far from signal center,
699
+ # it's likely a square signal, not Gaussian
700
+ max_center_offset = (x[-1] - x[0]) * 0.05 # 5% of signal range (stricter)
701
+ if (
702
+ abs(start_center - center_x) > max_center_offset
703
+ or abs(stop_center - center_x) > max_center_offset
704
+ ):
705
+ # Too asymmetric for a Gaussian
706
+ return None
707
+
708
+ # For Gaussian signals, calculate rise/fall time on ONE side only
709
+ # start_roots[0] = left side, start_roots[1] = right side
710
+ # stop_roots[0] = left side, stop_roots[1] = right side
711
+ if stop_ratio > start_ratio:
712
+ # Rise time: use left side only (start_ratio to stop_ratio)
713
+ start_time = start_roots[0] # Left side at start_ratio
714
+ stop_time = stop_roots[0] # Left side at stop_ratio
715
+ else:
716
+ # Fall time: use right side only (start_ratio to stop_ratio)
717
+ start_time = start_roots[1] # Right side at start_ratio
718
+ stop_time = stop_roots[1] # Right side at stop_ratio
719
+
720
+ return (start_time, stop_time)
721
+
722
+ except (ValueError, PolarityDetectionError, InvalidSignalError):
723
+ return None
724
+
725
+
726
+ def _get_rise_time_traditional(
727
+ x: np.ndarray,
728
+ y: np.ndarray,
729
+ start_range: tuple[float, float],
730
+ end_range: tuple[float, float],
731
+ start_ratio: float,
732
+ stop_ratio: float,
733
+ ) -> float | None:
734
+ """Internal function for traditional ratio-based rise time calculation.
735
+
736
+ This avoids recursion by providing the core traditional implementation.
737
+ For Gaussian signals, it uses special multi-crossing logic.
738
+ """
739
+ # Check if this might be a Gaussian signal by detecting signal shape
740
+ # Only try Gaussian method for signals that have clean symmetric crossings
741
+ try:
742
+ gaussian_result = _find_gaussian_crossing_times(
743
+ x, y, start_ratio, stop_ratio, start_range, end_range
744
+ )
745
+ if gaussian_result is not None:
746
+ start_time, stop_time = gaussian_result
747
+ return abs(stop_time - start_time)
748
+ except (InvalidSignalError, PolarityDetectionError):
749
+ pass # Fall back to traditional method
750
+
751
+ # Traditional method for step/square signals
752
+ # Find crossing times for both ratios
753
+ start_time = find_crossing_at_ratio(x, y, start_ratio, start_range, end_range)
754
+ stop_time = find_crossing_at_ratio(x, y, stop_ratio, start_range, end_range)
755
+
756
+ if start_time is None or stop_time is None:
757
+ return None
758
+
759
+ # Validate that start_time and stop_time are in correct order
760
+ if (stop_ratio > start_ratio and start_time >= stop_time) or (
761
+ stop_ratio < start_ratio and stop_time >= start_time
762
+ ):
763
+ return None
764
+
765
+ return abs(stop_time - start_time)
766
+
767
+
768
+ def get_rise_time_estimated(
769
+ x: np.ndarray,
770
+ y: np.ndarray,
771
+ start_range: tuple[float, float] | None = None,
772
+ end_range: tuple[float, float] | None = None,
773
+ start_ratio: float = 0.1,
774
+ stop_ratio: float = 0.9,
775
+ ) -> float | None:
776
+ """Calculates rise time using heuristic foot detection and 50% crossing estimation.
777
+
778
+ This method uses a more robust approach:
779
+ 1. Find the true start of the systematic rise (foot end time)
780
+ 2. Find the 50% amplitude crossing
781
+ 3. Estimate the full rise duration from these two points
782
+ 4. Calculate the requested ratio-based rise time from the estimated parameters
783
+
784
+ Args:
785
+ x: 1D array of x values (e.g., time).
786
+ y: 1D array of y values corresponding to `x`.
787
+ start_range: Tuple defining the start plateau region (before the rise).
788
+ end_range: Tuple defining the end plateau region (after the rise).
789
+ start_ratio: Fraction of the step height at which the rise starts.
790
+ stop_ratio: Fraction of the step height at which the rise ends.
791
+
792
+ Returns:
793
+ The estimated rise time between the specified ratios.
794
+ """
795
+ if start_range is None:
796
+ start_range = get_start_range(x)
797
+ if end_range is None:
798
+ end_range = get_end_range(x)
799
+
800
+ # Step 1: Find the true start of the rise (foot end)
801
+ try:
802
+ foot_end_time = heuristically_find_rise_start_time(x, y, start_range)
803
+ except InvalidSignalError:
804
+ foot_end_time = None
805
+ if foot_end_time is None:
806
+ # Fallback to traditional method if heuristic fails
807
+ return _get_rise_time_traditional(
808
+ x, y, start_range, end_range, start_ratio, stop_ratio
809
+ )
810
+
811
+ # Step 2: Find the 50% crossing point
812
+ t_50_percent = find_crossing_at_ratio(x, y, 0.5, start_range, end_range)
813
+ if t_50_percent is None:
814
+ # Fallback to traditional method if 50% crossing not found
815
+ return _get_rise_time_traditional(
816
+ x, y, start_range, end_range, start_ratio, stop_ratio
817
+ )
818
+
819
+ # Step 3: Estimate the full rise duration
820
+ # If we assume linear rise: t_50% = t_start + 0.5 * total_rise_time
821
+ # Therefore: total_rise_time = 2 * (t_50% - t_start)
822
+ estimated_total_rise_time = 2.0 * (t_50_percent - foot_end_time)
823
+
824
+ # Validate the estimation makes sense
825
+ if estimated_total_rise_time <= 0:
826
+ warnings.warn(
827
+ f"Invalid rise time estimation: foot_end ({foot_end_time:.3f}) >= "
828
+ f"50% crossing ({t_50_percent:.3f}). Using fallback method."
829
+ )
830
+ return _get_rise_time_traditional(
831
+ x, y, start_range, end_range, start_ratio, stop_ratio
832
+ )
833
+
834
+ # Step 4: Calculate ratio-based times from the estimated parameters
835
+ estimated_start_time = foot_end_time + start_ratio * estimated_total_rise_time
836
+ estimated_stop_time = foot_end_time + stop_ratio * estimated_total_rise_time
837
+
838
+ return estimated_stop_time - estimated_start_time
839
+
840
+
841
+ def get_rise_time(
842
+ x: np.ndarray,
843
+ y: np.ndarray,
844
+ start_ratio: float = 0.1,
845
+ stop_ratio: float = 0.9,
846
+ start_range: tuple[float, float] | None = None,
847
+ end_range: tuple[float, float] | None = None,
848
+ ) -> float | None:
849
+ """Calculates the rise time of a step-like signal between two defined plateaus.
850
+
851
+ The rise time is defined as the time it takes for the signal to increase from
852
+ start_ratio to stop_ratio of the total amplitude change.
853
+
854
+ For rise time calculations (stop_ratio > start_ratio), this function
855
+ automatically uses an improved estimation method that combines heuristic foot
856
+ detection with 50% crossing analysis for better accuracy in noisy signals.
857
+
858
+ For fall time calculations (stop_ratio < start_ratio), it uses the
859
+ traditional ratio-based method.
860
+
861
+ Args:
862
+ x: 1D array of x values (e.g., time).
863
+ y: 1D array of y values corresponding to `x`.
864
+ start_ratio: Fraction of the step height at which the rise starts.
865
+ Default is 0.1 (i.e., 10% of the step height).
866
+ stop_ratio: Fraction of the step height at which the rise ends.
867
+ Default is 0.9 (i.e., 90% of the step height).
868
+ start_range: Tuple defining the start plateau region (before the rise).
869
+ end_range: Tuple defining the end plateau region (after the rise).
870
+
871
+ Returns:
872
+ The rise time (difference between the stop and start ratio crossings).
873
+
874
+ Raises:
875
+ ValueError: If ratios are not between 0 and 1.
876
+ """
877
+ if start_ratio < 0.0 or start_ratio > 1.0:
878
+ raise ValueError("start_ratio must be between 0 and 1")
879
+ if stop_ratio < 0.0 or stop_ratio > 1.0:
880
+ raise ValueError("stop_ratio must be between 0 and 1")
881
+
882
+ if start_range is None:
883
+ start_range = get_start_range(x)
884
+ if end_range is None:
885
+ end_range = get_end_range(x)
886
+
887
+ # For rise time calculations (stop > start), try traditional method first
888
+ # and use enhanced method only when needed for robustness
889
+ if stop_ratio > start_ratio:
890
+ # Check if we have a degenerate range (single point) - use traditional only
891
+ if start_range[0] == start_range[1]:
892
+ return _get_rise_time_traditional(
893
+ x, y, start_range, end_range, start_ratio, stop_ratio
894
+ )
895
+
896
+ # Try traditional method first (better for clean signals)
897
+ traditional_result = _get_rise_time_traditional(
898
+ x, y, start_range, end_range, start_ratio, stop_ratio
899
+ )
900
+
901
+ if traditional_result is not None:
902
+ # Check if this is a Gaussian signal - if so, trust the Gaussian result
903
+ gaussian_result = _find_gaussian_crossing_times(
904
+ x, y, start_ratio, stop_ratio, start_range, end_range
905
+ )
906
+ if gaussian_result is not None:
907
+ # Gaussian detection succeeded - trust this result
908
+ return traditional_result
909
+
910
+ # For non-Gaussian signals, check if enhanced method needed
911
+ # Estimate signal quality by checking foot end detection reliability
912
+ foot_end_time = heuristically_find_rise_start_time(x, y, start_range)
913
+ if foot_end_time is not None:
914
+ # Compare traditional result with enhanced method
915
+ enhanced_result = get_rise_time_estimated(
916
+ x, y, start_range, end_range, start_ratio, stop_ratio
917
+ )
918
+
919
+ if enhanced_result is not None:
920
+ # If results differ significantly, signal might be noisy
921
+ max_result = max(traditional_result, enhanced_result)
922
+ relative_diff = abs(traditional_result - enhanced_result)
923
+ relative_diff /= max_result
924
+
925
+ # Use enhanced method if significant discrepancy (indicating noise)
926
+ if relative_diff > 0.3: # 30% threshold
927
+ return enhanced_result
928
+
929
+ return traditional_result
930
+
931
+ # If traditional method fails, try enhanced method
932
+ enhanced_result = get_rise_time_estimated(
933
+ x, y, start_range, end_range, start_ratio, stop_ratio
934
+ )
935
+ if enhanced_result is not None:
936
+ return enhanced_result
937
+
938
+ # Traditional method for fall time calculations or as fallback
939
+ result = _get_rise_time_traditional(
940
+ x, y, start_range, end_range, start_ratio, stop_ratio
941
+ )
942
+
943
+ if result is None:
944
+ warnings.warn(
945
+ "Could not determine start or stop time for the step rise. Returning None."
946
+ )
947
+
948
+ return result
949
+
950
+
951
+ def get_fall_time(
952
+ x: np.ndarray,
953
+ y: np.ndarray,
954
+ start_ratio: float = 0.9,
955
+ stop_ratio: float = 0.1,
956
+ plateau_range: tuple[float, float] | None = None,
957
+ end_range: tuple[float, float] | None = None,
958
+ fraction: float = 0.05,
959
+ ) -> float | None:
960
+ """Calculates the fall time of a step-like signal between two defined plateaus.
961
+
962
+ The fall time is defined as the time it takes for the signal to decrease from
963
+ start_ratio to stop_ratio of the total amplitude change.
964
+
965
+ This function internally reverses the signal and applies the rise time calculation
966
+ to determine the fall time.
967
+
968
+ Args:
969
+ x: 1D array of x values (e.g., time).
970
+ y: 1D array of y values corresponding to `x`.
971
+ start_ratio: Fraction of the step height at which the fall starts.
972
+ Default is 0.9 (i.e., 90% of the step height).
973
+ stop_ratio: Fraction of the step height at which the fall ends.
974
+ Default is 0.1 (i.e., 10% of the step height).
975
+ plateau_range: Tuple defining the plateau region (top of the step).
976
+ If None, uses the peak y-value.
977
+ end_range: Tuple defining the end plateau region (after the fall).
978
+ fraction: Fraction of the x-range to use for baseline calculations if
979
+ plateau_range is None.
980
+
981
+ Returns:
982
+ The fall time (difference between the stop and start ratio crossings).
983
+
984
+ Raises:
985
+ ValueError: If start_ratio is not greater than stop_ratio or if ratios are
986
+ not between 0 and 1.
987
+ """
988
+ if start_ratio < 0.0 or start_ratio > 1.0:
989
+ raise ValueError("start_ratio must be between 0 and 1")
990
+ if stop_ratio < 0.0 or stop_ratio > 1.0:
991
+ raise ValueError("stop_ratio must be between 0 and 1")
992
+ if start_ratio <= stop_ratio:
993
+ raise ValueError("For fall time, start_ratio must be greater than stop_ratio")
994
+
995
+ # Check if this might be a Gaussian signal
996
+ try:
997
+ if end_range is None:
998
+ end_range = get_end_range(x)
999
+ start_range = get_start_range(x)
1000
+
1001
+ signal_shape = heuristically_recognize_shape(x, y, start_range, end_range)
1002
+ if signal_shape in ["square", "gaussian"]: # Gaussian often detected as square
1003
+ # For Gaussian signals, use symmetric crossing calculation
1004
+ gaussian_result = _find_gaussian_crossing_times(
1005
+ x, y, start_ratio, stop_ratio, start_range, end_range
1006
+ )
1007
+ if gaussian_result is not None:
1008
+ start_time, stop_time = gaussian_result
1009
+ return abs(stop_time - start_time)
1010
+ except (InvalidSignalError, PolarityDetectionError):
1011
+ pass # Fall back to traditional method
1012
+
1013
+ # Traditional method for step/square signals
1014
+ if plateau_range is None:
1015
+ ymax_idx = np.argmax(y)
1016
+ else:
1017
+ # Use the index of the lower plateau boundary as the peak index:
1018
+ plateau_mask = (x >= plateau_range[0]) & (x <= plateau_range[1])
1019
+ if not np.any(plateau_mask):
1020
+ raise InvalidSignalError("No data points found in plateau_range")
1021
+ ymax_idx = np.nonzero(plateau_mask)[0][0]
1022
+ # For fall time calculation, we need a proper baseline range in the fall segment
1023
+ # Use a small portion near the peak as baseline instead of degenerate range
1024
+ x_fall = x[ymax_idx:]
1025
+ if len(x_fall) > 10: # Ensure we have enough points
1026
+ # Use the plateau if provided
1027
+ if plateau_range is None:
1028
+ # Use first fraction% of the fall segment as baseline, but at least 2 points
1029
+ baseline_points = max(2, int(fraction * len(x_fall)))
1030
+ fall_baseline_range = (x_fall[0], x_fall[baseline_points])
1031
+ else:
1032
+ fall_baseline_range = plateau_range
1033
+ else:
1034
+ # Fallback to a small range around the peak
1035
+ fall_baseline_range = (x[ymax_idx], x[min(ymax_idx + 2, len(x) - 1)])
1036
+ fall_time = get_rise_time(
1037
+ x[ymax_idx:],
1038
+ y[ymax_idx:],
1039
+ start_ratio,
1040
+ stop_ratio,
1041
+ fall_baseline_range,
1042
+ end_range,
1043
+ )
1044
+ return fall_time
1045
+
1046
+
1047
+ @check_1d_arrays(x_sorted=True)
1048
+ def heuristically_find_rise_start_time(
1049
+ x: np.ndarray, y: np.ndarray, start_range: tuple[float, float]
1050
+ ) -> float | None:
1051
+ """Finds the point where a step signal begins its systematic rise from baseline.
1052
+
1053
+ This function uses multiple strategies to detect the true start of a step
1054
+ transition:
1055
+ 1. Trend analysis to identify sustained directional change
1056
+ 2. Moving window statistics to detect consistent deviations
1057
+ 3. Gradient analysis for backup detection
1058
+
1059
+ Args:
1060
+ x: 1D array of x values (e.g., time).
1061
+ y: 1D array of y values corresponding to `x`.
1062
+ start_range: Tuple defining the lower plateau region (start of the step).
1063
+
1064
+ Returns:
1065
+ The x-value of the first systematic rise, or None if no such value is found.
1066
+
1067
+ Raises:
1068
+ InvalidSignalError: If insufficient data is provided.
1069
+ """
1070
+ if y.size < 20:
1071
+ raise InvalidSignalError(
1072
+ "Insufficient data for statistical analysis (need ≥20 points)"
1073
+ )
1074
+
1075
+ start_indices = np.nonzero(x >= start_range[1])[0]
1076
+ if len(start_indices) == 0:
1077
+ raise InvalidSignalError("No data points found after start_baseline_range")
1078
+
1079
+ start_idx = start_indices[0]
1080
+
1081
+ # Calculate baseline statistics from the start_range
1082
+ baseline_mask = (x >= start_range[0]) & (x <= start_range[1])
1083
+ if np.sum(baseline_mask) < 5:
1084
+ raise InvalidSignalError("Insufficient baseline data")
1085
+
1086
+ baseline_y = y[baseline_mask]
1087
+ baseline_mean = np.mean(baseline_y)
1088
+ baseline_std = np.std(baseline_y)
1089
+
1090
+ # Strategy 1: Look for consistent upward trend
1091
+ # Use a moving window to detect sustained increase
1092
+ window_size = max(5, len(y) // 100) # Adaptive window size
1093
+
1094
+ for i in range(start_idx, len(y) - window_size):
1095
+ # Get a window of data points
1096
+ window_y = y[i : i + window_size]
1097
+ window_mean = np.mean(window_y)
1098
+
1099
+ # Check if this window is significantly above baseline
1100
+ if window_mean > baseline_mean + 1.5 * baseline_std:
1101
+ # Verify this is the start of a trend by checking if subsequent windows
1102
+ # continue to be elevated
1103
+ confirmation_windows = 0
1104
+ for j in range(
1105
+ i + window_size,
1106
+ min(i + 3 * window_size, len(y) - window_size),
1107
+ window_size,
1108
+ ):
1109
+ next_window_y = y[j : j + window_size]
1110
+ next_window_mean = np.mean(next_window_y)
1111
+ if next_window_mean >= window_mean:
1112
+ confirmation_windows += 1
1113
+
1114
+ # If we have at least one confirming window, this looks like the start
1115
+ if confirmation_windows >= 1:
1116
+ return x[i]
1117
+
1118
+ # Strategy 2: Gradient-based detection with smoothing
1119
+ # Smooth the signal to reduce noise effects
1120
+ y_smooth = scipy.ndimage.gaussian_filter1d(y, sigma=2.0)
1121
+
1122
+ dy = np.gradient(y_smooth, x)
1123
+
1124
+ # Find the region to search (after start_range)
1125
+ search_mask = x >= start_range[1]
1126
+ search_x = x[search_mask]
1127
+ search_dy = dy[search_mask]
1128
+
1129
+ if len(search_dy) > 10:
1130
+ # Look for sustained positive gradient
1131
+ baseline_dy = dy[(x >= start_range[0]) & (x <= start_range[1])]
1132
+ dy_baseline_std = np.std(baseline_dy) if len(baseline_dy) > 0 else 0.1
1133
+
1134
+ # Find first point where gradient is consistently above noise level
1135
+ gradient_threshold = 3 * dy_baseline_std
1136
+
1137
+ for i in range(len(search_dy) - 3):
1138
+ # Check if gradient is above threshold for several consecutive points
1139
+ if np.all(search_dy[i : i + 3] > gradient_threshold):
1140
+ return search_x[i]
1141
+
1142
+ # Strategy 3: Fall back to simple threshold above baseline
1143
+ # Look for first point that's consistently above baseline + 2*std
1144
+ threshold_y = baseline_mean + 2.0 * baseline_std
1145
+
1146
+ search_y = y[search_mask]
1147
+ for i in range(len(search_y) - 2):
1148
+ if np.all(search_y[i : i + 3] > threshold_y):
1149
+ return search_x[i]
1150
+
1151
+ return None
1152
+
1153
+
1154
+ def get_rise_start_time(
1155
+ x: np.ndarray,
1156
+ y: np.ndarray,
1157
+ start_range: tuple[float, float],
1158
+ end_range: tuple[float, float],
1159
+ threshold: float | None = None,
1160
+ ) -> float:
1161
+ """Find the rise start time of a step signal using multiple strategies.
1162
+
1163
+ This function tries multiple approaches to find the rise start time:
1164
+ 1. Uses threshold crossing if threshold is provided
1165
+ 2. Uses heuristic detection as fallback
1166
+ 3. Validates results to ensure they make physical sense
1167
+
1168
+ Args:
1169
+ x: 1D array of x values (e.g., time or position).
1170
+ y: 1D array of y values (same size as x).
1171
+ start_range: A range (min, max) representing the initial flat region ("foot").
1172
+ end_range: A range (min, max) representing the final high region after the rise.
1173
+ threshold: If provided, use this fractional amplitude (0-1) to determine the
1174
+ end of the foot. If None, use heuristic detection.
1175
+
1176
+ Returns:
1177
+ The rise start time (foot end time).
1178
+
1179
+ Raises:
1180
+ InvalidSignalError: If rise start time cannot be determined.
1181
+ """
1182
+ # Try heuristic detection first as it's often more reliable for step detection
1183
+ try:
1184
+ heuristic_result = heuristically_find_rise_start_time(x, y, start_range)
1185
+ except InvalidSignalError:
1186
+ heuristic_result = None
1187
+
1188
+ # Try threshold method if requested
1189
+ threshold_result = None
1190
+ if threshold is not None:
1191
+ try:
1192
+ threshold_result = find_crossing_at_ratio(
1193
+ x, y, threshold, start_range, end_range
1194
+ )
1195
+ except InvalidSignalError:
1196
+ pass
1197
+
1198
+ # Validate and choose the best result
1199
+ if heuristic_result is not None and threshold_result is not None:
1200
+ # If both methods give results, prefer the one that's more reasonable
1201
+ # For step signals, the heuristic should give a later (more accurate) time
1202
+ # than a low threshold crossing
1203
+ if threshold <= 0.2 and heuristic_result > threshold_result:
1204
+ return heuristic_result
1205
+ return threshold_result
1206
+ if heuristic_result is not None:
1207
+ return heuristic_result
1208
+ if threshold_result is not None:
1209
+ return threshold_result
1210
+
1211
+ # Last resort: look for the steepest part of the signal
1212
+ dy = np.gradient(y, x)
1213
+ search_mask = (x >= start_range[1]) & (x <= end_range[0])
1214
+ if np.any(search_mask):
1215
+ search_indices = np.where(search_mask)[0]
1216
+ max_dy_idx = search_indices[np.argmax(dy[search_mask])]
1217
+ # Move back to find the start of the steep region
1218
+ for i in range(max_dy_idx, max(0, max_dy_idx - 50), -1):
1219
+ if dy[i] <= dy[max_dy_idx] * 0.1: # 10% of max gradient
1220
+ return x[i]
1221
+ return x[max_dy_idx]
1222
+
1223
+ raise InvalidSignalError("Could not determine rise start time with any method")
1224
+
1225
+
1226
+ @check_1d_arrays(x_sorted=True)
1227
+ def full_width_at_y(
1228
+ x: np.ndarray,
1229
+ y: np.ndarray,
1230
+ level: float,
1231
+ ) -> tuple[float, float, float, float]:
1232
+ """Compute the full width at a given y level of a square shaped signal using
1233
+ zero-crossing method.
1234
+
1235
+ Args:
1236
+ x: 1D array of x values.
1237
+ y: 1D array of y values.
1238
+ level: The Y level at which to compute the width
1239
+
1240
+ Returns:
1241
+ Full width segment coordinates (x1, level, x2, level)
1242
+ """
1243
+ tmax_idx = np.argmax(y)
1244
+
1245
+ roots1 = features.find_x_values_at_y(
1246
+ x[0 : tmax_idx + 1],
1247
+ y[0 : tmax_idx + 1],
1248
+ level,
1249
+ )
1250
+ if len(roots1) > 1:
1251
+ warnings.warn("Multiple crossing points found. Returning first.")
1252
+ roots2 = features.find_x_values_at_y(
1253
+ x[tmax_idx:],
1254
+ y[tmax_idx:],
1255
+ level,
1256
+ )
1257
+ if len(roots2) > 1:
1258
+ warnings.warn("Multiple crossing points found. Returning last.")
1259
+ t1 = roots1[0] if len(roots1) > 0 else np.nan
1260
+ t2 = roots2[-1] if len(roots2) > 0 else np.nan
1261
+ return t1, level, t2, level
1262
+
1263
+
1264
+ def full_width_at_ratio(
1265
+ x: np.ndarray,
1266
+ y: np.ndarray,
1267
+ ratio: float,
1268
+ start_range: tuple[float, float] | None = None,
1269
+ end_range: tuple[float, float] | None = None,
1270
+ fraction: float = 0.05,
1271
+ ) -> tuple[float, float, float, float]:
1272
+ """
1273
+ Calculate the full width at a specified ratio of the amplitude for a pulse signal.
1274
+
1275
+ This function determines the two crossing points (x1, x2) where the normalized
1276
+ signal crosses a given ratio of its amplitude, and returns these points along with
1277
+ the corresponding y-level.
1278
+
1279
+ Args:
1280
+ x: 1D array of x-values.
1281
+ y: 1D array of y-values.
1282
+ ratio: Ratio (between 0 and 1) of the amplitude at which to measure the width.
1283
+ start_range: Range of x-values to estimate the start baseline.
1284
+ end_range: Range of x-values to estimate the end baseline.
1285
+ fraction: Fraction of the x-range to use for baseline calculations if
1286
+ start_range or end_range are None.
1287
+
1288
+ Returns:
1289
+ Full width segment coordinates (x1, level, x2, level), where x1 and x2 are the
1290
+ crossing points at the specified ratio, and level is the corresponding y-value.
1291
+
1292
+ Raises:
1293
+ ValueError: If the amplitude of the signal is zero.
1294
+ RuntimeWarning: If the polarity cannot be determined, returns NaN for crossing
1295
+ times.
1296
+
1297
+ Notes:
1298
+ - The function normalizes the signal based on the detected amplitude and
1299
+ polarity.
1300
+ - The crossing times are computed using `features.find_first_x_at_y_value`
1301
+ function.
1302
+ """
1303
+ amplitude = get_amplitude(x, y, start_range, end_range)
1304
+
1305
+ try:
1306
+ polarity = detect_polarity(x, y, start_range, end_range)
1307
+ except PolarityDetectionError as e:
1308
+ raise InvalidSignalError(f"Cannot determine width at ratio: {e}") from e
1309
+
1310
+ if start_range is None:
1311
+ start_range = get_start_range(x, fraction)
1312
+ if end_range is None:
1313
+ end_range = get_end_range(x, fraction)
1314
+ start_baseline = get_range_mean_y(x, y * polarity, start_range)
1315
+
1316
+ if amplitude == 0:
1317
+ raise InvalidSignalError(
1318
+ "Amplitude of your square signal is zero. Check your data."
1319
+ )
1320
+
1321
+ y_norm = np.asarray(polarity * (y - start_baseline) / amplitude, dtype=y.dtype.type)
1322
+
1323
+ level = y.dtype.type(ratio * polarity * amplitude + start_baseline)
1324
+
1325
+ tmax_idx = np.argmax(y_norm)
1326
+
1327
+ try:
1328
+ roots1 = features.find_x_values_at_y(
1329
+ x[0 : tmax_idx + 1],
1330
+ y_norm[0 : tmax_idx + 1],
1331
+ ratio,
1332
+ )
1333
+ except ValueError:
1334
+ roots1 = []
1335
+ if len(roots1) > 1:
1336
+ warnings.warn("Multiple crossing points found. Returning first.")
1337
+ x1 = roots1[0] if len(roots1) > 0 else np.nan
1338
+ try:
1339
+ roots2 = features.find_x_values_at_y(
1340
+ x[tmax_idx:],
1341
+ y_norm[tmax_idx:],
1342
+ ratio,
1343
+ )
1344
+ except ValueError:
1345
+ roots2 = []
1346
+ if len(roots2) > 1:
1347
+ warnings.warn("Multiple crossing points found. Returning last.")
1348
+ x2 = roots2[-1] if len(roots2) > 0 else np.nan
1349
+ return x1, level, x2, level
1350
+
1351
+
1352
+ def fwhm(
1353
+ x: np.ndarray,
1354
+ y: np.ndarray,
1355
+ method: Literal["zero-crossing", "gauss", "lorentz", "voigt"] = "zero-crossing",
1356
+ xmin: float | None = None,
1357
+ xmax: float | None = None,
1358
+ ) -> tuple[float, float, float, float]:
1359
+ """Compute Full Width at Half Maximum (FWHM) of the input data
1360
+
1361
+ Args:
1362
+ x: 1D array of x-values.
1363
+ y: 1D array of y-values.
1364
+ method: Calculation method. Two types of methods are supported: a zero-crossing
1365
+ method and fitting methods (based on various models: Gauss, Lorentz, Voigt).
1366
+ Defaults to "zero-crossing".
1367
+ xmin: Lower X bound for the fitting. Defaults to None (no lower bound,
1368
+ i.e. the fitting starts from the first point).
1369
+ xmax: Upper X bound for the fitting. Defaults to None (no upper bound,
1370
+ i.e. the fitting ends at the last point)
1371
+
1372
+ Returns:
1373
+ FWHM segment coordinates
1374
+ """
1375
+ dx, dy, base = np.max(x) - np.min(x), np.max(y) - np.min(y), np.min(y)
1376
+ sigma, mu = dx * 0.1, peakdetection.xpeak(x, y)
1377
+ if isinstance(xmin, float):
1378
+ indices = np.where(x >= xmin)[0]
1379
+ x = x[indices]
1380
+ y = y[indices]
1381
+ if isinstance(xmax, float):
1382
+ indices = np.where(x <= xmax)[0]
1383
+ x = x[indices]
1384
+ y = y[indices]
1385
+
1386
+ if method == "zero-crossing":
1387
+ x1, y1, x2, y2 = full_width_at_ratio(x, y, 0.5)
1388
+ return x1, y1, x2, y2
1389
+
1390
+ try:
1391
+ fit_model_class: type[PulseFitModel] = {
1392
+ "gauss": GaussianModel,
1393
+ "lorentz": LorentzianModel,
1394
+ "voigt": VoigtModel,
1395
+ }[method]
1396
+ except KeyError as exc:
1397
+ raise ValueError(f"Invalid method {method}") from exc
1398
+
1399
+ def func(params) -> np.ndarray:
1400
+ """Fitting model function"""
1401
+ # pylint: disable=cell-var-from-loop
1402
+ return y - fit_model_class.func(x, *params)
1403
+
1404
+ amp = fit_model_class.get_amp_from_amplitude(dy, sigma)
1405
+ (amp, sigma, mu, base), _ier = scipy.optimize.leastsq(
1406
+ func, np.array([amp, sigma, mu, base])
1407
+ )
1408
+ return fit_model_class.half_max_segment(amp, sigma, mu, base)
1409
+
1410
+
1411
+ @check_1d_arrays(x_sorted=True)
1412
+ def fw1e2(x: np.ndarray, y: np.ndarray) -> tuple[float, float, float, float]:
1413
+ """Compute Full Width at 1/e² of the input data (using a Gaussian model fitting).
1414
+
1415
+ Args:
1416
+ x: 1D array of x-values.
1417
+ y: 1D array of y-values.
1418
+
1419
+ Returns:
1420
+ FW at 1/e² segment coordinates
1421
+ """
1422
+ dx, dy, base = np.max(x) - np.min(x), np.max(y) - np.min(y), np.min(y)
1423
+ sigma, mu = dx * 0.1, peakdetection.xpeak(x, y)
1424
+ amp = GaussianModel.get_amp_from_amplitude(dy, sigma)
1425
+ p_in = np.array([amp, sigma, mu, base])
1426
+
1427
+ def func(params):
1428
+ """Fitting model function"""
1429
+ # pylint: disable=cell-var-from-loop
1430
+ return y - GaussianModel.func(x, *params)
1431
+
1432
+ p_out, _ier = scipy.optimize.leastsq(func, p_in)
1433
+ amp, sigma, mu, base = p_out
1434
+ hw = 2 * sigma
1435
+ yhm = GaussianModel.amplitude(amp, sigma) / np.e**2 + base
1436
+ return mu - hw, yhm, mu + hw, yhm
1437
+
1438
+
1439
+ @dataclass
1440
+ class PulseFeatures:
1441
+ """Extracted features from a pulse signal.
1442
+
1443
+ Attributes:
1444
+ signal_shape: The shape of the signal (step or square).
1445
+ polarity: The polarity of the signal (1 for positive, -1 for negative).
1446
+ amplitude: The amplitude of the signal.
1447
+ offset: The baseline offset of the signal.
1448
+ foot_duration: The duration of the foot (flat region before rise) of the signal.
1449
+ xstartmin: The minimum x-value of the start baseline region.
1450
+ xstartmax: The maximum x-value of the start baseline region.
1451
+ xendmin: The minimum x-value of the end baseline region.
1452
+ xendmax: The maximum x-value of the end baseline region.
1453
+ xplateaumin: The minimum x-value of the plateau region (if applicable).
1454
+ xplateaumax: The maximum x-value of the plateau region (if applicable).
1455
+ rise_time: The rise time of the signal (time from start_ratio to stop_ratio).
1456
+ fall_time: The fall time of the signal (time from stop_ratio to start_ratio).
1457
+ fwhm: The full width at half maximum of the signal.
1458
+ x50: The time at which the signal reaches 50% of its amplitude.
1459
+ x100: The time at which the signal reaches its maximum amplitude.
1460
+ """
1461
+
1462
+ signal_shape: SignalShape = SignalShape.STEP
1463
+ polarity: int = 1
1464
+ amplitude: float = 0.0
1465
+ offset: float = 0.0
1466
+ foot_duration: float = 0.0
1467
+ xstartmin: float = 0.0
1468
+ xstartmax: float = 0.0
1469
+ xendmin: float = 0.0
1470
+ xendmax: float = 0.0
1471
+ xplateaumin: float | None = None
1472
+ xplateaumax: float | None = None
1473
+ rise_time: float | None = None
1474
+ fall_time: float | None = None
1475
+ fwhm: float | None = None
1476
+ x0: float | None = None
1477
+ x50: float | None = None
1478
+ x100: float | None = None
1479
+
1480
+
1481
+ def extract_pulse_features(
1482
+ x: np.ndarray,
1483
+ y: np.ndarray,
1484
+ start_range: tuple[float, float],
1485
+ end_range: tuple[float, float],
1486
+ start_ratio: float = 0.1,
1487
+ stop_ratio: float = 0.9,
1488
+ signal_shape: SignalShape | None = None,
1489
+ fraction: float = 0.05,
1490
+ denoise: bool = True,
1491
+ ) -> PulseFeatures:
1492
+ """Extract various pulse features from the input signal.
1493
+
1494
+ Args:
1495
+ x: 1D array of x values (e.g., time).
1496
+ y: 1D array of y values (signal).
1497
+ start_range: Interval for the first plateau (baseline).
1498
+ end_range: Interval for the second plateau (peak).
1499
+ signal_shape: Signal type (None for auto-detection).
1500
+ start_ratio: Fraction for rise start.
1501
+ stop_ratio: Fraction for rise end.
1502
+ fraction: Fraction of the x-range to use for baseline calculations if
1503
+ start_range or end_range are None.
1504
+ denoise: If True, apply a denoising filter to the signal before analysis.
1505
+
1506
+ Returns:
1507
+ Pulse features.
1508
+
1509
+ Raises:
1510
+ ValueError: If input parameters are invalid.
1511
+ """
1512
+ if start_ratio > 1.0 or start_ratio < 0.0:
1513
+ raise ValueError("start_ratio must be between 0 and 1")
1514
+ if stop_ratio > 1.0 or stop_ratio < 0.0:
1515
+ raise ValueError("stop_ratio must be between 0 and 1")
1516
+ if start_ratio >= stop_ratio:
1517
+ raise ValueError("start_ratio must be less than stop_ratio")
1518
+
1519
+ if signal_shape is None:
1520
+ signal_shape = heuristically_recognize_shape(x, y, start_range, end_range)
1521
+ if not isinstance(signal_shape, (SignalShape, str)):
1522
+ raise ValueError("Invalid signal_shape")
1523
+
1524
+ if denoise:
1525
+ y = filtering.denoise_preserve_shape(y)[0]
1526
+
1527
+ polarity = detect_polarity(x, y, start_range, end_range, signal_shape=signal_shape)
1528
+ plateau_range = None
1529
+ if signal_shape == SignalShape.SQUARE:
1530
+ plateau_range = get_plateau_range(
1531
+ x, y, polarity, fraction, start_range, end_range
1532
+ )
1533
+ amplitude = get_amplitude(x, y, start_range, end_range, plateau_range, signal_shape)
1534
+
1535
+ ymax_idx = np.argmax(y)
1536
+
1537
+ if signal_shape == SignalShape.STEP:
1538
+ rise_time = get_rise_time(x, y, start_ratio, stop_ratio, start_range, end_range)
1539
+ x0 = get_rise_start_time(x, y, start_range, end_range)
1540
+ x50 = find_crossing_at_ratio(x, y, 0.5, start_range, end_range)
1541
+ fall_time = None
1542
+ fwhm_val = None
1543
+ else: # is square
1544
+ rise_time = get_rise_time(
1545
+ x[0 : ymax_idx + 1],
1546
+ y[0 : ymax_idx + 1],
1547
+ start_ratio,
1548
+ stop_ratio,
1549
+ start_range,
1550
+ (x[ymax_idx], x[ymax_idx]),
1551
+ )
1552
+ # Check if this is a Gaussian signal - if so, x50 should be on the rise
1553
+ gaussian_result = _find_gaussian_crossing_times(
1554
+ x, y, start_ratio, stop_ratio, start_range, end_range
1555
+ )
1556
+ if gaussian_result is not None:
1557
+ # For Gaussian signals, x50 is the 50% crossing on the rise (left side)
1558
+ x50 = find_crossing_at_ratio(
1559
+ x[0 : ymax_idx + 1],
1560
+ y[0 : ymax_idx + 1],
1561
+ 0.5,
1562
+ start_range,
1563
+ (x[ymax_idx], x[ymax_idx]),
1564
+ )
1565
+ else:
1566
+ # For square signals, x50 is at the 50% crossing
1567
+ x50 = find_crossing_at_ratio(
1568
+ x[0 : ymax_idx + 1],
1569
+ y[0 : ymax_idx + 1],
1570
+ 0.5,
1571
+ start_range,
1572
+ (x[ymax_idx], x[ymax_idx]),
1573
+ )
1574
+ fall_time = get_fall_time(
1575
+ x, y, stop_ratio, start_ratio, plateau_range, end_range
1576
+ )
1577
+ x0 = get_rise_start_time(
1578
+ x[0 : ymax_idx + 1],
1579
+ y[0 : ymax_idx + 1],
1580
+ start_range,
1581
+ (x[ymax_idx], x[ymax_idx]),
1582
+ )
1583
+ x1, _, x2, _ = fwhm(x, y, "zero-crossing")
1584
+ fwhm_val = x2 - x1 # full width at half maximum
1585
+ mean_x_sampling_time = float(np.mean(np.diff(x)))
1586
+ if fwhm_val <= 10 * mean_x_sampling_time:
1587
+ # if the fwhm is smaller than 10 times the mean sampling time, we cannot
1588
+ # rely on rising and falling times, as the pulse is too narrow
1589
+ fall_time = None
1590
+ rise_time = None
1591
+
1592
+ if x50 is None:
1593
+ # No x50 found (e.g., for very narrow pulses or Gaussian signals)
1594
+ x100 = x[ymax_idx]
1595
+ else:
1596
+ # For step/square signals, calculate conventional x100
1597
+ # Check if this is likely a Gaussian signal (symmetric crossings)
1598
+ gaussian_result = _find_gaussian_crossing_times(
1599
+ x, y, start_ratio, stop_ratio, start_range, end_range
1600
+ )
1601
+ if gaussian_result is not None:
1602
+ # Gaussian signal: x100 should be at the actual maximum
1603
+ x100 = x[ymax_idx]
1604
+ else:
1605
+ # Step/square signal: use traditional extrapolation from x0/x50
1606
+ x100 = x50 + (x50 - x0)
1607
+
1608
+ return PulseFeatures(
1609
+ signal_shape=signal_shape,
1610
+ polarity=polarity,
1611
+ amplitude=amplitude,
1612
+ offset=get_range_mean_y(x, y * polarity, start_range),
1613
+ foot_duration=x0 - x[0],
1614
+ xstartmin=start_range[0],
1615
+ xstartmax=start_range[1],
1616
+ xendmin=end_range[0],
1617
+ xendmax=end_range[1],
1618
+ xplateaumin=None if plateau_range is None else plateau_range[0],
1619
+ xplateaumax=None if plateau_range is None else plateau_range[1],
1620
+ rise_time=rise_time,
1621
+ fall_time=fall_time,
1622
+ fwhm=fwhm_val,
1623
+ x0=x0,
1624
+ x50=x50,
1625
+ x100=x100,
1626
+ )