def _add_particles(self, iterable):
        data_set = self.data_set
        points = data_set.points
        particle2index = self.particle2index
        item_uids = []
        for particle in iterable:
            with self._add_item(particle, particle2index) as item:
                if self.initialized:
                    # We remove the dummy point
                    self.data_set.points = tvtk.Points()
                    points = data_set.points
                    self.initialized = False
                index = points.insert_next_point(item.coordinates)
                particle2index[item.uid] = index
                self.index2particle[index] = item.uid
                self.point_data.append(item.data)
                item_uids.append(item.uid)

        # adding new points causes the cached array under
        # tvtk.array_handler to be inconsistent with the
        # points FloatArray, therefore we need to remove
        # the reference in the tvtk.array_handler._array_cache
        # for points.to_array() to work properly
        _array_cache = None
        for name in ['array_handler', 'tvtk.array_handler']:
            if name in sys.modules:
                mod = sys.modules[name]
                if hasattr(mod, '_array_cache'):
                    _array_cache = mod._array_cache
                break
        if _array_cache:
            _array_cache._remove_array(tvtk.to_vtk(points.data).__this__)

        return item_uids
Example #2
0
 def _set_origin(self, value):
     # Ugly, but needed.
     w = tvtk.to_vtk(self.widget)
     old = w.GetOrigin()
     w.SetOrigin(list(value))
     self.trait_property_changed('origin', old, value)
     self.update_plane()
Example #3
0
 def _recorder_changed(self, r):
     """When the recorder is set we add an event handler so we can
     record the change to the camera position after the interaction.
     """
     iren = self._interactor
     if r is not None:
         self._script_id = r.get_script_id(self)
         id = iren.add_observer("EndInteractionEvent", messenger.send)
         self._camera_observer_id = id
         i_vtk = tvtk.to_vtk(iren)
         messenger.connect(i_vtk, "EndInteractionEvent", self._record_camera_position)
     else:
         self._script_id = ""
         iren.remove_observer(self._camera_observer_id)
         i_vtk = tvtk.to_vtk(iren)
         messenger.disconnect(i_vtk, "EndInteractionEvent", self._record_camera_position)
Example #4
0
    def OnPaint(self, event):
        """This method is overridden temporarily in order to create
        the light manager.  This is necessary because it makes sense
        to create the light manager only when the widget is realized.
        Only when the widget is realized is the VTK render window
        created and only then are the default lights all setup
        correctly.  This handler is removed on the first Paint event
        and the default paint handler of the
        wxVTKRenderWindowInteractor is used instead."""

        # Call the original handler (this will Show the widget)
        self._vtk_control.OnPaint(event)
        if len(self.renderer.lights) == 0:
            # The renderer is not ready yet, we do not do anything, and
            # we do not remove this callback, so that it will be called
            # later.
            return
        # Now create the light manager.
        self.light_manager = light_manager.LightManager(self)

        renwin = self._renwin
        renwin.update_traits()

        vtk_rw = tvtk.to_vtk(renwin)
        renwin.add_observer('StartEvent', messenger.send)
        messenger.connect(vtk_rw, 'StartEvent', self._start_event_callback)
        renwin.add_observer('EndEvent', messenger.send)
        messenger.connect(vtk_rw, 'EndEvent', self._end_event_callback)

        # Reset the event handler to the default since our job is done.
        wx.EVT_PAINT(self._vtk_control, None) # Remove the default handler.
        wx.EVT_PAINT(self._vtk_control, self._vtk_control.OnPaint)
Example #5
0
    def _data_changed(self, old, new):
        if has_attributes(self.data):
            aa = self._assign_attribute
            self.configure_input_data(aa, new)
            self._update_data()
            aa.update()
            self.outputs = [aa.output]
        else:
            self.outputs = [self.data]
        self.data_changed = True

        self.output_info.datasets = \
                [get_tvtk_dataset_name(self.outputs[0])]

        # Add an observer to the VTK dataset after removing the one
        # for the old dataset.  We use the messenger to avoid an
        # uncollectable reference cycle.  See the
        # tvtk.messenger module documentation for details.
        if old is not None:
            old.remove_observer(self._observer_id)
        self._observer_id = new.add_observer('ModifiedEvent',
                                             messenger.send)
        new_vtk = tvtk.to_vtk(new)
        messenger.connect(new_vtk, 'ModifiedEvent',
                          self._fire_data_changed)

        # Change our name so that our label on the tree is updated.
        self.name = self._get_name()
Example #6
0
 def __init__(self, input):
     self.dataset = dsa.WrapDataObject(
         tvtk.to_vtk(get_new_output(input, update=True))
     )
     self._composite = isinstance(self.dataset, dsa.CompositeDataSet)
     self._scalars = None
     self._vectors = None
    def _data_changed(self, old, new):
        """When the vtk dataset changes, adjust the pipeline
        accordingly so that we sync against the new dataset"""

        if has_attributes(self.data):
            aa = self._assign_attribute
            self.configure_input_data(aa, new)
            self._update_vtk_dataset_content()
            aa.update()
            self.outputs = [aa.output]
        else:
            self.outputs = [self.data]

        # Notify the pipeline to refresh against the new data.
        self.data_changed = True

        self.output_info.datasets = \
            [get_tvtk_dataset_name(self.outputs[0])]

        # Add an observer to the VTK dataset after removing the one
        # for the old dataset.  We use the messenger to avoid an
        # uncollectable reference cycle.  See the
        # tvtk.messenger module documentation for details.
        if old is not None:
            old.remove_observer(self._observer_id)
        self._observer_id = new.add_observer('ModifiedEvent',
                                             messenger.send)
        new_vtk = tvtk.to_vtk(new)
        messenger.connect(new_vtk,
                          'ModifiedEvent',
                          self._fire_data_changed)
    def __len__(self):
        """ The number of contained cells.

        """
        # Need to use the vtk implementation due to issue
        # https://github.com/enthought/mayavi/issues/178
        vtk_object = tvtk.to_vtk(self._cell_array)
        return vtk_object.GetNumberOfCells()
Example #9
0
 def test_to_vtk_returns_vtk_object(self):
     # Given
     x = tvtk.ContourFilter()
     # When
     v = tvtk.to_vtk(x)
     # Then
     self.assertEqual(v.GetClassName(), 'vtkContourFilter')
     self.assertTrue(v is x._vtk_obj)
Example #10
0
    def get_children(self, obj):
        """Returns the child objects of a particular tvtk object in a
        dictionary, the keys are the trait names.  This is used to
        generate the tree in the browser."""

        vtk_obj = tvtk.to_vtk(obj)
        methods = self._get_methods(vtk_obj)

        kids = {}
        def _add_kid(key, x):
            if x is None:
                kids[key] = None
            else:
                if type(x) in (type([]), type(())):
                    x1 = [i for i in x if isinstance(i, TVTKBase)]
                    if x1:
                        kids[key] = x1
                elif isinstance(x, TVTKBase):
                    if hasattr(x, '__iter__'):
                        # Don't add iterable objects that contain non
                        # acceptable nodes
                        if len(list(x)) and isinstance(list(x)[0], TVTKBase):
                            kids[key] = x
                    else:
                        kids[key] = x

        for method in methods:
            attr = camel2enthought(method[0])
            if hasattr(obj, attr):
                _add_kid(attr, getattr(obj, attr))

        # Check for sources and inputs.
        if hasattr(obj, 'number_of_sources'):
            srcs = [obj.get_source(i)
                    for i in range(obj.number_of_sources)]
            _add_kid('source', srcs)
        elif hasattr(obj, 'source'):
            _add_kid('source', obj.source)

        if hasattr(obj, 'get_input_algorithm'):
            inputs = []
            if hasattr(obj, 'number_of_input_ports'):
                inputs = [obj.get_input_algorithm(i, j)
                          for i in range(obj.number_of_input_ports)
                          for j in range(
                                  obj.get_number_of_input_connections(i))]
            _add_kid('input', inputs)
        elif hasattr(obj, 'get_input'):
            inputs = [obj.get_input(i)
                      for i in range(obj.number_of_inputs)]
            _add_kid('input', inputs)
        elif hasattr(obj, 'input'):
            _add_kid('input', obj.input)

        if hasattr(obj, 'producer_port'):
            _add_kid('producer_port', obj.producer_port)

        return kids
Example #11
0
 def _remove_listners(self):
     object = self.object
     kids = self.children_cache
     for key, val in kids.items():
         if isinstance(val, tvtk.Collection):
             vtk_obj = tvtk.to_vtk(val)
             messenger.disconnect(vtk_obj, 'ModifiedEvent',
                                  self._notify_children)
         else:
             object.on_trait_change(self._notify_children, key, remove=True)
Example #12
0
 def test_add_dataset_works_with_vtk_datasets(self):
     # Given
     pd = vtk.vtkPolyData()
     # When
     mlab.pipeline.add_dataset(pd)
     # Then
     e = mlab.get_engine()
     src = e.scenes[0].children[0]
     from mayavi.sources.vtk_data_source import VTKDataSource
     self.assertTrue(isinstance(src, VTKDataSource))
     self.assertEqual(tvtk.to_vtk(src.data), pd)
Example #13
0
 def _number_of_labels_changed(self, value):
     if self.input is None:
         return
     f = self.mask.filter
     inp = self.input.get_output_dataset()
     data_obj = dsa.WrapDataObject(tvtk.to_vtk(inp))
     npts = data_obj.GetNumberOfPoints()
     typ = type(f.on_ratio)
     f.on_ratio = typ(max(npts/value, 1))
     if self.mask.running:
         f.update()
         self.mask.data_changed = True
Example #14
0
 def __init__(self, figure=None, **traits):
     super(RemoteScene, self).__init__(**traits)
     if figure is None:
         figure = gcf()
     self.figure = figure
     self.scene = figure.scene
     self.trw = self.scene.render_window
     self.trwi = self.scene.interactor
     self.rwi = tvtk.to_vtk(self.trwi)
     self.rw = tvtk.to_vtk(self.trw)
     self.ren = tvtk.to_vtk(self.scene.renderer)
     self.id = id(self)
     self._last_image = ''
     self._last_render = 0
     self._time_to_render = 0
     self._time_for_image = 0
     self._render_size = 200*200
     self._pending_render = False
     self._doing_render = False
     self._timer_enabled = True
     self._setup_scene()
Example #15
0
def has_attributes(dataset):
    """Returns `True` when the given TVTK `dataset` has any attribute
    arrays in point and cell data and `False` otherwise.
    """
    if dataset is None:
        return False
    obj = dsa.WrapDataObject(tvtk.to_vtk(get_new_output(dataset)))

    if obj.PointData and len(obj.PointData.keys()) > 0:
        return True
    if obj.CellData and len(obj.CellData.keys()) > 0:
        return True

    return False
def tvtk_show(renderer, width=400, height=300):
    """
    Takes vtkRenderer instance and returns an IPython Image with the rendering.
    """
    renderWindow = tvtk.RenderWindow(off_screen_rendering=True,size=[width,height])
    renderWindow.add_renderer(renderer)
    renderWindow.render()
     
    windowToImageFilter = tvtk.WindowToImageFilter(input=renderWindow)
    windowToImageFilter.update()
     
    writer = tvtk.PNGWriter(write_to_memory=True,input=windowToImageFilter.output)
    writer.write()
    data = str(buffer(tvtk.to_vtk(writer).GetResult()))
    return Image(data)
Example #17
0
    def get_children(self, obj):
        """Returns the child objects of a particular tvtk object in a
        dictionary, the keys are the trait names.  This is used to
        generate the tree in the browser."""

        vtk_obj = tvtk.to_vtk(obj)
        methods = self._get_methods(vtk_obj)

        kids = {}
        def _add_kid(key, x):
            if x is None:
                kids[key] = None
            else:
                if type(x) in (type([]), type(())):
                    x1 = [i for i in x if isinstance(i, TVTKBase)]
                    if x1:
                        kids[key] = x1
                elif isinstance(x, TVTKBase):
                    if hasattr(x, '__iter__'):
                        # Don't add iterable objects that contain non
                        # acceptable nodes
                        if len(list(x)) and isinstance(list(x)[0], TVTKBase):
                            kids[key] = x
                    else:
                        kids[key] = x

        for method in methods:
            attr = camel2enthought(method[0])
            if hasattr(obj, attr):
                _add_kid(attr, getattr(obj, attr))

        if hasattr(obj, 'number_of_input_ports'):
            count = obj.number_of_input_ports
            inputs = []
            for i in range(count):
                for j in range(obj.get_number_of_input_connections(i)):
                    producer = obj.get_input_connection(i, j).producer
                    if isinstance(producer, tvtk.TrivialProducer):
                        producer = obj.get_input_data_object(i, j)
                    inputs.append(producer)
            _add_kid('input', inputs)

        return kids
Example #18
0
    def paintEvent(self, e):
        """ Reimplemented to create the light manager only when needed.  This
        is necessary because it makes sense to create the light manager only
        when the widget is realized.  Only when the widget is realized is the
        VTK render window created and only then are the default lights all
        setup correctly.
        """
        QVTKRenderWindowInteractor.paintEvent(self, e)

        scene = self._scene

        if scene.light_manager is None:
            scene.light_manager = light_manager.LightManager(scene)
            renwin = scene._renwin
            renwin.update_traits()
            vtk_rw = tvtk.to_vtk(renwin)
            renwin.add_observer('StartEvent', messenger.send)
            messenger.connect(vtk_rw, 'StartEvent', self._start_event_callback)
            renwin.add_observer('EndEvent', messenger.send)
            messenger.connect(vtk_rw, 'EndEvent', self._end_event_callback)
Example #19
0
    def get_children(self, obj):
        """Returns the child objects of a particular tvtk object in a
        dictionary, the keys are the trait names.  This is used to
        generate the tree in the browser."""

        vtk_obj = tvtk.to_vtk(obj)
        methods = self._get_methods(vtk_obj)

        kids = {}
        def _add_kid(key, x):
            if x is None:
                kids[key] = None
            else:
                if type(x) in (type([]), type(())):
                    x1 = [i for i in x if isinstance(i, TVTKBase)]
                    if x1:
                        kids[key] = x1
                elif isinstance(x, TVTKBase):
                    if hasattr(x, '__iter__'):
                        # Don't add iterable objects that contain non
                        # acceptable nodes
                        if len(list(x)) and isinstance(list(x)[0], TVTKBase):
                            kids[key] = x
                    else:
                        kids[key] = x

        for method in methods:
            attr = camel2enthought(method[0])
            if hasattr(obj, attr):
                _add_kid(attr, getattr(obj, attr))

        # Check for sources and inputs.
        if hasattr(obj, 'number_of_sources'):
            srcs = [obj.get_source(i) \
                    for i in range(obj.number_of_sources)]
            _add_kid('source', srcs)
        elif hasattr(obj, 'source'):
            _add_kid('source', obj.source)

        if hasattr(obj, 'get_input'):
            inputs = []
            if hasattr(obj, 'number_of_input_ports'):
                if obj.number_of_input_ports:
                    # Sometimes not all the inputs can be retrieved using
                    # 'get_input', as they may be sources (for instance
                    # the ProbeFilter).
                    inputs = list()
                    for i in range(obj.number_of_input_ports):
                        try:
                            inputs.append(obj.get_input(i))
                        except TypeError:
                            pass
                    if not inputs:
                        inputs = [obj.get_input()]
            else:
                inputs = [obj.get_input(i) \
                          for i in range(obj.number_of_inputs)]
            _add_kid('input', inputs)
        elif hasattr(obj, 'input'):
            _add_kid('input', obj.input)

        if hasattr(obj, 'producer_port'):
            _add_kid('producer_port', obj.producer_port)

        return kids
out_dir = sys.argv[1]
fromi = int(sys.argv[2])
toi = int(sys.argv[3])

print "out_dir = ",out_dir," averaging from i = ",fromi," to ",toi

particles_sum = Particles()
particles = Particles()

for i in range(fromi,toi):
    filename = '%s/vtkAveraged%04d.vtu'%(out_dir,i)
    print 'reading from file ',filename

    r = tvtk.XMLUnstructuredGridReader(file_name=filename)
    r.update()
    grid = tvtk.to_vtk(r.output)
    particles.copy_from_vtk_grid(grid)
    
    if i == fromi:
        particles_sum.copy_from_vtk_grid(tvtk.to_vtk(r.output))
    else:
        for p_sum,p in zip(particles_sum,particles):
            delta = p_sum.averaged_orientation - p.averaged_orientation
            total_n = p_sum.number_of_moves + p.number_of_moves
            p_sum.averaged_orientation = p.averaged_orientation + delta*float(p_sum.number_of_moves)/total_n
            #p_sum.variance_orientation = p_sum.variance_orientation + p.variance_orientation + delta**2*p_sum.number_of_moves*p.number_of_moves/total_n
            p_sum.variance_orientation = p.variance_orientation
            p_sum.number_of_moves = total_n

        
w = tvtk.XMLUnstructuredGridWriter(input=particles_sum.get_grid(), file_name='%s/vtkAveragedAverage%04d_%04d.vtu'%(out_dir,fromi,toi))
#

lut = tvtk.LookupTable(hue_range=[0.66667,0.0],range=[0,1]);
lut.build()

lut2 = tvtk.LookupTable(hue_range=[0.66667,0.0],range=[0,0.1]);
lut2.build()

domain_source = tvtk.CubeSource(x_length=L,y_length=L,z_length=0,center=[L/2.0,L/2.0,0])
aDomainSource = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=domain_source.output),property=tvtk.Property(representation='w'))
aScalarBar = tvtk.ScalarBarActor(lookup_table=lut,title="s",position=[0.87,0.1],label_format='%-#2.1g',maximum_width_in_pixels=100)
aScalarBar2 = tvtk.ScalarBarActor(lookup_table=lut2,title="Q Var",position=[0.87,0.1],label_format='%-#2.1g',maximum_width_in_pixels=100)


transform = tvtk.Transform()
tvtk.to_vtk(transform).RotateZ(90)
cylinder_source = tvtk.TransformPolyDataFilter(input=tvtk.CylinderSource(height=reduce*sigma_s*2,radius=reduce*sigma_s/5).output,transform=transform)



#
# Averaged Visualisation
#
if len(averaged_files)>0:
    r = tvtk.XMLUnstructuredGridReader(file_name=averaged_files[0])
    calc1 = tvtk.ArrayCalculator(input=r.output,result_array_name="s",function="mag(averaged_orientation)",replacement_value=0, replace_invalid_values=True)
    calc1.add_vector_variable('averaged_orientation','averaged_orientation')
    calc2 = tvtk.ArrayCalculator(input=calc1.output,result_array_name="n1",function="sqrt(ao_X/(2*s) + 0.5)",replacement_value=0,replace_invalid_values=True)
    calc2.add_scalar_variable('ao_X','averaged_orientation',0)
    calc2.add_scalar_variable('s','s')
    calc3 = tvtk.ArrayCalculator(input=calc2.output,result_array_name="n2",function="ao_Y/(2*s*n1)",replacement_value=1,replace_invalid_values=True)
Example #22
0
 def _find_number_of_points_in_input(self):
     inp = self.inputs[0].get_output_dataset()
     o = dsa.WrapDataObject(tvtk.to_vtk(inp))
     return o.GetNumberOfPoints()
Example #23
0
 def test_suppress_vtk_warnings(self):
     obj = tvtk.to_vtk(tvtk.Object())
     self.assertEqual(obj.GetGlobalWarningDisplay(), 1)
     with suppress_vtk_warnings():
         self.assertEqual(obj.GetGlobalWarningDisplay(), 0)
     self.assertEqual(obj.GetGlobalWarningDisplay(), 1)
Example #24
0
 def __hash__(self):
     return hash(tvtk.to_vtk(self.object))
Example #25
0
 def _add_observer(self, obj, event, cb):
     """ Adds a vtk observer using messenger to avoid generating uncollectable objects. """
     obj.add_observer(event, messenger.send)
     messenger.connect(tvtk.to_vtk(obj), event, cb)