Skip to content

Wrapper

Subprocess wrappers for external command-line tools.

Quick reference

Symbol Summary Preferred for
Wrapper Base: run any CLI executable Generic external tools
AntechamberWrapper AMBER antechamber (type + charge assignment) GAFF atom typing
Parmchk2Wrapper AMBER parmchk2 (missing parameter generation) Force field completion
TLeapWrapper AMBER tleap (topology building) System assembly
PrepgenWrapper AMBER prepgen (residue template generation) Polymer residues

Canonical example

from molpy.wrapper import Wrapper

echo = Wrapper(name="echo", exe="echo")
result = echo.run(args=["hello", "world"])
print(result.stdout) # "hello world\n"
print(result.returncode) # 0

Key behavior

  • Environment isolation is owned by EnvSpec (env + env_manager); no auto-detection of manager type
  • Both parameters must be set together, or both omitted for the system PATH
  • Supported managers: conda, venv (aliases: pip, virtualenv)
  • Safe to instantiate even if executable is missing (failure at .run() time)
  • All wrappers accept workdir for controlling working directory

Full API

Environment

env

Process-environment isolation for external tool wrappers.

Users configure isolation explicitly with env + env_manager. There is no auto-detection of manager type from paths or tool layout.

Supported managers
  • None + env is None — system environment (current PATH).
  • "conda"conda run -n <name> or conda run -p <prefix>.
  • "venv" / "pip" / "virtualenv" — inject <prefix>/bin (or Scripts on Windows) into PATH. Covers standard venv, virtualenv, and uv-created environments (same layout).
Path contract

Public entry points accept str | Path (path-like). On resolve, any value that is a path (or looks like one) is converted to :class:~pathlib.Path and stored/used as Path only. Conda env names (no path separators) remain plain str. Subprocess argv receives str(path) at the OS boundary only.

This module is the single owner of env-isolation logic used by :class:~molpy.wrapper.base.Wrapper and higher-level facades that construct wrappers.

EnvSpec dataclass

EnvSpec(env=None, env_manager=None)

Validated subprocess environment isolation.

Construct via :meth:resolve (or :meth:system). After resolve:

  • system — both fields None
  • conda name — env: str, env_manager: "conda"
  • conda prefix / venv — env: Path, env_manager: "conda"|"venv"
is_system property
is_system

True when no isolation is configured.

command_prefix
command_prefix(*, no_capture_output=False)

Return an argv prefix for the configured manager, or [].

For conda this is [conda, run, (-n|-p), <env>]. For venv / system the prefix is empty (isolation is via :meth:merge_environ). Path prefixes are emitted as str(path) for the OS.

Parameters:

Name Type Description Default
no_capture_output bool

When True, insert --no-capture-output after run (useful for engines that stream logs).

False
merge_environ
merge_environ(base=None, extra=None)

Build a subprocess environment dict.

Merge order (later wins): base (default os.environ) → venv PATH / VIRTUAL_ENV injection when applicable → extra.

resolve classmethod
resolve(env=None, env_manager=None)

Validate and normalise user env / env_manager input.

Both must be set together, or both omitted for the system environment. Manager type is never inferred from env. Path-like values are stored as :class:~pathlib.Path.

Parameters:

Name Type Description Default
env str | Path | None

Conda env name / prefix, or venv prefix (str | Path).

None
env_manager str | None

"conda", "venv", "pip", or "virtualenv".

None

Returns:

Type Description
EnvSpec

A frozen :class:EnvSpec.

Raises:

Type Description
ValueError

If exactly one of the pair is set, or the manager string is unsupported.

resolve_executable
resolve_executable(exe)

Best-effort absolute path for exe inside this environment.

exe may be path-like at the public boundary; filesystem paths are converted to :class:~pathlib.Path immediately. Returns a str suitable for subprocess argv, or None if not found.

system classmethod
system()

No isolation — use the current process environment.

Base

base

Base Wrapper class for external package wrappers.

Wrappers are minimal shells around external binaries and CLIs. They are peer-level to Adapters: - Adapter: Keeps MolPy ↔ external data structures in sync - Wrapper: Encapsulates external package invocation (binaries, CLIs, scripts)

Wrappers MUST NOT contain high-level domain logic.

Environment isolation is owned by :class:~molpy.wrapper.env.EnvSpec (env + env_manager). See that module for supported managers.

Wrapper dataclass

Wrapper(
    name,
    exe,
    workdir=None,
    env_vars=dict(),
    env=None,
    env_manager=None,
)

Bases: ABC

Minimal base class for external tool wrappers.

check
check()

Validate the wrapper configuration.

Returns:

Type Description
str

The resolved executable path.

Raises:

Type Description
FileNotFoundError

if the executable is not found.

is_available
is_available()

Return True if the executable can be resolved on this machine.

process_env
process_env()

Return the validated :class:EnvSpec for this wrapper.

resolve_executable
resolve_executable()

Resolve the configured executable to an absolute path if possible.

Returns:

Type Description
str | None

The resolved executable path, or None if it cannot be found.

run
run(
    args=None,
    *,
    input_text=None,
    capture_output=True,
    check=False,
)

Execute the wrapper's command in the configured workdir.

Parameters:

Name Type Description Default
args list[str] | None

Command-line arguments (without the executable name).

None
input_text str | None

Text to send to stdin.

None
capture_output bool

Whether to capture stdout/stderr.

True
check bool

Whether to raise if returncode != 0.

False

Returns:

Type Description
CompletedProcess[str]

The completed process result.

Antechamber

antechamber

Wrapper for the 'antechamber' CLI.

Higher-level workflow decisions belong in compute nodes.

AntechamberWrapper dataclass

AntechamberWrapper(
    name,
    exe="antechamber",
    workdir=None,
    env_vars=dict(),
    env=None,
    env_manager=None,
)

Bases: Wrapper

Wrapper for the 'antechamber' CLI.

atomtype_assign
atomtype_assign(
    input_file,
    output_file,
    *,
    input_format="pdb",
    output_format="mol2",
    charge_method="bcc",
    atom_type="gaff2",
    net_charge=0,
    formal_charges=False,
    check=False,
)

Perform atom type assignment and charge calculation.

This is the primary workflow for preparing ligands with antechamber: assigning GAFF atom types and computing partial charges.

Parameters:

Name Type Description Default
input_file str | Path

Input structure file.

required
output_file str | Path

Output structure file (with assigned atom types and charges).

required
input_format Literal['pdb', 'mol2', 'ac']

Input file format.

'pdb'
output_format Literal['mol2', 'ac']

Output file format.

'mol2'
charge_method Literal['gas', 'bcc', 'be3', 'cm2', 'esp']

Method for charge calculation (gas: Gasteiger; bcc: Bond charge correction; etc.).

'bcc'
atom_type Literal['gaff', 'gaff2', 'amber', 'sybyl']

Atom type scheme (gaff, gaff2, amber, sybyl).

'gaff2'
net_charge int

Net charge of the molecule.

0
formal_charges bool

If True, use formal charges instead of computing them.

False
check bool

If True, raise CalledProcessError on a non-zero exit.

False

Returns:

Type Description
CompletedProcess[str]

The completed process result.

run_raw
run_raw(args, *, input_text=None, check=False)

Execute antechamber with raw arguments.

Parameters:

Name Type Description Default
args list[str]

Command-line arguments (without 'antechamber').

required
input_text str | None

Text to send to stdin.

None
check bool

If True, raise CalledProcessError on a non-zero exit.

False

Returns:

Type Description
CompletedProcess[str]

The completed process result.

read_antechamber_output

read_antechamber_output(path)

Read antechamber-generated output (.ac or .mol2) into a Frame.

write_antechamber_input_pdb

write_antechamber_input_pdb(path, atomistic)

Write a PDB suitable as antechamber input.

This intentionally avoids using Atomistic.to_frame() which may enforce bond typing constraints that are irrelevant for PDB inputs.

Prepgen

prepgen

Wrappers for prepgen and parmchk2 AmberTools utilities.

prepgen generates residue templates (.prepi) with connection points. parmchk2 checks and generates missing force field parameters.

Parmchk2Wrapper dataclass

Parmchk2Wrapper(
    name,
    exe="parmchk2",
    workdir=None,
    env_vars=dict(),
    env=None,
    env_manager=None,
)

Bases: Wrapper

Wrapper for the 'parmchk2' tool.

generate_parameters
generate_parameters(
    input_file,
    output_file,
    *,
    input_format="mol2",
    force_field="gaff2",
    check=False,
)

Check and generate missing force field parameters.

This is the primary workflow: read atom types and bonds from antechamber output, check against force field parameters, and generate missing ones.

Parameters:

Name Type Description Default
input_file str | Path

Input structure file (mol2 or ac format, typically from antechamber).

required
output_file str | Path

Output AMBER parameter file (frcmod format).

required
input_format Literal['mol2', 'ac', 'mol', 'pdb']

Input file format (mol2, ac, mol, pdb).

'mol2'
force_field Literal['gaff', 'gaff2']

Force field parameter set to use (-s flag): "gaff" for GAFF, "gaff2" for GAFF2 (default).

'gaff2'
check bool

If True, raise CalledProcessError on a non-zero exit.

False

Returns:

Type Description
CompletedProcess[str]

The completed process result.

run_raw
run_raw(args, *, input_text=None, check=False)

Execute parmchk2 with raw arguments.

Parameters:

Name Type Description Default
args list[str]

Command-line arguments (without 'parmchk2').

required
input_text str | None

Text to send to stdin.

None
check bool

If True, raise CalledProcessError on a non-zero exit.

False

Returns:

Type Description
CompletedProcess[str]

The completed process result.

PrepgenWrapper dataclass

PrepgenWrapper(
    name,
    exe="prepgen",
    workdir=None,
    env_vars=dict(),
    env=None,
    env_manager=None,
)

Bases: Wrapper

Wrapper for the 'prepgen' CLI.

Prepgen generates AMBER residue templates (.prepi files) with connection points defined by control files specifying HEAD_NAME, TAIL_NAME, etc.

Example

wrapper = PrepgenWrapper(name="prepgen", workdir=Path("./work")) wrapper.generate_residue( ... input_file="mol.ac", ... output_file="mol.prepi", ... control_file="mol.chain", ... residue_name="MOL", ... )

generate_residue
generate_residue(
    input_file,
    output_file,
    control_file,
    residue_name,
    *,
    output_format="prepi",
    check=False,
)

Generate a residue template with connection points.

Parameters:

Name Type Description Default
input_file str | Path

Input structure file (.ac format from antechamber).

required
output_file str | Path

Output residue template file (.prepi).

required
control_file str | Path

Control file specifying HEAD_NAME, TAIL_NAME, OMIT_NAME.

required
residue_name str

Name for the residue (max 4 chars recommended).

required
output_format Literal['prepi', 'prepc']

Output format (prepi or prepc).

'prepi'
check bool

If True, raise CalledProcessError on a non-zero exit.

False

Returns:

Type Description
CompletedProcess[str]

The completed process result.

Example control file content

HEAD_NAME C1 TAIL_NAME O5 OMIT_NAME H1 OMIT_NAME H2 PRE_HEAD_TYPE c3 POST_TAIL_TYPE os CHARGE 0

run_raw
run_raw(args, *, input_text=None, check=False)

Execute prepgen with raw arguments.

Parameters:

Name Type Description Default
args list[str]

Command-line arguments (without 'prepgen').

required
input_text str | None

Text to send to stdin.

None
check bool

If True, raise CalledProcessError on a non-zero exit.

False

Returns:

Type Description
CompletedProcess[str]

The completed process result.

write_prepgen_control_file

write_prepgen_control_file(
    path,
    *,
    variant,
    head_name=None,
    tail_name=None,
    head_type=None,
    tail_type=None,
    omit_names=None,
    charge=0,
)

Write a prepgen control file for residue template generation.

Parameters:

Name Type Description Default
path Path

Output path for the control file.

required
variant Literal['chain', 'head', 'tail']

Type of residue variant: - "chain": Both HEAD and TAIL connection points - "head": Only TAIL connection (for chain start) - "tail": Only HEAD connection (for chain end)

required
head_name str | None

Atom name for HEAD connection (required for chain/tail).

None
tail_name str | None

Atom name for TAIL connection (required for chain/head).

None
head_type str | None

Atom type for PRE_HEAD_TYPE (e.g., "c3").

None
tail_type str | None

Atom type for POST_TAIL_TYPE (e.g., "os").

None
omit_names list[str] | None

Atom names to omit (leaving groups).

None
charge int

Net charge of the residue (default 0).

0

Raises:

Type Description
ValueError

If required atom names are missing for the variant.

Example

write_prepgen_control_file( ... Path("mol.chain"), ... variant="chain", ... head_name="C1", ... tail_name="O5", ... head_type="c3", ... tail_type="os", ... omit_names=["H1", "H2"], ... )

TLeap

tleap

Wrapper for the 'tleap' binary.

This wrapper runs tleap on a generated script file.

TLeapWrapper dataclass

TLeapWrapper(
    name,
    exe="tleap",
    workdir=None,
    env_vars=dict(),
    env=None,
    env_manager=None,
)

Bases: Wrapper

run_from_script
run_from_script(
    script_text, *, script_name="tleap.in", check=False
)

Execute tleap from a script text.

Parameters:

Name Type Description Default
script_text str

The tleap script content.

required
script_name str

Name of the script file to create (in workdir).

'tleap.in'
check bool

If True, raise CalledProcessError on a non-zero exit.

False

Returns:

Type Description
CompletedProcess[str]

The completed process result.

Raises:

Type Description
ValueError

If no workdir is set.

read_tleap_outputs

read_tleap_outputs(prmtop_path, inpcrd_path)

Read tleap output files (prmtop and inpcrd) into Frame and ForceField.

Parameters:

Name Type Description Default
prmtop_path Path

Path to the AMBER topology file (.prmtop).

required
inpcrd_path Path

Path to the AMBER coordinate file (.inpcrd).

required

Returns:

Type Description
tuple[Frame, ForceField]

Tuple of (Frame, ForceField) objects.