molcrafts-molpack 0.1.1

Faithful Rust port of Packmol molecular packing (split off from molrs)
Documentation
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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! Bounded-region restraints (Packmol kinds 2–9): cube, box, sphere, ellipsoid.
//!
//! Moved verbatim from the original single-file `src/restraint.rs`; each
//! `impl AtomRestraint` resolves the trait through the unchanged
//! `crate::restraint` path.

use crate::restraint::AtomRestraint;
use molrs::types::F;

/// Packmol kind 2 — quadratic penalty forcing atom inside axis-aligned cube.
#[derive(Debug, Clone, Copy)]
pub struct InsideCubeRestraint {
    pub origin: [F; 3],
    pub side: F,
}

impl InsideCubeRestraint {
    pub fn new(origin: [F; 3], side: F) -> Self {
        Self { origin, side }
    }
}

impl AtomRestraint for InsideCubeRestraint {
    fn f(&self, pos: &[F; 3], scale: F, _scale2: F) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let (xmin, ymin, zmin) = (self.origin[0], self.origin[1], self.origin[2]);
        let (xmax, ymax, zmax) = (xmin + self.side, ymin + self.side, zmin + self.side);
        let a1 = (x - xmin).min(0.0);
        let a2 = (y - ymin).min(0.0);
        let a3 = (z - zmin).min(0.0);
        let mut f = scale * (a1 * a1 + a2 * a2 + a3 * a3);
        let a1 = (x - xmax).max(0.0);
        let a2 = (y - ymax).max(0.0);
        let a3 = (z - zmax).max(0.0);
        f += scale * (a1 * a1 + a2 * a2 + a3 * a3);
        f
    }

    fn fg(&self, pos: &[F; 3], scale: F, scale2: F, g: &mut [F; 3]) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let (xmin, ymin, zmin) = (self.origin[0], self.origin[1], self.origin[2]);
        let (xmax, ymax, zmax) = (xmin + self.side, ymin + self.side, zmin + self.side);
        let a1 = x - xmin;
        let a2 = y - ymin;
        let a3 = z - zmin;
        if a1 < 0.0 {
            g[0] += scale * 2.0 * a1;
        }
        if a2 < 0.0 {
            g[1] += scale * 2.0 * a2;
        }
        if a3 < 0.0 {
            g[2] += scale * 2.0 * a3;
        }
        let a1 = x - xmax;
        let a2 = y - ymax;
        let a3 = z - zmax;
        if a1 > 0.0 {
            g[0] += scale * 2.0 * a1;
        }
        if a2 > 0.0 {
            g[1] += scale * 2.0 * a2;
        }
        if a3 > 0.0 {
            g[2] += scale * 2.0 * a3;
        }
        self.f(pos, scale, scale2)
    }
}

/// Packmol kind 3 — quadratic penalty forcing atom inside axis-aligned box.
///
/// `periodic[k] == true` marks axis `k` as periodic: the pair-kernel
/// minimum-image wrap uses this box's extent for axis `k`, and the cell
/// list on axis `k` wraps instead of clamping. The soft confinement
/// penalty (`f` / `fg`) is always active regardless of `periodic` — a
/// periodic axis still keeps atoms in the reference image via the
/// penalty; `periodic` only affects pair-distance and cell lookup.
#[derive(Debug, Clone, Copy)]
pub struct InsideBoxRestraint {
    pub min: [F; 3],
    pub max: [F; 3],
    pub periodic: [bool; 3],
}

impl InsideBoxRestraint {
    /// Construct a box restraint with explicit bounds and per-axis
    /// periodicity flags. Pass `[false; 3]` for a purely-confining box;
    /// `[true; 3]` for a fully-periodic box; mixed flags give slab
    /// geometries (e.g. `[true, true, false]` = XY-periodic slab).
    pub fn new(min: [F; 3], max: [F; 3], periodic: [bool; 3]) -> Self {
        Self { min, max, periodic }
    }

    /// Construct an axis-aligned cubic box from an origin and isotropic
    /// side length, with per-axis periodicity flags.
    pub fn cube_from_origin(origin: [F; 3], side: F, periodic: [bool; 3]) -> Self {
        Self {
            min: origin,
            max: [origin[0] + side, origin[1] + side, origin[2] + side],
            periodic,
        }
    }

    /// Construct an axis-aligned box from a molrs-core `SimBox`.
    ///
    /// The restraint bounds are `origin` → `origin + lengths`; caller
    /// supplies the `periodic` flags explicitly (the `SimBox` type does
    /// not currently carry per-axis periodicity). Off-axis cells
    /// (triclinic tilts) are not representable as an axis-aligned
    /// restraint — write a custom `impl AtomRestraint` for those.
    pub fn from_simbox(simbox: &molrs::spatial::region::SimBox, periodic: [bool; 3]) -> Self {
        let origin = simbox.origin_view();
        let lengths = simbox.lengths();
        let o = [origin[0], origin[1], origin[2]];
        Self {
            min: o,
            max: [o[0] + lengths[0], o[1] + lengths[1], o[2] + lengths[2]],
            periodic,
        }
    }
}

impl AtomRestraint for InsideBoxRestraint {
    fn f(&self, pos: &[F; 3], scale: F, _scale2: F) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let a1 = (x - self.min[0]).min(0.0);
        let a2 = (y - self.min[1]).min(0.0);
        let a3 = (z - self.min[2]).min(0.0);
        let mut f = scale * (a1 * a1 + a2 * a2 + a3 * a3);
        let a1 = (x - self.max[0]).max(0.0);
        let a2 = (y - self.max[1]).max(0.0);
        let a3 = (z - self.max[2]).max(0.0);
        f += scale * (a1 * a1 + a2 * a2 + a3 * a3);
        f
    }

    fn fg(&self, pos: &[F; 3], scale: F, scale2: F, g: &mut [F; 3]) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let a1 = x - self.min[0];
        let a2 = y - self.min[1];
        let a3 = z - self.min[2];
        if a1 < 0.0 {
            g[0] += scale * 2.0 * a1;
        }
        if a2 < 0.0 {
            g[1] += scale * 2.0 * a2;
        }
        if a3 < 0.0 {
            g[2] += scale * 2.0 * a3;
        }
        let a1 = x - self.max[0];
        let a2 = y - self.max[1];
        let a3 = z - self.max[2];
        if a1 > 0.0 {
            g[0] += scale * 2.0 * a1;
        }
        if a2 > 0.0 {
            g[1] += scale * 2.0 * a2;
        }
        if a3 > 0.0 {
            g[2] += scale * 2.0 * a3;
        }
        self.f(pos, scale, scale2)
    }

    fn periodic_box(&self) -> Option<([F; 3], [F; 3], [bool; 3])> {
        if self.periodic.iter().any(|&p| p) {
            Some((self.min, self.max, self.periodic))
        } else {
            None
        }
    }
}

/// Packmol kind 4 — quadratic penalty forcing atom inside sphere.
#[derive(Debug, Clone, Copy)]
pub struct InsideSphereRestraint {
    pub center: [F; 3],
    pub radius: F,
}

impl InsideSphereRestraint {
    pub fn new(center: [F; 3], radius: F) -> Self {
        Self { center, radius }
    }
}

impl AtomRestraint for InsideSphereRestraint {
    fn f(&self, pos: &[F; 3], _scale: F, scale2: F) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let c = self.center;
        let w = (x - c[0]).powi(2) + (y - c[1]).powi(2) + (z - c[2]).powi(2) - self.radius.powi(2);
        let a1 = w.max(0.0);
        scale2 * a1 * a1
    }

    fn fg(&self, pos: &[F; 3], scale: F, scale2: F, g: &mut [F; 3]) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let c = self.center;
        let d = (x - c[0]).powi(2) + (y - c[1]).powi(2) + (z - c[2]).powi(2) - self.radius.powi(2);
        if d > 0.0 {
            g[0] += 4.0 * scale2 * (x - c[0]) * d;
            g[1] += 4.0 * scale2 * (y - c[1]) * d;
            g[2] += 4.0 * scale2 * (z - c[2]) * d;
        }
        self.f(pos, scale, scale2)
    }
}

/// Packmol kind 5 — quadratic penalty forcing atom inside ellipsoid.
#[derive(Debug, Clone, Copy)]
pub struct InsideEllipsoidRestraint {
    pub center: [F; 3],
    pub axes: [F; 3],
    pub exponent: F,
}

impl InsideEllipsoidRestraint {
    pub fn new(center: [F; 3], axes: [F; 3], exponent: F) -> Self {
        // Each axis halves the penalty via division by `axes[k]²`; a zero axis
        // produces NaN/inf at eval time. The contract is positive semi-axes.
        debug_assert!(
            axes.iter().all(|&a| a > 0.0),
            "ellipsoid semi-axes must be strictly positive, got {axes:?}"
        );
        Self {
            center,
            axes,
            exponent,
        }
    }
}

impl AtomRestraint for InsideEllipsoidRestraint {
    fn f(&self, pos: &[F; 3], _scale: F, scale2: F) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let c = self.center;
        let ax = self.axes;
        let a1 = (x - c[0]).powi(2) / ax[0].powi(2);
        let a2 = (y - c[1]).powi(2) / ax[1].powi(2);
        let a3 = (z - c[2]).powi(2) / ax[2].powi(2);
        let w = a1 + a2 + a3 - self.exponent.powi(2);
        let v = w.max(0.0);
        scale2 * v * v
    }

    fn fg(&self, pos: &[F; 3], scale: F, scale2: F, g: &mut [F; 3]) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let c = self.center;
        let a1 = x - c[0];
        let b1 = y - c[1];
        let c1 = z - c[2];
        let a2 = self.axes[0].powi(2);
        let b2 = self.axes[1].powi(2);
        let c2 = self.axes[2].powi(2);
        let d = a1.powi(2) / a2 + b1.powi(2) / b2 + c1.powi(2) / c2 - self.exponent.powi(2);
        if d > 0.0 {
            g[0] += scale2 * 4.0 * d * a1 / a2;
            g[1] += scale2 * 4.0 * d * b1 / b2;
            g[2] += scale2 * 4.0 * d * c1 / c2;
        }
        self.f(pos, scale, scale2)
    }
}

/// Packmol kind 6 — linear penalty forcing atom outside axis-aligned cube.
#[derive(Debug, Clone, Copy)]
pub struct OutsideCubeRestraint {
    pub origin: [F; 3],
    pub side: F,
}

impl OutsideCubeRestraint {
    pub fn new(origin: [F; 3], side: F) -> Self {
        Self { origin, side }
    }
}

impl AtomRestraint for OutsideCubeRestraint {
    fn f(&self, pos: &[F; 3], scale: F, _scale2: F) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let (xmin, ymin, zmin) = (self.origin[0], self.origin[1], self.origin[2]);
        let (xmax, ymax, zmax) = (xmin + self.side, ymin + self.side, zmin + self.side);
        if x > xmin && x < xmax && y > ymin && y < ymax && z > zmin && z < zmax {
            let xmed = (xmax - xmin) / 2.0;
            let ymed = (ymax - ymin) / 2.0;
            let zmed = (zmax - zmin) / 2.0;
            let a1 = if x <= xmin + xmed { x - xmin } else { xmax - x };
            let a2 = if y <= ymin + ymed { y - ymin } else { ymax - y };
            let a3 = if z <= zmin + zmed { z - zmin } else { zmax - z };
            scale * (a1 + a2 + a3)
        } else {
            0.0
        }
    }

    fn fg(&self, pos: &[F; 3], scale: F, scale2: F, g: &mut [F; 3]) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let (xmin, ymin, zmin) = (self.origin[0], self.origin[1], self.origin[2]);
        let (xmax, ymax, zmax) = (xmin + self.side, ymin + self.side, zmin + self.side);
        if x > xmin && x < xmax && y > ymin && y < ymax && z > zmin && z < zmax {
            let xmed = (xmax - xmin) / 2.0;
            let ymed = (ymax - ymin) / 2.0;
            let zmed = (zmax - zmin) / 2.0;
            let (a1, a4) = if x <= xmin + xmed {
                (1.0, 0.0)
            } else {
                (0.0, -1.0)
            };
            let (a2, a5) = if y <= ymin + ymed {
                (1.0, 0.0)
            } else {
                (0.0, -1.0)
            };
            let (a3, a6) = if z <= zmin + zmed {
                (1.0, 0.0)
            } else {
                (0.0, -1.0)
            };
            g[0] += scale * (a1 + a4);
            g[1] += scale * (a2 + a5);
            g[2] += scale * (a3 + a6);
        }
        self.f(pos, scale, scale2)
    }
}

/// Packmol kind 7 — linear penalty forcing atom outside axis-aligned box.
#[derive(Debug, Clone, Copy)]
pub struct OutsideBoxRestraint {
    pub min: [F; 3],
    pub max: [F; 3],
}

impl OutsideBoxRestraint {
    pub fn new(min: [F; 3], max: [F; 3]) -> Self {
        Self { min, max }
    }
}

impl AtomRestraint for OutsideBoxRestraint {
    fn f(&self, pos: &[F; 3], scale: F, _scale2: F) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let (xmin, ymin, zmin) = (self.min[0], self.min[1], self.min[2]);
        let (xmax, ymax, zmax) = (self.max[0], self.max[1], self.max[2]);
        if x > xmin && x < xmax && y > ymin && y < ymax && z > zmin && z < zmax {
            let xmed = (xmax - xmin) / 2.0;
            let ymed = (ymax - ymin) / 2.0;
            let zmed = (zmax - zmin) / 2.0;
            let a1 = if x <= xmin + xmed { x - xmin } else { xmax - x };
            let a2 = if y <= ymin + ymed { y - ymin } else { ymax - y };
            let a3 = if z <= zmin + zmed { z - zmin } else { zmax - z };
            scale * (a1 + a2 + a3)
        } else {
            0.0
        }
    }

    fn fg(&self, pos: &[F; 3], scale: F, scale2: F, g: &mut [F; 3]) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let (xmin, ymin, zmin) = (self.min[0], self.min[1], self.min[2]);
        let (xmax, ymax, zmax) = (self.max[0], self.max[1], self.max[2]);
        if x > xmin && x < xmax && y > ymin && y < ymax && z > zmin && z < zmax {
            let xmed = (xmax - xmin) / 2.0;
            let ymed = (ymax - ymin) / 2.0;
            let zmed = (zmax - zmin) / 2.0;
            let (a1, a4) = if x <= xmin + xmed {
                (1.0, 0.0)
            } else {
                (0.0, -1.0)
            };
            let (a2, a5) = if y <= ymin + ymed {
                (1.0, 0.0)
            } else {
                (0.0, -1.0)
            };
            let (a3, a6) = if z <= zmin + zmed {
                (1.0, 0.0)
            } else {
                (0.0, -1.0)
            };
            g[0] += scale * (a1 + a4);
            g[1] += scale * (a2 + a5);
            g[2] += scale * (a3 + a6);
        }
        self.f(pos, scale, scale2)
    }
}

/// Packmol kind 8 — quadratic penalty forcing atom outside sphere.
#[derive(Debug, Clone, Copy)]
pub struct OutsideSphereRestraint {
    pub center: [F; 3],
    pub radius: F,
}

impl OutsideSphereRestraint {
    pub fn new(center: [F; 3], radius: F) -> Self {
        Self { center, radius }
    }
}

impl AtomRestraint for OutsideSphereRestraint {
    fn f(&self, pos: &[F; 3], _scale: F, scale2: F) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let c = self.center;
        let w = (x - c[0]).powi(2) + (y - c[1]).powi(2) + (z - c[2]).powi(2) - self.radius.powi(2);
        let a1 = w.min(0.0);
        scale2 * a1 * a1
    }

    fn fg(&self, pos: &[F; 3], scale: F, scale2: F, g: &mut [F; 3]) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let c = self.center;
        let d = (x - c[0]).powi(2) + (y - c[1]).powi(2) + (z - c[2]).powi(2) - self.radius.powi(2);
        if d < 0.0 {
            g[0] += 4.0 * scale2 * (x - c[0]) * d;
            g[1] += 4.0 * scale2 * (y - c[1]) * d;
            g[2] += 4.0 * scale2 * (z - c[2]) * d;
        }
        self.f(pos, scale, scale2)
    }
}

/// Packmol kind 9 — quadratic penalty forcing atom outside ellipsoid.
///
/// Both `f` and `fg` apply the `scale2` factor — `f` previously omitted
/// it (a transcription artefact of the original Fortran-port comment),
/// which left `f` and `fg` 100× out of phase at the default
/// `scale2 = 0.01` and made the optimizer's gradient look 100× flatter
/// than the function value reported. The `scale2` factor here matches
/// the documented "quadratic penalty group" convention (kinds 4 / 5 /
/// 8 / 9 / 12 / 13) and the sister kind-5 [`InsideEllipsoidRestraint`].
#[derive(Debug, Clone, Copy)]
pub struct OutsideEllipsoidRestraint {
    pub center: [F; 3],
    pub axes: [F; 3],
    pub exponent: F,
}

impl OutsideEllipsoidRestraint {
    pub fn new(center: [F; 3], axes: [F; 3], exponent: F) -> Self {
        // Each axis halves the penalty via division by `axes[k]²`; a zero axis
        // produces NaN/inf at eval time. The contract is positive semi-axes.
        debug_assert!(
            axes.iter().all(|&a| a > 0.0),
            "ellipsoid semi-axes must be strictly positive, got {axes:?}"
        );
        Self {
            center,
            axes,
            exponent,
        }
    }
}

impl AtomRestraint for OutsideEllipsoidRestraint {
    fn f(&self, pos: &[F; 3], _scale: F, scale2: F) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let c = self.center;
        let ax = self.axes;
        let a1 = (x - c[0]).powi(2) / ax[0].powi(2);
        let a2 = (y - c[1]).powi(2) / ax[1].powi(2);
        let a3 = (z - c[2]).powi(2) / ax[2].powi(2);
        let w = a1 + a2 + a3 - self.exponent.powi(2);
        let v = w.min(0.0);
        scale2 * v * v
    }

    fn fg(&self, pos: &[F; 3], scale: F, scale2: F, g: &mut [F; 3]) -> F {
        let (x, y, z) = (pos[0], pos[1], pos[2]);
        let c = self.center;
        let a1 = x - c[0];
        let b1 = y - c[1];
        let c1 = z - c[2];
        let a2 = self.axes[0].powi(2);
        let b2 = self.axes[1].powi(2);
        let c2 = self.axes[2].powi(2);
        let d = a1.powi(2) / a2 + b1.powi(2) / b2 + c1.powi(2) / c2 - self.exponent.powi(2);
        if d < 0.0 {
            let ds = scale2 * d;
            g[0] += 4.0 * ds * a1 / a2;
            g[1] += 4.0 * ds * b1 / b2;
            g[2] += 4.0 * ds * c1 / c2;
        }
        self.f(pos, scale, scale2)
    }
}