Wrapper¶
Subprocess wrappers for external command-line tools.
Quick reference¶
| Symbol | Summary | Preferred for |
|---|---|---|
Tool |
The core every engine and wrapper shares: settings → environment → executable → env vars → timeout → logger; command, run_command, check_executable |
Subclassing through Wrapper or Engine |
ToolError |
The one failure: tool, returncode, tail (stderr, stdout or log) |
Catching a failed, missing or timed-out tool |
Wrapper |
Base: settings from [wrapper.<tool>], logged subprocess runs, check=True by default |
Writing a wrapper for another program |
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 |
SanderWrapper |
AMBER sander: run_from_mdin(mdin_text, prmtop, inpcrd) |
Running a caller's mdin on a prmtop/inpcrd |
EnvironmentSpec |
The conda / venv a tool runs in, resolved from its settings | Inspecting or building a command prefix |
run_step |
run_step(tool, output, call): run one step, require the file it must write; raises ToolError with the tool's output |
Chaining tools in a pipeline |
Canonical example¶
# docs: skip — needs AmberTools
from molpy.config import load_config
from molpy.wrapper import TleapWrapper
config = load_config({"wrapper": {"env": "AmberTools25", "env_manager": "conda"}})
leap = TleapWrapper("leap_work", config=config)
result = leap.run_from_script("source leaprc.gaff2\nquit\n")
print(result.returncode) # 0
Key behavior¶
- A wrapper's executable, environment (
env+env_manager),env_varsandtimeoutare its[wrapper.<tool>]settings in molpy's configuration, falling back to[wrapper](molpy.config); the constructor takes the working directory and, optionally, theconfig - Environment isolation is owned by
EnvironmentSpec; no auto-detection of manager type.envandenv_managerare set together, or both omitted for the systemPATH; managers arecondaandvenv(one spelling each) - Safe to instantiate even if the executable is missing
(
check_executable()raises,is_available()reports it;run_steprefuses to start). The lookup runs once per instance; a conda lookup (conda run … which) is logged at DEBUG and time-limited - Every failure is a
ToolError(aRuntimeError) carryingtool("wrapper.tleap"),returncodeandtail: a missing executable, a program that cannot start, a timeout, a non-zero exit (check=Trueis the default;check=Falsereturns theCompletedProcess) or, inrun_step, a missing output - A third-party wrapper subclasses
Wrapper, names its table intooland reads[wrapper.<tool>]like the built-in ones (Adding a Wrapper) - Every run is logged to
molpy.wrapper.<tool>as mollog records (process started/finished/failed/timed out) carrying thecommand,cwd,returncodeandelapsed_s
Related¶
- Concepts: Wrapper and Adapter
- Guide: AmberTools Integration
- Guide: Configure and Log a Run
- API: Config
Full API¶
Environment¶
EnvironmentSpec
dataclass
¶
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"
conda_executable is the conda that conda run invokes.
:meth:resolve_executable remembers each answer for the life of the
instance (each engine and wrapper resolves its own).
command_prefix ¶
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
|
False
|
merge_environ ¶
Build a subprocess environment dict.
Merge order (later wins): base (default os.environ) →
venv PATH / VIRTUAL_ENV injection when applicable →
extra.
resolve
classmethod
¶
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 ( |
None
|
env_manager
|
str | None
|
|
None
|
conda_executable
|
str
|
The |
'conda'
|
Returns:
| Type | Description |
|---|---|
EnvironmentSpec
|
A frozen :class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If exactly one of the pair is set, or the manager string is unsupported. |
resolve_executable ¶
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. A conda env is
asked with conda run … which through
:func:~molpy.wrapper._process.run_process (logged at DEBUG to
logger, killed after :data:RESOLVE_TIMEOUT seconds). Each answer
is remembered by this instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exe
|
str | Path
|
A program name or a path. |
required |
logger
|
Logger | None
|
Where the conda lookup logs; |
None
|
Returns:
| Type | Description |
|---|---|
str | None
|
A |
str | None
|
(or the lookup could not run). |
Base¶
Tool ¶
An external program resolved from molpy's configuration.
Subclasses set :attr:group (the base class does: "engine" or
"wrapper") and :attr:tool, the name of the configuration table
([<group>.<tool>], falling back to [<group>]).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workdir
|
str | Path | None
|
Where the tool runs; |
None
|
config
|
Config | None
|
molpy's configuration (:func: |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
settings |
The resolved :class: |
|
environment |
The :class: |
|
logger |
The tool's logger, |
|
executable |
str
|
The program to run ( |
workdir |
Where the tool runs, or |
|
launcher |
list[str]
|
MPI / scheduler prefix before the executable (engines; empty for wrappers). |
env_vars |
dict[str, str]
|
Environment variables set for the subprocess. |
timeout |
Seconds before a subprocess is killed ( |
Raises:
| Type | Description |
|---|---|
KeyError
|
:attr: |
ValueError
|
The configured environment is incomplete or its manager unsupported, or no executable is configured and the tool has no default. |
check_executable ¶
The executable's resolved path.
Raises:
| Type | Description |
|---|---|
ToolError
|
The executable is not found; the message names the settings to fix. |
command ¶
The full argv: [env prefix] [launcher] executable args.
The env prefix is :meth:EnvironmentSpec.command_prefix (conda's
conda run --no-capture-output -n <env>; empty for venv and the
system, which act through the environment variables).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
Sequence[str]
|
What follows the executable. |
()
|
launch
|
bool
|
Put :attr: |
True
|
resolve_executable ¶
The executable's absolute path in the environment, or None.
Looked up once per instance (:meth:EnvironmentSpec.resolve_executable).
run_command ¶
Start command in cwd with the tool's environment and time limit.
The run is logged to :attr:logger (process started /
finished / failed / timed out), each record carrying the
command, the directory and fields (e.g. step="mdrun").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
command
|
Sequence[str]
|
The full argv (usually :meth: |
required |
cwd
|
str | Path | None
|
Working directory; |
required |
capture_output
|
bool
|
Capture stdout / stderr. |
required |
check
|
bool
|
Raise :class: |
True
|
input_text
|
str | None
|
Text sent to stdin. |
None
|
log
|
Path | None
|
The program's log file, the error's tail when nothing was captured. |
None
|
**fields
|
Any
|
Extra structured fields on every record. |
{}
|
Raises:
| Type | Description |
|---|---|
ToolError
|
The program could not start, timed out, or (with check) exited non-zero. |
ToolError ¶
Bases: RuntimeError
An external tool failed.
It is missing, could not start, timed out, exited non-zero, or left an output it must write unwritten.
Attributes:
| Name | Type | Description |
|---|---|---|
tool |
The tool's settings table, |
|
reason |
What went wrong, in one line. |
|
returncode |
The exit status; |
|
tail |
The last lines of its stderr, its stdout, or its log file
(whichever is the first non-empty); |
Wrapper ¶
Bases: Tool
Minimal base class for external tool wrappers.
A subclass names its configuration table in :attr:tool ("tleap"
reads [wrapper.tleap], falling back to [wrapper]). Settings,
environment, executable, logger and the failure contract come from
:class:~molpy.wrapper.Tool.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workdir
|
str | Path | None
|
Where the tool runs; |
None
|
config
|
Config | None
|
molpy's configuration (:func: |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
The configured environment is incomplete or its manager unsupported, or no executable is configured. |
run ¶
Execute the wrapper's command in :attr:workdir.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
Sequence[str]
|
Command-line arguments (without the executable). |
()
|
input_text
|
str | None
|
Text to send to stdin. |
None
|
capture_output
|
bool
|
Whether to capture stdout/stderr. |
True
|
check
|
bool
|
Raise :class: |
True
|
Returns:
| Type | Description |
|---|---|
CompletedProcess[str]
|
The completed process result. |
Raises:
| Type | Description |
|---|---|
ToolError
|
The tool could not start, timed out, or (with check) exited non-zero. |
run_step ¶
Run one tool step and require the file it must write.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tool
|
Tool
|
The tool |
required |
output
|
Path
|
The file the step must leave behind. |
required |
call
|
Callable[[], CompletedProcess[str]]
|
Runs the step (typically a bound wrapper method in a lambda). |
required |
Returns:
| Type | Description |
|---|---|
CompletedProcess[str]
|
The completed process. |
Raises:
| Type | Description |
|---|---|
ToolError
|
The executable is missing, the step fails, or it exits 0
but leaves |
Antechamber¶
AntechamberWrapper ¶
Bases: Wrapper
Wrapper for the 'antechamber' CLI.
atomtype_assign ¶
atomtype_assign(
input_file,
output_file,
*,
parameter_set,
input_format="pdb",
output_format="mol2",
charge_method="bcc",
net_charge=0,
formal_charges=False,
check=True,
)
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 |
parameter_set
|
Literal['gaff', 'gaff2', 'amber', 'bcc', 'abcg2', 'sybyl']
|
The atom-type table ( |
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', 'abcg2', 'mul', 'be3', 'cm2', 'esp']
|
Method for charge calculation (gas: Gasteiger; bcc / abcg2: AM1-BCC / ABCG2; mul: sqm's AM1 Mulliken charges, unequivalenced; etc.). |
'bcc'
|
net_charge
|
int
|
Net charge of the molecule. |
0
|
formal_charges
|
bool
|
If True, use formal charges instead of computing them. |
False
|
check
|
bool
|
Raise :class: |
True
|
Returns:
| Type | Description |
|---|---|
CompletedProcess[str]
|
The completed process result. |
Prepgen¶
PrepgenWrapper ¶
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("./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=True,
)
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
|
Raise :class: |
True
|
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
Parmchk2Wrapper ¶
Bases: Wrapper
Wrapper for the 'parmchk2' tool.
generate_parameters ¶
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'
|
parameter_set
|
Literal['gaff', 'gaff2']
|
The GAFF generation whose parameters are checked
( |
required |
check
|
bool
|
Raise :class: |
True
|
Returns:
| Type | Description |
|---|---|
CompletedProcess[str]
|
The completed process result. |
TLeap¶
TleapWrapper ¶
Bases: Wrapper
Wrapper for the 'tleap' binary ([wrapper.tleap]).
run_from_script ¶
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
|
Raise :class: |
True
|
Returns:
| Type | Description |
|---|---|
CompletedProcess[str]
|
The completed process result. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no workdir is set. |
ToolError
|
tleap failed (with check). |
Sander¶
SanderWrapper ¶
Bases: Wrapper
Wrapper for the 'sander' binary ([wrapper.sander]).
run_from_mdin ¶
Write <name>.in and run sander on it.
Runs sander -O -i <name>.in -p <prmtop> -c <inpcrd> -r <name>.rst
-o <name>.out in :attr:workdir; the restart <name>.rst and
the output <name>.out land there.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mdin_text
|
str
|
The |
required |
prmtop
|
str | Path
|
The topology. |
required |
inpcrd
|
str | Path
|
The starting coordinates. |
required |
name
|
str
|
Stem of the control, restart and output files. |
'sander'
|
check
|
bool
|
Raise :class: |
True
|
Returns:
| Type | Description |
|---|---|
CompletedProcess[str]
|
The completed process result. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no workdir is set. |
ToolError
|
sander failed (with check). |