
Packmol
- 1 installs
- 404 repo stars
- Updated August 5, 2026
- aiskillstore/marketplace
packmol is a Claude Code skill that builds initial molecular-dynamics configurations by generating Packmol input files that pack molecules under spatial constraints.
About
packmol is a Claude Code skill for building initial configurations for molecular dynamics simulations using Packmol. It generates Packmol input files that pack molecules into boxes, spheres, cylinders and ellipsoids, solvate proteins with water and ions, and build liquid-liquid interfaces without atom overlaps. A computational chemist uses it to set up MD starting structures from a natural-language request.
- Builds initial molecular-dynamics configurations with Packmol input files
- Packs molecules in boxes, solvates proteins, and builds liquid-liquid interfaces
- Ships 6 helper scripts, 8 examples, 3 templates, and 4 reference docs
Packmol by the numbers
- 1 all-time installs (skills.sh)
- Ranked #1,803 of 2,064 Data Science & ML skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
packmol capabilities & compatibility
- Capabilities
- input generation · simulation setup · data analysis
- Use cases
- data analysis
- Pricing
- Free
What packmol says it does
Build initial configurations for molecular dynamics simulations using Packmol.
Packmol creates initial configurations for MD simulations by packing molecules according to spatial constraints.
npx skills add https://github.com/aiskillstore/marketplace --skill packmolAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| repo stars | ★ 404 |
| Last updated | August 5, 2026 |
| Repository | aiskillstore/marketplace ↗ |
What it does
Generate Packmol input files to pack molecules, solvate proteins, and build MD simulation starting structures.
Who is it for?
Computational chemists building MD starting structures, solvating proteins, or packing molecules
Skip if: Tasks unrelated to molecular packing or MD setup
When should I use this skill?
creating a packmol input, packing molecules, solvating a protein, or building an initial MD configuration
What you get
A valid Packmol input file is produced that packs molecules into the requested geometry without overlaps.
- Packmol .inp input files
- solvated/packed PDB configurations
By the numbers
- 6 helper Python scripts
- 8 example input files
- 3 templates and 4 reference docs
Files
Packmol Skill
Build initial configurations for molecular dynamics simulations using Packmol.
What is Packmol?
Packmol creates initial configurations for MD simulations by packing molecules according to spatial constraints. It places molecules in boxes, around proteins, at interfaces, or within complex geometries (spheres, cylinders, ellipsoids) while ensuring no overlaps.
Installation
Install Packmol via pip:
pip install packmolVerify installation:
packmol -hFor more installation options, see the Packmol website.
Quick Start
Basic Box Packing
Create a simple box of water molecules:
# water_box.inp
tolerance 2.0
filetype pdb
output water_box.pdb
structure water.pdb
number 1000
inside box 0. 0. 0. 40. 40. 40.
end structureRun Packmol:
packmol < water_box.inpSolvate a Protein
Solvate a protein with water and ions:
# solvation.inp
tolerance 2.0
filetype pdb
output solvated.pdb
structure protein.pdb
number 1
fixed 0. 0. 0. 0. 0. 0.
center
end structure
structure water.pdb
number 5000
inside box -10. -10. -10. 50. 50. 50.
end structure
structure SOD.pdb
number 10
inside box -10. -10. -10. 50. 50. 50.
end structure
structure CLA.pdb
number 10
inside box -10. -10. -10. 50. 50. 50.
end structureLiquid-Liquid Interface
Build a water/chloroform interface:
# interface.inp
tolerance 2.0
filetype pdb
output interface.pdb
pbc -20. -20. -30. 20. 20. 30.
structure water.pdb
number 1000
below plane 0. 0. 1. 0.
end structure
structure chloroform.pdb
number 200
above plane 0. 0. 1. 0.
end structureCore Concepts
Input File Structure
Every Packmol input file requires:
1. tolerance: Minimum distance between atoms (Å) 2. output: Output filename 3. filetype: Format (pdb, xyz, tinker) 4. structure blocks: Define molecules to place
Structure Block Syntax
structure molecule.pdb
number <N> # Number of molecules
inside|outside <constraint> # Spatial constraint
[optional parameters]
end structureCommon Constraint Types
- box:
inside box xmin ymin zmin xmax ymax zmax - sphere:
inside sphere xcenter ycenter zcenter radius - cylinder:
inside cylinder x1 y1 z1 dx dy dz radius length - plane:
above plane a b c dorbelow plane a b c d - ellipsoid:
inside ellipsoid xc yc zc xa yb zc scale
See references/constraints.md for complete constraint documentation.
Workflows
1. Basic Molecular Packing
Build boxes with multiple molecule types.
Example: Water/ethanol mixture
tolerance 2.0
output mixture.pdb
filetype pdb
structure water.pdb
number 800
inside box 0. 0. 0. 40. 40. 40.
end structure
structure ethanol.pdb
number 200
inside box 0. 0. 0. 40. 40. 40.
end structure2. Protein Solvation
Solvate biomolecules with water and ions for neutralization.
Key parameters:
- Use
fixedwithcenterfor the protein - Add Na+/Cl- ions for neutrality and concentration
- Calculate box size based on protein + solvent shell
Automatic solvation helper:
python scripts/solvate_helper.py protein.pdb --shell 15.0 --charge +43. Interface Systems
Build liquid-liquid or liquid-vapor interfaces using plane constraints.
Example: Water/hexane interface
tolerance 2.0
output interface.pdb
pbc -20. -20. -30. 20. 20. 30.
structure water.pdb
number 1000
below plane 0. 0. 1. 0.
end structure
structure hexane.pdb
number 200
above plane 0. 0. 1. 0.
end structure4. Advanced Constraints
Use spherical, cylindrical, or ellipsoidal constraints for complex geometries.
Example: Spherical vesicle
structure lipid.pdb
number 2000
inside sphere 0. 0. 0. 40.
atoms 1 2 3 4
outside sphere 0. 0. 0. 35.
end atoms
end structure
structure water.pdb
number 2000
inside sphere 0. 0. 0. 35.
end structure
structure water.pdb
number 5000
outside sphere 0. 0. 0. 45.
end structureInput Parameters
Required Parameters
- tolerance
<distance>: Minimum intermolecular distance (Å). Default: 2.0 for all-atom - output
<filename>: Output file name - filetype
<format>: pdb, xyz, or tinker
Optional Parameters
- pbc
<dimensions>: Periodic boundary conditions (e.g.,pbc 30. 30. 60.) - seed
<integer>: Random seed for reproducibility - discale
<factor>: Distance scaling for optimization (default: 1.0) - maxit
<N>: Maximum iterations (default: 20) - precision
<value>: Convergence precision (default: 0.01)
See references/parameters.md for complete parameter reference.
Structure Block Options
Positioning Options
- number: Molecule count
- inside/outside: Spatial constraint
- fixed: Fix position and rotation (6 parameters: x, y, z, α, β, γ)
- center: Use center of mass for positioning
Rotation Constraints
constrain_rotation x 180. 20. # Constrain rotation around x-axis
constrain_rotation y 180. 20. # Constrain rotation around y-axis
constrain_rotation z 180. 20. # Constrain rotation around z-axisAtom Selection
Apply constraints to specific atoms within molecules:
structure molecule.pdb
number 100
inside box 0. 0. 0. 30. 30. 30.
atoms 1 2 3
inside box 0. 0. 25. 30. 30. 30.
end atoms
end structureRunning Packmol
Basic Execution
packmol < input.inpOutput Interpretation
Success message:
------------------------------
Success!
Final objective function value: .22503E-01
Maximum violation of target distance: 0.000000
Maximum violation of the constraints: .78985E-02
------------------------------Check that both violations are < 0.01 for a valid solution.
Validation
Check Overlaps
python scripts/check_overlaps.py output.pdb --tolerance 2.0Verify Success
python scripts/verify_success.py input.inp output.pdbAnalyze Density
python scripts/analyze_density.py output.pdbValidate Input
python scripts/validate_input.py input.inpTroubleshooting
Common Issues
1. "Killed" error: System too large
- Reduce number of molecules
- Use restart files to build incrementally
- See references/troubleshooting.md
2. No convergence:
- Try
discale 1.5to scale distances - Reduce molecule count
- Simplify constraints
- Increase
maxit
3. Strange geometries:
- Add
checkkeyword to validate constraints without packing - Verify constraint syntax
- Check for conflicting constraints
4. Incorrect atom count:
- Verify structure files are readable
- Check for duplicate atoms in input files
- Validate with
scripts/validate_input.py
See references/troubleshooting.md for detailed solutions.
Examples
Explore example input files in the examples/ directory:
- Basic: examples/basic/ - Simple boxes and mixtures
- Solvation: examples/solvation/ - Proteins with water and ions
- Interface: examples/interface/ - Liquid-liquid interfaces
- Advanced: examples/advanced/ - Vesicles, bilayers, complex geometries
Templates
Use templates in templates/ as starting points:
- [templates/basic_template.inp](templates/basic_template.inp): Minimal template for simple packing
- [templates/solvation_template.inp](templates/solvation_template.inp): Protein solvation setup
- [templates/interface_template.inp](templates/interface_template.inp): Interface systems
Helper Scripts
Use Python scripts in scripts/ for automation:
- generate_input.py: Generate inputs programmatically
- validate_input.py: Validate input syntax before running
- check_overlaps.py: Detect atomic overlaps in output
- analyze_density.py: Calculate system density
- solvate_helper.py: Automatic protein solvation setup
- verify_success.py: Verify Packmol completed successfully
Advanced Topics
Periodic Boundary Conditions
Use pbc for periodic systems:
pbc 30. 30. 60. # or pbc xmin ymin zmin xmax ymax zmaxRestart Files
Build large systems incrementally:
structure water.pdb
number 1000
inside box 0. 0. 0. 40. 40. 40.
restart_to water1.pack
end structureThen restart:
structure water.pdb
number 1000
restart_from water1.pack
end structureAtom-Specific Radii
Set different radii for multiscale models:
structure molecule.pdb
number 100
radius 1.5 # All atoms
end structure
structure molecule.pdb
number 100
atoms 1 2
radius 1.5 # Specific atoms
end atoms
end structureConstraint Validation
Validate constraints without packing:
structure molecule.pdb
number 100
inside box 0. 0. 0. 30. 30. 30.
check
end structureBest Practices
1. Start simple: Test with few molecules before scaling up 2. Use appropriate tolerance: 2.0 Å for all-atom, larger for coarse-grained 3. Check constraints: Add check keyword to validate regions 4. Validate output: Use scripts to check overlaps and density 5. Reproducibility: Set seed for repeatable results 6. Large systems: Use restart files or build in stages 7. Box size: Allow 10-15 Å padding around solutes for solvation
Tips for Common Use Cases
Protein Solvation
- Add 10-15 Å solvent shell around protein
- Calculate ions for neutrality:
N_ions = charge / e - Add salt ions for desired concentration (e.g., 0.15 M NaCl)
- Use
fixedwithcenterfor protein positioning
Mixed Solvents
- Calculate total number of molecules from desired molar ratios
- Use same tolerance for all components
- Test with small systems first
Membrane Systems
- Use
constrain_rotationto orient lipids - Build in stages: lipids first, then water
- Consider using specialized membrane builders for large systems
Nanotubes/Pores
- Use
cylinderconstraint for pore region - Combine with
outsideconstraint for bulk region - May need atom selection for specific molecule orientations
Resources
- Official documentation: Packmol User Guide
- Examples: Packmol Examples
- GitHub: Packmol Repository
- Paper: Martínez et al. J Comput Chem 2009
References
For detailed information on specific topics, see:
- constraints.md - Complete constraint syntax and examples
- parameters.md - All input parameters and options
- file_formats.md - File format specifications
- troubleshooting.md - Problem-solving guide
# Water-Urea Mixture Example
#
# This example demonstrates packing multiple molecule types
# to create a mixed solvent system.
#
# Output: A 40 × 40 × 40 Å box with water and urea
# Usage: packmol < mixture.inp
# Required parameters
tolerance 2.0
filetype pdb
output mixture.pdb
# Water molecules (80% of mixture)
structure water.pdb
number 800
inside box 0. 0. 0. 40. 40. 40.
end structure
# Urea molecules (20% of mixture)
structure urea.pdb
number 200
inside box 0. 0. 0. 40. 40. 40.
end structure
# ============================================================================
# Notes
# ============================================================================
#
# This creates a 8:2 molar ratio of water:urea, commonly used
# in protein denaturation studies.
#
# Expected results:
# - Output file: mixture.pdb
# - Total molecules: 1000 (800 water + 200 urea)
# - Box dimensions: 40 × 40 × 40 Å
#
# Tips:
# - Adjust the ratio by changing the 'number' values
# - Use the same tolerance for all molecule types
# - Make sure all structure files (water.pdb, urea.pdb) exist
Basic Packmol Examples
This directory contains simple Packmol input files demonstrating basic molecular packing.
Examples
1. simple_box.inp
Purpose: Create a box containing a single type of molecule
Description: This is the minimal Packmol input file. It packs 1000 water molecules into a 40 × 40 × 40 Å box.
Use case: Starting point for creating pure solvent boxes, understanding basic Packmol syntax
Requirements:
water.pdb- PDB file with a single water molecule
To run:
packmol < simple_box.inpExpected output: water_box.pdb with 3000 atoms (1000 water molecules)
Modifications:
- Change
number 1000to adjust molecule count - Change box dimensions (
0. 0. 0. 40. 40. 40.) for different box sizes - Replace
water.pdbwith any other molecule file
Tips:
- For 1.0 g/cm³ water density, use ~1200 water molecules in this box size
- Adjust
tolerancebased on your model (2.0 Å for all-atom)
---
2. mixture.inp
Purpose: Create a box with multiple molecule types
Description: Demonstrates packing two different molecule types (water and urea) in the same box with an 8:2 molar ratio.
Use case: Mixed solvent systems, cosolvents, additive solutions
Requirements:
water.pdb- PDB file with a single water moleculeurea.pdb- PDB file with a single urea molecule
To run:
packmol < mixture.inpExpected output: mixture.pdb with 1000 total molecules (800 water + 200 urea)
Modifications:
- Adjust molar ratios by changing
numbervalues - Replace molecule types for different mixtures
- Common mixtures: water/ethanol, water/glycerol, water/DMSO
Tips:
- Maintain total number appropriate for desired density
- Use same tolerance for all components
- Test with small systems first
---
General Notes
Preparing Molecule Files
Each .pdb file should contain:
- A single molecule (or repeat unit)
- Proper atom coordinates
- Correct element names in columns 13-14
- Optional: CONECT records for bonds
Common Issues
1. "ERROR: Opening file": Ensure all .pdb files exist in current directory 2. Low density: Increase number values to add more molecules 3. High density: Decrease number values or increase box size 4. No convergence: Try increasing tolerance or reducing molecule count
Typical Densities
For 40 × 40 × 40 Å box (64,000 ų volume):
- Water (1.0 g/cm³): ~1200 molecules
- Water/urea mixtures: ~1000-1100 total molecules
- Pure organic solvents: Varies by molecular weight
Next Steps
After mastering these basic examples, explore:
- Solvation examples: Add biomolecules to solvent boxes
- Interface examples: Create liquid-liquid interfaces
- Advanced examples: Complex geometries like vesicles and cylinders
---
Testing Your Setup
To verify Packmol is working correctly:
1. Create a minimal water.pdb file with coordinates:
ATOM 1 O HOH 1 0.000 0.000 0.000 1.00 0.00
ATOM 2 H1 HOH 1 0.959 0.000 -0.243 1.00 0.00
ATOM 3 H2 HOH 1 -0.240 0.000 -0.927 1.00 0.00
END2. Run packmol < simple_box.inp
3. Check for success message in output
4. Verify output file water_box.pdb was created
For more help, see the main SKILL.md or references.
# Simple Box Example - Water Box
#
# This example demonstrates the minimal Packmol input file
# to create a box of 1000 water molecules.
#
# Output: A 40 x 40 x 40 Å box containing 1000 water molecules
# Usage: packmol < simple_box.inp
# Required parameters
tolerance 2.0
filetype pdb
output water_box.pdb
# Structure definition
structure water.pdb
number 1000
inside box 0. 0. 0. 40. 40. 40.
end structure
# ============================================================================
# Notes
# ============================================================================
#
# To run this example, you need a water.pdb file with a single water molecule.
#
# Expected results:
# - Output file: water_box.pdb
# - Number of atoms: 3000 (1000 water molecules × 3 atoms)
# - Box dimensions: 40 × 40 × 40 Å
# - Density: ~0.83 g/cm³ (adjust number of waters for 1.0 g/cm³)
#
# To get 1.0 g/cm³ density in a 40×40×40 Å box, use ~1200 water molecules.
# Liquid-Liquid Interface Example
#
# This example creates a water/chloroform interface, commonly used
# to study partitioning, solvation, and interfacial phenomena.
#
# System: Water phase below, chloroform phase above
# Interface: Horizontal plane at z = 0
# Usage: packmol < liquid_liquid.inp
# Required parameters
tolerance 2.0
filetype pdb
output interface.pdb
# Periodic boundary conditions
pbc -20. -20. -30. 20. 20. 30.
# Water phase (below interface at z=0)
structure water.pdb
number 1000
below plane 0. 0. 1. 0.
chain W
end structure
# Chloroform phase (above interface at z=0)
structure chloroform.pdb
number 200
above plane 0. 0. 1. 0.
chain C
end structure
# ============================================================================
# Notes
# ============================================================================
#
# This creates a liquid-liquid interface with:
# - Water phase: z < 0 (40×40×30 Å = 48,000 ų)
# - Chloroform phase: z > 0 (40×40×30 Å = 48,000 ų)
# - Interface plane: z = 0 (horizontal)
# - Periodic in x, y, z directions
#
# Expected densities:
# - Water: ~1000 molecules / 48,000 ų ≈ 1.0 g/cm³ ✓
# - Chloroform: ~200 molecules / 48,000 ų (appropriate density)
#
# Plane equation explanation:
# Plane: 0*x + 0*y + 1*z = 0 → z = 0
# - below plane: z < 0 (water region)
# - above plane: z > 0 (chloroform region)
#
# To adapt for other solvent pairs:
# 1. Adjust molecule counts for desired density
# (density ~1 g/cm³ for most organic liquids)
# 2. Change box dimensions for different system sizes
# 3. Modify plane position if needed
#
# Common modifications:
# - Add salt to water phase: include SOD.pdb and CLA.pdb below plane
# - Add solute: place at interface with specific z coordinate
# - Different solvents: hexane, octanol, benzene, etc.
#
# Required structure files:
# - water.pdb: Single water molecule
# - chloroform.pdb: Single chloroform molecule
#
# Expected results:
# - Output file: interface.pdb
# - Clear interface at z = 0
# - Water molecules below, chloroform molecules above
# - No mixing across interface (initial configuration)
Interface Examples
Examples for creating liquid-liquid and liquid-vapor interfaces using plane constraints.
Examples
liquid_liquid.inp
Purpose: Create a water/chloroform liquid-liquid interface
Description: Builds two immiscible liquid phases with a planar interface, commonly used to study partitioning, solvation, and interfacial phenomena.
Use case:
- Partition coefficient calculations
- Interfacial tension studies
- Surfactant behavior at interfaces
- Solvent extraction systems
System setup:
- Water phase: 1000 molecules (z < 0)
- Chloroform phase: 200 molecules (z > 0)
- Interface: Horizontal plane at z = 0
- Periodic boundaries: 40 × 40 × 60 Å box
Requirements:
water.pdb- Single water moleculechloroform.pdb- Single chloroform molecule
To run:
packmol < liquid_liquid.inpExpected output:
interface.pdbwith ~3600 atoms- Clear interface at z = 0
- Water below, chloroform above
Modifications:
1. Different solvent pairs:
# Water/hexane
structure water.pdb
number 1000
below plane 0. 0. 1. 0.
end structure
structure hexane.pdb
number 200
above plane 0. 0. 1. 0.
end structure2. Add salt to aqueous phase:
# Add below interface with water
structure SOD.pdb
number 10
below plane 0. 0. 1. 0.
end structure
structure CLA.pdb
number 10
below plane 0. 0. 1. 0.
end structure3. Adjust interface position:
# Interface at z = 30 (in 60 Å box)
structure water.pdb
number 1000
below plane 0. 0. 1. 30.
end structure
structure chloroform.pdb
number 200
above plane 0. 0. 1. 30.
end structure4. Inclined interface:
# 45° angle: plane z = -x
structure water.pdb
number 1000
below plane 1. 0. 1. 0.
end structureTips:
- Use periodic boundaries in all directions
- Make z-dimension 1.5-2× larger than x,y for stability
- Test with small systems first
- Verify interfacial area matches your needs
---
benzene_water.inp
Purpose: Create a water/benzene liquid-liquid interface
Description: Builds an interface between water and benzene, a classic aromatic solvent system. Benzene is planar and non-polar, making it ideal for studying π-interactions, solvation of aromatic compounds, and interfacial behavior of non-polar solvents.
Use case:
- Aromatic solvent extraction studies
- Partitioning of organic compounds
- Interfacial tension of aromatic systems
- Benchmark for non-polar solvent simulations
- Studies of π-π interactions at interfaces
System setup:
- Water phase: 1000 molecules (z < 0)
- Benzene phase: 220 molecules (z > 0)
- Interface: Horizontal plane at z = 0
- Periodic boundaries: 40 × 40 × 60 Å box
Requirements:
water.pdb- Single water moleculebenzene.pdb- Single benzene molecule (C₆H₆)
To run:
packmol < benzene_water.inpExpected output:
benzene_water.pdbwith ~5,640 atoms- Clear interface at z = 0
- Water below, benzene above
- Planar benzene molecules randomly oriented
Special considerations:
- Benzene is planar - molecules may align parallel to interface
- Lower density than water (0.88 vs 1.0 g/cm³)
- All atoms coplanar in each benzene molecule
- Volume per benzene molecule: ~148 ų
Modifications:
1. Different aromatic solvents:
# Water/toluene
structure water.pdb
number 1000
below plane 0. 0. 1. 0.
end structure
structure toluene.pdb
number 180
above plane 0. 0. 1. 0.
end structure2. Benzene orientation control (for alignment studies):
# Keep benzene planar with interface
structure benzene.pdb
number 220
above plane 0. 0. 1. 0.
constrain rotation x 0. 10.
constrain rotation y 0. 10.
end structure3. Add solute at interface:
# Place aromatic solute at interface
structure phenol.pdb
number 10
inside box -10. -10. -2. 10. 10. 2.
end structure---
Interface Theory
Plane Equation
Plane constraints use the equation: ax + by + cz = d
Parameters:
(a, b, c): Normal vector to plane (doesn't need normalization)d: Distance from origin along normal
Examples:
1. Horizontal plane at z = 0:
Plane: 0*x + 0*y + 1*z = 0
Packmol: plane 0. 0. 1. 0.2. Horizontal plane at z = 10:
Plane: 0*x + 0*y + 1*z = 10
Packmol: plane 0. 0. 1. 10.3. Vertical plane:
Plane: 1*x + 0*y + 0*z = 0 (yz plane at x=0)
Packmol: plane 1. 0. 0. 0.4. 45° inclined plane:
Plane: 1*x + 0*y + 1*z = 0 (z = -x)
Packmol: plane 1. 0. 1. 0.Molecule Placement
- below plane:
ax + by + cz < d - above plane:
ax + by + cz > d
Periodic Box Setup
For interface centered in box:
Box: 40 × 40 × 60 Å
Interface: z = 30 (middle)
PBC: 0. 0. 0. 40. 40. 60.
or: pbc 0. 0. 0. 40. 40. 60.
Phase 1 (below): z < 30
Phase 2 (above): z > 30For symmetric interface at origin:
Box: -20 to 20 in x,y, -30 to 30 in z (40×40×60 Å)
Interface: z = 0
PBC: -20. -20. -30. 20. 20. 30.
Phase 1 (below): z < 0 (30 Å region)
Phase 2 (above): z > 0 (30 Å region)---
Common Interface Systems
Water/Oil Interface
Typical systems:
- Water/hexane: Non-polar solvent
- Water/chloroform: Dense organic phase
- Water/octanol: Partition coefficient studies
- Water/benzene: Aromatic solvent (see benzene_water.inp example above)
- Molecular structure: Planar C₆H₆ ring
- Density: 0.88 g/cm³ (lighter than water)
- Applications: Aromatic partitioning, π-interaction studies
Example: Water/octanol
tolerance 2.0
filetype pdb
output water_octanol.pdb
pbc -20. -20. -30. 20. 20. 30.
structure water.pdb
number 1000
below plane 0. 0. 1. 0.
end structure
structure octanol.pdb
number 150
above plane 0. 0. 1. 0.
end structureLiquid/Vapor Interface
Purpose: Study surface tension, evaporation
Setup: Only one phase, vacuum above
tolerance 2.0
filetype pdb
output liquid_vapor.pdb
pbc 0. 0. 0. 40. 40. 80.
structure water.pdb
number 1000
below plane 0. 0. 1. 40. # All water at z < 40
above plane 0. 0. 1. 10. # But above z = 10 (slab)
end structureNote: Creates vacuum region for z > 40
Bilayer Systems
Purpose: Membrane simulations
Setup: Two interfaces with water on both sides
tolerance 2.0
filetype pdb
output bilayer.pdb
pbc 0. 0. 0. 60. 60. 80.
# Lower leaflet (lipids oriented)
structure lipid.pdb
number 200
above plane 0. 0. 1. 25.
below plane 0. 0. 1. 35.
constrain_rotation x 0. 10.
constrain_rotation y 0. 10.
end structure
# Water below membrane
structure water.pdb
number 2000
below plane 0. 0. 1. 25.
end structure
# Water above membrane
structure water.pdb
number 2000
above plane 0. 0. 1. 55.
end structure---
Density Calculations
Estimating Molecule Count
For a liquid phase:
V = L × W × H (ų)
N_molecules = V / V_per_molecule
For water at 1.0 g/cm³:
V_per_molecule ≈ 30 ų
N = V / 30
For chloroform at 1.5 g/cm³:
V_per_molecule = (MW / density) / NA
MW = 119.38 g/mol
density = 1.48 g/cm³
V_per_molecule ≈ 134 ų
N = V / 134Example calculations:
For 40×40×30 Å phase (48,000 ų):
- Water: 48,000 / 30 ≈ 1600 molecules
- Chloroform: 48,000 / 134 ≈ 360 molecules
Verifying Density
# Check density after packing
python scripts/analyze_density.py interface.pdb
# Should get ~1.0 g/cm³ for water
# and appropriate density for other solvent---
Common Issues
Interface Mixing
Symptom: Molecules from different phases mix at interface
Cause: Natural - Packmol creates initial configuration, MD will equilibrate
Solution:
- Some initial mixing is OK
- MD equilibration will form proper interface
- Or use
constrain_rotationfor surfactants
Wrong Phase Distribution
Symptom: Molecules on wrong side of interface
Cause: Plane equation error
Solution:
- Verify plane equation:
ax + by + cz = d - Test with 1-2 molecules first
- Use
checkkeyword to validate
Poor Interface Definition
Symptom: Interface not well-defined
Cause: Too few molecules or wrong density
Solution:
- Increase molecule count
- Verify densities with
analyze_density.py - Ensure adequate phase thickness (~15-20 Å minimum)
PBC Artifacts
Symptom: Molecules interact across periodic boundaries
Cause: Box too small
Solution:
- Increase lateral dimensions (x, y)
- Keep z-dimension adequate for both phases
- Use vacuum padding if needed
---
Tips for Interface Systems
1. Start simple: Test with small systems first 2. Use PBC: Essential for interface simulations 3. Adequate thickness: Each phase ≥ 15-20 Å 4. Verify density: Use analyze_density.py 5. Consider equilibration: Interface will form during MD 6. Plan area: Larger area = better statistics but slower 7. Visualization: Check interface in VMD/PyMOL
---
Workflow
1. Choose solvent pair: Based on research question 2. Calculate densities: Estimate molecule counts 3. Set up PBC box: Appropriate dimensions 4. Define plane: Interface position and orientation 5. Create input file: Use template as starting point 6. Validate: validate_input.py 7. Run Packmol: packmol < interface.inp 8. Verify: Check interface formation, density 9. Equilibrate: Run MD to relax interface 10. Production: Your actual simulation
---
For More Help
- Main skill: SKILL.md
- Templates: ../../templates/
- Constraints: ../../references/constraints.md
- Troubleshooting: ../../references/troubleshooting.md
# Protein Solvation Example
#
# This example demonstrates solvating a protein with water and ions
# to prepare a system for molecular dynamics simulation.
#
# System: Protein + water shell + Na+ and Cl- ions for neutrality
# Usage: packmol < protein_solvation.inp
# Required parameters
tolerance 2.0
filetype pdb
output solvated.pdb
# Optional: periodic boundary conditions for MD
# Remove comment for periodic simulations
# pbc 0. 0. 0. 60. 60. 80.
# Protein (fixed at center)
structure protein.pdb
number 1
fixed 30. 30. 40. 0. 0. 0.
center
chain A
end structure
# Water solvation shell
structure water.pdb
number 5000
inside box 0. 0. 0. 60. 60. 80.
chain W
end structure
# Sodium ions (for neutrality and salt)
structure SOD.pdb
number 10
inside box 0. 0. 0. 60. 60. 80.
chain NA
end structure
# Chloride ions (for neutrality and salt)
structure CLA.pdb
number 10
inside box 0. 0. 0. 60. 60. 80.
chain CL
end structure
# ============================================================================
# Notes
# ============================================================================
#
# This creates a 60×60×80 Å box with:
# - 1 protein (fixed at center: 30, 30, 40)
# - 5000 water molecules
# - 10 Na+ ions
# - 10 Cl- ions
#
# Assumptions:
# - Protein fits within ~40×40×60 Å region
# - 10 Å solvent shell around protein
# - Protein is neutral (10 Na+ and 10 Cl- for 0.15 M salt)
#
# To adapt for your system:
# 1. Replace protein.pdb with your protein file
# 2. Adjust box dimensions based on your protein size
# 3. Calculate number of waters for desired density
# 4. Adjust ion counts for:
# - Protein charge (neutralization)
# - Desired salt concentration
#
# For automatic solvation setup:
# python scripts/solvate_helper.py protein.pdb --shell 15.0
#
# Required structure files:
# - protein.pdb: Your protein structure
# - water.pdb: Single water molecule (TIP3P recommended)
# - SOD.pdb: Sodium ion
# - CLA.pdb: Chloride ion
#
# Expected results:
# - Output file: solvated.pdb
# - Total atoms: ~25,000 (5000 waters × 3 + protein atoms + ions)
# - Density: ~1.0 g/cm³ (verify with analyze_density.py)
Solvation Examples
Examples for solvating biomolecules with water and ions for molecular dynamics simulations.
Examples
1. protein_solvation.inp
Purpose: Solvate a protein with water and ions
Description: Creates a solvation shell around a protein, with Na⁺ and Cl⁻ ions for neutrality and salt concentration.
Use case: Preparing protein systems for MD simulations
System setup:
- 1 protein (fixed at box center)
- 5000 water molecules
- 10 Na⁺ ions
- 10 Cl⁻ ions
- Box size: 60 × 60 × 80 Å
Requirements:
protein.pdb- Your protein structurewater.pdb- Single water molecule (TIP3P recommended)SOD.pdb- Sodium ionCLA.pdb- Chloride ion
To run:
packmol < protein_solvation.inpExpected output: solvated.pdb with ~25,000 atoms
Modifications: 1. Adjust box size:
- Get protein dimensions from
protein.pdb - Add 10-15 Å solvent shell around protein
- Example: protein spans 0-40 Å → box -10 to 70 Å (80 Å total)
2. Calculate water molecules:
- For 60×60×80 Å box = 288,000 ų
- At 1 g/cm³: ~9600 water molecules
- Subtract protein volume
- This example uses 5000 (adjust for density)
3. Adjust ions:
- Neutralization: Add ions to counter protein charge
- If protein charge = +4: Add 4 Cl⁻
- Salt concentration: Add equal amounts of Na⁺ and Cl⁻
- For 0.15 M NaCl in 60×60×80 Å box: ~15 Na⁺ and 15 Cl⁻
- Formula:
N_ions = concentration × volume(L) × NA
Tips:
- Use
solvate_helper.pyfor automatic setup:
python scripts/solvate_helper.py protein.pdb --shell 15.0 --charge +4 --conc 0.15- Verify density with
analyze_density.py - Check for overlaps with
check_overlaps.py - Add PBC for periodic MD simulations
---
2. water_box.inp
Purpose: Create a pure water box
Description: Simple water box at ~1.0 g/cm³ density, useful as a starting point or for testing.
Use case:
- Equilibration runs
- Solvent for adding solutes later
- Testing water models and MD parameters
System setup:
- 1200 water molecules
- Box size: 40 × 40 × 40 Å
- Density: ~1.0 g/cm³
Requirements:
water.pdb- Single water molecule
To run:
packmol < water_box.inpExpected output: water_box.pdb with 3600 atoms
Modifications:
- Change box dimensions for different sizes
- Adjust molecule count for desired density
- Add salt ions: include SOD.pdb and CLA.pdb structure blocks
Water models:
- TIP3P: Most common, recommended
- SPC/E: Slightly better bulk properties
- TIP4P: Better diffusion properties
- TIP5P: Five-site model (more accurate, slower)
Tips:
- Verify density with
analyze_density.py - 1 water ≈ 30 ų at 1 g/cm³
- For NPT equilibration: start with slightly lower density
- Add solutes later using
fixedconstraint
---
General Solvation Guidelines
Preparing Structure Files
Protein PDB:
- Clean structure: remove waters, ligands, ions
- Add missing hydrogens (use pdb2gmx, reduce, etc.)
- Check for missing residues/atoms
- Verify proper protonation states
Water Model:
- Use consistent water model for your MD software
- TIP3P is standard for AMBER, CHARMM
- Download or create single water PDB
Ions:
- Use standard ion names for your MD software
- AMBER: SOD (Na⁺), CLA (Cl⁻)
- CHARMM: SOD, CLA (or specific ion types)
- GROMACS: NA, CL (convert with pdb2gmx)
Calculating Box Size
1. Get protein dimensions:
# Use grep to find min/max coordinates
grep "^ATOM" protein.pdb | awk '{print $7, $8, $9}'Or use visualization software (VMD, PyMOL)
2. Add solvent shell:
- Minimum: 10 Å (may have artifacts)
- Recommended: 12-15 Å
- For large proteins: 15-20 Å
3. Example calculation:
Protein spans: 0 to 45 Å in x, y, z
Solvent shell: 15 Å
Box size: 60 × 60 × 60 ÅCalculating Water Molecules
Rough estimation:
V_box = L × W × H (ų)
V_protein = approximate from molecular weight or software
V_water = V_box - V_protein
N_water = V_water / 30 (at 1.0 g/cm³)For 60×60×60 Å box:
V_box = 216,000 ų
V_protein ≈ 30,000 ų (typical medium protein)
V_water = 186,000 ų
N_water ≈ 186,000 / 30 ≈ 6200 moleculesBetter approach: Use solvate_helper.py script
Ion Calculations
Neutralization:
Charge to neutralize = protein charge / e
N_counterions = |charge|
If protein = +4:
Add 4 Cl⁻Salt concentration:
N_ions = concentration × volume × NA
For 0.15 M in 60×60×60 Å box:
V = 216,000 ų = 216,000 × 10⁻³⁰ L = 2.16 × 10⁻²² L
N = 0.15 mol/L × 2.16 × 10⁻²² L × 6.022 × 10²³ mol⁻¹
N ≈ 20 ions of each type
Total: 10 Na⁺, 10 Cl⁻ (if neutral)
14 Na⁺, 10 Cl⁻ (if protein +4 charge)Common Issues
1. Low density:
- Increase
numberof waters - Check box dimensions
- Verify with
analyze_density.py
2. Protein too close to box edge:
- Increase box size
- Add larger solvent shell
- Use
centerwithfixedproperly
3. Wrong ion count:
- Calculate protein charge first
- Use
pdb2gmxor similar to determine charge - Verify neutralization
4. Overlaps:
- Check with
check_overlaps.py - May need to increase
tolerance - Ensure protein structure is reasonable
Workflow
1. Prepare protein: Clean, add hydrogens, verify 2. Calculate box size: Based on protein + shell 3. Calculate water count: For desired density 4. Calculate ions: Neutralization + salt 5. Create input file: Use template or script 6. Validate input: validate_input.py 7. Run Packmol: packmol < input.inp 8. Verify output: verify_success.py, check_overlaps.py 9. Check density: analyze_density.py
Next Steps
After solvation:
1. Energy minimization: Remove any remaining overlaps 2. Equilibration: NVT then NPT to relax solvent 3. Production MD: Your actual simulation 4. Analysis: As needed for your research
Automatic Tools
Use solvate_helper.py for automation:
python scripts/solvate_helper.py protein.pdb \
--shell 15.0 \
--charge +4 \
--conc 0.15 \
--output solvated.pdbThis automatically:
- Calculates box size
- Estimates water count
- Calculates ions
- Generates Packmol input
- Optionally runs Packmol
---
For More Help
- Main skill: SKILL.md
- Templates: ../../templates/
- Scripts: ../../scripts/
- Troubleshooting: ../../references/troubleshooting.md
# Pure Water Box Example
#
# This example creates a pure water box, commonly used as:
# - Starting point for equilibration
# - Solvent for adding solutes later
# - Testing MD parameters
#
# Usage: packmol < water_box.inp
# Required parameters
tolerance 2.0
filetype pdb
output water_box.pdb
# Optional: periodic boundary conditions
pbc 0. 0. 0. 40. 40. 40.
# Water molecules
structure water.pdb
number 1200
inside box 0. 0. 0. 40. 40. 40.
end structure
# ============================================================================
# Notes
# ============================================================================
#
# This creates a 40×40×40 Å box with 1200 water molecules.
#
# Expected density: ~1.0 g/cm³
# Total atoms: 3600 (1200 waters × 3 atoms)
#
# For accurate 1.0 g/cm³ density at room temperature:
# - Use TIP3P or SPC/E water model
# - 1200 molecules in this box size gives ~1.0 g/cm³
# - Adjust as needed: 1 molecule ≈ 30 ų at 1 g/cm³
#
# Common modifications:
# - Change box size for different systems
# - Add salt ions: include SOD.pdb and CLA.pdb
# - Use different water models (TIP4P, TIP5P, etc.)
#
# To verify density:
# python scripts/analyze_density.py water_box.pdb
#
# To add solute later:
# Use this as template, add solute with 'fixed' constraint
Packmol Constraints Reference
Complete guide to spatial constraints in Packmol for defining molecular placement regions.
Overview
Constraints define where molecules can be placed in 3D space. Each structure block must have at least one constraint. Constraints can be combined to create complex geometries.
Constraint Syntax
Constraints are specified within structure blocks:
structure molecule.pdb
number 100
<constraint> # Required: where to place molecules
[additional constraints]
[parameters]
end structureFixed Constraint
Fix a molecule at a specific position and orientation.
fixed x y z a b cParameters:
x y z: Translation (Å)a b c: Rotation angles in degrees around x, y, z axes
Example:
structure protein.pdb
number 1
fixed 0. 0. 0. 0. 0. 0.
center
end structureUse with:
center: Use center of mass for positioning- Solvated biomolecules
- Multi-stage packing
Box Constraints
Inside Box
Place molecules within a rectangular region.
inside box xmin ymin zmin xmax ymax zmaxParameters:
xmin ymin zmin: Minimum corner coordinates (Å)xmax ymax zmax: Maximum corner coordinates (Å)
Example:
structure water.pdb
number 1000
inside box 0. 0. 0. 40. 40. 40.
end structureOutside Box
Place molecules outside a rectangular region.
outside box xmin ymin zmin xmax ymax zmaxUse case: Create shells around solutes
Example:
structure water.pdb
number 1000
outside box 10. 10. 10. 30. 30. 30.
end structureCube Constraint
Shorthand for equal-sized boxes.
inside cube xmin ymin zmin sizeExample:
structure water.pdb
number 500
inside cube 0. 0. 0. 40.
end structureEquivalent to inside box 0. 0. 0. 40. 40. 40.
Sphere Constraints
Inside Sphere
Place molecules within a sphere.
inside sphere xcenter ycenter zcenter radiusParameters:
xcenter ycenter zcenter: Sphere center coordinates (Å)radius: Sphere radius (Å)
Example: Create spherical water droplet
structure water.pdb
number 1000
inside sphere 0. 0. 0. 20.
end structureOutside Sphere
Place molecules outside a sphere.
outside sphere xcenter ycenter zcenter radiusExample: Create spherical shell
structure water.pdb
number 2000
inside sphere 0. 0. 0. 30.
atoms 1
outside sphere 0. 0. 0. 20.
end atoms
end structureCombining Inside/Outside Spheres
Create spherical shells or vesicles:
# Vesicle: lipids in shell, water inside and outside
structure lipid.pdb
number 500
inside sphere 0. 0. 0. 30.
atoms 1 2 3
outside sphere 0. 0. 0. 25.
end atoms
end structure
structure water.pdb
number 500
inside sphere 0. 0. 0. 25.
end structureEllipsoid Constraints
Inside Ellipsoid
inside ellipsoid xc yc zc xa yb zc scaleParameters:
xc yc zc: Ellipsoid centerxa yb zc: Semi-axes (a, b, c) before scalingscale: Scaling factor
Equation: (x-xc)²/(xa·scale)² + (y-yc)²/(yb·scale)² + (z-zc)²/(zc·scale)² ≤ 1
Example: Prolate ellipsoid
structure water.pdb
number 1000
inside ellipsoid 0. 0. 0. 20. 20. 30. 1.0
end structureOutside Ellipsoid
outside ellipsoid xc yc zc xa yb zc scaleCylinder Constraints
Inside Cylinder
Place molecules within a cylinder.
inside cylinder x1 y1 z1 dx dy dz radius lengthParameters:
x1 y1 z1: Cylinder axis start pointdx dy dz: Cylinder axis direction vectorradius: Cylinder radius (Å)length: Cylinder length (Å)
Example: Vertical cylinder
structure water.pdb
number 500
inside cylinder 0. 0. 0. 0. 0. 1. 15. 40.
end structureExample: Nanotube/pore
structure water.pdb
number 1000
inside cylinder 0. 0. 0. 1. 0. 0. 10. 50.
end structureOutside Cylinder
outside cylinder x1 y1 z1 dx dy dz radius lengthUse case: Create cylindrical pores or channels
Plane Constraints
Above Plane
Place molecules above (positive side of) a plane.
above plane a b c dPlane equation: a·x + b·y + c·z = d
Parameters:
a b c: Normal vector (not necessarily normalized)d: Distance from origin
Example: Horizontal plane at z=0
structure water.pdb
number 1000
above plane 0. 0. 1. 0.
end structureExample: Inclined plane
structure molecule.pdb
number 500
above plane 0. 1. 1. 0.
end structureBelow Plane
Place molecules below (negative side of) a plane.
below plane a b c dExample: Liquid-liquid interface
structure water.pdb
number 1000
below plane 0. 0. 1. 0.
end structure
structure oil.pdb
number 200
above plane 0. 0. 1. 0.
end structureCombining Plane Constraints
Create slabs or layers:
# Water slab between z=-10 and z=10
structure water.pdb
number 1000
above plane 0. 0. 1. -10.
below plane 0. 0. 1. 10.
end structureGaussian Surface Constraint
inside xygauss x0 y0 z0 sigma a0 b0 c0Creates a Gaussian surface for density profiles.
Use case: Interface modeling with density gradients
Combining Constraints
Multiple constraints can be combined using atom selection:
Within Single Molecule
Apply different constraints to different atoms:
structure surfactant.pdb
number 100
# Headgroup in water region
atoms 1 2 3 4
above plane 0. 0. 1. 0.
end atoms
# Tail in oil region
atoms 5 6 7 8 9 10
below plane 0. 0. 1. 0.
end atoms
end structureMultiple Spatial Constraints
Combine inside/outside constraints:
# Molecules in shell between two spheres
structure water.pdb
number 1000
inside sphere 0. 0. 0. 50.
outside sphere 0. 0. 0. 40.
end structureConstraint Validation
Validate constraints without running full packing:
structure molecule.pdb
number 100
inside box 0. 0. 0. 30. 30. 30.
check
end structureOutput shows constraint validity without optimization.
Common Constraint Patterns
Solvation Shell
# Water around protein
structure protein.pdb
number 1
fixed 0. 0. 0. 0. 0. 0.
center
end structure
structure water.pdb
number 5000
inside box -15. -15. -15. 65. 65. 65.
end structureMicelle/Spherical Aggregate
# Surfactants in sphere
structure surfactant.pdb
number 200
inside sphere 0. 0. 0. 25.
atoms 1 2 3
outside sphere 0. 0. 0. 15.
end atoms
end structureBilayer
# Lipid bilayer with water
structure lipid.pdb
number 500
above plane 0. 0. 1. 0.
below plane 0. 0. 1. 30.
constrain_rotation x 0. 10.
constrain_rotation y 0. 10.
end structure
structure water.pdb
number 5000
above plane 0. 0. 1. 30.
end structure
structure water.pdb
number 5000
below plane 0. 0. 1. -30.
end structureNanotube with Solution
# Water inside nanotube
structure water.pdb
number 500
inside cylinder 0. 0. 0. 0. 0. 1. 5. 40.
end structure
# Water outside nanotube
structure water.pdb
number 5000
outside cylinder 0. 0. 0. 0. 0. 1. 8. 50.
end structureTips for Using Constraints
1. Start simple: Test with one constraint before combining 2. Use check keyword: Validate constraints before running full optimization 3. Visualize: Load constraint boundaries in VMD/PyMOL to verify 4. Avoid conflicts: Make sure constraint regions overlap properly 5. Consider periodicity: Use pbc with constraints for periodic systems 6. Tolerance matters: Ensure tolerance is smaller than constraint features
Troubleshooting Constraints
No Solution Found
- Cause: Constraint region too small for number of molecules
- Solution: Reduce molecule count or increase constraint region
Unexpected Placements
- Cause: Conflicting or overlapping constraints
- Solution: Use
checkkeyword to validate constraint geometry - Solution: Visualize constraint boundaries
Molecules Missing
- Cause:
outsideconstraint removing molecules - Solution: Ensure sufficient volume in valid region
- Solution: Check that
insideandoutsideregions overlap correctly
Advanced Constraint Features
Atom Selection for Constraints
Apply constraints only to specific atoms within molecules:
structure molecule.pdb
number 100
inside box 0. 0. 0. 30. 30. 30.
atoms 1 2 3 4
inside sphere 15. 15. 15. 10.
end atoms
end structureConstrained Rotations
Control molecular orientation:
structure molecule.pdb
number 100
inside box 0. 0. 0. 30. 30. 30.
constrain_rotation x 180. 20.
constrain_rotation y 180. 20.
end structureParameters: constrain_rotation <axis> <range> <increment>
axis: x, y, or zrange: Rotation range in degreesincrement: Sampling increment
Fixed Molecules in Multi-Stage Packing
Build complex systems incrementally:
Stage 1: Place lipids
structure lipid.pdb
number 500
inside box 0. 0. 0. 50. 50. 50.
restart_to lipids.pack
end structureStage 2: Add water
structure lipid.pdb
number 500
restart_from lipids.pack
fixed 0. 0. 0. 0. 0. 0.
end structure
structure water.pdb
number 5000
inside box 0. 0. 0. 50. 50. 50.
end structureRelated Topics
- Parameters reference - Input parameters and optimization
- File formats - Structure file requirements
- Troubleshooting - Common constraint issues
For more examples, see:
- examples/interface/ - Plane constraints
- examples/advanced/ - Complex geometries
Packmol File Formats Reference
Complete guide to file format specifications and requirements for Packmol input and output.
Overview
Packmol supports three structure file formats:
- PDB (Protein Data Bank) - Most common, recommended
- XYZ - Simple Cartesian coordinate format
- TINKER - TINKER molecular mechanics format
Format is specified with the filetype parameter:
filetype pdb # or xyz or tinkerPDB Format (Recommended)
Format Specification
Packmol reads and writes standard PDB format (as defined by the Protein Data Bank, version 3.3).
Required Fields
Each atom record must have:
ATOM serial atom res chain resseq x y z occ temp
1234567890123456789012345678901234567890123456789012345678901234567890
1-7 13-16 17-20 22 23-26 31-38 39-46 47-54 55-60 61-66Critical columns:
- 1-6: Record type ("ATOM" or "HETATM")
- 13-16: Atom name
- 17-20: Residue name
- 23-26: Residue sequence number
- 31-38: X coordinate (Å, right-justified, 8.3f format)
- 39-46: Y coordinate (Å, right-justified, 8.3f format)
- 47-54: Z coordinate (Å, right-justified, 8.3f format)
Element identification (columns 13-16):
Correct:
ATOM 1 O HOH 1 0.000 0.000 0.000 1.00 0.00
ATOM 2 H1 HOH 1 0.959 0.000 -0.243 1.00 0.00
ATOM 3 H2 HOH 1 -0.240 0.000 -0.927 1.00 0.00
Incorrect (missing space):
ATOM 11OG HOH 1 0.000 0.000 0.000 1.00 0.00Example: Water Molecule
ATOM 1 O HOH 1 0.000 0.000 0.000 1.00 0.00
ATOM 2 H1 HOH 1 0.959 0.000 -0.243 1.00 0.00
ATOM 3 H2 HOH 1 -0.240 0.000 -0.927 1.00 0.00
ENDExample: Protein Fragment
ATOM 1 N MET 1 10.204 20.157 30.281 1.00 0.00
ATOM 2 CA MET 1 11.523 20.853 30.673 1.00 0.00
ATOM 3 C MET 1 12.498 19.758 31.210 1.00 0.00
ATOM 4 O MET 1 12.134 18.588 31.059 1.00 0.00
ATOM 5 CB MET 1 11.345 21.892 31.770 1.00 0.00
ATOM 6 CG MET 1 12.754 22.534 31.923 1.00 0.00
ATOM 7 SD MET 1 13.058 23.743 30.889 1.00 0.00
ATOM 8 CE MET 1 14.642 23.412 30.630 1.00 0.00
TER
ENDOptional Features
CONECT Records
Define connectivity between atoms:
ATOM 1 O HOH 1 0.000 0.000 0.000 1.00 0.00
ATOM 2 H1 HOH 1 0.959 0.000 -0.243 1.00 0.00
ATOM 3 H2 HOH 1 -0.240 0.000 -0.927 1.00 0.00
CONECT 1 2 3
ENDNote: Packmol doesn't use CONECT records for packing, but preserves them in output.
TER Records
Indicate chain/terminus:
ATOM 1 N ALA 1 0.000 0.000 0.000 1.00 0.00
ATOM 2 CA ALA 1 1.458 0.000 0.000 1.00 0.00
TER
ATOM 3 N GLY 2 3.102 0.000 0.000 1.00 0.00
ENDChain Identifiers
Specify chain with column 22:
ATOM 1 N MET A 1 10.204 20.157 30.281 1.00 0.00
ATOM 2 N MET B 1 15.204 20.157 30.281 1.00 0.00Or use chain parameter in input:
structure protein.pdb
number 1
chain A
fixed 0. 0. 0. 0. 0. 0.
end structureResidue Numbering
Control with resnumbers parameter:
structure water.pdb
number 100
resnumbers 2 # Number each water separately
inside box 0. 0. 0. 40. 40. 40.
end structureOutput numbering:
resnumbers 0: Sequential across all molecules (default)resnumbers 1: Same as input fileresnumbers 2: Increment per moleculeresnumbers 3: Increment by chain
PDB Format Requirements Summary
✓ Must have:
- ATOM or HETATM records
- Element symbol correctly positioned (columns 13-14)
- XYZ coordinates in columns 31-54 (8.3f format)
✓ Recommended:
- TER records between molecules
- Unique atom serial numbers
- Proper residue names
✗ Common issues:
- Element not in columns 13-14
- Coordinates not 8.3f format
- Missing spaces in atom names (e.g., "OG" instead of " OG")
- Missing END record
XYZ Format
Format Specification
Simple Cartesian coordinate format:
N_atoms
comment_line
element x y z
element x y z
...Example: Ethanol
9
Ethanol molecule
C 1.2000 0.0000 0.0000
C 0.0000 0.0000 0.0000
O -1.2000 0.0000 0.0000
H 1.6000 1.0000 0.0000
H 1.6000 -0.5000 0.8660
H 1.6000 -0.5000 -0.8660
H -0.4000 0.9400 0.0000
H -0.4000 -0.4700 0.8140
H -1.6000 -0.4700 -0.8140Requirements
- First line: number of atoms
- Second line: comment (ignored by Packmol)
- Subsequent lines: element symbol and coordinates (in Å)
- Coordinates can be free format or fixed
Advantages
- Simple and human-readable
- Easy to generate programmatically
- No specific column requirements
Disadvantages
- No residue or chain information
- Limited metadata
- Not suitable for biomolecules
TINKER Format
Format Specification
TINKER Cartesian coordinate format:
N_atoms # comment
atom_num atom_type x y z [bond_connectivity]
...Example: Water
3
1 8 0.000000 0.000000 0.000000 2 2 3
2 1 0.959000 0.000000 -0.243000 1 1
3 1 -0.240000 0.000000 -0.927000 1 1Requirements
- First line: number of atoms
- Atom types must match TINKER force field
- Coordinates in Angstroms
- Bond connectivity (optional but recommended)
Advantages
- Includes bond connectivity
- Force field atom types
- Suitable for molecular mechanics
Disadvantages
- Requires TINKER atom types
- Less common than PDB
- More complex format
Converting Between Formats
Using Open Babel
# PDB to XYZ
obabel -ipdb input.pdb -oxyz output.xyz
# XYZ to PDB
obabel -ixyz input.xyz -opdb output.pdb
# PDB to TINKER
obabel -ipdb input.pdb -xtinker output.xyzUsing Python (MDAnalysis)
import MDAnalysis as mda
# Read any format
u = mda.Universe('input.pdb')
# Write to any format
u.atoms.write('output.xyz')
u.atoms.write('output.pdb')Using VMD
# Load and save
set mol [molinfo top]
set sel [atomselect $mol all]
$sel writepdb "output.pdb"Format-Specific Considerations
For Biomolecular Systems
Use PDB format because:
- Residue and chain information preserved
- Standard in structural biology
- Compatible with MD software (GROMACS, AMBER, CHARMM, NAMD)
- Supports secondary structure metadata
For Small Molecules
Options:
- PDB: Most compatible, use for consistency
- XYZ: Simpler, easier to generate programmatically
- TINKER: Use if working with TINKER force field
For Coarse-Grained Models
Use PDB format:
- Create custom residue names for beads
- Set appropriate atomic radii with
radiusparameter - Example: MARTINI beads
ATOM 1 BB ALA 1 0.000 0.000 0.000 1.00 0.00
ATOM 2 SC1 ALA 1 1.000 0.000 0.000 1.00 0.00File Preparation Checklist
Before Running Packmol
- [ ] Verify file format matches
filetypeparameter - [ ] Check element symbols in correct columns (PDB)
- [ ] Ensure coordinates are in Angstroms
- [ ] Verify no missing atoms in structure
- [ ] Test file can be read by visualization software
- [ ] Check for duplicate atoms
- [ ] Verify molecule is complete and reasonable geometry
Validation Commands
# Count atoms (PDB)
grep "^ATOM\|^HETATM" file.pdb | wc -l
# Check for END record (PDB)
tail -1 file.pdb
# Visualize in VMD
vmd file.pdb
# Convert formats
obabel -ipdb file.pdb -oxyz file.xyzCommon Format Issues
Issue: Element Not Recognized
Symptom: Packmol ignores atoms or gives errors
Cause: Element symbol not in columns 13-14 (PDB)
Solution:
# Wrong
ATOM 11OG HOH 1 0.000 0.000 0.000
# Right
ATOM 1 O HOH 1 0.000 0.000 0.000
^^ ^^
| |
space elementIssue: Wrong Coordinates
Symptom: Molecules deformed or in wrong positions
Cause: Coordinates not in correct format or units
Solution:
- Ensure 8.3f format (PDB columns 31-54)
- Verify units are Angstroms (not nanometers or picometers)
- Check coordinate signs
Issue: Missing Atoms
Symptom: Fewer atoms in output than expected
Cause: Format reading errors or skipped records
Solution:
- Verify all records are ATOM or HETATM
- Check for non-standard characters
- Validate file format specification
Format Recommendations by Use Case
Protein Solvation
filetype pdb
# Use PDB for protein and solventLiquid Mixtures
filetype pdb
# PDB or XYZ both workCoarse-Grained
filetype pdb
# Create custom residue names for beadsInterface Systems
filetype pdb
# PDB recommended for compatibilityGas Phase Clusters
filetype xyz
# XYZ is simpler for small moleculesOutput Format Features
Packmol PDB Output
Packmol writes standard PDB with:
- All input atoms with new positions
- Original atom serial numbers (or renumbered)
- Original residue names and numbers (unless
resnumbersspecified) - Chain identifiers (if specified)
- TER records between molecules
- END record at file end
- CONECT records (if present in input)
Atom Numbering in Output
Atom serial numbers are renumbered sequentially: 1. First molecule, atom 1 2. First molecule, atom 2 3. ... 4. Second molecule, atom 1 5. ...
To control numbering, use resnumbers parameter.
Chain Identifiers in Output
Set chains with chain parameter:
structure protein.pdb
number 1
chain A
fixed 0. 0. 0. 0. 0. 0.
end structure
structure water.pdb
number 1000
chain W
inside box 0. 0. 0. 40. 40. 40.
end structureRelated Topics
- Parameters reference - filetype parameter, chain, resnumbers
- Constraints reference - Spatial constraints for molecules
- Troubleshooting - File format issues
For format examples in context, see:
- examples/basic/ - Simple PDB files
- examples/solvation/ - Protein and solvent PDB
Packmol Parameters Reference
Complete guide to all input parameters in Packmol for controlling packing behavior and optimization.
Overview
Packmol input files consist of: 1. Global parameters (file-level) 2. Structure blocks with per-molecule parameters 3. Optimization parameters (optional)
Required Parameters
Three parameters are required in every Packmol input file:
tolerance
Minimum allowed distance between atoms of different molecules.
Syntax: tolerance <distance>
Units: Angstroms (Å)
Default: None (required)
Typical values:
2.0- All-atom models2.5-3.0- United-atom models3.0-5.0- Coarse-grained models1.5-1.8- Precise packing (slower)
Example:
tolerance 2.0Notes:
- Smaller values = tighter packing but longer optimization
- Larger values = faster but more void space
- Critical for preventing overlaps
- Adjust based on atomic radii in your system
output
Output filename for the packed structure.
Syntax: output <filename>
Default: None (required)
Example:
output system.pdbNotes:
- File extension determines format (.pdb, .xyz)
- Overwrites existing files without warning
- Format must match
filetypeparameter
filetype
Format of input and output structure files.
Syntax: filetype <format>
Options:
pdb- Protein Data Bank format (default)xyz- XYZ Cartesian coordinatestinker- TINKER molecular mechanics format
Example:
filetype pdbSee: file_formats.md for format specifications
Global Optional Parameters
pbc
Periodic boundary conditions for the system.
Syntax:
pbc xmin ymin zmin xmax ymax zmaxor
pbc a b c # for orthorhombic boxParameters:
xmin ymin zmin: Minimum box coordinatesxmax ymax zmax: Maximum box coordinates- OR
a b c: Box lengths for orthorhombic box starting at origin
Example:
pbc 0. 0. 0. 40. 40. 60.or
pbc 40. 40. 60.Notes:
- Required for periodic MD simulations
- Molecules can wrap across boundaries
- Constraint
inside boxis typically set to PBC region - Supported in Packmol 20.15.0 and later
seed
Random seed for reproducible results.
Syntax: seed <integer>
Default: 12345 (fixed seed)
Values:
- Positive integer: Use as seed
-1: Use system time (non-reproducible)
Example:
seed 12345Notes:
- Critical for reproducibility
- Same seed + same input = identical output
- Use
-1for different random configurations
discale
Distance tolerance scaling factor for optimization.
Syntax: discale <factor>
Default: 1.0
Range: 1.0 to 2.0
Example:
discale 1.5Notes:
- Increases effective tolerance during optimization
- Helps with difficult convergence
- Higher values = faster convergence but less precise packing
- Try
1.5if packing fails to converge
maxit
Maximum number of optimization iterations per loop.
Syntax: maxit <N>
Default: 20
Example:
maxit 50Notes:
- Increase for difficult systems
- Trade-off: more iterations vs. computation time
- Convergence typically occurs before
maxit
precision
Solution precision for convergence.
Syntax: precision <value>
Default: 0.01
Units: Fraction of tolerance
Example:
precision 0.001Notes:
- Smaller values = tighter convergence
- Typical range: 0.001 to 0.1
- Too small may prevent convergence
nloop
Number of optimization loops.
Syntax: nloop <N>
Default: Automatic (varies by system)
Example:
nloop 5Notes:
- Controls optimization strategy
- Usually automatic is best
- Modify only for special cases
sidemax
Maximum system size for optimization.
Syntax: sidemax <value>
Default: Automatic
Units: Angstroms (Å)
Example:
sidemax 100.Notes:
- Limits search region during optimization
- Larger values = slower but more thorough
- Usually automatic is sufficient
Structure Block Parameters
number
Number of molecules of this type to place.
Syntax: number <N>
Required: Yes (within each structure block)
Example:
structure water.pdb
number 1000
inside box 0. 0. 0. 40. 40. 40.
end structureradius
Atomic radius for overlap detection.
Syntax: radius <value>
Default: 1.0 (multiplied by discale)
Units: Angstroms (Å)
Example:
structure molecule.pdb
number 100
radius 1.5
inside box 0. 0. 0. 30. 30. 30.
end structureAtom-specific radii:
structure molecule.pdb
number 100
atoms 1 2
radius 1.5
end atoms
atoms 3 4 5
radius 1.0
end atoms
end structureNotes:
- Useful for multiscale models
- Larger radius = more spacing
- Can vary per atom for coarse-graining
resnumbers
Residue numbering strategy.
Syntax: resnumbers <scheme>
Options:
0- Sequential numbering across all molecules (default)1- Each molecule gets same residue numbers as input2- Residue numbers increment per molecule3- Residue numbers increment by chain
Example:
structure protein.pdb
number 1
resnumbers 1
fixed 0. 0. 0. 0. 0. 0.
end structure
structure water.pdb
number 1000
resnumbers 2
inside box 0. 0. 0. 40. 40. 40.
end structureNotes:
- Important for MD software compatibility
- Option 0: All waters numbered sequentially
- Option 2: Each water molecule numbered separately
chain
Chain identifier for molecules.
Syntax: chain <letter>
Example:
structure protein.pdb
number 1
chain A
fixed 0. 0. 0. 0. 0. 0.
end structure
structure water.pdb
number 1000
chain W
inside box 0. 0. 0. 40. 40. 40.
end structureNotes:
- Single character (A-Z, 0-9)
- Useful for organizing output
- Required by some MD packages
center
Use center of mass for positioning.
Syntax: center
Used with: fixed constraint
Example:
structure protein.pdb
number 1
fixed 20. 20. 20. 0. 0. 0.
center
end structureNotes:
- Places molecule center at specified coordinates
- Without
center, uses first atom position - Essential for solvating biomolecules
Optimization Parameters (Per Structure)
movefrac
Fraction of molecules to displace during heuristic optimization.
Syntax: movefrac <value>
Default: 0.05 (5% of molecules)
Range: 0.0 to 1.0
Example:
structure water.pdb
number 1000
inside box 0. 0. 0. 40. 40. 40.
movefrac 0.1
end structureNotes:
- Higher values = more aggressive optimization
- Can help escape local minima
- Too high may slow convergence
maxmove
Maximum number of molecules to displace.
Syntax: maxmove <N>
Default: Dynamic
Example:
structure water.pdb
number 5000
inside box 0. 0. 0. 50. 50. 50.
maxmove 100
end structureNotes:
- Limits number of molecules moved per iteration
- Useful for very large systems
- Works with
movefrac
disable_movebad
Disable the move-bad heuristic.
Syntax: disable_movebad
Default: Disabled (move-bad heuristic is active)
Example:
structure molecule.pdb
number 100
inside box 0. 0. 0. 30. 30. 30.
disable_movebad
end structureNotes:
- Move-bad heuristic repositions overlapping molecules
- Disable only if causing problems
- Usually best left enabled
Rotation Constraints
constrain_rotation
Limit molecular rotation during packing.
Syntax: constrain_rotation <axis> <range> <increment>
Parameters:
axis: x, y, or zrange: Rotation range in degrees (typically 180)increment: Sampling step in degrees
Example: Constrain rotation around all axes
structure lipid.pdb
number 100
inside box 0. 0. 0. 40. 40. 40.
constrain_rotation x 180. 20.
constrain_rotation y 180. 20.
constrain_rotation z 180. 20.
end structureExample: Restrict to specific orientation
structure molecule.pdb
number 50
inside box 0. 0. 0. 30. 30. 30.
constrain_rotation z 0. 10.
end structureNotes:
- Smaller increment = more orientations tested (slower)
- Useful for anisotropic molecules (lipids, surfactants)
- Range of 180° samples all unique orientations
Restart Parameters
restart_to
Save molecular positions to a restart file.
Syntax: restart_to <filename>
Example: Stage 1 - Place lipids
structure lipid.pdb
number 500
inside box 0. 0. 0. 50. 50. 50.
restart_to lipids.pack
end structurerestart_from
Load molecular positions from a restart file.
Syntax: restart_from <filename>
Example: Stage 2 - Add water around fixed lipids
structure lipid.pdb
number 500
restart_from lipids.pack
fixed 0. 0. 0. 0. 0. 0.
end structure
structure water.pdb
number 5000
inside box 0. 0. 0. 50. 50. 50.
end structureNotes:
- Build large systems incrementally
- Saves time by reusing previous results
- Critical for multi-stage packing
Output Options
writecrd
Write additional coordinate file in CHARMM format.
Syntax: writecrd <filename>
Example:
writecrd system.crdadd_amber_ter
Add TER cards for AMBER compatibility.
Syntax: add_amber_ter
Example:
structure protein.pdb
number 1
fixed 0. 0. 0. 0. 0. 0.
add_amber_ter
end structureadd_box_sides
Add box vectors for GROMACS compatibility.
Syntax: add_box_sides
Example: Automatically adds CRYST1 record
Advanced Parameters
fbins
Number of bins for finite-distance calculation.
Syntax: fbins <N>
Default: Automatic
Example:
fbins 100Notes:
- Affects optimization algorithm
- Usually automatic is best
- Modify only for special cases
short_tol
Short-distance tolerance.
Syntax: short_tol <value>
Default: Automatic
Example:
short_tol 0.1Notes:
- Used for overlap detection
- Affects optimization precision
- Usually automatic is sufficient
Parameter Combinations
Basic System
tolerance 2.0
filetype pdb
output system.pdb
structure water.pdb
number 1000
inside box 0. 0. 0. 40. 40. 40.
end structureSolvated Protein
tolerance 2.0
filetype pdb
output solvated.pdb
seed 12345
structure protein.pdb
number 1
fixed 20. 20. 20. 0. 0. 0.
center
chain A
resnumbers 1
end structure
structure water.pdb
number 5000
inside box 0. 0. 0. 50. 50. 50.
chain W
resnumbers 2
end structureDifficult Convergence
tolerance 2.0
filetype pdb
output system.pdb
discale 1.5
maxit 50
precision 0.001
structure molecule.pdb
number 100
inside box 0. 0. 0. 30. 30. 30.
movefrac 0.1
end structurePeriodic System
tolerance 2.0
filetype pdb
output periodic.pdb
pbc 0. 0. 0. 40. 40. 60.
structure water.pdb
number 2000
inside box 0. 0. 0. 40. 40. 60.
end structureMulti-Stage Packing
Stage 1:
tolerance 2.0
filetype pdb
output stage1.pdb
structure lipid.pdb
number 500
inside box 0. 0. 0. 50. 50. 50.
restart_to lipids.pack
end structureStage 2:
tolerance 2.0
filetype pdb
output stage2.pdb
structure lipid.pdb
number 500
restart_from lipids.pack
fixed 0. 0. 0. 0. 0. 0.
end structure
structure water.pdb
number 5000
inside box 0. 0. 0. 50. 50. 50.
end structureParameter Selection Guide
For Quick Tests
tolerance: 2.5-3.0maxit: 10- Small system sizes
For Production Runs
tolerance: 2.0 (all-atom) or 2.5 (united-atom)seed: Fixed value for reproducibilitymaxit: Default (20)- Add
pbcfor periodic systems
For Difficult Systems
discale: 1.5maxit: 50movefrac: 0.1- Consider restart files
For Coarse-Grained Models
tolerance: 3.0-5.0radius: Larger values per bead type- Fewer molecules due to larger effective size
Troubleshooting Parameters
System Won't Converge
1. Increase discale to 1.5 2. Increase maxit to 50 3. Reduce number of molecules 4. Increase tolerance slightly
Too Many Overlaps
1. Check tolerance is appropriate 2. Verify radius values 3. Reduce system size 4. Use check keyword
Wrong Density
1. Adjust number of molecules 2. Verify box dimensions 3. Check structure file integrity
Non-Reproducible Results
1. Set fixed seed value 2. Ensure identical input files 3. Check for randomness in other tools
Related Topics
- Constraints reference - Spatial constraint syntax
- File formats - Input/output format specifications
- Troubleshooting - Common parameter issues
For parameter examples in context, see:
- examples/basic/ - Simple parameter sets
- examples/solvation/ - Solvation parameters
- examples/advanced/ - Advanced parameter usage
Packmol Troubleshooting Guide
Solutions to common issues and errors when using Packmol.
Overview
This guide helps diagnose and resolve problems with Packmol input files, convergence, and output quality. Issues are organized by error type and symptom.
Quick Diagnosis
Check Your Input First
Before troubleshooting, validate your input:
python scripts/validate_input.py your_input.inpTest with Minimal System
Create a minimal test case:
- Reduce molecule count to 10-50
- Use simple box constraint
- Remove optional parameters
If minimal case works, scale up gradually.
Common Errors
"ERROR: Opening file"
Symptom: Packmol cannot read structure file
Causes: 1. File doesn't exist 2. Wrong file path 3. Incorrect permissions 4. File format issues
Solutions:
# Check file exists in current directory
ls -l water.pdb
# Use relative or absolute paths
structure /path/to/water.pdb
number 100
inside box 0. 0. 0. 40. 40. 40.
end structure
# Verify file format
head -20 water.pdbPrevention:
- Keep all structure files in same directory as input file
- Use simple filenames (no spaces)
- Verify PDB format compliance
"Killed" Error
Symptom: Process terminates with "Killed" message
Cause: System ran out of memory
Solutions:
1. Reduce system size
# Reduce molecule count
structure water.pdb
number 500 # Was 5000
inside box 0. 0. 0. 40. 40. 40.
end structure2. Use restart files - Build system in stages
# Stage 1
structure water.pdb
number 2500
restart_to stage1.pack
end structure
# Stage 2 (in separate input file)
structure water.pdb
number 2500
restart_from stage1.pack
fixed 0. 0. 0. 0. 0. 0.
end structure
structure water.pdb
number 2500
inside box 0. 0. 0. 40. 40. 40.
end structure3. Increase system memory or use machine with more RAM
4. Reduce molecule complexity - Use united-atom instead of all-atom
Prevention:
- Start with small systems
- Estimate memory: ~1-2 GB per 10,000 atoms
- Use restart files for large systems
"ERROR: No solution found"
Symptom: Packmol cannot place all molecules
Causes: 1. Constraint region too small 2. Tolerance too large for region 3. Too many molecules for space 4. Conflicting constraints
Solutions:
1. Reduce molecule count
structure water.pdb
number 800 # Was 1000
inside box 0. 0. 0. 40. 40. 40.
end structure2. Increase constraint region
structure water.pdb
number 1000
inside box 0. 0. 0. 45. 45. 45. # Was 40. 40. 40.
end structure3. Reduce tolerance
tolerance 1.8 # Was 2.04. Check constraint conflicts
# Use check keyword
structure water.pdb
number 100
inside box 0. 0. 0. 30. 30. 30.
check
end structure5. Use discale for difficult cases
discale 1.5Prevention:
- Test with small systems first
- Calculate approximate density
- Leave room for optimization
- Use
checkkeyword to validate constraints
Convergence Issues
Symptom: Optimization runs but doesn't converge
Causes: 1. System too crowded 2. Complex constraints 3. Inappropriate tolerance 4. Local minima
Solutions:
1. Increase discale
discale 1.5 # Allows larger effective tolerance during optimization2. Increase maxit
maxit 50 # Allow more iterations (default: 20)3. Adjust movefrac
structure molecule.pdb
number 100
inside box 0. 0. 0. 30. 30. 30.
movefrac 0.1 # Move more molecules per iteration
end structure4. Reduce system complexity
- Remove some constraint types
- Simplify geometry
- Reduce molecule count
5. Change tolerance
tolerance 2.5 # Larger tolerance = easier convergencePrevention:
- Start with simple systems
- Use appropriate tolerance for model type
- Build complex systems in stages
Incorrect Geometry
Symptom: Output looks wrong (molecules in wrong positions)
Causes: 1. Misunderstood constraint syntax 2. Wrong constraint type 3. Coordinate system confusion 4. Conflicting constraints
Solutions:
1. Visualize constraints (mentally or with software) 2. Use check keyword
structure molecule.pdb
number 10
inside box 0. 0. 0. 30. 30. 30.
check # Validates constraints without optimization
end structure3. Test with small system
structure water.pdb
number 10 # Small number for testing
inside box 0. 0. 0. 30. 30. 30.
end structure4. Verify constraint syntax
- Box:
inside box xmin ymin zmin xmax ymax zmax - Sphere:
inside sphere xc yc zc radius - Plane:
above plane a b c d(ax + by + cz = d)
5. Check plane equation
# Horizontal plane at z=0
below plane 0. 0. 1. 0.
above plane 0. 0. 1. 0.
# NOT
below plane 0. 0. 0. 0. # Wrong: normal vector can't be zeroPrevention:
- Start with box constraints (simplest)
- Test constraints with check keyword
- Visualize output after each run
- Read constraint documentation
Atoms Too Close
Symptom: Output has overlapping atoms
Causes: 1. Tolerance too small 2. Radius values inappropriate 3. Input files have issues 4. Wrong atomic radii
Solutions:
1. Check for overlaps
python scripts/check_overlaps.py output.pdb --tolerance 2.02. Increase tolerance
tolerance 2.5 # Was 2.03. Set appropriate radii
structure molecule.pdb
number 100
radius 1.5 # Larger atomic radius
inside box 0. 0. 0. 30. 30. 30.
end structure4. Verify input files
# Check for duplicate atoms
grep "^ATOM" water.pdb | wc -l
# Check coordinates
less water.pdb5. Use verify script
python scripts/verify_success.py input.inp output.pdbPrevention:
- Always check Packmol output for violation values
- Use appropriate tolerance for model type
- Validate input structure files
Wrong Atom/Molecule Count
Symptom: Output has different count than expected
Causes: 1. Structure file has multiple molecules 2. CONECT records causing issues 3. Residue numbering problems 4. Misunderstanding of number parameter
Solutions:
1. Check structure file
# Count molecules in PDB
grep "^ATOM" molecule.pdb | wc -l
# Check for multiple TER/END records
grep -E "^TER|^END" molecule.pdb2. Verify single molecule per file
- Structure file should contain one molecule
- Use one
numberparameter per structure block
3. Check output statistics
# Count atoms in output
grep "^ATOM" output.pdb | wc -l
# Count residues
grep "^ATOM" output.pdb | awk '{print $6}' | sort -u | wc -lPrevention:
- Keep one molecule per structure file
- Understand
numberparameter means copies - Verify structure files before use
Density Issues
Symptom: System too dense or too dilute
Causes: 1. Wrong number of molecules 2. Incorrect box dimensions 3. Unit confusion
Solutions:
1. Calculate density
python scripts/analyze_density.py output.pdb2. Adjust molecule count
- For water: 1 molecule ≈ 30 ų at 1 g/cm³
- For 40×40×40 Å box: ~64,000 ų → ~2100 water molecules
3. Calculate required molecules
N = (ρ × V) / (M / NA)
ρ = density (g/cm³)
V = volume (cm³)
M = molecular weight (g/mol)
NA = Avogadro's number4. Test density with small system
# Test box
tolerance 2.0
output test.pdb
filetype pdb
structure water.pdb
number 100
inside box 0. 0. 0. 20. 20. 20.
end structurePrevention:
- Calculate approximate molecule count first
- Test with small systems
- Use density analysis scripts
PBC Issues
Symptom: Problems with periodic boundary conditions
Causes: 1. PBC not set correctly 2. Box size mismatch 3. Wrong Packmol version
Solutions:
1. Check Packmol version (PBC requires 20.15.0+)
packmol -h | head -52. Set PBC correctly
# Correct
pbc 0. 0. 0. 40. 40. 60.
# OR for orthorhombic at origin
pbc 40. 40. 60.3. Match box constraints to PBC
pbc 0. 0. 0. 40. 40. 60.
structure water.pdb
number 2000
inside box 0. 0. 0. 40. 40. 60. # Matches PBC
end structure4. Update Packmol if needed
pip install --upgrade packmolPrevention:
- Use Packmol 20.15.0 or later for PBC
- Ensure box constraints match PBC region
- Verify output has correct dimensions
File Format Issues
Symptom: Packmol can't read structure files
Causes: 1. Wrong format 2. Missing required fields 3. Non-standard PDB format
Solutions:
1. Verify PDB format
ATOM 1 O HOH 1 0.000 0.000 0.000 1.00 0.00
1234567890123456789012345678901234567890123456789012345678901234567890
^^ ^ ^ ^^ ^^^^^^^^^^^^^^^^
| | | | coordinates
| | | residue number
| | residue name
| atom name
element (columns 13-14)2. Check required columns
- Columns 1-6: "ATOM"
- Columns 13-14: Element symbol
- Columns 31-54: XYZ coordinates
3. Fix element names
# Wrong
ATOM 1 CA ALA 1 0.000 0.000 0.000
# Right
ATOM 1 CA ALA 1 0.000 0.000 0.000
^^
Right-justified element name4. Convert formats if needed
- Use Open Babel:
obabel -h input.xyz -opdb - Use MDAnalysis
- Use VMD/PyMOL
Prevention:
- Use standard PDB format
- Verify element columns (13-14)
- Test with simple molecule first
Performance Issues
Slow Optimization
Symptom: Packmol takes too long
Causes: 1. System too large 2. Small tolerance 3. Complex constraints 4. Too many molecule types
Solutions:
1. Reduce system size
- Fewer molecules
- Smaller box
2. Increase tolerance
tolerance 2.5 # Faster than 2.03. Simplify constraints
- Use box instead of complex shapes
- Reduce number of constraint types
4. Adjust optimization parameters
discale 1.5 # Faster convergence
maxit 15 # Fewer iterations5. Use restart files for very large systems
Prevention:
- Test with small systems
- Estimate runtime before large runs
- Use appropriate tolerance
Memory Issues
Symptom: System swaps or becomes unresponsive
Solutions:
1. Close other applications 2. Reduce system size 3. Use restart files 4. Run on machine with more RAM
Output Quality Issues
High Objective Function Value
Symptom: Final objective function > 0.1
Cause: Packing not optimal
Solutions:
1. Check violations in output
Maximum violation of target distance: X.XXX
Maximum violation of the constraints: Y.YYY2. Rerun with different seed
seed 54321 # Different random initial configuration3. Increase optimization effort
maxit 50
precision 0.0014. Accept if violations < 0.01
- Small violations are acceptable
- MD equilibration will fix minor overlaps
Gaps in Structure
Symptom: Empty spaces in output
Causes: 1. Tolerance too large 2. Not enough molecules 3. Constraint geometry
Solutions:
1. Reduce tolerance
tolerance 1.82. Increase molecule count
number 1200 # Was 10003. Check density with script
python scripts/analyze_density.py output.pdbGetting Help
Information to Provide
When asking for help, include:
1. Complete input file 2. Error message (full text) 3. Packmol version
packmol -h | head -54. System size (number of atoms/molecules) 5. What you've tried
Useful Commands
# Validate input
python scripts/validate_input.py input.inp
# Check overlaps
python scripts/check_overlaps.py output.pdb --tolerance 2.0
# Verify success
python scripts/verify_success.py input.inp output.pdb
# Analyze density
python scripts/analyze_density.py output.pdb
# Count atoms
grep "^ATOM" output.pdb | wc -lResources
Diagnostic Flowchart
System fails?
│
├─ "Killed" error?
│ └─→ Reduce system size or use restart files
│
├─ "No solution found"?
│ └─→ Reduce molecule count or increase region
│
├─ Won't converge?
│ └─→ Increase discale, maxit, or reduce complexity
│
├─ Wrong geometry?
│ └─→ Use check keyword, verify constraint syntax
│
├─ Overlaps in output?
│ └─→ Increase tolerance, check radii
│
└─ Other?
└─→ Validate input, test with minimal systemPrevention Checklist
Before running large systems:
- [ ] Test with minimal system (10-50 molecules)
- [ ] Validate input file syntax
- [ ] Check constraint geometry with
checkkeyword - [ ] Calculate expected density
- [ ] Estimate memory requirements
- [ ] Set random seed for reproducibility
- [ ] Verify all structure files exist
- [ ] Check PDB format compliance
- [ ] Document your input parameters
Related Topics
- Parameters reference - Parameter details and defaults
- Constraints reference - Constraint syntax and examples
- File formats - Input file requirements
For more help:
- Main skill documentation: SKILL.md
- Example files: examples/
#!/usr/bin/env python3
"""
Analyze density and composition of PDB files.
This script calculates the density, mass, and composition of molecular
systems from PDB files, useful for verifying Packmol output quality.
Usage:
python analyze_density.py output.pdb
Example:
python analyze_density.py system.pdb --target-density 1.0
"""
import sys
import argparse
from pathlib import Path
from typing import Dict, List, Tuple
import math
# Atomic masses (IUPAC atomic weights)
ATOMIC_MASSES = {
'H': 1.008, 'C': 12.011, 'N': 14.007, 'O': 15.999,
'P': 30.974, 'S': 32.06, 'Na': 22.990, 'K': 39.098,
'CL': 35.45, 'CA': 40.078, 'MG': 24.305, 'FE': 55.845,
'ZN': 65.38, 'CU': 63.546, 'MN': 54.938, 'CO': 58.933,
'F': 18.998, 'BR': 79.904, 'I': 126.90, 'SE': 78.971,
}
class Atom:
"""Represent an atom from a PDB file."""
def __init__(self, line: str):
"""Parse atom from PDB line."""
self.serial = int(line[6:11].strip())
self.name = line[12:16].strip()
self.alt_loc = line[16:17].strip()
self.res_name = line[17:20].strip()
self.chain = line[21:22].strip()
self.res_seq = int(line[22:26].strip())
self.x = float(line[30:38].strip())
self.y = float(line[38:46].strip())
self.z = float(line[46:54].strip())
self.element = self._get_element(line)
self.mass = ATOMIC_MASSES.get(self.element, 0.0)
def _get_element(self, line: str) -> str:
"""Extract element symbol from atom name."""
# Try columns 13-14 first (standard PDB)
elem = line[12:14].strip().upper()
if elem and elem[0].isalpha():
# Check if two-letter element
if len(elem) == 2 and elem[1].isalpha():
return elem
# Single letter element
if len(elem) == 1:
return elem
# Fallback: parse from atom name
name = self.name.upper()
# Remove numbers
name = ''.join(c for c in name if c.isalpha())
# Try two-letter element
if len(name) >= 2 and name[:2] in ATOMIC_MASSES:
return name[:2]
# Try single letter
if name and name[0] in ATOMIC_MASSES:
return name[0]
return 'UNKNOWN'
class DensityAnalyzer:
"""Analyze density and composition of PDB files."""
def __init__(self, pdb_file: str):
"""Initialize analyzer with PDB file."""
self.pdb_file = Path(pdb_file)
self.atoms = []
self.box_size = None
self.volume = None
self.mass = None
self.density = None
def read_pdb(self) -> bool:
"""Read PDB file and extract atoms."""
if not self.pdb_file.exists():
print(f"Error: File not found: {self.pdb_file}")
return False
try:
with open(self.pdb_file, 'r') as f:
for line in f:
if line.startswith('ATOM') or line.startswith('HETATM'):
try:
atom = Atom(line)
self.atoms.append(atom)
except (ValueError, IndexError):
print(f"Warning: Could not parse line: {line.strip()}")
return True
except Exception as e:
print(f"Error reading file: {e}")
return False
def calculate_box_size(self) -> Tuple[float, float, float]:
"""Calculate box dimensions from atom coordinates."""
if not self.atoms:
return (0.0, 0.0, 0.0)
x_coords = [atom.x for atom in self.atoms]
y_coords = [atom.y for atom in self.atoms]
z_coords = [atom.z for atom in self.atoms]
x_min, x_max = min(x_coords), max(x_coords)
y_min, y_max = min(y_coords), max(y_coords)
z_min, z_max = min(z_coords), max(z_coords)
x_size = x_max - x_min
y_size = y_max - y_min
z_size = z_max - z_min
self.box_size = (x_size, y_size, z_size)
return self.box_size
def calculate_volume(self) -> float:
"""Calculate system volume."""
if self.box_size is None:
self.calculate_box_size()
# Assume rectangular box
x, y, z = self.box_size
self.volume = x * y * z
return self.volume
def calculate_mass(self) -> float:
"""Calculate total system mass."""
total_mass = sum(atom.mass for atom in self.atoms if atom.mass > 0)
self.mass = total_mass
return self.mass
def calculate_density(self) -> float:
"""Calculate system density in g/cm³."""
if self.volume is None:
self.calculate_volume()
if self.mass is None:
self.calculate_mass()
# Convert ų to cm³: 1 Å = 10^-8 cm, 1 ų = 10^-24 cm³
volume_cm3 = self.volume * 1e-24
if volume_cm3 > 0:
# Density = mass / volume
self.density = self.mass / volume_cm3
else:
self.density = 0.0
return self.density
def analyze_composition(self) -> Dict[str, int]:
"""Analyze system composition."""
composition = {}
# Count by element
elements = {}
for atom in self.atoms:
elements[atom.element] = elements.get(atom.element, 0) + 1
# Count by residue
residues = {}
for atom in self.atoms:
key = f"{atom.res_name}:{atom.chain}"
residues[key] = residues.get(key, 0) + 1
composition['elements'] = elements
composition['residues'] = residues
composition['total_atoms'] = len(self.atoms)
composition['unique_elements'] = len(elements)
composition['unique_residues'] = len(residues)
return composition
def estimate_water_count(self) -> int:
"""Estimate number of water molecules."""
water_count = 0
for atom in self.atoms:
if atom.res_name.strip() in ['HOH', 'WAT', 'TIP3']:
# Count by residue sequence
water_count = max(water_count, atom.res_seq)
return water_count
def print_report(self, target_density: float = None):
"""Print analysis report."""
if not self.atoms:
print("Error: No atoms found in PDB file")
return
print("="*60)
print("DENSITY ANALYSIS REPORT")
print("="*60)
print(f"\nPDB file: {self.pdb_file}")
print(f"Total atoms: {len(self.atoms)}")
# Box dimensions
box = self.calculate_box_size()
print(f"\nBox dimensions:")
print(f" X: {box[0]:.2f} Å")
print(f" Y: {box[1]:.2f} Å")
print(f" Z: {box[2]:.2f} Å")
# Volume
volume = self.calculate_volume()
print(f"\nVolume: {volume:.2f} ų = {volume * 1e-24:.2e} cm³")
# Mass
mass = self.calculate_mass()
print(f"\nTotal mass: {mass:.2f} Da = {mass / 6.022e23:.2e} g")
# Density
density = self.calculate_density()
print(f"\nDensity: {density:.3f} g/cm³")
if target_density:
diff = density - target_density
pct = (diff / target_density) * 100
print(f"Target: {target_density:.3f} g/cm³")
print(f"Difference: {diff:+.3f} g/cm³ ({pct:+.1f}%)")
if abs(diff) < 0.1:
print("✓ Density is close to target!")
elif diff > 0:
print("⚠ Density is higher than target (too many molecules)")
else:
print("⚠ Density is lower than target (too few molecules)")
# Composition
composition = self.analyze_composition()
print(f"\n" + "-"*60)
print("COMPOSITION")
print("-"*60)
print(f"\nUnique elements: {composition['unique_elements']}")
print("Element distribution:")
elements = composition['elements']
sorted_elements = sorted(elements.items(), key=lambda x: x[1], reverse=True)
for element, count in sorted_elements[:15]:
mass = count * ATOMIC_MASSES.get(element, 0)
pct = (mass / self.mass) * 100 if self.mass > 0 else 0
print(f" {element:3s}: {count:6d} atoms ({pct:5.1f}% mass)")
# Water count
water_count = self.estimate_water_count()
if water_count > 0:
print(f"\nEstimated water molecules: {water_count}")
if volume > 0:
vol_per_water = volume / water_count
print(f" Volume per water: {vol_per_water:.1f} ų")
print(f" (Expected: ~30 ų at 1.0 g/cm³)")
# Top residues
if composition['unique_residues'] > 0:
print(f"\nUnique residue types: {composition['unique_residues']}")
residues = composition['residues']
sorted_residues = sorted(residues.items(), key=lambda x: x[1], reverse=True)
print("Top residue types:")
for residue, count in sorted_residues[:10]:
print(f" {residue}: {count} atoms")
print("="*60)
def suggest_molecule_count(self, target_density: float = 1.0) -> int:
"""Suggest molecule count for target density."""
if self.volume is None:
self.calculate_volume()
if self.mass is None:
self.calculate_mass()
# Current density
current_density = self.density if self.density else self.calculate_density()
if current_density == 0:
return 0
# Suggested scaling
scaling_factor = target_density / current_density
# Estimate based on atoms
suggested_atoms = int(len(self.atoms) * scaling_factor)
print(f"\nSuggestions for {target_density:.2f} g/cm³ density:")
print(f" Scale molecule count by: {scaling_factor:.2f}x")
print(f" Suggested total atoms: {suggested_atoms}")
print(f" Change: {suggested_atoms - len(self.atoms):+d} atoms")
return suggested_atoms
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description='Analyze density and composition of PDB files',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Analyze density
python analyze_density.py system.pdb
# Compare to target density
python analyze_density.py system.pdb --target-density 1.0
# Get suggestions for correct density
python analyze_density.py system.pdb --target-density 1.0 --suggest
Typical densities:
Water: 1.0 g/cm³
Proteins in water: ~1.0-1.4 g/cm³ (depends on protein content)
Pure organic liquids: 0.7-1.5 g/cm³ (depends on molecule)
"""
)
parser.add_argument('pdb_file', help='PDB file to analyze')
parser.add_argument('--target-density', type=float, default=None,
help='Target density for comparison (g/cm³)')
parser.add_argument('--suggest', action='store_true',
help='Suggest molecule count for target density')
args = parser.parse_args()
# Create analyzer
analyzer = DensityAnalyzer(args.pdb_file)
# Read PDB
if not analyzer.read_pdb():
sys.exit(1)
# Print report
analyzer.print_report(args.target_density)
# Suggest if requested
if args.suggest and args.target_density:
analyzer.suggest_molecule_count(args.target_density)
# Exit with appropriate code
if args.target_density and analyzer.density:
diff = abs(analyzer.density - args.target_density)
if diff > 0.2: # More than 20% difference
sys.exit(1)
sys.exit(0)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Check for atomic overlaps in Packmol output PDB files.
This script reads a PDB file and checks for atoms that are closer than
the specified tolerance, indicating potential overlaps that should be
resolved before using the structure in MD simulations.
Usage:
python check_overlaps.py output.pdb --tolerance 2.0
Example:
python check_overlaps.py system.pdb --tolerance 2.0
"""
import sys
import argparse
from pathlib import Path
from typing import List, Tuple, Dict
import math
class Atom:
"""Represent an atom from a PDB file."""
def __init__(self, line: str):
"""Parse atom from PDB line."""
self.serial = int(line[6:11].strip())
self.name = line[12:16].strip()
self.alt_loc = line[16:17].strip()
self.res_name = line[17:20].strip()
self.chain = line[21:22].strip()
self.res_seq = int(line[22:26].strip())
self.x = float(line[30:38].strip())
self.y = float(line[38:46].strip())
self.z = float(line[46:54].strip())
self.element = line[12:14].strip().replace(' ', '')
self.line = line
def __repr__(self):
"""String representation."""
return f"{self.element}{self.serial}/{self.res_name}{self.res_seq}"
class OverlapChecker:
"""Check for atomic overlaps in PDB files."""
def __init__(self, pdb_file: str, tolerance: float):
"""Initialize checker with PDB file and tolerance."""
self.pdb_file = Path(pdb_file)
self.tolerance = tolerance
self.atoms = []
self.overlaps = []
def read_pdb(self) -> bool:
"""Read PDB file and extract atoms."""
if not self.pdb_file.exists():
print(f"Error: File not found: {self.pdb_file}")
return False
try:
with open(self.pdb_file, 'r') as f:
for line in f:
if line.startswith('ATOM') or line.startswith('HETATM'):
try:
atom = Atom(line)
self.atoms.append(atom)
except (ValueError, IndexError) as e:
print(f"Warning: Could not parse line: {line.strip()}")
return True
except Exception as e:
print(f"Error reading file: {e}")
return False
def calculate_distance(self, atom1: Atom, atom2: Atom) -> float:
"""Calculate distance between two atoms."""
dx = atom1.x - atom2.x
dy = atom1.y - atom2.y
dz = atom1.z - atom2.z
return math.sqrt(dx*dx + dy*dy + dz*dz)
def check_overlaps(self):
"""Check for overlapping atoms."""
n_atoms = len(self.atoms)
print(f"Checking {n_atoms} atoms for overlaps < {self.tolerance} Å...\n")
# Check all pairs
for i in range(n_atoms):
atom1 = self.atoms[i]
# Skip same residue (intramolecular)
for j in range(i + 1, n_atoms):
atom2 = self.atoms[j]
# Skip if same molecule/residue
if atom1.res_seq == atom2.res_seq and atom1.chain == atom2.chain:
continue
# Calculate distance
dist = self.calculate_distance(atom1, atom2)
# Check for overlap
if dist < self.tolerance:
self.overlaps.append({
'atom1': atom1,
'atom2': atom2,
'distance': dist,
'violation': self.tolerance - dist
})
def report_overlaps(self, max_display: int = 20):
"""Generate overlap report."""
if not self.overlaps:
print("✓ No overlaps found!")
print(f" All atom pairs are >= {self.tolerance} Å apart.")
return
# Sort by violation magnitude
self.overlaps.sort(key=lambda x: x['violation'], reverse=True)
print(f"❌ Found {len(self.overlaps)} overlapping atom pairs!\n")
# Display worst violations
display_count = min(max_display, len(self.overlaps))
print(f"Top {display_count} worst violations:\n")
for i, overlap in enumerate(self.overlaps[:display_count], 1):
atom1 = overlap['atom1']
atom2 = overlap['atom2']
dist = overlap['distance']
violation = overlap['violation']
print(f"{i}. {atom1} - {atom2}")
print(f" Distance: {dist:.3f} Å (violation: {violation:.3f} Å)")
if len(self.overlaps) > max_display:
print(f"\n... and {len(self.overlaps) - max_display} more overlaps")
# Statistics
print("\n" + "="*60)
print("Statistics:")
print("="*60)
violations = [o['violation'] for o in self.overlaps]
print(f" Mean violation: {sum(violations)/len(violations):.3f} Å")
print(f" Max violation: {max(violations):.3f} Å")
print(f" Min violation: {min(violations):.3f} Å")
print(f" Total overlaps: {len(self.overlaps)}")
# Distribution
small = sum(1 for v in violations if v < 0.1)
medium = sum(1 for v in violations if 0.1 <= v < 0.5)
large = sum(1 for v in violations if v >= 0.5)
print("\nViolation distribution:")
print(f" < 0.1 Å: {small:4d} (minor)")
print(f" 0.1-0.5 Å: {medium:4d} (moderate)")
print(f" > 0.5 Å: {large:4d} (severe)")
def get_atom_statistics(self):
"""Print atom statistics."""
if not self.atoms:
return
# Count by element
elements = {}
for atom in self.atoms:
elements[atom.element] = elements.get(atom.element, 0) + 1
print("\nAtom statistics:")
print("-" * 40)
print(f" Total atoms: {len(self.atoms)}")
print(f" Unique elements: {len(elements)}")
# Top elements
sorted_elements = sorted(elements.items(), key=lambda x: x[1], reverse=True)
for element, count in sorted_elements[:10]:
print(f" {element:2s}: {count:6d}")
def check_system_quality(self) -> bool:
"""Check if system quality is acceptable."""
if not self.overlaps:
return True
# Check for severe violations
severe = sum(1 for o in self.overlaps if o['violation'] > 0.5)
moderate = sum(1 for o in self.overlaps if 0.1 < o['violation'] <= 0.5)
if severe > 0:
print("\n" + "!"*60)
print("WARNING: Severe overlaps detected!")
print("The system should not be used for MD simulation without fixing.")
print("!"*60)
return False
elif moderate > 10:
print("\n" + "!"*60)
print("CAUTION: Multiple moderate overlaps detected.")
print("Consider energy minimization before MD simulation.")
print("!"*60)
return False
else:
print("\n" + "*"*60)
print("Minor overlaps detected.")
print("These may be resolved during MD equilibration.")
print("*"*60)
return True
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description='Check for atomic overlaps in PDB files',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Check with default tolerance of 2.0 Å
python check_overlaps.py system.pdb
# Check with custom tolerance
python check_overlaps.py system.pdb --tolerance 1.5
# Show detailed report
python check_overlaps.py system.pdb --tolerance 2.0 --max-display 50
"""
)
parser.add_argument('pdb_file', help='PDB file to check')
parser.add_argument('--tolerance', type=float, default=2.0,
help='Minimum allowed distance between atoms (Å) [default: 2.0]')
parser.add_argument('--max-display', type=int, default=20,
help='Maximum number of overlaps to display [default: 20]')
args = parser.parse_args()
print("="*60)
print("Packmol Overlap Checker")
print("="*60)
print(f"PDB file: {args.pdb_file}")
print(f"Tolerance: {args.tolerance} Å")
print("="*60)
print()
# Create checker
checker = OverlapChecker(args.pdb_file, args.tolerance)
# Read PDB
if not checker.read_pdb():
sys.exit(1)
# Get statistics
checker.get_atom_statistics()
print()
# Check overlaps
checker.check_overlaps()
# Report
checker.report_overlaps(args.max_display)
# Check quality
print()
quality_ok = checker.check_system_quality()
print()
if quality_ok:
sys.exit(0)
else:
sys.exit(1)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Generate Packmol input files programmatically.
This script provides a Python API for creating Packmol input files,
making it easier to generate complex systems programmatically.
Usage (CLI):
python generate_input.py --output system.inp
Usage (Python):
from generate_input import PackmolInput
inp = PackmolInput()
inp.add_tolerance(2.0)
inp.add_structure('water.pdb', 1000, 'inside box 0. 0. 0. 40. 40. 40.')
inp.write('system.inp')
"""
import sys
import argparse
from typing import List, Dict, Optional
class PackmolInput:
"""Generate Packmol input files programmatically."""
def __init__(self):
"""Initialize Packmol input generator."""
self.tolerance = None
self.output = None
self.filetype = 'pdb'
self.pbc = None
self.seed = None
self.discale = None
self.maxit = None
self.precision = None
self.structures = []
self.comments = []
def add_tolerance(self, value: float):
"""Set tolerance parameter."""
if value <= 0:
raise ValueError("Tolerance must be positive")
self.tolerance = value
return self
def add_output(self, filename: str):
"""Set output filename."""
self.output = filename
return self
def add_filetype(self, fmt: str):
"""Set file type (pdb, xyz, or tinker)."""
fmt = fmt.lower()
if fmt not in ['pdb', 'xyz', 'tinker']:
raise ValueError(f"Invalid filetype: {fmt}. Must be pdb, xyz, or tinker")
self.filetype = fmt
return self
def add_pbc(self, *dimensions):
"""Set periodic boundary conditions."""
if len(dimensions) not in [3, 6]:
raise ValueError("PBC requires 3 (orthorhombic) or 6 (box) parameters")
try:
self.pbc = [float(d) for d in dimensions]
except ValueError:
raise ValueError("PBC parameters must be numeric")
return self
def add_seed(self, seed: int):
"""Set random seed."""
self.seed = int(seed)
return self
def add_discale(self, value: float):
"""Set distance scaling factor."""
if value <= 0:
raise ValueError("Discale must be positive")
self.discale = float(value)
return self
def add_maxit(self, value: int):
"""Set maximum iterations."""
if value <= 0:
raise ValueError("Maxit must be positive")
self.maxit = int(value)
return self
def add_precision(self, value: float):
"""Set convergence precision."""
if value <= 0:
raise ValueError("Precision must be positive")
self.precision = float(value)
return self
def add_comment(self, comment: str):
"""Add a comment line."""
self.comments.append(comment)
return self
def add_structure(self, filename: str, number: int, constraint: str, **kwargs):
"""
Add a structure definition.
Args:
filename: Path to structure file
number: Number of molecules
constraint: Constraint string (e.g., 'inside box 0. 0. 0. 40. 40. 40.')
**kwargs: Additional parameters (chain, radius, resnumbers, etc.)
Returns:
self for method chaining
"""
if number <= 0:
raise ValueError("Number of molecules must be positive")
structure = {
'filename': filename,
'number': number,
'constraint': constraint,
'chain': kwargs.get('chain'),
'radius': kwargs.get('radius'),
'resnumbers': kwargs.get('resnumbers'),
'fixed': kwargs.get('fixed'),
'center': kwargs.get('center', False),
'constrain_rotation': kwargs.get('constrain_rotation'),
'movefrac': kwargs.get('movefrac'),
'maxmove': kwargs.get('maxmove'),
'disable_movebad': kwargs.get('disable_movebad', False),
'check': kwargs.get('check', False),
'atoms': kwargs.get('atoms'),
}
self.structures.append(structure)
return self
def validate(self) -> List[str]:
"""
Validate input parameters.
Returns:
List of error messages (empty if valid)
"""
errors = []
# Check required parameters
if self.tolerance is None:
errors.append("Missing required parameter: tolerance")
if self.output is None:
errors.append("Missing required parameter: output")
if not self.structures:
errors.append("No structures defined")
# Validate structures
for i, struct in enumerate(self.structures, 1):
if not struct['filename']:
errors.append(f"Structure {i}: Missing filename")
if struct['number'] <= 0:
errors.append(f"Structure {i}: Invalid number")
return errors
def generate(self) -> str:
"""
Generate Packmol input file content.
Returns:
Input file content as string
"""
# Validate first
errors = self.validate()
if errors:
raise ValueError("Invalid input:\n" + "\n".join(errors))
lines = []
# Add comments
if self.comments:
for comment in self.comments:
lines.append(f"# {comment}")
lines.append("")
# Required parameters
lines.append(f"tolerance {self.tolerance}")
lines.append(f"filetype {self.filetype}")
lines.append(f"output {self.output}")
lines.append("")
# Optional parameters
if self.pbc:
pbc_str = " ".join(str(v) for v in self.pbc)
lines.append(f"pbc {pbc_str}")
if self.seed is not None:
lines.append(f"seed {self.seed}")
if self.discale:
lines.append(f"discale {self.discale}")
if self.maxit:
lines.append(f"maxit {self.maxit}")
if self.precision:
lines.append(f"precision {self.precision}")
if self.pbc or self.seed or self.discale or self.maxit or self.precision:
lines.append("")
# Structure definitions
for struct in self.structures:
lines.append(f"structure {struct['filename']}")
lines.append(f" number {struct['number']}")
# Constraint
lines.append(f" {struct['constraint']}")
# Optional parameters
if struct['fixed']:
fixed = struct['fixed']
if isinstance(fixed, (list, tuple)):
fixed_str = " ".join(str(v) for v in fixed)
lines.append(f" fixed {fixed_str}")
else:
lines.append(f" fixed {fixed}")
if struct['center']:
lines.append(f" center")
if struct['chain']:
lines.append(f" chain {struct['chain']}")
if struct['radius']:
lines.append(f" radius {struct['radius']}")
if struct['resnumbers']:
lines.append(f" resnumbers {struct['resnumbers']}")
if struct['constrain_rotation']:
rot = struct['constrain_rotation']
if isinstance(rot, (list, tuple)) and len(rot) == 3:
lines.append(f" constrain_rotation {rot[0]} {rot[1]} {rot[2]}")
if struct['movefrac']:
lines.append(f" movefrac {struct['movefrac']}")
if struct['maxmove']:
lines.append(f" maxmove {struct['maxmove']}")
if struct['disable_movebad']:
lines.append(f" disable_movebad")
if struct['check']:
lines.append(f" check")
# Atom selection
if struct['atoms']:
atoms = struct['atoms']
if isinstance(atoms, (list, tuple)):
atom_str = " ".join(str(a) for a in atoms)
lines.append(f" atoms {atom_str}")
# Check if there are constraints for these atoms
# (This is simplified; full implementation would be more complex)
lines.append("end structure")
lines.append("")
return "\n".join(lines)
def write(self, filename: str):
"""
Write input file to disk.
Args:
filename: Output filename
"""
content = self.generate()
with open(filename, 'w') as f:
f.write(content)
return self
def __str__(self):
"""String representation."""
return self.generate()
# Convenience functions for common systems
def create_simple_box(molecule_file: str, n_molecules: int,
box_size: tuple, tolerance: float = 2.0,
output_file: str = "system.pdb") -> PackmolInput:
"""Create a simple box system."""
xmin, ymin, zmin = 0, 0, 0
xmax, ymax, zmax = box_size
inp = PackmolInput()
inp.add_tolerance(tolerance)
inp.add_output(output_file)
inp.add_structure(
molecule_file,
n_molecules,
f"inside box {xmin:.1f} {ymin:.1f} {zmin:.1f} {xmax:.1f} {ymax:.1f} {zmax:.1f}"
)
return inp
def create_mixture(molecules: list, box_size: tuple,
tolerance: float = 2.0,
output_file: str = "mixture.pdb") -> PackmolInput:
"""
Create a mixture of multiple molecule types.
Args:
molecules: List of (filename, count) tuples
box_size: (xmax, ymax, zmax) tuple
tolerance: Tolerance value
output_file: Output filename
"""
xmax, ymax, zmax = box_size
inp = PackmolInput()
inp.add_tolerance(tolerance)
inp.add_output(output_file)
for mol_file, n_mol in molecules:
inp.add_structure(
mol_file,
n_mol,
f"inside box 0. 0. 0. {xmax:.1f} {ymax:.1f} {zmax:.1f}"
)
return inp
def create_solvation(protein_file: str, box_size: tuple,
n_water: int, n_cations: int = 0, n_anions: int = 0,
tolerance: float = 2.0,
output_file: str = "solvated.pdb") -> PackmolInput:
"""
Create a solvated protein system.
Args:
protein_file: Path to protein PDB file
box_size: (xmax, ymax, zmax) tuple
n_water: Number of water molecules
n_cations: Number of cations (e.g., Na+)
n_anions: Number of anions (e.g., Cl-)
tolerance: Tolerance value
output_file: Output filename
"""
xmax, ymax, zmax = box_size
center_x, center_y, center_z = xmax/2, ymax/2, zmax/2
inp = PackmolInput()
inp.add_tolerance(tolerance)
inp.add_output(output_file)
inp.add_pbc(0., 0., 0., xmax, ymax, zmax)
# Fixed protein at center
inp.add_structure(
protein_file,
1,
f"fixed {center_x:.1f} {center_y:.1f} {center_z:.1f} 0. 0. 0.",
center=True,
chain='A'
)
# Water
inp.add_structure(
'water.pdb',
n_water,
f"inside box 0. 0. 0. {xmax:.1f} {ymax:.1f} {zmax:.1f}",
chain='W'
)
# Cations (if specified)
if n_cations > 0:
inp.add_structure(
'SOD.pdb',
n_cations,
f"inside box 0. 0. 0. {xmax:.1f} {ymax:.1f} {zmax:.1f}",
chain='NA'
)
# Anions (if specified)
if n_anions > 0:
inp.add_structure(
'CLA.pdb',
n_anions,
f"inside box 0. 0. 0. {xmax:.1f} {ymax:.1f} {zmax:.1f}",
chain='CL'
)
return inp
def create_interface(phase1_file: str, n_phase1: int,
phase2_file: str, n_phase2: int,
box_size: tuple, interface_z: float = 0.0,
tolerance: float = 2.0,
output_file: str = "interface.pdb") -> PackmolInput:
"""
Create a liquid-liquid interface system.
Args:
phase1_file: Molecule file for phase 1 (below interface)
n_phase1: Number of molecules in phase 1
phase2_file: Molecule file for phase 2 (above interface)
n_phase2: Number of molecules in phase 2
box_size: (xmax, ymax, zmax) tuple
interface_z: Z-coordinate of interface
tolerance: Tolerance value
output_file: Output filename
"""
xmax, ymax, zmax = box_size
inp = PackmolInput()
inp.add_tolerance(tolerance)
inp.add_output(output_file)
inp.add_pbc(0., 0., 0., xmax, ymax, zmax)
# Phase 1 (below interface)
inp.add_structure(
phase1_file,
n_phase1,
f"below plane 0. 0. 1. {interface_z:.1f}",
chain='P1'
)
# Phase 2 (above interface)
inp.add_structure(
phase2_file,
n_phase2,
f"above plane 0. 0. 1. {interface_z:.1f}",
chain='P2'
)
return inp
def main():
"""Main entry point for CLI usage."""
parser = argparse.ArgumentParser(
description='Generate Packmol input files programmatically',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Simple water box
python generate_input.py --molecule water.pdb --number 1000 \\
--box 40 40 40 --output water_box.inp
# Mixture
python generate_input.py --molecule water.pdb --number 800 \\
--molecule ethanol.pdb --number 200 --box 40 40 40 \\
--output mixture.inp
# Solvated protein
python generate_input.py --protein protein.pdb --water 5000 \\
--box 60 60 80 --cations 10 --anions 10 --output solvated.inp
# Interface
python generate_input.py --interface \\
--phase1 water.pdb 1000 --phase2 chloroform.pdb 200 \\
--box 40 40 60 --output interface.inp
"""
)
# General options
parser.add_argument('--output', required=True, help='Output input file name')
parser.add_argument('--tolerance', type=float, default=2.0,
help='Tolerance value [default: 2.0]')
# Simple box mode
parser.add_argument('--molecule', help='Molecule file (for simple box)')
parser.add_argument('--number', type=int, help='Number of molecules')
parser.add_argument('--box', nargs=3, type=float, metavar=('X', 'Y', 'Z'),
help='Box size (Å)')
# Solvation mode
parser.add_argument('--protein', help='Protein file (for solvation)')
parser.add_argument('--water', type=int, help='Number of water molecules')
parser.add_argument('--cations', type=int, default=0, help='Number of cations')
parser.add_argument('--anions', type=int, default=0, help='Number of anions')
# Interface mode
parser.add_argument('--interface', action='store_true',
help='Create interface system')
parser.add_argument('--phase1', nargs=2, metavar=('FILE', 'N'),
help='Phase 1: file and count')
parser.add_argument('--phase2', nargs=2, metavar=('FILE', 'N'),
help='Phase 2: file and count')
args = parser.parse_args()
inp = None
# Determine mode
if args.interface:
# Interface mode
if not args.phase1 or not args.phase2 or not args.box:
print("Error: Interface mode requires --phase1, --phase2, and --box")
sys.exit(1)
phase1_file, n1 = args.phase1
phase2_file, n2 = args.phase2
n1, n2 = int(n1), int(n2)
inp = create_interface(
phase1_file, n1,
phase2_file, n2,
tuple(args.box),
tolerance=args.tolerance,
output_file=args.output.replace('.inp', '.pdb')
)
elif args.protein:
# Solvation mode
if not args.box or not args.water:
print("Error: Solvation mode requires --box and --water")
sys.exit(1)
inp = create_solvation(
args.protein,
tuple(args.box),
args.water,
args.cations,
args.anions,
tolerance=args.tolerance,
output_file=args.output.replace('.inp', '.pdb')
)
elif args.molecule and args.number and args.box:
# Simple box mode
inp = create_simple_box(
args.molecule,
args.number,
tuple(args.box),
tolerance=args.tolerance,
output_file=args.output.replace('.inp', '.pdb')
)
else:
print("Error: Must specify --molecule/--number/--box, --protein, or --interface")
parser.print_help()
sys.exit(1)
# Write input file
inp.write(args.output)
print(f"Generated Packmol input file: {args.output}")
print(f"Output will be written to: {args.output.replace('.inp', '.pdb')}")
if __name__ == "__main__":
main()
# Packmol input template for basic box packing
#
# Instructions:
# 1. Replace values in brackets with your parameters
# 2. Remove or comment out lines you don't need
# 3. Save with a .inp extension
# 4. Run: packmol < your_file.inp
# ============================================================================
# Required parameters
# ============================================================================
tolerance 2.0 # Minimum distance between atoms (Angstroms)
filetype pdb # Input/output format: pdb, xyz, or tinker
output system.pdb # Output filename
# ============================================================================
# Optional global parameters
# ============================================================================
# seed 12345 # Random seed for reproducibility (or -1 for auto)
# discale 1.0 # Distance scaling factor for optimization
# maxit 20 # Maximum optimization iterations
# precision 0.01 # Convergence precision
# ============================================================================
# Structure definitions
# ============================================================================
# Define each molecule type to pack
# Replace MOLECULE.pdb with your structure file
# Replace N with the number of molecules
# Replace box coordinates with your desired region
structure MOLECULE.pdb
number N # Number of molecules
inside box xmin ymin zmin xmax ymax zmax # Spatial constraint
end structure
# ============================================================================
# Additional structure examples (uncomment and modify as needed)
# ============================================================================
# For multiple molecule types, add more structure blocks:
#
# structure water.pdb
# number 800
# inside box 0. 0. 0. 40. 40. 40.
# end structure
#
# structure ethanol.pdb
# number 200
# inside box 0. 0. 0. 40. 40. 40.
# end structure
# For different constraint types:
#
# structure molecule.pdb
# number 100
# inside sphere xcenter ycenter zcenter radius
# end structure
#
# structure molecule.pdb
# number 100
# inside cylinder x1 y1 z1 dx dy dz radius length
# end structure
# ============================================================================
# Notes
# ============================================================================
# - All coordinates are in Angstroms
# - Use 'inside' or 'outside' for spatial constraints
# - Box constraint: inside box xmin ymin zmin xmax ymax zmax
# - Sphere constraint: inside sphere xc yc zc radius
# - Common tolerance values:
# * 2.0 Å for all-atom models
# * 2.5-3.0 Å for united-atom models
# * Larger for coarse-grained models
Related skills
FAQ
How is Packmol installed?
Install via pip install packmol and verify with packmol -h.
What constraint types does it support?
box, sphere, cylinder, plane (above/below), and ellipsoid constraints.