From 8215a17a5b820adf1cfebda28c0abb52018c1e7c Mon Sep 17 00:00:00 2001
From: ahmedk <karim.ahmed@xfel.eu>
Date: Tue, 18 Oct 2022 23:42:59 +0200
Subject: [PATCH] Keep only one enum class JungfrauSettings

---
 ...Jungfrau_Gain_Correct_and_Verify_NBC.ipynb |  6 +-
 ...rk_analysis_all_gains_burst_mode_NBC.ipynb | 25 +++----
 ...retrieve_constants_precorrection_NBC.ipynb |  6 +-
 src/cal_tools/enums.py                        | 63 +++++++++-------
 src/cal_tools/jungfraulib.py                  | 75 +++++++------------
 5 files changed, 83 insertions(+), 92 deletions(-)

diff --git a/notebooks/Jungfrau/Jungfrau_Gain_Correct_and_Verify_NBC.ipynb b/notebooks/Jungfrau/Jungfrau_Gain_Correct_and_Verify_NBC.ipynb
index d94448d28..d1b58acf0 100644
--- a/notebooks/Jungfrau/Jungfrau_Gain_Correct_and_Verify_NBC.ipynb
+++ b/notebooks/Jungfrau/Jungfrau_Gain_Correct_and_Verify_NBC.ipynb
@@ -196,11 +196,11 @@
     "    integration_time = ctrl_data.get_integration_time()\n",
     "    bias_voltage = ctrl_data.get_bias_voltage()\n",
     "    gain_setting = ctrl_data.get_gain_setting()\n",
-    "    gain_mode, gain_mode_str = ctrl_data.get_gain_mode()\n",
+    "    gain_mode = ctrl_data.get_gain_mode()\n",
     "\n",
     "print(f\"Integration time is {integration_time} us\")\n",
-    "print(f\"Gain setting is {gain_setting} (run settings: {ctrl_data.settings_value})\")\n",
-    "print(f\"Gain mode is {gain_mode} ({gain_mode_str})\")\n",
+    "print(f\"Gain setting is {gain_setting} (run settings: {ctrl_data.run_settings})\")\n",
+    "print(f\"Gain mode is {gain_mode} ({ctrl_data.run_mode})\")\n",
     "print(f\"Bias voltage is {bias_voltage} V\")\n",
     "print(f\"Number of memory cells are {memory_cells}\")"
    ]
diff --git a/notebooks/Jungfrau/Jungfrau_dark_analysis_all_gains_burst_mode_NBC.ipynb b/notebooks/Jungfrau/Jungfrau_dark_analysis_all_gains_burst_mode_NBC.ipynb
index 74f620a23..3b2aa945f 100644
--- a/notebooks/Jungfrau/Jungfrau_dark_analysis_all_gains_burst_mode_NBC.ipynb
+++ b/notebooks/Jungfrau/Jungfrau_dark_analysis_all_gains_burst_mode_NBC.ipynb
@@ -91,7 +91,6 @@
     "from cal_tools.ana_tools import save_dict_to_hdf5\n",
     "from cal_tools.enums import (\n",
     "    BadPixels,\n",
-    "    JungfrauGainModes,\n",
     "    JungfrauSettings,\n",
     ")\n",
     "from cal_tools.tools import (\n",
@@ -116,17 +115,13 @@
     "sensor_size = (1024, 512)\n",
     "gains = [0, 1, 2]\n",
     "\n",
-    "fixed_settings_old = [\n",
-    "    str(JungfrauSettings.FIX_GAIN_1),\n",
-    "    str(JungfrauSettings.FIX_GAIN_2),\n",
-    "    ]\n",
     "fixed_settings = [\n",
-    "    str(JungfrauGainModes.FIX_GAIN_1),\n",
-    "    str(JungfrauGainModes.FIX_GAIN_2),\n",
-    "]\n",
+    "    JungfrauSettings.FIX_GAIN_1.name,\n",
+    "    JungfrauSettings.FIX_GAIN_2.name,\n",
+    "    ]\n",
     "dynamic_settings = [\n",
-    "    str(JungfrauGainModes.FORCE_SWITCH_HG1),\n",
-    "    str(JungfrauGainModes.FORCE_SWITCH_HG2),\n",
+    "    JungfrauSettings.FORCE_SWITCH_HG1.name,\n",
+    "    JungfrauSettings.FORCE_SWITCH_HG2.name,\n",
     "    ]\n",
     "\n",
     "creation_time = None\n",
@@ -189,7 +184,7 @@
     "            integration_time = ctrl_data.get_integration_time()\n",
     "            bias_voltage = ctrl_data.get_bias_voltage()\n",
     "            gain_setting = ctrl_data.get_gain_setting()\n",
-    "            print(f\"Gain setting is {gain_setting} ({ctrl_data.settings_value})\")\n",
+    "            print(f\"Gain setting is {gain_setting} ({ctrl_data.run_settings})\")\n",
     "            print(f\"Integration time is {integration_time} us\")\n",
     "            print(f\"Bias voltage is {bias_voltage} V\")\n",
     "        if run_mcells == 1:\n",
@@ -201,9 +196,9 @@
     "            print('Dark runs in burst mode, '\n",
     "                  f'storage cell start: {sc_start:02d}')\n",
     "    else:\n",
-    "        gain_mode, gain_mode_str = ctrl_data.get_gain_mode()\n",
+    "        gain_mode = ctrl_data.get_gain_mode()\n",
     "\n",
-    "        med_low_settings.append(gain_mode_str)\n",
+    "        med_low_settings.append(JungfrauSettings(ctrl_data.run_mode).name)\n",
     "\n",
     "# A transperent workaround for old raw data with wrong/missing medium and low settings\n",
     "if med_low_settings == [None, None]:\n",
@@ -213,10 +208,10 @@
     "    print(f\"WARNING: run.settings for medium and low gain runs are wrong {med_low_settings}. \"\n",
     "          f\"This is an expected bug for old raw data. Setting gain_mode to {gain_mode}.\")\n",
     "# Validate that low_med_settings is not a mix of adaptive and fixed settings.\n",
-    "elif not (sorted(med_low_settings) in [fixed_settings, dynamic_settings, fixed_settings_old]):  # noqa\n",
+    "elif not (sorted(med_low_settings) in [fixed_settings, dynamic_settings]):  # noqa\n",
     "    raise ValueError(\n",
     "        \"Medium and low run settings are not as expected. \"\n",
-    "        f\"Either {dynamic_settings}, {fixed_settings}, or {fixed_settings_old} are expected.\\n\"\n",
+    "        f\"Either {dynamic_settings} or {fixed_settings} are expected.\\n\"\n",
     "        f\"Got {sorted(med_low_settings)} for both runs, respectively.\")\n",
     "\n",
     "print(f\"Gain mode is {gain_mode} ({med_low_settings})\")\n",
diff --git a/notebooks/Jungfrau/Jungfrau_retrieve_constants_precorrection_NBC.ipynb b/notebooks/Jungfrau/Jungfrau_retrieve_constants_precorrection_NBC.ipynb
index 2c33e2de4..50115ad43 100644
--- a/notebooks/Jungfrau/Jungfrau_retrieve_constants_precorrection_NBC.ipynb
+++ b/notebooks/Jungfrau/Jungfrau_retrieve_constants_precorrection_NBC.ipynb
@@ -117,11 +117,11 @@
     "    integration_time = ctrl_data.get_integration_time()\n",
     "    bias_voltage = ctrl_data.get_bias_voltage()\n",
     "    gain_setting = ctrl_data.get_gain_setting()\n",
-    "    gain_mode, gain_mode_str = ctrl_data.get_gain_mode()\n",
+    "    gain_mode = ctrl_data.get_gain_mode()\n",
     "\n",
     "print(f\"Integration time is {integration_time} us\")\n",
-    "print(f\"Gain setting is {gain_setting} (run settings: {ctrl_data.settings_value}\")\n",
-    "print(f\"Gain mode is {gain_mode} ({gain_mode_str})\")\n",
+    "print(f\"Gain setting is {gain_setting} (run settings: {ctrl_data.run_settings}\")\n",
+    "print(f\"Gain mode is {gain_mode} ({ctrl_data.run_mode})\")\n",
     "print(f\"Bias voltage is {bias_voltage} V\")\n",
     "print(f\"Number of memory cells are {memory_cells}\")"
    ]
diff --git a/src/cal_tools/enums.py b/src/cal_tools/enums.py
index 735ed2939..7231c5700 100644
--- a/src/cal_tools/enums.py
+++ b/src/cal_tools/enums.py
@@ -47,31 +47,44 @@ class AgipdGainMode(IntEnum):
 
 
 class JungfrauSettings(Enum):
-    """Jungfrau run gain settings."""
-    GAIN_0 = "gain0"
-    HIGH_GAIN_0 = "highgain0"
-
-    # Jungfrau run gain settings before hardware update. (End of 2022)
-    # https://git.xfel.eu/karaboDevices/slsDetectors/-/commit/4433ae9c00edcca3309bec8b7515e0938f5f502c  # noqa
-
-    DYNAMIC_GAIN = "dynamicgain"
-    DYNAMIC_GAIN_HG0 = "dynamichg0"
-    FIX_GAIN_1 = "fixgain1"
-    FIX_GAIN_2 = "fixgain2"
-    FORCE_SWITCH_HG1 = "forceswitchg1"
-    FORCE_SWITCH_HG2 = "forceswitchg2"
-
-    def __str__(self):
-        return str(self.value)
-
-
-class JungfrauGainModes(Enum):
-    """Jungfrau run gain modes."""
-    DYNAMIC = "dynamic"
-    FIX_GAIN_1 = "fixg1"
-    FIX_GAIN_2 = "fixg2"
+    """Jungfrau run gain settings.
+
+    Jungfrau run gain settings was updated around the end of 2022
+    https://git.xfel.eu/karaboDevices/slsDetectors/-/commit/4433ae9c00edcca3309bec8b7515e0938f5f502c  # noqa
+
+    settings_lookup = {  # old setting:  new setting, new mode
+        "dynamicgain": ("gain0", "dynamic"),
+        "dynamichg0":  ("highgain0", "dynamic"),
+        "fixgain1": ("fixg1"),
+        "fixgain2": ("fixg2"),
+        "forceswitchg1": ("forceswitchg1"),
+        "forceswitchg2": ("forceswitchg2"),
+    }
+    """
+    # old setting, new setting, new mode
+    DYNAMIC_GAIN = ("dynamicgain", "gain0", "dynamic")
+    DYNAMIC_GAIN_HG0 = ("dynamichg0", "highgain0", "dynamic")
+    # old setting, new mode
+    FIX_GAIN_1 = ("fixgain1", "fixg1")
+    FIX_GAIN_2 = ("fixgain2", "fixg2")
+    # old setting = new mode
     FORCE_SWITCH_HG1 = "forceswitchg1"
     FORCE_SWITCH_HG2 = "forceswitchg2"
 
-    def __str__(self):
-        return str(self.value)
+    def __eq__(self, other):
+        return other in self.__dict__['_value_']
+
+    def __new__(cls, *values):
+        obj = object.__new__(cls)
+        for other_value in values:
+            cls._value2member_map_[other_value] = obj
+        obj._all_values = values
+        return obj
+        
+    def __repr__(self):
+        """Display all enum values."""
+        return "<%s.%s: %s>" % (
+                self.__class__.__name__,
+                self._name_,
+                ', '.join([repr(v) for v in self._all_values]),
+                )
diff --git a/src/cal_tools/jungfraulib.py b/src/cal_tools/jungfraulib.py
index aa6e4a41c..63ae54459 100644
--- a/src/cal_tools/jungfraulib.py
+++ b/src/cal_tools/jungfraulib.py
@@ -1,23 +1,19 @@
-from typing import Optional, Tuple, Union
+from typing import Optional, Tuple
 
 import extra_data
 
-from cal_tools.enums import JungfrauGainModes, JungfrauSettings
+from cal_tools.enums import JungfrauSettings
 
 
 def _get_settings(
     run_dc: extra_data.DataCollection,
     ctrl_src: str
     ) -> Optional[str]:
-    """Get run settings string value and identify
-    the enum to use for the jungfau run settings.
-    """
+    """Get JUNGFRAU run settings."""
     try:
         return run_dc.get_run_value(ctrl_src, "settings")
     except extra_data.PropertyNameError:
-        print(
-            "WARNING: \'settings.value\' key is not available for this run.")
-
+        print("WARNING: \'settings.value\' key is not available for this run.")
 
 class JungfrauCtrl():
     def __init__(
@@ -31,7 +27,15 @@ class JungfrauCtrl():
         """
         self.run_dc = run_dc
         self.ctrl_src = ctrl_src
-        self.settings_value = _get_settings(run_dc, ctrl_src)
+        self.run_settings = _get_settings(run_dc, ctrl_src)
+        self.run_mode = self._get_mode()
+
+    def _get_mode(self) -> Optional[str]:
+        """Get JUNGFRAU run settings."""
+        try: # After Junfrau V5 (End of 2022) update `gainMode` is available.
+            return self.run_dc.get_run_value(self.ctrl_src, "gainMode")
+        except extra_data.PropertyNameError:
+            return self.run_settings
 
     def get_memory_cells(self) -> Tuple[int, int]:
         n_storage_cells = int(self.run_dc.get_run_value(
@@ -58,32 +62,18 @@ class JungfrauCtrl():
         """Get run gain settings to identify if run is in
         High CDS or Low CDS.
         """
-        if (
-            self.settings_value == str(JungfrauSettings.GAIN_0) or
-            self.settings_value == str(JungfrauSettings.DYNAMIC_GAIN_HG0)
-            ):
+        gain_setting = 0  # e.g. For JungfrauSettings.DYNAMIC_GAIN
+        if self.run_settings == JungfrauSettings.DYNAMIC_GAIN_HG0:
             gain_setting = 1
-        else:  # JungfrauSettings.DYNAMIC_GAIN or JungfrauSettings.HIGH_GAIN_0
-            gain_setting = 0
-            # Old RAW data didn't have the key `setting.value`
-            print(
-                "WARNING: Setting \'gain_setting\' to 0, "
-                "assuming that this is an old run. "
-                f"\'settings.value\' = {self.settings_value}.\n")
-        return gain_setting
+        elif self.run_settings is None:
+             # Old RAW data didn't have the key `setting.value`
+            print("Setting \'gain_setting\' to 0, "
+                  "assuming that this is an old run. "
+                  f"\'settings.value\' = {self.run_settings}.\n")
 
-    def _get_gain_mode_settings(self) -> Tuple[int, JungfrauSettings]:
-        """Gain Mode is fixed (1) if the enum
-        is fixgain1 or fixgain2.
-        """
-        if self.settings_value in [
-                str(JungfrauSettings.FIX_GAIN_1),
-                str(JungfrauSettings.FIX_GAIN_2)]:
-            return 1, self.settings_value
-        else:
-            return 0, self.settings_value
+        return gain_setting
 
-    def _get_gain_mode_run(self) -> Tuple[int, JungfrauGainModes]:
+    def get_gain_mode(self) -> int:
         """From Jungfrau SW V5 gain_mode is deducted from
         /RUN/..../gainMode.
         With different enums: dynamic, fixg1, fixg2,
@@ -91,18 +81,11 @@ class JungfrauCtrl():
         if the value is 0 or 1.
         Gain Mode is fixed (1) if the enum is fixg1 or fixg2.
         """
-        gain_mode = self.run_dc.get_run_value(self.ctrl_src, "gainMode")
-        if gain_mode in [
-                str(JungfrauGainModes.FIX_GAIN_1),
-                str(JungfrauGainModes.FIX_GAIN_2)]:
-            return 1, gain_mode
-        else:
-            return 0, gain_mode
 
-    def get_gain_mode(
-        self
-    ) -> Tuple[int, Union[JungfrauSettings, JungfrauGainModes]]:
-        try:  # After Junfrau V5 (End of 2022) update `gainMode` is available.
-            return self._get_gain_mode_run()
-        except extra_data.PropertyNameError:
-            return self._get_gain_mode_settings()
+        if (
+            self.run_mode == JungfrauSettings.FIX_GAIN_1 or
+            self.run_mode == JungfrauSettings.FIX_GAIN_2
+            ):
+            return 1
+        else:
+            return 0
-- 
GitLab