Example #1
0
def _finalize_source(fld, arr, grid, dat_target):
    if isinstance(fld, field.ScalarField):
        dat_target.scalars = arr
        dat_target.scalars.name = fld.name
    elif isinstance(fld, field.VectorField):
        dat_target.vectors = arr
        dat_target.vectors.name = fld.name
    src = VTKDataSource(data=grid)
    src.name = fld.name
    return src
Example #2
0
 def vtkdatasource(self):
     self.vtkdatasource_mesh = VTKDataSource(data=self.unstrgrid_mesh,
                                             name='Geometry')
     self.vtkdatasource_displacement = VTKDataSource(
         data=self.unstrgrid_displacement, name='DisplacementData')
     self.vtkdatasource_stress = VTKDataSource(data=self.unstrgrid_stress,
                                               name='StessData')
     self.vtkdatasource_strain = VTKDataSource(data=self.unstrgrid_strain,
                                               name='StrainData')
     self.vtkdatasource_density = VTKDataSource(data=self.unstrgrid_density,
                                                name='DensiytData')
    def do(self):
        ############################################################
        # Imports.
        script = self.script
        from mayavi.sources.vtk_data_source import VTKDataSource
        from mayavi.modules.api import ImagePlaneWidget

        # Create dataset with multiple scalars.
        arr1 = zeros(27, 'f')
        for n in range(27):
            arr1[n] = (1 + float(n)) / 10.0
        arr2 = (arr1 + 1).astype('d')
        arr3 = arr1 + 2.0 * (0.5 - random.random(27))
        arr3 = arr3.astype('f')

        p = tvtk.ImageData(dimensions=[3, 3, 3], spacing=[1, 1, 1])

        p.point_data.scalars = arr1
        p.point_data.scalars.name = 'first'
        j2 = p.point_data.add_array(arr2)
        p.point_data.get_array(j2).name = 'second'
        j3 = p.point_data.add_array(arr3)
        p.point_data.get_array(j3).name = 'third'

        # Make the pipeline.
        self.new_scene()
        src = VTKDataSource(data=p)
        script.add_source(src)
        ipw = ImagePlaneWidget()
        script.add_module(ipw)

        # Test.
        ipw = ipw.ipw
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr1), max(arr1)
        assert r == expect
        o = src.outputs[0]
        o.update_traits()

        src.point_scalars_name = 'second'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr2), max(arr2)
        assert r == expect
        o.update_traits()

        src.point_scalars_name = 'third'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr3), max(arr3)
        assert r == expect
        o.update_traits()
Example #4
0
def add_dataset(dataset, name='', **kwargs):
    """Add a dataset object to the Mayavi pipeline.

    **Parameters**

    :dataset: a tvtk dataset, or a Mayavi source.
              The dataset added to the Mayavi pipeline
    :figure: a figure identifier number or string, None or False, optionnal.

            If no `figure` keyword argument is given, the data
            is added to the current figure (a new figure if created if
            necessary).

            If a `figure` keyword argument is given, it should either the name
            the number of the figure the dataset should be added to, or None,
            in which case the data is not added to the pipeline.

            If figure is False, a null engine is created. This null
            engine does not create figures, and is mainly usefull for
            tensting, or using the VTK algorithms without visualization.

    **Returns**

    The corresponding Mayavi source is returned.
    """
    if isinstance(dataset, tvtk.Object):
        d = VTKDataSource()
        d.data = dataset
    elif isinstance(dataset, Source):
        d = dataset
    else:
        raise TypeError(
              "first argument should be either a TVTK object"\
              " or a mayavi source")

    if len(name) > 0:
        d.name = name
    if not 'figure' in kwargs:
        # No figure has been specified, retrieve the default one.
        gcf()
        engine = get_engine()
    elif kwargs['figure'] is False:
        # Get a null engine that we can use.
        engine = get_null_engine()
    elif kwargs['figure'] is not None:
        figure = kwargs['figure']
        engine = engine_manager.find_figure_engine(figure)
        engine.current_scene = figure
    else:
        # Return early, as we don't want to add the source to an engine.
        return d
    engine.add_source(d)
    return d
    def setUp(self):
        """Initial setting up of test fixture, automatically called by
        TestCase before any other test method is invoked"""
        e = NullEngine()
        # Uncomment to see visualization for debugging etc.
        #e = Engine()
        e.start()
        s = e.new_scene()
        self.e = e
        self.s = s

        ############################################################
        # Create a new scene and set up the visualization.

        #Make the grid
        grid = self.make_grid4scatter()
        e.add_source(grid)

        eg = ExtractGrid()
        e.add_filter(eg)

        nb_ticks = 6

        eg.x_ratio = eg.y_ratio = eg.z_ratio = 100 / (nb_ticks - 1) / 2

        gpx = GridPlane()
        e.add_module(gpx)
        gpx.grid_plane.axis = 'x'

        gpy = GridPlane()
        e.add_module(gpy)
        gpy.grid_plane.axis = 'y'

        gpz = GridPlane()
        e.add_module(gpz)
        gpz.grid_plane.axis = 'z'

        #Add the scatter
        d = VTKDataSource()
        d.data = self.make_scatter()
        e.add_source(d)
        if is_old_pipeline():
            a = Axes()
            e.add_module(a)
            a.axes.number_of_labels = nb_ticks

        self.eg = eg
        self.gpx = gpx
        self.gpy = gpy
        self.gpz = gpz
        self.scene = e.current_scene
        return
    def setUp(self):
        """Initial setting up of test fixture, automatically called by
        TestCase before any other test method is invoked"""
        e = NullEngine()
        # Uncomment to see visualization for debugging etc.
        #e = Engine()
        e.start()
        s=e.new_scene()
        self.e=e
        self.s=s

        ############################################################
        # Create a new scene and set up the visualization.

        #Make the grid
        grid = self.make_grid4scatter()
        e.add_source(grid)

        eg = ExtractGrid()
        e.add_filter(eg)

        nb_ticks = 6

        eg.x_ratio = eg.y_ratio = eg.z_ratio = 100/(nb_ticks-1)/2

        gpx = GridPlane()
        e.add_module(gpx)
        gpx.grid_plane.axis = 'x'

        gpy = GridPlane()
        e.add_module(gpy)
        gpy.grid_plane.axis = 'y'

        gpz = GridPlane()
        e.add_module(gpz)
        gpz.grid_plane.axis = 'z'

        #Add the scatter
        d = VTKDataSource()
        d.data = self.make_scatter()
        e.add_source(d)
        if is_old_pipeline():
            a = Axes()
            e.add_module(a)
            a.axes.number_of_labels = nb_ticks

        self.eg = eg
        self.gpx = gpx
        self.gpy = gpy
        self.gpz = gpz
        self.scene = e.current_scene
        return
Example #7
0
 def make_grid4scatter(self):
     src = VTKDataSource()
     xmin, xmax, dx = 100, 200, 2
     nx = int((xmax-xmin)/dx)+1
     ymin, ymax, dy = 100, 200, 2
     ny = int((ymax-ymin)/dy)+1
     zmin, zmax, dz = 100, 200, 2
     nz  = int((zmax-zmin)/dz)+1
     image_data = tvtk.ImageData(origin=(xmin, ymin, zmin),
                                 spacing=(dx, dy, dz),
                                 extent=(0, nx-1, 0, ny-1, 0, nz-1))
     src.data = image_data
     return src
 def make_grid4scatter(self):
     src = VTKDataSource()
     xmin, xmax, dx = 100, 200, 2
     nx = int((xmax-xmin)/dx)+1
     ymin, ymax, dy = 100, 200, 2
     ny = int((ymax-ymin)/dy)+1
     zmin, zmax, dz = 100, 200, 2
     nz  = int((zmax-zmin)/dz)+1
     image_data = tvtk.ImageData(origin=(xmin, ymin, zmin),
                                 spacing=(dx, dy, dz),
                                 extent=(0, nx-1, 0, ny-1, 0, nz-1))
     image_data.whole_extent = image_data.extent
     src.data = image_data
     return src
Example #9
0
    def test_add_attribute_works_for_cell_data(self):
        # Given
        sgrid = self.sgrid
        s1 = numpy.ones(4)
        sgrid.cell_data.scalars = s1
        sgrid.cell_data.scalars.name = 's1'
        src = VTKDataSource(data=sgrid)
        self.assertEqual(src.cell_scalars_name, 's1')
        self.assertEqual(sorted(src._cell_scalars_list), ['', 's1'])

        # When
        s2 = s1 + 1.0
        src.add_attribute(s2, 's2', category='cell')
        v1 = numpy.ones((4, 3))
        src.add_attribute(v1, 'v1', category='cell')
        t1 = numpy.ones((4, 9))
        src.add_attribute(t1, 't1', category='cell')

        # Then
        self.assertEqual(src._cell_scalars_list, ['', 's1', 's2'])
        self.assertTrue(
            numpy.allclose(src.data.cell_data.get_array('s2').to_array(), s2)
        )
        self.assertEqual(src._cell_vectors_list, ['', 'v1'])
        self.assertTrue(
            numpy.allclose(src.data.cell_data.get_array('v1').to_array(), v1)
        )
        self.assertEqual(src._cell_tensors_list, ['', 't1'])
        self.assertTrue(
            numpy.allclose(src.data.cell_data.get_array('t1').to_array(), t1)
        )
Example #10
0
    def setUp(self):
        # Create dataset with multiple scalars.
        arr1 = zeros(27, 'f')
        for n in range(27):
            arr1[n] = (1+float(n))/10.0
        arr2 = (arr1 + 1).astype('d')
        arr3 = arr1 + 2.0*(0.5 - random.random(27))
        arr3 = arr3.astype('f')

        p = tvtk.ImageData(dimensions=[3,3,3],spacing=[1,1,1],
                scalar_type='int')
        p.point_data.scalars = arr1
        p.point_data.scalars.name = 'first'
        j2 = p.point_data.add_array(arr2)
        p.point_data.get_array(j2).name='second'
        j3 = p.point_data.add_array(arr3)
        p.point_data.get_array(j3).name='third'
        p.update()
        self.img = p
        self.first = arr1
        self.second = arr2
        self.third = arr3

        # Setup the mayavi pipeline.
        e = NullEngine()
        e.start()
        e.new_scene()
        self.e = e

        src = VTKDataSource(data=p)
        e.add_source(src)
        self.src = src
        ipw = ImagePlaneWidget()
        e.add_module(ipw)
        self.ipw = ipw
Example #11
0
    def test_with_structured_data(self):
        e = self.e

        sgrid = datasets.generateStructuredGrid()
        src = VTKDataSource(data=sgrid)
        e.add_source(src)

        self.check()
Example #12
0
    def test_rename_attribute(self):
        # Given
        sgrid = self.sgrid
        s1 = numpy.ones(4)
        sgrid.point_data.scalars = s1
        sgrid.point_data.scalars.name = 's1'
        src = VTKDataSource(data=sgrid)
        self.assertEqual(src.point_scalars_name, 's1')
        self.assertEqual(sorted(src._point_scalars_list), ['', 's1'])

        # When
        src.rename_attribute('s1', 's2')

        # Then
        self.assertEqual(sorted(src._point_scalars_list), ['', 's2'])
        self.assertTrue(numpy.all(src.data.point_data.get_array('s2') == s1))
        self.assertEqual(src.data.point_data.get_array('s1'), None)
Example #13
0
def view():
    from mayavi import mlab

    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.outline import Outline
    from mayavi.modules.surface import Surface
    from mayavi.modules.vectors import Vectors
    from mayavi.modules.api import IsoSurface

    scene = mayavi.new_scene()
    #scene.background = "black"

    # The single type one
    src = VTKDataSource(data=ug)
    mayavi.add_source(src)
    mayavi.add_module(Outline())
    #mayavi.add_module(Surface())
    #mayavi.add_module(Vectors())

    #translucent isosurfaces
    iso = IsoSurface()
    mayavi.add_module(iso)
    iso.module_manager.scalar_lut_manager.lut_mode = "plasma"

    iso.contour.contours = np.linspace(0.0, 0.03, 30).tolist()
    iso.actor.property.opacity = 0.3

    #iso = mayavi.mlab.pipeline.iso_surface(ug, contours=[1e-15,1e-14,1e-12], opacity=0.3)
    #from mayavi import mlab
    #mlab.contour3d(ug, opacity=0.3)

    #corned
    outline = engine.scenes[0].children[0].children[0].children[0]
    outline.outline_filter.reference_count = 2
    outline.outline_filter.progress = 1.0
    outline.actor.mapper.scalar_range = np.array([0., 1.])
    outline.actor.mapper.progress = 1.0
    outline.outline_mode = 'cornered'

    #show the xyz arrow axis
    scene.scene.show_axes = True

    scene.scene.background = (0.0, 0.0, 0.0)
    scene.scene.isometric_view()
    #v = mlab.view()
    (azimuth, elevation, distance, focalpoint) = mlab.view()
    elevation += 20.0  #move cam a little lower
    distance *= 0.6

    for i, ang in enumerate(np.linspace(0.0, 360, 100)):
        si = str(i).rjust(4, '0')
        scene.scene.save('out/snapshot{}.png'.format(si))

        mlab.view(azimuth=azimuth + ang,
                  elevation=elevation,
                  distance=distance,
                  focalpoint=focalpoint)
        scene.scene.render()
Example #14
0
def drawCubeMesh():
    
    from mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.modules.outline import Outline
    from enthought.mayavi.modules.grid_plane import GridPlane
    from mayavi.modules.surface import Surface

    center = [0., 0., 0.]
#    mlab.points3d(center[0], center[1], center[2])
    
    corners = np.matrix(np.zeros((8, 3)))
    print corners
    print corners[0:4, 2] 
    radius = 1.
    corners[0:4, 2] = center[2] - radius
    corners[4:, 2] = center[2] + radius
    corners[::2, 0] = center[0] - radius
    corners[1::2, 0] = center[0] + radius
    corners[np.ix_([2,3,6,7],[1])] = center[1] - radius
    corners[np.ix_([0,1,4,5],[1])] = center[1] + radius
    print corners

#    mlab.points3d(corners[:, 0], corners[:, 1], corners[:, 2])
#    mlab.show()
    squares = np.array([[0,1,2,3], [4,5,7,6], [0,1,5,4], [2,3,7,6], [1,3,7,5], [0,2,6,4]])
    mesh = tvtk.PolyData(points = np.array(corners, 'f'), polys = squares)
    ##mesh.point_data.scalar_mul()        
    #mesh.point_data.scalars = self.rgb
    #mesh.point_data.scalars.name = 'rgb'
    ##mesh.point_data.scalars = self.intensity
    ##mesh.point_data.scalars.name = 'Intensity'
    #                
    #verts = np.arange(0, corners.shape[0], 1)
    #verts.shape = (corners.shape[0], 1)
    #mesh.verts = verts
    
    
    #
    mayavi.new_scene() 
    d = VTKDataSource()
    d.data = mesh
    mayavi.add_source(d)    
    s = Surface()
    mayavi.add_module(s)
    s.actor.property.set(representation = 'p', point_size = 2)
Example #15
0
def view():
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.surface import Surface

    mayavi.new_scene()
    src = VTKDataSource(data=mesh)
    mayavi.add_source(src)
    s = Surface()
    mayavi.add_module(s)
Example #16
0
def view():
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.outline import Outline
    from mayavi.modules.image_plane_widget import ImagePlaneWidget

    mayavi.new_scene()
    src = VTKDataSource(data=spoints)
    mayavi.add_source(src)
    mayavi.add_module(Outline())
    mayavi.add_module(ImagePlaneWidget())
Example #17
0
def add_dataset(dataset, name='', **kwargs):
    """Add a dataset object to the Mayavi pipeline.

    **Parameters**

    :dataset: a tvtk/vtk dataset/tvtk/VTK Algorithm, or a Mayavi source. The
              dataset added to the Mayavi pipeline

    :figure: a figure identifier number or string, None or False, optional.

            If no `figure` keyword argument is given, the data
            is added to the current figure (a new figure if created if
            necessary).

            If a `figure` keyword argument is given, it should either the name
            the number of the figure the dataset should be added to, or None,
            in which case the data is not added to the pipeline.

            If figure is False, a null engine is created. This null
            engine does not create figures, and is mainly usefull for
            tensting, or using the VTK algorithms without visualization.

    **Returns**

    The corresponding Mayavi source is returned.

    """
    if isinstance(dataset, (tvtk.DataSet, vtk.vtkDataSet)):
        d = VTKDataSource()
        d.data = tvtk.to_tvtk(dataset)
    elif isinstance(dataset, (tvtk.DataObject, vtk.vtkDataObject)):
        d = VTKObjectSource()
        tp = tvtk.TrivialProducer()
        tp.set_output(tvtk.to_tvtk(dataset))
        d.object = tp
    elif isinstance(dataset, (tvtk.Object, vtk.vtkObject)):
        d = VTKObjectSource()
        d.object = tvtk.to_tvtk(dataset)
    elif isinstance(dataset, Source):
        d = dataset
    else:
        raise TypeError(
              "first argument should be either a TVTK object"
              " or a mayavi source")

    if len(name) > 0:
        d.name = name
    engine = _get_engine_from_kwarg(kwargs)
    if engine is None:
        # Return early, as we don't want to add the source to an engine.
        return d
    engine.add_source(d)
    return d
Example #18
0
def view():
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.outline import Outline
    from mayavi.modules.surface import Surface
    from mayavi.modules.vectors import Vectors

    mayavi.new_scene()
    # The single type one
    src = VTKDataSource(data = ug1)
    mayavi.add_source(src)
    mayavi.add_module(Outline())
    mayavi.add_module(Surface())
    mayavi.add_module(Vectors())

    # Mixed types.
    src = VTKDataSource(data = ug2)
    mayavi.add_source(src)
    mayavi.add_module(Outline())
    mayavi.add_module(Surface())
    mayavi.add_module(Vectors())
Example #19
0
    def xregister_mv_pipelines(self, e):
        '''Register as a source in the pipelane
        '''
        # Remarks[rch]:
        #
        # Pipeline construction
        # ---------------------
        # Maybe this should be done only on demand
        # when the visualization is requested either by the update
        # event triggered here, or by the user. For a batch-like
        # simulation no scenes would be necessary.
        #
        # In that case, the engine could be simply registered and
        # the pipeline construction can be deffered to the explicit
        # request.
        #
        # Further question concerns the multiplicity of the relations.
        # One tracer can construct several sources. The source can be
        # for example the standard array source or parametric surface.
        # There should be no link back to the tracer.
        #
        # Links between tracers and scenes
        # --------------------------------
        # On the other hand, several tracers can contribute to a single
        # scene. Then the tracer explicitly specifies the name
        # of the scene it is contributing to. This type of sharing makes
        # sence if the spatial context of the tracer is the same.
        #
        # The scene management is a separate issue, no general
        # rules can be formulated at this time.
        #
        scene = e.new_scene()
        scene.name = 'Polar domain'

        # Construct the source
        from mayavi.sources.vtk_data_source import VTKDataSource
        from tvtk.api import tvtk

        self._mv_src = VTKDataSource(name='Time-Strain Cylinder',
                                     data=tvtk.PolyData())
        e.add_source(self._mv_src)

        # Construct the warp filter
        if self.var_warp_on:
            from mayavi.filters.api import WarpVector
            e.add_filter(WarpVector())

        # Construct visualization modules
        from mayavi.modules.api import Outline, Surface
        s = Surface()
        e.add_module(Outline())
        e.add_module(s)
        s.module_manager.scalar_lut_manager.show_scalar_bar = True
        s.module_manager.scalar_lut_manager.reverse_lut = True
Example #20
0
    def Render(self):
        
        from mayavi.sources.vtk_data_source import VTKDataSource
        from enthought.mayavi.modules.outline import Outline
        from mayavi.modules.surface import Surface
        #import enthought.mayavi as mayavi
        
        # The TVTK dataset.
        mesh = tvtk.PolyData(points = array(self.xyz, 'f'))
        #mesh.point_data.scalar_mul()        
        mesh.point_data.scalars = self.rgb
        mesh.point_data.scalars.name = 'rgb'
        #mesh.point_data.scalars = self.intensity
        #mesh.point_data.scalars.name = 'Intensity'
                        
        verts = np.arange(0, self.xyz.shape[0], 1)
        verts.shape = (self.xyz.shape[0], 1)
        mesh.verts = verts        

        mayavi.new_scene() 
        d = VTKDataSource()
        d.data = mesh
        mayavi.add_source(d)
        #mayavi.add_module(Outline())
        s = Surface()
        mayavi.add_module(s)
        s.actor.property.set(representation = 'p', point_size = 2)
        # You could also use glyphs to render the points via the Glyph module.
        
        dataset = self.Outline()        
        fig = mlab.figure(bgcolor = (1, 1, 1), fgcolor = (0, 0, 0),
                      figure = dataset.class_name[3:])
        surf = mlab.pipeline.surface(dataset, opacity=.01)
        mlab.pipeline.surface(mlab.pipeline.extract_edges(surf),
                            color = (0, 0, 0), )
    
        s = [0.1]
        center = self.boundingCube.center
        print center[0]
        pts = mlab.points3d([center[0]], [center[1]], [center[2]], s, color = (1, 0, 0), )
        pts.glyph.glyph.clamping = False
Example #21
0
def main():
    arguments = docopt.docopt(__doc__, version='0.1')

    if arguments['--type'] == 'curvi':
        import updates_d3d as updates
    else:
        import updates_fm as updates

    logger.info("%s", arguments)
    # load the source generator
    source_generator = getattr(sources, arguments['--type'] + '_from_file')
    # generate the vtksources
    grids = list(source_generator(arguments['<file>']))
    pipe_list = list(pipes.pipes[arguments['--type']])
    print arguments['--type']
    update_list = list(updates.updates[arguments['--type']])
    # # Setup the scen
    scene = mayavi.new_scene()
    scene.scene.background = (0.182, 0.182, 0.182)

    # scene.scene.camera.position = [58166.583048915491, 485959.0247321708, 16043.572309725338]
    # scene.scene.camera.focal_point = [69999.998654336974, 450767.75405880535, -1590.5715721476552]
    # scene.scene.camera.view_angle = 30.0
    # scene.scene.camera.view_up = [0.17119034045790907, -0.39476891515875417, 0.90269118249725122]
    # scene.scene.camera.clipping_range = [138.29111167241902, 138291.11167241901]
    # scene.scene.camera.compute_view_plane_normal()
    camera = scene.scene.camera

    #camera.position = [35000, 525000, 10000]
    #camera.focal_point = [60000, 450000, 0]
    #camera.view_angle = 30
    #camera.view_up = [0.17119034045790907, -0.39476891515875417, 0.90269118249725122]
    # bathymetry grid, waterlevel grid (different z's)
    # ug_bathy, ug_waterlevel = list(ugs)

    # wrap the sources in vtk
    for grid, pipe in zip(grids, pipe_list):
        vtkgrid = VTKDataSource(data=grid)
        # add the grid to the scen
        mayavi.add_source(vtkgrid)
        pipe(mayavi)
    scene.scene.isometric_view()
    mlab.view(azimuth=90, elevation=70, distance=50000)
    #camera.compute_view_plane_normal()
    scene.render()
    for t in range(75):
        logger.info("rendering %s", t)
        for grid, update in zip(grids, update_list):
            update(arguments['<file>'], grid, t)
        scene.render()
        mlab.savefig('test%03d.png' % (t, ))
    import sys
    sys.exit(0)
Example #22
0
 def _mk_structured_grid(self):
     """ Creates a StructuredGrid VTK data set using the factory's
         attributes.
     """
     # FIXME: We need to figure out the dimensions of the data
     # here, if any.
     sg = tvtk.StructuredGrid(dimensions=self.scalar_data.shape)
     sg.points = c_[self.position_x.ravel(),
                    self.position_y.ravel(),
                    self.position_z.ravel(), ]
     self._vtk_source = sg
     self._mayavi_source = VTKDataSource(data=self._vtk_source)
Example #23
0
    def test_set_without_scalars_attribute_works(self):
        # Given
        class MySource(sources.MlabSource):
            x = sources.ArrayNumberOrNone

        src = MySource(x=1.0, dataset=tvtk.PolyData())
        src.m_data = VTKDataSource(data=src.dataset)

        # When
        src.update()

        # Then
        np.testing.assert_almost_equal(src.x, 1.0)
Example #24
0
def view():
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.filters.warp_scalar import WarpScalar
    from mayavi.filters.poly_data_normals import PolyDataNormals
    from mayavi.modules.surface import Surface

    mayavi.new_scene()
    src = VTKDataSource(data = spoints)
    mayavi.add_source(src)
    mayavi.add_filter(WarpScalar())
    mayavi.add_filter(PolyDataNormals())
    s = Surface()
    mayavi.add_module(s)
Example #25
0
    def setUp(self):
        """Initial setting up of test fixture, automatically called by TestCase before any other test method is invoked"""

        e = NullEngine()
        # Uncomment to see visualization for debugging etc.
        #e = Engine()
        e.start()
        e.new_scene()
        self.e = e

        sgrid = datasets.generateStructuredGrid()
        src = VTKDataSource(data=sgrid)
        e.add_source(src)

        # Create an outline for the data.
        o = Outline()
        e.add_module(o)

        # Create one ContourGridPlane normal to the 'x' axis.
        cgp1 = ContourGridPlane()
        e.add_module(cgp1)
        # Set the position to the middle of the data.
        cgp1.grid_plane.position = 15

        # Another with filled contours normal to 'y' axis.
        cgp2 = ContourGridPlane()
        cgp2.contour.filled_contours = True
        # Set the axis and position to the middle of the data.
        cgp2.grid_plane.axis = 'y'
        cgp2.grid_plane.position = 15
        e.add_module(cgp2)

        # An isosurface module.
        iso = IsoSurface(compute_normals=True)
        e.add_module(iso)
        iso.contour.contours = [5]

        # An interactive scalar cut plane.
        cp = ScalarCutPlane()
        e.add_module(cp)
        ip = cp.implicit_plane
        ip.normal = 0, 0, 1
        ip.origin = 0.5, 0.5, 1.0
        # Since this is running offscreen this seems necessary.
        ip.widget.origin = 0.5, 0.5, 1.0
        ip.widget.enabled = False
        self.scene = e.current_scene
        self.cgp2 = cgp2
        self.iso = iso
        self.cp = cp
        return
Example #26
0
def add_dataset(dataset, name='', **kwargs):
    """Add a dataset object to the Mayavi pipeline.

    **Parameters**

    :dataset: a tvtk/vtk dataset/tvtk/VTK Algorithm, or a Mayavi source. The
              dataset added to the Mayavi pipeline

    :figure: a figure identifier number or string, None or False, optionnal.

            If no `figure` keyword argument is given, the data
            is added to the current figure (a new figure if created if
            necessary).

            If a `figure` keyword argument is given, it should either the name
            the number of the figure the dataset should be added to, or None,
            in which case the data is not added to the pipeline.

            If figure is False, a null engine is created. This null
            engine does not create figures, and is mainly usefull for
            tensting, or using the VTK algorithms without visualization.

    **Returns**

    The corresponding Mayavi source is returned.

    """
    if isinstance(dataset, (tvtk.DataSet, vtk.vtkDataSet)):
        d = VTKDataSource()
        d.data = tvtk.to_tvtk(dataset)
    elif isinstance(dataset, (tvtk.DataObject, vtk.vtkDataObject)):
        d = VTKObjectSource()
        tp = tvtk.TrivialProducer()
        tp.set_output(tvtk.to_tvtk(dataset))
        d.object = tp
    elif isinstance(dataset, (tvtk.Object, vtk.vtkObject)):
        d = VTKObjectSource()
        d.object = tvtk.to_tvtk(dataset)
    elif isinstance(dataset, Source):
        d = dataset
    else:
        raise TypeError(
              "first argument should be either a TVTK object"
              " or a mayavi source")

    if len(name) > 0:
        d.name = name
    engine = _get_engine_from_kwarg(kwargs)
    if engine is None:
        # Return early, as we don't want to add the source to an engine.
        return d
    engine.add_source(d)
    return d
Example #27
0
def main():
    # Create some random points to view.
    pd = tvtk.PolyData()
    pd.points = np.random.random((1000, 3))
    verts = np.arange(0, 1000, 1)
    verts.shape = (1000, 1)
    pd.verts = verts
    pd.point_data.scalars = np.random.random(1000)
    pd.point_data.scalars.name = 'scalars'

    # Now visualize it using mayavi2.
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.outline import Outline
    from mayavi.modules.surface import Surface

    mayavi.new_scene()
    d = VTKDataSource()
    d.data = pd
    mayavi.add_source(d)
    mayavi.add_module(Outline())
    s = Surface()
    mayavi.add_module(s)
    s.actor.property.set(representation='p', point_size=2)
def main():
    # Create some random points to view.
    pd = tvtk.PolyData()
    pd.points = np.random.random((1000, 3))
    verts = np.arange(0, 1000, 1)
    verts.shape = (1000, 1)
    pd.verts = verts
    pd.point_data.scalars = np.random.random(1000)
    pd.point_data.scalars.name = 'scalars'

    # Now visualize it using mayavi2.
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.outline import Outline
    from mayavi.modules.surface import Surface

    mayavi.new_scene()
    d = VTKDataSource()
    d.data = pd
    mayavi.add_source(d)
    mayavi.add_module(Outline())
    s = Surface()
    mayavi.add_module(s)
    s.actor.property.trait_set(representation='p', point_size=2)
Example #29
0
    def test_add_attribute_raises_errors(self):
        # Given
        sgrid = self.sgrid
        s1 = numpy.ones(4)
        sgrid.point_data.scalars = s1
        sgrid.point_data.scalars.name = 's1'
        src = VTKDataSource(data=sgrid)

        # When/Then
        data = numpy.ones((4, 3, 3))
        self.assertRaises(AssertionError, src.add_attribute, data, 's2')

        data = numpy.ones((4, 5))
        self.assertRaises(AssertionError, src.add_attribute, data, 's2')
Example #30
0
    def _renderScene(self):

        script = self.script
        w = script.get_active_window()
        w.size = self.windowSize
        script.new_scene()
        scene = script.engine.current_scene.scene
        scene.disable_render = True
        scene.anti_aliasing_frames = self.aaframes
        scene.background = self.colorBg
        scene.foreground = self.colorFg

        script = self.script
        script.add_source(VTKDataSource(data=self._readData()))
        script.engine.current_object.name = "Solution"

        warp = WarpVector()
        warp.filter.scale_factor = scaleFactor
        script.add_filter(warp)

        norm = ExtractVectorNorm()
        script.add_filter(norm)

        surf = Surface()
        script.add_module(surf)

        wire = Surface()
        script.add_module(wire)
        wire.actor.actor.property.representation = "wireframe"
        wire.actor.actor.property.color = (0.0, 0.0, 0.0)
        wire.actor.mapper.scalar_visibility = False

        colorbar = script.engine.current_object.module_manager.scalar_lut_manager
        colorbar.lut_mode = self.lut
        colorbar.reverse_lut = self.lutReverse
        colorbar.scalar_bar.orientation = "horizontal"
        colorbar.scalar_bar.label_format = "%3.1f"
        colorbar.scalar_bar.label_text_property.shadow = True
        colorbar.scalar_bar.label_text_property.italic = False
        colorbar.scalar_bar.title_text_property.italic = False
        colorbar.scalar_bar.title_text_property.shadow = True
        colorbar.show_scalar_bar = True
        colorbar.data_range = (0.0, 5.0)
        colorbar.number_of_labels = 6
        colorbar.data_name = "Displacement / Coesismic Slip"
        scalar_bar = colorbar.scalar_bar_widget.representation
        scalar_bar.position2 = (0.4, 0.15)
        scalar_bar.position = (0.25, 0.02)

        return
Example #31
0
    def set_data(self,orig_data_verts,orig_data_speeds,reconstructor,align_json):
        self.orig_data_verts = orig_data_verts
        self.orig_data_speeds = orig_data_speeds
        self.reconstructor = reconstructor

        assert orig_data_verts.ndim == 2
        assert orig_data_speeds.ndim == 1
        assert orig_data_verts.shape[0] == 4
        assert orig_data_verts.shape[1] == orig_data_speeds.shape[0]


        # from mayavi2-2.0.2a1/enthought.tvtk/enthought/tvtk/tools/mlab.py
        #   Glyphs.__init__
        points = hom2vtk(orig_data_verts)
        polys = numpy.arange(0, len(points), 1, 'l')
        polys = numpy.reshape(polys, (len(points), 1))
        pd = tvtk.PolyData(points=points, polys=polys)
        pd.point_data.scalars = orig_data_speeds
        pd.point_data.scalars.name = 'speed'
        self.viewed_data = pd
        self.source = VTKDataSource(data=self.viewed_data, name='aligned data')

        if align_json:
            j = json.loads(open(align_json).read())
            self.params.s = j["s"]
            for i,k in enumerate(("tx", "ty", "tz")):
                setattr(self.params, k, j["t"][i])

            R = np.array(j["R"])
            rx,ry,rz = np.rad2deg(euler_from_matrix(R, 'sxyz'))

            self.params.r_x = rx
            self.params.r_y = ry
            self.params.r_z = rz

            self._params_changed()
Example #32
0
    def make_data(self):
        script = self.script
        from mayavi.sources.vtk_data_source import VTKDataSource
        from tvtk.api import tvtk

        ############################################################
        # Create a new scene and set up the visualization.
        s = self.new_scene()

        # Read a VTK (old style) data file.
        r = tvtk.StructuredPointsReader()
        r.file_name = get_example_data('heart.vtk')
        r.update()
        d = VTKDataSource(data=r.output)
        script.add_source(d)
Example #33
0
def view():
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.api import Outline, GridPlane

    mayavi.new_scene()
    src = VTKDataSource(data=sgrid)
    mayavi.add_source(src)
    mayavi.add_module(Outline())
    g = GridPlane()
    g.grid_plane.axis = 'x'
    mayavi.add_module(g)
    g = GridPlane()
    g.grid_plane.axis = 'y'
    mayavi.add_module(g)
    g = GridPlane()
    g.grid_plane.axis = 'z'
    mayavi.add_module(g)
Example #34
0
    def _annotateScene(self):

        script = self.script

        # Domain (axes and outline)
        script.add_source(VTKDataSource(data=vtk_geometry.domain()))
        script.engine.current_object.name = "Domain"
        outline = Outline()
        script.add_module(outline)
        outline.actor.property.opacity = 0.2
        axes = Axes()
        axes.axes.x_label = "X"
        axes.axes.y_label = "Y"
        axes.axes.z_label = "Z"
        axes.axes.label_format = "%-0.1f"
        script.add_module(axes)

        return
Example #35
0
 def _mk_polydata(self):
     """ Creates a PolyData vtk data set using the factory's
         attributes.
     """
     points = c_[self.position_x.ravel(),
                 self.position_y.ravel(),
                 self.position_z.ravel(), ]
     lines = None
     if self.lines:
         np = len(points) - 1
         lines = zeros((np, 2), 'l')
         lines[:, 0] = arange(0, np - 0.5, 1, 'l')
         lines[:, 1] = arange(1, np + 0.5, 1, 'l')
     self._vtk_source = tvtk.PolyData(points=points, lines=lines)
     if (self.connectivity_triangles is not None and self.connected):
         assert self.connectivity_triangles.shape[1] == 3, \
                 "The connectivity list must be Nx3."
         self._vtk_source.polys = self.connectivity_triangles
     self._mayavi_source = VTKDataSource(data=self._vtk_source)
Example #36
0
def view3d(sgrid):
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.api import Outline, GridPlane
    from mayavi.api import Engine
    from mayavi.core.ui.engine_view import EngineView
    e=Engine()
    e.start()
    s = e.new_scene()
     # Do this if you need to see the MayaVi tree view UI.
    ev = EngineView(engine=e)
    ui = ev.edit_traits()

#    mayavi.new_scene()
    src = VTKDataSource(data=sgrid)
    e.add_source(src)
    e.add_module(Outline())
    g = GridPlane()
    g.grid_plane.axis = 'x'
    e.add_module(g)
Example #37
0
    def test_set_without_scalars_works(self):
        # Given
        x, y, z, s, src = self.get_data()
        src = sources.MLineSource()
        src.reset(x=x, y=y, z=z)

        # When
        src.m_data = VTKDataSource(data=src.dataset)
        src.set(y=y + 1)

        # Then
        self.assertTrue(np.allclose(src.y, y + 1))

        # When
        src.reset(x=x, y=y + 1, z=z + 1)

        # Then
        self.assertTrue(np.allclose(src.y, y + 1))
        self.assertTrue(np.allclose(src.z, z + 1))
Example #38
0
def add_data(tvtk_data):
    """Add a TVTK data object `tvtk_data` to the mayavi pipleine.
    """
    d = VTKDataSource()
    d.data = tvtk_data
    mayavi.add_source(d)
    def do(self):
        ############################################################
        # Imports.
        script = self.script
        from mayavi.sources.vtk_data_source import VTKDataSource
        from mayavi.modules.api import ImagePlaneWidget

        # Create dataset with multiple scalars.
        arr1 = zeros(27, 'f')
        for n in range(27):
            arr1[n] = (1+float(n))/10.0
        arr2 = (arr1 + 1).astype('d')
        arr3 = arr1 + 2.0*(0.5 - random.random(27))
        arr3 = arr3.astype('f')

        p = tvtk.ImageData(dimensions=[3,3,3], spacing=[1,1,1])
        if is_old_pipeline():
            p.scalar_type = 'int'

        p.point_data.scalars = arr1
        p.point_data.scalars.name = 'first'
        j2 = p.point_data.add_array(arr2)
        p.point_data.get_array(j2).name='second'
        j3 = p.point_data.add_array(arr3)
        p.point_data.get_array(j3).name='third'
        if is_old_pipeline():
            p.update()

        # Make the pipeline.
        self.new_scene()
        src = VTKDataSource(data=p)
        script.add_source(src)
        ipw = ImagePlaneWidget()
        script.add_module(ipw)

        # Test.
        ipw = ipw.ipw
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr1), max(arr1)
        assert r == expect
        o = src.outputs[0]
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 10
            assert st == 'float'

        src.point_scalars_name = 'second'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr2), max(arr2)
        assert r == expect
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 11
            assert st == 'double'

        src.point_scalars_name = 'third'
        scalars = ipw.input.point_data.scalars
        r = scalars.range
        expect = min(arr3), max(arr3)
        assert r == expect
        o.update_traits()
        if is_old_pipeline():
            st = ipw.input.scalar_type
            assert scalars.data_type == 10
            assert st == 'float'
Example #40
0
def fancy_axes(figure=None, target=None, nb_labels=5, xl=None, xh=None,
               tight=False, symmetric=False, padding=0.05, opacity=0.7,
               face_color=None, line_width=2.0, grid_color=None,
               labels=True, label_color=None, label_shadow=True,
               consolidate_labels=True):
    """Make axes with 3 shaded walls and a grid similar to matplotlib

    Args:
        figure (mayavi.core.scene.Scene): specific figure, or None for
            :py:func:`mayavi.mlab.gcf`
        target (Mayavi Element): If either xl or xh are not given, then
            get that limit from a bounding box around `target`
        nb_labels (int, sequence): number of labels in all, or each
            (x, y, z) directions
        xl (float, sequence): lower corner of axes
        xh (float, sequence): upper corner of axes
        tight (bool): If False, then let xl and xh expand to make nicer
            labels. This uses matplotlib to determine new extrema
        symmetric (bool): If True, then xl + xh = 0
        padding (float): add padding as a fraction of the total length
        opacity (float): opacity of faces
        face_color (sequence): color (r, g, b) of faces
        line_width (float): Width of grid lines
        grid_color (sequence): Color of grid lines
        labels (bool): Whether or not to put axis labels on
        label_color (sequence): color of axis labels
        label_shadow (bool): Add shadows to all labels
        consolidate_labels (bool): if all nb_labels are the same, then
            only make one axis for the labels

    Returns:
        VTKDataSource: source to which 2 surfaces and 3 axes belong
    """
    if figure is None:
        figure = mlab.gcf()

    # setup xl and xh
    if xl is None or xh is None:
        _outline = mlab.outline(target, figure=figure)

        if xl is None:
            xl = _outline.bounds[0::2]
        if xh is None:
            xh = _outline.bounds[1::2]
        _outline.remove()

    nb_labels = np.broadcast_to(nb_labels, (3,))
    xl = np.array(np.broadcast_to(xl, (3,)))
    xh = np.array(np.broadcast_to(xh, (3,)))
    L = xh - xl

    xl -= padding * L
    xh += padding * L

    # now adjust xl and xh to be prettier
    if symmetric:
        tight = False
    if not tight:
        from matplotlib.ticker import AutoLocator
        for i in range(len(xl)):  # pylint: disable=consider-using-enumerate
            l = AutoLocator()
            l.create_dummy_axis()
            l.set_view_interval(xl[i], xh[i])
            locs = l()
            xl[i] = locs[0]
            xh[i] = locs[-1]

    dx = (xh - xl) / (nb_labels - 1)
    grid = tvtk.ImageData(dimensions=nb_labels, origin=xl, spacing=dx)
    src = VTKDataSource(data=grid)
    src.name = "fancy_axes"

    if face_color is None:
        face_color = figure.scene.background
    if grid_color is None:
        grid_color = figure.scene.foreground
    if label_color is None:
        label_color = grid_color

    face = mlab.pipeline.surface(src, figure=figure, opacity=opacity,
                                 color=face_color)
    face.actor.property.frontface_culling = True

    if line_width:
        grid = mlab.pipeline.surface(src, figure=figure, opacity=1.0,
                                     color=grid_color, line_width=line_width,
                                     representation='wireframe')
        grid.actor.property.frontface_culling = True

    if labels:
        def _make_ax_for_labels(_i, all_axes=False):
            if all_axes:
                _ax = Axes(name='axes-labels')
            else:
                _ax = Axes(name='{0}-axis-labels'.format('xyz'[_i]))
                # VTK bug... y_axis and z_axis are flipped... how is VTK still
                # the de-facto 3d plotting library?
                if _i == 0:
                    _ax.axes.x_axis_visibility = True
                    _ax.axes.y_axis_visibility = False
                    _ax.axes.z_axis_visibility = False
                elif _i == 1:
                    _ax.axes.x_axis_visibility = False
                    _ax.axes.y_axis_visibility = False
                    _ax.axes.z_axis_visibility = True  # VTK bug
                elif _i == 2:
                    _ax.axes.x_axis_visibility = False
                    _ax.axes.y_axis_visibility = True  # VTK bug
                    _ax.axes.z_axis_visibility = False
                else:
                    raise ValueError()
            _ax.property.opacity = 0.0
            _ax.axes.number_of_labels = nb_labels[_i]
            # import IPython; IPython.embed()
            _ax.title_text_property.color = label_color
            _ax.title_text_property.shadow = label_shadow
            _ax.label_text_property.color = label_color
            _ax.label_text_property.shadow = label_shadow
            src.add_module(_ax)

        if consolidate_labels and np.all(nb_labels[:] == nb_labels[0]):
            _make_ax_for_labels(0, all_axes=True)
        else:
            _make_ax_for_labels(0, all_axes=False)
            _make_ax_for_labels(1, all_axes=False)
            _make_ax_for_labels(2, all_axes=False)

    return src