Exemple #1
0
def double_pendulum(theta, length, mass):
    gr.clearws()
    gr.setviewport(0, 1, 0, 1)

    direction = []
    position = [(0, 0, 0)]
    for i in range(2):
        direction.append(
            (sin(theta[i]) * length[i] * 2, -cos(theta[i]) * length[i] * 2, 0))
        position.append([position[-1][j] + direction[-1][j] for j in range(3)])

    gr3.clear()
    # draw pivot point
    gr3.drawcylindermesh(1, (0, 0.2, 0), (0, 1, 0), (0.4, 0.4, 0.4), 0.4, 0.05)
    gr3.drawcylindermesh(1, (0, 0.2, 0), (0, -1, 0), (0.4, 0.4, 0.4), 0.05,
                         0.2)
    gr3.drawspheremesh(1, (0, 0, 0), (0.4, 0.4, 0.4), 0.05)
    # draw rods
    gr3.drawcylindermesh(2, position, direction, (0.6, 0.6, 0.6) * 2,
                         (0.05, 0.05), [l * 2 for l in length])
    # draw bobs
    gr3.drawspheremesh(2, position[1:], (1, 1, 1) * 2, [m * 0.2 for m in mass])

    gr3.drawimage(0, 1, 0, 1, 500, 500, gr3.GR3_Drawable.GR3_DRAWABLE_GKS)
    gr.updatews()
    return
Exemple #2
0
    def draw_image(self):
        if not self.needs_refresh:
            return
        self.needs_refresh = False
        w, h = (self.w, self.h)
        clearws()
        setwindow(0, self.w, 0, self.h)
        setviewport(0, 1, 0, 1)

        setbackgroundcolor(1, 1, 1, 0)
        vertices, normals = triangulate(data, \
          (1.0/64, 1.0/64, 1.0/128), (-0.5, -0.5, -0.5), self.isolevel)
        mesh = createmesh(len(vertices)*3, vertices, normals, \
          ones(vertices.shape))
        drawmesh(mesh, 1, (0,0,0), (0,0,1), (0,1,0), (1,1,1), (1,1,1))
        center = spherical_to_cartesian(-2, pi*self.y/self.h+pi/2, pi*self.x/self.w)
        up = spherical_to_cartesian(1, pi*self.y/self.h+pi, pi*self.x/self.w)
        cameralookat(center[0], center[1], -0.25+center[2], 0, 0, -0.25, up[0], up[1], up[2])
        drawimage(0, self.w, 0, self.h, \
          self.w, self.h, GR3_Drawable.GR3_DRAWABLE_GKS)
        if self.export:
            export("mri.html", 800, 800)
            print("Saved current isosurface to mri.html")
            self.export = False
        clear()
        deletemesh(c_int(mesh.value))
Exemple #3
0
    def draw_image(self):
        w, h = (self.w, self.h)
        clearws()
        setwindow(0, self.w, 0, self.h)
        setviewport(0, 1, 0, 1)

        setbackgroundcolor(1, 1, 1, 0)
        vertices, normals = triangulate(data, \
          (1.0/64, 1.0/64, 1.0/128), (-0.5, -0.5, -0.5), self.isolevel)
        mesh = createmesh(len(vertices)*3, vertices, normals, \
          ones(vertices.shape))
        drawmesh(mesh, 1, (0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 1),
                 (1, 1, 1))
        center = spherical_to_cartesian(-2, pi * self.y / self.h + pi / 2,
                                        pi * self.x / self.w)
        up = spherical_to_cartesian(1, pi * self.y / self.h + pi,
                                    pi * self.x / self.w)
        cameralookat(center[0], center[1], -0.25 + center[2], 0, 0, -0.25,
                     up[0], up[1], up[2])
        drawimage(0, self.w, 0, self.h, \
          self.w, self.h, GR3_Drawable.GR3_DRAWABLE_GKS)
        if self.export:
            export("mri.html", 800, 800)
            print("Saved current isosurface to mri.html")
            self.export = False
        clear()
        deletemesh(c_int(mesh.value))
Exemple #4
0
    def draw_image(self):
        if not self.needs_refresh:
            return
        self.needs_refresh = False
        gr.clearws()
        gr.setwindow(0, self.w, 0, self.h)
        gr.setviewport(0, 1, 0, 1)

        gr3.setbackgroundcolor(1, 1, 1, 0)
        vertices, normals = gr3.triangulate(data,
                                            (1.0 / 64, 1.0 / 64, 1.0 / 128),
                                            (-0.5, -0.5, -0.5), self.isolevel)
        mesh = gr3.createmesh(
            len(vertices) * 3, vertices, normals, np.ones(vertices.shape))
        gr3.drawmesh(mesh, 1, (0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 1),
                     (1, 1, 1))
        center = spherical_to_cartesian(-2,
                                        np.pi * self.y / self.h + np.pi / 2,
                                        np.pi * self.x / self.w)
        up = spherical_to_cartesian(1, np.pi * self.y / self.h + np.pi,
                                    np.pi * self.x / self.w)
        gr3.cameralookat(center[0], center[1], -0.25 + center[2], 0, 0, -0.25,
                         up[0], up[1], up[2])
        gr3.drawimage(0, self.w, 0, self.h, self.w, self.h,
                      gr3.GR3_Drawable.GR3_DRAWABLE_GKS)
        if self.export:
            gr3.export("mri.html", 800, 800)
            print("Saved current isosurface to mri.html")
            self.export = False
        gr3.clear()
        gr3.deletemesh(c_int(mesh.value))
Exemple #5
0
def draw(mesh, x=None, y=None, z=None):
    gr3.clear()
    gr3.drawmesh(mesh, 1, (0,0,0), (0,0,1), (0,1,0), (1,1,1), (1,1,1))
    gr3.drawslicemeshes(data,  x=x, y=y, z=z)
    gr.clearws()
    gr3.drawimage(0, 1, 0, 1, 500, 500, gr3.GR3_Drawable.GR3_DRAWABLE_GKS)
    gr.updatews()
Exemple #6
0
def draw(mesh, x=None, y=None, z=None):
    gr3.clear()
    gr3.drawmesh(mesh, 1, (0, 0, 0), (0, 0, 1), (0, 1, 0), (1, 1, 1),
                 (1, 1, 1))
    gr3.drawslicemeshes(data, x=x, y=y, z=z)
    gr.clearws()
    gr3.drawimage(0, 1, 0, 1, 500, 500, gr3.GR3_Drawable.GR3_DRAWABLE_GKS)
    gr.updatews()
Exemple #7
0
def _plot_iso(v):
    global _plt
    viewport = _plt.kwargs['viewport']
    if viewport[3] - viewport[2] < viewport[1] - viewport[0]:
        width = viewport[3] - viewport[2]
        center_x = 0.5 * (viewport[0] + viewport[1])
        x_min = max(center_x - 0.5 * width, viewport[0])
        x_max = min(center_x + 0.5 * width, viewport[1])
        y_min = viewport[2]
        y_max = viewport[3]
    else:
        height = viewport[1] - viewport[0]
        center_y = 0.5 * (viewport[2] + viewport[3])
        x_min = viewport[0]
        x_max = viewport[1]
        y_min = max(center_y - 0.5 * height, viewport[2])
        y_max = min(center_y + 0.5 * height, viewport[3])

    gr.selntran(0)
    usable_vs = v[np.abs(v) != np.inf]
    if np.prod(usable_vs.shape) == 0:
        return
    v_max = usable_vs.max()
    v_min = usable_vs.min()
    if v_min == v_max:
        return
    uint16_max = np.iinfo(np.uint16).max
    v = (np.clip(v, v_min, v_max) - v_min) / (v_max - v_min) * uint16_max
    values = v.astype(np.uint16)
    nx, ny, nz = v.shape
    isovalue = _plt.kwargs.get('isovalue', 0.5)
    rotation = np.radians(_plt.kwargs.get('rotation', 40))
    tilt = np.radians(_plt.kwargs.get('tilt', 70))
    gr3.clear()
    mesh = gr3.createisosurfacemesh(values,
                                    (2 / (nx - 1), 2 / (ny - 1), 2 / (nz - 1)),
                                    (-1., -1., -1.),
                                    int(isovalue * uint16_max))
    color = _plt.kwargs.get('color', (0.0, 0.5, 0.8))
    gr3.setbackgroundcolor(1, 1, 1, 0)
    gr3.drawmesh(mesh, 1, (0, 0, 0), (0, 0, 1), (0, 1, 0), color, (1, 1, 1))
    r = 2.5
    gr3.cameralookat(r * np.sin(tilt) * np.sin(rotation), r * np.cos(tilt),
                     r * np.sin(tilt) * np.cos(rotation), 0, 0, 0, 0, 1, 0)
    gr3.drawimage(x_min, x_max, y_min, y_max, 500, 500,
                  gr3.GR3_Drawable.GR3_DRAWABLE_GKS)
    gr3.deletemesh(mesh)
    gr.selntran(1)
Exemple #8
0
def pendulum(t, theta, omega, acceleration):
    gr.clearws()
    gr.setviewport(0, 1, 0, 1)

    x, y = (sin(theta) * 3.0, -cos(theta) * 3.0)

    gr3.clear()
    # draw pivot point
    gr3.drawspheremesh(1, (0, 0, 0), (0.4, 0.4, 0.4), 0.1)
    # draw rod
    gr3.drawcylindermesh(1, (0, 0, 0), (x, y, 0), (0.6, 0.6, 0.6), 0.05, 3.0)
    # draw sphere
    gr3.drawspheremesh(1, (x, y, 0), (1, 1, 1), 0.25)
    # show angular velocity
    V = 0.3 * omega - sign(omega) * 0.15
    gr3.drawcylindermesh(1, (x, y, 0), (cos(theta), sin(theta), 0), (0, 0, 1),
                         0.05, V)
    gr3.drawconemesh(1, (x + cos(theta) * V, y + sin(theta) * V, 0),
                     (-y, x, 0), (0, 0, 1), 0.1,
                     sign(omega) * 0.25)
    # show angular acceleration
    A = 0.3 * acceleration
    gr3.drawcylindermesh(1, (x, y, 0), (sin(theta), cos(theta), 0), (1, 0, 0),
                         0.05, A)
    gr3.drawconemesh(1, (x + sin(theta) * A, y + cos(theta) * A, 0),
                     (x, -y, 0), (1, 0, 0), 0.1, 0.25)
    # draw GR3 objects
    gr3.drawimage(0, 1, 0.15, 0.85, 500, 350,
                  gr3.GR3_Drawable.GR3_DRAWABLE_GKS)

    gr.settextfontprec(2, gr.TEXT_PRECISION_STRING)
    gr.setcharheight(0.024)
    gr.settextcolorind(1)
    gr.textext(0.05, 0.96, 'Damped Pendulum')
    gr.mathtex(0.05, 0.9, '\\omega=\\dot{\\theta}')
    gr.mathtex(0.05, 0.83,
               '\\dot{\\omega}=-\\gamma\\omega-\\frac{g}{l}sin(\\theta)')
    gr.setcharheight(0.020)
    gr.textext(0.05, 0.20, 't:%7.2f' % t)
    gr.textext(0.05, 0.16, '\\theta:%7.2f' % (theta / pi * 180))
    gr.settextcolorind(4)
    gr.textext(0.05, 0.12, '\\omega:%7.2f' % omega)
    gr.settextcolorind(2)
    gr.textext(0.05, 0.08, 'y_{A}:%6.2f' % acceleration)
    gr.updatews()
    return
Exemple #9
0
def _plot_iso(v):
    global _plt
    viewport = _plt.kwargs['viewport']
    if viewport[3] - viewport[2] < viewport[1] - viewport[0]:
        width = viewport[3] - viewport[2]
        center_x = 0.5 * (viewport[0] + viewport[1])
        x_min = max(center_x - 0.5 * width, viewport[0])
        x_max = min(center_x + 0.5 * width, viewport[1])
        y_min = viewport[2]
        y_max = viewport[3]
    else:
        height = viewport[1] - viewport[0]
        center_y = 0.5 * (viewport[2] + viewport[3])
        x_min = viewport[0]
        x_max = viewport[1]
        y_min = max(center_y - 0.5 * height, viewport[2])
        y_max = min(center_y + 0.5 * height, viewport[3])

    gr.selntran(0)
    usable_vs = v[np.abs(v) != np.inf]
    if np.prod(usable_vs.shape) == 0:
        return
    v_max = usable_vs.max()
    v_min = usable_vs.min()
    if v_min == v_max:
        return
    uint16_max = np.iinfo(np.uint16).max
    v = (np.clip(v, v_min, v_max) - v_min) / (v_max - v_min) * uint16_max
    values = v.astype(np.uint16)
    nx, ny, nz = v.shape
    isovalue = _plt.kwargs.get('isovalue', 0.5)
    rotation = np.radians(_plt.kwargs.get('rotation', 40))
    tilt = np.radians(_plt.kwargs.get('tilt', 70))
    gr3.clear()
    mesh = gr3.createisosurfacemesh(values, (2/(nx-1), 2/(ny-1), 2/(nz-1)),
                                    (-1., -1., -1.),
                                    int(isovalue * uint16_max))
    color = _plt.kwargs.get('color', (0.0, 0.5, 0.8))
    gr3.setbackgroundcolor(1, 1, 1, 0)
    gr3.drawmesh(mesh, 1, (0, 0, 0), (0, 0, 1), (0, 1, 0), color, (1, 1, 1))
    r = 2.5
    gr3.cameralookat(r*np.sin(tilt)*np.sin(rotation), r*np.cos(tilt), r*np.sin(tilt)*np.cos(rotation), 0, 0, 0, 0, 1, 0)
    gr3.drawimage(x_min, x_max, y_min, y_max, 500, 500, gr3.GR3_Drawable.GR3_DRAWABLE_GKS)
    gr3.deletemesh(mesh)
    gr.selntran(1)
Exemple #10
0
def pendulum(t, theta, omega, acceleration):
    gr.clearws()
    gr.setviewport(0, 1, 0, 1)
    
    x, y = (sin(theta) * 3.0, -cos(theta) * 3.0)
    
    gr3.clear()
    # draw pivot point
    gr3.drawspheremesh(1, (0, 0, 0), (0.4, 0.4, 0.4), 0.1)
    # draw rod
    gr3.drawcylindermesh(1, (0, 0, 0), (x, y, 0), (0.6, 0.6, 0.6), 0.05, 3.0)
    # draw sphere
    gr3.drawspheremesh(1, (x, y, 0), (1, 1, 1), 0.25)
    # show angular velocity
    V = 0.3 * omega - sign(omega) * 0.15
    gr3.drawcylindermesh(1, (x, y, 0), (cos(theta), sin(theta), 0), (0, 0, 1),
                         0.05, V)
    gr3.drawconemesh(1, (x + cos(theta) * V, y + sin(theta) * V, 0),
                     (-y, x, 0), (0, 0, 1), 0.1, sign(omega) * 0.25)
    # show angular acceleration
    A = 0.3 * acceleration
    gr3.drawcylindermesh(1, (x, y, 0), (sin(theta), cos(theta), 0), (1, 0, 0),
                         0.05, A)
    gr3.drawconemesh(1, (x + sin(theta) * A, y + cos(theta) * A, 0),
                     (x, -y, 0), (1, 0, 0), 0.1, 0.25)
    # draw GR3 objects
    gr3.drawimage(0, 1, 0.15, 0.85, 500, 350, gr3.GR3_Drawable.GR3_DRAWABLE_GKS)
    
    gr.settextfontprec(2, gr.TEXT_PRECISION_STRING)
    gr.setcharheight(0.024)
    gr.settextcolorind(1)
    gr.textext(0.05, 0.96, 'Damped Pendulum')
    gr.mathtex(0.05, 0.9, '\\omega=\\dot{\\theta}')
    gr.mathtex(0.05, 0.83, '\\dot{\\omega}=-\\gamma\\omega-\\frac{g}{l}sin(\\theta)')
    gr.setcharheight(0.020)
    gr.textext(0.05, 0.20, 't:%7.2f' % t)
    gr.textext(0.05, 0.16, '\\theta:%7.2f' % (theta / pi * 180))
    gr.settextcolorind(4)
    gr.textext(0.05, 0.12, '\\omega:%7.2f' % omega)
    gr.settextcolorind(2)
    gr.textext(0.05, 0.08, 'y_{A}:%6.2f' % acceleration)
    gr.updatews()
    return
Exemple #11
0
def _create_gr3_scene(molecule, show_bonds=True):
    """
    Create the GR3 scene from the provided molecule and - if show_bonds is
    True (default) - the atomic bonds in the molecule.
    """
    gr3.clear()
    num_atoms = len(molecule.atomic_numbers)
    gr3.drawspheremesh(num_atoms,
                       molecule.positions,
                       ATOM_COLORS[molecule.atomic_numbers],
                       molecule.atomic_radii)
    if show_bonds and len(molecule.bonds.index_pairs) > 0:
        index_pairs = molecule.bonds.index_pairs
        num_bonds = len(molecule.bonds)
        bond_positions = molecule.positions[index_pairs[:, 0]]
        bond_directions = molecule.positions[index_pairs[:, 1]]-bond_positions
        bond_lengths = la.norm(bond_directions, axis=1)
        bond_directions /= bond_lengths.reshape(num_bonds, 1)
        bond_radii = np.ones(num_bonds, dtype=np.float32)*BOND_RADIUS
        bond_colors = np.ones((num_bonds, 3), dtype=np.float32)*0.3
        gr3.drawcylindermesh(num_bonds, bond_positions, bond_directions,
                             bond_colors, bond_radii, bond_lengths)
Exemple #12
0
def _create_gr3_scene(molecule, show_bonds=True):
    """
    Create the GR3 scene from the provided molecule and - if show_bonds is
    True (default) - the atomic bonds in the molecule.
    """
    gr3.clear()
    num_atoms = len(molecule.atomic_numbers)
    gr3.drawspheremesh(num_atoms,
                       molecule.positions,
                       ATOM_COLORS[molecule.atomic_numbers],
                       molecule.atomic_radii)
    if show_bonds and len(molecule.bonds.index_pairs) > 0:
        index_pairs = molecule.bonds.index_pairs
        num_bonds = len(molecule.bonds)
        bond_positions = molecule.positions[index_pairs[:, 0]]
        bond_directions = molecule.positions[index_pairs[:, 1]]-bond_positions
        bond_lengths = la.norm(bond_directions, axis=1)
        bond_directions /= bond_lengths.reshape(num_bonds, 1)
        bond_radii = np.ones(num_bonds, dtype=np.float32)*BOND_RADIUS
        bond_colors = np.ones((num_bonds, 3), dtype=np.float32)*0.3
        gr3.drawcylindermesh(num_bonds, bond_positions, bond_directions,
                             bond_colors, bond_radii, bond_lengths)
Exemple #13
0
import gr
import gr3
gr.setviewport(0, 1, 0, 1)
for i in range(360):
    gr.clearws()
    gr3.clear()
    gr3.drawmolecule('dna.xyz', bond_delta=2, tilt=45, rotation=i)
    gr3.drawimage(0, 1, 0, 1, 500, 500, gr3.GR3_Drawable.GR3_DRAWABLE_GKS)
    gr.settextcolorind(0)
    gr.settextalign(gr.TEXT_HALIGN_CENTER, gr.TEXT_VALIGN_TOP)
    gr.text(0.5, 1, "DNA rendered using gr3.drawmolecule")
    gr.updatews()
Exemple #14
0
def _plot_data(**kwargs):
    global _plt
    _plt.kwargs.update(kwargs)
    if not _plt.args:
        return
    kind = _plt.kwargs.get('kind', 'line')
    if _plt.kwargs['clear']:
        gr.clearws()
    if kind in ('imshow', 'isosurface'):
        _set_viewport(kind, _plt.kwargs['subplot'])
    elif not _plt.kwargs['ax']:
        _set_viewport(kind, _plt.kwargs['subplot'])
        _set_window(kind)
        if kind == 'polar':
            _draw_polar_axes()
        else:
            _draw_axes(kind)

    if 'cmap' in _plt.kwargs:
        warnings.warn('The parameter "cmap" has been replaced by "colormap". The value of "cmap" will be ignored.', stacklevel=3)
    colormap = _plt.kwargs.get('colormap', gr.COLORMAP_VIRIDIS)
    if colormap is not None:
        gr.setcolormap(colormap)
    gr.uselinespec(" ")
    for x, y, z, c, spec in _plt.args:
        gr.savestate()
        if 'alpha' in _plt.kwargs:
            gr.settransparency(_plt.kwargs['alpha'])
        if kind == 'line':
            mask = gr.uselinespec(spec)
            if mask in (0, 1, 3, 4, 5):
                gr.polyline(x, y)
            if mask & 2:
                gr.polymarker(x, y)
        elif kind == 'scatter':
            gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE)
            if z is not None or c is not None:
                if c is not None:
                    c_min = c.min()
                    c_ptp = c.ptp()
                for i in range(len(x)):
                    if z is not None:
                        gr.setmarkersize(z[i] / 100.0)
                    if c is not None:
                        c_index = 1000 + int(255 * (c[i]-c_min)/c_ptp)
                        gr.setmarkercolorind(c_index)
                    gr.polymarker([x[i]], [y[i]])
            else:
                gr.polymarker(x, y)
        elif kind == 'stem':
            gr.setlinecolorind(1)
            gr.polyline(_plt.kwargs['window'][:2], [0, 0])
            gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE)
            gr.uselinespec(spec)
            for xi, yi in zip(x, y):
                gr.polyline([xi, xi], [0, yi])
            gr.polymarker(x, y)
        elif kind == 'hist':
            y_min = _plt.kwargs['window'][2]
            for i in range(1, len(y)+1):
                gr.setfillcolorind(989)
                gr.setfillintstyle(gr.INTSTYLE_SOLID)
                gr.fillrect(x[i-1], x[i], y_min, y[i-1])
                gr.setfillcolorind(1)
                gr.setfillintstyle(gr.INTSTYLE_HOLLOW)
                gr.fillrect(x[i-1], x[i], y_min, y[i-1])
        elif kind == 'contour':
            z_min, z_max = _plt.kwargs['zrange']
            gr.setspace(z_min, z_max, 0, 90)
            h = [z_min + i/19*(z_max-z_min) for i in range(20)]
            if x.shape == y.shape == z.shape:
                x, y, z = gr.gridit(x, y, z, 200, 200)
            z.shape = np.prod(z.shape)
            gr.contour(x, y, h, z, 1000)
            _colorbar(0, 20)
        elif kind == 'contourf':
            z_min, z_max = _plt.kwargs['zrange']
            gr.setspace(z_min, z_max, 0, 90)
            scale = _plt.kwargs['scale']
            gr.setscale(scale)
            if x.shape == y.shape == z.shape:
                x, y, z = gr.gridit(x, y, z, 200, 200)
                z.shape = (200, 200)
            gr.surface(x, y, z, gr.OPTION_CELL_ARRAY)
            _colorbar()
        elif kind == 'hexbin':
            nbins = _plt.kwargs.get('nbins', 40)
            cntmax = gr.hexbin(x, y, nbins)
            if cntmax > 0:
                _plt.kwargs['zrange'] = (0, cntmax)
                _colorbar()
        elif kind == 'heatmap':
            x_min, x_max, y_min, y_max = _plt.kwargs['window']
            width, height = z.shape
            cmap = _colormap()
            icmap = np.zeros(256, np.uint32)
            for i in range(256):
                r, g, b, a = cmap[i]
                icmap[i] = (int(r*255) << 0) + (int(g*255) << 8) + (int(b*255) << 16) + (int(a*255) << 24)
            z_min, z_max = _plt.kwargs.get('zlim', (np.min(z), np.max(z)))
            if z_max < z_min:
                z_max, z_min = z_min, z_max
            if z_max > z_min:
                data = (z - z_min) / (z_max - z_min) * 255
            else:
                data = np.zeros((width, height))
            rgba = np.zeros((width, height), np.uint32)
            for x in range(width):
                for y in range(height):
                    rgba[x, y] = icmap[int(data[x, y])]
            gr.drawimage(x_min, x_max, y_min, y_max, width, height, rgba)
            _colorbar()
        elif kind == 'wireframe':
            if x.shape == y.shape == z.shape:
                x, y, z = gr.gridit(x, y, z, 50, 50)
            gr.setfillcolorind(0)
            z.shape = np.prod(z.shape)
            gr.surface(x, y, z, gr.OPTION_FILLED_MESH)
            _draw_axes(kind, 2)

        elif kind == 'surface':
            if x.shape == y.shape == z.shape:
                x, y, z = gr.gridit(x, y, z, 200, 200)
            z.shape = np.prod(z.shape)
            if _plt.kwargs.get('accelerate', True):
                gr3.clear()
                gr3.surface(x, y, z, gr.OPTION_COLORED_MESH)
            else:
                gr.surface(x, y, z, gr.OPTION_COLORED_MESH)
            _draw_axes(kind, 2)
            _colorbar(0.05)
        elif kind == 'plot3':
            gr.polyline3d(x, y, z)
            _draw_axes(kind, 2)
        elif kind == 'scatter3':
            gr.polymarker3d(x, y, z)
            _draw_axes(kind, 2)
        elif kind == 'imshow':
            _plot_img(z)
        elif kind == 'isosurface':
            _plot_iso(z)
        elif kind == 'polar':
            gr.uselinespec(spec)
            _plot_polar(x, y)
        elif kind == 'trisurf':
            gr.trisurface(x, y, z)
            _draw_axes(kind, 2)
            _colorbar(0.05)
        elif kind == 'tricont':
            zmin, zmax = _plt.kwargs['zrange']
            levels = np.linspace(zmin, zmax, 20)
            gr.tricontour(x, y, z, levels)
        gr.restorestate()
    if kind in ('line', 'scatter', 'stem') and 'labels' in _plt.kwargs:
        _draw_legend()

    if _plt.kwargs['update']:
        gr.updatews()
        if gr.isinline():
            return gr.show()
Exemple #15
0
    def create_scene(self):
        """
        Create GR3 meshes. ``self.results`` contains the mesh data
        and in ``self.settings`` is specified which meshes shound be rendered.
        """

        c = config.Colors.background
        gr3.setbackgroundcolor(c[0], c[1], c[2], 1.0)
        gr3.clear()

        if self.results is None:
            return

        show_domains = self.settings.show_domains
        show_surface_cavities = self.settings.show_surface_cavities
        show_center_cavities = self.settings.show_center_cavities
        if show_center_cavities and self.results.center_cavities is not None:
            show_surface_cavities = False
        elif show_surface_cavities and self.results.surface_cavities is not None:
            show_domains = False

        self.objectids = [None]
        edges = self.results.atoms.volume.edges
        num_edges = len(edges)
        edge_positions = [edge[0] for edge in edges]
        edge_directions = [[edge[1][i]-edge[0][i] for i in range(3)] for edge in edges]
        edge_lengths = [sum([c*c for c in edge])**0.5 for edge in edge_directions]
        edge_radius = min(edge_lengths)/200
        if self.settings.show_bounding_box:
            gr3.drawcylindermesh(num_edges, edge_positions, edge_directions,
                                 [config.Colors.bounding_box]*num_edges,
                                 [edge_radius]*num_edges, edge_lengths)
            corners = list(set([tuple(edge[0]) for edge in edges] + [tuple(edge[1]) for edge in edges]))
            num_corners = len(corners)
            gr3.drawspheremesh(num_corners, corners,
                               [config.Colors.bounding_box]*num_corners,
                               [edge_radius]*num_corners)

        if self.settings.show_atoms and self.results.atoms is not None:
            visible_atom_indices = self.settings.visible_atom_indices
            if visible_atom_indices is not None:
                visible_atom_indices = [comp for comp in visible_atom_indices if 0 <= comp < self.results.atoms.number]
            else:
                visible_atom_indices = range(self.results.atoms.number)
            if len(visible_atom_indices) == 0:
                visible_atom_indices = None
            if visible_atom_indices is not None:
                visible_atom_indices = np.array(visible_atom_indices)
                gr3.drawspheremesh(len(visible_atom_indices),
                                   self.results.atoms.positions[visible_atom_indices],
                                   self.results.atoms.colors[visible_atom_indices],
                                   np.ones(len(visible_atom_indices))*config.OpenGL.atom_radius)
                if self.settings.show_bonds:
                    bonds = self.results.atoms.bonds
                    for start_index, target_indices in enumerate(bonds):
                        if start_index not in visible_atom_indices:
                            continue
                        target_indices = np.array([i for i in target_indices if i in visible_atom_indices])
                        if len(target_indices) == 0:
                            continue
                        start_position = self.results.atoms.positions[start_index]
                        target_positions = self.results.atoms.positions[target_indices]
                        directions = target_positions - start_position
                        bond_lengths = la.norm(directions, axis=1)
                        directions /= bond_lengths.reshape(len(directions), 1)
                        gr3.drawcylindermesh(len(target_indices),
                                             target_positions,
                                             -directions,
                                             [config.Colors.bonds] * self.results.atoms.number,
                                             np.ones(bond_lengths.shape)*config.OpenGL.bond_radius,
                                             bond_lengths)

        if self.results is None:
            return
        if show_domains and self.results.domains is not None:
            self.draw_cavities(self.results.domains,
                               config.Colors.domain, 'domain',
                               self.settings.visible_domain_indices)
        if show_surface_cavities and self.results.surface_cavities is not None:
            self.draw_cavities(self.results.surface_cavities,
                               config.Colors.surface_cavity, 'surface cavity',
                               self.settings.visible_surface_cavity_indices)
        if show_center_cavities and self.results.center_cavities is not None:
            self.draw_cavities(self.results.center_cavities,
                               config.Colors.center_cavity, 'center cavity',
                               self.settings.visible_center_cavity_indices)
Exemple #16
0
def _plot_data(**kwargs):
    global _plt
    _plt.kwargs.update(kwargs)
    if not _plt.args:
        return
    kind = _plt.kwargs.get('kind', 'line')
    if _plt.kwargs['clear']:
        gr.clearws()
    if kind in ('imshow', 'isosurface'):
        _set_viewport(kind, _plt.kwargs['subplot'])
    elif not _plt.kwargs['ax']:
        _set_viewport(kind, _plt.kwargs['subplot'])
        _set_window(kind)
        if kind == 'polar':
            _draw_polar_axes()
        else:
            _draw_axes(kind)

    gr.setcolormap(_plt.kwargs.get('colormap', gr.COLORMAP_COOLWARM))
    gr.uselinespec(" ")
    for x, y, z, c, spec in _plt.args:
        gr.savestate()
        if 'alpha' in _plt.kwargs:
            gr.settransparency(_plt.kwargs['alpha'])
        if kind == 'line':
            mask = gr.uselinespec(spec)
            if mask in (0, 1, 3, 4, 5):
                gr.polyline(x, y)
            if mask & 2:
                gr.polymarker(x, y)
        elif kind == 'scatter':
            gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE)
            if z is not None or c is not None:
                if c is not None:
                    c_min = c.min()
                    c_ptp = c.ptp()
                for i in range(len(x)):
                    if z is not None:
                        gr.setmarkersize(z[i] / 100.0)
                    if c is not None:
                        c_index = 1000 + int(255 * (c[i]-c_min)/c_ptp)
                        gr.setmarkercolorind(c_index)
                    gr.polymarker([x[i]], [y[i]])
            else:
                gr.polymarker(x, y)
        elif kind == 'stem':
            gr.setlinecolorind(1)
            gr.polyline(_plt.kwargs['window'][:2], [0, 0])
            gr.setmarkertype(gr.MARKERTYPE_SOLID_CIRCLE)
            gr.uselinespec(spec)
            for xi, yi in zip(x, y):
                gr.polyline([xi, xi], [0, yi])
            gr.polymarker(x, y)
        elif kind == 'hist':
            y_min = _plt.kwargs['window'][2]
            for i in range(1, len(y)+1):
                gr.setfillcolorind(989)
                gr.setfillintstyle(gr.INTSTYLE_SOLID)
                gr.fillrect(x[i-1], x[i], y_min, y[i-1])
                gr.setfillcolorind(1)
                gr.setfillintstyle(gr.INTSTYLE_HOLLOW)
                gr.fillrect(x[i-1], x[i], y_min, y[i-1])
        elif kind == 'contour':
            z_min, z_max = _plt.kwargs['zrange']
            gr.setspace(z_min, z_max, 0, 90)
            h = [z_min + i/19*(z_max-z_min) for i in range(20)]
            if x.shape == y.shape == z.shape:
                x, y, z = gr.gridit(x, y, z, 200, 200)
            z.shape = np.prod(z.shape)
            gr.contour(x, y, h, z, 1000)
            _colorbar(0, 20)
        elif kind == 'contourf':
            z_min, z_max = _plt.kwargs['zrange']
            gr.setspace(z_min, z_max, 0, 90)
            if x.shape == y.shape == z.shape:
                x, y, z = gr.gridit(x, y, z, 200, 200)
                z.shape = (200, 200)
            if _plt.kwargs['scale'] & gr.OPTION_Z_LOG != 0:
                z = np.log(z)
            gr.surface(x, y, z, gr.OPTION_CELL_ARRAY)
            _colorbar()
        elif kind == 'hexbin':
            nbins = _plt.kwargs.get('nbins', 40)
            cntmax = gr.hexbin(x, y, nbins)
            if cntmax > 0:
                _plt.kwargs['zrange'] = (0, cntmax)
                _colorbar()
        elif kind == 'heatmap':
            x_min, x_max, y_min, y_max = _plt.kwargs['window']
            width, height = z.shape
            cmap = _colormap()
            icmap = np.zeros(256, np.uint32)
            for i in range(256):
                r, g, b, a = cmap[i]
                icmap[i] = (int(r*255) << 0) + (int(g*255) << 8) + (int(b*255) << 16) + (int(a*255) << 24)
            z_range = np.ptp(z)
            if z_range > 0:
                data = (z - np.min(z)) / z_range * 255
            else:
                data = np.zeros((width, height))
            rgba = np.zeros((width, height), np.uint32)
            for x in range(width):
                for y in range(height):
                    rgba[x, y] = icmap[int(data[x, y])]
            gr.drawimage(x_min, x_max, y_min, y_max, width, height, rgba)
            _colorbar()
        elif kind == 'wireframe':
            if x.shape == y.shape == z.shape:
                x, y, z = gr.gridit(x, y, z, 50, 50)
            gr.setfillcolorind(0)
            z.shape = np.prod(z.shape)
            gr.surface(x, y, z, gr.OPTION_FILLED_MESH)
            _draw_axes(kind, 2)

        elif kind == 'surface':
            if x.shape == y.shape == z.shape:
                x, y, z = gr.gridit(x, y, z, 200, 200)
            z.shape = np.prod(z.shape)
            if _plt.kwargs.get('accelerate', True):
                gr3.clear()
                gr3.surface(x, y, z, gr.OPTION_COLORED_MESH)
            else:
                gr.surface(x, y, z, gr.OPTION_COLORED_MESH)
            _draw_axes(kind, 2)
            _colorbar(0.05)
        elif kind == 'plot3':
            gr.polyline3d(x, y, z)
            _draw_axes(kind, 2)
        elif kind == 'scatter3':
            gr.polymarker3d(x, y, z)
            _draw_axes(kind, 2)
        elif kind == 'imshow':
            _plot_img(z)
        elif kind == 'isosurface':
            _plot_iso(z)
        elif kind == 'polar':
            gr.uselinespec(spec)
            _plot_polar(x, y)
        elif kind == 'trisurf':
            gr.trisurface(x, y, z)
            _draw_axes(kind, 2)
            _colorbar(0.05)
        gr.restorestate()
    if kind in ('line', 'scatter', 'stem') and 'labels' in _plt.kwargs:
        _draw_legend()

    if _plt.kwargs['update']:
        gr.updatews()
        if gr.isinline():
            return gr.show()