def default_traits_view(self): """ Returns the default view to use for this class. """ # NOTE: I moved the view to this method so we can declare a handler # for the view. Alternatively, we could move the DemoController class # to the top and declare view=Instance(HasTraits) instead. traits_view = View( Item( 'plot', editor=ComponentEditor(), show_label=False, ), menubar=MenuBar( Menu( Action(name="Save Plot", action="save"), # see Controller for Action(name="Load Plot", action="load"), # these callbacks Separator(), CloseAction, name="File", ), ), width=600, height=600, resizable=True, handler=DemoController) return traits_view
def launch_viewer(sources=None): '''Create the plot window''' if sources is None: sources = [] if not isinstance(sources, (list, tuple)): sources = [sources] h = -20 info_pane = Item('ipane', show_label=False, resizable=False) plot_window = VGroup( spring, HGroup(Item('displayed_fields', show_label=False), spring, Item('displayed_files', show_label=False), spring, Item('frame_first', show_label=False), Item('frame_prev', show_label=False), Item('frame_next', show_label=False), Item('frame_last', show_label=False), Item('sfstr', show_label=False, editor=TitleEditor())), HGroup( VGroup( Item('plotu', show_label=False), Item('plotd', show_label=False), Item('plotcu', show_label=False), Item('plotcd', show_label=False), Item('plotscale', show_label=False), Item('plotpts', show_label=False), '_', #Item('plotf', show_label=False), Item('plotana', show_label=False), '_', Item('plotp', show_label=False)), VGroup( Item('plotter', show_label=False, springy=True, resizable=True, width=900, height=600)))) menubar = MenuBar( Menu(Action(name='Open Output Database', action='open_file'), Action(name='Take Screenshot', action='print_screen'), Action(name='Quit', action='quit'), name='File'), Menu(name='Edit'), Menu(Action(name='Plot Analytic Function', action='plot_analytic'), Action(name='Field Variable', action='change_field'), Action(name='Scale', action='adjust_plot_scales'), name='Plot Options'), Menu(name='Help')) toolbar = None title = "Viewer" view = View(HSplit(info_pane, plot_window), style='custom', resizable=True, title=title, menubar=menubar, toolbar=toolbar) main_window = Application(sources=sources) main_window.configure_traits(view=view, handler=ApplicationHandler) return main_window
class MainUi(HasTraits): traits_view = View( resizable=True, width=600, height=400, menubar=MenuBar(Menu(CloseAction, name='&File'), ), )
def default_menubar(self): return MenuBar( Menu(Action(name="&Open", action="load_run"), Action(name="&Save", action="save_run"), Action(name="&Exit", action="exit"), name="&File"), Menu(Action(name="About PStudy", action="about_pstudy"), HelpAction, name="Help"))
class ModelView(HasTraits): model = Instance(Model) view = Instance(PlotUI) traits_view = View(Item('@view', show_label=False), menubar=MenuBar( Menu(Action(name="Edit Model", action="edit_model"), Action(name="Edit Plot", action="edit_plot"), CloseAction, name="File")), handler=Controller, title="Function Inspector", resizable=True) @on_trait_change('model, view') def update_view(self): if self.model is not None and self.view is not None: self.view.update(self.model)
class DialogWithToolbar(HasTraits): """Test dialog with toolbar and menu.""" action_successful = Bool(False) def test_clicked(self): self.action_successful = True menubar = MenuBar(Menu(ActionGroup(TestAction), name='&Test menu'), ) toolbar = ToolBar(ActionGroup(TestAction), ) traits_view = View( Item(label="Click the button on the toolbar or the menu item.\n" "The 'Action successful' element should turn to True."), Item('action_successful', style='readonly'), menubar=menubar, toolbar=toolbar, buttons=['OK'])
class DialogWithToolbar(HasTraits): """Test dialog with toolbar and menu.""" action_successful = Bool(False) def test_clicked(self): print("perform action") self.action_successful = True menubar = MenuBar(Menu(ActionGroup(TestAction), name="&Test menu")) toolbar = ToolBar(ActionGroup(TestAction)) traits_view = View( Item(label="Click the button on the toolbar or the menu item.\n" "The 'Action successful' element should turn to True."), Item("action_successful", style="readonly"), menubar=menubar, toolbar=toolbar, buttons=[TestAction, "OK"], )
class Temperature_Sensor(ManagedJob, GetSetItemsMixin): keep_data = Bool( False) # helper variable to decide whether to keep existing data temperature = Array() vremya = Array() sleep_time = Range(low=0., high=3600., value=300., desc='periodicity of measurements', label='interval [s]', mode='text', auto_set=False, enter_set=True) plot_data = Instance(ArrayPlotData) temperature_plot = Instance(Plot, editor=ComponentEditor()) voltage = Range(low=0., high=12., value=12.0, desc='Voltage [V]', label='Voltage [V]', mode='text', auto_set=False, enter_set=True) current = Range(low=0., high=2., value=3.0, desc='Current [A]', label='Current [A]', mode='text', auto_set=False, enter_set=True) limiting_voltage = Range(low=0., high=70., value=20.0, desc='Voltage [V]', label='limiting voltage [V]', mode='text', auto_set=False, enter_set=True) limiting_current = Range(low=0., high=10., value=4.0, desc='Current [A]', label='limiting current [A]', mode='text', auto_set=False, enter_set=True) set_limiting_current_button = Button(label='set limiting curent', desc='set limiting current') set_limiting_voltage_button = Button(label='set limiting curent', desc='set limiting current') set_current_button = Button(label='set current', desc='set current') set_voltage_button = Button(label='set voltage', desc='set voltage') stop_heating_button = Button(label='swich heating off', desc='swich off heating') perform_fit = Bool(False, label='perform fit') fit_result = Array(value=np.array((np.nan, np.nan, np.nan, np.nan))) def __init__(self): super(Temperature_Sensor, self).__init__() self._create_temperature_plot() self.on_trait_change(self._update_plot_data, 'temperature, perform_fit', dispatch='ui') self.on_trait_change(self._update_fit, 'temperature, perform_fit', dispatch='ui') self.on_trait_change(self._update_plot_fit, 'fit_result', dispatch='ui') def _run(self): logging.getLogger().debug("trying run") try: self.state = 'run' k = 0 while True: for i in range(10): buffer = ser.readline() if len(buffer) == 49: temperature = float(buffer[40:45]) c = time.strftime('%H:%M:%S') vremya = float( c[0:2]) + float(c[3:5]) / 60 + float(c[6:8]) / 3600 self.temperature = np.append(self.temperature, temperature) self.vremya = np.append(self.vremya, vremya) time.sleep(self.sleep_time) if threading.currentThread().stop_request.isSet(): break self.state = 'done' except: logging.getLogger().exception('Error in temperature sensor') self.state = 'error' # plotting ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ def _update_plot_data(self): self.plot_data.set_data('time', self.vremya) self.plot_data.set_data('temperature', self.temperature) def _create_temperature_plot(self): plot_data = ArrayPlotData(time=np.array((0., 1.)), temperature=np.array((0., 40.)), fit=np.array((0., 0.))) plot = Plot(plot_data, width=50, height=40, padding=8, padding_left=64, padding_bottom=32) plot.plot(('time', 'temperature'), color='green') plot.index_axis.title = 'time [h]' plot.value_axis.title = 'temperature [C]' self.plot_data = plot_data self.temperature_plot = plot return self.temperature_plot def save_temperature_plot(self, filename): self.save_figure(self.temperature_plot, filename + '.png') self.save(filename + 'TPlot_' + '_V=' + string.replace(str(self.voltage), '.', 'd') + '.pyd') # fitting--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _perform_fit_changed(self, new): plot = self.temperature_plot if new: plot.plot(('time', 'fit'), style='line', color='red', name='fit') else: plot.delplot('fit') plot.request_redraw() def _update_fit(self): if self.perform_fit: try: p = fitting.fit_exp_raise(self.vremya, self.temperature, 0.5) except Exception: logging.getLogger().debug('temperature fit failed.', exc_info=True) p = np.nan * np.empty(4) else: p = np.nan * np.empty(4) self.fit_result = p def _update_plot_fit(self): if not np.isnan(self.fit_result[0]): self.plot_data.set_data( 'fit', fitting.ExponentialTemperatureSaturation(*self.fit_result[0])( self.vremya)) #self.decay_time=self.fit_result[0][0]*1e-3 Tsat, a, tau, T0 # heating system-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _set_limiting_current_button_fired(self): power_supply._set_limiting_current(self.limiting_current) def _set_limiting_voltage_button_fired(self): power_supply._set_limiting_voltage(self.limiting_voltage) def _set_current_button_fired(self): power_supply._set_current(self.current) def _set_voltage_button_fired(self): power_supply._set_voltage(self.voltage) def _stop_heating_button_fired(self): power_supply._set_current(0) power_supply._set_voltage(0) def submit(self): """Submit the job to the JobManager.""" self.keep_data = False ManagedJob.submit(self) print threading.currentThread().getName() traits_view = View(VGroup( HGroup(Item('submit_button', show_label=False), Item('remove_button', show_label=False), Item('state', style='readonly'), Item('sleep_time', width=-70, format_str='%.f'), Item('current', width=-40), Item('set_current_button', show_label=False), Item('voltage', width=-40), Item('set_voltage_button', show_label=False), Item('limiting_current', width=-40), Item('set_limiting_current_button', show_label=False), Item('limiting_voltage', width=-40), Item('set_limiting_voltage_button', show_label=False), Item('stop_heating_button', show_label=False), Item('perform_fit')), HGroup(Item('temperature_plot', show_label=False, resizable=True)), ), menubar=MenuBar( Menu(Action(action='saveTemperaturePlot', name='Save Temperature Plot'), Action(action='load', name='Load'), name='File')), title='Temperature control', width=1380, height=750, buttons=[], resizable=True, handler=SensorHandler) get_set_items = ['temperature', 'vremya', '__doc__']
class tcWindow(HasTraits): project = tcProject plot = tcPlot assert True, "tcWindow" def __init__(self, project): self.project = project self.plot = create_timechart_container(project) self.plot_range_tools = self.plot.range_tools self.plot_range_tools.on_trait_change(self._selection_time_changed, "time") self.trait_view().title = self.get_title() def get_title(self): if self.project.filename == "dummy": return "PyTimechart: Please Open a File" return "PyTimechart:" + self.project.filename # Create an action that exits the application. status = Str("Welcome to PyTimechart") traits_view = View( HSplit( VSplit( Item('project', show_label=False, editor=InstanceEditor(view='process_view'), style='custom', width=150), # Item('plot_range_tools', show_label = False, editor=InstanceEditor(view = 'selection_view'), style='custom',width=150,height=100) ), Item('plot', show_label=False, editor=ComponentEditor()), ), toolbar=ToolBar(*_create_toolbar_actions(), image_size=(24, 24), show_tool_names=False), menubar=MenuBar(*_create_menubar_actions()), statusbar=[ StatusItem(name='status'), ], resizable=True, width=1280, height=1024, handler=tcActionHandler()) def _on_open_trace_file(self): if open_file(None) and self.project.filename == "dummy": self._ui.dispose() def _on_view_properties(self): self.plot.options.edit_traits() def _on_exit(self, n=None): self.close() sys.exit(0) def close(self, n=None): pass def _on_about(self): aboutBox().edit_traits() def _on_doc(self): browse_doc() def _selection_time_changed(self): self.status = "selection time:%s" % (self.plot_range_tools.time)
menu_bar = MenuBar( Menu(Action(name='New', action='new_action'), Action(name='Open', action='open_action'), Action(name='Save As', action='saveas_action'), Action(name='Exit', action='exit_action'), name='File'), Menu(Action(name='Init / Restart', action='init_action'), name='Start'), Menu( #Action(name='Show original image',action='showimg_action',enabled_when='pass_init'), Action(name='High pass filter', action='highpass_action', enabled_when='pass_init'), Action(name='Image coord', action='img_coord_action', enabled_when='pass_init'), Action(name='Correspondences', action='corresp_action', enabled_when='pass_init'), name='Preprocess'), Menu(Action(name='3D positions', action='threed_positions'), name='3D Positions'), Menu( Action(name='Create calibration', action='calib_action'), #,enabled_when='pass_init'), name='Calibration'), Menu(Action(name='Sequence without display', action='sequence_action', enabled_when='pass_init'), name='Sequence'), Menu(Action(name='Detected Particles', action='detect_part_track', enabled_when='pass_init'), Action(name='Tracking without display', action='track_no_disp_action', enabled_when='pass_init'), Action(name='Tracking with display', action='track_disp_action', enabled_when='pass_init'), Action(name='Tracking backwards', action='track_back_action', enabled_when='pass_init'), Action(name='Show trajectories', action='traject_action', enabled_when='pass_init'), name='Tracking'), Menu(Action(name='Configure tracking/sequence', action='plugin_action'), name='Plugins'), Menu(Action(name='Run multigrid demo', action='multigrid_demo'), name='Demo'), )
def trait_view(self, name='default'): file_menu = Menu( ActionGroup(Action(name='New \t Ctrl+N', action='new'), Action(name='Open \t Ctrl+O', action='open'), Action(name='Close \t Ctrl+W', action='close_tab')), ActionGroup(Action(name='Save \t Ctrl+S', action='save'), Action(name='Save As', action='saveAs')), ActionGroup(Action(name='Exit \t Ctrl+Q', action='exit')), name='File') edit_menu = Menu( ActionGroup(Action(name='Undo \t Ctrl+Z', action='undo'), Action(name='Redo \t Ctrl+Y', action='redo')), ActionGroup(Action(name='Cut \t Ctrl+X', action='cut'), Action(name='Copy \t Ctrl+C', action='copy'), Action(name='Paste \t Ctrl+V', action='paste')), ActionGroup( Action(name='Select All \t Ctrl+A', action='select_all')), name='Edit') search_menu = Menu(ActionGroup( Action(name='Find \t Ctrl+F', action='enable_find'), Action(name='Replace \t Ctrl+R', action='enable_replace')), name='Search') view_menu = Menu(ActionGroup( Action(name='Toggle File Browser', action='toggle_file_browser')), name='View') prefs_menu = Menu(Action(name='Sync view on change', action='toggle_sync_on_change', checked=self.sync_on_change, style='toggle'), Action(name='Auto fix table', action='toggle_auto_table_fix', checked=self.auto_table_fix, style='toggle'), Action(name='Use Sphinx', action='toggle_sphinx', checked=self.use_sphinx, style='toggle'), Action(name='Set Sphinx resources path...', action='change_sphinx_static_path'), Action(name='Change font', action='change_font'), name='Preferences') help_menu = Menu(Action(name='About', action='about'), name='Help') convert_menu = Menu(Action(name='Docutils - HTML', action='docutils_rst2html'), Action(name='Docutils - LaTeX', action='docutils_rst2latex'), Action(name='Sphinx - HTML', action='sphinx_rst2html'), Action(name='rst2pdf', action='rst2pdf'), name='Convert') menu_bar = MenuBar(file_menu, edit_menu, search_menu, view_menu, prefs_menu, convert_menu, help_menu) ######################################################################## file_group = ActionGroup( Action(tooltip='New', action='new', image=ImageResource('new')), Action(tooltip='Open', action='open', image=ImageResource('open')), Action(tooltip='Save', action='save', image=ImageResource('save')), Action(tooltip='Save As', action='saveAs', image=ImageResource('save-as')), Action(tooltip='Close', action='close_tab', image=ImageResource('close'))) edit_group = ActionGroup( Action(tooltip='Cut', action='cut', image=ImageResource('cut')), Action(tooltip='Copy', action='copy', image=ImageResource('copy')), Action(tooltip='Paste', action='paste', image=ImageResource('paste'))) undo_group = ActionGroup( Action(tooltip='Undo', action='undo', image=ImageResource('undo')), Action(tooltip='Redo', action='redo', image=ImageResource('redo'))) search_group = ActionGroup( Action(tooltip='Find', action='enable_find', image=ImageResource('find')), Action(tooltip='Replace', action='enable_replace', image=ImageResource('replace'))) markup_group = ActionGroup( Action(tooltip='Bold', action='bold', image=ImageResource('bold')), Action(tooltip='Italic', action='italic', image=ImageResource('italic')), Action(tooltip='Inline Literal', action='inline_literal', image=ImageResource('literal')), Action(tooltip='Fix underline (Ctrl+D)', action='fix_underline', image=ImageResource('underline')), Action(tooltip='Fix underline and overline (Ctrl+Shift+D)', action='fix_under_overline', image=ImageResource('under-over'))) sync_group = ActionGroup( Action(tooltip='Sync rst2html', action='sync_scrollbar_rst2html', image=ImageResource('sync_rst2html')), Action(tooltip='Sync html2rst', action='sync_scrollbar_html2rst', image=ImageResource('sync_html2rst'))) tool_bar = ToolBar(file_group, edit_group, undo_group, search_group, markup_group, sync_group) ################################## key_bindings = KeyBindings( KeyBinding(binding1='Ctrl-n', method_name='new'), KeyBinding(binding1='Ctrl-o', method_name='open'), KeyBinding(binding1='Ctrl-s', method_name='save'), KeyBinding(binding1='Ctrl-w', method_name='close_tab'), KeyBinding(binding1='Ctrl-q', method_name='exit'), KeyBinding(binding1='Ctrl-d', method_name='fix_underline'), KeyBinding(binding1='Ctrl-Shift-d', method_name='fix_under_overline'), # The following are identical to the already set hotkeys in # the source editor. We just want them to work regardless of # whether the editor has focus. KeyBinding(binding1='Ctrl-z', method_name='undo'), KeyBinding(binding1='Ctrl-y', method_name='redo'), KeyBinding(binding1='Ctrl-x', method_name='cut'), KeyBinding(binding1='Ctrl-c', method_name='copy'), KeyBinding(binding1='Ctrl-v', method_name='paste'), KeyBinding(binding1='Ctrl-a', method_name='select_all'), KeyBinding(binding1='Ctrl-f', method_name='enable_find'), KeyBinding(binding1='Ctrl-r', method_name='enable_replace')) return View(Group(Item('_tree', style='custom', width=0.25, editor=InstanceEditor()), Item('open_views', style='custom', editor=ListEditor(use_notebook=True, deletable=True, dock_style='tab', ui_kind='panel', selected='selected_view', page_name='.title')), id='rest_editor_view.EditorSplit', orientation='horizontal', layout='split', show_labels=False), id='rest_editor_view.EditorView', handler=ReSTHTMLEditorHandler(), width=1024, height=786, resizable=True, menubar=menu_bar, toolbar=tool_bar, key_bindings=key_bindings, title="reStructured Text Editor", icon=self.icon)
class ODMR(ManagedJob, GetSetItemsMixin): """Provides ODMR measurements.""" # starting and stopping keep_data = Bool( False) # helper variable to decide whether to keep existing data resubmit_button = Button( label='resubmit', desc= 'Submits the measurement to the job manager. Tries to keep previously acquired data. Behaves like a normal submit if sequence or time bins have changed since previous run.' ) # measurement parameters power = Range(low=-100., high=25., value=-20, desc='Power [dBm]', label='Power [dBm]', mode='text', auto_set=False, enter_set=True) frequency_begin = Range(low=1, high=20e9, value=2.85e9, desc='Start Frequency [Hz]', label='Begin [Hz]', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%e')) frequency_end = Range(low=1, high=20e9, value=2.88e9, desc='Stop Frequency [Hz]', label='End [Hz]', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%e')) frequency_delta = Range(low=1e-3, high=20e9, value=1e6, desc='frequency step [Hz]', label='Delta [Hz]', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%e')) t_pi = Range(low=1., high=100000., value=1000., desc='length of pi pulse [ns]', label='pi [ns]', mode='text', auto_set=False, enter_set=True) laser = Range(low=1., high=10000., value=300., desc='laser [ns]', label='laser [ns]', mode='text', auto_set=False, enter_set=True) wait = Range(low=1., high=10000., value=1000., desc='wait [ns]', label='wait [ns]', mode='text', auto_set=False, enter_set=True) pulsed = Bool(False, label='pulsed') seconds_per_point = Range(low=20e-3, high=1, value=20e-3, desc='Seconds per point', label='Seconds per point', mode='text', auto_set=False, enter_set=True) stop_time = Range( low=1., value=np.inf, desc='Time after which the experiment stops by itself [s]', label='Stop time [s]', mode='text', auto_set=False, enter_set=True) n_lines = Range(low=1, high=10000, value=50, desc='Number of lines in Matrix', label='Matrix lines', mode='text', auto_set=False, enter_set=True) # control data fitting perform_fit = Bool(False, label='perform fit') number_of_resonances = Trait( 'auto', String('auto', auto_set=False, enter_set=True), Int(10000., desc='Number of Lorentzians used in fit', label='N', auto_set=False, enter_set=True)) threshold = Range( low=-99, high=99., value=-50., desc= 'Threshold for detection of resonances [%]. The sign of the threshold specifies whether the resonances are negative or positive.', label='threshold [%]', mode='text', auto_set=False, enter_set=True) # fit result fit_parameters = Array(value=np.array((np.nan, np.nan, np.nan, np.nan))) fit_frequencies = Array(value=np.array((np.nan, )), label='frequency [Hz]') fit_line_width = Array(value=np.array((np.nan, )), label='line_width [Hz]') fit_contrast = Array(value=np.array((np.nan, )), label='contrast [%]') # measurement data frequency = Array() counts = Array() counts_matrix = Array() run_time = Float(value=0.0, desc='Run time [s]', label='Run time [s]') # plotting line_label = Instance(PlotLabel) line_data = Instance(ArrayPlotData) matrix_data = Instance(ArrayPlotData) line_plot = Instance(Plot, editor=ComponentEditor()) matrix_plot = Instance(Plot, editor=ComponentEditor()) def __init__(self): super(ODMR, self).__init__() self._create_line_plot() self._create_matrix_plot() self.on_trait_change(self._update_line_data_index, 'frequency', dispatch='ui') self.on_trait_change(self._update_line_data_value, 'counts', dispatch='ui') self.on_trait_change(self._update_line_data_fit, 'fit_parameters', dispatch='ui') self.on_trait_change(self._update_matrix_data_value, 'counts_matrix', dispatch='ui') self.on_trait_change(self._update_matrix_data_index, 'n_lines,frequency', dispatch='ui') self.on_trait_change( self._update_fit, 'counts,perform_fit,number_of_resonances,threshold', dispatch='ui') def _counts_matrix_default(self): return np.zeros((self.n_lines, len(self.frequency))) def _frequency_default(self): return np.arange(self.frequency_begin, self.frequency_end + self.frequency_delta, self.frequency_delta) def _counts_default(self): return np.zeros(self.frequency.shape) # data acquisition def apply_parameters(self): """Apply the current parameters and decide whether to keep previous data.""" frequency = np.arange(self.frequency_begin, self.frequency_end + self.frequency_delta, self.frequency_delta) if not self.keep_data or np.any(frequency != self.frequency): self.frequency = frequency self.counts = np.zeros(frequency.shape) self.run_time = 0.0 self.keep_data = True # when job manager stops and starts the job, data should be kept. Only new submission should clear data. def _run(self): try: self.state = 'run' self.apply_parameters() if self.run_time >= self.stop_time: self.state = 'done' return # if pulsed, turn on sequence if self.pulsed: ha.PulseGenerator().Sequence( 100 * [(['laser', 'aom', 'red'], self.laser), ([], self.wait), (['mw'], self.t_pi)]) else: ha.PulseGenerator().Open() n = len(self.frequency) """ ha.Microwave().setOutput( self.power, np.append(self.frequency,self.frequency[0]), self.seconds_per_point) self._prepareCounter(n) """ ha.Microwave().setPower(self.power) ha.Microwave().initSweep( self.frequency, self.power * np.ones(self.frequency.shape)) ha.Counter().configure(n, self.seconds_per_point, DutyCycle=0.8) time.sleep(0.5) while self.run_time < self.stop_time: start_time = time.time() if threading.currentThread().stop_request.isSet(): break ha.Microwave().resetListPos() counts = ha.Counter().run() self.run_time += time.time() - start_time self.counts += counts self.counts_matrix = np.vstack( (counts, self.counts_matrix[:-1, :])) self.trait_property_changed('counts', self.counts) """ ha.Microwave().doSweep() timeout = 3. start_time = time.time() while not self._count_between_markers.ready(): time.sleep(0.1) if time.time() - start_time > timeout: print "count between markers timeout in ODMR" break counts = self._count_between_markers.getData(0) self._count_between_markers.clean() """ if self.run_time < self.stop_time: self.state = 'idle' else: self.state = 'done' ha.Microwave().setOutput(None, self.frequency_begin) ha.PulseGenerator().Light() ha.Counter().clear() except: logging.getLogger().exception('Error in odmr.') self.state = 'error' finally: ha.Microwave().setOutput(None, self.frequency_begin) # fitting def _update_fit(self): if self.perform_fit: N = self.number_of_resonances if N != 'auto': N = int(N) try: p = fitting.fit_multiple_lorentzians(self.frequency, self.counts, N, threshold=self.threshold * 0.01) except Exception: logging.getLogger().debug('ODMR fit failed.', exc_info=True) p = np.nan * np.empty(4) else: p = np.nan * np.empty(4) self.fit_parameters = p self.fit_frequencies = p[1::3] self.fit_line_width = p[2::3] N = len(p) / 3 contrast = np.empty(N) c = p[0] pp = p[1:].reshape((N, 3)) for i, pi in enumerate(pp): a = pi[2] g = pi[1] A = np.abs(a / (np.pi * g)) if a > 0: contrast[i] = 100 * A / (A + c) else: contrast[i] = 100 * A / c self.fit_contrast = contrast # plotting def _create_line_plot(self): line_data = ArrayPlotData(frequency=np.array((0., 1.)), counts=np.array((0., 0.)), fit=np.array((0., 0.))) line_plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=32) line_plot.plot(('frequency', 'counts'), style='line', color='blue') line_plot.index_axis.title = 'Frequency [MHz]' line_plot.value_axis.title = 'Fluorescence counts' line_label = PlotLabel(text='', hjustify='left', vjustify='bottom', position=[64, 128]) line_plot.overlays.append(line_label) self.line_label = line_label self.line_data = line_data self.line_plot = line_plot def _create_matrix_plot(self): matrix_data = ArrayPlotData(image=np.zeros((2, 2))) matrix_plot = Plot(matrix_data, padding=8, padding_left=64, padding_bottom=32) matrix_plot.index_axis.title = 'Frequency [MHz]' matrix_plot.value_axis.title = 'line #' matrix_plot.img_plot('image', xbounds=(self.frequency[0], self.frequency[-1]), ybounds=(0, self.n_lines), colormap=Spectral) self.matrix_data = matrix_data self.matrix_plot = matrix_plot def _perform_fit_changed(self, new): plot = self.line_plot if new: plot.plot(('frequency', 'fit'), style='line', color='red', name='fit') self.line_label.visible = True else: plot.delplot('fit') self.line_label.visible = False plot.request_redraw() def _update_line_data_index(self): self.line_data.set_data('frequency', self.frequency * 1e-6) self.counts_matrix = self._counts_matrix_default() def _update_line_data_value(self): self.line_data.set_data('counts', self.counts) def _update_line_data_fit(self): if not np.isnan(self.fit_parameters[0]): self.line_data.set_data( 'fit', fitting.NLorentzians(*self.fit_parameters)(self.frequency)) p = self.fit_parameters f = p[1::3] w = p[2::3] N = len(p) / 3 contrast = np.empty(N) c = p[0] pp = p[1:].reshape((N, 3)) for i, pi in enumerate(pp): a = pi[2] g = pi[1] A = np.abs(a / (np.pi * g)) if a > 0: contrast[i] = 100 * A / (A + c) else: contrast[i] = 100 * A / c s = '' for i, fi in enumerate(f): s += 'f %i: %.6e Hz, HWHM %.3e Hz, contrast %.1f%%\n' % ( i + 1, fi, w[i], contrast[i]) self.line_label.text = s def _update_matrix_data_value(self): self.matrix_data.set_data('image', self.counts_matrix) def _update_matrix_data_index(self): if self.n_lines > self.counts_matrix.shape[0]: self.counts_matrix = np.vstack( (self.counts_matrix, np.zeros((self.n_lines - self.counts_matrix.shape[0], self.counts_matrix.shape[1])))) else: self.counts_matrix = self.counts_matrix[:self.n_lines] self.matrix_plot.components[0].index.set_data( (self.frequency[0] * 1e-6, self.frequency[-1] * 1e-6), (0.0, float(self.n_lines))) # saving data def save_line_plot(self, filename): self.save_figure(self.line_plot, filename) def save_matrix_plot(self, filename): self.save_figure(self.matrix_plot, filename) def save_all(self, filename): self.save_line_plot(filename + '_ODMR_Line_Plot.png') self.save_matrix_plot(filename + '_ODMR_Matrix_Plot.png') self.save(filename + '_ODMR.pys') # react to GUI events def submit(self): """Submit the job to the JobManager.""" self.keep_data = False ManagedJob.submit(self) def resubmit(self): """Submit the job to the JobManager.""" self.keep_data = True ManagedJob.submit(self) def _resubmit_button_fired(self): """React to start button. Submit the Job.""" self.resubmit() traits_view = View(VGroup( HGroup( Item('submit_button', show_label=False), Item('remove_button', show_label=False), Item('resubmit_button', show_label=False), Item('priority', enabled_when='state != "run"'), Item('state', style='readonly'), Item('run_time', style='readonly', format_str='%.f'), Item('stop_time'), ), VGroup( HGroup( Item('power', width=-40, enabled_when='state != "run"'), Item('frequency_begin', width=-80, enabled_when='state != "run"'), Item('frequency_end', width=-80, enabled_when='state != "run"'), Item('frequency_delta', width=-80, enabled_when='state != "run"'), ), HGroup( Item('seconds_per_point', width=-40, enabled_when='state != "run"'), Item('pulsed', enabled_when='state != "run"'), Item('laser', width=-50, enabled_when='state != "run"'), Item('wait', width=-50, enabled_when='state != "run"'), Item('t_pi', width=-50, enabled_when='state != "run"'), ), HGroup( Item('perform_fit'), Item('number_of_resonances', width=-60), Item('threshold', width=-60), Item('n_lines', width=-60), ), HGroup( Item('fit_contrast', style='readonly'), Item('fit_line_width', style='readonly'), Item('fit_frequencies', style='readonly'), ), ), VSplit( Item('matrix_plot', show_label=False, resizable=True), Item('line_plot', show_label=False, resizable=True), ), ), menubar=MenuBar( Menu(Action(action='saveLinePlot', name='SaveLinePlot (.png)'), Action(action='saveMatrixPlot', name='SaveMatrixPlot (.png)'), Action(action='save', name='Save (.pyd or .pys)'), Action(action='saveAll', name='Save All (.png+.pys)'), Action(action='export', name='Export as Ascii (.asc)'), Action(action='load', name='Load'), Action(action='_on_close', name='Quit'), name='File')), title='ODMR', width=900, height=800, buttons=[], resizable=True, handler=ODMRHandler) get_set_items = [ 'frequency', 'counts', 'counts_matrix', 'fit_parameters', 'fit_contrast', 'fit_line_width', 'fit_frequencies', 'perform_fit', 'run_time', 'power', 'frequency_begin', 'frequency_end', 'frequency_delta', 'laser', 'wait', 'pulsed', 't_pi', 'seconds_per_point', 'stop_time', 'n_lines', 'number_of_resonances', 'threshold', '__doc__' ]
class Yasso(HasTraits): """ The Yasso model """ # Parameters p_sets = _get_parameter_files() parameter_set = Enum(p_sets) leaching = Float() # Initial condition initial_mode = Enum(['non zero', 'zero', 'steady state']) initial_litter = List(trait=LitterComponent) steady_state = List(trait=LitterComponent) # Litter input at each timestep in the simulation litter_mode = Enum(['zero', 'yearly', 'constant yearly', 'monthly']) constant_litter = List(trait=LitterComponent) monthly_litter = List(trait=TimedLitterComponent) yearly_litter = List(trait=TimedLitterComponent) zero_litter = List(trait=LitterComponent) # Assumes that this defaults to 0 woody_size_limit = Float(default_value=3.0) area_change = List(trait=AreaChange) # Climate definition for the simulation climate_mode = Enum(['yearly', 'constant yearly', 'monthly']) constant_climate = YearlyClimate() monthly_climate = List(trait=MonthlyClimate, value=[MonthlyClimate(month=1), MonthlyClimate(month=2), MonthlyClimate(month=3), MonthlyClimate(month=4), MonthlyClimate(month=5), MonthlyClimate(month=6), MonthlyClimate(month=7), MonthlyClimate(month=8), MonthlyClimate(month=9), MonthlyClimate(month=10), MonthlyClimate(month=11), MonthlyClimate(month=12)] ) yearly_climate = List(trait=YearlyClimate) # All data as text all_data = Str() data_file = Str() # How the model will be run sample_size = Int() duration_unit = Enum(['year', 'month']) timestep_length = Range(low=1) simulation_length = Range(low=1) result_type = Enum(['C stock', 'C change', 'CO2 production']) presentation_type = Enum(['chart', 'array']) chart_type = Enum(['common scale', 'autofit']) # Buttons new_data_file_event = Button('New...') open_data_file_event = Button('Open...') save_data_file_event = Button('Save') save_as_file_event = Button('Save as...') modelrun_event = Button('Run model') save_result_event = Button('Save raw results...') save_moment_event = Button('Save moment results...') # and the results stored # Individual model calls # iteration,time, total, woody, acid, water, ethanol, non_soluble, humus c_stock = Array(dtype=float32, shape=(None, 10)) # iteration,time, total, woody, acid, water, ethanol, non_soluble, humus c_change = Array(dtype=float32, shape=(None, 10)) # time, iteration, CO2 production co2_yield = Array(dtype=float32, shape=(None, 3)) # time, mean, mode, var, skewness, kurtosis, 95% conf-, 95% conf+ stock_tom = Array(dtype=float32, shape=(None, 8)) stock_woody = Array(dtype=float32, shape=(None, 8)) stock_non_woody = Array(dtype=float32, shape=(None, 8)) stock_acid = Array(dtype=float32, shape=(None, 8)) stock_water = Array(dtype=float32, shape=(None, 8)) stock_ethanol = Array(dtype=float32, shape=(None, 8)) stock_non_soluble = Array(dtype=float32, shape=(None, 8)) stock_humus = Array(dtype=float32, shape=(None, 8)) change_tom = Array(dtype=float32, shape=(None, 8)) change_woody = Array(dtype=float32, shape=(None, 8)) change_non_woody = Array(dtype=float32, shape=(None, 8)) change_acid = Array(dtype=float32, shape=(None, 8)) change_water = Array(dtype=float32, shape=(None, 8)) change_ethanol = Array(dtype=float32, shape=(None, 8)) change_non_soluble = Array(dtype=float32, shape=(None, 8)) change_humus = Array(dtype=float32, shape=(None, 8)) co2 = Array(dtype=float32, shape=(None, 8)) # plot variables stock_plots = Instance(GridContainer) change_plots = Instance(GridContainer) co2_plot = Instance(GridContainer) p_timestep = Array() ps_tom = Array() ps_woody = Array() ps_non_woody = Array() ps_acid = Array() ps_water = Array() ps_ethanol = Array() ps_non_soluble = Array() ps_humus = Array() pc_tom = Array() pc_non_woody = Array() pc_acid = Array() pc_water = Array() pc_ethanol = Array() pc_non_soluble = Array() pc_humus = Array() ############################################################# # UI view ############################################################# view = View( VGroup( HGroup( Item('new_data_file_event', show_label=False,), Item('open_data_file_event', show_label=False,), Item('save_data_file_event', show_label=False,), Item('save_as_file_event', show_label=False,), Item('data_file', style='readonly', show_label=False,), ), HGroup( Item('all_data', show_label=False, editor=CodeEditor(), has_focus=True, width=300, height=400, ), ), label='All data', ), VGroup( HGroup( Item('parameter_set', width=-145), Item('leaching', width=-45, label='Leaching parameter', visible_when='initial_mode!="steady state"'), show_border=True, ), VGroup( HGroup( Item(name='initial_mode', style='custom', label='Initial state:', emphasized=True, ), ), Item('initial_litter', visible_when='initial_mode=="non zero"', show_label=False, editor=litter_te, width=790, height=75, ), ), VGroup( HGroup( Item('litter_mode', style='custom', label='Soil carbon input:', emphasized=True ) ), HGroup( Item('constant_litter', visible_when='litter_mode=="constant yearly"', show_label=False, editor=litter_te, full_size=False, springy=False, #width=-790, height=-75 ), Item('monthly_litter', visible_when='litter_mode=="monthly"', show_label=False, editor=timed_litter_te, full_size=False, springy=False, #width=-790, height=-75 ), Item('yearly_litter', visible_when='litter_mode=="yearly"', show_label=False, editor=timed_litter_te, full_size=False, springy=False, #width=-790,height=-75 ), ), HGroup( Item('area_change', visible_when='litter_mode=="yearly" or '\ 'litter_mode=="monthly"', show_label=False, editor=change_te, full_size=False, springy=False, width=-150,height=-75 ), spring, ), ), VGroup( HGroup( Item('climate_mode', style='custom', label='Climate:', emphasized=True, ), ), HGroup( Item('monthly_climate', show_label=False, visible_when='climate_mode=="monthly"', editor=monthly_climate_te, width=200, height=75 ), Item('yearly_climate', show_label=False, visible_when='climate_mode=="yearly"', editor=yearly_climate_te, width=200, height=75 ), VGroup( Item('object.constant_climate.mean_temperature', style='readonly',), Item('object.constant_climate.annual_rainfall', style='readonly',), Item('object.constant_climate.variation_amplitude', style='readonly',), show_border=True, visible_when='climate_mode=="constant yearly"' ), ), ), label='Data to use', ), VGroup( Group( HGroup( Item('sample_size', width=-45, ), Item('simulation_length', width=-45, label='Number of timesteps', ), Item('timestep_length', width=-45, ), Item('duration_unit', style='custom', show_label=False,), ), HGroup( Item('woody_size_limit', width=-45, ), Item('modelrun_event', show_label=False), ), show_border=True ), HGroup( Item('result_type', style='custom', label='Show', emphasized=True, ), Item('save_result_event', show_label=False,), Item('save_moment_event', show_label=False,), ), HGroup( Item('presentation_type', style='custom', label='As', emphasized=True, ), Item('chart_type', style='custom', label='Chart type', visible_when='presentation_type=="chart"'), ), HGroup( Item('c_stock', visible_when='result_type=="C stock" and \ presentation_type=="array"', show_label=False, editor=c_stock_te, #width=600 ), Item('c_change', visible_when='result_type=="C change" and \ presentation_type=="array"', show_label=False, editor=c_stock_te,), Item('co2_yield', visible_when='result_type=="CO2 production" '\ 'and presentation_type=="array"', show_label=False, editor=co2_yield_te,), Item('stock_plots', editor=ComponentEditor(), show_label=False, visible_when='result_type=="C stock" and \ presentation_type=="chart"',), Item('change_plots', editor=ComponentEditor(), show_label=False, visible_when='result_type=="C change" and \ presentation_type=="chart"',), Item('co2_plot', editor=ComponentEditor(), show_label=False, visible_when='result_type=="CO2 production" and \ presentation_type=="chart"',), ), label='Model run', ), VGroup( Label(label='Yasso15 soil carbon model', emphasized=True), Label(label="<placeholder>", id="about_text"), label='About', ), title = 'Yasso 15', id = 'simosol.yasso15', dock = 'horizontal', width = 800, height = 600, resizable = True, scrollable= True, buttons=NoButtons, icon=app_ir, menubar = MenuBar( Menu(CloseAction, name = 'File'), Menu(UndoAction, RedoAction, RevertAction, name = 'Edit'), ), help=False, ) ############################################################################### # Initialisation ############################################################################### def __init__(self): self.sample_size = 10 self.simulation_length = 10 fn = os.path.split(sys.executable) if fn[1].lower().startswith('python'): exedir = os.path.abspath(os.path.split(sys.argv[0])[0]) self.data_file = self._get_data_file_path(exedir) else: self.data_file = self._get_data_file_path(fn[0]) try: f = codecs.open(self.data_file, 'r', 'utf8') self._load_all_data(f) f.close() except: self.all_data = DATA_STRING self.data_file = '' try: cfg = ConfigParser.ConfigParser() fn = os.path.split(sys.executable) if fn[1].lower().startswith('python'): exedir = os.path.abspath(os.path.split(sys.argv[0])[0]) else: exedir = fn[0] inipath = os.path.join(exedir, 'yasso.ini') cfg.readfp(codecs.open(inipath, "r", "utf8")) about_text = cfg.get("about", "text") about_text = about_text.replace("\\n", "\n") default_param = cfg.get("data", "default_param") if default_param in self.p_sets: self.parameter_set = default_param self.trait_view('about_text').label = about_text except Exception as error: print "Error reading yasso.ini. See the error log for details." raise error def _get_data_file_path(self, exedir): join = os.path.join self.state_file = join(exedir, 'yasso.state') if os.path.exists(self.state_file): f = codecs.open(self.state_file, 'r', 'utf8') datafile = f.read() if len(datafile)>0 and datafile[-1]=='\n': datafile = datafile[:-1] f.close() if not os.path.exists(datafile): os.remove(self.state_file) datafile = join(exedir, 'demo_data.txt') else: datafile = join(exedir, 'demo_data.txt') return datafile def _write_state(self, filename): f = codecs.open(self.state_file, 'w', 'utf8') f.write(filename) f.close() ############################################################################### # Custom derived properties ############################################################################### @property def leach_parameter(self): """Leach parameter can only be 0 when the initialization mode is by steady state. In other cases, the leaching parameter is the trait "leaching". This is to be called from the YassoModel instead of the traits themselves.""" if self.initial_mode=='steady state': return 0 else: return self.leaching ############################################################################### # Event handlers ############################################################################### ######################### # for plot data ######################### def _create_stock_plots(self, common_scale=False): max = None min = 0 stom, max, min = self._create_plot(max, min, self.stock_tom, 'Total organic matter') swoody, max, min = self._create_plot(max, min, self.stock_woody, 'Woody matter') snonwoody, max, min = self._create_plot(max, min, self.stock_non_woody, 'Non-woody matter') sa, max, min = self._create_plot(max, min, self.stock_acid, 'A') sw, max, min = self._create_plot(max, min, self.stock_water, 'W') se, max, min = self._create_plot(max, min, self.stock_ethanol, 'E') sn, max, min = self._create_plot(max, min, self.stock_non_soluble, 'N') sh, max, min = self._create_plot(max, min, self.stock_humus, 'H') if common_scale: for pl in (stom, swoody, snonwoody, sa, sw, se, sn, sh): pl.value_range.set_bounds(min, max) container = GridContainer(stom, swoody, snonwoody, sa, sw, se, sn, sh) container.shape = (3,3) container.spacing = (-8,-8) self.stock_plots = container def _create_change_plots(self, common_scale=False): max = None min = 0 ctom, max, min = self._create_plot(max, min, self.change_tom, 'Total organic matter') cwoody, max, min = self._create_plot(max, min, self.change_woody, 'Woody matter') cnonwoody, max, min = self._create_plot(max, min, self.change_non_woody, 'Non-woody matter') ca, max, min = self._create_plot(max, min, self.change_acid, 'A') cw, max, min = self._create_plot(max, min, self.change_water, 'W') ce, max, min = self._create_plot(max, min, self.change_ethanol, 'E') cn, max, min = self._create_plot(max, min, self.change_non_soluble, 'N') ch, max, min = self._create_plot(max, min, self.change_humus, 'H') if common_scale: for pl in (ctom, cwoody, cnonwoody, ca, cw, ce, cn, ch): pl.value_range.set_bounds(min, max) container = GridContainer(ctom, cwoody, cnonwoody, ca, cw, ce, cn, ch) container.shape = (3,3) container.spacing = (-15,-15) self.change_plots = container def _create_co2_plot(self): max = None min = 0 co2, max, min = self._create_plot(max, min, self.co2, 'CO2 production (in carbon)') container = GridContainer(co2, Plot(), Plot(), Plot()) container.shape= (2,2) self.co2_plot = container def _create_plot(self, max, min, dataobj, title): x = dataobj[:,0] y = dataobj[:,1] if y.max()>max: max = y.max() if y.min()<min: min = y.min() if self.sample_size>1: y2 = dataobj[:,6] y3 = dataobj[:,7] if y3.max()>max: max = y3.max() if y2.min()<min: min = y2.min() plotdata = ArrayPlotData(x=x, y=y, y2=y2, y3=y3) else: plotdata = ArrayPlotData(x=x, y=y) plot = Plot(plotdata) plot.plot(("x", "y"), type="line", color="blue") if self.sample_size>1: plot.plot(("x", "y2"), type="line", color="red") plot.plot(("x", "y3"), type="line", color="red") plot.title = title plot.title_font = 'Arial 10' return plot, max, min ######################## # for running the model ######################## def _modelrun_event_fired(self): # set the parameter set to use fn = os.path.split(sys.executable) if fn[1].lower().startswith('python'): exedir = os.path.abspath(os.path.split(sys.argv[0])[0]) else: exedir = fn[0] pdir = os.path.join(exedir, 'param') parfile = os.path.join(pdir, '%s.dat' % self.parameter_set) if self.initial_mode=='zero' and self.litter_mode=='zero': errmsg = ("Both soil carbon input and initial state may not be " "zero simultaneously.") error(errmsg, title='Invalid model parameters', buttons=['OK']) return if self.climate_mode=='yearly' and not self.yearly_climate: errmsg = ("Climate mode may not be 'yearly' if there are no " "yearly climate entries in the data file.") error(errmsg, title='Invalid model parameters', buttons=['OK']) return if self.leaching>0: errmsg = ("Leaching parameter may not be larger than 0.") error(errmsg, title='Invalid model parameters', buttons=['OK']) return if self.climate_mode=='monthly' and not self.monthly_climate: errmsg = ("Climate mode may not be 'monthly' if there are no " "monthly climate entries in the data file.") error(errmsg, title='Invalid model parameters', buttons=['OK']) return yassorunner = ModelRunner(parfile) if not yassorunner.is_usable_parameter_file(): errmsg = ("The selected parameter file has wrong number of columns " "and cannot be used.") error(errmsg, title='Invalid model parameters', buttons=['OK']) return self.yassorunner = yassorunner if self.initial_mode=='steady state': steady_state = self.yassorunner.compute_steady_state(self) self._set_steady_state(steady_state) self._init_results() self.c_stock, self.c_change, self.co2_yield = \ self.yassorunner.run_model(self) self._create_co2_plot() self._chart_type_changed() ######################## # for chart type ######################## def _chart_type_changed(self): if self.chart_type=='autofit': self._create_stock_plots() self._create_change_plots() elif self.chart_type=='common scale': self._create_stock_plots(common_scale=True) self._create_change_plots(common_scale=True) ######################## # for buttons ######################## def _new_data_file_event_fired(self): filename = save_file() if filename != '': try: self._reset_data() f=codecs.open(filename, 'w', 'utf8') f.close() self.data_file = filename self._write_state(filename) self.all_data=DATA_STRING except: pass def _open_data_file_event_fired(self): filename = open_file() if filename != '': try: f=codecs.open(filename, 'r', 'utf8') self.data_file = filename self._write_state(filename) self._load_all_data(f) f.close() except: pass def _save_data_file_event_fired(self): if self.data_file=='': filename = save_file() if filename=='': return self.data_file = filename self._write_state(filename) self._save_all_data() def _save_as_file_event_fired(self): filename = save_file() if filename=='': return self.data_file = filename self._write_state(filename) self._save_all_data() def _load_all_data(self, datafile): """ Loads all data from a single file. Data in sections defined by [name], data in whitespace delimited rows """ self._reset_data() sectionp = re.compile('\[([\w+\s*]+)\]') datap = re.compile('[+-Ee\d+\.\d*\s*]+') active = None data = defaultdict(list) alldata = '' linecount = 0 for line in datafile: linecount += 1 alldata += line m = re.match(sectionp, line) if m is not None: active = m.group(1) d = re.match(datap, line) if d is not None: try: vals = [float(val) for val in d.group(0).split()] data[active].append(vals) except ValueError: errmsg="There's an error on line %s\n %s"\ "for section %s\n"\ "Values must be space separated and . is the decimal"\ " separator" % (linecount, d.group(0), active) error(errmsg, title='Error saving data', buttons=['OK']) self.all_data = alldata for section, vallist in data.items(): if section=='Initial state': self._set_initial_state(vallist) elif section=='Constant soil carbon input': self._set_constant_litter(vallist) elif section=='Monthly soil carbon input': self._set_monthly_litter(vallist) elif section=='Yearly soil carbon input': self._set_yearly_litter(vallist) elif section=='Relative area change': self._set_area_change(vallist) elif section=='Constant climate': self._set_constant_climate(vallist) elif section=='Monthly climate': self._set_monthly_climate(vallist) elif section=='Yearly climate': self._set_yearly_climate(vallist) def _save_all_data(self): f = codecs.open(self.data_file, 'w', 'utf8') f.write(self.all_data) f.close() f = codecs.open(self.data_file, 'r', 'utf8') self._load_all_data(f) f.close() def _reset_data(self): """ Empties all input data structures """ self.initial_litter = [] self.steady_state = [] self.constant_litter = [] self.monthly_litter = [] self.yearly_litter = [] self.area_change = [] self.constant_climate.mean_temperature = 0 self.constant_climate.annual_rainfall = 0 self.constant_climate.variation_amplitude = 0 self.yearly_climate = [] self.monthly_climate = [] def _set_initial_state(self, data): errmsg = 'Soil carbon components should contain: \n'\ ' mass, mass std, acid, acid std, water, water std,\n'\ ' ethanol, ethanol std, non soluble, non soluble std,'\ '\n humus, humus std, size class' for vals in data: ok, obj = self._load_litter_object(vals, errmsg) if not ok: break self.initial_litter.append(obj) def _set_steady_state(self, data): errmsg = 'Soil carbon components should contain: \n'\ ' mass, mass std, acid, acid std, water, water std,\n'\ ' ethanol, ethanol std, non soluble, non soluble std,'\ '\n humus, humus std, size class' self.steady_state = [] for vals in data: ok, obj = self._load_litter_object(vals, errmsg) if not ok: break self.steady_state.append(obj) def _set_constant_litter(self, data): errmsg = 'Soil carbon components should contain: \n'\ ' mass, mass std, acid, acid std, water, water std,\n'\ ' ethanol, ethanol std, non soluble, non soluble std,'\ '\n humus, humus std, size class' for vals in data: ok, obj = self._load_litter_object(vals, errmsg) if not ok: break self.constant_litter.append(obj) def _set_monthly_litter(self, data): errmsg = 'timed soil carbon components should contain: \n'\ ' timestep, mass, mass std, acid, acid std, water, '\ 'water std,\n'\ ' ethanol, ethanol std, non soluble, non soluble std,'\ '\n humus, humus std, size class' for vals in data: ok, obj = self._load_litter_object(vals, errmsg, True) if not ok: break self.monthly_litter.append(obj) def _set_yearly_litter(self, data): errmsg = 'timed soil carbon components should contain: \n'\ ' timestep, mass, mass std, acid, acid std, water, '\ 'water std,\n'\ ' ethanol, ethanol std, non soluble, non soluble std,'\ '\n humus, humus std, size class' for vals in data: ok, obj = self._load_litter_object(vals, errmsg, True) if not ok: break self.yearly_litter.append(obj) def _set_area_change(self, data): errmsg = 'Area change should contain:\n timestep, relative area change' for vals in data: if len(vals)==2: obj = AreaChange(timestep=int(vals[0]), rel_change=vals[1]) self.area_change.append(obj) elif vals!=[]: errmsg = errmsg + '\n%s data values found, 2 needed' % (len(data)) error(errmsg, title='error reading data', buttons=['OK']) break def _set_yearly_climate(self, data): errmsg = 'Yearly climate should contain: timestep, mean temperature,\n'\ 'annual rainfall and temperature variation amplitude' for vals in data: if len(vals)==4: obj = YearlyClimate(timestep=int(vals[0]), mean_temperature=vals[1], annual_rainfall=vals[2], variation_amplitude=vals[3]) self.yearly_climate.append(obj) elif vals!=[]: errmsg = errmsg + '\n%s data values found, 4 needed' % (len(data)) error(errmsg, title='error reading data', buttons=['OK']) break def _set_constant_climate(self, data): errmsg = 'Constant climate should contain: mean temperature,\n'\ 'annual rainfall and temperature variation amplitude' if len(data[0])==3: self.constant_climate.mean_temperature = data[0][0] self.constant_climate.annual_rainfall = data[0][1] self.constant_climate.variation_amplitude = data[0][2] elif data[0]!=[]: errmsg = errmsg + '\n%s data values found, 3 needed' % (len(data)) error(errmsg, title='error reading data', buttons=['OK']) def _set_monthly_climate(self, data): errmsg = 'Monthly climate data should contain: month,\n'\ 'temperature and rainfall' for vals in data: if len(vals)==3: obj = MonthlyClimate(month=int(vals[0]), temperature=vals[1], rainfall=vals[2]) self.monthly_climate.append(obj) elif vals!=[]: errmsg = errmsg + '\n%s data values found, 3 needed' % (len(data)) error(errmsg, title='Error reading data', buttons=['OK']) break def _load_litter_object(self, data, errmsg, hastime=False): obj = None loaded = True if hastime: if len(data)==14: obj = TimedLitterComponent(timestep=int(data[0]), mass=data[1], mass_std=data[2], acid=data[3], acid_std=data[4], water=data[5], water_std=data[6], ethanol=data[7], ethanol_std=data[8], non_soluble=data[9], non_soluble_std=data[10], humus=data[11], humus_std=data[12], size_class=data[13]) elif data!=[]: errmsg = errmsg + '\n%s data values found, 14 needed' % (len(data)) error(errmsg, title='Error reading data', buttons=['OK']) loaded = False elif data==[]: loaded = False else: if len(data)==13: obj = LitterComponent(mass=data[0], mass_std=data[1], acid=data[2], acid_std=data[3], water=data[4], water_std=data[5], ethanol=data[6], ethanol_std=data[7], non_soluble=data[8], non_soluble_std=data[9], humus=data[10], humus_std=data[11], size_class=data[12]) elif data!=[]: errmsg = errmsg + '\n%s data values found, 13 needed' % (len(data)) error(errmsg, title='Error reading data', buttons=['OK']) loaded = False elif data==[]: loaded = False return loaded, obj def _save_moment_event_fired(self): filename = save_file() if filename != '': f=codecs.open(filename, 'w', 'utf8') if self.result_type=='C stock': comps = (('tom', self.stock_tom), ('woody', self.stock_woody), ('non-woody', self.stock_non_woody), ('acid', self.stock_acid), ('water', self.stock_water), ('ethanol', self.stock_ethanol), ('non-soluble', self.stock_non_soluble), ('humus', self.stock_humus)) elif self.result_type=='C change': comps = (('tom', self.change_tom), ('woody', self.change_woody), ('non-woody', self.change_non_woody), ('acid', self.change_acid), ('water', self.change_water), ('ethanol', self.change_ethanol), ('non-soluble', self.change_non_soluble), ('humus', self.change_humus)) elif self.result_type=='CO2 production': comps = (('CO2', self.co2),) header = '# component, time step, mean, mode, var, skewness, '\ 'kurtosis, 95% confidence lower limit, 95% upper limit' header = self._make_result_header(header) f.write(header+'\n') for comp, res in comps: for row in res: resrow = '' for num in row: resrow = ' '.join([resrow, str(num)]) resrow = ' '.join((comp, resrow)) f.write(resrow+'\n') f.close() def _save_result_event_fired(self): filename = save_file() if filename != '': f=codecs.open(filename, 'w', 'utf8') if self.result_type=='C stock': res = self.c_stock header = '# sample, time step, total om, woody om, non-woody om,'\ ' acid, water, ethanol, non-soluble, humus' elif self.result_type=='C change': res = self.c_change header = '# sample, time step, total om, woody om, non-woody om,'\ ' acid, water, ethanol, non soluble, humus' elif self.result_type=='CO2 production': res = self.co2_yield header = '# sample, time step, CO2 production (in carbon)' header = self._make_result_header(header) f.write(header+'\n') for row in res: resrow = '' for num in row: resrow = ' '.join([resrow, str(num)]) f.write(resrow+'\n') f.close() def _make_result_header(self, header): '''Adds metadata about the results into the header''' hstr = '#########################################################\n' hstr += '# ' + self.result_type + '\n' hstr += '#########################################################\n' hstr += '# Datafile used: ' + self.data_file + '\n' hstr += '# Settings:\n' hstr += '# initial state: ' + self.initial_mode + '\n' hstr += '# soil carbon input: ' + self.litter_mode + '\n' hstr += '# climate: ' + self.climate_mode + '\n' hstr += '# sample size: ' + str(self.sample_size) + '\n' hstr += ''.join(['# timestep length: ', str(self.timestep_length), ' (', self.duration_unit, ')\n']) hstr += '# woody litter size limit: ' + str(self.woody_size_limit)+'\n' hstr += '#\n' return hstr + header def _init_results(self): """ model results: stock & change sample, timestep, tom, woody, non-woody, acid, water, ethanol, non soluble humus model results: CO2 sample, timestep, CO2 production summary results common format: time, mean, mode, var, skewness, kurtosis, 95% confidence-, 95% confidence+ """ self.c_stock = empty(dtype=float32, shape=(0, 10)) self.c_change = empty(dtype=float32, shape=(0, 10)) self.co2_yield = empty(dtype=float32, shape=(0, 3)) self.stock_tom = empty(dtype=float32, shape=(0, 8)) self.stock_woody = empty(dtype=float32, shape=(0, 8)) self.stock_non_woody = empty(dtype=float32, shape=(0, 8)) self.stock_acid = empty(dtype=float32, shape=(0, 8)) self.stock_water = empty(dtype=float32, shape=(0, 8)) self.stock_ethanol = empty(dtype=float32, shape=(0, 8)) self.stock_non_soluble = empty(dtype=float32, shape=(0, 8)) self.stock_humus = empty(dtype=float32, shape=(0, 8)) self.change_tom = empty(dtype=float32, shape=(0, 8)) self.change_woody = empty(dtype=float32, shape=(0, 8)) self.change_non_woody = empty(dtype=float32, shape=(0, 8)) self.change_acid = empty(dtype=float32, shape=(0, 8)) self.change_water = empty(dtype=float32, shape=(0, 8)) self.change_ethanol = empty(dtype=float32, shape=(0, 8)) self.change_non_soluble = empty(dtype=float32, shape=(0, 8)) self.change_humus = empty(dtype=float32, shape=(0, 8)) self.co2 = empty(dtype=float32, shape=(0, 8))
MenuBar( Menu( Group( OpenProjectAction, OpenAction, ImportDataFileAction, #RunCustomUIAction, ), Group( SaveProjectAction, SaveProjectAsAction, #SaveDataAction, SaveAction, SaveAsAction, ), Group( ExportAsFunctionAction, ExportAsScriptAction, ), Group( CloseAction, ), name = 'File' ), Menu( Group( ExecuteAction, ToggleAutoExecuteAction, ), name='Run'), Menu( Group( ResetAction, ), name='Reset'), #Menu( Group(ClearContextAction), # name = "Data" ), Menu( Group( SetToolbarHideAction, ), name = "Preferences" ), )
class Autocorrelation( ManagedJob, GetSetItemsMixin): window_size = Range(low=1., high=10000., value=500., desc='window_size in the time domain [ns]', label='window_size', mode='text', auto_set=False, enter_set=True) bin_width = Range(low=0.01, high=1000., value=1., desc='bin width [ns]', label='bin width', mode='text', auto_set=False, enter_set=True) chan1 = Enum(0,1,2,3,4,5,6,7, desc="the trigger channel", label="Channel 1") chan2 = Enum(0,1,2,3,4,5,6,7, desc="the signal channel", label="Channel 2") normalize = Bool(False, desc="normalize autocorrelation", label="normalize") counts = Array() time_bins = Array() keep_data = Bool(False) # helper variable to decide whether to keep existing data resubmit_button = Button(label='resubmit', desc='Submits the measurement to the job manager. Tries to keep previously acquired data. Behaves like a normal submit if sequence or time bins have changed since previous run.') run_time = Float(value=0.0, label='run time [s]') stop_time = Range(low=1., value=np.inf, desc='Time after which the experiment stops by itself [s]', label='Stop time [s]', mode='text', auto_set=False, enter_set=True) plot = Instance( Plot ) plot_data = Instance( ArrayPlotData ) get_set_items=['window_size', 'bin_width', 'chan1', 'chan2', 'normalize', 'counts', 'time_bins', 'norm_factor'] def __init__(self): super(Autocorrelation, self).__init__() self._create_plot() def submit(self): """Submit the job to the JobManager.""" self.keep_data = False self.run_time = 0.0 ManagedJob.submit(self) def resubmit(self): """Submit the job to the JobManager.""" self.keep_data = True ManagedJob.submit(self) def _resubmit_button_fired(self): """React to start button. Submit the Job.""" self.resubmit() @on_trait_change('chan1,chan2,window_size,bin_width') def _create_threads(self): self.p1 = TimeTagger.Pulsed(int(np.round(self.window_size/self.bin_width)),int(np.round(self.bin_width*1000)),1,self.chan1,self.chan2) self.p2 = TimeTagger.Pulsed(int(np.round(self.window_size/self.bin_width)),int(np.round(self.bin_width*1000)),1,self.chan2,self.chan1) self.run_time = 0.0 def _run(self): """Acquire data.""" try: # run the acquisition self.state='run' if self.run_time >= self.stop_time: logging.getLogger().debug('Runtime larger than stop_time. Returning') self.state='done' return n_bins = int(np.round(self.window_size/self.bin_width)) time_bins = self.bin_width*np.arange(-n_bins+1,n_bins) if self.keep_data: try: self.p1.start() self.p2.start() except: self._create_threads() else: self._create_threads() start_time = time.time() self.time_bins = time_bins self.n_bins = n_bins self.keep_data = True # when job manager stops and starts the job, data should be kept. Only new submission should clear data. while self.run_time < self.stop_time: data1 = self.p1.getData() data2 = self.p2.getData() current_time = time.time() self.run_time += current_time - start_time start_time = current_time data = np.append(np.append(data1[0][-1:0:-1], max(data1[0][0],data2[0][0])),data2[0][1:]) self.counts = data try: self.norm_factor = self.run_time/(self.bin_width*1e-9*self.p1.getCounts()*self.p2.getCounts()) except: self.norm_factor = 1.0 self.thread.stop_request.wait(1.0) if self.thread.stop_request.isSet(): logging.getLogger().debug('Caught stop signal. Exiting.') break self.p1.stop() self.p2.stop() if self.run_time < self.stop_time: self.state = 'idle' else: self.state='done' except: # if anything fails, recover logging.getLogger().exception('Error in autocorrelation.') self.state='error' def save_plot(self, filename): self.save_figure(self.plot, filename) def _counts_default(self): return np.zeros((int(np.round(self.window_size/self.bin_width))*2-1,)) def _time_bins_default(self): return self.bin_width*np.arange(-int(np.round(self.window_size/self.bin_width))+1,int(np.round(self.window_size/self.bin_width))) def _time_bins_changed(self): self.plot_data.set_data('t', self.time_bins) def _counts_changed(self): if self.normalize: self.plot_data.set_data('y', self.counts*self.norm_factor) else: self.plot_data.set_data('y', self.counts) def _chan1_default(self): return 0 def _chan2_default(self): return 1 def _window_size_changed(self): self.counts = self._counts_default() self.time_bins = self._time_bins_default() def _create_plot(self): data = ArrayPlotData(t=self.time_bins, y=self.counts) plot = Plot(data, width=500, height=500, resizable='hv') plot.plot(('t','y'), type='line', color='blue') self.plot_data=data self.plot=plot traits_view = View(HGroup(Item('submit_button', show_label=False), Item('remove_button', show_label=False), Item('resubmit_button', show_label=False), Item('priority'), Item('state', style='readonly'), Item('run_time', style='readonly',format_str='%.f'), Item('stop_time'), ), Item('plot', editor=ComponentEditor(), show_label=False), HGroup( Item('window_size'), Item('bin_width'), Item('chan1'), Item('chan2'), Item('normalize'), ), menubar = MenuBar( Menu( Action(action='save', name='Save (.pyd or .pys)'), Action(action='load', name='Load'), Action(action='save_plot', name='Save Plot (.png)'), Action(action='_on_close', name='Quit'), name='File')), title='Autocorrelation', width=900, height=800, buttons=[], resizable=True, handler=AutocorrelationHandler)
if filename.find('.png') == -1: filename = filename + '.png' info.object.save_line_plot(filename) def save_all(self, info): filename = save_file(title='Save All') if filename is '': return else: info.object.save_all(filename) menubar = MenuBar(Menu(Action(action='save', name='Save (.pyd or .pys)'), Action(action='load', name='Load (.pyd or .pys)'), Action(action='save_hist_plot', name='Save Hist Plot (.png)'), Action(action='save_line_plot', name='Save Line Plot (.png)'), Action(action='save_all', name='Save All'), Action(action='_on_close', name='Quit'), name='File' ), ) class PulsedFit(HasTraits, GetSetItemsMixin): """ Base class for a pulsed fit. Provides calculation of normalized intensity. Derive from this to create fits for pulsed measurements. """ measurement = Instance(ss.Pulsed, factory=ss.Pulsed) x_tau = Array(value=np.array((0., 1.)))
info.object.save_matrix_plot(filename) def save_line_plot(self, info): filename = save_file(title='Save Line Plot') if filename is '': return else: if filename.find('.png') == -1: filename = filename + '.png' info.object.save_line_plot(filename) menubar = MenuBar( Menu(Action(action='save', name='Save (.pyd or .pys)'), Action(action='load', name='Load (.pyd or .pys)'), Action(action='save_matrix_plot', name='Save Matrix Plot (.png)'), Action(action='save_line_plot', name='Save Line Plot (.png)'), Action(action='_on_close', name='Quit'), name='File'), ) class GSDAna(ManagedJob): plot = Instance(Plot) line_data = Instance(ArrayPlotData) # overwrite this to change the window title traits_view = View(VGroup( Item(name='measurement', style='custom', show_label=False), HGroup( Item('integration_width'), Item('position_signal'),
class BMCSWindow(HasStrictTraits): '''View object for a cross section state. ''' root = Instance(BMCSTreeNode) selected_node = Instance(HasStrictTraits) def _selected_node_changed(self): self.selected_node.ui = self plot_dock_pane = Instance(PlotDockPane, ()) data_changed = Event replot = Button def _replot_fired(self): self.figure.clear() self.selected_node.plot(self.figure) self.data_changed = True clear = Button() def _clear_fired(self): self.figure.clear() self.data_changed = True #time = self.root.time view = View( HSplit( Group( Item( 'root', id='bmcs.hsplit.left.tree.id', dock='tab', editor=tree_editor, resizable=True, show_label=False, width=300, height=200, ), # Item('selected_node@'), id='bmcs.hsplit.left.id', dock='tab', ), Group( Item( 'plot_dock_pane@', show_label=False, id='bmcs.hsplit.viz3d.notebook.id', dock='tab', ), # Item('self.root.time', label='t/T_max'), dock='tab', id='bmcs.hsplit.viz3d.id', label='plot sheet', ), dock='tab', id='bmcs.hsplit.id', ), # dock='tab', id='bmcs.id', width=1.0, height=1.0, title='BMCS', resizable=True, handler=BMCSTreeViewHandler(), toolbar=ToolBar(*toolbar_actions), menubar=MenuBar( Menu(menu_exit, Separator(), menu_save, menu_open, name='File')))
class Distance_to_NV(HasTraits, GetSetItemsMixin): counts = Array() counts2 = Array() hi = Array() time = Array() normalized_counts = Array() nu = Array() S = Array() FFx = Array() FFy = Array() tau = Array() #pulse spacing line_label = Instance(PlotLabel) line_data = Instance(ArrayPlotData) myfile = File(exists=True) substance = Enum( 'immersion oil, H1 signal', 'hBN, B11 signal', label='substance', desc='choose the nucleus to calculate larmor frequency', editor=EnumEditor(values={ 'immersion oil, H1 signal': '1:immersion oil, H1 signal', 'hBN, B11 signal': '2:hBN, B11 signal' }, cols=8), ) rabi_contrast = pulse_spacing = Float(value=30.0, desc='pulse_spacing', label='contrast', mode='text', auto_set=True, enter_set=True) z = Float(value=0., desc='distance to NV [nm]', label='distance to NV [nm]') frequencies = Float(value=0., desc='frequencies [MHz]', label='frequencies [MHz]') z2 = Float(value=0., desc='distance to NV [nm]', label='distance to NV [nm]') fit_threshold = Range( low=-99, high=99., value=50., desc= 'Threshold for detection of resonances [%]. The sign of the threshold specifies whether the resonances are negative or positive.', label='threshold [%]', mode='text', auto_set=False, enter_set=True) n_FFT = Range(low=2.**10, high=3.0e+6, value=2.0e+06, desc='NUMBER OF POINTS FOR FOURIER TRANSFORM', label='N FFT', editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_str='%.2e')) alpha = Range(low=0., high=1000., value=1., desc='fitting paramenter', label='alpha', auto_set=False, enter_set=True, mode='spinner') pulse_spacing = Float(value=0., desc='pulse_spacing', label='pulse spacing [ns]') pi_pulse = Float(value=0., desc='pi pulse', label='pi pulse') baseline = Float(value=0., desc='baseline', label='baseline') Brms = Float(value=0., desc='Brms', label='Brms [nT]') Brms2 = Float(value=0., desc='Brms', label='Brms [nT]') N = Range(low=0, high=1000, value=6, desc='number of repetitions', label='XY8-N', mode='text', auto_set=True, enter_set=True) Magnetic_field = Range(low=0., high=3000., value=330., desc='magnetic field', label='Magnetic field [G]', auto_set=False, enter_set=True) x0 = Float(value=0., desc='pi pulse', label='pi pulse') a = Float(value=9.4e-14, desc='a', label='a') g = Float(value=5e+3, desc='g', label='g') k = Float(value=0., desc='pi pulse', label='pi pulse') b = Float(value=0., desc='pi pulse', label='pi pulse') perform_fit = Bool(False, label='perform fit') number_of_resonances = Trait( 'auto', String('auto', auto_set=False, enter_set=True), Int(10000., desc='Number of Lorentzians used in fit', label='N', auto_set=False, enter_set=True)) norm_button = Button(label='filter function', desc='normalize') import_data_button = Button(label='import data', desc='import xy8') calculate_noise_spectrum_button = Button(label='calculate spectrum', desc='calculate noise spectrum') distance_to_NV_button = Button(label='calculate distance', desc='calculate distance to NV') filter_function_button = Button(label='Filter Function Fourier Transform', desc='calculate filter function') distance_from_envelope_button = Button( label='calculate distance from envelope', desc='calculate distance from envelope') check_button = Button(label='check', desc='do integration') show_calculation = Button(label='show calculation', desc='show calculation') plot_data_xy8_line = Instance(ArrayPlotData) xy8_plot = Instance(Plot, editor=ComponentEditor()) plot_data_normxy8_line = Instance(ArrayPlotData) normxy8_plot = Instance(Plot, editor=ComponentEditor()) plot_data_filter_function = Instance(ArrayPlotData) filter_function_plot = Instance(Plot, editor=ComponentEditor()) plot_data_spin_noise = Instance(ArrayPlotData) spin_noise_plot = Instance(Plot, editor=ComponentEditor()) N_tau = Range(low=0, high=50, value=6, desc='N tau', label='n tau', mode='spinner', auto_set=False, enter_set=False) line_width = Float(value=0., desc='line_width', label='linewidth [kHz]') fit_parameters = Array(value=np.array((np.nan, np.nan, np.nan, np.nan))) fit_centers = Array(value=np.array((np.nan, )), label='center_position [Hz]') fit_line_width = Array(value=np.array((np.nan, )), label='uncertanity [Hz]') fit_contrast = Array(value=np.array((np.nan, )), label='contrast [%]') error_approximation = Float(value=0.0, desc='error %', label='error %') error_depth = Float(value=0.0, desc='error', label='error [nm]') fitting_func = Enum( 'gaussian', 'loretzian', label='fit', desc='fitting function', editor=EnumEditor(values={ 'gaussian': '1:gaussian', 'loretzian': '2:loretzian' }, cols=2), ) sequence = Enum( 'XY8', 'XY16', label='sequence', desc='sequence', editor=EnumEditor(values={ 'XY8': '1:XY8', 'XY16': '2:XY16' }, cols=2), ) def __init__(self): super(Distance_to_NV, self).__init__() self._create_xy8_plot() self._create_normxy8_plot() self._create_filter_function_plot() self._create_spin_noise_plot() self.on_trait_change(self._update_line_data_fit, 'perform_fit, fitting_func,fit_parameters', dispatch='ui') self.on_trait_change(self._update_fit, 'fit, perform_fit', dispatch='ui') #self.on_trait_change(self._update_plot, 'alpha, line_width, n_FFT', dispatch='ui') def _counts_default(self): return np.zeros(self.pdawg3.fit.x_tau.shape[0]) def _counts2_default(self): return np.zeros(self.pdawg3.fit.x_tau.shape[0]) def _normalized_counts_default(self): return np.zeros(self.pdawg3.fit.x_tau.shape[0]) def _time_default(self): return np.zeros(self.pdawg3.fit.x_tau.shape[0]) def _create_normxy8_plot(self): plot_data_normxy8_line = ArrayPlotData(normalized_counts=np.array( (0., 1.)), time=np.array((0., 0.)), fit=np.array((0., 0.))) plot = Plot(plot_data_normxy8_line, width=50, height=40, padding=8, padding_left=64, padding_bottom=32) plot.plot(('time', 'normalized_counts'), color='green', line_width=2) plot.index_axis.title = 't_prime [ns]' plot.value_axis.title = 'f(t, t_prime)' #plot.title='normalized counts' self.plot_data_normxy8_line = plot_data_normxy8_line self.normxy8_plot = plot return self.normxy8_plot def _create_xy8_plot(self): plot_data_xy8_line = ArrayPlotData(counts2=np.array((0., 1.)), time=np.array((0., 0.)), fit=np.array((0., 0.))) plot = Plot(plot_data_xy8_line, width=50, height=40, padding=8, padding_left=64, padding_bottom=32) plot.plot(('time', 'counts2'), color='green', line_width=2) plot.index_axis.title = 'time [ns]' plot.value_axis.title = 'counts' #plot.title='counts' self.plot_data_xy8_line = plot_data_xy8_line self.xy8_plot = plot return self.xy8_plot def _create_filter_function_plot(self): plot_data_filter_function = ArrayPlotData(freq=np.array((0., 1.)), value=np.array((0., 0.)), fit=np.array((0., 0.))) plot = Plot(plot_data_filter_function, width=50, height=40, padding=8, padding_left=64, padding_bottom=32) plot.plot(('freq', 'value'), color='red', type='line', line_width=3) plot.index_axis.title = 'frequency [MHz]' plot.value_axis.title = 'Filter Function Fourier Transform' #plot.title='Fourier transform of filter function' self.plot_data_filter_function = plot_data_filter_function self.filter_function_plot = plot return self.filter_function_plot def _create_spin_noise_plot(self): plot_data_spin_noise = ArrayPlotData(value=np.array((0., 1.)), time=np.array((0., 0.)), fit=np.array((0., 0.))) plot = Plot(plot_data_spin_noise, width=50, height=40, padding=8, padding_left=64, padding_bottom=32) plot.plot(('time', 'value'), color='green', line_width=2) plot.index_axis.title = 'frequency [MHz]' plot.value_axis.title = 'noise spectrum [nT^2/Hz]' #plot.title='noise spectrum' line_label = PlotLabel(text='', hjustify='left', vjustify='top', position=[50, 100]) plot.overlays.append(line_label) self.line_label = line_label self.plot_data_spin_noise = plot_data_spin_noise self.spin_noise_plot = plot return self.spin_noise_plot def _import_data_button_fired(self): File1 = open(self.myfile, 'r') File2 = cPickle.load(File1) #File2.keys() if self.sequence == 'XY8': self.N = File2['measurement']['pulse_num'] elif self.sequence == 'XY16': self.N = File2['measurement']['pulse_num'] * 2 self.counts = File2['fit']['spin_state1'] self.counts2 = File2['fit']['spin_state2'] self.time = File2['measurement']['tau'] self.pi_pulse = File2['measurement']['pi_1'] self.rabi_contrast = File2['measurement']['rabi_contrast'] #self.rabi_contrast=40 counts = self.counts2 - self.counts l = (self.counts + self.counts2) / 2. self.baseline = sum(l) / len(l) C0_up = self.baseline / (1 - 0.01 * self.rabi_contrast / 2) C0_down = C0_up * (1 - 0.01 * self.rabi_contrast) counts = self.counts2 - self.counts self.normalized_counts = (counts) / (C0_up - C0_down) self.tau = (2 * self.time + self.pi_pulse) * 1e-9 # in seconds self.plot_data_xy8_line.set_data('time', self.tau * 1e+9) self.plot_data_xy8_line.set_data('counts2', self.normalized_counts) #self.fitting_func = 'loretzian' self.a = 9.4e-14 self.g = 5e+3 self._norm_button_fired() def _norm_button_fired(self): T, v = self._filter_function(self.tau[self.N_tau]) self.plot_data_normxy8_line.set_data('time', T * 1e+9) self.plot_data_normxy8_line.set_data('normalized_counts', v) def _calculate_noise_spectrum_button_fired(self): # Noise spectrum #g=2*np.pi*2.8*1e+10 #Hz/T #g=2*np.pi*2.8*10 #Hz/nT #T=self.tau*8*self.N+0.5*self.pi_pulse*1e-9 #S=-np.log(self.normalized_counts)*2/(g**2*T) # noise spectrum #self.plot_data_spin_noise.set_data('value', self.S*1e18) #elf.plot_data_spin_noise.set_data('time', (1/(2*self.tau))*1e-6) #0 approximation x0 = 1 / (2 * self.tau[np.argmin(self.normalized_counts)]) g0 = self.g a0 = self.a self._fourier_transform(self.tau[0]) freq = self.FFx d = self.FFx[1] - self.FFx[0] delta = 0.05 FFx = np.zeros((len(self.tau), len(freq))) FFy = np.zeros((len(self.tau), len(freq))) for i in range(len(self.tau)): self._fourier_transform( self.tau[i]) # now we have self.FFx and self.FFy FFx[i][:] = self.FFx FFy[i][:] = self.FFy**2 dif2 = 1 dif1 = 1 dif = 1 dif0 = 1 self.k = 0.0 self.b = 0.0 self.x0 = x0 self.g = g0 self.a = a0 #b=x0/5.0 k = 0.0 b = 0.0 # find background====================================================================================================================================================================================================== sequence = np.where( self.normalized_counts >= max(self.normalized_counts) * 0.9)[0] uy = np.take(self.normalized_counts, sequence) while True: # optimize background self.b = b dif = dif1 dif2 = 1 k = 0 while True: k = (k - 0.1) * 1e-8 SS = (k * freq + b) * 1e-18 dif1 = dif2 hi = [] for i in sequence: Int = trapz(SS * FFy[i][:], dx=d) * 1e+18 # integration hi.append(Int) hi = [-x for x in hi] cc = np.exp(hi) dif2 = np.sqrt(sum((cc - uy)**2) / (len(uy) - 1)) #dif2=np.abs(np.sum((cc-uy)/cc)/len(uy)) #dif2=np.std(cc-uy) if dif2 >= dif1: break b = b + 0.001 self.k = k if dif1 >= dif: break dif2 = 1 dif1 = 1 dif = 1 ux = np.linspace(x0 * 0.98, x0 * 1.02, 40) x0 = 1 / (2 * self.tau[np.argmin(self.normalized_counts)]) g = g0 a = a0 while True: self.g = g a = a0 dif = dif1 while True: #optimize amplitude a = a * 1.1 S = (a / np.pi) * g / ( (freq - x0)**2 + g**2) + (self.k * freq + self.b) * 1e-18 dif1 = dif2 hi = [] for i in range(len(self.tau)): Int = trapz(S * FFy[i][:], dx=d) * 1e+18 # integration hi.append(Int) hi = [-x for x in hi] calculated_counts = np.exp(hi) dif2 = np.sqrt( sum((calculated_counts - self.normalized_counts)**2) / (len(calculated_counts) - 1)) #dif2=np.std(calculated_counts-self.normalized_counts) #dif2=np.abs(np.sum((calculated_counts-self.normalized_counts)/calculated_counts)/len(calculated_counts)) if dif2 >= dif1: break self.a = a dif2 = dif1 g = g - 200 if dif1 >= dif: break param = np.zeros((40)) for i in range(len(ux)): # optimize position S = (self.a / np.pi) * self.g / ((freq - ux[i])**2 + self.g**2) + ( self.k * freq + self.b) * 1e-18 hi = [] for j in range(len(self.tau)): Int = trapz(S * FFy[j][:], dx=d) * 1e+18 # integration hi.append(Int) hi = [-x for x in hi] calculated_counts = np.exp(hi) #param[i]=np.abs(np.sum((calculated_counts-self.normalized_counts)/calculated_counts)/len(calculated_counts)) param[i] = np.std(calculated_counts - self.normalized_counts) self.x0 = ux[np.argmin(param)] dif2 = 1 dif1 = 1 dif = 1 g = g0 while True: self.g = g a = a0 dif = dif1 while True: #optimize amplitude a = a * 1.1 S = (a / np.pi) * g / ((freq - self.x0)**2 + g**2) + (self.k * freq + self.b) * 1e-18 dif1 = dif2 hi = [] for i in range(len(self.tau)): Int = trapz(S * FFy[i][:], dx=d) * 1e+18 # integration hi.append(Int) hi = [-x for x in hi] calculated_counts = np.exp(hi) #dif2=np.std(calculated_counts-self.normalized_counts) #dif2=np.abs(np.sum((calculated_counts-self.normalized_counts)/calculated_counts)/len(calculated_counts)) dif2 = np.sqrt( sum((calculated_counts - self.normalized_counts)**2) / (len(calculated_counts) - 1)) if dif2 >= dif1: break self.a = a dif2 = dif1 g = g - 200 if dif1 >= dif: break self._show_calculation_button_fired() def _show_calculation_button_fired(self): d = self.FFx[1] - self.FFx[0] FFx = np.zeros((len(self.tau), len(self.FFx))) FFy = np.zeros((len(self.tau), len(self.FFx))) for i in range(len(self.tau)): self._fourier_transform( self.tau[i]) # now we have self.FFx and self.FFy FFx[i][:] = self.FFx FFy[i][:] = self.FFy**2 self.S = (self.a / np.pi) * self.g / ( (self.FFx - self.x0)**2 + self.g**2) + (self.k * self.FFx + self.b) * 1e-18 #self.S=(self.k*self.FFx+self.b)*1e-18 #self.S=np.exp(-(self.FFx+self.FFx[0])/self.b)*1e-18 self.plot_data_spin_noise.set_data('value', self.S * 1e18) self.plot_data_spin_noise.set_data('time', self.FFx * 1e-6) hi = [] hi1 = [] for i in range(len(self.tau)): Int = trapz(self.S * FFy[i][:], dx=d) * 1e+18 # integration hi.append(Int) Int1 = trapz((self.k * self.FFx + self.b) * FFy[i][:], dx=d) # integration hi1.append(Int1) hi = [-x for x in hi] hi1 = [-x for x in hi1] calculated_counts = np.exp(hi) plot = self.xy8_plot plot.plot(('time', 'fit'), color='purple', line_width=2) self.plot_data_xy8_line.set_data('fit', calculated_counts) self.error_approximation = 100 * np.sum( np.abs(self.normalized_counts - calculated_counts) / calculated_counts) / len(self.normalized_counts) self.plot_data_xy8_line.set_data('x1', self.tau * 1e+9) self.plot_data_xy8_line.set_data('y1', np.exp(hi1)) self.xy8_plot.plot(('x1', 'y1'), color='red', line_width=2) def _filter_function(self, tau): #generate filter function dt = 1e-9 n = int(tau / dt) v = np.zeros(8 * self.N * n) T = np.linspace(0, dt * n * 8 * self.N, num=8 * self.N * n) v[:n / 2] = 1 k = n / 2 + 1 for j in range(8 * self.N - 1): v[(n / 2 + j * n):(n / 2 + j * n + n)] = (-1)**(j + 1) k = k + 1 v[8 * self.N * n - n / 2:8 * self.N * n] = np.ones((n / 2, ), dtype=np.int) return T, v def _fourier_transform(self, tau): T, v = self._filter_function(tau) g = int(self.n_FFT) signalFFT = np.fft.fft(v, g) yf = (np.abs(signalFFT)**2) * (1e-9) / (8 * self.N) xf = np.fft.fftfreq(g, 1e-9) self.FFy = yf[0:g] #take only real part self.FFx = xf[0:g] f1 = (1 / (2 * self.tau[0])) * 1.03 #bigger f2 = (1 / (2 * self.tau[-1])) * 0.97 #smaller yf1 = self.FFy[np.where(self.FFx <= f1)] xf1 = self.FFx[np.where(self.FFx <= f1)] self.FFy = self.FFy[np.where(xf1 >= f2)] self.FFx = self.FFx[np.where(xf1 >= f2)] def _filter_function_button_fired(self): self._fourier_transform(self.tau[self.N_tau]) self.plot_data_filter_function.set_data('value', self.FFy) self.plot_data_filter_function.set_data('freq', self.FFx * 1e-6) self.pulse_spacing = self.tau[self.N_tau] * 1e+9 def _iteration(self): self._fourier_transform(self.tau[0]) d = self.FFx[1] - self.FFx[0] # step of the frequency grid N = len(self.FFx) hi = -np.log(self.normalized_counts) q = N / len(self.normalized_counts) fd = np.ones((N)) * hi[-1] # generate enought amount of points time = np.ones((N)) * self.tau[-1] for i in range(len(self.normalized_counts)): fd[i * q:i * q + q] = hi[i] time[i * q:i * q + q] = self.tau[i] FFx = np.zeros((N, N)) FFy = np.zeros((N, N)) for i in range(N): self._fourier_transform( time[i]) # now we have self.FFx and self.FFy FFx[i][:] = self.FFx FFy[i][:] = self.FFy**2 As = np.zeros((N)) # operator on the grid s = np.zeros((N)) # Noise spectrum for i in range(N): As[i] = sum(s * FFy[i][:]) * d delta = 0.001 step = 0 # iteration process while True: r = As - fd #nevyazka Ar = np.zeros((N)) # operator on the grid for i in range(N): Ar[i] = sum(r * FFy[i][:]) * d tau = sum(r * r) / sum(Ar * r) #tau=0.01 s = s - tau * Ar for i in range(N): As[i] = sum(s * FFy[i][:]) * d norma = np.sqrt(sum((As - fd)**2) / N) step = step + 1 if norma < delta or step == 2000: break return s def _check_button_fired(self): #we have calculated noise spectrum #for each free evolution time we perform Fourier transform and integrate from 0 to inf with fit of the noise spectrum hi = [] if self.fitting_func == 'loretzian': fit_func = fitting.NLorentzians elif self.fitting_func == 'gaussian': fit_func = fitting.NGaussian self._fourier_transform(self.tau[0]) FFx = np.zeros((len(self.tau), len(self.FFx))) FFy = np.zeros((len(self.tau), len(self.FFx))) for i in range(len(self.tau)): self._fourier_transform( self.tau[i]) # now we have self.FFx and self.FFy FFx[i][:] = self.FFx FFy[i][:] = self.FFy**2 d = self.FFx[1] - self.FFx[0] S = fit_func(*self.fit_parameters)(self.FFx * 1e-6) # fit for intergration for i in range(len(self.tau)): Int = trapz(S * FFy[i][:], dx=d) # integration hi.append(Int) hi = [-x for x in hi] calculated_counts = np.exp(hi) self.plot_data_xy8_line.set_data('fit', calculated_counts) plot = self.xy8_plot plot.plot(('time', 'fit'), color='purple', line_width=2) self.error_approximation = 100 * np.sum( np.abs(calculated_counts - self.normalized_counts) / calculated_counts) / len(self.normalized_counts) def _distance_to_NV_button_fired(self): rho_H = 5 * 1e+28 # m^(-3), density of protons rho_B11 = 2.1898552552552544e+28 # m^(-3), density of B11 mu_p = 1.41060674333 * 1e-26 # proton magneton, J/T g_B11 = 85.847004 * 1e+6 / (2 * np.pi) # Hz/T hbar = 1.054571800e-34 #J*s mu_B11 = hbar * g_B11 * 2 * np.pi # for central transition if self.substance == 'immersion oil, H1 signal': rho = rho_H mu = mu_p elif self.substance == 'hBN, B11 signal': rho = rho_B11 mu = mu_B11 g = 2 * np.pi * 2.8 * 1e+10 #rad/s/T mu0 = 4 * np.pi * 1e-7 # vacuum permeability, H/m or T*m/A freq = self.FFx # in Hz d = self.FFx[1] - self.FFx[0] S = self.S * 1e+18 base = (self.k * self.FFx + self.b) Int = trapz((S - base), dx=d) # integration self.Brms = np.sqrt(2 * Int) if self.substance == 'immersion oil, H1 signal': self.z = np.power(rho * ((0.05 * mu0 * mu / self.Brms * 1e9)**2), 1 / 3.) elif self.substance == 'hBN, B11 signal': C1 = np.sqrt(0.654786) / (4 * np.pi) self.z = np.power(rho * ((C1 * mu0 * mu / self.Brms * 1e9)**2), 1 / 3.) self.z = self.z * 1e+9 self.error_depth = self.error_approximation * self.z / 100 x1 = freq * 1e-6 #baseline y1 = base x_key1 = 'x1' y_key1 = 'y1' self.plot_data_spin_noise.set_data(x_key1, x1) self.plot_data_spin_noise.set_data(y_key1, y1) self.spin_noise_plot.plot((x_key1, y_key1), color='red', line_width=1) #convolution # Sum=np.ones(len(self.tau)) # for i in range(len(self.tau)): # self._fourier_transform(self.tau[i]) # self.FFy=self.FFy[np.where(self.FFx<=freq[0]*1.05)] # fit_x=self.FFx[np.where(self.FFx<=freq[0]*1.05)] # self.FFy=self.FFy[np.where(fit_x>=freq[-1]*0.95)] # S0=0 # for j in range(len(S)): # S0=S0+S[j]*self.FFy[j]*1e-18/self.alpha # Sum[i]=S0 # hi=((g**2)/2.)*Sum # calculated_counts=np.exp(-hi) # x3 =self.tau*1e+9 # y3 = calculated_counts # x_key3 = 'x3' # y_key3 = 'y3' # self.plot_data_normxy8_line.set_data(x_key3, x3) # self.plot_data_normxy8_line.set_data(y_key3, y3) # self.normxy8_plot.plot((x_key3, y_key3), color='red', line_width = 1) #fitting--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- def _perform_fit_changed(self, new): plot = self.spin_noise_plot x_name = self.plot_data_spin_noise.list_data()[2] if new: plot.plot(('time', 'fit'), style='line', color='blue', name='fit', line_width=1) self.line_label.visible = True self.line_width = self.fit_parameters[2] else: plot.delplot('fit') self.line_label.visible = False plot.request_redraw() def _update_fit(self): if self.perform_fit: if self.fitting_func == 'loretzian': fit_func = fitting.fit_multiple_lorentzians elif self.fitting_func == 'gaussian': fit_func = fitting.fit_multiple_gaussian N = self.number_of_resonances # number of peaks #fit_x = self.FFx fit_x = (1 / (2 * self.tau)) * 1e-6 self.counts = self.S * 1e18 p = fit_func(fit_x, self.counts, N, threshold=self.fit_threshold * 0.01) else: p = np.nan * np.empty(4) self.fit_parameters = p self.fit_centers = p[1::3] self.fit_line_width = p[2::3] N = len(p) / 3 contrast = np.empty(N) c = p[0] pp = p[1:].reshape((N, 3)) for i, pn in enumerate(pp): a = pn[2] g = pn[1] A = np.abs(a / (np.pi * g)) if a > 0: contrast[i] = 100 * A / (A + c) else: contrast[i] = 100 * A / c self.fit_contrast = contrast self.line_width = self.fit_parameters[2] #self.frequencies=self.centers[1]*1e+6 def _update_line_data_fit(self): if not np.isnan(self.fit_parameters[0]): if self.fitting_func == 'loretzian': fit_func = fitting.NLorentzians elif self.fitting_func == 'gaussian': fit_func = fitting.NGaussian #fit_x = self.FFx # fit_x = (1 / (2 * self.tau)) * 1e-6 self.plot_data_spin_noise.set_data( 'fit', fit_func(*self.fit_parameters)((1 / (2 * self.tau)) * 1e-6)) p = self.fit_parameters f = p[1::3] w = p[2::3] N = len(p) / 3 contrast = np.empty(N) c = p[0] pp = p[1:].reshape((N, 3)) for i, pi in enumerate(pp): a = pi[2] g = pi[1] A = np.abs(a / (np.pi * g)) if a > 0: contrast[i] = 100 * A / (A + c) else: contrast[i] = 100 * A / c s = '' for i, fi in enumerate(f): s += '%.2f MHz, LW %.2f kHz, contrast %.1f%%\n' % (fi, w[i], contrast[i]) self.line_label.text = s self.line_width = self.fit_parameters[2] def _update_plot(self): self._distance_to_NV_button_fired() # self._ditance_button_fired() # self._ditance_button_fired() # self._ditance_button_fired() def save_all(self, filename): self.save_figure(self.xy8_plot, filename + 'XY8-' + str(self.N) + '_counts' + '.png') self.save_figure( self.normxy8_plot, filename + 'XY8-' + str(self.N) + '_normalized_counts' + '.png') self.save_figure( self.spin_noise_plot, filename + 'XY8-' + str(self.N) + '_noise_spectrum_z=' + string.replace(str(self.z)[0:4], '.', 'd') + 'nm_B=' + string.replace(str(self.Brms)[0:4], '.', 'd') + 'nT.png') self.save(filename + 'XY8-' + str(self.N) + '_distance' + '.pyd') self.save_figure( self.second_method_plot, filename + 'XY8-' + str(self.N) + '_noise_spectrum_z=' + string.replace(str(self.z2)[0:4], '.', 'd') + 'nm_B=' + string.replace(str(self.Brms2)[0:4], '.', 'd') + 'nT.png') traits_view = View( VGroup( HGroup( VGroup( HGroup(Item('myfile', show_label=False), Item('import_data_button', show_label=False), Item('substance', style='custom', show_label=False)), HGroup(Item('xy8_plot', show_label=False, resizable=True), ), HGroup(Item('filter_function_button', show_label=False)), HGroup(Item('N_tau', width=-40), Item('pulse_spacing', width=-40, format_str='%.1f'), Item('n_FFT', width=-70)), HGroup( Item('filter_function_plot', show_label=False, resizable=True), ), ), VGroup( HGroup( #Item('norm_button', show_label=False), Item('rabi_contrast', width=-40), Item('N', width=-40), ), HGroup( Item('normxy8_plot', show_label=False, resizable=True)), HGroup( Item('sequence', style='custom', show_label=False), Item('calculate_noise_spectrum_button', show_label=False), #Item('check_button', show_label=False), Item('show_calculation', show_label=False), Item('a', width=-60, format_str='%.1e'), Item('g', width=-60, format_str='%.1e')), # HGroup( Item('fit_threshold', width= -40), # Item('perform_fit'), # Item('number_of_resonances', width= -60), # ), HGroup( Item('spin_noise_plot', show_label=False, resizable=True)), ), ), HGroup( #Item('alpha', width= -60, format_str='%.2f'), #Item('line_width', width= -60, format_str='%.2f'), #Item('fitting_func', style='custom', show_label=False), Item('distance_to_NV_button', show_label=False), Item('z', width=-60, style='readonly', format_str='%.1f'), Item('error_depth', width=-60, style='readonly', format_str='%.1f'), Item('error_approximation', width=-60, style='readonly', format_str='%.1f'), Item('Brms', width=-60, style='readonly', format_str='%.0f'))), menubar=MenuBar( Menu(Action(action='Save_All', name='Save all'), Action(action='load', name='Load'), name='File')), title='NV depth', width=1200, height=800, buttons=[], resizable=True, handler=DistanceHandler) get_set_items = [ 'N_tau', 'pulse_spacing', 'rabi_contrast', 'N', 'alpha', 'line_width', 'S', 'time', 'counts', 'counts2', 'z', 'Brms', 'normalized_counts', 'tau', 'fit_parameters', 'fit_centers', 'fit_contrast', 'fit_line_width', 'fitting_func', 'n_FFT', '__doc__' ]
def _menubar_factory(self): ''' ''' menus = self.menus_factory() return MenuBar(*menus)
class PLE(ManagedJob, GetSetItemsMixin): """Provides PLE measurements.""" keep_data = Bool( False) # helper variable to decide whether to keep existing data resubmit_button = Button( label='resubmit', desc= 'Submits the measurement to the job manager. Tries to keep previously acquired data. Behaves like a normal submit if sequence or time bins have changed since previous run.' ) mw = Enum('off', 'on', desc='switching MW on and off', label='MW') mw_frequency = Range(low=1, high=20e9, value=2.8770e9, desc='microwave frequency', label='MW frequency [Hz]', mode='text', auto_set=False, enter_set=True) mw_power = Range(low=-100., high=25., value=-5.0, desc='microwave power', label='MW power [dBm]', mode='text', auto_set=False, enter_set=True) green = Enum('off', 'on', 'pulse', desc='Green laser control', label='Green') light = Enum('light', 'night', desc='Status control', label='Light') off_mw = Enum('off', 'on', desc='MW control when not running', label='MW when not running') off_red = Enum('off', 'on', desc='red laser control when not running', label='red when not running') off_green = Enum('off', 'on', desc='Green laser control when not running', label='Green for red when not running') green_length = Range(low=1e-3, high=10., value=0.5, desc='TTL On [s]', label='Green laser [s]', mode='text', auto_set=False, enter_set=True) switch = Enum('fix wave', 'scan wave', desc='switching from large scan to small scan', label='scan mode') red = Enum('off', 'on', desc='switching Red laser on and off', label='Red', auto_set=False, enter_set=True) wavelength = Range(low=636.0, high=639.0, value=636.86, desc='Wavelength[nm]', label='Red Wavelength [nm]', auto_set=False, enter_set=True) current = Range(low=0.0, high=80.0, value=0., desc='Current of red [mA]', label='Red Current [mA]', auto_set=False, enter_set=True) detuning = Range(low=-45.0, high=45.0, value=0., desc='detuning', label='Red detuning [GHz]', auto_set=False, enter_set=True) go_detuning = Bool(False, label='Go to detuning') lock_box = Bool(False, label='lockbox mode') red_monitor = Enum('on', 'off', desc='red laser status', label='Red Status') wavelength_monitor = Range(low=0.0, high=639.0, value=0.0, desc='Wavelength[nm]', label='Red Wavelength [nm]') current_monitor = Range(low=0.0, high=150.0, value=0.0, desc='Current of red [mA]', label='Red Current [mA]') power_monitor = Range(low=0.0, high=20.0, value=0.0, desc='power of red [mW]', label='Red Power [mW]') detuning_monitor = Range(low=-50., high=50., value=0., desc='detuning', label='detuning freq [GHz]') scan_begin = Range(low=636., high=639., value=636.5, desc='Start Wavelength [nm]', label='Start Wavelength [nm]') scan_end = Range(low=636., high=639., value=637.5, desc='Stop Wavelength [nm]', label='Stop Wavelength [nm]') scan_rate = Range(low=0.01, high=1., value=1.0e-2, desc='Scan rate[nm/s]', label='Scan Rate [nm/s]') detuning_begin = Range(low=-45.0, high=45.0, value=-45.0, desc='Start detuning [GHz]', label='Begin detuning [GHz]') detuning_end = Range(low=-45.0, high=45.0, value=45.0, desc='Stop detuning [GHz]', label='End detuning [GHz]') number_points = Range(low=1, high=1e5, value=1000, desc='number of points', label='number of points') #detuning_delta = Range(low=0.0, high=45.0, value=0.10, desc='detuning step[GHz]', label='Delta detuning [GHz]') seconds_per_point = Range(low=1.0e-4, high=1, value=2.0e-3, desc='Seconds per point', label='Seconds per point', mode='text', auto_set=False, enter_set=True) n_lines = Range(low=1, high=10000, value=50, desc='Number of lines in Matrix', label='Matrix lines', mode='text', auto_set=False, enter_set=True) stop_time = Range( low=1., value=np.inf, desc='Time after which the experiment stops by itself [s]', label='Stop time [s]', mode='text', auto_set=False, enter_set=True) run_time = Float(value=0.0, desc='Run time [s]', label='Run time [s]') detuning_mesh = Array() counts = Array() single_line_counts = Array() counts_matrix = Array() # plotting line_data = Instance(ArrayPlotData) single_line_data = Instance(ArrayPlotData) matrix_data = Instance(ArrayPlotData) line_plot = Instance(Plot, editor=ComponentEditor()) single_line_plot = Instance(Plot, editor=ComponentEditor()) matrix_plot = Instance(Plot, editor=ComponentEditor()) def __init__(self): super(PLE, self).__init__() self._create_line_plot() self._create_single_line_plot() self._create_matrix_plot() self.on_trait_change(self._update_index, 'detuning_mesh', dispatch='ui') self.on_trait_change(self._update_line_data_value, 'counts', dispatch='ui') self.on_trait_change(self._update_single_line_data_value, 'single_line_counts', dispatch='ui') self.on_trait_change(self._update_matrix_data_value, 'counts_matrix', dispatch='ui') self.on_trait_change(self._update_matrix_data_index, 'n_lines,detuning', dispatch='ui') self.red_monitor = ha.LaserRed().check_status() self.red = self.red_monitor ha.LaserRed().set_output(self.current, self.wavelength) self.wavelength_monitor = ha.LaserRed().get_wavelength() self.current_monitor = ha.LaserRed().get_current() self.power_monitor = ha.LaserRed().get_power() self.detuning_monitor = ha.LaserRed().get_detuning() def submit(self): """Submit the job to the JobManager.""" self.keep_data = False ManagedJob.submit(self) def resubmit(self): """Submit the job to the JobManager.""" self.keep_data = True ManagedJob.submit(self) def _resubmit_button_fired(self): """React to start button. Submit the Job.""" if self.switch == 'scan wave': ha.LaserRed().resume_scan() self.resubmit() @on_trait_change('red') def _open_laser(self): if self.red == 'on': ha.LaserRed().on() time.sleep(7.0) self.red_monitor = ha.LaserRed().check_status() elif self.red == 'off': ha.LaserRed().off() time.sleep(1.0) self.red_monitor = ha.LaserRed().check_status() @on_trait_change('off_mw') def _off_mw_control(self): if self.state == 'idle': if self.off_mw == 'on': ha.Microwave().setOutput(self.mw_power, self.mw_frequency) else: ha.Microwave().setOutput(None, self.mw_frequency) @on_trait_change('off_green,off_red,off_mw') def _off_control(self): if self.state == 'idle' and self.light == 'night' and self.off_red == 'on': if self.off_green == 'on' and self.off_mw == 'on': ha.PulseGenerator().Continuous(['mw', 'mw_x', 'red', 'green']) elif self.off_green == 'off' and self.off_mw == 'on': ha.PulseGenerator().Continuous(['mw', 'mw_x', 'red']) elif self.off_green == 'on' and self.off_mw == 'off': ha.PulseGenerator().Continuous(['red', 'green']) elif self.off_green == 'off' and self.off_mw == 'off': ha.PulseGenerator().Continuous(['red']) elif self.state == 'idle' and self.off_red == 'off' and self.light == 'light': ha.PulseGenerator().Light() elif self.state == 'idle' and self.off_red == 'off' and self.light == 'night': ha.PulseGenerator().Night() @on_trait_change('light') def _set_day(self): if self.state == 'idle': if self.light == 'light': ha.PulseGenerator().Light() elif self.off_red == 'on': if self.off_green == 'on' and self.off_mw == 'on': ha.PulseGenerator().Continuous( ['mw', 'mw_x', 'red', 'green']) elif self.off_green == 'off' and self.off_mw == 'on': ha.PulseGenerator().Continuous(['mw', 'mw_x', 'red']) elif self.off_green == 'on' and self.off_mw == 'off': ha.PulseGenerator().Continuous(['red', 'green']) elif self.off_green == 'off' and self.off_mw == 'off': ha.PulseGenerator().Continuous(['red']) else: ha.PulseGenerator().Night() @on_trait_change('current,wavelength') def _set_laser(self): """React to set laser button. Submit the Job.""" ha.LaserRed().set_output(self.current, self.wavelength) self.wavelength_monitor = ha.LaserRed().get_wavelength() self.current_monitor = ha.LaserRed().get_current() self.power_monitor = ha.LaserRed().get_power() @on_trait_change('detuning,go_detuning') def _detuning_changed(self, detuning): """React to set laser button. Submit the Job.""" if self.go_detuning: ha.LaserRed().set_detuning(detuning) self.detuning_monitor = ha.LaserRed().get_detuning() def apply_parameters(self): """Apply the current parameters and decide whether to keep previous data.""" step = (self.detuning_end - self.detuning_begin) / float( self.number_points) detuning_mesh = np.arange(self.detuning_begin, self.detuning_end, step) if not self.keep_data or np.any(detuning_mesh != self.detuning_mesh): self.counts = np.zeros(detuning_mesh.shape) self.run_time = 0.0 self.detuning_mesh = detuning_mesh self.keep_data = True # when job manager stops and starts the job, data should be kept. Only new submission should clear data. def _run(self): try: self.state = 'run' self.apply_parameters() if self.run_time >= self.stop_time: self.state = 'done' return n = len(self.detuning_mesh) self.red_monitor = ha.LaserRed().check_status() if self.red_monitor == 'off': ha.LaserRed().on() time.sleep(7.0) self.red_monitor = ha.LaserRed().check_status() #ha.LaserRed().set_output(self.current, self.wavelength) ha.Microwave().setOutput(self.mw_power, self.mw_frequency) time.sleep(0.5) if self.switch == 'scan wave': ha.LaserRed().scan(self.scan_begin, self.scan_end, self.scan_rate) self.wavelength_monitor = ha.LaserRed().get_wavelength() self.detuning_monitor = ha.LaserRed().get_detuning() while self.run_time < self.stop_time: start_time = time.time() if threading.currentThread().stop_request.isSet(): break if self.green == 'pulse': if self.mw == 'on': ha.PulseGenerator().Continuous( ['mw', 'mw_x', 'red', 'green']) else: ha.PulseGenerator().Continuous(['red', 'green']) time.sleep(self.green_length) if self.mw == 'on' and self.green == 'on': ha.PulseGenerator().Continuous( ['green', 'mw', 'mw_x', 'red']) elif self.mw == 'off' and self.green == 'on': ha.PulseGenerator().Continuous(['green', 'red']) elif self.mw == 'on' and (self.green == 'off' or self.green == 'pulse'): ha.PulseGenerator().Continuous(['mw', 'mw_x', 'red']) elif self.mw == 'off' and (self.green == 'off' or self.green == 'pulse'): ha.PulseGenerator().Continuous(['red']) if self.lock_box: #voltage = ha.LaserRed()._detuning_to_voltage(self.detuning_end) step = (self.detuning_begin - self.detuning_end) / float( self.number_points) detuning_mesh = np.arange(self.detuning_end, self.detuning_begin, step) counts = ha.LaserRed().piezo_scan(detuning_mesh, self.seconds_per_point) junk = ha.LaserRed().piezo_scan(self.detuning_mesh, self.seconds_per_point) self.single_line_counts = counts self.counts += counts self.trait_property_changed('counts', self.counts) self.counts_matrix = np.vstack( (counts, self.counts_matrix[:-1, :])) time.sleep(0.1) else: counts = ha.LaserRed().piezo_scan(self.detuning_mesh, self.seconds_per_point) #ha.LaserRed().set_detuning(self.detuning_begin) #time.sleep(0.1) self.run_time += time.time() - start_time self.single_line_counts = counts self.counts += counts self.trait_property_changed('counts', self.counts) self.counts_matrix = np.vstack( (counts, self.counts_matrix[:-1, :])) """ return to origin """ voltage = ha.LaserRed()._detuning_to_voltage( self.detuning_end) junks = ha.LaserRed().ni_task.line( np.arange(voltage, -3.0, ha.LaserRed()._detuning_to_voltage(-0.1)), 0.001) ha.LaserRed().ni_task.point(-3.0) voltage = ha.LaserRed()._detuning_to_voltage( self.detuning_begin) if voltage > -2.90: junks = ha.LaserRed().ni_task.line( np.arange(-3.0, voltage, ha.LaserRed()._detuning_to_voltage(0.1)), 0.001) ha.LaserRed().ni_task.point(voltage) time.sleep(0.1) self.wavelength_monitor = ha.LaserRed().get_wavelength() self.detuning_monitor = ha.LaserRed().get_detuning() if self.run_time < self.stop_time: self.state = 'idle' else: self.state = 'done' if self.switch == 'scan wave': ha.LaserRed().stop_scan() ha.LaserRed().set_detuning(self.detuning) #ha.Microwave().setOutput(None, self.mw_frequency) if self.light == 'light': ha.PulseGenerator().Light() ha.Microwave().setOutput(None, self.mw_frequency) elif self.off_red == 'on': if self.off_green == 'on' and self.off_mw == 'on': ha.PulseGenerator().Continuous( ['mw', 'mw_x', 'red', 'green']) elif self.off_green == 'off' and self.off_mw == 'on': ha.PulseGenerator().Continuous(['mw', 'mw_x', 'red']) elif self.off_green == 'on' and self.off_mw == 'off': ha.Microwave().setOutput(None, self.mw_frequency) ha.PulseGenerator().Continuous(['red', 'green']) elif self.off_green == 'off' and self.off_mw == 'off': ha.Microwave().setOutput(None, self.mw_frequency) ha.PulseGenerator().Continuous(['red']) else: ha.Microwave().setOutput(None, self.mw_frequency) ha.PulseGenerator().Night() except: logging.getLogger().exception('Error in PLE.') self.state = 'error' # plotting def _create_line_plot(self): line_data = ArrayPlotData(frequency=np.array((0., 1.)), counts=np.array((0., 0.)), fit=np.array((0., 0.))) line_plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=32) line_plot.plot(('frequency', 'counts'), style='line', color='blue') line_plot.index_axis.title = 'Detuning [GHz]' line_plot.value_axis.title = 'Fluorescence counts' self.line_data = line_data self.line_plot = line_plot def _create_single_line_plot(self): line_data = ArrayPlotData(frequency=np.array((0., 1.)), counts=np.array((0., 0.)), fit=np.array((0., 0.))) line_plot = Plot(line_data, padding=8, padding_left=64, padding_bottom=32) line_plot.plot(('frequency', 'counts'), style='line', color='blue') line_plot.index_axis.title = 'Detuning [GHz]' line_plot.value_axis.title = 'Fluorescence counts' self.single_line_data = line_data self.single_line_plot = line_plot def _create_matrix_plot(self): matrix_data = ArrayPlotData(image=np.zeros((2, 2))) matrix_plot = Plot(matrix_data, padding=8, padding_left=64, padding_bottom=32) matrix_plot.index_axis.title = 'Detuning [GHz]' matrix_plot.value_axis.title = 'line #' matrix_plot.img_plot('image', xbounds=(self.detuning_mesh[0], self.detuning_mesh[-1]), ybounds=(0, self.n_lines), colormap=Spectral) self.matrix_data = matrix_data self.matrix_plot = matrix_plot def _counts_matrix_default(self): return np.zeros((self.n_lines, len(self.detuning_mesh))) @on_trait_change('detuning_begin,detuning_end,number_points') def _detuning_mesh_(self): step = (self.detuning_end - self.detuning_begin) / float( self.number_points) self.detuning_mesh = np.arange(self.detuning_begin, self.detuning_end, step) self.counts = np.zeros(self.detuning_mesh.shape) self.single_line_counts = np.zeros(self.detuning_mesh.shape) self.counts_matrix = np.zeros((self.n_lines, len(self.detuning_mesh))) self.line_data.set_data('frequency', self.detuning_mesh) self.single_line_data.set_data('frequency', self.detuning_mesh) def _detuning_mesh_default(self): step = (self.detuning_end - self.detuning_begin) / float( self.number_points) return np.arange(self.detuning_begin, self.detuning_end, step) def _counts_default(self): return np.zeros(self.detuning_mesh.shape) def _single_line_counts_default(self): return np.zeros(self.detuning_mesh.shape) def _update_index(self): self.line_data.set_data('frequency', self.detuning_mesh) self.single_line_data.set_data('frequency', self.detuning_mesh) self.counts_matrix = self._counts_matrix_default() def _update_line_data_value(self): self.line_data.set_data('counts', self.counts) def _update_single_line_data_value(self): self.single_line_data.set_data('counts', self.single_line_counts) def _update_matrix_data_value(self): self.matrix_data.set_data('image', self.counts_matrix) def _update_matrix_data_index(self): if self.n_lines > self.counts_matrix.shape[0]: self.counts_matrix = np.vstack( (self.counts_matrix, np.zeros((self.n_lines - self.counts_matrix.shape[0], self.counts_matrix.shape[1])))) else: self.counts_matrix = self.counts_matrix[:self.n_lines] self.matrix_plot.components[0].index.set_data( (self.detuning_mesh[0], self.detuning_mesh[-1]), (0.0, float(self.n_lines))) def save_line_plot(self, filename): self.save_figure(self.line_plot, filename) def save_single_line_plot(self, filename): self.save_figure(self.single_line_plot, filename) def save_matrix_plot(self, filename): self.save_figure(self.matrix_plot, filename) def save_as_text(self, filename): matsave = np.vstack((self.detuning_mesh, self.counts_matrix)) np.savetxt(filename, matsave) def save_all(self, filename): self.save_line_plot(filename + '_PLE_Line_Plot.png') self.save_single_line_plot(filename + '_PLE_SingleLine_Plot.png') self.save_matrix_plot(filename + '_PLE_Matrix_Plot.png') self.save_as_text(filename + '_PLE_.txt') self.save(filename + '_PLE.pys') traits_view = View( VGroup( HGroup( Item('submit_button', show_label=False), Item('remove_button', show_label=False), Item('resubmit_button', show_label=False), Item('priority'), Item('state', style='readonly'), Item('n_lines'), Item('run_time', style='readonly', format_str='%.f'), ), Group( HGroup( Item('mw', style='custom'), Item('mw_frequency', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_func=lambda x: '%e' % x)), Item('mw_power', width=-40, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('green', style='custom'), Item('green_length', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float, format_func=lambda x: '%e' % x)), ), HGroup( Item('light', style='custom'), Item('off_mw', style='custom'), Item('off_red', style='custom'), Item('off_green', style='custom'), Item('lock_box', style='custom'), ), HGroup( Item('red', style='custom', enabled_when='state == "idle"'), Item('red_monitor', width=-20, style='readonly'), Item('wavelength', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('wavelength_monitor', width=-80, style='readonly'), Item('current', width=-40, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('current_monitor', width=-40, style='readonly'), Item('power_monitor', width=-40, style='readonly'), Item('detuning', width=-40, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('detuning_monitor', width=-40, style='readonly'), Item('go_detuning'), ), HGroup( Item('switch', style='custom', enabled_when='state == "idle"'), Item('scan_begin', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('scan_end', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('scan_rate', width=-80, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('detuning_begin', width=-40, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('detuning_end', width=-40, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('number_points', width=-40, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), #Item('detuning_delta', width= -40, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), Item('seconds_per_point', width=-40, editor=TextEditor(auto_set=False, enter_set=True, evaluate=float)), ), ), VSplit( Item('matrix_plot', show_label=False, resizable=True), Item('single_line_plot', show_label=False, resizable=True), Item('line_plot', show_label=False, resizable=True), ), ), menubar=MenuBar( Menu(Action(action='saveLinePlot', name='SaveLinePlot (.png)'), Action(action='saveMatrixPlot', name='SaveMatrixPlot (.png)'), Action(action='save', name='Save (.pyd or .pys)'), Action(action='saveAsText', name='SaveAsText (.txt)'), Action(action='saveAll', name='Save All (.png+.pys)'), Action(action='export', name='Export as Ascii (.asc)'), Action(action='load', name='Load'), Action(action='_on_close', name='Quit'), name='File')), title='PLE', width=1200, height=1000, buttons=[], resizable=True, handler=PLEHandler) get_set_items = [ 'mw', 'mw_frequency', 'mw_power', 'wavelength', 'current', 'detuning', 'number_points', 'detuning_begin', 'detuning_end', 'detuning_mesh', 'red', 'green_length', 'scan_begin', 'scan_end', 'scan_rate', 'seconds_per_point', 'stop_time', 'n_lines', 'counts', 'counts_matrix', 'run_time', '__doc__' ] get_set_order = ['detuning', 'n_lines']
class BMCSWindow(BMCSStudy): selected_node = Instance(HasStrictTraits) def _selected_node_changed(self): self.selected_node.ui = self def get_vot_range(self): return self.viz_sheet.get_vot_range() vot = DelegatesTo('viz_sheet') data_changed = Event replot = Button def _replot_fired(self): self.figure.clear() self.selected_node.plot(self.figure) self.data_changed = True clear = Button() def _clear_fired(self): self.figure.clear() self.data_changed = True view = View( HSplit( VGroup( Item( 'model', id='bmcs.hsplit.left.tree.id', dock='tab', editor=tree_editor, resizable=True, show_label=False, width=300, height=200, ), # Item('selected_node@'), id='bmcs.hsplit.left.id', dock='tab', ), VGroup( Item( 'viz_sheet@', show_label=False, id='bmcs.hsplit.viz3d.notebook.id', dock='tab', ), dock='tab', id='bmcs.hsplit.viz3d.id', label='viz sheet', ), dock='tab', id='bmcs.hsplit.id', ), # dock='tab', id='bmcs.id', width=1.0, height=1.0, title='BMCS', resizable=True, handler=BMCSTreeViewHandler(), key_bindings=key_bindings, toolbar=ToolBar(*toolbar_actions, image_size=(32, 32), show_tool_names=False, show_divider=True, name='view_toolbar'), menubar=MenuBar( Menu(menu_exit, Separator(), menu_save, menu_open, name='File'), Menu(menu_tools_report_tex, menu_tools_report_pdf, name='Tools'), ))
class TracePulsedAnalyzer(HasTraits, GetSetItemsMixin): """Fits a pulsed measurement with a pulsed fit. """ measurement = Instance(ss.Pulsed, factory=ss.Pulsed) fit = Instance(PulsedFit, factory=PulsedFit) hist_binning = Int(1) refresh_hist = Button() histogram = Array() histogram_bins = Array() hist_plot_data = Instance( ArrayPlotData, transient=True ) hist_plot = Instance( Plot, transient=True ) line_plot = Instance(Plot) # line_data is provided by fit class def __init__(self): super(TracePulsedAnalyzer, self).__init__() self.on_trait_change(self.refresh_line_data, 'measurement.count_data, fit.spin_state', dispatch='ui') self.on_trait_change(self.refresh_hist_plot_data, 'fit.spin_state', dispatch='ui') self.on_trait_change(self._update_processed_plot_data_fit, 'fit.fit_parameters', dispatch='ui') self.histogram, self.histogram_bins = np.histogram(self.fit.spin_state, bins=np.arange(self.fit.spin_state.min(),self.fit.spin_state.max() + 1, 1)) def _histogram_bins_changed(self): self.hist_plot_data.set_data('x', self.histogram_bins[1:]) def _histogram_changed(self): self.hist_plot_data.set_data('y', self.histogram) self.hist_plot.request_redraw() def _measurement_changed(self, new): self.fit = PulsedFit() def _histogram_bins_default(self): return np.arange(10) def _histogram_default(self): return np.zeros(self.histogram_bins[1:].shape) def _hist_plot_data_default(self): return ArrayPlotData(x=self.histogram_bins[1:], y=self.histogram) def refresh_hist_plot_data(self): self.histogram, self.histogram_bins = np.histogram(self.fit.spin_state, bins=np.arange(self.fit.spin_state.min(), self.fit.spin_state.max() + 1, 1)) self.hist_plot_data.set_data('x', self.histogram_bins[1:]) self.hist_plot_data.set_data('y', self.histogram) def _update_processed_plot_data_fit(self): if not np.isnan(self.fit.fit_parameters[0]): self.hist_plot_data.set_data('fit', fitting.NLorentzians(*self.fit.fit_parameters)(self.histogram_bins[1:])) self.hist_plot.plot(('x', 'fit'), color='red', style='line', line_width = 1) p = self.fit.fit_parameters f = p[1::3] w = p[2::3] N = len(p) / 3 contrast = np.empty(N) c = p[0] pp = p[1:].reshape((N, 3)) for i, pi in enumerate(pp): a = pi[2] g = pi[1] A = np.abs(a / (np.pi * g)) if a > 0: contrast[i] = 100 * A / (A + c) else: contrast[i] = 100 * A / c s = '' for i, fi in enumerate(self.fit.fit_times): s += 'f %i: %.1f, HWHM %.1f, contrast %.1f%%\n,' % (i + 1, fi, self.fit.fit_line_width[i], contrast[i]) self.text = s def refresh_line_data(self): self.fit.line_data.set_data('tau', self.fit.x_tau) self.fit.line_data.set_data('spin_state', self.fit.spin_state) def _hist_plot_default(self): plot = Plot(self.hist_plot_data, padding_left=50, padding_top=10, padding_right=10, padding_bottom=30) plot.plot(('x','y'), style='line', color='blue', name='hist') plot.index_axis.title = '# counts' plot.value_axis.title = '# of events' plot.tools.append(PanTool(plot)) plot.overlays.append(ZoomTool(plot)) return plot def _refresh_hist_changed(self): self.trace_binned = np.zeros(int(len(self.fit.spin_state)/self.hist_binning)) a=0 for i in range(len(self.fit.spin_state[:-(self.hist_binning)])): if i % self.hist_binning == 0: self.trace_binned[a] = self.fit.spin_state[i:(i+self.hist_binning)].sum() a = a+1 self.histogram, self.histogram_bins = np.histogram(self.trace_binned, bins=np.arange(self.trace_binned.min(),self.trace_binned.max()+1,1)) self._histogram_changed() self._histogram_bins_changed() def _line_plot_default(self): plot = Plot(self.fit.line_data, padding=8, padding_left=64, padding_bottom=36) for item in self.fit.plots: plot.plot(**item) plot.index_axis.title = '# bin' plot.value_axis.title = 'spin state' return plot def _fit_changed(self, name, old, new): old.measurement = None new.measurement = self.measurement plot = self.line_plot # delete all old plots for key in plot.plots.keys(): plot.delplot(key) # set new data source plot.data = self.fit.line_data # make new plots for item in self.fit.plots: plot.plot(**item) # if the fit has an attr 'text' attached to it, print it in the lower left corner of the plot if hasattr(old, 'text'): label = plot.overlays[0] old.sync_trait('text', label, 'text', mutual=False, remove=True) plot.overlays = [] if hasattr(new, 'text'): label = PlotLabel(text=self.fit.text, hjustify='left', vjustify='bottom', position=[64, 32]) new.sync_trait('text', label, 'text', mutual=False) plot.overlays = [label] def save_hist_plot(self, filename): self.save_figure(self.hist_plot, filename) def save_line_plot(self, filename): self.save_figure(self.line_plot, filename) def save_all(self, filename): self.save_line_plot(filename + 'line.png') self.save_hist_plot(filename + 'hist.png') self.save(filename + '.pyd') # Menu of the PulsedAnalyzer, only include tested measurements and Fits please! traits_view = View(HGroup(VGroup(Item(name='measurement', style='custom', show_label=False), Item('line_plot', name='normalized intensity', editor=ComponentEditor(), show_label=False, width=300, height=300, resizable=True), ), VGroup(Item(name='fit', style='custom', show_label=False), HGroup(Item('hist_binning', label='# of bins'), Item('refresh_hist', label = 'Refresh histogram', show_label=False)), Item('hist_plot', editor=ComponentEditor(), show_label=False, width=300, height=300, resizable=True), ), ), menubar=MenuBar(Menu(Action(action='save', name='Save (.pyd or .pys)'), Action(action='load', name='Load (.pyd or .pys)'), Action(action='save_hist_plot', name='Save Hist Plot (.png)'), Action(action='save_line_plot', name='Save Line Plot (.png)'), Action(action='save_all', name='Save All'), Action(action='_on_close', name='Quit'), name='File'), Menu(Action(action='new_trace_measurement', name='SSTTrace'), name='Measurement'), Menu(Action(action='new_pulsed_fit', name='Pulsed'), Action(action='new_unknown_fit', name='SSTtraceFit'), Action(action = 'new_odmr_fit_XY8', name = 'Fit Lorentzians'), name='Fit'), ), title='TracePulsedAnalyzer',width=1400, height=600, buttons=[], resizable=True, handler=TracePulsedAnalyzerHandler) get_set_items = ['measurement', 'fit'] get_set_order = ['measurement', 'fit']
class Polarization(ManagedJob, GetSetItemsMixin): """ Record a polarization curve. written by: [email protected] last modified: 2012-08-17 """ seconds_per_point = Range(low=1e-4, high=100., value=1., desc='integration time for one point', label='seconds per point', mode='text', auto_set=False, enter_set=True) angle_step = Range(low=1e-3, high=100., value=1., desc='angular step', label='angle step', mode='text', auto_set=False, enter_set=True) angle = Array() intensity = Array() power = Array() plot = Instance(Plot) plot_data = Instance(ArrayPlotData) get_set_items = [ '__doc__', 'seconds_per_point', 'angle_step', 'angle', 'intensity', 'power' ] def __init__(self): super(Polarization, self).__init__() self._create_plot() self.on_trait_change(self._update_index, 'angle', dispatch='ui') self.on_trait_change(self._update_value, 'intensity', dispatch='ui') def _run(self): """Acquire data.""" try: # run the acquisition self.state = 'run' RotationStage().go_home() self.angle = np.array(()) self.intensity = np.array(()) self.power = np.array(()) c1 = TimeTagger.Countrate(0) c2 = TimeTagger.Countrate(1) for phi in np.arange(0., 360., self.angle_step): RotationStage().set_angle(phi) c1.clear() c2.clear() self.thread.stop_request.wait(self.seconds_per_point) if self.thread.stop_request.isSet(): logging.getLogger().debug('Caught stop signal. Exiting.') self.state = 'idle' break self.angle = np.append(self.angle, phi) self.intensity = np.append(self.intensity, c1.getData() + c2.getData()) self.power = np.append(self.power, PowerMeter().getPower()) else: self.state = 'done' except: # if anything fails, recover logging.getLogger().exception('Error in polarization.') self.state = 'error' finally: del c1 del c2 def _create_plot(self): plot_data = ArrayPlotData( angle=np.array(()), intensity=np.array(()), ) plot = Plot(plot_data, padding=8, padding_left=64, padding_bottom=64) plot.plot(('angle', 'intensity'), color='blue') plot.index_axis.title = 'angle [deg]' plot.value_axis.title = 'intensity [count/s]' self.plot_data = plot_data self.plot = plot def _update_index(self, new): self.plot_data.set_data('angle', new) def _update_value(self, new): self.plot_data.set_data('intensity', new) def save_plot(self, filename): self.save_figure(self.plot, filename) traits_view = View(HGroup( Item('submit_button', show_label=False), Item('remove_button', show_label=False), Item('priority'), Item('state', style='readonly'), ), HGroup( Item('seconds_per_point'), Item('angle_step'), ), Item('plot', editor=ComponentEditor(), show_label=False), menubar=MenuBar( Menu(Action(action='save', name='Save (.pyd or .pys)'), Action(action='load', name='Load'), Action(action='save_plot', name='Save Plot (.png)'), Action(action='_on_close', name='Quit'), name='File')), title='Polarization', width=640, height=640, buttons=[], resizable=True, handler=PolarizationHandler)
from .model import ToDoItem, ToDoList # ---------------------------------------------------------------------------- # TraitsUI Actions and Menus # ---------------------------------------------------------------------------- new_item_action = Action( name='New Item', action='new_item', accelerator='Ctrl++' ) menubar = MenuBar( Menu( ActionGroup(new_item_action, name='list_group'), name='Edit', ), ) # ---------------------------------------------------------------------------- # TraitsUI Views # ---------------------------------------------------------------------------- #: Stripped down view for use in list editor to_do_item_view = View( HGroup( Item('completed', show_label=False), Item('description', show_label=False, springy=True), Item('controller.delete',show_label=False) ),
class PulsedAnalyzer(HasTraits, GetSetItemsMixin): """Fits a pulsed measurement with a pulsed fit. Example of usage: a = PulsedAnalyzer() a.measurement = Rabi a.fit = RabiFit() a.edit_traits() """ measurement = Instance(dr.PulsedDEER, factory=dr.PulsedDEER) fit = Instance(PulsedFit, factory=PulsedFit) matrix_plot_data = Instance(ArrayPlotData) pulse_plot_data = Instance(ArrayPlotData) matrix_plot = Instance(Plot) pulse_plot = Instance(Plot) line_plot = Instance(Plot) # line_data is provided by fit class def __init__(self): super(PulsedAnalyzer, self).__init__() self.on_trait_change(self.refresh_matrix_axis, 'measurement.time_bins,measurement.n_laser', dispatch='ui') self.on_trait_change(self.refresh_matrix, 'measurement.count_data', dispatch='ui') self.on_trait_change(self.refresh_pulse, 'fit.pulse', dispatch='ui') self.on_trait_change(self.refresh_time_bins, 'measurement.time_bins', dispatch='ui') self.on_trait_change(self.refresh_flank, 'fit.flank', dispatch='ui') def _measurement_changed(self, new): self.fit = PulsedFit() def _matrix_plot_data_default(self): return ArrayPlotData(image=np.zeros((self.measurement.n_laser, self.measurement.n_bins))) def _pulse_plot_data_default(self): return ArrayPlotData(x=self.measurement.time_bins, y=self.fit.pulse) def _matrix_plot_default(self): plot = Plot(self.matrix_plot_data, width=500, height=500, resizable='hv', padding=8, padding_left=48, padding_bottom=36) plot.index_axis.title = 'time [ns]' plot.value_axis.title = 'laser pulse' plot.img_plot('image', xbounds=(self.measurement.time_bins[0], self.measurement.time_bins[-1]), ybounds=(0, self.measurement.n_laser), colormap=Spectral)[0] return plot def _pulse_plot_default(self): plot = Plot(self.pulse_plot_data, padding=8, padding_left=64, padding_bottom=36) plot.plot(('x', 'y'), style='line', color='blue', name='data') edge_marker = LinePlot(index=ArrayDataSource(np.array((0, 0))), value=ArrayDataSource(np.array((0, 1e9))), color='red', index_mapper=LinearMapper(range=plot.index_range), value_mapper=LinearMapper(range=plot.value_range), name='marker') plot.add(edge_marker) plot.index_axis.title = 'time [ns]' plot.value_axis.title = 'intensity' return plot def _line_plot_default(self): plot = Plot(self.fit.line_data, padding=8, padding_left=64, padding_bottom=36) for item in self.fit.plots: plot.plot(**item) plot.index_axis.title = 'time [ns]' plot.value_axis.title = 'spin state' return plot def refresh_matrix_axis(self): self.matrix_plot.components[0].index.set_data((self.measurement.time_bins[0], self.measurement.time_bins[-1]), (0.0, float(self.measurement.n_laser))) def refresh_matrix(self): s = self.measurement.count_data.shape if not s[0] * s[1] > 1000000: self.matrix_plot_data.set_data('image', self.measurement.count_data) def refresh_pulse(self): self.pulse_plot_data.set_data('y', self.fit.pulse) def refresh_time_bins(self): self.pulse_plot_data.set_data('x', self.measurement.time_bins) def refresh_flank(self): self.pulse_plot.components[1].index.set_data(np.array((self.fit.flank, self.fit.flank))) def _fit_changed(self, name, old, new): old.measurement = None new.measurement = self.measurement plot = self.line_plot # delete all old plots for key in plot.plots.keys(): plot.delplot(key) # set new data source plot.data = self.fit.line_data # make new plots for item in self.fit.plots: plot.plot(**item) # if the fit has an attr 'text' attached to it, print it in the lower left corner of the plot if hasattr(old, 'text'): label = plot.overlays[0] old.sync_trait('text', label, 'text', mutual=False, remove=True) plot.overlays = [] if hasattr(new, 'text'): label = PlotLabel(text=self.fit.text, hjustify='left', vjustify='bottom', position=[64, 32]) new.sync_trait('text', label, 'text', mutual=False) plot.overlays = [label] def save_matrix_plot(self, filename): self.save_figure(self.matrix_plot, filename) def save_line_plot(self, filename): self.save_figure(self.line_plot, filename) # Menu of the PulsedAnalyzer, only include tested measurements and Fits please! traits_view = View(HGroup(VGroup(Item(name='measurement', style='custom', show_label=False), Item('line_plot', name='normalized intensity', editor=ComponentEditor(), show_label=False, width=300, height=300, resizable=True), ), VGroup(Item(name='fit', style='custom', show_label=False), Tabbed(Item('matrix_plot', editor=ComponentEditor(), show_label=False, width=300, height=300, resizable=True), Item('pulse_plot', name='pulse profile', editor=ComponentEditor(), show_label=False, width=300, height=300, resizable=True), ), ), ), menubar=MenuBar(Menu(Action(action='save', name='Save (.pyd or .pys)'), Action(action='load', name='Load (.pyd or .pys)'), Action(action='save_matrix_plot', name='Save Matrix Plot (.png)'), Action(action='save_line_plot', name='Save Line Plot (.png)'), #TODO Action(action='save_all', name='Save Line Plot (.png) + .pys'), Action(action='_on_close', name='Quit'), name='File'), Menu(Action(action='new_rabi_measurement', name='Electron Rabi'), Action(action='new_deer_measurement', name='DEER'), name='Measurement'), Menu(Action(action='new_pulsed_fit', name='Pulsed'), Action(action='new_rabiphase_fit', name='Rabi_phase'), name='Fit'), ), title='Pulsed DEER Analyzer', buttons=[], resizable=True, handler=PulsedAnalyzerHandler) get_set_items = ['measurement', 'fit'] get_set_order = ['measurement', 'fit']
class SimPStudy(HasTraits): """ The main application window. """ def __init__(self, **kw): super(SimPStudy, self).__init__(**kw) # The initialization should not be considered dirty # therefore set the flag to indicate unsaved study to false # self.dirty = False sim_array = Instance(SimArray) def _sim_array_default(self): return SimArray() sim_model = Property() def _set_sim_model(self, value): self.sim_array.sim_model = value def __getitem__(self, factor_slices): '''Direct access to the sim_array. ''' return self.sim_array[factor_slices] #--------------------------------------------------------------- # PERSISTENCY #------------------------------------------------------------------- file_base_name = Property() def _get_file_base_name(self): return self.sim_model.__class__.__name__ file_path = Str('') dirty = False @on_trait_change('sim_array.changed') def _set_dirty(self): self.dirty = True def new(self): sim_model = self.sim_array.sim_model self.sim_array = SimArray(sim_model=sim_model) self.dirty = False def load(self, file_name): file = open(file_name, 'r') self.sim_array = pickle.load(file) file.close() self.dirty = False def save(self, file_name): file = open(file_name, 'w') pickle.dump(self.sim_array, file) file.close() self.dirty = False def clear_cache(self): self.sim_array.clear_cache() toolbar = ToolBar( Action(name="New Study", tooltip='Create a new study', image=ImageResource('New-32'), action="new_study"), Action(name="Open Study", tooltip='Open a study', image=ImageResource('fileopen-32'), action="open_study"), Action(name="Save Study", tooltip='Save study', image=ImageResource('save'), action="save_study"), Action(name="New View", tooltip='Create new view', image=ImageResource('new_view'), action="new_view"), Action(name="Clear Cache", tooltip='Reset cache', image=ImageResource('reset'), action="clear_cache"), image_size=(22, 22), show_tool_names=False, show_divider=True, name='study_toolbar') menubar = MenuBar(Menu(Action(name="&New", action="new_study"), Action(name="&Open", action="open_study"), Action(name="&Save", action="save_study"), Action(name="Save &As", action="save_study_as"), Action(name="&Exit", action="exit_study"), name="&File"), Menu(Action(name="&New View", action="new_view"), name="&View"), Menu(Action(name="&Clear Cache", action="clear_cache"), name="&Data"), Menu(Action(name="About PStudy", action="about_pstudy"), HelpAction, name="Help") ) view = View( Item('sim_array@', show_label=False), id='simvisage.simiter.pstudy', dock='tab', menubar=menubar, toolbar=toolbar, resizable=True, width=0.8, height=0.8, title='SimVisage: Parametric Study', handler=SimPStudyController, )
class Saturation(ManagedJob, GetSetItemsMixin): """ Measures saturation curves. written by: [email protected] last modified: 2012-08-17 """ v_begin = Range(low=0., high=5., value=0., desc='begin [V]', label='begin [V]', mode='text', auto_set=False, enter_set=True) v_end = Range(low=0., high=5., value=5., desc='end [V]', label='end [V]', mode='text', auto_set=False, enter_set=True) v_delta = Range(low=0., high=5., value=.1, desc='delta [V]', label='delta [V]', mode='text', auto_set=False, enter_set=True) seconds_per_point = Range(low=1e-3, high=1000., value=1., desc='Seconds per point', label='Seconds per point', mode='text', auto_set=False, enter_set=True) voltage = Array() power = Array() rate = Array() plot_data = Instance(ArrayPlotData) plot = Instance(Plot) get_set_items = [ '__doc__', 'v_begin', 'v_end', 'v_delta', 'seconds_per_point', 'voltage', 'power', 'rate' ] traits_view = View(VGroup( HGroup( Item('submit_button', show_label=False), Item('remove_button', show_label=False), Item('priority'), Item('state', style='readonly'), ), HGroup( Item('v_begin'), Item('v_end'), Item('v_delta'), ), HGroup(Item('seconds_per_point'), ), Item('plot', editor=ComponentEditor(), show_label=False, resizable=True), ), menubar=MenuBar( Menu(Action(action='savePlot', name='Save Plot (.png)'), Action(action='save', name='Save (.pyd or .pys)'), Action(action='load', name='Load'), Action(action='_on_close', name='Quit'), name='File')), title='Saturation', buttons=[], resizable=True, handler=CustomHandler) def __init__(self): super(Saturation, self).__init__() self._create_plot() self.on_trait_change(self._update_index, 'power', dispatch='ui') self.on_trait_change(self._update_value, 'rate', dispatch='ui') def _run(self): try: self.state = 'run' voltage = np.arange(self.v_begin, self.v_end, self.v_delta) power = np.zeros_like(voltage) rate = np.zeros_like(voltage) counter_0 = TimeTagger.Countrate(0) counter_1 = TimeTagger.Countrate(1) for i, v in enumerate(voltage): Laser().voltage = v power[i] = PowerMeter().getPower() counter_0.clear() counter_1.clear() self.thread.stop_request.wait(self.seconds_per_point) if self.thread.stop_request.isSet(): logging.getLogger().debug('Caught stop signal. Exiting.') self.state = 'idle' break rate[i] = counter_0.getData() + counter_1.getData() power[i] = PowerMeter().getPower() else: self.state = 'done' del counter_0 del counter_1 self.voltage = voltage self.power = power self.rate = rate finally: self.state = 'idle' def _create_plot(self): plot_data = ArrayPlotData( power=np.array(()), rate=np.array(()), ) plot = Plot(plot_data, padding=8, padding_left=64, padding_bottom=64) plot.plot(('power', 'rate'), color='blue') plot.index_axis.title = 'Power [mW]' plot.value_axis.title = 'rate [kcounts/s]' self.plot_data = plot_data self.plot = plot def _update_index(self, new): self.plot_data.set_data('power', new * 1e3) def _update_value(self, new): self.plot_data.set_data('rate', new * 1e-3) def save_plot(self, filename): self.save_figure(self.plot, filename)
class MFnPolar(HasTraits): numpoints = Int(80) low = Float(0.) high = Float(2 * pi) # arguments to configure the Polar function to be plotted alpha = Range(0., pi, 0., auto_set=False) delta_alpha = Range(0., pi / 2, 0., auto_set=False) delta_trans = Range(0., pi, 0., auto_set=False) phi_residual = Float(0.65) phi_quasibrittle = Float(-0.25) strech_residual = Range(0., 1, 0., auto_set=False) strech_quasibrittle = Range(0., 1, 0., auto_set=False) # arguments to configure the plot plotrange_min = Float(0., desc='lower bound of the plot range') plotrange_max = Float(1., desc='upper bound of the plot range') frac_noplot = Range(0., 1, 0.3, desc='fraction of the \ plot-circle that is not used for display of plot values ', auto_set=False) # @todo: put this into the status bar info = Str('') theta = Array def _theta_default(self): theta_arr = arange(self.low, self.high, (self.high - self.low) / self.numpoints) # add theta=0 to the end of theta-array theta_zero = array([0]) return hstack([theta_arr, theta_zero]) # function to be plotted (returns radius_value for a given theta_value) def radius_fn(self, theta, alpha, delta_alpha, delta_trans, strech_residual, strech_quasibrittle, phi_residual, phi_quasibrittle): # 1st quadrant if ((theta - alpha) >= 0. and (theta - alpha) <= (pi / 2)): theta_tilde = theta - alpha # 2nd quadrant elif ((theta - alpha) <= pi and (theta - alpha) >= pi / 2): theta_tilde = pi - (theta - alpha) # 3rd quadrant positive elif ((theta - alpha) >= pi and (theta - alpha) <= 3 * pi / 2): theta_tilde = theta - alpha - pi # 3rd quadrant negative elif ((theta - alpha) >= -pi and (theta - alpha) <= -pi / 2): theta_tilde = theta - alpha + pi # 4th quadrant positive elif ((theta - alpha) <= 2 * pi and (theta - alpha) >= 3 * pi / 2): theta_tilde = (2 * pi) - (theta - alpha) # 4th quadrant negative elif ((theta - alpha) <= 0. and (theta - alpha) >= -pi / 2): theta_tilde = -(theta - alpha) # Definition of function to be plotted in the range of 0 and Pi/2: _phi_residual = phi_residual + \ (1 - phi_residual) * strech_residual _phi_quasibrittle = phi_quasibrittle + \ (1 - phi_quasibrittle) * strech_quasibrittle # constant values with linear transition function: # (for delta_alpha = 0 the transition function is evaluated) if abs(theta_tilde) < delta_alpha: radius_fn = _phi_residual elif abs(theta_tilde) >= delta_alpha and \ abs(theta_tilde) < delta_alpha + delta_trans: radius_fn = (_phi_residual - ((theta_tilde - delta_alpha) * (_phi_residual - _phi_quasibrittle) / (delta_trans))) else: radius_fn = _phi_quasibrittle return radius_fn radius = Property(Array, depends_on='theta,alpha,delta_alpha,\ delta_trans,frac_noplot,\ strech_residual,\ strech_quasibrittle,\ phi_residual,phi_quasibrittle ') @cached_property def _get_radius(self): vradius_fn = frompyfunc(self.radius_fn, 8, 1) return array(vradius_fn(self.theta, self.alpha, self.delta_alpha, self.delta_trans, self.strech_residual, self.strech_quasibrittle, self.phi_residual, self.phi_quasibrittle), dtype='float_') def __call__(self, theta_value): # return a single value for the specified theta_value radius_value = self.radius_fn(theta_value, self.alpha, self.delta_alpha, self.delta_trans, self.strech_residual, self.strech_quasibrittle, self.phi_residual, self.phi_quasibrittle) return radius_value plot_type = Enum('polar') # radiusplot = MFnPolarPlotItem("theta", ["radius", "plotrange_min", # "plotrange_max", "frac_noplot"], # type_trait="plot_type", # # # Basic axis and label properties # # show_label=False, # resizable=False, # width=260, # height=260, # # # Plot properties # color="green", # bgcolor="lightyellow", # # # Border, padding properties # border_visible=True, # show_label=False, # border_width=1) radius_min = Property(Float, depends_on='current_theta,alpha,delta_alpha,\ delta_trans,strech_residual,\ strech_quasibrittle') @cached_property def _get_radius_min(self): r_min = self.radius.min() return r_min radius_max = Property(Float, depends_on='current_theta,alpha,delta_alpha,\ delta_trans,strech_residual,\ strech_quasibrittle') @cached_property def _get_radius_max(self): r_max = self.radius.max() return r_max info = Property(Float, depends_on='current_theta,alpha,delta_alpha,\ delta_trans,strech_residual,\ strech_quasibrittle, plotrange_min, \ plotrange_max') @cached_property # check for plausibility and return an information or an error message def _get_info(self): if self.plotrange_min >= self.plotrange_max: info = '### Error ###: invalid plot ranges. \ plotrange_max must be greater than plotrange_min.' elif not (self.plotrange_min <= self.radius_min and self.radius_max <= self.plotrange_max): info = '# Note #: Some value of the function are out of \ the specified plot ranges!' else: info = '(valid plot ranges)' return info current_theta = Float(0.0) current_radius = Property(Float, depends_on='current_theta,alpha,\ delta_alpha,delta_trans,\ strech_residual,\ strech_quasibrittle') @cached_property def _get_current_radius(self): return self.__call__(self.current_theta) traits_view = View( VGroup( Group(Item("alpha"), Item("delta_alpha"), Item("delta_trans"), HGroup( Spring(), Item("phi_residual", resizable=False), Spring(), Item("phi_quasibrittle", resizable=False), Spring(), ), Item("strech_residual"), Item("strech_quasibrittle"), show_border=True, label='Function parameters'), HGroup( Group( Item("plotrange_min"), Item("plotrange_max"), Item("frac_noplot"), Item('current_theta'), Item('current_radius', style='readonly'), Item('radius_min', style='readonly'), Item('radius_max', style='readonly'), #Item('info', style = 'readonly' ), springy=True, show_border=True, label='Plot parameters'), # radiusplot ), ), buttons=[OKButton, CancelButton], menubar=MenuBar( Menu(Action(name="O&pen..", action="open_data"), Action(name="S&ave..", action="save_file"), Action(name="E&xit", action="exit_file"), name='File')), handler=MFnWTHandler, resizable=True, scrollable=True, width=700, height=800)
class LearningGUI(HasTraits): plot = Instance(Plot) meanrate = CFloat(0.0) cv = CFloat(0.0) teach = Bool(0) teach_active = Bool(0) teach_high = Range(100., 1000.) teach_low = Range(100., 1000.) f_max = Range(0., 1000.) f_min = Range(0., 1000.) updater = Instance(EventsUpdater) npre = Int(1) f_max_demo = Range(0., 1000.) durationl = Range(0., 10000.) stimlearn = traitsButton() inilearn = traitsButton() set_wij = traitsButton() get_wij = traitsButton() reset0_wij = traitsButton() reset1_wij = traitsButton() learning = Bool #Plot properties tDuration = Range(0.,20) channel = Enum(range(getDefaultMonChannelAddress().nChannels)) period = 1 port = 50002 host = nsetup.communicator.kwargs['host'] stimulator = PoissonStimulator(SeqChannelAddress=None, channel=1, host=host, port_stim=port, rates=[], period=period) def _tDuration_default(self): return 5. def _meanrate_default(self): return 0. def _cv_default(self): return 0. def _learning_default(self): return True def _teach_high_default(self): return 200. def _teach_low_default(self): return 500. def _f_max_default(self): return 55. def _f_min_default(self): return 10. def _f_max_demo_default(self): return 55. def _durationl_default(self): return 200. def __init__(self, markersize=4, marker='circle', color='black'): super(LearningGUI, self).__init__() self.plotdata = ArrayPlotData(neurons = [0], times = [0]) plot = Plot(self.plotdata) plot.plot(( "times", "neurons" ), type = "scatter", marker = marker, marker_size = markersize, color=color) self.plot = plot self.wijstate = ArrayPlotData(imagedata=zeros((124, 28))) wijstate_plot = Plot(self.wijstate) wijstate_plot.img_plot("imagedata") self.wijstate_plot = wijstate_plot self.char = ArrayPlotData(imagedata=zeros((28, 28))) char_plot = Plot(self.char) char_plot.img_plot("imagedata") self.char_plot = char_plot def _channel_changed(self): print('Switching to channel: %d' % self.channel) self.updater.channel = self.channel self.updater.tot_neurons = [] self.updater.tot_times = [] try: self.updater.eventsQueue.stop() except: pass #addrBuildHashTable(self.updater.stcs[self.channel]) self.updater.eventsQueue = pyAex.netMonClient(MonChannelAddress=self.updater.stcs, channels = [self.channel], host = self.updater.host, port = self.updater.port, autostart = True, fps = self.updater.fps) def _teach_active_changed(self): if self.teach_active: host = nsetup.communicator.kwargs['host'] self.stimulator = PoissonStimulator(SeqChannelAddress=None, channel=1, seq_export=False, host=host, port_stim=50002, rates=[[SYN_PADDR, self.teach_low]], period=self.period) self.set_teacher() self.stimulator.start() else: self.stimulator.stop() def _teach_changed(self): self.set_teacher() def set_teacher(self): if self.teach: self.stimulator.rates = [[SYN_PADDR, self.teach_high]] else: self.stimulator.rates = [[SYN_PADDR, self.teach_low]] def _teach_high_changed(self): if self.teach: self.stimulator.rates = [[SYN_PADDR, self.teach_high]] def _teach_low_changed(self): if not self.teach: self.stimulator.rates = [[SYN_PADDR, self.teach_low]] def _learning_changed(self): if self.learning: chip.setBias(learning_on_biases) else: chip.setBias(learning_off_biases) traits_view = View( Group( Group( Group( Item('teach_active', label='Teacher active '), Group( Item('teach_low', label='NO freq ', editor=RangeEditor(low=100, high=1000, mode='xslider')), Item('teach_high', label='YES freq ', editor=RangeEditor(low=100, high=1000, mode='xslider')), orientation='vertical' ), Item('teach', label='Teach! '), label='Teacher', orientation='vertical', ), #Group( #Item('f_max_demo', label="f_max "), #Item('npre', label="Rounds "), #Item('durationl', label="Stim duration "), #Item('inilearn', show_label=False), #label='Demo stimulator', #orientation='vertical', #), Group( # can't resize to fit in the window #Item('char_plot', editor=ComponentEditor(), show_label=False), Item('f_max', label="f_max "), Item('f_min', label="f_min "), Item('durationl', label="Stim duration "), Item('learning', label="Plasticity "), Item('stimlearn', show_label=False), label='Stimulator', orientation='vertical', ), Group( Item('meanrate', label='MeanRate(Hz) ', style='readonly'), Item('cv', label='ISI CV ', style='readonly'), label='Quick measures', orientation='vertical' ), ), Group( Item('plot', editor=ComponentEditor(), show_label=False), label='Viewer', orientation='vertical', ), orientation='horizontal' ), dock='tab', menubar=MenuBar(Menu(Action(name="Edit Plot", action="edit_plot"), CloseAction, name="File"), Menu(Action(name="Default", action="load_default_biases"), Action(name="Set scan 0", action="setscanx_0"), name="Biases")), buttons=LiveButtons, handler = Controller, width=1600, height=600, resizable=True, title="Leonardo", ) plot_edit_view = View(Group(Item('tDuration'), #Item('colormap'), Item('channel')), buttons=['OK','Cancel'])