Skip to content

Optimization

Geometry optimization using potential energy functions.

Quick reference

Symbol Summary Preferred for
LBFGS Limited-memory BFGS optimizer Geometry relaxation of small/medium structures
BondPotentialWrapper Adapts bond potentials to Frame interface Optimizer integration
AnglePotentialWrapper Adapts angle potentials to Frame interface Optimizer integration
  • 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 StructLike (Struct, Atomistic, CoarseGrain, etc.) that: - Has .entities (TypeBucket) containing entities with "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 from molpy.potential.bond import Harmonic

potential = Harmonic(k=100.0, r0=1.5) 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.potential.bond import Harmonic from molpy.optimize import LBFGS

struct = Atomistic()

... add atoms and bonds ...

potential = Harmonic(k=100.0, r0=1.5) 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.

Potential Wrappers

potential_wrappers

Potential wrappers for optimizer compatibility.

Since potentials in molpy work with raw arrays (positions, indices, types), not Frame objects, we need simple wrappers to extract data from Frames.

Each wrapper implements calc_energy(frame) and calc_forces(frame) by extracting the appropriate data and calling the underlying potential.

AnglePotentialWrapper

AnglePotentialWrapper(potential)

Wrapper for angle potentials to work with Frame interface.

Extracts (r, angle_idx, angle_types) from Frame and calls underlying potential.

calc_energy
calc_energy(frame)

Extract angle data from Frame and compute energy.

calc_forces
calc_forces(frame)

Extract angle data from Frame and compute forces.

BondPotentialWrapper

BondPotentialWrapper(potential)

Wrapper for bond potentials to work with Frame interface.

Extracts (r, bond_idx, bond_types) from Frame and calls underlying potential.

calc_energy
calc_energy(frame)

Extract bond data from Frame and compute energy.

calc_forces
calc_forces(frame)

Extract bond data from Frame and compute forces.