Coverage for /builds/kinetik161/ase/ase/geometry/cell.py: 88.17%
93 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-12-10 11:04 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-12-10 11:04 +0000
1# Copyright (C) 2010, Jesper Friis
2# (see accompanying license files for details).
4# XXX bravais objects need to hold tolerance eps, *or* temember variant
5# from the beginning.
6#
7# Should they hold a 'cycle' argument or other data to reconstruct a particular
8# cell? (E.g. rotation, niggli transform)
9#
10# Implement total ordering of Bravais classes 1-14
12import numpy as np
13from numpy import arccos, cos, dot, pi, sin, sqrt
14from numpy.linalg import norm
17def unit_vector(x):
18 """Return a unit vector in the same direction as x."""
19 y = np.array(x, dtype='float')
20 return y / norm(y)
23def angle(x, y):
24 """Return the angle between vectors a and b in degrees."""
25 return arccos(dot(x, y) / (norm(x) * norm(y))) * 180. / pi
28def cell_to_cellpar(cell, radians=False):
29 """Returns the cell parameters [a, b, c, alpha, beta, gamma].
31 Angles are in degrees unless radian=True is used.
32 """
33 lengths = [np.linalg.norm(v) for v in cell]
34 angles = []
35 for i in range(3):
36 j = i - 1
37 k = i - 2
38 ll = lengths[j] * lengths[k]
39 if ll > 1e-16:
40 x = np.dot(cell[j], cell[k]) / ll
41 angle = 180.0 / pi * arccos(x)
42 else:
43 angle = 90.0
44 angles.append(angle)
45 if radians:
46 angles = [angle * pi / 180 for angle in angles]
47 return np.array(lengths + angles)
50def cellpar_to_cell(cellpar, ab_normal=(0, 0, 1), a_direction=None):
51 """Return a 3x3 cell matrix from cellpar=[a,b,c,alpha,beta,gamma].
53 Angles must be in degrees.
55 The returned cell is orientated such that a and b
56 are normal to `ab_normal` and a is parallel to the projection of
57 `a_direction` in the a-b plane.
59 Default `a_direction` is (1,0,0), unless this is parallel to
60 `ab_normal`, in which case default `a_direction` is (0,0,1).
62 The returned cell has the vectors va, vb and vc along the rows. The
63 cell will be oriented such that va and vb are normal to `ab_normal`
64 and va will be along the projection of `a_direction` onto the a-b
65 plane.
67 Example:
69 >>> from ase.geometry.cell import cellpar_to_cell
71 >>> cell = cellpar_to_cell([1, 2, 4, 10, 20, 30], (0, 1, 1), (1, 2, 3))
72 >>> np.round(cell, 3)
73 array([[ 0.816, -0.408, 0.408],
74 [ 1.992, -0.13 , 0.13 ],
75 [ 3.859, -0.745, 0.745]])
77 """
78 if a_direction is None:
79 if np.linalg.norm(np.cross(ab_normal, (1, 0, 0))) < 1e-5:
80 a_direction = (0, 0, 1)
81 else:
82 a_direction = (1, 0, 0)
84 # Define rotated X,Y,Z-system, with Z along ab_normal and X along
85 # the projection of a_direction onto the normal plane of Z.
86 ad = np.array(a_direction)
87 Z = unit_vector(ab_normal)
88 X = unit_vector(ad - dot(ad, Z) * Z)
89 Y = np.cross(Z, X)
91 # Express va, vb and vc in the X,Y,Z-system
92 alpha, beta, gamma = 90., 90., 90.
93 if isinstance(cellpar, (int, float)):
94 a = b = c = cellpar
95 elif len(cellpar) == 1:
96 a = b = c = cellpar[0]
97 elif len(cellpar) == 3:
98 a, b, c = cellpar
99 else:
100 a, b, c, alpha, beta, gamma = cellpar
102 # Handle orthorhombic cells separately to avoid rounding errors
103 eps = 2 * np.spacing(90.0, dtype=np.float64) # around 1.4e-14
104 # alpha
105 if abs(abs(alpha) - 90) < eps:
106 cos_alpha = 0.0
107 else:
108 cos_alpha = cos(alpha * pi / 180.0)
109 # beta
110 if abs(abs(beta) - 90) < eps:
111 cos_beta = 0.0
112 else:
113 cos_beta = cos(beta * pi / 180.0)
114 # gamma
115 if abs(gamma - 90) < eps:
116 cos_gamma = 0.0
117 sin_gamma = 1.0
118 elif abs(gamma + 90) < eps:
119 cos_gamma = 0.0
120 sin_gamma = -1.0
121 else:
122 cos_gamma = cos(gamma * pi / 180.0)
123 sin_gamma = sin(gamma * pi / 180.0)
125 # Build the cell vectors
126 va = a * np.array([1, 0, 0])
127 vb = b * np.array([cos_gamma, sin_gamma, 0])
128 cx = cos_beta
129 cy = (cos_alpha - cos_beta * cos_gamma) / sin_gamma
130 cz_sqr = 1. - cx * cx - cy * cy
131 assert cz_sqr >= 0
132 cz = sqrt(cz_sqr)
133 vc = c * np.array([cx, cy, cz])
135 # Convert to the Cartesian x,y,z-system
136 abc = np.vstack((va, vb, vc))
137 T = np.vstack((X, Y, Z))
138 cell = dot(abc, T)
140 return cell
143def metric_from_cell(cell):
144 """Calculates the metric matrix from cell, which is given in the
145 Cartesian system."""
146 cell = np.asarray(cell, dtype=float)
147 return np.dot(cell, cell.T)
150def complete_cell(cell):
151 """Calculate complete cell with missing lattice vectors.
153 Returns a new 3x3 ndarray.
154 """
156 cell = np.array(cell, dtype=float)
157 missing = np.nonzero(~cell.any(axis=1))[0]
159 if len(missing) == 3:
160 cell.flat[::4] = 1.0
161 if len(missing) == 2:
162 # Must decide two vectors:
163 V, s, WT = np.linalg.svd(cell.T)
164 sf = [s[0], 1, 1]
165 cell = (V @ np.diag(sf) @ WT).T
166 if np.sign(np.linalg.det(cell)) < 0:
167 cell[missing[0]] = -cell[missing[0]]
168 elif len(missing) == 1:
169 i = missing[0]
170 cell[i] = np.cross(cell[i - 2], cell[i - 1])
171 cell[i] /= np.linalg.norm(cell[i])
173 return cell
176def is_orthorhombic(cell):
177 """Check that cell only has stuff in the diagonal."""
178 return not (np.flatnonzero(cell) % 4).any()
181def orthorhombic(cell):
182 """Return cell as three box dimensions or raise ValueError."""
183 if not is_orthorhombic(cell):
184 raise ValueError('Not orthorhombic')
185 return cell.diagonal().copy()
188# We make the Cell object available for import from here for compatibility
189from ase.cell import Cell # noqa