MACEInference¶
MACEInference ¶
High-level interface for MACE machine learning force field inference.
This class provides a unified API for common inference tasks including: - Single-point energy calculations - Structure optimization - Molecular dynamics (NVT/NPT) - Phonon calculations - Mechanical properties - Adsorption energies
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str
|
MACE model name ("small", "medium", "large") or path to custom model |
'medium'
|
device
|
Literal['auto', 'cpu', 'cuda']
|
Compute device ("auto", "cpu", or "cuda") |
'auto'
|
enable_d3
|
bool
|
Enable DFT-D3 dispersion correction |
False
|
d3_damping
|
str
|
D3 damping function ("bj", "zero", "zerom", "bjm") |
'bj'
|
d3_xc
|
str
|
D3 exchange-correlation functional (e.g., "pbe", "b3lyp") |
'pbe'
|
default_dtype
|
str
|
Default data type ("float32" or "float64") |
'float64'
|
Examples:
>>> # Basic usage
>>> calc = MACEInference(model="medium", device="auto")
>>> result = calc.single_point("structure.cif")
Source code in src/mace_inference/core.py
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 | |
__init__ ¶
__init__(model: str = 'medium', device: Literal['auto', 'cpu', 'cuda'] = 'auto', enable_d3: bool = False, d3_damping: str = 'bj', d3_xc: str = 'pbe', default_dtype: str = 'float64')
Source code in src/mace_inference/core.py
single_point ¶
single_point(structure: Union[str, Path, Atoms], properties: Optional[List[str]] = None) -> Dict[str, Any]
Perform single-point energy calculation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Union[str, Path, Atoms]
|
Structure file path or Atoms object |
required |
properties
|
Optional[List[str]]
|
Properties to calculate (default: ["energy", "forces", "stress"]) |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with calculated properties |
Examples:
>>> result = calc.single_point("structure.cif")
>>> print(f"Energy: {result['energy']:.4f} eV")
>>> print(f"Max force: {result['forces'].max():.4f} eV/A")
Source code in src/mace_inference/core.py
optimize ¶
optimize(structure: Union[str, Path, Atoms], fmax: float = 0.05, steps: int = 500, optimizer: str = 'LBFGS', optimize_cell: bool = False, trajectory: Optional[str] = None, logfile: Optional[str] = None, output: Optional[str] = None) -> Atoms
Optimize atomic structure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Union[str, Path, Atoms]
|
Input structure |
required |
fmax
|
float
|
Force convergence criterion (eV/A) |
0.05
|
steps
|
int
|
Maximum optimization steps |
500
|
optimizer
|
str
|
Optimization algorithm ("LBFGS", "BFGS", "FIRE") |
'LBFGS'
|
optimize_cell
|
bool
|
Whether to optimize cell parameters |
False
|
trajectory
|
Optional[str]
|
Trajectory file path |
None
|
logfile
|
Optional[str]
|
Optimization log file path |
None
|
output
|
Optional[str]
|
Output structure file path |
None
|
Returns:
| Type | Description |
|---|---|
Atoms
|
Optimized Atoms object |
Examples:
>>> optimized = calc.optimize("structure.cif", fmax=0.05)
>>> optimized = calc.optimize("structure.cif", optimize_cell=True, output="opt.cif")
Source code in src/mace_inference/core.py
run_md ¶
run_md(structure: Union[str, Path, Atoms], ensemble: Literal['nvt', 'npt'] = 'nvt', temperature_K: float = 300, steps: int = 1000, timestep: float = 1.0, pressure_GPa: Optional[float] = None, taut: Optional[float] = None, taup: Optional[float] = None, trajectory: Optional[str] = None, logfile: Optional[str] = None, log_interval: int = 100, progress_callback: Optional[Callable[[int, int], None]] = None) -> Atoms
Run molecular dynamics simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Union[str, Path, Atoms]
|
Input structure |
required |
ensemble
|
Literal['nvt', 'npt']
|
MD ensemble ("nvt" or "npt") |
'nvt'
|
temperature_K
|
float
|
Target temperature (K) |
300
|
steps
|
int
|
Number of MD steps |
1000
|
timestep
|
float
|
Time step (fs) |
1.0
|
pressure_GPa
|
Optional[float]
|
Target pressure for NPT (GPa) |
None
|
taut
|
Optional[float]
|
Temperature coupling time (fs) |
None
|
taup
|
Optional[float]
|
Pressure coupling time (fs) |
None
|
trajectory
|
Optional[str]
|
Trajectory file path |
None
|
logfile
|
Optional[str]
|
MD log file path |
None
|
log_interval
|
int
|
Logging interval (steps) |
100
|
progress_callback
|
Optional[Callable[[int, int], None]]
|
Optional callback function(current_step, total_steps) |
None
|
Returns:
| Type | Description |
|---|---|
Atoms
|
Final Atoms object |
Examples:
>>> # NVT simulation
>>> final = calc.run_md("structure.cif", ensemble="nvt", temperature_K=300, steps=10000)
>>> # NPT simulation
>>> final = calc.run_md("structure.cif", ensemble="npt", temperature_K=300,
... pressure_GPa=1.0, steps=10000)
>>> # With progress callback
>>> def progress(current, total):
... print(f"MD: {current}/{total} steps")
>>> final = calc.run_md("structure.cif", steps=1000, progress_callback=progress)
Source code in src/mace_inference/core.py
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 | |
phonon ¶
phonon(structure: Union[str, Path, Atoms], supercell_matrix: Union[List[int], int] = 2, displacement: float = 0.01, mesh: List[int] = None, temperature_range: Optional[tuple] = None, output_dir: Optional[str] = None) -> Dict[str, Any]
Calculate phonon properties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Union[str, Path, Atoms]
|
Input structure |
required |
supercell_matrix
|
Union[List[int], int]
|
Supercell size for phonon calculation |
2
|
displacement
|
float
|
Atomic displacement distance (A) |
0.01
|
mesh
|
List[int]
|
k-point mesh for phonon DOS (default: [20, 20, 20]) |
None
|
temperature_range
|
Optional[tuple]
|
Temperature range for thermal properties (min, max, step) |
None
|
output_dir
|
Optional[str]
|
Directory for output files |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with phonon properties |
Examples:
>>> result = calc.phonon("structure.cif", supercell_matrix=[2, 2, 2])
>>> print(f"Frequencies: {result['frequencies']}")
Source code in src/mace_inference/core.py
bulk_modulus ¶
bulk_modulus(structure: Union[str, Path, Atoms], scale_range: tuple = (0.95, 1.05), n_points: int = 11, optimize_first: bool = True, fmax: float = 0.01, eos_type: str = 'birchmurnaghan') -> Dict[str, Any]
Calculate bulk modulus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Union[str, Path, Atoms]
|
Input structure |
required |
scale_range
|
tuple
|
Volume scaling range as (min_scale, max_scale) |
(0.95, 1.05)
|
n_points
|
int
|
Number of volume points for EOS fitting |
11
|
optimize_first
|
bool
|
Whether to optimize structure first |
True
|
fmax
|
float
|
Force criterion for optimization |
0.01
|
eos_type
|
str
|
Equation of state type ("birchmurnaghan", "murnaghan", etc.) |
'birchmurnaghan'
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with bulk modulus results |
Examples:
>>> result = calc.bulk_modulus("structure.cif")
>>> print(f"Bulk modulus: {result['B_GPa']:.1f} GPa")
Source code in src/mace_inference/core.py
adsorption_energy ¶
adsorption_energy(framework: Union[str, Path, Atoms], adsorbate: Union[str, Atoms], site_position: List[float], optimize: bool = True, fmax: float = 0.05, fix_framework: bool = True) -> Dict[str, Any]
Calculate adsorption energy.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
framework
|
Union[str, Path, Atoms]
|
Framework structure (e.g., MOF, zeolite) |
required |
adsorbate
|
Union[str, Atoms]
|
Adsorbate molecule (formula or Atoms) |
required |
site_position
|
List[float]
|
Adsorption site position [x, y, z] |
required |
optimize
|
bool
|
Whether to optimize the combined structure |
True
|
fmax
|
float
|
Force criterion for optimization |
0.05
|
fix_framework
|
bool
|
Whether to fix framework atoms during optimization |
True
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with adsorption energy results |
Examples:
>>> result = calc.adsorption_energy(
... framework="mof.cif",
... adsorbate="CO2",
... site_position=[5.0, 5.0, 5.0]
... )
>>> print(f"Adsorption energy: {result['adsorption_energy']:.3f} eV")
Source code in src/mace_inference/core.py
coordination ¶
coordination(structure: Union[str, Path, Atoms], metal_indices: Optional[List[int]] = None, cutoff_multiplier: float = 1.3) -> Dict[str, Any]
Analyze coordination environment of metal atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
structure
|
Union[str, Path, Atoms]
|
Input structure |
required |
metal_indices
|
Optional[List[int]]
|
Indices of metal atoms to analyze (auto-detect if None) |
None
|
cutoff_multiplier
|
float
|
Multiplier for covalent radii cutoff |
1.3
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary with coordination analysis results |
Examples:
>>> result = calc.coordination("mof.cif")
>>> for metal_idx, info in result["coordination"].items():
... print(f"Metal {metal_idx}: CN = {info['coordination_number']}")
Source code in src/mace_inference/core.py
Constructor¶
MACEInference(
model: str = "medium",
device: str = "auto",
enable_d3: bool = False,
d3_xc: str = "pbe",
d3_damping: str = "bj",
default_dtype: str = "float64"
)
Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
model |
str |
"medium" |
Model name ("small", "medium", "large") or path to .model file |
device |
str |
"auto" |
Device: "auto", "cpu", "cuda", "cuda:0", "mps" |
enable_d3 |
bool |
False |
Enable DFT-D3 dispersion correction |
d3_xc |
str |
"pbe" |
Exchange-correlation functional for D3 |
d3_damping |
str |
"bj" |
D3 damping function ("bj" or "zero") |
default_dtype |
str |
"float64" |
Default precision ("float32" or "float64") |
Example¶
from mace_inference import MACEInference
# Basic initialization
calc = MACEInference(model="medium", device="auto")
# With D3 correction
calc = MACEInference(
model="medium",
device="cuda",
enable_d3=True,
d3_xc="pbe"
)
# Custom model
calc = MACEInference(model="/path/to/model.model")
Methods¶
single_point¶
Calculate energy, forces, and stress for a structure.
Parameters:
atoms(Atoms): ASE Atoms object
Returns: dict with keys:
energy(float): Total energy in eVenergy_per_atom(float): Energy per atom in eVforces(ndarray): Forces array (N, 3) in eV/Åmax_force(float): Maximum force magnitude in eV/Åstress(ndarray): Stress tensor in Voigt notation (eV/ų)
optimize¶
def optimize(
self,
atoms: Atoms,
fmax: float = 0.05,
steps: int = 500,
optimizer: str = "LBFGS",
optimize_cell: bool = False,
trajectory: Optional[str] = None,
logfile: Optional[str] = None,
output: Optional[str] = None
) -> Atoms
Optimize atomic positions and optionally cell parameters.
Parameters:
atoms(Atoms): Structure to optimizefmax(float): Force convergence criterion in eV/Åsteps(int): Maximum optimization stepsoptimizer(str):"LBFGS","BFGS"or"FIRE"optimize_cell(bool): Also optimize cell parameterstrajectory(str): Save trajectory to this filelogfile(str): Optimization log fileoutput(str): Save optimized structure to this file
Returns: Atoms - Optimized structure
run_md¶
def run_md(
self,
atoms: Atoms,
ensemble: str = "nvt",
temperature_K: float = 300,
steps: int = 1000,
timestep: float = 1.0,
pressure_GPa: Optional[float] = None,
taut: Optional[float] = None,
taup: Optional[float] = None,
trajectory: Optional[str] = None,
logfile: Optional[str] = None,
log_interval: int = 100,
progress_callback: Optional[Callable] = None
) -> Atoms
Run molecular dynamics simulation.
Parameters:
atoms(Atoms): Initial structureensemble(str):"nvt"or"npt"temperature_K(float): Temperature in Kelvinsteps(int): Number of MD stepstimestep(float): Time step in fspressure_GPa(float): Pressure in GPa (NPT only)taut(float): Temperature coupling time in fstaup(float): Pressure coupling time in fstrajectory(str): Save trajectory to this filelogfile(str): MD log filelog_interval(int): Logging interval in stepsprogress_callback(Callable): Callback function(current_step, total_steps)
Returns: Atoms - Final structure after MD simulation
phonon¶
def phonon(
self,
atoms: Atoms,
supercell_matrix: Union[List[int], int] = 2,
displacement: float = 0.01,
mesh: List[int] = [20, 20, 20],
temperature_range: Optional[tuple] = None,
output_dir: Optional[str] = None
) -> dict
Calculate phonon properties.
Parameters:
atoms(Atoms): Unit cell structuresupercell_matrix(intorlist): Supercell dimensions (e.g., 2 or [2, 2, 2])displacement(float): Displacement magnitude in Åmesh(list): q-point mesh for DOStemperature_range(tuple): Temperature range for thermal properties (min, max, step)output_dir(str): Directory for output files
Returns: dict with keys:
frequencies(ndarray): Frequencies at Γ in THzphonon(Phonopy): Phonopy objectthermal(dict): Thermal properties (if temperature_range provided)
bulk_modulus¶
def bulk_modulus(
self,
atoms: Atoms,
scale_range: Tuple[float, float] = (0.95, 1.05),
n_points: int = 7,
eos: str = "birchmurnaghan"
) -> dict
Calculate bulk modulus by fitting equation of state.
Parameters:
atoms(Atoms): Structure (should be optimized)scale_range(tuple): Volume scaling rangen_points(int): Number of points for fiteos(str): Equation of state type
Returns: dict with keys:
bulk_modulus(float): Bulk modulus in GPaequilibrium_volume(float): Equilibrium volume in ųequilibrium_energy(float): Energy at equilibrium in eVvolumes(list): Volumes used in fitenergies(list): Energies at each volume
adsorption_energy¶
def adsorption_energy(
self,
framework: Atoms,
adsorbate: Atoms,
site_position: List[float],
optimize: bool = True,
fmax: float = 0.05,
fix_framework: bool = True
) -> dict
Calculate gas adsorption energy in a framework.
Parameters:
framework(Atoms): Framework structure (MOF, zeolite, etc.)adsorbate(Atoms): Gas moleculesite_position(list): Position [x, y, z] to place adsorbateoptimize(bool): Optimize the complexfmax(float): Force tolerance in eV/Åfix_framework(bool): Keep framework fixed
Returns: dict with keys:
E_ads(float): Adsorption energy in eVE_mof(float): Framework energy in eVE_gas(float): Gas molecule energy in eVE_complex(float): Complex energy in eVcomplex_structure(Atoms): Final complex structureoptimized(bool): Whether structure was optimized
coordination¶
def coordination(
self,
atoms: Atoms,
metal_indices: Optional[List[int]] = None,
cutoff_multiplier: float = 1.3
) -> dict
Analyze coordination environment of metal atoms.
Parameters:
atoms(Atoms): Structure to analyzemetal_indices(list): Indices of metal atoms (auto-detect if None)cutoff_multiplier(float): Multiplier for covalent radii cutoff
Returns: dict with keys:
coordination(dict): Coordination info for each metal atommetal_indices(list): Indices of metal atoms analyzed
get_calculator¶
Get the underlying ASE calculator.
Returns: ASE Calculator object (MACE or MACE+D3)