def _extra_menu_items(self): """Return a save output menu action.""" save_output = Action(name='Save output to file', action='object._save_output_action', enabled_when='len(object.outputs) > 0') return [save_output]
def _toolbar_default(self): return ToolBar(Action(name="Open file"))
from traits.has_traits import HasTraits from traits.trait_types import Bool from traitsui.menu import Action, ActionGroup, Menu, MenuBar, ToolBar from traitsui.item import Item from traitsui.view import View from traitsui.tests._tools import * from traitsui.tests._tools import _is_current_backend if _is_current_backend('null'): import nose raise nose.SkipTest("Not supported using the null backend") TestAction = Action(name='Test', action='test_clicked', tooltip='Click to test') 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), )
def get_menu(self, obj, trait, row, column): actions = [ Action(name='Delete', action='delete'), ] return MenuManager(*actions)
def get_menu(self, obj, trait, row, column): return MenuManager( Action(name='Find Associated Identifiers', action='find_associated_identifiers'), Action(name='Configure', action='configure_sample_table'), )
def get_menu(self): """ Returns the right-click context menu for an object. """ return Menu( *[Action(name="Create Data", action="node.adapter.append_child",)] )
from mayavi.preferences.api import preference_manager from mayavi.core.common import get_engine # Setup a logger for this module. logger = logging.getLogger(__name__) # Subdirectory that the Base class will check for possible external views. UI_DIR_NAME = ['ui'] #------------------------------------------------------------------------------- # The core tree node menu actions: #------------------------------------------------------------------------------- NewAction = 'NewAction' CopyAction = Action(name='Copy', action='editor._menu_copy_node', enabled_when='editor._is_copyable(object)') CutAction = Action(name='Cut', action='editor._menu_cut_node', enabled_when='editor._is_cutable(object)') PasteAction = Action(name='Paste', action='editor._menu_paste_node', enabled_when='editor._is_pasteable(object)') DeleteAction = Action(name='Delete', action='editor._menu_delete_node', enabled_when='editor._is_deletable(object)') RenameAction = Action(name='Rename', action='editor._menu_rename_node', enabled_when='editor._is_renameable(object)') standard_menu_actions = [ Separator(),
def traits_view(self): cols = [ CheckboxColumn(name='status'), ObjectColumn(name='status'), ObjectColumn(name='runid'), ObjectColumn(name='age'), ObjectColumn(name='age_err'), ObjectColumn(name='group'), ObjectColumn(name='aliquot'), ObjectColumn(name='sample'), ] gcols = [ ObjectColumn(name='name'), ObjectColumn( name='weighted_mean', label='Wtd. Mean', format='%0.6f', ), ObjectColumn(name='weighted_mean_err', format='%0.6f', label=PLUSMINUS_ONE_SIGMA), ObjectColumn(name='mswd', format='%0.3f', label='MSWD'), ObjectColumn(name='displayn', label='N'), ObjectColumn(name='mean', format='%0.6f', label='Mean'), ObjectColumn(name='std', format='%0.6f', label='Std') ] button_grp = HGroup(UItem('save_button'), UItem('save_as_button'), UItem('clear_button'), UItem('open_via_finder_button'), UItem('test_button')), repo_grp = VGroup( BorderVGroup(UItem('repo_filter'), UItem('repositories', width=200, editor=ListStrEditor(selected='repository')), label='Repositories'), BorderVGroup(UItem('name_filter'), UItem('names', editor=ListStrEditor(selected='name')), label='DataSets')) record_grp = VSplit( UItem( 'records', editor=TableEditor( columns=cols, selected='selected', sortable=False, edit_on_first_click=False, # clear_selection_on_dclicked=True, menu=MenuManager( Action(name='Group Selected', perform=self._group_selected)), selection_mode='rows')), UItem('groups', editor=TableEditor(columns=gcols))) main_grp = HSplit(repo_grp, record_grp) v = okcancel_view( VGroup(button_grp, main_grp), width=800, height=500, title='CSV Dataset', # handler=CSVDataSetFactoryHandler() ) return v
from traits.api import Bool from traitsui.menu import Action # ============= standard library imports ======================== # ============= local library imports ========================== from pychron.viewable import Viewable, ViewableHandler class SaveableHandler(ViewableHandler): def save(self, info): info.object.save() def save_as(self, info): info.object.save_as() def apply(self, info): info.object.apply() class Saveable(Viewable): handler_klass = SaveableHandler save_enabled = Bool(False) SaveButton = Action(name='Save', action='save', enabled_when='object.save_enabled') SaveAsButton = Action(name='Save As', action='save_as') SaveableButtons = [SaveButton, SaveAsButton] # ============= EOF =============================================
def trait_view(self, name=None, view_element=None): """ Use proxy views when the UI has to refresh """ # Static view if name != 'actual_view': filename = os.path.split(self.filename) settings = { 'buttons': [ Action(name='Back', action='show_file_dialog'), OKButton, CancelButton ], 'title': 'Importing Data as Context', 'width': 700, 'height': 600, 'resizable': True, 'close_result': False, 'handler': ConfigurableImportUIHandler, } return View( Item(name='_view_proxy', show_label=False, editor=InstanceEditor(view='actual_view'), style='custom'), **settings) # Dynamic view items = [] if has_geo and self.model: if isinstance(self.model, FileLogReaderUI): items = [ Tabbed( Group( Group( Item('object.model.log_reader_info', show_label=False, style='custom', height=375), ), '_', HGroup( Item('object.model.select_deselect_all', label='Select/deselect all'), '_', Item('object.model.lower_case'), ), label='Select Curves', ), Group( Item('object.model.text_view', style='custom', show_label=False), label='File View', ), ) ] else: items = [ Tabbed( Group(HGroup( Item('object.model.samples_per_trace', style='readonly', width=50), Item('object.model.trace_count', style='readonly', width=50), Item('object.model.sample_rate'), label='Header info', show_border=True, ), VGrid( HGroup( Item('object.model.inline_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), Item('object.model.crossline_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), ), HGroup( Item('object.model.x_location_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), Item('object.model.y_location_bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), Item('object.model.xy_scale_bytes', label='XY Scale Bytes', editor=RangeEditor(mode='spinner', low=1, high=240)), ), label='Byte offsets', show_border=True, ), HGroup( Item('object.model.data_type'), Item('object.model.byte_order', style='readonly'), label='Data format', show_border=True, ), label='File Format'), Group(Item('object.model.active_traceheader', style='custom', show_label=False), label='Trace Header'), ) ] # Insert file name at the begin; and save options in the end. items.insert( 0, Group(Item('filename', style='readonly', show_label=False), show_border=True, label='File')) items.append( Group( Item('save_choice', style='custom', show_label=False), show_border=True, label='Save new context as', )) return View(Group(*items))
class SphereTSGUI(HasTraits): """ Calculate and show the sphere TS using the TraitsUI framework. """ default_material = 'Tungsten carbide' m = sphere_ts.material_properties() params = m[default_material] params['material'] = default_material params['a'] = 0.0381 / 2.0 params['rho'] = 1026.2 params['c'] = 1490.0 spot_freqs = [12, 18, 38, 50, 70, 120, 200, 333, 420] spot_freqs = list(zip(spot_freqs, list(map(str, spot_freqs)))) extra_spot_freqs = List(Range(low=0., exclude_low=True), desc='comma separated frequencies [kHz]', label='Additional spot freqs [kHz]') sphere_material = Str(params['material'], label='Material') sphere_diameter = Range(low=0., value=params['a'] * 2 * 1000.0, exclude_low=True, label='Diameter [mm]') sphere_density = Range(low=0., value=params['rho1'], exclude_low=True, label='Density [kg/m^3]') sphere_c1 = Range(low=0., value=params['c1'], exclude_low=True, label='Longitudal sound speed [m/s]') sphere_c2 = Range(low=0., value=params['c2'], exclude_low=True, label='Transverse sound speed [m/s]') use_ctd = Bool(True) use_another_material = Bool(False, label='Another material') fluid_c = Range(low=0., value=params['c'], exclude_low=True, label='Sound speed in water [m/s]') fluid_density = Range(low=0., value=params['rho'], exclude_low=True, label='Density of water [kg/m^3]') fluid_temperature = Range(-2.0, 60, 10.0, label='Temperature [degC]') fluid_salinity = Range(0.0, 60.0, 35.0, label='Salinity [PSU]') fluid_depth = Range(0.0, 15000.0, 30.0, label='Depth [m]') freq_start = Range(low=0.0, value=12., label='Start frequency [kHz]') freq_end = Range(low=0.0, value=200., label='End frequency [kHz]') averaging_bandwidth = Range(low=0.1, value=2.5, label='Bandwidth for averaged TS [kHz]') CalculateButton = Action(name='Calculate', action='calculate') AboutButton = Action(name='About', action='show_about') EK60Button = Action(name='EK60 tables', action='show_ek60_ts') CloseButton = Action(name='Close', action='close') aboutDialog = AboutDialog() ek60Dialog = EK60Dialog() view = View( Group( Group(Item('sphere_diameter'), Item('sphere_material', style='custom', enabled_when='not use_another_material', editor=EnumEditor(values=list(m.keys()), cols=2)), Item('use_another_material'), Item('sphere_density', enabled_when='use_another_material'), Item('sphere_c1', enabled_when='use_another_material'), Item('sphere_c2', enabled_when='use_another_material'), label='Sphere properties', show_border=True), '10', # some extra space Group(Item('use_ctd', label='Calculate from T, S, and D'), Item('fluid_temperature', enabled_when='use_ctd', style='text'), Item('fluid_salinity', enabled_when='use_ctd', style='text'), Item('fluid_depth', enabled_when='use_ctd', style='text'), Item('fluid_c', enabled_when='not use_ctd', format_str='%.1f'), Item('fluid_density', enabled_when='not use_ctd', format_str='%.1f'), label='Environmental properties', show_border=True), '10', # some extra space Group(Item('spot_freqs', style='custom', label='Spot frequencies [kHz]', editor=CheckListEditor(values=spot_freqs, cols=3)), Item('extra_spot_freqs', editor=CSVListEditor()), Item('freq_start'), Item('freq_end'), Item('averaging_bandwidth'), label='Frequencies', show_border=True)), resizable=True, title='Sphere TS calculator', buttons=[EK60Button, AboutButton, CalculateButton, CloseButton], handler=UIHandler())
def edit_task_extensions(ts): e = EditExtensionsView() for args in ts: e.add_additions(*args) e.load() nodes = [ TreeNode(node_for=[ViewModel], icon_open='', children='task_extensions'), TETreeNode(node_for=[TaskExtensionModel], auto_open=False, children='additions', label='name', menu=MenuManager( Action(name='Enable All', visible_when='not object.all_enabled', action='set_all_enabled'), Action(name='Disable All', visible_when='object.all_enabled', action='set_all_disabled'))), AdditionTreeNode(node_for=[AdditionModel], label='name', menu=MenuManager( Action(name='Enable', action='set_enabled', visible_when='not object.enabled'), Action(name='Disable', visible_when='object.enabled', action='set_disabled'))) ] tgrp = VGroup( UItem('predefined', tooltip='List of Predefined UI configurations'), UItem( 'filter_value', tooltip= 'Filter items by name. Show only items where NAME starts with the specified value' ), HGroup( icon_button_editor('collapse_all', 'collapse'), icon_button_editor('expand_all', 'collapse'), ), UItem( 'view_model', height=-400, editor=TreeEditor( nodes=nodes, # selection_mode='extended', hide_root=True, selected='selected', dclick='dclicked', show_disabled=True, collapse_all='collapse_all', expand_all='expand_all', refresh='refresh_needed', refresh_all_icons='refresh_all_needed', editable=False))) dgrp = VGroup( UItem( 'description', style='custom', # height=-100, editor=TextEditor(read_only=True)), show_border=True, label='Description') av = View(VGroup(tgrp, dgrp), title='Edit UI', width=500, height=700, resizable=True, handler=EEHandler(), buttons=['OK', 'Cancel'], kind='livemodal') # info = e.configure_traits(view=AView) info = e.edit_traits(view=av) if info.result: e.dump() return confirm(None, 'Restart?') == YES
class DialogPortDO(DialogPort): """ Dialog to create a instance of the class PortDO. The dialog checks all attributes and make sure that a invalid port can not created. """ def __init__(self, measuring_card): self.measuring_card = measuring_card self.id.add_item("Auxport", UL.AUXPORT) #========================================================================= # Methods to handle the dialog with other classes #========================================================================= def open_dialog(self): """Open the dialog to input the values for the port. :returns: True, if the user want create a port, False otherwise :rtype: bool """ self._check_attributes() return self.configure_traits(kind="livemodal") def load(self): """Creates a instance of the class PortAI with the attributes \ of the view. :returns: Digital output port with the attributes. :rtype: PortDO """ port = PortDO(self.measuring_card, self.id.get_selected_value(), self.id.selected_key, self) # resets the name and set the invalid port to true # to make sure that the new port will be checked self.name = "" self.error = True return port def _get_attributes(self): # return all attributes of the view pid = self.id.get_selected_value() return self.measuring_card, pid, self.id.selected_key #========================================================================= # Traitsview + Traitsevent #========================================================================= ConfirmButton = Action(name="OK", enabled_when="not error") @on_trait_change("board_id,port_id,name") def _check_attributes(self): # Checks whether the given attributes are correctly and no port # with the same id already exist try: PortDO(self.measuring_card, self.id.get_selected_value(), self.id.selected_key, None) pid = self.id.get_selected_value() if self.measuring_card.output_port_exists(pid): raise ValueError("The port is already in use") self.error = False except ValueError, e: self.error_msg = str(e) self.error = True
class DialogPortAI(DialogPort): """ Dialog to create a instance of the class PortAI. The dialog checks all attributes and make sure that a invalid port can not created. """ name = Str() scale_factor = Float() offset = Float() value = Float() update_running = Bool(False) ConfirmButton = Action(name="OK", enabled_when="not error") def __init__(self, measuring_card): self.measuring_card = measuring_card for i in range(8): self.id.add_item("Input {0}".format(i), i) #========================================================================= # Methods to handle the dialog with other classes #========================================================================= def open_dialog(self): """Open the dialog to input the values for the port. :returns: True, if the user want create a port, False otherwise :rtype: bool """ self.update_running = True # updates the value of the port automatically after pass a given time # to make sure that the user see all of the time # the current value of the port RunThread(target=self._update_value) self._check_attributes() confirm = self.configure_traits(kind="livemodal") self.update_running = False return confirm def load(self): """Creates a instance of the class PortAI with the attributes\ of the view. :returns: Analog input port with the attributes. :rtype: PortAI """ port = PortAI(self.measuring_card, self.id.get_selected_value(), self.scale_factor, self.offset, self.name, self) # resets the name and set the invalid port to true # to make sure that the new port will be checked self.name = "" self.invalid_port = True return port def update_attributes(self, args): # update the view with the arguments of the port pid, self.scale_factor, self.offset, self.name = args self.id.show_value(pid) def _update_value(self): # Update the value to show the current recorded value # of the port. while self.update_running: sleep(0.2) self._check_attributes() def _get_attributes(self): # return all attributes of the view return self.measuring_card, self.id.get_selected_value(), \ self.scale_factor, self.offset, self.name #========================================================================= # Traitsview + Traitsevent #========================================================================= @on_trait_change("scale_factor,offset,board_id,port_id,name") def _check_attributes(self): # Checks whether the given attributes are correctly and no port # with the same id already exist try: port = PortAI(self.measuring_card, self.id.get_selected_value(), self.scale_factor, self.offset, self.name, None) self.value = port.record_port(self.measuring_card.volt_interval) if self.measuring_card.input_port_exists(self.id.get_selected_value()): raise ValueError("The selected port is already in use") self.error = False except ValueError, e: self.value = 0 self.error = True self.error_msg = str(e)
class DialogPhaseTime(DialogPhase): """ Dialog to create a instance of the class PhaseTime. The dialog checks all attributes and make sure that a invalid phase can not created. """ position = Instance(Combobox, ()) name = Str interval = Str(secs_to_time(0)) ticks = Str(secs_to_time(0)) def _get_attributes(self): # Return all attributes of the view. idays, ihours, imins, isecs = map(int, self.interval.split(":")) interval = idays * 24 * 60**2 + ihours * 60**2 + imins * 60 + isecs tdays, thours, tmins, tsecs = map(int, self.ticks.split(":")) ticks = tdays * 24 * 60**2 + thours * 60**2 + tmins * 60 + tsecs return interval, ticks, self.name, self.reset, self.reset_time,\ self.interval, self.ticks def _update_attributes(self, args): # update the attributes of the view with the given arguments self.name, self.reset, self.reset_time,\ self.interval, self.ticks = args #========================================================================= # Methods to handle the dialog with other classes #========================================================================= def open_dialog(self, phase_num, phases=None): if not phases == None: self.cur_phases = phases self.position.reset() for i in range(1, phase_num + 1): self.position.add_item("Position " + str(i), i) self._check_attributes() return self.configure_traits(kind="livemodal") def load(self): """Create a instance of the class PhaseTime with the attributes\ of the view. :returns: Time based phase :rtype: PhaseTime """ phase = PhaseTime(self.model, self, *self._get_attributes()) self.name = "" return phase #========================================================================= # Traitsview + Traitsevent #========================================================================= ConfirmButton = Action(name="OK", enabled_when="not error") @on_trait_change("name,interval,ticks") def _check_attributes(self): # Checks whether the given attributes are correctly. try: for phase in self.cur_phases: if phase.name == self.name: raise ValueError("The name does already exists") interval, ticks = self._get_attributes()[:2] if interval < 1: raise ValueError("The interval must be positive") elif ticks < 1: raise ValueError("The ticks must be positive") elif ticks > interval: raise ValueError("The interval must be greater than the ticks") elif self.position.get_selected_value() < 1: raise ValueError("The position is invalid") PhaseTime(self.model, None, *self._get_attributes()) self.error = False except Exception, e: self.error = True self.error_msg = str(e)
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 DialogPhaseInter(DialogPhase): position = Instance(Combobox, ()) id = Instance(Combobox, ()) name = Str limit = Float smaller = Bool time = Int #========================================================================= # Methods to handle the dialog with other classes #========================================================================= def open_dialog(self, phase_num, ports, phases=None): if not phases == None: self.cur_phases = phases self.position.reset() self.id.reset() for i in range(1, phase_num + 1): self.position.add_item('Position ' + str(i), i) for p in ports: self.id.add_item(p.name, p.id) self._check_phase() return self.configure_traits(kind='livemodal') def load(self): """Create a instance of the class PhaseValue with the attributes\ of the view. :returns: Value based phase :rtype: PhaseValue """ phase = PhasePause(self.model, self, *self._get_attributes()) self.name = '' return phase def _get_attributes(self): # Return all attributes of the view. pid = self.id.get_selected_value() return self.limit, self.smaller, self.time, pid,\ self.name, self.reset, self.reset_time def _update_attributes(self, args): # update the attributes of the view self.limit, self.smaller, self.time, pid,\ self.name, self.reset, self.reset_time = args self.id.show_value(pid) #========================================================================= # Traitsview + Traitsevent #========================================================================= ConfirmButton = Action(name='OK', enabled_when='not error') @on_trait_change('name,id,time,limit') def _check_phase(self): # Checks whether the given attributes are correctly. try: for phase in self.cur_phases: if phase.name == self.name: raise ValueError("The name does already exists") if self.time < 1: raise ValueError('The time must positive') PhasePause(self.model, self, *self._get_attributes()) self.error = False except Exception, e: self.error = True self.error_msg = str(e)
from traits.api import (Button, Enum, Instance, List, Property, Str, on_trait_change) from traitsui.api import (ButtonEditor, Controller, HGroup, InstanceEditor, Item, ListEditor, ModelView, Spring, VGroup, View) from traitsui.menu import (Action, ActionGroup, Menu, MenuBar, RedoAction, UndoAction) 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(UndoAction, RedoAction, name='undo_group'), ActionGroup(new_item_action, name='list_group'), name='Edit', ), ) # ---------------------------------------------------------------------------- # TraitsUI Views # ---------------------------------------------------------------------------- #: Stripped down view for use in list editor to_do_item_view = View(
class DialogCycle(DialogPhase, IPhaseContainer): """ Dialog to create a instance of the class Cycle. The dialog checks all attributes and make sure that a invalid cycle can not created. """ position = Instance(Combobox, ()) name = Str phases = List() repeats = Int def __init__(self): IPhaseContainer.__init__(self) self.logger.debug("Initialize cycle") #========================================================================= # Methods to handle the dialog with other classes #========================================================================= def open_dialog(self, phase_num, phases): self.cur_phases = phases self.position.reset() for i in range(1, phase_num + 1): self.position.add_item("Position " + str(i), i) return self.configure_traits(kind="livemodal") def load(self): """Create a instance of the class Cycle with the attributes\ of the view. :returns: Created cycle :rtype: Cycle """ cycle = Cycle(self.model, self, *self._get_attributes()) self.name = "" self.phases = [] self.invalid_phase = True return cycle def _update_attributes(self, args): # update the view with the given attributes self.name, self.phases, self.repeats = args def _get_attributes(self): # Return all attributes of the view. return self.name, self.phases, self.repeats #========================================================================= # Traitsview + Traitsevent #========================================================================= combobox = Instance(Combobox, ()) ConfirmButton = Action(name="OK", enabled_when="not error") add_btn = Button('Add') def _name_changed(self): try: for phase in self.cur_phases: if phase.name == self.name: raise ValueError("The name does already exists") if len(self.name) < 1: raise ValueError("Define a name for the phase") self.error = False except Exception, e: self.error = True self.error_msg = str(e)
def get_menu(self, object): menu = Menu( Action(name='New Step', action='info.object.new_step()'), Action(name='Remove Selected from Program', action='info.object.remove_steps(info.object.selected)')) return menu
def get_menu(self, obj, trait, row, column): tag_actions = [ Action(name='OK', action='tag_ok'), Action(name='Omit', action='tag_omit'), Action(name='Invalid', action='tag_invalid'), Action(name='Skip', action='tag_skip') ] group_actions = [ Action(name='Group Selected', action='group_selected'), Action(name='Clear Grouping', action='clear_grouping') ] select_actions = [ Action(name='Same Identifier', action='select_same'), Action(name='Same Attr', action='select_same_attr'), Action(name='Clear', action='clear_selection'), Action(name='Remove Others', action='remove_others') ] actions = [ Action(name='Configure', action='configure_analysis_table'), Action(name='Unselect', action='unselect_analyses'), Action(name='Open', action='recall_items'), Action(name='Review Status Details', action='review_status_details'), Action(name='Load Review Status', action='load_review_status'), Action(name='Toggle Freeze', action='toggle_freeze'), MenuManager(name='Selection', *select_actions), MenuManager(name='Grouping', *group_actions), MenuManager(name='Tag', *tag_actions) ] return MenuManager(*actions)
class ViewChooser(HasTraits): """ Allow the user to choose a view. This implementation shows views in a tree grouped by category. """ # The window that contains the views to choose from. window = Instance("pyface.workbench.api.WorkbenchWindow") # The currently selected tree item (at any point in time this might be # either None, a view category, or a view). selected = Any() # The selected view (None if the selected item is not a view). view = Instance(IView) # Traits UI views -----------------------------------------------------# traits_ui_view = View( Item( name="window", editor=TreeEditor( nodes=[ WorkbenchWindowTreeNode( auto_open=True, label="=Views", rename=False, copy=False, delete=False, insert=False, menu=None, ), TreeNode( node_for=[Category], auto_open=True, children="views", label="name", rename=False, copy=False, delete=False, insert=False, menu=None, ), IViewTreeNode( auto_open=False, label="name", rename=False, copy=False, delete=False, insert=False, menu=None, ), ], editable=False, hide_root=True, selected="selected", show_icons=True, ), show_label=False, ), buttons=[Action(name="OK", enabled_when="view is not None"), "Cancel"], resizable=True, style="custom", title="Show View", width=0.2, height=0.4, ) # ------------------------------------------------------------------------ # 'ViewChooser' interface. # ------------------------------------------------------------------------ def _selected_changed(self, old, new): """ Static trait change handler. """ # If the assignment fails then the selected object does *not* implement # the 'IView' interface. try: self.view = new except TraitError: self.view = None return
def get_menu(self, obj, trait, row, column): return MenuManager(Action(name='Unselect', action='unselect_projects'))
class ResultExplorer(HasTraits): # source of result data Beamformer = Instance(BeamformerBase) # traits for the plots plot_data = Instance(ArrayPlotData, transient=True) # the map map_plot = Instance(Plot, transient=True) imgp = Instance(ImagePlot, transient=True) # map interpolation interpolation = DelegatesTo('imgp', transient=True) # the colorbar for the map colorbar = Instance(ColorBar, transient=True) # the spectrum spec_plot = Instance(Plot, transient=True) # the main container for the plots plot_container = Instance(BasePlotContainer, transient=True) # zoom and integration box tool for map plot zoom = Instance(RectZoomSelect, transient=True) # selection of freqs synth = Instance(FreqSelector, transient=True) # cursor tool for spectrum plot cursor = Instance(BaseCursorTool, transient=True) # dynamic range of the map drange = Instance(DataRange1D, transient=True) # dynamic range of the spectrum plot yrange = Instance(DataRange1D, transient=True) # set if plots are invalid invalid = Bool(False, transient=True) # remember the last valid result last_valid_digest = Str(transient=True) # starts calculation thread start_calc = Button(transient=True) # signals end of calculation calc_ready = Event(transient=True) # calculation thread CThread = Instance(Thread, transient=True) # is calculation active ? running = Bool(False, transient=True) rmesg = Property(depends_on='running') # automatic recalculation ? automatic = Bool(False, transient=True) # picture pict = File(filter=['*.png', '*.jpg'], desc="name of picture file", transient=True) pic_x_min = Float(-1.0, desc="minimum x-value picture plane") pic_y_min = Float(-0.75, desc="minimum y-value picture plane") pic_scale = Float(400, desc="maximum x-value picture plane") pic_flag = Bool(False, desc="show picture ?") view = View( HSplit( VGroup( HFlow(Item('synth{}', style='custom', width=0.8), Item('start_calc{Recalc}', enabled_when='invalid'), show_border=True), TGroup( Item('plot_container{}', editor=ComponentEditor()), dock='vertical', ), ), Tabbed( [Item('Beamformer', style='custom'), '-<>[Beamform]'], [ Item('Beamformer', style='custom', editor=InstanceEditor(view=fview)), '-<>[Data]' ], ), # ['invalid{}~','last_valid_digest{}~', # 'calc_ready','running', # '|'], dock='vertical'), #HSplit statusbar=[StatusItem(name='rmesg', width=0.5)], # icon= ImageResource('py.ico'), title="Beamform Result Explorer", resizable=True, menubar=MenuBarManager( MenuManager( MenuManager(Action(name='Open', action='load'), Action(name='Save as', action='save_as'), name='&Project'), MenuManager(Action(name='VI logger csv', action='import_time_data'), Action(name='Pulse mat', action='import_bk_mat_data'), Action(name='td file', action='import_td'), name='&Import'), MenuManager(Action(name='NI-DAQmx', action='import_nidaqmx'), name='&Acquire'), Action(name='R&un script', action='run_script'), Action(name='E&xit', action='_on_close'), name='&File', ), MenuManager( Group( Action(name='&Delay+Sum', style='radio', action='set_Base', checked=True), Action(name='&Eigenvalue', style='radio', action='set_Eig'), Action(name='&Capon', style='radio', action='set_Capon'), Action(name='M&usic', style='radio', action='set_Music'), Action(name='D&amas', style='radio', action='set_Damas'), Action(name='Clea&n', style='radio', action='set_Clean'), Action(name='C&lean-SC', style='radio', action='set_Cleansc'), Action(name='&Orthogonal', style='radio', action='set_Ortho'), Action(name='&Functional', style='radio', action='set_Functional'), Action(name='C&MF', style='radio', action='set_CMF'), ), Separator(), Action(name='Auto &recalc', style='toggle', checked_when='automatic', action='toggle_auto'), name='&Options', ), MenuManager( Group( # Action(name='&Frequency', action='set_Freq'), Action(name='&Interpolation method', action='set_interp'), Action(name='&Map dynamic range', action='set_drange'), Action(name='&Plot dynamic range', action='set_yrange'), Action(name='Picture &underlay', action='set_pic'), ), name='&View', ), )) #View # init the app def __init__(self, **kwtraits): super(ResultExplorer, self).__init__(**kwtraits) # containers bgcolor = "sys_window" #(212/255.,208/255.,200/255.) # Windows standard background self.plot_container = container = VPlotContainer(use_backbuffer=True, padding=0, fill_padding=False, valign="center", bgcolor=bgcolor) subcontainer = HPlotContainer(use_backbuffer=True, padding=0, fill_padding=False, halign="center", bgcolor=bgcolor) # freqs self.synth = FreqSelector(parent=self) # data source self.plot_data = pd = ArrayPlotData() self.set_result_data() self.set_pict() # map plot self.map_plot = Plot(pd, padding=40) self.map_plot.img_plot("image", name="image") imgp = self.map_plot.img_plot("map_data", name="map", colormap=jet)[0] self.imgp = imgp t1 = self.map_plot.plot(("xpoly", "ypoly"), name="sector", type="polygon") t1[0].face_color = (0, 0, 0, 0) # set face color to transparent # map plot tools and overlays imgtool = ImageInspectorTool(imgp) imgp.tools.append(imgtool) overlay = ImageInspectorOverlay(component=imgp, image_inspector=imgtool, bgcolor="white", border_visible=True) self.map_plot.overlays.append(overlay) self.zoom = RectZoomSelect(self.map_plot, drag_button='right', always_on=True, tool_mode='box') self.map_plot.overlays.append(self.zoom) self.map_plot.tools.append(PanTool(self.map_plot)) # colorbar colormap = imgp.color_mapper self.drange = colormap.range self.drange.low_setting = "track" self.colorbar = cb = ColorBar( index_mapper=LinearMapper(range=colormap.range), color_mapper=colormap, plot=self.map_plot, orientation='v', resizable='v', width=10, padding=20) # colorbar tools and overlays range_selection = RangeSelection(component=cb) cb.tools.append(range_selection) cb.overlays.append( RangeSelectionOverlay(component=cb, border_color="white", alpha=0.8, fill_color=bgcolor)) range_selection.listeners.append(imgp) # spectrum plot self.spec_plot = Plot(pd, padding=25) px = self.spec_plot.plot(("freqs", "spectrum"), name="spectrum", index_scale="log")[0] self.yrange = self.spec_plot.value_range px.index_mapper = MyLogMapper(range=self.spec_plot.index_range) # spectrum plot tools self.cursor = CursorTool( px) #, drag_button="left", color='blue', show_value_line=False) px.overlays.append(self.cursor) self.cursor.current_position = 0.3, 0.5 px.index_mapper.map_screen(0.5) # self.map_plot.tools.append(SaveTool(self.map_plot, filename='pic.png')) # layout self.set_map_details() self.reset_sector() subcontainer.add(self.map_plot) subcontainer.add(self.colorbar) # subcontainer.tools.append(SaveTool(subcontainer, filename='pic.png')) container.add(self.spec_plot) container.add(subcontainer) container.tools.append(SaveTool(container, filename='pic.pdf')) self.last_valid_digest = self.Beamformer.ext_digest def _get_rmesg(self): if self.running: return "Running ..." else: return "Ready." @on_trait_change('Beamformer.ext_digest') def invalidate(self): if self.last_valid_digest != "" and self.Beamformer.ext_digest != self.last_valid_digest: self.invalid = True def _start_calc_fired(self): if self.CThread and self.CThread.isAlive(): pass else: self.CThread = CalcThread() self.CThread.b = self.Beamformer self.CThread.caller = self self.CThread.start() def _calc_ready_fired(self): f = self.Beamformer.freq_data low, high = f.freq_range print low, high fr = f.fftfreq() if self.synth.synth_freq < low: self.synth.synth_freq = fr[1] if self.synth.synth_freq > high: self.synth.synth_freq = fr[-2] self.set_result_data() self.set_map_details() self.plot_container.request_redraw() self.map_plot.request_redraw() @on_trait_change('invalid') def activate_plot(self): self.plot_container.visible = not self.invalid self.plot_container.request_redraw() if self.invalid and self.automatic: self._start_calc_fired() @on_trait_change('cursor.current_position') def update_synth_freq(self): self.synth.synth_freq = self.cursor.current_position[0] def reset_sector(self): g = self.Beamformer.grid if self.zoom: self.zoom.x_min = g.x_min self.zoom.y_min = g.y_min self.zoom.x_max = g.x_max self.zoom.y_max = g.y_max @on_trait_change( 'zoom.box,synth.synth_freq,synth.synth_type,drange.+,yrange.+') def set_result_data(self): if self.invalid: return if self.cursor: self.cursor.current_position = self.synth.synth_freq, 0 pd = self.plot_data if not pd: return g = self.Beamformer.grid try: map_data = self.Beamformer.synthetic(self.synth.synth_freq, self.synth.synth_type_).T map_data = L_p(map_data) except: map_data = arange(0, 19.99, 20. / g.size).reshape(g.shape) pd.set_data("map_data", map_data) f = self.Beamformer.freq_data if self.zoom and self.zoom.box: sector = self.zoom.box else: sector = (g.x_min, g.y_min, g.x_max, g.y_max) pd.set_data("xpoly", array(sector)[[0, 2, 2, 0]]) pd.set_data("ypoly", array(sector)[[1, 1, 3, 3]]) ads = pd.get_data("freqs") if not ads: freqs = ArrayDataSource(f.fftfreq()[f.ind_low:f.ind_high], sort_order='ascending') pd.set_data("freqs", freqs) else: ads.set_data(f.fftfreq()[f.ind_low:f.ind_high], sort_order='ascending') self.synth.enumerate() try: spectrum = self.Beamformer.integrate(sector)[f.ind_low:f.ind_high] spectrum = L_p(spectrum) except: spectrum = f.fftfreq()[f.ind_low:f.ind_high] pd.set_data("spectrum", spectrum) @on_trait_change('pic+') def set_map_details(self): if self.invalid: return mp = self.map_plot # grid g = self.Beamformer.grid xs = linspace(g.x_min, g.x_max, g.nxsteps) ys = linspace(g.y_min, g.y_max, g.nysteps) mp.range2d.sources[1].set_data(xs, ys, sort_order=('ascending', 'ascending')) mp.aspect_ratio = (xs[-1] - xs[0]) / (ys[-1] - ys[0]) yl, xl = self.plot_data.get_data("image").shape[0:2] xp = (self.pic_x_min, self.pic_x_min + xl * 1.0 / self.pic_scale) yp = (self.pic_y_min, self.pic_y_min + yl * 1.0 / self.pic_scale) mp.range2d.sources[0].set_data(xp, yp, sort_order=('ascending', 'ascending')) mp.range2d.low_setting = (g.x_min, g.y_min) mp.range2d.high_setting = (g.x_max, g.y_max) # dynamic range map = mp.plots["map"][0] #map.color_mapper.range.low_setting="track" # colormap map.color_mapper._segmentdata['alpha'] = [(0.0, 0.0, 0.0), (0.001, 0.0, 1.0), (1.0, 1.0, 1.0)] map.color_mapper._recalculate() mp.request_redraw() @on_trait_change('pict') def set_pict(self): pd = self.plot_data if not pd: return try: imgd = ImageData.fromfile(self.pict)._data[::-1] except: imgd = ImageData() imgd.set_data(255 * ones((2, 2, 3), dtype='uint8')) imgd = imgd._data pd.set_data("image", imgd) def save_as(self): dlg = FileDialog(action='save as', wildcard='*.rep') dlg.open() if dlg.filename != '': fi = file(dlg.filename, 'w') dump(self, fi) fi.close() def load(self): dlg = FileDialog(action='open', wildcard='*.rep') dlg.open() if dlg.filename != '': fi = file(dlg.filename, 'rb') s = load(fi) self.copy_traits(s) fi.close() def run_script(self): dlg = FileDialog(action='open', wildcard='*.py') dlg.open() if dlg.filename != '': #~ try: rx = self b = rx.Beamformer script = dlg.path execfile(dlg.path) #~ except: #~ pass def import_time_data(self): t = self.Beamformer.freq_data.time_data ti = csv_import() ti.from_file = 'C:\\tyto\\array\\07.03.2007 16_45_59,203.txt' ti.configure_traits(kind='modal') t.name = "" ti.get_data(t) def import_bk_mat_data(self): t = self.Beamformer.freq_data.time_data ti = bk_mat_import() ti.from_file = 'C:\\work\\1_90.mat' ti.configure_traits(kind='modal') t.name = "" ti.get_data(t) def import_td(self): t = self.Beamformer.freq_data.time_data ti = td_import() ti.from_file = 'C:\\work\\x.td' ti.configure_traits(kind='modal') t.name = "" ti.get_data(t) def import_nidaqmx(self): t = self.Beamformer.freq_data.time_data ti = nidaq_import() ti.configure_traits(kind='modal') t.name = "" ti.get_data(t) def set_Base(self): b = self.Beamformer self.Beamformer = BeamformerBase(freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env) self.invalid = True def set_Eig(self): b = self.Beamformer self.Beamformer = BeamformerEig(freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env) self.invalid = True def set_Capon(self): b = self.Beamformer self.Beamformer = BeamformerCapon(freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env) self.invalid = True def set_Music(self): b = self.Beamformer self.Beamformer = BeamformerMusic(freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env) self.invalid = True def set_Damas(self): b = self.Beamformer self.Beamformer = BeamformerDamas(beamformer=BeamformerBase( freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env)) self.invalid = True def set_Cleansc(self): b = self.Beamformer self.Beamformer = BeamformerCleansc(freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env) self.invalid = True def set_Ortho(self): b = self.Beamformer self.Beamformer = BeamformerOrth(beamformer=BeamformerEig( freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env)) self.Beamformer.n = 10 self.invalid = True def set_Functional(self): b = self.Beamformer self.Beamformer = BeamformerFunctional(freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env) self.invalid = True def set_Clean(self): b = self.Beamformer self.Beamformer = BeamformerClean(beamformer=BeamformerBase( freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env)) self.invalid = True def set_CMF(self): b = self.Beamformer self.Beamformer = BeamformerCMF(freq_data=b.freq_data, grid=b.grid, mpos=b.mpos, c=b.c, env=b.env) self.invalid = True def toggle_auto(self): self.automatic = not self.automatic def set_interp(self): self.configure_traits(kind='live', view=interpview) def set_drange(self): self.drange.configure_traits(kind='live', view=drangeview) def set_yrange(self): self.yrange.configure_traits(kind='live', view=drangeview) def set_pic(self): self.configure_traits(kind='live', view=picview)
def get_menu(self, obj, trait, row, column): if obj.selected_samples: return MenuManager( Action(name='Unselect', action='unselect_samples'), Action(name='Chronological View', action='load_chrono_view'), Action(name='Configure', action='configure_sample_table'))
""" Create menus that operate on TableEditors. Useful for making a right-click context menu. """ # Enthought library imports. from traits.api import List, Int from traitsui.api import Handler from traitsui.menu import Action, Menu from traitsui.api import TableEditor as _TableEditor new_delete_menu = Menu(Action(name="New", action="new_in_table"), Action(name="Delete", action="delete_from_table")) class TableMenuHandler(Handler): """ A Handler that provides for menu options to operate on the selected rows """ # The list of table editors in the View table_editors = List(_TableEditor) ######################################################################### # Handler interface ######################################################################### def init(self, info): """ Find table editors in the ui object that is passed. """ self.table_editors = [ editor for editor in info.ui._editors
add=[Employee]), TreeNode(node_for=[Department], auto_open=True, children='employees', label='name', menu=Menu(NewAction, Separator(), DeleteAction, Separator(), RenameAction, Separator(), CopyAction, CutAction, PasteAction), view=View(['name', '|<']), add=[Employee]), TreeNode(node_for=[Employee], auto_open=True, label='name', menu=Menu( NewAction, Separator(), Action(name='Default title', action='object.default_title'), Action( name='Department', action='handler.employee_department(editor,object)'), Separator(), CopyAction, CutAction, PasteAction, Separator(), DeleteAction, Separator(), RenameAction), view=View(['name', 'title', 'phone', '|<'])) ]) #------------------------------------------------------------------------- # 'TreeHandler' class: #------------------------------------------------------------------------- class TreeHandler(Handler): def employee_department(self, editor, object):
class DialogPhaseValue(DialogPhase): """ Dialog to create a instance of the class PhaseValue. The dialog checks all attributes and make sure that a invalid phase can not created. """ position = Instance(Combobox, ()) id = Instance(Combobox, ()) name = Str start_value = Float end_value = Float ticks = Float #========================================================================= # Methods to handle the dialog with other classes #========================================================================= def open_dialog(self, phase_num, ports, phases=None): if not phases == None: self.cur_phases = phases self.position.reset() self.id.reset() for i in range(1, phase_num + 1): self.position.add_item("Position " + str(i), i) for p in ports: self.id.add_item(p.name, p.id) self._check_phase() return self.configure_traits(kind="livemodal") def load(self): """Create a instance of the class PhaseValue with the attributes\ of the view. :returns: Value based phase :rtype: PhaseValue """ phase = PhaseValue(self.model, self, *self._get_attributes()) self.name = "" return phase def _get_attributes(self): # Return all attributes of the view. pid = self.id.get_selected_value() return self.start_value, self.end_value, self.ticks, pid,\ self.name, self.reset, self.reset_time def _update_attributes(self, args): # update the attributes of the view self.start_value, self.end_value, self.ticks, pid,\ self.name, self.reset, self.reset_time = args self.id.show_value(pid) #========================================================================= # Traitsview + Traitsevent #========================================================================= ConfirmButton = Action(name="OK", enabled_when="not error") @on_trait_change("name,id,start_value,end_value,ticks") def _check_phase(self): # Checks whether the given attributes are correctly. try: for phase in self.cur_phases: if phase.name == self.name: raise ValueError("The name does already exists") if self.start_value == self.end_value: raise ValueError("The start and end value are the same") elif self.ticks <= 0: raise ValueError("Ticks must be positve") elif self.position < 1: raise ValueError("Invalid position") PhaseValue(self.model, self, *self._get_attributes()) self.error = False except Exception, e: self.error = True self.error_msg = str(e)
def get_menu(self, obj, trait, row, column): # item = getattr(obj, trait)[row] actions = [Action(name='Move', action='move_to_session')] menu = MenuManager(*actions) return menu
def step_dclicked(object): object.dclicked() def frame_dclicked(object): object.dclicked() def db_dclicked(object): object.dclicked() # Actions used by tree editor context menu open_outputdb_action = Action(name='Open output database', action='handler.open_outputdb(editor,object)') reload_outputdb_action = Action( name='Reload', action='handler.reload_outputdb(editor,object)') close_outputdb_action = Action(name='Close', action='handler.remove_outputdb(editor,object)') refresh_action = Action(name='Refresh Tree', action='handler.refresh(editor,object)') # Tree editor tree_editor = TreeEditor(nodes=[ TreeNode(node_for=[Root], children='', label='name', view=View(Group('name', orientation='vertical', show_left=True))), TreeNode(node_for=[Root], children='outputdbs',