Skip to content

BaderPlotter

Bases: BaseAnalysis

A convenience class for creating plots of individual Bader basins using pyvista's package for VTK.

Parameters:

Name Type Description Default
bader Bader

The Bader object to use for isolating basins and creating isosurfaces. The structure will be pulled from the charge grid.

required
grid_name str

The name of the grid property with the desired data to plot. Options are 'charge_grid', 'total_charge_grid', or 'reference_grid'. The default is 'reference_grid'

'reference_grid'

Returns:

Type Description
None.
Source code in src/baderkit/plotting/bader/bader.py
 8
 9
10
11
12
13
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
class BaderPlotter(BaseAnalysis):
    """
    A convenience class for creating plots of individual Bader basins
    using pyvista's package for VTK.

    Parameters
    ----------
    bader : Bader
        The Bader object to use for isolating basins and creating isosurfaces.
        The structure will be pulled from the charge grid.
    grid_name : str, optional
        The name of the grid property with the desired data to plot. Options
        are 'charge_grid', 'total_charge_grid', or 'reference_grid'. The
        default is 'reference_grid'

    Returns
    -------
    None.

    """

    _label_grids = [
        "maxima_basin_labels",
        "atom_labels",
    ]
    _alt_label_names = {
        "maxima_basin_labels": "bader_basins",
        "atom_labels": "atom_basins",
    }

    def __init__(
        self,
        bader: Bader,
        grid_name: str = "reference_grid",
        **kwargs,
    ):

        super().__init__(base_analysis=bader, grid_name=grid_name, **kwargs)

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.

grid_name property writable

Returns:

Type Description
str

The name of the grid to plot

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