1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411 |
- 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
- from scipy.optimize import curve_fit
- 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
- from ..base.backend.TimeScan import TimeScan
- from ..base.backend.board import available_boards
- from ..base import backendinterface as bif
- from ..base.groupedelements import Elements, live_plot_windows
- from ..base.globals import glob as global_objects
- from .. import config
- from ..config import colours, coloursTrans
- from ..base import storage
- from ..base.backend.CalibrationHandle import theCalibration
- from . import UpdateCalibrationWidget
- from . import CorrelationWidget
- import logging
- import time
- from time import sleep
- import h5py
- import traceback
- import numpy as np
- import os
- __widget_id__ = None
- MODE_ALL = 0
- MODE_THREASHOLD = 1
- MODE_AUTOBUCKET = 2
- MODE_AUTOBUCKET_TMP_THRESHOLD = 3
- MODE_BUCKET = 4
- MODE_BUCKET_THRESHOLD = 5
- MODE_ALL_BUCKETS = 6
- class ScanThread(QtCore.QObject):
- '''Timescan Thread class'''
- pbarSignal = QtCore.pyqtSignal(object, float)
- stopSignal = QtCore.pyqtSignal(object, str)
- plotSignal = QtCore.pyqtSignal(object)
- def __init__(self, c_min, c_max, f_min, f_max, board_id, index, info, outdir="", threshold=0, saveraw=False, c25_min=-1, c25_max=-1, step4=False, meanMode=MODE_ALL, fastMode=False, calibScan=False):
- super(ScanThread, self).__init__()
- self.c_min = c_min
- self.c_max = c_max
- self.f_min = f_min
- self.f_max = f_max
- self.c25_min = c25_min
- self.c25_max = c25_max
- self.step4 = step4
- self.board_id = board_id
- self.threshold = threshold
- self.index = index
- self.info = info
- self.saveraw = saveraw
- self.rawdir = ""
- self.outdir = outdir
- self.adc_number = board.get_board_config(self.board_id).get('adc_number')
- self.board_config = board.get_board_config(self.board_id)
-
- self.timescan = TimeScan()
- self.stop = False
- self.timestamp = 0
- self.meanMode = meanMode
- self.buckets = None
- self.fastMode = fastMode
- self.calibrationScan = calibScan
-
- def setDelay(self, value):
- board.get_board_config(self.board_id).update('delay_330_th', value)
- board.get_board_config(self.board_id).update('delay_330_th_2', value)
- def setDelay25(self, value):
- board.get_board_config(self.board_id).update('delay_25_th', value)
- board.get_board_config(self.board_id).update('delay_25_th_2', value)
- def setDelayB(self, value):
- board.get_board_config(self.board_id).update('delay_330_th_2', value)
- def setDelayB25(self, value):
- board.get_board_config(self.board_id).update('delay_25_th_2', value)
- def setFineDelay(self, value):
- board.get_board_config(self.board_id).update('chip_delay', [value,value,value,value,value,value,value,value])
- def scan(self):
- print('##################################################################')
- self.stop = False
- self.timestamp = time.time()
- self.timescan.prepare(self.adc_number, self.meanMode==MODE_ALL_BUCKETS)
- if self.fastMode:
- print('fastMode')
- self.board_config.update('chip_delay', [0,10,20,30,0,10,20,30])
- if self.saveraw or self.meanMode in [MODE_AUTOBUCKET_TMP_THRESHOLD, MODE_AUTOBUCKET]:
- self.saveraw = True
- self.rawdir = os.path.join(self.outdir, 'raw')#, '{:02d}_{:.3f}'.format(self.index, self.timestamp))
- self.rawfilename = os.path.join(self.rawdir, '{:02d}_{:.3f}.hdf'.format(self.index, self.timestamp))
- if not os.path.isdir(self.rawdir):
- os.makedirs(self.rawdir)
- self.rawFile = h5py.File(self.rawfilename, 'w')
- self.dataGroup = self.rawFile.create_group('data')
- for c_step in range(self.c_min, self.c_max+1):
- self.setDelay(c_step)
- sleep(0.1)
- step = 1
- if self.step4:
- step=4
- for c25_step in range(self.c25_min, self.c25_max+1, step):
- if board.get_board_config(self.board_id).is_KAPTURE2():
- self.setDelay25(c25_step)
- if self.calibrationScan:
- #self.setDelayB(0)
- self.setDelayB25(4)
- c25_step_b = 4
- pass
- c25_step_b = board.get_board_config(self.board_id).get('delay_25_th_2')
-
- for f_step in range(self.f_min, self.f_max+1):
- if not self.fastMode:
- self.setFineDelay(f_step)
- self.startTime = time.time()
- print('--------------------------------------------------------')
- print('{:4.3f} step'.format(time.time()))
- if not kcgw.testing:
- sleep(0.25)
- else:
- sleep(0.05)
- if self.stop:
- self.finished(c_step, c25_step, f_step)
- return
-
- self.readData(c_step, c25_step, f_step, 0, c25_step_b)
- #for f_step
- if self.calibrationScan:
- self.setFineDelay(0)
- f_step = 0
- self.setDelayB(0)
- c_step_b = 0
- for c25_step_b in range(1, 8+1):
- self.setDelayB25(c25_step_b)
- print('--------------------------------------------------------')
- print('{:4.3f} step'.format(time.time()))
- if not kcgw.testing:
- sleep(0.25)
- else:
- sleep(0.05)
- if self.stop:
- self.finished(c_step, c25_step, f_step)
- return
- self.readData(c_step, c25_step, f_step, c_step_b, c25_step_b)
- #if calibrationScan
- #for c25_step
- #for c_step
- self.finished(c_step, c25_step, f_step)
- def readData(self, c_step, c25_step, f_step, c_step_b=0, c25_step_b=0):
- try:
- # -----------[ IMPORTANT ]---------------------
- if not kcgw.testing:
- data_raw = np.fromstring(bif._bif_read_data(self.board_id, True), dtype=np.uint32)
- if data_raw is None:
- print('no data returned')
- self.stop = True
- self.finished(c_step, c25_step, f_step)
- return
- # ----------------------------------------------
- else:
- f_name = "t/1544038883.603.out"#1529502127.686.out"
- data_raw = np.memmap(f_name, dtype='uint32')
-
-
- data = DataSet(rawData=data_raw, tRev=config.tRev, bunchesPerTurn=config.bunches_per_turn, shiftFMC2=config.shiftFMC2)
-
- #print('{:4.3f} emit Plot'.format(time.time()-self.startTime))
- self.plotSignal.emit(data)
- #print('{:4.3f} emit Plot done'.format(time.time()-self.startTime))
- except Exception as e:
- print(e)
- self.stop = True
- self.finished(c_step, c25_step, f_step)
- return
- if self.saveraw:
- self.dataGroup.create_dataset(
- "{:02d}_{:02d}_{:02d}_{:02d}_{:02d}".format(c_step, c25_step, f_step, c_step_b, c25_step_b),
- data=data_raw, dtype='uint32',
- shuffle=False, chunks=(2**8,4),
- compression='lzf'
- )
- baseline = 2048
- tmpmeans=[0,0,0,0,0,0,0,0]
- for adc in range(self.adc_number):
- 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]:
- if self.threshold > 0:
- tmp = tmp[np.where((tmp > (baseline)+self.threshold))]# | (tmp < baseline-self.threshold))]
- else:
- tmp = tmp[np.where((tmp < (baseline)+self.threshold))]# | (tmp < baseline-self.threshold))]
- #print('{:4.3f} MODE_THREASHOLD done'.format(time.time()-self.startTime))
- elif self.meanMode in [MODE_BUCKET]:
- tmp = tmp[self.threshold::184]
- #print('{:4.3f} MODE_BUCKET done'.format(time.time()-self.startTime))
-
- elif self.meanMode in [MODE_ALL_BUCKETS]:
- tmp = np.reshape(tmp, (-1,184))
- if len(tmp) < 5:
- tmp=[baseline,baseline]
- mean = np.mean(tmp,0)
- std = np.std(tmp,0)
-
- self.timescan.appendData(mean,std,adc, c_step, c25_step, f_step, c25_step_b)
-
- #print('{:4.3f} emit pbar'.format(time.time()-self.startTime))
- 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))
- )
- #print('{:4.3f} emit pbar done'.format(time.time()-self.startTime))
- def finished(self, c_step=0, c25_step=0, f_step=0):
- '''Method to handle the end of the thread'''
-
- if self.saveraw:
- grp = self.rawFile.create_group('info')
- grp['Nr'] = self.index
- grp['Info'] = '{}'.format(self.info)
- grp['Threshold'] = self.threshold
- grp['T/H'] = [self.c_min, self.c_max]
- grp['25ps'] = [self.c25_min, self.c25_max]
- grp['fine'] = [self.f_min, self.f_max]
- grp['Step4'] = self.step4
- grp['Mode'] = self.meanMode
- grp['stop'] = [c_step, c25_step, f_step]
- grp['fastMode'] = self.fastMode
- grp['Calibration'] = self.calibrationScan
- self.rawFile.close()
-
- file= '{:02d}_{:0.3f}.scan'.format(self.index, self.timestamp)
- filename = os.path.join(self.outdir, file)
- self.timescan.saveScan(filename, self.index, self.info, self.threshold,
- self.c_min, self.c_max, self.c25_min, self.c25_max,
- self.f_min, self.f_max, self.stop, c_step, c25_step, f_step,
- self.step4, self.meanMode, self.fastMode, self.calibrationScan)
-
- board.get_board_status(self.board_id).time_scan = False
- self.stop = True
- self.stopSignal.emit(self.timescan, filename)
- return
-
- # 8888888b. 888 888 888 888 d8b 888 888
- # 888 Y88b 888 888 888 o 888 Y8P 888 888
- # 888 888 888 888 888 d8b 888 888 888
- # 888 d88P 888 .d88b. 888888 888 d888b 888 888 .d88888 .d88b. .d88b. 888888
- # 8888888P" 888 d88""88b 888 888d88888b888 888 d88" 888 d88P"88b d8P Y8b 888
- # 888 888 888 888 888 88888P Y88888 888 888 888 888 888 88888888 888
- # 888 888 Y88..88P Y88b. 8888P Y8888 888 Y88b 888 Y88b 888 Y8b. Y88b.
- # 888 888 "Y88P" "Y888 888P Y888 888 "Y88888 "Y88888 "Y8888 "Y888
- # 888
- # Y8b d88P
- # "Y88P"
- LINEAR = 0
- GAUSS = 1
- EGAUSS = 2
- EGAUSSB= 3
- SKEW = 4
- SINUS = 5
- __timing_plot_widget_id__ = {}
- __timing_plot_widget__ = None
- __datastorage__ = None
- ##################################################################################
- class ScanPlotWidget(kcgw.KCGWidgets):
- """
- The Timescan result plot subwindow.
- """
- def __init__(self, unique_id, board_id, parent=None):
- """
- Initialises the timing plot window
- :param unique_id: the id for this window
- :param parent: parent object
- :return: -
- """
- super(ScanPlotWidget, self).__init__()
- self.id = unique_id
- self.par = parent
- self.board_id = board_id
- self.timeScan = None
- #self.block = False
- # ------[ Variable declaration ]------------
- self.xrange = (0, 1) #T/H
- self.yrange = (0, 1) #fine
- self.zrange = (0, 1) #25ps
- self.x = 1 # Number of Ticks in the x-direction This is set by the gui programmatically
- self.y = 1 # Number of Ticks in the y-direction This is set by the gui programmatically
- self.z = 1
- self.data = None # Data to plot
- self.levels = None # Levels for colors
- self.step4 = False
- self.type=0
- self.board_config = board.get_board_config(self.board_id)
- self.adc_number = self.board_config.get('adc_number')
-
- self.plotList = []
- self.scanyAll = []
- self.delays = np.zeros(self.adc_number)
- # -------[ Create structure ]----------
- self.outerLayout = QtGui.QVBoxLayout() # Outermost layout of this window
- self.setLayout(self.outerLayout)
- self.plotWidget1 = QtGui.QWidget()
- self.plotlayout1 = QtGui.QGridLayout()
- self.adc_plot_widgets = []
- for i in range(self.adc_number):
- self.adc_plot_widgets.append(pg.PlotWidget(title="ADC {}".format(i+1)))
-
- for i,item in enumerate(self.adc_plot_widgets):
- self.plotlayout1.addWidget(item, i//(self.adc_number//2), i%(self.adc_number//2))
- self.plotWidget1.setLayout(self.plotlayout1)
-
- self.plotWidget2 = QtGui.QWidget()
- self.plotlayout2 = QtGui.QGridLayout() # Main Layout to hold the most elements in this window
- self.all_plot_widget = pg.PlotWidget(title="over Time")
- self.plotlayout2.addWidget(self.all_plot_widget, 0, 0)
- self.plotWidget2.setLayout(self.plotlayout2)
- self.layout = QtGui.QGridLayout() # Main Layout to hold the most elements in this window
- lineindex = 0
- self.adccb = []
- for adc in range(self.adc_number):
- self.adccb.append(self.createCheckbox('ADC{}'.format(adc+1), checked=True, connect=self.plot, color=colours[adc]))
- self.layout.addWidget(self.adccb[adc],lineindex,adc)
- lineindex +=1
- self.layout.addWidget(self.createLabel('Plot Type:'), lineindex,0)
- self.plotSelect = QtGui.QComboBox(self)
- self.plotSelect.addItem("default") #0
- self.plotSelect.addItem("timecorreted") #1
- 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.useCalib=self.createCheckbox('use Calib', connect=self.plot)
- self.layout.addWidget(self.useCalib, lineindex,3)
- self.showADC=self.createCheckbox('show ADCs', connect=self.plot)
- self.layout.addWidget(self.showADC, lineindex,4)
- self.updateCalib = self.createButton('Update Calibration', connect=self.onUpdateCalibration)
- self.layout.addWidget(self.updateCalib, lineindex, 5)
- self.correlationTest = self.createButton('Correlation Test', connect=self.onCorrelation)
- self.layout.addWidget(self.correlationTest, lineindex, 6)
- lineindex += 1
- self.multiBunchSelector = self.createSpinbox(0,184, start_value=0, interval=1, connect=self.plot)
- self.multiBunchSelectorLabel = self.createLabel('Bunch Selection:')
- self.layout.addWidget(self.multiBunchSelectorLabel, lineindex, 0)
- self.layout.addWidget(self.multiBunchSelector, lineindex, 1)
- self.multiBunchSelector.hide()
- self.multiBunchSelectorLabel.hide()
- lineindex += 1
- self.fitSin=self.createCheckbox('plot Fit', connect=self.plot)
- self.layout.addWidget(self.fitSin, lineindex,0)
- self.fitSelect = QtGui.QComboBox(self)
- self.fitSelect.addItem("Linear") #0
- self.fitSelect.addItem("Gauss") #1
- self.fitSelect.addItem("Exponential mod Gauss") #2
- self.fitSelect.addItem("Exponential mod Gauss V2") #3
- self.fitSelect.addItem("skew Gauss") #4
- self.fitSelect.addItem("Sinus") #5
- self.fitSelect.currentIndexChanged.connect(self.plot)
- self.layout.addWidget(self.fitSelect, lineindex, 1)
- self.fitoffset = self.createSpinbox(-1000,1100, start_value=-1, interval=1, connect=self.plot)
- self.layout.addWidget(self.fitoffset, lineindex,2)
- self.fitInfoLable = self.createLabel()
- self.layout.addWidget(self.fitInfoLable, lineindex, 4)
-
- self.invertFit=self.createCheckbox('invert Fit', connect=self.plot)
- self.layout.addWidget(self.invertFit, lineindex, 3)
- lineindex += 1
-
-
- self.outerLayout.addWidget(self.plotWidget1)
- self.outerLayout.addWidget(self.plotWidget2)
- self.plotWidget2.hide()
- 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, '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):
- #print('set ADC Delays')
- self.delays = np.zeros(self.adc_number)
- id = 'None'
- if self.useCalib.isChecked():
- id = 'current'
- for i in range(self.adc_number):
- value = theCalibration.calibrateX(i, self.board_config.get('delay_330_th'), self.board_config.get('delay_25_th'), self.board_config.get('chip_delay')[i], self.board_config.get("delay_25_th_2"), id=id)
- self.delays[i] = value
- self.plotADCPositions()
-
- def setPlotParams(self, c_min, c_max, c25_min, c25_max, f_min, f_max, step4):
- self.xrange = (c_min, c_max)
- self.zrange = (c25_min, c25_max)
- self.yrange = (f_min, f_max)
- self.step4 = step4
-
- @pyqtSlot(object)
- def new_data(self, timeScan):
- #while self.block:
- # pass
- self.block = True
- self.timeScan = timeScan
- if self.timeScan.multibunch:
- self.multiBunchSelector.show()
- self.multiBunchSelectorLabel.show()
- else:
- self.multiBunchSelector.hide()
- self.multiBunchSelectorLabel.hide()
- self.plot(True)
- self.block = False
- def changePlotType(self, type):
- self.type=type
- if type == 0:
- self.plotWidget2.hide()
- self.plotWidget1.show()
- self.plot()
- else:
- self.plotWidget1.hide()
- self.plotWidget2.show()
- self.plot()
- def onUpdateCalibration(self):
- if self.timeScan is not None:
- calibrationUpdater = UpdateCalibrationWidget.addUpdateCalibrationWidget()
- calibrationUpdater.openWith(self.timeScan, bunch=self.multiBunchSelector.value())
- def onCorrelation(self):
- if self.timeScan is not None:
- w = CorrelationWidget.addCorrelationWidget()
- w.updateTimeScan(self.timeScan)
- ##################################################################################
- def line_plot_axis_strings(self, values, scale, spacing):
- """
- Plot to format the strings for the line plot
- This is used to override the default tickStrings method of pyqtgraph.AxisItem
- :param values: See pyqtgraph.AxisItem.tickStrings
- :param scale: See pyqtgraph.AxisItem.tickStrings
- :param spacing: See pyqtgraph.AxisItem.tickStrings
- :return: See pyqtgraph.AxisItem.tickStrings
- """
- #print(values)
- mult = 1
- if self.step4:
- mult = 4
- coarses = [self.xrange[0] + i//(self.x) for i in values]
- c25 = [self.zrange[0] + (i//(self.y))%(self.z) for i in values]
- fines = [self.yrange[0] + i%(self.y) for i in values]
-
- if board.get_board_config(self.board_id).is_KAPTURE2():
- return [str(int(c))+"\n"+str(int(c25*mult))+"\n"+str(int(f)) for c, c25, f in zip(coarses, c25, fines)]
- else:
- return [str(int(c))+"\n"+str(int(f)) for c, f in zip(coarses, fines)]
- ##################################################################################
- def spacing(self, minVal, maxVal, size):
- """
- Calculate spacing between ticks
- This is used to override the default tickSpacing method of pyqtgraph.AxisItem
- :param minVal: See pyqtgraph.AxisItem.tickSpacing
- :param maxVal: See pyqtgraph.AxisItem.tickSpacing
- :param size: See pyqtgraph.AxisItem.tickSpacing
- :return: See pyqtgraph.AxisItem.tickSpacing
- """
- if maxVal - minVal < 10.:
- return [(1, 0),]
- else:
- return [(round((maxVal-minVal)/10.), 0),]
- ##################################################################################
- def y_axis_strings(self, values, scale, spacing):
- """
- Sets the strings for the y axis
- :param values:
- :param scale:
- :param spacing:
- :return:
- """
- if np.mean(values) > 3:
- return [str(int(v)) for v in values]
- return [str(v) for v in values]
- ##################################################################################
- def line_plot(self):
- """
- Initialise the Line Plot
- :return: -
- """
- self.plot_type = "line"
- for item in self.adc_plot_widgets:
- item.enableAutoRange()
- item.plotItem.setLabel("left", "Intensity")
- item.plotItem.setLabel("bottom", "Coarse over Fine")
- bax = item.plotItem.getAxis('bottom')
- lax = item.plotItem.getAxis('left')
- bax.setTickSpacing()
- bax.tickSpacing = self.spacing
- bax.tickStrings = self.line_plot_axis_strings
- lax.setTickSpacing()
- def setAxis(axis, lable, unit="", setSpace=False):
- labelStyle = {'color': '#000', 'font-size': '14pt'}
- axis.setLabel(lable, units=unit, **labelStyle)
-
- font=QtGui.QFont()
- font.setPixelSize(15)
- axis.tickFont = font
- axis.setStyle(tickTextOffset = 20)
- if unit != "":
- axis.enableAutoSIPrefix()
- if setSpace:
- axis.setWidth(int(80))
- setAxis(self.all_plot_widget.plotItem.getAxis('bottom'), 't', 's')
- setAxis(self.all_plot_widget.plotItem.getAxis('left'), 'ADC counts', '', True)
- ##################################################################################
- def plot(self, nonblock=False):
- """
- Plot Data
- :return: -
- """
- """
- if self.block:
- if nonblock == False:
- return
- else:
- self.block = True
- """
- try:
- #print('plot')
- if self.timeScan is None:
- return
- if self.type == 0:
- self.z = 1
- if board.get_board_config(self.board_id).is_KAPTURE2():
- self.z = (self.zrange[1]-self.zrange[0]+1)
- if self.step4:
- self.z = self.z//4+1
- self.y = (self.yrange[1]-self.yrange[0]+1)
- self.x = self.z*self.y
- for i, item in enumerate(self.adc_plot_widgets):
- item.plotItem.clear()
- #item.plotItem.plot(np.array(self.timeScan.scanData[i]).T[0])
- scanx, scany, scane = self.timeScan.getScanOverDelay(i, bunch=self.multiBunchSelector.value())
- item.plotItem.plot(scany)
- else:
- self.all_plot_widget.plotItem.clear()
- #if self.useCalib.isChecked():
- # self.calibrationFile = h5py.File(config.config_path('calibration.hdf'), 'r')
- dt = []
- self.scanyAll = []
- 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(), 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():
- 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
- 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():
- if type in [SINUS, GAUSS, EGAUSS, SKEW, EGAUSSB, GAUSSB]:
- text += 'delta T '
- for i in range(len(dt)):
- text += '| {:.3f}ps '.format(dt[0]-dt[i])
-
- self.fitInfoLable.setText(text)
- self.plotADCPositions()
- #if self.useCalib.isChecked():
- # self.calibrationFile.close()
- # ---[ Show this window and set focus to it ]------
- self.parent().show()
- self.show()
- except:
- pass
- self.block = False
- #self.setFocus()
- def plotADCPositions(self):
- if self.type != 1:
- return
- if not self.showADC.isChecked():
- return
- #print('plot delays')
- if self.scanyAll == []:
- self.scanyAll.extend([0,1])
- i=1
- font = QtGui.QFont()
- font.setPixelSize(14)
- if self.plotList != []:
- for item in self.plotList:
- self.all_plot_widget.plotItem.removeItem(item)
- self.plotList = []
-
- 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=colours[i-1])
- text.setFont(font)
- text.setPos(x,np.max(self.scanyAll)+24)
- self.all_plot_widget.addItem(text)
- self.plotList.append(text)
- i += 1
- def doFit(self, x,y, type, p0=None):
- def linear(x,a,b):
- return a + b*x
- def gauss(x, sigma, mu, A, b):
- return A*np.exp(-0.5*((x-mu)/sigma)**2) + b
- def expgauss(x, s, m, a ,l, b):
- return a*l/2*np.exp(l/2*(2*m + l*s**2 - 2*x)) * erfc((m +l*s**2 -x)/(np.sqrt(2)*s)) + b
- def expgauss2(x, s, m, a, t, b):
- return a*s/t*np.sqrt(np.pi/2) * np.exp(0.5 * (s/t)**2 - (x-m)/t) * erfc(1/np.sqrt(2)*(s/t - (x-m)/s)) + b
- def sinus(x,a,b,c,d):
- return a*np.sin(b*x*(2*np.pi)+d)+c
- def skewnorm(x, s, m, a, l, b):
- def p(x):
- return 1/np.sqrt(2*np.pi) * np.exp(- x**2/2)
- def g(x):
- return 0.5*(1+erf(x/np.sqrt(2)))
- return a*2/s*p((x-m)/s)*g(l*(x-m)/s) +b
-
- if self.invertFit.isChecked():
- startx = x[np.where(y==np.min(y))]
- else:
- startx = x[np.where(y==np.max(y))]
- y = y[np.argsort(x)]
- x = x[np.argsort(x)]
- if type == LINEAR:
- fitFun = linear
- label = ['a' , 'b']
- elif type == GAUSS:
- fitFun = gauss
- p0 = (90e-12, startx, 500, 2000)
- label = ['sigma', ' mu ', ' A ', ' b ']
- if self.invertFit.isChecked():
- p0 = (90e-12, startx, -500, 2000)
- end = np.argmax(y)+self.fitoffset.value()
- x = x[:end]
- y = y[:end]
- elif type == EGAUSS:
- fitFun = expgauss
- p0 = (23e-12, startx, 7e-8, 0.02e12, 2040)
- if self.invertFit.isChecked():
- p0 = (23e-12, startx, -7e-8, 0.02e12, 2040)
- label = [' s ', ' m ', ' a ', ' l ', ' b ']
- elif type == EGAUSSB:
- fitFun = expgauss2
- p0 = (22e-12, startx, 1200, 70e-12, 2040)
- if self.invertFit.isChecked():
- p0 = (22e-12, startx, -1200, 70e-12, 2040)
- end = self.fitoffset.value()
- x = x[:end]
- y = y[:end]
- label = [' s ', ' m ', ' a ', ' l ', ' b ']
- elif type == SKEW:
- fitFun = skewnorm
- end = self.fitoffset.value()
- x = x[:end]
- y = y[:end]
- p0 = (80e-12, startx, 6e-8, 3, 2040) # 220e-12
- label = [' s ', ' m ', ' a ', ' l ', ' b ']
- if self.invertFit.isChecked():
- p0 = (80e-12, startx, -6e-8, 3, 2040) # 220e-12
- elif type == SINUS:
- fitFun = sinus
- if p0 == None:
- p0 = (-700, 500e6, 2048, 0.5)
- label = [' A ', ' f ', ' b ', ' phi']
- else:
- print('Fit type unknown ', type)
- return 0,0, lambda x: x , 0
- if p0 is not None:
- popt, pcov = curve_fit(fitFun, x, y, p0=p0)
- else:
- popt, pcov = curve_fit(fitFun, x, y)
- #popt = p0
- perr = np.sqrt(np.absolute(np.diag(pcov)))
- #print(popt)
- return popt, perr, fitFun, pcov, label, x
- ##################################################################################
- def closeEvent(self, event):
- """
- 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__
- __timing_plot_widget_id__ = {}
- global __timing_plot_widget__
- __timing_plot_widget__ = None
-
- del self.par.widgets[self.id]
- # d8888 888 888 d8b
- # d88888 888 888 Y8P
- # d88P888 888 888
- # d88P 888 888 888 888888 .d88b. 88888b.d88b. 8888b. 888888 888 .d88b. 88888b.
- # d88P 888 888 888 888 d88""88b 888 "888 "88b "88b 888 888 d88""88b 888 "88b
- # d88P 888 888 888 888 888 888 888 888 888 .d888888 888 888 888 888 888 888
- # d8888888888 Y88b 888 Y88b. Y88..88P 888 888 888 888 888 Y88b. 888 Y88..88P 888 888
- # d88P 888 "Y88888 "Y888 "Y88P" 888 888 888 "Y888888 "Y888 888 "Y88P" 888 888
- #
- #
- #
- class AutomationThread(QtCore.QObject):
- '''Automation Thread class'''
- updateSignal = QtCore.pyqtSignal(int)
- stopSignal = QtCore.pyqtSignal()
- startScan = QtCore.pyqtSignal()
- poststartScan = QtCore.pyqtSignal()
- running = False
- def __init__(self, start, stop, step, board_id):
- super(AutomationThread, self).__init__()
- self.start = start
- self.stop = stop
- self.step = step
- self.board_id = board_id
- def scan(self):
- self.running = True
- for v in range(self.start, self.stop+self.step, self.step):
- self.updateSignal.emit(v)
- sleep(0.5)
- print('startScan')
- self.startScan.emit()
- while not board.get_board_status(self.board_id).time_scan:
- #wait for Scan to start
- sleep(0.05)
- if not self.running:
- self.stopSignal.emit()
- return
-
- self.poststartScan.emit()
-
- while board.get_board_status(self.board_id).time_scan:
- #wait for Scan to stop
- sleep(0.05)
- if not self.running:
- self.stopSignal.emit()
- return
-
-
- if not self.running:
- self.stopSignal.emit()
- return
- self.running = False
- self.stopSignal.emit()
- from ..extensions import deltaPower
- class Automation(kcgw.KCGWidgets):
- def __init__(self, layout, startScan, info, abortScan):
- super(Automation, self).__init__()
- self.layout = layout
- self.startScan = startScan
- self.abortScan = abortScan
- self.info = info
- self.outdir = os.path.join(storage.storage.save_location, storage.storage.subdirname, 'CalibrationScan')
- self.running = False
- self.power = None #deltaPower.DeltaPower("192.1.1.1")
- lineindex = 0
- self.layout.addWidget(self.createLabel("Automated Voltage Scan"), lineindex, 0,1,3)
- lineindex +=1
- self.layout.addWidget(self.createLabel("Power Supply IP"), lineindex, 0)
- self.input = self.createInput('10.1.0.101')
- self.layout.addWidget(self.input, lineindex, 1,1,2)
- self.buttonConnect = self.createButton('connect', connect=self.connect)
- self.layout.addWidget(self.buttonConnect, lineindex, 3)
- lineindex += 1
- self.layout.addWidget(self.createLabel("Spannung (mV)"), lineindex, 0)
- self.vin = self.createSpinbox(0,1000, start_value=0)
- self.layout.addWidget(self.vin, lineindex, 1)
- self.buttonSetV = self.createButton('set', connect=lambda: self.setV(self.vin.value()))
- self.layout.addWidget(self.buttonSetV, lineindex, 2)
- lineindex += 1
- self.layout.addWidget(self.createLabel("Start"), lineindex, 1)
- self.layout.addWidget(self.createLabel("Stop"), lineindex, 2)
- self.layout.addWidget(self.createLabel("Schritt"), lineindex, 3)
- lineindex += 1
- self.layout.addWidget(self.createLabel("Spannung (mV)"), lineindex, 0)
- self.vmin = self.createSpinbox(0,1000, start_value=0)
- self.vmax = self.createSpinbox(0,1000, start_value=800)
- self.vstep = self.createSpinbox(0,500, start_value=20)
- self.layout.addWidget(self.vmin, lineindex, 1)
- self.layout.addWidget(self.vmax, lineindex, 2)
- self.layout.addWidget(self.vstep, lineindex, 3)
- lineindex += 1
- self.button = self.createButton('start', connect=self.start)
- self.layout.addWidget(self.button, lineindex, 0)
- Elements.addButton(['timescan','acquire_0', 'automation'], [self.button, self.buttonConnect, self.buttonSetV])
- Elements.addButton(['automation'], [self.input, self.vin, self.vmin, self.vmax, self.vstep])
-
- lineindex += 1
- self.progressbar = QtGui.QProgressBar()
- self.layout.addWidget(self.progressbar, lineindex,0,1,4)
- self.progressbar.setRange(0,1000)
- lineindex += 1
- self.tst = None
-
- def connect(self):
- try:
- self.power = deltaPower.DeltaPower(str(self.input.text()))
- except Exception as e:
- logging.error('Not connected to Powersupply - ' + str(e))
- self.power = None
- def setV(self, value):
- if self.power is not None:
- self.power.write_Voltage(value/1000.0)
- else:
- logging.error('no Powersupply')
-
- def start(self):
- self.thread = storage.get_board_specific_storage(available_boards[0]).setdefault("AutoScanThread", storage.ThreadStorage())
- if self.thread.running:
- logging.info("Time scan already running")
- self.tst.running = False
-
- return
- start = self.vmin.value()
- stop = self.vmax.value()
- step = self.vstep.value()
- fileinfo = os.path.join(self.outdir, 'scan.info')
- f = open(fileinfo, 'a')
- f.write('##########################\n')
- f.write('#Automated Voltage Scan\n')
- f.write('#Range: {:4d} - {:4d}\n'.format(start,stop))
- f.write('#Step: {:4d}\n'.format(step))
- f.write('\n')
- f.close()
- self.tst = AutomationThread(start, stop, step, available_boards[0])
- self.thread.register(self.tst)
- self.thread.connect('updateSignal', self.update)
- self.thread.connect('stopSignal', self.stop)
- self.thread.connect('startScan', self.startScan)
- self.thread.connect('poststartScan', self.reactivateButton)
- self.progressbar.setRange(start, stop+step)
- self.thread.start('scan')
- self.scaning = True
- self.button.setText('stop')
- Elements.setEnabled('automation', False, exclude=[self.button])
- Elements.setEnabled('timescan', False)
-
- def stop(self):
- if board.get_board_status(available_boards[0]).time_scan:
- self.abortScan()
- while board.get_board_status(available_boards[0]).time_scan:
- sleep(0.05)
- self.thread.stop()
- self.scaning = False
- print('Automation Stop')
- self.progressbar.setValue(self.vmax.value()+self.vstep.value())
- self.button.setText('start')
- Elements.setEnabled('automation', True)
- Elements.setEnabled('timescan', True)
- fileinfo = os.path.join(self.outdir, 'scan.info')
- f = open(fileinfo, 'a')
- f.write('#End\n')
- f.write('##########################\n')
- f.write('\n')
- f.close()
- pass
- def update(self, value):
- self.setV(value)
- self.progressbar.setValue(value)
- self.info.setText("Auto: {:4d} mV".format(value))
- print('Automation update')
- pass
- def reactivateButton(self):
- self.button.setEnabled(True)
- # 88888888888 d8b .d8888b. 888 888 d8b 888 888
- # 888 Y8P d88P Y88b 888 o 888 Y8P 888 888
- # 888 Y88b. 888 d8b 888 888 888
- # 888 888 88888b.d88b. .d88b. "Y888b. .d8888b 8888b. 88888b. 888 d888b 888 888 .d88888 .d88b. .d88b. 888888
- # 888 888 888 "888 "88b d8P Y8b "Y88b. d88P" "88b 888 "88b 888d88888b888 888 d88" 888 d88P"88b d8P Y8b 888
- # 888 888 888 888 888 88888888 "888 888 .d888888 888 888 88888P Y88888 888 888 888 888 888 88888888 888
- # 888 888 888 888 888 Y8b. Y88b d88P Y88b. 888 888 888 888 8888P Y8888 888 Y88b 888 Y88b 888 Y8b. Y88b.
- # 888 888 888 888 888 "Y8888 "Y8888P" "Y8888P "Y888888 888 888 888P Y888 888 "Y88888 "Y88888 "Y8888 "Y888
- # 888
- # Y8b d88P
- # "Y88P"
- class TimeScanWidget(kcgw.KCGWidgets):
- def __init__(self, unique_id, parent):
- super(TimeScanWidget, self).__init__()
- self.scaning = False
- self.id = unique_id
- self.par = parent
- self.scanNumber = 0
- #self.layout = QtGui.QHBoxLayout()
- self.board_id = available_boards[0]
- self.board_config = board.get_board_config(self.board_id)
-
- self.layout = QtGui.QGridLayout()
- self.outerLayout = QtGui.QVBoxLayout()
- self.outerLayout.addLayout(self.layout)
- self.setLayout(self.outerLayout)
- lineindex = 0
-
- if self.board_config.is_KAPTURE2():
- #KAPTURE 2#########################################
- self.layout.addWidget(self.createLabel("330 ps Delay"), lineindex, 0)
- self.delaythmin = self.createSpinbox(0,6, start_value=0)
- self.delaythmax = self.createSpinbox(0,12, start_value=6)
- self.layout.addWidget(self.delaythmin, lineindex, 1)
- self.layout.addWidget(self.delaythmax, lineindex, 2)
- lineindex += 1
- self.layout.addWidget(self.createLabel("25 ps Delay"), lineindex, 0)
- self.delay25min = self.createSpinbox(0,23, start_value=0)
- self.delay25max = self.createSpinbox(0,23, start_value=12)
- self.layout.addWidget(self.delay25min, lineindex, 1)
- self.layout.addWidget(self.delay25max, lineindex, 2)
- lineindex += 1
- self.stepSwitcher = self.createSwitch(startRight=True)
- self.layout.addWidget(self.createLabel("25ps Step 1"), lineindex, 0)
- self.layout.addWidget(self.stepSwitcher, lineindex, 1)
- self.layout.addWidget(self.createLabel("25ps Step 4"), lineindex, 2)
- lineindex += 1
- Elements.addButton(['timescan'], [
- self.delaythmin,
- self.delaythmax,
- self.delay25max,
- self.delay25min,
- self.stepSwitcher
- ])
-
- else:
- #KAPTURE 1#########################################
- self.layout.addWidget(self.createLabel("ADC to T/H Delay"), lineindex, 0)
- self.delayADCTH = self.createSpinbox(0,15, start_value=self.board_config.get('th_to_adc_cycles'), connect=lambda x: self.board_config.update('th_to_adc_cycles', x))
- self.layout.addWidget(self.delayADCTH, lineindex, 1)
- lineindex += 1
- line = QtGui.QFrame()
- line.setFrameStyle(QtGui.QFrame.HLine)
- self.layout.addWidget(line, lineindex, 0, 1, 10)
- lineindex += 1
- self.layout.addWidget(self.createLabel("T/H Delay"), lineindex, 0)
- self.delaythmin = self.createSpinbox(0,15, start_value=0)
- self.delaythmax = self.createSpinbox(0,15, start_value=15)
- self.layout.addWidget(self.delaythmin, lineindex, 1)
- self.layout.addWidget(self.delaythmax, lineindex, 2)
- lineindex += 1
- Elements.addButton(['timescan'], [
- self.delaythmin,
- self.delaythmax,
- self.delayADCTH
- ])
- self.layout.addWidget(self.createLabel("Fine Delay"), lineindex, 0)
- self.delayfinemin = self.createSpinbox(0,31, start_value=0)
- self.delayfinemax = self.createSpinbox(0,31, start_value=31)
- self.layout.addWidget(self.delayfinemin, lineindex, 1)
- self.layout.addWidget(self.delayfinemax, lineindex, 2)
- lineindex += 1
- self.layout.addWidget(self.createLabel("Number of turns"), lineindex, 0)
- self.numofturns = self.createSpinbox(0,1e6, start_value=1000)
- self.layout.addWidget(self.numofturns, lineindex, 1)
- lineindex += 1
- self.layout.addWidget(self.createLabel("Turns to skip"), lineindex, 0)
- self.numofturnsSkip = self.createSpinbox(0,1e6, start_value=0)
- self.layout.addWidget(self.numofturnsSkip, lineindex, 1)
- lineindex += 1
-
- self.layout.addWidget(self.createLabel("Identifyer"), lineindex, 0)
- self.input = self.createInput()
- self.layout.addWidget(self.input, lineindex, 1)
- lineindex += 1
- self.comboBox = QtGui.QComboBox(self)
- self.comboBox.addItem("Mean over Everything", MODE_ALL) #0
- self.comboBox.addItem("Use Threshold", MODE_THREASHOLD) #1
- #self.comboBox.addItem("Use Bucket Detection - processed after scan", MODE_AUTOBUCKET) #2
- #self.comboBox.addItem("Use Bucket Detection and Threshold for live", MODE_AUTOBUCKET_TMP_THRESHOLD) #3
- self.comboBox.addItem("Use Bucket", MODE_BUCKET) #4
- #self.comboBox.addItem("Use TDS Mode", MOD) #5
- self.comboBox.addItem("Use All Buckets", MODE_ALL_BUCKETS) #6
- self.layout.addWidget(self.comboBox, lineindex, 0,1,3)
- lineindex += 1
- self.layout.addWidget(self.createLabel("Threshold / Bucket"), lineindex, 0)
- self.threshold = self.createSpinbox(-2000,2000, start_value=15)
- self.layout.addWidget(self.threshold, lineindex, 1)
- lineindex += 1
- Elements.addButton(['timescan'], [
- self.delayfinemin,
- self.delayfinemax,
- self.numofturns,
- self.numofturnsSkip,
- self.input,
- self.comboBox,
- self.threshold
- ])
- self.layout.addWidget(self.createLabel("Fast Mode"), lineindex, 0)
- self.fastModeSelector = self.createSwitch('Fast Mode', connect=self.setFastMode)
- self.fastModeSelector.setState(False)
- self.layout.addWidget(self.fastModeSelector, lineindex, 1)
- lineindex +=1
- if self.board_config.is_KAPTURE2():
- self.layout.addWidget(self.createLabel("Calibration Scan"), lineindex, 0)
- self.calibSelector = self.createSwitch('Calibration Scan')
- self.calibSelector.setState(False)
- self.layout.addWidget(self.calibSelector, lineindex, 1)
- lineindex +=1
- self.button = self.createButton('start', connect=self.startScan)
- self.layout.addWidget(self.button, lineindex, 1,1,2)
-
- Elements.addButton(['timescan','acquire_0'], self.button)
- self.saverawCB = self.createCheckbox('save Raw', checked=False)
- self.layout.addWidget(self.saverawCB, lineindex, 0)
- lineindex += 1
- self.labelBucket = self.createLabel("")
- self.layout.addWidget(self.labelBucket, lineindex, 0,1,3)
- lineindex += 1
- self.progressbar = QtGui.QProgressBar()
- self.layout.addWidget(self.progressbar, lineindex,0,1,3)
- self.progressbar.setRange(0,1000)
- lineindex += 1
- line = QtGui.QFrame()
- line.setFrameStyle(QtGui.QFrame.HLine)
- self.layout.addWidget(line, lineindex, 0, 1, 3)
- lineindex += 1
-
- ###########################################################
- ### Automation
- #self.automationLayout = QtGui.QGridLayout()
- #self.outerLayout.addLayout(self.automationLayout)
- #self.auto = Automation(self.automationLayout, self.startScan, self.input, self.abort)
- ###########################################################
- self.outerLayout.addStretch(1)
- self.adjustSize()
- #self.layout.addStretch(1)
- self.setWindowTitle("Time Scan Widget")
- self.openPlotWidget()
- self.tst = None
- def setFastMode(self):
- if self.fastModeSelector.state:
- self.delaythmin.setValue(0)
- self.delaythmax.setValue(6)
- self.delay25min.setValue(0)
- self.delay25max.setValue(12)
- self.delayfinemax.setValue(0)
- self.delayfinemin.setValue(0)
- self.threshold.setValue(15)
- self.comboBox.setCurrentIndex(1)
- self.stepSwitcher.setState(False)
- self.calibSelector.setState(False)
- self.stepSwitcher.setEnabled(False)
- self.calibSelector.setEnabled(False)
- self.delayfinemin.setEnabled(False)
- self.delayfinemax.setEnabled(False)
- self.saverawCB.setChecked(False)
- else:
- self.delaythmin.setValue(0)
- self.delaythmax.setValue(6)
- self.delay25min.setValue(0)
- self.delay25max.setValue(12)
- self.delayfinemax.setValue(32)
- self.delayfinemin.setValue(0)
- self.threshold.setValue(3)
- self.comboBox.setCurrentIndex(3)
- self.stepSwitcher.setState(True)
- self.stepSwitcher.setEnabled(True)
- self.calibSelector.setEnabled(True)
- self.delayfinemin.setEnabled(True)
- self.delayfinemax.setEnabled(True)
- #self.saverawCB.setChecked(True)
- def openPlotWidget(self):
- global __timing_plot_widget_id__
- global __timing_plot_widget__
- if __timing_plot_widget__ == None:
- nid = kcgw.idg.genid()
- __timing_plot_widget_id__[self.board_id] = nid
- self.plotWidget = ScanPlotWidget(nid, self.board_id, global_objects.get_global('area'))
- __timing_plot_widget__ = self.plotWidget
- global_objects.get_global('area').newWidget(self.plotWidget, "Timing result", nid, widget_type=5)
-
- def startScan(self):
- if not self.scaning:
- 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)
-
- self.board_config.update('turns_observe', self.numofturns.value())
- self.board_config.update('turns_skip', self.numofturnsSkip.value())
- if self.board_config.is_KAPTURE2():
- self.start(self.delaythmin.value(), self.delaythmax.value(), self.delayfinemin.value(), self.delayfinemax.value(),
- self.input.text(), outdir, self.threshold.value(), saveraw,
- c25_min=self.delay25min.value(), c25_max=self.delay25max.value(), step4=self.stepSwitcher.state,
- meanMode =self.comboBox.itemData(self.comboBox.currentIndex()), fastMode=self.fastModeSelector.state, calibScan=self.calibSelector.state)
- else:
- self.start(self.delaythmin.value(), self.delaythmax.value(), self.delayfinemin.value(), self.delayfinemax.value(),
- self.input.text(), outdir, self.threshold.value(), saveraw, meanMode =self.comboBox.itemData(self.comboBox.currentIndex()))
- else:
- self.abort()
- #self.stop()
- def start(self, c_min, c_max, f_min, f_max, ident, outdir, threshold, saveraw, c25_min=-1, c25_max=-1, step4=False, meanMode=MODE_ALL, fastMode=False, calibScan=False):
- try:
- self.progressbar.setValue(0)
- board.get_board_status(self.board_id).time_scan = True
- self.openPlotWidget()
- self.plotWidget.setPlotParams(c_min, c_max, c25_min, c25_max, f_min, f_max, step4)
- self.thread = storage.get_board_specific_storage(self.board_id).setdefault("TimeScanThread", storage.ThreadStorage())
- if self.thread.running:
- logging.info("Time scan already running")
- return
- self.tst = ScanThread(c_min, c_max, f_min, f_max, available_boards[0], self.scanNumber, ident, outdir, threshold, saveraw, c25_min, c25_max, step4, meanMode, fastMode, calibScan)
- self.thread.register(self.tst)
- self.thread.connect('pbarSignal', self.update)
- self.thread.connect('stopSignal', self.stop)
- self.thread.connect('plotSignal', self.plot)
- self.thread.start('scan')
- self.scaning = True
- self.button.setText('stop')
- except Exception as e:
- logging.error('Start Calibrationscan: ' + str(e))
- def abort(self):
- if self.tst is not None:
- self.tst.stop = True
- #board.get_board_status(self.board_id).time_scan = False
-
- def stop(self, timeScan, file):
- self.thread.stop()
- self.openPlotWidget()
- self.plotWidget.new_data(timeScan)
- #self.labelBucket.setText('Signal in Buckets: {}'.format(self.tst.buckets))
- self.scaning = False
- board.get_board_status(self.board_id).time_scan = False
- self.scanNumber +=1
- self.button.setText('start')
- self.progressbar.setValue(1000)
- #self.plotWidget.giveFilename(file)
- Elements.setEnabled('acquire_{}'.format(self.board_id), True)
- Elements.setEnabled("acquireTrigger_{}".format(self.board_id), True)
- print('fine')
- def update(self, timescan, prozent):
- # print(c_step, f_step, data, prozent)
- #print('update')
- self.openPlotWidget()
- self.plotWidget.new_data(timescan)
- self.progressbar.setValue(prozent*1000)
- def plot(self, data):
- #print('plot', len(data_raw))
- #bif._bif_read_and_update_data_from_string(self.board_id, data_raw)
- if live_plot_windows.hasWindows(self.board_id):
- for plotwin in live_plot_windows.getWindows(self.board_id):
- plotwin.plot_live(data=data)
- QtGui.qApp.processEvents()
- def closeEvent(self, event):
- self.abort()
- global __widget_id__
- __widget_id__ = None
- global updateData
- updateData = None
- del self.par.widgets[self.id]
- def addCalibrationWidget():
- global __widget_id__
- if __widget_id__:
- global_objects.get_global('area').widgets[__widget_id__].setFocus()
- else:
- nid = kcgw.idg.genid()
- __widget_id__ = nid
- w = TimeScanWidget(nid, global_objects.get_global('area'))
- global_objects.get_global('area').newWidget(w, "Time Scan Widget", nid, widget_type=4, minSize=True)
- kcgw.register_widget(QtGui.QIcon(config.icon_path("timescan.png")), "Time Scan Widget", addCalibrationWidget, "Ctrl+Shift+T")
|