Example #1
0
    def __init__(self,
                 meshes,
                 center=True,
                 vmin=None,
                 vmax=None,
                 offset_axis=0,
                 offset_spacing=0.2,
                 contours=None,
                 colormap='RdBu',
                 show_labels=False,
                 actor_options=dict(),
                 offset_axis2=1,
                 offset_spacing2=0.5,
                 label_offset_axis=None,
                 label_offset=1.1,
                 num_columns=None,
                 **kwargs):
        HasTraits.__init__(self)

        if type(meshes) is dict:
            names, verts, tris, weights = list(
                zip(*[(n, v, t, w) for n, (v, t, w) in meshes.items()]))
        elif type(meshes) in [list, tuple]:
            names, verts, tris, weights = [], [], [], []
            for i, mesh in enumerate(meshes):
                # (verts, tris, weights, name)
                verts.append(mesh[0])
                tris.append(mesh[1])
                weights.append(mesh[2])
                if len(mesh) < 4:
                    names.append(str(i))
                else:
                    names.append(mesh[3])
        else:
            raise ValueError('illegal value for parameter "meshes"')

        ## single arrays given?
        #share_verts, share_tris = False, False
        #if type(weights) is np.ndarray and weights.ndim == 2:
        #    weights = [weights]
        #if type(verts) is np.ndarray and verts.ndim == 2:
        #    verts = cycle([verts])
        #    share_verts = True
        #if type(tris) is np.ndarray and tris.ndim == 2:
        #    tris = cycle([tris])
        #    share_tris = True
        #else:
        #    if not share_tris and len(tris) != len(weights):
        #        raise ValueError, "need the same number of weight and triangle arrays"
        #    if not share_verts and len(verts) != len(weights):
        #        raise ValueError, "need the same number of weight and vertex arrays"
        #    if names is not None and len(names) != len(weights):
        #        raise ValueError, "need the same number of weight arrays and names"

        if names is not None:
            assert len(set(names)) == len(names)

        self._weights = list(map(_centered, weights)) if center else weights
        self._verts = verts
        self._tris = tris
        valid_weights = [
            w.shape[-1] - 1 for w in self._weights if w is not None
        ]
        self._max_weight = max(valid_weights) if len(valid_weights) > 0 else 0
        self._names = names
        #self._names = map(str, range(len(self._weights))) if names is None else names
        #if len(weights) == 2:
        #    self.display_all = True

        # visualize each mesh
        self._trimeshes = []
        self._texts = []
        self._offsets = []
        offset = np.zeros(3)
        for i, (verts_i, tris_i, weights_i,
                name_i) in enumerate(zip(verts, tris, weights, names)):
            if i > 0:
                offset[offset_axis] += verts_i[:, offset_axis].ptp() * (
                    1 + offset_spacing)
            if num_columns is not None and i % num_columns == 0:
                offset[offset_axis2] += verts_i[:, offset_axis2].ptp() * (
                    1 + offset_spacing2)
                offset[offset_axis] = 0
            if center:
                vmin, vmax = 0, 1
            else:
                vmin, vmax = vmin, vmax
            # draw mesh
            tm = mlab.triangular_mesh(
                verts_i[:, 0],
                verts_i[:, 1],
                verts_i[:, 2],
                tris_i,
                scalars=weights_i[..., 0] if weights_i is not None
                and not weights_i.dtype == np.uint8 else None,
                colormap=colormap,
                vmin=vmin,
                vmax=vmax,
                figure=self.scene.mayavi_scene)
            if weights_i is None:
                tm.actor.mapper.scalar_visibility = False
            # disable normal splitting
            tm.parent.parent.filter.splitting = False

            if contours is not None and weights_i is not None:
                from mayavi.modules.surface import Surface
                engine = tm.scene.engine
                tm_contour = Surface()
                engine.add_filter(tm_contour, tm.module_manager)
                tm_contour.enable_contours = True
                tm_contour.contour.number_of_contours = contours
                tm_contour.actor.mapper.scalar_visibility = False
                tm_contour.actor.property.set(color=(0.0, 0.0, 0.0),
                                              line_width=4)

                self._trimeshes.append([tm, tm_contour])
            else:
                self._trimeshes.append([tm])

            if show_labels:
                txt = mlab.text(0,
                                0,
                                str(name_i),
                                z=0,
                                color=(0, 0, 0),
                                width=0.12)
                txt.actor.text_scale_mode = 'none'
                txt.property.set(font_size=11, justification='centered')
                self._texts.append(txt)

            #tm.actor.actor.property.edit_traits()
            # for the next mesh, add the extent of the current mesh (plus spacing) to the offset
            self._offsets.append(offset.copy())
            tm.actor.property.set(**actor_options)
            #if handle_points is not None:
            #    h = verts2.ptp()
            #    mlab.points3d(handle_points[:,0], handle_points[:,1], handle_points[:,2], scale_factor=h / 20)

        #actor_prop.edit_traits()
        self.selected_mesh = self._names[0]
        self._label_offset_axis = label_offset_axis
        self._label_offset = label_offset
        if self._label_offset_axis is None:
            self._label_offset_axis = (np.abs(self._offsets[-1]).argmax() +
                                       1) % 3
        self._update_view()
        self._reposition_meshes()
Example #2
0
    def test_script_recording(self):
        "Does script recording work correctly."
        # Create a mayavi pipeline and record it.
        tape = self.tape
        e = NullEngine()
        e.start()
        # Start recording.
        tape.recording = True
        tape.register(e, known=True, script_id='engine')
        e.new_scene()
        self.assertEqual(tape.lines[-1], "dummy_viewer = engine.new_scene()")

        src = ParametricSurface()
        e.add_source(src)
        expect = 'from mayavi.sources.parametric_surface '\
                 'import ParametricSurface'
        self.assertEqual(tape.lines[-3], expect)
        self.assertEqual(tape.lines[-2],
                         "parametric_surface = ParametricSurface()")
        self.assertEqual(tape.lines[-1],
                         "engine.add_source(parametric_surface)")

        src.function = 'dini'
        self.assertEqual(tape.lines[-1],
                         "parametric_surface.function = 'dini'")

        o = Outline()
        e.add_module(o)
        expect = 'from mayavi.modules.outline import Outline'
        self.assertEqual(tape.lines[-3], expect)
        self.assertEqual(tape.lines[-2], "outline = Outline()")
        self.assertEqual(tape.lines[-1], "engine.add_module(outline)")

        o.actor.property.color = (1, 0, 0)
        self.assertEqual(tape.lines[-1],
                         "outline.actor.property.color = (1.0, 0.0, 0.0)")

        s = Surface()
        e.add_module(s)
        expect = 'from mayavi.modules.surface import Surface'
        self.assertEqual(tape.lines[-3], expect)
        self.assertEqual(tape.lines[-2], "surface = Surface()")
        self.assertEqual(tape.lines[-1], "engine.add_module(surface)")

        s.actor.property.representation = 'wireframe'
        self.assertEqual(
            tape.lines[-1],
            "surface.actor.property.representation = 'wireframe'")

        o.actor.property.representation = 'wireframe'
        self.assertEqual(
            tape.lines[-1],
            "outline.actor.property.representation = 'wireframe'")

        s.actor.property.opacity = 0.5
        self.assertEqual(tape.lines[-1],
                         "surface.actor.property.opacity = 0.5")

        s.actor.mapper.scalar_visibility = False
        self.assertEqual(tape.lines[-1],
                         "surface.actor.mapper.scalar_visibility = False")

        # Stop recording and test.
        tape.unregister(e)
        tape.record('#end')  # Placeholder
        o.actor.property.opacity = 0.5
        self.assertEqual(tape.lines[-1], '#end')
        s.actor.property.color = (1, 0, 0)
        self.assertEqual(tape.lines[-1], '#end')
        s.enable_contours = True
        self.assertEqual(tape.lines[-1], '#end')
        src.function = 'klein'
        self.assertEqual(tape.lines[-1], '#end')
Example #3
0
    def test_script_recording(self):
        "Does script recording work correctly."
        # Create a mayavi pipeline and record it.
        tape = self.tape
        e = NullEngine()
        e.start()
        # Start recording.
        tape.recording = True
        tape.register(e, known=True, script_id='engine')
        e.new_scene()
        #print tape.script
        self.assertEqual(tape.lines[-1],
                         "dummy_viewer = engine.new_scene()")

        src = ParametricSurface()
        e.add_source(src)
        expect = 'from mayavi.sources.parametric_surface '\
                 'import ParametricSurface'
        self.assertEqual(tape.lines[-3], expect)
        self.assertEqual(tape.lines[-2],
                         "parametric_surface = ParametricSurface()")
        self.assertEqual(tape.lines[-1],
                         "engine.add_source(parametric_surface)")

        src.function = 'dini'
        self.assertEqual(tape.lines[-1],
                         "parametric_surface.function = 'dini'")

        o = Outline()
        e.add_module(o)
        expect = 'from mayavi.modules.outline import Outline'
        self.assertEqual(tape.lines[-3], expect)
        self.assertEqual(tape.lines[-2], "outline = Outline()")
        self.assertEqual(tape.lines[-1],
                         "engine.add_module(outline)")

        o.actor.property.color = (1,0,0)
        self.assertEqual(tape.lines[-1],
                         "outline.actor.property.color = (1.0, 0.0, 0.0)")

        s = Surface()
        e.add_module(s)
        expect = 'from mayavi.modules.surface import Surface'
        self.assertEqual(tape.lines[-3], expect)
        self.assertEqual(tape.lines[-2], "surface = Surface()")
        self.assertEqual(tape.lines[-1],
                         "engine.add_module(surface)")

        s.actor.property.representation = 'wireframe'
        self.assertEqual(tape.lines[-1],
                         "surface.actor.property.representation = 'wireframe'")

        o.actor.property.representation = 'wireframe'
        self.assertEqual(tape.lines[-1],
                         "outline.actor.property.representation = 'wireframe'")

        s.actor.property.opacity = 0.5
        self.assertEqual(tape.lines[-1],
                         "surface.actor.property.opacity = 0.5")

        s.actor.mapper.scalar_visibility = False
        self.assertEqual(tape.lines[-1],
                         "surface.actor.mapper.scalar_visibility = False")

        #print tape.script

        # Stop recording and test.
        tape.unregister(e)
        tape.record('#end') # Placeholder
        o.actor.property.opacity = 0.5
        self.assertEqual(tape.lines[-1], '#end')
        s.actor.property.color = (1,0,0)
        self.assertEqual(tape.lines[-1], '#end')
        s.enable_contours = True
        self.assertEqual(tape.lines[-1], '#end')
        src.function = 'klein'
        self.assertEqual(tape.lines[-1], '#end')
Example #4
0
    def __init__(self, meshes, center=True, vmin=None, vmax=None, offset_axis=0, offset_spacing=0.2, contours=None, colormap='RdBu', show_labels=False, actor_options=dict(), offset_axis2=1, offset_spacing2=0.5, label_offset_axis=None, label_offset=1.1, num_columns=None, **kwargs):
        HasTraits.__init__(self)

        if type(meshes) is dict:
            names, verts, tris, weights = zip(*[(n, v, t, w) for n, (v, t, w) in meshes.iteritems()])
        elif type(meshes) in [list, tuple]:
            names, verts, tris, weights = [], [], [], []
            for i, mesh in enumerate(meshes):
                # (verts, tris, weights, name)
                verts.append(mesh[0])
                tris.append(mesh[1])
                weights.append(mesh[2])
                if len(mesh) < 4:
                    names.append(str(i))
                else:
                    names.append(mesh[3])
        else:
            raise ValueError, 'illegal value for parameter "meshes"'

        ## single arrays given?
        #share_verts, share_tris = False, False
        #if type(weights) is np.ndarray and weights.ndim == 2:
        #    weights = [weights]
        #if type(verts) is np.ndarray and verts.ndim == 2:
        #    verts = cycle([verts])
        #    share_verts = True
        #if type(tris) is np.ndarray and tris.ndim == 2:
        #    tris = cycle([tris])
        #    share_tris = True
        #else:
        #    if not share_tris and len(tris) != len(weights):
        #        raise ValueError, "need the same number of weight and triangle arrays"
        #    if not share_verts and len(verts) != len(weights):
        #        raise ValueError, "need the same number of weight and vertex arrays"
        #    if names is not None and len(names) != len(weights):
        #        raise ValueError, "need the same number of weight arrays and names"

        if names is not None:
            assert len(set(names)) == len(names)

        self._weights = map(_centered, weights) if center else weights
        self._verts = verts
        self._tris = tris
        valid_weights = [w.shape[-1] - 1 for w in self._weights if w is not None]
        self._max_weight = max(valid_weights) if len(valid_weights) > 0 else 0
        self._names = names
        #self._names = map(str, range(len(self._weights))) if names is None else names
        #if len(weights) == 2:
        #    self.display_all = True

        # visualize each mesh
        self._trimeshes = []
        self._texts = []
        self._offsets = []
        offset = np.zeros(3)
        for i, (verts_i, tris_i, weights_i, name_i) in enumerate(zip(verts, tris, weights, names)):
            if i > 0:
                offset[offset_axis] += verts_i[:,offset_axis].ptp() * (1 + offset_spacing)
            if num_columns is not None and i % num_columns == 0:
                offset[offset_axis2] += verts_i[:, offset_axis2].ptp() * (1 + offset_spacing2)
                offset[offset_axis] = 0
            if center:
                vmin, vmax = 0, 1
            else:
                vmin, vmax = vmin, vmax
            # draw mesh
            tm = mlab.triangular_mesh(
                verts_i[:,0], verts_i[:,1], verts_i[:,2], tris_i, 
                scalars=weights_i[...,0] if weights_i is not None and not weights_i.dtype == np.uint8 else None, 
                colormap=colormap,
                vmin=vmin, vmax=vmax,
                figure=self.scene.mayavi_scene)
            if weights_i is None:
                tm.actor.mapper.scalar_visibility = False
            # disable normal splitting
            tm.parent.parent.filter.splitting = False

            if contours is not None and weights_i is not None:
                from mayavi.modules.surface import Surface
                engine = tm.scene.engine
                tm_contour = Surface()
                engine.add_filter(tm_contour, tm.module_manager)
                tm_contour.enable_contours = True
                tm_contour.contour.number_of_contours = contours
                tm_contour.actor.mapper.scalar_visibility = False
                tm_contour.actor.property.set(color = (0.0, 0.0, 0.0), line_width=4)

                self._trimeshes.append([tm, tm_contour])
            else:
                self._trimeshes.append([tm])

            if show_labels:
                txt = mlab.text(0, 0, str(name_i), z=0, color=(0, 0, 0), width=0.12)
                txt.actor.text_scale_mode = 'none'
                txt.property.set(font_size=11, justification='centered')
                self._texts.append(txt)


            #tm.actor.actor.property.edit_traits()
            # for the next mesh, add the extent of the current mesh (plus spacing) to the offset
            self._offsets.append(offset.copy())
            tm.actor.property.set(**actor_options)
            #if handle_points is not None:
            #    h = verts2.ptp()
            #    mlab.points3d(handle_points[:,0], handle_points[:,1], handle_points[:,2], scale_factor=h / 20)

        #actor_prop.edit_traits()
        self.selected_mesh = self._names[0]
        self._label_offset_axis = label_offset_axis
        self._label_offset = label_offset
        if self._label_offset_axis is None:
            self._label_offset_axis = (np.abs(self._offsets[-1]).argmax() + 1) % 3
        self._update_view()
        self._reposition_meshes()
Example #5
0
from numpy import array
from mayavi.modules.axes import Axes
from mayavi.api import Engine
from mayavi.modules.surface import Surface
from mayavi.tools.show import show

try:
    engine = mayavi.engine
except NameError:
    engine = Engine()
    engine.start()
if len(engine.scenes) == 0:
    engine.new_scene()

scene = engine.scenes[0]
vtk_file_reader = engine.open(sys.argv[1], scene)
axes = Axes()
axes.property.color = (0.0, 0.0, 0.0)
engine.add_filter(axes, vtk_file_reader)
surface = Surface()
engine.add_filter(surface, vtk_file_reader)
scene.scene.background = (1.0, 1.0, 1.0)
scene.scene.foreground = (0.0, 0.0, 0.0)
surface.contour.contours = [1.5]
surface.actor.mapper.progress = 1.0
surface.actor.mapper.scalar_range = array([ 0.,  3.])
surface.enable_contours = True

show()