dkist-processing-visp 4.0.0__py3-none-any.whl → 5.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 (32) hide show
  1. dkist_processing_visp/models/constants.py +50 -9
  2. dkist_processing_visp/models/fits_access.py +5 -1
  3. dkist_processing_visp/models/metric_code.py +10 -0
  4. dkist_processing_visp/models/parameters.py +128 -19
  5. dkist_processing_visp/parsers/spectrograph_configuration.py +75 -0
  6. dkist_processing_visp/parsers/visp_l0_fits_access.py +6 -0
  7. dkist_processing_visp/tasks/geometric.py +115 -7
  8. dkist_processing_visp/tasks/l1_output_data.py +202 -0
  9. dkist_processing_visp/tasks/lamp.py +50 -91
  10. dkist_processing_visp/tasks/parse.py +19 -0
  11. dkist_processing_visp/tasks/science.py +14 -14
  12. dkist_processing_visp/tasks/solar.py +894 -451
  13. dkist_processing_visp/tasks/visp_base.py +1 -0
  14. dkist_processing_visp/tests/conftest.py +98 -35
  15. dkist_processing_visp/tests/header_models.py +71 -20
  16. dkist_processing_visp/tests/local_trial_workflows/local_trial_helpers.py +25 -1
  17. dkist_processing_visp/tests/test_assemble_quality.py +89 -4
  18. dkist_processing_visp/tests/test_geometric.py +40 -0
  19. dkist_processing_visp/tests/test_instrument_polarization.py +2 -1
  20. dkist_processing_visp/tests/test_lamp.py +17 -22
  21. dkist_processing_visp/tests/test_parameters.py +120 -18
  22. dkist_processing_visp/tests/test_parse.py +73 -1
  23. dkist_processing_visp/tests/test_science.py +5 -6
  24. dkist_processing_visp/tests/test_solar.py +319 -102
  25. dkist_processing_visp/tests/test_visp_constants.py +35 -6
  26. {dkist_processing_visp-4.0.0.dist-info → dkist_processing_visp-5.0.0.dist-info}/METADATA +40 -37
  27. {dkist_processing_visp-4.0.0.dist-info → dkist_processing_visp-5.0.0.dist-info}/RECORD +31 -30
  28. docs/conf.py +4 -1
  29. docs/gain_correction.rst +50 -42
  30. dkist_processing_visp/tasks/mixin/line_zones.py +0 -116
  31. {dkist_processing_visp-4.0.0.dist-info → dkist_processing_visp-5.0.0.dist-info}/WHEEL +0 -0
  32. {dkist_processing_visp-4.0.0.dist-info → dkist_processing_visp-5.0.0.dist-info}/top_level.txt +0 -0
@@ -2,12 +2,15 @@
2
2
 
3
3
  from enum import Enum
4
4
 
5
+ import astropy.units as u
6
+ from astropy.units import Quantity
5
7
  from dkist_processing_common.models.constants import ConstantsBase
6
8
 
7
9
 
8
10
  class VispBudName(Enum):
9
11
  """Names to be used in Visp buds."""
10
12
 
13
+ arm_id = "ARM_ID"
11
14
  num_raster_steps = "NUM_RASTER_STEPS"
12
15
  polarimeter_mode = "POLARIMETER_MODE"
13
16
  wavelength = "WAVELENGTH"
@@ -22,6 +25,10 @@ class VispBudName(Enum):
22
25
  polcal_readout_exp_times = "POLCAL_READOUT_EXP_TIMES"
23
26
  non_dark_task_readout_exp_times = "NON_DARK_TASK_READOUT_EXP_TIMES"
24
27
  num_map_scans = "NUM_MAP_SCANS"
28
+ incident_light_angle_deg = "INCIDENT_LIGHT_ANGLE_DEG"
29
+ reflected_light_angle_deg = "REFLECTED_LIGHT_ANGLE_DEG"
30
+ grating_constant_inverse_mm = "GRATING_CONSTANT_INVERSE_MM"
31
+ solar_gain_ip_start_time = "SOLAR_GAIN_IP_START_TIME"
25
32
  axis_1_type = "AXIS_1_TYPE"
26
33
  axis_2_type = "AXIS_2_TYPE"
27
34
  axis_3_type = "AXIS_3_TYPE"
@@ -31,6 +38,16 @@ class VispBudName(Enum):
31
38
  class VispConstants(ConstantsBase):
32
39
  """Visp specific constants to add to the common constants."""
33
40
 
41
+ @property
42
+ def arm_id(self) -> str:
43
+ """
44
+ Return the current ViSP arm ID.
45
+
46
+ Arm IDs are ints in the headers, but we convert them to str here because that's what downstream machinery expects
47
+ the type to be.
48
+ """
49
+ return str(self._db_dict[VispBudName.arm_id])
50
+
34
51
  @property
35
52
  def wavelength(self) -> float:
36
53
  """Wavelength."""
@@ -76,17 +93,17 @@ class VispConstants(ConstantsBase):
76
93
  raise ValueError(f"No init set known for {retarder_name = }")
77
94
 
78
95
  @property
79
- def lamp_exposure_times(self) -> [float]:
96
+ def lamp_exposure_times(self) -> list[float]:
80
97
  """Find the lamp exposure time."""
81
98
  return self._db_dict[VispBudName.lamp_exposure_times.value]
82
99
 
83
100
  @property
84
- def solar_exposure_times(self) -> [float]:
101
+ def solar_exposure_times(self) -> list[float]:
85
102
  """Find the solar exposure time."""
86
103
  return self._db_dict[VispBudName.solar_exposure_times.value]
87
104
 
88
105
  @property
89
- def polcal_exposure_times(self) -> [float]:
106
+ def polcal_exposure_times(self) -> list[float]:
90
107
  """Find the polarization calibration exposure time."""
91
108
  if self.correct_for_polarization:
92
109
  return self._db_dict[VispBudName.polcal_exposure_times.value]
@@ -94,22 +111,22 @@ class VispConstants(ConstantsBase):
94
111
  return []
95
112
 
96
113
  @property
97
- def observe_exposure_times(self) -> [float]:
114
+ def observe_exposure_times(self) -> list[float]:
98
115
  """Find the observation exposure time."""
99
116
  return self._db_dict[VispBudName.observe_exposure_times.value]
100
117
 
101
118
  @property
102
- def lamp_readout_exp_times(self) -> [float]:
119
+ def lamp_readout_exp_times(self) -> list[float]:
103
120
  """Find the lamp readout exposure time."""
104
121
  return self._db_dict[VispBudName.lamp_readout_exp_times.value]
105
122
 
106
123
  @property
107
- def solar_readout_exp_times(self) -> [float]:
124
+ def solar_readout_exp_times(self) -> list[float]:
108
125
  """Find the solar readout exposure time."""
109
126
  return self._db_dict[VispBudName.solar_readout_exp_times.value]
110
127
 
111
128
  @property
112
- def polcal_readout_exp_times(self) -> [float]:
129
+ def polcal_readout_exp_times(self) -> list[float]:
113
130
  """Find the polarization calibration readout exposure time."""
114
131
  if self.correct_for_polarization:
115
132
  return self._db_dict[VispBudName.polcal_readout_exp_times.value]
@@ -117,7 +134,7 @@ class VispConstants(ConstantsBase):
117
134
  return []
118
135
 
119
136
  @property
120
- def non_dark_task_readout_exp_times(self) -> [float]:
137
+ def non_dark_task_readout_exp_times(self) -> list[float]:
121
138
  """
122
139
  Find all readout exposure times that *need* to exist in a dark IP.
123
140
 
@@ -127,10 +144,34 @@ class VispConstants(ConstantsBase):
127
144
  return self._db_dict[VispBudName.non_dark_task_readout_exp_times.value]
128
145
 
129
146
  @property
130
- def observe_readout_exp_times(self) -> [float]:
147
+ def observe_readout_exp_times(self) -> list[float]:
131
148
  """Find the observation readout exposure time."""
132
149
  return self._db_dict[VispBudName.observe_readout_exp_times.value]
133
150
 
151
+ @property
152
+ def incident_light_angle_deg(self) -> Quantity:
153
+ """Return the spectrograph incident light angle [deg]."""
154
+ return self._db_dict[VispBudName.incident_light_angle_deg] * u.deg
155
+
156
+ @property
157
+ def reflected_light_angle_deg(self) -> Quantity:
158
+ """
159
+ Return the spectrograph reflected light angle [deg].
160
+
161
+ This angle is the incident light angle plus the angular position of the ViSP arm.
162
+ """
163
+ return self._db_dict[VispBudName.reflected_light_angle_deg] * u.deg
164
+
165
+ @property
166
+ def grating_constant_inverse_mm(self) -> Quantity:
167
+ """Return the spectrograph grating constant [1/mm]."""
168
+ return self._db_dict[VispBudName.grating_constant_inverse_mm] / u.mm
169
+
170
+ @property
171
+ def solar_gain_ip_start_time(self) -> str:
172
+ """Return the start time of the SOLAR GAIN Instrument Program."""
173
+ return self._db_dict[VispBudName.solar_gain_ip_start_time]
174
+
134
175
  @property
135
176
  def axis_1_type(self) -> str:
136
177
  """Find the type of the first array axis."""
@@ -6,11 +6,15 @@ from enum import StrEnum
6
6
  class VispMetadataKey(StrEnum):
7
7
  """Controlled list of names for FITS metadata header keys."""
8
8
 
9
+ arm_id = "VSPARMID"
10
+ number_of_modulator_states = "VSPNUMST"
9
11
  raster_scan_step = "VSPSTP"
10
12
  total_raster_steps = "VSPNSTP"
11
13
  modulator_state = "VSPSTNUM"
12
- number_of_modulator_states = "VSPNUMST"
13
14
  polarimeter_mode = "VISP_006"
15
+ grating_angle_deg = "VSPGRTAN"
16
+ arm_position_deg = "VSPARMPS"
17
+ grating_constant_inverse_mm = "VSPGRTCN"
14
18
  axis_1_type = "CTYPE1"
15
19
  axis_2_type = "CTYPE2"
16
20
  axis_3_type = "CTYPE3"
@@ -0,0 +1,10 @@
1
+ """Controlled list of quality metric codes."""
2
+
3
+ from enum import StrEnum
4
+
5
+
6
+ class VispMetricCode(StrEnum):
7
+ """Controlled list of quality metric codes."""
8
+
9
+ solar_first_vignette = "SOLAR_CAL_FIRST_VIGNETTE"
10
+ solar_final_vignette = "SOLAR_CAL_FINAL_VIGNETTE"
@@ -1,9 +1,14 @@
1
1
  """Visp calibration pipeline parameters."""
2
2
 
3
3
  from datetime import datetime
4
+ from random import randint
5
+ from typing import Any
4
6
 
7
+ import astropy.units as u
8
+ from dkist_processing_common.models.parameters import ParameterArmIdMixin
5
9
  from dkist_processing_common.models.parameters import ParameterBase
6
10
  from dkist_processing_common.models.parameters import ParameterWavelengthMixin
11
+ from solar_wavelength_calibration import DownloadConfig
7
12
 
8
13
 
9
14
  class VispParsingParameters(ParameterBase):
@@ -22,7 +27,7 @@ class VispParsingParameters(ParameterBase):
22
27
  )
23
28
 
24
29
 
25
- class VispParameters(ParameterBase, ParameterWavelengthMixin):
30
+ class VispParameters(ParameterBase, ParameterWavelengthMixin, ParameterArmIdMixin):
26
31
  """Put all Visp parameters parsed from the input dataset document in a single property."""
27
32
 
28
33
  @property
@@ -69,7 +74,7 @@ class VispParameters(ParameterBase, ParameterWavelengthMixin):
69
74
 
70
75
  @property
71
76
  def hairline_mask_spatial_smoothing_width_px(self) -> float:
72
- """Amount to smooth the hairling mask in the spatial direction.
77
+ """Amount to smooth the hairline mask in the spatial direction.
73
78
 
74
79
  This helps capture the higher-flux wings of the hairlines that would otherwise require a `hairline_fraction`
75
80
  that was so low it captures other optical features.
@@ -134,9 +139,34 @@ class VispParameters(ParameterBase, ParameterWavelengthMixin):
134
139
  return self._find_most_recent_past_value("visp_geo_poly_fit_order")
135
140
 
136
141
  @property
137
- def solar_spectral_avg_window(self):
142
+ def geo_zone_prominence(self):
143
+ """Relative peak prominence threshold used to identify strong spectral features."""
144
+ return self._find_parameter_closest_wavelength("visp_geo_zone_prominence")
145
+
146
+ @property
147
+ def geo_zone_width(self):
148
+ """Pixel width used to search for strong spectral features."""
149
+ return self._find_parameter_closest_wavelength("visp_geo_zone_width")
150
+
151
+ @property
152
+ def geo_zone_bg_order(self):
153
+ """Order of polynomial fit used to remove continuum when identifying strong spectral features."""
154
+ return self._find_parameter_closest_wavelength("visp_geo_zone_bg_order")
155
+
156
+ @property
157
+ def geo_zone_normalization_percentile(self):
158
+ """Fraction of CDF to use for normalizing spectrum when search for strong features."""
159
+ return self._find_parameter_closest_wavelength("visp_geo_zone_normalization_percentile")
160
+
161
+ @property
162
+ def geo_zone_rel_height(self):
163
+ """Relative height at which to compute the width of strong spectral features."""
164
+ return self._find_most_recent_past_value("visp_geo_zone_rel_height")
165
+
166
+ @property
167
+ def solar_spatial_median_filter_width_px(self):
138
168
  """Pixel width of spatial median filter used to compute characteristic solar spectra."""
139
- return self._find_parameter_closest_wavelength("visp_solar_spectral_avg_window")
169
+ return self._find_parameter_closest_wavelength("visp_solar_spatial_median_filter_width_px")
140
170
 
141
171
  @property
142
172
  def solar_characteristic_spatial_normalization_percentile(self) -> float:
@@ -146,29 +176,108 @@ class VispParameters(ParameterBase, ParameterWavelengthMixin):
146
176
  )
147
177
 
148
178
  @property
149
- def solar_zone_prominence(self):
150
- """Relative peak prominence threshold used to identify strong spectral features."""
151
- return self._find_parameter_closest_wavelength("visp_solar_zone_prominence")
179
+ def solar_vignette_initial_continuum_poly_fit_order(self) -> int:
180
+ """
181
+ Define the order of polynomial to use when fitting the initial continuum function.
182
+
183
+ Note that "initial" in this context does not refer to an initial guess in the wavecal fitter, but rather the
184
+ fact that this represents the initial estimate of the vignette signal.
185
+ """
186
+ return self._find_most_recent_past_value(
187
+ "visp_solar_vignette_initial_continuum_poly_fit_order"
188
+ )
152
189
 
153
190
  @property
154
- def solar_zone_width(self):
155
- """Pixel width used to search for strong spectral features."""
156
- return self._find_parameter_closest_wavelength("visp_solar_zone_width")
191
+ def solar_vignette_crval_bounds_px(self) -> float:
192
+ """
193
+ Define the bounds (in *pixels*) on crval when fitting the initial vignette signal.
194
+
195
+ The actual bounds on the value of crval are equal to ± the initial dispersion times this number. Note that the
196
+ total range searched by the fitting algorithm will be twice this number (in pixels).
197
+ """
198
+ return self._find_most_recent_past_value("visp_solar_vignette_crval_bounds_px") * u.pix
157
199
 
158
200
  @property
159
- def solar_zone_bg_order(self):
160
- """Order of polynomial fit used to remove continuum when identifying strong spectral features."""
161
- return self._find_parameter_closest_wavelength("visp_solar_zone_bg_order")
201
+ def solar_vignette_dispersion_bounds_fraction(self) -> float:
202
+ """
203
+ Define the ± fraction away from the initial value for bounds on dispersion when fitting the initial vignette signal.
204
+
205
+ This value should be between 0 and 1. For example, the minimum bound is `init_value * (1 - solar_vignette_dispersion_bounds_fraction)`.
206
+ """
207
+ return self._find_most_recent_past_value("visp_solar_vignette_dispersion_bounds_fraction")
162
208
 
163
209
  @property
164
- def solar_zone_normalization_percentile(self):
165
- """Fraction of CDF to use for normalzing spectrum when search for strong features."""
166
- return self._find_parameter_closest_wavelength("visp_solar_zone_normalization_percentile")
210
+ def solar_vignette_wavecal_fit_kwargs(self) -> dict[str, Any]:
211
+ """Define extra keyword arguments to pass to the wavelength calibration fitter."""
212
+ doc_dict = self._find_most_recent_past_value("visp_solar_vignette_wavecal_fit_kwargs")
213
+ rng_kwarg = dict()
214
+ fitting_method = doc_dict.get("method", False)
215
+ if fitting_method in ["basinhopping", "differential_evolution", "dual_annealing"]:
216
+ rng = randint(1, 1_000_000)
217
+ rng_kwarg["rng"] = rng
218
+
219
+ # The order here allows us to override `rng` in a parameter value
220
+ fit_kwargs = rng_kwarg | doc_dict
221
+ return fit_kwargs
167
222
 
168
223
  @property
169
- def solar_zone_rel_height(self):
170
- """Relative height at which to compute the width of strong spectral features."""
171
- return self._find_most_recent_past_value("visp_solar_zone_rel_height")
224
+ def solar_vignette_spectral_poly_fit_order(self) -> int:
225
+ """Define the order of spectral polynomial used when computing the full, 2D vignette signal."""
226
+ return self._find_most_recent_past_value("visp_solar_vignette_spectral_poly_fit_order")
227
+
228
+ @property
229
+ def solar_vignette_min_samples(self) -> float:
230
+ """Return fractional number of samples required for the RANSAC regressor used to fit the 2D vignette signal."""
231
+ return self._find_most_recent_past_value("visp_solar_vignette_min_samples")
232
+
233
+ @property
234
+ def wavecal_camera_lens_parameters(self) -> list[u.Quantity]:
235
+ r"""
236
+ Define the 2nd order polynomial coefficients for computing the total camera focal length as a function of wavelength.
237
+
238
+ The total focal length of the lens is :math:`f = a_0 + a_1\lambda + a_2\lambda^2` where this property is
239
+ :math:`[a_0, a_1, a_2]`
240
+ """
241
+ value_list = self._find_parameter_for_arm("visp_wavecal_camera_lens_parameters")
242
+ unit_list = [u.m, u.m / u.nm, u.m / u.nm**2]
243
+ return [v * u for v, u in zip(value_list, unit_list)]
244
+
245
+ @property
246
+ def wavecal_pixel_pitch_micron_per_pix(self) -> u.Quantity:
247
+ """Define the physical size of ViSP detector pixels."""
248
+ return (
249
+ self._find_most_recent_past_value("visp_wavecal_pixel_pitch_micron_per_pix")
250
+ * u.micron
251
+ / u.pix
252
+ )
253
+
254
+ @property
255
+ def wavecal_atlas_download_config(self) -> DownloadConfig:
256
+ """Define the `~solar_wavelength_calibration.DownloadConfig` used to grab the Solar atlas used for wavelength calibration."""
257
+ config_dict = self._find_most_recent_past_value("visp_wavecal_atlas_download_config")
258
+ return DownloadConfig.model_validate(config_dict)
259
+
260
+ @property
261
+ def wavecal_init_crval_guess_normalization_percentile(self) -> float | None:
262
+ """Define the CDF percentage used to normalize the Atlas to the input spectrum level when computing an initial CRVAL guess."""
263
+ return self._find_most_recent_past_value(
264
+ "visp_wavecal_init_crval_guess_normalization_percentile"
265
+ )
266
+
267
+ @property
268
+ def wavecal_init_resolving_power(self) -> int:
269
+ """Define the initial guess for ViSP resolving power in wavecal fits."""
270
+ return self._find_most_recent_past_value("visp_wavecal_init_resolving_power")
271
+
272
+ @property
273
+ def wavecal_init_straylight_fraction(self) -> float:
274
+ """Define the initial guess for straylight fraction in wavecal fits."""
275
+ return self._find_most_recent_past_value("visp_wavecal_init_straylight_fraction")
276
+
277
+ @property
278
+ def wavecal_init_opacity_factor(self) -> float:
279
+ """Define the initial guess for opacity factor in wavecal fits."""
280
+ return self._find_most_recent_past_value("visp_wavecal_init_opacity_factor")
172
281
 
173
282
  @property
174
283
  def polcal_spatial_median_filter_width_px(self) -> int:
@@ -0,0 +1,75 @@
1
+ """Buds for parsing the incident and reflected light angles of the ViSP spectrograph."""
2
+
3
+ from dkist_processing_common.models.flower_pot import SpilledDirt
4
+ from dkist_processing_common.models.flower_pot import Stem
5
+ from dkist_processing_common.models.task_name import TaskName
6
+ from dkist_processing_common.parsers.task import parse_header_ip_task_with_gains
7
+ from dkist_processing_common.parsers.unique_bud import TaskUniqueBud
8
+
9
+ from dkist_processing_visp.models.constants import VispBudName
10
+ from dkist_processing_visp.models.fits_access import VispMetadataKey
11
+ from dkist_processing_visp.parsers.visp_l0_fits_access import VispL0FitsAccess
12
+
13
+
14
+ def convert_grating_angle_to_incident_light_angle(grating_angle: float) -> float:
15
+ """Convert the raw header "grating angle" to the incident light angle expected by the solar wavecal library."""
16
+ return -1 * grating_angle
17
+
18
+
19
+ class IncidentLightAngleBud(TaskUniqueBud):
20
+ """Special case of `TaskUniqueBud` so we can apply the sign shift to the header incident light angle values."""
21
+
22
+ def __init__(self):
23
+ super().__init__(
24
+ constant_name=VispBudName.incident_light_angle_deg.value,
25
+ metadata_key=VispMetadataKey.grating_angle_deg,
26
+ ip_task_types=[TaskName.observe.value, TaskName.solar_gain.value],
27
+ task_type_parsing_function=parse_header_ip_task_with_gains,
28
+ )
29
+
30
+ def setter(self, fits_obj: VispL0FitsAccess) -> float | type[SpilledDirt]:
31
+ """Apply a sign flip to the raw header value for incident light angle."""
32
+ grating_angle = super().setter(fits_obj)
33
+
34
+ if grating_angle is SpilledDirt:
35
+ return grating_angle
36
+
37
+ return convert_grating_angle_to_incident_light_angle(grating_angle)
38
+
39
+
40
+ class ReflectedLightAngleBud(Stem):
41
+ """Bud that combines the incident light angle and arm position header values to compute the reflected light angle."""
42
+
43
+ key_to_petal_dict: dict[str, float]
44
+
45
+ def __init__(self):
46
+ super().__init__(stem_name=VispBudName.reflected_light_angle_deg.value)
47
+ self.ip_task_types = [
48
+ task.casefold() for task in [TaskName.observe.value, TaskName.solar_gain.value]
49
+ ]
50
+
51
+ def setter(self, fits_obj: VispL0FitsAccess) -> float | type[SpilledDirt]:
52
+ """
53
+ Compute the reflected light angle.
54
+
55
+ The reflected light angle is `-1 * fits_objs.grating_angle_deg + fits_obj.arm_position_deg`.
56
+ """
57
+ task = parse_header_ip_task_with_gains(fits_obj)
58
+
59
+ if task.casefold() in self.ip_task_types:
60
+ incident_light_angle = convert_grating_angle_to_incident_light_angle(
61
+ fits_obj.grating_angle_deg
62
+ )
63
+ arm_position = fits_obj.arm_position_deg
64
+ return incident_light_angle + arm_position
65
+
66
+ return SpilledDirt
67
+
68
+ def getter(self, key: str) -> float:
69
+ """Get the value for the reflected light angle and raise an error if it is not unique."""
70
+ value_set = set(self.key_to_petal_dict.values())
71
+ if len(value_set) > 1:
72
+ raise ValueError(
73
+ f"Multiple {self.stem_name} values found for key {key}. Values: {value_set}"
74
+ )
75
+ return value_set.pop()
@@ -32,6 +32,7 @@ class VispL0FitsAccess(L0FitsAccess):
32
32
  ):
33
33
  super().__init__(hdu=hdu, name=name, auto_squeeze=auto_squeeze)
34
34
 
35
+ self.arm_id: int = self.header[VispMetadataKey.arm_id]
35
36
  self.number_of_modulator_states: int = self.header[
36
37
  VispMetadataKey.number_of_modulator_states
37
38
  ]
@@ -39,6 +40,11 @@ class VispL0FitsAccess(L0FitsAccess):
39
40
  self.total_raster_steps: int = self.header[VispMetadataKey.total_raster_steps]
40
41
  self.modulator_state: int = self.header[VispMetadataKey.modulator_state]
41
42
  self.polarimeter_mode: str = self.header[VispMetadataKey.polarimeter_mode]
43
+ self.grating_angle_deg: float = self.header[VispMetadataKey.grating_angle_deg]
44
+ self.arm_position_deg: float = self.header[VispMetadataKey.arm_position_deg]
45
+ self.grating_constant_inverse_mm: float = self.header[
46
+ VispMetadataKey.grating_constant_inverse_mm
47
+ ]
42
48
  self.axis_1_type: str = self.header[VispMetadataKey.axis_1_type]
43
49
  self.axis_2_type: str = self.header[VispMetadataKey.axis_2_type]
44
50
  self.axis_3_type: str = self.header[VispMetadataKey.axis_3_type]
@@ -7,9 +7,11 @@ See :doc:`this page </geometric>` for more information.
7
7
  from typing import Generator
8
8
 
9
9
  import numpy as np
10
+ import peakutils
10
11
  import peakutils as pku
11
12
  import scipy.ndimage as spnd
12
13
  import scipy.optimize as spo
14
+ import scipy.signal as sps
13
15
  import skimage.exposure as skie
14
16
  import skimage.metrics as skim
15
17
  import skimage.morphology as skimo
@@ -33,7 +35,6 @@ from dkist_processing_visp.models.tags import VispTag
33
35
  from dkist_processing_visp.parsers.visp_l0_fits_access import VispL0FitsAccess
34
36
  from dkist_processing_visp.tasks.mixin.beam_access import BeamAccessMixin
35
37
  from dkist_processing_visp.tasks.mixin.corrections import CorrectionsMixin
36
- from dkist_processing_visp.tasks.mixin.line_zones import LineZonesMixin
37
38
  from dkist_processing_visp.tasks.visp_base import VispTaskBase
38
39
 
39
40
  __all__ = ["GeometricCalibration"]
@@ -44,7 +45,6 @@ class GeometricCalibration(
44
45
  BeamAccessMixin,
45
46
  CorrectionsMixin,
46
47
  QualityMixin,
47
- LineZonesMixin,
48
48
  ):
49
49
  """
50
50
  Task class for computing the spectral geometry. Geometry is represented by three quantities.
@@ -1074,11 +1074,11 @@ class GeometricCalibration(
1074
1074
  `compute_single_state_offset`.
1075
1075
  """
1076
1076
  zone_kwargs = {
1077
- "prominence": self.parameters.solar_zone_prominence,
1078
- "width": self.parameters.solar_zone_width,
1079
- "bg_order": self.parameters.solar_zone_bg_order,
1080
- "normalization_percentile": self.parameters.solar_zone_normalization_percentile,
1081
- "rel_height": self.parameters.solar_zone_rel_height,
1077
+ "prominence": self.parameters.geo_zone_prominence,
1078
+ "width": self.parameters.geo_zone_width,
1079
+ "bg_order": self.parameters.geo_zone_bg_order,
1080
+ "normalization_percentile": self.parameters.geo_zone_normalization_percentile,
1081
+ "rel_height": self.parameters.geo_zone_rel_height,
1082
1082
  }
1083
1083
  zones = self.compute_line_zones(array, **zone_kwargs)
1084
1084
  logger.info(f"Found {zones = }")
@@ -1088,6 +1088,114 @@ class GeometricCalibration(
1088
1088
 
1089
1089
  return mask
1090
1090
 
1091
+ def compute_line_zones(
1092
+ self,
1093
+ spec_2d: np.ndarray,
1094
+ prominence: float = 0.2,
1095
+ width: float = 2,
1096
+ bg_order: int = 22,
1097
+ normalization_percentile: int = 99,
1098
+ rel_height: float = 0.97,
1099
+ ) -> list[tuple[int, int]]:
1100
+ """
1101
+ Identify spectral regions around strong spectra features.
1102
+
1103
+ Parameters
1104
+ ----------
1105
+ spec_2d
1106
+ Data
1107
+
1108
+ prominence
1109
+ Zone prominence threshold used to identify strong spectral features
1110
+
1111
+ width
1112
+ Zone width
1113
+
1114
+ bg_order
1115
+ Order of polynomial fit used to remove continuum when identifying strong spectral features
1116
+
1117
+ normalization_percentile
1118
+ Compute this percentile of the data along a specified axis
1119
+
1120
+ rel_height
1121
+ The relative height at which the peak width is measured as a percentage of its prominence. E.g., 1.0 measures
1122
+ the peak width at the lowest contour line.
1123
+
1124
+ Returns
1125
+ -------
1126
+ regions
1127
+ List of indices defining the found spectral lines
1128
+
1129
+ """
1130
+ logger.info(
1131
+ f"Finding zones using {prominence=}, {width=}, {bg_order=}, {normalization_percentile=}, and {rel_height=}"
1132
+ )
1133
+ # Compute average along slit to improve signal. Line smearing isn't important here
1134
+ avg_1d = np.mean(spec_2d, axis=1)
1135
+
1136
+ # Convert to an emission spectrum and remove baseline continuum so peakutils has an easier time
1137
+ em_spec = -1 * avg_1d + avg_1d.max()
1138
+ em_spec /= np.nanpercentile(em_spec, normalization_percentile)
1139
+ baseline = peakutils.baseline(em_spec, bg_order)
1140
+ em_spec -= baseline
1141
+
1142
+ # Find indices of peaks
1143
+ peak_idxs = sps.find_peaks(em_spec, prominence=prominence, width=width)[0]
1144
+
1145
+ # Find the rough width based only on the height of the peak
1146
+ # rips and lips are the right and left borders of the region around the peak
1147
+ _, _, rips, lips = sps.peak_widths(em_spec, peak_idxs, rel_height=rel_height)
1148
+
1149
+ # Convert to ints so they can be used as indices
1150
+ rips = np.floor(rips).astype(int)
1151
+ lips = np.ceil(lips).astype(int)
1152
+
1153
+ # Remove any regions that are contained within another region
1154
+ ranges_to_remove = self.identify_overlapping_zones(rips, lips)
1155
+ rips = np.delete(rips, ranges_to_remove)
1156
+ lips = np.delete(lips, ranges_to_remove)
1157
+
1158
+ return list(zip(rips, lips))
1159
+
1160
+ @staticmethod
1161
+ def identify_overlapping_zones(rips: np.ndarray, lips: np.ndarray) -> list[int]:
1162
+ """
1163
+ Identify line zones that overlap with other zones. Any overlap greater than 1 pixel is flagged.
1164
+
1165
+ Parameters
1166
+ ----------
1167
+ rips
1168
+ Right borders of the region around the peak
1169
+
1170
+ lips
1171
+ Left borders of the region around the peak
1172
+
1173
+ Returns
1174
+ -------
1175
+ overlapping regions
1176
+ List indices into the input arrays that represent an overlapped region that can be removed
1177
+ """
1178
+ all_ranges = [np.arange(zmin, zmax) for zmin, zmax in zip(rips, lips)]
1179
+ ranges_to_remove = []
1180
+ for i in range(len(all_ranges)):
1181
+ target_range = all_ranges[i]
1182
+ for j in range(i + 1, len(all_ranges)):
1183
+ if (
1184
+ np.intersect1d(target_range, all_ranges[j]).size > 1
1185
+ ): # Allow for a single overlap just to be nice
1186
+ if target_range.size > all_ranges[j].size:
1187
+ ranges_to_remove.append(j)
1188
+ logger.info(
1189
+ f"Zone ({all_ranges[j][0]}, {all_ranges[j][-1]}) inside zone ({target_range[0]}, {target_range[-1]})"
1190
+ )
1191
+ else:
1192
+ ranges_to_remove.append(i)
1193
+ logger.info(
1194
+ f"Zone ({target_range[0]}, {target_range[-1]}) inside zone ({all_ranges[j][0]}, {all_ranges[j][-1]})"
1195
+ )
1196
+
1197
+ return ranges_to_remove
1198
+
1091
1199
  @staticmethod
1092
1200
  def high_pass_filter_array(array: np.ndarray) -> np.ndarray:
1093
1201
  """Perform a simple high-pass filter to accentuate narrow features (hairlines and spectra)."""