Skip to content

Grid

Bases: StructurePlotter

Source code in src/baderkit/plotting/core/plotter.py
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
class GridPlotter(StructurePlotter):
    def __init__(
        self,
        grid: Grid,
        off_screen: bool = False,
        # downscale: int | None = 400,
    ):
        """
        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.
        off_screen : bool, optional
            Whether or not the plotter should be in offline mode. The default is False.

        Returns
        -------
        None.

        """
        # apply StructurePlotter kwargs
        structure = grid.structure
        super().__init__(structure=structure, off_screen=off_screen)

        # Grid specific items
        # if downscale is not None:
        #     if grid.voxel_resolution > downscale:
        #         # downscale the grid for speed
        #         logging.info("Grid is above desired resolution. Downscaling.")
        #         grid = grid.regrid(downscale)
        self.grid = grid
        self._show_surface = True
        self._show_caps = True
        self._surface_opacity = 0.8
        self._cap_opacity = 0.8
        self._colormap = "viridis"
        self._use_solid_surface_color = False
        self._use_solid_cap_color = False
        self._surface_color = "#BA8E23"
        self._cap_color = "#BA8E23"

        # wrap values around to get one extra voxel on the far side of each axis.
        values = np.pad(grid.total, pad_width=((0, 1), (0, 1), (0, 1)), mode="wrap")
        self.shape = values.shape
        self.values = values.ravel(order="F")
        self.min_val = self.values.min()
        # make min val slightly above 0
        self.min_val += +0.0000001 * self.min_val
        self.max_val = self.values.max()
        # determine default iso if not provided
        self._iso_val = self.min_val  # np.mean(grid.total)
        # generate the structured grid
        indices = np.indices(self.shape).reshape(3, -1, order="F").T
        self.points = grid.get_cart_coords_from_vox(indices)
        self.structured_grid = self._make_structured_grid(self.values)
        # generate the surface
        self.surface = self.structured_grid.extract_surface()
        # update plotter
        self.plotter = self._create_grid_plot(off_screen)

    def _make_structured_grid(self, values: NDArray[float]) -> pv.StructuredGrid:
        """
        Creates a pyvista StructuredGrid object for making isosurfaces. This
        should generally not be called directly.

        Parameters
        ----------
        values : NDArray[float]
            A 3xN array of values representing the data in the structured grid.
            These should be raveled/reshaped using Fortran's conventions (order='F'')

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

        """
        structured_grid = pv.StructuredGrid()
        structured_grid.points = self.points
        structured_grid.dimensions = self.shape
        structured_grid["values"] = values
        return structured_grid

    @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 "iso" in self.plotter.actors.keys():
            actor = self.plotter.actors["iso"]
            actor.visibility = show_surface
        self._show_surface = show_surface

    @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 "cap" in self.plotter.actors.keys():
            actor = self.plotter.actors["cap"]
            actor.visibility = show_caps
        self._show_caps = show_caps

    @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 "iso" in self.plotter.actors.keys():
            actor = self.plotter.actors["iso"]
            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" in self.plotter.actors.keys():
            actor = self.plotter.actors["cap"]
            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):
        # update settings
        self._colormap = colormap
        if not self.use_solid_surface_color:
            self._add_iso_mesh()
        if not self.use_solid_cap_color:
            self._add_cap_mesh()

    @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):
        # update property
        self._use_solid_surface_color = use_solid_surface_color
        # remove surface and add it back with new color/cmap
        self._add_iso_mesh()

    @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):
        # update property
        self._use_solid_cap_color = use_solid_cap_color
        # remove cap and add it back with new color/cmap
        self._add_cap_mesh()

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

        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):
        self._surface_color = surface_color
        if self.use_solid_surface_color:
            self._add_iso_mesh()

    @property
    def cap_color(self):
        """

        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):
        self._cap_color = cap_color
        if self.use_solid_cap_color:
            self._add_cap_mesh()

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

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

        """
        return self._iso_val

    @iso_val.setter
    def iso_val(self, iso_val: float):
        # make sure iso value is within range
        iso_val = max(self.min_val, min(iso_val, self.max_val))
        self._update_surface_mesh(iso_val)
        self._add_iso_mesh()
        self._add_cap_mesh()

    def _update_surface_mesh(self, iso_value: float):
        """
        Updates the surface meshes to the provided iso_value

        Parameters
        ----------
        iso_value : float
            The value to update the surface meshes to

        Returns
        -------
        None.

        """
        self.iso = self.structured_grid.contour([iso_value])
        self.cap = self.surface.contour_banded(
            2, rng=[iso_value, self.max_val], generate_contour_edges=False
        )

    def _get_surface_kwargs(self) -> dict:
        """
        Generates the keyword arguments to use when adding the surface to
        the plotter. We need this because setting a solid color vs. a colormap
        requires different keywords

        Returns
        -------
        dict
            The keyword arguments for setting the surface mesh in the plotter.

        """
        kwargs = {
            "opacity": self.surface_opacity,
            "pbr": True,
            "name": "iso",
        }
        kwargs["color"] = self.surface_color
        if self.use_solid_surface_color:
            kwargs["color"] = self.surface_color
        else:
            kwargs["colormap"] = self.colormap
            kwargs["scalars"] = "values"
            kwargs["clim"] = [self.min_val, self.max_val]
            kwargs["show_scalar_bar"] = False
        return kwargs

    def _get_cap_kwargs(self) -> dict:
        """
        Generates the keyword arguments to use when adding the caps to
        the plotter. We need this because setting a solid color vs. a colormap
        requires different keywords

        Returns
        -------
        dict
            The keyword arguments for setting the caps mesh in the plotter.

        """
        kwargs = {
            "opacity": self.cap_opacity,
            "pbr": True,
            "name": "cap",
        }
        if self.use_solid_cap_color:
            kwargs["color"] = self.cap_color
        else:
            kwargs["cmap"] = self.colormap
            kwargs["scalars"] = "values"
            kwargs["clim"] = [self.min_val, self.max_val]
            kwargs["show_scalar_bar"] = False
        return kwargs

    def _add_iso_mesh(self):
        """
        Removes the current isosurface mesh than adds a new one.

        Returns
        -------
        None.

        """
        if self.show_surface:
            if "iso" in self.plotter.actors.keys():
                self.plotter.remove_actor("iso")
            if len(self.iso["values"]) > 0:
                self.plotter.add_mesh(self.iso, **self._get_surface_kwargs())

    def _add_cap_mesh(self) -> dict:
        """
        Removes the current cap mesh than adds a new one.

        Returns
        -------
        None.

        """
        if self.show_caps:
            if "cap" in self.plotter.actors.keys():
                self.plotter.remove_actor("cap")
            if len(self.iso["values"]) > 0:
                self.plotter.add_mesh(self.cap, **self._get_cap_kwargs())

    def _create_grid_plot(self, off_screen) -> 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.

        Parameters
        ----------
        off_screen : bool
            Whether or not the plotter should run in off_screen mode.

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

        """
        # get initial plotter with structure
        plotter = self._create_structure_plot(off_screen=off_screen)
        # generate initial surface meshes
        self._update_surface_mesh(self.iso_val)
        # Add iso mesh
        if len(self.iso["values"]) > 0:
            plotter.add_mesh(self.iso, **self._get_surface_kwargs())
        # Add cap mesh
        if len(self.cap["values"]) > 0:
            plotter.add_mesh(self.cap, **self._get_cap_kwargs())
        return plotter

    def rebuild(self):
        """
        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
            GridPlotter class.

        """
        return self._create_grid_plot(self._off_screen)

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

Returns:

Type Description
float

The value to set the isosurface to.

show_caps property writable

Returns:

Type Description
bool

Whether or not to display caps on the isosurface.

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.

__init__(grid, off_screen=False)

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
off_screen bool

Whether or not the plotter should be in offline mode. The default is False.

False

Returns:

Type Description
None.
Source code in src/baderkit/plotting/core/plotter.py
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
def __init__(
    self,
    grid: Grid,
    off_screen: bool = False,
    # downscale: int | None = 400,
):
    """
    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.
    off_screen : bool, optional
        Whether or not the plotter should be in offline mode. The default is False.

    Returns
    -------
    None.

    """
    # apply StructurePlotter kwargs
    structure = grid.structure
    super().__init__(structure=structure, off_screen=off_screen)

    # Grid specific items
    # if downscale is not None:
    #     if grid.voxel_resolution > downscale:
    #         # downscale the grid for speed
    #         logging.info("Grid is above desired resolution. Downscaling.")
    #         grid = grid.regrid(downscale)
    self.grid = grid
    self._show_surface = True
    self._show_caps = True
    self._surface_opacity = 0.8
    self._cap_opacity = 0.8
    self._colormap = "viridis"
    self._use_solid_surface_color = False
    self._use_solid_cap_color = False
    self._surface_color = "#BA8E23"
    self._cap_color = "#BA8E23"

    # wrap values around to get one extra voxel on the far side of each axis.
    values = np.pad(grid.total, pad_width=((0, 1), (0, 1), (0, 1)), mode="wrap")
    self.shape = values.shape
    self.values = values.ravel(order="F")
    self.min_val = self.values.min()
    # make min val slightly above 0
    self.min_val += +0.0000001 * self.min_val
    self.max_val = self.values.max()
    # determine default iso if not provided
    self._iso_val = self.min_val  # np.mean(grid.total)
    # generate the structured grid
    indices = np.indices(self.shape).reshape(3, -1, order="F").T
    self.points = grid.get_cart_coords_from_vox(indices)
    self.structured_grid = self._make_structured_grid(self.values)
    # generate the surface
    self.surface = self.structured_grid.extract_surface()
    # update plotter
    self.plotter = self._create_grid_plot(off_screen)

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 GridPlotter class.

Source code in src/baderkit/plotting/core/plotter.py
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
def rebuild(self):
    """
    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
        GridPlotter class.

    """
    return self._create_grid_plot(self._off_screen)