def default_traits_view(self): base_view = BasePlotParams.default_traits_view(self) return View( Item('xlim', label="X Limits", editor=TupleEditor(editors=[ TextEditor(auto_set=False, evaluate=float, format_func=lambda x: "" if x == None else str(x)), TextEditor(auto_set=False, evaluate=float, format_func=lambda x: "" if x == None else str(x)) ], labels=["Min", "Max"], cols=1)), Item('ylim', label="Y Limits", editor=TupleEditor(editors=[ TextEditor(auto_set=False, evaluate=float, format_func=lambda x: "" if x == None else str(x)), TextEditor(auto_set=False, evaluate=float, format_func=lambda x: "" if x == None else str(x)) ], labels=["Min", "Max"], cols=1)), base_view.content)
def control_panel(self): return VGroup( Item("lo_diff", label=u"负方向范围", width=-20, editor=TupleEditor(cols=2)), Item("hi_diff", label=u"正方向范围", editor=TupleEditor(cols=2)), Item("fill_color", label=u"填充颜色", editor=TupleEditor(cols=2)), Item("point", label=u"种子坐标", editor=TupleEditor(cols=2, labels=["x", "y"])), Item("option", label=u"算法标志"))
def create_editor(self): """ Returns the default UI editor for the trait. """ editor = None auto_set = False if self.auto_set is None: auto_set = True enter_set = self.enter_set or False if self.shape is not None and len(self.shape) == 2: from traitsui.api import ArrayEditor editor = ArrayEditor(auto_set=auto_set, enter_set=enter_set) else: from traitsui.api import TupleEditor if self.dtype is None: types = Any else: types = dtype2trait(self.dtype) editor = TupleEditor( types=types, labels=self.labels or [], cols=self.cols or 1, auto_set=auto_set, enter_set=enter_set, ) return editor
class DummyModel(HasStrictTraits): """ Dummy model with a Tuple trait. """ data = Tuple(Float, Float, Str) traits_view = View(Item(name="data", editor=TupleEditor()))
def default_traits_view(self): base_view = Stats1DPlotParams.default_traits_view(self) return View(Item('variable_lim', label = "Variable\nLimits", editor = TupleEditor(editors = [TextEditor(auto_set = False, evaluate = float, format_func = lambda x: "" if x == None else str(x)), TextEditor(auto_set = False, evaluate = float, format_func = lambda x: "" if x == None else str(x))], labels = ["Min", "Max"], cols = 1)), Item('linestyle'), Item('marker'), Item('markersize', editor = TextEditor(auto_set = False), format_func = lambda x: "" if x == None else str(x)), Item('capsize', editor = TextEditor(auto_set = False), format_func = lambda x: "" if x == None else str(x)), Item('alpha'), Item('shade_error'), Item('shade_alpha'), base_view.content)
class Stats1DParamsHandler(Controller): view_params_view = \ View(Item('variable_lim', label = "Variable\nLimits", editor = TupleEditor(editors = [TextEditor(auto_set = False, evaluate = float, format_func = lambda x: "" if x == None else str(x)), TextEditor(auto_set = False, evaluate = float, format_func = lambda x: "" if x == None else str(x))], labels = ["Min", "Max"], cols = 1)), Item('linestyle'), Item('marker'), Item('markersize', editor = TextEditor(auto_set = False), format_func = lambda x: "" if x == None else str(x)), Item('capsize', editor = TextEditor(auto_set = False), format_func = lambda x: "" if x == None else str(x)), Item('alpha'), Item('shade_error'), Item('shade_alpha'), Stats1DPlotParamsView.content)
class Animator(HasTraits): start = Button('Start Animation') stop = Button('Stop Animation') next_frame = Button('+') prev_frame = Button('-') delay = Range(10, 100000, 500) loop = Bool(True) current_frame = Int(-1) _last_frame = Int() # TODO use Range(high="trait name") render_from_frame = Int() render_to_frame = Int() render_animation = Button() is_rendering = Bool(False) # indicator bool is True when rendering is_rendering_animation = Bool(False) render_directory = Directory("/tmp", exists=False) render_name_pattern = String("frame_%05d.png") magnification = Range(1, 128) fix_image_size = Bool(False) image_size = Tuple(Int(1280), Int(720)) render = Event() enable_cameraman = Bool(False) set_keyframe = Button() remove_keyframe = Button() timer = Instance(Timer) traits_view = View( Tabbed( Group( HGroup( Item('start', show_label=False), Item('stop', show_label=False), Item('next_frame', show_label=False, enabled_when='current_frame < _last_frame'), Item('prev_frame', show_label=False, enabled_when='current_frame > 0'), ), HGroup( Item(name = 'loop'), Item(name = 'delay'), ), Item(name = 'current_frame', editor=RangeEditor(is_float=False, high_name='_last_frame', mode='slider')), Group( HGroup( Item(name = 'enable_cameraman', label='enabled'), Item(name = 'set_keyframe', show_label=False), Item(name = 'remove_keyframe', show_label=False), Item(name = 'interpolation_type', object='object._camera_interpolator'), ), label = 'Cameraman', ), label = 'Timeline', ), Group( HGroup( Item('fix_image_size', label="Set Image Size"), Item('magnification', visible_when='not fix_image_size', label='Magnification'), Item('image_size', visible_when='fix_image_size', show_label=False, editor=TupleEditor(cols=2, labels=['W', 'H'])), ), Item("_"), Item("render_directory", label="Target Dir"), Item("render_name_pattern", label="Filename Pattern"), Item("_"), HGroup( Item("render_from_frame", label="from", editor=RangeEditor(is_float=False, low=0, high_name='render_to_frame')), Item("render_to_frame", label="to", editor=RangeEditor(is_float=False, low_name='render_from_frame', high_name='_last_frame')), ), Item("render_animation", show_label=False), label = "Render", ), ), title = 'Animation Controller', buttons = []) def __init__(self, num_frames, callable, millisec=40, figure=None, play=True, *args, **kwargs): HasTraits.__init__(self) self.delay = millisec self._last_frame = num_frames - 1 self._callable = callable if figure is None: figure = mlab.gcf() self._figure = figure self._camera_interpolator = tvtk.CameraInterpolator(interpolation_type='spline') self._t_keyframes = {} self.render_to_frame = self._last_frame self.timer = Timer(millisec, self._on_timer, *args, **kwargs) if not play: self.stop = True self._internal_generator = None self.current_frame = 0 self.on_trait_change(self._render, "render, current_frame", dispatch="ui") def _render(self): self.is_rendering = True if self._internal_generator is not None: try: next(self._internal_generator) except StopIteration: # is ok since generator should yield just once to render pass except: # catch and re-raise other errors raise else: raise "The render function should be either a simple function or a generator that yields just once to render" # before we call the user function, we want to disallow rendering # this speeds up animations that use mlab functions scene = self._figure.scene scene.disable_render = True r = self._callable(self.current_frame) if isinstance(r, types.GeneratorType): next(r) # save away generator to yield when another frame has to be displayed self._internal_generator = r # render scene without dumb hourglass cursor, # can be prevented by setting _interacting before calling render old_interacting = scene._interacting if self._camera_interpolator.number_of_cameras >= 2 and self.enable_cameraman: t = self.current_frame / float(self._last_frame) self._camera_interpolator.interpolate_camera(t, mlab.get_engine().current_scene.scene.camera) mlab.gcf().scene.renderer.reset_camera_clipping_range() scene._interacting = True scene.disable_render = False scene.render() scene._interacting = old_interacting self.is_rendering = False @on_trait_change('set_keyframe') def _set_keyframe(self): t = self.current_frame / float(self._last_frame) self._camera_interpolator.add_camera(t, mlab.get_engine().current_scene.scene.camera) self._t_keyframes[self.current_frame] = t def _next_frame_fired(self): self.current_frame += 1 def _prev_frame_fired(self): self.current_frame -= 1 @on_trait_change('remove_keyframe') def _remove_keyframe(self): if self.current_frame in self._t_keyframes: self._camera_interpolator.remove_last_keyframe(self._t_keyframes[self.current_frame]) def _on_timer(self, *args, **kwargs): if self.loop or self.current_frame != self._last_frame: self.current_frame = (self.current_frame + 1) % (self._last_frame + 1) else: self.stop = True def _delay_changed(self, value): t = self.timer if t is None: return if t.IsRunning(): t.Stop() t.Start(value) def _start_fired(self): if not self.loop and self.current_frame == self._last_frame: self.current_frame = 0 self.timer.Start(self.delay) def _stop_fired(self): self.timer.Stop() def _render_animation_fired(self): self.stop = True n_frames_render = self.render_to_frame - self.render_from_frame # prepare the render window renwin = self._figure.scene.render_window aa_frames = renwin.aa_frames renwin.aa_frames = 8 renwin.alpha_bit_planes = 1 # turn on off screen rendering #renwin.off_screen_rendering = True # set size of window if self.fix_image_size: orig_size = renwin.size renwin.size = self.image_size # render the frames progress = ProgressDialog(title="Rendering", max=n_frames_render, show_time=True, can_cancel=True) progress.open() self.is_rendering_animation = True for frame in range(self.render_from_frame, self.render_to_frame + 1): # move animation to desired frame, this will also render the scene self.current_frame = frame # prepare window to image writer render = tvtk.WindowToImageFilter(input=renwin, magnification=1)#, input_buffer_type='rgba') if not self.fix_image_size: render.magnification = self.magnification exporter = tvtk.PNGWriter(file_name=path.join(self.render_directory, self.render_name_pattern % frame)) configure_input(exporter,render) exporter.write() do_continue, skip = progress.update(frame - self.render_from_frame) if not do_continue: break # reset the render window to old values renwin.aa_frames = aa_frames if self.fix_image_size: renwin.size = orig_size #renwin.off_screen_rendering = False self.is_rendering_animation = False progress.close()
def get_editor(self, trait): from traitsui.api import TupleEditor return TupleEditor(types=self.types, labels=trait.labels or [], cols=trait.cols or 1)
class TroughParabloid(BaseMirror): """ An trough mirror object """ name = "trough" abstract = False length = Float(100.0, desc="length of trough") X_bounds = Tuple((-25.5, 25.5), desc="width of parabolic profile") EFL = Float(50.8, desc="effective focal length") EFL_centre = Bool(True, desc="make focus the centre") max_length = Float(1000.0) body = Instance(tvtk.ProgrammableSource, ()) extrude = Instance(tvtk.LinearExtrusionFilter, ()) traits_view = View( VGroup( Traceable.uigroup, Item('length', editor=NumEditor), Item('width', editor=NumEditor), Item('EFL', editor=NumEditor), Item('X_bounds', editor=TupleEditor(cols=2, auto_set=False, editors=[NumEditor, NumEditor], labels=['min', 'max'])), Item('max_length', editor=NumEditor), ), ) @on_trait_change("X_bounds, EFL") def change_params(self): self.body.modified() self.update = True def _length_changed(self, l): self.extrude.scale_factor = l self.update = True def calc_profile(self): output = self.body.poly_data_output xmin, xmax = min(self.X_bounds), max(self.X_bounds) a = 1 / (4 * self.EFL) #create the 2d profile of parabolic trough size = 20 x = numpy.linspace(xmin, xmax, size) z = a * (x**2) - self.EFL #this is a 2d profile but Y-coord sets the starting plane from #which the extrusion extends from y = numpy.ones_like(x) * (self.length / 2.) points = numpy.array([x, y, z]).T cells = [[i, i + 1] for i in range(size - 1)] output.points = points output.lines = cells return output def _vtkproperty_default(self): return tvtk.Property(opacity=0.7, color=(0.8, 0.8, 0)) def _faces_default(self): return [TroughMirrorFace(owner=self)] # This is not necessary unless you want to export STEP files # def make_step_shape(self): # from raytrace.step_export import make_OAP # return make_OAP(self.EFL, self.diameter, self.height, # self.centre, self.direction, self.x_axis), "yellow" def _pipeline_default(self): self.body.set_execute_method(self.calc_profile) extrude = self.extrude extrude.input = self.body.output extrude.extrusion_type = "vector" extrude.vector = (0, 1, 0) extrude.scale_factor = self.length # cut parabolics.py here and inserted from prisms.py t = self.transform transF = tvtk.TransformFilter(input=extrude.output, transform=t) return transF def trace_segment(self, seg, last_optic=None, last_cell=None): """ Don't care about last_optic or last_cell. We filter out intersections too close to the segment origin """ p1 = seg.origin p2 = p1 + seg.MAX_RAY_LENGTH * seg.direction i = self.intersect_with_line(p1, p2) if i is None: return None i = numpy.array(i) dist = numpy.sqrt(((i - p1)**2).sum()) return dist, i, 0, self
editor = TextEditor(auto_set = False, placeholder = "None")), Item('max_quantile', editor = TextEditor(auto_set = False, placeholder = "None")), BasePlotParamsView.content) Data1DPlotParamsView = View(Item('orientation'), Item('lim', label = "Data\nLimits", editor = TupleEditor(editors = [TextEditor(auto_set = False, evaluate = float, placeholder = "None", format_func = lambda x: "" if x is None else str(x)), TextEditor(auto_set = False, evaluate = float, placeholder = "None", format_func = lambda x: "" if x is None else str(x))], labels = ["Min", "Max"], cols = 1)), DataPlotParamsView.content) Data2DPlotParamsView = View(Item('xlim', label = "X Limits", editor = TupleEditor(editors = [TextEditor(auto_set = False, evaluate = float, placeholder = "None", format_func = lambda x: "" if x is None else str(x)), TextEditor(auto_set = False, evaluate = float,
from itertools import chain, islice, count import yaml from raytrace.constraints import BaseConstraint from raytrace.has_queue import HasQueue, on_trait_change from raytrace.utils import normaliseVector, transformNormals, transformPoints,\ transformVectors, dotprod from raytrace import ctracer, cmaterials Vector = Array(shape=(3,)) NumEditor = TextEditor(auto_set=False, enter_set=True, evaluate=float) ComplexEditor = TextEditor(auto_set=False, enter_set=True, evaluate=float) ROField = TextEditor(auto_set=False, enter_set=True, evaluate=float) VectorEditor = TupleEditor(labels=['x','y','z'], auto_set=False, enter_set=True) counter = count() class Float(BaseFloat): def validate(self, obj, name, value): return float(value) class RaytraceObjectMetaclass(MetaHasTraits): """ The metaclass for YAMLObject. """ def __init__(cls, name, bases, kwds): super(RaytraceObjectMetaclass, cls).__init__(name, bases, kwds)