12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412 |
- 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)
-
- if c25_step_b == 4 and c_step_b == 0:
- #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")
|