OptimizeGeometry

OptimizeGeometry(configuration, max_forces=None, max_stress=None, max_steps=None, max_step_length=None, constraints=None, trajectory_filename=None, trajectory_object_id=None, optimize_cell=None, disable_stress=None, optimizer_method=None, target_stress=None, pre_step_hook=None, post_step_hook=None, constrain_bravais_lattice=None, trajectory_interval=None, restart_strategy=None, remove_drift=None, enable_optimization_stop_file=None, write_raw_stress=None, write_raw_forces=None, compute_stress=None)

Function for optimizing the geometry and/or the unit cell of the given configuration.

Parameters:
  • configuration (MoleculeConfiguration | BulkConfiguration | DeviceConfiguration | SurfaceConfiguration) – The configuration to be optimized.

  • max_forces (PhysicalQuantity of type force) – The convergence criterion for the atomic forces.
    Default: 0.05*eV/Angstrom

  • max_stress (PhysicalQuantity of type pressure) – The convergence criterion for the maximum difference between the internal stress and the target stress.
    Default: 0.1*GPa

  • max_steps (int) – The maximum number of optimization steps.
    Default: 200

  • max_step_length (PhysicalQuantity of type length) – The maximum step length the optimizer may take.
    Default: 0.2*Ang

  • constraints (list of integers and Constraints objects) – A list of indices of the atom with fixed positions and Constraints objects.
    Default: []

  • trajectory_filename (str | None) – The filename used to store the trajectory. If the value is None then no trajectory file will be written.
    Default: None

  • trajectory_object_id (str | None) – The object id to use when saving to HDF5. If the object-id already exists in the given file, it will be overwritten.
    Default: None

  • disable_stress
    Deprecated: from v2022.03, use optimize_cell parameter instead.

  • optimize_cell (bool) – If enabled, allow the lattice vectors to change during the optimization. This also enables stress calculation for bulk configurations. Cell optimization is disabled if the cell is constrained in all directions (see Constraints).
    Default: True for BulkConfigurations otherwise False

  • optimizer_method (FIRE | LBFGS) – The optimization algorithm to use.
    Default: LBFGS

  • target_stress (PhysicalQuantity of type pressure) – The target internal stress (tensor) of the system. Can be given as a single value in case of isotropic pressure, or as an internal stress vector in Voigt notation or as a 3x3-matrix.
    Default: 0*GPa

  • pre_step_hook (A callable function or method) – An optional user-defined function which will be called just before each optimization step. The signature of the function requires the arguments (step, configuration). The return status is ignored. Unhandled exceptions will terminate the optimization.
    Default: None

  • post_step_hook (A callable function or method) – An optional user-defined function which will be called just after each optimization step. The signature of the function requires the arguments (step, configuration). The return status is ignored. Unhandled exceptions will terminate the optimization.
    Default: None

  • constrain_bravais_lattice (bool) – Enable preserving the Bravais lattice symmetry of the configuration.
    Default: True if the target_stress is commensurate with the lattice symmetries

  • trajectory_interval (int | PhysicalQuantity of type time) – The resolution used in saving steps to a trajectory file. This can either be given as an integer (a value of 1 results in all steps being saved; a value of 2 results in every second step being saved; etc.) or as a time interval.
    Default: 1

  • restart_strategy (NoRestart | RestartFromTrajectory) – The restart mechanism based on trajectory data saved in a given file.
    Default: RestartFromTrajectory()

  • remove_drift (bool) – In ab-initio calculations, the sum of the forces along each Cartesian direction does not necessarily sum to zero due to numerical inaccuracies. This option controls if the “drift” in the forces should be removed by subtracting the average force along each Cartesian direction from all atoms.
    Default: True

  • enable_optimization_stop_file (bool) – Determines whether to enable a file for stopping the geometry optimization. If True, creation of the stop file will stop the optimization at the next step. The name of the stop file will be shown in the log output; it will be stop-geometry-optimization-uniqueID, where uniqueID is a randomly generated identifier for this optimization. The file must be created in the current working directory.
    Default: True

  • write_raw_stress
    Deprecated: from v2025.06, use compute_stress parameter instead.

  • write_raw_forces
    Deprecated: from v2025.06, forces are always written to trajectory.

  • compute_stress (Automatic | bool) – Compute and write stress to trajectory regardless if cell optimization is enabled or not. If cell optimization is enabled stress will automatically be computed and written. If cell optimization is disabled and you wish to compute and write stress to the trajectory, you need to explicitly enable compute stress.
    Default: Automatic meaning; the same as optimize cell flag.

Returns:

The optimized configuration. The returned configuration is assigned the self-consistent calculation associated with the final step of the optimization loop.

Return type:

MoleculeConfiguration | BulkConfiguration | DeviceConfiguration | SurfaceConfiguration

Usage Examples

Optimize the geometry of a water molecule:

# Define elements
elements = [Oxygen, Hydrogen, Hydrogen]

# Define coordinates
cartesian_coordinates = [[  0.0,  -1.70000000e-05,   1.20198000e-01],
                         [  0.0,   7.59572000e-01,  -4.86714000e-01],
                         [  0.0,  -7.59606000e-01,  -4.86721000e-01]]*Angstrom

# Set up configuration
molecule_configuration = MoleculeConfiguration(
    elements=elements,
    cartesian_coordinates=cartesian_coordinates
    )

# Define a calculator
molecule_configuration.setCalculator(LCAOCalculator())

# Perform optimization and store the relaxation trajectory
optimized_configuration = OptimizeGeometry(molecule_configuration,
			                   trajectory_filename='opt.nc'
					   )

# Save the relaxed configuration
nlsave('optimized_configuration.nc', optimized_configuration)


optimize.py

Optimize a silicon unit cell under a uniaxial tensile stress:

# Set up lattice
vector_a = [0.0, 2.7153, 2.7153]*Angstrom
vector_b = [2.7153, 0.0, 2.7153]*Angstrom
vector_c = [2.7153, 2.7153, 0.0]*Angstrom
lattice = UnitCell(vector_a, vector_b, vector_c)

# Define elements
elements = [Silicon, Silicon]

# Define coordinates
fractional_coordinates = [[ 0.  ,  0.  ,  0.  ],
                          [ 0.25,  0.25,  0.25]]

# Set up configuration
bulk_configuration = BulkConfiguration(
    bravais_lattice=lattice,
    elements=elements,
    fractional_coordinates=fractional_coordinates
    )

# -------------------------------------------------------------
# Calculator
# -------------------------------------------------------------

potentialSet = StillingerWeber_Si_1985()
calculator = TremoloXCalculator(parameters=potentialSet)

bulk_configuration.setCalculator(calculator)

# -------------------------------------------------------------
# Optimize Geometry
# -------------------------------------------------------------

bulk_configuration = OptimizeGeometry(
        bulk_configuration,
        max_forces=0.001*eV/Ang,
        max_stress=0.0001*eV/Ang**3,
        max_steps=200,
        max_step_length=0.2*Ang,
        constraints=[],
        trajectory_filename='opt2.nc',
        optimizer_method=LBFGS(),
        target_stress=[2.0, 0.0, 0.0, 0.0, 0.0, 0.0]*GPa,
        )

# Save the relaxed configuration
nlsave('optimized_configuration2.nc', bulk_configuration)

optimize2.py

Notes

By default, all cell optimizations are performed under zero stress.

The definition of target stress is that if a single value is given, it will be interpreted as an external pressure value from which the internal target stress tensor is calculated as

\[\begin{split}\sigma = \left( \begin{matrix} -p & 0 & 0 \\ 0 & -p & 0 \\ 0 & 0 & -p \end{matrix}\right) \, .\end{split}\]

If a target stress tensor is given, it will be interpreted as internal stress of the system, meaning that a negative entry on the diagonal will result in a compression in the corresponding direction and vice versa. The target stress may also be specified in Voigt notation.

By default constrain_bravais_lattice is True when the target_stress is commensurate with the lattice symmetries. This means that the Bravais lattice type will not change unless a symmetry breaking internal stress is applied. If a symmetry breaking target_stress is used then the Bravais Lattice of the configuration is automatically converted to a UnitCell, to enable changes in the shape of the cell.

Note

The last line of the logging output of OptimizeGeometry provides the tag OPT which can be used to grep for the current step, volume, max. force, max. stress error and energy / enthalpy.

Optimization simulations can be restarted from a previous run, e.g. if the simulation was interrupted or the optimization did not converge in the maximum number of steps. The detailed restart behavior is specified and documented in RestartFromTrajectory.

External electric field

The inclusion of a homogeneous external electric field in bulk periodic DFT calculations with periodic boundary conditions is supported via the object ElectricFieldConstraint. For other geometries (i.e. slab or molecules), it is also possible to add an electric field by means of metallic regions in the Poisson solver (see Poisson solvers).