From 3b8f8ddb0a1fad27f7bc74f09f6e367d3bc3d37f Mon Sep 17 00:00:00 2001
From: amitjans <amitjans@ethz.ch>
Date: Fri, 2 Jul 2021 17:33:32 +0200
Subject: [PATCH] Solve trap state and delete useless files. Change realtive
 height of peak width measure

---
 ".\\features\\noise.npy" | Bin 144 -> 0 bytes
 features/region.npy      | Bin 160 -> 0 bytes
 tools.py                 |  39 ++++++++++++++++++---------------------
 3 files changed, 18 insertions(+), 21 deletions(-)
 delete mode 100644 ".\\features\\noise.npy"
 delete mode 100644 features/region.npy

diff --git "a/.\\features\\noise.npy" "b/.\\features\\noise.npy"
deleted file mode 100644
index 8f073d57a5a1b037dfc41eefd3595f3724c10a34..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001

literal 144
zcmbR27wQ`j$;eQ~P_3SlTAW;@Zl$1ZlV+i=qoAIaUsO_*m=~X4l#&V(cT3DEP6dh=
mXCxM+0{I$7I+{8PwF(pfuB756EwVCR4&vXO9`3s>?*ITn&LTws

diff --git a/features/region.npy b/features/region.npy
deleted file mode 100644
index 2f93132a326b48942dae8c06b3e3fbf0b56fb039..0000000000000000000000000000000000000000
GIT binary patch
literal 0
HcmV?d00001

literal 160
zcmbR27wQ`j$;eQ~P_3SlTAW;@Zl$1ZlWC!@qoAIaUsO_*m=~X4l#&V(cT3DEP6dh=
mXCxM+0{I$7ItoUbItsN4WCN~+j0|AV52amMApA}y2n_)8ARTxB

diff --git a/tools.py b/tools.py
index 4d856b1..0978320 100644
--- a/tools.py
+++ b/tools.py
@@ -82,8 +82,8 @@ class Main:
                         'linearity': 'cloud',
                         'max_int': -1,
                         'num_pixels': -1,
-                        'noise_mean': self.trap_state.noise[0],
-                        'noise_std': self.trap_state.noise[1],
+                        'noise_mean': int(self.trap_state.noise[0]),
+                        'noise_std': int(self.trap_state.noise[1]),
                         'reorder_avg': self.count_avg.moving_avg,
                         'reorder_flag': -1,
                         'max_spot_size': -1,
@@ -98,6 +98,7 @@ class Main:
             output['time'] = 60 - int(running_time)
             if running_time >= 60:
                 self.init_time = time.time()
+                self.trap_state.update_trap_state()
 
             # Save variables in self.memory
             self._save_in_memory(output)
@@ -155,8 +156,8 @@ class Main:
             'linearity': linearity,
             'max_int': int(max_int),
             'num_pixels': int(num_pix),
-            'noise_mean': self.trap_state.noise[0],
-            'noise_std': self.trap_state.noise[1],
+            'noise_mean': int(self.trap_state.noise[0]),
+            'noise_std': int(self.trap_state.noise[1]),
             'reorder_avg': self.count_avg.moving_avg,
             'reorder_flag': reorder_flag,
             'max_spot_size': int(max_spot_size),
@@ -270,7 +271,7 @@ class Memory:
         try:
             max_value = self.memory[self.max_idx]
         except IndexError:
-            max_value = np.empty((1, 3))
+            max_value = [[-1, -1, -1]]
 
         return max_value
 
@@ -318,7 +319,6 @@ class TrapState:
         self.noise = [0, 0]
         self.empty = True
 
-        self.update_trap_state()
         self.toggle_ions()
 
     def update_trap_state(self):
@@ -326,9 +326,6 @@ class TrapState:
         Measures contrast (and noise) of the image and determines the state of the trap.
         This function is executed every 60 seconds.
         """
-        _thread = threading.Timer(60, self.update_trap_state)
-        _thread.daemon = True
-        _thread.start()
 
         # Measure contrast and noise
         contrast, self.noise = _contrast_and_noise()
@@ -341,7 +338,7 @@ class TrapState:
         elif not self.empty and contrast:
             self.trap_state = 'Crystallized ions'
         elif not self.empty and not contrast:
-            self.trap_state = 'Bad detection: No contrast but ions detected'
+            self.trap_state = 'No contrast but ions detected'
         else:
             self.trap_state = 'Empty'
 
@@ -384,6 +381,7 @@ def load_image():
     sem = acquire_semaphore_read(settings.SEM_NAME)
     shm = SharedArray.attach(settings.SHM_NAME) >> 4
     image = shm.copy()
+
     del shm
     release_semaphore_read(sem)
     return image
@@ -446,16 +444,16 @@ def ion_roundness(image, center):
 
     c_x = center[0]
     c_y = center[1]
-    image_copy = image_copy[c_x - 25 : c_x + 25, c_y - 25 : c_y + 25]  # crop the image
+    image_copy = image_copy[max(0, c_x - 25) : c_x + 25, max(0, c_y - 25) : c_y + 25]  # crop the image
 
     # get coordinates of ion pixels
-    # TODO: fix this (sometimes the image_copy is empty)
     pca_input = np.swapaxes(np.stack(np.where(image_copy > image_copy.max()*0.5)), 0, 1)
+        
     if len(pca_input) > 1:
         pca = PCA(n_components=2)  # compute PCA
         pca.fit(pca_input)
         var1, var2 = pca.explained_variance_  # return variance of 2 principal components
-        roundness = var2 / var1  # if the ion is a circle, var1 / var2 = 1
+        roundness = var2 / var1  # if the ion is a circle, var2 / var1 = 1
     else:
         roundness = 0
 
@@ -757,9 +755,10 @@ def _contrast_and_noise():
         time.sleep(1) # wait one second
         img2 = load_image() # load image
         _laser_switch(True) # turn on laser
+        time.sleep(1)
     except requests.exceptions.ConnectionError:
         warnings.warn("Connection to API couldn't be stablished.")
-        return None, [0, 0]
+        return None, [-1, -1]
 
     max2 = _max_coord(img2)
     try:
@@ -823,7 +822,7 @@ def _ion_max_spot_size(y):
     Return max width of peaks.
     """
     y = _smooth(y, window_len=15, window='hamming')
-    width, _, _, _ = peak_widths(y, [np.argmax(y)], rel_height=0.75)
+    width, _, _, _ = peak_widths(y, [np.argmax(y)], rel_height=0.5)
     return np.max(width)
 
 
@@ -906,11 +905,9 @@ def _ion_distance(coord):
 def _compare_coord(coord1, coord2):
     same_coord = False
 
-    same_len = len(coord1) == len(coord2)
-    same_type = all(coord1[:, 2] == coord2[:, 2])
-    same_pos = np.abs(coord1[:, :2] - coord2[:, :2]).sum()
-
-    if same_len and same_type and same_pos < 30:
-        same_coord = True
+    if len(coord1) == len(coord2):
+        if all(coord1[:, 2] == coord2[:, 2]):
+            if np.abs(coord1[:, :2] - coord2[:, :2]).sum() < 30:
+                same_coord = True
         
     return same_coord
\ No newline at end of file
-- 
GitLab