forked from IMAP-Science-Operations-Center/imap_processing
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
1301 lines (1104 loc) · 45.3 KB
/
Copy pathutils.py
File metadata and controls
1301 lines (1104 loc) · 45.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""IMAP-Hi utils functions."""
from __future__ import annotations
import logging
import re
from collections.abc import Generator, Iterable, Sequence
from dataclasses import dataclass
from enum import IntEnum
from pathlib import Path
from typing import IO, Any
import numpy as np
import pandas as pd
import xarray as xr
from numpy import typing as npt
from numpy.typing import NDArray
from imap_processing.cdf.imap_cdf_manager import ImapCdfAttributes
logger = logging.getLogger(__name__)
class HIAPID(IntEnum):
"""Create ENUM for apid."""
H45_MEMDMP = 740
H45_APP_NHK = 754
H45_SCI_CNT = 769
H45_SCI_DE = 770
H45_DIAG_FEE = 772
H90_MEMDMP = 804
H90_APP_NHK = 818
H90_SCI_CNT = 833
H90_SCI_DE = 834
H90_DIAG_FEE = 836
@property
def sensor(self) -> str:
"""
Define the sensor name attribute for this class.
Returns
-------
str
"45sensor" or "90sensor".
"""
return self.name[1:3] + "sensor"
@dataclass(frozen=True)
class HiConstants:
"""
Constants for Hi instrument.
Attributes
----------
DE_CLOCK_TICK_US : int
Duration of Direct Event clock tick in microseconds. This is the time
resolution of the Direct Event time tags. See IMAP-Hi Algorithm Document
Section 2.2.5 Annotated Direct Events for more details.
DE_CLOCK_TICK_S : float
Duration of Direct Event clock tick in seconds.
This is derived from DE_CLOCK_TICK_US.
HALF_CLOCK_TICK_S : float
Half of the Direct Event clock tick duration in seconds. This is derived
from DE_CLOCK_TICK_S.
TOF1_TICK_DUR : int
Duration of Time-of-Flight 1 clock tick in nanoseconds.
TOF2_TICK_DUR : int
Duration of Time-of-Flight 2 clock tick in nanoseconds.
TOF3_TICK_DUR : int
Duration of Time-of-Flight 3 clock tick in nanoseconds.
TOF1_BAD_VALUES : tuple[int]
Tuple of values indicating TOF1 does not contain a valid time.
TOF2_BAD_VALUES : tuple[int]
Tuple of values indicating TOF2 does not contain a valid time.
TOF3_BAD_VALUES : tuple[int]
Tuple of values indicating TOF3 does not contain a valid time.
STAT_FILTER_MIN_POINTINGS : int
Minimum number of Pointings required for statistical filters.
STAT_FILTER_0_THRESHOLD_FACTOR : float
Multiplier for median comparison in Statistical Filter 0.
Values exceeding threshold_factor * median are culled.
STAT_FILTER_0_TOF_AB_LIMIT_NS : int
Maximum abs(tof_ab) in nanoseconds for AB coincidences in Filter 0.
STAT_FILTER_1_CONSECUTIVE_SIGMA : float
Sigma multiplier for consecutive interval check in Filter 1.
STAT_FILTER_1_EXTREME_SIGMA : float
Sigma multiplier for extreme outlier check in Filter 1.
STAT_FILTER_1_MIN_CONSECUTIVE : int
Minimum consecutive intervals above threshold in Filter 1.
STAT_FILTER_2_MIN_EVENTS : int
Minimum events to form a pulse cluster in Filter 2.
STAT_FILTER_2_MAX_TIME_DELTA : float
Maximum time span in seconds for events to be considered clustered
in Filter 2.
STAT_FILTER_2_BIN_PADDING : int
Number of bins to add on each side of pulse angle range in Filter 2.
GAIN_CONFIG_HV_FIELDS : tuple[str, ...]
Detector high voltage monitor field names used to classify which gain
configuration a pointing is running.
EXCESS_BACKGROUND_COUNT_RATE : float
Constant rate offset (per second) to subtract from combined background
rates. Corrects for excess counts from the outer ESA during background
testing. Applied after summing individual background components.
"""
# TODO: read DE_CLOCK_TICK_US from
# instrument status summary later. This value
# is rarely change but want to be able to change
# it if needed. It stores information about how
# fast the time was ticking. It is in microseconds.
DE_CLOCK_TICK_US = 1999
DE_CLOCK_TICK_S = DE_CLOCK_TICK_US / 1e6
HALF_CLOCK_TICK_S = DE_CLOCK_TICK_S / 2
TOF1_TICK_DUR = 1 # 1 ns
TOF2_TICK_DUR = 1 # 1 ns
TOF3_TICK_DUR = 0.5 # 0.5 ns
# These values are stored in the TOF telemetry when the TOF timer
# does not have valid data. See IMAP-Hi Algorithm Document Section
# 2.2.5 Annotated Direct Events
TOF1_BAD_VALUES = (511,)
TOF2_BAD_VALUES = (511,)
TOF3_BAD_VALUES = (1023,)
# Statistical Filter tuning parameters
# See IMAP-Hi Algorithm Document Section 2.3.2.3
STAT_FILTER_MIN_POINTINGS = 4
STAT_FILTER_0_THRESHOLD_FACTOR = 1.5
STAT_FILTER_0_TOF_AB_LIMIT_NS = 15
STAT_FILTER_1_CONSECUTIVE_SIGMA = 1.8
STAT_FILTER_1_EXTREME_SIGMA = 5.0
STAT_FILTER_1_MIN_CONSECUTIVE = 3
STAT_FILTER_2_MIN_EVENTS = 6
STAT_FILTER_2_MAX_TIME_DELTA = 5000 * DE_CLOCK_TICK_S
STAT_FILTER_2_BIN_PADDING = 1
# Detector high voltage monitors used to classify which gain configuration
# a pointing is running. See the gain-configuration ancillary file
# (utils.load_gain_configuration()) and hi_l1b.classify_gain_configuration().
# Note "tof" is the raw CCSDS mnemonic name for the U-Can voltage monitor
# (see IMAP-Hi Algorithm Document Section 8, Level 0 Packet Definitions).
GAIN_CONFIG_HV_FIELDS = (
"pos_defl",
"neg_defl",
"tof", # aka U-Can
"mcp_f",
"mcp_b",
"cem_f",
"cem_bk_a",
"cem_bk_b",
)
# Background rate correction
# Constant offset to subtract from combined background rates to correct
# for excess counts from the outer ESA during background testing.
EXCESS_BACKGROUND_COUNT_RATE = 0.002 # per second
EXCESS_BACKGROUND_COUNT_RATE_UNC = 0.001
# ESAs 7, 8, 9 get an extra 0.0025/s uncertainty to account for possible
# unidentified additional background in these ESA steps.
UPPER_ESA_EXTRA_BACKGROUND_UNC = xr.DataArray(
np.array([0.0025, 0.0025, 0.0055]),
dims=["esa_energy_step"],
coords={"esa_energy_step": np.array([7, 8, 9], dtype=int)},
)
def parse_sensor_number(full_string: str) -> int:
"""
Parse the sensor number from a string.
This function uses regex to match any portion of the input string
containing "(45|90)sensor".
Parameters
----------
full_string : str
A string containing sensor number.
Returns
-------
sensor_number : int
The integer sensor number. For IMAP-Hi this is 45 or 90.
"""
regex_str = r".*(?P<sensor_num>(45|90))sensor.*?"
match = re.match(regex_str, full_string)
if match is None:
raise ValueError(
f"String 'sensor(45|90)' not found in input string: '{full_string}'"
)
return int(match["sensor_num"])
def load_gain_configuration(path: str | Path | IO[str]) -> pd.DataFrame:
"""
Load the detector gain configuration ancillary CSV file.
Each row corresponds to one (config_id, esa_energy_step) combination and
gives that step's geometric factor. The detector high voltage nominal/
tolerance ("{field}_v"/"{field}_delta_v") columns are constant across
esa_energy_step within a config_id (see HiConstants.GAIN_CONFIG_HV_FIELDS
for the monitored fields), so they only need to be specified on the first
esa_energy_step row of each config_id group -- subsequent rows are
forward-filled.
Parameters
----------
path : str or pathlib.Path
Location of the gain configuration ancillary CSV file. Anything
accepted by ``pandas.read_csv`` (e.g. a file-like object) also works.
Returns
-------
pandas.DataFrame
DataFrame indexed by (config_id, esa_energy_step), with columns
"geometric_factor" and "{field}_v"/"{field}_delta_v" for each field
in HiConstants.GAIN_CONFIG_HV_FIELDS.
Raises
------
ValueError
If geometric_factor is null for any row, if {field}_v/{field}_delta_v
values are missing for a config_id's first esa_energy_step row, or if
they are inconsistent across esa_energy_step within a config_id.
"""
df = pd.read_csv(path, index_col=["config_id", "esa_energy_step"], comment="#")
hv_columns = [
f"{field}{suffix}"
for field in HiConstants.GAIN_CONFIG_HV_FIELDS
for suffix in ("_v", "_delta_v")
]
df[hv_columns] = df.groupby(level="config_id")[hv_columns].ffill()
if df["geometric_factor"].isna().any():
null_rows = df.index[df["geometric_factor"].isna()].tolist()
raise ValueError(f"Null geometric_factor value(s) found for rows: {null_rows}.")
# Validate {field}_v/{field}_delta_v columns are non-null and consistent
# across esa_energy_step for each config_id. This catches a missing first
# row (forward-fill leaves NaN) or an authoring mistake (inconsistent
# values).
for config_id, group in df.groupby(level="config_id"):
for col in hv_columns:
if group[col].isna().any():
raise ValueError(
f"Missing {col} value(s) for config_id={config_id}. The "
f"first esa_energy_step row for each config_id must "
f"specify voltage and tolerance values for every field."
)
if group[col].nunique() > 1:
raise ValueError(
f"Inconsistent {col} values across esa_energy_step for "
f"config_id={config_id}: {group[col].unique().tolist()}. "
f"Voltage and tolerance values must be identical across "
f"all esa_energy_step rows for a config_id."
)
return df
def full_dataarray(
name: str,
attrs: dict,
coords: dict[str, xr.DataArray] | None = None,
shape: int | Sequence[int] | None = None,
fill_value: float | None = None,
) -> xr.DataArray:
"""
Generate an empty xarray.DataArray with appropriate attributes.
Data in DataArray are filled with FILLVAL defined in attributes
retrieved from ATTR_MGR with shape matching coordinates defined by
dims or overridden by optional `shape` input.
Parameters
----------
name : str
Variable name.
attrs : dict
CDF variable attributes. Usually retrieved from ImapCdfAttributes.
coords : dict, Optional
Coordinate variables for the Dataset. This function will extract the
sizes of each dimension defined by the attributes dictionary to determine
the size of the DataArray to be created.
shape : int or tuple, Optional
Shape of ndarray data array to instantiate in the xarray.DataArray. If
shape is provided, the DataArray created will have this shape regardless
of whether coordinates are provided or not.
fill_value : Optional, float
Override the fill value that the DataArray will be filled with. If not
supplied, the "FILLVAL" value from `attrs` will be used.
Returns
-------
data_array : xarray.DataArray
Meeting input specifications.
"""
_attrs = attrs.copy()
dtype = _attrs.pop("dtype", None)
# extract dims keyword argument from DEPEND_i attributes
dims = [v for k, v in sorted(_attrs.items()) if k.startswith("DEPEND")]
# define shape of the ndarray to generate
if shape is None:
shape = [coords[k].data.size for k in dims] # type: ignore
if hasattr(shape, "__len__") and len(shape) > len(dims):
dims.append("")
if fill_value is None:
fill_value = _attrs["FILLVAL"]
data_array = xr.DataArray(
np.full(shape, fill_value, dtype=dtype),
name=name,
dims=dims,
attrs=_attrs,
)
return data_array
def create_dataset_variables(
variable_names: list[str],
variable_shape: int | Sequence[int] | None = None,
coords: dict[str, xr.DataArray] | None = None,
fill_value: float | None = None,
att_manager_lookup_str: str = "{0}",
) -> dict[str, xr.DataArray]:
"""
Instantiate new `xarray.DataArray` variables.
Variable attributes are retrieved from CdfAttributeManager.
Parameters
----------
variable_names : list[str]
List of variable names to create.
variable_shape : int or Sequence of int, Optional
Shape of the new variables data ndarray. If not provided the shape will
attempt to be derived from the coords dictionary.
coords : dict, Optional
Coordinate variables for the Dataset. If `variable_shape` is not provided
the dataset variables created will use this dictionary along with variable
attributes from the CdfAttributeManager to determine the shapes of the
dataset variables created.
fill_value : Optional, float
Value to fill the new variables data arrays with. If not supplied,
the fill value is pulled from the CDF variable attributes "FILLVAL"
attribute.
att_manager_lookup_str : str
String defining how to build the string passed to the
CdfAttributeManager in order to retrieve the CdfAttributes for each
variable. The string passed to CdfAttributeManager will be the result
of calling the `str.format()` method on this input string with the
variable name from `variable_names` as the single argument. Defaults to
"{0}".
Returns
-------
new_variables : dict[str, xarray.DataArray]
Dictionary of new xarray.DataArray variables.
"""
attr_mgr = ImapCdfAttributes()
attr_mgr.add_instrument_global_attrs("hi")
attr_mgr.add_instrument_variable_attrs(instrument="hi", level=None)
new_variables = dict()
for var in variable_names:
attrs = attr_mgr.get_variable_attributes(
att_manager_lookup_str.format(var), check_schema=False
)
new_variables[var] = full_dataarray(
var, attrs, shape=variable_shape, coords=coords, fill_value=fill_value
)
return new_variables
class CoincidenceBitmap(IntEnum):
"""IntEnum class for coincidence type bitmap values."""
A = 2**3
B = 2**2
C1 = 2**1
C2 = 2**0
@staticmethod
def detector_hit_str_to_int(detector_hit_str: str) -> int:
"""
Convert a detector hit string to a coincidence type integer value.
A detector hit string is a string containing all detectors that were hit
for a direct event. Possible detectors include: [A, B, C1, C2]. Converting
the detector hit string to a coincidence type integer value involves
summing the coincidence bitmap value for each detector hit. e.g. "AC1C2"
results in 2**3 + 2**1 + 2**0 = 11.
Parameters
----------
detector_hit_str : str
The string containing the set of detectors hit.
e.g. "AC1C2".
Returns
-------
coincidence_type : int
The integer value of the coincidence type.
"""
# Join all detector names with a pipe for use with regex
pattern = r"|".join(c.name for c in CoincidenceBitmap)
matches = re.findall(pattern, detector_hit_str)
# Sum the integer value assigned to the detector name for each match
return sum(CoincidenceBitmap[m] for m in matches)
class EsaEnergyStepLookupTable:
"""Class for holding a esa_step to esa_energy lookup table."""
def __init__(self) -> None:
self.df = pd.DataFrame(
{
"start_met": pd.Series(dtype="float64"),
"end_met": pd.Series(dtype="float64"),
"esa_step": pd.Series(dtype="int64"),
"esa_energy_step": pd.Series(dtype="int64"),
}
)
self._indexed = False
# Get the FILLVAL from the CDF attribute manager that will be returned
# for queries without matches
attr_mgr = ImapCdfAttributes()
attr_mgr.add_instrument_global_attrs("hi")
attr_mgr.add_instrument_variable_attrs(instrument="hi", level=None)
var_attrs = attr_mgr.get_variable_attributes(
"hi_de_esa_energy_step", check_schema=False
)
self._fillval = var_attrs["FILLVAL"]
self._esa_energy_step_dtype = var_attrs["dtype"]
def add_entry(
self, start_met: float, end_met: float, esa_step: int, esa_energy_step: int
) -> None:
"""
Add a single entry to the lookup table.
Parameters
----------
start_met : float
Start mission elapsed time of the time range.
end_met : float
End mission elapsed time of the time range.
esa_step : int
ESA step value.
esa_energy_step : int
ESA energy step value to be stored.
"""
new_row = pd.DataFrame(
{
"start_met": [start_met],
"end_met": [end_met],
"esa_step": [esa_step],
"esa_energy_step": [esa_energy_step],
}
)
self.df = pd.concat([self.df, new_row], ignore_index=True)
self._indexed = False
def _ensure_indexed(self) -> None:
"""
Create index for faster queries if not already done.
Notes
-----
This method sorts the internal DataFrame by start_met and esa_step
for improved query performance.
"""
if not self._indexed:
# Sort by start_met and esa_step for better query performance
self.df = self.df.sort_values(["start_met", "esa_step"]).reset_index(
drop=True
)
self._indexed = True
def query(
self,
query_met: float | Iterable[float],
esa_step: int | Iterable[float],
) -> float | np.ndarray:
"""
Query MET(s) and esa_step(s) to retrieve esa_energy_step(s).
Parameters
----------
query_met : float or array_like
Mission elapsed time value(s) to query.
Can be a single float or array-like of floats.
esa_step : int or array_like
ESA step value(s) to match. Can be a single int or array-like of ints.
Must be same type (scalar or array-like) as query_met.
Returns
-------
float or numpy.ndarray
- If inputs are scalars: returns float (esa_energy_step)
- If inputs are array-like: returns numpy array of esa_energy_steps
with same length as inputs.
Contains FILLVAL for queries with no matches.
Raises
------
ValueError
If one input is scalar and the other is array-like, or if both are
array-like but have different lengths.
Notes
-----
If multiple entries match a query, returns the first match found.
"""
self._ensure_indexed()
# Check if inputs are scalars
is_scalar_met = np.isscalar(query_met)
is_scalar_step = np.isscalar(esa_step)
# Check for mismatched input types
if is_scalar_met != is_scalar_step:
raise ValueError(
"query_met and esa_step must both be scalars or both be array-like"
)
# Convert to arrays for uniform processing
query_mets = np.atleast_1d(query_met)
esa_steps = np.atleast_1d(esa_step)
# Ensure both arrays have the same shape
if query_mets.shape != esa_steps.shape:
raise ValueError(
"query_met and esa_step must have the same "
"length when both are array-like"
)
results = np.full_like(query_mets, self._fillval)
# Lookup esa_energy_steps for queries
for i, (qm, es) in enumerate(zip(query_mets, esa_steps, strict=False)):
mask = (
(self.df["start_met"] <= qm)
& (self.df["end_met"] >= qm)
& (self.df["esa_step"] == es)
)
matches = self.df[mask]
if not matches.empty:
results[i] = matches["esa_energy_step"].iloc[0]
# Return scalar for scalar inputs, array for array inputs
if is_scalar_met and is_scalar_step:
return results.astype(self._esa_energy_step_dtype)[0]
else:
return results.astype(self._esa_energy_step_dtype)
class GainConfigLookupTable:
"""Class for holding a MET range to gain configuration (config_id) LUT."""
# Sentinel returned for MET values that don't fall within any segment
# matching the pointing's classified gain configuration (e.g. the
# configuration could not be classified for the pointing, or this
# particular segment doesn't match it -- such as during a mid-pointing
# gain test). This is purely an internal L1B processing detail, not tied
# to any CDF variable's FILLVAL.
NO_MATCH = -1
def __init__(self) -> None:
self.df = pd.DataFrame(
{
"start_met": pd.Series(dtype="float64"),
"end_met": pd.Series(dtype="float64"),
"config_id": pd.Series(dtype="int64"),
}
)
self._indexed = False
def add_entry(self, start_met: float, end_met: float, config_id: int) -> None:
"""
Add a single entry to the lookup table.
Parameters
----------
start_met : float
Start mission elapsed time of the time range.
end_met : float
End mission elapsed time of the time range.
config_id : int
Gain configuration id that applies over this time range.
"""
new_row = pd.DataFrame(
{
"start_met": [start_met],
"end_met": [end_met],
"config_id": [config_id],
}
)
self.df = pd.concat([self.df, new_row], ignore_index=True)
self._indexed = False
def _ensure_indexed(self) -> None:
"""Sort the internal DataFrame by start_met for faster queries."""
if not self._indexed:
self.df = self.df.sort_values("start_met").reset_index(drop=True)
self._indexed = True
def query(self, query_met: float | Iterable[float]) -> int | np.ndarray:
"""
Query MET(s) to retrieve the matching gain configuration id(s).
Parameters
----------
query_met : float or array_like
Mission elapsed time value(s) to query.
Returns
-------
int or numpy.ndarray
- If input is scalar: returns int (config_id or NO_MATCH).
- If input is array-like: returns numpy array of config_ids with
the same length as the input, containing NO_MATCH for queries
with no matching entry.
Notes
-----
If multiple entries match a query, returns the first match found.
"""
self._ensure_indexed()
is_scalar_met = np.isscalar(query_met)
query_mets = np.atleast_1d(query_met)
results = np.full(query_mets.shape, self.NO_MATCH, dtype=np.int64)
if self.df.empty:
logger.debug(
"GainConfigLookupTable is empty (no matching gain "
"configuration segments); all %d queried MET value(s) "
"return NO_MATCH.",
query_mets.size,
)
else:
starts = self.df["start_met"].to_numpy()
ends = self.df["end_met"].to_numpy()
config_ids = self.df["config_id"].to_numpy()
for start, end, cfg in zip(starts, ends, config_ids, strict=False):
mask = (
(results == self.NO_MATCH)
& (query_mets >= start)
& (query_mets <= end)
)
results[mask] = cfg
n_no_match = int(np.sum(results == self.NO_MATCH))
if n_no_match > 0:
logger.debug(
"%d of %d queried MET value(s) fell outside all gain "
"configuration segments and returned NO_MATCH (likely "
"gain test intervals or time outside HVSCI segments).",
n_no_match,
query_mets.size,
)
return int(results[0]) if is_scalar_met else results
class _BaseConfigAccessor:
"""
Base class for configuration DataFrame accessors.
Provides common functionality for validating and processing configuration
DataFrames with coincidence types and TOF windows.
Parameters
----------
pandas_obj : pandas.DataFrame
Object to run validation and use accessor functions on.
"""
# Subclasses must define these
index_columns: tuple[str, ...]
required_columns: tuple[str, ...]
tof_detector_pairs = ("ab", "ac1", "bc1", "c1c2")
def __init__(self, pandas_obj: pd.DataFrame) -> None:
self._validate(pandas_obj)
self._obj = pandas_obj
self._add_coincidence_values_column()
def _validate(self, df: pd.DataFrame) -> None:
"""
Validate the current configuration.
Parameters
----------
df : pandas.DataFrame
Object to validate.
Raises
------
AttributeError : If the dataframe does not pass validation.
"""
for index_name in self.index_columns:
if index_name not in df.index.names:
raise AttributeError(
f"Required index {index_name} not present in dataframe."
)
# Verify that the Dataframe has all the required columns
for col in self.required_columns:
if col not in df.columns:
raise AttributeError(f"Required column {col} not present in dataframe.")
def _add_coincidence_values_column(self) -> None:
"""Generate and add the coincidence_type_values column to the dataframe."""
# Add a column that consists of the coincidence type strings converted
# to integer values
self._obj["coincidence_type_values"] = self._obj.apply(
lambda row: tuple(
CoincidenceBitmap.detector_hit_str_to_int(entry)
for entry in row["coincidence_type_list"]
),
axis=1,
)
@property
def calibration_product_numbers(self) -> npt.NDArray[np.int_]:
"""
Get the calibration product numbers from the current configuration.
Returns
-------
cal_prod_numbers : numpy.ndarray
Array of calibration product numbers from the configuration.
These are sorted in ascending order and can be arbitrary integers.
"""
return (
self._obj.index.get_level_values("calibration_prod")
.unique()
.sort_values()
.values
)
@pd.api.extensions.register_dataframe_accessor("cal_prod_config")
class CalibrationProductConfig(_BaseConfigAccessor):
"""Register custom accessor for calibration product configuration DataFrames."""
index_columns = (
"calibration_prod",
"esa_energy_step",
)
required_columns = (
"coincidence_type_list",
*[
f"tof_{det_pair}_{limit}"
for det_pair in _BaseConfigAccessor.tof_detector_pairs
for limit in ["low", "high"]
],
)
@classmethod
def from_csv(cls, path: str | Path | IO[str]) -> pd.DataFrame:
"""
Read calibration product configuration CSV file into a pandas.DataFrame.
Parameters
----------
path : str or pathlib.Path or file-like object
Location of the calibration product configuration CSV file.
Returns
-------
dataframe : pandas.DataFrame
Validated calibration product configuration DataFrame with
coincidence_type_values column added.
"""
df = pd.read_csv(
path,
index_col=cls.index_columns,
converters={"coincidence_type_list": lambda s: tuple(s.split("|"))},
comment="#",
)
# Trigger the accessor to run validation and add coincidence_type_values
_ = df.cal_prod_config.number_of_products
return df
@property
def number_of_products(self) -> int:
"""
Get the number of calibration products in the current configuration.
Returns
-------
number_of_products : int
The maximum number of calibration products defined in the list of
calibration product definitions.
"""
return len(self._obj.index.unique(level="calibration_prod"))
@pd.api.extensions.register_dataframe_accessor("background_config")
class BackgroundConfig(_BaseConfigAccessor):
"""Register custom accessor for background configuration DataFrames."""
index_columns = (
"calibration_prod",
"background_index",
"esa_energy_step",
)
# Columns that must be consistent across esa_energy_step for each
# (calibration_prod, background_index) combination
tof_columns = tuple(
f"tof_{det_pair}_{limit}"
for det_pair in _BaseConfigAccessor.tof_detector_pairs
for limit in ["low", "high"]
)
required_columns = (
"coincidence_type_list",
*tof_columns,
"scaling_factor",
"uncertainty",
)
def _validate(self, df: pd.DataFrame) -> None:
"""
Validate the background configuration.
Extends base validation to verify:
1. TOF windows and coincidence types are consistent across esa_energy_step
for each (calibration_prod, background_index) combination.
2. All required columns (coincidence_type_list, TOF windows, scaling_factor,
uncertainty) are non-null for every row.
Parameters
----------
df : pandas.DataFrame
DataFrame to validate.
Raises
------
AttributeError
If required columns or index are missing.
ValueError
If TOF windows or coincidence types differ across ESA energy steps,
or if any required values are null/missing.
"""
super()._validate(df)
# Check that all required columns have non-null values for every row
# This catches cases where forward-fill didn't populate values
# (e.g., missing first row in a group) or where scaling_factor/uncertainty
# are missing for some ESA steps
required_non_null = [
"coincidence_type_list",
*self.tof_columns,
"scaling_factor",
"uncertainty",
]
for col in required_non_null:
null_mask = df[col].isna()
if null_mask.any():
# Get the index values of rows with null values
null_rows = df.index[null_mask].tolist()
raise ValueError(
f"Null values found in required column '{col}' for rows: "
f"{null_rows}. All background configuration rows must have "
f"non-null values for coincidence_type_list, TOF windows, "
f"scaling_factor, and uncertainty."
)
# Columns that must be consistent across ESA steps
consistency_columns = [*self.tof_columns, "coincidence_type_list"]
# Group by (calibration_prod, background_index) and check consistency
grouped = df.groupby(level=["calibration_prod", "background_index"])
for (cal_prod, bg_idx), group in grouped:
for col in consistency_columns:
unique_values = group[col].unique()
if len(unique_values) > 1:
raise ValueError(
f"Inconsistent {col} values across esa_energy_step for "
f"calibration_prod={cal_prod}, background_index={bg_idx}. "
f"Found values: {unique_values.tolist()}. "
f"TOF windows and coincidence types must be identical "
f"across all ESA energy steps."
)
def get_tof_config(self) -> pd.DataFrame:
"""
Get TOF window configuration with one row per background.
Returns one row per (calibration_prod, background_index) combination.
Since TOF windows are validated to be consistent across esa_energy_step,
this returns the first row for each (calibration_prod, background_index)
combination containing only the TOF-related columns.
Returns
-------
tof_config : pandas.DataFrame
DataFrame indexed by (calibration_prod, background_index) with
coincidence_type_list, coincidence_type_values, and TOF window columns.
"""
tof_cols = [
"coincidence_type_list",
"coincidence_type_values",
*self.tof_columns,
]
return self._obj.groupby(level=["calibration_prod", "background_index"])[
tof_cols
].first()
@classmethod
def from_csv(cls, path: str | Path | IO[str]) -> pd.DataFrame:
"""
Read background configuration CSV file into a pandas.DataFrame.
TOF window columns and coincidence_type_list can be specified only on
the first row of each (calibration_prod, background_index) group and
will be forward-filled to subsequent rows. This reduces redundancy in
the CSV file since these values must be identical across ESA energy
steps.
Parameters
----------
path : str or pathlib.Path or file-like object
Location of the background configuration CSV file.
Returns
-------
dataframe : pandas.DataFrame
Validated background configuration DataFrame with
coincidence_type_values column added.
"""
def parse_coincidence_list(s: str) -> tuple | None:
"""
Parse coincidence type list, returning None for empty strings.
Parameters
----------
s : str
Pipe-delimited string of coincidence types.
Returns
-------
tuple or None
Tuple of coincidence type strings, or None if input is empty.
"""
if pd.isna(s) or s == "":
return None
return tuple(s.split("|"))
df = pd.read_csv(
path,
index_col=cls.index_columns,
converters={"coincidence_type_list": parse_coincidence_list},
comment="#",
)
# Forward-fill TOF columns and coincidence_type_list within each
# (calibration_prod, background_index) group. This allows the CSV to
# specify these values only on the first row of each group.
fill_columns = ["coincidence_type_list", *cls.tof_columns]
df[fill_columns] = df.groupby(level=["calibration_prod", "background_index"])[
fill_columns
].ffill()
# Trigger the accessor to run validation and add coincidence_type_values
_ = df.background_config.calibration_product_numbers
return df
def get_tof_window_mask(
de_ds: xr.Dataset,
tof_windows: dict[str, tuple[float, float]],
tof_fill_vals: dict[str, float],
) -> NDArray[np.bool_]:
"""
Generate mask indicating which DEs pass TOF window checks.
An event passes the TOF window check for a given detector pair if its TOF value
is within the (low, high) bounds OR equals the fill value (indicating the detector
pair was not hit).
Parameters
----------
de_ds : xarray.Dataset
Direct Event Dataset with TOF variables (tof_ab, tof_ac1, tof_bc1, tof_c1c2).
tof_windows : dict[str, tuple[float, float]]