1
2
3
4
5
6
7
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
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
use crate::utils::*;
use molar::prelude::*;
use numpy::{
nalgebra::{Const, Dyn, MatrixView, VectorView},
AllowTypeChange, PyArray1, PyArray2, PyArrayLike1, PyArrayLike2, ToPyArray,
};
use pyo3::{
exceptions::{PyTypeError, PyValueError},
prelude::*,
types::PyTuple,
};
/// Periodic simulation box geometry and minimum-image/PBC utilities.
///
/// Construct either from a `3x3` box matrix or from vectors and angles.
///
/// **Example**
///
/// .. code-block:: python
///
/// import pymolar as molar
/// import numpy as np
///
/// box = molar.PeriodicBox(np.eye(3, dtype=np.float32) * 10.0)
/// d = box.distance(
/// np.array([0.0, 0.0, 0.0], dtype=np.float32),
/// np.array([9.0, 0.0, 0.0], dtype=np.float32),
/// [True, True, True],
/// )
#[pyclass(name = "PeriodicBox")]
pub(super) struct PeriodicBoxPy(pub(super) PeriodicBox);
#[pymethods]
impl PeriodicBoxPy {
#[new]
#[pyo3(signature = (*py_args))]
/// Create a periodic box.
///
/// :param py_args:
/// Positional arguments:
///
/// - ``(matrix,)`` where ``matrix`` is a ``3x3`` array-like
/// - ``(vectors, angles)`` where each is length-3 array-like
/// :returns: Initialized periodic box.
/// :rtype: PeriodicBox
/// :raises TypeError: If argument count is not 1 or 2.
/// :raises ValueError: If input shapes are incompatible.
fn new<'py>(py_args: &Bound<'py, PyTuple>) -> PyResult<Self> {
match py_args.len() {
1 => {
// From matrix
let arr: PyArrayLike2<'py, f32, AllowTypeChange> =
py_args.get_item(0)?.extract()?;
let m: MatrixView<f32, Const<3>, Const<3>, Dyn, Dyn> = arr
.try_as_matrix()
.ok_or_else(|| PyValueError::new_err("conversion to 3x3 matrix has failed"))?;
let pb = PeriodicBox::from_matrix(m)
.map_err(|e| PyValueError::new_err(e.to_string()))?;
Ok(PeriodicBoxPy(pb))
}
2 => {
// From vectors and angles
let v_arr: PyArrayLike1<'py, f32, AllowTypeChange> =
py_args.get_item(0)?.extract()?;
let a_arr: PyArrayLike1<'py, f32, AllowTypeChange> =
py_args.get_item(1)?.extract()?;
let v: VectorView<f32, Const<3>, Dyn> = v_arr.try_as_matrix().ok_or_else(|| {
PyValueError::new_err("conversion of vectors to Vector3 has failed")
})?;
let a: VectorView<f32, Const<3>, Dyn> = a_arr.try_as_matrix().ok_or_else(|| {
PyValueError::new_err("conversion of angles to Vector3 has failed")
})?;
let pb = PeriodicBox::from_vectors_angles(v[0], v[1], v[2], a[0], a[1], a[2])
.map_err(|e| PyValueError::new_err(e.to_string()))?;
Ok(PeriodicBoxPy(pb))
}
_ => Err(PyTypeError::new_err(
"wrong number of arguments: 1 or 2 required",
)),
}
}
/// Return vector-length and angle representation.
///
/// :returns: Tuple ``(vectors, angles)`` as NumPy arrays of length 3.
/// :rtype: tuple[numpy.ndarray, numpy.ndarray]
fn to_vectors_angles<'py>(
slf: Bound<'py, Self>,
) -> (Bound<'py, PyArray1<f32>>, Bound<'py, PyArray1<f32>>) {
let (v, a) = slf.borrow().0.to_vectors_angles();
let v_arr = clone_vec_to_pyarray1(&v, slf.py());
let a_arr = clone_vec_to_pyarray1(&a, slf.py());
(v_arr, a_arr)
}
#[pyo3(signature = (arr, dims=None))]
#[pyo3(text_signature = "($self, arr, dims=None)")]
/// Compute minimum-image displacement vector.
///
/// :param arr: Input displacement vector (length 3).
/// :param dims: Periodic dimensions as ``[x, y, z]`` booleans.
/// :returns: Minimum-image displacement vector.
/// :rtype: numpy.ndarray
/// :raises ValueError: If vector conversion fails.
///
/// **Example**
///
/// .. code-block:: python
///
/// v = box.shortest_vector([1.0, 0.0, 0.0])
fn shortest_vector<'py>(
&self,
py: Python<'py>,
arr: PyArrayLike1<'py, f32, AllowTypeChange>,
dims: Option<[bool; 3]>,
) -> PyResult<Bound<'py, PyArray1<f32>>> {
let dims = dims.unwrap_or([true, true, true]);
let v: VectorView<f32, Const<3>, Dyn> = arr
.try_as_matrix()
.ok_or_else(|| PyValueError::new_err("conversion to Vector3 has failed"))?;
let pbc = PbcDims::new(dims[0], dims[1], dims[2]);
let out_v = self.0.shortest_vector_dims(&v, pbc);
Ok(clone_vec_to_pyarray1(&out_v, py))
}
#[pyo3(signature = (point, target, dims=None))]
#[pyo3(text_signature = "($self, point, target, dims=None)")]
/// Return periodic image of ``point`` closest to ``target``.
///
/// :param point: Point to image (length 3).
/// :param target: Reference target point (length 3).
/// :param dims: Periodic dimensions as ``[x, y, z]`` booleans.
/// :returns: Imaged point closest to ``target``.
/// :rtype: numpy.ndarray
/// :raises ValueError: If vector conversion fails.
fn closest_image<'py>(
&self,
py: Python<'py>,
point: PyArrayLike1<'py, f32, AllowTypeChange>,
target: PyArrayLike1<'py, f32, AllowTypeChange>,
dims: Option<[bool; 3]>,
) -> PyResult<Bound<'py, PyArray1<f32>>> {
let dims = dims.unwrap_or([true, true, true]);
let p: VectorView<f32, Const<3>, Dyn> = point
.try_as_matrix()
.ok_or_else(|| PyValueError::new_err("conversion of point to Vector3 has failed"))?;
let t: VectorView<f32, Const<3>, Dyn> = target
.try_as_matrix()
.ok_or_else(|| PyValueError::new_err("conversion of target to Vector3 has failed"))?;
let pbc = PbcDims::new(dims[0], dims[1], dims[2]);
let out = t + self.0.shortest_vector_dims(&(p - t), pbc);
Ok(clone_vec_to_pyarray1(&out, py))
}
/// Return full box matrix.
///
/// :returns: ``3x3`` box matrix.
/// :rtype: numpy.ndarray
fn get_matrix<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray2<f32>> {
self.0.get_matrix().to_pyarray(py)
}
/// Convert Cartesian coordinates to box coordinates.
///
/// :param point: Cartesian coordinate vector (length 3).
/// :returns: Coordinate in box basis.
/// :rtype: numpy.ndarray
/// :raises ValueError: If vector conversion fails.
fn to_box_coords<'py>(
&self,
py: Python<'py>,
point: PyArrayLike1<'py, f32, AllowTypeChange>,
) -> PyResult<Bound<'py, PyArray1<f32>>> {
let p: VectorView<f32, Const<3>, Dyn> = point
.try_as_matrix()
.ok_or_else(|| PyValueError::new_err("conversion of point to Vector3 has failed"))?;
let v = self.0.to_box_coords(&p);
Ok(clone_vec_to_pyarray1(&v, py))
}
/// Convert box coordinates to Cartesian coordinates.
///
/// :param point: Coordinate in box basis (length 3).
/// :returns: Coordinate in Cartesian/lab basis.
/// :rtype: numpy.ndarray
/// :raises ValueError: If vector conversion fails.
fn to_lab_coords<'py>(
&self,
py: Python<'py>,
point: PyArrayLike1<'py, f32, AllowTypeChange>,
) -> PyResult<Bound<'py, PyArray1<f32>>> {
let p: VectorView<f32, Const<3>, Dyn> = point
.try_as_matrix()
.ok_or_else(|| PyValueError::new_err("conversion of point to Vector3 has failed"))?;
let v = self.0.to_lab_coords(&p);
Ok(clone_vec_to_pyarray1(&v, py))
}
/// Return box extents in box basis.
///
/// :returns: Length-3 vector of extents.
/// :rtype: numpy.ndarray
fn get_box_extents<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<f32>> {
clone_vec_to_pyarray1(&self.0.get_box_extents(), py)
}
/// Return box extents in lab basis.
///
/// :returns: Length-3 vector of extents in lab basis.
/// :rtype: numpy.ndarray
fn get_lab_extents<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray1<f32>> {
clone_vec_to_pyarray1(&self.0.get_box_extents(), py)
}
/// Check whether the box is triclinic.
///
/// :returns: ``True`` for triclinic geometry, else ``False``.
/// :rtype: bool
fn is_triclinic(&self) -> bool {
self.0.is_triclinic()
}
fn __repr__(&self) -> String {
let (v, a) = self.0.to_vectors_angles();
format!(
"PeriodicBox([{:.3}, {:.3}, {:.3}] nm, [{:.1}, {:.1}, {:.1}]°)",
v[0], v[1], v[2], a[0], a[1], a[2]
)
}
/// Compute squared distance with optional periodic dimensions.
///
/// :param p1: First point (length 3).
/// :param p2: Second point (length 3).
/// :param dims: Periodic dimensions as ``[x, y, z]`` booleans.
/// :returns: Squared minimum-image distance.
/// :rtype: float
/// :raises ValueError: If vector conversion fails.
fn distance_squared<'py>(
&self,
p1: PyArrayLike1<'py, f32, AllowTypeChange>,
p2: PyArrayLike1<'py, f32, AllowTypeChange>,
dims: [bool; 3],
) -> PyResult<f32> {
let p1: VectorView<f32, Const<3>, Dyn> = p1
.try_as_matrix()
.ok_or_else(|| PyValueError::new_err("conversion of point to Vector3 has failed"))?;
let p2: VectorView<f32, Const<3>, Dyn> = p2
.try_as_matrix()
.ok_or_else(|| PyValueError::new_err("conversion of target to Vector3 has failed"))?;
let pbc = PbcDims::new(dims[0], dims[1], dims[2]);
Ok(self.0.shortest_vector_dims(&(p2 - p1), pbc).norm_squared())
}
/// Compute distance with optional periodic dimensions.
///
/// :param p1: First point (length 3).
/// :param p2: Second point (length 3).
/// :param dims: Periodic dimensions as ``[x, y, z]`` booleans.
/// :returns: Minimum-image distance in nm.
/// :rtype: float
///
/// **Example**
///
/// .. code-block:: python
///
/// d = box.distance([0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [True, True, True])
fn distance<'py>(
&self,
p1: PyArrayLike1<'py, f32, AllowTypeChange>,
p2: PyArrayLike1<'py, f32, AllowTypeChange>,
dims: [bool; 3],
) -> PyResult<f32> {
Ok(self.distance_squared(p1, p2, dims)?.sqrt())
}
/// Wrap point into the primary unit cell.
///
/// :param p: Input point (length 3).
/// :returns: Wrapped point.
/// :rtype: numpy.ndarray
/// :raises ValueError: If vector conversion fails.
///
/// **Example**
///
/// .. code-block:: python
///
/// wrapped = box.wrap_point([5.0, 5.0, 5.0]) # back into unit cell
fn wrap_point<'py>(
&self,
py: Python<'py>,
p: PyArrayLike1<'py, f32, AllowTypeChange>,
) -> PyResult<Bound<'py, PyArray1<f32>>> {
let v: VectorView<f32, Const<3>, Dyn> = p
.try_as_matrix()
.ok_or_else(|| PyValueError::new_err("conversion of point to Vector3 has failed"))?;
Ok(clone_vec_to_pyarray1(&self.0.wrap_vec(&v), py))
}
}