def setupBlComm(): # global message_string_pv thread.start_new_thread(process_commands,(.05,)) # message_string_pv = PV(beamlineName + "_comm:message_string") comm_pv = PV(beamlineName + "_comm:command_s") comm_pv.put("\n",wait=True) comm_pv.add_callback(comm_cb)
def __init__(self, pvStatusName="", pvControlName="", pvHutchName="", mnemonic="", invert=False): StandardDevice.__init__(self, mnemonic) self.delay = 0.01 self.invert = invert self.pvStatus = PV(pvStatusName) self.pvControl = PV(pvControlName) self.pvHutch = PV(pvHutchName)
def __init__(self, verbose=False, pidfile=None, heartbeat_pvname=None, pulsecount_pvname=None, **kws): self.verbose = verbose self.scandb = ScanDB() try: self.set_state(0) except: raise RuntimeError("Cannot connect to ScanDB") self.state = 0 self.last = self.pulse = -1 self.last_move_time = 0 self.config = None self.dead_time = 0.5 self.id_lookahead = 2 self.with_id = False self.counters = [] self.pidfile = pidfile or DEFAULT_PIDFILE self.pulsecount_pv = None self.heartbeat_pv = None if pulsecount_pvname is not None: self.pulsecount_pv = PV(pulsecount_pvname) if heartbeat_pvname is not None: self.heartbeat_pv = PV(heartbeat_pvname) self.connected = False self.connect()
def __init__(self, pvName, mnemonic): """ **Constructor** See :class:`py4syn.epics.StandardDevice` Parameters ---------- pvName : `string` Power supply base naming of the PV (Process Variable) mnemonic : `string` Power supply mnemonic """ super().__init__(mnemonic) self.pvName = pvName self.voltage = Device(pvName + ':VOLTAGE:', self.RANGE) self.current = Device(pvName + ':CURRENT:', self.RANGE) self.program = Device(pvName + ':PROGRAM:', self.PROGRAM) self.programVoltage = Device(pvName + ':PROGRAM:VOLTAGE:', self.PROGRAM_SUB) self.programCurrent = Device(pvName + ':PROGRAM:CURRENT:', self.PROGRAM_SUB) self.resetPV = PV(pvName + ':RESET') self.mode = Device(pvName + ':MODE:', ['SET', 'GET', 'GET.PROC']) self.operationFlag = Device(pvName + ':', ['GET:OPERATION:FLAG', 'GET:OPERATION:FLAG.PROC']) self.timePV = PV(pvName + ':PROGRAM:TIME:ADD') self.error = Device(pvName + ':', ['ERROR', 'ERROR.PROC', 'ERROR:TEXT']) self.defaults() # Operation mode (voltage x current) is cached, so get it immediatelly self.procAndGet(self.mode, 'GET')
def move(self, val, wait=True, delta=0.005, timeout=360.0): """Put value and press Go button.""" PV.put(self, val) sleep(0.2) self.go.put(1) if wait: Motor.motorWait(self, val, delta, timeout)
def start_processes(counter_pv, data_pv, logger, *args): """ This is a main thread that starts thread reacting to the callback, starts the consuming process, and sets a callback on the frame counter PV change. The function then awaits for the data in the exit queue that indicates that all frames have been processed. The functin cancells the callback on exit. Parameters ---------- counter_pv : str a PV string for the area detector frame counter data_pv : str a PV string for the area detector frame data logger : Logger a Logger instance, typically synchronized with the consuming process logger *args : list a list of arguments specific to the client process Returns ------- None """ data_thread = CAThread(target = deliver_data, args=(data_pv, logger,)) data_thread.start() start_process(globals.process_dataq, logger, *args) cntr = PV(counter_pv) cntr.add_callback(on_change, index = 1) globals.exitq.get() cntr.clear_callbacks()
def __init__(self, pvname, pvnumber=None, rbv=None, pvtype=None): if pvnumber and not pvname: pvname = PV(pvPrefix + ':SCANPV' + str(pvnumber) + ':PVNAME').get() self.pvname = pvname if self.pvname: self.pvnumber = pvnumber self.rbv = rbv # Get PV type from 'PV type' menu pvtypePv = PV(pvPrefix + ':SCANPV' + str(self.pvnumber) + ':PVTYPE') if not pvtype: pvtype = pvtypePv.get() # Create PV instance if pvtype == 1: scanpv = Motor(self.pvname, self.pvnumber) elif pvtype == 2: scanpv = PolluxMotor(self.pvname, self.pvnumber) elif pvtype == 3: scanpv = BeckhoffMotor(self.pvname, self.pvnumber) elif pvtype == 4: scanpv = Magnet(self.pvname, self.pvnumber) elif pvtype == 5: scanpv = Lakeshore(self.pvname, self.pvnumber) else: scanpv = BasePv(self.pvname, self.pvnumber, self.rbv) self.scanpv = scanpv self.pvtype = pvtype self.pvtypePv = pvtypePv else: self.scanpv = ''
class BeckhoffMotor(Motor): """Beckhoff Motor class which inherits from pvScan Motor class.""" def __init__(self, pvname, pvnumber=0): if 'ESB' in pvname: rbv = pvname.split(':')[0] + ':CALC:' + ':'.join(pvname.split(':')[3:5]) + ':POS:MM' go = pvname.split(':')[0] + ':BO:' + ':'.join(pvname.split(':')[3:5]) + ':GO:POS' abort = pvname.split(':')[0] + ':BO:' + ':'.join(pvname.split(':')[3:5]) + ':STOP' elif 'UEDM' in pvname: rbv = pvname.split(':')[0] + ':UEDM:' + 'AI:' + pvname.split(':')[-2] + ':POS' go = pvname.split(':')[0] + ':UEDM:' + 'BO:' + pvname.split(':')[-2] + ':GOPOS' abort = pvname.split(':')[0] + ':UEDM:' + pvname.split(':')[-2] + ':STOP' else: rbv = pvname.split(':')[0] + ':CALC:' + ':'.join(pvname.split(':')[2:3]) + ':POS:MM' go = pvname.split(':')[0] + ':BO:' + ':'.join(pvname.split(':')[2:3]) + ':GO:POS:ABS' abort = pvname.split(':')[0] + ':BO:' + ':'.join(pvname.split(':')[2:3]) + ':STOP' BasePv.__init__(self, pvname, pvnumber, rbv) self.go = PV(go) self.abort = PV(abort) def move(self, val, wait=True, delta=0.005, timeout=360.0): """Put value and press Go button.""" PV.put(self, val) sleep(0.2) self.go.put(1) if wait: Motor.motorWait(self, val, delta, timeout)
class PolluxMotor(Motor): """Pollux Motor class which inherits from pvScan Motor class.""" def __init__(self, pvname, pvnumber=0): if pvname.endswith('ACTPOS'): rbv = pvname velo = ':'.join(pvname.split(':')[0:2]) + ':AO:VELO' go = ':'.join(pvname.split(':')[0:2]) + ':BO:GOABS' abort = ':'.join(pvname.split(':')[0:2]) + ':BO:ABORT' pvname = ':'.join(pvname.split(':')[0:2]) + ':AO:ABSMOV' else: rbv = ':'.join(pvname.split(':')[0:2]) + ':AI:ACTPOS' velo = ':'.join(pvname.split(':')[0:2]) + ':AO:VELO' go = ':'.join(pvname.split(':')[0:2]) + ':BO:GOABS' abort = ':'.join(pvname.split(':')[0:2]) + ':BO:ABORT' BasePv.__init__(self, pvname, pvnumber, rbv) self.velo = PV(velo) self.go = PV(go) self.abort = PV(abort) def move(self, val, wait=True, delta=0.005, timeout=360.0): """Put value and press Go button.""" PV.put(self, val) sleep(0.2) self.go.put(1) if wait: Motor.motorWait(self, val, delta, timeout)
def testEnumPut(self): pv = PV(pvnames.enum_pv) self.assertIsNot(pv, None) pv.put('Stop') time.sleep(0.1) val = pv.get() self.assertEqual(val, 0)
def __init__(self): self.radiator = PV("BEAM:GONI:RADIATOR_INDEX") self.diamond = PV("BEAM:GONI:RADIATOR_ID") self.plane = PV("BEAM:CBREM:PLANE") self.edge = PV("BEAM:CBREM:EDGE") #self.name = PV("BEAM:GONI:RAD{:.0f}:NAME",format(self.radiator.get())) self.name = PV("BEAM:GONI:RAD"+str(int(self.radiator.get()))+":NAME")
def connect_to_mca_pvs(med_name,nelem=4): mcas = ["%smca%i" % (med_name,i+1) for i in range(nelem)] for key,suff in (('REAL_TIME','ERTM'),('LIVE_TIME','ELTM'), ('CAL_OFFSET','CALO'),('CAL_SLOPE','CALS'), ('CAL_QUAD','CALQ'), ('TWO_THETA','TTH')): for mca in mcas: x = PV("%s.%s" % (mca,suff)) i = 0 look_for_rois = True while look_for_rois: i = i + 1 look_for_rois = (i < 32) for mca in mcas: try: x = PV('%s.R%iNM' % (mca,i)) val = x.get() if val == '' or val is None: look_for_rois = False break except: look_for_rois = False break lo = PV('%s.R%iLO' % (mca,i)) hi = PV('%s.R%iHI' % (mca,i)) return i
def __init__(self, pvNameIN, pvNameOUT, mnemonic, scalerObject=""): StandardDevice.__init__(self, mnemonic) # IN DXAS:DIO:bi8 # 1.0 (read TTL OUT from CCD) # OUT DXAS:DIO:bo17 # 6.1 (write Trigger IN to CCD start acquisition) self.pvAcquire = PV(pvNameOUT) self.pvMonitor = PV(pvNameIN, callback=self.onAcquireChange) self._done = self.isDone() self.countTime = 1
def __init__(self, pvName="", pvHutchName="", mnemonic=""): StandardDevice.__init__(self, mnemonic) self.delay = 0.01 self.pvFilter1 = PV(pvName+":DIO:XIA:Filter1") self.pvFilter2 = PV(pvName+":DIO:XIA:Filter2") self.pvFilter3 = PV(pvName+":DIO:XIA:Filter3") self.pvFilter4 = PV(pvName+":DIO:XIA:Filter4") self.pvHutch = PV(pvHutchName)
def test_put_string_waveform(self): write('String Array: \n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['a', 'b', 'c'] pv.put(put_value) get_value = pv.get(use_monitor=False, count=len(put_value)) numpy.testing.assert_array_equal(get_value, put_value)
def __init__(self): self.eiger = EigerTest('10.130.11.111', '80') self.arm_pv = PV('13EIG1:cam1:ARM_CMD', self.epics_cb) self.trigger_pv = PV('13EIG1:cam1:TRIGGER_CMD', self.epics_cb) self.disarm_pv = PV('13EIG1:cam1:DISARM_CMD', self.epics_cb) self.ntrigger_pv = PV('13EIG1:cam1:NTRIGGER', self.epics_cb) self.triggermode_pv = PV('13EIG1:cam1:TRIGGER_MODE', self.epics_cb) self.sequence_id_pv = PV('13EIG1:cam1:SEQUENCE_ID')
def test_waveform_get_with_count_arg(self): with no_simulator_updates(): wf = PV(pvnames.char_arr_pv, count=32) val=wf.get() self.assertEquals(len(val), 32) val=wf.get(count=wf.nelm) self.assertEquals(len(val), wf.nelm)
def test_get1(self): write('Simple Test: test value and char_value on an integer\n') with no_simulator_updates(): pv = PV(pvnames.int_pv) val = pv.get() cval = pv.get(as_string=True) self.failUnless(int(cval)== val)
def test_get1(self): write('Simple Test: test value and char_value on an integer\n') pause_updating() pv = PV(pvnames.int_pv) val = pv.get() cval = pv.get(as_string=True) self.failUnless(int(cval)== val) resume_updating()
class Shutter(object): def __init__(self, pvname): self.out_pv = PV(pvname) def open(self): self.out_pv.put(str(1)) def close(self): self.out_pv.put(str(0))
def get(d, pv_name, size, start, pid): pv = PV(pv_name) if pv.wait_for_connection(timeout=1.0): d[pv_name] = pv.get(use_monitor=False) else: d[pv_name] = 'not connected' if len(d) == size: print int(round((time.time() - start) * 1000)) os.kill(pid, signal.SIGTERM)
def test_put_string_waveform_zero_length_strings(self): write('String Array: put zero length strings\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['', '', ''] pv.put(put_value, wait=True) time.sleep(0.05) get_value = pv.get(use_monitor=False, as_numpy=False) numpy.testing.assert_array_equal(get_value, put_value)
def test_put_string_waveform_empty_list(self): write('String Array: put empty list\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = [] pv.put(put_value, wait=True) time.sleep(0.05) get_value = pv.get(use_monitor=False, as_numpy=False) self.failUnless('' == ''.join(get_value))
def test_put_string_waveform_mixed_types(self): write('String Array: put mixed types\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['a', 2, 'b'] pv.put(put_value, wait=True) time.sleep(0.05) get_value = pv.get(use_monitor=False, as_numpy=False) numpy.testing.assert_array_equal(get_value, ['a', '2', 'b'])
def testA_CreatedWithConn(self): write('Simple Test: create pv with conn callback\n') pv = PV(pvnames.int_pv, connection_callback=onConnect) val = pv.get() global CONN_DAT conn = CONN_DAT.get(pvnames.int_pv, None) self.assertEqual(conn, True)
class Shutter(object): def __init__(self): self.out_pv = PV('34idc:softGlue:OR-1_IN2_Signal') def open(self): self.out_pv.put(str(1)) def close(self): self.out_pv.put(str(0))
def test_put_string_waveform_single_element(self): write('String Array: put single element\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['a'] pv.put(put_value, wait=True) time.sleep(0.05) get_value = pv.get(use_monitor=False, as_numpy=False) self.failUnless(put_value[0] == get_value)
def connect(self): self.config = json.loads(self.scandb.get_config('qxafs').notes) pulse_channel = "%sCurrentChannel" % self.config['mcs_prefix'] self.pulse_pv = PV(pulse_channel, callback=self.onPulse) self.idarray_pv = PV(self.config['id_array_pv']) self.iddrive_pv = PV(self.config['id_drive_pv']) self.idbusy_pv = PV(self.config['id_busy_pv']) self.pulsecount_pv = PV(PULSECOUNT_PVNAME) self.heartbeat_pv = PV(HEARTBEAT_PVNAME)
def move(self, val, wait=False, delta=0.005, timeout=300.0): """Put with optional wait.""" PV.put(self,val) if wait or self.rbv: if not self.delta: delta = delta else: delta = self.delta self.pvWait(val, delta, timeout)
def init_var_channels(beamlineComm): global var_channel_list,beamlineStateChannel beamlineStateChannel = PV(beamlineComm + "beamlineState") beamlineStateChannel.put(0) for varname in list(stateVars.keys()): var_channel_list[varname] = PV(beamlineComm + varname) # beamline_support.pvPut(var_channel_list[varname],stateVars[varname]) var_channel_list[varname].add_callback(var_list_item_changeCb,varname=varname)
def main(argv=None): global simulate global fp global shut_open global current #parse command line options usage = "usage: %prog [options]\nData files are written to /data/<year>/<month>/<day>/" parser = OptionParser(usage) parser.add_option("--detname", action="store", type="string", dest="detname", help="detector PV base") parser.add_option("--xstart", action="store", type="float", dest="xo", help="starting X position") parser.add_option("--xnumstep", action="store", type="int", dest="Nx", help="number of steps in X") parser.add_option("--xstepsize", action="store", type="float", dest="dx", help="step size in X") parser.add_option("--ystart", action="store", type="float", dest="yo", help="starting Y position") parser.add_option("--ynumstep", action="store", type="int", dest="Ny", help="number of steps in Y") parser.add_option("--ystepsize", action="store", type="float", dest="dy", help="step size in Y") parser.add_option("--wait", action="store", type="float", dest="stall", help="wait at each step [seconds]") parser.add_option("--simulate", action="store_true", dest="sim", default=False, help="simulate motor moves") parser.add_option("--checkbeam", action="store_true", dest="checkbeam", default=False, help="only acquire when beam is on") parser.add_option("--acqtime", action="store", type="float", dest="acqt", help="image integration time [sec]") (options, args) = parser.parse_args() #open log file D0 = time.localtime()[0] D1 = time.localtime()[1] D2 = time.localtime()[2] D3 = time.localtime()[3] D4 = time.localtime()[4] cd = os.getcwd() filedir = '/nfs/xf05id1/data/' if sys.argv[0][0] == '.': out_filename=filedir+repr(D0)+'/'+repr(D1)+'/'+repr(D2)+'/'+'log_'+repr(D3)+'_'+repr(D4)+'_'+\ string.split(string.strip(sys.argv[0],'./'),'/')[0]+'.txt' else: out_filename=filedir+repr(D0)+'/'+repr(D1)+'/'+repr(D2)+'/'+'log_'+repr(D3)+'_'+repr(D4)+'_'+\ string.split(string.strip(sys.argv[0],'./'),'/')[5]+'.txt' try: os.chdir(filedir + repr(D0)) except OSError: try: os.mkdir(filedir + repr(D0)) except Exception: print 'cannot create directory: ' + '/data/' + repr(D0) sys.exit() try: os.chdir(filedir + repr(D0) + '/' + repr(D1)) except OSError: try: os.mkdir(filedir + repr(D0) + '/' + repr(D1)) except Exception: print 'cannot create directory: ' + '/data/' + repr( D0) + '/' + repr(D1) sys.exit() try: os.chdir(filedir + repr(D0) + '/' + repr(D1) + '/' + repr(D2)) except OSError: try: os.mkdir(filedir + repr(D0) + '/' + repr(D1) + '/' + repr(D2)) except Exception: print 'cannot create directory: ' + filedir + repr( D0) + '/' + repr(D1) + '/' + repr(D2) sys.exit() try: fp = open(out_filename, 'a') except Exception: print 'cannot open file: ' + out_filename sys.exit() os.chdir(cd) fp.write('#' + ', '.join(sys.argv)) fp.write('\n') H5path = '/epics/data/201507/300126' #initialize PVs and callbacks if options.detname == None: # detstr='XF:03IDA-BI{FS:1-CAM:1}' detstr = '' print "must provide detector pv base, e.g., 'XF:28IDA-BI{URL:01}'" sys.exit() else: detstr = options.detname xmotname = 'XF:05IDD-ES:1{Stg:Smpl1-Ax:X}' ymotname = 'XF:05IDD-ES:1{Stg:Smpl1-Ax:Y}' xmot = PV(xmotname + 'Mtr.VAL') xmot_cur = PV(xmotname + 'Mtr.RBV') ymot = PV(ymotname + 'Mtr.VAL') ymot_cur = PV(ymotname + 'Mtr.RBV') shut_status = PV('SR:C05-EPS{PLC:1}Shutter:Sum-Sts') beam_current = PV('SR:C03-BI{DCCT:1}I:Total-I') #transmission #check command line options if options.yo == None: print "must provide a starting point in the vertical" sys.exit() else: yo = options.yo if options.xo == None: print "must provide a starting point in the horizontal" sys.exit() else: xo = options.xo if options.dx == None: dx = 0.00000001 else: dx = options.dx if options.dy == None: dy = 0.00000001 else: dy = options.dy if options.Nx == None: Nx = 0 else: Nx = options.Nx if options.Ny == None: Ny = 0 else: Ny = options.Ny if options.stall == None: twait = 0. else: twait = options.stall diode0 = PV(detstr + 'Cur:I0-I') diode1 = PV(detstr + 'Cur:I1-I') diode2 = PV(detstr + 'Cur:I2-I') diode3 = PV(detstr + 'Cur:I3-I') x3acq = PV('XSPRESS3-EXAMPLE:Acquire') x3erase = PV('XSPRESS3-EXAMPLE:ERASE') x3acqtime = PV('XSPRESS3-EXAMPLE:AcquireTime') x3acqnum = PV('XSPRESS3-EXAMPLE:NumImages') x3tmode = PV('XSPRESS3-EXAMPLE:TriggerMode') x3h5path = PV('XSPRESS3-EXAMPLE:HDF5:FilePath') x3h5fname = PV('XSPRESS3-EXAMPLE:HDF5:FileName') x3h5fnum = PV('XSPRESS3-EXAMPLE:HDF5:FileNumber') x3h5capture = PV('XSPRESS3-EXAMPLE:HDF5:Capture') #report ROIs for channels and counts at each point x3ch1roi0min = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI1_LLM') x3ch1roi0max = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI1_HLM') x3ch1roi0ct = PV('XSPRESS3-EXAMPLE:C1_ROI1:Value_RBV') x3ch1roi1min = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI2_LLM') x3ch1roi1max = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI2_HLM') x3ch1roi1ct = PV('XSPRESS3-EXAMPLE:C1_ROI2:Value_RBV') x3ch1roi2min = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI3_LLM') x3ch1roi2max = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI3_HLM') x3ch1roi2ct = PV('XSPRESS3-EXAMPLE:C1_ROI3:Value_RBV') x3ch2roi0min = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI1_LLM') x3ch2roi0max = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI1_HLM') x3ch2roi0ct = PV('XSPRESS3-EXAMPLE:C2_ROI1:Value_RBV') x3ch2roi1min = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI2_LLM') x3ch2roi1max = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI2_HLM') x3ch2roi1ct = PV('XSPRESS3-EXAMPLE:C2_ROI2:Value_RBV') x3ch2roi2min = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI3_LLM') x3ch2roi2max = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI3_HLM') x3ch2roi2ct = PV('XSPRESS3-EXAMPLE:C2_ROI3:Value_RBV') x3ch3roi0min = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI1_LLM') x3ch3roi0max = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI1_HLM') x3ch3roi0ct = PV('XSPRESS3-EXAMPLE:C3_ROI1:Value_RBV') x3ch3roi1min = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI2_LLM') x3ch3roi1max = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI2_HLM') x3ch3roi1ct = PV('XSPRESS3-EXAMPLE:C3_ROI2:Value_RBV') x3ch3roi2min = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI3_LLM') x3ch3roi2max = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI3_HLM') x3ch3roi2ct = PV('XSPRESS3-EXAMPLE:C3_ROI3:Value_RBV') #claim ROI 4 for our own use. we will integrate over all 4096 channels. x3ch1roi3min = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI4_LLM') x3ch1roi3max = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI4_HLM') x3ch1roi3ct = PV('XSPRESS3-EXAMPLE:C1_ROI4:Value_RBV') x3ch2roi3min = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI4_LLM') x3ch2roi3max = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI4_HLM') x3ch2roi3ct = PV('XSPRESS3-EXAMPLE:C2_ROI4:Value_RBV') x3ch3roi3min = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI4_LLM') x3ch3roi3max = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI4_HLM') x3ch3roi3ct = PV('XSPRESS3-EXAMPLE:C3_ROI4:Value_RBV') xmot_cur.get() ymot_cur.get() norm0 = PV('XF:05IDD-BI:1{BPM:01}.S20') norm1 = PV('XF:05IDD-BI:1{BPM:01}.S21') norm2 = PV('XF:05IDD-BI:1{BPM:01}.S22') norm3 = PV('XF:05IDD-BI:1{BPM:01}.S23') xmot_cur.add_callback(cbfx) ymot_cur.add_callback(cbfy) shut_status.add_callback(cbf_shut) beam_current.add_callback(cbf_curr) xmot_cur.run_callbacks() ymot_cur.run_callbacks() shut_status.run_callbacks() beam_current.run_callbacks() x3h5path.put(H5path) x3h5fname.put(repr(D3) + '_' + repr(D4) + '_') x3h5fnum.put(0) x3acqtime.put(options.acqt) x3acqnum.put(1) x3tmode.put(1) x3ch1roi3min.put(0) x3ch2roi3min.put(0) x3ch3roi3min.put(0) x3ch1roi3max.put(4096) x3ch2roi3max.put(4096) x3ch3roi3max.put(4096) str = '#Start time is ' + time.asctime() print str fp.write(str) fp.write('\n') str = '#[point #]\tX pos\tY pos\tch 1\tch 2\tch 3\tch 4\tBPM1\troi0\troi1\troi2\troi3\ttime' print str fp.write(str) fp.write('\n') str='# x: %(hs)6.4f ; y: %(vs)6.4f ; ROI1 %(roi1i)d:%(roi1a)d ; ROI2 %(roi2i)d:%(roi2a)d ; ROI3 %(roi3i)d:%(roi3a)d'%\ {"hs":xmot_cur.get(),"vs":ymot_cur.get(), 'roi1i':x3ch1roi1min.get(), 'roi1a':x3ch1roi1max.get(), 'roi2i':x3ch1roi2min.get(), 'roi2a':x3ch1roi2max.get(), 'roi3i':x3ch1roi3min.get(), 'roi3a':x3ch1roi3max.get(),} print str fp.write(str) fp.write('\n') roits = x3ch3roi3ct.timestamp if options.sim is True: str = " -----simulating motor moves and bursts-----" print str fp.write(str) fp.write('\n') time.sleep(2) #number of rows and columns completed by scan Ncol = Nrow = 0 LN = 0 #diode readback is now limiting factor for scan speed oldsig = 0. #when the cryocooler kicks in, the beam is unusable for ~3200sec cryo = PV('XF:05IDA-OP:1{Mono:HDCM}T:LN2Out-I') ct = cryo.get() while (ct is None): time.sleep(0.05) ct = cryo.get() t0 = time.time() cryocounter = 0 shut_toggle = False #nested loops for scanning z,x,y for y in np.linspace(yo, yo + ((Ny) * dy), Ny + 1): tar[1][0] = y tar[1][1] = 1 if options.sim is False: ymot.put(tar[1][0]) if indeadband(float(tar[1][0]), float(ymot_cur.get()), dbd) == 1: tar[1][1] = 0 if Nrow % 2 == 0: xs = 0. + xo xe = ((Nx + 1) * dx) + xo - dx xi = dx else: xs = ((Nx) * dx) + xo xe = 0. + xo xi = -dx for x in np.linspace(xs, xe, Nx + 1): tar[0][0] = x tar[0][1] = 1 if indeadband(float(tar[0][0]), float(xmot_cur.get()), dbd) == 1: tar[0][1] = 0 if options.sim is False: xmot.put(tar[0][0]) while ((tar[0][1] == 1) or (tar[1][1] == 1)): time.sleep(0.01) signal0 = signal1 = signal2 = signal3 = 0. nsig0 = nsig1 = nsig2 = nsig3 = 0. sig0 = sig1 = sig2 = sig3 = 0. time.sleep(twait) while (options.checkbeam and (cryo.get() < (ct - 0.1))): print "Stopped. Detected possible cryocooler activation." time.sleep(1) cryocounter = cryocounter + 1 #if the above is true for five cycles, the cryocooler was on, wait another 10min if (options.checkbeam and cryocounter > 300): print "Detected cryocooler activation, waiting 10min" time.sleep(600) cryocounter = 0 while (options.checkbeam and (shut_open == False or beam_current == False)): print "Stopped. Waiting for scan conditions to return to normal." if shut_open == False: shut_toggle = True time.sleep(10.) if shut_toggle == True: print "Entering optics conditioning period. Waiting 5min" time.sleep(300) shut_toggle = False if options.sim is False: x3h5capture.put(1) x3erase.put(1) x3acq.put(1) while signal0 == 0.: signal0 = diode0.get() while signal1 == 0.: signal1 = float(diode1.get()) while (signal1 == oldsig): time.sleep(0.05) signal1 = diode1.get() oldsig = signal1 while signal2 == 0.: signal2 = diode2.get() while signal3 == 0.: signal3 = diode3.get() while nsig0 == 0.: nsig0 = float(norm0.get()) while nsig1 == 0.: nsig1 = float(norm1.get()) while nsig2 == 0.: nsig2 = float(norm2.get()) while nsig3 == 0.: nsig3 = float(norm3.get()) time.sleep(options.acqt) while (x3ch3roi3ct.timestamp == roits): time.sleep(0.1) roits = x3ch3roi3ct.timestamp while (x3ch3roi3ct.timestamp == roits): time.sleep(0.1) sig0 = x3ch1roi0ct.get() + x3ch2roi0ct.get() + x3ch3roi0ct.get( ) sig1 = x3ch1roi1ct.get() + x3ch2roi1ct.get() + x3ch3roi1ct.get( ) sig2 = x3ch1roi2ct.get() + x3ch2roi2ct.get() + x3ch3roi2ct.get( ) sig3 = x3ch1roi3ct.get() + x3ch2roi3ct.get() + x3ch3roi3ct.get( ) roits = x3ch3roi3ct.timestamp tn = time.time() - t0 if options.sim is False: str = '[%(X)06d] at ( %(XC)9.4f , %(YC)9.4f ): %(d1)10.7e %(d2)10.7e %(d3)10.7e %(d4)10.7e %(norm)10.7e %(s0)10.7e %(s1)10.7e %(s2)10.7e %(s3)10.7e %(time)9.2f' % { 'X': Ncol, 'XC': xmot_cur.get(), "YC": ymot_cur.get(), "d1": float(signal0), "d2": float(signal1), "d3": float(signal2), "d4": float(signal3), 'norm': nsig0 + nsig1 + nsig2 + nsig3, "s0": sig0, "s1": sig1, "s2": sig2, "s3": sig3, "time": tn } print str fp.write(str) fp.write('\n') else: str = '[%(X)06d] at ( %(XC)8.4f , %(YC)8.4f ): %(d1)10.7e %(d2)10.7e %(d3)10.7e %(d4)10.7e' % { "X": int(Ncol), "XC": tar[0][0], "YC": tar[1][0], "d1": float(signal0), "d2": float(signal1), "d3": float(signal2), "d4": float(signal3) } print str fp.write(str) fp.write('\n') Ncol = Ncol + 1 Nrow = Nrow + 1 str = 'End time is ' + time.asctime() print str fp.write(str) fp.write('\n') fp.close() return 0
smtp.login('*****@*****.**', 'Controle123') subject = 'Alerta Radiação via Supervisório' mail_de = '*****@*****.**' mail_para = '*****@*****.**' mail_msgm1 = 'Subject: %s\n\n%s' % (subject,'ALERTA !!\nUma das sondas de Radiação atingiu o limite da Integral em 4 horas!') mail_msgm2 = '\n \nDiagnóstico dos dados: \n \n' + '{}: {} uSv \n{}: {} uSv \n{}: {} uSv \n'.format(thermo, valorthermo, el, valorel, berthold, valorberthold) mail_msgm3 = '\n\nObservação: O email foi enviado pelo supervisório pois alguém apertou o botão para restaurar o sistema' mail_msgm4 = '\n\nProteção Radiológica - SIRIUS\nGrupo de Controle\nLNLS - CNPEM' mail_msgm = mail_msgm1 + mail_msgm2 + mail_msgm3 + mail_msgm4 smtp.sendmail(mail_de,mail_para, mail_msgm) smtp.close() # obj PV thermo = PV('RAD:THERMO:DoseIntegral') Else = PV('RAD:ELSE:DoseIntegral') berthold = PV('RAD:Berthold:DoseIntegral') # Pegando o valor do obj PV pvthermo = thermo.value pvelse = Else.value pvberthold = berthold.value # nome das PVs namethermo = 'Thermo' nameelse = 'Else' nameberthold = 'Berthold' # chama a função enviar email send(namethermo, pvthermo, nameelse, pvelse, nameberthold, pvberthold)
class M40_Tester(Tester): def __init__(self, path, test_name): self.path = path + str(test_name) Tester.__init__(self, self.path) self.data1 = [] self.data2 = [] self.stop = 99 self.status = PV('status') if test_name == 'epics': self.connected = True else: self.connected = util.check_device( 'A1', self.proc) and self.status.get() in range(0, 4) def io(self): if not self.connected: print "Device not connected" return False d_o = [] a_o = [] d_i = [] a_i = [] d_outs = { 1: PV('digitalOut1'), 2: PV('digitalOut2'), 3: PV('digitalOut3'), 4: PV('digitalOut4'), 5: PV('digitalOut5'), 6: PV('digitalOut6'), 7: PV('digitalOut7'), 8: PV('digitalOut8') } d_ins = { 1: PV('digitalIn1'), 2: PV('digitalIn2'), 3: PV('digitalIn3'), 4: PV('digitalIn4'), 5: PV('digitalIn5'), 6: PV('digitalIn6'), 7: PV('digitalIn7'), 8: PV('digitalIn8') } a_outs = { 1: PV('analogOut1'), 2: PV('analogOut2'), 3: PV('analogOut3'), 4: PV('analogOut4'), 5: PV('analogOut5'), 6: PV('analogOut6'), 7: PV('analogOut7'), 8: PV('analogOut8') } a_ins = { 1: PV('analogIn1'), 2: PV('analogIn2'), 3: PV('analogIn3'), 4: PV('analogIn4'), 5: PV('analogIn5'), 6: PV('analogIn6'), 7: PV('analogIn7'), 8: PV('analogIn8'), } poll(evt=1.e-5, iot=0.01) for i in range(0, 8): d_o.append(util.put_check(d_outs[i + 1], 1)) a_o.append(util.put_check(a_outs[i + 1], i)) d_i.append(util.pv_check(d_ins[i + 1], 1)) a_i.append(a_ins[i + 1].get() != None) return [x for sublist in [d_i, a_i, d_o, a_o] for x in sublist] def set_digital_outs(self): d_o = [] d_outs = { 1: PV('digitalOut1'), 2: PV('digitalOut2'), 3: PV('digitalOut3'), 4: PV('digitalOut4'), 5: PV('digitalOut5'), 6: PV('digitalOut6'), 7: PV('digitalOut7'), 8: PV('digitalOut8') } poll(evt=1.e-5, iot=0.01) for i in range(0, 8): d_o.append(util.put_check(d_outs[i + 1], 1)) return d_o def set_analog_outs(self): a_o = [] a_outs = { 1: PV('analogOut1'), 2: PV('analogOut2'), 3: PV('analogOut3'), 4: PV('analogOut4'), 5: PV('analogOut5'), 6: PV('analogOut6'), 7: PV('analogOut7'), 8: PV('analogOut8') } poll(evt=1.e-5, iot=0.01) for i in range(0, 8): a_o.append(util.put_check(a_outs[i + 1], i)) return a_o def get_digital_ins(self): d_i = [] d_ins = { 1: PV('digitalIn1'), 2: PV('digitalIn2'), 3: PV('digitalIn3'), 4: PV('digitalIn4'), 5: PV('digitalIn5'), 6: PV('digitalIn6'), 7: PV('digitalIn7'), 8: PV('digitalIn8') } poll(evt=1.e-5, iot=0.01) for i in range(0, 8): d_i.append(util.pv_check(d_ins[i + 1], 0)) return d_i def get_analog_ins(self): a_i = [] a_ins = { 1: PV('analogIn1'), 2: PV('analogIn2'), 3: PV('analogIn3'), 4: PV('analogIn4'), 5: PV('analogIn5'), 6: PV('analogIn6'), 7: PV('analogIn7'), 8: PV('analogIn8'), } poll(evt=1.e-5, iot=0.01) for i in range(0, 8): a_i.append(a_ins[i + 1].get() != None) return a_i def enable_stopcount(self): if not self.connected: print "Device not connected" return False stop = 100 data1 = [] data2 = [] def getData1(pvname, value, **kw): if value != 0: data1.append(value) def getData2(pvname, value, **kw): if value != 0: data2.append(value) analog1 = PV('analogIn1') stop_count = PV('outStopCount') init = PV('initiate') analog2 = PV('analogIn2') poll(evt=1.e-5, iot=0.01) analog1.wait_for_connection() analog2.wait_for_connection() init.wait_for_connection() stop_count.wait_for_connection() analog1.add_callback(getData1) if util.put_check(stop_count, stop): init.put(1) t0 = time.time() while time.time() - t0 < 30: poll(evt=1.e-5, iot=0.01) else: print "Stopcount not set" return False buffered_run = len(data1) analog2.add_callback(getData2) time.sleep(2) if util.put_check(stop_count, -1): init.put(1) t0 = time.time() while time.time() - t0 < 30: poll(evt=1.e-5, iot=0.01) else: print "Stopcount not set 2nd time" return False unbuffered_run = len(data2) return buffered_run, unbuffered_run def init(self): if not self.connected: print "Device not conncted" return False init = PV('initiate') a_in_1 = PV('analogIn1') poll(evt=1.e-5, iot=0.01) before_init = a_in_1.get() init.put(1) poll(evt=1, iot=1) after_init = a_in_1.get() return before_init, after_init def abort(self): if not self.connected: print "Device not conncted" return False init = PV('initiate') data = [] a_in_1 = PV('analogIn1') poll(evt=1.e-5, iot=0.01) def getData1(pvname, value, **kw): if value != 0: data.append(value) a_in_1.add_callback(getData1) poll(evt=1.e-5, iot=0.01) init.put(1) poll(evt=1.e-5, iot=0.01) t0 = time.time() while time.time() - t0 < 10: poll(evt=1.e-5, iot=0.01) if len(data) >= 50: init.put(0) time.sleep(2) return len(data) def stopcount_value(self): if not self.connected: print "Device not connected" return False #util.pv_check('status', 0) #self.stop = 1001 data1 = [] data2 = [] def getData1(pvname, value, **kw): if value != 0: data1.append(value) def getData2(pvname, value, **kw): if value != 0: data2.append(value) analog1 = PV('analogIn1') stop_count = PV('outStopCount') init = PV('initiate') analog2 = PV('analogIn2') poll(evt=1.e-5, iot=0.01) analog1.wait_for_connection() analog2.wait_for_connection() init.wait_for_connection() stop_count.wait_for_connection() util.put_check(stop_count, 100) analog1.add_callback(getData1) init.put(1) poll(evt=1.e-5, iot=0.01) t0 = time.time() while time.time() - t0 < 10: poll(evt=1.e-5, iot=0.01) first_run = len(data1) analog1.remove_callback(0) analog1.add_callback(getData2) time.sleep(2) util.put_check(stop_count, 200) init.put(1) poll(evt=1.e-5, iot=0.01) t0 = time.time() while time.time() - t0 < 10: poll(evt=1.e-5, iot=0.01) second_run = len(data2) return first_run, second_run
def io(self): if not self.connected: print "Device not connected" return False d_o = [] a_o = [] d_i = [] a_i = [] d_outs = { 1: PV('digitalOut1'), 2: PV('digitalOut2'), 3: PV('digitalOut3'), 4: PV('digitalOut4'), 5: PV('digitalOut5'), 6: PV('digitalOut6'), 7: PV('digitalOut7'), 8: PV('digitalOut8') } d_ins = { 1: PV('digitalIn1'), 2: PV('digitalIn2'), 3: PV('digitalIn3'), 4: PV('digitalIn4'), 5: PV('digitalIn5'), 6: PV('digitalIn6'), 7: PV('digitalIn7'), 8: PV('digitalIn8') } a_outs = { 1: PV('analogOut1'), 2: PV('analogOut2'), 3: PV('analogOut3'), 4: PV('analogOut4'), 5: PV('analogOut5'), 6: PV('analogOut6'), 7: PV('analogOut7'), 8: PV('analogOut8') } a_ins = { 1: PV('analogIn1'), 2: PV('analogIn2'), 3: PV('analogIn3'), 4: PV('analogIn4'), 5: PV('analogIn5'), 6: PV('analogIn6'), 7: PV('analogIn7'), 8: PV('analogIn8'), } poll(evt=1.e-5, iot=0.01) for i in range(0, 8): d_o.append(util.put_check(d_outs[i + 1], 1)) a_o.append(util.put_check(a_outs[i + 1], i)) d_i.append(util.pv_check(d_ins[i + 1], 1)) a_i.append(a_ins[i + 1].get() != None) return [x for sublist in [d_i, a_i, d_o, a_o] for x in sublist]
class OceanOpticsSpectrometer(ImageHDF): # CONSTRUCTOR OF Ocean CLASS def __init__(self, mnemonic, pv=None, responseTimeout=15, output="./out", numPoints=1044, mcas=False): """Constructor responseTimeout : how much time to wait qe65000 answer numPoints : how many points are collected each time """ super().__init__(mnemonic, numPoints, output, 'ocean') self.acquireChanged = Event() self.acquiring = False try: # determines the start of counting self.pvStart = PV(pv + ":Acquire") # determines mode of Acquisition (Single,Continous, Dark Spectrum) self.pvAcquireMode = PV(pv + ":AcquisitionMode") # use darkcorrection self.pvDarkCorrection = PV(pv + ":ElectricalDark") # spectrum self.pvSpectrum = PV(pv + ":Spectra") self.pvSpectrumCorrected = PV(pv + ":DarkCorrectedSpectra") # set Acquire Time self.pvAcquireTime = PV(pv + ":SetIntegration") # integration Time self.pvTime = PV(pv + ":IntegrationTime:Value") # control the end of acquire process self.pvAcquire = PV(pv + ":Acquiring") self.pvAcquire.add_callback(self.statusChange) # acquisition mode self.pvAcMode = PV(pv + ":AcquisitionMode") # set to single mode self.pvAcMode.put("Single") # axis Spectra pvAxis = PV(pv + ":SpectraAxis") self.axis = pvAxis.get(as_numpy=True)[:self.numPoints] # regions of interest self.ROIS = [] self.mcas = mcas self.responseTimeout = responseTimeout self.timer = Timer(self.responseTimeout) except TypeError: raise RuntimeError('PV not found') except ValueError: raise RuntimeError('Device is offline') def statusChange(self, value, **kw): """ Helper callback used to wait for the end of the acquisition. """ if value == 0: self.acquiring = False else: self.acquiring = True # threads waiting are awakened self.acquireChanged.set() def setCountTime(self, time): """ Method to set the count time of a scaler device. Parameters ---------- time : `float` Count time to set to scaler device . Returns ------- out : None """ self.pvTime.put(time, wait=True) self.timer = Timer(time + self.responseTimeout) def getCountTime(self): return self.pvTime.get() def setCountStop(self): # TODO: test # Work only when in continuos mode pass def close(self): self.setCountStop() def saveUniquePoint(self, data, fmt, suffixName=""): self.mcaFile = super().nameFile(self.output, self.prefix + suffixName, "mca") np.savetxt(self.mcaFile, data, fmt=fmt) def saveSpectrum(self, **kwargs): ''' save the spectrum intensity in a mca file or an hdf file ''' dark = self.pvDarkCorrection.get() # the spectra come from different pv if use darkcorrection if dark == 1: allSpectrum =\ self.pvSpectrumCorrected.get(as_numpy=True)[:self.numPoints] else: allSpectrum = self.pvSpectrum.get(as_numpy=True)[:self.numPoints] self.spectrum = allSpectrum suffix = "" if self.image: super().saveSpectrum() if not self.image or self.mcas: self.saveUniquePoint( np.array([self.axis, self.spectrum]).T, "%f\t%f") # there are ROIS to save / works only for points if len(self.ROIS) > 0 and not self.image: i = 1 for mini, maxi in self.ROIS: # get the spectrum positions start = bisect(self.axis, mini) end = bisect(self.axis, maxi) roi = allSpectrum[start:end] self.spectrum = roi data = np.array([self.axis[start:end], self.spectrum]).T self.saveUniquePoint(data, "%f\t%f", suffixName="_ROI" + str(i)) i += 1 def isCountRunning(self): return (self.acquiring) def wait(self): """ Blocks until the acquisition completes. """ if self.acquiring is False: return self.acquireChanged.clear() # while acquiring and not time out waits # TODO: find a better way to do this while self.acquiring and self.timer.check(): self.acquireChanged.wait(0.001) self.acquireChanged.clear() if self.timer.expired(): raise RuntimeError('Ocean is not answering') def canMonitor(self): """ Returns false indicating cannot be use as a counter monitor""" return False def canStopCount(self): """ Returns true indicating that Dxp has a stop command. """ return False def getValue(self, **kwargs): """Return intensity It's a dummy method, always return 1.0. """ self.saveSpectrum() return 1.0 def isCounting(self): return self.acquiring def startCount(self): """ Starts acquiring an spectrum It's necessary to call setCounTime before""" if self.acquiring: raise RuntimeError('Already counting') self.acquiring = True self.pvStart.put("Stop") # resets initial time value self.timer.mark() def stopCount(self): self.setCountStop() def setPresetValue(self, channel, val): """Dummy method""" pass def startCollectImage(self, rows=0, cols=0): super().startCollectImage('float32', rows, cols) def addRoi(self, roi): """ Insert a new roi roi: a tuple with begin and end: (begin,end)""" self.ROIS.append(roi)
def output_cspad_streak(ds=None, alias='DscCsPad', pvbase='CXI:SC1:DIFFRACT', nevents=10, **kwargs): """ Output cspad jet streak information """ beam_x_pv = PV(':'.join([pvbase, 'X0'])) beam_y_pv = PV(':'.join([pvbase, 'Y0'])) streak_angle_pv = PV(':'.join([pvbase, 'STREAK_PHI'])) streak_intensity_pv = PV(':'.join([pvbase, 'STREAK_INTENSITY'])) streak_width_pv = PV(':'.join([pvbase, 'STREAK_WIDTH'])) if not ds: ds = DataSource(**kwargs) # Now set in epics -- update as needed from epics. # beam_x_pv.put(2094.9301668334006) # run 104 # beam_y_pv.put(-1796.5697333657126) detector = ds._detectors[alias] detector.next() detector.add.property(asic) cy, cx = get_center(detector, beam_x_pv, beam_y_pv) j_map_1, j_map_2 = find_proj_mapping(cy, cx) detector.add.parameter(proj_map_1=j_map_1, proj_map_2=j_map_2) detector.add.property(streak_angle_raw) detector.add.property(streak_present) try: iloop = 0 time0 = time.time() while True: streak_angle = detector.streak_angle_raw[0] streak_intensity = detector.streak_angle_raw[1] streak_width = detector.streak_angle_raw[2] streak_angle_pv.put(streak_angle) streak_intensity_pv.put(streak_intensity) streak_width_pv.put(streak_width) if not (iloop + 1) % nevents and detector.streak_present: evt_rate = iloop / (time.time() - time0) print('{:15} {:6.1f} Hz {:5.1f} {:5.1f} {:5.3f} {}' ''.format(iloop, evt_rate, streak_angle, streak_intensity, streak_width, int(detector.streak_present))) iloop += 1 detector.next() except KeyboardInterrupt: return
from epics import PV pv = PV('OPS:message1') val = pv.get() print(val)
def _get_pv(self, pvname): if not pvname in self._pvs: self._pvs[pvname] = PV(pvname) return self._pvs[pvname]
from eco.devices_general.alvradetectors import DIAClient bsdaqJF = DIAClient( "bsdaqJF", instrument="alvra", api_address="http://sf-daq-alvra:10000", jf_name="JF_4.5M", ) try: bsdaqJF.pgroup = int(exp_config["pgroup"][1:]) except: print("Could not set p group in bsdaqJF !!") checkerPV = PV("SARFE10-PBPG050:HAMP-INTENSITY-CAL") def checker_function(limits): cv = checkerPV.get() if cv > limits[0] and cv < limits[1]: return True else: return False checker = {} checker["checker_call"] = checker_function checker["args"] = [[100, 300]] checker["kwargs"] = {} checker["wait_time"] = 3
class SensorOcean(QThread): ''' SensorOcean is a class that acquires spectrogram from OceanOpticsSpectrometer and calculates the two most important peaks to calculate pressure ''' error_message = pyqtSignal(str) signal = pyqtSignal([np.ndarray]) def __init__(self, pvname): QThread.__init__(self) self.pvname = pvname try: self.createOcean() except RuntimeError: self.ocean = None def createOcean(self): self.numPoints = 2048 self.mnemonic = str(int(time.time())) self.ocean = OceanOpticsSpectrometer(self.mnemonic, pv=self.pvname, numPoints=self.numPoints) createCounter(self.mnemonic, self.ocean) # disable graph and fitscan setPlotGraph(False) setFitScan(False) self.pvProgressBar = PV(self.pvname + ':ProgressBar') if self.pvProgressBar.get() <= 1: if (self.ocean.pvStart.get() == "Start"): self.ocean.pvStart.put("Stop") self.pvProgressBar.add_callback(self.searchPeaks) def editIntegrationTime(self, timeValue): ''' Edit integration time ''' ''' It was developed due to a good interface user style''' try: self.timeValue = timeValue self.ocean.pvTime.put(value = timeValue, wait = True) return True except: return False def isReady(self): # if ocean is disconnected cannot run if self.ocean is None: try: self.createOcean() except RuntimeError: return False return True def searchPeaks(self,pvname=None, value=None, char_value=None, **kws): try: if (char_value is not None) and (float(char_value) >= 100): start = time.time() ''' Defining which data is X or Y ''' ydata = self.getYdata() xdata = self.getXdata() ''' Selecting peaks and getting the respective wavelength ''' wavelength = indexes(ydata,xdata) #wavelength = np.array([695,694]) print('wavelength',wavelength) ''' Filtering situations to emit signal''' if wavelength is not None: self.signal.emit(wavelength) else: self.signal.emit(np.array([-1])) stop = time.time() print('Time exec: ',(stop-start)) except OSError as err: self.error_message.emit("Fatal exception error! Close E-MA application! ->" + str(err)) def getYdata(self): ''' Getting Y data ''' dark = self.ocean.pvDarkCorrection.get() ''' The spectra come from different pv if use darkcorrection ''' if dark == 1: allSpectrum =self.ocean.pvSpectrumCorrected.get(as_numpy=True)[:self.numPoints] elif dark == 0: allSpectrum = self.ocean.pvSpectrum.get(as_numpy=True)[:self.numPoints] else: allSpectrum = 0 return allSpectrum def getXdata(self): ''' Getting X data ''' return self.ocean.axis #I need to test if axis X will have the same range regardless of time''' def saveData(self,pathComp,peak1zero = 692.80,peak2zero = 694.26,temp = 300.00): try: np.savetxt(pathComp, np.array([self.getXdata(), self.getYdata()]).T, fmt="%f\t%f", header = self.headerData(peak1zero,peak2zero,temp)) if ((os.path.isfile(pathComp))): self.error_message.emit("Spectrogram data saved!" + str(' See:') + pathComp) return True else: self.error_message.emit("Average file not saved. Error saving file.") return False except OSError as err: self.error_message.emit("Average file not saved. Error saving file: " + str(err)) return False def headerData(self,peak1 = 692.80,peak2 = 694.26,temp = 300.00): itime = '\n Integration time (s): ' + str(self.timeValue) peaks1 = '\nPeak1 (nm): ' + str(peak1) peaks2 = '\nPeak2 (nm): ' + str(peak2) temp = '\nTemperature (K): ' + str(temp) clocktime = '\nSaved at: ' + time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) return HEADER + DEVICE + itime + PAPERS + STANDARD + peaks1 + peaks2 + temp + clocktime + LEGEND def run(self): import time while(True): try: #start = time.time() ''' Getting data from PV''' dark = self.ocean.pvDarkCorrection.get() print('Dark value: ', dark) if dark is None: break else: #self.searchPeaks(dark) sleep(self.scantime) #stop = time.time() #print('Time exec: ',(stop-start)) except OSError as err: self.error_message.emit("Error on automatic search peak: " + str(err)) break def oneread(self): try: ''' Getting data from PV''' dark = self.ocean.pvDarkCorrection.get() print('Dark value: ', dark) if dark is not None: self.searchPeaks(dark) except OSError as err: self.error_message.emit("Error on automatic search peak: " + str(err))
return response file_datetime = datetime.datetime.now().strftime('%Y%m%d.%H%M%S') print('file identifier:', file_datetime) # Create any directories needed BASEDIR = 'Tests_3.0m/' + device #os.makedirs(BASEDIR) rawfo = open(BASEDIR + '/data_' + file_datetime + '.dat', 'w') asynpv = 'SR:C11-ID:G1{IVU20:1}Asyn' pvid = 'SR:C11-ID:G1{IVU20:1' aout = PV('SR:C04-ID:G1{IVU:1}Asyn.AOUT') ainp = PV('SR:C04-ID:G1{IVU:1}Asyn.AINP') gap_set = PV(pvid + '-Mtr:2}Inp:Pos') start = PV(pvid + '-Mtr:2}Sw:Go.PROC') # Servo interrupt time (need for gather period) i10 = float(command('I10')) servo_interrupt_time = i10 / 8388608. / 1e3 gather_period = sample_time / nsamples / servo_interrupt_time print('gather period', gather_period) sample_period = int(gather_period) * servo_interrupt_time total_time = sample_period * nsamples print('total_time', total_time) rawfo.write(str(sample_period) + '\n')
import time bval = 0 def func(x, a, b, c): return a * np.exp(-(x - b)**2 / (2 * c**2)) def onChanges(pvname=None, value=None, char_value=None, **kw): global bval bval = value return mypv = PV('LEBT-DIAG:WS002:BValue') mypv.add_callback(onChanges) t0 = time.time() """while time.time() - t0 < 5.0:""" while True: bvalue = bval if bvalue: x = np.linspace(-10, 10, 100) """y = func(x, 2, 0, 2)""" y = func(x, 1e-5, 0, 3) np.random.seed(int(time.time())) yn = y + 0.2 * np.random.normal(size=len(x)) popt, pcov = curve_fit(func, x, yn) print(popt) wavepv = PV('LEBT-DIAG:WS002:WValue')
class Motoman(StandardDevice): def finish(self, value, **kw): if value == "Done": self.motomanfinish = True else: self.motomanfinish = False def __init__(self, pvPrefix="", mnemonic=""): StandardDevice.__init__(self, mnemonic) self.pvBVAL_RBV = PV(pvPrefix + ":BVAL_RBV") self.pvBVAL = PV(pvPrefix + ":BVAL") self.pvBPOS = PV(pvPrefix + ":BPOS") self.pvSVON = PV(pvPrefix + ":SVON") self.pvRUNNING = PV(pvPrefix + ":RUNNING") self.pvRUNNING.add_callback(self.finish) self.pvJOB = PV(pvPrefix + ":JOB") self.pvGOJOB = PV(pvPrefix + ":GOJOB") self.pvSTA1 = PV(pvPrefix + ":STA1") self.pvSTA2 = PV(pvPrefix + ":STA2") self.motomanfinish = False def changeJOB(self, job=""): self.pvJOB.put(job) def goJOB(self): self.pvGOJOB.put(1) self.motomanfinish = False while not self.motomanfinish: sleep(0.1) def waitFinish(self): while not self.motomanfinish: sleep(0.01) def servoON(self, bool): if ((bool != 0) and (bool != 1)): self.pvSVON.put(0) else: self.pvSVON.put(bool) def readBVAL(self): return self.pvBVAL_RBV.get() def setBVAL(self, val): if ((val < 0) or (val > 50)): self.pvBVAL.put(0) self.pvSVON.put(0) else: self.pvBVAL.put(val) def setBPOS(self, pos): if ((pos < 0) or (pos > 2)): self.pvBPOS.put(000) else: self.pvBPOS.put(pos) def readSTA1(self): return self.pvSTA1.get() def readSTA2(self): return self.pvSTA2.get() def setSample(self, val): self.setBPOS(0) self.setBVAL(val) def removeSample(self): self.setBPOS(2) self.setBVAL(1) def run(self): self.changeJOB("CICLO") self.goJOB()
from epics import PV from time import sleep import datetime,os,sys newpid=os.fork() # Run as a separate (detached) process if newpid!=0: sys.exit(0) #filepath='/nfs/slac/g/nlcta/u01/nlcta/phantom/scanData/' filepath='/home/nlcta/phantom/scanData/' # writing to local disk is faster datalogpts=90 # total number of PV data points to log dataint=0.5 # pause between PV data log points xstagerbvpv=PV('ESB:XPS1:m3:MOTR.RBV') xspeedpv=PV('ESB:XPS4:m2:MOTR.VELO') ystagerbvpv=PV('ESB:XPS1:m4:MOTR.RBV') rotstagerbvpv=PV('ESB:XPS1:m6:MOTR.RBV') foilstagerbvpv=PV('ESB:XPS4:m1:MOTR.RBV') lasershutterpv=PV('ESB:THSC01:SHUTTER:OC') laserstopperpv=PV('ESB:BO:2124-8:BIT5') screenpv=PV('ESB:BO:2114-1:BIT5') lsrpwrpv=PV('ESB:A01:ADC1:AI:CH3') toroid0355pv=PV('ESB:A01:ADC1:AI:CH4') toroid2150pv=PV('ESB:A01:ADC1:AI:CH5') pvlist=[lsrpwrpv,toroid0355pv,toroid2150pv,lasershutterpv,laserstopperpv,screenpv,xspeedpv,xstagerbvpv,ystagerbvpv,rotstagerbvpv,foilstagerbvpv] #pvlist=[xstagepv,ystagepv,rotstagepv]
def __init__(self, pvPrefix="", mnemonic=""): StandardDevice.__init__(self, mnemonic) self.pvBVAL_RBV = PV(pvPrefix + ":BVAL_RBV") self.pvBVAL = PV(pvPrefix + ":BVAL") self.pvBPOS = PV(pvPrefix + ":BPOS") self.pvSVON = PV(pvPrefix + ":SVON") self.pvRUNNING = PV(pvPrefix + ":RUNNING") self.pvRUNNING.add_callback(self.finish) self.pvJOB = PV(pvPrefix + ":JOB") self.pvGOJOB = PV(pvPrefix + ":GOJOB") self.pvSTA1 = PV(pvPrefix + ":STA1") self.pvSTA2 = PV(pvPrefix + ":STA2") self.motomanfinish = False
def build_threshold_table(self, rt_d, t, force_write, ignore_pv, is_bpm): # fist check the parameters valid_pvs = True bad_pv_names = '' ro_pvs = False ro_pv_names = '' # read-only pv names self.force_write = force_write self.ignore_pv = ignore_pv for l in t: [table_name, t_index, integrator, t_type, value] = l table_name = table_name.lower() t_index = t_index.lower() integrator = integrator.lower() t_type = t_type.lower() if (table_name != 'lc2' and table_name != 'alt' and table_name != 'lc1' and table_name != 'idl'): print 'ERROR: Invalid thresholds for device {0}, table {1}, integrator {2}, threshold {3}'.\ format(rt_d.mpsdb_name, table_name, integrator, t_index) print 'ERROR: Invalid table "{0}" (parameter={1})'.format( l[0], l) return False if (not (((integrator.startswith('i')) and len(integrator) == 2 and int(integrator[1]) >= 0 and int(integrator[1]) <= 3) or integrator == 'x' or integrator == 'y' or integrator == 'tmit')): print 'ERROR: Invalid thresholds for device {0}, table {1}, integrator {2}, threshold {3}'.\ format(rt_d.mpsdb_name, table_name, integrator, t_index) print 'ERROR: Invalid integrator "{0}" (parameter={1})'.format( integrator, l) return False if (not (t_index.startswith('t'))): print 'ERROR: Invalid thresholds for device {0}, table {1}, integrator {2}, threshold {3}'.\ format(rt_d.mpsdb_name, table_name, integrator, t_index) print 'ERROR: Invalid threshold "{0}", must start with T (parameter={1})'.format( t_index, l) return False else: if (len(t_index) != 2): print 'ERROR: Invalid thresholds for device {0}, table {1}, integrator {2}, threshold {3}'.\ format(rt_d.mpsdb_name, table_name, integrator, t_index) print 'ERROR: Invalid threshold "{0}", must be in T<index> format (parameter={1})'.format( t_index, l) return False else: if (table_name == 'lc2' or table_name == 'alt'): if (int(t_index[1]) < 0 or int(t_index[1]) > 7): print 'ERROR: Invalid thresholds for device {0}, table {1}, integrator {2}, threshold {3}'.\ format(rt_d.mpsdb_name, table_name, integrator, t_index) print 'ERROR: Invalid threshold index "{0}", must be between 0 and 7 (parameter={1})'.\ format(t_index[1], l) return False else: if (int(t_index[1]) != 0): print 'ERROR: Invalid thresholds for device {0}, table {1}, integrator {2}, threshold {3}'.\ format(rt_d.mpsdb_name, table_name, integrator, t_index) print 'ERROR: Invalid threshold index "{0}", must be 0'.\ format(t_index[1], l) return False if (not (t_type == 'lolo' or t_type == 'hihi')): print 'ERROR: Invalid thresholds for device {0}, table {1}, integrator {2}, threshold {3}'.\ format(rt_d.mpsdb_name, table_name, integrator, t_index) print 'ERROR: Invalid threshold type "{0}", must be LOLO or HIHI (parameter={1})'.\ format(t_type, l) return False # build a dictionary with the input parameters self.table = {} for l in t: [table_name, t_index, integrator, t_type, value] = l table_name = table_name.lower() t_index = t_index.lower() integrator = integrator.lower() t_type = t_type.lower() # Rename fields to match database if (integrator == 'x'): integrator = 'i0' if (integrator == 'y'): integrator = 'i1' if (integrator == 'tmit'): integrator = 'i2' if (t_type == 'lolo'): t_type = 'l' if (t_type == 'hihi'): t_type = 'h' if (not table_name in self.table.keys()): self.table[table_name] = {} if (not t_index in self.table[table_name].keys()): self.table[table_name][t_index] = {} if (not integrator in self.table[table_name][t_index].keys()): self.table[table_name][t_index][integrator] = {} if (not t_type in self.table[table_name][t_index][integrator].keys()): self.table[table_name][t_index][integrator][t_type] = value pv_name = self.mps_names.getThresholdPv( self.mps_names.getAnalogDeviceNameFromId(rt_d.mpsdb_id), table_name, t_index, integrator, t_type, is_bpm) pv_name_enable = pv_name + '_EN' pv = PV(pv_name) pv_enable = PV(pv_name_enable) if (t_type == 'l'): self.table[table_name][t_index][integrator]['l_pv'] = pv self.table[table_name][t_index][integrator][ 'l_pv_enable'] = pv_enable else: self.table[table_name][t_index][integrator]['h_pv'] = pv self.table[table_name][t_index][integrator][ 'h_pv_enable'] = pv_enable if (pv.host == None or pv_enable.host == None): if (not ignore_pv): valid_pvs = False bad_pv_names = '{} {}'.format(bad_pv_names, pv_name) elif (not force_write): if (not pv.write_access): ro_pvs = True ro_pv_names = '{} {}'.format(ro_pv_names, pv_name) # pp=PrettyPrinter(indent=4) # pp.pprint(self.table) if (not valid_pvs): error_message = 'Cannot find PV(s)' print( 'ERROR: The following PV(s) cannot be reached, threshold change not allowed:' ) print(bad_pv_names) return error_message, bad_pv_names, False if (ro_pvs): error_message = 'Read-only PV(s)' print( 'ERROR: The following PV(s) are read-only, threshold change not allowed:' ) print(ro_pv_names) return error_message, ro_pv_names, False return 'OK', '', True
def output_cspad_sum(ds=None, alias='DscCsPad', pvbase='CXI:SC1:DIFFRACT', calc_period=True, calc_streak=False, psd_events=None, psd_rate=None, psd_resolution=None, **kwargs): """Outputs cspad sum and certain statistics as PVs Parameters ---------- ds : DataSource, optional DataSource object, if not specified, loads it using kwargs alias : str, optional Name for CsPad data pvbase : str, optional Base for PV names calc_period : bool, optional Determines the execution of frequency analysis psd_events : int, optional Number of events for frequency analysis, default is 240 psd_rate : int or float, optional Event rate [Hz], default is 120 psd_resolution : int, optional Resolution setting will perform rolling mean [Hz] """ # Configure epics PVs print('Initializing epics PVs') cspad_sum_pv = PV(':'.join([pvbase, 'TOTAL_ADU'])) streak_fraction_pv = PV(':'.join([pvbase, 'STREAK_FRACTION'])) stats_mean_pv = PV(':'.join([pvbase, 'STATS_MEAN'])) stats_std_pv = PV(':'.join([pvbase, 'STATS_STD'])) stats_min_pv = PV(':'.join([pvbase, 'STATS_MIN'])) stats_max_pv = PV(':'.join([pvbase, 'STATS_MAX'])) psd_frequency_pv = PV(':'.join([pvbase, 'PSD_FREQUENCY'])) psd_amplitude_pv = PV(':'.join([pvbase, 'PSD_AMPLITUDE'])) psd_rate_pv = PV(':'.join([pvbase, 'PSD_RATE'])) psd_events_pv = PV(':'.join([pvbase, 'PSD_EVENTS'])) psd_resolution_pv = PV(':'.join([pvbase, 'PSD_RESOLUTION'])) psd_freq_min_pv = PV(':'.join([pvbase, 'PSD_FREQ_MIN'])) psd_freq_wf_pv = PV(':'.join([pvbase, 'PSD_FREQ_WF'])) psd_amp_wf_pv = PV(':'.join([pvbase, 'PSD_AMP_WF'])) # psd_amp_array_pv = PV(':'.join([pvbase,'PSD_AMP_ARRAY'])) if psd_rate: psd_rate_pv.put(psd_rate) psd_rate = psd_rate_pv.get() if psd_rate > 360 or psd_rate < 10: psd_rate = 120. psd_rate_pv.put(psd_rate) if psd_events: psd_events_pv.put(psd_events) psd_events = psd_events_pv.get() if psd_events > 1200 or psd_events < 60: psd_events = psd_rate * 2. psd_events_pv.put(psd_events) if psd_resolution: psd_resolution_pv.put(psd_resolution) psd_resolution = psd_resolution_pv.get() if psd_resolution > 5 or psd_resolution < 0.1: psd_resolution = psd_rate / float(psd_events) psd_resolution_pv.put(psd_resolution) nroll = int(psd_resolution * psd_events / float(psd_rate)) psd_freq_min = psd_freq_min_pv.get() if psd_freq_min > 40 or psd_freq_min < 2: psd_freq_min = 5. psd_freq_min_pv.put(psd_freq_min) if0 = int(psd_freq_min / float(psd_rate) * psd_events) psd_freq_wf = np.arange(psd_events / 2. + 1.) * \ float(psd_rate) / float(psd_events) psd_freq_wf_pv.put(psd_freq_wf) print('Events = {}'.format(psd_events)) print('... done') if not ds: ds = DataSource(**kwargs) print('... done') detector = ds._detectors[alias] detector.next() detector.add.property(asic) detector.add.property(streak_present) try: no_streak = [] iloop = 0 icheck = 0 streaks = 0 time0 = time.time() time_last = time0 sums = [] # aPxx = [] # atime = [] while True: cspad_sum = detector.corr.sum() sums.append(cspad_sum) cspad_sum_pv.put(cspad_sum) if calc_streak: streak = detector.streak_present streaks += streak if not streak: no_streak.append(iloop) iloop += 1 icheck += 1 if not iloop % psd_events: sums = np.asarray(sums) det_avg = sums.mean() det_std = sums.std() det_max = sums.max() det_min = sums.min() stats_mean_pv.put(det_avg) stats_max_pv.put(det_max) stats_min_pv.put(det_min) stats_std_pv.put(det_std) if calc_period: # f should be same as psd_freq_wf f, Pxx = periodogram(sums, psd_rate) if nroll > 1: Pxx = pd.DataFrame(Pxx).rolling(nroll).mean().values[ nroll:, 0] f = f[nroll:] psd_frequency = f[Pxx[if0:].argmax() + if0] psd_amplitude = Pxx[if0:].max() / 4 * psd_rate / psd_events psd_frequency_pv.put(psd_frequency) psd_amplitude_pv.put(psd_amplitude) psd_amp_wf_pv.put(Pxx) time_next = time.time() evtrate = icheck / (time_next - time_last) icheck = 0 time_last = time_next print('{:8.1f} Hz - {:8.1f} {:12} {:12} {:12}' ''.format(evtrate, psd_frequency, psd_amplitude, det_avg, det_std)) # # Need to makd sure right shape before outputting array # aPxx.append(Pxx) # psd_amp_array_pv.put(np.asarray(aPxx)) if calc_streak: streak_fraction = streaks / psd_events streak_fraction_pv.put(streak_fraction) sums = [] # aPxx = [] # atime = [] streaks = 0 no_streak = [] # Change to evt.next() in future and count damage detector.next() except KeyboardInterrupt: return except Exception as e: print(e)
def main(argv=None): global simulate global fp global shut_open global current #parse command line options usage = "usage: %prog [options]\nData files are written to /data/<year>/<month>/<day>/" parser = OptionParser(usage) parser.add_option("--detname", action="store", type="string", dest="detname", help="detector PV base") parser.add_option("--xstart", action="store", type="float", dest="xo", help="starting X position") parser.add_option("--xnumstep", action="store", type="int", dest="Nx", help="number of steps in X") parser.add_option("--xstepsize", action="store", type="float", dest="dx", help="step size in X") parser.add_option("--ystart", action="store", type="float", dest="yo", help="starting Y position") parser.add_option("--ynumstep", action="store", type="int", dest="Ny", help="number of steps in Y") parser.add_option("--ystepsize", action="store", type="float", dest="dy", help="step size in Y") parser.add_option("--wait", action="store", type="float", dest="stall", help="wait at each step [seconds]") parser.add_option("--simulate", action="store_true", dest="sim", default=False, help="simulate motor moves") parser.add_option("--checkbeam", action="store_true", dest="checkbeam", default=False, help="only acquire when beam is on") (options, args) = parser.parse_args() #open log file D0 = time.localtime()[0] D1 = time.localtime()[1] D2 = time.localtime()[2] D3 = time.localtime()[3] D4 = time.localtime()[4] cd = os.getcwd() filedir = '/nfs/xf05id1/data/' if sys.argv[0][0] == '.': out_filename=filedir+repr(D0)+'/'+repr(D1)+'/'+repr(D2)+'/'+'log_'+repr(D3)+'_'+repr(D4)+'_'+\ string.split(string.strip(sys.argv[0],'./'),'/')[0]+'.txt' else: out_filename=filedir+repr(D0)+'/'+repr(D1)+'/'+repr(D2)+'/'+'log_'+repr(D3)+'_'+repr(D4)+'_'+\ string.split(string.strip(sys.argv[0],'./'),'/')[5]+'.txt' try: os.chdir(filedir + repr(D0)) except OSError: try: os.mkdir(filedir + repr(D0)) except Exception: print 'cannot create directory: ' + '/data/' + repr(D0) sys.exit() try: os.chdir(filedir + repr(D0) + '/' + repr(D1)) except OSError: try: os.mkdir(filedir + repr(D0) + '/' + repr(D1)) except Exception: print 'cannot create directory: ' + '/data/' + repr( D0) + '/' + repr(D1) sys.exit() try: os.chdir(filedir + repr(D0) + '/' + repr(D1) + '/' + repr(D2)) except OSError: try: os.mkdir(filedir + repr(D0) + '/' + repr(D1) + '/' + repr(D2)) except Exception: print 'cannot create directory: ' + filedir + repr( D0) + '/' + repr(D1) + '/' + repr(D2) sys.exit() try: fp = open(out_filename, 'a') except Exception: print 'cannot open file: ' + out_filename sys.exit() os.chdir(cd) fp.write('#' + ', '.join(sys.argv)) fp.write('\n') #initialize PVs and callbacks if options.detname == None: # detstr='XF:03IDA-BI{FS:1-CAM:1}' detstr = '' print "must provide detector pv base, e.g., 'XF:28IDA-BI{URL:01}'" sys.exit() else: detstr = options.detname xmotname = 'XF:05IDD-ES:1{Stg:Smpl1-Ax:X}' #AerotechX ymotname = 'XF:05IDD-ES:1{Stg:Smpl1-Ax:Y}' #AerotechY xmot = PV(xmotname + 'Mtr.VAL') xmot_cur = PV(xmotname + 'Mtr.RBV') ymot = PV(ymotname + 'Mtr.VAL') ymot_cur = PV(ymotname + 'Mtr.RBV') shut_status = PV('SR:C05-EPS{PLC:1}Shutter:Sum-Sts') beam_current = PV('SR:C03-BI{DCCT:1}I:Total-I') #transmission #check command line options if options.yo == None: print "must provide a starting point in the vertical" sys.exit() else: yo = options.yo if options.xo == None: print "must provide a starting point in the horizontal" sys.exit() else: xo = options.xo if options.dx == None: dx = 0.00000001 else: dx = options.dx if options.dy == None: dy = 0.00000001 else: dy = options.dy if options.Nx == None: Nx = 0 else: Nx = options.Nx if options.Ny == None: Ny = 0 else: Ny = options.Ny if options.stall == None: twait = 0. else: twait = options.stall diode0 = PV(detstr + 'Cur:I0-I') diode1 = PV(detstr + 'Cur:I1-I') diode2 = PV(detstr + 'Cur:I2-I') diode3 = PV(detstr + 'Cur:I3-I') xmot_cur.get() ymot_cur.get() norm0 = PV('xf05bpm03:DataRead_Ch1') norm1 = PV('xf05bpm03:DataRead_Ch2') norm2 = PV('xf05bpm03:DataRead_Ch3') norm3 = PV('xf05bpm03:DataRead_Ch4') ssa0 = PV('XF:05IDA-BI{BPM:05}AH501:Current1:MeanValue_RBV') ssa0.get() ssa1 = PV('XF:05IDA-BI{BPM:05}AH501:Current2:MeanValue_RBV') ssa1.get() ssa2 = PV('XF:05IDA-BI{BPM:05}AH501:Current3:MeanValue_RBV') ssa2.get() ssa3 = PV('XF:05IDA-BI{BPM:05}AH501:Current4:MeanValue_RBV') ssa3.get() xmot_cur.add_callback(cbfx) ymot_cur.add_callback(cbfy) shut_status.add_callback(cbf_shut) beam_current.add_callback(cbf_curr) xmot_cur.run_callbacks() ymot_cur.run_callbacks() shut_status.run_callbacks() beam_current.run_callbacks() str = '#Start time is ' + time.asctime() print str fp.write(str) fp.write('\n') str = '#[point #]\tX pos\tY pos\tch 1\tch 2\tch 3\tch 4\tBPM1\tssa0\tssa1\tssa2\tssa3\ttime' print str fp.write(str) fp.write('\n') str='# x: %(hs)6.4f ; y: %(vs)6.4f '%\ {"hs":xmot_cur.get(),"vs":ymot_cur.get()} print str fp.write(str) fp.write('\n') if options.sim is True: str = " -----simulating motor moves and bursts-----" print str fp.write(str) fp.write('\n') time.sleep(2) #number of rows and columns completed by scan Ncol = Nrow = 0 LN = 0 #diode readback is now limiting factor for scan speed oldsig = 0. #when the cryocooler kicks in, the beam is unusable for ~3200sec cryo = PV('XF:05IDA-OP:1{Mono:HDCM}T:LN2Out-I') ct = cryo.get() while (ct is None): time.sleep(0.05) ct = cryo.get() t0 = time.time() cryocounter = 0 shut_toggle = False #nested loops for scanning z,x,y for y in np.linspace(yo, yo + ((Ny) * dy), Ny + 1): tar[1][0] = y tar[1][1] = 1 if options.sim is False: ymot.put(tar[1][0]) if indeadband(float(tar[1][0]), float(ymot_cur.get()), dbd) == 1: tar[1][1] = 0 if Nrow % 2 == 0: xs = 0. + xo xe = ((Nx + 1) * dx) + xo - dx xi = dx else: xs = ((Nx) * dx) + xo xe = 0. + xo xi = -dx for x in np.linspace(xs, xe, Nx + 1): tar[0][0] = x tar[0][1] = 1 if indeadband(float(tar[0][0]), float(xmot_cur.get()), dbd) == 1: tar[0][1] = 0 if options.sim is False: xmot.put(tar[0][0]) while ((tar[0][1] == 1) or (tar[1][1] == 1)): time.sleep(0.01) signal0 = signal1 = signal2 = signal3 = 0. nsig0 = nsig1 = nsig2 = nsig3 = 0. sigssa0 = sigssa1 = sigssa2 = sigssa3 = 0. time.sleep(twait) while (options.checkbeam and (cryo.get() < (ct))): print "Stopped. Detected possible cryocooler activation." time.sleep(1) cryocounter = cryocounter + 1 #if the above is true for five cycles, the cryocooler was on, wait another 5min if (options.checkbeam and cryocounter > 300): print "Detected cryocooler activation, waiting 10min" time.sleep(600) cryocounter = 0 while (options.checkbeam and (shut_open == False or beam_current == False)): print "Stopped. Waiting for scan conditions to return to normal." if shut_open == False: shut_toggle = True time.sleep(10.) if shut_toggle == True: print "Entering optics conditioning period. Waiting 5min" time.sleep(300) shut_toggle = False if options.sim is False: while signal0 == 0.: signal0 = diode0.get() while signal1 == 0.: signal1 = float(diode1.get()) while (signal1 == oldsig): time.sleep(0.05) signal1 = diode1.get() oldsig = signal1 while signal2 == 0.: signal2 = diode2.get() while signal3 == 0.: signal3 = diode3.get() while nsig0 == 0.: nsig0 = float(norm0.get()) while nsig1 == 0.: nsig1 = float(norm1.get()) while nsig2 == 0.: nsig2 = float(norm2.get()) while nsig3 == 0.: nsig3 = float(norm3.get()) sigssa0 = ssa0.get() sigssa1 = ssa1.get() sigssa2 = ssa2.get() sigssa3 = ssa3.get() tn = time.time() - t0 if options.sim is False: str = '[%(X)06d] at ( %(XC)9.4f , %(YC)9.4f ): %(d1)10.7e %(d2)10.7e %(d3)10.7e %(d4)10.7e %(norm)10.7e %(s0)10.7e %(s1)10.7e %(s2)10.7e %(s3)10.7e %(time)9.2f' % { 'X': Ncol, 'XC': xmot_cur.get(), "YC": ymot_cur.get(), "d1": float(signal0), "d2": float(signal1), "d3": float(signal2), "d4": float(signal3), 'norm': nsig0 + nsig1 + nsig2 + nsig3, "s0": sigssa0, "s1": sigssa1, "s2": sigssa2, "s3": sigssa3, "time": tn } print str fp.write(str) fp.write('\n') else: str = '[%(X)06d] at ( %(XC)8.4f , %(YC)8.4f ): %(d1)10.7e %(d2)10.7e %(d3)10.7e %(d4)10.7e' % { "X": int(Ncol), "XC": tar[0][0], "YC": tar[1][0], "d1": float(signal0), "d2": float(signal1), "d3": float(signal2), "d4": float(signal3) } print str fp.write(str) fp.write('\n') Ncol = Ncol + 1 Nrow = Nrow + 1 str = 'End time is ' + time.asctime() print str fp.write(str) fp.write('\n') fp.close() return 0
args = parser.parse_args() # pv_prefix = args.pv_prefix try: n_scans = int(args.n_scans) except ValueError as e: print(e) print('--> Setting n_scans to 1') n_scans = 1 # Global timestamps NOW = datetime.datetime.now().strftime('%Y%m%d_%H%M') TODAY = datetime.datetime.now().strftime('%Y%m%d') ## Get/Set some PVs msgPv = PV(pv_prefix + ':MSG') msgPv.put('Initializing run...') print('Initializing run...') DEBUG = PV(pv_prefix + ':WDEBUG:ENABLE').get() script_pv = PV(pv_prefix + ':SCRIPT') script = script_pv.get(as_string=True) filepath_autoset = PV(pv_prefix + ':DATA:FILEPATH:AUTOSET').get() filepath_pv = PV(pv_prefix + ':DATA:FILEPATH') n_scans_pv = PV(pv_prefix + ':N_SCANS') scan_count_pv = PV(pv_prefix + ':SCAN:COUNT') scan_count_pv.put(0) run_pv = PV(pv_prefix + ':RUNFLAG') #exp_name = PV(pv_prefix + ':EXP:NAME').get(as_string=True) #sample_name = PV(pv_prefix + ':SCAN:SAMPLE_NAME').get(as_string=True) exp_name_pv = PV(pv_prefix + ':EXP:NAME') sample_name_pv = PV(pv_prefix + ':SCAN:SAMPLE_NAME')
#!/usr/bin/env python # For aborting scans. # mdunning 1/7/16 from epics import PV from time import sleep import os,sys,signal # PV prefix for pvScan IOC; should be passed as an argument to this script. pvPrefix=sys.argv[1] # Set an environment variable for so pvScan module can use it os.environ['PVSCAN_PVPREFIX']=pvPrefix # For printing status messages to PV msgPv=PV(pvPrefix + ':MSG') msgPv.put('Aborting...') print 'Aborting...' # Import pvScan module sys.path.append('/afs/slac/g/testfac/extras/scripts/pvScan/prod/modules/') import pvscan # Get PID PV pid=pvscan.pidPV.get() #--- Scan PVs ------------------------------------------ # Create ScanPv objects, one for each PV you are scanning. # First argument is the scan PV, leave as empty string to get from pvScan IOC. # Second arg is an index which should be unique. scanPv1=pvscan.ScanPv('',1) scanPv2=pvscan.ScanPv('',2)
def enable_stopcount(self): if not self.connected: print "Device not connected" return False stop = 100 data1 = [] data2 = [] def getData1(pvname, value, **kw): if value != 0: data1.append(value) def getData2(pvname, value, **kw): if value != 0: data2.append(value) analog1 = PV('analogIn1') stop_count = PV('outStopCount') init = PV('initiate') analog2 = PV('analogIn2') poll(evt=1.e-5, iot=0.01) analog1.wait_for_connection() analog2.wait_for_connection() init.wait_for_connection() stop_count.wait_for_connection() analog1.add_callback(getData1) if util.put_check(stop_count, stop): init.put(1) t0 = time.time() while time.time() - t0 < 30: poll(evt=1.e-5, iot=0.01) else: print "Stopcount not set" return False buffered_run = len(data1) analog2.add_callback(getData2) time.sleep(2) if util.put_check(stop_count, -1): init.put(1) t0 = time.time() while time.time() - t0 < 30: poll(evt=1.e-5, iot=0.01) else: print "Stopcount not set 2nd time" return False unbuffered_run = len(data2) return buffered_run, unbuffered_run
# For doing DAQ scans. Logs PV data to a file while doing scan of an arbitrary PV. Uses a supporting IOC (pvScan). # mdunning 1/7/16 from epics import PV from time import sleep import datetime,os,sys,math from threading import Thread # PV prefix for pvScan IOC; should be passed as an argument to this script. pvPrefix=sys.argv[1] # Set an environment variable for so pvscan module can use it os.environ['PVSCAN_PVPREFIX']=pvPrefix # For printing status messages to PV msgPv=PV(pvPrefix + ':MSG') msgPv.put('Initializing...') print 'Initializing...' # Import pvscan module sys.path.append('/afs/slac/g/testfac/extras/scripts/pvScan/prod/modules/') import pvscan #--- Experiment --------------------------------------- # Create Experiment object. Sets default filepath and gets experiment name from PV. # First argument (optional) is an experiment name, leave blank to get from pvScan IOC. # Second arg (optional) is a filepath, leave blank to get from pvScan IOC. # Third arg (optional) is a scan name, leave blank to get from pvScan IOC. exp1=pvscan.Experiment() #--- Scan PVs ------------------------------------------
def stopcount_value(self): if not self.connected: print "Device not connected" return False #util.pv_check('status', 0) #self.stop = 1001 data1 = [] data2 = [] def getData1(pvname, value, **kw): if value != 0: data1.append(value) def getData2(pvname, value, **kw): if value != 0: data2.append(value) analog1 = PV('analogIn1') stop_count = PV('outStopCount') init = PV('initiate') analog2 = PV('analogIn2') poll(evt=1.e-5, iot=0.01) analog1.wait_for_connection() analog2.wait_for_connection() init.wait_for_connection() stop_count.wait_for_connection() util.put_check(stop_count, 100) analog1.add_callback(getData1) init.put(1) poll(evt=1.e-5, iot=0.01) t0 = time.time() while time.time() - t0 < 10: poll(evt=1.e-5, iot=0.01) first_run = len(data1) analog1.remove_callback(0) analog1.add_callback(getData2) time.sleep(2) util.put_check(stop_count, 200) init.put(1) poll(evt=1.e-5, iot=0.01) t0 = time.time() while time.time() - t0 < 10: poll(evt=1.e-5, iot=0.01) second_run = len(data2) return first_run, second_run
def test_db(softioc, caclient): pv_in1 = PV("ET_dummyHost:LI1") pv_in2 = PV("ET_dummyHost:LI2") pv_calc = PV("ET_dummyHost:CALC") pv_in1.wait_for_connection(timeout=30) pv_in2.wait_for_connection(timeout=30) pv_calc.wait_for_connection(timeout=30) pv_in1.put(1, timeout=1) pv_in2.put(2, timeout=1) time.sleep(0.1) pv_calc.get() assert pv_calc.value == 3
class QtEpicsMotorWidget(QtWidgets.QWidget): """ This module provides a class library for a GUI label field widget bound to an Epics PV. The PV is monitored and the field is updated when the PV changes """ changeColor = QtCore.Signal(str) def __init__(self, pvname, parent, input_width, precision = 2, editable=False): """ Inputs: pvname: The name of the epics process variable. parent: The container to place the entry widget. input_width: precision: highlight_on_change: Example: detstat_file = epicsPVLabel("x12c_comm:datafilename",filestat_frame,70) detstat_file.getEntry().pack(side=LEFT,fill=X,expand=YES) """ super(QtEpicsMotorWidget, self).__init__() self.precision = precision self.editable = editable #self.applyOnEnter = applyOnEnter self.entry_var = "" # Creates the PV self.entry_pv = PV(pvname+".RBV", connection_callback=self._conCB) self.base_pv = PV(pvname) if(self.editable): self.entry = QtWidgets.QLineEdit(parent) else: self.entry = QtWidgets.QLabel(parent) if (input_width != 0): self.entry.setFixedWidth(input_width) time.sleep(0.05) try: #because the connection CB handles the timeout for PVs that don't exist self._set_entry_var_with_precision(self.entry_pv.get()) self.entry.setText(self.entry_var) except: self.entry_var = "-----" self.entry.setText(self.entry_var) self.changeColor.emit("white") return self.changeColor.connect(self.setColor) self.entry_pv.add_callback(self._entry_pv_movingCb) self.entry_dmov_pv = PV(pvname+".DMOV") self.entry_dmov_pv.add_callback(self._entry_pv_dmovCb) def _conCB(self,conn,**kwargs): # print "in Con callback %d" % epics_args[1] if (conn): self.changeColor.emit("blue") # self.entry.configure(background="#729fff") else: self.entry_var = "-----" self.entry.setText(self.entry_var) self.changeColor.emit("white") def _entry_pv_movingCb(self,value,**kwargs): # print "in callback " + str(epics_args['pv_value']) + " " + ca.dbf_text(epics_args['type']) self._set_entry_var_with_precision(value) self.entry.setText(self.entry_var) # self.emit(QtCore.SIGNAL("changeColor"),"green") def _entry_pv_dmovCb(self,value,**kwargs): # print "in callback " + str(epics_args['pv_value']) if (value == 1): self.changeColor.emit("None") else: # self.emit(QtCore.SIGNAL("changeColor"),"#99FF66") self.changeColor.emit("yellow") def _set_entry_var_with_precision(self,inval): try: val = float(inval) if (self.precision == 0): self.entry_var = "%.0f" % val elif (self.precision == 1): self.entry_var = "%.1f" % val elif (self.precision == 2): self.entry_var = "%.2f" % val elif (self.precision == 3): self.entry_var ="%.3f" % val elif (self.precision == 4): self.entry_var = "%.4f" % val else: self.entry_var ="%.5f" % val except TypeError: #TODO: check this waveform_to_string function self.entry_var = "Type Error" # waveform_to_string(inval) pass except ValueError: #TODO: check this waveform_to_string function self.entry_var = "Value Error" # waveform_to_string(inval) pass # def pack(self,side=LEFT,padx=0,pady=0): #pass the params in # self.entry.pack(side=side,padx=padx,pady=pady) def getEntry(self): return self.entry def getBasePV(self): return self.base_pv def getField(self): return self.entry_var def setField(self,value): self.entry_var = value def setColor(self,color_s="pink"): self.entry.setStyleSheet("background-color: %s;" % color_s)
def main(argv=None): global dbd global simulate global fp global shut_open global current global T_stop dSi111 = SRXenergy.d111 dbragg = SRXenergy.dBragg #parse command line options usage = "usage: %prog [options]\nData files are written to /data/<year>/<month>/<day>/" parser = OptionParser(usage) parser.add_option("--wait", action="store", type="float", dest="stall", help="wait at each step [seconds]") parser.add_option("--config", action="store", type="string", dest="fname", help="name of config file") parser.add_option("--simulate", action="store_true", dest="sim", default=False, help="simulate motor moves and bursting") parser.add_option("--checkbeam", action="store_true", dest="checkbeam", default=False, help="only acquire when beam is on") parser.add_option("--acqtime", action="store", type="float", dest="acqt", help="image integration time [sec]") parser.add_option("--acqnum", action="store", type="int", dest="acqn", help="images to collect") (options, args) = parser.parse_args() #open log file D0 = time.localtime()[0] D1 = time.localtime()[1] D2 = time.localtime()[2] D3 = time.localtime()[3] D4 = time.localtime()[4] cd = os.getcwd() fstr = '/nfs/xf05id1/data/' if sys.argv[0][0] == '.': out_filename=fstr+repr(D0)+'/'+repr(D1)+'/'+repr(D2)+'/'+'log_'+repr(D0)+'_'+repr(D1)+'_'+repr(D2)+'_'+repr(D3)+'_'+repr(D4)+'_'+\ string.split(string.strip(sys.argv[0],'./'),'/')[0]+'.txt' else: out_filename=fstr+repr(D0)+'/'+repr(D1)+'/'+repr(D2)+'/'+'log_'+repr(D0)+'_'+repr(D1)+'_'+repr(D2)+'_'+repr(D3)+'_'+repr(D4)+'_'+\ string.split(string.strip(sys.argv[0],'./'),'/')[5]+'.txt' try: os.chdir(fstr + repr(D0)) except OSError: try: os.mkdir(fstr + repr(D0)) except Exception: print 'cannot create directory: ' + fstr + repr(D0) sys.exit() try: os.chdir(fstr + repr(D0) + '/' + repr(D1)) except OSError: try: os.mkdir(fstr + repr(D0) + '/' + repr(D1)) except Exception: print 'cannot create directory: ' + fstr + repr(D0) + '/' + repr( D1) sys.exit() try: os.chdir(fstr + repr(D0) + '/' + repr(D1) + '/' + repr(D2)) except OSError: try: os.mkdir(fstr + repr(D0) + '/' + repr(D1) + '/' + repr(D2)) except Exception: print 'cannot create directory: ' + fstr + repr(D0) + '/' + repr( D1) + '/' + repr(D2) sys.exit() try: fp = open(out_filename, 'a') except Exception: print 'cannot open file: ' + out_filename sys.exit() try: os.chdir(fstr + repr(D0) + '/' + repr(D1) + '/' + repr(D2) + '/' + 'HDF5') except OSError: try: os.mkdir(fstr + repr(D0) + '/' + repr(D1) + '/' + repr(D2) + '/' + 'HDF5') except Exception: print 'cannot create directory: ' + fstr + repr(D0) + '/' + repr( D1) + '/' + repr(D2) + '/' + 'HDF5' sys.exit() # H5path=fstr+repr(D0)+'/'+repr(D1)+'/'+repr(D2)+'/HDF5' H5path = '/epics/data/2015-3/300226-2' # H5path='/epics/data/2015-3/in-house' os.chdir(cd) fp.write('#') fp.write(', '.join(sys.argv)) fp.write('\n') #open list of scan points try: fconfig = open(options.fname) except Exception: print "cannot open file containing scan points. Error opening: " + options.fname sys.exit() fstr = '#a default string' pN = 0 angle = list() ivu = list() t2gap = list() while fstr.rsplit().__len__() > 0: if (fstr[0] is not '#'): pN = pN + 1 angle.append(fstr.rsplit()[0]) ivu.append(fstr.rsplit()[1]) t2gap.append(fstr.rsplit()[2]) fstr = fconfig.readline() fconfig.close() #initialize PVs and callbacks detstr = 'XF:05IDA{IM:1}' bmot = PV('XF:05IDA-OP:1{Mono:HDCM-Ax:P}Mtr.VAL', connection_timeout=4) bmot_cur = PV('XF:05IDA-OP:1{Mono:HDCM-Ax:P}Mtr.RBV', connection_timeout=4) bmot_stop = PV('XF:05IDA-OP:1{Mono:HDCM-Ax:P}Mtr.STOP', connection_timeout=4) umot = PV('SR:C5-ID:G1{IVU21:1-Mtr:2}Inp:Pos', connection_timeout=4) umot_cur = PV('SR:C5-ID:G1{IVU21:1-LEnc}Gap', connection_timeout=4) umot_go = PV('SR:C5-ID:G1{IVU21:1-Mtr:2}Sw:Go', connection_timeout=4) gmot = PV('XF:05IDA-OP:1{Mono:HDCM-Ax:X2}Mtr.VAL', connection_timeout=4) gmot_cur = PV('XF:05IDA-OP:1{Mono:HDCM-Ax:X2}Mtr.RBV', connection_timeout=4) gmot_stop = PV('XF:05IDA-OP:1{Mono:HDCM-Ax:X2}Mtr.STOP', connection_timeout=4) shut_status = PV('SR:C05-EPS{PLC:1}Shutter:Sum-Sts', connection_timeout=4) beam_current = PV('SR:C03-BI{DCCT:1}I:Total-I', connection_timeout=4) bragg_temp = PV('XF:05IDA-OP:1{Mono:HDCM-Ax:P}T-I', connection_timeout=4) norm0 = PV('XF:05IDD-BI:1{BPM:01}.S20', connection_timeout=4) norm1 = PV('XF:05IDD-BI:1{BPM:01}.S21', connection_timeout=4) norm2 = PV('XF:05IDD-BI:1{BPM:01}.S22', connection_timeout=4) norm3 = PV('XF:05IDD-BI:1{BPM:01}.S23', connection_timeout=4) wb = srxslit.nsls2slit(tb='XF:05IDA-OP:1{Slt:1-Ax:T}', bb='XF:05IDA-OP:1{Slt:1-Ax:B}', ib='XF:05IDA-OP:1{Slt:1-Ax:I}', ob='XF:05IDA-OP:1{Slt:1-Ax:O}') pb = srxslit.nsls2slit(ib='XF:05IDA-OP:1{Slt:2-Ax:I}', ob='XF:05IDA-OP:1{Slt:2-Ax:O}') ssa = srxslit.nsls2slit(tb='XF:05IDB-OP:1{Slt:SSA-Ax:T}', bb='XF:05IDB-OP:1{Slt:SSA-Ax:B}', ob='XF:05IDB-OP:1{Slt:SSA-Ax:O}', ib='XF:05IDB-OP:1{Slt:SSA-Ax:I}') x3acq = PV('XSPRESS3-EXAMPLE:Acquire', connection_timeout=4) x3erase = PV('XSPRESS3-EXAMPLE:ERASE', connection_timeout=4) x3acqtime = PV('XSPRESS3-EXAMPLE:AcquireTime', connection_timeout=4) x3acqnum = PV('XSPRESS3-EXAMPLE:NumImages', connection_timeout=4) x3tmode = PV('XSPRESS3-EXAMPLE:TriggerMode', connection_timeout=4) x3h5path = PV('XSPRESS3-EXAMPLE:HDF5:FilePath', connection_timeout=4) x3h5fname = PV('XSPRESS3-EXAMPLE:HDF5:FileName', connection_timeout=4) x3h5fnum = PV('XSPRESS3-EXAMPLE:HDF5:FileNumber', connection_timeout=4) x3h5vdim = PV('XSPRESS3-EXAMPLE:HDF5:NumExtraDims', connection_timeout=4) x3h5size = PV('XSPRESS3-EXAMPLE:HDF5:ExtraDimSizeN', connection_timeout=4) x3h5d1 = PV('XSPRESS3-EXAMPLE:HDF5:ExtraDimSizeX', connection_timeout=4) x3h5d2 = PV('XSPRESS3-EXAMPLE:HDF5:ExtraDimSizeY', connection_timeout=4) x3h5writerbv = PV('XSPRESS3-EXAMPLE:HDF5:WriteFile_RBV', connection_timeout=2) #report ROIs for channels and counts at each point x3ch1roi0min = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI1_LLM', connection_timeout=4) x3ch1roi0max = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI1_HLM', connection_timeout=4) x3ch1roi0ct = PV('XSPRESS3-EXAMPLE:C1_ROI1:Value_RBV', connection_timeout=4) x3ch1roi1min = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI2_LLM', connection_timeout=4) x3ch1roi1max = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI2_HLM', connection_timeout=4) x3ch1roi1ct = PV('XSPRESS3-EXAMPLE:C1_ROI2:Value_RBV', connection_timeout=4) x3ch1roi2min = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI3_LLM', connection_timeout=4) x3ch1roi2max = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI3_HLM', connection_timeout=4) x3ch1roi2ct = PV('XSPRESS3-EXAMPLE:C1_ROI3:Value_RBV', connection_timeout=4) x3ch2roi0min = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI1_LLM', connection_timeout=4) x3ch2roi0max = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI1_HLM', connection_timeout=4) x3ch2roi0ct = PV('XSPRESS3-EXAMPLE:C2_ROI1:Value_RBV', connection_timeout=4) x3ch2roi1min = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI2_LLM', connection_timeout=4) x3ch2roi1max = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI2_HLM', connection_timeout=4) x3ch2roi1ct = PV('XSPRESS3-EXAMPLE:C2_ROI2:Value_RBV', connection_timeout=4) x3ch2roi2min = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI3_LLM', connection_timeout=4) x3ch2roi2max = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI3_HLM', connection_timeout=4) x3ch2roi2ct = PV('XSPRESS3-EXAMPLE:C2_ROI3:Value_RBV', connection_timeout=4) x3ch3roi0min = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI1_LLM', connection_timeout=4) x3ch3roi0max = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI1_HLM', connection_timeout=4) x3ch3roi0ct = PV('XSPRESS3-EXAMPLE:C3_ROI1:Value_RBV', connection_timeout=4) x3ch3roi1min = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI2_LLM', connection_timeout=4) x3ch3roi1max = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI2_HLM', connection_timeout=4) x3ch3roi1ct = PV('XSPRESS3-EXAMPLE:C3_ROI2:Value_RBV', connection_timeout=4) x3ch3roi2min = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI3_LLM', connection_timeout=4) x3ch3roi2max = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI3_HLM', connection_timeout=4) x3ch3roi2ct = PV('XSPRESS3-EXAMPLE:C3_ROI3:Value_RBV', connection_timeout=4) #claim ROI 4 for our own use. we will integrate over all 4096 channels. x3ch1roi3min = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI4_LLM', connection_timeout=4) x3ch1roi3max = PV('XSPRESS3-EXAMPLE:C1_MCA_ROI4_HLM', connection_timeout=4) x3ch1roi3ct = PV('XSPRESS3-EXAMPLE:C1_ROI4:Value_RBV', connection_timeout=4) x3ch2roi3min = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI4_LLM', connection_timeout=4) x3ch2roi3max = PV('XSPRESS3-EXAMPLE:C2_MCA_ROI4_HLM', connection_timeout=4) x3ch2roi3ct = PV('XSPRESS3-EXAMPLE:C2_ROI4:Value_RBV', connection_timeout=4) x3ch3roi3min = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI4_LLM', connection_timeout=4) x3ch3roi3max = PV('XSPRESS3-EXAMPLE:C3_MCA_ROI4_HLM', connection_timeout=4) x3ch3roi3ct = PV('XSPRESS3-EXAMPLE:C3_ROI4:Value_RBV', connection_timeout=4) dett = PV('XF:05IDD-ES:1{EVR:1-Out:FP3}Src:Scale-SP', connection_timeout=4) deti = PV('XF:05IDA{IM:1}Per-SP', connection_timeout=4) detinit = PV('XF:05IDA{IM:1}Cmd:Init', connection_timeout=4) det0 = PV(detstr + 'Cur:I0-I', connection_timeout=4) det1 = PV(detstr + 'Cur:I1-I', connection_timeout=4) det2 = PV(detstr + 'Cur:I2-I', connection_timeout=4) det3 = PV(detstr + 'Cur:I3-I', connection_timeout=4) bmot.info bmot_cur.info bmot_stop.info umot.info umot_cur.info umot_go.info gmot.info gmot_cur.info gmot_stop.info det0.info det1.info det2.info det3.info bragg_temp.info bmot_cur.add_callback(cbfx) bmot_cur.run_callbacks() umot_cur.add_callback(cbfy) umot_cur.run_callbacks() gmot_cur.add_callback(cbfz) gmot_cur.run_callbacks() shut_status.add_callback(cbf_shut) beam_current.add_callback(cbf_curr) shut_status.run_callbacks() beam_current.run_callbacks() bragg_temp.add_callback(cbf_temp) bragg_temp.run_callbacks() x3h5path.put(H5path) x3h5fname.put( repr(D0) + '_' + repr(D1) + '_' + repr(D2) + '_' + repr(D3) + '_' + repr(D4) + '_') x3h5fnum.put(0) x3acqtime.put(options.acqt) x3acqnum.put(options.acqn) x3tmode.put(1) x3ch1roi3min.put(0) x3ch2roi3min.put(0) x3ch3roi3min.put(0) x3ch1roi3max.put(4096) x3ch2roi3max.put(4096) x3ch3roi3max.put(4096) #h5 set up x3h5vdim.put(1) x3h5size.put(options.acqn) x3h5d1.put(pN) x3h5d2.put(0) roits = x3ch3roi3ct.timestamp dett.put(3) #overhead on triggering F460 deti.put(float(options.acqn) * options.acqt * .9) detinit.put(1) #check command line options if options.stall == None: twait = 0. else: twait = options.stall str = '#NSLS-II SRX' + time.asctime() fp.write(str) fp.write('\n') str = '# Start time is ' + time.asctime() print str fp.write(str) fp.write('\n') if options.sim is True: str = " -----simulating motor moves and bursts-----" print str fp.write(str) fp.write('\n') else: x3h5capture.put(1) dett.put(4) while x3h5capture.get() == 0: time.sleep(0.5) time.sleep(2) while x3h5writerbv.get() == 0: x3h5capture.put(0) print "File write is not confirmed. Waiting for confirmation..." time.sleep(30) x3h5capture.put(1) time.sleep(2) dett.put(3) str='# bragg: %(br)6.4f ; undulator: %(un)6.4f ; gap: %(cg)f ; ROI1 %(roi1i)d:%(roi1a)d ; ROI2 %(roi2i)d:%(roi2a)d ; ROI3 %(roi3i)d:%(roi3a)d'%\ {"br":bmot_cur.get(),"un":umot_cur.get(), "cg":gmot_cur.get(),'roi1i':x3ch1roi0min.get(), 'roi1a':x3ch1roi0max.get(), 'roi2i':x3ch1roi1min.get(), 'roi2a':x3ch1roi1max.get(), 'roi3i':x3ch1roi2min.get(), 'roi3a':x3ch1roi2max.get()} print str fp.write(str) fp.write('\n') str = "# --------------------" print str fp.write(str) fp.write('\n') str = "# bragg u-gap c-gap energy I0-1 I0-2 I0-3 I0-4 time ROI-1 ROI-2 ROI-3 ROI-4 intensity" print str fp.write(str) fp.write('\n') LN = 0 oldsig = det0.get() t0 = time.time() sig0 = 0. sig1 = 0. sig2 = 0. sig3 = 0. nsig0 = 0. nsig1 = 0. nsig2 = 0. nsig3 = 0. for x in range(0, pN): tar[0][1] = 1 tar[0][0] = float(angle[x]) tar[1][1] = 1 tar[1][0] = float(ivu[x]) tar[2][1] = 1 tar[2][0] = float(t2gap[x]) #if tar[0][0] is the original position, raise "in position" flag if indeadband(float(tar[0][0]), float(bmot_cur.get()), dbd) == 1: tar[0][1] = 0 if indeadband(float(tar[1][0]), float(umot_cur.get()), dbd) == 1: tar[1][1] = 0 if indeadband(float(tar[2][0]), float(gmot_cur.get()), dbd) == 1: tar[2][1] = 0 if options.sim is False: bmot.put(tar[0][0]) umot.put(tar[1][0]) gmot.put(tar[2][0]) time.sleep(1) umot_go.put(0) else: tar[0][1] = 0 tar[1][1] = 0 tar[2][1] = 0 while (tar[0][1] == 1) or (tar[1][1] == 1) or (tar[2][1] == 1): time.sleep(0.05) if LN > 400: umot_go.put(0) LN = 0 else: LN = LN + 1 if options.sim is False: time.sleep(twait) while (options.checkbeam and (shut_open == False or beam_current == False)) or T_stop == True: print "Stopped. Waiting for scan conditions to return to normal." if shut_open == False: print "\t->shutter is closed" elif beam_current == False: print "\t->Ring current is below threshold" elif T_stop == True: print "\t->HDCM pitch motor is too hot" else: print "\t->why not have a nice cup of tea or hit ctrl-C?" time.sleep(60.) x3erase.put(1) dett.put(4) nsig0 = norm0.get() nsig1 = norm1.get() nsig2 = norm2.get() nsig3 = norm3.get() #?? # sig0=sig1=sig2=sig3=3 sig0 = sig1 = sig2 = sig3 = 0 for i in range(0, options.acqn): x3acq.put(1) while (x3ch3roi3ct.get() == 0.0 or x3ch3roi3ct.timestamp == roits): time.sleep(0.02) sig0 = sig0 + x3ch1roi0ct.get() + x3ch2roi0ct.get( ) + x3ch3roi0ct.get() sig1 = sig1 + x3ch1roi1ct.get() + x3ch2roi1ct.get( ) + x3ch3roi1ct.get() sig2 = sig2 + x3ch1roi2ct.get() + x3ch2roi2ct.get( ) + x3ch3roi2ct.get() sig3 = sig3 + x3ch1roi3ct.get() + x3ch2roi3ct.get( ) + x3ch3roi3ct.get() # sig0=sig0+x3ch2roi0ct.get()+x3ch3roi0ct.get() # sig1=sig1+x3ch2roi1ct.get()+x3ch3roi1ct.get() # sig2=sig2+x3ch2roi2ct.get()+x3ch3roi2ct.get() # sig3=sig3+x3ch2roi3ct.get()+x3ch3roi3ct.get() roits = x3ch3roi3ct.timestamp signal0 = float(det1.get()) while (signal0 == 0.0): signal0 = float(det1.get()) # while(signal0 == oldsig): # signal0=det0.get() # oldsig=signal0 dett.put(3) else: while (options.checkbeam and (shut_open == False or beam_current == False)): print "Stopped. Waiting for beam to return." time.sleep(60.) signal0 = 0. nsig1 = 0 nsig2 = 0 nsig3 = 0 tn = time.time() - t0 if options.sim is False: # str=' %(B)8.4f %(U)8.4f %(G)8.3f %(E)8.2f %(C0)10.7e %(C1)10.7e %(C2)10.7e %(C3)10.7e %(T)d %(ROI1)d %(ROI2)d %(ROI3)d %(ROI4)d %(T1)10.7e'%{"B":float(bmot_cur.get()), "U":float(umot_cur.get()), "G":float(gmot_cur.get()), "C0":nsig0, "C1":nsig1, "C2":nsig2, "C3":nsig3, "ROI1":sig0,'T':tn,"ROI2":sig1,"ROI3":sig2,"ROI4":sig3,"T1":signal0,"E":12398.4 / (2 * 3.13029665951 * math.sin((bmot_cur.get()+0.323658778534)/180.*np.pi))} str = ' %(B)8.4f %(U)8.4f %(G)8.3f %(E)8.2f %(C0)10.7e %(C1)10.7e %(C2)10.7e %(C3)10.7e %(T)d %(ROI1)d %(ROI2)d %(ROI3)d %(ROI4)d %(T1)10.7e' % { "B": float(bmot_cur.get()), "U": float(umot_cur.get()), "G": float(gmot_cur.get()), "C0": nsig0, "C1": nsig1, "C2": nsig2, "C3": nsig3, "ROI1": sig0, 'T': tn, "ROI2": sig1, "ROI3": sig2, "ROI4": sig3, "T1": signal0, "E": 12398.4 / (2 * dSi111 * math.sin( (bmot_cur.get() + dbragg) / 180. * np.pi)) } print str fp.write(str) fp.write('\n') else: str = ' B= %(B)8.4f U= %(U)8.4f G= %(G)8.3f : %(C0)10.7e %(C1)10.7e %(C2)10.7e %(C3)10.7e %(ROI)d %(T)d' % { "B": tar[0][0], "U": tar[1][0], "G": tar[2][0], "C0": signal0, "C1": nsig1, "C2": nsig2, "C3": nsig3, "ROI": x3ch1roi0ct.get(), 'T': time.time() } print str fp.write(str) fp.write('\n') str = '#End time is ' + time.asctime() print str fp.write(str) fp.write('\n') fp.close() bmot_cur.clear_callbacks() umot_cur.clear_callbacks() gmot_cur.clear_callbacks() shut_status.clear_callbacks() beam_current.clear_callbacks() bragg_temp.clear_callbacks() return 0
import subprocess import argparse parser = argparse.ArgumentParser(description='Accumulate run information.') #parser.add_argument('-k', '--kine', # default = 'DBASE/COIN/auto_standard.kinematics', # help = 'output put for automatic standard.kinematics', # dest='kinematics') parser.add_argument('-i','--input', default = 'db2/run_list.json', help='input json run database', dest='input_file') args = parser.parse_args() kine_setting_num_pv = PV('hcKinematicSettingNumber') kine_setting_group_pv = PV('hcKinematicSettingGroup') kine_setting_id_pv = PV('hcKinematicSettingID') run_in_progress_pv = PV('hcCOINRunInProgress') def update_epics_kinematics(pvname=None, value=None, host=None, **kws): p = subprocess.Popen(['bash','/group/c-csv/cdaq/csv_run_plan/bin/get_current_setting.sh'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() #print out values = out.split() epics.caput('hcKinematicSettingGroup', int(values[0])) epics.caput('hcKinematicSettingNumber',int(values[1])) epics.caput('hcKinematicSettingID', int(values[2])) print values[0] print values[1] print values[2]
# Necessary modules from epics import PV import Adafruit_BBIO.GPIO as GPIO import sys import time # Configuration of the BeagleBone Black pin used to open or close the relay contact GPIO.setup("P9_14", GPIO.OUT) GPIO.output("P9_14", GPIO.HIGH) # These are the EPICS PVs that should be observed by this program PV1 = PV("RAD:Berthold:Int") PV2 = PV("RAD:ELSE:DoseIntegral") PV3 = PV("RAD:THERMO:DoseIntegral") # The radiation dose limit (in uSv) is an argument of the program dose_limit = float(sys.argv[1]) # Loop while (True): try: # If any of the three radiation measurements exceeded the limit, the program opens the # relay contact. If this is not the case, the relay contact is kept closed.
def __init__(self, mnemonic, pv=None, responseTimeout=15, output="./out", numPoints=1044, mcas=False): """Constructor responseTimeout : how much time to wait qe65000 answer numPoints : how many points are collected each time """ super().__init__(mnemonic, numPoints, output, 'ocean') self.acquireChanged = Event() self.acquiring = False try: # determines the start of counting self.pvStart = PV(pv + ":Acquire") # determines mode of Acquisition (Single,Continous, Dark Spectrum) self.pvAcquireMode = PV(pv + ":AcquisitionMode") # use darkcorrection self.pvDarkCorrection = PV(pv + ":ElectricalDark") # spectrum self.pvSpectrum = PV(pv + ":Spectra") self.pvSpectrumCorrected = PV(pv + ":DarkCorrectedSpectra") # set Acquire Time self.pvAcquireTime = PV(pv + ":SetIntegration") # integration Time self.pvTime = PV(pv + ":IntegrationTime:Value") # control the end of acquire process self.pvAcquire = PV(pv + ":Acquiring") self.pvAcquire.add_callback(self.statusChange) # acquisition mode self.pvAcMode = PV(pv + ":AcquisitionMode") # set to single mode self.pvAcMode.put("Single") # axis Spectra pvAxis = PV(pv + ":SpectraAxis") self.axis = pvAxis.get(as_numpy=True)[:self.numPoints] # regions of interest self.ROIS = [] self.mcas = mcas self.responseTimeout = responseTimeout self.timer = Timer(self.responseTimeout) except TypeError: raise RuntimeError('PV not found') except ValueError: raise RuntimeError('Device is offline')
class PylonCCDTriggered(PylonCCD): """ Python class to help configuration and control of Charge-Coupled Devices (CCD) via Hyppie over EPICS and external trigger mechanism. CCD is the most common mechanism for converting optical images to electrical signals. In fact, the term CCD is know by many people because of their use of video cameras and digital still cameras. """ # PyLoN CCD callback function for acquire status def onAcquireChange(self, value, **kw): # If 'Output Signal' of Trigger in LF is 'Waiting For Trigger', # then value when done (waiting) is 1 (one); # Otherwise, if output signal is 'Reading Out', then value when # done (read) is 0 (zero). self._done = (value == 0) # PyLoN CCD constructor # readoutMode = 0 (FullFrame) # readoutMode = 1 (Kinetics) def __init__(self, pvName, pvNameIN, pvNameOUT, mnemonic, accumulations=1, readoutMode=0): # IN DXAS:DIO:bi8 # 1.0 (read TTL OUT from CCD) # OUT DXAS:DIO:bo17 # 6.1 (write Trigger IN to CCD start acquisition) self.pvTriggerAcquire = PV(pvNameOUT) self.pvMonitor = PV(pvNameIN, callback=self.onAcquireChange) # Number of accumulations per frame self.accumulations = accumulations # Then call parent initializer # Operation Mode of readout control self.readoutMode = readoutMode PylonCCD.__init__(self, pvName, mnemonic) # Configurable timeout to control triggers self.triggerTimeout = None def isDone(self): # If 'Output Signal' of Trigger in LF is 'Waiting For Trigger', # then value when done (waiting) is 1 (one); # Otherwise, if output signal is 'Reading Out', then value when # done (read) is 0 (zero). return (self.pvMonitor.get() == 0) def acquire(self, waitComplete=False): # Necessary wait if a pause command was sent to the system # This is being used by furnace experiments (temperature scan) while (self.isPaused()): sleep(0.2) #print(self.readoutMode) if (self.readoutMode == 0): # FullFrame repeatTimes = self.accumulations elif (self.readoutMode == 1): # Kinetics repeatTimes = 1 for currentAccumulation in range(repeatTimes): # Set the attribute of done acquisition to False self._done = False #################################################################### # The digital output port which trigger the CCD should be pulsed. # Minor pulse width in tests were 10 ms. #################################################################### self.pvTriggerAcquire.put(1) sleep(0.01) # Just to guarantee a 10ms trigger... self.pvTriggerAcquire.put(0) if ((waitComplete)): self.wait() def startLightFieldAcquisition(self): self.pvAcquire.put(1) def waitFinishAcquiring(self): accumulation_wait = 0 while (not self._done and accumulation_wait < self.getTriggerTimeout()): accumulation_wait += WAIT_ACQUIRING sleep(WAIT_ACQUIRING) def wait(self): """ Wait for a complete PyLoN CCD acquiring process to finish. Returns ------- out : `bool` """ self.waitFinishAcquiring() def startCount(self): """ Trigger the acquisition process of PyLoN CCD. """ self.acquire(True) def isCounting(self): """ Abstract method to check if the device is counting or not. Returns ------- out : `bool` """ return (not self.isDone()) def setTriggerTimeout(self, timeout): self.triggerTimeout = timeout def getTriggerTimeout(self): if (self.triggerTimeout is None): return TIMEOUT_SECONDS else: return self.triggerTimeout