From 77a6274e029aee9effa02ad573bd23475b09f83a Mon Sep 17 00:00:00 2001
From: Luca Scarabello <luca.scarabello@sed.ethz.ch>
Date: Thu, 2 Mar 2017 12:54:13 +0100
Subject: [PATCH] mpi bug fix: duplicated events

---
 mpi/template_matching.py | 24 +++++++++++++-----------
 1 file changed, 13 insertions(+), 11 deletions(-)

diff --git a/mpi/template_matching.py b/mpi/template_matching.py
index 4a31ea6..354a9e2 100644
--- a/mpi/template_matching.py
+++ b/mpi/template_matching.py
@@ -367,18 +367,20 @@ class TemplateMatching(object):
         for detection in xcorr_results:
             time, amp, ccc = detection
             #
-            # Check the same event has not already been found (because of chuks overlapping)
+            # Check the same event has not already been found (because of chunks overlapping)
             #
-            i = self.events.bisect_key_left(time) # Locate the leftmost value exactly equal to time
-            if i != len(self.events):
-                ev_time, ev_amp, ev_template, ev_ccc = self.events[i]
-                if (ev_template == template+1 and
-                    abs(ev_time - time) <= 0.1): #tolerance 0.1 seconds
-                    self.logger.info("duplicated event found (%s)" % str(self.events[i]) )
-                    continue
-            ev = (time, amp, template+1, ccc)
-            new_events.append(ev)
-            self.logger.debug('New events found  (%s)' % str(ev) )
+            duplicate = False
+            tolerance = 0.1
+            for e in self.events.irange_key(min_key=time-tolerance, max_key=time+tolerance):
+                ev_time, ev_amp, ev_template, ev_ccc = e
+                if (ev_template == template+1 and abs(ev_time - time) <= tolerance):
+                    self.logger.info("Duplicated event found (%s, %d)" % (str(detection), template) )
+                    duplicate = True
+                    break
+            if not duplicate:
+                ev = (time, amp, template+1, ccc)
+                new_events.append(ev)
+                self.logger.debug('New events found  (%s)' % str(ev) )
 
         self.events.update(new_events)
 
-- 
GitLab