Skip to content

Optimization

Geometry optimization using potential energy functions.

Quick reference

Symbol Summary Preferred for
Optimizer Base class driving any calc_energy(frame) / calc_forces(frame) potential Custom optimizers
OptimizationResult Result record (final frame, energy, convergence info) Inspecting outcomes
LBFGS Limited-memory BFGS optimizer Geometry relaxation of small/medium structures
ForceFieldPotential Wraps a molrs ForceField (via ff.to_potentials(frame)) as an optimizer potential Optimizing with force-field energies/forces
  • Potential -- energy/force implementations used by optimizers

Full API

Base

base

Base classes for geometry optimization.

OptimizationResult dataclass

OptimizationResult(structure, energy, fmax, nsteps, converged, reason)

Bases: Generic[S]

Result of a geometry optimization.

Attributes:

Name Type Description
structure S

Final optimized structure (same object if inplace=True)

energy float

Final potential energy

fmax float

Final maximum force component

nsteps int

Number of optimization steps taken

converged bool

Whether convergence criteria were met

reason str

Human-readable termination reason

Optimizer

Optimizer(potential, *, entity_type=Entity)

Bases: ABC, Generic[S]

Base class for structure optimizers.

Works with any structure leaf (Atomistic, CoarseGrain, etc.) that: - Has .atoms (or .beads) yielding entity views with an "xyz" field - Has .to_frame() method to convert to Frame format

The optimizer calls potential.calc_energy(frame) and potential.calc_forces(frame) directly - each potential is responsible for extracting what it needs from Frame.

Parameters:

Name Type Description Default
potential PotentialLike

Potential with calc_energy/calc_forces methods

required
entity_type type[Entity]

Type of entity to optimize (default: Entity for all)

Entity
Example

from molpy.optimize import LBFGS, ForceFieldPotential

potential = ForceFieldPotential(forcefield) # molrs ForceField opt = LBFGS(potential, maxstep=0.04, memory=20) result = opt.run(struct, fmax=0.01, steps=500)

attach
attach(func, interval=1, **kwargs)

Attach a callback function.

The callback will be called every interval steps with the optimizer instance and current structure as arguments.

Parameters:

Name Type Description Default
func Callable

Callback function(optimizer, structure, **kwargs)

required
interval int

Call every N steps

1
**kwargs Any

Additional arguments for callback

{}
get_energy
get_energy(structure)

Compute energy for structure.

Parameters:

Name Type Description Default
structure S

Structure to evaluate

required

Returns:

Type Description
float

Potential energy

get_energy_and_forces
get_energy_and_forces(structure)

Compute energy and forces via Frame interface.

Converts structure to Frame and calls potential methods directly. Each potential is responsible for extracting what it needs from Frame.

Parameters:

Name Type Description Default
structure S

Structure to evaluate

required

Returns:

Type Description
tuple[float, ndarray]

(energy, forces) where forces is (N, 3) array

get_forces
get_forces(structure)

Compute forces for structure as (N, 3) array.

Parameters:

Name Type Description Default
structure S

Structure to evaluate

required

Returns:

Type Description
ndarray

(N, 3) array of forces

get_positions
get_positions(structure)

Extract positions as (N, 3) array from entities.

Parameters:

Name Type Description Default
structure S

Structure to extract positions from

required

Returns:

Type Description
ndarray

(N, 3) numpy array of positions

run
run(structure, fmax=0.01, steps=1000, *, inplace=True)

Run optimization until convergence or max steps.

Parameters:

Name Type Description Default
structure S

Structure to optimize

required
fmax float

Convergence threshold (max force component)

0.01
steps int

Maximum number of steps

1000
inplace bool

If True, modify structure in-place; if False, work on copy

True

Returns:

Type Description
OptimizationResult[S]

OptimizationResult with final state

set_positions
set_positions(structure, positions)

Write positions back into structure entities.

Parameters:

Name Type Description Default
structure S

Structure to update

required
positions ndarray

(N, 3) array of new positions

required
step abstractmethod
step(structure)

Perform one optimization step.

Parameters:

Name Type Description Default
structure S

Structure to optimize (modified in-place)

required

Returns:

Type Description
tuple[float, float]

(energy, fmax) tuple where: energy: potential energy after step fmax: maximum force component after step

PotentialLike

Bases: Protocol

Protocol for potential functions compatible with calc_energy_from_frame.

LBFGS

lbfgs

L-BFGS geometry optimizer.

LBFGS

LBFGS(potential, *, maxstep=0.04, memory=20, damping=1.0, entity_type=None)

Bases: Optimizer[S]

Limited-memory BFGS geometry optimizer.

Implements the L-BFGS algorithm for quasi-Newton optimization with limited memory storage. Uses two-loop recursion to compute search directions efficiently.

Parameters:

Name Type Description Default
potential Potential

Potential with calc_energy/calc_forces methods.

required
maxstep float

Maximum step size (as displacement norm).

0.04
memory int

Number of previous steps to store for Hessian approximation.

20
damping float

Damping factor for step size.

1.0
entity_type type[Entity]

Type of entity to optimize.

None

Attributes:

Name Type Description
maxstep

Maximum allowed step size

memory

LBFGS memory size

damping

Step damping factor

s_history list[ndarray]

Position difference history

y_history list[ndarray]

Gradient difference history

rho_history list[float]

Curvature history (1 / y·s)

Example

from molpy.core.atomistic import Atomistic from molpy.optimize import LBFGS, ForceFieldPotential

struct = Atomistic()

... add atoms and bonds ...

potential = ForceFieldPotential(forcefield) # molrs ForceField opt = LBFGS(potential, maxstep=0.04, memory=20) result = opt.run(struct, fmax=0.01, steps=500)

step
step(structure)

Perform one L-BFGS optimization step.

Parameters:

Name Type Description Default
structure S

Structure to optimize (modified in-place).

required

Returns:

Type Description
tuple[float, float]

tuple[float, float]: (energy, fmax) tuple where energy is potential energy after step and fmax is maximum force component after step.

ForceField Potential

forcefield_potential

Adapter exposing a molrs ForceField as an optimizer potential.

The optimizer base (:class:molpy.optimize.base.Optimizer) drives any object that answers calc_energy(frame) / calc_forces(frame). molrs's native :class:molrs.Potentials instead consumes flat coordinate vectors and must be recompiled against the current frame each step (geometry changes while the topology/types stay fixed). This thin adapter bridges the two: it compiles the force field against the live frame and evaluates energy/forces from the frame's coordinates.

ForceFieldPotential

ForceFieldPotential(forcefield)

Evaluate a molrs :class:~molrs.ForceField from a :class:~molrs.Frame.

Parameters:

Name Type Description Default
forcefield ForceField

A molrs ForceField whose styles/types are fully defined. The frame passed to :meth:calc_energy / :meth:calc_forces must carry type columns whose values match the force field's type names (e.g. a bond labelled "OW-HW").

required
calc_energy
calc_energy(frame)

Return the total potential energy for frame.

calc_forces
calc_forces(frame)

Return the per-atom forces for frame as an (N, 3) array.