Skip to content

Pack

The pack module handles packing of molecules into a simulation box.

MolPack

Molpack - High-level molecular packing interface.

This module provides the main entry point for molecular packing using Packmol.

Molpack

Molpack(workdir)

High-level molecular packing interface.

This class provides a clean API for molecular packing using Packmol backend.

Usage

packer = Molpack(workdir=Path("packing")) packer.add_target(frame, number=100, constraint=box_constraint) result = packer.optimize(max_steps=1000, seed=42)

Initialize Molpack.

Parameters:

Name Type Description Default
workdir Path

Working directory for packing operations

required
Source code in src/molpy/pack/molpack.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def __init__(
    self,
    workdir: Path,
):
    """
    Initialize Molpack.

    Args:
        workdir: Working directory for packing operations
    """
    if not workdir.exists():
        workdir.mkdir(parents=True, exist_ok=True)
    self.workdir = workdir
    self.targets = []
    self.packer = get_packer(workdir=workdir)

add_target

add_target(frame, number, constraint)

Add a packing target.

Parameters:

Name Type Description Default
frame Frame

Frame containing the molecule structure

required
number int

Number of copies to pack

required
constraint Constraint

Spatial constraint for packing

required

Returns:

Type Description
Target

Target object

Source code in src/molpy/pack/molpack.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def add_target(self, frame: Frame, number: int, constraint: "Constraint") -> Target:
    """
    Add a packing target.

    Args:
        frame: Frame containing the molecule structure
        number: Number of copies to pack
        constraint: Spatial constraint for packing

    Returns:
        Target object
    """
    target = Target(frame, number, constraint)
    self.targets.append(target)
    self.packer.add_target(target)
    return target

optimize

optimize(max_steps=1000, seed=None)

Run packing optimization.

Parameters:

Name Type Description Default
max_steps int

Maximum optimization steps

1000
seed int | None

Random seed. If None, uses random seed.

None

Returns:

Type Description
Frame

Packed Frame

Source code in src/molpy/pack/molpack.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def optimize(self, max_steps: int = 1000, seed: int | None = None) -> Frame:
    """
    Run packing optimization.

    Args:
        max_steps: Maximum optimization steps
        seed: Random seed. If None, uses random seed.

    Returns:
        Packed Frame
    """
    if seed is None:
        seed = random.randint(1, 10000)
    # Use __call__ method instead of legacy pack() method
    return self.packer(self.targets, max_steps=max_steps, seed=seed)

Constraint

Constraint

Base class for all packing constraints.

dpenalty

dpenalty(points)

Calculate gradient of penalty with respect to points.

Source code in src/molpy/pack/constraint.py
14
15
16
def dpenalty(self, points: np.ndarray) -> np.ndarray:
    """Calculate gradient of penalty with respect to points."""
    raise NotImplementedError

penalty

penalty(points)

Calculate penalty for given points. Lower is better.

Source code in src/molpy/pack/constraint.py
10
11
12
def penalty(self, points: np.ndarray) -> float:
    """Calculate penalty for given points. Lower is better."""
    raise NotImplementedError

Target

Target

Target(frame, number, constraint, is_fixed=False, name='')
Source code in src/molpy/pack/target.py
15
16
17
18
19
20
21
22
23
24
25
26
27
def __init__(
    self,
    frame: Frame,
    number: int,
    constraint: "Constraint",
    is_fixed: bool = False,
    name: str = "",
):
    self.frame = frame
    self.number = number
    self.constraint = constraint
    self.is_fixed = is_fixed
    self.name = name

points property

points

Get all points (coordinates replicated for each copy).

Packer

Packer

Packer()

Bases: ABC

Base class for all packer implementations.

Source code in src/molpy/pack/packer/base.py
17
18
def __init__(self):
    self.targets: list[Target] = []

add_target

add_target(target)

Add a target to the packer.

Source code in src/molpy/pack/packer/base.py
20
21
22
def add_target(self, target: Target) -> None:
    """Add a target to the packer."""
    self.targets.append(target)

def_target

def_target(frame, number, constraint, is_fixed=False, name='')

Define a target for packing.

Parameters:

Name Type Description Default
frame Frame

Frame containing the molecule structure

required
number int

Number of copies to pack

required
constraint Constraint

Spatial constraint for packing

required
is_fixed bool

Whether this target is fixed

False
name str

Optional name for this target

''

Returns:

Type Description
Target

Created Target object

Source code in src/molpy/pack/packer/base.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def def_target(
    self,
    frame: "Frame",
    number: int,
    constraint: "Constraint",
    is_fixed: bool = False,
    name: str = "",
) -> Target:
    """
    Define a target for packing.

    Args:
        frame: Frame containing the molecule structure
        number: Number of copies to pack
        constraint: Spatial constraint for packing
        is_fixed: Whether this target is fixed
        name: Optional name for this target

    Returns:
        Created Target object
    """
    target = Target(frame, number, constraint, is_fixed, name)
    self.add_target(target)
    return target

pack abstractmethod

pack(targets=None, max_steps=1000, seed=None)

Pack molecules according to targets.

Parameters:

Name Type Description Default
targets list[Target] | None

List of packing targets. If None, uses stored targets.

None
max_steps int

Maximum optimization steps

1000
seed int | None

Random seed for packing

None

Returns:

Type Description
Frame

Packed Frame

Source code in src/molpy/pack/packer/base.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@abstractmethod
def pack(
    self,
    targets: list[Target] | None = None,
    max_steps: int = 1000,
    seed: int | None = None,
) -> "Frame":
    """
    Pack molecules according to targets.

    Args:
        targets: List of packing targets. If None, uses stored targets.
        max_steps: Maximum optimization steps
        seed: Random seed for packing

    Returns:
        Packed Frame
    """
    ...

Packmol

Packmol(executable=None, workdir=None)

Bases: Packer

Packer implementation using Packmol binary.

This class provides a packer that uses Packmol binary for packing molecules.

Usage

packer = Packmol(executable="packmol") result = packer(targets, max_steps=1000, seed=4628)

Initialize Packmol packer.

Parameters:

Name Type Description Default
executable str | None

Path to packmol executable. If None, uses: 1. PACKMOL_BIN environment variable 2. "packmol" on PATH

None
workdir Path | None

Working directory for temporary files. If None, creates a temporary directory.

None
Source code in src/molpy/pack/packer/packmol.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def __init__(
    self,
    executable: str | None = None,
    workdir: Path | None = None,
):
    """
    Initialize Packmol packer.

    Args:
        executable: Path to packmol executable. If None, uses:
                   1. PACKMOL_BIN environment variable
                   2. "packmol" on PATH
        workdir: Working directory for temporary files.
                If None, creates a temporary directory.
    """
    Packer.__init__(self)
    self.executable = executable
    self.workdir = workdir

generate_input_only

generate_input_only(targets=None, max_steps=1000, seed=4628, tolerance=2.0, workdir=None)

Generate Packmol input file without running the packing.

Parameters:

Name Type Description Default
targets list[Target] | None

List of packing targets. If None, uses stored targets.

None
max_steps int

Maximum optimization steps

1000
seed int

Random seed for packing

4628
tolerance float

Distance tolerance in Angstroms

2.0
workdir Path | None

Optional working directory

None

Returns:

Type Description
Path

Path to generated input file

Source code in src/molpy/pack/packer/packmol.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
def generate_input_only(
    self,
    targets: list[Target] | None = None,
    max_steps: int = 1000,
    seed: int = 4628,
    tolerance: float = 2.0,
    workdir: Path | None = None,
) -> Path:
    """
    Generate Packmol input file without running the packing.

    Args:
        targets: List of packing targets. If None, uses stored targets.
        max_steps: Maximum optimization steps
        seed: Random seed for packing
        tolerance: Distance tolerance in Angstroms
        workdir: Optional working directory

    Returns:
        Path to generated input file
    """
    if targets is None:
        targets = self.targets

    if not targets:
        raise ValueError("No targets provided")

    workdir = workdir if workdir is not None else self.workdir
    if workdir is None:
        workdir = Path(tempfile.mkdtemp(prefix="molpack_"))
    else:
        workdir = Path(workdir)
        workdir.mkdir(parents=True, exist_ok=True)

    input_file = self._generate_input(targets, max_steps, seed, tolerance, workdir)
    return input_file

generate_input_script

generate_input_script(targets=None, max_steps=1000, seed=4628, tolerance=2.0, workdir=None)

Generate Packmol input script as a Script object without saving.

This allows you to preview, edit, or format the script before saving.

Parameters:

Name Type Description Default
targets list[Target] | None

List of packing targets. If None, uses stored targets.

None
max_steps int

Maximum optimization steps

1000
seed int

Random seed for packing

4628
tolerance float

Distance tolerance in Angstroms

2.0
workdir Path | None

Optional working directory (for structure file paths)

None

Returns:

Type Description
Script

Script object containing Packmol input

Raises:

Type Description
ValueError

If no targets provided

Source code in src/molpy/pack/packer/packmol.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def generate_input_script(
    self,
    targets: list[Target] | None = None,
    max_steps: int = 1000,
    seed: int = 4628,
    tolerance: float = 2.0,
    workdir: Path | None = None,
) -> Script:
    """
    Generate Packmol input script as a Script object without saving.

    This allows you to preview, edit, or format the script before saving.

    Args:
        targets: List of packing targets. If None, uses stored targets.
        max_steps: Maximum optimization steps
        seed: Random seed for packing
        tolerance: Distance tolerance in Angstroms
        workdir: Optional working directory (for structure file paths)

    Returns:
        Script object containing Packmol input

    Raises:
        ValueError: If no targets provided
    """
    if targets is None:
        targets = self.targets

    if not targets:
        raise ValueError("No targets provided")

    workdir = workdir if workdir is not None else self.workdir
    if workdir is None:
        workdir = Path(tempfile.mkdtemp(prefix="molpack_"))
    else:
        workdir = Path(workdir)
        workdir.mkdir(parents=True, exist_ok=True)

    return self._generate_input_script(targets, max_steps, seed, tolerance, workdir)

pack

pack(targets=None, max_steps=1000, seed=None)

Pack molecules using Packmol backend.

This method implements the abstract pack() method from Packer base class. It delegates to call() for the actual implementation.

Source code in src/molpy/pack/packer/packmol.py
619
620
621
622
623
624
625
626
627
628
629
630
def pack(
    self,
    targets: list[Target] | None = None,
    max_steps: int = 1000,
    seed: int | None = None,
) -> Frame:
    """Pack molecules using Packmol backend.

    This method implements the abstract pack() method from Packer base class.
    It delegates to __call__() for the actual implementation.
    """
    return self(targets, max_steps=max_steps, seed=seed)

get_packer

get_packer(*args, **kwargs)

Factory function to get a packer instance.

Currently only supports Packmol backend.

Parameters:

Name Type Description Default
*args Any

Positional arguments passed to Packmol constructor

()
**kwargs Any

Keyword arguments passed to Packmol constructor

{}

Returns:

Type Description
Packmol

Packmol instance

Source code in src/molpy/pack/packer/__init__.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def get_packer(*args: Any, **kwargs: Any) -> Packmol:
    """
    Factory function to get a packer instance.

    Currently only supports Packmol backend.

    Args:
        *args: Positional arguments passed to Packmol constructor
        **kwargs: Keyword arguments passed to Packmol constructor

    Returns:
        Packmol instance
    """
    return Packmol(*args, **kwargs)