def __init__(self): """Initialise GUI.""" QMainWindow.__init__(self) filename = os.path.join(os.path.dirname(__file__), self.UI_FILENAME) self.ui = uic.loadUi(filename) self.parent = QtGui.QMainWindow() self.pv_monitor = controls.PvMonitors.get_instance() self.knobs = magnet_jogs.MagnetCoordinator() self.pv_writer = writers.PvWriter() # Initial setting for GUI: jog scaling = 1. self.jog_scale = 1.0 self.gauss_scale = 1.0 # Initialise adjustment of Gaussian amplitude and standard deviation. self.amp_step = 0 self.sig_step = 0 self.graph = plots.OverlaidWaveforms(controls) self.toolbar = NavigationToolbar(self.graph, self) # Connect buttons to PVs. self.ui.bumpleftplusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BUMP_LEFT, 1)) self.ui.bumpleftminusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BUMP_LEFT, -1)) self.ui.bumprightplusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BUMP_RIGHT, 1)) self.ui.bumprightminusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BUMP_RIGHT, -1)) self.ui.ampplusButton.clicked.connect(self.amp_plus) self.ui.ampminusButton.clicked.connect(self.amp_minus) self.ui.sigmaplusButton.clicked.connect(self.sig_plus) self.ui.sigmaminusButton.clicked.connect(self.sig_minus) self.ui.ampplusButton.setEnabled(False) self.ui.ampminusButton.setEnabled(False) self.ui.sigmaplusButton.setEnabled(False) self.ui.sigmaminusButton.setEnabled(False) self.ui.autoscaleButton.clicked.connect(self.autoscale) self.ui.checkBox.clicked.connect(self.gauss_fit) self.ui.jog_scale_slider.valueChanged.connect(self.set_jog_scaling) self.ui.jog_scale_textbox.setText(str(self.jog_scale)) self.ui.gauss_scale_slider.valueChanged.connect(self.set_gauss_scaling) self.ui.gauss_scale_textbox.setText(str(self.gauss_scale)) # Monitor the states of magnets and cycling. camonitor(controls.PvReferences.MAGNET_STATUS_PV, self.update_magnet_led, format=FORMAT_CTRL) camonitor(controls.PvReferences.CYCLING_STATUS_PV, self.update_cycling_textbox, format=FORMAT_CTRL) # Add graphs to the GUI. self.ui.graph_layout.addWidget(self.graph) self.ui.graph_layout.addWidget(self.toolbar)
def pressed(state): import cothread from cothread import catools cothread.iqt(run_exec=False) global label label = QtGui.QLabel('Hello there', None) label.show() catools.camonitor('SR21C-DI-DCCT-01:SIGNAL', signal)
def pressed(state): import cothread from cothread import catools cothread.iqt(run_exec = False) global label label = QtGui.QLabel('Hello there', None) label.show() catools.camonitor('SR21C-DI-DCCT-01:SIGNAL', signal)
def __init__(self, parent=None): QObject.__init__(self, parent) self.extractMask = 0 # 0 - no mask, 1 - mask self.extractStatus = 0 self.extractRequest = 0 # 0 - idle, 1 - requested self.eventCount = 0 # incrementing when cycle end. self.startSrc = 0 # source of starting signals self.pvs_connect = [ "V5:SYN:XFER:SwitchC", "V5:SYN:XFER:MaskC.B0", "V5:SYN:XFER:StartC.PROC", "V5:SYN:XFER:StopC.PROC" ] catools.connect(self.pvs_connect) catools.camonitor("V5:SYN:XFER:EventM", self.eventUpdate, datatype=int) catools.camonitor("V5:SYN:XFER:StatusRbv", self.statusUpdate, datatype=int) catools.camonitor("V5:SYN:XFER:MaskC.RBV", self.maskUpdate, datatype=int) catools.camonitor("V5:SYN:XFER:SwitchC", self.startSrcUpdate, datatype=int)
def reconnect(self): # release old monitor self.disconnect() # make the connection in cothread's thread, use caget for initial value pvs = [self.rbv] if self.pv and self.pv != self.rbv: pvs.append(self.pv) ca_values = assert_connected( catools.caget( pvs, format=catools.FORMAT_CTRL, datatype=self.datatype, throw=self.throw, ), self.throw, ) if self.on_connect: self.on_connect(ca_values[0]) self._update_value(ca_values[0]) # now setup monitor on rbv self.monitor = catools.camonitor( self.rbv, self._monitor_callback, format=catools.FORMAT_TIME, datatype=self.datatype, notify_disconnect=True, )
def test_monitor(self): self.assertIOCRunning() longout = self.testprefix + 'longout' values = [] def callback(value): values.append(value) m = catools.camonitor(longout, callback, notify_disconnect=True) # Wait for connection while not values: cothread.Sleep(0.1) catools.caput(longout, 43, wait=True) catools.caput(longout, 44, wait=True) self.iocStop() # Can't call iocStop twice... def iocStop(): return self.iocStop = iocStop m.close() self.assertEqual(len(values), 4) self.assertEqual(values[:3], [42, 43, 44]) self.assertEqual([v.ok for v in values], [True, True, True, False])
def start_subscription(self): """ """ self.camonitor_subscription = camonitor(self.current_pv_name, self.camonitor_callback, format=FORMAT_TIME, all_updates=False)
def setup_tune_feedback(self, tune_csv=None): """Read the tune feedback .csv and find the associated offset PVs, before starting monitoring them for a change to mimic the behaviour of the quadrupoles used by the tune feedback system on the live machine. Args: tune_csv (str): A path to a tune feedback .csv file to be used instead of the default filepath passed at startup. """ if tune_csv is not None: self._tune_fb_csv_path = tune_csv if self._tune_fb_csv_path is None: raise ValueError("No tune feedback .csv file was given at " "start-up, please provide one now; i.e. " "server.start_tune_feedback('<path_to_csv>')") csv_reader = csv.DictReader(open(self._tune_fb_csv_path)) if not self._pv_monitoring: self.monitor_mirrored_pvs() self.tune_feedback_status = True for line in csv_reader: offset_record = self.all_record_names[line["offset"]] self._offset_pvs[line["set pv"]] = offset_record mask = callback_offset(self, line["set pv"], offset_record) try: self._monitored_pvs[line["delta"]] = camonitor( line["delta"], mask.callback) except Exception as e: warn(e)
def addPv(self, pvs): """add a pv or list of pvs""" if not pvs: return kw_cg = {"format": cothread.catools.FORMAT_CTRL, "timeout": self.timeout, "throw": False} kw_cm = {"format": cothread.catools.FORMAT_TIME } if isinstance(pvs, (list, tuple, set)): newpvs = [ pv for pv in pvs if pv not in self.data ] elif isinstance(pvs, str) and pvs not in self.data: newpvs = [ pvs ] else: newpvs = [] if len(newpvs) == 0: return d = caget(newpvs, **kw_cg) newmons = camonitor(newpvs, self._ca_update, **kw_cm) for i,pv in enumerate(newpvs): if not d[i].ok: self._dead.add(newpvs[i]) else: self._monitors[pv] = newmons[i] self.data[pv] = deque([d[i]], self.samples) try: self._wfsize[pv] = len(d[i]) except: self._wfsize[pv] = None for fhk in self.hook.get(pv, []): fhk(d[i], None) d1 = caget(self.data.keys(), timeout = self.timeout, **kw_cm) for i,v in enumerate(d1): self.data[v.name].append(v)
def reconnect(self): # release old monitor self.disconnect() # make the connection in cothread's thread, use caget for initial ca_values = assert_connected( catools.caget( self.pv_list, format=catools.FORMAT_CTRL, datatype=self.datatype, throw=self.throw, ), self.throw, ) for ind, value in enumerate(ca_values): if self.on_connect: self.on_connect(value) self._local_value[self.name_list[ind]] = value self._local_value.severity = max(self._local_value.severity, value.severity) self._local_value.ok = self._local_value.ok or value.ok self._update_value(self._local_value) # now setup monitors for all the things self.monitor = catools.camonitor( self.pv_list, self._monitor_callback, format=catools.FORMAT_TIME, datatype=self.datatype, notify_disconnect=True, )
def __init__(self, pv, count): self.count = count self.accum = [] self.done = cothread.Event() self.monitor = camonitor(pv, self.add_value, format=FORMAT_TIME, all_updates=True)
def addEpicsCallback(self,pv,callback): """Add PV callbacks and store the subscriptions""" s = catools.camonitor(pv,callback, format=catools.FORMAT_CTRL, notify_disconnect=True) logging.info("addEpicsCallback() : Callback added for PV %s", pv) if type(s) == list: self.epicsSubscriptions += s else: self.epicsSubscriptions.append(s)
def addEpicsCallback(self, pv, callback): """Add PV callbacks and store the subscriptions""" s = catools.camonitor(pv, callback, format=catools.FORMAT_CTRL, notify_disconnect=True) logging.info("addEpicsCallback() : Callback added for PV %s", pv) if type(s) == list: self.epicsSubscriptions += s else: self.epicsSubscriptions.append(s)
def monitor_mirrored_pvs(self): """Start monitoring the input PVs for mirrored records, so that they can update their value on change. """ self._pv_monitoring = True for pv, output in self._mirrored_records.items(): mask = callback_set(output) try: self._monitored_pvs[pv] = camonitor(pv, mask.callback) except Exception as e: warn(e)
def test_reset(self): p = self.create_part() catools.caget.return_value = [caint(4), caint(5)] p.connect_pvs() catools.caget.assert_called_with( ["pv2", "pv"], format=catools.FORMAT_CTRL, datatype=p.get_datatype()) catools.camonitor.assert_called_once_with( "pv2", p.on_update, format=catools.FORMAT_CTRL, datatype=p.get_datatype(), notify_disconnect=True) self.assertEqual(p.attr.value, 4) self.assertEqual(p.monitor, catools.camonitor())
def test_cothread_ioc(cothread_ioc): import cothread from cothread.catools import ca_nothing, caget, caput, camonitor pre = cothread_ioc.pv_prefix with Listener(ADDRESS) as listener, listener.accept() as conn: select_and_recv(conn, "R") # "Ready" # Start assert caget(pre + ":UPTIME").startswith("00:00:0") # WAVEFORM caput(pre + ":SINN", 4, wait=True) q = cothread.EventQueue() m = camonitor(pre + ":SIN", q.Signal, notify_disconnect=True) assert len(q.Wait(1)) == 4 # STRINGOUT assert caget(pre + ":STRINGOUT") == "watevah" caput(pre + ":STRINGOUT", "something", wait=True) assert caget(pre + ":STRINGOUT") == "something" # Check pvaccess works from p4p.client.cothread import Context with Context("pva") as ctx: assert ctx.get(pre + ":STRINGOUT") == "something" conn.send("D") # "Done" select_and_recv(conn, "D") # "Done" # Stop cothread_ioc.proc.send_signal(signal.SIGINT) # Disconnect assert isinstance(q.Wait(10), ca_nothing) m.close() # check closed and output out, err = cothread_ioc.proc.communicate() out = out.decode() err = err.decode() # check closed and output try: assert "%s:SINN.VAL 1024 -> 4" % pre in out assert 'update_sin_wf 4' in out assert "%s:STRINGOUT.VAL watevah -> something" % pre in out assert 'on_update \'something\'' in out assert 'Starting iocInit' in err assert 'iocRun: All initialization complete' in err except Exception: # Useful printing for when things go wrong! print("Out:", out) print("Err:", err) raise
def start_camonitors(self): catools.camonitor(self.XBPMSharedPVs.fb_enable_status.name, self.enable_status) catools.camonitor(self.XBPMSharedPVs.status_monitor, self.feedback_inputs) catools.camonitor(self.XBPMSharedPVs.xbpm_fb_checklist, self.feedback_inputs)
def _updateMonitors(self): """ prepare the PV list for camonitor """ #print "Updating monitors" pvs = [] self.pvs_rb_val = [] for i in range(self.table.rowCount()): for j in range(len(self.pvs_rb[i])): self.pvs_rb_val.append([i, 0.0]) pvs.extend(self.pvs_rb[i]) for p in self.pvmoni: p.close() self.pvmoni = camonitor(pvs, self._updatePvValues)
def test_reset(self): p = self.create_part() catools.caget.return_value = [caint(4), caint(5)] p.connect_pvs() catools.caget.assert_called_with(["pv2", "pv"], format=catools.FORMAT_CTRL, datatype=p.get_datatype()) catools.camonitor.assert_called_once_with("pv2", p.on_update, format=catools.FORMAT_CTRL, datatype=p.get_datatype(), notify_disconnect=True) self.assertEqual(p.attr.value, 4) self.assertEqual(p.monitor, catools.camonitor())
def start_observation(): print("start_observation") pvs_to_watch = [] init_data = {} for pv in PVS: pv_val = ca.caget(pv) pv_name = "".join(chr(_) for _ in pv_val).strip() if len(pv_name) > 0: print("pv_name: {}".format(pv_name)) dm_map[pv_name] = pv pvs_to_watch.append(pv_name) init_data[pv] = ca.caget(pv_name) dm.append_data(datetime.utcnow(), init_data) for pv_name in pvs_to_watch: subscription_obj.append(ca.camonitor(str(pv_name), process, format=ca.FORMAT_TIME))
def connect_pvs(self): # release old monitor self.close_monitor() # make the connection in cothread's thread, use caget for initial value pvs = [self.rbv] if self.pv: pvs.append(self.pv) ca_values = cothread.CallbackResult( catools.caget, pvs, format=self.ca_format, datatype=self.get_datatype()) # check connection is ok for i, v in enumerate(ca_values): assert v.ok, "CA connect failed with %s" % v.state_strings[v.state] self.update_value(ca_values[0]) # now setup monitor on rbv self.monitor = catools.camonitor( self.rbv, self.on_update, notify_disconnect=True, format=self.ca_format, datatype=self.get_datatype())
def __init__(self, argv, parent=None): gui.QMainWindow.__init__(self, parent) self.ui = Ui_EvgSoftSeq() self.ui.setupUi(self) self.srcText = None labels = ["Event Code", "Timestamp"] self.ui.tableWidget.setHorizontalHeaderLabels(labels) if len(argv) == 4: self.prefix = '%s{%s-%s}' % tuple(argv[1:]) elif len(argv) == 2: self.prefix = argv[1] else: print "Invalid number of arguments" exit(0) self.ui.label_Heading.setText(self.prefix) self.connect(self.ui.pb_setSequence, SIGNAL("clicked()"), self.setSequence) self.updated = False self.enableAll.connect(self.ui.tableWidget.setEnabled) self.enableAll.connect(self.ui.pb_setSequence.setEnabled) self.enableAll.emit(False) self.codes, self.times = [], [] pv = self.prefix + "TsResolution-RB" camonitor(pv, self.sequenceRB, notify_disconnect=True) pv = self.prefix + "TsInpMode-RB" camonitor(pv, self.sequenceRB, notify_disconnect=True) pv = self.prefix + "EvtCode-RB" camonitor(pv, self.newCodes, notify_disconnect=True) pv = self.prefix + "Timestamp-RB" camonitor(pv, self.newTimes, notify_disconnect=True)
def __init__(self, argv, parent=None): gui.QMainWindow.__init__(self, parent) self.ui = Ui_EvgSoftSeq() self.ui.setupUi(self) self.srcText=None labels = ["Event Code", "Timestamp"] self.ui.tableWidget.setHorizontalHeaderLabels(labels) if len(argv)==4: self.prefix='%s{%s-%s}' % tuple(argv[1:]) elif len(argv)==2: self.prefix=argv[1] else: print "Invalid number of arguments" exit(0) self.ui.label_Heading.setText(self.prefix) self.connect(self.ui.pb_setSequence, SIGNAL("clicked()"), self.setSequence) self.updated = False self.enableAll.connect(self.ui.tableWidget.setEnabled) self.enableAll.connect(self.ui.pb_setSequence.setEnabled) self.enableAll.emit(False) self.codes, self.times = [], [] pv = self.prefix + "TsResolution-RB" camonitor(pv, self.sequenceRB, notify_disconnect=True) pv = self.prefix + "TsInpMode-RB" camonitor(pv, self.sequenceRB, notify_disconnect=True) pv = self.prefix + "EvtCode-RB" camonitor(pv, self.newCodes, notify_disconnect=True) pv = self.prefix + "Timestamp-RB" camonitor(pv, self.newTimes, notify_disconnect=True)
def wait_for_acq(self, toggle_tag=False, tag=False, timeout=5.0, instance=[]): """Wait for next waveform acquisition to complete. If tag=True, then wait for the next acquisition which includes the side-effects of all preceding register writes """ if tag or toggle_tag: self.pv_write('dsp_tag', 'increment', 1, instance=instance) T = self.pv_read('dsp_tag', 'readback') _log.debug('Acquire T=%d toggle=%s tag=%s', T, toggle_tag, tag) if self._S is None: # since we need to return the whole thing anyway, # monitor the slow data _waveform_. pv = self.pv_name('slow_data', 'rawinput', instance=instance) _log.debug('Monitoring %s', pv) self._S = camonitor(pv, self._E.Signal, format=FORMAT_TIME) # wait for, and consume, initial update self._E.Wait(timeout=timeout) while True: slow = self._E.Wait(timeout=timeout) now = datetime.datetime.utcnow() tag_old = slow[34] tag_new = slow[33] dT = (tag_old - T) & 0xff tag_match = dT == 0 and tag_new == tag_old if not tag: break if tag_match: break # all done, waveform reflects latest parameter changes if dT != 0xff: raise RuntimeError( 'acquisition collides with another client: %d %d %d' % (tag_old, tag_new, T)) _log.debug('Acquire retry') return tag_match, slow, now
def fill_buffer_one(pv, length, datatype=float, timeout=None): '''Performs a camonitor on pv to fill a buffer.''' count = [0] result = numpy.empty(length, dtype=datatype) done = cothread.Event() def on_update(value): result[count[0]] = value count[0] += 1 if count[0] >= length: done.Signal() subscription.close() subscription = catools.camonitor(pv, on_update, datatype=datatype) try: done.Wait(timeout) finally: subscription.close() return result
def fill_buffer_one(pv, length, datatype=float, timeout=None): '''Performs a camonitor on pv to fill a buffer.''' count = [0] result = numpy.empty(length, dtype = datatype) done = cothread.Event() def on_update(value): result[count[0]] = value count[0] += 1 if count[0] >= length: done.Signal() subscription.close() subscription = catools.camonitor(pv, on_update, datatype = datatype) try: done.Wait(timeout) finally: subscription.close() return result
def __init__(self, pvs, samples=20, **kwargs): """ - pvs a list of PV - samples number of data points for std/var/average optional: - simulation [True|False] use simulated data or real pv data """ self.samples = samples self.simulation = kwargs.get('simulation', False) n = 1 if isinstance(pvs, (list, tuple)): n = len(pvs) self.pvs = pvs[:] elif isinstance(pvs, str): n = 1 self.pvs = [pvs] self.data = np.zeros((n, self.samples), 'd') self.std = np.zeros(n, 'd') self.avg = np.zeros(n, 'd') self._icur = np.zeros(n, 'i') self._count = np.ones(n, 'i') self.recent = np.zeros(n, 'd') if not self.simulation: for i in range(self.samples): self.data[:,i] = caget(self.pvs) self.recent[:] = self.data[:,-1] self.avg[:] = self.recent[:] #np.average(self.data, axis=1) #self.std[:] = #np.std(self.data, axis=1) #print type(self.recent) self.monitors = camonitor(self.pvs, self._ca_update) else: self.monitors = SimData(self._ca_update, len(self.pvs)) self.monitors.start() print "Thread is running"
def __init__(self, pvs, samples=20, **kwargs): """ - pvs a list of PV - samples number of data points for std/var/average optional: - simulation [True|False] use simulated data or real pv data """ self.samples = samples self.simulation = kwargs.get('simulation', False) n = 1 if isinstance(pvs, (list, tuple)): n = len(pvs) self.pvs = pvs[:] elif isinstance(pvs, str): n = 1 self.pvs = [pvs] self.data = np.zeros((n, self.samples), 'd') self.std = np.zeros(n, 'd') self.avg = np.zeros(n, 'd') self._icur = np.zeros(n, 'i') self._count = np.ones(n, 'i') self.recent = np.zeros(n, 'd') if not self.simulation: for i in range(self.samples): self.data[:, i] = caget(self.pvs) self.recent[:] = self.data[:, -1] self.avg[:] = self.recent[:] #np.average(self.data, axis=1) #self.std[:] = #np.std(self.data, axis=1) #print type(self.recent) self.monitors = camonitor(self.pvs, self._ca_update) else: self.monitors = SimData(self._ca_update, len(self.pvs)) self.monitors.start() print("Thread is running")
def camonitor(pvs, callback, events=None, datatype=None, format=FORMAT_RAW, count=0, all_updates=False, notify_disconnect=False, connect_timeout=None): """ Convenience function that wraps the cothread.cotools.camonitor() function with safe handling of unicode string in Python 2.X. """ # The argument 'format' redefines builtin function # pylint: disable=redefined-builtin return catools.camonitor(_to_str(pvs), callback, events=events, datatype=datatype, format=format, count=count, all_updates=all_updates, notify_disconnect=notify_disconnect, connect_timeout=connect_timeout)
def __init__(self, parent=None): QObject.__init__(self, parent) # state variables. self.runmode = 0 # 0 - continous, 1 - counter self.runRequested = 0 # 0 - run not requested, 1 - requested self.counterRun = 0 # 0 - not running, 1 - running self.shotsLeft = 0 # 4095 - stop point self.nevents = 0 # inctementing when counter cycle ends self.nshots = 0 # number of requested shots # pre-connect PV's self.pvs_connect = [ "V5:SYN:Status00C.B4", "V5:SYN:CountC", "V5:SYN:StartC.PROC", "V5:SYN:StopC.PROC" ] catools.connect(self.pvs_connect) catools.camonitor("V5:SYN:CountM", self.shotsLeftUpdate, datatype=int) catools.camonitor("V5:SYN:EventM", self.neventsUpdate, datatype=int) catools.camonitor("V5:SYN:Status00Rbv", self.statusUpdate, datatype=int)
def _execute(self): """Execute the virtual accelerator. This includes the following: 1. Creating a temporary working directory for execution of IMPACT. 2. Setup the working directory by symlinking from the data directory. 3. Writing the EPICS DB to the working directory (va.db). 4. Starting the softIoc and channel initializing monitors. 5. Add noise to the settings for all input (CSET) channels. 6. Generate the IMPACT lattice file in working directory (test.in). 7. Execute IMPACT simulation and read the output files (fort.??). 8. Update the READ channels of all devives. 9. Update the REST channels of input devies. 10. Repeat from step #5. """ _LOGGER.debug("VirtualAccelerator: Execute virtual accelerator") if self._chanprefix is None: chanprefix = "" else: chanprefix = self._chanprefix # Add channel for VA configuration and control channoise = chanprefix+"SVR:NOISE" self._epicsdb.append(("ao", channoise, OrderedDict([ ("DESC", "Noise level of Virtual Accelerator"), ("VAL", 0.001), ("PREC", 5) ]))) chanstat = chanprefix+"SVR:STATUS" self._epicsdb.append(("bi", chanstat, OrderedDict([ ("DESC", "Status of Virtual Accelerator"), ("VAL", 1), ("ZNAM", "ERR"), ("ONAM", "OK"), ("PINI", "1") ]))) chancharge = chanprefix+"SVR:CHARGE" self._epicsdb.append(("ai", chancharge, OrderedDict([ ("DESC", "Q/M of Virtual Accelerator"), ("VAL", 0.0), ("PREC", 5) ]))) if self.work_dir != None: os.makedirs(self.work_dir) self._rm_work_dir = False else: self.work_dir = tempfile.mkdtemp(_TEMP_DIRECTORY_SUFFIX) self._rm_work_dir = True _LOGGER.info("VirtualAccelerator: Working directory: %s", self._work_dir) # input file paths epicsdbpath = os.path.join(self.work_dir, "va.db") latticepath = os.path.join(self.work_dir, "test.in") modelmappath = os.path.join(self.work_dir, "model.map") #output file paths fort18path = os.path.join(self.work_dir, "fort.18") fort24path = os.path.join(self.work_dir, "fort.24") fort25path = os.path.join(self.work_dir, "fort.25") epicslogpath = os.path.join(self.work_dir, "softioc.log") if os.path.isabs(self.data_dir): abs_data_dir = self.data_dir else: abs_data_dir = os.path.abspath(self.data_dir) for datafile in os.listdir(abs_data_dir): srcpath = os.path.join(abs_data_dir, datafile) destpath = os.path.join(self.work_dir, datafile) if os.path.isfile(os.path.join(abs_data_dir, datafile)): os.symlink(srcpath, destpath) _LOGGER.debug("VirtualAccelerator: Link data file %s to %s", srcpath, destpath) with open(epicsdbpath, "w") as outfile: self._write_epicsdb(outfile) self._ioc_logfile = open(epicslogpath, "w") self._ioc_process = _Cothread_Popen(["softIoc", "-d", "va.db"], cwd=self.work_dir, stdout=self._ioc_logfile, stderr=subprocess.STDOUT) self._subscriptions = [] self._subscriptions.append(catools.camonitor(channoise, self._handle_noise_monitor)) self._subscriptions.extend(catools.camonitor(self._csetmap.keys(), self._handle_cset_monitor)) while self._continue: # update the RSET channels with new settings for cset in self._csetmap.items(): name, field = self._fieldmap[cset[0]] catools.caput(cset[1][0], self._settings[name][field]) settings = self._copy_settings_with_noise() self._latfactory.settings = settings lattice = self._latfactory.build() catools.caput(chancharge, lattice.initialCharge) with open(latticepath, "w") as outfile: with open(modelmappath, "w") as mapfile: lattice.write(outfile, mapstream=mapfile) start = time.time() if os.path.isfile(fort18path): os.remove(fort18path) if os.path.isfile(fort24path): os.remove(fort24path) if os.path.isfile(fort25path): os.remove(fort25path) impact_process = _Cothread_Popen(["mpirun", "-np", str(lattice.nprocessors), str(self.impact_exe)], cwd=self.work_dir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) (stdout, _, status) = impact_process.communicate() # The virtual accelerator shutdown is likely to occur while IMPACT is executing, # so check if virtual accelerator has been stopped before proceeding. if not self._continue: break _LOGGER.info("VirtualAccelerator: IMPACT execution time: %f s", time.time()-start) if status == 0: catools.caput(chanstat, _VA_STATUS_GOOD) else: _LOGGER.warning("VirtualAccelerator: IMPACT exited with non-zero status code: %s\r\n%s", status, stdout) catools.caput(chanstat, _VA_STATUS_BAD) if os.path.isfile(fort18path): fort18 = numpy.loadtxt(fort18path, usecols=(0, 1, 3)) fort18length = fort18.shape[0] else: _LOGGER.warning("VirtualAccelerator: IMPACT output not found: %s", fort18path) catools.caput(chanstat, _VA_STATUS_BAD) fort18length = 0 if os.path.isfile(fort24path): fort24 = numpy.loadtxt(fort24path, usecols=(1, 2)) fort24length = fort24.shape[0] else: _LOGGER.warning("VirtualAccelerator: IMPACT output not found: %s", fort24path) catools.caput(chanstat, _VA_STATUS_BAD) fort24length = 0 if os.path.isfile(fort25path): fort25 = numpy.loadtxt(fort25path, usecols=(1, 2)) fort25length = fort25.shape[0] else: _LOGGER.warning("VirtualAccelerator: IMPACT output not found: %s", fort25path) catools.caput(chanstat, _VA_STATUS_BAD) fort25length = 0 output_map = [] for elem in lattice.elements: if elem.itype in [ -28 ]: output_map.append(elem.name) output_length = len(output_map) if(fort18length < output_length): _LOGGER.warning("VirtualAccelerator: IMPACT fort.18 length %s, expecting %s", fort18length, output_length) catools.caput(chanstat, _VA_STATUS_BAD) if(fort24length < output_length): _LOGGER.warning("VirtualAccelerator: IMPACT fort.24 length %s, expecting %s", fort24length, output_length) catools.caput(chanstat, _VA_STATUS_BAD) if(fort25length < output_length): _LOGGER.warning("VirtualAccelerator: IMPACT fort.25 length %s, expecting %s", fort25length, output_length) catools.caput(chanstat, _VA_STATUS_BAD) for idx in xrange(min(fort18length, fort24length, fort25length)): elem = self._elemmap[output_map[idx]] if isinstance(elem, BPMElement): _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.x], fort24[idx,0]) catools.caput(self._readfieldmap[elem.name][elem.fields.x], fort24[idx,0]) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.y], fort25[idx,0]) catools.caput(self._readfieldmap[elem.name][elem.fields.y], fort25[idx,0]) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.phase], fort18[idx,1]) catools.caput(self._readfieldmap[elem.name][elem.fields.phase], fort18[idx,1]) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.energy], fort18[idx,2]) catools.caput(self._readfieldmap[elem.name][elem.fields.energy], fort18[idx,2]) elif isinstance(elem, PMElement): _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.x], fort24[idx,0]) catools.caput(self._readfieldmap[elem.name][elem.fields.x], fort24[idx,0]) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.y], fort25[idx,0]) catools.caput(self._readfieldmap[elem.name][elem.fields.y], fort25[idx,0]) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.xrms], fort24[idx,1]) catools.caput(self._readfieldmap[elem.name][elem.fields.xrms], fort24[idx,1]) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.yrms], fort25[idx,1]) catools.caput(self._readfieldmap[elem.name][elem.fields.yrms], fort25[idx,1]) else: _LOGGER.warning("VirtualAccelerator: Output from element type not supported: %s", type(elem).__name__) # Write the default error value to the remaing output PVs. for idx in xrange(min(fort18length, fort24length, fort25length), output_length): elem = self._elemmap[output_map[idx]] if isinstance(elem, BPMElement): _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.x], _DEFAULT_ERROR_VALUE) catools.caput(self._readfieldmap[elem.name][elem.fields.x], _DEFAULT_ERROR_VALUE) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.y], _DEFAULT_ERROR_VALUE) catools.caput(self._readfieldmap[elem.name][elem.fields.y], _DEFAULT_ERROR_VALUE) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.phase], _DEFAULT_ERROR_VALUE) catools.caput(self._readfieldmap[elem.name][elem.fields.phase], _DEFAULT_ERROR_VALUE) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.energy], _DEFAULT_ERROR_VALUE) catools.caput(self._readfieldmap[elem.name][elem.fields.energy], _DEFAULT_ERROR_VALUE) elif isinstance(elem, PMElement): _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.x], _DEFAULT_ERROR_VALUE) catools.caput(self._readfieldmap[elem.name][elem.fields.x], _DEFAULT_ERROR_VALUE) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.y], _DEFAULT_ERROR_VALUE) catools.caput(self._readfieldmap[elem.name][elem.fields.y], _DEFAULT_ERROR_VALUE) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.xrms], _DEFAULT_ERROR_VALUE) catools.caput(self._readfieldmap[elem.name][elem.fields.xrms], _DEFAULT_ERROR_VALUE) _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", self._readfieldmap[elem.name][elem.fields.yrms], _DEFAULT_ERROR_VALUE) catools.caput(self._readfieldmap[elem.name][elem.fields.yrms], _DEFAULT_ERROR_VALUE) else: _LOGGER.warning("VirtualAccelerator: Output from element type not supported: %s", type(elem).__name__) for name, value in self._csetmap.iteritems(): name, field = self._fieldmap[name] _LOGGER.debug("VirtualAccelerator: Update read: %s to %s", value[1], settings[name][field]) catools.caput(value[1], settings[name][field]) # Sleep for a fraction (10%) of the total execution time # when one simulation costs more than 0.50 seconds. # Otherwise, sleep for the rest of 1 second. # If a scan is being done on this virtual accelerator, # then the scan server has a period of time to update # setpoints before the next run of IMPACT. if (time.time()-start) > 0.50: cothread.Sleep((time.time()-start)*0.1) else: cothread.Sleep(1.0 - (time.time()-start))
def __init__(self): """Monitor values of PVs: offsets, scales etc.""" if self.__guard: raise RuntimeError('Do not instantiate. ' + 'If you require an instance use get_instance.') self.arrays = { Arrays.OFFSETS: caget( [ctrl + ':OFFSET' for ctrl in PvReferences.CTRLS]), Arrays.SCALES: caget( [ctrl + ':WFSCA' for ctrl in PvReferences.CTRLS]), Arrays.SET_SCALES: caget( [name + ':SETWFSCA' for name in PvReferences.NAMES]), Arrays.WAVEFORMS: caget(PvReferences.TRACES), Arrays.SETI: caget([name + ':SETI' for name in PvReferences.NAMES]), Arrays.IMIN: caget([name + ':IMIN' for name in PvReferences.NAMES]), Arrays.IMAX: caget([name + ':IMAX' for name in PvReferences.NAMES]), Arrays.ERRORS: caget( [name + ':ERRGSTR' for name in PvReferences.NAMES]) } self.listeners = {'straight': [], 'trace': []} for i in range(len(PvReferences.CTRLS)): camonitor(PvReferences.CTRLS[i] + ':OFFSET', lambda x, i=i: self.update_values( x, Arrays.OFFSETS, i, 'straight')) camonitor(PvReferences.CTRLS[i] + ':WFSCA', lambda x, i=i: self.update_values( x, Arrays.SCALES, i, 'straight')) for idx, ioc in enumerate(PvReferences.NAMES): camonitor(ioc + ':SETWFSCA', lambda x, i=idx: self.update_values( x, Arrays.SET_SCALES, i, 'straight')) camonitor(ioc + ':SETI', lambda x, i=idx: self.update_values( x, Arrays.SETI, i, 'straight')) camonitor(ioc + ':IMIN', lambda x, i=idx: self.update_values( x, Arrays.IMIN, i, 'straight')) camonitor(ioc + ':IMAX', lambda x, i=idx: self.update_values( x, Arrays.IMAX, i, 'straight')) camonitor(ioc + ':ERRGSTR', lambda x, i=idx: self.update_values( x, Arrays.ERRORS, i, 'straight'), format=FORMAT_TIME) camonitor(PvReferences.TRACES[0], lambda x: self.update_values(x, Arrays.WAVEFORMS, 0, 'trace')) camonitor(PvReferences.TRACES[1], lambda x: self.update_values(x, Arrays.WAVEFORMS, 1, 'trace')) cothread.Yield() # Ensure monitored values are connected
def startmonitorcommand(): monstub = ca.camonitor([commandsppv, commandrbpv], callback4command, notify_disconnect = True) return monstub
def __init__(self): """Initialise GUI.""" QMainWindow.__init__(self) filename = os.path.join(os.path.dirname(__file__), self.UI_FILENAME) self.ui = uic.loadUi(filename) self.parent = QtGui.QMainWindow() # Get instances of required classes. self.straight = straight.Straight() self.pv_monitor = controls.PvMonitors.get_instance() self.simcontrol = straight.SimModeController() self.realcontrol = straight.RealModeController() self.pv_writer = writers.PvWriter() self.sim_writer = writers.SimWriter(self.simcontrol) # Register listeners. self.realcontrol.register_straight(self.straight) self.pv_monitor.register_straight_listener(self.update_table) # Set up simulation, toolbar and table in the GUI. self.simulation = plots.Simulation(self.straight) self.toolbar = NavigationToolbar(self.simulation, self) self.setup_table() # Initial settings for GUI: connected to PVs and jog scale = 1. self.writer = self.pv_writer self.jog_scale = 1.0 # Connect buttons to PVs. self.ui.kplusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.STEP_K3, 1)) self.ui.kminusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.STEP_K3, -1)) self.ui.bumpleftplusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BUMP_LEFT, 1)) self.ui.bumpleftminusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BUMP_LEFT, -1)) self.ui.bumprightplusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BUMP_RIGHT, 1)) self.ui.bumprightminusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BUMP_RIGHT, -1)) self.ui.bpm1plusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BPM1, 1)) self.ui.bpm1minusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BPM1, -1)) self.ui.bpm2plusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BPM2, 1)) self.ui.bpm2minusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.BPM2, -1)) self.ui.scaleplusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.SCALE, 1)) self.ui.scaleminusButton.clicked.connect( lambda: self.jog_handler(magnet_jogs.Moves.SCALE, -1)) self.ui.simButton.setChecked(False) self.ui.simButton.clicked.connect(self.toggle_simulation) self.ui.resetButton.clicked.connect(self.reset) self.ui.resetButton.setEnabled(False) self.ui.quitButton.clicked.connect(sys.exit) self.ui.jog_scale_slider.valueChanged.connect(self.set_jog_scaling) self.ui.jog_scale_textbox.setText(str(self.jog_scale)) # Monitor the states of magnets, BURT and cycling. camonitor(controls.PvReferences.BURT_STATUS_PV, self.update_burt_led) camonitor(controls.PvReferences.MAGNET_STATUS_PV, self.update_magnet_led, format=FORMAT_CTRL) camonitor(controls.PvReferences.CYCLING_STATUS_PV, self.update_cycling_textbox, format=FORMAT_CTRL) # Add simulation and toolbar to the GUI. self.ui.matplotlib_layout.addWidget(self.simulation) self.ui.matplotlib_layout.addWidget(self.toolbar) # Add shading to indicate ranges over which photon beams sweep, and # dotted lines indicating limits of magnet tolerances. self.simulation.update_colourin() self.simulation.magnet_limits()
def start_subscription(self): """ """ self.camonitor_subscription = camonitor( self.current_pv_name, self.camonitor_callback, format=FORMAT_TIME, all_updates=False )
def camonitor_scale(self): catools.camonitor(self.id_energy, self.set_vertical_xbpm_scale_factor)
def camonitor_range(self): catools.camonitor(self.tetramm_prefix + self.xbpm_num + ':SumAll:MeanValue_RBV', self.check_range)
def monitordeviceselection(self): """Start a process to monitor device selection.""" return ca.camonitor([self.pvmapping.__deviceselected__, self.pvmapping.__srcposition__], self.deviceselectioncallback)
def start_monitor(self): self.capturing = caget( self.pv['capture_rbv']) is 1 self.mon_handle = camonitor( self.pv['capture_rbv'], self.monitor_capture )
def start_monitor(self): self.acquiring = caget( self.pv['acquire_rbv']) is 1 self.mon_handle = camonitor( self.pv['acquire_rbv'], self.monitor_acquire)
def startmonitorenergy(): monstub = ca.camonitor(energysppv, callback4energy, notify_disconnect = True) return monstub
def test_start_camonitor(): # XBPM1 feedback check (RUN1): catools.camonitor(my_list, test_checkFeedbackInputs)
def monitorplane(self): """Start a process to monitor source plane.""" return ca.camonitor(self.pvmapping.__plane__, self.planecallback)
pchans[9].setValue(active_power / full_power) for i in range(6): pchans[i].setValue(powers[i]) if (datetime.date.today() - workdate).days > 0: workdate = datetime.date.today() elastday_chan.setValue(E_today) E_today = 0 t = time.time() dt = t - last_time last_time = t E_today += dt * full_power / 3600.0 etoday_chan.setValue(E_today) def UINewData(value, index): uichans[index].setValue(value) app = cothread.iqt() a = camonitor(powerPVs, PowerNewData) pchans = [cda.DChan(pwa1_server + '.' + x) for x in cnames] b = camonitor(uiPVs, UINewData) uichans = [cda.DChan(pwa1_server + '.' + x) for x in uicnames] etoday_chan = cda.DChan(pwa1_server + '.Etoday') elastday_chan = cda.DChan(pwa1_server + '.Elastday') cothread.WaitForQuit()
def monitorundo(self): """Monitor the PV to trig local bump computing.""" return ca.camonitor(self.pvmapping.__undo__, self.undocallback)
def monitorapply(self): """Monitor the PV to trig setting data to IOC.""" return ca.camonitor(self.pvmapping.__apply__, self.applycallback)
def __init__(self, pv, **kws): self.name=u'CACache("%s",%s)'%(pv, kws) _L.debug('camonitor %s', self.name) self.__S = ca.camonitor(pv, self.__update, notify_disconnect=True, **kws) self.value = ca.ca_nothing(pv, ECA_DISCONN)
def __init__(self, motor_pv): self._motor_pv = motor_pv self._done_moving_pv = motor_pv + '.DMOV' self._completed_one_move = False self._moving = not ca.caget(self._done_moving_pv) ca.camonitor(self._done_moving_pv, self.state_changed)
def monitorsource(self): """Start a process to monitor source s position.""" return ca.camonitor(self.pvmapping.__deviceselected__, self.sourcecallback)
def startmonitorrb(pvs): monstub = ca.camonitor(pvs, callback4rb, notify_disconnect = True) return monstub
def monitorbumpsettings(self): """Monitor local bump settings""" return ca.camonitor([self.pvmapping.__shift__, self.pvmapping.__angle__], self.bumpsettingscallback)