class PerspectiveDemo(HasTraits): src = Array(shape=(4,2), dtype=np.float32) dst = Array(shape=(4,2), dtype=np.float32) View = View( Item("dst", label="变换后坐标"), title = "Perspective Demo控制面板" ) def __init__(self, **traits): super(PerspectiveDemo, self).__init__(**traits) self.img = cv.imread("lena.jpg") w = self.img.size().width h = self.img.size().height self.src = np.array([[0,0],[w,0],[0,h],[w,h]],dtype=np.float32) self.dst = np.array([[0,0],[w,0],[0,h],[w,h]],dtype=np.float32) self.on_trait_change(self.redraw, "src,dst") self.redraw() def redraw(self): src = cv.asvector_Point2f(self.src) dst = cv.asvector_Point2f(self.dst) m = cv.getPerspectiveTransform(src, dst) print(m) img2 = cv.Mat() cv.warpPerspective(self.img, img2, m, self.img.size()) cv.imshow("Perspective Demo", img2)
class AffineDemo(HasTraits): m = Array(np.float, (2, 3)) size = Array(np.int, (1, 2)) view = View(Item("m", label="变换矩阵"), Item("size", label="图像大小"), title="Affine Demo控制面板") def __init__(self, **traits): super(AffineDemo, self).__init__(**traits) self.img = cv.imread("lena.jpg") self.m = np.array([[0.5, -0.3, 100], [0.3, 0.5, 0]]) size = self.img.size() self.on_trait_change(self.redraw, "m,size") self.size = np.array([[size.width, size.height]]) def redraw(self): M = cv.asMat(self.m, force_single_channel=True) size = cv.Size(int(self.size[0, 0]), int(self.size[0, 1])) img2 = cv.Mat() if size.width > 0 and size.height > 0: cv.warpAffine(self.img, img2, M, size, borderValue=cv.CV_RGB(255, 255, 255)) cv.imshow("Affine Demo", img2)
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 FitData(HasTraits): """ """ X = Array( dtype=numpy.float64, shape=(None, None) ) #2D array where each ith row is the data for the ith independent variable in 'func' Y = Array( dtype=numpy.float64, shape=(None, None) ) #2D array where each jth row is the data for the ith dependent variable, the value of'func' W = Array( dtype=numpy.float64, shape=(None, None) ) #2D array where each jth row is the data for the weighting of the ith dependent variable #-------------------------------------------------------------------------- def load_data(self, X, Y, W=None): #load the data for the independent variables X = array(X) d = len(X.shape) if d == 1: #promote 1D to 2D X = X.reshape((1, -1)) elif d > 2: raise ValueError, "'X' dimension must be 1 or 2, detected incommensurate data of dimension %d" % d self.X = X #load the data for the dependent variables Y = array(Y) d = len(Y.shape) if d == 1: #promote 1D to 2D Y = Y.reshape((1, -1)) elif d > 2: raise ValueError, "'Y' dimension must be 1 or 2, detected incommensurate data of dimension %d" % d self.Y = Y #configure the wieghting data if W is None: W = ones_like(self.Y) #use unity weighting by default W = array(W) assert W.shape == Y.shape self.W = W def get_data(self): X = self.X[:] Y = self.Y[:] W = self.W[:] return (X, Y, W) def get_selection(self, low_index, high_index): if low_index > high_index: #swap if order reversed low_index, high_index = high_index, low_index X = self.X[:, low_index:high_index] Y = self.Y[:, low_index:high_index] W = self.W[:, low_index:high_index] return (X, Y, W)
class ArrayEditorTest(HasPrivateTraits): three = Array(Int, (3, 3)) four = Array(Float, (4, 4), editor=ArrayEditor(width=-50)) view = View(Item('three', label='3x3 Integer'), '_', Item('three', label='Integer Read-only', style='readonly'), '_', Item('four', label='4x4 Float'), '_', Item('four', label='Float Read-only', style='readonly'), buttons=NoButtons, resizable=True)
class MorphologyDemo(HasTraits): structing_element = Array(shape=(3, 3), dtype=np.uint8) process_type = Enum("dilate", "erode", "MORPH_OPEN", "MORPH_CLOSE", "MORPH_GRADIENT", "MORPH_TOPHAT", "MORPH_BLACKHAT") iter = Int(1) view = View(Item("structing_element", label=u"结构元素"), Item("process_type", label=u"处理类型"), Item("iter", label=u"迭代次数"), title=u"Morphology Demo控制面板") def __init__(self, *args, **kwargs): super(MorphologyDemo, self).__init__(*args, **kwargs) self.structing_element = np.ones((3, 3), dtype=np.uint8) self.img = cv.imread("lena.jpg") self.on_trait_change(self.redraw, "structing_element,process_type,iter") self.redraw() def redraw(self): img2 = cv.Mat() element = cv.asMat(self.structing_element, force_single_channel=True) if self.process_type.startswith("MORPH_"): type = getattr(cv, self.process_type) cv.morphologyEx(self.img, img2, type, element, iterations=self.iter) else: func = getattr(cv, self.process_type) func(self.img, img2, element, iterations=self.iter) cv.imshow("Morphology Demo", img2)
class Equalizer(HasTraits): freq = Range(10.0, SAMPLING_RATE / 2, 1000) Q = Range(0.1, 10.0, 1.0) gain = Range(-24.0, 24.0, 0) a = List(Float, [1.0, 0.0, 0.0]) b = List(Float, [1.0, 0.0, 0.0]) h = Array(dtype=np.complex, transient=True) def __init__(self): super(Equalizer, self).__init__() self.design_parameter() @on_trait_change("freq,Q,gain") def design_parameter(self): '''设计系数并计算频率响应''' try: self.b, self.a = design_equalizer(self.freq, self.Q, self.gain, SAMPLING_RATE) except: self.b, self.a = [1.0, 0.0, 0.0], [1.0, 0.0, 0.0] self.h = myfreqz(self.b, self.a, W) def export_parameters(self, f): '''输出滤波器系数为C语言数组''' tmp = self.b[0], self.b[1], self.b[2], self.a[1], self.a[ 2], self.freq, self.Q, self.gain f.write("{%s,%s,%s,%s,%s}, // %s,%s,%s\n" % tmp)
class Quiver3D(Points3d): """ Plots glyphs (like arrows) indicating the direction of the vectors at the positions supplied. **Function signatures**:: quiver3d(u, v, w, ...) quiver3d(x, y, z, u, v, w, ...) quiver3d(x, y, z, f, ...) u, v, w are numpy arrays giving the components of the vectors. If only 3 arrays, u, v, and w are passed, they must be 3D arrays, and the positions of the arrows are assumed to be the indices of the corresponding points in the (u, v, w) arrays. If 6 arrays, (x, y, z, u, v, w) are passed, the 3 first arrays give the position of the arrows, and the 3 last the components. They can be of any shape. If 4 positional arguments, (x, y, z, f) are passed, the last one must be a callable, f, that returns vectors components (u, v, w) given the positions (x, y, z).""" scalars = Array(help="""optional scalar data.""") _source_function = Callable(vector_scatter) _pipeline = [ VectorsFactory, ]
class MarkerPrimitive(HasTraits): locs = Array('d') path = Instance(PathPrimitive, ()) # marker path in points affine = Instance(Affine, ()) # transformation for the verts def _locs_default(self): return npy.array([[0, 0], [0, 0]], npy.float_)
class ImageSilhouette(HasTraits): """Class representing a silhouette image of segmented cells.""" label_image = Array() object_slices = List(Tuple(slice, slice), ()) def __init__(self, *args, **kwargs): """ Construct an ImageSilhouette object from a PyTables node containing a binary mask array. """ super(ImageSilhouette, self).__init__(*args, **kwargs) # Label the binary array from the HDF5 file self.label_image, number = ndimage.label(self.node.read()) if DEBUG: print "%d objects segmented." % number # Get slices that index the array self.object_slices = ndimage.find_objects(self.label_image) def __len__(self): return len(self.object_slices) def __getitem__(self, key): if type(key) is slice: indices = islice(xrange(len(self)), *key.indices(len(self))) return [self[nkey] for nkey in indices] else: image = self.label_image[self.object_slices[key]] == (key + 1) return ObjectSilhouette(image=image) def __contains__(self): raise TypeError("Containment checking not supported: %s" % str(self))
class ArraySet(Simple): floatingType = String("arraySet") data = Array() ds = Instance(DS) def _ds_default(self): return DS()
class Bear(HasTraits): name = Str color = RGBColor("gold") weight = Float location = Array() favorite_food = Enum("Honey", "Turkey", "PaloAltian", default="Honey") datadir = Directory("./")
class Test ( HasPrivateTraits ): #--------------------------------------------------------------------------- # Trait definitions: #--------------------------------------------------------------------------- three = Array( int, (3,3) ) four = Array( float, (4,4), editor = ArrayEditor( width = -50 ) ) #--------------------------------------------------------------------------- # Traits view definitions: #--------------------------------------------------------------------------- view = View( 'three', '_', 'three', '_', 'three~', '_', 'four', '_', 'four', '_', 'four~', title = 'ArrayEditor Test Case', resizable = True )
class FloodFillDemo(HasTraits): lo_diff = Array(np.float, (1, 4)) hi_diff = Array(np.float, (1, 4)) plot = Instance(Plot) point = Tuple((0, 0)) option = Trait(u"以邻点为标准-4联通", Options) view = View(VGroup( VGroup(Item("lo_diff", label=u"负方向范围"), Item("hi_diff", label=u"正方向范围"), Item("option", label=u"算法标志")), Item("plot", editor=ComponentEditor(), show_label=False), ), title=u"FloodFill Demo控制面板", width=500, height=450, resizable=True) def __init__(self, *args, **kwargs): self.lo_diff.fill(5) self.hi_diff.fill(5) self.img = cv.imread("lena.jpg") self.data = ArrayPlotData(img=self.img[:, :, ::-1]) w = self.img.size().width h = self.img.size().height self.plot = Plot(self.data, padding=10, aspect_ratio=float(w) / h) self.plot.x_axis.visible = False self.plot.y_axis.visible = False self.imgplot = self.plot.img_plot("img", origin="top left")[0] self.imgplot.interpolation = "nearest" self.imgplot.overlays.append( PointPicker(application=self, component=self.imgplot)) self.on_trait_change(self.redraw, "point,lo_diff,hi_diff,option") def redraw(self): img = self.img.clone() cv.floodFill(img, cv.Point(*self.point), cv.Scalar(255, 0, 0, 255), loDiff=cv.asScalar(self.lo_diff[0]), upDiff=cv.asScalar(self.hi_diff[0]), flags=self.option_) self.data["img"] = img[:, :, ::-1]
class BodyViewer(HasTraits): body = Instance(Body) # x,dia diameters = Property(Array(numpy.float), depends_on='_cp,num_pts') num_pts = Int(20) # numpoints, xyx radius bodydata = Property(Array(dtype=numpy.float, shape=(None, 4)), depends_on='diameters') # inflexion_pt, min, max of the x coordinates data_props = Property(Tuple(Int, Float, Float), depends_on='body.data') @cached_property def _get_data_props(self): x = self.body.data[:, 0] if x[1] > x[0]: return numpy.argmax(x), numpy.min(x), numpy.max(x) else: return numpy.argmin(x), numpy.min(x), numpy.max(x) @cached_property def _get_diameters(self): x = numpy.linspace(numpy.min(self.data_props[2]), numpy.min(self.data_props[1]), self.num_pts) # datax, datay dxu, dyu = self.body.data[:self.data_props[0], 0], self.body.data[:self.data_props[0], 1] dxl, dyl = self.body.data[self.data_props[0] - 1:, 0], self.body.data[self.data_props[0] - 1:, 1] #iu, il = numpy.searchsorted(dxu, x), numpy.searchsorted(dxl, x) #yu = dyu[iu] - (dyu[iu] - dyu[iu - 1]) * (dxu[iu]-x) / (dxu[iu]-dx[iu-1]) #yl = dyl[il] - (dyl[il] - dyl[il - 1]) * (dxl[il]-x) / (dxl[il]-dx[il-1]) yu = numpy.interp(x, dxu, dyu) yl = numpy.interp(x, dxl, dyl) return numpy.array([x, abs(yu - yl)]).T # superior will take care of yduplicate @cached_property def _get_bodydata(self): ret = numpy.empty((self.num_pts, 4)) # y,z coords are 0 ret[:, 1:3] = 0.0 # scale : radii (by sqrt(y*z)) and x # set the radii ret[:, 3] = self.diameters[:, 1] / 2 * (self.body.scale[1] * self.body.scale[2]) ** 0.5 # set the radii centers ret[:, 0] = self.diameters[:, 0] * self.body.scale[0] # translate ret[:, :3] += self.body.translate return ret
class ScatterPlotTraits(HasTraits): plot = Instance(Plot) color = ColorTrait("blue") marker = marker_trait marker_size = Int(4) x = Array() y = Array() traits_view = View(Group(Item('color', label="Color", style="custom"), Item('marker', label="Marker"), Item('marker_size', label="Size"), Item('plot', editor=ComponentEditor(), show_label=False), orientation="vertical"), width=800, height=600, resizable=True, title="Chaco Plot") def __init__(self): super(ScatterPlotTraits, self).__init__() x = linspace(-14, 14, 10) y = sin(x) * x**3 plotdata = ArrayPlotData(x=x, y=y) plot = Plot(plotdata) self.x = x self.y = y self.renderer = plot.plot(("x", "y"), type="scatter", color="blue")[0] self.plot = plot def _color_changed(self): self.renderer.color = self.color def _marker_changed(self): self.renderer.marker = self.marker def _marker_size_changed(self): self.renderer.marker_size = self.marker_size
class OutputSystemViewer(HasTraits): num_outputs = Property(Int(1), depends_on='runoutput.eigenmodes') @cached_property def _get_num_outputs(self): ret = len(self.runoutput.eigenmodes) #print 'num_outputs', ret return ret run_number = Int(1) #Range(low=1, high='num_outputs') runoutput = Instance(RunOutput) modes = Property(List(EigenMode), depends_on='runoutput.eigenmodes,run_number') @cached_property def _get_modes(self): return self.runoutput.eigenmodes[self.run_number - 1] modes_array = Property(Array(numpy.complex), depends_on='modes') @cached_property def _get_modes_array(self): ret = numpy.empty((len(self.modes), 13), dtype='complex') for i, mode in enumerate(self.modes): ret[i, 0] = mode.eigenvalue #.real #ret[i,1] = mode.eigenvalue.imag ret[i, 1:] = mode.eigenvector #print mode.eigenvector return ret matrix = Property(Instance(EigenMatrix), depends_on='runoutput.eigenmatrix,run_number') @cached_property def _get_matrix(self): #print len(self.runoutput.eigenmatrix) return self.runoutput.eigenmatrix[self.run_number - 1] view = View(Item('run_number', editor=RangeEditor(mode='spinner')), Group( Item('modes_array', editor=TabularEditor(adapter=ModesAdapter(), operations=[], editable=False), show_label=False), Item('object.matrix.matrix', editor=TabularEditor(adapter=EigenMatrixAdapter(), operations=[], editable=False), show_label=False)), resizable=True)
class Equalizers(HasTraits): eqs = List(Equalizer, [Equalizer()]) h = Array(dtype=np.complex, transient=True) # Equalizer列表eqs的编辑器定义 table_editor = TableEditor(columns=[ ObjectColumn(name="freq", width=0.4, style="readonly"), ObjectColumn(name="Q", width=0.3, style="readonly"), ObjectColumn(name="gain", width=0.3, style="readonly"), ], deletable=True, sortable=True, auto_size=False, show_toolbar=True, edit_on_first_click=False, orientation='vertical', edit_view=View(Group( Item("freq", editor=EnumEditor(values=EQ_FREQS)), Item("freq", editor=scrubber(1.0)), Item("Q", editor=scrubber(0.01)), Item("gain", editor=scrubber(0.1)), show_border=True, ), resizable=True), row_factory=Equalizer) view = View(Item("eqs", show_label=False, editor=table_editor), width=0.25, height=0.5, resizable=True) @on_trait_change("eqs.h") def recalculate_h(self): '''计算多组均衡器级联时的频率响应''' try: tmp = np.array([ eq.h for eq in self.eqs if eq.h != None and len(eq.h) == len(W) ]) self.h = np.prod(tmp, axis=0) except: pass def export(self, path): '''将均衡器的系数输出为C语言文件''' f = file(path, "w") f.write("double EQ_PARS[][5] = {\n") f.write("//b0,b1,b2,a1,a2 // frequency, Q, gain\n") for eq in self.eqs: eq.export_parameters(f) f.write("};\n") f.close()
class Axis(ArtistContainer): zorder = Float(1.5) tickmarker = Instance(Marker, ()) line = Instance(Line, ()) ticklocs = Array('d') ticksize = Float(7.0) loc = Float(0.) # the y location of the x-axis tickoffset = Float(0) # -1 for outer, -0.5 for centered, 0 for inner sequence = 'axes' def __init__(self): ArtistContainer.__init__(self) self.affine.on_trait_change(self._update_blended_affine, 'vec6') self.tickmarker.antialiased = False self.line.antialiased = False self.add_artist(self.line, followdata=False) self.add_artist(self.tickmarker, followdata=False) # XXX, do we have to manually call these or will they get # calle dautomagically in init self._update_tick_path() self._update_marker_locations() self._update_blended_affine() self._update_linepath() def _ticklocs_changed(self, old, new): self._update_marker_locations() def _loc_changed(self, old, new): self._update_blended_affine() def _ticksize_changed(self, old, new): self._update_tick_path() def _tickoffset_changed(self, old, new): self._update_tick_path() def _update_blended_affine(self): 'blend of xdata and y axis affine' raise NotImplementedError def _update_marker_locations(self): raise NotImplementedError def _update_tick_path(self): raise NotImplementedError def _update_linepath(self): raise NotImplementedError
class Flow(Pipeline): """ Creates a trajectory of particles following the flow of a vector field. **Function signatures**:: flow(u, v, w, ...) flow(x, y, z, u, v, w, ...) flow(x, y, z, f, ...) u, v, w are numpy arrays giving the components of the vectors. If only 3 arrays, u, v, and w are passed, they must be 3D arrays, and the positions of the arrows are assumed to be the indices of the corresponding points in the (u, v, w) arrays. If 6 arrays, (x, y, z, u, v, w) are passed, the 3 first arrays give the position of the arrows, and the 3 last the components. The x, y and z arrays are then supposed to have been generated by `numpy.mgrid`, in other words, they are 3D arrays, with positions lying on a 3D orthogonal and regularly spaced grid with nearest neighbor in space matching nearest neighbor in the array. The function builds a vector field assuming the points are regularly spaced. If 4 positional arguments, (x, y, z, f) are passed, the last one must be a callable, f, that returns vectors components (u, v, w) given the positions (x, y, z).""" scalars = Array(help="""optional scalar data.""") _source_function = Callable(vector_field) _pipeline = [ ExtractVectorNormFactory, StreamlineFactory, ] def __call_internal__(self, *args, **kwargs): """ Override the call to be able to choose whether to apply an ExtractVectorNorm filter. """ self.source = self._source_function(*args, **kwargs) kwargs.pop('name', None) self.store_kwargs(kwargs) # Copy the pipeline so as not to modify it for the next call self.pipeline = self._pipeline[:] if tools._has_scalar_data(self.source): self.pipeline.pop(0) return self.build_pipeline()
class EigenMode(HasTraits): eigenvalue = Complex() # the = theta order = ['u', 'w', 'q', 'the', 'v', 'p', 'r', 'phi', 'x', 'y', 'z', 'psi'] eigenvector = Array(numpy.complex, shape=(12,)) editor = Instance(TableEditor) def _editor_default(self): cols = [ObjectColumn(name='eigenvalue', label='EigenValue')] cols += [ObjectColumn(name='name', label=s) for s in self.order] ret = TableEditor( auto_size=False, editable=False, columns=None)
class RunOutput(HasTraits): '''class to store the output if a sequence of runcases''' # the names of the variables variable_names = List(String) # 2d array variable_values = Array(numpy.float, shape=(None, None)) eigenmodes = List(List(EigenMode)) eigenmatrix = List(EigenMatrix) #output_view = Instance(View) #eigenmode_view = Instance(View) def save_variables(self, file): file.write('"%s"\n' %('"\t"'.join(self.variable_names))) for row in self.variable_values: file.write('%s\n' %('\t'.join([str(var) for var in row])))
class OptimizerBase(HasTraits): cost_map = Function #function taking N parameters and yielding M values args = List #additional arguments to the cost function P = Array(dtype=numpy.float64, shape=( None, )) #1D array, represents a set of N parameters with ordering cost = Array(dtype=numpy.float64, shape=(None, )) #1D array, length M ndf = Int #number of degrees of freedom def __init__(self, cost_map, P0, args=None): super(OptimizerBase, self).__init__() self.cost_map = cost_map if args is None: args = [] self.args = list(args) self.P = P0 @on_trait_change('P') def update_cost(self): self.cost = self.cost_map(self.P, *self.args) self.ndf = len(self.P) def optimize(self, P0=None, args=None): raise NotImplementedError
class MTraitsNamespace: DPI = Float(72.) Alpha = traits.Range(0., 1., 0.) Affine = Trait(Affine()) AntiAliased = traits.true Color = Trait('black', ColorHandler()) DPI = Float(72.) Interval = Array('d', (2, ), npy.array([0.0, 1.0], npy.float_)) LineStyle = Trait('-', '--', '-.', ':', 'steps', None) LineWidth = Float(1.0) Marker = Trait(None, '.', ',', 'o', '^', 'v', '<', '>', 's', '+', 'x', 'd', 'D', '|', '_', 'h', 'H', 'p', '1', '2', '3', '4') MarkerSize = Float(6) Visible = traits.true
class ObjectSilhouette(HasTraits): """Class representing a single cell silhouette in an image.""" image = Array(dtype=bool) is_aligned = Bool() #_medial_repr = Instance("MedialRepresentation") # This could be a Delegate, except that we'd like to trigger creation # on get aligned_version = Property(depends_on='_aligned_version') medial_repr = Property(depends_on='_medial_repr') ######################### Private interface ########################## def _get_aligned_version(self): """ Return an aligned version of this ObjectSilhouette """ # If we _are_ the aligned version if self.is_aligned: return self # In case we have it cached if not getattr(self, '_aligned_version', None): image = self.image try: coeffs = fit_ellipse(*(np.where(image))) except EllipseFitError: traceback.print_exc() return None try: rotated, angle = align_image_to_ellipse(coeffs, image) except EllipseAlignmentError: traceback.print_exc() return None newobj = ObjectSilhouette(image=rotated, is_aligned=True) self._aligned_version = newobj return self._aligned_version def _get_medial_repr(self): """ Return the medial representation object, constructing one if necessary. """ if self.is_aligned: if not getattr(self, "_medial_repr", None): self._medial_repr = MedialRepresentation(self) return self._medial_repr else: raise ValueError("Object %s is not aligned version" % repr(self))
class PlotModel(HasTraits): figure = Instance(Figure, ()) axes = Instance(Axes) line = Instance(Line2D) _draw_pending = Bool(False) scale = Range(0.1, 10.0) x = Array(value=numpy.linspace(-5, 5, 512)) y = Property(Array, depends_on=['scale', 'x']) traits_view = View(Item('figure', editor=CustomEditor(MakePlot), resizable=True), Item('scale'), resizable=True) def _axes_default(self): return self.figure.add_subplot(111) def _line_default(self): return self.axes.plot(self.x, self.y)[0] @cached_property def _get_y(self): return numpy.sin(self.scale * self.x) @on_trait_change("x, y") def update_line(self, obj, name, val): attr = {'x': "set_xdata", 'y': "set_ydata"}[name] getattr(self.line, attr)(val) self.redraw() def redraw(self): if self._draw_pending: return canvas = self.figure.canvas if canvas is None: return def _draw(): canvas.draw() self._draw_pending = False wx.CallLater(50, _draw).Start() self._draw_pending = True
class PlotModel(HasTraits): """A Model for displaying a matplotlib figure""" #we need instances of a Figure, a Axes and a Line2D figure = Instance(Figure, ()) axes = Instance(Axes) line = Instance(Line2D) _draw_pending = Bool(False) #a flag to throttle the redraw rate #a variable paremeter scale = Range(0.1,10.0) #an independent variable x = Array(value=numpy.linspace(-5,5,512)) #a dependent variable y = Property(Array, depends_on=['scale','x']) traits_view = View( Item('figure', editor=CustomEditor(MakePlot), resizable=True),
class Line(Path): XY = Array('d') sequence = 'lines' def _facecolor_default(self): return None def _XY_default(self): return npy.array([[0, 1], [0, 1]], npy.float_) def _XY_changed(self): #print 'LINE: XY changed' codes = LINETO * npy.ones(len(self.XY), npy.uint8) codes[0] = MOVETO #print 'LINE shapes', codes.shape, self.XY.shape self.pathdata = codes, self.XY
class PathPrimitive(HasTraits): """ The path is an object that talks to the backends, and is an intermediary between the high level path artists like Line and Polygon, and the backend renderer """ color = mtraits.Color('black') facecolor = mtraits.Color('blue') alpha = mtraits.Alpha(1.0) linewidth = mtraits.LineWidth(1.0) antialiased = mtraits.AntiAliased pathdata = Tuple(Array('b'), VertexArray) affine = Instance(Affine, ()) def _pathdata_default(self): return (npy.array([0, 0], dtype=npy.uint8), npy.array([[0, 0], [0, 0]], npy.float_))
class VMPlotSpec(HasTraits): pf = Instance(EnzoStaticOutput) field = Str('Density') field_list = Property(depends_on='pf') center = Array(shape=(3, ), dtype='float64') axis = Enum(0, 1, 2) @cached_property def _get_field_list(self): fl = self.pf.h.field_list df = self.pf.h.derived_field_list fl.sort() df.sort() return fl + df def _center_default(self): return self.pf.h.find_max("Density")[1]