Example #1
0
def test_volshow_max_shape():
    x, y, z = ipyvolume.examples.xyz(shape=32)
    I = x * y * z
    v = p3.volshow(I, max_shape=16, extent=[[0, 32]] * 3)
    assert v.data.shape == (16, 16, 16)
    data = v.data
    p3.xlim(0, 16)
Example #2
0
 def update_image(self, intensity_image):
     with self.output:
         p3.volshow(intensity_image.T, controls=self._first_time)
         self._first_time = False
         p3.xlim(*self.limits[0])
         p3.ylim(*self.limits[1])
         p3.zlim(*self.limits[2])
Example #3
0
    def _update_image(self):
        with self.output:
            grid = self.get_grid()
            if self.smooth_pre:
                for i in range(grid.shape[0]):
                    grid[i] = vaex.grids.gf(grid[i], self.smooth_pre)
            f = vaex.dataset._parse_f(self.f)
            fgrid = f(grid)
            if self.smooth_post:
                for i in range(grid.shape[0]):
                    fgrid[i] = vaex.grids.gf(fgrid[i], self.smooth_post)
            ngrid, fmin, fmax = self.normalise(fgrid)
            print(ngrid.shape)
            if len(ngrid.shape) == 4:
                #if ngrid.shape[0] == 1:
                ngrid = ngrid[-1]
            p3.volshow(ngrid.T, controls=self._first_time)

            vx, vy, vz = self.vgrids[:3]
            vcount = self.vcount
            if vx is not None and vy is not None and vz is not None and vcount is not None:
                vcount = vcount[-1] # no multivolume render, just take the last selection
                vx = vx[-1]
                vy = vy[-1]
                vz = vz[-1]
                print(vx.shape)
                ok = np.isfinite(vx) & np.isfinite(vy) & np.isfinite(vz)
                vcount_min = None
                vcount_max = None
                if self.vcount_limits is not None:
                    try:
                        vcount_min, vcount_max = self.vcount_limits
                    except:
                        vcount_min = self.vcount_limits
                if vcount_min is not None:
                    ok &= (vcount > vcount_min)
                if vcount_max is not None:
                    ok &= (vcount < vcount_max)
                x, y, z = ipyvolume.examples.xyz(self.get_vshape()[0], limits=self.limits, sparse=False, centers=True)
                v1d = [k[ok] for k in [x, y, z, vx, vy, vz]]
                vsize = 5
                vcolor = "grey"
                if self._first_time:
                    self.quiver = p3.quiver(*v1d, size=vsize, color=vcolor)
                else:
                    self.quiver.x = x[ok]
                    self.quiver.y = y[ok]
                    self.quiver.z = z[ok]
                    self.quiver.vx = vx[ok]
                    self.quiver.vy = vy[ok]
                    self.quiver.vz = vz[ok]

            p3.xlim(*self.limits[0])
            p3.ylim(*self.limits[1])
            p3.zlim(*self.limits[2])
            self._first_time = False
Example #4
0
def test_limits():
    f = p3.figure()
    p3.xlim(-10, 11)
    assert f.xlim[0] == -10
    assert f.xlim[1] == 11

    p3.ylim(-12, 13)
    assert f.ylim[0] == -12
    assert f.ylim[1] == 13

    p3.zlim(-14, 15)
    assert f.zlim[0] == -14
    assert f.zlim[1] == 15

    p3.xyzlim(-17, 17)
    assert f.xlim[0] == -17
    assert f.xlim[1] == 17
    assert f.ylim[0] == -17
    assert f.ylim[1] == 17
    assert f.zlim[0] == -17
    assert f.zlim[1] == 17
Example #5
0
def test_limits():
    f = p3.figure()
    p3.xlim(-10, 11)
    assert f.xlim[0] == -10
    assert f.xlim[1] == 11

    p3.ylim(-12, 13)
    assert f.ylim[0] == -12
    assert f.ylim[1] == 13

    p3.zlim(-14, 15)
    assert f.zlim[0] == -14
    assert f.zlim[1] == 15

    p3.xyzlim(-17, 17)
    assert f.xlim[0] == -17
    assert f.xlim[1] == 17
    assert f.ylim[0] == -17
    assert f.ylim[1] == 17
    assert f.zlim[0] == -17
    assert f.zlim[1] == 17

    # TODO: actually, default xlim should be None, and the limits should
    # then now grow, but 'move' around the new point
    f = ipv.figure()
    assert f.xlim == [0, 1]
    ipv.ylim(0, 10)
    ipv.zlim(-10, 0)
    ipv.scatter(3, 4, 5)
    assert f.xlim == [0, 3]
    assert f.ylim == [0, 10]
    assert f.zlim == [-10, 5]

    f = ipv.figure()
    ipv.volshow(np.random.rand(5, 5, 5),
                extent=[[0.1, 0.9], [0.5, 2], [-2, 5]])
    assert f.xlim == [0, 1]
    assert f.ylim == [0, 2]
    assert f.zlim == [-2, 5]
Example #6
0
def show_spatial_series(node: SpatialSeries, **kwargs):

    data, unit = get_timeseries_in_units(node)
    tt = get_timeseries_tt(node)

    if len(data.shape) == 1:
        fig, ax = plt.subplots()
        ax.plot(tt, data, **kwargs)
        ax.set_xlabel('t (sec)')
        if unit:
            ax.set_xlabel('x ({})'.format(unit))
        else:
            ax.set_xlabel('x')
        ax.set_ylabel('x')

    elif data.shape[1] == 2:
        fig, ax = plt.subplots()
        ax.plot(data[:, 0], data[:, 1], **kwargs)
        if unit:
            ax.set_xlabel('x ({})'.format(unit))
            ax.set_ylabel('y ({})'.format(unit))
        else:
            ax.set_xlabel('x')
            ax.set_ylabel('y')
        ax.axis('equal')

    elif data.shape[1] == 3:
        import ipyvolume.pylab as p3

        fig = p3.figure()
        p3.scatter(data[:, 0], data[:, 1], data[:, 2], **kwargs)
        p3.xlim(np.min(data[:, 0]), np.max(data[:, 0]))
        p3.ylim(np.min(data[:, 1]), np.max(data[:, 1]))
        p3.zlim(np.min(data[:, 2]), np.max(data[:, 2]))

    else:
        raise NotImplementedError

    return fig
Example #7
0
def create_ivol(vstruct,
                width=500,
                height=400,
                ssize=5,
                min_voxels=None,
                max_voxels=None,
                **volargs):
    """

    Parameters
    ----------
    vstruct: dict
    width: int
    height: int
    ssize: int
    min_voxels : int
        minimum number of voxels in density cube
    max_voxels : int
        maximum number of voxels in density cube
    volargs: dict

    Returns
    -------

    Examples
    --------

    >>> from jsonextended import edict

    >>> dstruct = {
    ...  'type': 'repeat_density',
    ...  'dtype': 'charge',
    ...  'name': '',
    ...  'dcube':np.ones((3,3,3)),
    ...  'centre':[0,0,0],
    ...  'cell_vectors':{
    ...      'a':[2.,0,0],
    ...      'b':[0,2.,0],
    ...      'c':[0,0,2.]},
    ...   'color_bbox': 'black',
    ...   'transforms': []
    ... }
    >>> cstruct = {
    ...  'type': 'repeat_cell',
    ...  'name': '',
    ...  'centre':[0,0,0],
    ...  'cell_vectors':{
    ...      'a':[2.,0,0],
    ...      'b':[0,2.,0],
    ...      'c':[0,0,2.]},
    ...   'color_bbox': 'black',
    ...   'sites': [{
    ...         'label': "Fe",
    ...         'ccoord': [1,1,1],
    ...         'color_fill': "red",
    ...         'color_outline': None,
    ...         'transparency': 1,
    ...         'radius': 1,
    ...   }],
    ...   'bonds': [],
    ...   'transforms': []
    ... }
    >>> vstruct = {"elements": [dstruct, cstruct], "transforms": []}
    >>> new_struct, fig, controls = create_ivol(vstruct)

    >>> print(edict.apply(edict.filter_keys(new_struct, ["ivol"], list_of_dicts=True),
    ...                   "ivol", lambda x: [v.__class__.__name__ for v in x], list_of_dicts=True))
    {'elements': [{'ivol': ['Figure', 'Mesh']}, {'ivol': ['Mesh', 'Scatter']}]}

    """
    new_struct = apply_transforms(vstruct)
    bonds = compute_bonds(
        new_struct
    )  #edict.filter_keyvals(vstruct, {"type": "repeat_cell"}, keep_siblings=True))

    # ivolume currently only allows one volume rendering per plot
    # voltypes = edict.filter_keyvals(vstructs,[('type','repeat_density')])
    vol_index = [
        i for i, el in enumerate(vstruct['elements'])
        if el['type'] == 'repeat_density'
    ]
    assert len(
        vol_index) <= 1, "ipyvolume only allows one volume rendering per scene"

    p3.clear()
    fig = p3.figure(width=width, height=height, controls=True)
    fig.screen_capture_enabled = True

    # the volume rendering must be created first,
    # for appropriately scaled axis
    if vol_index:
        volstruct = new_struct['elements'][vol_index[0]]
        a = volstruct['cell_vectors']['a']
        b = volstruct['cell_vectors']['b']
        c = volstruct['cell_vectors']['c']
        centre = volstruct['centre']
        #print(centre)

        # convert dcube to cartesian
        out = cube_frac2cart(volstruct['dcube'],
                             a,
                             b,
                             c,
                             centre,
                             max_voxels=max_voxels,
                             min_voxels=min_voxels,
                             make_cubic=True)
        new_density, (xmin, ymin, zmin), (xmax, ymax, zmax) = out

        vol = p3.volshow(new_density, **volargs)

        if volstruct["color_bbox"] is not None:
            a = np.asarray(a)
            b = np.asarray(b)
            c = np.asarray(c)
            o = np.asarray(centre) - 0.5 * (a + b + c)
            mesh = _create_mesh([
                o, o + a, o + b, o + c, o + a + b, o + a + c, o + c + b,
                o + a + b + c
            ],
                                color=volstruct["color_bbox"],
                                line_indices=[[0, 1], [0, 2], [0, 3], [2, 4],
                                              [2, 6], [1, 4], [1, 5], [3, 5],
                                              [3, 6], [7, 6], [7, 4], [7, 5]])
            vol = [vol, mesh]

        # todo better way of storing ivol components?
        volstruct['ivol'] = vol

        # appropriately scale axis
        p3.xlim(xmin, xmax)
        p3.ylim(ymin, ymax)
        p3.zlim(zmin, zmax)

    for element in new_struct['elements']:
        if element['type'] == 'repeat_density':
            continue
        elif element['type'] == 'repeat_cell':
            scatters = []
            if element["color_bbox"] is not None:
                a = np.asarray(element['cell_vectors']['a'])
                b = np.asarray(element['cell_vectors']['b'])
                c = np.asarray(element['cell_vectors']['c'])
                centre = element['centre']
                o = np.asarray(centre) - 0.5 * (a + b + c)
                mesh = _create_mesh([
                    o, o + a, o + b, o + c, o + a + b, o + a + c, o + c + b,
                    o + a + b + c
                ],
                                    color=element["color_bbox"],
                                    line_indices=[[0, 1], [0, 2], [0,
                                                                   3], [2, 4],
                                                  [2, 6], [1, 4], [1,
                                                                   5], [3, 5],
                                                  [3, 6], [7, 6], [7, 4],
                                                  [7, 5]])
                scatters.append(mesh)

            for color, radius in set([(s['color_fill'], s['radius'])
                                      for s in element["sites"]]):

                scatter = edict.filter_keyvals(element, {
                    "color_fill": color,
                    "radius": radius
                },
                                               "AND",
                                               keep_siblings=True,
                                               list_of_dicts=True)
                scatter = edict.combine_lists(scatter, ["sites"],
                                              deepcopy=False)
                scatter = edict.remove_keys(scatter, ["sites"], deepcopy=False)

                x, y, z = np.array(scatter['ccoord']).T
                s = p3.scatter(x,
                               y,
                               z,
                               marker='sphere',
                               size=ssize * radius,
                               color=color)
                scatters.append(s)

            element['ivol'] = scatters
        elif element['type'] == 'repeat_poly':
            polys = []
            for poly in element['polys']:
                mesh = _create_mesh(poly, element['color'], element['solid'])
                polys.append(mesh)
            element['ivol'] = polys
        else:
            raise ValueError("unknown element type: {}".format(
                element['type']))

    for bond in bonds:
        p1, p2, c1, c2, radius = bond
        meshes = _create_bond(p1, p2, c1, c2, radius)

    # split up controls
    if vol_index:
        (level_ctrls, figbox, extractrl1, extractrl2) = p3.gcc().children
        controls = OrderedDict([('transfer function', [level_ctrls]),
                                ('lighting', [extractrl1, extractrl2])])
    else:
        # figbox = p3.gcc().children
        controls = {}

    return new_struct, fig, controls