Пример #1
0
def Scatter():
    # Create some random points to view.
    data = Data()
    p, r = data.slice
    pd = tvtk.PolyData()
    pd.points = p
    verts = arange( 0, len( r ), 1 )
    verts.shape = ( len( r ), 1 )
    pd.verts = verts
    pd.point_data.scalars = r
    pd.point_data.scalars.name = 'scalars'

    # Now visualize it using mayavi2.
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.modules.outline import Outline
    from enthought.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 )
Пример #2
0
def Lines():
    # Create some random points to view.
    data = Data()
    p, r = data.slice
    pd = tvtk.PolyData()
    pd.points = p
    verts = arange( 0, len( r ), 1 )
    verts.shape = ( len( r ), 1 )
    pd.verts = verts
    pd.point_data.scalars = r
    pd.point_data.scalars.name = 'scalars'
    pd.lines = arange( 0, len( r ), 1 ).reshape( len( r ) / 15, 15 )
    
    # Now visualize it using mayavi2.
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.modules.outline import Outline
    from enthought.mayavi.modules.surface import Surface
    from enthought.mayavi.modules.iso_surface import IsoSurface
    from enthought.mayavi.modules.streamline import Streamline

    mayavi.new_scene()
    d = VTKDataSource()
    d.data = pd
    mayavi.add_source( d )
    o = Outline()
    mayavi.add_module( o )

    s = Surface() #enable_contours=True
    mayavi.add_module( s )
    s.actor.property.set( representation='p', point_size=2 )
Пример #3
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)
    return d
Пример #4
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)
    return d
Пример #5
0
 def add_points(self, points):
     g = mlab.Glyphs(points, None, None)
     d = VTKDataSource()
     d.data = g.poly_data
     self.scene.add_child(d)
     v = Vectors()
     v.glyph.color_mode = "no_coloring"
     v.glyph.glyph_source = tvtk.PointSource(radius=0, number_of_points=1)
     d.add_child(v)
Пример #6
0
 def add_points(self, points):
     g = mlab.Glyphs(points, None, None)
     d = VTKDataSource()
     d.data = g.poly_data
     self.scene.add_child(d)
     v = Vectors()
     v.glyph.color_mode = 'no_coloring'
     v.glyph.glyph_source = tvtk.PointSource(radius=0,
                                             number_of_points=1)
     d.add_child(v)
Пример #7
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
Пример #8
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
Пример #9
0
 def add_source_data(self, data):
     from enthought.mayavi.filters.poly_data_normals import PolyDataNormals
     d = VTKDataSource()
     d.data = data
     obj = self.scene.add_child(d)
     w = WarpScalar()
     d.add_child(w)
     n = PolyDataNormals()
     n.filter.feature_angle = 45
     w.add_child(n)
     s = Surface()
     n.add_child(s)
Пример #10
0
 def add_source_data(self, data):
     from enthought.mayavi.filters.poly_data_normals import PolyDataNormals
     d = VTKDataSource()
     d.data = data
     obj = self.scene.add_child(d)
     w = WarpScalar()
     d.add_child(w)
     n = PolyDataNormals()
     n.filter.feature_angle = 45
     w.add_child(n)
     s = Surface()
     n.add_child(s)
Пример #11
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()
        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)
        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
Пример #12
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()
        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)
        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
Пример #13
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))
     image_data.whole_extent = image_data.extent
     src.data = image_data
     return src
Пример #14
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)
     )
     image_data.whole_extent = image_data.extent
     src.data = image_data
     return src
Пример #15
0
def view():
    col0 = numpy.arange(0, numpts - 1, 1)
    col1 = numpy.arange(1, numpts, 1)
    lines = array([col0, col1]).transpose()

    curve = tvtk.PolyData(points=points, lines=lines)
    # assign temperature in sequence so that we now the "direction" of the curve
    curve.point_data.scalars = numpy.arange(0, numpts, 1)
    curve.point_data.scalars.name = 'temperature'

    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    #from enthought.mayavi.modules.outline import Outline
    from enthought.mayavi.modules.surface import Surface
    from enthought.mayavi.modules.axes import Axes
    from enthought.mayavi.modules.text import Text

    scene = mayavi.new_scene()
    scene.scene.background = (1.0, 1.0, 1.0)
    scene.scene.foreground = (0.0, 0.0, 0.0)

    src = VTKDataSource(data=curve)
    mayavi.add_source(src)
    #mayavi.add_module(Outline())
    s = Surface()
    mayavi.add_module(s)
    s.actor.property.set(representation='p', color=(0., 1., 0.), line_width=2)
Пример #16
0
    def create_source(self):
        """Create a VTK source from data in a SfePy-supported file."""
        if self.io is None:
            self.read_common(self.filename[self.step])

        dataset = self.create_dataset()

        src = VTKDataSource(data=dataset)
        return src
Пример #17
0
def view():
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.modules.surface import Surface

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

    mayavi2.new_scene()
    src = VTKDataSource(data=spoints)
    mayavi2.add_source(src)
    mayavi2.add_module(Outline())
    mayavi2.add_module(ImagePlaneWidget())
Пример #19
0
def view3d(sgrid):
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.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)
Пример #20
0
def view():
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.modules.outline import Outline
    from enthought.mayavi.modules.surface import Surface
    from enthought.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())
Пример #21
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)
Пример #22
0
def view():
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.modules.outline import Outline
    from enthought.mayavi.modules.surface import Surface
    from enthought.mayavi.modules.vectors import Vectors
    from enthought.mayavi.modules.api import TensorGlyph
    from enthought.mayavi.filters.api import WarpVector, ExtractTensorComponents

    mayavi.new_scene()
    
    wv = WarpVector()
    tc = ExtractTensorComponents()
    tc2 = ExtractTensorComponents()
    # The single type one
    src = VTKDataSource(data = mesh)
    print "str1", mesh.point_data.is_array_an_attribute(0)
    print "id ", mesh.point_data.has_array("d2")
    mayavi.add_source(src) 
    mayavi.add_filter(wv)
    src.add_child(tc)
    tc.add_module(Surface())
    #src.add_child(Surface())
    
    mesh.point_data.set_active_tensors('first')
    src2 = VTKDataSource(data = mesh)
    
    mayavi.add_source(src2) 
    #tg = TensorGlyph()
    #tg.glyph.glyph.scale_factor = 100.
    #mayavi.add_module(tg)
    #mayavi.add_module(Surface())
    #mayavi.add_module(Vectors())
    src2.add_child(tc2)
    tc2.add_module(Surface())
    tc2.scene.z_plus_view()
Пример #23
0
def view():
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.filters.warp_scalar import WarpScalar
    from enthought.mayavi.filters.poly_data_normals import PolyDataNormals
    from enthought.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)
Пример #24
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
Пример #25
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 enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.modules.outline import Outline
    from enthought.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)
Пример #26
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 enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.modules.outline import Outline
    from enthought.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)
Пример #27
0
    def make_data(self):
        script = self.script
        from enthought.mayavi.sources.vtk_data_source import VTKDataSource
        from enthought.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)
Пример #28
0
  def run(self):    
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.filters.threshold import Threshold
    from enthought.mayavi.modules.surface import Surface
    from enthought.mayavi.modules.scalar_cut_plane import ScalarCutPlane

    self._setupScene()
    data = self._readData()

    script = self.script
    script.add_source(VTKDataSource(data=data))
    script.engine.current_object.name = "Error"
    error = script.engine.current_object

    threshold = Threshold()
    script.add_filter(threshold)
    threshold.lower_threshold = -3.0
    
    surf = Surface()
    script.add_filter(surf)

    if showSlice:
      surf.actor.property.opacity = 0.3
      script.engine.current_object = error
      slice = ScalarCutPlane()
      script.add_module(slice)
      slice.actor.property.opacity = 0.5
      slice.implicit_plane.origin = (12.0, 12.0, -12.0)
      slice.implicit_plane.normal = (0, -1.0, 0.0)

    for obj in [slice, surf]:
      colorbar = obj.module_manager.scalar_lut_manager
      colorbar.data_range = (threshold.lower_threshold, -2.0)
      colorbar.lut_mode = "hot"
      colorbar.reverse_lut = True
    colorbar.show_scalar_bar = True
    colorbar.number_of_labels = 6
    colorbar.scalar_bar.label_format = "%-3.1f"
    w,h = colorbar.scalar_bar.position2
    colorbar.scalar_bar.position2 = (w, 0.1)

    light = script.engine.current_scene.scene.light_manager.lights[0]
    light.elevation = 20.0
    light.azimuth = -45.0

    import vtk_geometry
    vtk_geometry.setCamera(script.engine.current_scene.scene.camera)
    return
Пример #29
0
  def _renderScene(self, data):

    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.add_source(VTKDataSource(data=data))
    objTop = script.engine.current_object
    script.engine.current_object.name = "fault"

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

    surf = Surface()
    script.add_module(surf)

    colorbar = script.engine.current_object.module_manager.scalar_lut_manager
    colorbar.data_name = "Velocity (m/s)"
    colorbar.lut_mode = self.lut
    colorbar.reverse_lut = self.lutReverse
    colorbar.scalar_bar.label_format = "%4.2f"
    colorbar.scalar_bar.label_text_property.font_size = 18
    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 = False
    colorbar.data_range = (0.0, 1.0)
    #colorbar.number_of_labels = 0

    colorbar.scalar_bar.orientation = "horizontal"
    scalar_bar = colorbar.scalar_bar_widget.representation
    scalar_bar.position2 = (0.33, 0.12)
    scalar_bar.position = (0.01, 0.02)

    surf = Surface()
    script.add_module(surf)

    

    return
Пример #30
0
 def add_lines(self, points):
     np = len(points) - 1
     lines = scipy.zeros((np, 2), "l")
     lines[:, 0] = scipy.arange(0, np - 0.5, 1, "l")
     lines[:, 1] = scipy.arange(1, np + 0.5, 1, "l")
     pd = tvtk.PolyData(points=points, lines=lines)
     d = VTKDataSource()
     d.data = pd
     self.scene.add_child(d)
     filter = tvtk.TubeFilter(number_of_sides=6)
     filter.radius = 0.01
     f = FilterBase(filter=filter, name="TubeFilter")
     d.add_child(f)
     s = Surface()
     s.actor.mapper.scalar_visibility = False
     d.add_child(s)
Пример #31
0
  def run(self):    
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.filters.warp_vector import WarpVector
    from enthought.mayavi.filters.extract_vector_norm import ExtractVectorNorm
    from enthought.mayavi.modules.surface import Surface
    from enthought.mayavi.modules.glyph import Glyph

    self._setupScene(showFault=False, showMaterials=False)
    data = self._readData()

    script = self.script
    script.add_source(VTKDataSource(data=data))
    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)

    glyph = Glyph()
    script.add_module(glyph)
    glyph.actor.property.color = (1,1,1)
    glyph.actor.mapper.scalar_visibility = False
    glyph.glyph.glyph_position = 'tail'
    glyph.glyph.glyph.scale_factor = scaleFactor
    glyph.glyph.glyph_source = glyph.glyph.glyph_list[1]
    
    colorbar = script.engine.current_object.module_manager.scalar_lut_manager
    colorbar.show_scalar_bar = True
    colorbar.data_range = (0.0, 0.5)
    colorbar.number_of_labels = 6
    colorbar.scalar_bar.label_format = "%3.1f"
    w,h = colorbar.scalar_bar.position2
    colorbar.scalar_bar.position2 = (w, 0.1)
    colorbar.data_name = "Displacement [m]"
    
    import vtk_geometry
    vtk_geometry.setCamera(script.engine.current_scene.scene.camera)
    return
Пример #32
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)
Пример #33
0
def zzz_reader(fname, engine):
    """Reader for .zzz files.
    
    Parameters:
    -----------

    fname -- Filename to be read.

    engine -- The engine the source will be associated with.
    """
    from enthought.tvtk.api import tvtk
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    # Do your own reader stuff here, I'm just reading a VTK file with a
    # different extension here.
    r = tvtk.StructuredPointsReader(file_name=fname)
    r.update()

    src = VTKDataSource(data=r.output)
    return src
Пример #34
0
  def _plotScene(self):
    from enthought.mayavi.sources.vtk_data_source import VTKDataSource
    from enthought.mayavi.filters.extract_vector_norm import ExtractVectorNorm
    from enthought.mayavi.modules.outline import Outline
    from enthought.mayavi.modules.axes import Axes
    from enthought.mayavi.modules.surface import Surface
    from enthought.tvtk.api import tvtk

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

    t = 0.0
    self.dataVtk = self.surfdata.toVtk(t)
    script.engine.current_object.name = "Velocity"

    script.add_source(VTKDataSource(data=self.dataVtk))
    surf = Surface()
    surf.actor.property.representation = "wireframe"
    script.add_module(surf)

    colorbar = script.engine.current_object.module_manager.scalar_lut_manager
    colorbar.show_scalar_bar = True
    colorbar.scalar_bar.label_format = "%3.1f"
    colorbar.use_default_range = False
    colorbar.data_range = (-3, 1)
    colorbar.number_of_labels = 4
    colorbar.data_name = "Velocity (m/s)"
    colorbar.lut_mode = "hot"
    colorbar.reverse_lut = self.lutReverse

    scalar_bar = colorbar.scalar_bar_widget.representation
    scalar_bar.position2 = (0.05, 0.33)
    scalar_bar.position = (0.05, 0.05)


    return
Пример #35
0
 def _mk_rectilinear_grid(self):
     """ Creates a RectilinearGrid VTK data set using the factory's 
         attributes.
     """
     rg = tvtk.RectilinearGrid()
     x = self.position_x.squeeze()
     if x.ndim == 3:
         x = x[:, 0, 0]
     y = self.position_y.squeeze()
     if y.ndim == 3:
         y = y[0, :, 0]
     z = self.position_z.squeeze()
     if z.ndim == 3:
         z = z[0, 0, :]
     # FIXME: We should check array size here.
     rg.dimensions = (x.size, y.size, z.size)
     rg.x_coordinates = x
     rg.y_coordinates = y
     rg.z_coordinates = z
     self._vtk_source = rg
     self._mayavi_source = VTKDataSource(data=self._vtk_source)
Пример #36
0
 def add_lines(self, points):
     np = len(points) - 1
     lines = scipy.zeros((np, 2), 'l')
     lines[:,0] = scipy.arange(0, np-0.5, 1, 'l')
     lines[:,1] = scipy.arange(1, np+0.5, 1, 'l')
     pd = tvtk.PolyData(points=points, lines=lines)
     d = VTKDataSource()
     d.data = pd
     self.scene.add_child(d)
     filter = tvtk.TubeFilter(number_of_sides=6)
     filter.radius = 0.01
     f = FilterBase(filter=filter, name='TubeFilter')
     d.add_child(f)
     s = Surface()
     s.actor.mapper.scalar_visibility = False
     d.add_child(s)
Пример #37
0
    def run(self):
        from enthought.mayavi.sources.vtk_data_source import VTKDataSource
        from enthought.mayavi.modules.surface import Surface

        self._setupScene(showFault=False, showMaterials=False)
        mesh = self._readMesh()

        script = self.script
        script.add_source(VTKDataSource(data=mesh))
        script.engine.current_object.name = "Mesh"

        surf = Surface()
        script.add_module(surf)
        surf.actor.property.color = (0, 1, 0)

        surf = Surface()
        script.add_module(surf)
        surf.actor.property.representation = 'wireframe'

        import vtk_geometry
        vtk_geometry.setCamera(script.engine.current_scene.scene.camera)
        return
Пример #38
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 three simple grid plane modules.
        # First normal to 'x' axis.
        gp1 = GridPlane()
        e.add_module(gp1)
        # Second normal to 'y' axis.
        gp2 = GridPlane()
        # We'll test how robust things are by setting attributes
        gp2.grid_plane.axis = 'y'
        gp2.grid_plane.position = 16
        e.add_module(gp2)
        # Third normal to 'z' axis.
        gp3 = GridPlane()
        e.add_module(gp3)
        gp3.grid_plane.axis = 'z'
        gp3.grid_plane.position = 6

        for gp in (gp1, gp2, gp3):
            gp.actor.property.set(ambient=1.0)

        self.scene = e.current_scene
        return
Пример #39
0
    def create_source(self):
        """
        Create a VTK source from data in a SfePy-supported file.

        Notes
        -----
        All data need to be set here, otherwise time stepping will not
        work properly - data added by user later will be thrown away on
        time step change.
        """
        if self.io is None:
            self.read_common(self.filename)

        dataset = self.create_dataset()

        try:
            out = self.io.read_data(self.step)
        except ValueError:
            out = None

        if out is not None:
            self.add_data_to_dataset(dataset, out)

        if self.mat_id_name is not None:
            mat_id = self.mesh.cmesh.cell_groups
            if self.single_color:
                rm = mat_id.min(), mat_id.max()
                mat_id[mat_id > rm[0]] = rm[1]

            dm = DatasetManager(dataset=dataset)
            dm.add_array(mat_id, self.mat_id_name, 'cell')

        src = VTKDataSource(data=dataset)
        #        src.print_traits()
        #        debug()
        return src
Пример #40
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
Пример #41
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)

        c = Contour()
        # `name` is used for the notebook tabs.
        n = PolyDataNormals(name='Normals')
        o = Optional(filter=n, label_text='Compute normals')
        coll = Collection(filters=[c, o], name='IsoSurface')
        e.add_filter(coll)
        s = Surface()
        e.add_module(s)
        self.coll = coll
        self.scene = e.current_scene
        return
Пример #42
0
    def run(self):

        from enthought.mayavi.sources.vtk_file_reader import VTKFileReader
        #import modules here
        from enthought.mayavi.modules import surface, glyph , axes, outline, orientation_axes, scalar_cut_plane  
        from enthought.mayavi.sources.vtk_data_source import VTKDataSource 
        from enthought.tvtk.api import tvtk
        #CitcomS filter
        from plugins.filter.CitcomSshowCaps import CitcomSshowCaps
        from plugins.filter.CitcomSreduce import CitcomSreduce
        import re
        
        
        script = self.script
        
        #DEFINES
        orange = (1.0,0.5,0)
                
        ################
        #Read Meta information
        meta = ""
        try:
            vtk = open(self.filename, "r")
            vtk.readline()
            meta = vtk.readline()
        except IOError:
            print 'cannot open file'
        try:
            print "Reading meta-information"
            m = re.search('(?<=NX:)\d+', meta)
            nx = int(m.group(0))
            print "NX: ", nx
            m = re.search('(?<=NY:)\d+', meta)
            ny = int(m.group(0))
            print "NY: ", ny
            m = re.search('(?<=NZ:)\d+', meta)
            nz = int(m.group(0))
            print "NZ: ", nz
            m = re.search('(?<=Radius_Inner:)(\d+|.)+', meta)
            print m.group(0)
            radius_inner = float(m.group(0))
            print "Radius Inner: ", radius_inner
            
        except ValueError:
            print "Non-valid meta information in file..."
    
        vtk.close()
        
        
        ################
        
        #Read Vtk file
        src_vtkf = VTKFileReader()
        src_vtkf.initialize(self.filename)
        
        ###########Display Data############
        #Create new scene
        script.new_scene()     
        
        
        script.add_source(src_vtkf)
        
        
        scap = CitcomSshowCaps()
        script.add_filter(scap)
        
        #Show ScalarCutPlane
        scp = scalar_cut_plane.ScalarCutPlane()
        script.add_module(scp)
        
        #Add filter for a reduce grid
        redu = CitcomSreduce()
        script.add_filter(redu)
       
        #Shows Glyph on reduce grid
        gly = glyph.Glyph()
        gly.glyph.glyph_source.scale = 0.082
        gly.glyph.scale_mode = 'scale_by_scalar'
        gly.glyph.color_mode = 'color_by_scalar'
        script.add_module(gly)
        mm = gly.module_manager
        mm.scalar_lut_manager.use_default_range = False
        mm.scalar_lut_manager.data_range = 0.0, 1.0
        ################### Create CORE ################################
        #Load VTK Data Sets
        sphere = tvtk.SphereSource()
        sphere.radius = radius_inner 
        sphere.theta_resolution = 24 
        sphere.phi_resolution = 24
          
        # Create a mesh from the data created above.
        src = VTKDataSource()
        src.data = sphere.output
        script.add_source(src)
        
        #Show Surface
        surf_module = surface.Surface()
        surf_module.actor.property.color = orange
        script.add_module(surf_module)
Пример #43
0
    def run(self):

        from enthought.mayavi.sources.vtk_file_reader import VTKFileReader
        #import modules here
        from enthought.mayavi.modules import surface, glyph , axes, outline, orientation_axes, scalar_cut_plane  
        from enthought.mayavi.sources.vtk_data_source import VTKDataSource 
        from enthought.tvtk.api import tvtk
        #citcomS Filter and Modules
        from plugins.CitcomSHDFUgrid import CitcomSHDFUgrid
        from plugins.filter.CitcomSshowCaps import CitcomSshowCaps
        from plugins.filter.CitcomSreduce import CitcomSreduce
        
        import re
        
        
        script = self.script
         
        #DEFINES
        orange = (1.0,0.5,0)
        reduce_factor = 2
        
        
        #Read Hdf file
        src_hdf = CitcomSHDFUgrid()
        hexgrid = src_hdf.initialize(self.filename,self.timestep,self.nx_redu,self.ny_redu,self.nz_redu)
        radius_inner = src_hdf._radius_inner
        data = VTKDataSource()
        data.data = hexgrid
        
        
        ###########Display Data############
        #Create new scene
        script.new_scene()     
        script.add_source(data)
             
        scap = CitcomSshowCaps()
        script.add_filter(scap)
        
        
        #Show ScalarCutPlane
        scp = scalar_cut_plane.ScalarCutPlane()
        script.add_module(scp)
        
        #Add filter for a reduce grid
        redu = CitcomSreduce()
        #redu.setvalues(nx,ny,nz)
        script.add_filter(redu)
       
        gly = glyph.Glyph()
        gly.glyph.glyph_source.scale = 0.082
        gly.glyph.scale_mode = 'scale_by_scalar'
        gly.glyph.color_mode = 'color_by_scalar'
        script.add_module(gly)
        mm = gly.module_manager
        mm.scalar_lut_manager.use_default_range = False
        mm.scalar_lut_manager.data_range = 0.0, 1.0
        ################### Create CORE ################################
        #Load VTK Data Sets
        sphere = tvtk.SphereSource()
        sphere.radius = radius_inner 
        sphere.theta_resolution = 24 
        sphere.phi_resolution = 24
          
        # Create a mesh from the data created above.
        src = VTKDataSource()
        src.data = sphere.output
        script.add_source(src)
        
        #Show Surface
        surf_module = surface.Surface()
        surf_module.actor.property.color = orange
        script.add_module(surf_module)
Пример #44
0
#  e.add_module(a)

# STATIONS

  #d=VTKDataSource()
  #d.data=pd
  #e.add_source(d)

  #g=Glyph()
  #e.add_module(g)
  #g.glyph.glyph_source.glyph_source=g.glyph.glyph_source.glyph_list[4]
  #g.glyph.glyph_source.glyph_source.radius=0.1

# DEM

  d=VTKDataSource()
  d.data=dem_data
  e.add_source(d)

  df=Delaunay2D()
  e.add_filter(df)

  s=Surface()
  e.add_module(s)
  #s.actor.property.set(representation='p', point_size=100)
  

  #view(azimuth=-60,elevation=60,distance=120)
  output_file="tmp.png"
  win.scene.save(output_file,size=(800,600))
Пример #45
0
def plot_slice_mayavi(dat_filename,output_file,hyp_x,hyp_y,hyp_z,search_grid_file_name,max_stack_value):

  base_path=os.getenv('WAVELOC_PATH')
  lib_path="%s/lib"%base_path

  # grid geometry
  hdr_file=lib_path + os.sep + search_grid_file_name

  # detection
  detection=50

  # stations
  stations_file="%s/coord_stations_piton"%lib_path
  sta=StationList()
  sta.read_from_file(stations_file)

  # create the object to contain the stations
  pd = tvtk.PolyData()
  pd.points = [[s.x/1000.0, s.y/1000.0, -s.elev/1000.0] for s in sta.stations.values()]

  # create the object to contain the stations
  try:
    pd_hyp = tvtk.PolyData()
    pd_hyp.points=[[hyp_x,hyp_y,hyp_z]]
  except TypeError:
    pass

  # read the dat file
  print dat_filename
  data=QDGrid()
  data.read_NLL_hdr_file(hdr_file)
  data.buf=numpy.fromfile(dat_filename, dtype=numpy.int16)
  max_ib=numpy.argmax(data.buf)
  print max_ib
  max_val=data.buf[max_ib]
  ix,iy,iz=data.get_ix_iy_iz(max_ib)
  #data.buf=numpy.array(data.buf, dtype=numpy.float)
  data.buf.shape = (data.nx, data.ny, data.nz)


  # 'mayavi' is always defined on the interpreter.
  e = OffScreenEngine()
  #e = Engine()
  e.start()
  win = e.new_scene(magnification=1)
  e.current_scene.scene.off_screen_rendering = True
  win.scene.isometric_view()
  
  # Make the data and add it to the pipeline.
  src = ArraySource(transpose_input_array=True)
  src.scalar_data = data.buf
  src.spacing=(data.dx, data.dy, -data.dz)
  src.origin=(data.x_orig, data.y_orig, -data.z_orig)
  e.add_source(src)

  # Visualize the data.
  o = Outline()
  e.add_module(o)

  lut=e.scenes[0].children[0].children[0].scalar_lut_manager
  lut.data_range=[-1,max_stack_value]
  lut.show_legend = True
  lut.data_name = 'Stack'


  # Create one ContourGridPlane normal to the 'x' axis.
  cgp = ContourGridPlane()
  e.add_module(cgp)
  # Set the position to the middle of the data.
  if max_val > detection:
    cgp.grid_plane.position = ix
  else:
    cgp.grid_plane.position = data.nx/2
  cgp.contour.filled_contours = True
  cgp.actor.property.opacity = 0.6
  output=cgp.grid_plane.outputs[0]
  x_data=numpy.array(output.point_data.scalars.to_array())

  # Another with filled contours normal to 'y' axis.
  cgp = ContourGridPlane()
  e.add_module(cgp)
  # Set the axis and position to the middle of the data.
  cgp.grid_plane.axis = 'y'
  if max_val > detection:
    cgp.grid_plane.position = iy
  else:
    cgp.grid_plane.position = data.ny/2
  cgp.contour.filled_contours = True
  cgp.actor.property.opacity = 0.6
  output=cgp.grid_plane.outputs[0]
  y_data=numpy.array(output.point_data.scalars.to_array())

  # Another with filled contours normal to 'z' axis.
  cgp = ContourGridPlane()
  e.add_module(cgp)
  # Set the axis and position to the middle of the data.
  cgp.grid_plane.axis = 'z'
  if max_val > detection:
    cgp.grid_plane.position = iz
  else:
    cgp.grid_plane.position = data.nz/2
  cgp.contour.filled_contours = True
  cgp.actor.property.opacity = 0.6
  output=cgp.grid_plane.outputs[0]
  z_data=numpy.array(output.point_data.scalars.to_array())

  a=Axes()
  e.add_module(a)

  d=VTKDataSource()
  d.data=pd
  e.add_source(d)
  
  g=Glyph()
  e.add_module(g)
  g.glyph.glyph_source.glyph_source=g.glyph.glyph_source.glyph_list[4]
  g.glyph.glyph_source.glyph_source.radius=0.1

  d=VTKDataSource()
  d.data=pd_hyp
  e.add_source(d)
  
  g=Glyph()
  e.add_module(g)
  g.glyph.glyph_source.glyph_source=g.glyph.glyph_source.glyph_list[4]
  g.glyph.glyph_source.glyph_source.radius=0.5
  g.actor.property.color=(0.0,0.0,0.0)



  #view(azimuth=-60,elevation=60,distance=120)
  win.scene.save(output_file,size=(800,800))

  e.stop()
  del win
  del e

  return (x_data, y_data, z_data)
Пример #46
0
    def do(self):
        ############################################################
        # Imports.
        script = self.script
        from enthought.mayavi.sources.vtk_data_source import VTKDataSource
        from enthought.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],
                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()

        # 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()
        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()
        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()
        st = ipw.input.scalar_type
        assert scalars.data_type == 10
        assert st == 'float'
Пример #47
0
# is a script that create a !SurfRegular object using mlab, and then loads
# it in !MayaVi2. A more detailed version of this script is given in the
# examples pages [:Cookbook/MayaVi/Examples].
# 
# <codecell>


import numpy
def f(x, y):
    return numpy.sin(x*y)/(x*y)
x = numpy.arange(-7., 7.05, 0.1)
y = numpy.arange(-5., 5.05, 0.05)
from enthought.tvtk.tools import mlab
s = mlab.SurfRegular(x, y, f)
from enthought.mayavi.sources.vtk_data_source import VTKDataSource
d = VTKDataSource()
d.data = s.data
mayavi.add_source(d)
from enthought.mayavi.filters.warp_scalar import WarpScalar
w = WarpScalar()
mayavi.add_filter(w)
from enthought.mayavi.modules.outline import Outline
from enthought.mayavi.modules.surface import Surface
o = Outline()
s = Surface()
mayavi.add_module(o)
mayavi.add_module(s)

# <markdowncell>

# You can run this script by running "mayavi2 -n -x script.py", loading it