예제 #1
0
def test_bokeh():
    from bokeh.io import output_notebook, show
    from bokeh.plotting import figure
    import ipyvolume.bokeh

    x, y, z = np.random.random((3, 100))

    p3.figure()
    scatter = p3.scatter(x, y, z)

    tools = "wheel_zoom,box_zoom,box_select,lasso_select,help,reset,"
    p = figure(title="E Lz space",
               tools=tools,
               webgl=True,
               width=500,
               height=500)
    r = p.circle(x, y, color="navy", alpha=0.2)
    ipyvolume.bokeh.link_data_source_selection_to_widget(
        r.data_source, scatter, 'selected')

    from bokeh.resources import CDN
    from bokeh.embed import components

    script, div = components(p)
    ipyvolume.embed.embed_html(
        "tmp/bokeh.html", [p3.gcc(), ipyvolume.bokeh.wmh],
        all=True,
        extra_script_head=script + CDN.render_js() + CDN.render_css(),
        body_pre="<h2>Do selections in 2d (bokeh)<h2>" + div +
        "<h2>And see the selection in ipyvolume<h2>")
예제 #2
0
 def create_widget(self, output, plot, dataset, limits):
     self.output = output
     self.plot = plot
     self.dataset = dataset
     self.limits = np.array(limits).tolist()
     self._first_time = True
     self._first_time_vector = True
     self.figure = p3.figure()
     self.widget = p3.gcc()
예제 #3
0
    def create_widget(self, output, plot, dataset, limits):
        self.output = output
        self.plot = plot
        self.dataset = dataset
        self.limits = np.array(limits).tolist()
        self._first_time = True
        self._first_time_vector = True
        self.figure = p3.figure()
        self.widget = p3.gcc()

        self.figure.observe(self._update_limits, 'xlim ylim zlim'.split())
예제 #4
0
    def create_widget(self, output, plot, dataset, limits):
        self.output = output
        self.plot = plot
        self.dataset = dataset
        self.limits = np.array(limits).tolist()
        self._first_time = True
        self._first_time_vector = True
        self.figure = p3.figure()
        self.widget = p3.gcc()

        self.figure.observe(self._update_limits, 'xlim ylim zlim'.split())
예제 #5
0
    def interactive_plot(self):

        import ipyvolume.pylab as p3
        self._create_widgets()
        self.scatters = {}
        self.vectors = {}
        self.legend = widgets.Output()
        with self.legend:
            self.pltfigure = plt.figure(figsize=(8, 8))
            # creating a dummy figure, so that 'self.pltfigure.clf()'
            # in self._legend_handler() does not throw an error
            # during initialization

        p3.clear()
        data = self.get_frame(self._widgets.frame.value)['arrays']
        for array_name in self._widgets.particles.keys():
            pa_widgets = self._widgets.particles[array_name]
            if pa_widgets.scalar.value != 'None':
                colormap = getattr(mpl.cm, pa_widgets.scalar_cmap.value)
                c = colormap(getattr(data[array_name],
                                     pa_widgets.scalar.value))
                self.scatters[array_name] = p3.scatter(
                    data[array_name].x,
                    data[array_name].y,
                    data[array_name].z,
                    color=c,
                    size=pa_widgets.scalar_size.value,
                )
        self.plot_container = p3.gcc()
        self.plot = p3.gcf()  # used in 'self._save_figure_handler()'
        self._legend_handler(None)
        display(
            widgets.HBox(
                [widgets.VBox([self.plot]),
                 widgets.VBox([self.legend])]))
        # HBox does not allow custom layout, therefore using an HBox
        # of two VBoxes to place 'plot' and 'legend' next to each other
        display(self._widgets._create_vbox())
예제 #6
0
    def interactive_plot(self):
        self._create_widgets()
        self.scatters = {}
        display(self._widgets._create_vbox())
        self.vectors = {}
        self.legend = widgets.Output()

        import ipyvolume.pylab as p3

        p3.clear()
        data = self.get_frame(self._widgets.frame.value)['arrays']
        for array_name in self._widgets.particles.keys():
            pa_widgets = self._widgets.particles[array_name]
            colormap = getattr(mpl.cm, pa_widgets.scalar_cmap.value)
            c = colormap(getattr(data[array_name], pa_widgets.scalar.value))
            self.scatters[array_name] = p3.scatter(
                data[array_name].x,
                data[array_name].y,
                data[array_name].z,
                color=c,
                size=pa_widgets.scalar_size.value,
            )
        self._legend_handler(None)
        display(widgets.VBox((p3.gcc(), self.legend)))
예제 #7
0
 def show(self):
     container = p3.gcc()
     vbox = widgets.VBox([container, self.progress, widgets.VBox(self.tools), self.output])
     display(vbox)
예제 #8
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