From d38c138ae5d7d808560834a78a5cfa54608e73a6 Mon Sep 17 00:00:00 2001
From: Hampus Wikmark Kreuger <hampus.wikmark@physics.uu.se>
Date: Tue, 28 Jun 2022 15:11:13 +0200
Subject: [PATCH] Add energy calibration and associated helper functions to
 hrixs class

---
 src/toolbox_scs/detectors/hrixs.py | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/src/toolbox_scs/detectors/hrixs.py b/src/toolbox_scs/detectors/hrixs.py
index 217c4e9..70c9a23 100644
--- a/src/toolbox_scs/detectors/hrixs.py
+++ b/src/toolbox_scs/detectors/hrixs.py
@@ -302,6 +302,9 @@ class hRIXS:
     DARK_MASK_THRESHOLD = 100
     MASK_AVG_X = np.s_[1850:2000]
     MASK_AVG_Y = np.s_[500:1500]
+    
+    # Early energy calibration (to estimate mono drift)
+    PIX2EV_POLY = [6.31196512e-02, 6.05502748e+02]
 
     ENERGY_INTERCEPT = 0
     ENERGY_SLOPE = 1
@@ -319,6 +322,23 @@ class hRIXS:
                       'factor', 'range', 'bins',
                       'method', 'fields')
         return {param: getattr(self, param.upper()) for param in params}
+    
+    def pixel2energy(self, pixel):         
+        # Calculates energy based on pixel position from PIX2EV_POLY (re-fit as needed).
+        return np.polyval(self.PIX2EV_POLY, pixel)
+
+    def energy2pixel(self, ev):
+        # Calculates the expected pixel position of a given energy.
+        # Only works (somewhat) predictably for 1st and 2nd order polynomials!
+        if len(self.PIX2EV_POLY)>3:
+            # The length of PIX2EV_POLY is order+1
+            raise ValueError('Too high polynomial order!')
+        epoly = np.poly1d(self.PIX2EV_POLY)
+        pixel = (epoly-ev).roots[-1]
+        if np.imag(pixel) == 0:
+            return pixel
+        else:
+            raise ValueError('Complex root! (Out of fit bounds?)')
 
     def from_run(self, runNB, proposal=None, extra_fields=()):
         if proposal is None:
-- 
GitLab