imap-processing 1.0.1__py3-none-any.whl → 1.0.3__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 (58) hide show
  1. imap_processing/_version.py +2 -2
  2. imap_processing/cdf/config/imap_codice_global_cdf_attrs.yaml +18 -0
  3. imap_processing/cdf/config/imap_codice_l1a_variable_attrs.yaml +101 -258
  4. imap_processing/cdf/config/imap_enamaps_l2-common_variable_attrs.yaml +1 -1
  5. imap_processing/cdf/config/imap_hi_variable_attrs.yaml +12 -2
  6. imap_processing/cdf/config/imap_idex_global_cdf_attrs.yaml +1 -8
  7. imap_processing/cdf/config/imap_idex_l1b_variable_attrs.yaml +16 -5
  8. imap_processing/cdf/config/imap_idex_l2a_variable_attrs.yaml +27 -25
  9. imap_processing/cdf/config/imap_idex_l2b_variable_attrs.yaml +16 -16
  10. imap_processing/cdf/config/imap_idex_l2c_variable_attrs.yaml +2 -2
  11. imap_processing/cdf/config/imap_swapi_variable_attrs.yaml +2 -13
  12. imap_processing/cdf/config/imap_ultra_l1c_variable_attrs.yaml +12 -0
  13. imap_processing/cdf/utils.py +2 -2
  14. imap_processing/cli.py +4 -16
  15. imap_processing/codice/codice_l1a_lo_angular.py +362 -0
  16. imap_processing/codice/codice_l1a_lo_species.py +282 -0
  17. imap_processing/codice/codice_l1b.py +80 -97
  18. imap_processing/codice/codice_l2.py +270 -103
  19. imap_processing/codice/codice_new_l1a.py +64 -0
  20. imap_processing/codice/constants.py +37 -2
  21. imap_processing/codice/utils.py +270 -0
  22. imap_processing/ena_maps/ena_maps.py +51 -39
  23. imap_processing/ena_maps/utils/corrections.py +196 -14
  24. imap_processing/ena_maps/utils/naming.py +3 -1
  25. imap_processing/hi/hi_l1c.py +57 -19
  26. imap_processing/hi/hi_l2.py +89 -36
  27. imap_processing/ialirt/calculate_ingest.py +19 -1
  28. imap_processing/ialirt/constants.py +12 -6
  29. imap_processing/ialirt/generate_coverage.py +6 -1
  30. imap_processing/ialirt/l0/parse_mag.py +1 -0
  31. imap_processing/ialirt/l0/process_hit.py +1 -0
  32. imap_processing/ialirt/l0/process_swapi.py +1 -0
  33. imap_processing/ialirt/l0/process_swe.py +2 -0
  34. imap_processing/ialirt/process_ephemeris.py +6 -2
  35. imap_processing/ialirt/utils/create_xarray.py +3 -2
  36. imap_processing/lo/l1b/lo_l1b.py +12 -2
  37. imap_processing/lo/l1c/lo_l1c.py +4 -4
  38. imap_processing/lo/l2/lo_l2.py +101 -8
  39. imap_processing/quality_flags.py +1 -0
  40. imap_processing/swapi/constants.py +4 -0
  41. imap_processing/swapi/l1/swapi_l1.py +47 -20
  42. imap_processing/swapi/l2/swapi_l2.py +17 -3
  43. imap_processing/ultra/l1a/ultra_l1a.py +121 -72
  44. imap_processing/ultra/l1b/de.py +57 -1
  45. imap_processing/ultra/l1b/ultra_l1b_annotated.py +0 -1
  46. imap_processing/ultra/l1b/ultra_l1b_extended.py +24 -11
  47. imap_processing/ultra/l1c/helio_pset.py +34 -8
  48. imap_processing/ultra/l1c/l1c_lookup_utils.py +4 -2
  49. imap_processing/ultra/l1c/spacecraft_pset.py +13 -7
  50. imap_processing/ultra/l1c/ultra_l1c.py +6 -6
  51. imap_processing/ultra/l1c/ultra_l1c_pset_bins.py +79 -20
  52. imap_processing/ultra/l2/ultra_l2.py +2 -2
  53. imap_processing/ultra/utils/ultra_l1_utils.py +6 -0
  54. {imap_processing-1.0.1.dist-info → imap_processing-1.0.3.dist-info}/METADATA +1 -1
  55. {imap_processing-1.0.1.dist-info → imap_processing-1.0.3.dist-info}/RECORD +58 -54
  56. {imap_processing-1.0.1.dist-info → imap_processing-1.0.3.dist-info}/LICENSE +0 -0
  57. {imap_processing-1.0.1.dist-info → imap_processing-1.0.3.dist-info}/WHEEL +0 -0
  58. {imap_processing-1.0.1.dist-info → imap_processing-1.0.3.dist-info}/entry_points.txt +0 -0
@@ -1,6 +1,8 @@
1
1
  """L2 corrections common to multiple IMAP ENA instruments."""
2
2
 
3
+ import logging
3
4
  from pathlib import Path
5
+ from typing import TypeVar
4
6
 
5
7
  import numpy as np
6
8
  import pandas as pd
@@ -8,11 +10,23 @@ import xarray as xr
8
10
  from numpy.polynomial import Polynomial
9
11
  from scipy.constants import electron_volt, erg, proton_mass
10
12
 
11
- from imap_processing.ena_maps.ena_maps import LoHiBasePointingSet
13
+ from imap_processing.ena_maps.ena_maps import (
14
+ LoHiBasePointingSet,
15
+ )
12
16
  from imap_processing.ena_maps.utils.coordinates import CoordNames
13
17
  from imap_processing.spice import geometry
14
18
  from imap_processing.spice.time import ttj2000ns_to_et
15
19
 
20
+ logger = logging.getLogger(__name__)
21
+
22
+ # Tell ruff to ignore ambiguous Greek letters in formulas in this file
23
+ # ruff: noqa: RUF003
24
+
25
+ # Create a TypeVar to represent the specific class being passed in
26
+ # Bound to LoHiBasePointingSet, meaning it must be LoHiBasePointingSet
27
+ # or a subclass of it
28
+ LoHiBasePsetSubclass = TypeVar("LoHiBasePsetSubclass", bound=LoHiBasePointingSet)
29
+
16
30
  # Physical constants for Compton-Getting correction
17
31
  # Units: electron_volt = [J / eV]
18
32
  # erg = [J / erg]
@@ -307,7 +321,9 @@ class PowerLawFluxCorrector:
307
321
  return corrected_flux, corrected_flux_stat_unc
308
322
 
309
323
 
310
- def _add_spacecraft_velocity_to_pset(pset: LoHiBasePointingSet) -> None:
324
+ def _add_spacecraft_velocity_to_pset(
325
+ pset: LoHiBasePsetSubclass,
326
+ ) -> LoHiBasePsetSubclass:
311
327
  """
312
328
  Calculate and add spacecraft velocity data to pointing set.
313
329
 
@@ -316,6 +332,11 @@ def _add_spacecraft_velocity_to_pset(pset: LoHiBasePointingSet) -> None:
316
332
  pset : LoHiBasePointingSet
317
333
  Pointing set object to be updated.
318
334
 
335
+ Returns
336
+ -------
337
+ pset : LoHiBasePointingSet
338
+ Pointing set object with spacecraft velocity data added.
339
+
319
340
  Notes
320
341
  -----
321
342
  Adds the following DataArrays to pset.data:
@@ -342,8 +363,10 @@ def _add_spacecraft_velocity_to_pset(pset: LoHiBasePointingSet) -> None:
342
363
  )
343
364
  pset.data["sc_direction_vector"] = pset.data["sc_velocity"] / sc_velocity_km_per_sec
344
365
 
366
+ return pset
367
+
345
368
 
346
- def _add_cartesian_look_direction(pset: LoHiBasePointingSet) -> None:
369
+ def _add_cartesian_look_direction(pset: LoHiBasePsetSubclass) -> LoHiBasePsetSubclass:
347
370
  """
348
371
  Calculate and add look direction vectors to pointing set.
349
372
 
@@ -352,6 +375,11 @@ def _add_cartesian_look_direction(pset: LoHiBasePointingSet) -> None:
352
375
  pset : LoHiBasePointingSet
353
376
  Pointing set object to be updated.
354
377
 
378
+ Returns
379
+ -------
380
+ pset : LoHiBasePointingSet
381
+ Pointing set object with look direction vectors added.
382
+
355
383
  Notes
356
384
  -----
357
385
  Adds the following DataArray to pset.data:
@@ -376,11 +404,13 @@ def _add_cartesian_look_direction(pset: LoHiBasePointingSet) -> None:
376
404
  dims=[*longitudes.dims, CoordNames.CARTESIAN_VECTOR.value],
377
405
  )
378
406
 
407
+ return pset
408
+
379
409
 
380
410
  def _calculate_compton_getting_transform(
381
- pset: LoHiBasePointingSet,
411
+ pset: LoHiBasePsetSubclass,
382
412
  energy_hf: xr.DataArray,
383
- ) -> None:
413
+ ) -> LoHiBasePsetSubclass:
384
414
  """
385
415
  Apply Compton-Getting transformation to compute ENA source directions.
386
416
 
@@ -400,14 +430,24 @@ def _calculate_compton_getting_transform(
400
430
  energy_hf : xr.DataArray
401
431
  ENA energies in the heliosphere frame in eV.
402
432
 
433
+ Returns
434
+ -------
435
+ pset : LoHiBasePointingSet
436
+ Pointing set object with Compton-Getting related variables added and
437
+ updated az_el_points.
438
+
403
439
  Notes
404
440
  -----
405
441
  The algorithm is based on the "Appendix A. The IMAP-Lo Mapping Algorithms"
406
442
  document.
407
443
  Adds the following DataArrays to pset.data:
408
444
  - "energy_sc": ENA energies in spacecraft frame (eV)
409
- - "ena_source_hae_longitude": ENA source longitudes in heliosphere frame (degrees)
410
- - "ena_source_hae_latitude": ENA source latitudes in heliosphere frame (degrees)
445
+ - "energy_hf": ENA energies in the heliosphere frame (eV)
446
+ - "ram_mask": Mask indicating whether ENA source direction is from the ram
447
+ direction.
448
+ Updates the following DataArrays in pset.data:
449
+ - "hae_longitude": ENA source longitudes in heliosphere frame (degrees)
450
+ - "hae_latitude": ENA source latitudes in heliosphere frame (degrees)
411
451
  """
412
452
  # Store heliosphere frame energies
413
453
  pset.data["energy_hf"] = energy_hf
@@ -455,6 +495,8 @@ def _calculate_compton_getting_transform(
455
495
  # Velocity magnitude factor calculation (Equation 62)
456
496
  # x_k = (êₛ · û_sc) + sqrt(y² + (êₛ · û_sc)² - 1)
457
497
  x = dot_product + np.sqrt(y**2 + dot_product**2 - 1)
498
+ # Get the dimensions in the right order so that spatial is last
499
+ x = x.transpose(dot_product.dims[0], y.dims[0], dot_product.dims[1])
458
500
 
459
501
  # Calculate ENA speed in the spacecraft frame
460
502
  # |v⃗_sc| = x_k * U_sc
@@ -504,11 +546,13 @@ def _calculate_compton_getting_transform(
504
546
  dims=velocity_vector_helio.dims[:-1],
505
547
  )
506
548
 
549
+ return pset
550
+
507
551
 
508
552
  def apply_compton_getting_correction(
509
- pset: LoHiBasePointingSet,
553
+ pset: LoHiBasePsetSubclass,
510
554
  energy_hf: xr.DataArray,
511
- ) -> None:
555
+ ) -> LoHiBasePsetSubclass:
512
556
  """
513
557
  Apply Compton-Getting correction to a pointing set and update coordinates.
514
558
 
@@ -532,6 +576,11 @@ def apply_compton_getting_correction(
532
576
  ENA energies in the heliosphere frame in eV. Must be 1D with an
533
577
  energy dimension.
534
578
 
579
+ Returns
580
+ -------
581
+ pset : LoHiBasePointingSet
582
+ Updated pointing set object with Compton-Getting related variables added.
583
+
535
584
  Notes
536
585
  -----
537
586
  This function adds the following variables to the pointing set dataset:
@@ -540,20 +589,153 @@ def apply_compton_getting_correction(
540
589
  - "look_direction": Cartesian unit vectors of observation directions
541
590
  - "energy_hf": ENA energies in heliosphere frame (eV)
542
591
  - "energy_sc": ENA energies in spacecraft frame (eV)
543
- - "ena_source_hae_longitude": ENA source longitudes in heliosphere frame (degrees)
544
- - "ena_source_hae_latitude": ENA source latitudes in heliosphere frame (degrees)
592
+ This function modifies the following variables in the pointing set dataset:
593
+ - "hae_longitude": ENA source longitudes in heliosphere frame (degrees)
594
+ - "hae_latitude": ENA source latitudes in heliosphere frame (degrees)
545
595
 
546
596
  The az_el_points attribute is updated to use the corrected coordinates,
547
597
  which will be used for subsequent binning operations.
548
598
  """
549
599
  # Step 1: Add spacecraft velocity and direction to pset
550
- _add_spacecraft_velocity_to_pset(pset)
600
+ pset = _add_spacecraft_velocity_to_pset(pset)
551
601
 
552
602
  # Step 2: Calculate and add look direction vectors to pset
553
- _add_cartesian_look_direction(pset)
603
+ pset = _add_cartesian_look_direction(pset)
554
604
 
555
605
  # Step 3: Apply Compton-Getting transformation
556
- _calculate_compton_getting_transform(pset, energy_hf)
606
+ pset = _calculate_compton_getting_transform(pset, energy_hf)
557
607
 
558
608
  # Step 4: Update az_el_points to use the corrected coordinates
559
609
  pset.update_az_el_points()
610
+
611
+ return pset
612
+
613
+
614
+ def interpolate_map_flux_to_helio_frame(
615
+ map_ds: xr.Dataset,
616
+ esa_energies_ev: xr.DataArray,
617
+ helio_energies_ev: xr.DataArray,
618
+ ) -> xr.Dataset:
619
+ """
620
+ Interpolate flux from spacecraft frame to heliocentric frame energies.
621
+
622
+ This implements the Compton-Getting interpolation step that transforms
623
+ flux measurements from the spacecraft frame to the heliocentric frame.
624
+ The algorithm follows these steps:
625
+ 1. For each spatial pixel and energy step, get the spacecraft energy
626
+ 2. Find bounding ESA energy channels for interpolation
627
+ 3. Perform power-law interpolation between bounding channels to spacecraft energy
628
+ 4. Apply energy scaling transformation to heliocentric frame
629
+
630
+ Parameters
631
+ ----------
632
+ map_ds : xarray.Dataset
633
+ Map dataset with `energy_sc` data variable containing the spacecraft
634
+ frame energies for each spatial pixel and ESA energy step.
635
+ esa_energies_ev : xarray.DataArray
636
+ The ESA nominal central energies (in eV).
637
+ helio_energies_ev : xarray.DataArray
638
+ The heliocentric frame energies to interpolate to (in eV).
639
+ In practice, these are the same as esa_energies_ev.
640
+
641
+ Returns
642
+ -------
643
+ map_ds : xarray.Dataset
644
+ Updated map dataset with interpolated heliocentric frame fluxes.
645
+ """
646
+ logger.info("Performing Compton-Getting interpolation to heliocentric frame")
647
+
648
+ # Work with xarray DataArrays to handle arbitrary spatial dimensions
649
+ energy_sc = map_ds["energy_sc"]
650
+ intensity = map_ds["ena_intensity"]
651
+ stat_unc = map_ds["ena_intensity_stat_uncert"]
652
+ sys_err = map_ds["ena_intensity_sys_err"]
653
+
654
+ # Step 1: Find bounding ESA energy indices for each position
655
+ # Use np.searchsorted on flattened array, then reshape back
656
+ esa_energy_vals = esa_energies_ev.values
657
+ energy_sc_flat = energy_sc.values.ravel()
658
+
659
+ # Find right bound index for each element (vectorized)
660
+ right_idx_flat = np.searchsorted(esa_energy_vals, energy_sc_flat, side="right")
661
+ right_idx_flat = np.clip(right_idx_flat, 1, len(esa_energy_vals) - 1)
662
+ left_idx_flat = right_idx_flat - 1
663
+
664
+ # Reshape indices back to match energy_sc shape
665
+ right_idx = right_idx_flat.reshape(energy_sc.shape)
666
+ left_idx = left_idx_flat.reshape(energy_sc.shape)
667
+
668
+ # Create DataArrays for indices with same dims as energy_sc
669
+ # Note: we need to avoid coordinate name conflicts when using isel()
670
+ # The energy dimension should be present in dims but not as a coordinate
671
+ # since we're using these as indices into the energy dimension
672
+ # Create coordinates dict without the energy coordinate
673
+ coords_without_energy = {k: v for k, v in energy_sc.coords.items() if k != "energy"}
674
+
675
+ right_idx_da = xr.DataArray(
676
+ right_idx, dims=energy_sc.dims, coords=coords_without_energy
677
+ )
678
+ left_idx_da = xr.DataArray(
679
+ left_idx, dims=energy_sc.dims, coords=coords_without_energy
680
+ )
681
+
682
+ # Step 2: Extract flux values at bounding energy channels
683
+ # Use xarray's advanced indexing to get fluxes at left and right indices
684
+ flux_left = intensity.isel({"energy": left_idx_da})
685
+ flux_right = intensity.isel({"energy": right_idx_da})
686
+ stat_unc_left = stat_unc.isel({"energy": left_idx_da})
687
+ stat_unc_right = stat_unc.isel({"energy": right_idx_da})
688
+ sys_err_left = sys_err.isel({"energy": left_idx_da})
689
+
690
+ # Get energy values at boundaries - select from esa_energies_ev using indices
691
+ energy_left = esa_energies_ev.isel({"energy": left_idx_da})
692
+ energy_right = esa_energies_ev.isel({"energy": right_idx_da})
693
+
694
+ # Step 3: Perform power-law interpolation to spacecraft energy
695
+ # slope = log(f_right/f_left) / log(e_right/e_left)
696
+ # flux_sc = f_left * (energy_sc / e_left)^slope
697
+ with np.errstate(divide="ignore", invalid="ignore"):
698
+ # Calculate slope for power-law interpolation
699
+ slope = np.log(flux_right / flux_left) / np.log(energy_right / energy_left)
700
+
701
+ # Interpolate flux using power-law
702
+ flux_sc = flux_left * ((energy_sc / energy_left) ** slope)
703
+
704
+ # Interpolation factor for uncertainty propagation (Equations 75 & 76)
705
+ unc_factor = np.log(energy_sc / energy_left) / np.log(
706
+ energy_right / energy_left
707
+ )
708
+
709
+ # Statistical uncertainty propagation (Equation 75):
710
+ # δJ = J * sqrt((δJ_left/J_left)^2 * (1 + unc_factor^2) + (δJ_right/J_right)^2)
711
+ stat_unc_sc = flux_sc * np.sqrt(
712
+ (stat_unc_left / flux_left) ** 2 * (1.0 + unc_factor**2)
713
+ + (stat_unc_right / flux_right) ** 2
714
+ )
715
+
716
+ # Systematic uncertainty propagation (Equation 76):
717
+ # σJ^g = σJ^src_kref * (⟨E^s_kref⟩ / E^ESA_kref)^γ_kref * (E^h / ⟨E^s_kref⟩)
718
+ # Systematic error scales proportionally with flux during power-law
719
+ # interpolation
720
+ sys_err_sc = sys_err_left * ((energy_sc / energy_left) ** slope)
721
+
722
+ # Step 4: Energy scaling transformation (Liouville theorem)
723
+ # flux_helio = flux_sc * (helio_energy / energy_sc)
724
+ # Use xarray broadcasting - helio_energies_ev will broadcast along esa_energy_step
725
+ with np.errstate(divide="ignore", invalid="ignore"):
726
+ energy_ratio = helio_energies_ev / energy_sc
727
+ flux_helio = flux_sc * energy_ratio
728
+ stat_unc_helio = stat_unc_sc * energy_ratio
729
+ sys_err_helio = sys_err_sc * energy_ratio
730
+
731
+ # Set any location where the value is not finite to NaN (converts +/-inf to NaN)
732
+ flux_helio = flux_helio.where(np.isfinite(flux_helio), np.nan)
733
+ stat_unc_helio = stat_unc_helio.where(np.isfinite(stat_unc_helio), np.nan)
734
+ sys_err_helio = sys_err_helio.where(np.isfinite(sys_err_helio), np.nan)
735
+
736
+ # Update the dataset with interpolated values
737
+ map_ds["ena_intensity"] = flux_helio
738
+ map_ds["ena_intensity_stat_uncert"] = stat_unc_helio
739
+ map_ds["ena_intensity_sys_err"] = sys_err_helio
740
+
741
+ return map_ds
@@ -342,7 +342,9 @@ class MapDescriptor:
342
342
  elif frame_str == "gcs":
343
343
  return SpiceFrame.IMAP_GCS
344
344
  else:
345
- raise NotImplementedError("Coordinate frame is not yet implemented.")
345
+ raise NotImplementedError(
346
+ f"Coordinate frame {frame_str} is not yet implemented."
347
+ )
346
348
 
347
349
  def to_empty_map(
348
350
  self,
@@ -29,11 +29,12 @@ from imap_processing.spice.geometry import (
29
29
  frame_transform,
30
30
  frame_transform_az_el,
31
31
  )
32
+ from imap_processing.spice.repoint import get_pointing_times
32
33
  from imap_processing.spice.spin import (
33
34
  get_instrument_spin_phase,
34
35
  get_spin_data,
35
36
  )
36
- from imap_processing.spice.time import ttj2000ns_to_et
37
+ from imap_processing.spice.time import met_to_ttj2000ns, ttj2000ns_to_et
37
38
 
38
39
  N_SPIN_BINS = 3600
39
40
  SPIN_PHASE_BIN_EDGES = np.linspace(0, 1, N_SPIN_BINS + 1)
@@ -101,14 +102,14 @@ def generate_pset_dataset(
101
102
  config_df = CalibrationProductConfig.from_csv(calibration_prod_config_path)
102
103
 
103
104
  pset_dataset = empty_pset_dataset(
104
- de_dataset.epoch.data[0],
105
- de_dataset.esa_energy_step.data,
105
+ de_dataset.ccsds_met.data.mean(),
106
+ de_dataset.esa_energy_step,
106
107
  config_df.cal_prod_config.number_of_products,
107
108
  logical_source_parts["sensor"],
108
109
  )
109
- pset_et = ttj2000ns_to_et(pset_dataset.epoch.data[0])
110
110
  # Calculate and add despun_z, hae_latitude, and hae_longitude variables to
111
111
  # the pset_dataset
112
+ pset_et = ttj2000ns_to_et(pset_dataset.epoch.data[0])
112
113
  pset_dataset.update(pset_geometry(pset_et, logical_source_parts["sensor"]))
113
114
  # Bin the counts into the spin-bins
114
115
  pset_dataset.update(pset_counts(pset_dataset.coords, config_df, de_dataset))
@@ -121,16 +122,17 @@ def generate_pset_dataset(
121
122
 
122
123
 
123
124
  def empty_pset_dataset(
124
- epoch_val: int, l1b_energy_steps: np.ndarray, n_cal_prods: int, sensor_str: str
125
+ l1b_met: float, l1b_energy_steps: xr.DataArray, n_cal_prods: int, sensor_str: str
125
126
  ) -> xr.Dataset:
126
127
  """
127
128
  Allocate an empty xarray.Dataset with appropriate pset coordinates.
128
129
 
129
130
  Parameters
130
131
  ----------
131
- epoch_val : int
132
- The starting epoch in J2000 TT nanoseconds for data in the PSET.
133
- l1b_energy_steps : np.ndarray
132
+ l1b_met : float
133
+ Any met from the input L1B DE dataset. This is used to query the
134
+ repoint-table data to get the start and end times of the pointing.
135
+ l1b_energy_steps : xarray.DataArray
134
136
  The array of esa_energy_step data from the L1B DE product.
135
137
  n_cal_prods : int
136
138
  Number of calibration products to allocate.
@@ -148,13 +150,18 @@ def empty_pset_dataset(
148
150
 
149
151
  # preallocate coordinates xr.DataArrays
150
152
  coords = dict()
153
+
154
+ # Get the Pointing start and end times
155
+ pointing_mets = get_pointing_times(l1b_met)
156
+ epochs = met_to_ttj2000ns(np.asarray(pointing_mets))
157
+
151
158
  # epoch coordinate has only 1 entry for pointing set
152
159
  epoch_attrs = attr_mgr.get_variable_attributes("epoch", check_schema=False)
153
160
  epoch_attrs.update(
154
161
  attr_mgr.get_variable_attributes("hi_pset_epoch", check_schema=False)
155
162
  )
156
163
  coords["epoch"] = xr.DataArray(
157
- np.array([epoch_val], dtype=np.int64), # TODO: get dtype from cdf attrs?
164
+ np.array([epochs[0]], dtype=np.int64),
158
165
  name="epoch",
159
166
  dims=["epoch"],
160
167
  attrs=epoch_attrs,
@@ -164,8 +171,12 @@ def empty_pset_dataset(
164
171
  "hi_pset_esa_energy_step", check_schema=False
165
172
  ).copy()
166
173
  dtype = attrs.pop("dtype")
167
- # Find the unique, non-zero esa_energy_steps from the L1B data
168
- esa_energy_steps = np.array(sorted(set(l1b_energy_steps) - {0}), dtype=dtype)
174
+ # Find the unique esa_energy_steps from the L1B data
175
+ # Exclude 0 and FILLVAL
176
+ esa_energy_steps = np.array(
177
+ sorted(set(l1b_energy_steps.values) - {0, l1b_energy_steps.attrs["FILLVAL"]}),
178
+ dtype=dtype,
179
+ )
169
180
  coords["esa_energy_step"] = xr.DataArray(
170
181
  esa_energy_steps,
171
182
  name="esa_energy_step",
@@ -197,6 +208,15 @@ def empty_pset_dataset(
197
208
 
198
209
  # Allocate the coordinate label variables
199
210
  data_vars = dict()
211
+ # Generate the epoch_delta variable
212
+ data_vars["epoch_delta"] = xr.DataArray(
213
+ np.diff(epochs),
214
+ name="epoch_delta",
215
+ dims=["epoch"],
216
+ attrs=attr_mgr.get_variable_attributes(
217
+ "hi_pset_epoch_delta", check_schema=False
218
+ ),
219
+ )
200
220
  # Generate label variables
201
221
  data_vars["esa_energy_step_label"] = xr.DataArray(
202
222
  coords["esa_energy_step"].values.astype(str),
@@ -253,7 +273,7 @@ def pset_geometry(pset_et: float, sensor_str: str) -> dict[str, xr.DataArray]:
253
273
  Returns
254
274
  -------
255
275
  geometry_vars : dict[str, xarray.DataArray]
256
- Keys are variable names and values are data arrays.
276
+ Keys are variable names, and values are data arrays.
257
277
  """
258
278
  geometry_vars = create_dataset_variables(
259
279
  ["despun_z"], (1, 3), att_manager_lookup_str="hi_pset_{0}"
@@ -571,11 +591,26 @@ def find_second_de_packet_data(l1b_dataset: xr.Dataset) -> xr.Dataset:
571
591
  # We should get two CCSDS packets per 8-spin ESA step.
572
592
  # Get the indices of the packet before each ESA change.
573
593
  esa_step = epoch_dataset["esa_step"].values
594
+ esa_energy_step = epoch_dataset["esa_energy_step"].values
595
+ # A change in esa_step should indicate the location of the second packet in
596
+ # each pair of DE packets at an esa_energy_step. In practice, during some
597
+ # calibration activities, it was observed that the esa_energy_step can change
598
+ # when the esa_step did not. So, we look for either to change and use the
599
+ # indices of those changes to identify the second packet in each pair. We
600
+ # also need to add the last packet index and assume an energy step change
601
+ # occurs after the last packet.
574
602
  second_esa_packet_idx = np.append(
575
- np.flatnonzero(np.diff(esa_step) != 0), len(esa_step) - 1
603
+ np.flatnonzero((np.diff(esa_step) != 0) | (np.diff(esa_energy_step) != 0)),
604
+ len(esa_step) - 1,
605
+ )
606
+ # Remove esa energy steps at 0 - these are calibrations
607
+ keep_mask = esa_energy_step[second_esa_packet_idx] != 0
608
+ # Remove esa energy steps at FILLVAL - these are unidentified
609
+ keep_mask &= (
610
+ esa_energy_step[second_esa_packet_idx]
611
+ != l1b_dataset["esa_energy_step"].attrs["FILLVAL"]
576
612
  )
577
- # Remove esa steps at 0 - these are calibrations
578
- second_esa_packet_idx = second_esa_packet_idx[esa_step[second_esa_packet_idx] != 0]
613
+ second_esa_packet_idx = second_esa_packet_idx[keep_mask]
579
614
  # Remove indices where we don't have two consecutive packets at the same ESA
580
615
  if second_esa_packet_idx[0] == 0:
581
616
  logger.warning(
@@ -584,7 +619,8 @@ def find_second_de_packet_data(l1b_dataset: xr.Dataset) -> xr.Dataset:
584
619
  )
585
620
  second_esa_packet_idx = second_esa_packet_idx[1:]
586
621
  missing_esa_pair_mask = (
587
- esa_step[second_esa_packet_idx - 1] != esa_step[second_esa_packet_idx]
622
+ esa_energy_step[second_esa_packet_idx - 1]
623
+ != esa_energy_step[second_esa_packet_idx]
588
624
  )
589
625
  if missing_esa_pair_mask.any():
590
626
  logger.warning(
@@ -629,9 +665,11 @@ def get_de_clock_ticks_for_esa_step(
629
665
  # ESA step group so this match is the end time. The start time is
630
666
  # 8-spins earlier.
631
667
  spin_start_mets = spin_df.spin_start_met.to_numpy()
632
- # CCSDS MET has one second resolution, add one to it to make sure it is
633
- # greater than the spin start time it ended on.
634
- end_time_ind = np.flatnonzero(ccsds_met + 1 >= spin_start_mets).max()
668
+ # CCSDS MET has one second resolution, add two to it to make sure it is
669
+ # greater than the spin start time it ended on. Theotretically, adding
670
+ # one second should be sufficeint, but in practice, with flight data, adding
671
+ # two seconds was found to be necessary.
672
+ end_time_ind = np.flatnonzero(ccsds_met + 2 >= spin_start_mets).max()
635
673
 
636
674
  # If the minimum absolute difference is greater than 1/2 the spin-phase
637
675
  # we have a problem.