def check(self): ''' ''' local_info = None major = None minor = None # get the local version info if os.path.isfile(self.local_path): with open(self.local_path, 'rb') as f: local_info = pickle.load(f) if os.path.isfile(self.src_path): # get the version_info associated with the src code with open(self.src_path, 'rb') as f: f.readline() line = f.readline() major = line.split('=')[1].strip() line = f.readline() minor = line.split('=')[1].strip() self.version_info = VersionInfo(major=major, minor=minor) f.readline() p = [] ps = [] new_para = False for line in f: line = line.strip() if new_para: ps.append(p) p = [] new_para = False if len(line) > 0: if len(p) == 0 and line[0] == '#': line = '<h5><u>{}</u></h5>'.format(line[1:]) p.append(line) else: new_para = True self.version_info.text = \ ''.join(['<p>{}</p>'.format(pj) for pj in [' '.join(pi) for pi in ps if len(pi) > 0]]) if minor is not None and major is not None: mismatch = True if local_info is not None: mismatch = local_info.version != '.'.join((major, minor)) if mismatch: if local_info is not None: self.local_version = local_info.version elif local_info is None: do_later(self.edit_traits, kind='modal')
def _get_component_hook(self, model=None): if model is None: model = self.figure_model rs = [] ts = [] for p in model.panels: ags = [] for pp in p.figures: ag = pp.analysis_group group = pp.options.get_group(pp.group_id) color = group.color ag.color = color ags.append(ag) # ags = [pp.analysis_group for pp in p.figures] if self.plotter_options.show_results_table: r = IdeogramResultsTable(ags, self.plotter_options.nsigma) rs.append(r) if self.plotter_options.show_ttest_table and len(ags) > 1: t = TTestTable(ags) ts.append(t) do_later(self.trait_set, results_tables=rs, ttest_tables=ts)
def _update_editor(self, editor, editor_factory, identifier, aliquot, layout=True, use_date_range=False, calculate_age=False): if editor is None: editor = editor_factory() # if layout: # self.task.split_editors(-2, -1) # else: # if not self._polling: # self.task.activate_editor(editor) #gather analyses tool=None if hasattr(editor, 'search_tool'): tool = editor.search_tool ans = self._get_analyses(tool, identifier, aliquot, use_date_range) ans = self._sort_analyses(ans) if calculate_age: for ai in ans: ai.calculate_age() editor.set_items(ans, update_graph=False) group_analyses_by_key(editor.analyses, 'labnumber') editor.clear_aux_plot_limits() do_later(editor.rebuild) # editor.rebuild() return editor
def _open_individual(self, si): si = self._record_factory(si) if isinstance(si, str): si = self._record_factory(si) else: si.selector = self if not si.initialize(): return sid = si.record_id try: si.load_graph() si.window_x = self.wx si.window_y = self.wy def do(si, sid): self.debug('{}'.format(si)) info = si.edit_traits() self._open_window(sid, info) self.debug('do later open') do_later(do, si, sid) except Exception, e: import traceback traceback.print_exc() self.warning(e)
def open_power_graph(self, rid, path=None): if self.power_graph is not None: self.power_graph.close() del(self.power_graph) g = StreamGraph( window_x=0.01, window_y=0.4, container_dict=dict(padding=5), # view_identifier='pychron.fusions.power_graph' ) self.power_graph = g g.window_title = 'Power Readback - {}'.format(rid) g.new_plot(data_limit=60, scan_delay=1, xtitle='time (s)', ytitle='power (%)', ) g.new_series() if self.record_brightness: g.new_series() do_later(self._open_power_graph, g)
def perform(self, event): app = event.task.window.application kw = {} for attr, prot, msg in (('spectrometer_manager', SPECTROMETER_PROTOCOL, 'Spectrometer Manager'), ('ion_optics_manager', ION_OPTICS_PROTOCOL, 'Ion Optics Manager'), ('el_manager', EL_PROTOCOL, 'Extraction Line Manager')): srv = app.get_service(prot) if not srv: app.warning('No {} available'.format(msg)) return kw[attr] = srv pyscript_task = app.get_task('pychron.pyscript.task', activate=False) if not pyscript_task: app.warning('PyScript Plugin not available') from pychron.spectrometer.auto_mftable import AutoMFTable a = AutoMFTable(pyscript_task=pyscript_task, **kw) do_later(a.do_auto_mftable)
def _current_task_name_changed(self, new): print 'task change {} {}, no_update {}'.format(id(self), new, self._no_update) if self._no_update: return func = getattr(self, 'activate_{}_task'.format(new.lower())) do_later(func)
def app_factory(): ''' assemble the plugins return a Pychron WorkbenchApplication ''' plugins = [ CorePlugin(), WorkbenchPlugin(), PychronWorkbenchPlugin(), PychronWorkbenchUIPlugin(), ] plugins += get_hardware_plugins() plugins += get_user_plugins() app = Pychron(plugins=plugins) gLoggerDisplay.application = app gMessageDisplay.application = app gWarningDisplay.application = app gTraceDisplay.application = app if globalv.open_logger_on_launch: do_later(gLoggerDisplay.open_view, gLoggerDisplay) return app
def _print_results(self): def wrapper(display, *args): display.freeze() display.clear(gui=False) for ai in args: ai(display) display.thaw() def func(): wrapper(self.signal_display, self._print_signals, self._print_baselines ) wrapper(self.ratio_display, self._print_ratios, self._print_blanks ) wrapper(self.summary_display, self._print_summary ) wrapper(self.fit_display, self._print_fits ) do_later(func)
def _update_queue(self, name, new): self.debug('update queue {}={}'.format(name, new)) if self.queue: self.queue.trait_set(**{name: new}) self.queue.changed = True if name == 'repository_identifier': for a in self.queue.automated_runs: a.repository_identifier = new if name == 'mass_spectrometer': self.debug('_update_queue "{}"'.format(new)) self.mass_spectrometer = new self.run_factory.set_mass_spectrometer(new) elif name == 'extract_device': # self._set_extract_device(new) do_later(self._set_extract_device, new) # elif name == 'username': # self._username = new # elif name=='email': # self.email=new # self.queue.username = new self._auto_save()
def _set_message(self, v): if v: self.console = '{}\n{}'.format(self.console, self.format_message(v)) do_later(self.trait_set, message='') cmd = self.process_command(v) if isinstance(cmd, str): self._update_console(cmd)
def _listen(self): self._otime = self.otime while self._alive: time.sleep(1 / self._freq) if self._check(): do_later(self._callback) # self._callback() self._otime = self.otime
def close_valve(self, name, **kw): if not self._close_logic(name): self.debug('logic failed') do_later(self.warning_dialog, 'Close Valve Failed. Prevented by safety logic') return False, False if self.switch_manager: return self.switch_manager.close_switch(name, **kw)
def check(self): ''' ''' local_info = None major = None minor = None # get the local version info if os.path.isfile(self.local_path): with open(self.local_path, 'rb') as f: local_info = pickle.load(f) if os.path.isfile(self.src_path): # get the version_info associated with the pychron code with open(self.src_path, 'rb') as f: f.readline() line = f.readline() major = line.split('=')[1].strip() line = f.readline() minor = line.split('=')[1].strip() self.version_info = VersionInfo(major=major, minor=minor) f.readline() p = [] ps = [] new_para = False for line in f: line = line.strip() if new_para: ps.append(p) p = [] new_para = False if len(line) > 0: if len(p) == 0 and line[0] == '#': line = '<h5><u>{}</u></h5>'.format(line[1:]) p.append(line) else: new_para = True self.version_info.text = \ ''.join(['<p>{}</p>'.format(pj) for pj in [' '.join(pi) for pi in ps if len(pi) > 0]]) if minor is not None and major is not None: mismatch = True if local_info is not None: mismatch = local_info.version != '.'.join((major, minor)) if mismatch: if local_info is not None: self.local_version = local_info.version elif local_info is None: do_later(self.edit_traits, kind='modal')
def show(self, **kw): args = tuple() if not self.initialized: func = self.edit_traits else: func = self.trait_set kw['raised'] = True do_later(func, *args, **kw)
def _open_graph(self, graph=None): def _open(graph): if graph is None: graph = self.graph ui = graph.edit_traits() if self.parent: self.parent.add_window(ui) do_later(_open, graph=graph)
def _reset_connection_label(self, d): def func(): self._connected_label = 'Not Tested' self._connected_color = 'orange' if d: do_later(func) else: func()
def _add_marker_button_fired(self): # self.add_recording_marker() # xs = self.graph.get_data('x0') def do(): xs = self.graph.plots[0].data.get_data('x0') self.record_data_manager.write_to_frame(tuple(' ')) self.graph.add_vertical_rule(xs[-1]) do_later(do)
def do_grapher(args): op = args.o[0] g = Grapher() g.load(args.datafile[0], args.kind[0]) if op: do_later(g.graph.save_pdf, op) g.configure_traits()
def _add_button_fired(self): """ only allow add button to be fired every 0.5s use consumermixin.add_consumable instead of frequency limiting """ self.debug('add run fired') # self.add_consumable(5) do_later(self._add_run)
def _make_alternate_figure(self, evt): self.add_pipeline = True _, name, groups = evt self._set_template(name) self.pipeline.nodes[0].unknowns = [ ai for gi in groups for ai in gi.analyses ] do_later(self.trait_set, run_needed=True)
def activated(self): # self.manager.tray = 'A' # self.manager.irradiation = 'NM-251' # self.manager.level = 'H' # self.manager.labnumber = '61311' if self.manager.setup(): bind_preference(self, 'save_directory', 'pychron.loading.save_directory') else: do_later(self.window.close)
def _test(self): det = self.detector do_later(det.edit_traits) import time time.sleep(1) det.collect_baseline() while 1: do_later(det.get_value, verbose=False) time.sleep(0.25)
def _test_interpolate_one(self): sm = self.stage_map ca = self.canvas h = sm.get_hole('7') args = sm.get_interpolated_position('7') # print args color = (1, 1, 0) if args: nx = args[0] ny = args[1] self.record_interpolation(h, nx, ny, color, dump=False) do_later(ca.invalidate_and_redraw)
def _equilibrate_temp(self, temp, func, st, tol, std): ''' wait until pyrometer temp equilibrated ''' temps = [] # ttemps = [] py = self.laser_manager.pyrometer tc = self.laser_manager.get_device('temperature_monitor') n = 15 self.laser_manager.set_laser_temperature(temp) ctemp = self.laser_manager.map_temperature(temp) # ctemp = self.laser_manager.temperature_controller.map_temperature(temp) while 1: if self._cancel: break sti = time.time() py_t = py.read_temperature(verbose=False) tc_t = tc.read_temperature(verbose=False) # t = time.time() - st do_later(func, py_t, tc_t) temps.append(py_t) # ttemps.append(tc_t) ns = array(temps[-n:]) # ts = array(ttemps[-n:]) if abs(ns.mean() - ctemp) < tol and ns.std() < std: break elapsed = time.time() - sti time.sleep(max(0.0001, min(1, 1 - elapsed))) nn = 30 ptemps = [] ctemps = [] for _ in range(nn): if self._cancel: break sti = time.time() # t = sti - st py_t = py.read_temperature(verbose=False) tc_t = tc.read_temperature(verbose=False) do_later(func, py_t, tc_t) ptemps.append(py_t) ctemps.append(tc_t) elapsed = time.time() - sti time.sleep(max(0.0001, min(1, 1 - elapsed))) return array(ptemps).mean(), array(ctemps).mean()
def _execute_power_calibration_check(self): """ """ g = Graph() g.new_plot() g.new_series() g.new_series(x=[0, 100], y=[0, 100], line_style='dash') do_later(self._open_graph, graph=g) self._stop_signal = TEvent() callback = lambda pi, r: None self._iterate(self.check_parameters, g, False, callback)
def refresh(self): hist = None if self.histories: selh = self.record._dbrecord.selected_histories hist = getattr(selh, self.apply_name) sh = next((hi for hi in self.histories if hi.history == hist), None) def up(): self.oselected_history = sh self.selected_history = None self.selected_history = sh super(HistorySummary, self).build_summary(history=hist) do_later(up)
def _test_interpolate_all(self): sm = self.stage_map ca = self.canvas colors = [(1, 1, 0), (0, 1, 1), (0, 0.75, 1), (0, 0.5, 1), (0, 0.75, 0.75), (0, 0.5, 0.75) ] for j, color in enumerate(colors[:1]): self.info('iteration {}'.format(j + 1)) s = 0 for i in range(60, -1, -1): h = sm.get_hole(str(i + 1)) self.set_current_hole(h) r = random.randint(0, 10) r = 0 if r > 5: nx, ny = self._apply_calibration(h) nx = self._add_error(nx) ny = self._add_error(ny) self.record_correction(h, nx, ny, dump=False) sm.set_hole_correction(h.id, nx, ny) else: kw = dict(cpos=self.center, rotation=self.rotation) if not self.use_calibration: kw['cpos'] = (0, 0) kw['rotation'] = 0 args = sm.get_interpolated_position(h.id, **kw ) if args: s += 1 nx = args[0] ny = args[1] self.record_interpolation(h, nx, ny , color, dump=False) else: if not h.has_correction(): self.record_uncorrected(h) # time.sleep(0.5) # do_later(ca.invalidate_and_redraw) n = 61 - sum([1 for si in sm.sample_holes if si.has_correction()]) self.info('interpolated holes {} - noncorrected {}'.format(s, n)) if not n or not s: break do_later(ca.invalidate_and_redraw) self.dump() self.info('noncorrected holes = {}'.format(n))
def _execute_power_calibration_check(self): ''' ''' g = Graph() g.new_plot() g.new_series() g.new_series(x=[0, 100], y=[0, 100], line_style='dash') do_later(self._open_graph, graph=g) self._stop_signal = TEvent() callback = lambda pi, r: None self._iterate(self.check_parameters, g, False, callback)
def _execute_(self): ca = self.canvas self.clear() sm = self.stage_map sm.clear_correction_file() sm.clear_interpolations() ca.build_map(sm, calibration=[self.center, self.rotation] if self.use_calibration else None ) do_later(ca.invalidate_and_redraw) # set some correction values vs = range(61) # vs.remove(17) # vs.remove(26) # vs.remove(25) # vs.remove(34) # vs.remove(35) # vs.remove(0) # vs.remove(1) # vs.remove(2) # # vs.remove(58) # vs.remove(59) # vs.remove(60) # vs.remove(3) # vs.remove(6) vs.remove(30) # vs = range(50, 60) for i in vs: # for i in [21, 29, 30]: h = sm.get_hole(str(i + 1)) x, y = self._apply_calibration(h) x = self._add_error(x) y = self._add_error(y) # ca.record_correction(h, x, y) # sm.set_hole_correction(h.id, x, y) r = random.randint(0, 10) # r = 7 if r > 6: self.record_correction(h, x, y, dump=False) sm.set_hole_correction(h.id, x, y) # self._test_interpolate_one() self._test_interpolate_all()
def _selected_project_changed(self): self.groups = [] if self.selected_project: gs = [] db = self.db with db.session_ctx(): hists = db.get_interpreted_age_groups(self.selected_project.name) for hi in hists: gs.append(IAGroup(name=hi.name, project=self.selected_project.name, id=int(hi.id), create_date=hi.create_date)) self.groups = gs if gs: self.selected_groups = gs[-1:] do_later(self.trait_set, scroll_to_row=len(gs) - 1)
def _check_detector_protection(self, prev, is_detector): """ return True if magnet move should be aborted @todo: this should be more sophisticated. eg refdet=H1, refiso=Ar40 H1 0 AX 100 L1 0 L2 0 CDD 1 move H1,Ar40 to L2 this would place the 100 on CDD but this algorithm would not catch this problem """ if self.use_detector_safety and self.detector: threshold = self.detector.protection_threshold if threshold: # for di in self.detectors: # print di, di.isotope # find detector that the desired isotope is being measured on det = next((di for di in self.detectors if di.isotope == self.isotope), None) if det: # check that the intensity is less than threshold abort = det.intensity > threshold if abort: if not self.confirmation_dialog( 'Are you sure you want to make this move.\n' 'This will place {} fA on {}'.format( det.intensity, self.detector)): self.debug( 'aborting magnet move {} intensity {} > {}'.format( det, det.intensity, threshold)) if is_detector: do_later(self.trait_set, detector=prev) else: do_later(self.trait_set, isotope=prev) return True
def _check_detector_protection(self, prev, is_detector): """ return True if magnet move should be aborted @todo: this should be more sophisticated. eg refdet=H1, refiso=Ar40 H1 0 AX 100 L1 0 L2 0 CDD 1 move H1,Ar40 to L2 this would place the 100 on CDD but this algorithm would not catch this problem """ if self.use_detector_safety and self.detector: threshold = self.detector.protection_threshold if threshold: # for di in self.detectors: # print di, di.isotope # find detector that the desired isotope is being measured on det = next( (di for di in self.detectors if di.isotope == self.isotope), None) if det: # check that the intensity is less than threshold abort = det.intensity > threshold if abort: if not self.confirmation_dialog( 'Are you sure you want to make this move.\n' 'This will place {} fA on {}'.format( det.intensity, self.detector)): self.debug( 'aborting magnet move {} intensity {} > {}'. format(det, det.intensity, threshold)) if is_detector: do_later(self.trait_set, detector=prev) else: do_later(self.trait_set, isotope=prev) return True
def _selected_project_changed(self): self.groups = [] if self.selected_project: gs = [] db = self.db with db.session_ctx(): hists = db.get_interpreted_age_groups( self.selected_project.name) for hi in hists: gs.append( IAGroup(name=hi.name, project=self.selected_project.name, id=int(hi.id), create_date=hi.create_date)) self.groups = gs if gs: self.selected_groups = gs[-1:] do_later(self.trait_set, scroll_to_row=len(gs) - 1)
def load_experiment_queue(self, path=None, edit=True, saveable=False): # self.bind_preferences() # make sure we have a database connection if not self.test_connections(): return if path is None: path = self.open_file_dialog(default_directory=paths.experiment_dir) if path is not None: self.experiment_queue = None self.experiment_queues = [] # parse the file into individual experiment sets ts = self._parse_experiment_file(path) ws = [] for text in ts: exp = self._experiment_queue_factory(path=path) exp._warned_labnumbers = ws if exp.load(text): self.experiment_queues.append(exp) # # if edit: # exp.automated_run = exp.automated_runs[-1].clone_traits() # exp.set_script_names() ws = exp._warned_labnumbers self._update(all_info=True) self._test() if self.experiment_queues: self.experiment_queue = self.experiment_queues[0] self.start_file_listener(self.experiment_queue.path) def func(): self.set_selector.selected_index = -2 self.set_selector.selected_index = 0 do_later(func) self._load_experiment_queue_hook() self.save_enabled = True return True
def open_image(self, auto_close=True): if self.target_image is not None: self.target_image.close() im = StandAloneImage(title=self.title, view_identifier='pychron.fusions.co2.target' ) self.target_image = im if self.parent is not None: # use a manager to open so will auto close on quit self.parent.open_view(im) if auto_close: minutes = 1 t = Timer(60 * minutes, self.target_image.close) t.start() else: from pyface.timer.do_later import do_later do_later(im.edit_traits)
def run(self, tokens): self.info('Do "Run" script. tokens={}'.format(tokens)) self.debug('.... running ...') if tokens[0] == 'experiment': name, path = self._get_experiment(tokens[1:]) if self.application: def func(): task = self.application.get_task(EXP_ID) if task: if task.open(path): self.console_event='Running experiment "{}"'.format(name) task.execute() else: self.warning('no experiment task available') do_later(func) else: self.debug('no application') self.info('"Run" finished') return True
def object_dclicked_changed(self, info): if info.initialized: do_later(info.ui.dispose, True)
def open_summary_table(self): do_later(self._open_summary_table)
# =============================================================================== # views # =============================================================================== def traits_view(self): v = View(Item('as_series'), Item('delimiter', editor=EnumEditor(values=DELIMITERS)), HGroup(Item('open_button', show_label=False), Item('plot_button', enabled_when='_path', show_label=False), Item('file_name', show_label=False, style='readonly')), Item('data_selectors', show_label=False, editor=ListEditor(mutable=False, style='custom', editor=InstanceEditor())), resizable=True, width=525, height=225, title='CSV Plotter' ) return v if __name__ == '__main__': cs = CSVGrapher() # cs.quick_graph('/Users/ross/Sandbox/scan007.txt') # do_later(cs.quick_graph, '/Users/ross/Sandbox/baselines/scan013.txt') # do_later(cs.quick_graph, '/Users/ross/Sandbox/baselines/scan011.txt') do_later(cs.quick_graph, '/Users/argonlab2/Pychrondata/data/spectrometer_scans/scan017.txt') cs.configure_traits() # ============= EOF =============================================
def post_make(self): self._fix_log_axes() do_later(self.graph.refresh)