Building Packed Systems with Packmol#

This example illustrates several ways of building liquid or gas mixtures and solid-liquid interfaces from Python with Packmol-driven structure generation.

Note

packmol returns a ChemicalSystem when passed a ChemicalSystem or a list containing only ChemicalSystem objects. Mixed lists containing PLAMS molecules return a PLAMS Molecule.

Initial imports#

from typing import Any, Dict, Optional

from scm.base import ChemicalSystem, Lattice
from scm.plams import packmol, packmol_around, view

Helper functions#

def printsummary(mol: ChemicalSystem, details: Optional[Dict[str, Any]] = None) -> None:
    if details:
        density = details["density"]
    else:
        density = mol.density("g/cm3")
    s = f"{len(mol)} atoms, density = {density:.3f} g/cm^3"
    if mol.lattice.num_vectors:
        s += f", box = {mol.lattice.vectors[0, 0]:.3f}, {mol.lattice.vectors[1, 1]:.3f}, {mol.lattice.vectors[2, 2]:.3f}"
    s += f", formula = {mol.formula()}"
    if details:
        s += f"\n#added molecules per species: {details['n_molecules']}, mole fractions: {details['mole_fractions']}"
    print(s)

Liquid water (fluid with 1 component)#

First, create the gasphase molecule:

water = ChemicalSystem.from_smiles("O")
view(water, width=200, height=200)
image generated from notebook
print("pure liquid from approximate number of atoms and exact density (in g/cm^3), cubic box with auto-determined size")
out = packmol(water, n_atoms=194, density=1.0)
printsummary(out)
out.write_xyz("water-1.xyz")
view(out, width=300, height=300, padding=-2)
pure liquid from approximate number of atoms and exact density (in g/cm^3), cubic box with auto-determined size
195 atoms, density = 1.000 g/cm^3, box = 12.482, 12.482, 12.482, formula = H130O65
image generated from notebook
print("pure liquid from approximate density (in g/cm^3) and an orthorhombic box")
out = packmol(water, density=1.0, box_bounds=[0.0, 0.0, 0.0, 8.0, 12.0, 14.0])
printsummary(out)
out.write_xyz("water-2.xyz")
view(out, width=300, height=300, padding=-2)
pure liquid from approximate density (in g/cm^3) and an orthorhombic box
135 atoms, density = 1.001 g/cm^3, box = 8.000, 12.000, 14.000, formula = H90O45
image generated from notebook
print("pure liquid with explicit number of molecules and exact density")
out = packmol(water, n_molecules=64, density=1.0)
printsummary(out)
out.write_xyz("water-3.xyz")
view(out, width=300, height=300, padding=-2)
pure liquid with explicit number of molecules and exact density
192 atoms, density = 1.000 g/cm^3, box = 12.417, 12.417, 12.417, formula = H128O64
image generated from notebook
print("pure liquid with explicit number of molecules and box")
out = packmol(water, n_molecules=64, box_bounds=[0.0, 0.0, 0.0, 12.0, 13.0, 14.0])
printsummary(out)
out.write_xyz("water-4.xyz")
view(out, width=300, height=300, padding=-2)
pure liquid with explicit number of molecules and box
192 atoms, density = 0.876 g/cm^3, box = 12.000, 13.000, 14.000, formula = H128O64
image generated from notebook
print("water-5.xyz: pure liquid in non-orthorhombic box (requires AMS2025 or later)")
print("NOTE: Non-orthorhombic boxes may yield inaccurate results, always carefully check the output")
# You can pack inside any lattice using the packmol_around function
box = ChemicalSystem()
box.lattice = Lattice([[10.0, 2.0, -1.0], [-5.0, 8.0, 0.0], [0.0, -2.0, 11.0]])
out = packmol_around(box, molecules=[water], n_molecules=[32])
out.write_xyz("water-5.xyz")
view(out, width=300, height=300, padding=-2)
water-5.xyz: pure liquid in non-orthorhombic box (requires AMS2025 or later)
NOTE: Non-orthorhombic boxes may yield inaccurate results, always carefully check the output


Note: The following floating-point exceptions are signalling: IEEE_INVALID_FLAG IEEE_DIVIDE_BY_ZERO
image generated from notebook
print("Experimental feature (AMS2025): guess density for pure liquid")
print("Note: This density is meant to be equilibrated with NPT MD. It can be very inaccurate!")
out = packmol(water, n_atoms=100)
print(f"Guessed density: {out.density('kg/m3'):.2f} kg/m^3")
view(out, width=200, height=200, padding=-2)
Experimental feature (AMS2025): guess density for pure liquid
Note: This density is meant to be equilibrated with NPT MD. It can be very inaccurate!
Guessed density: 1013.70 kg/m^3
image generated from notebook

Water-acetonitrile mixture (fluid with 2 or more components)#

Let’s also create a single acetonitrile molecule:

acetonitrile = ChemicalSystem.from_smiles("CC#N")
view(acetonitrile, width=200, height=200)
image generated from notebook

Set the desired mole fractions and density. Here, the density is calculated as the weighted average of water (1.0 g/cm^3) and acetonitrile (0.76 g/cm^3) densities, but you could use any other density.

# MIXTURES
x_water = 0.666  # mole fraction
x_acetonitrile = 1 - x_water  # mole fraction
# weighted average of pure component densities
density = (x_water * 1.0 + x_acetonitrile * 0.76) / (x_water + x_acetonitrile)

print("MIXTURES")
print(f"x_water = {x_water:.3f}")
print(f"x_acetonitrile = {x_acetonitrile:.3f}")
print(f"target density = {density:.3f} g/cm^3")
MIXTURES
x_water = 0.666
x_acetonitrile = 0.334
target density = 0.920 g/cm^3

By setting return_details=True, you can get information about the mole fractions of the returned system. They may not exactly match the mole fractions you put in.

print(
    "2-1 water-acetonitrile from approximate number of atoms and exact density (in g/cm^3), "
    "cubic box with auto-determined size"
)
out, details = packmol(
    molecules=[water, acetonitrile],
    mole_fractions=[x_water, x_acetonitrile],
    n_atoms=200,
    density=density,
    return_details=True,
)
printsummary(out, details)
out.write_xyz("water-acetonitrile-1.xyz")
view(out, width=300, height=300, padding=-2)
2-1 water-acetonitrile from approximate number of atoms and exact density (in g/cm^3), cubic box with auto-determined size
201 atoms, density = 0.920 g/cm^3, box = 13.263, 13.263, 13.263, formula = C34H117N17O33
#added molecules per species: [33, 17], mole fractions: [0.66, 0.34]
image generated from notebook

The details is a dictionary as follows:

for k, v in details.items():
    print(f"{k}: {v}")
n_molecules: [33, 17]
mole_fractions: [0.66, 0.34]
n_atoms: 201
molecule_type_indices: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
molecule_indices: [np.int64(0), np.int64(0), np.int64(0), np.int64(1), np.int64(1), np.int64(1), np.int64(2), np.int64(2), np.int64(2), np.int64(3), np.int64(3), np.int64(3), np.int64(4), np.int64(4), np.int64(4), np.int64(5), np.int64(5), np.int64(5), np.int64(6), np.int64(6), np.int64(6), np.int64(7), np.int64(7), np.int64(7), np.int64(8), np.int64(8), np.int64(8), np.int64(9), np.int64(9), np.int64(9), np.int64(10), np.int64(10), np.int64(10), np.int64(11), np.int64(11), np.int64(11), np.int64(12), np.int64(12), np.int64(12), np.int64(13), np.int64(13), np.int64(13), np.int64(14), np.int64(14), np.int64(14), np.int64(15), np.int64(15), np.int64(15), np.int64(16), np.int64(16), np.int64(16), np.int64(17), np.int64(17), np.int64(17), np.int64(18), np.int64(18), np.int64(18), np.int64(19), np.int64(19), np.int64(19), np.int64(20), np.int64(20), np.int64(20), np.int64(21), np.int64(21), np.int64(21), np.int64(22), np.int64(22), np.int64(22), np.int64(23), np.int64(23), np.int64(23), np.int64(24), np.int64(24), np.int64(24), np.int64(25), np.int64(25), np.int64(25), np.int64(26), np.int64(26), np.int64(26), np.int64(27), np.int64(27), np.int64(27), np.int64(28), np.int64(28), np.int64(28), np.int64(29), np.int64(29), np.int64(29), np.int64(30), np.int64(30), np.int64(30), np.int64(31), np.int64(31), np.int64(31), np.int64(32), np.int64(32), np.int64(32), np.int64(33), np.int64(33), np.int64(33), np.int64(33), np.int64(33), np.int64(33), np.int64(34), np.int64(34), np.int64(34), np.int64(34), np.int64(34), np.int64(34), np.int64(35), np.int64(35), np.int64(35), np.int64(35), np.int64(35), np.int64(35), np.int64(36), np.int64(36), np.int64(36), np.int64(36), np.int64(36), np.int64(36), np.int64(37), np.int64(37), np.int64(37), np.int64(37), np.int64(37), np.int64(37), np.int64(38), np.int64(38), np.int64(38), np.int64(38), np.int64(38), np.int64(38), np.int64(39), np.int64(39), np.int64(39), np.int64(39), np.int64(39), np.int64(39), np.int64(40), np.int64(40), np.int64(40), np.int64(40), np.int64(40), np.int64(40), np.int64(41), np.int64(41), np.int64(41), np.int64(41), np.int64(41), np.int64(41), np.int64(42), np.int64(42), np.int64(42), np.int64(42), np.int64(42), np.int64(42), np.int64(43), np.int64(43), np.int64(43), np.int64(43), np.int64(43), np.int64(43), np.int64(44), np.int64(44), np.int64(44), np.int64(44), np.int64(44), np.int64(44), np.int64(45), np.int64(45), np.int64(45), np.int64(45), np.int64(45), np.int64(45), np.int64(46), np.int64(46), np.int64(46), np.int64(46), np.int64(46), np.int64(46), np.int64(47), np.int64(47), np.int64(47), np.int64(47), np.int64(47), np.int64(47), np.int64(48), np.int64(48), np.int64(48), np.int64(48), np.int64(48), np.int64(48), np.int64(49), np.int64(49), np.int64(49), np.int64(49), np.int64(49), np.int64(49)]
atom_indices_in_molecule: [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]
volume: 2333.0853879652004
density: 0.9198400000000004
print("2-1 water-acetonitrile from approximate density (in g/cm^3) and box bounds")
out, details = packmol(
    molecules=[water, acetonitrile],
    mole_fractions=[x_water, x_acetonitrile],
    box_bounds=[0, 0, 0, 13.2, 13.2, 13.2],
    density=density,
    return_details=True,
)
printsummary(out, details)
out.write_xyz("water-acetonitrile-2.xyz")
view(out, width=300, height=300, padding=-2)
2-1 water-acetonitrile from approximate density (in g/cm^3) and box bounds
201 atoms, density = 0.933 g/cm^3, box = 13.200, 13.200, 13.200, formula = C34H117N17O33
#added molecules per species: [33, 17], mole fractions: [0.66, 0.34]
image generated from notebook
print("2-1 water-acetonitrile from explicit number of molecules and density, cubic box with auto-determined size")
out, details = packmol(
    molecules=[water, acetonitrile],
    n_molecules=[32, 16],
    density=density,
    return_details=True,
)
printsummary(out, details)
out.write_xyz("water-acetonitrile-3.xyz")
view(out, width=300, height=300, padding=-2)
2-1 water-acetonitrile from explicit number of molecules and density, cubic box with auto-determined size
192 atoms, density = 0.920 g/cm^3, box = 13.058, 13.058, 13.058, formula = C32H112N16O32
#added molecules per species: [32, 16], mole fractions: [0.6666666666666666, 0.3333333333333333]
image generated from notebook
print("2-1 water-acetonitrile from explicit number of molecules and box")
out = packmol(
    molecules=[water, acetonitrile],
    n_molecules=[32, 16],
    box_bounds=[0, 0, 0, 13.2, 13.2, 13.2],
)
printsummary(out)
out.write_xyz("water-acetonitrile-4.xyz")
view(out, width=300, height=300, padding=-2)
2-1 water-acetonitrile from explicit number of molecules and box
192 atoms, density = 0.890 g/cm^3, box = 13.200, 13.200, 13.200, formula = C32H112N16O32
image generated from notebook
print("Experimental feature (AMS2025): guess density for mixture")
print("Note: This density is meant to be equilibrated with NPT MD. It can be very inaccurate!")
out = packmol([water, acetonitrile], mole_fractions=[x_water, x_acetonitrile], n_atoms=100)
print(f"Guessed density: {out.density('kg/m3'):.2f} kg/m^3")
view(out, width=200, height=200, padding=-2)
Experimental feature (AMS2025): guess density for mixture
Note: This density is meant to be equilibrated with NPT MD. It can be very inaccurate!
Guessed density: 848.96 kg/m^3
image generated from notebook

NaCl solution (solvent with 1 or more solutes)#

sodium = ChemicalSystem.from_smiles("[Na+]")
chloride = ChemicalSystem.from_smiles("[Cl-]")

For dilute solutions, it can be useful to specify the number of solute species, and fill up the rest of the box with solvent.

The required number of solvent molecules are then added to fill up the box to the target overall density or number of atoms.

This feature can be used if exactly one of the elements of the n_molecules list is None.

print(
    "NaCl solution from approximate density (in g/cm^3) and box bounds, and auto-determined number of solvent molecules"
)
out = packmol(
    [sodium, chloride, water],
    n_molecules=[5, 5, None],
    density=1.029,
    box_bounds=[0, 0, 0, 19, 19, 19],
)
printsummary(out)
out.write_xyz("sodium-chloride-solution-1.xyz")
view(out, width=300, height=300, padding=-3, fixed_atom_size=False)
NaCl solution from approximate density (in g/cm^3) and box bounds, and auto-determined number of solvent molecules
670 atoms, density = 1.029 g/cm^3, box = 19.000, 19.000, 19.000, formula = Cl5H440Na5O220
image generated from notebook

Specify the total number of atoms instead of box bounds, and auto-determine a cubic box:

print("NaCl solution from approximate number of atoms and density:")
out = packmol([sodium, chloride, water], n_molecules=[5, 5, None], density=1.029, n_atoms=500)
printsummary(out)
out.write_xyz("sodium-chloride-solution-2.xyz")
view(out, width=300, height=300, padding=-3, fixed_atom_size=False)
NaCl solution from approximate number of atoms and density:
499 atoms, density = 1.028 g/cm^3, box = 17.336, 17.336, 17.336, formula = Cl5H326Na5O163
image generated from notebook

Specify the total number of atoms instead of the density (less useful option):

print("NaCl solution from approximate number of atoms and box_bounds:")
out = packmol(
    [sodium, chloride, water],
    n_molecules=[5, 5, None],
    n_atoms=500,
    box_bounds=[0, 0, 0, 12, 18, 24],
)
printsummary(out)
out.write_xyz("sodium-chloride-solution-3.xyz")
view(out, width=300, height=300, padding=-3, fixed_atom_size=False)
NaCl solution from approximate number of atoms and box_bounds:
499 atoms, density = 1.033 g/cm^3, box = 12.000, 18.000, 24.000, formula = Cl5H326Na5O163
image generated from notebook

Pack inside sphere#

Set sphere=True to pack in a sphere (non-periodic) instead of in a periodic box. The sphere will be centered near the origin.

print("water in a sphere from exact density and number of molecules")
out, details = packmol(molecules=[water], n_molecules=[100], density=1.0, return_details=True, sphere=True)
printsummary(out, details)
print(f"Radius  of sphere: {details['radius']:.3f} ang.")
print(f"Center of mass xyz (ang): {out.center_of_mass()}")
out.write_xyz("water-sphere.xyz")
view(out, width=300, height=300, padding=-3)
water in a sphere from exact density and number of molecules
300 atoms, density = 1.000 g/cm^3, formula = H200O100
#added molecules per species: [100], mole fractions: [1.0]
Radius  of sphere: 8.939 ang.
Center of mass xyz (ang): [-0.30857162  0.1042778   0.00876474]
image generated from notebook
print(
    "2-1 water-acetonitrile in a sphere from exact density (in g/cm^3) and "
    "approximate number of atoms and mole fractions"
)
out, details = packmol(
    molecules=[water, acetonitrile],
    mole_fractions=[x_water, x_acetonitrile],
    n_atoms=500,
    density=density,
    return_details=True,
    sphere=True,
)
printsummary(out, details)
out.write_xyz("water-acetonitrile-sphere.xyz")
view(out, width=300, height=300, padding=-3)
2-1 water-acetonitrile in a sphere from exact density (in g/cm^3) and approximate number of atoms and mole fractions
501 atoms, density = 0.920 g/cm^3, formula = C84H292N42O83
#added molecules per species: [83, 42], mole fractions: [0.664, 0.336]
image generated from notebook

Packing ions, total system charge#

The total system charge will be sum of the charges of the constituent molecules.

For a ChemicalSystem, system.charge specifies the total charge:

ammonium = ChemicalSystem.from_smiles("[NH4+]")  # ammonium.charge == +1
chloride = ChemicalSystem.from_smiles("[Cl-]")  # chloride.charge == -1
print("3 water molecules, 3 ammonium, 1 chloride (non-periodic)")
print("Initial charges:")
print(f"Water: {water.charge}")
print(f"Ammonium: {ammonium.charge}")
print(f"Chloride: {chloride.charge}")
out = packmol(molecules=[water, ammonium, chloride], n_molecules=[3, 3, 1], density=0.4, sphere=True)
tot_charge = out.charge
print(f"Total charge of packmol-generated system: {tot_charge}")
out.write_xyz("water-ammonium-chloride.xyz")
view(out, width=300, height=300)
3 water molecules, 3 ammonium, 1 chloride (non-periodic)
Initial charges:
Water: 0.0
Ammonium: 1.0
Chloride: -1.0
Total charge of packmol-generated system: 2.0
image generated from notebook

Microsolvation#

packmol_microsolvation can create a microsolvation sphere around a solute.

from scm.plams import packmol_microsolvation

out = packmol_microsolvation(solute=acetonitrile, solvent=water, density=1.5, threshold=4.0)
# for microsolvation it's a good idea to have a higher density than normal to get enough solvent molecules
print(f"Microsolvated structure: {len(out)} atoms.")
out.write_xyz("acetonitrile-microsolvated.xyz")

view(out, width=300, height=300, padding=-1)
Microsolvated structure: 66 atoms.
image generated from notebook

Solid-liquid or solid-gas interfaces#

First, create a slab using the ASE fcc111 function

from ase.build import fcc111

rotation = "90x,0y,0z"  # sideview of slab
slab = ChemicalSystem.from_ase_atoms(fcc111("Al", size=(4, 6, 3), vacuum=15.0, orthogonal=True, periodic=True))
view(slab, width=300, height=300, direction="along_y", fixed_atom_size=False)
image generated from notebook
print("water surrounding an Al slab, from an approximate density")
out = packmol_around(slab, water, density=1.0)
printsummary(out)
out.write_xyz("al-water-pure.xyz")
view(out, width=300, height=300, direction="along_y", fixed_atom_size=False)
water surrounding an Al slab, from an approximate density
534 atoms, density = 1.325 g/cm^3, box = 11.455, 14.881, 34.677, formula = Al72H308O154
image generated from notebook
print("2-1 water-acetonitrile mixture surrounding an Al slab, from mole fractions and an approximate density")
out = packmol_around(slab, [water, acetonitrile], mole_fractions=[x_water, x_acetonitrile], density=density)
printsummary(out)
out.write_xyz("al-water-acetonitrile.xyz")
view(out, width=300, height=300, direction="along_y", fixed_atom_size=False)
2-1 water-acetonitrile mixture surrounding an Al slab, from mole fractions and an approximate density
468 atoms, density = 1.260 g/cm^3, box = 11.455, 14.881, 34.677, formula = C66H231Al72N33O66
image generated from notebook
from ase.build import surface

print("water surrounding non-orthorhombic Au(211) slab, from an approximate number of molecules")
print("NOTE: non-orthorhombic cell, results are approximate, requires AMS2025")
slab = surface("Au", (2, 1, 1), 6)
slab.center(vacuum=11.0, axis=2)
slab.set_pbc(True)
out = packmol_around(ChemicalSystem.from_ase_atoms(slab), [water], n_molecules=[32], tolerance=1.8)
out.write_xyz("Au211-water.xyz")
print(f"{out.lattice.vectors=}")
view(out, width=300, height=300, direction="along_y", fixed_atom_size=False)
water surrounding non-orthorhombic Au(211) slab, from an approximate number of molecules
NOTE: non-orthorhombic cell, results are approximate, requires AMS2025
out.lattice.vectors=array([[ 9.12315735,  0.        ,  0.        ],
       [ 3.64926294,  4.46941607,  0.        ],
       [ 0.        ,  0.        , 31.16109164]])
image generated from notebook

Pack inside voids in crystals#

Use the packmol_around function. You can decrease tolerance if you need to pack very tightly. The default value for tolerance is 2.0.

from ase.build import bulk

bulk_Al = ChemicalSystem.from_ase_atoms(bulk("Al", cubic=True).repeat((3, 3, 3)))
rotation = "-85x,5y,0z"
view(bulk_Al, width=300, height=300, direction="corner_z", fixed_atom_size=False)
image generated from notebook
out = packmol_around(
    current=bulk_Al,
    molecules=[ChemicalSystem.from_smiles("[H]"), ChemicalSystem.from_smiles("[He]")],
    n_molecules=[50, 20],
    tolerance=1.5,
)
printsummary(out)
out.write_xyz("al-bulk-with-h-he.xyz")
view(out, width=300, height=300, direction="corner_z", fixed_atom_size=False)
178 atoms, density = 2.819 g/cm^3, box = 12.150, 12.150, 12.150, formula = Al108H50He20
image generated from notebook

Bonds, atom properties (force field types, regions, …)#

The packmol() function accepts the arguments keep_bonds and keep_atom_properties. These options will keep the bonds defined for the constitutent molecules, as well as any atomic properties.

Packmol estimates the box size using standard elemental masses. Custom isotope masses are retained when keep_atom_properties=True, so the actual mass density can differ from the requested density.

The bonds and atom properties are easiest to see by printing the System block for an AMS job:

water = ChemicalSystem.from_smiles("O")
n2 = ChemicalSystem.from_smiles("N#N")

water.add_atom_to_region(0, "oxygen_atom")
water.atoms[1].mass = 2.014  # deuterium
water.bonds.remove_bonds_between_atoms(0, 1)  # delete the O-H bond (zero-based indices)
from scm.plams import AMSJob

out = packmol([water, n2], n_molecules=[2, 1], density=0.5)
print(AMSJob(molecule=out).get_input())
System
   Atoms
      O 3.878972 2.010742 4.718733 region=mol0,oxygen_atom
      H 3.0060099999999994 2.475347 4.770519 mass=2.014 region=mol0
      H 4.548649 2.740219 4.718631 region=mol0
      O 1.558575 4.027315 4.180336 region=mol0,oxygen_atom
      H 2.355371 4.495653 4.535836 mass=2.014 region=mol0
      H 0.915441 4.025336 4.933316 region=mol0
      N 3.923588 1.286183 1.021527 region=mol1
      N 4.968752 1.46364 1.382857 region=mol1
... output trimmed ....
      4 6 1
      7 8 3
   End
   Lattice
      5.9692549746 0 0
      0 5.9692549746 0
      0 0 5.9692549746
   End
End

By default, the packmol() function assigns regions called mol0, mol1, etc. to the different added molecules. The region_names option lets you set custom names.

out = packmol(
    [water, n2],
    n_molecules=[2, 1],
    density=0.5,
    region_names=["water", "nitrogen_molecule"],
)
print(AMSJob(molecule=out).get_input())
System
   Atoms
      O 2.934391 3.833586 3.139533 region=oxygen_atom,water
      H 3.486016 3.024419 2.992692 mass=2.014 region=water
      H 3.089479 4.389030999999999 2.3345279999999997 region=water
      O 0.982183 3.833184 1.999829 region=oxygen_atom,water
      H 1.185132 4.179977 1.09476 mass=2.014 region=water
      H 0.925664 4.641906 2.568492 region=water
      N 4.875662 4.087907 0.974893 region=nitrogen_molecule
      N 5.0611 5.00467 1.590991 region=nitrogen_molecule
... output trimmed ....
      4 6 1
      7 8 3
   End
   Lattice
      5.9692549746 0 0
      0 5.9692549746 0
      0 0 5.9692549746
   End
End

Below, we also set keep_atom_properties=False, this will remove the previous regions (in this example “oxygen_atom”) and mass.

out = packmol([water, n2], n_molecules=[2, 1], density=0.5, keep_atom_properties=False)
print(AMSJob(molecule=out).get_input())
System
   Atoms
      O 1.319763 4.091122 1.70527 region=mol0
      H 1.5991420000000003 3.541112 0.930648 region=mol0
      H 1.82534 4.9366 1.604467 region=mol0
      O 4.533636 3.836158 1.353628 region=mol0
      H 4.005669 3.2060000000000004 1.905675 region=mol0
      H 3.931439 4.610149 1.216153 region=mol0
      N 1.800653 4.188555 4.960393 region=mol1
      N 0.9832 4.952673 4.912283 region=mol1
... output trimmed ....
      4 6 1
      7 8 3
   End
   Lattice
      5.9692549746 0 0
      0 5.9692549746 0
      0 0 5.9692549746
   End
End

keep_bonds=False will additionally ignore any defined bonds:

out = packmol(
    [water, n2],
    n_molecules=[2, 1],
    density=0.5,
    region_names=["water", "nitrogen_molecule"],
    keep_bonds=False,
    keep_atom_properties=False,
)
print(AMSJob(molecule=out).get_input())
System
   Atoms
      O 2.498086 4.280675 2.093432 region=water
      H 3.233159 4.933933 2.209727 region=water
      H 1.803728 4.571353 2.736842 region=water
      O 4.314268 3.576884 1.017454 region=water
      H 4.925452 4.356022 1.016261 region=water
      H 4.915424 2.789987 1.020403 region=water
      N 1.00009 1.15278 1.468094 region=nitrogen_molecule
      N 2.116726 1.206794 1.400087 region=nitrogen_molecule
   End
   Lattice
      5.9692549746 0 0
      0 5.9692549746 0
      0 0 5.9692549746
   End
End

See also#

Python Script#

#!/usr/bin/env python
# coding: utf-8

# ## Initial imports

from typing import Any, Dict, Optional

from scm.base import ChemicalSystem, Lattice
from scm.plams import packmol, packmol_around, view


# ## Helper functions

def printsummary(mol: ChemicalSystem, details: Optional[Dict[str, Any]] = None) -> None:
    if details:
        density = details["density"]
    else:
        density = mol.density("g/cm3")
    s = f"{len(mol)} atoms, density = {density:.3f} g/cm^3"
    if mol.lattice.num_vectors:
        s += f", box = {mol.lattice.vectors[0, 0]:.3f}, {mol.lattice.vectors[1, 1]:.3f}, {mol.lattice.vectors[2, 2]:.3f}"
    s += f", formula = {mol.formula()}"
    if details:
        s += f"\n#added molecules per species: {details['n_molecules']}, mole fractions: {details['mole_fractions']}"
    print(s)


# ## Liquid water (fluid with 1 component)
# First, create the gasphase molecule:

water = ChemicalSystem.from_smiles("O")
view(water, width=200, height=200, picture_path="picture1.png")


print("pure liquid from approximate number of atoms and exact density (in g/cm^3), cubic box with auto-determined size")
out = packmol(water, n_atoms=194, density=1.0)
printsummary(out)
out.write_xyz("water-1.xyz")
view(out, width=300, height=300, padding=-2, picture_path="picture2.png")


print("pure liquid from approximate density (in g/cm^3) and an orthorhombic box")
out = packmol(water, density=1.0, box_bounds=[0.0, 0.0, 0.0, 8.0, 12.0, 14.0])
printsummary(out)
out.write_xyz("water-2.xyz")
view(out, width=300, height=300, padding=-2, picture_path="picture3.png")


print("pure liquid with explicit number of molecules and exact density")
out = packmol(water, n_molecules=64, density=1.0)
printsummary(out)
out.write_xyz("water-3.xyz")
view(out, width=300, height=300, padding=-2, picture_path="picture4.png")


print("pure liquid with explicit number of molecules and box")
out = packmol(water, n_molecules=64, box_bounds=[0.0, 0.0, 0.0, 12.0, 13.0, 14.0])
printsummary(out)
out.write_xyz("water-4.xyz")
view(out, width=300, height=300, padding=-2, picture_path="picture5.png")


print("water-5.xyz: pure liquid in non-orthorhombic box (requires AMS2025 or later)")
print("NOTE: Non-orthorhombic boxes may yield inaccurate results, always carefully check the output")
# You can pack inside any lattice using the packmol_around function
box = ChemicalSystem()
box.lattice = Lattice([[10.0, 2.0, -1.0], [-5.0, 8.0, 0.0], [0.0, -2.0, 11.0]])
out = packmol_around(box, molecules=[water], n_molecules=[32])
out.write_xyz("water-5.xyz")
view(out, width=300, height=300, padding=-2, picture_path="picture6.png")


print("Experimental feature (AMS2025): guess density for pure liquid")
print("Note: This density is meant to be equilibrated with NPT MD. It can be very inaccurate!")
out = packmol(water, n_atoms=100)
print(f"Guessed density: {out.density('kg/m3'):.2f} kg/m^3")
view(out, width=200, height=200, padding=-2, picture_path="picture7.png")


# ## Water-acetonitrile mixture (fluid with 2 or more components)
# Let's also create a single acetonitrile molecule:

acetonitrile = ChemicalSystem.from_smiles("CC#N")
view(acetonitrile, width=200, height=200, picture_path="picture8.png")


# Set the desired mole fractions and density. Here, the density is calculated as the weighted average of water (1.0 g/cm^3) and acetonitrile (0.76 g/cm^3) densities, but you could use any other density.

# MIXTURES
x_water = 0.666  # mole fraction
x_acetonitrile = 1 - x_water  # mole fraction
# weighted average of pure component densities
density = (x_water * 1.0 + x_acetonitrile * 0.76) / (x_water + x_acetonitrile)

print("MIXTURES")
print(f"x_water = {x_water:.3f}")
print(f"x_acetonitrile = {x_acetonitrile:.3f}")
print(f"target density = {density:.3f} g/cm^3")


# By setting ``return_details=True``, you can get information about the mole fractions of the returned system. They may not exactly match the mole fractions you put in.

print(
    "2-1 water-acetonitrile from approximate number of atoms and exact density (in g/cm^3), "
    "cubic box with auto-determined size"
)
out, details = packmol(
    molecules=[water, acetonitrile],
    mole_fractions=[x_water, x_acetonitrile],
    n_atoms=200,
    density=density,
    return_details=True,
)
printsummary(out, details)
out.write_xyz("water-acetonitrile-1.xyz")
view(out, width=300, height=300, padding=-2, picture_path="picture9.png")


# The ``details`` is a dictionary as follows:

for k, v in details.items():
    print(f"{k}: {v}")


print("2-1 water-acetonitrile from approximate density (in g/cm^3) and box bounds")
out, details = packmol(
    molecules=[water, acetonitrile],
    mole_fractions=[x_water, x_acetonitrile],
    box_bounds=[0, 0, 0, 13.2, 13.2, 13.2],
    density=density,
    return_details=True,
)
printsummary(out, details)
out.write_xyz("water-acetonitrile-2.xyz")
view(out, width=300, height=300, padding=-2, picture_path="picture10.png")


print("2-1 water-acetonitrile from explicit number of molecules and density, cubic box with auto-determined size")
out, details = packmol(
    molecules=[water, acetonitrile],
    n_molecules=[32, 16],
    density=density,
    return_details=True,
)
printsummary(out, details)
out.write_xyz("water-acetonitrile-3.xyz")
view(out, width=300, height=300, padding=-2, picture_path="picture11.png")


print("2-1 water-acetonitrile from explicit number of molecules and box")
out = packmol(
    molecules=[water, acetonitrile],
    n_molecules=[32, 16],
    box_bounds=[0, 0, 0, 13.2, 13.2, 13.2],
)
printsummary(out)
out.write_xyz("water-acetonitrile-4.xyz")
view(out, width=300, height=300, padding=-2, picture_path="picture12.png")


print("Experimental feature (AMS2025): guess density for mixture")
print("Note: This density is meant to be equilibrated with NPT MD. It can be very inaccurate!")
out = packmol([water, acetonitrile], mole_fractions=[x_water, x_acetonitrile], n_atoms=100)
print(f"Guessed density: {out.density('kg/m3'):.2f} kg/m^3")
view(out, width=200, height=200, padding=-2, picture_path="picture13.png")


# ## NaCl solution (solvent with 1 or more solutes)

sodium = ChemicalSystem.from_smiles("[Na+]")
chloride = ChemicalSystem.from_smiles("[Cl-]")


# For dilute solutions, it can be useful to specify the number of solute species, and fill up the rest of the box with solvent.
# 
# The required number of solvent molecules are then added to fill up the box to the target overall density or number of atoms.
# 
# This feature can be used if exactly **one** of the elements of the ``n_molecules`` list is None.

print(
    "NaCl solution from approximate density (in g/cm^3) and box bounds, and auto-determined number of solvent molecules"
)
out = packmol(
    [sodium, chloride, water],
    n_molecules=[5, 5, None],
    density=1.029,
    box_bounds=[0, 0, 0, 19, 19, 19],
)
printsummary(out)
out.write_xyz("sodium-chloride-solution-1.xyz")
view(out, width=300, height=300, padding=-3, fixed_atom_size=False, picture_path="picture14.png")


# Specify the total number of atoms instead of box bounds, and auto-determine a cubic box:

print("NaCl solution from approximate number of atoms and density:")
out = packmol([sodium, chloride, water], n_molecules=[5, 5, None], density=1.029, n_atoms=500)
printsummary(out)
out.write_xyz("sodium-chloride-solution-2.xyz")
view(out, width=300, height=300, padding=-3, fixed_atom_size=False, picture_path="picture15.png")


# Specify the total number of atoms instead of the density (less useful option):

print("NaCl solution from approximate number of atoms and box_bounds:")
out = packmol(
    [sodium, chloride, water],
    n_molecules=[5, 5, None],
    n_atoms=500,
    box_bounds=[0, 0, 0, 12, 18, 24],
)
printsummary(out)
out.write_xyz("sodium-chloride-solution-3.xyz")
view(out, width=300, height=300, padding=-3, fixed_atom_size=False, picture_path="picture16.png")


# ## Pack inside sphere
# 
# Set ``sphere=True`` to pack in a sphere (non-periodic) instead of in a periodic box. The sphere will be centered near the origin.

print("water in a sphere from exact density and number of molecules")
out, details = packmol(molecules=[water], n_molecules=[100], density=1.0, return_details=True, sphere=True)
printsummary(out, details)
print(f"Radius  of sphere: {details['radius']:.3f} ang.")
print(f"Center of mass xyz (ang): {out.center_of_mass()}")
out.write_xyz("water-sphere.xyz")
view(out, width=300, height=300, padding=-3, picture_path="picture17.png")


print(
    "2-1 water-acetonitrile in a sphere from exact density (in g/cm^3) and "
    "approximate number of atoms and mole fractions"
)
out, details = packmol(
    molecules=[water, acetonitrile],
    mole_fractions=[x_water, x_acetonitrile],
    n_atoms=500,
    density=density,
    return_details=True,
    sphere=True,
)
printsummary(out, details)
out.write_xyz("water-acetonitrile-sphere.xyz")
view(out, width=300, height=300, padding=-3, picture_path="picture18.png")


# ## Packing ions, total system charge
# 
# The total system charge will be sum of the charges of the constituent molecules.
# 
# For a ``ChemicalSystem``, ``system.charge`` specifies the total charge:

ammonium = ChemicalSystem.from_smiles("[NH4+]")  # ammonium.charge == +1
chloride = ChemicalSystem.from_smiles("[Cl-]")  # chloride.charge == -1
print("3 water molecules, 3 ammonium, 1 chloride (non-periodic)")
print("Initial charges:")
print(f"Water: {water.charge}")
print(f"Ammonium: {ammonium.charge}")
print(f"Chloride: {chloride.charge}")
out = packmol(molecules=[water, ammonium, chloride], n_molecules=[3, 3, 1], density=0.4, sphere=True)
tot_charge = out.charge
print(f"Total charge of packmol-generated system: {tot_charge}")
out.write_xyz("water-ammonium-chloride.xyz")
view(out, width=300, height=300, picture_path="picture19.png")


# ## Microsolvation
# ``packmol_microsolvation`` can create a microsolvation sphere around a solute.

from scm.plams import packmol_microsolvation

out = packmol_microsolvation(solute=acetonitrile, solvent=water, density=1.5, threshold=4.0)
# for microsolvation it's a good idea to have a higher density than normal to get enough solvent molecules
print(f"Microsolvated structure: {len(out)} atoms.")
out.write_xyz("acetonitrile-microsolvated.xyz")

view(out, width=300, height=300, padding=-1, picture_path="picture20.png")


# ## Solid-liquid or solid-gas interfaces
# First, create a slab using the ASE ``fcc111`` function

from ase.build import fcc111

rotation = "90x,0y,0z"  # sideview of slab
slab = ChemicalSystem.from_ase_atoms(fcc111("Al", size=(4, 6, 3), vacuum=15.0, orthogonal=True, periodic=True))
view(slab, width=300, height=300, direction="along_y", fixed_atom_size=False, picture_path="picture21.png")


print("water surrounding an Al slab, from an approximate density")
out = packmol_around(slab, water, density=1.0)
printsummary(out)
out.write_xyz("al-water-pure.xyz")
view(out, width=300, height=300, direction="along_y", fixed_atom_size=False, picture_path="picture22.png")


print("2-1 water-acetonitrile mixture surrounding an Al slab, from mole fractions and an approximate density")
out = packmol_around(slab, [water, acetonitrile], mole_fractions=[x_water, x_acetonitrile], density=density)
printsummary(out)
out.write_xyz("al-water-acetonitrile.xyz")
view(out, width=300, height=300, direction="along_y", fixed_atom_size=False, picture_path="picture23.png")


from ase.build import surface

print("water surrounding non-orthorhombic Au(211) slab, from an approximate number of molecules")
print("NOTE: non-orthorhombic cell, results are approximate, requires AMS2025")
slab = surface("Au", (2, 1, 1), 6)
slab.center(vacuum=11.0, axis=2)
slab.set_pbc(True)
out = packmol_around(ChemicalSystem.from_ase_atoms(slab), [water], n_molecules=[32], tolerance=1.8)
out.write_xyz("Au211-water.xyz")
print(f"{out.lattice.vectors=}")
view(out, width=300, height=300, direction="along_y", fixed_atom_size=False, picture_path="picture24.png")


# ## Pack inside voids in crystals
# 
# Use the ``packmol_around`` function. You can decrease ``tolerance`` if you need to pack very tightly. The default value for ``tolerance`` is 2.0.

from ase.build import bulk

bulk_Al = ChemicalSystem.from_ase_atoms(bulk("Al", cubic=True).repeat((3, 3, 3)))
rotation = "-85x,5y,0z"
view(bulk_Al, width=300, height=300, direction="corner_z", fixed_atom_size=False, picture_path="picture25.png")


out = packmol_around(
    current=bulk_Al,
    molecules=[ChemicalSystem.from_smiles("[H]"), ChemicalSystem.from_smiles("[He]")],
    n_molecules=[50, 20],
    tolerance=1.5,
)
printsummary(out)
out.write_xyz("al-bulk-with-h-he.xyz")
view(out, width=300, height=300, direction="corner_z", fixed_atom_size=False, picture_path="picture26.png")


# ## Bonds, atom properties (force field types, regions, ...)
# 
# The ``packmol()`` function accepts the arguments ``keep_bonds`` and ``keep_atom_properties``. These options will keep the bonds defined for the constitutent molecules, as well as any atomic properties.
# 
# Packmol estimates the box size using standard elemental masses. Custom isotope masses are retained when `keep_atom_properties=True`, so the actual mass density can differ from the requested density.
# 
# The bonds and atom properties are easiest to see by printing the System block for an AMS job:

water = ChemicalSystem.from_smiles("O")
n2 = ChemicalSystem.from_smiles("N#N")

water.add_atom_to_region(0, "oxygen_atom")
water.atoms[1].mass = 2.014  # deuterium
water.bonds.remove_bonds_between_atoms(0, 1)  # delete the O-H bond (zero-based indices)


from scm.plams import AMSJob

out = packmol([water, n2], n_molecules=[2, 1], density=0.5)
print(AMSJob(molecule=out).get_input())


# By default, the ``packmol()`` function assigns regions called ``mol0``, ``mol1``, etc. to the different added molecules. The ``region_names`` option lets you set custom names. 

out = packmol(
    [water, n2],
    n_molecules=[2, 1],
    density=0.5,
    region_names=["water", "nitrogen_molecule"],
)
print(AMSJob(molecule=out).get_input())


# Below, we also set ``keep_atom_properties=False``, this will remove the previous regions (in this example "oxygen_atom") and mass. 

out = packmol([water, n2], n_molecules=[2, 1], density=0.5, keep_atom_properties=False)
print(AMSJob(molecule=out).get_input())


# ``keep_bonds=False`` will additionally ignore any defined bonds:

out = packmol(
    [water, n2],
    n_molecules=[2, 1],
    density=0.5,
    region_names=["water", "nitrogen_molecule"],
    keep_bonds=False,
    keep_atom_properties=False,
)
print(AMSJob(molecule=out).get_input())