class Axes(AxesLikeModuleFactory): """ Creates axes for the current (or given) object.""" xlabel = String(None, adapts='axes.x_label', help='the label of the x axis') ylabel = String(None, adapts='axes.y_label', help='the label of the y axis') zlabel = String(None, adapts='axes.z_label', help='the label of the z axis') nb_labels = Range(0, 50, 2, adapts='axes.number_of_labels', desc='The number of labels along each direction') ranges = Trait( None, None, CArray(shape=(6, )), help="""[xmin, xmax, ymin, ymax, zmin, zmax] Ranges of the labels displayed on the axes. Default is the object's extents.""", ) x_axis_visibility = true( adapts='axes.x_axis_visibility', help="Whether or not the x axis is visible (boolean)") y_axis_visibility = true( adapts='axes.y_axis_visibility', help="Whether or not the y axis is visible (boolean)") z_axis_visibility = true( adapts='axes.z_axis_visibility', help="Whether or not the z axis is visible (boolean)") _target = Instance(modules.Axes, ()) def _extent_changed(self): """ Code to modify the extents for """ axes = self._target axes.axes.use_data_bounds = False axes.axes.bounds = self.extent if self.ranges is None: axes.axes.ranges = \ axes.module_manager.source.outputs[0].bounds def _ranges_changed(self): if self.ranges is not None: self._target.axes.ranges = self.ranges self._target.axes.use_ranges = True
class Base(HasTraits): name = String("default_name") def get_children_name(self, children): for attr in self.__dict__: if self.__dict__[attr] is children: return attr
class ArraySet(Simple): floatingType = String("arraySet") data = Array() ds = Instance(DS) def _ds_default(self): return DS()
class TraitedSource(HasTraits): SourceName = String(sourcename, desc='source name', label='name of %s [String]' % classtype.__name__) for parameter in classtype.outputlist: if hasattr(classorinstance, parameter[0]): defval = getattr(classorinstance, parameter[0]) else: try: defval = defaultvalues[parameter[1]] except: defval = parameter[2] if hasattr(classorinstance, parameter[0] + '_Unit'): unitval = getattr(classorinstance, parameter[0] + '_Unit') else: unitval = parameter[1] # set the input label parlabel = '%s [%s]' % (parameter[0], unitval) # create the traits object exec('%s = Float(defval,desc=parameter[3],label=parlabel)' % parameter[0])
class OrientationAxesFactory(SingletonModuleFactory): """Applies the OrientationAxes mayavi module to the given VTK data object. """ xlabel = String(None, adapts='axes.x_axis_label_text', help='the label of the x axis') ylabel = String(None, adapts='axes.y_axis_label_text', help='the label of the y axis') zlabel = String(None, adapts='axes.z_axis_label_text', help='the label of the z axis') _target = Instance(modules.OrientationAxes, ())
class UnstructuredMesh(Mesh): type = String("unstructured") nodes = Array(dtype=numpy.float32) elementTypes = Array(dtype=numpy.int8) elementNodes = Array(dtype=numpy.int32) selectorOnMesh = Instance(USelectorOnMesh) def _selectorOnMesh_default(self): return USelectorOnMesh()
class StructuredMesh(Mesh): type = String("structured") cartesianGrid = Instance(CartesianGrid()) selectorOnMesh = Instance(SSelectorOnMesh) def _cartesianGrid_default(self): return CartesianGrid() def _selectorOnMesh_default(self): return SSelectorOnMesh()
class SSelectorOnMeshElement(Base): shortName = String(ELEMENT_LENGTH) imin = Int() jmin = Int() kmin = Int() imax = Int() jmax = Int() kmax = Int() v1 = Float(-1.0) v2 = Float(-1.0) v3 = Float(-1.0)
class Parameter(HasTraits): name = String('name') value = Float def __str__(self): return '{%s:%f}' %(self.name,self.value) def __repr__(self): return '{%s:%f}' %(self.name,self.value) editor = TableEditor( auto_size=False, columns=[ObjectColumn(name='name', label='Name', editable=False), ObjectColumn(name='value', label='Value', editor=TextEditor(evaluate=float, enter_set=True, auto_set=False)), ])
class TrimCaseConfig(RunOptionsConfig): trimcase = Instance(TrimCase, TrimCase()) #runcase = DelegatesTo('trimcase') varying_param = String('velocity') varying_expr = Expression('100') param_name_list = Property(List(String), depends_on='trimcase.parameters') @cached_property def _get_param_name_list(self): return sorted(self.trimcase.parameters.keys(), key=lambda x: x.lower()) @on_trait_change('trimcase.parameter_view.value,trimcase.type') def on_trimcase_changed(self, object, name, old, new): print 'trimcase_changed' if name == 'value': self.trimcase.runcase.update_trim_case(self.trimcase, object) self.trimcase.update_parameters_from_avl() elif name == 'type': self.trimcase.update_parameters_from_avl() self.param_name_list[0] # send changed value of trimcase to avl, parameter is Parameter instance def update_trim_case(self, trimcase, parameter): print 'update_trim_case' self.get_parameters_info_from_avl(self.avl) self.avl.sendline('oper') self.avl.sendline(trimcase.type_) self.avl.expect(AVL.patterns['/oper/m']) #print self.parameters.keys() #for p, v in trimcase.parameters.iteritems(): self.avl.sendline('%s %f' % (parameter.cmd, parameter.value)) AVL.goto_state(self.avl) custom_group = Group( Item('object.trimcase.type'), Group(Item('object.trimcase.parameter_view', editor=Parameter.editor, show_label=False, height=0.4), label='Parameters', scrollable=True), #Item('trimcase', style='custom', show_label=False), Group(Item('varying_param', editor=EnumEditor(name='param_name_list')), Item('varying_expr', label='Expression')))
class SetActiveAttributeFactory(PipeFactory): """ Applies the SetActiveAttribute Filter mayavi filter to the given VTK object. """ point_scalars = String(adapts="point_scalars_name", help="The name of the active point scalars") point_vectors = String(adapts="point_vectors_name", help="The name of the active point vectors") point_tensors = String(adapts="point_tensors_name", help="The name of the active point tensors") cell_scalars = String(adapts="cell_scalars_name", help="The name of the active cell scalars") cell_vectors = String(adapts="cell_vectors_name", help="The name of the active cell vectors") cell_tensors = String(adapts="cell_tensors_name", help="The name of the active cell tensors") _target = Instance(filters.SetActiveAttribute, ())
class Interval(LinearListOfReal1): floatingType = String("LinearListOfReal1") first = Float(0.0) last = Float(0.0) number_of_values = None
class LinearListOfInteger2(Simple): floatingType = String("linearListOfInteger2") first = Float(0.0) step = Float(0.0) number_of_values = Int(0)
class PerDecadeListOfReal(Simple): floatingType = String("perDecadeListOfReal") first = Float(0.0) number_of_decades = Int(0) number_Of_values_per_decade = Int(0)
class LogarithmListOfReal(Simple): floatingType = String("logarithmListOfReal") first = Float(0.0) last = Float(0.0) number_of_values = 0
class LinearListOfReal1(Simple): floatingType = String("linearListOfReal1") first = Float(0.0) last = Float(0.0) number_of_values = Int(0)
class ParameterPanel(HasTraits): scan_type = String('') parameter_list = [] #Load all Python modules in the scripts directory and import #the UserParameter object if it exists. See /scripts/parameter.template #for user parameter script syntax.if sys.platform == 'darwin': if sys.platform == 'darwin': script_path = os.path.expanduser( '~/Library/Application Support/RadPy/Scripts') if not os.path.exists(script_path): os.makedirs(script_path) for name in glob.glob('../Scripts/*.py'): shutil.copy(name, script_path) else: script_path = os.path.join(os.pardir, 'Scripts') # for name in os.listdir(script_path): if name.endswith(".py") and name != '__init__.py': try: module = os.path.splitext(name)[0] f, filename, description = imp.find_module( module, [script_path]) # Import the module if no exception occurred #class_name = module+'.UserParameter' script = imp.load_module(module, f, filename, description) # If the module is a single file, close it if not (description[2] == imp.PKG_DIRECTORY): f.close() parameter_list.append(script.UserParameter()) #print 'Plugin:', module, 'loaded' except (ImportError, AttributeError): # Not able to find module so pass pass # sys.path.append(os.path.join(os.pardir,'Scripts')) # for name in os.listdir(os.path.join(os.pardir,'Scripts')) : # if name.endswith(".py" ) and name != '__init__.py': # name = os.path.splitext(name)[0] # try: # exec("from " + name +" import UserParameter") # # except ImportError: # pass # # except: # print "Unexpected error:", sys.exc_info()[0] # raise # # else: # parameter_list.append(UserParameter()) # item_list = [] for i in parameter_list: exec(i.name + ' = Float') item_list.append(i.get_item()) traits_ui_view = View( VGroup(item_list, id='radpy.plugins.BeamAnalysis.Parameters', padding=15, show_border=True), resizable=True, title="Parameters", #id='radpy.plugins.BeamAnalysis.ParameterPanel' id='ParameterPanel') def update_parameters(self, beam): if beam: self.scan_type = beam.get_scan_type() for i in self.parameter_list: parameter = i.calc(beam) setattr(self, i.name, parameter) else: self.scan_type = 'None'
class SSelectorOnMeshNode(Base): shortName = String(ELEMENT_LENGTH) i = Int() j = Int() k = Int()
class SegmentorRW(SegmentorBase): name = "Random Walk Segmentation" description = "Segmentation plugin using the Random Walk algorithm " author = "C. N. Straehle, HCI - University of Heidelberg" homepage = "http://hci.iwr.uni-heidelberg.de" gamma = Float(10) difference = Bool(False) lisOptions = String("-p saamg -tol 1.0e-4") view = View( Item('gamma'), Item('difference'), Item('lisOptions'), buttons=['OK', 'Cancel'], ) def segment3D(self, labelVolume, labelValues, labelIndices): seeds = numpy.zeros(labelVolume.shape[0:-1], numpy.uint8) seeds[:, :, :] = labelVolume[:, :, :, 0] print "Executing Random walker with gamma ", self.gamma res = vigra.rw.randomWalk( numpy.exp(-(self.weights)**2 / self.gamma**2), seeds, self.lisOptions) #.swapaxes(0,2).view(vigra.ScalarVolume)) self.potentials = res ret = numpy.argmax(res, 3) + 1 #ret[:] = ret.swapaxes(0,2).view(numpy.ndarray) ret.shape = ret.shape + (1, ) return ret def segment2D(self, labelVolume, labelValues, labelIndices): #TODO: implement return labelVolume def setupWeights(self, weights): #self.weights = numpy.average(weights, axis = 3).astype(numpy.uint8)#.swapaxes(0,2).view(vigra.ScalarVolume) self.weights = numpy.ndarray(weights.shape + (3, ), numpy.float32) tw = numpy.ndarray(weights.shape, numpy.float32) tw[:] = weights[:] self.weights[-1, :, :, 0] = 0 self.weights[:, -1, :, 1] = 0 self.weights[0, :, -1, 2] = 0 if self.difference: self.weights[0:-1, :, :, 0] = numpy.abs(tw[1:, :, :] - tw[0:-1, :, :]) self.weights[:, 0:-1, :, 1] = numpy.abs(tw[:, 1:, :] - tw[:, 0:-1, :]) self.weights[:, :, 0:-1, 2] = numpy.abs(tw[:, :, 1:] - tw[:, :, 0:-1]) else: self.weights[ 0:-1, :, :, 0] = 1 - numpy.abs(tw[1:, :, :] + tw[0:-1, :, :]) / 2 self.weights[:, 0:-1, :, 1] = 1 - numpy.abs(tw[:, 1:, :] + tw[:, 0:-1, :]) / 2 self.weights[:, :, 0:-1, 2] = 1 - numpy.abs(tw[:, :, 1:] + tw[:, :, 0:-1]) / 2
class GeneralRationalFraction(Vector): floatingType = String("generalRationalFraction") values = Array(dtype=numpy.complex64)
class Text(Component): """ Component with text traits """ #-------------------------------------------------------------------------- # "Text" interface: #-------------------------------------------------------------------------- # The background color of this component. bgcolor = "transparent" #"fuchsia" # Pen for drawing text pen = Instance(Pen, desc="pen instance with which to draw the text") # X-axis coordinate text_x = Float(desc="x-axis coordinate") # Y-axis coordinate text_y = Float(desc="y-axis coordinate") # Text justification justification = Int(-1, desc="(LEFT, CENTER, RIGHT = -1, 0, 1)") # justification = Trait("Left", {"Left": -1, "Centre": 0, "Right": 1}) # Width of the text text_w = Float(desc="width of the text as computed by the library") # Text to be drawn text = String(desc="text") #-------------------------------------------------------------------------- # Views: #-------------------------------------------------------------------------- traits_view = View( Group(Item("pen", style="custom", show_label=False), label="Pen", show_border=True), Item("text_x"), Item("text_y"), Item("text_w"), Item("justification"), Item("text")) #-------------------------------------------------------------------------- # Draw component on the graphics context: #-------------------------------------------------------------------------- def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the component """ gc.save_state() try: # Specify the font font = str_to_font(str(self.pen.font)) gc.set_font(font) gc.set_fill_color(self.pen.color_) x = self.text_x - (self.text_w / 2) y = self.text_y - (font.size / 2) # Show text at the same scale as the graphics context ctm = gc.get_ctm() if hasattr(ctm, "__len__") and len(ctm) == 6: scale = sqrt( (ctm[0] + ctm[1]) * (ctm[0] + ctm[1]) / 2.0 + \ (ctm[2] + ctm[3]) * (ctm[2] + ctm[3]) / 2.0 ) elif hasattr(gc, "get_ctm_scale"): scale = gc.get_ctm_scale() else: raise RuntimeError("Unable to get scale from GC.") x *= scale y *= scale gc.show_text_at_point(self.text, x, y) finally: gc.restore_state() @on_trait_change("pen.+,text_x,text_y,text_w,justification,text") def _update(self): if self.pen is None: return x = self.text_x - (self.text_w / 2) x2 = x + self.text_w font = str_to_font(str(self.pen.font)) y = self.text_y - (font.size / 2) y2 = y + font.size self.position = [x, y] # If bounds are set to 0, horizontal/vertical lines will not render. self.bounds = [max(x2 - x, 1), max(y2 - y, 1)] self.request_redraw() def normal_left_down(self, event): print "Text [%s] selected at (%d, %d)" % (self.text, event.x, event.y)
class SingleReal(Simple): floatingType = String("singleReal") value = Float(0.0)
class Simple(Base): floatingType = String("simple") label = String("a_simple") physicalNature = String("length") unit = String("meter") comment = String("a_comment")
class Vector(Simple): floatingType = String("vector") values = Array()
class rationalFraction(Vector): floatingType = String("rationalFraction") values = Array(dtype=numpy.float32)
class Link(Base): subject = String("") object = String("")
class rational(Simple): floatingType = String("rational") data = Array(Any)
class Group(Base): type = String("node") values = Array(dtype=numpy.int32)
class DataSet(Simple): floatingType = String("dataSet") values = Array()
self.runoutput.variable_values[:, var_names.index(self.var_x)]) self.plotdata.set_data( 'y', self.runoutput.variable_values[:, var_names.index(self.var_y)]) except ValueError, e: pass self.replot() #@on_trait_change('runoutput.eigenmatrix') def replot(self): self.plot.title = 'Output' self.plot.request_redraw() var_x = String('Alpha') var_y = String('CLtot') def __init__(self, *l, **kw): # TODO: implement aspect ratio maintaining HasTraits.__init__(self, *l, **kw) #self.plotdata = ArrayPlotData(x=self.pointsx, y=self.pointsy) plot = Plot(self.plotdata) plot.plot(("x", "y")) plot.plot(("x", "y"), type='scatter') plot.tools.append(PanTool(plot, drag_button='left')) plot.tools.append(ZoomTool(plot, tool_mode='box')) plot.tools.append(DragZoom(plot, tool_mode='box', drag_button='right')) plot.tools.append(CustomSaveTool( plot)) #, filename='/home/pankaj/Desktop/file.png'))