class FileSource(PointSource): file = File() #name = Str('Points File') def getPoints(self): import numpy as np return np.load(self.file)
class CSVGrapher(HasTraits): """ 主界面包括绘图列表,数据源,文件选择器和添加绘图按钮 """ graph_list = List(Instance(Graph)) # 绘图列表 data_source = Instance(DataSource) # 数据源 csv_file_name = File(filter=[u"*.csv"]) # 文件选择 add_graph_button = Button(u"添加绘图") # 添加绘图按钮 view = View( # 整个窗口分为上下两个部分 VGroup( # 上部分横向放置控件,因此用HGroup HGroup( # 文件选择控件 Item("csv_file_name", label=u"选择CSV文件", width=400), # 添加绘图按钮 Item("add_graph_button", show_label=False) ), # 下部分是绘图列表,采用ListEditor编辑器显示 Item("graph_list", style="custom", show_label=False, editor=ListEditor( use_notebook=True, # 是用多标签页格式显示 deletable=True, # 可以删除标签页 dock_style="tab", # 标签dock样式 page_name=".name") # 标题页的文本使用Graph对象的name属性 ) ), resizable = True, height = 0.8, width = 0.8, title = u"CSV数据绘图器" ) def _csv_file_name_changed(self): """ 打开新文件时的处理,根据文件创建一个DataSource """ self.data_source = DataSource() self.data_source.load_csv(self.csv_file_name) del self.graph_list[:] def _add_graph_button_changed(self): """ 添加绘图按钮的事件处理 """ if self.data_source != None: self.graph_list.append( Graph(data_source = self.data_source) )
class FigureInspectorData(FigureInspector): """See :class:`Figure`. In adition.. defines a filename attribute.. ta load images from file """ filename = File() traits_view = View('filename', Group(Item('container', editor=ComponentEditor(size=size, bgcolor=bg_color), show_label=False), orientation="vertical"), resizable=True) def _filename_changed(self, new): image = ImageData.fromfile(new) self.plot_image(image._data)
class AnimatedGIFDemo(HasTraits): # The animated GIF file to display: gif_file = File(files[0]) # Is the animation playing or not? playing = Bool(True) # The traits view: view = View(VGroup( HGroup( Item('gif_file', editor=AnimatedGIFEditor(playing='playing'), show_label=False), Item('playing'), ), '_', Item('gif_file', label='GIF File', editor=EnumEditor(values=files))), title='Animated GIF Demo', buttons=['OK'])
class SimpleFileDriver(IODriver): """ Simple file input driver. Reads lines from a file periodically. """ name = Str('Simple File Driver') view = View(Item(name='data_file', label='Input file'), Item(name='period_ms', label='Period / ms'), title='Simple file input driver') data_file = File() period_ms = Range(10, 10000, 200) _fp = Any() def open(self): try: self._fp = open(self.data_file, 'r') except IOError: self._fp = None def close(self): if self._fp: self._fp.close() def receive(self): if self._fp: time.sleep(self.period_ms / 1000.0) return self._fp.readline() else: return None @on_trait_change('data_file') def reopen_file(self): self.close() self.open()
class Case(HasTraits): ''' A class representing an avl input file ''' name = Str() mach_no = Float() symmetry = List(minlen=3, maxlen=3) ref_area = Float() ref_chord = Float() ref_span = Float() ref_cg = Array(numpy.float, (3, )) CD_p = Float geometry = Instance(Geometry) cwd = Directory case_filename = File('') traits_view = View(Item('name'), Item('mach_no'), Item('symmetry'), Item('ref_area'), Item('ref_chord'), Item('ref_span'), Item('ref_cg', editor=ArrayEditor()), Item('CD_p')) #@cached_property #def _get_geometries(self): # return [self.geometry] if self.geometry is not None else [] controls = DelegatesTo('geometry') def write_input_file(self, file): ''' Write all the data in the case in the appropriate format as in input .avl file for the AVL program ''' file.write(self.name + '\n') file.write('#Mach no\n%f\n' % self.mach_no) file.write('#iYsym iZsym Zsym\n%s %s %s\n' % tuple(self.symmetry)) file.write('#Sref Cref Bref\n%f %f %f\n' % (self.ref_area, self.ref_chord, self.ref_span)) file.write('#Xref Yref Zref\n%f %f %f\n' % tuple(self.ref_cg)) if self.CD_p != 0.0: file.write('#CD_p profile drag coefficient\n%f\n' % self.CD_p) file.write('\n') file.write('#' * 70) file.write('\n') self.geometry.write_to_file(file) file.write('') @classmethod def case_from_input_file(cls, file, cwd=''): ''' return an instance of Case by reading its data from an input file ''' lines = file.readlines() lines = filter_lines(lines) lineno = 0 name = lines[0] mach_no = float(lines[1].split()[0]) symmetry = lines[2].split() symmetry = [int(symmetry[0]), int(symmetry[1]), float(symmetry[2])] ref_area, ref_chord, ref_span = [ float(value) for value in lines[3].split()[:3] ] ref_cg = [float(value) for value in lines[4].split()[:3]] lineno = 5 try: CD_p = float(lines[5].split()[0]) lineno = 6 except ValueError: CD_p = 0.0 geometry = Geometry.create_from_lines(lines, lineno, cwd=cwd) case = Case(name=name, mach_no=mach_no, symmetry=symmetry, ref_area=ref_area, ref_chord=ref_chord, ref_span=ref_span, ref_cg=ref_cg, CD_p=CD_p, geometry=geometry, cwd=cwd) return case
class TiffDataSource(BaseDataSource): open_button = Button ('Load TIFF file..') file_name = File (filter = tiff_filter) available_channels = List(Str) selected_channel = Str(editor=EnumEditor(name = 'available_channels', cols=1)) # Private traits tiff = Instance (TiffBase) tiff_array = Instance(TiffArray) tiff_array_info = Dict tables_info = Dict view = View( Item ('open_button', show_label=False),'_', Item ('file_name', style='readonly', springy=True), Item ('selected_channel', style = 'custom', label='Channel'), Item ('kind', style='custom', label = 'View as'), Item ('voxel_sizes', editor=TupleEditor (cols=3, labels = ['Z', 'Y', 'X']), visible_when='is_image_stack'), Item ('pixel_sizes', editor=TupleEditor (cols=2, labels = ['Y', 'X']), visible_when='is_image_timeseries'), '_', Item ('description', style='readonly', show_label=False, resizable = True), scrollable = True, resizable = True) def _open_button_changed (self): tiffinfo = TiffFileInfo() fd = OpenFileDialog(file_name = os.path.abspath(self.file_name or ''), filter = tiff_filter, extensions = tiffinfo) if fd.edit_traits(view = 'open_file_view' ).result and tiffinfo.is_ok: self.file_name = fd.file_name #self.kind = tiffinfo.kind self.description = tiffinfo.description def _file_name_changed(self): print self.file_name if not os.path.isfile(self.file_name): raise ValueError ("File does not exist: %r" % (self.file_name)) self.reset() tiff_array_info = {} tables_info = {} if os.path.basename(self.file_name)=='configuration.txt': tiff_files = {} dir_path = os.path.dirname(self.file_name) csv_files = glob.glob(os.path.join(dir_path, '*.csv')) default_kind = 'image_timeseries' for d in ['Imperx', 'Andor', 'Confocal']: channel_label = '%s' % (d) d_path = os.path.join(dir_path, '%s_index.txt' % (d)) if not os.path.isfile (d_path): # mari-ism support d_path = os.path.join(dir_path, d, '%s_index.txt' % (d)) if os.path.isfile (d_path): d_index = {} time_map = defaultdict(lambda:[]) file_map = defaultdict(lambda:[]) for index, line in enumerate(open (d_path).readlines ()): t, fn = line.strip().split() t = float(t) fn = os.path.join(os.path.dirname(d_path), fn) d_index[t, index] = fn time_map[fn].append(t) file_map[t].append(fn) if len (file_map)<=1: default_kind = 'image_stack' elif len (file_map[t])>1: default_kind = 'image_stack_timeseries' files = [d_index[k] for k in sorted (d_index)] tiff = TiffFiles(files, time_map = time_map) tiff_files[channel_label] = tiff tiff_array_info[channel_label] = dict(channel=channel_label, subfile_type=0, sample_index=0, assume_one_image_per_file=True) tables = {} for csv_path in csv_files: print 'Reading',csv_path,'..' name = os.path.basename(csv_path)[:-4] titles = None table_data = defaultdict(lambda:[]) for line in open(csv_path).readlines(): line = line.strip() if not line: continue if titles is None: titles = [title[1:-1] for title in line. split('\t')] else: data = line.split ('\t') for title, value in zip (titles, data): table_data[title].append (float(value)) tables[name] = table_data print 'done' for channel_label in tiff_files: tables_info[channel_label] = tables tiff = TiffChannelsAndFiles(tiff_files) else: tiff = TIFFfile(self.file_name) default_kind = 'image_stack' for subfile_type in tiff.get_subfile_types(): ifd = tiff.get_first_ifd(subfile_type=subfile_type) depth = tiff.get_depth(subfile_type=subfile_type) width = ifd.get_value('ImageWidth') height = ifd.get_value('ImageLength') if subfile_type!=0: print '%s._file_name_changed: ignoring subfile_type %r' % (self.__class__.__name__, subfile_type) continue for i, (name, dtype) in enumerate(zip (ifd.get_sample_names(), ifd.get_sample_dtypes())): tname = str(dtype) channel_label = '%s: %s [%sx%sx%s %s]' % (subfile_type, name, depth, height, width, tname) tiff_array_info[channel_label] = dict (subfile_type=subfile_type, sample_index=i) self.kind = default_kind self.tiff = tiff try: info = tiff.get_info() except Exception, msg: info = 'failed to get TIFF info: %s' % (msg) self.tiff_array_info = tiff_array_info self.tables_info = tables_info self.available_channels = sorted (tiff_array_info) self.selected_channel = self.available_channels[0] self.description = info
class MultiSelections(HasTraits): """ Object used to store analysis objects in List of points """ selections = List(RectangleSelection) selection = Instance(RectangleSelection, transient=True) #: default filename for points load, save filename = File() add_point = Button() load = Button() save = Button() index_high = Property(Int, depends_on='selections', transient=True) index = Property(Int, depends_on='selection,index_high', transient=True) updated = Event() _update = Bool(True) view = View(Item('index', editor=RangeEditor(low=0, high_name='index_high', is_float=False, mode='spinner')), HGroup( Item('add_point', show_label=False, springy=True), Item('load', show_label=False, springy=True), Item('save', show_label=False, springy=True), ), '_', VGroup( Item('selections@', id='notebook', show_label=False, editor=ListEditor(use_notebook=True, deletable=True, selected='selection', export='DockWindowShell', page_name='.name')), ), id='enthought.traits.ui.demo.Traits UI Demo.Advanced.' 'List_editor_notebook_selection_demo', dock='horizontal', resizable=True, height=-0.5) def _load_fired(self): f = FileDialog(action='open', title='Load points', default_path=self.filename, wildcard='*.points') if f.open() == OK: self.filename = f.path self.from_file() def _save_fired(self): f = FileDialog(action='save as', title='Save points', default_path=self.filename, wildcard='*.points') if f.open() == OK: self.filename = f.path self.to_file() def _selection_default(self): return self.selections[0] def _get_index_high(self): return len(self.selections) - 1 def _add_point_fired(self): self._update = False point = (self.selections[self.index]).clone_traits() point.name = 'point ' + str(len(self.selections)) self.selections.append(point) self.selection = self.selections[-1] self._update = True self.update() def _selections_default(self): return POINTS @on_trait_change('selections[]') def _update_names(self): #update point names for i, point in enumerate(self.selections): point.name = 'point ' + str(i) def _get_index(self): try: return self.selections.index(self.selection) except: return self.index_high self.update() def _set_index(self, value): self.selection = self.selections[value] def from_file(self): """Reads selections from file """ with open(self.filename, 'rb') as f: self._update = False self.selections = pickle.load(f) self.index = 0 self._update = True self.update() def to_file(self): """Stores selections to file """ with open(self.filename, 'wb') as f: pickle.dump(self.selections, f) @on_trait_change('selection.updated') def update(self): """ Notify update """ if self._update: self.updated = True
class TraitsTest(HasTraits): #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- enabled = true integer_text = Int(1) enumeration = Trait('one', 'two', 'three', 'four', 'five', 'six', cols=3) float_range = Range(0.0, 10.0, 10.0) int_range = Range(1, 6) int_range2 = Range(1, 50) compound = Trait(1, Range(1, 6), 'one', 'two', 'three', 'four', 'five', 'six') boolean = true instance = Trait(Instance()) color = Color('cyan') font = Font() check_list = List( editor=CheckListEditor(values=['one', 'two', 'three', 'four'], cols=4)) list = List(Str, ['East of Eden', 'The Grapes of Wrath', 'Of Mice and Men']) button = Event(0, editor=ButtonEditor(label='Click')) file = File() directory = Directory() image_enum = Trait(editor=ImageEnumEditor(values=origin_values, suffix='_origin', cols=4, klass=Instance), *origin_values) #--------------------------------------------------------------------------- # View definitions: #--------------------------------------------------------------------------- view = View( ('|{Enum}', ('enabled', ), ('|<[Enumeration]', 'f1:enumeration[Simple]', '_', 'f2:enumeration[Custom]@', '_', 'f3:enumeration[Text]*', '_', 'f4:enumeration[Readonly]~'), ('|<[Check List]', 'f5:check_list[Simple]', '_', 'f6:check_list[Custom]@', '_', 'f7:check_list[Text]*', '_', 'f8:check_list[Readonly]~')), ('|{Range}', ('|<[Float Range]', 'f9:float_range[Simple]', '_', 'f10:float_range[Custom]@', '_', 'f11:float_range[Text]*', '_', 'f12:float_range[Readonly]~'), ('|<[Int Range]', 'f13:int_range[Simple]', '_', 'f14:int_range[Custom]@', '_', 'f15:int_range[Text]*', '_', 'f16:int_range[Readonly]~'), ('|<[Int Range 2]', 'f17:int_range2[Simple]', '_', 'f18:int_range2[Custom]@', '_', 'f19:int_range2[Text]*', '_', 'f20:int_range2[Readonly]~')), ('|{Misc}', ('|<[Integer Text]', 'f21:integer_text[Simple]', '_', 'f22:integer_text[Custom]@', '_', 'f23:integer_text[Text]*', '_', 'f24:integer_text[Readonly]~'), ('|<[Compound]', 'f25:compound[Simple]', '_', 'f26:compound[Custom]@', '_', 'f27:compound[Text]*', '_', 'f28:compound[Readonly]~'), ('|<[Boolean]', 'f29:boolean[Simple]', '_', 'f30:boolean[Custom]@', '_', 'f31:boolean[Text]*', '_', 'f32:boolean[Readonly]~')), ('|{Color/Font}', ('|<[Color]', 'f33:color[Simple]', '_', 'f34:color[Custom]@', '_', 'f35:color[Text]*', '_', 'f36:color[Readonly]~'), ('|<[Font]', 'f37:font[Simple]', '_', 'f38:font[Custom]@', '_', 'f39:font[Text]*', '_', 'f40:font[Readonly]~')), ('|{List}', ('|<[List]', 'f41:list[Simple]', '_', 'f42:list[Custom]@', '_', 'f43:list[Text]*', '_', 'f44:list[Readonly]~')), ( '|{Button}', ('|<[Button]', 'f45:button[Simple]', '_', 'f46:button[Custom]@'), # 'button[Text]*', # 'button[Readonly]~' ), ('|<[Image Enum]', 'f47:image_enum[Simple]', '_', 'f48:image_enum[Custom]@', '_', 'f49:image_enum[Text]*', '_', 'f50:image_enum[Readonly]~'), ('|<[Instance]', 'f51:instance[Simple]', '_', 'f52:instance[Custom]@', '_', 'f53:instance[Text]*', '_', 'f54:instance[Readonly]~'), ), ('|{File}', ( '|<[File]', 'f55:file[Simple]', '_', 'f56:file[Custom]@', '_', 'f57:file[Text]*', '_', 'f58:file[Readonly]~', ), ('|<[Directory]', 'f59:directory[Simple]', '_', 'f60:directory[Custom]@', '_', 'f61:directory[Text]*', '_', 'f62:directory[Readonly]~')), apply=True, revert=True, undo=True, ok=True, handler=TraitsTestHandler())
class Figure(HasTraits): pd = Instance(ArrayPlotData, transient = True) plot = Instance(Component,transient = True) process_selection = Function(transient = True) file = File('/home/andrej/Pictures/img_4406.jpg') traits_view = View( Group( Item('plot', editor=ComponentEditor(size=size, bgcolor=bg_color), show_label=False), orientation = "vertical"), resizable = True ) def __init__(self,**kwds): super(Figure,self).__init__(**kwds) self.pd = self._pd_default() self.plot = self._plot_default() def _process_selection_default(self): def process(point0, point1): print('selection', point0, point1) return process def _pd_default(self): image = zeros(shape = (300,400)) pd = ArrayPlotData() pd.set_data("imagedata", toRGB(image)) return pd def _plot_default(self): return self._create_plot_component() def _create_plot_component(self): pd = self.pd # Create the plot plot = Plot(pd, default_origin="top left",orientation="h") shape = pd.get_data('imagedata').shape plot.aspect_ratio = float(shape[1]) / shape[0] plot.x_axis.orientation = "top" #plot.y_axis.orientation = "top" #img_plot = plot.img_plot("imagedata",colormap = jet)[0] img_plot = plot.img_plot("imagedata",name = 'image', colormap = jet)[0] # Tweak some of the plot properties #plot.bgcolor = "white" plot.bgcolor = bg_color # Attach some tools to the plot plot.tools.append(PanTool(plot,constrain_key="shift", drag_button = 'right')) printer = DataPrinter(component=plot, process = self.process_selection) plot.tools.append(printer) plot.overlays.append(ZoomTool(component=plot, tool_mode="box", always_on=False)) #plot.title = 'Default image' imgtool = ImageInspectorTool(img_plot) img_plot.tools.append(imgtool) plot.overlays.append(ImageInspectorOverlay(component=img_plot, image_inspector=imgtool)) return plot def _file_changed(self, new): image = ImageData.fromfile(new) self.update_image(image.data) def update_image(self,data): image = toRGB(data) shape = image.shape self.pd.set_data("imagedata", image) self.plot.aspect_ratio = float(shape[1]) / shape[0] self.plot.delplot('image') img_plot = self.plot.img_plot("imagedata",name = 'image', colormap = jet)[0] imgtool = ImageInspectorTool(img_plot) img_plot.tools.append(imgtool) self.plot.overlays.pop() self.plot.overlays.append(ImageInspectorOverlay(component=img_plot, image_inspector=imgtool)) #self.plot.plot('rectangle1',) self.plot.request_redraw() def plot_data(self, x, y, name = 'data 0', color = 'black'): xname = 'x_' + name yname = 'y_' + name self.pd.set_data(xname,x) self.pd.set_data(yname,y) self.del_plot(name) self.plot.plot((xname,yname), name = name, color = color) self.plot.request_redraw() def del_plot(self, name): try: self.plot.delplot(name) except: pass
class FileName(HasTraits): filename = File("saved_plot.png")
class FileName(HasTraits): filename = File() traits_view = View(Item('filename'), buttons=['OK', 'Cancel'])
class DLS_DataSelector(HasTraits): """ This class is used to visually analyze dls data and to choose, whether it is good or not.. for later analysis. >>> filenames = Filenames(directory = 'testdata', pattern = '*.ASC') >>> data = DLS_DataSelector(filenames = filenames) >>> data.configure_traits() >>> data.save_bad_data() """ filenames = Instance(DLS_Filenames, ()) selected = DelegatesTo('filenames') bad_data = DelegatesTo('filenames') #good_data = DelegatesTo('filenames') data = Instance(CorrelationData, ()) load_btn = Button('Load bad data') save_btn = Button('Save bad data') next_btn = Button('>') prev_btn = Button('<') good_btn = Button('Good') bad_btn = Button('Bad') calculate_btn = Button('Calculate') bad_name = File('bad_data.txt') view = View(Group( HGroup( Group(Item('filenames', show_label=False, style='custom'), HGroup(*items_from_names(IOBTNS, show_label=False))), Group(Item('data', style='custom', show_label=False), HGroup(*items_from_names(BTNS, show_label=False))))), resizable=True) def __init__(self, *args, **kw): super(DLS_DataSelector, self).__init__(*args, **kw) #try: # self.load_bad_data(self.bad_data) #except: # pass def _load_btn_fired(self): f = FileDialog(action='open', default_path=self.bad_name, wildcard='*.txt') if f.open() == OK: self.bad_name = f.path self.load_bad_data(self.bad_name) def _save_btn_fired(self): f = FileDialog(action='save as', default_path=self.bad_name, wildcard='*.txt') if f.open() == OK: self.bad_name = f.path self.save_bad_data(self.bad_name) def save_bad_data(self, fname='bad_data.txt'): with open(fname, 'w') as f: for data in self.bad_data: f.write(data + '\n') def load_bad_data(self, fname='bad_data.txt'): with open(fname, 'r') as f: for data in f: self.bad_data.add(data.strip()) def _bad_data_default(self): bad_data = set() try: with open('bad_data.txt', 'r') as f: for line in f: bad_data.add(line.strip()) except IOError: pass return bad_data def _selected_changed(self, name): log.info('Opening %s', name) header, self.data.correlation, self.data.count_rate = open_dls(name) def _next_btn_fired(self): try: self.filenames.index += 1 except IndexError: pass def _prev_btn_fired(self): if self.filenames.index > 0: self.filenames.index -= 1 def _good_btn_fired(self): try: self.bad_data.remove(self.filenames.selected) except: pass finally: self.filenames.index += 1 def _bad_btn_fired(self): self.bad_data.add(self.filenames.selected) self.filenames.index += 1 @on_trait_change('calculate_btn,filenames.updated') def calculate(self): """Calculates average correlation data """ corr = 0. n = 0 cr_sum = 0. for fname in self.filenames.filenames: if fname not in self.filenames.bad_data: header, correlation, count_rate = open_dls(fname) cr_mean = count_rate[:, 1].mean() n += 1 cr_sum += cr_mean corr += (correlation[:, 1] + 1.) * cr_mean**2. corr = corr * n / cr_sum**2. - 1. correlation_avg = np.empty(shape=(correlation.shape[0], 2), dtype='float') correlation_avg[:, 1] = corr - corr.min() correlation_avg[:, 0] = correlation[:, 0] self.data.correlation_avg = correlation_avg return corr
class RectangleSelections(HasTraits): """ Object used to store analysis objects in List of points """ selections = List(RectangleSelection) selection = Instance(RectangleSelection,transient = True) #: default filename for points load, save filename = File() add_point = Button() load = Button() save = Button() index_high = Property(Int,depends_on = 'selections',transient = True) index = Property(Int, depends_on = 'selection,index_high',transient = True) updated = Event() _update = Bool(True) view = View( Item('index' , editor = RangeEditor( low = 0, high_name = 'index_high', is_float = False, mode = 'spinner' )), HGroup( Item('add_point', show_label = False, springy = True), Item('load', show_label = False, springy = True), Item('save', show_label = False, springy = True), ), '_', VGroup( Item( 'selections@', id = 'notebook', show_label = False, editor = ListEditor( use_notebook = True, deletable = True, selected = 'selection', export = 'DockWindowShell', page_name = '.name' ) ), ), dock = 'horizontal' , resizable = True, height = -0.5) def _load_fired(self): f = FileDialog(action = 'open', title = 'Load points', default_path = self.filename, wildcard = '*.points') if f.open() == OK: self.filename = f.path self.from_file(f.path) def _save_fired(self): f = FileDialog(action = 'save as', title = 'Save points', default_path = self.filename, wildcard = '*.points') if f.open() == OK: self.filename = f.path self.to_file(f.path, self.selections) def _selection_default(self): return self.selections[0] def _get_index_high(self): return len(self.selections)-1 def _add_point_fired(self): self._update = False point = (self.selections[self.index]).clone_traits() point.name = 'point ' + str(len(self.selections)) self.selections.append(point) self.selection = self.selections[-1] self._update = True self.update() def _selections_default(self): return POINTS # @on_trait_change('selections[]') # def _update_names(self): # #update point names # for i, point in enumerate(self.selections): # point.name = 'point ' + str(i) def _get_index(self): try: return self.selections.index(self.selection) except: return self.index_high self.update() def _set_index(self, value): self.selection = self.selections[value] def from_file(self, filename): """Reads selections from file """ selections = [] with open(filename, 'rb') as f: for line in f: selections.append(RectangleSelection(**safe_eval(line))) self.selections = selections self._update = True self.update() return selections def to_file(self, filename, selections): """Stores selections to file """ with open(filename, 'wb') as f: for s in selections: kw = s.get('width', 'height', 'name') kw['center'] = tuple(s.center) f.write(str(kw)) f.write('\n') @on_trait_change('selection.updated') def update(self): """ Notify update """ if self._update: self.updated = True
class AVL(HasTraits): ''' A class representing an avl program instance. ''' patterns = {'/' : 'AVL c> ', '/oper' : re.compile(r"""\.OPER \(case (?P<case_num>\d)/(?P<num_cases>\d)\) c> """), '/plop' : r'Option, Value \(or <Return>\) c> ', '/oper/a': re.compile(r"""Select new constraint,value for (?P<param>.*?)\s+c> """), '/oper/m': r'Enter parameter, value \(or # - \+ N \) c> ', '/mode' : r'\.MODE c> ', '/mode/s': r'Enter output filename \(or <Return>\):', 'num' : r'(?P<val>[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?)' } run_cases = List(RunCase, []) state = String('/') selected_runcase = Int(1) case = Instance(Case) case_filename = File() mass = Instance(Mass) cwd = Directory reload_output = Action #runoutput = Instance(RunOutput) traits_view = View(Item('selected_runcase')) def _selected_case_changed(self): self.avl.sendline('oper') self.avl.sendline(str(self.selected_case)) AVL.goto_state(self.avl) def __init__(self, path='', cwd='', logfile='avl.log',**kwargs): ''' Constructor path is the directory where avl binary is found cwd is the working dir, where all the case related files are expected to be found (eg airfoil files) logfile is where all output is to be logged ''' super(AVL, self).__init__(**kwargs) self.avl = pexpect.spawn(os.path.join(path, 'avl'), logfile=open(logfile, 'w'), cwd=cwd) self.avl.timeout = 10 self.avl.delaybeforesend = 0 self.cwd = cwd self.disable_plotting() def execute_case(self, case_num=None): # TODO: implement if case_num is None: case_num = self.selected_case self.avl.sendline('oper') self.avl.expect(AVL.patterns['/oper']) self.avl.sendline(str(case_num)) self.avl.expect(AVL.patterns['/oper']) self.avl.sendline('x') AVL.goto_state(self.avl) def disable_plotting(self): self.avl.sendline('plop') self.avl.sendline('g') AVL.goto_state(self.avl) @classmethod def goto_state(cls, avl, state='/'): for i in xrange(6): avl.sendline('') try: avl.expect(AVL.patterns['/'], timeout=1) return except pexpect.TIMEOUT: pass raise Exception('Can\'t reach base state') def populate_runcases(self): self.avl.sendline('oper') self.avl.expect(AVL.patterns['/oper']) num_cases = int(self.avl.match.group('num_cases')) AVL.goto_state(self.avl) runcases = [] for case_num in xrange(1, num_cases + 1): runcases.append(RunCase.get_case_from_avl(self.avl, case_num)) self.run_cases = runcases self.selected_case = 1 def load_case_from_file(self, filename): self.avl.sendline('load %s' % filename) self.case_filename = filename if os.path.isabs(filename): f = open(filename) else: f = open(os.path.join(self.cwd, filename)) self.case = Case.case_from_input_file(f, cwd=self.cwd) f.close() AVL.goto_state(self.avl) self.populate_runcases() def _run_cases_changed(self): print 'run_cases changed' # self.reload_output = True def _case_changed(self): print 'case changed' def load_mass_from_file(self, filename): self.mass = Mass.mass_from_file(filename)