# ------------------------------------------------------------------------ # Trait event handlers ------------------------------------------------- def _on_name_changed(self, event): """ Called when the name has been changed. """ self.complete = len(event.new.strip()) > 0 return # Application entry point. if __name__ == "__main__": # Create the GUI (this does NOT start the GUI event loop). gui = GUI() wizard = SimpleWizard( parent=None, title="Create something magical", pages=[ SimpleWizardPage( id="foo", color="red", heading="The Red Page", subheading="The default color on this page is red.", ), SimpleWizardPage( id="bar", color="yellow", heading="The Yellow Page",
def test_coreg_gui(): """Test CoregFrame.""" _check_ci() home_dir = _TempDir() os.environ['_MNE_GUI_TESTING_MODE'] = 'true' os.environ['_MNE_FAKE_HOME_DIR'] = home_dir try: pytest.raises(ValueError, mne.gui.coregistration, subject='Elvis', subjects_dir=subjects_dir) from pyface.api import GUI from tvtk.api import tvtk gui = GUI() # avoid modal dialog if SUBJECTS_DIR is set to a directory that # does not contain valid subjects ui, frame = mne.gui.coregistration(subjects_dir='') frame.model.mri.subjects_dir = subjects_dir frame.model.mri.subject = 'sample' assert not frame.model.mri.fid_ok frame.model.mri.lpa = [[-0.06, 0, 0]] frame.model.mri.nasion = [[0, 0.05, 0]] frame.model.mri.rpa = [[0.08, 0, 0]] assert (frame.model.mri.fid_ok) frame.data_panel.raw_src.file = raw_path assert isinstance(frame.eeg_obj.glyph.glyph.glyph_source.glyph_source, tvtk.SphereSource) frame.data_panel.view_options_panel.eeg_obj.project_to_surface = True assert isinstance(frame.eeg_obj.glyph.glyph.glyph_source.glyph_source, tvtk.CylinderSource) # grow hair (faster for low-res) assert frame.data_panel.view_options_panel.head_high_res frame.data_panel.view_options_panel.head_high_res = False frame.model.grow_hair = 40. # scale frame.coreg_panel.n_scale_params = 3 frame.coreg_panel.scale_x_inc = True assert frame.model.scale_x == 101. frame.coreg_panel.scale_y_dec = True assert frame.model.scale_y == 99. # reset parameters frame.coreg_panel.reset_params = True assert_equal(frame.model.grow_hair, 0) assert not frame.data_panel.view_options_panel.head_high_res # configuration persistence assert (frame.model.prepare_bem_model) frame.model.prepare_bem_model = False frame.save_config(home_dir) ui.dispose() gui.process_events() ui, frame = mne.gui.coregistration(subjects_dir=subjects_dir) assert not frame.model.prepare_bem_model assert not frame.data_panel.view_options_panel.head_high_res ui.dispose() gui.process_events() finally: del os.environ['_MNE_GUI_TESTING_MODE'] del os.environ['_MNE_FAKE_HOME_DIR']
def _stop_timer(self): """Called when the user selecte "Stop Timer" from the menu.""" if self.my_timer is not None: self.my_timer.Stop() def _timer_task(self): """The method run periodically by the timer.""" self.counter += 1 print("counter = %d" % self.counter) if __name__ == "__main__": gui = GUI(splash_screen=splash_screen) # Create and open the main window. window = MainWindow() # Simulate a busy window initialization. for i in range(5): gui.process_events() time.sleep(1) window.open() # Start the GUI event loop! gui.start_event_loop()
def _gui_default(self): from pyface.api import GUI return GUI(splash_screen=self.splash_screen)
def event_loop(): from pyface.api import GUI gui = GUI() gui.start_event_loop()
def __init__(self): super(HasStrictTraits, self).__init__() self.gui = GUI()
def _gui_default(self): """ Trait initializer. """ return GUI(splash_screen=self.splash_screen)
def run_job(args): grid, prefix, job = args logging.info("starting job %s", job) result = Result.from_vtk(prefix, job[0]) sim = Simulation(result.mesh) result = sim.simulate(job, grid, sing=result.mesh_charge, fmm_on_eval=False) result.name += "_new" # FIXME: parametrize result.to_vtk(prefix) def main(): p = argparse.ArgumentParser( description="evaluate a bem simulation result (charge" " distribution) in another grid") p.add_argument("prefix", help="data path prefix") p.add_argument("electrodes", nargs="+", help="electrode name") args = p.parse_args() evaluate(args.prefix, args.electrodes) if __name__ == "__main__": main() from pyface.api import GUI GUI().start_event_loop()
def main(): parser = argparse.ArgumentParser() parser.add_argument('filename', nargs='+', help='name of flydra .hdf5 file', ) parser.add_argument("--stim-xml", type=str, default=None, help="name of XML file with stimulus info", required=True, ) parser.add_argument("--align-json", type=str, default=None, help="previously exported json file containing s,R,T", ) parser.add_argument("--radius", type=float, help="radius of line (in meters)", default=0.002, metavar="RADIUS") parser.add_argument("--obj-only", type=str) parser.add_argument("--obj-filelist", type=str, help="use object ids from list in text file", ) parser.add_argument( "-r", "--reconstructor", dest="reconstructor_path", type=str, help=("calibration/reconstructor path (if not specified, " "defaults to FILE)")) args = parser.parse_args() options = args # optparse OptionParser backwards compatibility reconstructor_path = args.reconstructor_path fps = None ca = core_analysis.get_global_CachingAnalyzer() by_file = {} for h5_filename in args.filename: assert(tables.is_hdf5_file(h5_filename)) obj_ids, use_obj_ids, is_mat_file, data_file, extra = ca.initial_file_load( h5_filename) this_fps = result_utils.get_fps( data_file, fail_on_error=False ) if fps is None: if this_fps is not None: fps = this_fps if reconstructor_path is None: reconstructor_path = data_file by_file[h5_filename] = (use_obj_ids, data_file) del h5_filename del obj_ids, use_obj_ids, is_mat_file, data_file, extra if options.obj_only is not None: obj_only = core_analysis.parse_seq(options.obj_only) else: obj_only = None if reconstructor_path is None: raise RuntimeError('must specify reconstructor from CLI if not using .h5 files') R = reconstruct.Reconstructor(reconstructor_path) if fps is None: fps = 100.0 warnings.warn('Setting fps to default value of %f'%fps) else: fps = 1.0 if options.stim_xml is None: raise ValueError( 'stim_xml must be specified (how else will you align the data?') if 1: stim_xml = xml_stimulus.xml_stimulus_from_filename( options.stim_xml, ) try: fanout = xml_stimulus.xml_fanout_from_filename( options.stim_xml ) except xml_stimulus.WrongXMLTypeError: pass else: include_obj_ids, exclude_obj_ids = fanout.get_obj_ids_for_timestamp( timestamp_string=file_timestamp ) if include_obj_ids is not None: use_obj_ids = include_obj_ids if exclude_obj_ids is not None: use_obj_ids = list( set(use_obj_ids).difference( exclude_obj_ids ) ) print('using object ids specified in fanout .xml file') if stim_xml.has_reconstructor(): stim_xml.verify_reconstructor(R) x = [] y = [] z = [] speed = [] if options.obj_filelist is not None: obj_filelist=options.obj_filelist else: obj_filelist=None if obj_filelist is not None: obj_only = 1 if obj_only is not None: if len(by_file) != 1: raise RuntimeError("specifying obj_only can only be done for a single file") if obj_filelist is not None: data = np.loadtxt(obj_filelist,delimiter=',') obj_only = np.array(data[:,0], dtype='int') print(obj_only) use_obj_ids = numpy.array(obj_only) h5_filename = by_file.keys()[0] (prev_use_ob_ids, data_file) = by_file[h5_filename] by_file[h5_filename] = (use_obj_ids, data_file) for h5_filename in by_file: (use_obj_ids, data_file) = by_file[h5_filename] for obj_id_enum,obj_id in enumerate(use_obj_ids): rows = ca.load_data( obj_id, data_file, use_kalman_smoothing=False, #dynamic_model_name = dynamic_model_name, #frames_per_second=fps, #up_dir=up_dir, ) verts = numpy.array( [rows['x'], rows['y'], rows['z']] ).T if len(verts)>=3: verts_central_diff = verts[2:,:] - verts[:-2,:] dt = 1.0/fps vels = verts_central_diff/(2*dt) speeds = numpy.sqrt(numpy.sum(vels**2,axis=1)) # pad end points speeds = numpy.array([speeds[0]] + list(speeds) + [speeds[-1]]) else: speeds = numpy.zeros( (verts.shape[0],) ) if verts.shape[0] != len(speeds): raise ValueError('mismatch length of x data and speeds') x.append( verts[:,0] ) y.append( verts[:,1] ) z.append( verts[:,2] ) speed.append(speeds) data_file.close() del h5_filename, use_obj_ids, data_file if 0: # debug if stim_xml is not None: v = None for child in stim_xml.root: if child.tag == 'cubic_arena': info = stim_xml._get_info_for_cubic_arena(child) v=info['verts4x4'] if v is not None: for vi in v: print('adding',vi) x.append( [vi[0]] ) y.append( [vi[1]] ) z.append( [vi[2]] ) speed.append( [100.0] ) x = np.concatenate(x) y = np.concatenate(y) z = np.concatenate(z) w = np.ones_like(x) speed = np.concatenate(speed) # homogeneous coords verts = np.array([x,y,z,w]) ####################################################### # Create the MayaVi engine and start it. e = Engine() # start does nothing much but useful if someone is listening to # your engine. e.start() # Create a new scene. from tvtk.tools import ivtk #viewer = ivtk.IVTK(size=(600,600)) viewer = IVTKWithCalGUI(size=(800,600)) viewer.open() e.new_scene(viewer) viewer.cal_align.set_data(verts,speed,R,args.align_json) if 0: # Do this if you need to see the MayaVi tree view UI. ev = EngineView(engine=e) ui = ev.edit_traits() # view aligned data e.add_source(viewer.cal_align.source) v = Vectors() v.glyph.scale_mode = 'data_scaling_off' v.glyph.color_mode = 'color_by_scalar' v.glyph.glyph_source.glyph_position='center' v.glyph.glyph_source.glyph_source = tvtk.SphereSource( radius=options.radius, ) e.add_module(v) if stim_xml is not None: if 0: stim_xml.draw_in_mayavi_scene(e) else: actors = stim_xml.get_tvtk_actors() viewer.scene.add_actors(actors) gui = GUI() gui.start_event_loop()
python_shell.bind("widget", self._tree_viewer) python_shell.bind("w", self._tree_viewer) python_shell.bind("window", self) python_shell.bind("actions", self._actions) return python_shell.control # Trait event handlers ------------------------------------------------- def _on_selection_changed(self, event): """ Called when the selection in the tree is changed. """ selection = event.new if len(selection) > 0: self._table_viewer.input = selection[0] return # Application entry point. if __name__ == "__main__": # Create the GUI and put up a splash screen (this does NOT start the GUI # event loop). gui = GUI(splash_screen=SplashScreen()) # Create and open the main window. window = MainWindow() window.open() # Start the GUI event loop. gui.start_event_loop()
def force_render(): _gui = GUI() orig_val = _gui.busy _gui.set_busy(busy=True) _gui.set_busy(busy=orig_val) _gui.process_events()
def _gui_default(self): return GUI(splash_screen=self.splash_screen)
def show(func=None, stop=False): """ Start interacting with the figure. By default, this function simply creates a GUI and starts its event loop if needed. If it is used as a decorator, then it may be used to decorate a function which requires a UI. If the GUI event loop is already running it simply runs the function. If not the event loop is started and function is run in the toolkit's event loop. The choice of UI is via `ETSConfig.toolkit`. If the argument stop is set to True then it pops up a UI where the user can stop the event loop. Subsequent calls to `show` will restart the event loop. **Parameters** :stop: A boolean which specifies if a UI dialog is displayed which allows the event loop to be stopped. **Examples** Here is a simple example demonstrating the use of show:: >>> from mayavi import mlab >>> mlab.test_contour3d() >>> mlab.show() You can stop interaction via a simple pop up UI like so:: >>> mlab.test_contour3d() >>> mlab.show(stop=True) The decorator can be used like so:: >>> @mlab.show ... def do(): ... mlab.test_contour3d() ... >>> do() The decorator can also be passed the stop argument:: >>> @mlab.show(stop=True) ... def do(): ... mlab.test_contour3d() ... >>> do() """ global _gui, _stop_show if func is None: if not is_ui_running(): g = GUI() _gui = g if stop: _stop_show = StopShow() g.start_event_loop() return def wrapper(*args, **kw): """Wrapper function to run given function inside the GUI event loop. """ global _gui, _stop_show tk = ETSConfig.toolkit if is_ui_running(): # In this case we should not pop up the UI since we likely # don't want to stop the mainloop. return func(*args, **kw) else: g = GUI() if tk == 'wx': # Create a dummy app so invoke later works on wx. a = ApplicationWindow(size=(1, 1)) GUI.invoke_later(lambda: a.close()) a.open() GUI.invoke_later(func, *args, **kw) _gui = g if stop: # Pop up the UI to stop the mainloop. _stop_show = StopShow() g.start_event_loop() return wrapper
def main(): try: from traits.etsconfig.api import ETSConfig ETSConfig.toolkit = 'qt4' from pyface.api import GUI except: print("did you install python-chaco?", file=sys.stderr) print( "maybe you did install chaco>=4, then you will need to install the package etsproxy", file=sys.stderr) print("sudo easy_install etsproxy", file=sys.stderr) raise # select the toolkit we want to use or just let auto detection # WX is more stable for now #ETSConfig.toolkit = 'qt4' #ETSConfig.toolkit = 'wx' print("DEBUG - toolkit is using ", ETSConfig.toolkit) raise_to_debug(3, __file__) # workaround bad bg color in ubuntu, with Ambiance theme # wxgtk (or traitsGUI, I dont know) looks like using the menu's bgcolor # for all custom widgets bg colors. :-( import os if ETSConfig.toolkit == 'wx': import wx, os if "gtk2" in wx.PlatformInfo: from gtk import rc_parse, MenuBar m = MenuBar() if m.rc_get_style( ).bg[0].red_float < 0.5: # only customize dark bg rc_parse( os.path.join(os.path.dirname(__file__), "images/gtkrc")) m.destroy() # workaround bug in kiva's font manager that fails to find a correct default font on linux if os.name == "posix": import warnings def devnull(*args): pass warnings.showwarning = devnull from kiva.fonttools.font_manager import fontManager, FontProperties try: font = FontProperties() font.set_name("DejaVu Sans") fontManager.defaultFont = fontManager.findfont(font) fontManager.warnings = None except: # this code will throw exception on ETS4, which has actually fixed fontmanager pass from window import open_file import optparse parser = optparse.OptionParser(usage="""\ %prog [options] [trace.txt|trace.txt.gz|trace.txt.lzma|trace.dat] pytimechart - Fast graphical exploration and visualisation for linux kernel traces.""" ) parser.add_option("-p", "--prof", dest="prof", action="store_true", help="activate profiling", default=False) (options, args) = parser.parse_args() # Create the GUI (this does NOT start the GUI event loop). gui = GUI() if len(args) == 0: args.append("dummy") for fn in args: if not open_file(fn): sys.exit(0) if options.prof: import cProfile dict = {"gui": gui} cProfile.runctx('gui.start_event_loop()', dict, dict, 'timechart.prof') else: gui.start_event_loop()
def make_frame(t): mlab.view(0,180+t/duration*360) GUI().process_events() return mlab.screenshot(antialiased=True)
def __init__(self): super().__init__() self.gui = GUI()