Skip to content

StructurePlotter

Bases: VtkPlotter

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

Parameters:

Name Type Description Default
structure Structure

The pymatgen Structure object to plot.

required
Source code in src/baderkit/plotting/toolkit/structure.py
 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
class StructurePlotter(VtkPlotter):
    """
    A convenience class for creating plots of crystal structures using
    pyvista's package for VTK.

    Parameters
    ----------
    structure : Structure
        The pymatgen Structure object to plot.

    """

    def __init__(
        self,
        structure: Structure,
        wrap_atoms=True,
        atom_metallicness=0.0,
        atom_roughness=0.0,
        radii_scale=0.3,
        atom_radii=None,
        atom_colors=None,
        **kwargs,
    ):

        # create initial class variables
        self._atom_opacities = np.array([1 for i in range(len(structure))], dtype=float)
        self._wrap_atoms = wrap_atoms
        self._atom_metallicness = atom_metallicness
        self._atom_roughness = atom_roughness
        self._radii_scale = radii_scale
        radii = []
        for s in structure:
            try:
                radius = s.specie.atomic_radius
            except:
                radius = 1.0
            radii.append(radius)
        self._atom_radii = np.array(radii)
        self._atom_colors = np.array(
            [ATOM_COLORS.get(s.specie.symbol, (1.00, 1.00, 1.00)) for s in structure]
        )

        # atom poly data
        self._map_wrapped_to_atoms = None
        self._atom_poly = None
        self._wrapped_atom_poly = None
        self._sphere_mesh = pv.Sphere(
            radius=1.0, theta_resolution=15, phi_resolution=15
        )
        # generate initial plotter
        super().__init__(structure=structure, **kwargs)
        if atom_radii is not None:
            try:
                self.atom_radii = atom_radii
            except:
                logging.info("Improper atom radii provided. Defaults will be used")
        if atom_colors is not None:
            try:
                self.atom_colors = atom_colors
            except:
                logging.info("Improper atom colors provided. Defaults will be used")

    ###########################################################################
    # Properties and Setters
    ###########################################################################
    @property
    def atom_opacities(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            Whether or not each atom is visible. This is actually the opacity
            if desired.

        """
        return self._atom_opacities

    @atom_opacities.setter
    def atom_opacities(self, atom_opacities: NDArray[float]):

        # convert to array
        atom_opacities = np.array(atom_opacities, dtype=np.float64)

        # make sure we have the write shape
        assert (
            self.atom_opacities.shape == atom_opacities.shape
        ), "Length match the number of atoms"

        # set visible atoms
        self._atom_opacities = atom_opacities
        # update
        self._update_site_meshes()

    @property
    def wrap_atoms(self):
        return self._wrap_atoms

    @wrap_atoms.setter
    def wrap_atoms(self, wrap_atoms: bool):
        assert type(wrap_atoms) == bool, "wrap_atoms must be a bool"

        # update
        self._wrap_atoms = wrap_atoms
        self._update_site_meshes()

    @property
    def atom_radii(self) -> NDArray[float]:
        """

        Returns
        -------
        NDArray[float]
            The radius to display for each atom in the structure. The actual
            displayed radius will be radii_scale*radius.

        """
        return self._atom_radii

    @atom_radii.setter
    def atom_radii(self, atom_radii: NDArray[float]):
        # fix atom_radii to be a list and make any negative values == 0.01
        atom_radii = np.array(atom_radii, dtype=np.float64)
        assert (
            self.atom_radii.shape == atom_radii.shape
        ), "Length match the number of atoms"

        atom_radii[atom_radii <= 0.01] = 0.01
        self._atom_radii = atom_radii
        self._update_site_meshes()

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

        Returns
        -------
        float
            A constant to multiply atom radii by

        """
        return self._radii_scale

    @radii_scale.setter
    def radii_scale(self, radii_scale: float):
        # ensure scale is not at or below zero
        radii_scale = float(radii_scale)
        radii_scale = max(radii_scale, 0.1)
        # update
        self._radii_scale = radii_scale
        self._update_site_meshes()

    @property
    def atom_colors(self) -> list[str]:
        """

        Returns
        -------
        list[str]
            The atom_colors to use for each atom as hex codes.

        """
        return self._atom_colors

    @atom_colors.setter
    def atom_colors(self, atom_colors: NDArray[float | str]):
        # for each site, check if the radius has changed and if it has remove it
        # then remake
        assert len(self.atom_colors) == len(
            atom_colors
        ), "Length match the number of atoms"

        # convert provided colors to rgb
        atom_colors = np.array(
            [pv.Color(i).float_rgb for i in atom_colors], dtype=np.float64
        )
        self._atom_colors = atom_colors
        self._update_site_meshes()

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

        Returns
        -------
        float
            The amount of metallic character in the atom display.

        """
        return self._atom_metallicness

    @atom_metallicness.setter
    def atom_metallicness(self, atom_metallicness: float):
        # update all atoms
        actor = self.plotter.actors["atom_glyphs"]
        actor.prop.metallic = atom_metallicness
        self._atom_metallicness = atom_metallicness

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

        Returns
        -------
        float
            The amount of roughness in the atom display.

        """
        return self._atom_roughness

    @atom_roughness.setter
    def atom_roughness(self, atom_roughness: float):
        # update all atoms
        actor = self.plotter.actors["atom_glyphs"]
        actor.prop.roughness = atom_roughness
        self._atom_roughness = atom_roughness

    @property
    def atom_df(self) -> pd.DataFrame:
        """

        Returns
        -------
        atom_df : TYPE
            A dataframe summarizing the properties of the atom meshes.

        """
        # construct a pandas dataframe for each atom
        visible = self.atom_opacities > 0
        atom_df = pd.DataFrame(
            {
                "Label": self.structure.labels,
                "Visible": visible,
                "Color": self.atom_colors,
                "Radius": self.atom_radii,
            }
        )
        return atom_df

    @atom_df.setter
    def atom_df(self, atom_df: pd.DataFrame):
        # set each property from the dataframe
        self.atom_opacities = atom_df["Visible"]
        self.atom_colors = atom_df["Color"]
        self.atom_radii = atom_df["Radius"]

    def _create_atom_polydata(self):
        wrapped_atom_coords = []
        corresponding_sites = []

        for i in range(len(self.structure)):
            frac_coords = self.structure.frac_coords[i]
            # get wrapped atoms as well
            wrapped_coords, shifts = self._wrap_near_edge(frac_coords)
            cart_coords = wrapped_coords @ self.structure.lattice.matrix
            # add to lists
            wrapped_atom_coords.extend(cart_coords)
            for j, shift in enumerate(shifts):
                corresponding_sites.append(i)

        # save the map from wrapped points to their original site
        self._map_wrapped_to_atoms = np.array(corresponding_sites, dtype=int)
        # create poly data of points for both the atoms with and without wrapping
        self._atom_poly = pv.PolyData(self.structure.cart_coords)
        self._wrapped_atom_poly = pv.PolyData(wrapped_atom_coords)

    def _update_site_meshes(self):
        if self._wrapped_atom_poly is None or self._atom_poly is None:
            self._create_atom_polydata()

        # get appropriate poly data
        if self.wrap_atoms:
            # get poly data including wrapped atoms
            atoms = self._wrapped_atom_poly
            # 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]
            # get radii
            radii = self.atom_radii[self._map_wrapped_to_atoms] * self.radii_scale
        else:
            # get poly data without wrapped atoms
            atoms = self._atom_poly
            # get atom colors
            atom_colors = self.atom_colors
            # get alpha values
            alpha = self.atom_opacities
            # get radii
            radii = self.atom_radii * self.radii_scale

        sphere = self._sphere_mesh
        # add alpha to colors
        colors = np.column_stack((atom_colors, alpha))

        # update poly data scalars
        atoms["atom_colors"] = colors
        atoms["atom_radii"] = radii

        # generate glyphs
        glyphs = atoms.glyph(geom=sphere, scale="atom_radii", orient=False)

        # add the atom glyphs to our plotter. This automatically overwrites any
        # previous meshes
        self.plotter.add_mesh(
            glyphs,
            scalars="atom_colors",
            rgb=True,
            name="atom_glyphs",
            pbr=self.pbr,
        )

    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()

        # add site meshes
        self._update_site_meshes()

        return plotter

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.

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_lattice property writable

Returns:

Type Description
bool

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

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

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