From 38b8fa1af77b5fe7b51fdb5d7cc74414ebfddbf4 Mon Sep 17 00:00:00 2001
From: Laurent Mercadier <laurent.mercadier@xfel.eu>
Date: Wed, 26 Mar 2025 08:48:48 +0100
Subject: [PATCH] Add option to keep darks of GH2 detector

---
 src/toolbox_scs/detectors/gotthard2.py | 22 +++++++++++++++++++---
 1 file changed, 19 insertions(+), 3 deletions(-)

diff --git a/src/toolbox_scs/detectors/gotthard2.py b/src/toolbox_scs/detectors/gotthard2.py
index 4ff9366..6aea6d9 100644
--- a/src/toolbox_scs/detectors/gotthard2.py
+++ b/src/toolbox_scs/detectors/gotthard2.py
@@ -17,10 +17,11 @@ log = logging.getLogger(__name__)
 
 
 def extract_GH2(ds, run, firstFrame=0, bunchPattern='scs_ppl',
-                gh2_dim='gh2_pId'):
+                gh2_dim='gh2_pId', keep_darks=False):
     '''
     Select and align the frames of the Gotthard-II that have been exposed
-    to light.
+    to light. `keep_darks` gives the option to keep the non-exposed
+    frames.
 
     Parameters
     ------
@@ -36,6 +37,9 @@ def extract_GH2(ds, run, firstFrame=0, bunchPattern='scs_ppl',
         'sa3_pId'.
     gh2_dim: str
         The name of the dimension that corresponds to the Gotthard-II frames.
+    keep_darks: bool
+        If True, the frames that do not correspond to the bunchPattern are
+        kept.
 
     Returns
     -------
@@ -52,10 +56,21 @@ def extract_GH2(ds, run, firstFrame=0, bunchPattern='scs_ppl',
     else:
         pattern = XrayPulses(run)
         dim = 'sa3_pId'
-    others = [var for var in ds if dim in ds[var].coords]
+    others = [var for var in ds if 
+              gh2_dim not in ds[var].dims or dim in ds[var].coords]
     nds = ds.drop_dims(dim, errors='ignore')
+    nds = ds.drop_vars(others, errors='ignore')
+    dark_ds = xr.Dataset()
     if pattern.is_constant_pattern():
         pulse_ids = pattern.peek_pulse_ids(labelled=False)
+        signal_on_gh_ids = pulse_ids + firstFrame
+        if keep_darks:
+            no_signal_ids = [i for i in nds[gh2_dim].values
+                             if i not in signal_on_gh_ids]
+            dark_ds = nds.isel({gh2_dim: no_signal_ids})
+            dark_ds = dark_ds.assign_coords({gh2_dim: no_signal_ids})
+            for n in dark_ds:
+                dark_ds = dark_ds.rename({n: f'{n}_dark'})
         nds = nds.isel({gh2_dim: pulse_ids + firstFrame})
         nds = nds.assign_coords({gh2_dim: pulse_ids})
         nds = nds.rename({gh2_dim: dim})
@@ -71,5 +86,6 @@ def extract_GH2(ds, run, firstFrame=0, bunchPattern='scs_ppl',
                                     dim: np.arange(mask.shape[1])})
         mask = mask.sel({dim: pulse_ids})
         nds = nds.where(mask, drop=True)
+    nds = nds.merge(dark_ds, join='inner')
     ret = ds[others].merge(nds, join='inner')
     return ret
-- 
GitLab