7 Commits 7e865b6a6c ... a815483c4c

Autor SHA1 Mensagem Data
  kapture2 a815483c4c fixes 4 anos atrás
  kapture2 a53880a7f0 fixes 4 anos atrás
  kapture2 a84c5898c5 fixes 4 anos atrás
  kapture2 9ff7aa2dc8 fix in CalibrationUpdater 4 anos atrás
  kapture2 b9a15daea5 added shiftFMC2 to Logfile 4 anos atrás
  kapture2 5693b24345 bugfixes in Correlation 4 anos atrás
  kapture2 99e4238749 fixes 4 anos atrás

+ 3 - 3
KCG/base/ControlWidget.py

@@ -260,7 +260,7 @@ class BoardControl(kcgw.KCGWidgets):
                                                                         "NOTE: ONLY DO THIS IF BOARD WAS CALIBRATED AND SYNCHRONIZED BEFORE"))
             
             self.set_default_button = self.createButton(text=tr("Button", "Set Defaults"), connect=lambda x: bif.bk_write_values(board_id=board_id, defaults=True))
-            #self.soft_reset_button  = self.createButton(text=tr("Button", "Soft Reset"),   connect=lambda x: bif.bk_soft_reset(board_id=board_id))
+            self.soft_reset_button  = self.createButton(text=tr("Button", "Soft Reset"),   connect=lambda x: bif.bk_soft_reset(board_id=board_id))
             #self.off_button         = self.createButton(text=tr("Button", "Board Off"),    connect=lambda x: bif.bk_stop_board(board_id=board_id))
             #self.off_button.setObjectName("off")
             self.check_status_button = self.createButton(text=tr("Button", "Check Status"), connect=lambda x: bif._bif_status_readout(board_id=board_id))
@@ -296,7 +296,7 @@ class BoardControl(kcgw.KCGWidgets):
             Elements.addItem('no_board_{}'.format(board_id),
                              [ 
                                  self.set_default_button,
-                                 #self.soft_reset_button,
+                                 self.soft_reset_button,
                                  #self.off_button,
                                  self.all_in_one_button
                              ])
@@ -305,7 +305,7 @@ class BoardControl(kcgw.KCGWidgets):
             self.mainControlLayout.addWidget(self.toggleButton)
             self.mainControlLayout.addWidget(self.skip_init_button)
             
-            #self.mainControlLayout.addWidget(self.soft_reset_button)
+            self.mainControlLayout.addWidget(self.soft_reset_button)
             #self.mainControlLayout.addWidget(self.off_button)
 
             self.statusLayout.addWidget(self.check_status_button)

+ 24 - 16
KCG/base/backend/CalibrationUpdater.py

@@ -254,10 +254,7 @@ class CalibrationUpdater(kcgw.KCGWidgets):
         pass
 
     def on_cancel(self, param):
-        if self.running:
-            theCalibration.closeHandle(self.calibId)
-            self.timeScan.calibId = self.old_id
-        self.parent.updater=None
+        
         self.close()
         pass
 
@@ -314,23 +311,29 @@ class CalibrationUpdater(kcgw.KCGWidgets):
             self.originalnotplotted = False
             self.all_plot_widget.plotItem.clear()
             for i in self.workingChannels:
-                scanx, scany, scane = self.timeScan.getScanOverTime(i, False, False, bunch=self.multiBunchSelector.value())
-                self.all_plot_widget.plotItem.plot(scanx, scany, pen=None, symbolPen=pg.mkPen(colours[i]), symbolSize=4, pxMode=True, symbolBrush=pg.mkBrush(colours[i]), downsample=200)
+                try:
+                    scanx, scany, scane = self.timeScan.getScanOverTime(i, False, False, bunch=self.multiBunchSelector.value())
+                    self.all_plot_widget.plotItem.plot(scanx, scany, pen=None, symbolPen=pg.mkPen(colours[i]), symbolSize=4, pxMode=True, symbolBrush=pg.mkBrush(colours[i]), downsample=200)
+                except:
+                    pass
                 
 
         
         self.calibrated_plot.plotItem.clear()
         for i in self.workingChannels:
-            scanx, scany, scane = self.timeScan.getScanOverTime(i, True, True, force=i==0, bunch=self.multiBunchSelector.value())
-            
-            sorter = np.argsort(scanx)
-            scanx = scanx[sorter]
-            scany = scany[sorter]
-            N=3
-            scanyAvg = np.convolve(scany, np.ones((N,))/N, mode='valid') 
-
-            self.calibrated_plot.plotItem.plot(scanx, scany, pen=None, symbolPen=pg.mkPen(colours[i]), symbolSize=4, pxMode=True, symbolBrush=pg.mkBrush(colours[i]), downsample=200)
-            self.calibrated_plot.plotItem.plot(scanx[1:-1], scanyAvg, pen=pg.mkPen(colours[i]), downsample=200)
+            try:
+                scanx, scany, scane = self.timeScan.getScanOverTime(i, True, True, force=i==0, bunch=self.multiBunchSelector.value())
+                
+                sorter = np.argsort(scanx)
+                scanx = scanx[sorter]
+                scany = scany[sorter]
+                N=3
+                scanyAvg = np.convolve(scany, np.ones((N,))/N, mode='valid') 
+
+                self.calibrated_plot.plotItem.plot(scanx, scany, pen=None, symbolPen=pg.mkPen(colours[i]), symbolSize=4, pxMode=True, symbolBrush=pg.mkBrush(colours[i]), downsample=200)
+                self.calibrated_plot.plotItem.plot(scanx[1:-1], scanyAvg, pen=pg.mkPen(colours[i]), downsample=200)
+            except:
+                pass
                 
         self.processbarWidget.close()
         self.processbarWidget = None
@@ -343,6 +346,11 @@ class CalibrationUpdater(kcgw.KCGWidgets):
         Event handler for closing this window
         """
         #reopen file so that it is in read only mode
+        if self.running:
+            theCalibration.closeHandle(self.calibId)
+            self.timeScan.calibId = self.old_id
+            self.calibId = self.old_id
+
         theCalibration.openFile(self.calibId, force=True)
         if self.processbarWidget is not None:
             self.processbarWidget.close()

+ 7 - 2
KCG/base/backend/DataSet.py

@@ -291,8 +291,8 @@ class DataSet(object):
 
         :return: 2D List [0] contains X data and Y data of all. [1] only for selected adc
         """
-        if len(working_channels) < 2:
-            raise ValueError('working_channels must have at least 2 channels; {}'.format(working))
+        if len(workingChannels) < 2:
+            raise ValueError('working_channels must have at least 2 channels; {}'.format(workingChannels))
 
         if turnbyturn:
             if to != -1:
@@ -676,6 +676,11 @@ class DataSet(object):
                 self.workingChannels = np.array([float(v) for v in self.log['Working Channels'][1:-1].split(',')])
             except:
                 self.workingChannels = None
+                
+            try:
+                self.shiftFMC2 = int(self.log['shiftFMC2'])
+            except:
+                pass
             #print('get good')
             return True
         except:

+ 21 - 12
KCG/base/backend/board/board_config.py

@@ -75,14 +75,14 @@ class BoardConfiguration(QtGui.QWidget):
             'chip_delay_factor': 3,
 
             
-            'delay_330_max': 20, #technisch 522 #min is 5 - wird in observer berucksichtigt
+            'delay_330_max': 20, #technical 522 #be aware: changing this makes the Delay Calibration invalid!
             'delay_330_factor': 330,
             'delay_330_th':   0,
             'delay_330_adc':  1,
             'delay_330_fpga': 1,
 
             #-Kapture 2 only--------------------
-            'delay_25_max' : 23,
+            'delay_25_max' : 23, #be aware: changing this makes the Delay Calibration invalid!
             'delay_25_factor': 25,
             'delay_25_th':   0,
             'delay_25_adc':  10,
@@ -99,8 +99,8 @@ class BoardConfiguration(QtGui.QWidget):
 
             'delay_cascade_max': 20,
             'delay_cascade_factor': 330,
-            'delay_cascade': 5,
-            'delay_cascade_25': 13,
+            'delay_cascade': 0,
+            'delay_cascade_25': 14,
 
             #-Clock Division--------------
             'clk_div': 6,
@@ -283,6 +283,9 @@ class BoardConfiguration(QtGui.QWidget):
         """
         Set observers that are always used
         """
+        def obsprint(x,y):
+            print(x, y)
+        self.observe_all(obsprint)
         self.observe_write(self._update_header, 'header')
         self.observe_write(self._update_pilot_bunch, 'pilot_bunch')
         
@@ -293,14 +296,16 @@ class BoardConfiguration(QtGui.QWidget):
             self.observe_write(self._set_adc_gain,   'adc_gain')
             self.observe_write(self._set_adc_offset, 'adc_offset')
 
-            #Setup Long delay 330ps. Value needs to be shifted to the left because first bit is used vor halfstep
+            #Attention: the th delays are inverted! Means: due to the internal setup by increasing the value the sampling
+                #would be earlier. This is not intuitive therefore the gui inverts the value by using the delay_max as offset.
+            #Setup Long delay 330ps. Value needs to be shifted to the left because first bit is used to set halfstep
             self.observe_write(lambda x: pci.write(self.identifier, hex((x+5)<<1), '0x9090'), 'delay_330_adc')
             self.observe_write(lambda x: pci.write(self.identifier, hex((self._config['delay_330_max']-x+5)<<1), '0x90B0'), 'delay_330_th')
             self.observe_write(lambda x: pci.write(self.identifier, hex((x+5)<<1), '0x90C0'), 'delay_330_fpga')
 
             self.observe_write(lambda x: pci.write(self.identifier, hex((x+5)<<1), '0x90D0'), 'delay_cascade')
             
-            #Setup short Delay 25ps
+            #Setup short Delay 25ps.
             self.observe_write(lambda x: pci.write(self.identifier, hex(x), '0x9094'), 'delay_25_adc')
             self.observe_write(lambda x: pci.write(self.identifier, hex(self._config['delay_25_max']-x), '0x90B4'), 'delay_25_th')
             #self.observe_write(lambda x: pci.write(self.identifier, hex(x), '0x90C4'), 'delay_25_fpga')
@@ -653,12 +658,14 @@ class BoardConfiguration(QtGui.QWidget):
 
     def _set_samplingrate(self, rate):
         return
-        if rate == 1:
+        if rate == 1: 
+            #500 MHz
             self.update('delay_25_adc', 10)
             self.update('delay_330_adc', 1)#
             self.update('delay_25_adc_2', 10)
             self.update('delay_330_adc_2', 1)
         elif rate == 2:
+            #1 GHz
             self.update('delay_25_adc', 10)
             self.update('delay_330_adc', 0)
             self.update('delay_25_adc_2', 10)
@@ -672,6 +679,8 @@ class BoardConfiguration(QtGui.QWidget):
         #sleep(0.1)
         self.update('delay_330_th_2', 0)
         sleep(0.1)
+        self.update('delay_25_th_2', 3)
+        sleep(0.1)
         self.update('delay_25_th_2', 4)
         sleep(0.1)
         self.update('chip_delay', [0,0,0,0, 0,0,0,0])
@@ -706,15 +715,15 @@ class BoardConfiguration(QtGui.QWidget):
 
             # --[ read and set th delay ]--
             val = pci.read(self.identifier, reg='90B0')[0]
-            self.update('delay_330_th', self._config['delay_330_max']-((int(val, 16)>>1)-5), write=False)
+            self.update('delay_330_th', self._config['delay_330_max'] - ((int(val, 16)>>1)-5), write=False)
             val = pci.read(self.identifier, reg='90B4')[0]
-            self.update('delay_25_th', int(val, 16), write=False)
+            self.update('delay_25_th',  self._config['delay_25_max'] - int(val, 16), write=False)
             val = pci.read(self.identifier, reg='90B8')[0]
             self.update('clk_div_th', int(val, 16), write=False)
 
             # --[ read and set adc delay ]--
             val = pci.read(self.identifier, reg='9090')[0]
-            self.update('delay_330_adc', self._config['delay_25_max']-((int(val, 16)>>1)-5), write=False)
+            self.update('delay_330_adc', (int(val, 16)>>1)-5, write=False)
             val = pci.read(self.identifier, reg='9094')[0]
             self.update('delay_25_adc', int(val, 16), write=False)
             val = pci.read(self.identifier, reg='9098')[0]
@@ -743,14 +752,14 @@ class BoardConfiguration(QtGui.QWidget):
             # --[ read FMC 2 ] --
             # --[ FMC2 read and set th delay ]--
             val = pci.read(self.identifier, reg='90A8')[0]
-            self.update('delay_330_th_2', self._config['delay_330_max']-((int(val, 16)>>1)-5), write=False)
+            self.update('delay_330_th_2', ((int(val, 16)>>1)-5), write=False)
             val = pci.read(self.identifier, reg='90AC')[0]
             self.update('delay_25_th_2', int(val, 16), write=False)
             
 
             # --[ FCM 2 read and set adc delay ]--
             val = pci.read(self.identifier, reg='90A0')[0]
-            self.update('delay_330_adc_2', self._config['delay_25_max']-((int(val, 16)>>1)-5), write=False)
+            self.update('delay_330_adc_2', ((int(val, 16)>>1)-5), write=False)
             val = pci.read(self.identifier, reg='90A4')[0]
             self.update('delay_25_adc_2', int(val, 16), write=False)
         

+ 2 - 1
KCG/base/backend/board/sequences/sequences_7.json

@@ -109,7 +109,8 @@
                 "0x301400C5", "0x9060",
                 "",
                 "OUT10",
-                "delay_330_th", "0"
+                "delay_330_th", "0",
+                "delay_25_th", "0"
             ],
             [
                 "0x33035006", "0x9060",

+ 3 - 1
KCG/base/backendinterface.py

@@ -190,6 +190,8 @@ def bk_run_sequence(board_id, name):
         bk_status_readout()
         progressbar.remove(0)
         _bif_disable_wait_cursor()
+        board.get_board_config(board_id).update('header',      board.get_board_config(board_id)._config['header'])
+        board.get_board_config(board_id).update('pilot_bunch', board.get_board_config(board_id)._config['pilot_bunch'])
 
     progressbar = _bif_ProgressBar(0, 10, tr("sw", comment))
 
@@ -438,7 +440,7 @@ def bk_change_pilot_bunch(board_id, value, silent=False):
 
 def _bif_update_working_dir():
     """
-    make Shure the currently set directory exists an a calibration File is present
+    make Shure the currently set directory exists and a calibration File is present
     """
     path = str(os.path.join(storage.storage.save_location, storage.storage.subdirname))
     print(path)

+ 2 - 1
KCG/base/log.py

@@ -72,7 +72,8 @@ class MeasurementLogger(object):
             ["ADC Delays", [bif.bk_get_config, (BOARDID, 'chip_delay')]],
             ["Delay Cascade", [bif.bk_get_config, (BOARDID, 'delay_cascade')]],
             ["Delay Cascade 25ps", [bif.bk_get_config, (BOARDID, 'delay_cascade_25')]],
-            ["Working Channels", [lambda x: config.working_channels, (1)]]
+            ["Working Channels", [lambda x: config.working_channels, (1)]],
+            ["shiftFMC2", [lambda x: config.shiftFMC2, (1)]]
             #["ADC 1 Delay", [bif.bk_get_config, (BOARDID, 'chip_delay', 0)]],
             #["ADC 2 Delay", [bif.bk_get_config, (BOARDID, 'chip_delay', 1)]],
             #["ADC 3 Delay", [bif.bk_get_config, (BOARDID, 'chip_delay', 2)]],

+ 2 - 1
KCG/default_config.cfg

@@ -90,7 +90,8 @@ default_log_entries = [
     "25ps Delay 2",
     "Delay Cascade",
     "Delay Cascade 25ps",
-    "Working Channels"
+    "Working Channels",
+    "shiftFMC2"
     ]
 
 

+ 1 - 1
KCG/widgets/AcquireSettingsWidget.py

@@ -523,7 +523,7 @@ class AcquireSettingsWidget(kcgw.KCGWidgets):
             wid.closeEvent(event)
         __widget_id__ = None
         del self.par.widgets[self.id]
-        super(AcquireSettings, self).closeEvent(event)
+        super(AcquireSettingsWidget, self).closeEvent(event)
 
 
 def addAcquireSettingsWidget(board_id=None):

+ 2 - 0
KCG/widgets/ConfigSetup.py

@@ -260,6 +260,8 @@ class ConfigSetup(kcgw.KCGWidgets):
                             '"T/H Delay 2" \n'
                             '"Delay Cascade" \n'
                             '"Delay Cascade 2" \n'
+                            '"Working Channels"\n'
+                            '"shiftFMC2"\n'
                             'NOTE: These entries have to match the aforementioned strings exactly'
                     ]
     machine_configs = ['bunches_per_turn',

+ 23 - 7
KCG/widgets/CorrelationCorrection.py

@@ -9,10 +9,16 @@ import h5py
 import os
 import ast
 import sys
+import traceback
 
 from time import time, sleep
 
-
+try:
+    #for KCG
+    from ..base import kcgwidget as kcgw
+except:
+    #for Analysis GUI
+    import kcgwidget as kcgw
 
 
 import matplotlib
@@ -173,12 +179,22 @@ class CorrelationCorrection(QtCore.QObject):
         self.deltaVarianz = 15
         self.deltaMean    = 10
 
-        self._generateSimulationData(plotting)
-        self._runReconstruction()
-        self._calculateCorrections(plotting)
-        if plotting:
-            plt.show(block=False)
+        try:
+            self._generateSimulationData(plotting)
+            self._runReconstruction()
+            self._calculateCorrections(plotting)
+            if plotting:
+                plt.show(block=False)
+        except:
+            traceback.print_exc()
+            #popup = kcgw.PopupDialog("There was an error",
+            #                    title='Reminder', okonly=True)
+            #popup.exec_()
+            #popup.deleteLater()
+            #popup.get_return_value()
 
+            
+            pass
         self.stopSignal.emit()
         
         pass
@@ -321,7 +337,7 @@ class CorrelationCorrection(QtCore.QObject):
 
             
             scp = ssh.open_sftp()
-            #scp.put(localfile, remotefile, progress)
+            scp.put(localfile, remotefile)#, progress)
             scp.put(os.path.join(localpath, 'Measurement_board_6028.log'), self.remotepath+'simulationData/Measurement_board_6028.log', progress)
 
             print('calc')

+ 12 - 2
KCG/widgets/CorrelationWidget.py

@@ -271,10 +271,17 @@ class CorrelationWidget(kcgw.KCGWidgets):
         if self.thread.running:
             logging.info("already running")
             return
-        self.processbarWidget = WaitingWidget(self)
+        #self.processbarWidget = WaitingWidget(self)
+
+        self.popup = kcgw.PopupDialog("Please Wait\nSimulation ongoing",
+                            title='Running', okonly=True)
+        self.popup.show()
+        #self.popup.deleteLater()
+        #self.popup.get_return_value()
 
         scanx, scany, scane = self.timeScan.getScanOverTime(0, True, True)
-        self.updater = CorrelationCorrection(os.path.dirname(self.timeScan.fileName), scanx, scany, self.delays, workingChannels=self.workingChannels)
+        #self.updater = CorrelationCorrection(os.path.dirname(self.timeScan.fileName), scanx, scany, self.delays, workingChannels=self.workingChannels)
+        self.updater = CorrelationCorrection(os.path.dirname(self.timeScan.fileName), self.scanxAll, self.scanyAll, self.delays, workingChannels=self.workingChannels)
         self.thread.register(self.updater)
         self.thread.connect('stopSignal', self._threadStop)
         self.thread.start('run')
@@ -305,12 +312,15 @@ class CorrelationWidget(kcgw.KCGWidgets):
     def on_cancel(self, param):
         if self.thread.running:
             self.thread.stop()
+            print('on_cancel')
             self.parent.updater=None
         #self.close()
         pass
 
     def _threadStop(self):
         self.thread.stop()
+        print('_threadStop')
+        self.popup.close()
         if self.processbarWidget is not None:
             self.processbarWidget.close()
 

+ 3 - 3
KCG/widgets/PlotWidget.py

@@ -1140,16 +1140,16 @@ class PlotWidget(kcgw.KCGWidgets):
                                   fft_mode = self.fft_mode.currentIndex(),
                                   log=self.fft_log.isChecked())
         if type == PlotType.Heatmap:
-            self.plot_widget.plot(self.data.heatmap(adc=self.adc, frm=f, to=t).transpose(), autorange=autorange)
+            self.plot_widget.plot( self.data.heatmap(adc=self.adc, frm=f, to=t).transpose(), autorange=autorange)
         if type == PlotType.Compare:
             self.plot_widget.plot([self.data.heatmap(adc=self.adc, frm=f, to=t).transpose(), self.data.heatmap(adc=self.secadc, frm=f, to=t).transpose()], autorange=autorange)
         if type == PlotType.Trains:
             self.plot_widget.plot(self.data.train(adc=self.adc, frm=f, to=t, calibrate=self.useCalib.isChecked()), autorange=autorange)
         if type == PlotType.Combined:
-            self.plot_widget.plot(self.data.combined(frm=f, to=t, adc=self.adc, calibrate=self.useCalib.isChecked()), autorange=autorange, workingChannels=config.working_channels)
+            self.plot_widget.plot(self.data.combined(adc=self.adc, frm=f, to=t, calibrate=self.useCalib.isChecked(), workingChannels=config.working_channels), autorange=autorange)
         if type == PlotType.Peak:
             t = t+184
-            self.plot_widget.plot(self.data.combined(frm=f, to=t, adc=self.adc, turnbyturn=True, calibrate=self.useCalib.isChecked(), mean=self.makeMean.isChecked()), autorange=autorange, doFit=(6 if self.fittGauss.isChecked() else 0), workingChannels=config.working_channels)
+            self.plot_widget.plot(self.data.combined(adc=self.adc, frm=f, to=t, calibrate=self.useCalib.isChecked(), workingChannels=config.working_channels, turnbyturn=True, mean=self.makeMean.isChecked()), autorange=autorange, doFit=(6 if self.fittGauss.isChecked() else 0))
                     #print(time.time(), 'do_plot stop'))
     def change_identifier_text(self):
         """

+ 75 - 39
KCG/widgets/TimescanWidget.py

@@ -1,6 +1,7 @@
 from __future__ import print_function 
 
 from PyQt4 import QtGui, QtCore
+from PyQt4.QtCore import pyqtSlot
 import pyqtgraph as pg
 from PyQt4.QtGui import QFont, QTableWidget
 
@@ -9,6 +10,8 @@ from scipy.stats import chisquare
 from scipy.stats import chi2_contingency
 from scipy.special import erfc, erf
 
+import copy
+
 from ..base import kcgwidget as kcgw
 from ..base.backend import board
 from ..base.backend.DataSet import DataSet
@@ -219,8 +222,13 @@ class ScanThread(QtCore.QObject):
         tmpmeans=[0,0,0,0,0,0,0,0]
 
         for adc in range(self.adc_number):
-           
-            tmp = data.array[:,adc]
+            try:
+                tmp = data.array[:,adc]
+            except Exception as e:
+                print(e)
+                self.stop = True
+                self.finished(c_step, c25_step, f_step)  
+                return
             #print('{:4.3f} Calc ADC {} '.format(time.time()-self.startTime, adc))
             
             if self.meanMode in [MODE_THREASHOLD]:
@@ -249,7 +257,8 @@ class ScanThread(QtCore.QObject):
             
         if c25_step_b == 4 and c_step_b == 0:
             print('{:4.3f} emit pbar'.format(time.time()-self.startTime))
-            self.pbarSignal.emit(self.timescan, 
+            tmpScan = copy.deepcopy(self.timescan)
+            self.pbarSignal.emit(tmpScan, 
                                  ((c_step-self.c_min)*(self.c25_max-self.c25_min+1.0) * (self.f_max-self.f_min+1.0) + (c25_step-self.c25_min)*(self.f_max-self.f_min+1.0) + (f_step-self.f_min))/
                                  ((self.c_max-self.c_min+1.0) * (self.c25_max-self.c25_min+1.0) * (self.f_max-self.f_min+1.0))
                                 )
@@ -335,7 +344,7 @@ class ScanPlotWidget(kcgw.KCGWidgets):
         self.par = parent
         self.board_id = board_id
         self.timeScan = None
-        self.block = False
+        #self.block = False
 
         # ------[ Variable declaration ]------------
         self.xrange = (0, 1) #T/H
@@ -390,8 +399,8 @@ class ScanPlotWidget(kcgw.KCGWidgets):
         self.plotSelect.currentIndexChanged.connect(self.changePlotType)
         self.layout.addWidget(self.plotSelect, lineindex, 1)
 
-        self.showerror=self.createCheckbox('show Error', connect=self.plot)
-        self.layout.addWidget(self.showerror, lineindex,2)
+        self.showError=self.createCheckbox('show Error', connect=self.plot)
+        self.layout.addWidget(self.showError, lineindex,2)
         self.useCalib=self.createCheckbox('use Calib', connect=self.plot)
         self.layout.addWidget(self.useCalib, lineindex,3)
         self.showADC=self.createCheckbox('show ADCs', connect=self.plot)
@@ -400,10 +409,7 @@ class ScanPlotWidget(kcgw.KCGWidgets):
         self.layout.addWidget(self.updateCalib, lineindex, 5)
         self.correlationTest = self.createButton('Correlation Test', connect=self.onCorrelation)
         self.layout.addWidget(self.correlationTest, lineindex, 6)
-        Elements.addButton(['timescan', 'acquire_{}'.format(self.board_id)], [
-                                                self.updateCalib,
-                                                self.correlationTest
-                                             ])
+
         lineindex += 1
 
         self.multiBunchSelector = self.createSpinbox(0,184, start_value=0, interval=1, connect=self.plot)
@@ -444,16 +450,25 @@ class ScanPlotWidget(kcgw.KCGWidgets):
         self.outerLayout.addLayout(self.layout)
         self.setWindowTitle("Scan Results")
 
+
+        Elements.addButton(['timescan', 'acquire_{}'.format(self.board_id)], [
+                                                self.updateCalib,
+                                                self.correlationTest,
+                                                self.useCalib,
+                                                self.showError,
+                                                self.showADC,
+                                                self.fitSin
+                                             ])
+
         # Initially show the plot
         self.line_plot()  
 
        
 
-        self.board_config.observe(
-            self,
-            self.setADCdelays,
-            'chip_delay'
-            )
+        self.board_config.observe(self, self.setADCdelays, 'chip_delay')
+        self.board_config.observe(self, self.setADCdelays, 'delay_330_th')
+        self.board_config.observe(self, self.setADCdelays, 'delay_25_th')
+        self.board_config.observe(self, self.setADCdelays, 'delay_25_th_2')
 
 
     def setADCdelays(self, value):
@@ -477,9 +492,10 @@ class ScanPlotWidget(kcgw.KCGWidgets):
         self.yrange = (f_min, f_max)
         self.step4 = step4
         
+    @pyqtSlot(object)
     def new_data(self, timeScan):
-        while self.block:
-            pass
+        #while self.block:
+        #    pass
 
         self.block = True
         self.timeScan = timeScan
@@ -607,13 +623,15 @@ class ScanPlotWidget(kcgw.KCGWidgets):
         Plot Data
         :return: -
         """
+        """
         if self.block:
             if nonblock == False:
                 return 
         else:
             self.block = True
+        """
         try:
-            print('plot')
+            #print('plot')
             if self.timeScan is None:
                 return
 
@@ -642,31 +660,33 @@ class ScanPlotWidget(kcgw.KCGWidgets):
                 text = ""
                 for i in range(self.adc_number):
                     if self.adccb[i].isChecked():
-                        scanx, scany, scane = self.timeScan.getScanOverTime(i, calibrateX=self.useCalib.isChecked(), calibrateY=self.useCalib.isChecked(), force=True, bunch=self.multiBunchSelector.value())
+                        scanx, scany, scane = self.timeScan.getScanOverTime(i, calibrateX=self.useCalib.isChecked(), calibrateY=self.useCalib.isChecked(), bunch=self.multiBunchSelector.value())
                         #scanx, scany = self.calibrate(self.data[i], i)
                         self.scanyAll.append(scany)
                         self.all_plot_widget.plotItem.plot(scanx, scany, pen=None, symbolPen=pg.mkPen(colours[i]), symbolSize=2, pxMode=True, symbolBrush=pg.mkBrush(colours[i]), downsample=200)
                         
-                        if self.showerror.isChecked():
+                        if self.showError.isChecked():
                             self.all_plot_widget.plotItem.addItem(pg.ErrorBarItem(x=scanx, y=scany, height=scane, pen=pg.mkPen(coloursTrans[i], width=2), autoDownsample=True, clipToView=True ))
                         
                         if self.fitSin.isChecked():
                             # display fit
-                            type = self.fitSelect.currentIndex()
-                            popt, perr, fitFun, pcov, label, x = self.doFit(scanx, scany, type)
-                            
-                            fitx = np.linspace(np.min(scanx), np.max(scanx), 100000)
-                            fity = fitFun(fitx, *popt)
-                            self.plot_widget.plotItem.plot(fitx, fity, pen=pg.mkPen(colours[i]),  downsample=200)
-              
-                            if type == SINUS:
-                                dt.append(popt[3]/(2*np.pi)/popt[1]*1e12)
-                            elif type in [GAUSS, EGAUSS, SKEW, EGAUSSB, GAUSSB]:
-                                try:
-                                    dt.append(fitx[np.where(fity==np.min(fity))][0]*1e12)
-                                except:
-                                    pass
-                           
+                            try:
+                                type = self.fitSelect.currentIndex()
+                                popt, perr, fitFun, pcov, label, x = self.doFit(scanx, scany, type)
+                                
+                                fitx = np.linspace(np.min(scanx), np.max(scanx), 100000)
+                                fity = fitFun(fitx, *popt)
+                                self.plot_widget.plotItem.plot(fitx, fity, pen=pg.mkPen(colours[i]),  downsample=200)
+                  
+                                if type == SINUS:
+                                    dt.append(popt[3]/(2*np.pi)/popt[1]*1e12)
+                                elif type in [GAUSS, EGAUSS, SKEW, EGAUSSB, GAUSSB]:
+                                    try:
+                                        dt.append(fitx[np.where(fity==np.min(fity))][0]*1e12)
+                                    except:
+                                        pass
+                            except:
+                                pass
 
 
                 if self.fitSin.isChecked():
@@ -695,7 +715,7 @@ class ScanPlotWidget(kcgw.KCGWidgets):
         if not self.showADC.isChecked():
             return
 
-        print('plot delays')
+        #print('plot delays')
         if self.scanyAll == []:
             self.scanyAll.extend([0,1])
         i=1
@@ -709,7 +729,7 @@ class ScanPlotWidget(kcgw.KCGWidgets):
         for x in self.delays:
             if self.adccb[i-1].isChecked():
                 self.plotList.append(self.all_plot_widget.plotItem.plot([x,x], [np.min(self.scanyAll)-10, np.max(self.scanyAll)+20], pen=pg.mkPen(colours[0]), downsample=200))
-                text = pg.TextItem(str(i), anchor=(0.5,1), color=(0,0,0))
+                text = pg.TextItem(str(i), anchor=(0.5,1), color=colours[i-1])
                 text.setFont(font)
                 text.setPos(x,np.max(self.scanyAll)+24)
                 self.all_plot_widget.addItem(text)
@@ -807,6 +827,9 @@ class ScanPlotWidget(kcgw.KCGWidgets):
         Event handler for closing this window
         """
         self.board_config.unobserve(self, 'chip_delay')
+        self.board_config.unobserve(self, 'delay_330_th')
+        self.board_config.unobserve(self, 'delay_25_th')
+        self.board_config.unobserve(self, 'delay_25_th_2')
 
 
         global __timing_plot_widget_id__
@@ -1149,7 +1172,7 @@ class TimeScanWidget(kcgw.KCGWidgets):
         lineindex += 1
 
         self.layout.addWidget(self.createLabel("Threshold / Bucket"), lineindex, 0)
-        self.threshold = self.createSpinbox(-2000,2000, start_value=0)
+        self.threshold = self.createSpinbox(-2000,2000, start_value=15)
         self.layout.addWidget(self.threshold, lineindex, 1)
         lineindex += 1
         Elements.addButton(['timescan'], [
@@ -1222,7 +1245,7 @@ class TimeScanWidget(kcgw.KCGWidgets):
             self.delay25max.setValue(12)
             self.delayfinemax.setValue(0)
             self.delayfinemin.setValue(0)
-            self.threshold.setValue(30)
+            self.threshold.setValue(15)
             self.comboBox.setCurrentIndex(1)
             self.stepSwitcher.setState(False)
             self.calibSelector.setState(False)
@@ -1264,11 +1287,24 @@ class TimeScanWidget(kcgw.KCGWidgets):
             Elements.setEnabled('acquire_{}'.format(self.board_id), False, exclude=[self.button])
             Elements.setEnabled("acquireTrigger_{}".format(self.board_id), False)
 
+            if __timing_plot_widget__ == None:
+                __timing_plot_widget__.showError.setChecked(False)
+                __timing_plot_widget__.useCalib.setChecked(False)
+                __timing_plot_widget__.fitSin.setChecked(False)
+                __timing_plot_widget__.showADC.setChecked(False)
+
             outdir = os.path.join(storage.storage.save_location, storage.storage.subdirname, 'TimeScan')
             if not os.path.isdir(outdir):
                 bif._bif_update_working_dir()
                 os.makedirs(outdir)
 
+            self.scanNumber = 0
+            filelist = np.sort(os.listdir(outdir))
+            for file in filelist:
+                if '.scan' in file:
+                    self.scanNumber += 1
+            
+
             saveraw = self.saverawCB.isChecked()
             #print(saveraw)