Skip to main content

dftd4_sys/
lib.rs

1//! FFI bindings to the DFT-D4 dispersion correction library
2//!
3//! This crate provides low-level Rust bindings to the C API of the DFT-D4 library.
4//! DFT-D4 is a generally applicable atomic-charge dependent London dispersion correction.
5//!
6//! For more information, see: <https://github.com/dftd4/dftd4>
7//!
8//! # Input validation: failure channels that bypass the error handle
9//!
10//! The error handle ([`dftd4_error`]) is the C API's only error channel, but the
11//! pinned upstream (v4.2.0) does **not** report every invalid input through it.
12//! Two classes of degenerate input bypass the handle entirely and cannot be
13//! detected from Rust:
14//!
15//! - **Degenerate atom counts (`natoms <= 0`).** [`dftd4_new_structure`]
16//!   accepts them without setting the error handle, [`dftd4_new_d4_model`]
17//!   builds a model for the empty structure, and the first calculation
18//!   (e.g. [`dftd4_get_dispersion`]) then **terminates the host process** with
19//!   a Fortran `error stop` (stderr: `[Error]: Bunch-Kaufman factorization
20//!   failed.` / `ERROR STOP`, exit code 1). An empty structure is a routine
21//!   intermediate state in geometry-optimisation or sampling loops, where this
22//!   is an uncatchable process abort. Check `natoms > 0` before calling into
23//!   the library.
24//! - **Atomic numbers outside the element data tables (`number < 1` or
25//!   `number > 118`).** Upstream maps them to zero-valued filler data, so
26//!   calculations silently return wrong results (e.g. `energy = 0.0`) while
27//!   the error handle stays empty.
28//!
29//! The supported preconditions for the input functions are therefore
30//! `natoms > 0` and `1 <= numbers[i] <= 118`
31//! (see [`MAX_SUPPORTED_ATOMIC_NUMBER`]). Note that atomic numbers `104..=111`
32//! *are* reported through the error handle by [`dftd4_new_d4_model`] as
33//! "unsupported element" — that channel works as documented.
34//!
35//! A third bypass is detectable from Rust and therefore guarded by the
36//! checked constructor: passing a **null error handle**. Every upstream entry
37//! point that takes the handle checks it first and returns *silently* when it
38//! is null — [`dftd4_new_structure`] yields a null structure handle and the
39//! calculation functions leave their output arguments untouched (a
40//! `0.0`-initialised energy then looks like a valid "no dispersion" result,
41//! where a real handle gives e.g. `-4.4e-4` Eh for the argon dimer used in
42//! the tests). [`dftd4_check_error`] reports this only after the fact, with
43//! status `2` — always pass a real handle created by [`dftd4_new_error`].
44//!
45//! [`Dftd4Structure::try_new`] is a checked variant of [`dftd4_new_structure`]
46//! that rejects a null error handle and enforces both preconditions before the
47//! FFI call, returning a catchable [`Dftd4StructureError`] instead of letting
48//! the library misbehave.
49
50#![allow(non_camel_case_types)]
51#![allow(non_snake_case)]
52
53use std::os::raw::{c_char, c_double, c_int};
54
55/// Opaque error handle
56#[repr(C)]
57pub struct _dftd4_error {
58    _private: [u8; 0],
59}
60pub type dftd4_error = *mut _dftd4_error;
61
62/// Opaque molecular structure data
63#[repr(C)]
64pub struct _dftd4_structure {
65    _private: [u8; 0],
66}
67pub type dftd4_structure = *mut _dftd4_structure;
68
69/// Opaque dispersion model
70#[repr(C)]
71pub struct _dftd4_model {
72    _private: [u8; 0],
73}
74pub type dftd4_model = *mut _dftd4_model;
75
76/// Opaque damping parameters
77#[repr(C)]
78pub struct _dftd4_param {
79    _private: [u8; 0],
80}
81pub type dftd4_param = *mut _dftd4_param;
82
83/// Safe wrapper for dftd4_error handle that automatically frees on drop
84pub struct Dftd4Error(pub dftd4_error);
85
86impl Drop for Dftd4Error {
87    fn drop(&mut self) {
88        if !self.0.is_null() {
89            unsafe { dftd4_delete_error(&mut self.0) };
90        }
91    }
92}
93
94/// Safe wrapper for dftd4_structure handle that automatically frees on drop
95pub struct Dftd4Structure(pub dftd4_structure);
96
97impl Drop for Dftd4Structure {
98    fn drop(&mut self) {
99        if !self.0.is_null() {
100            unsafe { dftd4_delete_structure(&mut self.0) };
101        }
102    }
103}
104
105/// Safe wrapper for dftd4_model handle that automatically frees on drop
106pub struct Dftd4Model(pub dftd4_model);
107
108impl Drop for Dftd4Model {
109    fn drop(&mut self) {
110        if !self.0.is_null() {
111            unsafe { dftd4_delete_model(&mut self.0) };
112        }
113    }
114}
115
116/// Safe wrapper for dftd4_param handle that automatically frees on drop
117pub struct Dftd4Param(pub dftd4_param);
118
119impl Drop for Dftd4Param {
120    fn drop(&mut self) {
121        if !self.0.is_null() {
122            unsafe { dftd4_delete_param(&mut self.0) };
123        }
124    }
125}
126
127/// Largest atomic number covered by the upstream element data tables.
128///
129/// The pinned upstream (v4.2.0, via mctc-lib `0.5.1`) indexes all element
130/// properties (covalent radii, electronegativities, reference data, …) by
131/// atomic number up to this value. Larger (or non-positive) atomic numbers are
132/// **not** rejected by the library: they are mapped to zero-valued filler data
133/// and calculations silently return wrong energies (e.g. `0.0`) without
134/// setting the error handle.
135pub const MAX_SUPPORTED_ATOMIC_NUMBER: c_int = 118;
136
137/// Input rejected by a checked constructor such as [`Dftd4Structure::try_new`].
138///
139/// These conditions are validated *before* the FFI call because the pinned
140/// upstream cannot report them through the error handle: a degenerate atom
141/// count lets a later calculation abort the whole host process via a Fortran
142/// `error stop`, and out-of-range atomic numbers silently produce zero-valued
143/// results. See the crate-level documentation for details.
144#[derive(Debug, Clone, PartialEq, Eq)]
145pub enum Dftd4StructureError {
146    /// `natoms` was zero or negative. The raw API accepts this silently and
147    /// only the subsequent calculation calls fail — by terminating the host
148    /// process, not via the error handle.
149    EmptyAtomCount {
150        /// The rejected atom count.
151        natoms: c_int,
152    },
153    /// `numbers[index]` is outside the supported range
154    /// `1..=MAX_SUPPORTED_ATOMIC_NUMBER`.
155    AtomicNumberOutOfRange {
156        /// Index of the offending entry in `numbers`.
157        index: usize,
158        /// The rejected atomic number.
159        number: c_int,
160    },
161    /// A required array pointer (`numbers` or `positions`) was null.
162    MissingRequiredArray {
163        /// Name of the offending argument.
164        argument: &'static str,
165    },
166    /// The `error` handle pointer was null. Upstream v4.2.0 starts every
167    /// handle-taking API entry point by checking the handle and **returns
168    /// silently** when it is null: `dftd4_new_structure` hands back a null
169    /// structure handle, and the calculation functions leave their output
170    /// arguments untouched (a `0.0`-initialised energy then looks like a
171    /// valid "no dispersion" result). Rejected before the FFI call.
172    MissingErrorHandle,
173}
174
175impl core::fmt::Display for Dftd4StructureError {
176    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
177        match self {
178            Self::EmptyAtomCount { natoms } => write!(
179                f,
180                "degenerate atom count {natoms}: natoms must be > 0, \
181                 libdftd4 would accept it silently and abort the process \
182                 with a Fortran `error stop` in the first calculation"
183            ),
184            Self::AtomicNumberOutOfRange { index, number } => write!(
185                f,
186                "atomic number {number} at index {index} is outside the \
187                 supported range 1..={MAX_SUPPORTED_ATOMIC_NUMBER}, \
188                 libdftd4 would silently return zero-valued results for it"
189            ),
190            Self::MissingRequiredArray { argument } => {
191                write!(f, "required array argument `{argument}` is null")
192            }
193            Self::MissingErrorHandle => write!(
194                f,
195                "required error handle argument `error` is null: upstream \
196                 libdftd4 skips the whole call silently and returns a null \
197                 structure handle, which a checked constructor must never \
198                 report as Ok"
199            ),
200        }
201    }
202}
203
204impl std::error::Error for Dftd4StructureError {}
205
206impl Dftd4Structure {
207    /// Checked creation of molecular structure data (quantities in Bohr).
208    ///
209    /// Behaves exactly like [`dftd4_new_structure`], except that the degenerate
210    /// inputs the pinned upstream cannot report through the error handle are
211    /// rejected before the FFI call and returned as a catchable Rust error:
212    ///
213    /// - `natoms <= 0` → [`Dftd4StructureError::EmptyAtomCount`] (the raw call
214    ///   would return a handle with an empty error handle, and a later
215    ///   calculation would terminate the host process via `error stop`)
216    /// - `numbers[i]` outside `1..=MAX_SUPPORTED_ATOMIC_NUMBER` →
217    ///   [`Dftd4StructureError::AtomicNumberOutOfRange`] (the raw call would
218    ///   silently produce zero-valued results)
219    /// - null `numbers` or `positions` →
220    ///   [`Dftd4StructureError::MissingRequiredArray`]
221    /// - null `error` handle → [`Dftd4StructureError::MissingErrorHandle`]
222    ///   (upstream does not merely omit the reporting through a null handle:
223    ///   it skips the *entire* call and returns a null structure handle, so
224    ///   reporting that as `Ok` would hand out a dead wrapper)
225    ///
226    /// Conditions upstream *does* report (e.g. "unsupported element" for
227    /// atomic numbers `104..=111`, too close interatomic distances) still come
228    /// through `error` exactly as with the raw call — consult the handle after
229    /// an `Ok` result as usual. A rejected input leaves `error` untouched.
230    ///
231    /// # Safety
232    ///
233    /// Same requirements as [`dftd4_new_structure`], except that `error` must
234    /// **not** be null here: `error` must be a valid error handle created by
235    /// [`dftd4_new_error`], `numbers` must point to an array of at least
236    /// `natoms` atomic numbers, `positions` to an array of at least
237    /// `3 * natoms` Cartesian coordinates in Bohr, and `charge` (one value),
238    /// `lattice` (`3 * 3` values) and `periodic` (3 values) must each be
239    /// either null or point to valid storage. (A null `error` is rejected
240    /// with [`Dftd4StructureError::MissingErrorHandle`] instead of silently
241    /// producing a null handle wrapped in `Ok`, as the raw call does — see
242    /// the note above and on [`dftd4_new_structure`].)
243    pub unsafe fn try_new(
244        error: dftd4_error,
245        natoms: c_int,
246        numbers: *const c_int,
247        positions: *const c_double,
248        charge: *const c_double,
249        lattice: *const c_double,
250        periodic: *const bool,
251    ) -> Result<Self, Dftd4StructureError> {
252        if error.is_null() {
253            return Err(Dftd4StructureError::MissingErrorHandle);
254        }
255        if numbers.is_null() {
256            return Err(Dftd4StructureError::MissingRequiredArray {
257                argument: "numbers",
258            });
259        }
260        if positions.is_null() {
261            return Err(Dftd4StructureError::MissingRequiredArray {
262                argument: "positions",
263            });
264        }
265        if natoms <= 0 {
266            return Err(Dftd4StructureError::EmptyAtomCount { natoms });
267        }
268        // Validity of `numbers` for `natoms` elements is part of the safety
269        // contract, same as for the raw call this constructor guards.
270        let numbers = unsafe { core::slice::from_raw_parts(numbers, natoms as usize) };
271        if let Some((index, &number)) = numbers
272            .iter()
273            .enumerate()
274            .find(|(_, number)| **number < 1 || **number > MAX_SUPPORTED_ATOMIC_NUMBER)
275        {
276            return Err(Dftd4StructureError::AtomicNumberOutOfRange { index, number });
277        }
278        // With a non-null `error` the pinned upstream always allocates the
279        // structure before returning (`vmol = c_null_ptr` is only reachable
280        // through the null-error early return audited above), so the handle
281        // is guaranteed non-null here.
282        Ok(Dftd4Structure(unsafe {
283            dftd4_new_structure(
284                error,
285                natoms,
286                numbers.as_ptr(),
287                positions,
288                charge,
289                lattice,
290                periodic,
291            )
292        }))
293    }
294}
295
296#[link(name = "dftd4")]
297unsafe extern "C" {
298    /// Obtain library version as major * 10000 + minor * 100 + patch
299    pub fn dftd4_get_version() -> c_int;
300
301    // Error handle functions
302    /// Create new error handle object
303    pub fn dftd4_new_error() -> dftd4_error;
304
305    /// Check error handle status
306    ///
307    /// Return codes (upstream v4.2.0 `check_error_api`): `0` = valid handle,
308    /// no error set; `1` = valid handle with an error message; `2` = handle
309    /// pointer is null (invalid). Note that the other API entry points do
310    /// **not** report a null handle through these codes — they silently skip
311    /// the whole call (see [`dftd4_new_structure`]), so `2` is only observable
312    /// by checking a null handle explicitly. Prefer a real handle or
313    /// [`Dftd4Structure::try_new`], which rejects null handles up front.
314    pub fn dftd4_check_error(error: dftd4_error) -> c_int;
315
316    /// Get error message from error handle.
317    ///
318    /// `buffersize` is the *capacity* of `buffer`, in elements. It is declared
319    /// `*const c_int` deliberately: upstream dftd4 (checked at the pinned
320    /// v4.2.0 tag) declares `void dftd4_get_error(dftd4_error, char* buffer,
321    /// const int* buffersize)` and the Fortran implementation takes
322    /// `integer(c_int), intent(in) :: buffersize` — it is **input-only**, no
323    /// length is written back. (F0452: the review's "in/out `*const` aliasing
324    /// UB" premise was a false positive; do NOT "fix" this to `*mut c_int`,
325    /// which would *introduce* a signature mismatch against the real ABI.) The
326    /// C API reports no written length at all, so callers detect truncation from
327    /// the NUL terminator rather than a returned size.
328    pub fn dftd4_get_error(error: dftd4_error, buffer: *mut c_char, buffersize: *const c_int);
329
330    /// Delete error handle object
331    pub fn dftd4_delete_error(error: *mut dftd4_error);
332
333    // Molecular structure functions
334    /// Create new molecular structure data (quantities in Bohr)
335    ///
336    /// # Parameters
337    /// - `error`: Error handle
338    /// - `natoms`: Number of atoms
339    /// - `numbers`: Atomic numbers `[natoms]`
340    /// - `positions`: Cartesian coordinates in Bohr `[natoms][3]`
341    /// - `charge`: Total charge (nullable)
342    /// - `lattice`: Lattice vectors in Bohr `[3][3]` (nullable for molecules)
343    /// - `periodic`: Periodicity flags `[3]` (nullable): three 1-byte
344    ///   booleans with values `false`/`true` (0/1), e.g. `&[true, false,
345    ///   true]`. Upstream only tests `any(periodic)` when picking lattice
346    ///   points, so a single `true` flag enables the periodic code path.
347    ///   With a lattice present but `periodic` null, upstream defaults to
348    ///   fully periodic.
349    ///
350    /// `periodic` is a `*const bool` deliberately: upstream dftd4 (checked
351    /// at the pinned v4.2.0 tag) declares `const bool* /* periodic [3] */`
352    /// in `include/dftd4.h` and the Fortran implementation takes
353    /// `logical(c_bool), intent(in), optional :: c_periodic(3)` in
354    /// `src/dftd4/api.f90` — **one byte per flag**. Rust's `bool` is
355    /// guaranteed to be 1 byte and matches C99 `bool`/`_Bool`. Do **not**
356    /// "fix" this back to `*const c_int`: the Fortran side indexes the data
357    /// as a 1-byte array, so a caller obeying a 4-byte declaration would
358    /// hand it `(LSB of flags[0], 0, 0)` on little-endian, and every request
359    /// with `flags[0] == 0` (a 2D slab `[0,1,1]`, a chain `[0,0,1]`) would
360    /// be silently computed as a non-periodic molecule — with no error on
361    /// the handle and energies wrong by an order of magnitude. The
362    /// regression tests below pin the element width and the `[0,1,1]`
363    /// behaviour against the vendored library.
364    ///
365    /// # Preconditions
366    ///
367    /// - `natoms > 0`
368    /// - every `numbers[i]` must be in `1..=118`
369    ///   (see [`MAX_SUPPORTED_ATOMIC_NUMBER`])
370    ///
371    /// # Warning
372    ///
373    /// Violating the preconditions does **not** set the error handle. Upstream
374    /// v4.2.0 validates neither `natoms` nor the atomic numbers here:
375    /// - `natoms <= 0` is accepted silently, and the first calculation call
376    ///   (e.g. [`dftd4_get_dispersion`]) terminates the **entire host process**
377    ///   via a Fortran `error stop` — no catchable error is ever reported.
378    /// - Atomic numbers outside `1..=118` map to zero-valued filler data and
379    ///   silently produce wrong results (e.g. `energy = 0.0`).
380    /// - A **null `error` handle** makes upstream skip the *entire* call: it
381    ///   returns `NULL` (no structure created) with no diagnostics, and the
382    ///   calculation entry points likewise return without writing their
383    ///   outputs. Use a handle created by [`dftd4_new_error`], or
384    ///   [`Dftd4Structure::try_new`] which rejects a null handle with
385    ///   [`Dftd4StructureError::MissingErrorHandle`].
386    ///
387    /// Use [`Dftd4Structure::try_new`] for a checked variant that returns a
388    /// catchable [`Dftd4StructureError`] instead.
389    pub fn dftd4_new_structure(
390        error: dftd4_error,
391        natoms: c_int,
392        numbers: *const c_int,
393        positions: *const c_double,
394        charge: *const c_double,
395        lattice: *const c_double,
396        periodic: *const bool,
397    ) -> dftd4_structure;
398
399    /// Delete molecular structure data
400    pub fn dftd4_delete_structure(mol: *mut dftd4_structure);
401
402    /// Update coordinates and lattice parameters (quantities in Bohr)
403    ///
404    /// In-place replacement of the geometry behind an existing structure
405    /// handle: `positions` (`[natoms][3]`, always read) and, when non-null,
406    /// the `lattice` vectors (`3 * 3`). Model and parameter handles stay
407    /// valid across the update, so reusing one structure across
408    /// optimisation or sampling steps yields the same energies as a freshly
409    /// built structure at the same geometry (pinned by the
410    /// `test_update_structure_*` regression tests). For periodic structures
411    /// the updated coordinates are wrapped into the central cell, exactly as
412    /// in [`dftd4_new_structure`]; energies are unaffected by the wrap.
413    ///
414    /// # Errors
415    ///
416    /// Reported through `error` (upstream v4.2.0 `src/dftd4/api.f90`):
417    /// - null `mol` handle → "Molecular structure data is missing"
418    /// - malformed structure data → "Invalid molecular structure data
419    ///   provided"
420    /// - two atoms closer than `1e-9` Bohr after the update → "Too close
421    ///   interatomic distances found" (the same cold-fusion check as
422    ///   [`dftd4_new_structure`])
423    ///
424    /// With a null `error` handle the call is a silent no-op, as with the
425    /// other entry points (see the crate-level documentation).
426    pub fn dftd4_update_structure(
427        error: dftd4_error,
428        mol: dftd4_structure,
429        positions: *const c_double,
430        lattice: *const c_double,
431    );
432
433    // Dispersion model functions
434    /// Create new D4 dispersion model
435    ///
436    /// Errors that can be reported are signalled through `error` (e.g.
437    /// "unsupported element" for atomic numbers `104..=111`). A degenerate
438    /// structure created with `natoms <= 0` is **not** reported: model
439    /// creation succeeds with the error handle left empty, and the abort
440    /// happens later in the calculation functions (see
441    /// [`dftd4_get_dispersion`]).
442    pub fn dftd4_new_d4_model(error: dftd4_error, mol: dftd4_structure) -> dftd4_model;
443
444    /// Create new D4S dispersion model
445    ///
446    /// Same validation behaviour as [`dftd4_new_d4_model`].
447    pub fn dftd4_new_d4s_model(error: dftd4_error, mol: dftd4_structure) -> dftd4_model;
448
449    /// Create custom D4 dispersion model with parameters
450    ///
451    /// Same validation behaviour as [`dftd4_new_d4_model`].
452    pub fn dftd4_custom_d4_model(
453        error: dftd4_error,
454        mol: dftd4_structure,
455        ga: c_double,
456        gc: c_double,
457        wf: c_double,
458    ) -> dftd4_model;
459
460    /// Create custom D4S dispersion model with parameters
461    pub fn dftd4_custom_d4s_model(
462        error: dftd4_error,
463        mol: dftd4_structure,
464        ga: c_double,
465        gc: c_double,
466    ) -> dftd4_model;
467
468    /// Delete dispersion model
469    pub fn dftd4_delete_model(disp: *mut dftd4_model);
470
471    /// Set realspace cutoffs (quantities in Bohr)
472    ///
473    /// The cutoffs are stored with the model handle and used by *all*
474    /// subsequent calculation entry points ([`dftd4_get_dispersion`],
475    /// [`dftd4_get_properties`], [`dftd4_get_numerical_hessian`],
476    /// [`dftd4_get_pairwise_dispersion`]). They replace the library defaults
477    /// (two-body `disp2 = 60`, three-body `disp3 = 40`, coordination-number
478    /// `cn = 30` Bohr, hard cutoff); shrinking them trades accuracy for
479    /// performance in large, typically periodic systems.
480    ///
481    /// # Parameters
482    /// - `disp2`: two-body interaction cutoff
483    /// - `disp3`: three-body interaction cutoff
484    /// - `cn`: coordination number cutoff
485    ///
486    /// # Errors
487    ///
488    /// A null `disp` handle is reported through `error` as
489    /// "Dispersion model is missing". As with every entry point, a **null
490    /// `error` handle** makes this call return silently *before* even that
491    /// validation (see [`dftd4_new_structure`]), so always pass a real handle.
492    ///
493    /// # Version note
494    ///
495    /// This setter was introduced in libdftd4 v4.2.0 (header tag
496    /// `DFTD4_API_SUFFIX__V_4_2`) and is absent from older 4.x libraries.
497    /// The pinned vendored build provides it; a consumer linking a pre-4.2
498    /// system library gets a loud "undefined symbol" diagnostic if the
499    /// function is referenced, never a wrong result.
500    pub fn dftd4_set_model_realspace_cutoff(
501        error: dftd4_error,
502        disp: dftd4_model,
503        disp2: c_double,
504        disp3: c_double,
505        cn: c_double,
506    );
507
508    /// Set realspace cutoffs with smoothing widths (quantities in Bohr)
509    ///
510    /// Same as [`dftd4_set_model_realspace_cutoff`], except that the two- and
511    /// three-body interactions are not truncated hard at `disp2` / `disp3` but
512    /// ramp down to zero across a quintic smoothstep switch on
513    /// `[cutoff - width, cutoff]` (weight `1` below, `0` above). Zero widths
514    /// reproduce the hard cutoff of [`dftd4_set_model_realspace_cutoff`]; a
515    /// width larger than the cutoff is clamped to it upstream.
516    ///
517    /// # Parameters
518    /// - `disp2`, `disp3`, `cn`: see [`dftd4_set_model_realspace_cutoff`]
519    /// - `width2`: smoothing width of the two-body cutoff
520    /// - `width3`: smoothing width of the three-body cutoff
521    ///
522    /// Same error behaviour and v4.2.0 version note as
523    /// [`dftd4_set_model_realspace_cutoff`].
524    pub fn dftd4_set_model_realspace_cutoff_smooth(
525        error: dftd4_error,
526        disp: dftd4_model,
527        disp2: c_double,
528        disp3: c_double,
529        cn: c_double,
530        width2: c_double,
531        width3: c_double,
532    );
533
534    // Damping parameter functions
535    /// Create new rational damping parameters
536    ///
537    /// # Parameters
538    /// - `s6`: Scaling factor for C6 term
539    /// - `s8`: Scaling factor for C8 term
540    /// - `s9`: Scaling factor for three-body term
541    /// - `a1`: Damping parameter
542    /// - `a2`: Damping parameter
543    /// - `alp`: Damping parameter
544    pub fn dftd4_new_rational_damping(
545        error: dftd4_error,
546        s6: c_double,
547        s8: c_double,
548        s9: c_double,
549        a1: c_double,
550        a2: c_double,
551        alp: c_double,
552    ) -> dftd4_param;
553
554    /// Load rational damping parameters from internal storage
555    ///
556    /// # Parameters
557    /// - `method`: Name of the method (e.g., "pbe", "scan")
558    /// - `mbd`: Whether to use many-body dispersion
559    pub fn dftd4_load_rational_damping(
560        error: dftd4_error,
561        method: *const c_char,
562        mbd: c_int,
563    ) -> dftd4_param;
564
565    /// Delete damping parameters
566    pub fn dftd4_delete_param(param: *mut dftd4_param);
567
568    // Calculation functions
569    /// Evaluate properties related to the dispersion model
570    ///
571    /// # Parameters
572    /// - `cn`: Coordination numbers `[natoms]` (nullable)
573    /// - `charges`: Partial charges `[natoms]` (nullable)
574    /// - `c6`: C6 coefficients `[natoms*natoms]` (nullable), Fortran storage
575    ///   (entry `[i][j]` at flat index `i + natoms*j`), symmetric
576    /// - `alpha`: Polarizabilities `[natoms]` (nullable)
577    ///
578    /// Each non-null output is written in full over its documented extent;
579    /// the sizes are the caller's allocation contract (see
580    /// `test_get_properties_fills_documented_array_sizes`).
581    ///
582    /// # Warning
583    ///
584    /// A degenerate `mol` (`natoms <= 0`, see [`dftd4_new_structure`]) makes
585    /// this call terminate the host process via Fortran `error stop` instead
586    /// of setting `error` — same hazard as [`dftd4_get_dispersion`].
587    pub fn dftd4_get_properties(
588        error: dftd4_error,
589        mol: dftd4_structure,
590        disp: dftd4_model,
591        cn: *mut c_double,
592        charges: *mut c_double,
593        c6: *mut c_double,
594        alpha: *mut c_double,
595    );
596
597    /// Evaluate the dispersion energy and its derivatives
598    ///
599    /// # Parameters
600    /// - `energy`: Dispersion energy in Hartree
601    /// - `gradient`: Energy gradient `[natoms][3]` in Hartree/Bohr (nullable)
602    /// - `sigma`: Virial tensor `[3][3]` in Hartree (nullable)
603    ///
604    /// # Note
605    ///
606    /// `gradient` and `sigma` are documented as *independently* nullable, but
607    /// the pinned upstream v4.2.0 C wrapper has a bug exactly there: a
608    /// **non-null `sigma` with a null `gradient` kills the host process with
609    /// SIGSEGV** (the Fortran kernel zero-initializes both derivative arrays
610    /// as soon as *either* is present, and writing through the absent one
611    /// dereferences a null base address — the error handle is never set).
612    /// The vendored source build of this crate patches that missing guard
613    /// into the extracted tree (see `build.rs`,
614    /// `patch_get_dispersion_scratch_gradient`), so with the vendored library
615    /// the documented behavior holds; the unrequested gradient is computed
616    /// into scratch storage and discarded. A library located via pkg-config
617    /// or `DFTD4_DIR` is **not** patched — with such a library (reproduced on
618    /// v4.2.0 and still present on upstream `main` at the time of writing),
619    /// pass `gradient` and `sigma` together or expect the segfault.
620    ///
621    /// # Warning
622    ///
623    /// If `mol` is degenerate (created with `natoms <= 0`, see
624    /// [`dftd4_new_structure`]) this call does **not** report an error through
625    /// `error` — it terminates the entire host process with a Fortran
626    /// `error stop` (stderr: `[Error]: Bunch-Kaufman factorization failed.` /
627    /// `ERROR STOP`, exit code 1). Validate `natoms > 0` and the atomic
628    /// numbers up front, e.g. with [`Dftd4Structure::try_new`].
629    ///
630    /// With a **null `error` handle** this call is also a silent no-op: it
631    /// returns before touching `energy`, `gradient` or `sigma`, so untouched
632    /// values (e.g. a `0.0`-initialised energy) masquerade as results.
633    pub fn dftd4_get_dispersion(
634        error: dftd4_error,
635        mol: dftd4_structure,
636        disp: dftd4_model,
637        param: dftd4_param,
638        energy: *mut c_double,
639        gradient: *mut c_double,
640        sigma: *mut c_double,
641    );
642
643    /// Evaluate the dispersion hessian numerically
644    ///
645    /// # Parameters
646    /// - `hess`: Second-derivative matrix `[(3*natoms)*(3*natoms)]` in
647    ///   Hartree/Bohr², stored in Fortran (column) order: the entry
648    ///   `d2 E / dR[ia][ic] dR[ja][jc]` lives at
649    ///   `hess[(3*ia + ic) + 3*natoms * (3*ja + jc)]`, matching the
650    ///   `hessian(3,natoms,3,natoms)` reshape of upstream v4.2.0
651    ///   `api.f90`. It is obtained from central differences of the analytic
652    ///   gradient (step `1e-4` Bohr, `numdiff.f90`) and is therefore
653    ///   symmetric and translationally invariant (vanishing row sums) up to
654    ///   the numerical noise of that construction.
655    ///
656    /// # Warning
657    ///
658    /// A degenerate `mol` (`natoms <= 0`, see [`dftd4_new_structure`]) makes
659    /// this call terminate the host process via Fortran `error stop` instead
660    /// of setting `error` — same hazard as [`dftd4_get_dispersion`].
661    pub fn dftd4_get_numerical_hessian(
662        error: dftd4_error,
663        mol: dftd4_structure,
664        disp: dftd4_model,
665        param: dftd4_param,
666        hess: *mut c_double,
667    );
668
669    /// Evaluate the pairwise representation of the dispersion energy
670    ///
671    /// # Parameters
672    /// - `pair_energy2`: Two-body pair decomposition `[natoms][natoms]`
673    ///   (Fortran storage: entry `[i][j]` at flat index `i + natoms*j`)
674    /// - `pair_energy3`: Three-body pair decomposition `[natoms][natoms]`,
675    ///   same storage
676    ///
677    /// Both arrays are the caller-allocated pair-resolved breakdown of the
678    /// energy; the sum over all `2 * natoms*natoms` entries reproduces the
679    /// total `energy` of [`dftd4_get_dispersion`] and the matrices are
680    /// symmetric with zero diagonal (pinned by the
681    /// `test_get_pairwise_dispersion_*` regression tests).
682    ///
683    /// # Warning
684    ///
685    /// A degenerate `mol` (`natoms <= 0`, see [`dftd4_new_structure`]) makes
686    /// this call terminate the host process via Fortran `error stop` instead
687    /// of setting `error` — same hazard as [`dftd4_get_dispersion`].
688    pub fn dftd4_get_pairwise_dispersion(
689        error: dftd4_error,
690        mol: dftd4_structure,
691        disp: dftd4_model,
692        param: dftd4_param,
693        pair_energy2: *mut c_double,
694        pair_energy3: *mut c_double,
695    );
696}
697
698#[cfg(test)]
699mod tests {
700    use super::*;
701    use std::ptr::{null, null_mut};
702
703    /// Extracts the rejection from a checked constructor, panicking if it
704    /// unexpectedly accepted the input. Avoids `Result::expect_err`, which
705    /// would require `Debug` on the handle wrapper.
706    fn rejection<T>(result: Result<T, Dftd4StructureError>, what: &str) -> Dftd4StructureError {
707        match result {
708            Err(err) => err,
709            Ok(_) => panic!("{what} must be rejected"),
710        }
711    }
712
713    /// Major version of the libdftd4 the build script is allowed to link —
714    /// mirrors `PINNED_MAJOR` in `build.rs` (the F0443 guard), which is not
715    /// visible from test code.
716    const EXPECTED_MAJOR: c_int = 4;
717
718    /// Pins the compact version (`major * 10000 + minor * 100 + patch`) of the
719    /// library that is *actually loaded* to the major version the build script
720    /// promises to link. The earlier `version > 0` stayed green against *any*
721    /// libdftd4: a `DFTD4_DIR` install whose `dftd4.pc` lies about its minor
722    /// version (only the major is checked there) or has no `.pc` at all, or a
723    /// different `libdftd4.so` resolved at load time, could link an
724    /// ABI-incompatible library — e.g. one reporting `50000` (5.0.0) — and
725    /// only the functional tests would ever notice the mismatch.
726    #[test]
727    fn test_version() {
728        unsafe {
729            let version = dftd4_get_version();
730            assert_eq!(
731                version / 10000,
732                EXPECTED_MAJOR,
733                "libdftd4 reports the compact version {version}, expected a \
734                 {EXPECTED_MAJOR}.x library (major * 10000 + minor * 100 + patch)"
735            );
736            println!("DFT-D4 version: {version}");
737        }
738    }
739
740    #[test]
741    fn test_error_handle() {
742        unsafe {
743            let error = dftd4_new_error();
744            assert!(!error.is_null(), "Error handle should not be null");
745
746            let status = dftd4_check_error(error);
747            assert_eq!(status, 0, "New error handle should have no error");
748
749            dftd4_delete_error(&mut error.cast());
750        }
751    }
752
753    /// Reads the error message through the documented channel
754    /// ([`dftd4_get_error`]) into an owned Rust string, so tests can inspect
755    /// the status-1 message itself instead of only reaching it in the failure
756    /// branch of [`check_error`].
757    fn error_message(error: dftd4_error) -> String {
758        unsafe {
759            let mut buf = [0i8; 512];
760            let size: c_int = buf.len() as c_int;
761            dftd4_get_error(error, buf.as_mut_ptr().cast(), &size);
762            std::ffi::CStr::from_ptr(buf.as_ptr().cast())
763                .to_string_lossy()
764                .into_owned()
765        }
766    }
767
768    /// Regression test for the documented error *message* channel: status `1`
769    /// of `dftd4_check_error` plus the text delivered by `dftd4_get_error`.
770    /// An unknown damping functional is the simplest upstream-reported failure
771    /// (pinned v4.2.0 `api.f90`): the call returns a null parameter handle
772    /// and reports `"Functional '<name>' not known"` on the error handle.
773    /// Earlier tests only ever asserted statuses `0` and `2`, so this channel
774    /// — the crate's central documented failure path — was completely untested.
775    #[test]
776    fn test_error_message_unknown_functional() {
777        unsafe {
778            let error = Dftd4Error(dftd4_new_error());
779            let param = Dftd4Param(dftd4_load_rational_damping(
780                error.0,
781                c"no-such-functional".as_ptr(),
782                0,
783            ));
784            assert!(
785                param.0.is_null(),
786                "an unknown functional must not produce a parameter handle"
787            );
788            assert_eq!(
789                dftd4_check_error(error.0),
790                1,
791                "an unknown functional must set the handle (status 1 = message available)"
792            );
793            let msg = error_message(error.0);
794            assert!(
795                msg.contains("no-such-functional") && msg.contains("not known"),
796                "the message must name the rejected functional, got {msg:?}"
797            );
798        }
799    }
800
801    /// Regression test for the "unsupported element" failure the crate
802    /// documentation promises goes "through the error handle": atomic numbers
803    /// `104..=111` are inside the data tables (`1..=118`), so structure
804    /// creation succeeds, but the D4 model builder rejects them via the handle
805    /// (pinned v4.2.0 `model/d4.f90`) and hands out no model.
806    #[test]
807    fn test_error_message_unsupported_element() {
808        unsafe {
809            let error = Dftd4Error(dftd4_new_error());
810            let numbers = [104, 104]; // Rf (rutherfordium), inside 1..=118
811            let positions = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
812            let mol = Dftd4Structure(dftd4_new_structure(
813                error.0,
814                2,
815                numbers.as_ptr(),
816                positions.as_ptr(),
817                null(),
818                null(),
819                null(),
820            ));
821            assert!(
822                !mol.0.is_null(),
823                "Rf is inside the supported range, so structure creation must succeed"
824            );
825            assert_eq!(
826                dftd4_check_error(error.0),
827                0,
828                "structure creation must leave the handle empty"
829            );
830
831            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
832            assert!(
833                disp.0.is_null(),
834                "the model builder must not hand out a model for an unsupported element"
835            );
836            assert_eq!(
837                dftd4_check_error(error.0),
838                1,
839                "unsupported elements are the documented in-handle failure (status 1)"
840            );
841            let msg = error_message(error.0);
842            assert!(
843                msg.contains("unsupported element") && msg.contains("Rf"),
844                "the message must name the unsupported element, got {msg:?}"
845            );
846        }
847    }
848
849    /// Regression test for the two `dftd4_get_error` contracts pinned in its
850    /// documentation (F0452): `buffersize` is **input-only** (upstream
851    /// v4.2.0 declares it `intent(in)`, so no written length is ever reported
852    /// back) and truncation into a too-small buffer is NUL-terminated.
853    #[test]
854    fn test_get_error_buffersize_input_only_and_truncation_nul_terminated() {
855        unsafe {
856            let error = Dftd4Error(dftd4_new_error());
857            // Set a message through the documented failure path itself.
858            let _ = dftd4_load_rational_damping(error.0, c"no-such-functional".as_ptr(), 0);
859            assert_eq!(
860                dftd4_check_error(error.0),
861                1,
862                "precondition: the handle must carry a message"
863            );
864            let full = error_message(error.0);
865
866            // Too-small buffer, pre-filled with a sentinel: the truncated text
867            // must be NUL-terminated *inside* the buffer capacity.
868            let mut small = [b'X'; 8];
869            assert!(
870                full.len() > small.len(),
871                "precondition: the message must be long enough to truncate"
872            );
873            let size: c_int = small.len() as c_int;
874            dftd4_get_error(error.0, small.as_mut_ptr().cast(), &size);
875            assert!(
876                small.contains(&0),
877                "a truncated message must be NUL-terminated within the buffer: {small:?}",
878            );
879            let text = std::ffi::CStr::from_ptr(small.as_ptr().cast()).to_string_lossy();
880            assert!(
881                text.len() < small.len(),
882                "the truncated text plus its NUL terminator must fit the buffer, got {:?}",
883                text.as_ref()
884            );
885            assert!(
886                full.starts_with(&*text),
887                "the truncated text must be a prefix of the full message \
888                 ({text:?} vs {full:?})"
889            );
890
891            // `buffersize` is input-only: upstream must not write a length back.
892            assert_eq!(
893                size,
894                small.len() as c_int,
895                "buffersize is input-only and must be left untouched"
896            );
897        }
898    }
899
900    /// Regression test: a degenerate atom count (`natoms <= 0`) bypasses the
901    /// C error handle upstream — the raw API accepts it silently and a later
902    /// calculation aborts the whole process via a Fortran `error stop`.
903    /// `try_new` must reject it with a catchable error *before* the FFI call
904    /// (if the guard were missing, this test process would be killed).
905    #[test]
906    fn test_try_new_rejects_degenerate_atom_count() {
907        unsafe {
908            let error = Dftd4Error(dftd4_new_error());
909            let numbers = [18, 18];
910            let positions = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
911
912            for natoms in [0, -1] {
913                let err = rejection(
914                    Dftd4Structure::try_new(
915                        error.0,
916                        natoms,
917                        numbers.as_ptr(),
918                        positions.as_ptr(),
919                        null(),
920                        null(),
921                        null(),
922                    ),
923                    &format!("natoms = {natoms}"),
924                );
925                assert_eq!(err, Dftd4StructureError::EmptyAtomCount { natoms });
926            }
927
928            assert_eq!(
929                dftd4_check_error(error.0),
930                0,
931                "rejections must happen before the FFI call and leave the handle untouched"
932            );
933        }
934    }
935
936    /// Regression test: atomic numbers outside `1..=118` are not rejected by
937    /// the upstream data tables but silently mapped to zero-valued filler data
938    /// (raw API: `energy = 0.0`, empty error handle). `try_new` must reject
939    /// them with the offending index and number.
940    #[test]
941    fn test_try_new_rejects_out_of_range_atomic_numbers() {
942        unsafe {
943            let error = Dftd4Error(dftd4_new_error());
944            let positions = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
945
946            let beyond = [18, 999];
947            let err = rejection(
948                Dftd4Structure::try_new(
949                    error.0,
950                    2,
951                    beyond.as_ptr(),
952                    positions.as_ptr(),
953                    null(),
954                    null(),
955                    null(),
956                ),
957                "atomic number 999",
958            );
959            assert_eq!(
960                err,
961                Dftd4StructureError::AtomicNumberOutOfRange {
962                    index: 1,
963                    number: 999
964                }
965            );
966
967            let below = [0, 18];
968            let err = rejection(
969                Dftd4Structure::try_new(
970                    error.0,
971                    2,
972                    below.as_ptr(),
973                    positions.as_ptr(),
974                    null(),
975                    null(),
976                    null(),
977                ),
978                "atomic number 0",
979            );
980            assert_eq!(
981                err,
982                Dftd4StructureError::AtomicNumberOutOfRange {
983                    index: 0,
984                    number: 0
985                }
986            );
987
988            assert_eq!(dftd4_check_error(error.0), 0);
989        }
990    }
991
992    /// Null required arrays are reported instead of being passed into the FFI.
993    #[test]
994    fn test_try_new_rejects_null_arrays() {
995        unsafe {
996            let error = Dftd4Error(dftd4_new_error());
997            let numbers = [18, 18];
998            let positions = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
999
1000            let err = rejection(
1001                Dftd4Structure::try_new(
1002                    error.0,
1003                    2,
1004                    null(),
1005                    positions.as_ptr(),
1006                    null(),
1007                    null(),
1008                    null(),
1009                ),
1010                "null numbers",
1011            );
1012            assert_eq!(
1013                err,
1014                Dftd4StructureError::MissingRequiredArray {
1015                    argument: "numbers"
1016                }
1017            );
1018
1019            let err = rejection(
1020                Dftd4Structure::try_new(
1021                    error.0,
1022                    2,
1023                    numbers.as_ptr(),
1024                    null(),
1025                    null(),
1026                    null(),
1027                    null(),
1028                ),
1029                "null positions",
1030            );
1031            assert_eq!(
1032                err,
1033                Dftd4StructureError::MissingRequiredArray {
1034                    argument: "positions"
1035                }
1036            );
1037
1038            assert_eq!(dftd4_check_error(error.0), 0);
1039        }
1040    }
1041
1042    /// Regression test: `gradient` and `sigma` of [`dftd4_get_dispersion`] are
1043    /// documented as independently nullable, but the pinned upstream v4.2.0 C
1044    /// wrapper only guards one direction: a non-null `sigma` with a null
1045    /// `gradient` passes an unallocated (absent) gradient into the Fortran
1046    /// kernel, which zero-initializes *both* arrays as soon as *either* is
1047    /// present — the write hits a null base address and the whole host
1048    /// process dies with SIGSEGV (exit code 139) without the error handle
1049    /// ever being consulted. `build.rs` patches that missing guard into the
1050    /// vendored tree; this test pins the documented behavior (if the patch
1051    /// were removed, this test process would be killed here).
1052    #[test]
1053    fn test_get_dispersion_sigma_without_gradient() {
1054        /// Largest elementwise deviation between two output buffers.
1055        fn max_abs_diff(got: &[f64], want: &[f64]) -> f64 {
1056            got.iter()
1057                .zip(want)
1058                .map(|(g, w): (&f64, &f64)| (g - w).abs())
1059                .fold(0.0f64, f64::max)
1060        }
1061
1062        unsafe {
1063            let error = Dftd4Error(dftd4_new_error());
1064            // Argon dimer at 7.0 Bohr along x
1065            let numbers = [18, 18];
1066            let positions = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
1067            let mol = Dftd4Structure::try_new(
1068                error.0,
1069                2,
1070                numbers.as_ptr(),
1071                positions.as_ptr(),
1072                null(),
1073                null(),
1074                null(),
1075            )
1076            .expect("argon dimer is a valid structure");
1077            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
1078            assert_eq!(dftd4_check_error(error.0), 0, "D4 model build failed");
1079            let param = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
1080            assert_eq!(dftd4_check_error(error.0), 0, "parameter load failed");
1081
1082            // Reference: request gradient and sigma together.
1083            let mut e_ref = f64::NAN;
1084            let mut grad_ref = [0.0f64; 6];
1085            let mut sigma_ref = [0.0f64; 9];
1086            dftd4_get_dispersion(
1087                error.0,
1088                mol.0,
1089                disp.0,
1090                param.0,
1091                &mut e_ref,
1092                grad_ref.as_mut_ptr(),
1093                sigma_ref.as_mut_ptr(),
1094            );
1095            assert_eq!(dftd4_check_error(error.0), 0, "grad+sigma call failed");
1096            assert!(
1097                e_ref.is_finite() && e_ref < 0.0,
1098                "expected attractive finite energy, got {e_ref}"
1099            );
1100            // The reference buffers must carry real derivatives, otherwise the
1101            // sigma-only equality below would compare untouched buffers.
1102            assert!(
1103                grad_ref.iter().any(|g| *g != 0.0),
1104                "grad+sigma call produced an all-zero gradient"
1105            );
1106            assert!(
1107                sigma_ref.iter().any(|s| *s != 0.0),
1108                "grad+sigma call produced an all-zero sigma"
1109            );
1110
1111            // The documented-but-crashing call pattern: sigma non-null,
1112            // gradient NULL. SIGSEGVs without the build.rs wrapper patch.
1113            let mut e = f64::NAN;
1114            let mut sigma = [0.0f64; 9];
1115            dftd4_get_dispersion(
1116                error.0,
1117                mol.0,
1118                disp.0,
1119                param.0,
1120                &mut e,
1121                null_mut(),
1122                sigma.as_mut_ptr(),
1123            );
1124            assert_eq!(
1125                dftd4_check_error(error.0),
1126                0,
1127                "sigma-only call must succeed through the error handle"
1128            );
1129            assert!(
1130                e.is_finite() && e < 0.0,
1131                "sigma-only energy must be attractive and finite, got {e}"
1132            );
1133            assert!(
1134                (e - e_ref).abs() <= 1e-12,
1135                "sigma-only energy {e} deviates from the grad+sigma reference {e_ref}"
1136            );
1137            let diff = max_abs_diff(&sigma, &sigma_ref);
1138            assert!(
1139                diff <= 1e-12,
1140                "sigma-only virial deviates from the grad+sigma virial by {diff}"
1141            );
1142
1143            // The same pattern on a periodic structure (the segfault was
1144            // structure-agnostic).
1145            let lattice = [20.0f64, 0.0, 0.0, 0.0, 20.0, 0.0, 0.0, 0.0, 20.0];
1146            let periodic = [true, true, true];
1147            let pcell = Dftd4Structure::try_new(
1148                error.0,
1149                2,
1150                numbers.as_ptr(),
1151                positions.as_ptr(),
1152                null(),
1153                lattice.as_ptr(),
1154                periodic.as_ptr(),
1155            )
1156            .expect("periodic argon dimer box is a valid structure");
1157            let pdisp = Dftd4Model(dftd4_new_d4_model(error.0, pcell.0));
1158            assert_eq!(
1159                dftd4_check_error(error.0),
1160                0,
1161                "periodic D4 model build failed"
1162            );
1163
1164            let mut pe_ref = f64::NAN;
1165            let mut psigma_ref = [0.0f64; 9];
1166            dftd4_get_dispersion(
1167                error.0,
1168                pcell.0,
1169                pdisp.0,
1170                param.0,
1171                &mut pe_ref,
1172                null_mut(),
1173                psigma_ref.as_mut_ptr(),
1174            );
1175            assert_eq!(
1176                dftd4_check_error(error.0),
1177                0,
1178                "periodic sigma-only call failed"
1179            );
1180            assert!(
1181                pe_ref.is_finite() && pe_ref < 0.0,
1182                "periodic sigma-only energy must be attractive and finite, got {pe_ref}"
1183            );
1184            assert!(
1185                psigma_ref.iter().any(|s| *s != 0.0),
1186                "periodic sigma-only call produced an all-zero sigma"
1187            );
1188        }
1189    }
1190
1191    /// Regression test: with a null `error` handle the pinned upstream does
1192    /// not merely report less — `new_structure_api` (v4.2.0,
1193    /// `src/dftd4/api.f90`) starts with `vmol = c_null_ptr` followed by an
1194    /// early `if (.not.c_associated(verror)) return`, so the raw call returns
1195    /// a **null structure handle with no diagnostics at all**, and the
1196    /// calculation functions likewise return without writing their outputs
1197    /// (a `0.0`-initialised `energy` then looks like a valid "no dispersion"
1198    /// result; a real handle gives e.g. −4.4e-4 Eh for the argon dimer).
1199    /// `try_new` must reject a null handle before the FFI call instead of
1200    /// wrapping the null pointer as `Ok` (without this guard `try_new`
1201    /// returned `Ok` with `mol.0.is_null()`, so the `rejection()` assertion
1202    /// below failed).
1203    #[test]
1204    fn test_try_new_rejects_null_error_handle() {
1205        unsafe {
1206            let numbers = [18, 18];
1207            let positions = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
1208
1209            // Pin the silent upstream behaviour this guard exists for (the
1210            // early return happens before any allocation, so nothing leaks):
1211            // the raw call yields a null structure, and status 2 from
1212            // dftd4_check_error is the only, after-the-fact signal.
1213            let raw = dftd4_new_structure(
1214                null_mut(),
1215                2,
1216                numbers.as_ptr(),
1217                positions.as_ptr(),
1218                null(),
1219                null(),
1220                null(),
1221            );
1222            assert!(
1223                raw.is_null(),
1224                "vendored v4.2.0 returns a null structure for a null error \
1225                 handle; if this ever changes, revisit the try_new guard"
1226            );
1227            assert_eq!(
1228                dftd4_check_error(null_mut()),
1229                2,
1230                "status 2 must report an invalid (null) error handle"
1231            );
1232
1233            let err = rejection(
1234                Dftd4Structure::try_new(
1235                    null_mut(),
1236                    2,
1237                    numbers.as_ptr(),
1238                    positions.as_ptr(),
1239                    null(),
1240                    null(),
1241                    null(),
1242                ),
1243                "null error handle",
1244            );
1245            assert_eq!(err, Dftd4StructureError::MissingErrorHandle);
1246        }
1247    }
1248
1249    /// A valid structure passes the guard, is usable end-to-end, and the error
1250    /// handle remains the documented (here: silent) failure channel.
1251    #[test]
1252    fn test_try_new_accepts_valid_structure() {
1253        unsafe {
1254            let error = Dftd4Error(dftd4_new_error());
1255            // Argon dimer at 7.0 Bohr
1256            let numbers = [18, 18];
1257            let positions = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
1258
1259            let mol = Dftd4Structure::try_new(
1260                error.0,
1261                2,
1262                numbers.as_ptr(),
1263                positions.as_ptr(),
1264                null(),
1265                null(),
1266                null(),
1267            )
1268            .expect("argon dimer is a valid structure");
1269            assert!(!mol.0.is_null());
1270            assert_eq!(dftd4_check_error(error.0), 0);
1271
1272            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
1273            assert_eq!(dftd4_check_error(error.0), 0, "D4 model build failed");
1274            let param = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
1275            assert_eq!(dftd4_check_error(error.0), 0, "parameter load failed");
1276
1277            let mut energy = f64::NAN;
1278            dftd4_get_dispersion(
1279                error.0,
1280                mol.0,
1281                disp.0,
1282                param.0,
1283                &mut energy,
1284                null_mut(),
1285                null_mut(),
1286            );
1287            assert_eq!(dftd4_check_error(error.0), 0, "dispersion failed");
1288            assert!(
1289                energy.is_finite() && energy < 0.0,
1290                "argon dimer at 7.0 Bohr must get a finite, attractive energy, got {energy}"
1291            );
1292        }
1293    }
1294
1295    /// Regression test for the two v4.2.0 realspace-cutoff bindings
1296    /// [`dftd4_set_model_realspace_cutoff`] and
1297    /// [`dftd4_set_model_realspace_cutoff_smooth`]. Both symbols exist in the
1298    /// pinned library (`include/dftd4.h`, suffix `DFTD4_API_SUFFIX__V_4_2`)
1299    /// but were the only functions of the pinned C API without a Rust
1300    /// declaration, although the README documents full coverage — before they
1301    /// were bound this test did not even compile. It pins that the cutoffs
1302    /// actually take effect in the calculation entry points (they are stored
1303    /// on the model handle, `vp_model%cutoff` upstream): the periodic Ar cell
1304    /// (diamond-like basis (0,0,0)+(½,½,½), nearest-neighbour distance
1305    /// √3·a/2 ≈ 8.6 Bohr, next shell a ≈ 9.9 Bohr) loses its whole dispersion
1306    /// energy below a two-body cutoff of 8 Bohr, restoring the defaults
1307    /// restores the default energy, the zero-width smooth call equals the hard
1308    /// cutoff, and a smoothing width ramps the nearest-neighbour contribution
1309    /// (switch interval [cutoff-width, cutoff] = [5, 9] Bohr covers 8.6 and
1310    /// leaves it only ~0.8% of its weight). Also pins the upstream
1311    /// "Dispersion model is missing" error path for a null model handle.
1312    #[test]
1313    fn test_set_model_realspace_cutoff() {
1314        // Same cell as `ar_fcc_pbe_d4_energy` (a = 5.26 Å, Bohr).
1315        let a = 5.26 * 1.889_725_988_6;
1316        let numbers = [18, 18];
1317        let positions = [0.0, 0.0, 0.0, a / 2.0, a / 2.0, a / 2.0];
1318        let lattice = [a, 0.0, 0.0, 0.0, a, 0.0, 0.0, 0.0, a];
1319        let periodic = [true, true, true];
1320
1321        unsafe {
1322            let error = Dftd4Error(dftd4_new_error());
1323            let mol = Dftd4Structure(dftd4_new_structure(
1324                error.0,
1325                2,
1326                numbers.as_ptr(),
1327                positions.as_ptr(),
1328                null(),
1329                lattice.as_ptr(),
1330                periodic.as_ptr(),
1331            ));
1332            check_error(error.0, "new_structure");
1333            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
1334            check_error(error.0, "new_d4_model");
1335            let param = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
1336            check_error(error.0, "load_rational_damping");
1337
1338            let energy = |what: &str| {
1339                let mut e = f64::NAN;
1340                dftd4_get_dispersion(
1341                    error.0,
1342                    mol.0,
1343                    disp.0,
1344                    param.0,
1345                    &mut e,
1346                    null_mut(),
1347                    null_mut(),
1348                );
1349                check_error(error.0, what);
1350                assert!(e.is_finite(), "{what}: energy {e} is not finite");
1351                e
1352            };
1353
1354            let e_default = energy("default cutoffs");
1355            assert!(
1356                e_default < 0.0,
1357                "default PBE-D4 energy must be attractive, got {e_default}"
1358            );
1359
1360            // Two-/three-body cutoffs below the nearest-neighbour distance
1361            // (8.6 Bohr) leave no pair inside the interaction range.
1362            dftd4_set_model_realspace_cutoff(error.0, disp.0, 5.0, 5.0, 30.0);
1363            check_error(error.0, "set_model_realspace_cutoff");
1364            let e_tiny = energy("cutoffs 5/5/30 Bohr");
1365            assert!(
1366                e_tiny.abs() < 1e-8,
1367                "cutoffs below the nearest-neighbour distance must remove the \
1368                 dispersion energy, got {e_tiny} (default {e_default})"
1369            );
1370
1371            // Restoring the library defaults must restore the default result.
1372            dftd4_set_model_realspace_cutoff(error.0, disp.0, 60.0, 40.0, 30.0);
1373            check_error(error.0, "set_model_realspace_cutoff (defaults)");
1374            let e_restored = energy("restored defaults");
1375            assert!(
1376                (e_restored - e_default).abs() <= 1e-12,
1377                "restoring the default cutoffs must reproduce the default \
1378                 energy {e_default}, got {e_restored}"
1379            );
1380
1381            // Zero smoothing widths must equal the hard cutoff ...
1382            dftd4_set_model_realspace_cutoff_smooth(error.0, disp.0, 60.0, 40.0, 30.0, 0.0, 0.0);
1383            check_error(error.0, "set_model_realspace_cutoff_smooth (zero width)");
1384            let e_smooth_hard = energy("smooth 60/40/30, width 0");
1385            assert!(
1386                (e_smooth_hard - e_default).abs() <= 1e-12,
1387                "zero-width smooth cutoffs must equal the hard default energy \
1388                 {e_default}, got {e_smooth_hard}"
1389            );
1390
1391            // ... while a nonzero width ramps the switch: the nearest
1392            // neighbour at 8.6 Bohr sits inside the interval
1393            // [cutoff - width, cutoff] = [5, 9] Bohr of the 9 Bohr two-body
1394            // cutoff (switch variable x = (9 - 8.6)/4 ≈ 0.1, quintic weight
1395            // ~0.008) and keeps only a fraction of its weight, so the smooth
1396            // energy is strictly less attractive than the hard one (the
1397            // three-body term is identical in both calls and cancels in the
1398            // difference).
1399            dftd4_set_model_realspace_cutoff(error.0, disp.0, 9.0, 40.0, 30.0);
1400            check_error(error.0, "set_model_realspace_cutoff (9/40/30)");
1401            let e_hard9 = energy("hard cutoff 9/40/30");
1402            assert!(
1403                e_hard9 < 0.0,
1404                "nearest neighbours are inside a 9 Bohr cutoff, energy must be \
1405                 attractive, got {e_hard9}"
1406            );
1407            dftd4_set_model_realspace_cutoff_smooth(error.0, disp.0, 9.0, 40.0, 30.0, 4.0, 0.0);
1408            check_error(
1409                error.0,
1410                "set_model_realspace_cutoff_smooth (9/40/30, width 4)",
1411            );
1412            let e_smooth9 = energy("smooth cutoff 9/40/30, width2 4");
1413            assert!(
1414                e_smooth9 > e_hard9 + 1e-9,
1415                "smoothing the two-body cutoff must reduce |energy| (partial \
1416                 nearest-neighbour weight): hard {e_hard9}, smooth {e_smooth9}"
1417            );
1418
1419            // A null model handle is reported through the error handle
1420            // (fresh handles: an already-set error message is never cleared).
1421            for smooth in [false, true] {
1422                let probe = Dftd4Error(dftd4_new_error());
1423                if smooth {
1424                    dftd4_set_model_realspace_cutoff_smooth(
1425                        probe.0,
1426                        null_mut(),
1427                        60.0,
1428                        40.0,
1429                        30.0,
1430                        0.0,
1431                        0.0,
1432                    );
1433                } else {
1434                    dftd4_set_model_realspace_cutoff(probe.0, null_mut(), 60.0, 40.0, 30.0);
1435                }
1436                assert_ne!(
1437                    dftd4_check_error(probe.0),
1438                    0,
1439                    "a null model handle must be reported through the error handle"
1440                );
1441                let mut buf = [0i8; 512];
1442                let size: c_int = buf.len() as c_int;
1443                dftd4_get_error(probe.0, buf.as_mut_ptr().cast(), &size);
1444                let msg = std::ffi::CStr::from_ptr(buf.as_ptr().cast()).to_string_lossy();
1445                assert!(
1446                    msg.contains("Dispersion model is missing"),
1447                    "unexpected error message for a null model handle: {msg}"
1448                );
1449            }
1450
1451            // A null error handle returns before the validation above (the
1452            // documented crate-wide silent no-op) — must not crash.
1453            dftd4_set_model_realspace_cutoff(null_mut(), null_mut(), 1.0, 1.0, 1.0);
1454            dftd4_set_model_realspace_cutoff_smooth(
1455                null_mut(),
1456                null_mut(),
1457                1.0,
1458                1.0,
1459                1.0,
1460                1.0,
1461                1.0,
1462            );
1463        }
1464    }
1465
1466    /// Extracts the element width of the `periodic` parameter directly from
1467    /// the declared signature of `dftd4_new_structure`. It compiles against
1468    /// either pointee type, so it can pin the ABI width at runtime.
1469    const fn periodic_pointee_size<T>(
1470        _: unsafe extern "C" fn(
1471            dftd4_error,
1472            c_int,
1473            *const c_int,
1474            *const c_double,
1475            *const c_double,
1476            *const c_double,
1477            *const T,
1478        ) -> dftd4_structure,
1479    ) -> usize {
1480        std::mem::size_of::<T>()
1481    }
1482
1483    fn check_error(error: dftd4_error, what: &str) {
1484        unsafe {
1485            if dftd4_check_error(error) != 0 {
1486                let mut buf = [0i8; 512];
1487                let size: c_int = buf.len() as c_int;
1488                dftd4_get_error(error, buf.as_mut_ptr().cast(), &size);
1489                let msg = std::ffi::CStr::from_ptr(buf.as_ptr().cast()).to_string_lossy();
1490                panic!("dftd4 error in {what}: {msg}");
1491            }
1492        }
1493    }
1494
1495    /// PBE-D4 dispersion energy of the same two-atom fcc argon cell used by
1496    /// the regression tests (a = 5.26 Å, quantities in Bohr). `periodic`
1497    /// points at the three periodicity flags; the pointer is reinterpreted
1498    /// via `cast()` internally, so the element type actually read by the
1499    /// library is the one the binding declares. This lets one test drive
1500    /// both the 4-byte and the 1-byte layout. Note: with a lattice present,
1501    /// a *null* pointer would default to fully periodic (mctc-lib
1502    /// `new_structure`), so the non-periodic reference must pass explicit
1503    /// all-false flags.
1504    unsafe fn ar_fcc_pbe_d4_energy(periodic: *const bool) -> f64 {
1505        unsafe {
1506            let numbers = [18, 18];
1507            let a = 5.26 * 1.889_725_988_6;
1508            let positions = [0.0, 0.0, 0.0, a / 2.0, a / 2.0, a / 2.0];
1509            let lattice = [a, 0.0, 0.0, 0.0, a, 0.0, 0.0, 0.0, a];
1510
1511            let error = Dftd4Error(dftd4_new_error());
1512            let mol = Dftd4Structure(dftd4_new_structure(
1513                error.0,
1514                2,
1515                numbers.as_ptr(),
1516                positions.as_ptr(),
1517                null(),
1518                lattice.as_ptr(),
1519                periodic.cast(),
1520            ));
1521            check_error(error.0, "new_structure");
1522            assert!(
1523                !mol.0.is_null(),
1524                "dftd4_new_structure returned a null handle"
1525            );
1526
1527            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
1528            check_error(error.0, "new_d4_model");
1529            let param = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
1530            check_error(error.0, "load_rational_damping");
1531
1532            let mut energy = f64::NAN;
1533            dftd4_get_dispersion(
1534                error.0,
1535                mol.0,
1536                disp.0,
1537                param.0,
1538                &mut energy,
1539                null_mut(),
1540                null_mut(),
1541            );
1542            check_error(error.0, "get_dispersion");
1543            energy
1544        }
1545    }
1546
1547    /// ABI tripwire: upstream dftd4 (pinned v4.2.0) declares the periodicity
1548    /// flags in `include/dftd4.h` as `const bool* /* periodic [3] */` and the
1549    /// Fortran implementation reads `logical(c_bool) :: c_periodic(3)`
1550    /// (`src/dftd4/api.f90`) — **one byte per flag**. The binding's
1551    /// `periodic` parameter must therefore have a 1-byte pointee. With the
1552    /// previous `*const c_int`, the Fortran side indexed the caller's
1553    /// 4-byte-per-element array as a 1-byte array and on little-endian only
1554    /// ever saw `(LSB of flags[0], 0, 0)`.
1555    #[test]
1556    fn test_periodic_flags_are_one_byte() {
1557        assert_eq!(
1558            periodic_pointee_size(dftd4_new_structure),
1559            std::mem::size_of::<bool>(),
1560            "`dftd4_new_structure` must read the periodicity flags one byte \
1561             at a time (`*const bool`); see the ABI note on the declaration"
1562        );
1563    }
1564
1565    /// Behavior regression test: a 2D slab request (`periodic = [0, 1, 1]`)
1566    /// built exactly the way the binding's own signature dictates must yield
1567    /// the periodic dispersion energy. Upstream reduces the flags to
1568    /// `any(periodic)`, so `[0, 1, 1]` must behave like `[1, 1, 1]`. With the
1569    /// old `*const c_int` declaration the library read `(0, 0, 0)` from the
1570    /// 4-byte array and silently returned the non-periodic molecule energy
1571    /// (~12x too small here) without reporting an error.
1572    #[test]
1573    fn test_periodic_slab_flags() {
1574        unsafe {
1575            // Layout-independent references: three 1-byte bools, as the
1576            // upstream C header prescribes. [true, true, true] enables the
1577            // lattice path; [false, false, false] (upstream reduces the
1578            // flags to `any(periodic)`) leaves the cell a non-periodic
1579            // molecule. A null pointer would NOT: with a lattice present,
1580            // mctc-lib's `new_structure` defaults to fully periodic.
1581            let periodic_ref = [true, true, true];
1582            let molecule_ref = [false, false, false];
1583            let e_periodic = ar_fcc_pbe_d4_energy(periodic_ref.as_ptr());
1584            let e_molecule = ar_fcc_pbe_d4_energy(molecule_ref.as_ptr());
1585            assert!(
1586                (e_periodic - e_molecule).abs() > 1e-6,
1587                "sanity check failed: periodic ({e_periodic}) and non-periodic \
1588                 ({e_molecule}) energies are identical"
1589            );
1590
1591            // The flag array a caller *following the binding* would build
1592            // for [0, 1, 1], using the element type the binding declares.
1593            let flags4 = [0 as c_int, 1, 1];
1594            let flags1 = [false, true, true];
1595            let flags: *const bool = if periodic_pointee_size(dftd4_new_structure) == 4 {
1596                flags4.as_ptr().cast()
1597            } else {
1598                flags1.as_ptr()
1599            };
1600
1601            let e_slab = ar_fcc_pbe_d4_energy(flags);
1602            assert!(
1603                (e_slab - e_periodic).abs() < 1e-12,
1604                "periodic [0, 1, 1] computed {e_slab} instead of the periodic \
1605                 energy {e_periodic} (the non-periodic molecule value is \
1606                 {e_molecule}); the periodicity flags are being read with the \
1607                 wrong element width"
1608            );
1609        }
1610    }
1611
1612    /// Extracts the element widths of the two array pointees of
1613    /// [`dftd4_update_structure`] directly from its declared signature. The
1614    /// extractor compiles against any pointee types, so the tripwire below
1615    /// pins the ABI widths against the real library (same technique as
1616    /// [`periodic_pointee_size`]).
1617    const fn update_structure_pointee_sizes<T, U>(
1618        _: unsafe extern "C" fn(dftd4_error, dftd4_structure, *const T, *const U),
1619    ) -> (usize, usize) {
1620        (std::mem::size_of::<T>(), std::mem::size_of::<U>())
1621    }
1622
1623    /// Dispersion energy through [`dftd4_get_dispersion`] (energy only; no
1624    /// gradient or virial requested), asserting the error handle afterwards.
1625    unsafe fn dispersion_energy(
1626        error: dftd4_error,
1627        mol: dftd4_structure,
1628        disp: dftd4_model,
1629        param: dftd4_param,
1630    ) -> f64 {
1631        unsafe {
1632            let mut energy = f64::NAN;
1633            dftd4_get_dispersion(error, mol, disp, param, &mut energy, null_mut(), null_mut());
1634            check_error(error, "get_dispersion");
1635            energy
1636        }
1637    }
1638
1639    /// ABI tripwire: upstream (pinned v4.2.0) declares both array arguments
1640    /// of [`dftd4_update_structure`] as `const double*` in `include/dftd4.h`
1641    /// (`positions [natoms][3]`, optional `lattice [3][3]`) and the Fortran
1642    /// implementation reads them as `real(c_double)` — eight bytes per value.
1643    /// Narrower pointees (`c_float`, `c_int`) would silently misinterpret
1644    /// every coordinate, the same failure class as the periodicity-flag ABI
1645    /// incident pinned by [`test_periodic_flags_are_one_byte`].
1646    #[test]
1647    fn test_update_structure_arrays_are_double_width() {
1648        assert_eq!(
1649            update_structure_pointee_sizes(dftd4_update_structure),
1650            (
1651                std::mem::size_of::<c_double>(),
1652                std::mem::size_of::<c_double>()
1653            ),
1654            "`dftd4_update_structure` must read `positions` and `lattice` as \
1655             8-byte doubles (`*const c_double`)"
1656        );
1657    }
1658
1659    /// Regression test for the geometry-update hot path the crate
1660    /// documentation advertises (crate docs, crate-root line 21): reusing one
1661    /// structure handle across geometry steps of an optimisation or sampling
1662    /// loop. Updating the argon-dimer coordinates in place (with a null
1663    /// `lattice` for a molecule) must be reported through an otherwise clean
1664    /// handle, must actually change the energy computed with the **same**
1665    /// model and parameter handles, and must agree with a freshly built
1666    /// structure at the same geometry; updating back must restore the
1667    /// original energy. This pins the `positions` argument slot and its Bohr
1668    /// convention: swapped or unit-misread arguments land the atoms at another
1669    /// geometry and break the fresh-structure agreement.
1670    #[test]
1671    fn test_update_structure_molecule_matches_fresh_structure() {
1672        unsafe {
1673            let error = Dftd4Error(dftd4_new_error());
1674            let numbers = [18, 18];
1675            let pos7 = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
1676            let pos8 = [0.0, 0.0, 0.0, 8.0, 0.0, 0.0];
1677
1678            let mol = Dftd4Structure::try_new(
1679                error.0,
1680                2,
1681                numbers.as_ptr(),
1682                pos7.as_ptr(),
1683                null(),
1684                null(),
1685                null(),
1686            )
1687            .expect("argon dimer at 7 Bohr is a valid structure");
1688            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
1689            check_error(error.0, "new_d4_model");
1690            let param = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
1691            check_error(error.0, "load_rational_damping");
1692
1693            let e_before = dispersion_energy(error.0, mol.0, disp.0, param.0);
1694            assert!(
1695                e_before.is_finite() && e_before < 0.0,
1696                "argon dimer at 7.0 Bohr must be attractive and finite, got {e_before}"
1697            );
1698
1699            // Update the geometry in place; the same model and parameter
1700            // handles must stay valid (the optimisation-loop pattern).
1701            dftd4_update_structure(error.0, mol.0, pos8.as_ptr(), null());
1702            check_error(error.0, "update_structure");
1703            let e_after = dispersion_energy(error.0, mol.0, disp.0, param.0);
1704            assert!(
1705                e_after.is_finite() && e_after < 0.0,
1706                "argon dimer at 8.0 Bohr must be attractive and finite, got {e_after}"
1707            );
1708            assert!(
1709                (e_after - e_before).abs() > 1e-9,
1710                "the update did not change the energy ({e_before} -> {e_after}): \
1711                 positions were not read as 3 * natoms doubles in Bohr"
1712            );
1713
1714            // A fresh structure at the very same geometry is the reference.
1715            let fresh = Dftd4Structure::try_new(
1716                error.0,
1717                2,
1718                numbers.as_ptr(),
1719                pos8.as_ptr(),
1720                null(),
1721                null(),
1722                null(),
1723            )
1724            .expect("argon dimer at 8 Bohr is a valid structure");
1725            let fdisp = Dftd4Model(dftd4_new_d4_model(error.0, fresh.0));
1726            check_error(error.0, "new_d4_model (reference)");
1727            let e_fresh = dispersion_energy(error.0, fresh.0, fdisp.0, param.0);
1728            assert!(
1729                (e_after - e_fresh).abs() <= 1e-12,
1730                "energy after the in-place update ({e_after}) disagrees with \
1731                 the fresh structure at the same geometry ({e_fresh})"
1732            );
1733
1734            // Round trip: updating back to the original geometry must restore
1735            // the original energy.
1736            dftd4_update_structure(error.0, mol.0, pos7.as_ptr(), null());
1737            check_error(error.0, "update_structure (round trip)");
1738            let e_back = dispersion_energy(error.0, mol.0, disp.0, param.0);
1739            assert!(
1740                (e_back - e_before).abs() <= 1e-12,
1741                "updating back to the original geometry changed the energy \
1742                 ({e_before} -> {e_back})"
1743            );
1744        }
1745    }
1746
1747    /// Regression test for the optional `lattice` argument of
1748    /// [`dftd4_update_structure`]: isotropically expanding the periodic fcc
1749    /// argon cell (positions **and** lattice, quantities in Bohr) used by
1750    /// [`test_periodic_slab_flags`] through one in-place update must equal a
1751    /// fresh periodic structure at the scaled geometry. If the library
1752    /// ignored the `lattice` pointer, misread it from the `positions` slot, or
1753    /// vice versa, the updated structure carries a mixed geometry and this
1754    /// comparison fails.
1755    #[test]
1756    fn test_update_structure_periodic_lattice_matches_fresh_structure() {
1757        unsafe {
1758            let error = Dftd4Error(dftd4_new_error());
1759            let numbers = [18, 18];
1760            // fcc argon cell, a = 5.26 Å (quantities in Bohr)
1761            let a = 5.26 * 1.889_725_988_6;
1762            let pos = [0.0, 0.0, 0.0, a / 2.0, a / 2.0, a / 2.0];
1763            let lattice = [a, 0.0, 0.0, 0.0, a, 0.0, 0.0, 0.0, a];
1764            let periodic = [true, true, true];
1765
1766            let cell = Dftd4Structure::try_new(
1767                error.0,
1768                2,
1769                numbers.as_ptr(),
1770                pos.as_ptr(),
1771                null(),
1772                lattice.as_ptr(),
1773                periodic.as_ptr(),
1774            )
1775            .expect("periodic argon cell is a valid structure");
1776            let disp = Dftd4Model(dftd4_new_d4_model(error.0, cell.0));
1777            check_error(error.0, "new_d4_model");
1778            let param = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
1779            check_error(error.0, "load_rational_damping");
1780
1781            let e_before = dispersion_energy(error.0, cell.0, disp.0, param.0);
1782            assert!(
1783                e_before.is_finite() && e_before < 0.0,
1784                "the periodic argon cell must be attractive and finite, got {e_before}"
1785            );
1786
1787            // Isotropic expansion by 10 %: scale lattice vectors and
1788            // coordinates together.
1789            let s = 1.1f64;
1790            let pos_s = [0.0, 0.0, 0.0, s * a / 2.0, s * a / 2.0, s * a / 2.0];
1791            let lattice_s = [s * a, 0.0, 0.0, 0.0, s * a, 0.0, 0.0, 0.0, s * a];
1792            dftd4_update_structure(error.0, cell.0, pos_s.as_ptr(), lattice_s.as_ptr());
1793            check_error(error.0, "update_structure");
1794            let e_after = dispersion_energy(error.0, cell.0, disp.0, param.0);
1795            assert!(
1796                (e_after - e_before).abs() > 1e-9,
1797                "the update did not change the periodic cell energy \
1798                 ({e_before} -> {e_after}): positions or lattice were not applied"
1799            );
1800
1801            // Reference: fresh periodic structure at the scaled geometry.
1802            let fresh = Dftd4Structure::try_new(
1803                error.0,
1804                2,
1805                numbers.as_ptr(),
1806                pos_s.as_ptr(),
1807                null(),
1808                lattice_s.as_ptr(),
1809                periodic.as_ptr(),
1810            )
1811            .expect("scaled periodic argon cell is a valid structure");
1812            let fdisp = Dftd4Model(dftd4_new_d4_model(error.0, fresh.0));
1813            check_error(error.0, "new_d4_model (reference)");
1814            let e_fresh = dispersion_energy(error.0, fresh.0, fdisp.0, param.0);
1815            assert!(
1816                (e_after - e_fresh).abs() <= 1e-12,
1817                "energy after updating positions and lattice ({e_after}) \
1818                 disagrees with the fresh periodic structure at the same \
1819                 geometry ({e_fresh}); the optional lattice pointer may not \
1820                 be applied to the lattice"
1821            );
1822        }
1823    }
1824
1825    /// Regression test for the documented failure channel of
1826    /// [`dftd4_update_structure`] (upstream v4.2.0 `src/dftd4/api.f90`):
1827    /// updating onto a geometry with two atoms closer than 1e-9 Bohr trips
1828    /// the cold-fusion check (`"Too close interatomic distances found"`,
1829    /// status 1), and a null structure handle is reported as
1830    /// `"Molecular structure data is missing"` instead of being dereferenced.
1831    #[test]
1832    fn test_update_structure_reports_invalid_geometry() {
1833        // Test-local (not module-level) so the helper cannot collide with
1834        // similar helpers of other test groups.
1835        fn message(error: dftd4_error) -> String {
1836            unsafe {
1837                let mut buf = [0i8; 512];
1838                let size: c_int = buf.len() as c_int;
1839                dftd4_get_error(error, buf.as_mut_ptr().cast(), &size);
1840                std::ffi::CStr::from_ptr(buf.as_ptr().cast())
1841                    .to_string_lossy()
1842                    .into_owned()
1843            }
1844        }
1845
1846        unsafe {
1847            // Cold-fusion check on the *updated* geometry: the structure
1848            // itself is valid, only the update drives the atoms on top of
1849            // each other.
1850            let error = Dftd4Error(dftd4_new_error());
1851            let numbers = [18, 18];
1852            let positions = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
1853            let mol = Dftd4Structure::try_new(
1854                error.0,
1855                2,
1856                numbers.as_ptr(),
1857                positions.as_ptr(),
1858                null(),
1859                null(),
1860                null(),
1861            )
1862            .expect("argon dimer is a valid structure");
1863            assert_eq!(dftd4_check_error(error.0), 0, "setup must be clean");
1864
1865            let overlapping = [1.0, 2.0, 3.0, 1.0, 2.0, 3.0];
1866            dftd4_update_structure(error.0, mol.0, overlapping.as_ptr(), null());
1867            assert_eq!(
1868                dftd4_check_error(error.0),
1869                1,
1870                "updating both argon atoms onto the same position must set \
1871                 the handle (status 1 = message available)"
1872            );
1873            let msg = message(error.0);
1874            assert!(
1875                msg.contains("Too close interatomic distances"),
1876                "the message must report the cold-fusion check, got {msg:?}"
1877            );
1878
1879            // Null structure handle: guarded by upstream, reported through
1880            // the handle instead of being dereferenced.
1881            let error2 = Dftd4Error(dftd4_new_error());
1882            dftd4_update_structure(error2.0, null_mut(), positions.as_ptr(), null());
1883            assert_eq!(
1884                dftd4_check_error(error2.0),
1885                1,
1886                "a null structure handle must be reported, not dereferenced"
1887            );
1888            let msg = message(error2.0);
1889            assert!(
1890                msg.contains("Molecular structure data is missing"),
1891                "the message must report the missing structure, got {msg:?}"
1892            );
1893        }
1894    }
1895
1896    /// Bent water molecule (O at the origin, O–H distance 1.8 Bohr, HOH
1897    /// angle 104.5° in the xy plane) as `(numbers, positions)` with
1898    /// coordinates in Bohr. Unlike the argon dimer used by other tests it
1899    /// is large enough that the documented `[natoms*natoms]` output sizes
1900    /// (9 entries) differ from a `[2*natoms]`-style miscount (6), has
1901    /// nonzero coordination numbers on every atom (so all model and
1902    /// damping parameters are observable), carries three atoms (so the
1903    /// three-body ATM term is nonzero), and its non-collinear geometry
1904    /// fills the hessian with distinct off-diagonal couplings.
1905    unsafe fn water_geometry() -> ([c_int; 3], [f64; 9]) {
1906        let numbers = [8, 1, 1];
1907        let r = 1.8f64;
1908        let half = 0.5 * 104.5 * std::f64::consts::PI / 180.0;
1909        let positions = [
1910            0.0,
1911            0.0,
1912            0.0,
1913            r * half.sin(),
1914            r * half.cos(),
1915            0.0,
1916            -r * half.sin(),
1917            r * half.cos(),
1918            0.0,
1919        ];
1920        (numbers, positions)
1921    }
1922
1923    /// Regression test for the documented output-array contract of
1924    /// [`dftd4_get_properties`] (`cn` and `charges` `[natoms]`, `c6`
1925    /// `[natoms*natoms]`, `alpha` `[natoms]`; crate documentation). These
1926    /// sizes are the *caller's allocation contract*: an implementation
1927    /// writing fewer elements leaves stale buffer contents silently posing
1928    /// as physical properties, one writing more runs raw FFI writes past the
1929    /// caller's buffers — neither is detectable from Rust without this test.
1930    /// Buffers of exactly the documented sizes are prefilled with `NaN` and
1931    /// must come back fully written on the bent water molecule; the written
1932    /// values must also satisfy the physical invariants (positive `cn`,
1933    /// `alpha` and `C6`, a symmetric `C6` matrix, and partial charges that
1934    /// are negative on the oxygen, positive on the hydrogens, and sum to the
1935    /// neutral system charge). Finally, the documented per-output
1936    /// nullability must hold: requesting only `cn` and `c6` reproduces the
1937    /// full call's values through an otherwise clean handle.
1938    #[test]
1939    fn test_get_properties_fills_documented_array_sizes() {
1940        unsafe {
1941            let error = Dftd4Error(dftd4_new_error());
1942            let (numbers, positions) = water_geometry();
1943            let mol = Dftd4Structure::try_new(
1944                error.0,
1945                3,
1946                numbers.as_ptr(),
1947                positions.as_ptr(),
1948                null(),
1949                null(),
1950                null(),
1951            )
1952            .expect("bent water is a valid structure");
1953            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
1954            check_error(error.0, "new_d4_model");
1955
1956            let mut cn = [f64::NAN; 3];
1957            let mut charges = [f64::NAN; 3];
1958            let mut c6 = [f64::NAN; 9];
1959            let mut alpha = [f64::NAN; 3];
1960            dftd4_get_properties(
1961                error.0,
1962                mol.0,
1963                disp.0,
1964                cn.as_mut_ptr(),
1965                charges.as_mut_ptr(),
1966                c6.as_mut_ptr(),
1967                alpha.as_mut_ptr(),
1968            );
1969            check_error(error.0, "get_properties");
1970
1971            // Every documented entry must have been written: an untouched
1972            // NaN sentinel means the library wrote less than [natoms] /
1973            // [natoms*natoms] elements.
1974            assert!(
1975                cn.iter().all(|x| x.is_finite()),
1976                "cn must be written over its full [natoms] extent, got {cn:?}"
1977            );
1978            assert!(
1979                charges.iter().all(|x| x.is_finite()),
1980                "charges must be written over their full [natoms] extent, got {charges:?}"
1981            );
1982            assert!(
1983                c6.iter().all(|x| x.is_finite()),
1984                "c6 must be written over its full [natoms*natoms] extent, got {c6:?}"
1985            );
1986            assert!(
1987                alpha.iter().all(|x| x.is_finite()),
1988                "alpha must be written over its full [natoms] extent, got {alpha:?}"
1989            );
1990
1991            // Physical invariants of the written values.
1992            assert!(
1993                cn.iter().all(|&c| c > 0.0),
1994                "coordinated water atoms must have positive coordination numbers, got {cn:?}"
1995            );
1996            assert!(
1997                alpha.iter().all(|&a| a > 0.0),
1998                "polarizabilities must be positive, got {alpha:?}"
1999            );
2000            for i in 0..3 {
2001                for j in 0..3 {
2002                    assert!(
2003                        c6[i * 3 + j] > 0.0,
2004                        "the C6 matrix must be positive, got {c6:?}"
2005                    );
2006                    assert!(
2007                        (c6[i * 3 + j] - c6[j * 3 + i]).abs() <= 1e-12,
2008                        "the C6 matrix must be symmetric, got {c6:?}"
2009                    );
2010                }
2011            }
2012            assert!(
2013                charges[0] < 0.0 && charges[1] > 0.0 && charges[2] > 0.0,
2014                "electronegative oxygen must carry a negative, hydrogens \
2015                 positive partial charges, got {charges:?}"
2016            );
2017            assert!(
2018                charges.iter().sum::<f64>().abs() <= 1e-12,
2019                "partial charges must sum to the neutral system charge, got {charges:?}"
2020            );
2021
2022            // Documented nullability: a subset request must reproduce the
2023            // full call's values (bitwise results from the same deterministic
2024            // evaluation, compared with a numerical margin for thread-count
2025            // dependent summation orders).
2026            let mut cn_only = [f64::NAN; 3];
2027            let mut c6_only = [f64::NAN; 9];
2028            dftd4_get_properties(
2029                error.0,
2030                mol.0,
2031                disp.0,
2032                cn_only.as_mut_ptr(),
2033                null_mut(),
2034                c6_only.as_mut_ptr(),
2035                null_mut(),
2036            );
2037            check_error(error.0, "get_properties (cn and c6 only)");
2038            for i in 0..3 {
2039                assert!(
2040                    (cn_only[i] - cn[i]).abs() <= 1e-12,
2041                    "cn differs between the full and the subset call: {cn_only:?} vs {cn:?}"
2042                );
2043            }
2044            for i in 0..9 {
2045                assert!(
2046                    (c6_only[i] - c6[i]).abs() <= 1e-12,
2047                    "c6 differs between the full and the subset call: {c6_only:?} vs {c6:?}"
2048                );
2049            }
2050        }
2051    }
2052
2053    /// Regression test for the output contract of
2054    /// [`dftd4_get_pairwise_dispersion`] (`pair_energy2` and `pair_energy3`
2055    /// are `[natoms*natoms]` pair decompositions of the energy, upstream
2056    /// v4.2.0 `include/dftd4.h`): on the bent water molecule both exactly
2057    /// 9-entry buffers must be written in full, their total over both arrays
2058    /// must reproduce the energy of [`dftd4_get_dispersion`] (measured to
2059    /// agree to 3e-20), the diagonal must vanish (no self-interaction), and
2060    /// the matrices must be symmetric (Newton's third law). A silent change
2061    /// of the decomposition size or a broken pair summation would
2062    /// misassemble the caller's energy breakdown without ever touching the
2063    /// error handle.
2064    #[test]
2065    fn test_get_pairwise_dispersion_reproduces_total_energy() {
2066        unsafe {
2067            let error = Dftd4Error(dftd4_new_error());
2068            let (numbers, positions) = water_geometry();
2069            let mol = Dftd4Structure::try_new(
2070                error.0,
2071                3,
2072                numbers.as_ptr(),
2073                positions.as_ptr(),
2074                null(),
2075                null(),
2076                null(),
2077            )
2078            .expect("bent water is a valid structure");
2079            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
2080            check_error(error.0, "new_d4_model");
2081            let param = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
2082            check_error(error.0, "load_rational_damping");
2083
2084            let mut pair2 = [f64::NAN; 9];
2085            let mut pair3 = [f64::NAN; 9];
2086            dftd4_get_pairwise_dispersion(
2087                error.0,
2088                mol.0,
2089                disp.0,
2090                param.0,
2091                pair2.as_mut_ptr(),
2092                pair3.as_mut_ptr(),
2093            );
2094            check_error(error.0, "get_pairwise_dispersion");
2095            assert!(
2096                pair2.iter().all(|x| x.is_finite()) && pair3.iter().all(|x| x.is_finite()),
2097                "both [natoms*natoms] pair arrays must be written in full: {pair2:?} / {pair3:?}"
2098            );
2099
2100            let energy = dispersion_energy(error.0, mol.0, disp.0, param.0);
2101            assert!(
2102                energy.is_finite() && energy < 0.0,
2103                "water must have a finite, attractive dispersion energy, got {energy}"
2104            );
2105            let total: f64 = pair2.iter().sum::<f64>() + pair3.iter().sum::<f64>();
2106            assert!(
2107                (total - energy).abs() <= 1e-12,
2108                "the pairwise decomposition over both [natoms*natoms] arrays \
2109                 must reproduce the total energy {energy}, got {total}"
2110            );
2111
2112            // The symmetry assertions are only meaningful on nonzero pair
2113            // energies; at least the O–H pair must carry weight.
2114            assert!(
2115                pair2[1].abs() > 1e-9,
2116                "the O–H pair energy must be nonzero, got {pair2:?}"
2117            );
2118            for i in 0..3 {
2119                assert!(
2120                    pair2[i * 3 + i].abs() <= 1e-15 && pair3[i * 3 + i].abs() <= 1e-15,
2121                    "the pair decomposition must have no self-interaction, \
2122                     got {pair2:?} / {pair3:?}"
2123                );
2124            }
2125            for (i, j) in [(0, 1), (0, 2), (1, 2)] {
2126                assert!(
2127                    (pair2[i * 3 + j] - pair2[j * 3 + i]).abs() <= 1e-12,
2128                    "the two-body pair matrix must be symmetric, got {pair2:?}"
2129                );
2130                assert!(
2131                    (pair3[i * 3 + j] - pair3[j * 3 + i]).abs() <= 1e-12,
2132                    "the three-body pair matrix must be symmetric, got {pair3:?}"
2133                );
2134            }
2135        }
2136    }
2137
2138    /// Regression test for [`dftd4_get_numerical_hessian`], whose documented
2139    /// output is a flat `[(3*natoms)*(3*natoms)]` buffer in Fortran order,
2140    /// entry `(ia,ic),(ja,jc)` at `(3*ia + ic) + 3*natoms*(3*ja + jc)`
2141    /// (upstream v4.2.0 `api.f90` reshapes it as `hessian(3,nat,3,nat)`).
2142    /// On the bent water molecule the test pins:
2143    /// - the full `[3n x 3n]` extent is written (NaN prefill, 81 entries),
2144    /// - symmetry and vanishing row sums (translational invariance) at
2145    ///   1e-10, well above the construction noise (~1e-13), and
2146    /// - every entry against an independent central finite difference of the
2147    ///   analytic gradient (step 1e-3 Bohr), within 1e-4 of the largest
2148    ///   hessian element.
2149    ///
2150    /// The finite-difference cross-check is what pins the *flat layout*: an
2151    /// atom/cartesian index mix-up would move the ~7e-6 Eh/Bohr² O–H
2152    /// couplings into slots holding ~1e-16 values and fail with the full
2153    /// coupling as the deviation.
2154    #[test]
2155    fn test_get_numerical_hessian_matches_finite_difference_gradient() {
2156        const N: usize = 9; // 3 * natoms for water
2157        unsafe {
2158            let error = Dftd4Error(dftd4_new_error());
2159            let (numbers, positions) = water_geometry();
2160            let mol = Dftd4Structure::try_new(
2161                error.0,
2162                3,
2163                numbers.as_ptr(),
2164                positions.as_ptr(),
2165                null(),
2166                null(),
2167                null(),
2168            )
2169            .expect("bent water is a valid structure");
2170            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
2171            check_error(error.0, "new_d4_model");
2172            let param = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
2173            check_error(error.0, "load_rational_damping");
2174
2175            let mut hess = [f64::NAN; N * N];
2176            dftd4_get_numerical_hessian(error.0, mol.0, disp.0, param.0, hess.as_mut_ptr());
2177            check_error(error.0, "get_numerical_hessian");
2178            assert!(
2179                hess.iter().all(|x| x.is_finite()),
2180                "every entry of the documented 3n x 3n hessian must be written \
2181                 and finite, got {hess:?}"
2182            );
2183
2184            // Fortran-order accessor: d2E / dR[ia][ic] dR[ja][jc] at
2185            // (3*ia + ic) + N * (3*ja + jc).
2186            let h = |row: usize, col: usize| -> f64 { hess[row + N * col] };
2187
2188            let max_h = hess.iter().fold(0.0f64, |m, x| m.max(x.abs()));
2189            assert!(
2190                max_h > 1e-6,
2191                "the water hessian must carry real force constants, max |entry| is {max_h}"
2192            );
2193
2194            let mut asymmetry = 0.0f64;
2195            let mut row_deviation = 0.0f64;
2196            for row in 0..N {
2197                let mut rowsum = 0.0f64;
2198                for col in 0..N {
2199                    asymmetry = asymmetry.max((h(row, col) - h(col, row)).abs());
2200                    rowsum += h(row, col);
2201                }
2202                row_deviation = row_deviation.max(rowsum.abs());
2203            }
2204            assert!(
2205                asymmetry <= 1e-10,
2206                "the hessian must be symmetric up to its numerical construction \
2207                 (measured noise ~1e-13), deviation is {asymmetry}"
2208            );
2209            assert!(
2210                row_deviation <= 1e-10,
2211                "hessian rows must sum to zero (translational invariance), \
2212                 largest deviation is {row_deviation}"
2213            );
2214
2215            // Independent cross-check: central differences of the analytic
2216            // gradient along every flattened coordinate (3*natoms = 9).
2217            let step = 1e-3f64;
2218            let mut max_diff = 0.0f64;
2219            for col in 0..N {
2220                let mut plus = positions;
2221                plus[col] += step;
2222                let mut minus = positions;
2223                minus[col] -= step;
2224                let pcell = Dftd4Structure::try_new(
2225                    error.0,
2226                    3,
2227                    numbers.as_ptr(),
2228                    plus.as_ptr(),
2229                    null(),
2230                    null(),
2231                    null(),
2232                )
2233                .expect("displaced water (+) is a valid structure");
2234                let mcell = Dftd4Structure::try_new(
2235                    error.0,
2236                    3,
2237                    numbers.as_ptr(),
2238                    minus.as_ptr(),
2239                    null(),
2240                    null(),
2241                    null(),
2242                )
2243                .expect("displaced water (-) is a valid structure");
2244                let pdisp = Dftd4Model(dftd4_new_d4_model(error.0, pcell.0));
2245                check_error(error.0, "new_d4_model (displaced +)");
2246                let mdisp = Dftd4Model(dftd4_new_d4_model(error.0, mcell.0));
2247                check_error(error.0, "new_d4_model (displaced -)");
2248
2249                let mut g_plus = [0.0f64; N];
2250                let mut g_minus = [0.0f64; N];
2251                let mut e = f64::NAN;
2252                dftd4_get_dispersion(
2253                    error.0,
2254                    pcell.0,
2255                    pdisp.0,
2256                    param.0,
2257                    &mut e,
2258                    g_plus.as_mut_ptr(),
2259                    null_mut(),
2260                );
2261                check_error(error.0, "get_dispersion (displaced +)");
2262                dftd4_get_dispersion(
2263                    error.0,
2264                    mcell.0,
2265                    mdisp.0,
2266                    param.0,
2267                    &mut e,
2268                    g_minus.as_mut_ptr(),
2269                    null_mut(),
2270                );
2271                check_error(error.0, "get_dispersion (displaced -)");
2272
2273                for row in 0..N {
2274                    let fd = (g_plus[row] - g_minus[row]) / (2.0 * step);
2275                    max_diff = max_diff.max((h(row, col) - fd).abs());
2276                }
2277            }
2278            // Both are central differences of the same gradient (upstream
2279            // uses step 1e-4 Bohr); the deviation between the two estimates
2280            // is a truncation/noise difference far below the 1e-4 * scale
2281            // bound here (measured ~9e-11 against a scale of ~5e-5).
2282            assert!(
2283                max_diff <= 1e-10_f64.max(1e-4 * max_h),
2284                "the hessian deviates from a finite-difference of the gradient \
2285                 by {max_diff}, against a hessian scale of {max_h}: the flat \
2286                 layout or the derivatives are wrong"
2287            );
2288        }
2289    }
2290
2291    /// Regression test for the four model constructors
2292    /// [`dftd4_new_d4s_model`], [`dftd4_custom_d4_model`] and
2293    /// [`dftd4_custom_d4s_model`] (up to now, only [`dftd4_new_d4_model`]
2294    /// was ever called by a test), run against [`dftd4_new_d4_model`] as
2295    /// reference:
2296    /// - The D4S model must be a distinct, usable model: on the hydrogen
2297    ///   dimer it differs measurably from D4 (D4S replaces the scalar
2298    ///   weighting factor `wf = 6` by the per-pair table of
2299    ///   `data/wfpair.f90`, `wf(H,H) = 3.6735`; measured 3.6e-6 Eh apart —
2300    ///   an aliased constructor would go unnoticed on the argon dimer,
2301    ///   whose pair value is 6.0 and yields bitwise equal energies).
2302    /// - The custom constructors must reproduce the default models exactly
2303    ///   when handed the pinned default values (v4.2.0 `model/d4.f90`:
2304    ///   `ga = 3`, `gc = 2`, `wf = 6`; `model/d4s.f90`: `ga = 3`, `gc = 2`)
2305    ///   — the API wrappers call the very same Fortran builders.
2306    /// - The custom argument slots must not be interchangeable: swapping
2307    ///   `ga` and `wf` on hydrogen, and perturbing `ga` or `gc` singly on
2308    ///   water (the H2 dimer has vanishing coordination, so `gc` is only
2309    ///   observable on a coordinated system), must change the energy.
2310    #[test]
2311    fn test_d4s_and_custom_model_constructors() {
2312        unsafe {
2313            let error = Dftd4Error(dftd4_new_error());
2314            let param = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
2315            check_error(error.0, "load_rational_damping");
2316
2317            // Hydrogen dimer at 1.4 Bohr.
2318            let numbers = [1, 1];
2319            let positions = [0.0, 0.0, 0.0, 1.4, 0.0, 0.0];
2320            let mol = Dftd4Structure::try_new(
2321                error.0,
2322                2,
2323                numbers.as_ptr(),
2324                positions.as_ptr(),
2325                null(),
2326                null(),
2327                null(),
2328            )
2329            .expect("hydrogen dimer is a valid structure");
2330            let d4 = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
2331            check_error(error.0, "new_d4_model");
2332            let d4s = Dftd4Model(dftd4_new_d4s_model(error.0, mol.0));
2333            check_error(error.0, "new_d4s_model");
2334            assert!(
2335                !d4s.0.is_null(),
2336                "new_d4s_model must hand out a model for hydrogen"
2337            );
2338            let e_d4 = dispersion_energy(error.0, mol.0, d4.0, param.0);
2339            let e_d4s = dispersion_energy(error.0, mol.0, d4s.0, param.0);
2340            assert!(
2341                e_d4.is_finite() && e_d4 < 0.0,
2342                "the hydrogen dimer must be attractive under D4, got {e_d4}"
2343            );
2344            assert!(
2345                e_d4s.is_finite() && e_d4s < 0.0,
2346                "the hydrogen dimer must be attractive under D4S, got {e_d4s}"
2347            );
2348            assert!(
2349                (e_d4 - e_d4s).abs() > 1e-8,
2350                "D4 and D4S energies coincide ({e_d4} vs {e_d4s}) — with the \
2351                 pair weighting factor wf(H,H) = 3.6735 != 6 they must differ, \
2352                 so one of the constructors is not building its own model"
2353            );
2354
2355            // Custom constructors with the pinned default values reproduce
2356            // the default models exactly.
2357            let cd4 = Dftd4Model(dftd4_custom_d4_model(error.0, mol.0, 3.0, 2.0, 6.0));
2358            check_error(error.0, "custom_d4_model (defaults)");
2359            assert!(
2360                !cd4.0.is_null(),
2361                "custom_d4_model must hand out a model for hydrogen"
2362            );
2363            assert!(
2364                (dispersion_energy(error.0, mol.0, cd4.0, param.0) - e_d4).abs() <= 1e-12,
2365                "custom_d4_model(3, 2, 6) must equal the default D4 model ({e_d4})"
2366            );
2367            let cd4s = Dftd4Model(dftd4_custom_d4s_model(error.0, mol.0, 3.0, 2.0));
2368            check_error(error.0, "custom_d4s_model (defaults)");
2369            assert!(
2370                !cd4s.0.is_null(),
2371                "custom_d4s_model must hand out a model for hydrogen"
2372            );
2373            assert!(
2374                (dispersion_energy(error.0, mol.0, cd4s.0, param.0) - e_d4s).abs() <= 1e-12,
2375                "custom_d4s_model(3, 2) must equal the default D4S model ({e_d4s})"
2376            );
2377
2378            // Swapping the ga and wf argument slots must change the energy:
2379            // the arguments are not interchangeable and the default-value
2380            // equality above could not hold for a permuted signature.
2381            let swapped = Dftd4Model(dftd4_custom_d4_model(error.0, mol.0, 6.0, 2.0, 3.0));
2382            check_error(error.0, "custom_d4_model (ga/wf swapped)");
2383            assert!(
2384                (dispersion_energy(error.0, mol.0, swapped.0, param.0) - e_d4).abs() > 1e-8,
2385                "swapping ga and wf ({e_d4} unchanged) means both arguments \
2386                 feed the same Fortran dummy"
2387            );
2388
2389            // ga and gc are observable individually on a coordinated
2390            // system (on the bare H2 dimer gc does not enter the energy).
2391            let (wnumbers, wpositions) = water_geometry();
2392            let water = Dftd4Structure::try_new(
2393                error.0,
2394                3,
2395                wnumbers.as_ptr(),
2396                wpositions.as_ptr(),
2397                null(),
2398                null(),
2399                null(),
2400            )
2401            .expect("bent water is a valid structure");
2402            let wd4 = Dftd4Model(dftd4_new_d4_model(error.0, water.0));
2403            check_error(error.0, "new_d4_model (water)");
2404            let e_water = dispersion_energy(error.0, water.0, wd4.0, param.0);
2405            for (ga, gc) in [(2.0, 2.0), (3.0, 2.5)] {
2406                let probe = Dftd4Model(dftd4_custom_d4_model(error.0, water.0, ga, gc, 6.0));
2407                check_error(error.0, "custom_d4_model (perturbed)");
2408                assert!(
2409                    (dispersion_energy(error.0, water.0, probe.0, param.0) - e_water).abs() > 1e-8,
2410                    "ga = {ga}, gc = {gc} must change the water energy {e_water}: \
2411                     each argument must feed its own Fortran dummy"
2412                );
2413            }
2414        }
2415    }
2416
2417    /// Regression test for [`dftd4_new_rational_damping`] — previously never
2418    /// called by any test — against the `load_rational_damping` table it
2419    /// must be able to reproduce. In the pinned v4.2.0 (`param.f90`,
2420    /// `api.f90`) the "pbe" entry is `s6 = 1.0`, `s8 = 0.95948085`,
2421    /// `a1 = 0.38574991`, `a2 = 4.80688534` with defaults `s9 = 0`,
2422    /// `alp = 16`, and the `mbd` flag of the loader is nothing but `s9`
2423    /// (`0.0` or `1.0`). The test requires:
2424    /// - the hand-built PBE set reproduces the loaded parameters to 1e-12
2425    ///   on the argon dimer (energy measured bitwise equal),
2426    /// - swapping `s6`/`s8` or `a1`/`a2`, or doubling `s6`, changes the
2427    ///   energy — pinning all six argument slots and proving the values
2428    ///   actually feed the calculation,
2429    /// - and on bent water (three atoms, so the ATM term is live) `s9 = 1`
2430    ///   reproduces the `mbd = 1` load exactly while halving `alp` changes
2431    ///   the energy — the two slots that are invisible on any dimer.
2432    #[test]
2433    fn test_new_rational_damping_reproduces_and_pins_parameter_slots() {
2434        unsafe {
2435            let error = Dftd4Error(dftd4_new_error());
2436            let numbers = [18, 18];
2437            let positions = [0.0, 0.0, 0.0, 7.0, 0.0, 0.0];
2438            let mol = Dftd4Structure::try_new(
2439                error.0,
2440                2,
2441                numbers.as_ptr(),
2442                positions.as_ptr(),
2443                null(),
2444                null(),
2445                null(),
2446            )
2447            .expect("argon dimer is a valid structure");
2448            let disp = Dftd4Model(dftd4_new_d4_model(error.0, mol.0));
2449            check_error(error.0, "new_d4_model");
2450            let loaded = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 0));
2451            check_error(error.0, "load_rational_damping");
2452            let e_loaded = dispersion_energy(error.0, mol.0, disp.0, loaded.0);
2453
2454            let pbe = |s6: f64, s8: f64, s9: f64, a1: f64, a2: f64, alp: f64| {
2455                let param =
2456                    Dftd4Param(dftd4_new_rational_damping(error.0, s6, s8, s9, a1, a2, alp));
2457                check_error(error.0, "new_rational_damping");
2458                assert!(
2459                    !param.0.is_null(),
2460                    "new_rational_damping must hand out a parameter set"
2461                );
2462                param
2463            };
2464
2465            // The table values, assembled by hand, must reproduce the loader.
2466            let exact = pbe(1.0, 0.95948085, 0.0, 0.38574991, 4.80688534, 16.0);
2467            assert!(
2468                (dispersion_energy(error.0, mol.0, disp.0, exact.0) - e_loaded).abs() <= 1e-12,
2469                "hand-built PBE parameters must reproduce the loaded table \
2470                 entry energy {e_loaded}"
2471            );
2472
2473            // Every perturbed or permuted slot must change the energy;
2474            // otherwise the corresponding argument is silently ignored or
2475            // two slots share one Fortran dummy.
2476            let perturbations = [
2477                (
2478                    "s6/s8 swap",
2479                    pbe(0.95948085, 1.0, 0.0, 0.38574991, 4.80688534, 16.0),
2480                ),
2481                (
2482                    "a1/a2 swap",
2483                    pbe(1.0, 0.95948085, 0.0, 4.80688534, 0.38574991, 16.0),
2484                ),
2485                (
2486                    "s6 doubled",
2487                    pbe(2.0, 0.95948085, 0.0, 0.38574991, 4.80688534, 16.0),
2488                ),
2489            ];
2490            for (name, probe) in perturbations {
2491                let e = dispersion_energy(error.0, mol.0, disp.0, probe.0);
2492                assert!(
2493                    (e - e_loaded).abs() > 1e-9,
2494                    "{name} left the energy at {e}: the argument slots are not \
2495                     distinct or the values do not feed the calculation"
2496                );
2497            }
2498
2499            // s9 and alp act through the three-body (ATM) term, which is
2500            // zero on every dimer — exercise them on bent water instead.
2501            let (wnumbers, wpositions) = water_geometry();
2502            let water = Dftd4Structure::try_new(
2503                error.0,
2504                3,
2505                wnumbers.as_ptr(),
2506                wpositions.as_ptr(),
2507                null(),
2508                null(),
2509                null(),
2510            )
2511            .expect("bent water is a valid structure");
2512            let wd4 = Dftd4Model(dftd4_new_d4_model(error.0, water.0));
2513            check_error(error.0, "new_d4_model (water)");
2514            let atm = Dftd4Param(dftd4_load_rational_damping(error.0, c"pbe".as_ptr(), 1));
2515            check_error(error.0, "load_rational_damping (mbd)");
2516            let e_atm = dispersion_energy(error.0, water.0, wd4.0, atm.0);
2517            let e_nosatm = dispersion_energy(error.0, water.0, wd4.0, loaded.0);
2518            assert!(
2519                (e_atm - e_nosatm).abs() > 1e-13,
2520                "the mbd flag must enable the three-body term on water \
2521                 (both loads give {e_atm}) — precondition for pinning s9"
2522            );
2523            let with_s9 = pbe(1.0, 0.95948085, 1.0, 0.38574991, 4.80688534, 16.0);
2524            assert!(
2525                (dispersion_energy(error.0, water.0, wd4.0, with_s9.0) - e_atm).abs() <= 1e-12,
2526                "s9 = 1 must reproduce the mbd = 1 table load {e_atm}: \
2527                 the s9 slot is misplaced"
2528            );
2529            let soft_alp = pbe(1.0, 0.95948085, 1.0, 0.38574991, 4.80688534, 8.0);
2530            assert!(
2531                (dispersion_energy(error.0, water.0, wd4.0, soft_alp.0) - e_atm).abs() > 1e-9,
2532                "halving alp left the three-body energy at its default: \
2533                 the alp slot is silently ignored"
2534            );
2535        }
2536    }
2537}