imap-processing 0.17.0__py3-none-any.whl → 0.19.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.

Potentially problematic release.


This version of imap-processing might be problematic. Click here for more details.

Files changed (141) hide show
  1. imap_processing/_version.py +2 -2
  2. imap_processing/ancillary/ancillary_dataset_combiner.py +161 -1
  3. imap_processing/ccsds/excel_to_xtce.py +12 -0
  4. imap_processing/cdf/config/imap_codice_global_cdf_attrs.yaml +6 -6
  5. imap_processing/cdf/config/imap_codice_l1a_variable_attrs.yaml +312 -274
  6. imap_processing/cdf/config/imap_codice_l1b_variable_attrs.yaml +39 -28
  7. imap_processing/cdf/config/imap_codice_l2_variable_attrs.yaml +1048 -183
  8. imap_processing/cdf/config/imap_constant_attrs.yaml +4 -2
  9. imap_processing/cdf/config/imap_glows_l1b_variable_attrs.yaml +12 -0
  10. imap_processing/cdf/config/imap_hi_global_cdf_attrs.yaml +5 -0
  11. imap_processing/cdf/config/imap_hit_global_cdf_attrs.yaml +10 -4
  12. imap_processing/cdf/config/imap_hit_l1a_variable_attrs.yaml +163 -100
  13. imap_processing/cdf/config/imap_hit_l2_variable_attrs.yaml +4 -4
  14. imap_processing/cdf/config/imap_ialirt_l1_variable_attrs.yaml +97 -54
  15. imap_processing/cdf/config/imap_idex_l2a_variable_attrs.yaml +33 -4
  16. imap_processing/cdf/config/imap_idex_l2b_variable_attrs.yaml +44 -44
  17. imap_processing/cdf/config/imap_idex_l2c_variable_attrs.yaml +77 -61
  18. imap_processing/cdf/config/imap_lo_global_cdf_attrs.yaml +30 -0
  19. imap_processing/cdf/config/imap_lo_l1a_variable_attrs.yaml +4 -15
  20. imap_processing/cdf/config/imap_lo_l1c_variable_attrs.yaml +189 -98
  21. imap_processing/cdf/config/imap_mag_global_cdf_attrs.yaml +99 -2
  22. imap_processing/cdf/config/imap_mag_l1c_variable_attrs.yaml +24 -1
  23. imap_processing/cdf/config/imap_ultra_global_cdf_attrs.yaml +60 -0
  24. imap_processing/cdf/config/imap_ultra_l1b_variable_attrs.yaml +99 -11
  25. imap_processing/cdf/config/imap_ultra_l1c_variable_attrs.yaml +50 -7
  26. imap_processing/cli.py +121 -44
  27. imap_processing/codice/codice_l1a.py +165 -77
  28. imap_processing/codice/codice_l1b.py +1 -1
  29. imap_processing/codice/codice_l2.py +118 -19
  30. imap_processing/codice/constants.py +1217 -1089
  31. imap_processing/decom.py +1 -4
  32. imap_processing/ena_maps/ena_maps.py +32 -25
  33. imap_processing/ena_maps/utils/naming.py +8 -2
  34. imap_processing/glows/ancillary/imap_glows_exclusions-by-instr-team_20250923_v002.dat +10 -0
  35. imap_processing/glows/ancillary/imap_glows_map-of-excluded-regions_20250923_v002.dat +393 -0
  36. imap_processing/glows/ancillary/imap_glows_map-of-uv-sources_20250923_v002.dat +593 -0
  37. imap_processing/glows/ancillary/imap_glows_pipeline_settings_20250923_v002.json +54 -0
  38. imap_processing/glows/ancillary/imap_glows_suspected-transients_20250923_v002.dat +10 -0
  39. imap_processing/glows/l1b/glows_l1b.py +99 -9
  40. imap_processing/glows/l1b/glows_l1b_data.py +350 -38
  41. imap_processing/glows/l2/glows_l2.py +11 -0
  42. imap_processing/hi/hi_l1a.py +124 -3
  43. imap_processing/hi/hi_l1b.py +154 -71
  44. imap_processing/hi/hi_l2.py +84 -51
  45. imap_processing/hi/utils.py +153 -8
  46. imap_processing/hit/l0/constants.py +3 -0
  47. imap_processing/hit/l0/decom_hit.py +5 -8
  48. imap_processing/hit/l1a/hit_l1a.py +375 -45
  49. imap_processing/hit/l1b/constants.py +5 -0
  50. imap_processing/hit/l1b/hit_l1b.py +61 -131
  51. imap_processing/hit/l2/constants.py +1 -1
  52. imap_processing/hit/l2/hit_l2.py +10 -11
  53. imap_processing/ialirt/calculate_ingest.py +219 -0
  54. imap_processing/ialirt/constants.py +32 -1
  55. imap_processing/ialirt/generate_coverage.py +201 -0
  56. imap_processing/ialirt/l0/ialirt_spice.py +5 -2
  57. imap_processing/ialirt/l0/parse_mag.py +337 -29
  58. imap_processing/ialirt/l0/process_hit.py +5 -3
  59. imap_processing/ialirt/l0/process_swapi.py +41 -25
  60. imap_processing/ialirt/l0/process_swe.py +23 -7
  61. imap_processing/ialirt/process_ephemeris.py +70 -14
  62. imap_processing/ialirt/utils/constants.py +22 -16
  63. imap_processing/ialirt/utils/create_xarray.py +42 -19
  64. imap_processing/idex/idex_constants.py +1 -5
  65. imap_processing/idex/idex_l0.py +2 -2
  66. imap_processing/idex/idex_l1a.py +2 -3
  67. imap_processing/idex/idex_l1b.py +2 -3
  68. imap_processing/idex/idex_l2a.py +130 -4
  69. imap_processing/idex/idex_l2b.py +313 -119
  70. imap_processing/idex/idex_utils.py +1 -3
  71. imap_processing/lo/l0/lo_apid.py +1 -0
  72. imap_processing/lo/l0/lo_science.py +25 -24
  73. imap_processing/lo/l1a/lo_l1a.py +44 -0
  74. imap_processing/lo/l1b/lo_l1b.py +3 -3
  75. imap_processing/lo/l1c/lo_l1c.py +116 -50
  76. imap_processing/lo/l2/lo_l2.py +29 -29
  77. imap_processing/lo/lo_ancillary.py +55 -0
  78. imap_processing/lo/packet_definitions/lo_xtce.xml +5359 -106
  79. imap_processing/mag/constants.py +1 -0
  80. imap_processing/mag/l1a/mag_l1a.py +1 -0
  81. imap_processing/mag/l1a/mag_l1a_data.py +26 -0
  82. imap_processing/mag/l1b/mag_l1b.py +3 -2
  83. imap_processing/mag/l1c/interpolation_methods.py +14 -15
  84. imap_processing/mag/l1c/mag_l1c.py +23 -6
  85. imap_processing/mag/l1d/__init__.py +0 -0
  86. imap_processing/mag/l1d/mag_l1d.py +176 -0
  87. imap_processing/mag/l1d/mag_l1d_data.py +725 -0
  88. imap_processing/mag/l2/__init__.py +0 -0
  89. imap_processing/mag/l2/mag_l2.py +25 -20
  90. imap_processing/mag/l2/mag_l2_data.py +199 -130
  91. imap_processing/quality_flags.py +28 -2
  92. imap_processing/spice/geometry.py +101 -36
  93. imap_processing/spice/pointing_frame.py +1 -7
  94. imap_processing/spice/repoint.py +29 -2
  95. imap_processing/spice/spin.py +32 -8
  96. imap_processing/spice/time.py +60 -19
  97. imap_processing/swapi/l1/swapi_l1.py +10 -4
  98. imap_processing/swapi/l2/swapi_l2.py +66 -24
  99. imap_processing/swapi/swapi_utils.py +1 -1
  100. imap_processing/swe/l1b/swe_l1b.py +3 -6
  101. imap_processing/ultra/constants.py +28 -3
  102. imap_processing/ultra/l0/decom_tools.py +15 -8
  103. imap_processing/ultra/l0/decom_ultra.py +35 -11
  104. imap_processing/ultra/l0/ultra_utils.py +102 -12
  105. imap_processing/ultra/l1a/ultra_l1a.py +26 -6
  106. imap_processing/ultra/l1b/cullingmask.py +6 -3
  107. imap_processing/ultra/l1b/de.py +122 -26
  108. imap_processing/ultra/l1b/extendedspin.py +29 -2
  109. imap_processing/ultra/l1b/lookup_utils.py +424 -50
  110. imap_processing/ultra/l1b/quality_flag_filters.py +23 -0
  111. imap_processing/ultra/l1b/ultra_l1b_culling.py +356 -5
  112. imap_processing/ultra/l1b/ultra_l1b_extended.py +534 -90
  113. imap_processing/ultra/l1c/helio_pset.py +127 -7
  114. imap_processing/ultra/l1c/l1c_lookup_utils.py +256 -0
  115. imap_processing/ultra/l1c/spacecraft_pset.py +90 -15
  116. imap_processing/ultra/l1c/ultra_l1c.py +6 -0
  117. imap_processing/ultra/l1c/ultra_l1c_culling.py +85 -0
  118. imap_processing/ultra/l1c/ultra_l1c_pset_bins.py +446 -341
  119. imap_processing/ultra/l2/ultra_l2.py +0 -1
  120. imap_processing/ultra/utils/ultra_l1_utils.py +40 -3
  121. imap_processing/utils.py +3 -4
  122. {imap_processing-0.17.0.dist-info → imap_processing-0.19.0.dist-info}/METADATA +3 -3
  123. {imap_processing-0.17.0.dist-info → imap_processing-0.19.0.dist-info}/RECORD +126 -126
  124. imap_processing/idex/idex_l2c.py +0 -250
  125. imap_processing/spice/kernels.py +0 -187
  126. imap_processing/ultra/lookup_tables/Angular_Profiles_FM45_LeftSlit.csv +0 -526
  127. imap_processing/ultra/lookup_tables/Angular_Profiles_FM45_RightSlit.csv +0 -526
  128. imap_processing/ultra/lookup_tables/Angular_Profiles_FM90_LeftSlit.csv +0 -526
  129. imap_processing/ultra/lookup_tables/Angular_Profiles_FM90_RightSlit.csv +0 -524
  130. imap_processing/ultra/lookup_tables/EgyNorm.mem.csv +0 -32769
  131. imap_processing/ultra/lookup_tables/FM45_Startup1_ULTRA_IMGPARAMS_20240719.csv +0 -2
  132. imap_processing/ultra/lookup_tables/FM90_Startup1_ULTRA_IMGPARAMS_20240719.csv +0 -2
  133. imap_processing/ultra/lookup_tables/dps_grid45_compressed.cdf +0 -0
  134. imap_processing/ultra/lookup_tables/ultra45_back-pos-luts.csv +0 -4097
  135. imap_processing/ultra/lookup_tables/ultra45_tdc_norm.csv +0 -2050
  136. imap_processing/ultra/lookup_tables/ultra90_back-pos-luts.csv +0 -4097
  137. imap_processing/ultra/lookup_tables/ultra90_tdc_norm.csv +0 -2050
  138. imap_processing/ultra/lookup_tables/yadjust.csv +0 -257
  139. {imap_processing-0.17.0.dist-info → imap_processing-0.19.0.dist-info}/LICENSE +0 -0
  140. {imap_processing-0.17.0.dist-info → imap_processing-0.19.0.dist-info}/WHEEL +0 -0
  141. {imap_processing-0.17.0.dist-info → imap_processing-0.19.0.dist-info}/entry_points.txt +0 -0
@@ -1,6 +1,8 @@
1
1
  """Decommutate HIT CCSDS data and create L1a data products."""
2
2
 
3
3
  import logging
4
+ from datetime import datetime
5
+ from pathlib import Path
4
6
 
5
7
  import numpy as np
6
8
  import xarray as xr
@@ -19,6 +21,11 @@ from imap_processing.hit.l0.constants import (
19
21
  ZENITH_ANGLES,
20
22
  )
21
23
  from imap_processing.hit.l0.decom_hit import decom_hit
24
+ from imap_processing.spice.time import (
25
+ et_to_datetime64,
26
+ met_to_datetime64,
27
+ ttj2000ns_to_et,
28
+ )
22
29
 
23
30
  logger = logging.getLogger(__name__)
24
31
 
@@ -28,7 +35,7 @@ logger = logging.getLogger(__name__)
28
35
  fillval = -9223372036854775808
29
36
 
30
37
 
31
- def hit_l1a(packet_file: str) -> list[xr.Dataset]:
38
+ def hit_l1a(packet_file: Path, packet_date: str | None) -> list[xr.Dataset]:
32
39
  """
33
40
  Will process HIT L0 data into L1A data products.
34
41
 
@@ -36,31 +43,42 @@ def hit_l1a(packet_file: str) -> list[xr.Dataset]:
36
43
  ----------
37
44
  packet_file : str
38
45
  Path to the CCSDS data packet file.
46
+ packet_date : str
47
+ The date of the packet data in 'YYYYMMDD' format. This is used to filter
48
+ data to the correct processing day since L0 will have a 20-minute
49
+ buffer before and after the processing day.
39
50
 
40
51
  Returns
41
52
  -------
42
53
  processed_data : list[xarray.Dataset]
43
54
  List of Datasets of L1A processed data.
44
55
  """
56
+ if not packet_date:
57
+ raise ValueError("Packet date is required for processing L1A data.")
58
+
45
59
  # Unpack ccsds file to xarray datasets
46
- datasets_by_apid = get_datasets_by_apid(packet_file)
60
+ datasets_by_apid = get_datasets_by_apid(str(packet_file))
47
61
 
48
62
  # Create the attribute manager for this data level
49
63
  attr_mgr = get_attribute_manager("l1a")
50
64
 
51
- l1a_datasets = []
52
-
53
65
  # Process l1a data products
66
+ l1a_datasets = []
54
67
  if HitAPID.HIT_HSKP in datasets_by_apid:
55
68
  logger.info("Creating HIT L1A housekeeping dataset")
56
- l1a_datasets.append(
57
- process_housekeeping_data(
58
- datasets_by_apid[HitAPID.HIT_HSKP], attr_mgr, "imap_hit_l1a_hk"
59
- )
69
+ hk_dataset = process_housekeeping_data(
70
+ datasets_by_apid[HitAPID.HIT_HSKP], attr_mgr, "imap_hit_l1a_hk"
71
+ )
72
+ # filter the housekeeping dataset to the processing day
73
+ hk_dataset = filter_dataset_to_processing_day(
74
+ hk_dataset, str(packet_date), epoch_vals=hk_dataset["epoch"].values
60
75
  )
76
+ l1a_datasets.append(hk_dataset)
61
77
  if HitAPID.HIT_SCIENCE in datasets_by_apid:
62
78
  l1a_datasets.extend(
63
- process_science(datasets_by_apid[HitAPID.HIT_SCIENCE], attr_mgr)
79
+ process_science(
80
+ datasets_by_apid[HitAPID.HIT_SCIENCE], attr_mgr, str(packet_date)
81
+ )
64
82
  )
65
83
  return l1a_datasets
66
84
 
@@ -102,7 +120,15 @@ def subcom_sectorates(sci_dataset: xr.Dataset) -> xr.Dataset:
102
120
  sci_dataset : xarray.Dataset
103
121
  Xarray dataset with sectored rates data organized by species.
104
122
  """
105
- updated_dataset = sci_dataset.copy()
123
+ # Initialize the dataset with the required variables
124
+ updated_dataset = sci_dataset[
125
+ [
126
+ "sectorates",
127
+ "hdr_minute_cnt",
128
+ "livetime_counter",
129
+ "hdr_dynamic_threshold_state",
130
+ ]
131
+ ].copy(deep=True)
106
132
 
107
133
  # Calculate mod 10 values
108
134
  hdr_min_count_mod_10 = updated_dataset.hdr_minute_cnt.values % 10
@@ -245,25 +271,335 @@ def calculate_uncertainties(dataset: xr.Dataset) -> xr.Dataset:
245
271
  return dataset
246
272
 
247
273
 
274
+ def add_cdf_attributes(
275
+ dataset: xr.Dataset, logical_source: str, attr_mgr: ImapCdfAttributes
276
+ ) -> xr.Dataset:
277
+ """
278
+ Add attributes to the dataset.
279
+
280
+ This function adds attributes to the dataset variables and dimensions.
281
+ It also adds dimension labels as coordinates to the dataset.The attributes
282
+ are defined in a YAML file and retrieved by the attribute manager.
283
+
284
+ Parameters
285
+ ----------
286
+ dataset : xarray.Dataset
287
+ The dataset to update.
288
+ logical_source : str
289
+ The logical source of the dataset.
290
+ attr_mgr : ImapCdfAttributes
291
+ The attribute manager to retrieve attributes.
292
+
293
+ Returns
294
+ -------
295
+ xarray.Dataset
296
+ The updated dataset with attributes and dimension labels.
297
+ """
298
+ dataset.attrs = attr_mgr.get_global_attributes(logical_source)
299
+
300
+ # Assign attributes and dimensions to each data array in the Dataset
301
+ for var in dataset.data_vars.keys():
302
+ try:
303
+ if "energy_delta" in var or var in {
304
+ "pkt_len",
305
+ "version",
306
+ "type",
307
+ "src_seq_ctr",
308
+ "seq_flgs",
309
+ "pkt_apid",
310
+ "sec_hdr_flg",
311
+ }:
312
+ # skip schema check to avoid DEPEND_0 being added unnecessarily
313
+ dataset[var].attrs = attr_mgr.get_variable_attributes(
314
+ var, check_schema=False
315
+ )
316
+ else:
317
+ dataset[var].attrs = attr_mgr.get_variable_attributes(var)
318
+ except KeyError:
319
+ logger.warning(f"Field {var} not found in attribute manager.")
320
+
321
+ # check_schema=False to avoid attr_mgr adding stuff dimensions don't need
322
+ for dim in dataset.dims:
323
+ dataset[dim].attrs = attr_mgr.get_variable_attributes(dim, check_schema=False)
324
+ if dim != "epoch":
325
+ label_array = xr.DataArray(
326
+ dataset[dim].values.astype(str),
327
+ name=f"{dim}_label",
328
+ dims=[dim],
329
+ attrs=attr_mgr.get_variable_attributes(
330
+ f"{dim}_label", check_schema=False
331
+ ),
332
+ )
333
+ dataset.coords[f"{dim}_label"] = label_array
334
+ return dataset
335
+
336
+
337
+ def find_complete_mod10_sets(mod_vals: np.ndarray) -> np.ndarray:
338
+ """
339
+ Find start indices where mod values match [0,1,2,3,4,5,6,7,8,9] pattern.
340
+
341
+ Parameters
342
+ ----------
343
+ mod_vals : np.ndarray
344
+ 1D array of mod 10 values from the hdr_minute_cnt field in the L1A counts data.
345
+
346
+ Returns
347
+ -------
348
+ np.ndarray
349
+ Indices in mod_vals where the complete pattern [0, 1, ..., 9] starts.
350
+ """
351
+ # The pattern to match is an array from 0-9
352
+ window_size = 10
353
+
354
+ if mod_vals.size < window_size:
355
+ logger.warning(
356
+ "Mod 10 array is smaller than the required window size for "
357
+ "pattern matching."
358
+ )
359
+ return np.array([], dtype=int)
360
+ # Use sliding windows to find pattern matches
361
+ sw_view = np.lib.stride_tricks.sliding_window_view(mod_vals, window_size)
362
+ matches = np.all(sw_view == np.arange(window_size), axis=1)
363
+ return np.where(matches)[0]
364
+
365
+
366
+ def subset_sectored_counts(
367
+ sectored_counts_dataset: xr.Dataset, packet_date: str
368
+ ) -> xr.Dataset:
369
+ """
370
+ Subset data for complete sets of sectored counts and corresponding livetime values.
371
+
372
+ A set of sectored data starts with hydrogen and ends with iron and correspond to
373
+ the mod 10 values 0-9. The livetime values from the previous 10 minutes are used
374
+ to calculate the rates for each set since those counts are transmitted 10 minutes
375
+ after they were collected. Therefore, only complete sets of sectored counts where
376
+ livetime from the previous 10 minutes are available are included in the output.
377
+
378
+ Parameters
379
+ ----------
380
+ sectored_counts_dataset : xarray.Dataset
381
+ The sectored counts dataset.
382
+
383
+ packet_date : str
384
+ The date of the packet data in 'YYYYMMDD' format, used for filtering.
385
+
386
+ Returns
387
+ -------
388
+ xarray.Dataset
389
+ A dataset of complete sectored counts and corresponding livetime values
390
+ for the processing day.
391
+ """
392
+ # TODO: Update to use fill values for partial frames rather than drop them
393
+
394
+ # Modify livetime_counter to use a new epoch coordinate
395
+ # that is aligned with the original epoch dimension. This
396
+ # ensures that livetime doesn't get filtered when the original
397
+ # epoch dimension is filtered for complete sets.
398
+ sectored_counts_dataset = update_livetime_coord(sectored_counts_dataset)
399
+
400
+ # Identify 10-minute intervals of complete sectored counts
401
+ # by using the mod 10 values of the header minute counts.
402
+ # Mod 10 determines the species and energy bin the data belongs
403
+ # to. A mapping of mod 10 values to species and energy bins is
404
+ # provided in l0/constants.py for reference.
405
+ bin_size = 10
406
+ mod_10: np.ndarray = sectored_counts_dataset.hdr_minute_cnt.values % 10
407
+ start_indices = find_complete_mod10_sets(mod_10)
408
+
409
+ # Filter out start indices that are less than or equal to the bin size
410
+ # since the previous 10 minutes are needed for calculating rates
411
+ if start_indices.size == 0:
412
+ raise ValueError(
413
+ "No data to process - valid start indices not found for "
414
+ "complete sectored counts."
415
+ )
416
+ else:
417
+ start_indices = start_indices[start_indices >= bin_size]
418
+
419
+ # Subset data for complete sets of sectored counts.
420
+ # Each set of sectored counts is 10 minutes long, so we take the indices
421
+ # starting from the start indices and extending to the bin size of 10.
422
+ # This creates a 1D array of indices that correspond to the complete
423
+ # sets of sectored counts which is used to filter the L1A dataset and
424
+ # create the L1B sectored rates dataset.
425
+ data_indices = np.concatenate(
426
+ [np.arange(idx, idx + bin_size) for idx in start_indices]
427
+ )
428
+ complete_sectored_counts_dataset = sectored_counts_dataset.isel(epoch=data_indices)
429
+
430
+ epoch_per_complete_set = np.repeat(
431
+ [
432
+ complete_sectored_counts_dataset.epoch[idx : idx + bin_size].mean().item()
433
+ for idx in range(0, len(complete_sectored_counts_dataset.epoch), 10)
434
+ ],
435
+ bin_size,
436
+ )
437
+
438
+ # Filter dataset for data in the processing day
439
+
440
+ # Trim the sectored data to epoch_per_complete_set values in the processing day
441
+ filtered_dataset = filter_dataset_to_processing_day(
442
+ complete_sectored_counts_dataset, packet_date, epoch_vals=epoch_per_complete_set
443
+ )
444
+
445
+ # Trim livetime to the size of the sectored data but shifted 10 minutes earlier.
446
+ filtered_dataset = subset_livetime(filtered_dataset)
447
+
448
+ return filtered_dataset
449
+
450
+
451
+ def update_livetime_coord(sectored_dataset: xr.Dataset) -> xr.Dataset:
452
+ """
453
+ Update livetime_counter to use a new epoch coordinate.
454
+
455
+ Assign a new epoch coordinate to the `livetime_counter` variable.
456
+ This new coordinate is aligned with the original `epoch` dimension,
457
+ ensuring that `livetime_counter` remains unaffected when the original
458
+ `epoch` dimension is filtered for complete sets in `subset_sectored_counts`
459
+ function.
460
+
461
+ Parameters
462
+ ----------
463
+ sectored_dataset : xarray.Dataset
464
+ The dataset containing sectored counts and livetime_counter data.
465
+
466
+ Returns
467
+ -------
468
+ xarray.Dataset
469
+ The updated dataset with modified livetime_counter.
470
+ """
471
+ epoch_values = sectored_dataset.epoch.values
472
+ sectored_dataset = sectored_dataset.assign_coords(
473
+ {
474
+ "epoch_livetime": ("epoch", epoch_values),
475
+ }
476
+ )
477
+ da = sectored_dataset["livetime_counter"]
478
+ da = da.assign_coords(epoch_livetime=("epoch", epoch_values))
479
+
480
+ # Swap the dimension from 'epoch' to 'epoch_livetime'
481
+ da = da.swap_dims({"epoch": "epoch_livetime"})
482
+
483
+ # Update the dataset with the modified variable
484
+ sectored_dataset["livetime_counter"] = da
485
+
486
+ return sectored_dataset
487
+
488
+
489
+ def subset_livetime(dataset: xr.Dataset) -> xr.Dataset:
490
+ """
491
+ Trim livetime to values shifted 10 minutes earlier than sectored data.
492
+
493
+ This ensures that the livetime values correspond to the sectored counts correctly
494
+ since sectored data is collected 10 minutes before it's transmitted.
495
+
496
+ Parameters
497
+ ----------
498
+ dataset : xarray.Dataset
499
+ The dataset containing sectored counts and livetime data.
500
+
501
+ Returns
502
+ -------
503
+ xarray.Dataset
504
+ The updated dataset with trimmed livetime data.
505
+ """
506
+ # epoch values are per science frame which is 1 minute
507
+ epoch_vals = dataset["epoch"].values
508
+ epoch_livetime_vals = dataset["epoch_livetime"].values
509
+
510
+ if not epoch_vals.size:
511
+ raise ValueError(
512
+ "Epoch values are empty. Cannot proceed with livetime subsetting."
513
+ )
514
+
515
+ # Get index positions of epoch[0] and epoch[-1] in epoch_livetime
516
+ start_idx = np.where(epoch_livetime_vals == epoch_vals[0])[0][0]
517
+ end_idx = np.where(epoch_livetime_vals == epoch_vals[-1])[0][0]
518
+
519
+ if start_idx < 10:
520
+ raise ValueError(
521
+ "Start index for livetime is less than 10. This indicates that the "
522
+ "dataset is too small to shift livetime correctly."
523
+ )
524
+
525
+ # Compute shifted indices by 10 minutes
526
+ start_trimmed = max(start_idx - 10, 0)
527
+ end_trimmed = max(end_idx - 10, 0)
528
+
529
+ return dataset.isel(epoch_livetime=slice(start_trimmed, end_trimmed + 1))
530
+
531
+
532
+ def filter_dataset_to_processing_day(
533
+ dataset: xr.Dataset,
534
+ packet_date: str,
535
+ epoch_vals: np.ndarray,
536
+ sc_tick: bool = False,
537
+ ) -> xr.Dataset:
538
+ """
539
+ Filter the dataset for data within the processing day.
540
+
541
+ Parameters
542
+ ----------
543
+ dataset : xarray.Dataset
544
+ The dataset to filter.
545
+ packet_date : str
546
+ The date of the packet data in 'YYYYMMDD' format.
547
+ epoch_vals : np.ndarray
548
+ An array of epoch values. Used to identify indices of data that
549
+ belong in the processing day. For sectored counts data, an
550
+ array of mean epoch values for major frames (10 min. intervals)
551
+ is used to filter the dataset to ensure that major frames that span
552
+ midnight, but belong to the processing day, are included. For other
553
+ datasets, the dataset's epoch coordinate values will be used.
554
+ sc_tick : bool
555
+ If true, the dataset's sc_tick will be used to filter data as well.
556
+ This ensures that the ccsds headers that use sc_tick as a coordinate,
557
+ instead of epoch, also corresponds to the processing day.
558
+
559
+ Returns
560
+ -------
561
+ xarray.Dataset
562
+ The filtered dataset containing data within the processing day.
563
+ """
564
+ processing_day = datetime.strptime(packet_date, "%Y%m%d").strftime("%Y-%m-%d")
565
+
566
+ # Filter dataset by epoch indices in processing day
567
+ epoch_dt = et_to_datetime64(ttj2000ns_to_et(epoch_vals))
568
+ epoch_indices_in_processing_day = np.where(
569
+ epoch_dt.astype("datetime64[D]") == np.datetime64(processing_day)
570
+ )[0]
571
+ dataset = dataset.isel(epoch=epoch_indices_in_processing_day)
572
+
573
+ # If sc_tick is provided (coord for ccsds headers), filter by sc_tick too
574
+ if sc_tick:
575
+ sc_tick_dt = met_to_datetime64(dataset["sc_tick"].values)
576
+ indices_in_processing_day = np.where(
577
+ sc_tick_dt.astype("datetime64[D]") == np.datetime64(processing_day)
578
+ )[0]
579
+ dataset = dataset.isel(sc_tick=indices_in_processing_day)
580
+ return dataset
581
+
582
+
248
583
  def process_science(
249
- dataset: xr.Dataset, attr_mgr: ImapCdfAttributes
584
+ dataset: xr.Dataset, attr_mgr: ImapCdfAttributes, packet_date: str
250
585
  ) -> list[xr.Dataset]:
251
586
  """
252
587
  Will process science datasets for CDF products.
253
588
 
254
- Process binary science data for CDF creation. The data is
255
- grouped into science frames, decommutated and decompressed,
256
- and split into count rates and event datasets. Updates the
257
- dataset attributes and coordinates and data variable
258
- dimensions according to specifications in a cdf yaml file.
589
+ The function processes binary science data for CDF creation.
590
+ The data is decommutated, decompressed, grouped into science frames,
591
+ and split into count rates, sectored count rates, and event datasets.
592
+ It also updates the dataset attributes according to specifications
593
+ in a cdf yaml file.
259
594
 
260
595
  Parameters
261
596
  ----------
262
597
  dataset : xarray.Dataset
263
598
  A dataset containing HIT science data.
264
-
265
599
  attr_mgr : ImapCdfAttributes
266
600
  Attribute manager used to get the data product field's attributes.
601
+ packet_date : str
602
+ The date of the packet data, used for processing.
267
603
 
268
604
  Returns
269
605
  -------
@@ -275,49 +611,43 @@ def process_science(
275
611
  # Decommutate and decompress the science data
276
612
  sci_dataset = decom_hit(dataset)
277
613
 
278
- # Organize sectored rates by species type
279
- sci_dataset = subcom_sectorates(sci_dataset)
614
+ # Create dataset for sectored data organized by species type
615
+ sectored_dataset = subcom_sectorates(sci_dataset)
616
+
617
+ # Subset sectored data for complete sets (10 min intervals covering all species)
618
+ sectored_dataset = subset_sectored_counts(sectored_dataset, packet_date)
619
+
620
+ # TODO:
621
+ # - headers are values per packet rather than per frame. Do these need to align
622
+ # with the science frames?
623
+ # For instance, the mean epoch for a frame that spans midnight might contain
624
+ # packets from the previous day but filtering sc_tick by processing day will
625
+ # exclude those packets. Is this an issue?
626
+
627
+ # Filter the science dataset to only include data from the processing day
628
+ sci_dataset = filter_dataset_to_processing_day(
629
+ sci_dataset, packet_date, epoch_vals=sci_dataset["epoch"].values, sc_tick=True
630
+ )
280
631
 
281
632
  # Split the science data into count rates and event datasets
282
633
  pha_raw_dataset = xr.Dataset(
283
634
  {"pha_raw": sci_dataset["pha_raw"]}, coords={"epoch": sci_dataset["epoch"]}
284
635
  )
285
- count_rates_dataset = sci_dataset.drop_vars("pha_raw")
636
+ count_rates_dataset = sci_dataset.drop_vars(["pha_raw", "sectorates"])
286
637
 
287
638
  # Calculate uncertainties for count rates
288
639
  count_rates_dataset = calculate_uncertainties(count_rates_dataset)
640
+ sectored_count_rates_dataset = calculate_uncertainties(sectored_dataset)
289
641
 
290
642
  l1a_datasets: dict = {
291
- "imap_hit_l1a_counts": count_rates_dataset,
643
+ "imap_hit_l1a_counts-standard": count_rates_dataset,
644
+ "imap_hit_l1a_counts-sectored": sectored_count_rates_dataset,
292
645
  "imap_hit_l1a_direct-events": pha_raw_dataset,
293
646
  }
294
647
 
295
648
  # Update attributes and dimensions
296
649
  for logical_source, ds in l1a_datasets.items():
297
- ds.attrs = attr_mgr.get_global_attributes(logical_source)
298
-
299
- # Assign attributes and dimensions to each data array in the Dataset
300
- for field in ds.data_vars.keys():
301
- try:
302
- ds[field].attrs = attr_mgr.get_variable_attributes(field)
303
- except KeyError:
304
- print(f"Field {field} not found in attribute manager.")
305
- logger.warning(f"Field {field} not found in attribute manager.")
306
-
307
- # check_schema=False to avoid attr_mgr adding stuff dimensions don't need
308
- for dim in ds.dims:
309
- ds[dim].attrs = attr_mgr.get_variable_attributes(dim, check_schema=False)
310
- # TODO: should labels be added as coordinates? Check with SPDF
311
- if dim != "epoch":
312
- label_array = xr.DataArray(
313
- ds[dim].values.astype(str),
314
- name=f"{dim}_label",
315
- dims=[dim],
316
- attrs=attr_mgr.get_variable_attributes(
317
- f"{dim}_label", check_schema=False
318
- ),
319
- )
320
- ds.coords[f"{dim}_label"] = label_array
650
+ l1a_datasets[logical_source] = add_cdf_attributes(ds, logical_source, attr_mgr)
321
651
 
322
652
  logger.info(f"HIT L1A dataset created for {logical_source}")
323
653
 
@@ -4,6 +4,11 @@
4
4
  # This is used to calculate the fractional livetime
5
5
  LIVESTIM_PULSES = 270
6
6
 
7
+ # A factor used to find the count rate for sectored data that
8
+ # accounts for the fact that a single spacecraft rotation is
9
+ # split into 15 inclination ranges.
10
+ SECTORS = 15
11
+
7
12
  # Fill values for missing data
8
13
  FILLVAL_FLOAT32 = -1.00e31
9
14
  FILLVAL_INT64 = -9223372036854775808