Exemplo n.º 1
0
def add_text(text,
             pos,
             angle=0,
             fontName=None,
             fontSize=9,
             color='k',
             bgcolor=None,
             axes=None):
    '''
    Adds a text in the world space. Returns the Text object.
    Parameters:
    text    - String. The text of the label
    pos     - Tuple with two or three numbers. The (x,y,z) position of the text in
              world space.
    angle   - Float or int. The rotation of the label in degrees.
    fontname- String. Either 'mono', 'sans' or 'serif'.
    fontSize- Int. Size of the text. Default 9.
    color   - A 3-tuple or a character in 'rgbycmkw', etc that defines text color.
              Default 'k' (black).
    bgcolor - Background color. See color. Default None.
    axes    - Axes wherein the label is placed. If None then the current axes is 
              chosen.
    '''
    if axes is None:
        axes = vv.gca()
    text = vv.Text(axes,
                   text,
                   *pos,
                   fontName=fontName,
                   fontSize=fontSize,
                   color=color)
    text.bgcolor = bgcolor
    text.textAngle = angle
    return text
Exemplo n.º 2
0
    def putText(self,
                figureName,
                text,
                pos=(0, 0),
                size=10,
                color=(255, 255, 255),
                font='sans'):
        '''
		Fonts: 'mono', 'sans' or 'serif'
		Color: Can be character (e.g. 'r', 'g', 'k') or 3-element tuple

		Notes: 
		*This draws text onto the canvas and not the image.
		*You can use symbols (e.g. \leftarrow) and greek letters (e.g. \alpha, \omega,...)
		*Bold, italics, superscript, and subscript: \b{Text}, \i{Text}, \sup^{Text}, \sub_{Text}

		See here for examples and formatting: 
		*http://code.google.com/p/visvis/wiki/example_text		
		*http://code.google.com/p/visvis/wiki/Text
		'''
        # embed()
        win = self._getWindow(figureName)
        win['canvas'].GetFigure().MakeCurrent()
        win['text'].append(
            vv.Text(win['canvas'].GetAxes(),
                    text=text,
                    x=pos[0],
                    y=pos[1],
                    fontSize=size,
                    fontName=font,
                    color=color))
Exemplo n.º 3
0
def plot_reference_sphere(theta=0,
                          phi=0,
                          isometric=True,
                          ax=None,
                          azimuth=None,
                          elevation=None,
                          degrees=True,
                          labels=True,
                          light_ambient=.6,
                          zoom=1.4,
                          arrow_color=(.25, .95, .8),
                          close_figure=False):

    if azimuth is None:
        azimuth = DEFAULT_AZIMUTH
    if elevation is None:
        elevation = DEFAULT_ELEVATION

    import visvis as vv

    if ax is None:
        app = vv.use()
        fig = vv.figure()
        ax = vv.subplot(111)

    else:
        app = None
        fig = ax.GetFigure()

    ax.axis.visible = 0
    ax.axis.xLabel = 'x'
    ax.axis.yLabel = 'y'
    ax.axis.zLabel = 'z'

    # coordinate system
    length = 1.4
    cyl_diameter = .05
    for i in range(3):
        direction = np.zeros((3, ))
        direction[i] = 1
        cyl = vv.solidCylinder(translation=(0, 0, 0),
                               scaling=(cyl_diameter, cyl_diameter, length),
                               direction=tuple(direction),
                               axesAdjust=False,
                               axes=ax)
        cyl.faceColor = (.75, .75, .75)

        translation = np.zeros((3, ))
        translation[i] = length
        cone = vv.solidCone(translation=tuple(translation),
                            scaling=(.1, .1, .2),
                            direction=tuple(direction),
                            axesAdjust=False,
                            axes=ax)
        cone.faceColor = (.75, .75, .75)

    # example direction
    length = 1
    shrink = .825
    direction = sph2cart(1, theta, phi, degrees=degrees).ravel()
    cyl = vv.solidCylinder(translation=(0, 0, 0),
                           scaling=(.05, .05, shrink * length),
                           direction=tuple(direction),
                           axesAdjust=False,
                           axes=ax)
    cyl.faceColor = arrow_color

    translation = direction * shrink
    cone = vv.solidCone(translation=tuple(translation),
                        scaling=(.1, .1, .2),
                        direction=tuple(direction),
                        axesAdjust=False,
                        axes=ax)
    cone.faceColor = arrow_color

    # indicate unit sphere
    sphere = vv.solidSphere((0, 0, 0), N=100, M=100)
    sphere.faceColor = (.5, .5, .5, .25)

    # some lines on sphere indicating main axes
    phi = np.linspace(0, 2 * np.pi, 100)
    theta = np.ones_like(phi) * np.pi / 2.
    r = np.ones_like(phi)
    xyz = sph2cart(r, theta, phi, degrees=False)
    vv.plot(xyz[:, 0],
            xyz[:, 1],
            xyz[:, 2],
            lw=1,
            lc=(.5, .5, .5),
            ls="-",
            mc='b',
            axesAdjust=False,
            axes=ax)

    theta = np.linspace(-np.pi, np.pi, 100)
    phi = np.ones_like(theta) * 0
    r = np.ones_like(phi)
    xyz = sph2cart(r, theta, phi, degrees=False)
    vv.plot(xyz[:, 0],
            xyz[:, 1],
            xyz[:, 2],
            lw=1,
            lc=(.5, .5, .5),
            ls="-",
            mc='b',
            axesAdjust=False,
            axes=ax)

    theta = np.linspace(-np.pi, np.pi, 100)
    phi = np.ones_like(theta) * np.pi / 2.
    r = np.ones_like(phi)
    xyz = sph2cart(r, theta, phi, degrees=False)
    vv.plot(xyz[:, 0],
            xyz[:, 1],
            xyz[:, 2],
            lw=1,
            lc=(.5, .5, .5),
            ls="-",
            mc='b',
            axesAdjust=False,
            axes=ax)

    # add pitch and roll axes
    aa = np.deg2rad(np.linspace(45, 315, 100) - 90)
    r = .25 + .025
    d = 1.25 + .05
    color = (.25, .25, .25)

    # pitch rotation (in x/z plane, i.e. around y-axis)
    xx = r * np.cos(aa)
    zz = r * np.sin(aa)
    yy = d * np.ones_like(xx)
    vv.plot(xx, yy, zz, lw=5, lc=color, ls="-", axesAdjust=False, axes=ax)

    translation = (xx[0], yy[0], zz[0])
    direction = (xx[0] - xx[1], yy[0] - yy[1], zz[0] - zz[1])
    cone = vv.solidCone(translation=translation,
                        scaling=(.05, .05, .1),
                        direction=direction,
                        axesAdjust=False,
                        axes=ax)
    cone.faceColor = color

    if labels:
        vv.Text(ax, 'Pitch', x=0, y=1.25 * d, z=.25, fontSize=28, color=color)

    # roll rotation (in y/z plane, i.e. around x-axis)
    yy = r * np.cos(aa)
    zz = r * np.sin(aa)
    xx = d * np.ones_like(xx)
    vv.plot(xx, yy, zz, lw=5, lc=color, ls="-", axesAdjust=False, axes=ax)

    translation = (xx[-1], yy[-1], zz[-1])
    direction = (xx[-1] - xx[-2], yy[-1] - yy[-2], zz[-1] - zz[-2])
    cone = vv.solidCone(translation=translation,
                        scaling=(.05, .05, .1),
                        direction=direction,
                        axesAdjust=False,
                        axes=ax)
    cone.faceColor = color

    if labels:
        vv.Text(ax, 'Roll', x=1.25 * d, y=-.8, z=0, fontSize=28, color=color)

    # set camera view
    zoom_ = vv.view()['zoom']
    if isometric:
        vv.view(dict(azimuth=90 + ISO_AZIMUTH, elevation=ISO_ELEVATION),
                zoom=zoom * zoom_,
                axes=ax)
    else:
        vv.view(dict(azimuth=90 + azimuth, elevation=elevation),
                zoom=zoom * zoom_,
                _axes=ax)

    ax.light0.ambient = light_ambient
    ax.light0.specular = .5

    fig.DrawNow()

    if app is not None:
        app.ProcessEvents()

    img = vv.screenshot(None, ob=ax, sf=2, bg=None, format=None)

    if close_figure:
        vv.close(fig)
        fig = None

    return fig, img
Exemplo n.º 4
0
def plot_density_sphere(xyz_centers,
                        H,
                        ax=None,
                        method='hist',
                        azimuth=None,
                        elevation=None,
                        backend='visvis',
                        oversample=1,
                        smoothing=None,
                        zoom=1.7,
                        cmap='jet',
                        scaling='log',
                        log_offset=-.1,
                        clim=None,
                        isometric=False,
                        light_ambient=.6,
                        light_specular=.5,
                        avg_direction=None,
                        pitch_label=True,
                        roll_label=True,
                        pitch_arrow=True,
                        roll_arrow=True,
                        arrow_color=(.25, .95, .8),
                        close_figure=False):

    if azimuth is None:
        azimuth = DEFAULT_AZIMUTH
    if elevation is None:
        elevation = DEFAULT_ELEVATION

    scaling = scaling.lower()
    if scaling.startswith('log'):
        H = H / float(H.sum())
        v = H > 0
        if scaling == 'log':
            H[v] = np.log(H[v])
        elif scaling == 'log2':
            H[v] = np.log2(H[v])
        H[~v] = H[v].min() + log_offset

    if smoothing is not None and smoothing > 1:
        x = np.linspace(-3., 3., smoothing)
        xx, yy = np.meshgrid(x, x)
        G = np.exp((-xx**2 - yy**2))
        H = signal.convolve2d(H, G / G.sum(), mode='same', boundary='wrap')

    if backend in ['mpl', 'matplotlib']:

        if ax is None:
            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')

        from matplotlib.colors import LightSource
        ls = LightSource(azdeg=315, altdeg=45)
        cm = getattr(plt.cm, cmap)
        colors = ls.shade(H, cmap=cm, blend_mode='soft', vert_exag=1)
        ax.plot_surface(xyz_centers[:, 0].reshape(H),
                        xyz_centers[:, 1].reshape(H),
                        xyz_centers[:, 2].reshape(H),
                        cstride=1,
                        rstride=1,
                        facecolors=colors,
                        linewidth=0,
                        antialiased=False,
                        shade=False)

        # add arrows in front of sphere
        import mousecam_helpers as helpers
        arrow_props = dict(arrowstyle='simple',
                           mutation_scale=15,
                           mutation_aspect=None,
                           linewidth=.5,
                           facecolor=3 * [.75],
                           edgecolor=3 * [.1])
        length = .6

        arr = helpers.Arrow3D((1, 1 + length), (0, 0), (0, 0), **arrow_props)
        ax.add_artist(arr)

        arr = helpers.Arrow3D((0, 0), (1, 1 + length), (0, 0), **arrow_props)
        ax.add_artist(arr)

        arr = helpers.Arrow3D((0, 0), (0, 0), (1, 1 + length), **arrow_props)
        ax.add_artist(arr)

        extents = 3 * [[-.6, .6]]
        ax.auto_scale_xyz(*extents)
        ax.set_aspect('equal')
        ax.axis('off')

        ax.view_init(elev=elevation, azim=360 - azimuth)

    elif backend in ['mayavi', 'mlab']:

        from mayavi import mlab

        fig = mlab.figure(bgcolor=(1, 1, 1), size=(1000, 1000))
        fig.scene.parallel_projection = True

        mlab.mesh(xyz_centers[:, 0].reshape(H.shape),
                  xyz_centers[:, 1].reshape(H.shape),
                  xyz_centers[:, 2].reshape(H.shape),
                  scalars=H,
                  colormap='jet')

        from tvtk.tools import visual
        visual.set_viewer(fig)
        arrow_kw = dict(color=(.75, .75, .75),
                        length_cone=.1,
                        radius_cone=.05,
                        radius_shaft=.025)
        Arrow3D(0, 0, 0, 1.4, 0, 0, **arrow_kw)
        Arrow3D(0, 0, 0, 0, 1.4, 0, **arrow_kw)
        Arrow3D(0, 0, 0, 0, 0, 1.4, **arrow_kw)

        if isometric:
            fig.scene.isometric_view()
        else:
            mlab.view(azimuth=-azimuth, elevation=elevation, figure=fig)
        fig.scene.camera.zoom(zoom)

        ax = mlab.screenshot(figure=fig, mode='rgb', antialiased=False)

    elif backend in ['visvis']:

        import visvis as vv

        app = vv.use()

        fig = vv.figure()
        ax = vv.subplot(111)

        ax.axis.visible = 0
        ax.axis.xLabel = 'x'
        ax.axis.yLabel = 'y'
        ax.axis.zLabel = 'z'

        length = 1.4

        for i in range(3):
            direction = np.zeros((3, ))
            direction[i] = 1
            cyl = vv.solidCylinder(translation=(0, 0, 0),
                                   scaling=(.05, .05, length),
                                   direction=tuple(direction),
                                   axesAdjust=False,
                                   axes=ax)
            cyl.faceColor = (.75, .75, .75)

            translation = np.zeros((3, ))
            translation[i] = length
            cone = vv.solidCone(translation=tuple(translation),
                                scaling=(.1, .1, .2),
                                direction=tuple(direction),
                                axesAdjust=False,
                                axes=ax)
            cone.faceColor = (.75, .75, .75)

        surf = vv.surf(xyz_centers[:, 0].reshape(H.shape),
                       xyz_centers[:, 1].reshape(H.shape),
                       xyz_centers[:, 2].reshape(H.shape),
                       H,
                       axes=ax)

        # set colormap
        cmap = cmap.lower()
        if cmap.endswith('_r'):
            cm = vv.colormaps[cmap[:-2]]
            cm = cm[::-1]
        else:
            cm = vv.colormaps[cmap]
        surf.colormap = cm

        if clim is not None:
            # apply colormap limits
            surf.clim = clim


#            ax.Draw()

# add labels to indicate pitch and/or roll axes
        aa = np.deg2rad(np.linspace(45, 315, 100) - 90)
        r = .25 + .05
        d = 1.25 + .25
        color = (.25, .25, .25)

        if pitch_arrow:
            # pitch rotation (in x/z plane, i.e. around y-axis)
            xx = r * np.cos(aa)
            zz = r * np.sin(aa)
            yy = d * np.ones_like(xx)
            vv.plot(xx,
                    yy,
                    zz,
                    lw=5,
                    lc=color,
                    ls="-",
                    axesAdjust=False,
                    axes=ax)

            translation = (xx[0], yy[0], zz[0])
            direction = (xx[0] - xx[1], yy[0] - yy[1], zz[0] - zz[1])
            cone = vv.solidCone(translation=translation,
                                scaling=(.05, .05, .1),
                                direction=direction,
                                axesAdjust=False,
                                axes=ax)
            cone.faceColor = color

        if pitch_label:
            vv.Text(ax, 'Pitch', x=0, y=.9 * d, z=.5, fontSize=28, color=color)

        if roll_arrow:
            # roll rotation (in y/z plane, i.e. around x-axis)
            yy = r * np.cos(aa[::-1])
            zz = r * np.sin(aa[::-1])
            xx = d * np.ones_like(xx)
            vv.plot(xx,
                    yy,
                    zz,
                    lw=5,
                    lc=color,
                    ls="-",
                    axesAdjust=False,
                    axes=ax)

            translation = (xx[0], yy[0], zz[0])
            direction = (xx[0] - xx[1], yy[0] - yy[1], zz[0] - zz[1])
            cone = vv.solidCone(translation=translation,
                                scaling=(.05, .05, .1),
                                direction=direction,
                                axesAdjust=False,
                                axes=ax)
            cone.faceColor = color

        if roll_label:
            vv.Text(ax,
                    'Roll',
                    x=1.25 * d,
                    y=-.8,
                    z=0,
                    fontSize=28,
                    color=color)

        if avg_direction is not None:
            # indicate direction of avg head orientation
            avg_direction = avg_direction / np.sqrt(np.sum(avg_direction**2))
            avg_direction *= length
            cyl = vv.solidCylinder(translation=(0, 0, 0),
                                   scaling=(.05, .05, length),
                                   direction=tuple(avg_direction),
                                   axesAdjust=False,
                                   axes=ax)
            cyl.faceColor = arrow_color

            cone = vv.solidCone(translation=tuple(avg_direction),
                                scaling=(.1, .1, .2),
                                direction=tuple(avg_direction),
                                axesAdjust=False,
                                axes=ax)
            cone.faceColor = arrow_color

        zoom_ = vv.view()['zoom']
        if isometric:
            vv.view(dict(azimuth=90 + ISO_AZIMUTH, elevation=ISO_ELEVATION),
                    zoom=zoom_ * zoom,
                    axes=ax)
        else:
            vv.view(dict(azimuth=90 + azimuth, elevation=elevation),
                    zoom=zoom * zoom_,
                    axes=ax)

        ax.light0.ambient = light_ambient
        ax.light0.specular = light_specular

        fig.DrawNow()
        app.ProcessEvents()

        img = vv.screenshot(None, ob=ax, sf=2, bg=None, format=None)
        ax = img

        if close_figure:
            vv.close(fig)
            fig = None

    return fig, ax
Exemplo n.º 5
0
#!/usr/bin/env python
""" This example illustrate using text and formatting for text
world objects and labels.
"""

import visvis as vv

# Create figure and figure
fig = vv.figure()
a = vv.cla()
a.cameraType = '2d'
a.daspectAuto = True
a.SetLimits((0, 8), (-1, 10))

# Create text inside the axes
vv.Text(a, 'These are texts living in the scene:', 1, 3)
vv.Text(a, 'Text can be made \b{bold} easil\by!', 1, 2)
vv.Text(a, 'Text can be made \i{italic} easil\iy!', 1, 1)

# Create text labels
label0 = vv.Label(a, 'These are texts in widget coordinates:')
label0.position = 10, 20
label1 = vv.Label(a, 'Sub_{script} and super^{script} are easy as pi^2.')
label1.position = 10, 40
label2 = vv.Label(a, u'You can use many Unicode characters: \\u0183 = \u0183')
label2.position = 10, 60
label3 = vv.Label(
    a, 'And can use many Latex like commands: \\alpha \\Alpha' +
    '\\approx, \sigma, \pi, ')
label3.position = 10, 80
Exemplo n.º 6
0
"""

import visvis as vv

# Define a piece of Unicode text in a py2.x py3.x compatible manner
hello = u'Привет пустошь'

# Create figure and figure
fig = vv.figure()
a = vv.cla()
a.cameraType = '2d'
a.daspectAuto = True
a.SetLimits((0, 8), (-1, 10))

# Create text inside the axes
t1 = vv.Text(a, 'Visvis text', 0.2, 9, 0, 'mono', 30)
t2 = vv.Text(a, '... with FreeType!', 1, 8, 0, 'serif', 12)
t3 = vv.Text(a, '... and Unicode: %s!' % hello, 1, 7)
t3 = vv.Text(
    a, '\Gamma\rho\epsilon\epsilon\kappa letters and ' +
    ' \rightarrow math \otimes symbols', 1, 6)

t2 = vv.Text(
    a, '\b{bold}, \i{italic}, and \b{\i{bolditalic}} \bfon\its' +
    ' and sup^{script} and sub_{script}', 1, 5, 0, 'serif')
t3 = vv.Text(a, 'Look, I\'m at an angle!', 1, 4)
t3.textAngle = -20
t3.fontSize = 12

# Create text labels
label1 = vv.Label(a, 'This is a Label')