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