def _execute_seek(self, controller, pattern): from pychron.core.ui.gui import invoke_in_main_thread # from pychron.graph.graph import Graph duration = pattern.duration total_duration = pattern.total_duration imgplot, cp = self._setup_seek_graph(pattern) lm = self.laser_manager sm = lm.stage_manager ld = sm.lumen_detector ld.mask_kind = pattern.mask_kind ld.custom_mask = pattern.custom_mask_radius osdp = sm.canvas.show_desired_position sm.canvas.show_desired_position = False st = time.time() self.debug('Pre seek delay {}'.format(pattern.pre_seek_delay)) time.sleep(pattern.pre_seek_delay) self.debug('starting seek') self.debug('total duration {}'.format(total_duration)) self.debug('dwell duration {}'.format(duration)) if pattern.kind == 'DragonFly': self._dragonfly(st, controller, pattern, imgplot, cp) else: self._hill_climber(st, controller, pattern, imgplot, cp) sm.canvas.show_desired_position = osdp invoke_in_main_thread(self._info.dispose)
def block(self, n=3, tolerance=1, progress=None, homing=False): ''' ''' fail_cnt = 0 pos_buffer = [] while not self.parent.simulation: steps = self.load_data_position(set_pos=False) if homing: invoke_in_main_thread(self.trait_set, home_position=steps) if progress is not None: progress.change_message('{} position = {}'.format( self.name, steps), auto_increment=False) if steps is None: fail_cnt += 1 if fail_cnt > 5: break continue pos_buffer.append(steps) if len(pos_buffer) == n: if abs(float(sum(pos_buffer)) / n - steps) < tolerance: break else: pos_buffer.pop(0) time.sleep(0.1) if fail_cnt > 5: self.warning('Problem Communicating')
def block(self, n=3, tolerance=1, progress=None, homing=False): """ """ fail_cnt = 0 pos_buffer = [] while not self.parent.simulation: steps = self.load_data_position(set_pos=False) if homing: invoke_in_main_thread(self.trait_set, homing_position=steps) if progress is not None: progress.change_message('{} position = {}'.format(self.name, steps), auto_increment=False) if steps is None: fail_cnt += 1 if fail_cnt > 5: break continue pos_buffer.append(steps) if len(pos_buffer) == n: if abs(float(sum(pos_buffer)) / n - steps) < tolerance: break else: pos_buffer.pop(0) time.sleep(0.1) if fail_cnt > 5: self.warning('Problem Communicating')
def _wait_for_home(self, progress=None): # wait until homing signal set hbit = 5 if self.home_limit == 1 else 6 psteps = None while 1: steps = self.load_data_position(set_pos=False) invoke_in_main_thread(self.trait_set, homing_position=steps) status = self.read_defined_status() if not self._test_status_byte(status, setbits=[7]): break if self._test_status_byte(status, setbits=[7, hbit]): break if steps == psteps: step_count += 1 else: step_count = 0 if step_count > 10: break psteps = steps time.sleep(0.25) self.debug('wait for home complete')
def get_peak_center(self, ntries=2): self._alive = True self.canceled = False center_dac = self.center_dac self.info('starting peak center. center dac= {} step_width={}'.format(center_dac, self.step_width)) # self.graph = self._graph_factory() width = self.step_width smart_shift = False center = None self.debug('width = {}'.format(width)) for i in range(ntries): if not self.isAlive(): break self._reset_graph() if i == 0: self.graph.add_vertical_rule(self.center_dac, line_style='solid', color='black', line_width=1.5) else: self.graph.add_vertical_rule(center, line_style='solid', color='black', line_width=1.5) start, end = self._get_scan_parameters(i, center, smart_shift) center, smart_shift, success = self.iteration(start, end, width) if success: invoke_in_main_thread(self._post_execute) return center
def run_added_handler(self, last_run_uuid=None): """ add to sys mon series if atype is blank, air, cocktail, background add to atype series else if step heat add to spectrum else add to ideogram """ def func(): #with self.db_lock: self.info('refresh analyses. last UUID={}'.format(last_run_uuid)) proc = self.processor db = proc.db with db.session_ctx(): if last_run_uuid is None: dbrun = db.get_last_analysis(spectrometer=self.conn_spec.system_name) else: dbrun = db.get_analysis_uuid(last_run_uuid) #if last_run_uuid: # dbrun = db.get_analysis_uuid(last_run_uuid) if dbrun: an = proc.make_analysis(dbrun) self._refresh_sys_mon_series(an) self._refresh_figures(an) invoke_in_main_thread(func)
def _run_added_handler(self, last_run_uuid=None): """ add to sys mon series if atype is blank, air, cocktail, background add to atype series else if step heat add to spectrum else add to ideogram """ def func(lr): self._refresh_sys_mon_series() self.info('refresh analyses. last UUID={}'.format(lr)) proc = self.processor db = proc.db with db.session_ctx(): if last_run_uuid is None: dbrun = db.get_last_analysis( spectrometer=self.conn_spec.system_name) else: dbrun = db.get_analysis_uuid(last_run_uuid) self.debug('run_added_handler dbrun={}'.format(dbrun)) if dbrun: self.debug('run_added_handler identifier={}'.format( dbrun.labnumber.identifier)) an = proc.make_analysis(dbrun) self._refresh_figures(an) # self.rebuild() self._lock.release() invoke_in_main_thread(func, last_run_uuid)
def _peak_center(self, setup_kw=None, peak_kw=None): if setup_kw is None: setup_kw = {} if peak_kw is None: peak_kw = {} es = [] for e in self.editor_area.editors: if isinstance(e, PeakCenterEditor): try: es.append(int(e.name.split(' ')[-1])) except ValueError: pass i = max(es) + 1 if es else 1 ret = -1 ion = self.scan_manager.ion_optics_manager self._peak_center_start_hook() time.sleep(2) name = 'Peak Center {:02d}'.format(i) if ion.setup_peak_center(new=True, **setup_kw): self._on_peak_center_start() invoke_in_main_thread(self._open_editor, PeakCenterEditor(model=ion.peak_center, name=name)) ion.do_peak_center(**peak_kw) ret = ion.peak_center_result self._peak_center_stop_hook() return ret
def open_view(self, obj, **kw): def _open(): ui = obj.edit_traits(**kw) self.add_window(ui) from pychron.core.ui.gui import invoke_in_main_thread invoke_in_main_thread(_open)
def _set_motor(self, pos, main=True): if self._data_position != pos or not self._data_position: self.info('setting motor in data space {:0.3f}'.format(float(pos))) self._data_position = pos lm = self.linear_mapper steps = lm.map_steps(pos) hv = 0 hysteresis = self.hysteresis_value if hysteresis: self.do_hysteresis = False if hysteresis < 0: use_hysteresis = self._motor_position > steps else: use_hysteresis = self._motor_position < steps if use_hysteresis: self.do_hysteresis = True self.doing_hysteresis_correction = False hv = hysteresis self._set_motor_position(steps, hv) def launch(): self.timer = self.timer_factory() if main: invoke_in_main_thread(launch) else: launch()
def _refresh_info(self, new): if new: idx = self.automated_runs.index(new[-1]) self.debug('SSSSSSSSSSSSSS set AR scroll to {}'.format(idx)) invoke_in_main_thread( do_later, lambda: self.trait_set(automated_runs_scroll_to_row=idx))
def _set_motor(self, pos, main=True): # print self._data_position, pos if self._data_position != pos or not self._data_position: self.info('setting motor in data space {:0.3f}'.format(float(pos))) self._data_position = pos lm = self.linear_mapper steps = lm.map_steps(pos) hv = 0 hysteresis = self.hysteresis_value if hysteresis: self.do_hysteresis = False if hysteresis < 0: use_hysteresis = self._motor_position > steps else: use_hysteresis = self._motor_position < steps if use_hysteresis: self.do_hysteresis = True self.doing_hysteresis_correction = False hv = hysteresis self._set_motor_position_(steps, hv) def launch(): self.timer = self.timer_factory() if main: invoke_in_main_thread(launch) else: launch()
def _poll(self, last_run_uuid): self._polling = True sub = self.subscriber db_poll_interval = self._db_poll_interval poll_interval = self._poll_interval st = time.time() while 1: #only check subscription availability if one poll_interval has elapsed #sinde the last subscription message was received #check subscription availability if time.time() - sub.last_message_time > poll_interval: if sub.check_server_availability(timeout=0.5, verbose=True): if not sub.is_listening(): self.info('Subscription server now available. starting to listen') self.subscriber.listen() else: if sub.was_listening: self.warning('Subscription server no longer available. stop listen') self.subscriber.stop() if self._wait(poll_interval): if not sub.is_listening(): if time.time() - st > db_poll_interval: st = time.time() lr = self._get_last_run_uuid() self.debug('current uuid {} <> {}'.format(last_run_uuid, lr)) if lr != last_run_uuid: last_run_uuid = lr invoke_in_main_thread(self.run_added_handler, lr) else: break
def _loop2(self, n, d): invoke_in_main_thread(self._build_graph, n, d,) for i in range(100): if i % 10 == 0: print '{} {}'.format(i, get_current_mem()) time.sleep(0.1)
def run_added_handler(self, last_run_uuid=None): """ add to sys mon series if atype is blank, air, cocktail, background add to atype series else if step heat add to spectrum else add to ideogram """ def func(): #with self.db_lock: self.info('refresh analyses. last UUID={}'.format(last_run_uuid)) proc = self.processor db = proc.db with db.session_ctx(): if last_run_uuid is None: dbrun = db.get_last_analysis( spectrometer=self.conn_spec.system_name) else: dbrun = db.get_analysis_uuid(last_run_uuid) #if last_run_uuid: # dbrun = db.get_analysis_uuid(last_run_uuid) if dbrun: an = proc.make_analysis(dbrun) self._refresh_sys_mon_series(an) self._refresh_figures(an) invoke_in_main_thread(func)
def _run_added_handler(self, last_run_uuid=None): """ add to sys mon series if atype is blank, air, cocktail, background add to atype series else if step heat add to spectrum else add to ideogram """ def func(lr): self._refresh_sys_mon_series() self.info('refresh analyses. last UUID={}'.format(lr)) proc = self.processor db = proc.db with db.session_ctx(): if last_run_uuid is None: dbrun = db.get_last_analysis(spectrometer=self.conn_spec.system_name) else: dbrun = db.get_analysis_uuid(last_run_uuid) self.debug('run_added_handler dbrun={}'.format(dbrun)) if dbrun: self.debug('run_added_handler identifier={}'.format(dbrun.labnumber.identifier)) an = proc.make_analysis(dbrun) self._refresh_figures(an) # self.rebuild() self._lock.release() invoke_in_main_thread(func, last_run_uuid)
def set_run_inprogress(self, aid): run = self._find_run(aid) # using the no_update ctx manager was not working # have to manually toggle _no_update self._no_update = True if run is not None: self.automated_runs.remove(run) self.executed_runs.append(run) idx = len(self.executed_runs) - 1 # self.trait_set(executed_runs_scroll_to_row=idx) # do_later(self.trait_set, executed_runs_scroll_to_row=idx) # invoke_in_main_thread(do_later, lambda:self.trait_set(executed_runs_scroll_to_row=idx)) invoke_in_main_thread( do_later, lambda: self.trait_set(executed_runs_scroll_to_row=idx)) # invoke_in_main_thread(self.trait_set, executed_runs_scroll_to_row=idx) self.debug( '$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ set ex scroll to {}' .format(idx)) else: self.debug('Problem removing {}'.format(aid)) self._no_update = False
def stop(self): self.debug('stop') self.dump() if self._lum_evt: self._lum_evt.set() if self._info: invoke_in_main_thread(self._info.dispose, abort=True)
def run_with_except_hook(*args, **kw): try: run_old(*args, **kw) except (KeyboardInterrupt, SystemExit): raise except: from pychron.core.ui.gui import invoke_in_main_thread invoke_in_main_thread(sys.excepthook, *sys.exc_info())
def _show_pane(self, p): #if not self.suppress_pane_change: def _show(): ctrl = p.control if not p.visible: ctrl.show() ctrl.raise_() invoke_in_main_thread(_show)
def add_text(self, txt, color, force=False, **kw): ''' if txt,color same as previous txt,color than message only added if force=True ''' # ms = self.messages[-self.max_messages:] # ms.append((txt, color)) # self.message = (txt, color, force) self.qmessage.put((txt, color, force)) invoke_in_main_thread(self.trait_set, refresh=True)
def _do_hop(self): """ is it time for a magnet move """ # try: cycle, dets, isos, defls, settle, count = self.hop_generator.next() # except StopIteration: # return #update the iso/det in plotpanel # self.plot_panel.set_detectors(isos, dets) detector = dets[0] isotope = isos[0] # self.debug('c={} pc={} nc={}'.format(cycle, self.plot_panel.ncycles, self.ncycles)) if self.plot_panel.ncycles!=self.ncycles: if cycle >= self.plot_panel.ncycles: self.info('user termination. measurement iteration executed {}/{} cycles'.format(cycle, self.ncycles)) self.stop() return elif cycle>=self.ncycles: return if count == 0: #set deflections # only set deflections deflections were changed or need changing deflect = len([d for d in defls if d is not None]) if deflect or self._was_deflected: self._was_deflected = False for det, defl in zip(dets, defls): #use the measurement script to set the deflections #this way defaults from the config can be used if defl is None: defl = '' else: self._was_deflected = True self.measurement_script.set_deflection(det, defl) self.parent.set_magnet_position(isotope, detector, update_detectors=False, update_labels=False, update_isotopes=True, remove_non_active=False) msg = 'delaying {} for detectors to settle after peak hop'.format(settle) self.parent.wait(settle, msg) self.debug(msg) d = self.parent.get_detector(detector) # self.debug('cycle {} count {} {}'.format(cycle, count, id(self))) if self.plot_panel.is_baseline: isotope = '{}bs'.format(isotope) invoke_in_main_thread(self.plot_panel.trait_set, current_cycle='{} cycle={} count={}'.format(isotope, cycle + 1, count + 1), current_color=d.color) return dets, isos
def view_image(im, auto_close=True): def _func(): open_view(im) if auto_close: minutes = 2 t = Timer(60 * minutes, im.close_ui) t.start() invoke_in_main_thread(_func)
def _execute_lumen_degas(self, controller, pattern): from pychron.core.pid import PID from pychron.core.ui.gui import invoke_in_main_thread from pychron.lasers.pattern.mv_viewer import MVViewer from pychron.graph.stream_graph import StreamStackedGraph from pychron.mv.mv_image import MVImage lm = self.laser_manager sm = lm.stage_manager g = StreamStackedGraph() img = MVImage() img.setup_images(2, sm.get_frame_size()) mvviewer = MVViewer(graph=g, image=img) mvviewer.edit_traits() # g.edit_traits() g.new_plot(xtitle='Time', ytitle='Lumens') g.new_series() g.new_plot(xtitle='Time', ytitle='Error') g.new_series(plotid=1) g.new_plot(xtitle='Time', ytitle='Power') g.new_series(plotid=2) duration = pattern.duration lumens = pattern.lumens dt = pattern.period st = time.time() pid = PID() def update(c, e, o, cs, ss): g.record(c, plotid=0) g.record(e, plotid=1) g.record(o, plotid=2) img.set_image(cs, 0) img.set_image(ss, 1) while self._alive: if duration and time.time() - st > duration: break with PeriodCTX(dt): csrc, src, cl = sm.get_brightness() err = lumens - cl out = pid.get_value(err, dt) lm.set_laser_power(out) invoke_in_main_thread(update, (cl, err, out, csrc, src))
def message(self, msg): from pychron.displays.gdisplays import gMessageDisplay if not gMessageDisplay.opened and not gMessageDisplay.was_closed: gMessageDisplay.opened = True invoke_in_main_thread(gMessageDisplay.edit_traits) gMessageDisplay.add_text(msg) self.info(msg)
def _degas(self, lumens, pid): self.lumens = lumens g = self.stream_graph img = self.img_graph.plots[0] ld = self.laser_manager.stage_manager.lumen_detector def update(c, e, o, src, targets): g.record(c, plotid=0) g.record(e, plotid=1) g.record(o, plotid=2) if src.dtype == uint16: src = src.astype('uint32') src = src / 4095 * 255 src = src.astype('uint8') imgdata = gray2rgb(src) ld.draw_targets(imgdata, targets) img.data.set_data('imagedata', imgdata) evt = self._lum_evt set_laser_power = self.laser_manager.set_laser_power_hook ld.reset() get_brightness = self.laser_manager.get_brightness target = self.lumens prev = 0 sst = time.time() while not evt.is_set(): dt = pid.kdt st = time.time() src, current, targets = get_brightness(threshold=self.threshold) err = target - current out = pid.get_value(err) or 0 invoke_in_main_thread(update, current, err, out, src, targets) if abs(prev - out) > 0.02: self.debug('set power output={}'.format(out)) set_laser_power(out) prev = out if time.time() - sst > 10: sst = time.time() ld.reset() et = time.time() - st t = dt - et if t > 0: evt.wait(dt)
def _test(self): p = '/Users/ross/Pychrondata_demo/data/snapshots/scan6/007.jpg' g = Graph() g.new_plot() for scan_i, z, idxs in [ # 1, # 2, # 3, 4, 5, # (6, [20, 30, 40, 50, 60, 70, 80, 90, 100, ], # [2, 3, 4, 5, 6, 7, 8, 9, 10] # ), (6, [10], [1] ), # (6, [100, 90, 80, 70, 60, 50, 40, 30, 20], # [11, 12, 13, 14, 15, 16, 17, 18, 19] # ) ]: dxs = [] zs = [] root = '/Users/ross/Pychrondata_demo/data/snapshots/scan{}'.format(scan_i) for zi, idx in zip(z, idxs): pn = os.path.join(root, '{:03n}.jpg'.format(idx)) d = load_image(pn) dx = self._calculate_spacing(d) dxs.append(dx) zs.append(zi) g.new_series(zs, dxs, type='scatter') coeffs = polyfit(zs, dxs, 2) print 'parabolic intercept {}'.format(coeffs[-1]) xs = linspace(0, max(zs)) ys = polyval(coeffs, xs) g.new_series(xs, ys) fitfunc = lambda p, x: p[0] * exp(p[1] * x) + p[2] lr = LeastSquaresRegressor(fitfunc=fitfunc, initial_guess=[1, 0.1, 0], xs=zs, ys=dxs ) xs = linspace(0, max(zs)) ys = lr.predict(xs) print 'exponential intercept {}'.format(lr.predict(0)) g.new_series(xs, ys) invoke_in_main_thread(g.edit_traits)
def _flash_loop(self): while 1: if self._gen: t, state, label, color = next(self._gen) invoke_in_main_thread(self.trait_set, color=color, label=label) else: invoke_in_main_thread(self.trait_set, label='') break time.sleep(t) self._flash_daemon = None
def _consume(self, timeout): bt = self._buftime if bt: bt = bt / 1000. def get_func(): q = self._consumer_queue v = None while 1: try: v = q.get(timeout=bt) except Empty: break return v else: def get_func(): try: return self._consumer_queue.get(timeout=1) except Empty: return cfunc = self._consume_func st = time.time() while self._should_consume: if timeout: if time.time() - st > timeout: self._should_consume = False self._consumer_queue = None print 'consumer time out' break try: v = get_func() if v: if cfunc: if self._main: from pychron.core.ui.gui import invoke_in_main_thread invoke_in_main_thread(cfunc, v) else: cfunc(v) elif isinstance(v, tuple): func, a = v if self._main: from pychron.core.ui.gui import invoke_in_main_thread invoke_in_main_thread(func, a) else: func(a) except Exception, e: import traceback traceback.print_exc()
def power_map(self, *args, **kw): self._task = None self.debug('Opening power map task') invoke_in_main_thread(self._open_power_map, *args) # wait until task is opened while self._task is None: time.sleep(0.5) self._task.execute_active_editor(block=True) self.debug('power mapping complete')
def _auto_calibrate(self, calibration, center_hole, center_guess): npos, corrected = self._autocenter(center_hole, center_guess) if not corrected: invoke_in_main_thread( self.warning_dialog, 'Failed to located center hole. Try SemiAutoCalibration') self._warned = False self.calibration_step = 'Calibrate' self.calibration_enabled = True else: super(AutoCalibrator, self)._auto_calibrate(calibration)
def _consumer(self, prog, mq): while self._alive: if prog.canceled: self._alive = False break try: msg = mq.get(timeout=0.1) invoke_in_main_thread(prog.change_message, msg) except Empty: pass prog.close()
def _wait(self, delay, msg): wg = self.wait_group wc = self.get_wait_control() # wc = wg.active_control invoke_in_main_thread(wc.trait_set, wtime=delay, message=msg) # wc.trait_set(wtime=delay, # # message=msg # ) time.sleep(0.1) wc.reset() wc.start() wg.pop(wc)
def _timeout_loop(self, timeout, evt): st = time.time() while not evt.is_set(): time.sleep(0.25) if timeout: et = time.time() - st - 1 if et > timeout - 1: invoke_in_main_thread(self.destroy) return self.timeout_return_code if self.control: t = '{}\n\nTimeout in {:n}s'.format(self.message, int(timeout - et)) invoke_in_main_thread(self.control.setText, t)
def update_editor(self): image = self.factory.image if image is None: image = self.value qsize = self.image_ctrl.size() if self.factory.scale: w = qsize.width() else: w = None invoke_in_main_thread(self.set_pixmap, image, w)
def _loop(self, n, d): mem_log('<loop start') invoke_in_main_thread(self._build_graph, n, d,) self._iter_event = Event() self._iter_event.wait(0.1) self._iter(n, d) # time.sleep(10) self._iter_event.wait(n * 1.1) mem_log('> loop finished')
def _show_pane(self, p): def _show(): ctrl = p.control if ctrl: if not p.visible: ctrl.show() ctrl.raise_() else: self.debug('No control for pane={}'.format(p.id)) if p: # self.debug('$$$$$$$$$$$$$ show pane {}'.format(p.id)) invoke_in_main_thread(do_later, _show)
def create(self, dets): """ dets: list of Detector instances """ self.detectors = dets evt = Event() invoke_in_main_thread(self._create, evt) # wait here until _create finishes while not evt.is_set(): time.sleep(0.05)
def execute(self, block=False, duration=None, thread_safe=True): """ if block is true wait for patterning to finish before returning """ if not self.pattern: return self.start(show=self.show_patterning) evt = None # if current_thread().name != 'MainThread': if thread_safe: evt = Event() invoke_in_main_thread(self._pre_execute, evt) while not evt.is_set(): time.sleep(0.05) else: self._pre_execute(evt) self.debug('execute xy pattern') xyp = self.pattern.xy_pattern_enabled if duration: self.pattern.external_duration = float(duration) if xyp: self._xy_thread = Thread(target=self._execute_xy_pattern) self._xy_thread.start() pp = self.pattern.power_pattern if pp: self.debug('execute power pattern') self._power_thread = Thread(target=self._execute_power_pattern) self._power_thread.start() zp = self.pattern.z_pattern if zp: self.debug('execute z pattern') self._z_thread = Thread(target=self._execute_z_pattern) self._z_thread.start() if block: if self._xy_thread: self._xy_thread.join() if self._z_thread: self._z_thread.join() if self._power_thread: self._power_thread.join() self.finish()