Skip to content

GridPlotter

Bases: StructurePlotter

A convenience class for creating plots of crystal structures and isosurfaces using pyvista's package for VTK.

Parameters:

Name Type Description Default
grid Grid

The Grid object to use for isosurfaces. The structure will be pulled from this grid.

required
Source code in src/baderkit/plotting/toolkit/grid.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
class GridPlotter(StructurePlotter):
    """
    A convenience class for creating plots of crystal structures and isosurfaces
    using pyvista's package for VTK.

    Parameters
    ----------
    grid : Grid
        The Grid object to use for isosurfaces. The structure will be pulled
        from this grid.

    """

    def __init__(
        self,
        grid: Grid,
        show_surface=True,
        show_caps=True,
        surface_opacity=0.8,
        cap_opacity=0.8,
        colormap="viridis",
        use_solid_surface_color=False,
        use_solid_cap_color=False,
        surface_color="#BA8E23",
        cap_color="#BA8E23",
        iso_value=None,
        **structure_kwargs,
    ):
        self.grid = grid
        self._show_surface = show_surface
        self._show_caps = show_caps
        self._surface_opacity = surface_opacity
        self._cap_opacity = cap_opacity
        self._colormap = colormap
        self._use_solid_surface_color = use_solid_surface_color
        self._use_solid_cap_color = use_solid_cap_color
        self._surface_color = pv.Color(surface_color)
        self._cap_color = pv.Color(cap_color)
        self._hidden_mask = None  # for Bader class

        self._min_val = grid.total.min() + 0.0000001
        self._max_val = grid.total.max()
        if iso_value is None:
            self._iso_value = (self._min_val + self._max_val) / 4
        else:
            self._iso_value = max(self.min_val, min(iso_value, self.max_val))

        # meshes
        self._surface_mesh = None
        self._cap_mesh = None
        self._slice_meshes = {}
        self._slice_planes = {}
        self._slice_hkls = {}

        # apply StructurePlotter kwargs
        super().__init__(structure=grid.structure, **structure_kwargs)

    @property
    def show_surface(self) -> bool:
        """

        Returns
        -------
        bool
            whether or not to display the isosurface.

        """
        return self._show_surface

    @show_surface.setter
    def show_surface(self, show_surface: bool):
        if show_surface != self.show_surface:
            self._show_surface = show_surface
            self._update_surface_actor()

    @property
    def show_caps(self) -> bool:
        """

        Returns
        -------
        bool
            Whether or not to display caps on the isosurface.

        """
        return self._show_caps

    @show_caps.setter
    def show_caps(self, show_caps: bool):
        if show_caps != self.show_caps:
            self._show_caps = show_caps
            self._update_cap_actor()

    @property
    def surface_opacity(self) -> float:
        """

        Returns
        -------
        float
            Opacity of the isosurface.

        """
        return self._surface_opacity

    @surface_opacity.setter
    def surface_opacity(self, surface_opacity: float):
        if surface_opacity == self.surface_opacity:
            return
        actor = self.plotter.actors.get("iso", None)
        if actor is not None:
            actor.prop.opacity = surface_opacity
        self._surface_opacity = surface_opacity

    @property
    def cap_opacity(self) -> float:
        """

        Returns
        -------
        float
            Opacity of the caps.

        """
        return self._cap_opacity

    @cap_opacity.setter
    def cap_opacity(self, cap_opacity: float):
        if cap_opacity == self.cap_opacity:
            return
        actor = self.plotter.actors.get("cap", None)
        if actor is not None:
            actor.prop.opacity = cap_opacity
        self._cap_opacity = cap_opacity

    @property
    def colormap(self) -> str:
        """

        Returns
        -------
        str
            The colormap for the caps and isosurface. This is ignored when the
            surface or caps are set to use solid colors. Valid options are those
            available in matplotlib.

        """
        return self._colormap

    @colormap.setter
    def colormap(self, colormap: str):
        if colormap == self.colormap:
            return

        # update settings
        self._colormap = colormap
        self._update_clims_cmaps()

    @property
    def min_val(self) -> str:
        return self._min_val

    @min_val.setter
    def min_val(self, value: float):
        if value == self.min_val:
            return

        # update settings
        self._min_val = min(self.max_val, value)
        self._update_clims_cmaps()

    @property
    def max_val(self) -> str:
        return self._max_val

    @max_val.setter
    def max_val(self, value: float):
        if value == self.max_val:
            return

        # update settings
        self._max_val = max(self.min_val, value)
        self._update_clims_cmaps()

    @property
    def use_solid_surface_color(self) -> bool:
        """

        Returns
        -------
        bool
            whether or not to use a solid color for the isosurface.
        """
        return self._use_solid_surface_color

    # TODO: Figure out a way to set the cmap without remaking the surface?
    @use_solid_surface_color.setter
    def use_solid_surface_color(self, use_solid_surface_color: bool):
        if use_solid_surface_color != self.use_solid_surface_color:
            # update property
            self._use_solid_surface_color = use_solid_surface_color
            self._update_surface_actor()

    @property
    def use_solid_cap_color(self) -> bool:
        """

        Returns
        -------
        bool
            whether or not to use a solid color for the caps.
        """
        return self._use_solid_cap_color

    @use_solid_cap_color.setter
    def use_solid_cap_color(self, use_solid_cap_color: bool):
        if use_solid_cap_color != self.use_solid_cap_color:
            # update property
            self._use_solid_cap_color = use_solid_cap_color
            self._update_cap_actor()

    @property
    def surface_color(self) -> pv.Color:
        """

        Returns
        -------
        str
            The color to use for the surface as a hex string. This is ignored if
            the surface is not set to use solid colors.

        """
        return self._surface_color

    @surface_color.setter
    def surface_color(self, surface_color: str):
        color = pv.Color(surface_color)
        if color == self.surface_color:
            return
        self._surface_color = color
        actor = self.plotter.actors.get("iso", None)
        if actor is not None:
            actor.prop.color = color

    @property
    def cap_color(self) -> pv.Color:
        """

        Returns
        -------
        str
            The color to use for the caps as a hex string. This is ignored if
            the caps are not set to use solid colors.

        """
        return self._cap_color

    @cap_color.setter
    def cap_color(self, cap_color: str | NDArray):
        color = pv.Color(cap_color)
        if color == self.cap_color:
            return
        self._cap_color = color
        actor = self.plotter.actors.get("cap", None)
        if actor is not None:
            actor.prop.color = color

    @property
    def iso_value(self) -> float:
        """

        Returns
        -------
        float
            The value to set the isosurface to.

        """
        return self._iso_value

    @iso_value.setter
    def iso_value(self, iso_value: float):
        if iso_value == self.iso_value:
            return
        # make sure iso value is within range
        iso_value = max(self.min_val, min(iso_value, self.max_val))
        # update
        self._iso_value = iso_value
        self._update_grid_meshes()
        self._update_surface_actor()
        self._update_cap_actor()

    def _create_plot(self) -> pv.Plotter():
        """
        Generates a pyvista.Plotter object from the current class variables.
        This is called when the class is first instanced and generally shouldn't
        be called again.

        Returns
        -------
        plotter : pv.Plotter
            A pyvista Plotter object representing the provided Structure object.

        """
        plotter = super()._create_plot()

        # generate initial surface meshes
        self._make_structured_grid()
        self._update_grid_meshes()
        self._update_surface_actor()
        self._update_cap_actor()
        for key, (hkl, d) in self._slice_hkls.items():
            self.add_slice(hkl, d, key)
        return plotter

    def _update_surface_actor(self):
        surface_kwargs = {
            "opacity": self.surface_opacity,
            "pbr": self.pbr,
            "name": "iso",
            "color": self.surface_color,
        }

        if not self.use_solid_surface_color:
            surface_kwargs.update(
                {
                    "scalars": "values",
                    "clim": [self.min_val, self.max_val],
                    "show_scalar_bar": False,
                    "colormap": self.colormap,
                }
            )

        if self.show_surface and len(self._surface_mesh["values"]) > 0:
            self.plotter.add_mesh(self._surface_mesh, **surface_kwargs)
        else:
            actor = self.plotter.actors.get("iso", None)
            if actor is not None:
                self.plotter.remove_actor(actor)

    def _update_cap_actor(self):
        cap_kwargs = {
            "opacity": self.cap_opacity,
            "pbr": self.pbr,
            "name": "cap",
            "color": self.cap_color,
        }
        if not self.use_solid_cap_color:
            cap_kwargs.update(
                {
                    "scalars": "values",
                    "clim": [self.min_val, self.max_val],
                    "show_scalar_bar": False,
                    "colormap": self.colormap,
                }
            )

        if self.show_caps and len(self._cap_mesh["values"]) > 0:
            self.plotter.add_mesh(self._cap_mesh, **cap_kwargs)
        else:
            actor = self.plotter.actors.get("cap", None)
            if actor is not None:
                self.plotter.remove_actor(actor)

    def _update_grid_meshes(self):
        """
        Updates the surface meshes to the provided iso_value


        Returns
        -------
        None.

        """

        self._surface_mesh = self._structured_grid.contour(
            [self.iso_value]
        ).triangulate()
        self._cap_mesh = self._surface.contour_banded(
            2, rng=[self.iso_value, self.max_val], generate_contour_edges=False
        ).triangulate()

    def _update_clims_cmaps(self):
        actors = ["iso", "cap"]
        actors.extend([f"{i}" for i in self._slice_meshes.keys()])
        for actor_str in actors:
            actor = self.plotter.actors.get(actor_str, None)
            if actor is not None:
                actor.mapper.scalar_range = (self.min_val, self.max_val)
                actor.mapper.lookup_table.cmap = self.colormap

    def _make_structured_grid(self) -> pv.StructuredGrid:
        """
        Creates a pyvista StructuredGrid object for making isosurfaces. This
        should generally only be called once

        Returns
        -------
        structured_grid : pv.StructuredGrid
            A pyvista StructuredGrid with values representing the grid data.

        """

        grid = self.grid
        values = np.pad(grid.total, pad_width=((0, 1), (0, 1), (0, 1)), mode="wrap")
        shape = values.shape
        indices = np.indices(shape).reshape(3, -1, order="F").T
        points = grid.grid_to_cart(indices)

        # create structured grid
        structured_grid = pv.StructuredGrid()
        structured_grid.points = points
        structured_grid.dimensions = shape

        flat_values = values.ravel(order="F")
        # mask if any hidden mask exists
        if self._hidden_mask is not None:
            flat_values[self._hidden_mask] = -1

        structured_grid["values"] = flat_values

        # save and extract surface
        self._structured_grid = structured_grid
        self._surface = structured_grid.extract_surface(algorithm="dataset_surface")

    def add_slice(
        self,
        hkl: NDArray,
        d: float = 1.0,
        key=None,
    ):
        """
        Adds a slice of the grid to the plot. If a key is provided, this updates
        the corresponding slice rather than adding a new one.

        Parameters
        ----------
        hkl : NDArray
            The miller indices of the plane
        d : float
            The multiplier for the d-spacing of the plane
        key : int, optional
            A integer key for an existing plane to update. The default is None.

        """

        if key is not None:
            name = f"slice_{key}"
            assert (
                name in self._slice_meshes.keys()
            ), "Key must correspond to an existing slice"
        else:
            if len(self._slice_meshes.keys()) > 0:
                idx = max(list(self._slice_meshes.keys())) + 1
            else:
                idx = 0
            name = f"slice_{idx}"

        h, k, l = hkl
        # get normal vector in cart coords
        normal = self.structure.get_cart_from_miller(h, k, l)
        n = self.structure.lattice.d_hkl(hkl)
        origin = normal * n * d
        slice_plane = self._structured_grid.slice(normal=normal, origin=origin)

        self._slice_meshes[name] = slice_plane
        self._slice_planes[name] = (origin, normal)
        self._slice_hkls[name] = (hkl, d)
        # get key if no
        # create plotter
        self.plotter.add_mesh(
            slice_plane,
            scalars="values",
            cmap=self.colormap,
            clim=(self.min_val, self.max_val),
            show_scalar_bar=False,
            name=name,
        )

    def remove_slice(self, key):
        name = f"slice_{key}"
        if name in self._slice_meshes.keys():
            del self._slice_meshes[name]
            del self._slice_planes[name]
            del self._slice_hkls[name]
        actor = self.plotter.actors.get(name, None)
        if actor is not None:
            self.plotter.remove_actor(actor)

    def plot_slice(
        self,
        key,
        include_atoms: bool = True,
        filename: Path = None,
        **write_kwargs,
    ):
        """
        Generates a pyvista plot of a slice at the requested miller plane. If
        a filename is provided, the plot is written and no plot object is returned.

        Parameters
        ----------
        key : int
            The key of the plane to plot
        include_atoms : bool, optional
            Whether or not atoms should be incuded. Only atoms whose sphere mesh
            is sliced by the plane are included. The default is True.
        filename : Path, optional
            The filename to write the plot to if desired. The default is None.
        **write_kwargs
            any additional keyword arguments to provide to the plot writer.

        Returns
        -------
        p : pv.plotter | None
            the pyvista plot of the slice or None if a filename was provided.

        """
        if key is not None:
            name = f"slice_{key}"
            assert (
                name in self._slice_meshes.keys()
            ), "Key must correspond to an existing slice"
        # create plotter
        mesh = self._slice_meshes[name]

        p = StructurePlotter(
            structure=self.structure,
            off_screen=True,
            show_axes=False,
            show_lattice=False,
        )
        p.plotter.add_mesh(
            mesh,
            scalars="values",
            cmap=self.colormap,
            clim=(self.min_val, self.max_val),
            show_scalar_bar=False,
        )

        origin, normal = self._slice_planes[name]
        # if desired, add any atoms that sit on/near the plane
        if include_atoms:
            # get wrapped atom points
            atom_poly = p._wrapped_atom_poly
            points = atom_poly.points
            include_coords = np.zeros(len(points), dtype=np.bool_)
            for wrap_idx, (atom_idx, center) in enumerate(
                zip(self._map_wrapped_to_atoms, points)
            ):

                radius = self.atom_radii[atom_idx] * self.radii_scale
                dist = np.dot(center - origin, normal)
                if abs(dist) >= radius:
                    continue
                # otherwise add
                include_coords[wrap_idx] = True

            # get atom colors
            atom_colors = self.atom_colors[self._map_wrapped_to_atoms]
            # get alpha values
            alpha = self.atom_opacities[self._map_wrapped_to_atoms]
            # set alpha to zero at unwanted atoms
            alpha[~include_coords] = 0.0
            # update poly data scalars
            atom_poly["atom_colors"] = np.column_stack((atom_colors, alpha))
            atom_poly["atom_radii"] = (
                self.atom_radii[self._map_wrapped_to_atoms] * self.radii_scale
            )

            # generate glyphs
            glyphs = atom_poly.glyph(
                geom=self._sphere_mesh, scale="atom_radii", orient=False
            )

            # add the atom glyphs to our plotter. This automatically overwrites any
            # previous meshes
            p.plotter.add_mesh(
                glyphs,
                scalars="atom_colors",
                rgb=True,
                name="atom_glyphs",
                pbr=self.pbr,
            )
        else:
            # otherwise, remove all atoms from the plot
            visible = p.atom_opacities
            visible[:] = 0.0
            p.atom_opacities = visible

        # set camera to be perpendicular
        p.set_camera_to_vector(origin=origin, normal=normal)
        p._set_camera_tight()

        if filename is not None:
            p.get_plot_screenshot(filename=filename, **write_kwargs)
        else:
            image = p.get_plot_screenshot(return_image=True, **write_kwargs)
            return image

atom_colors property writable

Returns:

Type Description
list[str]

The atom_colors to use for each atom as hex codes.

atom_df property writable

Returns:

Name Type Description
atom_df TYPE

A dataframe summarizing the properties of the atom meshes.

atom_metallicness property writable

Returns:

Type Description
float

The amount of metallic character in the atom display.

atom_opacities property writable

Returns:

Type Description
NDArray[float]

Whether or not each atom is visible. This is actually the opacity if desired.

atom_radii property writable

Returns:

Type Description
NDArray[float]

The radius to display for each atom in the structure. The actual displayed radius will be radii_scale*radius.

atom_roughness property writable

Returns:

Type Description
float

The amount of roughness in the atom display.

background_color property writable

Returns:

Type Description
str

The color of the plot background as a hex code, rgb array, or color string.

cap_color property writable

Returns:

Type Description
str

The color to use for the caps as a hex string. This is ignored if the caps are not set to use solid colors.

cap_opacity property writable

Returns:

Type Description
float

Opacity of the caps.

colormap property writable

Returns:

Type Description
str

The colormap for the caps and isosurface. This is ignored when the surface or caps are set to use solid colors. Valid options are those available in matplotlib.

iso_value property writable

Returns:

Type Description
float

The value to set the isosurface to.

lattice_thickness property writable

Returns:

Type Description
float

The thickness of the lines outlining the unit cell.

light_color property writable

Returns:

Type Description
str

The color of the light shining on the scene as a hex code, rgb array, or color string.

light_intensity property writable

Returns:

Type Description
str

The intensity of the light on the scene from 0-1

parallel_projection property writable

Returns:

Type Description
bool

If True, a parallel projection scheme will be used rather than perspective.

pbr property writable

Returns:

Type Description
bool

If True, physically based rendering will be used

radii_scale property writable

Returns:

Type Description
float

A constant to multiply atom radii by

show_axes property writable

Returns:

Type Description
bool

Whether or not to show the axis widget.

show_caps property writable

Returns:

Type Description
bool

Whether or not to display caps on the isosurface.

show_lattice property writable

Returns:

Type Description
bool

Whether or not to display the outline of the unit cell.

show_surface property writable

Returns:

Type Description
bool

whether or not to display the isosurface.

surface_color property writable

Returns:

Type Description
str

The color to use for the surface as a hex string. This is ignored if the surface is not set to use solid colors.

surface_opacity property writable

Returns:

Type Description
float

Opacity of the isosurface.

use_solid_cap_color property writable

Returns:

Type Description
bool

whether or not to use a solid color for the caps.

use_solid_surface_color property writable

Returns:

Type Description
bool

whether or not to use a solid color for the isosurface.

add_slice(hkl, d=1.0, key=None)

Adds a slice of the grid to the plot. If a key is provided, this updates the corresponding slice rather than adding a new one.

Parameters:

Name Type Description Default
hkl NDArray

The miller indices of the plane

required
d float

The multiplier for the d-spacing of the plane

1.0
key int

A integer key for an existing plane to update. The default is None.

None
Source code in src/baderkit/plotting/toolkit/grid.py
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def add_slice(
    self,
    hkl: NDArray,
    d: float = 1.0,
    key=None,
):
    """
    Adds a slice of the grid to the plot. If a key is provided, this updates
    the corresponding slice rather than adding a new one.

    Parameters
    ----------
    hkl : NDArray
        The miller indices of the plane
    d : float
        The multiplier for the d-spacing of the plane
    key : int, optional
        A integer key for an existing plane to update. The default is None.

    """

    if key is not None:
        name = f"slice_{key}"
        assert (
            name in self._slice_meshes.keys()
        ), "Key must correspond to an existing slice"
    else:
        if len(self._slice_meshes.keys()) > 0:
            idx = max(list(self._slice_meshes.keys())) + 1
        else:
            idx = 0
        name = f"slice_{idx}"

    h, k, l = hkl
    # get normal vector in cart coords
    normal = self.structure.get_cart_from_miller(h, k, l)
    n = self.structure.lattice.d_hkl(hkl)
    origin = normal * n * d
    slice_plane = self._structured_grid.slice(normal=normal, origin=origin)

    self._slice_meshes[name] = slice_plane
    self._slice_planes[name] = (origin, normal)
    self._slice_hkls[name] = (hkl, d)
    # get key if no
    # create plotter
    self.plotter.add_mesh(
        slice_plane,
        scalars="values",
        cmap=self.colormap,
        clim=(self.min_val, self.max_val),
        show_scalar_bar=False,
        name=name,
    )

get_plot_html()

Creates an html string representing the current state of the StructurePlotter class.

Returns:

Type Description
str

The html string representing the current StructurePlotter class.

Source code in src/baderkit/plotting/base/base.py
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
def get_plot_html(self) -> str:
    """
    Creates an html string representing the current state of the StructurePlotter
    class.

    Returns
    -------
    str
        The html string representing the current StructurePlotter class.

    """
    if sys.platform == "win32":
        # We can return the html directly without opening a subprocess. And
        # we need to because the "fork" start method doesn't work
        html_plotter = self.plotter.export_html(filename=None)
        return html_plotter.read()
    # BUG-FIX: On Linux and maybe MacOS, pyvista's export_html must be run
    # as a main process. To do this within our streamlit apps, we use python's
    # multiprocess to run the process as is done in [stpyvista](https://github.com/edsaac/stpyvista/blob/main/src/stpyvista/trame_backend.py)
    queue = Queue(maxsize=1)
    process = Process(target=_export_html, args=(queue, self.plotter))
    process.start()
    html_plotter = queue.get().read()
    process.join()
    return html_plotter

get_plot_screenshot(filename=None, transparent_background=None, return_img=True, window_size=None, scale=None)

Creates a screenshot of the current state of the StructurePlotter class. This is a wraparound of pyvista's screenshot method

Parameters:

Name Type Description Default
filename str | Path | BytesIO

Location to write image to. If None, no image is written.

None
transparent_background bool

Whether to make the background transparent. The default is looked up on the plotter’s theme.

None
return_img bool

If True, a numpy.ndarray of the image will be returned. Defaults to True.

True
window_size tuple[int, int]

Set the plotter’s size to this (width, height) before taking the screenshot.

None
scale int

Set the factor to scale the window size to make a higher resolution image. If None this will use the image_scale property on this plotter which defaults to one.

None

Returns:

Type Description
NDArray[float]

Array containing pixel RGB and alpha. Sized:

[Window height x Window width x 3] if transparent_background is set to False.

[Window height x Window width x 4] if transparent_background is set to True.

Source code in src/baderkit/plotting/base/base.py
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
def get_plot_screenshot(
    self,
    filename: str | Path | io.BytesIO = None,
    transparent_background: bool = None,
    return_img: bool = True,
    window_size: tuple[int, int] = None,
    scale: int = None,
) -> NDArray[float]:
    """
    Creates a screenshot of the current state of the StructurePlotter class.
    This is a wraparound of pyvista's screenshot method

    Parameters
    ----------
    filename: str | Path | io.BytesIO
        Location to write image to. If None, no image is written.

    transparent_background: bool
        Whether to make the background transparent.
        The default is looked up on the plotter’s theme.

    return_img: bool
        If True, a numpy.ndarray of the image will be returned. Defaults to
        True.

    window_size: tuple[int, int]
        Set the plotter’s size to this (width, height) before taking the
        screenshot.

    scale: int
        Set the factor to scale the window size to make a higher resolution image. If None this will use the image_scale property on this plotter which defaults to one.

    Returns
    -------
    NDArray[float]
        Array containing pixel RGB and alpha. Sized:

        [Window height x Window width x 3] if transparent_background is set to False.

        [Window height x Window width x 4] if transparent_background is set to True.

    """

    plotter = self.plotter

    # if our plotter is not currently rendered, we want to temporarily set
    # it to be off screen to take the screenshot, then set it back
    plotter.render()
    screenshot = plotter.screenshot(
        filename=filename,
        transparent_background=transparent_background,
        return_img=return_img,
        window_size=window_size,
        scale=scale,
    )

    return screenshot

plot_slice(key, include_atoms=True, filename=None, **write_kwargs)

Generates a pyvista plot of a slice at the requested miller plane. If a filename is provided, the plot is written and no plot object is returned.

Parameters:

Name Type Description Default
key int

The key of the plane to plot

required
include_atoms bool

Whether or not atoms should be incuded. Only atoms whose sphere mesh is sliced by the plane are included. The default is True.

True
filename Path

The filename to write the plot to if desired. The default is None.

None
**write_kwargs

any additional keyword arguments to provide to the plot writer.

{}

Returns:

Name Type Description
p plotter | None

the pyvista plot of the slice or None if a filename was provided.

Source code in src/baderkit/plotting/toolkit/grid.py
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def plot_slice(
    self,
    key,
    include_atoms: bool = True,
    filename: Path = None,
    **write_kwargs,
):
    """
    Generates a pyvista plot of a slice at the requested miller plane. If
    a filename is provided, the plot is written and no plot object is returned.

    Parameters
    ----------
    key : int
        The key of the plane to plot
    include_atoms : bool, optional
        Whether or not atoms should be incuded. Only atoms whose sphere mesh
        is sliced by the plane are included. The default is True.
    filename : Path, optional
        The filename to write the plot to if desired. The default is None.
    **write_kwargs
        any additional keyword arguments to provide to the plot writer.

    Returns
    -------
    p : pv.plotter | None
        the pyvista plot of the slice or None if a filename was provided.

    """
    if key is not None:
        name = f"slice_{key}"
        assert (
            name in self._slice_meshes.keys()
        ), "Key must correspond to an existing slice"
    # create plotter
    mesh = self._slice_meshes[name]

    p = StructurePlotter(
        structure=self.structure,
        off_screen=True,
        show_axes=False,
        show_lattice=False,
    )
    p.plotter.add_mesh(
        mesh,
        scalars="values",
        cmap=self.colormap,
        clim=(self.min_val, self.max_val),
        show_scalar_bar=False,
    )

    origin, normal = self._slice_planes[name]
    # if desired, add any atoms that sit on/near the plane
    if include_atoms:
        # get wrapped atom points
        atom_poly = p._wrapped_atom_poly
        points = atom_poly.points
        include_coords = np.zeros(len(points), dtype=np.bool_)
        for wrap_idx, (atom_idx, center) in enumerate(
            zip(self._map_wrapped_to_atoms, points)
        ):

            radius = self.atom_radii[atom_idx] * self.radii_scale
            dist = np.dot(center - origin, normal)
            if abs(dist) >= radius:
                continue
            # otherwise add
            include_coords[wrap_idx] = True

        # get atom colors
        atom_colors = self.atom_colors[self._map_wrapped_to_atoms]
        # get alpha values
        alpha = self.atom_opacities[self._map_wrapped_to_atoms]
        # set alpha to zero at unwanted atoms
        alpha[~include_coords] = 0.0
        # update poly data scalars
        atom_poly["atom_colors"] = np.column_stack((atom_colors, alpha))
        atom_poly["atom_radii"] = (
            self.atom_radii[self._map_wrapped_to_atoms] * self.radii_scale
        )

        # generate glyphs
        glyphs = atom_poly.glyph(
            geom=self._sphere_mesh, scale="atom_radii", orient=False
        )

        # add the atom glyphs to our plotter. This automatically overwrites any
        # previous meshes
        p.plotter.add_mesh(
            glyphs,
            scalars="atom_colors",
            rgb=True,
            name="atom_glyphs",
            pbr=self.pbr,
        )
    else:
        # otherwise, remove all atoms from the plot
        visible = p.atom_opacities
        visible[:] = 0.0
        p.atom_opacities = visible

    # set camera to be perpendicular
    p.set_camera_to_vector(origin=origin, normal=normal)
    p._set_camera_tight()

    if filename is not None:
        p.get_plot_screenshot(filename=filename, **write_kwargs)
    else:
        image = p.get_plot_screenshot(return_image=True, **write_kwargs)
        return image

rebuild()

Builds a new pyvista plotter object representing the current state of the Plotter class.

Returns:

Type Description
Plotter

A pyvista Plotter object representing the current state of the StructurePlotter class.

Source code in src/baderkit/plotting/base/base.py
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
def rebuild(self) -> pv.Plotter:
    """
    Builds a new pyvista plotter object representing the current state of
    the Plotter class.

    Returns
    -------
    pv.Plotter
        A pyvista Plotter object representing the current state of the
        StructurePlotter class.

    """
    self.plotter = None
    plotter = self._create_plotter()
    plotter.suppress_rendering = True
    self._suppressing = True
    self._create_plot()
    plotter.suppress_rendering = False
    self._suppressing = True

show()

Renders the plot to a window. After closing the window, a new instance must be created to plot again. Pressing q pauses the rendering allowing changes to be made without fully exiting.

Returns:

Type Description
None.
Source code in src/baderkit/plotting/base/base.py
601
602
603
604
605
606
607
608
609
610
611
612
613
def show(self):
    """
    Renders the plot to a window. After closing the window, a new instance
    must be created to plot again. Pressing q pauses the rendering allowing
    changes to be made without fully exiting.

    Returns
    -------
    None.

    """

    self.plotter.show()

soft_rebuild()

reuilds the current pyvista plotter object with current settings.

Returns:

Type Description
Plotter

A pyvista Plotter object representing the current state of the StructurePlotter class.

Source code in src/baderkit/plotting/base/base.py
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def soft_rebuild(self) -> pv.Plotter:
    """
    reuilds the current pyvista plotter object with current settings.

    Returns
    -------
    pv.Plotter
        A pyvista Plotter object representing the current state of the
        StructurePlotter class.

    """
    plotter = self.plotter
    if plotter is None:
        plotter = self._create_plotter()
    plotter.suppress_rendering = True
    self._suppressing = True
    self._create_plot()
    plotter.suppress_rendering = False
    self._suppressing = True