dftd4-sys 0.1.0

Raw FFI bindings to the DFT-D4 dispersion correction library (libdftd4 C API)
//! FFI bindings to the DFT-D4 dispersion correction library
//!
//! This crate provides low-level Rust bindings to the C API of the DFT-D4 library.
//! DFT-D4 is a generally applicable atomic-charge dependent London dispersion correction.
//!
//! For more information, see: <https://github.com/dftd4/dftd4>

#![allow(non_camel_case_types)]
#![allow(non_snake_case)]

use std::os::raw::{c_char, c_double, c_int};

/// Opaque error handle
#[repr(C)]
pub struct _dftd4_error {
    _private: [u8; 0],
}
pub type dftd4_error = *mut _dftd4_error;

/// Opaque molecular structure data
#[repr(C)]
pub struct _dftd4_structure {
    _private: [u8; 0],
}
pub type dftd4_structure = *mut _dftd4_structure;

/// Opaque dispersion model
#[repr(C)]
pub struct _dftd4_model {
    _private: [u8; 0],
}
pub type dftd4_model = *mut _dftd4_model;

/// Opaque damping parameters
#[repr(C)]
pub struct _dftd4_param {
    _private: [u8; 0],
}
pub type dftd4_param = *mut _dftd4_param;

/// Safe wrapper for dftd4_error handle that automatically frees on drop
pub struct Dftd4Error(pub dftd4_error);

impl Drop for Dftd4Error {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { dftd4_delete_error(&mut self.0) };
        }
    }
}

/// Safe wrapper for dftd4_structure handle that automatically frees on drop
pub struct Dftd4Structure(pub dftd4_structure);

impl Drop for Dftd4Structure {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { dftd4_delete_structure(&mut self.0) };
        }
    }
}

/// Safe wrapper for dftd4_model handle that automatically frees on drop
pub struct Dftd4Model(pub dftd4_model);

impl Drop for Dftd4Model {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { dftd4_delete_model(&mut self.0) };
        }
    }
}

/// Safe wrapper for dftd4_param handle that automatically frees on drop
pub struct Dftd4Param(pub dftd4_param);

impl Drop for Dftd4Param {
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe { dftd4_delete_param(&mut self.0) };
        }
    }
}

#[link(name = "dftd4")]
unsafe extern "C" {
    /// Obtain library version as major * 10000 + minor * 100 + patch
    pub fn dftd4_get_version() -> c_int;

    // Error handle functions
    /// Create new error handle object
    pub fn dftd4_new_error() -> dftd4_error;

    /// Check error handle status
    pub fn dftd4_check_error(error: dftd4_error) -> c_int;

    /// Get error message from error handle.
    ///
    /// `buffersize` is the *capacity* of `buffer`, in elements. It is declared
    /// `*const c_int` deliberately: upstream dftd4 (checked at the pinned
    /// v4.2.0 tag) declares `void dftd4_get_error(dftd4_error, char* buffer,
    /// const int* buffersize)` and the Fortran implementation takes
    /// `integer(c_int), intent(in) :: buffersize` — it is **input-only**, no
    /// length is written back. (F0452: the review's "in/out `*const` aliasing
    /// UB" premise was a false positive; do NOT "fix" this to `*mut c_int`,
    /// which would *introduce* a signature mismatch against the real ABI.) The
    /// C API reports no written length at all, so callers detect truncation from
    /// the NUL terminator rather than a returned size.
    pub fn dftd4_get_error(error: dftd4_error, buffer: *mut c_char, buffersize: *const c_int);

    /// Delete error handle object
    pub fn dftd4_delete_error(error: *mut dftd4_error);

    // Molecular structure functions
    /// Create new molecular structure data (quantities in Bohr)
    ///
    /// # Parameters
    /// - `error`: Error handle
    /// - `natoms`: Number of atoms
    /// - `numbers`: Atomic numbers `[natoms]`
    /// - `positions`: Cartesian coordinates in Bohr `[natoms][3]`
    /// - `charge`: Total charge (nullable)
    /// - `lattice`: Lattice vectors in Bohr `[3][3]` (nullable for molecules)
    /// - `periodic`: Periodicity flags `[3]` (nullable)
    pub fn dftd4_new_structure(
        error: dftd4_error,
        natoms: c_int,
        numbers: *const c_int,
        positions: *const c_double,
        charge: *const c_double,
        lattice: *const c_double,
        periodic: *const c_int,
    ) -> dftd4_structure;

    /// Delete molecular structure data
    pub fn dftd4_delete_structure(mol: *mut dftd4_structure);

    /// Update coordinates and lattice parameters (quantities in Bohr)
    pub fn dftd4_update_structure(
        error: dftd4_error,
        mol: dftd4_structure,
        positions: *const c_double,
        lattice: *const c_double,
    );

    // Dispersion model functions
    /// Create new D4 dispersion model
    pub fn dftd4_new_d4_model(error: dftd4_error, mol: dftd4_structure) -> dftd4_model;

    /// Create new D4S dispersion model
    pub fn dftd4_new_d4s_model(error: dftd4_error, mol: dftd4_structure) -> dftd4_model;

    /// Create custom D4 dispersion model with parameters
    pub fn dftd4_custom_d4_model(
        error: dftd4_error,
        mol: dftd4_structure,
        ga: c_double,
        gc: c_double,
        wf: c_double,
    ) -> dftd4_model;

    /// Create custom D4S dispersion model with parameters
    pub fn dftd4_custom_d4s_model(
        error: dftd4_error,
        mol: dftd4_structure,
        ga: c_double,
        gc: c_double,
    ) -> dftd4_model;

    /// Delete dispersion model
    pub fn dftd4_delete_model(disp: *mut dftd4_model);

    // Damping parameter functions
    /// Create new rational damping parameters
    ///
    /// # Parameters
    /// - `s6`: Scaling factor for C6 term
    /// - `s8`: Scaling factor for C8 term
    /// - `s9`: Scaling factor for three-body term
    /// - `a1`: Damping parameter
    /// - `a2`: Damping parameter
    /// - `alp`: Damping parameter
    pub fn dftd4_new_rational_damping(
        error: dftd4_error,
        s6: c_double,
        s8: c_double,
        s9: c_double,
        a1: c_double,
        a2: c_double,
        alp: c_double,
    ) -> dftd4_param;

    /// Load rational damping parameters from internal storage
    ///
    /// # Parameters
    /// - `method`: Name of the method (e.g., "pbe", "scan")
    /// - `mbd`: Whether to use many-body dispersion
    pub fn dftd4_load_rational_damping(
        error: dftd4_error,
        method: *const c_char,
        mbd: c_int,
    ) -> dftd4_param;

    /// Delete damping parameters
    pub fn dftd4_delete_param(param: *mut dftd4_param);

    // Calculation functions
    /// Evaluate properties related to the dispersion model
    ///
    /// # Parameters
    /// - `cn`: Coordination numbers `[natoms]` (nullable)
    /// - `charges`: Partial charges `[natoms]` (nullable)
    /// - `c6`: C6 coefficients `[natoms*natoms]` (nullable)
    /// - `alpha`: Polarizabilities `[natoms]` (nullable)
    pub fn dftd4_get_properties(
        error: dftd4_error,
        mol: dftd4_structure,
        disp: dftd4_model,
        cn: *mut c_double,
        charges: *mut c_double,
        c6: *mut c_double,
        alpha: *mut c_double,
    );

    /// Evaluate the dispersion energy and its derivatives
    ///
    /// # Parameters
    /// - `energy`: Dispersion energy in Hartree
    /// - `gradient`: Energy gradient `[natoms][3]` in Hartree/Bohr (nullable)
    /// - `sigma`: Virial tensor `[3][3]` in Hartree (nullable)
    pub fn dftd4_get_dispersion(
        error: dftd4_error,
        mol: dftd4_structure,
        disp: dftd4_model,
        param: dftd4_param,
        energy: *mut c_double,
        gradient: *mut c_double,
        sigma: *mut c_double,
    );

    /// Evaluate the dispersion hessian numerically
    pub fn dftd4_get_numerical_hessian(
        error: dftd4_error,
        mol: dftd4_structure,
        disp: dftd4_model,
        param: dftd4_param,
        hess: *mut c_double,
    );

    /// Evaluate the pairwise representation of the dispersion energy
    pub fn dftd4_get_pairwise_dispersion(
        error: dftd4_error,
        mol: dftd4_structure,
        disp: dftd4_model,
        param: dftd4_param,
        pair_energy2: *mut c_double,
        pair_energy3: *mut c_double,
    );
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_version() {
        unsafe {
            let version = dftd4_get_version();
            assert!(version > 0, "Version should be positive");
            println!("DFT-D4 version: {version}");
        }
    }

    #[test]
    fn test_error_handle() {
        unsafe {
            let error = dftd4_new_error();
            assert!(!error.is_null(), "Error handle should not be null");

            let status = dftd4_check_error(error);
            assert_eq!(status, 0, "New error handle should have no error");

            dftd4_delete_error(&mut error.cast());
        }
    }
}