Documentation
Start with one of five workflows. Each guide shows the inputs, the returned results and a Python example you can copy.
Install from GitHub main
python -m pip install rdkit \
git+https://github.com/guillaume-osmo/mlxmolkit.git@mainQuantum chemistry
Use semiempirical models to calculate energies and atomic charges, obtain forces, or optimise a geometry. MLXMolKit exposes NDDO methods such as PM6 and PM7, and the GFN-xTB and g-xTB methods. The xTB module also provides ALPB water solvation.
- Input
- Atomic numbers, Cartesian coordinates in ångströms, and a model.
- Output
- The PM7 single-point result includes energy in eV, heat of formation in kcal/mol, atomic charges and SCF convergence.
Evaluate PM7 for water at a fixed geometry
from mlxmolkit.nddo import nddo_energy
result = nddo_energy(
[8, 1, 1],
[[0, 0, 0], [0.9572, 0, 0], [-0.2400, 0.9273, 0]],
method="PM7",
)
print(result["converged"], result["heat_of_formation_kcal"])COSMO and COSMO-RS
COSMO describes the screening charge on a molecule’s cavity surface. Read a compatible .cosmo file to calculate its σ-profile, the distribution of surface area by charge density.
COSMO-RS uses the component surfaces to calculate properties of liquid mixtures. The optional opencosmorspy backend provides activity coefficients and solid solubility in solvent mixtures.
Save the water COSMO file alongside the script to generate a σ-profile.
from pathlib import Path
from mlxmolkit.xtb import parse_xtb_cosmo, sigma_profile_klamt
surface = parse_xtb_cosmo(Path("water_gfn2_tmcosmo_inf.cosmo"))
sigma, area, averaged_sigma = sigma_profile_klamt(surface)
print(f"{len(sigma)} bins, {area.sum():.2f} Ų of surface area")Python API signatures
- mlxmolkit.nddo.nddo_energy
nddo_energy(atoms: list[int], coords: np.ndarray, max_iter: int=100, conv_tol: float=1e-06, verbose: bool=False, use_metal: bool=False, method: str='RM1', native: bool=False, molecular_charge: float=0.0, P_init: np.ndarray | None=None) -> dict - mlxmolkit.nddo.nddo_energy_batch
nddo_energy_batch(molecules: list[tuple[list[int], np.ndarray]], max_iter: int=100, conv_tol: float=1e-06, use_metal: bool=True, verbose: bool=False, method: str='RM1', molecular_charges: list[float] | None=None, density_solver: str='auto') -> list[dict] - mlxmolkit.xtb.gfn2_energy
gfn2_energy(atoms: list[int], coords_ang: np.ndarray, *, charge: int=0, max_iter: int=100, conv_tol: float=1e-06, mix: float=0.4, verbose: bool=False, use_d4: bool=True, alpb_solvent: str | None=None) -> dict - mlxmolkit.xtb.gxtb_energy
gxtb_energy(atomic_numbers, coords_ang, **kwargs) - mlxmolkit.xtb.parse_xtb_cosmo
parse_xtb_cosmo(path: Path) -> CosmoSegments - mlxmolkit.xtb.sigma_profile_klamt
sigma_profile_klamt(cosmo: CosmoSegments, *, variant: str='mullins', sigma_min: float=-0.025, sigma_max: float=0.025, bin_width: float=0.001) -> tuple[np.ndarray, np.ndarray, np.ndarray] - mlxmolkit.xtb.sigma_potential
sigma_potential(cosmo: CosmoSegments, *, sigma_grid_e_per_A2: np.ndarray | None=None, T: float=298.15, params: dict | None=None, sigma_bin_min: float=-0.03, sigma_bin_max: float=0.03, sigma_bin_step: float=0.001, klamt_variant: str='mullins', n_iter_max: int=500, conv_tol: float=1e-09, damping: float=0.7) -> tuple[np.ndarray, np.ndarray] - mlxmolkit.xtb.activity_coefficients
activity_coefficients(component_cosmo_paths: Sequence[str | Path], x: Sequence[float], *, labels: Sequence[str] | None=None, T: float=298.15, refst: str='pure_component') -> ActivityResult - mlxmolkit.xtb.solubility_in_solvent_mixture
solubility_in_solvent_mixture(component_cosmo_paths: Sequence[str | Path], solvent_x: Sequence[float], *, delta_h_fus_J_mol: float, T_fus_K: float, T: float=298.15, labels: Sequence[str] | None=None, iterative: bool=True, infinite_dilution_x: float=1e-08) -> dict[str, object]
Molecular dynamics
Simulate batches of replicas sharing a force-field topology with Metal force kernels. Use fixed-volume Langevin dynamics for NVT, add a barostat for NPT, or use Hamiltonian replica exchange for alchemical free energies.
- Input
- A parameterised topology, initial positions and velocities, and orthorhombic box lengths. The example defines a two-atom argon system.
- Output
- Sampled positions and energies, plus the final state for continuing a trajectory. Positions are in nm and potential energies in kJ/mol.
Run a short fixed-volume trajectory for two argon atoms
import numpy as np
from mlxmolkit.md import Dynamics, Topology, run_nvt
box = np.array([3.0, 3.0, 3.0])
empty = np.empty(0)
pairs = np.empty((0, 2), dtype=np.int32)
data = dict(
box=np.diag(box), masses=[39.948, 39.948], constraints=np.empty((0, 3)),
q=[0, 0], sigma=[0.34, 0.34], eps=[0.997, 0.997],
bond_idx=pairs, bond_r0=empty, bond_k=empty,
angle_idx=np.empty((0, 3), dtype=np.int32), angle_t0=empty, angle_k=empty,
tors_idx=np.empty((0, 4), dtype=np.int32), tors_n=empty,
tors_phase=empty, tors_k=empty,
exc_idx=pairs, exc_qq=empty, exc_sigma=empty, exc_eps=empty,
cutoff=1.0, switch=0.9, pme_alpha=3.0, pme_grid=[8, 8, 8], e_disp=0.0,
)
positions = np.array([[[0.8, 0.8, 0.8], [1.2, 0.8, 0.8]]])
dynamics = Dynamics(
Topology.from_npz(data), data, B=1, dt_ps=0.002,
temperature=298, friction=1.0, seed=7,
)
run = run_nvt(
dynamics, positions, np.zeros_like(positions), box, steps=5, sample_every=2,
)
print(run.steps, run.positions.shape)Python API signatures
- mlxmolkit.md.run_nvt
run_nvt(dynamics: Dynamics, positions, velocities, box, *, steps: int, sample_every: int=1) -> NVTTrajectory - mlxmolkit.md.run_npt
run_npt(dynamics: Dynamics, barostat: MonteCarloBarostat, positions, velocities, box, *, steps: int, sample_every: int=250) -> NPTTrajectory - mlxmolkit.md.run_hrex
run_hrex(dynamics: AlchemicalDynamics, positions, box, *, iterations: int, equilibration_iterations: int=0, steps_per_iteration: int=250, barostat: MonteCarloBarostat | None=None, seed: int=0) -> HREXResult
Partial charges
Assign per-atom charges using GPU implementations of eEEM and ePEOP. Use eEEM for a specific 3D geometry, ePEOP for the molecular graph, or its BCC option for AM1-BCC-style atom typing.
- Input
- An RDKit molecule. Include explicit hydrogens and a 3D conformer for eEEM. For ePEOP, add hydrogens when you need all atom charges and the complete molecular charge sum.
- Output
- An MLX array of partial charges in the molecule’s atom order.
Calculate three charge assignments for ethanol
from rdkit import Chem
from rdkit.Chem import AllChem
from mlxmolkit import eeem_charges_mlx, epeop_charges_mlx
mol = Chem.AddHs(Chem.MolFromSmiles("CCO"))
conf_id = AllChem.EmbedMolecule(mol, randomSeed=42)
if conf_id < 0:
raise RuntimeError("Could not embed ethanol")
print(eeem_charges_mlx(mol, conf_id=conf_id))
print(epeop_charges_mlx(mol))
print(epeop_charges_mlx(mol, bcc=True))Python API signatures
- mlxmolkit.eeem_charges_mlx
eeem_charges_mlx(mol, conf_id: int=-1) -> mx.array - mlxmolkit.epeop_charges_mlx
epeop_charges_mlx(mol, n_iter: int=12, *, bcc: bool=False) -> mx.array
3D conformers
Generate ensembles for a batch of molecules with distance geometry and experimental torsion preferences on Metal. Optionally refine the accepted conformers with MMFF94.
- Input
- SMILES, the requested conformer count, an ETKDG variant and a seed.
- Output
- A result per molecule with accepted 3D coordinates. A molecule can return fewer than the requested conformers.
Generate and refine small conformer ensembles
from mlxmolkit import generate_conformers_nk
result = generate_conformers_nk(
["CCCO", "CC(=O)O"],
n_confs_per_mol=4, variant="ETKDGv3", run_mmff=True, seed=42,
)
print([len(mol.positions_3d) for mol in result.molecules])Python API signatures
- mlxmolkit.generate_conformers_nk
generate_conformers_nk(smiles_list: Sequence[str], n_confs_per_mol: int | List[int]=10, *, max_confs_per_batch: Optional[int]=None, max_memory_bytes: Optional[int]=None, dg_max_iters: int=0, etk_max_iters: int=0, fourth_dim_weight: float=0.1, chiral_weight: float=1.0, variant: str='ETKDGv2', run_mmff: bool=False, mmff_max_iters: int=0, mmff_use_lbfgs: bool | None=None, mmff_variant: str='MMFF94', seed: int=42, max_attempts: Optional[int]=None, max_rounds: int=8, oversample: float=0.25, return_failed: bool=False) -> PipelineResult
Clustering
Group molecular fingerprints by Tanimoto similarity using Butina clustering. Set reordering=True to recompute active neighbour counts after each cluster is assigned.
- Input
- One row of packed Morgan fingerprint words per molecule and a Tanimoto similarity cutoff. RDKit’s equivalent distance threshold is one minus the similarity cutoff.
- Output
- Clusters of indices into the original input. Each cluster starts with its selected centre.
Create Morgan fingerprints and cluster with Butina
from rdkit import Chem
from mlxmolkit import butina_tanimoto_resident, morgan_fingerprints_mlx
mols = [Chem.MolFromSmiles(s) for s in ("CCO", "CCCO", "CC(C)O", "c1ccccc1")]
packed = morgan_fingerprints_mlx(mols)
result = butina_tanimoto_resident(packed, cutoff=0.25, reordering=True)
print(result.clusters())Python API signatures
- mlxmolkit.butina_tanimoto_resident
butina_tanimoto_resident(fingerprints, cutoff: float, *, reordering: bool=True, max_graph_bytes: int=128 << 20) -> ButinaDeviceResult