def get_initialization_model(): ip = InitializationParser() rtree = load_plugin_tree() gtree = load_global_tree() for gi in ip.get_plugin_groups(): tree = get_tree(gi, rtree) if tree: ps = ip.get_plugins(gi, element=True) if ps: for pp in ps: plugin = get_plugin(pp.text.strip(), tree) if plugin: plugin.enabled = to_bool(pp.get('enabled')) for gi in ip.get_globals(): gv = gtree.get_value(gi.tag) if gv: gv.enabled = to_bool(gi.text.strip()) model = InitializationModel(trees=[gtree, rtree], path_name=os.path.basename(ip.path), parser=ip) model.init_hash() return model
def __init__(self, schema_identifier='', attrs=None, kind=None): super(ConnectionFavoriteItem, self).__init__() self.schema_identifier = schema_identifier if kind is not None: self.kind = kind if attrs: attrs = attrs.split(',') try: self.name, self.kind, self.username, self.host, self.dbname, self.password = attrs except ValueError: try: self.name, self.kind, self.username, self.host, self.dbname, self.password, enabled = attrs self.enabled = to_bool(enabled) except ValueError: try: (self.name, self.kind, self.username, self.host, self.dbname, self.password, enabled, default) = attrs self.enabled = to_bool(enabled) self.default = to_bool(default) except ValueError: (self.name, self.kind, self.username, self.host, self.dbname, self.password, enabled, default, path) = attrs self.enabled = to_bool(enabled) self.default = to_bool(default) self.path = path self.load_names()
def __init__(self, schema_identifier='', attrs=None): super(ConnectionFavoriteItem, self).__init__() self.schema_identifier = schema_identifier if attrs: attrs = attrs.split(',') try: self.name, self.kind, self.username, self.host, self.dbname, self.password = attrs except ValueError: try: self.name, self.kind, self.username, self.host, self.dbname, self.password, enabled = attrs self.enabled = to_bool(enabled) except ValueError: try: (self.name, self.kind, self.username, self.host, self.dbname, self.password, enabled, default) = attrs self.enabled = to_bool(enabled) self.default = to_bool(default) except ValueError: (self.name, self.kind, self.username, self.host, self.dbname, self.password, enabled, default, path) = attrs self.enabled = to_bool(enabled) self.default = to_bool(default) self.path = path self.load_names()
def start(self): # if self.managers: from pychron.envisage.initialization.initializer import Initializer dp = DevicePreferences() afh = self.application.preferences.get('pychron.hardware.auto_find_handle') awh = self.application.preferences.get('pychron.hardware.auto_write_handle') if afh is not None: dp.serial_preference.auto_find_handle = to_bool(afh) dp.serial_preference.auto_write_handle = to_bool(awh) ini = Initializer(device_prefs=dp) for m in self.managers: ini.add_initialization(m) # any loaded managers will be registered as services if not ini.run(application=self.application): self.application.exit() # self.application.starting return # create the hardware proxy server ehs = to_bool(self.application.preferences.get('pychron.hardware.enable_hardware_server')) if ehs: # use_tx = to_bool(self.application.preferences.get('pychron.hardware.use_twisted', True)) use_tx = True if use_tx: from pychron.tx.server import TxServer rhm = TxServer() node = self.application.preferences.node('pychron.hardware') ports = eval(node.get('ports', '[]')) factories = eval(node.get('factories', '[]')) for protocol in eval(node.get('pnames', '[]')): factory = import_klass(factories[protocol]) port = int(ports[protocol]) exc = rhm.add_endpoint(port, factory(self.application)) if exc: msg = 'Failed starting Command Server for "{}:{}". Please check that multiple ' \ 'instances of pychron are not running on this computer. ' \ 'Exception: {}'.format(protocol, port, exc) self.warning_dialog(msg) else: self.info('Added Pychron Proxy Service: {}:{}'.format(protocol, port)) # else: # from pychron.remote_hardware.remote_hardware_manager import RemoteHardwareManager # rhm = RemoteHardwareManager(application=self.application) self._remote_hardware_manager = rhm rhm.bootstrap()
def start(self): # if self.managers: from pychron.envisage.initialization.initializer import Initializer dp = DevicePreferences() afh = self.application.preferences.get( 'pychron.hardware.auto_find_handle') awh = self.application.preferences.get( 'pychron.hardware.auto_write_handle') if afh is not None: dp.serial_preference.auto_find_handle = to_bool(afh) dp.serial_preference.auto_write_handle = to_bool(awh) ini = Initializer(device_prefs=dp) for m in self.managers: ini.add_initialization(m) # any loaded managers will be registered as services if not ini.run(application=self.application): self.application.exit() # self.application.starting return # create the hardware proxy server ehs = to_bool( self.application.preferences.get( 'pychron.hardware.enable_hardware_server')) if ehs: # use_tx = to_bool(self.application.preferences.get('pychron.hardware.use_twisted', True)) use_tx = True if use_tx: from pychron.tx.server import TxServer rhm = TxServer() node = self.application.preferences.node('pychron.hardware') ports = eval(node.get('ports')) factories = eval(node.get('factories')) for protocol in eval(node.get('pnames')): factory = import_klass(factories[protocol]) port = int(ports[protocol]) rhm.add_endpoint(port, factory(self.application)) self.debug('Added Pychron Proxy Service: {}:{}'.format( protocol, port)) else: from pychron.remote_hardware.remote_hardware_manager import RemoteHardwareManager rhm = RemoteHardwareManager(application=self.application) self._remote_hardware_manager = rhm rhm.bootstrap()
def wrapper(*args, **kw): r = func(*args, **kw) if r: r = r.strip() r = to_bool(r) # r = to_bool(r[4:-4]) return r
def _new_label(self, label, name, c, layer=1, origin=None, klass=None, **kw): if origin is None: ox, oy = 0, 0 else: ox, oy = origin if klass is None: klass = Label x, y = 0, 0 trans = label.find('translation') if trans is not None: x, y = map(float, trans.text.split(',')) c = self._make_color(c) l = klass(ox + x, oy + y, bgcolor=c, use_border=to_bool(label.get('use_border', 'T')), name=name, text=label.text.strip(), **kw) font = label.find('font') if font is not None: l.font = font.text.strip() self.add_item(l, layer=layer) return l
def _get_db(self): if self.use_workspace: return self.workspace.index_db elif to_bool(self.application.preferences.get('pychron.dvc.enabled')): return self.application.get_service('pychron.dvc.dvc.DVC') else: return self.manager.db
def _new_label(self, cp, label, name, c, layer=1, origin=None, klass=None, **kw): if origin is None: ox, oy = 0, 0 else: ox, oy = origin if klass is None: klass = Label x, y = self._get_translation(cp, label) # x, y = 0, 0 # trans = label.find('translation') # if trans is not None: # x, y = map(float, trans.text.split(',')) c = self._make_color(c) l = klass(ox + x, oy + y, bgcolor=c, use_border=to_bool(label.get('use_border', 'T')), name=name, text=label.text.strip(), **kw) font = label.find('font') if font is not None: l.font = font.text.strip() self.add_item(l, layer=layer) return l
def prepare(self): self.info('Prepare laser') self._ask('Prepare') cnt = 0 tries = 0 maxtries = 200 # timeout after 50 s if globalv.experiment_debug: maxtries = 1 nsuccess = 1 self._cancel_blocking = False ask = self._ask period = 1 cmd = 'IsReady' while tries < maxtries and cnt < nsuccess: if self._cancel_blocking: break time.sleep(period) resp = ask(cmd) if resp is not None: try: if to_bool(resp): cnt += 1 except: cnt = 0 else: cnt = 0 tries += 1 return cnt >= nsuccess
def wrapper(*args, **kw): r = func(*args, **kw) if r: r = to_bool(r.strip()) if invert: r = not r return r
def _new_rectangle(self, elem, c, bw=3, layer=1, origin=None, klass=None, type_tag=''): if klass is None: klass = RoundedRectangle if origin is None: ox, oy = 0, 0 else: ox, oy = origin key = elem.text.strip() display_name = elem.get('display_name', key) # print key, display_name fill = to_bool(elem.get('fill', 'T')) x, y = self._get_floats(elem, 'translation') w, h = self._get_floats(elem, 'dimension') color = elem.find('color') if color is not None: c = color.text.strip() cobj = self.get_item(c) if cobj is not None: c = cobj.default_color else: c = self._make_color(c) # if type_tag == 'turbo': # klass = Turbo # elif # else: # klass = RoundedRectangle rect = klass(x + ox, y + oy, width=w, height=h, name=key, border_width=bw, display_name=display_name, volume=get_volume(elem), default_color=c, type_tag=type_tag, fill=fill) font = elem.find('font') if font is not None: rect.font = font.text.strip() if type_tag in ('turbo', 'laser'): self.overlays.append(rect) rect.scene_visible = False self.add_item(rect, layer=layer) return rect
def _random_tip(self): if globalv.random_tip_enabled and to_bool(self.application.preferences.get('pychron.general.show_random_tip')): from pychron.envisage.tasks.tip_view import TipView t = random.choice(self.help_tips) tv = TipView(text=t) tv.edit_traits()
def _load_booleans(self, header, args, params): for attr in ['autocenter', 'use_cdd_warming', ('disable_between_positions', 'dis_btw_pos')]: v = self._get_attr_value(header, args, attr, cast=lambda x: to_bool(x.strip())) if v is not None: params[v[0]] = v[1]
def start(self): # if self.managers: from pychron.envisage.initialization.initializer import Initializer dp = DevicePreferences() afh = self.application.preferences.get('pychron.hardware.auto_find_handle') awh = self.application.preferences.get('pychron.hardware.auto_write_handle') if afh is not None: dp.serial_preference.auto_find_handle = to_bool(afh) dp.serial_preference.auto_write_handle = to_bool(awh) ini = Initializer(device_prefs=dp) for m in self.managers: ini.add_initialization(m) # any loaded managers will be registered as services if not ini.run(application=self.application): self.application.exit() # self.application.starting return # create the hardware proxy server ehs = to_bool(self.application.preferences.get('pychron.hardware.enable_hardware_server')) if ehs: # use_tx = to_bool(self.application.preferences.get('pychron.hardware.use_twisted', True)) use_tx = True if use_tx: from pychron.tx.server import TxServer rhm = TxServer() node = self.application.preferences.node('pychron.hardware') ports = eval(node.get('ports')) factories = eval(node.get('factories')) for protocol in eval(node.get('pnames')): factory = import_klass(factories[protocol]) port = int(ports[protocol]) rhm.add_endpoint(port, factory(self.application)) self.debug('Added Pychron Proxy Service: {}:{}'.format(protocol, port)) else: from pychron.remote_hardware.remote_hardware_manager import RemoteHardwareManager rhm = RemoteHardwareManager(application=self.application) self._remote_hardware_manager = rhm rhm.bootstrap()
def __init__(self, schema_identifier='', attrs=None, load_names=False): super(ConnectionFavoriteItem, self).__init__() self.schema_identifier = schema_identifier if attrs: attrs = attrs.split(',') try: (self.name, self.kind, self.username, self.host, self.dbname, self.password, enabled, default, path) = attrs except ValueError: (self.name, self.kind, self.username, self.host, self.dbname, self.password, enabled, default, self.path, self.organization, self.meta_repo_name, self.meta_repo_dir) = attrs self.enabled = to_bool(enabled) self.default = to_bool(default) if load_names: self.load_names()
def GoToHole(self, manager, hole, autocenter, *args): try: hole = int(hole) autocenter = to_bool(autocenter) err = manager.stage_manager.move_to_hole( str(hole), correct_position=autocenter) except (ValueError, TypeError): err = InvalidArgumentsErrorCode('GoToHole', (hole, autocenter)) return self.error_response(err)
def GoToHole(self, manager, hole, autocenter, *args): try: hole = int(hole) autocenter = to_bool(autocenter) err = manager.stage_manager.move_to_hole(str(hole), correct_position=autocenter) except (ValueError, TypeError): err = InvalidArgumentsErrorCode('GoToHole', (hole, autocenter)) return self.error_response(err)
def start(self): super(ThermoSpectrometerPlugin, self).start() if to_bool(self.application.preferences.get('pychron.spectrometer.auto_open_readout')): from pychron.spectrometer.readout_view import new_readout_view # # spec = self.application.get_service( # 'pychron.spectrometer.base_spectrometer_manager.BaseSpectrometerManager') # ro, v = new_readout_view(spectrometer=spec.spectrometer) rv = self.application.get_service(ReadoutView) v = new_readout_view(rv) open_view(rv, view=v)
def _check_required(self, subtree): # check the subtree has all required devices enabled devs = self._parser.get_devices(subtree, all_=True, element=True) for di in devs: required = True req = self._parser.get_parameter(di, 'required') if req: required = to_bool(req) enabled = to_bool(di.get('enabled')) if required and not enabled: name = di.text.strip().upper() msg = '''Device {} is REQUIRED but is not ENABLED. Do you want to quit to enable {} in the Initialization File?'''.format(name, name) result = self.confirmation_dialog(msg, title='Quit Pychron') if result: raise InitializerError() return True
def start(self): super(ThermoSpectrometerPlugin, self).start() if to_bool(self.application.preferences.get('pychron.spectrometer.auto_open_readout')): from pychron.spectrometer.readout_view import new_readout_view # # spec = self.application.get_service( # 'pychron.spectrometer.base_spectrometer_manager.BaseSpectrometerManager') # ro, v = new_readout_view(spectrometer=spec.spectrometer) rv = self.application.get_service(ReadoutView) v = new_readout_view(rv) self.application.open_view(rv, view=v)
def _new_rectangle(self, cp, elem, c, bw=3, layer=1, origin=None, klass=None, type_tag=''): if klass is None: klass = RoundedRectangle if origin is None: ox, oy = 0, 0 else: ox, oy = origin key = elem.text.strip() display_name = elem.get('display_name', key) # print key, display_name fill = to_bool(elem.get('fill', 'T')) # x, y = self._get_floats(elem, 'translation') x, y = self._get_translation(cp, elem) w, h = self._get_floats(elem, 'dimension') color = elem.find('color') if color is not None: c = color.text.strip() cobj = self.get_item(c) if cobj is not None: c = cobj.default_color else: c = self._make_color(c) # if type_tag == 'turbo': # klass = Turbo # elif # else: # klass = RoundedRectangle rect = klass(x + ox, y + oy, width=w, height=h, name=key, border_width=bw, display_name=display_name, volume=get_volume(elem), default_color=c, type_tag=type_tag, fill=fill) font = elem.find('font') if font is not None: rect.font = font.text.strip() if type_tag in ('turbo', 'laser'): self.overlays.append(rect) rect.scene_visible = False self.add_item(rect, layer=layer) return rect
def load(self): p = paths.task_extensions_file if os.path.isfile(p): with open(p, 'r') as rfile: yl = yaml.load(rfile) for te in self.task_extensions: yd = next((d for d in yl if d['plugin_id'] == te.id), None) if yd: for ai in yd['actions']: action, enabled = ai.split(',') tt = next((ta for ta in te.additions if ta.model.id == action), None) if tt: tt.enabled = to_bool(enabled)
def _get_switch_channel(self, data): if isinstance(data, dict): name = data['name'] else: name = data name = str(name) ch = self._switch_mapping.get(name, '') inverted = False if ',' in str(ch): ch, inverted = ch.split(',') inverted = to_bool(inverted) #self.debug('get switch channel {} {}'.format(name, ch)) return ch, inverted
def load_configuration(self): dm = self.dm sheet = dm.get_sheet(("Configuration", 4)) for ri in dm.iterrows(sheet, 1): name = ri[0].value v = ri[1].value if name == "autogenerate_labnumber": v = to_bool(v) self.debug('setting "{}"={}'.format(name, v)) if not hasattr(self, name): self.warning('Invalid configuration option "{}"'.format(name)) else: setattr(self, name, v)
def load_configuration(self): dm = self.dm sheet = dm.get_sheet(('Configuration', 4)) for ri in dm.iterrows(sheet, 1): name = ri[0].value v = ri[1].value if name == 'autogenerate_labnumber': v = to_bool(v) self.debug('setting "{}"={}'.format(name, v)) if not hasattr(self, name): self.warning('Invalid configuration option "{}"'.format(name)) else: setattr(self, name, v)
def get_task_extensions(self, pid): import yaml p = paths.task_extensions_file with open(p, 'r') as rfile: yl = yaml.load(rfile) for yi in yl: # print yi['plugin_id'], pid if yi['plugin_id'].startswith(pid): tid = yi.get('task_id', '') for ai in yi['actions']: a, e = ai.split(',') # print tid, a, e if to_bool(e): yield tid, a
def _go_to_hole(self, data): if isinstance(data, dict): hole, autocenter = data['hole'], data['autocenter'] else: hole, autocenter = data try: hole = int(hole) autocenter = to_bool(autocenter) err = self._manager.stage_manager.move_to_hole(str(hole), correct_position=autocenter) except (ValueError, TypeError): err = InvalidArgumentsErrorCode('GoToHole', (hole, autocenter)) return err or 'OK'
def _go_to_hole(self, data): if isinstance(data, dict): hole, autocenter = data['hole'], data['autocenter'] else: hole, autocenter = data try: hole = int(hole) autocenter = to_bool(autocenter) err = self._manager.stage_manager.move_to_hole( str(hole), correct_position=autocenter) except (ValueError, TypeError): err = InvalidArgumentsErrorCode('GoToHole', (hole, autocenter)) return err or 'OK'
def get_user(): """ current: str, current user. if supplied omit from available list """ login = Login() if to_bool(os.getenv('PYCHRON_USE_LOGIN', True)) or not (login.user and login.environment): while 1: info = login.edit_traits() if info.result: if login.user and login.environment: return login.user, login.environment else: break else: return login.user, login.environment
def get_plugins(self, category=None, all_=False, element=False): tree = self.get_root() tree = tree.find('plugins') if category: cat = tree.find(category) if cat is not None: plugins = cat.findall('plugin') else: try: plugins = tree.iter(tag='plugin') except AttributeError: plugins = tree.getiterator(tag='plugin') if plugins: return [p if element else p.text.strip() for p in plugins if all_ or to_bool(p.get('enabled'))]
def _editor_factory(self, is_uv=False, **kw): klass = UVExperimentEditor if is_uv else ExperimentEditor editor = klass(application=self.application, automated_runs_editable=self.automated_runs_editable, **kw) prefs = self.application.preferences prefid = 'pychron.experiment' bgcolor = prefs.get('{}.bg_color'.format(prefid)) even_bgcolor = prefs.get('{}.even_bg_color'.format(prefid)) use_analysis_type_colors = to_bool(prefs.get('{}.use_analysis_type_colors'.format(prefid))) editor.setup_tabular_adapters(bgcolor, even_bgcolor, self._assemble_state_colors(), use_analysis_type_colors, self._assemble_analysis_type_colors()) return editor
def activated(self): model = self._get_browser_model() self.browser_model = model if not model.is_activated: self._setup_browser_model() with no_update(self): self.browser_model.current_task_name = self.default_task_name # self._top_level_filter = None self.activate_workspace() self.browser_model.activated() if to_bool(self.application.preferences.get('pychron.dvc.enabled')): self.dvc = self.application.get_service('pychron.dvc.dvc.DVC')
def _editor_factory(self, is_uv=False, **kw): klass = UVExperimentEditor if is_uv else ExperimentEditor editor = klass(application=self.application, automated_runs_editable=self.automated_runs_editable, **kw) prefs = self.application.preferences prefid = 'pychron.experiment' bgcolor = prefs.get('{}.bg_color'.format(prefid)) even_bgcolor = prefs.get('{}.even_bg_color'.format(prefid)) use_analysis_type_colors = to_bool( prefs.get('{}.use_analysis_type_colors'.format(prefid))) editor.setup_tabular_adapters(bgcolor, even_bgcolor, self._assemble_state_colors(), use_analysis_type_colors, self._assemble_analysis_type_colors()) return editor
def set_dac(self, v, verbose=True, settling_time=None): self.debug('setting magnet DAC') self.debug('current : {:0.6f}'.format(self._dac)) self.debug('requested: {:0.6f}'.format(v)) dv = abs(self._dac - v) self.debug('Delta Dac: {:0.6f}'.format(dv)) unprotect = [] unblank = False if self.use_detector_protection: self.debug('Checking detector protection. dv={:0.5f}'.format(dv)) for pd in self.protected_detectors: det = self.spectrometer.get_detector(pd) self.debug('Checking detector "{}". Protection Threshold: {} (V)'.format(pd, det.protection_threshold)) if det.protection_threshold and dv > det.protection_threshold: self.ask('ProtectDetector {},On'.format(pd), verbose=verbose) self.ask('GetDeflection {}'.format(pd), verbose=verbose) unprotect.append(pd) if self.use_beam_blank: if dv > self.beam_blank_threshold: self.ask('BlankBeam True', verbose=verbose) unblank = True self.ask('SetMagnetDAC {}'.format(v), verbose=verbose) st = time.time() if unprotect or unblank: for i in xrange(50): if not to_bool(self.ask('GetMagnetMoving', verbose=verbose)): break time.sleep(0.25) st = time.time() if unprotect: for d in unprotect: self.ask('ProtectDetector {},Off'.format(d), verbose=verbose) self.ask('GetDeflection {}'.format(d), verbose=verbose) if unblank: self.ask('BlankBeam False', verbose=verbose) change = dv > 1e-7 if change: self._dac = v self.dac_changed = True et = time.time() - st if not self.simulation: if settling_time is None: settling_time = self.settling_time st = settling_time - et self.debug('Magnet settling time: {:0.3f}, actual time: {:0.3f}'.format(settling_time, st)) if st > 0: time.sleep(st) return change
def _switch_factory(self, v_elem, klass=None): if klass is None: klass = HardwareValve name = v_elem.text.strip() address = v_elem.find('address') act_elem = v_elem.find('actuator') description = v_elem.find('description') positive_interlocks = [i.text.strip() for i in v_elem.findall('positive_interlock')] interlocks = [i.text.strip() for i in v_elem.findall('interlock')] if description is not None: description = description.text.strip() actname = act_elem.text.strip() if act_elem is not None else 'switch_controller' actuator = self.get_actuator_by_name(actname) if actuator is None: if not globalv.ignore_initialization_warnings: self.warning_dialog( 'No actuator for {}. Valve will not operate. Check setupfiles/extractionline/valves.xml'.format( name)) qs = True vqs = v_elem.get('query_state') if vqs: qs = vqs == 'true' parent = v_elem.find('parent') parent_name = '' parent_inverted = False if parent is not None: parent_name = parent.text.strip() inverted = parent.find('inverted') if inverted is not None: parent_inverted = to_bool(inverted.text.strip()) check_actuation_enabled = True cae = v_elem.find('check_actuation_enabled') if cae is not None: check_actuation_enabled = to_bool(cae.text.strip()) check_actuation_delay = 0 cad = v_elem.find('check_actuation_delay') if cad is not None: check_actuation_delay = float(cad.text.strip()) st = v_elem.find('settling_time') if st is not None: st = float(st.txt.strip()) hv = klass(name, address=address.text.strip() if address is not None else '', parent=parent_name, parent_inverted=parent_inverted, check_actuation_enabled=check_actuation_enabled, check_actuation_delay=check_actuation_delay, actuator=actuator, description=description, query_state=qs, positive_interlocks=positive_interlocks, interlocks=interlocks, settling_time=st or 0) return name, hv
def _set_use_cdd_warming_text(self, v): self.item.use_cdd_warming = to_bool(v)
def load(self, path): parser = ElementTree(file=open(path, 'r')) circles = parser.find('circles') outline = parser.find('outline') bb = outline.find('bounding_box') bs = bb.find('width'), bb.find('height') w, h = [float(b.text) for b in bs] use_label = parser.find('use_label') if use_label is not None: use_label = to_bool(use_label.text.strip()) else: use_label = True data = ArrayPlotData() p = Plot(data=data, padding=100) p.x_grid.visible = False p.y_grid.visible = False p.x_axis.visible = False p.y_axis.visible = False p.x_axis.title = 'X cm' p.y_axis.title = 'Y cm' # font = 'modern 22' # p.x_axis.title_font = font # p.x_axis.tick_label_font = font # p.y_axis.title_font = font # p.y_axis.tick_label_font = font # p.x_axis_visible = False # p.y_axis_visible = False p.index_range.low_setting = -w / 2 p.index_range.high_setting = w / 2 p.value_range.low_setting = -h / 2 p.value_range.high_setting = h / 2 thetas = linspace(0, 2 * pi) radius = circles.find('radius').text radius = float(radius) face_color = circles.find('face_color') if face_color is not None: face_color = face_color.text else: face_color = 'white' labels = [] for i, pp in enumerate(circles.findall('point')): x, y, l = pp.find('x').text, pp.find('y').text, pp.find('label').text # print i, pp, x, y # load hole specific attrs r = pp.find('radius') if r is None: r = radius else: r = float(r.text) fc = pp.find('face_color') if fc is None: fc = face_color else: fc = fc.text x, y = list(map(float, (x, y))) xs = x + r * sin(thetas) ys = y + r * cos(thetas) xn, yn = 'px{:03d}'.format(i), 'py{:03d}'.format(i) data.set_data(xn, xs) data.set_data(yn, ys) plot = p.plot((xn, yn), face_color=fc, type='polygon')[0] labels.append((x, y, l)) # if use_label: # label = myDataLabel(component=plot, # data_point=(x, y), # label_text=l, # bgcolor='transparent') # plot.overlays.append(label) if use_label: p.overlays.append(LabelsOverlay(component=plot, labels=labels)) self.container.add(p) self.container.invalidate_and_redraw()
def set_motor_lock(self, name, value): m = self.get_motor(name) if m is not None: m.locked = to_bool(value) return True
def get_boolean_preference(self, pid, default=None): return to_bool(self.preferences.get(pid, default))
def set_dac(self, v, verbose=True, settling_time=None): self.debug('setting magnet DAC') self.debug('current : {:0.6f}'.format(self._dac)) self.debug('requested: {:0.6f}'.format(v)) dv = abs(self._dac - v) self.debug('Delta Dac: {:0.6f}'.format(dv)) unprotect = [] unblank = False if self.use_detector_protection: self.debug('Checking detector protection. dv={:0.5f}'.format(dv)) for pd in self.protected_detectors: det = self.spectrometer.get_detector(pd) self.debug( 'Checking detector "{}". Protection Threshold: {} (V)'. format(pd, det.protection_threshold)) if det.protection_threshold and dv > det.protection_threshold: self.ask('ProtectDetector {},On'.format(pd), verbose=verbose) self.ask('GetDeflection {}'.format(pd), verbose=verbose) unprotect.append(pd) if self.use_beam_blank: if dv > self.beam_blank_threshold: self.ask('BlankBeam True', verbose=verbose) unblank = True self.ask('SetMagnetDAC {}'.format(v), verbose=verbose) st = time.time() if unprotect or unblank: for i in xrange(50): if not to_bool(self.ask('GetMagnetMoving', verbose=verbose)): break time.sleep(0.25) st = time.time() if unprotect: for d in unprotect: self.ask('ProtectDetector {},Off'.format(d), verbose=verbose) self.ask('GetDeflection {}'.format(d), verbose=verbose) if unblank: self.ask('BlankBeam False', verbose=verbose) change = dv > 1e-7 if change: self._dac = v self.dac_changed = True et = time.time() - st if not self.simulation: if settling_time is None: settling_time = self.settling_time st = settling_time - et self.debug( 'Magnet settling time: {:0.3f}, actual time: {:0.3f}'. format(settling_time, st)) if st > 0: time.sleep(st) return change
def _assemble_dev_dicts(self): parser = get_parser() for dev in parser.get_elements('device'): name = dev.text.strip() dname = dev.find('name') if dname is None: self.warning('no device name for {}. use a <name> tag'.format(name)) continue denabled = dev.find('use') if denabled is not None: denabled = to_bool(denabled.text.strip()) vs = [] for v in dev.findall('value'): n = v.text.strip() tag = '<{},{}>'.format(name, n) func_name = get_xml_value(v, 'func', 'get') period = get_xml_value(v, 'period', 60) if not period == 'on_change': try: period = int(period) except ValueError: period = 60 enabled = to_bool(get_xml_value(v, 'enabled', False)) record = to_bool(get_xml_value(v, 'record', False)) timeout = get_xml_value(v, 'timeout', 60) threshold = float(get_xml_value(v, 'change_threshold', 1e-10)) units = get_xml_value(v, 'units', '') bindname = get_xml_value(v, 'bind', '') cs = [] conds = v.find('conditionals') if conds is not None: for warn in conds.findall('warn'): cd = {'teststr': warn.text.strip()} set_nfail(warn, cd) cs.append((WARNING, cd)) for critical in conds.findall('critical'): teststr = critical.text.strip() cd = {'teststr': teststr} set_nfail(critical, cd) script = critical.find('script') if script is not None: sname = script.text.strip() if self._validate_script(sname): cd['script'] = sname else: self.warning('Failed to add condition "{}". ' 'Invalid script "scripts/extraction/{}"'.format(teststr, sname)) continue cs.append((CRITICAL, cd)) vd = ({'name': n, 'tag': tag, 'func_name': func_name, 'period': period, 'enabled': enabled, 'threshold': threshold, 'units': units, 'timeout': timeout, 'record': record, 'bindname':bindname}, cs) vs.append(vd) dd = {'name': name, 'device': dname.text.strip(), 'enabled': bool(denabled), 'values': vs} yield dd
def _get_parameters(self, subtree, tag, all_=False, element=False): if subtree is None: print subtree return [d if element else d.text.strip() for d in subtree.findall(tag) if all_ or to_bool(d.get('enabled'))]
def get_managers(self, elem, all_=False, element=False): return [m if element else m.text.strip() for m in elem.findall('manager') if all_ or to_bool(m.get('enabled'))]