Skip to content

gemdat.shape

ShapeAnalyzer(*, sites, lattice, spacegroup)

The goal for this class is to have a generalized algorithm that for all symmetrically equivalent cluster centers, finds nearest atoms from trajectory or other list of positions, and transforms them back to the asymmetric unit.

Combining symmetrically equivalent coordinates helps the statistics for performing shape analysis.

Parameters:

  • sites (Collection[PeriodicSite]) –

    Collection of sites to cluster around

  • lattice (Lattice) –

    Input lattice

  • spacegroup (SpaceGroup) –

    Input spacegroup

Source code in src/gemdat/shape.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def __init__(
    self,
    *,
    sites: Collection[PeriodicSite],
    lattice: Lattice,
    spacegroup: SpaceGroup | SpacegroupOperations,
):
    """Set up shape analyzer from a collection of unique periodic sites,
    the lattice, and spacegroup.

    Parameters
    ----------
    sites : Collection[PeriodicSite]
        Collection of sites to cluster around
    lattice : Lattice
        Input lattice
    spacegroup : SpaceGroup
        Input spacegroup
    """
    self.sites = sites
    self.lattice = lattice
    self.spacegroup = spacegroup

analyze_positions(positions, *, radius=1.0)

Perform shape analysis on array of fractional coordinates.

Parameters:

  • positions (ndarray) –

    (n, 3) input array fractional coordinates. These must correspond to the same lattice as the structure used to instantiate this class.

  • supercell (None | tuple[float, float, float]) –

    If the trajectory is in a supercell of the input structure, the given supercell used to fold trajectory positions into same lattice.

  • radius (float, default: 1.0 ) –

    Cluster symmetrically equivalent positions within this distance from [unique_sites][ShapeAnalyzer.unique_sites].

Returns:

Source code in src/gemdat/shape.py
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
def analyze_positions(
    self, positions: np.ndarray, *, radius: float = 1.0
) -> list[ShapeData]:
    """Perform shape analysis on array of fractional coordinates.

    Parameters
    ----------
    positions : np.ndarray
        (n, 3) input array fractional coordinates. These must correspond to
        the same lattice as the structure used to instantiate this class.
    supercell : None | tuple[float, float, float], optional
        If the trajectory is in a supercell of the input structure,
        the given supercell used to fold trajectory positions into same
        lattice.
    radius : float, optional
        Cluster symmetrically equivalent positions
        within this distance from [unique_sites][ShapeAnalyzer.unique_sites].

    Returns
    -------
    shapes : list[ShapeData]
        Output shapes
    """
    shapes = []

    for site in self.sites:
        eqv_coords = self.find_equivalent_positions(
            site=site, positions=positions, radius=radius
        )

        shape = ShapeData(
            site=site,
            coords=eqv_coords,
            radius=radius,
        )

        shapes.append(shape)

    return shapes

analyze_trajectory(trajectory, *, supercell=None, radius=1.0)

Perform shape analysis on trajectory.

Similar to [analyze_positions()][ShapeAnalyzer.analyze_positions]. Handles coordinate conversion it trajectory is a supercell of the structure used to instantiate this class. The trajectory lattice must be similar or a supercell thereof.

Parameters:

  • trajectory (Trajectory) –

    Input trajectory.

  • supercell (None | tuple[float, float, float], default: None ) –

    If the trajectory is in a supercell of the input structure, the given supercell used to fold trajectory positions into same lattice.

  • radius (float, default: 1.0 ) –

    Cluster symmetrically equivalent positions within this distance from [unique_sites][ShapeAnalyzer.unique_sites].

Returns:

Source code in src/gemdat/shape.py
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
def analyze_trajectory(
    self,
    trajectory: Trajectory,
    *,
    supercell: None | tuple[float, float, float] = None,
    radius: float = 1.0,
) -> list[ShapeData]:
    """Perform shape analysis on trajectory.

    Similar to [analyze_positions()][ShapeAnalyzer.analyze_positions]. Handles
    coordinate conversion it trajectory is a supercell of the structure used to
    instantiate this class. The trajectory lattice must be similar or a
    supercell thereof.

    Parameters
    ----------
    trajectory : Trajectory
        Input trajectory.
    supercell : None | tuple[float, float, float], optional
        If the trajectory is in a supercell of the input structure,
        the given supercell used to fold trajectory positions into same
        lattice.
    radius : float, optional
        Cluster symmetrically equivalent positions
        within this distance from [unique_sites][ShapeAnalyzer.unique_sites].

    Returns
    -------
    shapes : list[ShapeData]
        Output shapes
    """
    test_lattice = trajectory.get_lattice(0)
    positions = trajectory.positions.reshape(-1, 3)

    if supercell is not None:
        scale_arr = np.array(supercell)

        scale_matrix = (1 / scale_arr) * np.eye(3)
        test_lattice = Lattice(np.dot(scale_matrix, test_lattice.matrix))

        positions = np.mod(positions, 1 / scale_arr) * scale_arr

    warn_lattice_not_close(self.lattice, test_lattice)

    return self.analyze_positions(positions=positions, radius=radius)

find_equivalent_positions(*, site, positions, radius=1.0)

Cluster all symmetrically equivalent positions within sphere around site.

All equivalent positions are transformed back to the identity symmetry operation.

Algorithm: - For every symmetry operation - Apply next symmetry operation to site coords - Find all positions within threshold radius - Copy and map points back to asymmetric unit (reverse symmetry op) - Subtract site coords (center on site)

Parameters:

  • site (PeriodicSite) –

    This site acts as the cluster center.

  • positions (ndarray) –

    Positions to sample from.

  • radius (float, default: 1.0 ) –

    Cluster symmetrically equivalent positions within this distance from the given site.

Returns:

  • centered ( ndarray ) –

    Clustered positions centered on site in Cartesian coordinate system

Source code in src/gemdat/shape.py
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
def find_equivalent_positions(
    self, *, site: PeriodicSite, positions: np.ndarray, radius: float = 1.0
) -> np.ndarray:
    """Cluster all symmetrically equivalent positions within sphere around
    `site`.

    All equivalent positions are transformed back to the identity symmetry
    operation.

    Algorithm:
    - For every symmetry operation
        - Apply next symmetry operation to site coords
        - Find all positions within threshold radius
        - Copy and map points back to asymmetric unit (reverse symmetry op)
        - Subtract site coords (center on site)

    Parameters
    ----------
    site : PeriodicSite
        This site acts as the cluster center.
    positions : np.ndarray
        Positions to sample from.
    radius : float, optional
        Cluster symmetrically equivalent positions
        within this distance from the given `site`.

    Returns
    -------
    centered : np.ndarray
        Clustered positions centered on `site` in Cartesian coordinate system
    """
    lattice = self.lattice
    spacegroup = self.spacegroup
    site_coords = site.frac_coords
    cluster = []

    for op in spacegroup:
        sym_coords = op.operate(site_coords)
        dists = lattice.get_all_distances(sym_coords, positions)

        sel = dists < radius
        close = positions[sel.flatten()]

        # digitize differences to move all close positions to
        # same sphere around coordr
        offsets = np.digitize(close - sym_coords, bins=[0.5, -0.4999999]) - 1
        close += offsets

        inversed = op.inverse.operate_multi(close)

        cluster.append(inversed)

    centered = np.vstack(cluster) - site_coords

    # convert to cartesian
    cart_coords = self.lattice.get_cartesian_coords(centered)
    return cart_coords

from_structure(structure) classmethod

Construct instance from [Structure][pymatgen.core.Structure].

The input structure will be symmetrized using SpacegroupAnalyzer.

Parameters:

  • structure (Structure) –

    Input structure

Source code in src/gemdat/shape.py
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
@classmethod
def from_structure(cls, structure: Structure):
    """Construct instance from [Structure][pymatgen.core.Structure].

    The input structure will be symmetrized using
    [SpacegroupAnalyzer][pymatgen.symmetry.analyzer.SpacegroupAnalyzer].

    Parameters
    ----------
    structure : Structure
        Input structure
    """
    sga = SpacegroupAnalyzer(structure)
    symmetrized_structure = sga.get_symmetrized_structure()
    return cls.from_symmetrized_structure(structure=symmetrized_structure)

from_symmetrized_structure(structure) classmethod

Construct instance from [SymmetrizedStructure][pymatgen.symmetry.str ucture.SymmetrizedStructure].

The input structure is already symmetrized using SpacegroupAnalyzer.

Parameters:

Source code in src/gemdat/shape.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
@classmethod
def from_symmetrized_structure(cls, structure: SymmetrizedStructure):
    """Construct instance from [SymmetrizedStructure][pymatgen.symmetry.str
    ucture.SymmetrizedStructure].

    The input structure is already symmetrized using
    [SpacegroupAnalyzer][pymatgen.symmetry.analyzer.SpacegroupAnalyzer].

    Parameters
    ----------
    structure : SymmetrizedStructure
        Input symmetrized structure structure
    """
    unique_sites = [sites[0] for sites in structure.equivalent_sites]
    lattice = structure.lattice
    spacegroup = structure.spacegroup
    return cls(sites=unique_sites, lattice=lattice, spacegroup=spacegroup)

optimize_sites(shapes, func=None)

Optimize unique sites from shape objects.

Note: This function does not take into account special positions.

Parameters:

  • shapes (Sequence[Shape]) –

    List of input shapes. These must match self.unique_sites

  • func (None | Callable, default: None ) –

    Specify function to calculate offsets in Cartesian setting. Must take Shape as its only argument. If None, use Shape.centroid() to determine offsets.

Returns:

  • shape_analyzer ( ShapeAnalyzer ) –

    Shape analyzer with optimized sites.

Source code in src/gemdat/shape.py
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
def optimize_sites(
    self, shapes: Sequence[ShapeData], func: None | Callable = None
) -> ShapeAnalyzer:
    """Optimize unique sites from shape objects.

    Note: This function does not take into account special positions.

    Parameters
    ----------
    shapes : Sequence[Shape]
        List of input shapes. These must match `self.unique_sites`
    func : None | Callable, optional
        Specify function to calculate offsets in Cartesian setting.
        Must take `Shape` as its only argument.
        If None, use `Shape.centroid()` to determine offsets.

    Returns
    -------
    shape_analyzer : ShapeAnalyzer
        Shape analyzer with optimized sites.
    """
    vectors = []

    for shape in shapes:
        if func:
            vector = func(shape)
        else:
            vector = shape.centroid()

        vectors.append(vector)

    return self.shift_sites(vectors=vectors, coords_are_cartesian=True)

shift_sites(vectors, coords_are_cartesian=True)

Shift .unique_sites by given vectors.

Parameters:

  • vectors (Sequence[None | Sequence[float, float, float]]) –

    List of vectors matching the sites. If None, do not shift this site.

  • coords_are_cartesian (bool, default: True ) –

    It true, vectors are cartesian, if false, fractional.

Returns:

  • shape_analyzer ( ShapeAnalyzer ) –

    Shape analyzer with shifted sites.

Source code in src/gemdat/shape.py
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
def shift_sites(
    self,
    vectors: Sequence[None | Sequence[float] | np.ndarray],
    coords_are_cartesian: bool = True,
) -> ShapeAnalyzer:
    """Shift `.unique_sites` by given vectors.

    Parameters
    ----------
    vectors : Sequence[None | Sequence[float, float, float]]
        List of vectors matching the sites.
        If None, do not shift this site.
    coords_are_cartesian : bool, optional
        It true, vectors are cartesian, if false, fractional.

    Returns
    -------
    shape_analyzer : ShapeAnalyzer
        Shape analyzer with shifted sites.
    """
    new_sites = []

    for site, offset in zip(self.sites, vectors):
        if offset is None:
            new_sites.append(site)
            continue

        coords = site.coords if coords_are_cartesian else site.frac_coords

        new_site = PeriodicSite(
            site.species,
            coords + offset,
            self.lattice,
            coords_are_cartesian=coords_are_cartesian,
            label=site.label,
        )
        new_sites.append(new_site)

    return ShapeAnalyzer(sites=new_sites, spacegroup=self.spacegroup, lattice=self.lattice)

to_structure()

Retrieve structure from this object.

Returns:

  • structure ( Structure ) –

    Pymatgen structure object

Source code in src/gemdat/shape.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def to_structure(self) -> Structure:
    """Retrieve structure from this object.

    Returns
    -------
    structure : Structure
        Pymatgen structure object
    """
    structure = Structure.from_spacegroup(
        sg=self.spacegroup.int_number,
        lattice=self.lattice,
        species=[site.specie for site in self.sites],
        coords=[site.frac_coords for site in self.sites],  # type: ignore
        labels=[site.label for site in self.sites],
    )
    return structure

ShapeData(site, coords, radius) dataclass

Data class for storing shape data.

Parameters:

  • name (str) –

    Name or label for associated with this shape

  • coords (ndarray) –

    (n, 3) coordinate array in cartesian system (Ã…)

  • radius (float) –

    Maximum distance from center (Ã…)

name property

Return name of shape.

origin property

Return origin coordinates for site.

x property

Return x coordinates.

y property

Return y coordinates.

z property

Return z coordinates.

centroid()

Find centroid (center of mass) for given set of coordinates.

Returns:

  • centroid ( ndarray ) –

    Center of coordinates.

Source code in src/gemdat/shape.py
67
68
69
70
71
72
73
74
75
76
def centroid(self) -> np.ndarray:
    """Find centroid (center of mass) for given set of coordinates.

    Returns
    -------
    centroid : np.ndarray
        Center of coordinates.
    """
    centroid = np.mean(self.coords, axis=0)
    return centroid

distances()

Return distances from origin in Ã….

Source code in src/gemdat/shape.py
38
39
40
def distances(self) -> np.ndarray:
    """Return distances from origin in Ã…."""
    return np.linalg.norm(self.coords, axis=1)

plot(*, module, **kwargs)

See gemdat.plots.shape for more info.

Source code in src/gemdat/shape.py
78
79
80
81
@plot_backend
def plot(self, *, module, **kwargs):
    """See [gemdat.plots.shape][] for more info."""
    return module.shape(shape=self, **kwargs)