View Javadoc
1   // ******************************************************************************
2   //
3   // Title:       Force Field X.
4   // Description: Force Field X - Software for Molecular Biophysics.
5   // Copyright:   Copyright (c) Michael J. Schnieders 2001-2025.
6   //
7   // This file is part of Force Field X.
8   //
9   // Force Field X is free software; you can redistribute it and/or modify it
10  // under the terms of the GNU General Public License version 3 as published by
11  // the Free Software Foundation.
12  //
13  // Force Field X is distributed in the hope that it will be useful, but WITHOUT
14  // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  // FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
16  // details.
17  //
18  // You should have received a copy of the GNU General Public License along with
19  // Force Field X; if not, write to the Free Software Foundation, Inc., 59 Temple
20  // Place, Suite 330, Boston, MA 02111-1307 USA
21  //
22  // Linking this library statically or dynamically with other modules is making a
23  // combined work based on this library. Thus, the terms and conditions of the
24  // GNU General Public License cover the whole combination.
25  //
26  // As a special exception, the copyright holders of this library give you
27  // permission to link this library with independent modules to produce an
28  // executable, regardless of the license terms of these independent modules, and
29  // to copy and distribute the resulting executable under terms of your choice,
30  // provided that you also meet, for each linked independent module, the terms
31  // and conditions of the license of that module. An independent module is a
32  // module which is not derived from or based on this library. If you modify this
33  // library, you may extend this exception to your version of the library, but
34  // you are not obligated to do so. If you do not wish to do so, delete this
35  // exception statement from your version.
36  //
37  // ******************************************************************************
38  package ffx.algorithms.optimize;
39  
40  import ffx.algorithms.AlgorithmListener;
41  import ffx.numerics.Potential;
42  import ffx.numerics.optimization.LineSearch;
43  import ffx.potential.ForceFieldEnergy;
44  import ffx.potential.MolecularAssembly;
45  import ffx.potential.bonded.Atom;
46  import ffx.potential.openmm.OpenMMContext;
47  import ffx.potential.openmm.OpenMMEnergy;
48  import ffx.potential.openmm.OpenMMState;
49  
50  import java.util.logging.Logger;
51  
52  import static edu.uiowa.jopenmm.OpenMMLibrary.OpenMM_State_DataType.OpenMM_State_Energy;
53  import static edu.uiowa.jopenmm.OpenMMLibrary.OpenMM_State_DataType.OpenMM_State_Forces;
54  import static edu.uiowa.jopenmm.OpenMMLibrary.OpenMM_State_DataType.OpenMM_State_Positions;
55  import static java.lang.Double.isInfinite;
56  import static java.lang.Double.isNaN;
57  import static java.lang.String.format;
58  import static org.apache.commons.math3.util.FastMath.sqrt;
59  
60  /**
61   * Given a Context, this class searches for a new set of particle positions that represent
62   * a local minimum of the potential energy.  The search is performed with the L-BFGS algorithm.
63   * Distance constraints are enforced during minimization by adding a harmonic restraining
64   * force to the potential function.  The strength of the restraining force is steadily increased
65   * until the minimum energy configuration satisfies all constraints to within the tolerance
66   * specified by the Context's Integrator.
67   * <p>
68   * Energy minimization is done using the force groups defined by the Integrator.
69   * If you have called setIntegrationForceGroups() on it to restrict the set of forces
70   * used for integration, only the energy of the included forces will be minimized.
71   *
72   * @author Michael J. Schnieders
73   * @since 1.0
74   */
75  public class MinimizeOpenMM extends Minimize {
76  
77    private static final Logger logger = Logger.getLogger(MinimizeOpenMM.class.getName());
78  
79    /**
80     * MinimizeOpenMM constructor.
81     *
82     * @param molecularAssembly the MolecularAssembly to optimize.
83     */
84    public MinimizeOpenMM(MolecularAssembly molecularAssembly) {
85      super(molecularAssembly, molecularAssembly.getPotentialEnergy(), null);
86    }
87  
88    /**
89     * MinimizeOpenMM constructor.
90     *
91     * @param molecularAssembly the MolecularAssembly to optimize.
92     * @param openMMEnergy      the OpenMM potential energy function.
93     */
94    public MinimizeOpenMM(MolecularAssembly molecularAssembly, OpenMMEnergy openMMEnergy) {
95      super(molecularAssembly, openMMEnergy, null);
96    }
97  
98    /**
99     * MinimizeOpenMM constructor.
100    *
101    * @param molecularAssembly the MolecularAssembly to optimize.
102    * @param openMMEnergy      the OpenMM potential energy function.
103    * @param algorithmListener report progress using the listener.
104    */
105   public MinimizeOpenMM(MolecularAssembly molecularAssembly, OpenMMEnergy openMMEnergy, AlgorithmListener algorithmListener) {
106     super(molecularAssembly, openMMEnergy, algorithmListener);
107   }
108 
109   /**
110    * Note the OpenMM L-BFGS minimizer does not accept the parameter "m" for the number of previous
111    * steps used to estimate the Hessian.
112    *
113    * @param m             The number of previous steps used to estimate the Hessian (ignored).
114    * @param eps           The convergence criteria.
115    * @param maxIterations The maximum number of iterations.
116    * @return The potential.
117    */
118   @Override
119   public Potential minimize(int m, double eps, int maxIterations) {
120     return minimize(eps, maxIterations);
121   }
122 
123   /**
124    * minimize
125    *
126    * @param eps           The convergence criteria.
127    * @param maxIterations The maximum number of iterations.
128    * @return a {@link ffx.numerics.Potential} object.
129    */
130   @Override
131   public Potential minimize(double eps, int maxIterations) {
132 
133     ForceFieldEnergy forceFieldEnergy = molecularAssembly.getPotentialEnergy();
134 
135     if (forceFieldEnergy instanceof OpenMMEnergy openMMEnergy) {
136       time = -System.nanoTime();
137 
138       // Respect the use flag, and lambda state.
139       Atom[] atoms = molecularAssembly.getAtomArray();
140       openMMEnergy.updateParameters(atoms);
141 
142       // Respect (in)active atoms.
143       openMMEnergy.setActiveAtoms();
144 
145       // Get the coordinates to start from.
146       openMMEnergy.getCoordinates(x);
147 
148       // Calculate the starting energy before optimization.
149       double e = openMMEnergy.energy(x);
150       logger.info(format("\n Initial energy:                 %12.6f (kcal/mol)", e));
151 
152       // Run the minimization in the current OpenMM Context.
153       OpenMMContext openMMContext = openMMEnergy.getContext();
154       openMMContext.optimize(eps, maxIterations);
155 
156       // Get the minimized coordinates, forces and potential energy back from OpenMM.
157       int mask = OpenMM_State_Energy | OpenMM_State_Positions | OpenMM_State_Forces;
158       OpenMMState openMMState = openMMContext.getOpenMMState(mask);
159       energy = openMMState.potentialEnergy;
160       openMMState.getPositions(x);
161       openMMState.getGradient(grad);
162       openMMState.destroy();
163 
164       // Compute the RMS gradient.
165       int index = 0;
166       double grad2 = 0;
167       for (Atom atom : atoms) {
168         if (atom.isActive()) {
169           double fx = grad[index++];
170           double fy = grad[index++];
171           double fz = grad[index++];
172           grad2 += fx * fx + fy * fy + fz * fz;
173         }
174       }
175       rmsGradient = sqrt(grad2 / n);
176 
177       double[] ffxGrad = new double[n];
178       openMMEnergy.getCoordinates(x);
179       double ffxEnergy = openMMEnergy.energyAndGradientFFX(x, ffxGrad);
180       double grmsFFX = 0.0;
181       for (int i = 0; i < n; i++) {
182         double gi = ffxGrad[i];
183         if (isNaN(gi) || isInfinite(gi)) {
184           String message = format(" The gradient of variable %d is %8.3f.", i, gi);
185           logger.warning(message);
186         }
187         grmsFFX += gi * gi;
188       }
189       grmsFFX = sqrt(grmsFFX / n);
190 
191       time += System.nanoTime();
192       logger.info(format(" Final energy for OpenMM         %12.6f vs. FFX %12.6f in %8.3f (sec).", energy, ffxEnergy, time * 1.0e-9));
193       logger.info(format(" Convergence criteria for OpenMM %12.6f vs. FFX %12.6f (kcal/mol/A).", rmsGradient, grmsFFX));
194     }
195 
196     if (algorithmListener != null) {
197       algorithmListener.algorithmUpdate(molecularAssembly);
198     }
199 
200     return forceFieldEnergy;
201   }
202 
203   /**
204    * MinimizeOpenMM does not support the OptimizationListener interface.
205    *
206    * @since 1.0
207    */
208   @Override
209   public boolean optimizationUpdate(int iteration, int nBFGS, int functionEvaluations,
210                                     double rmsGradient, double rmsCoordinateChange, double energy, double energyChange,
211                                     double angle, LineSearch.LineSearchResult lineSearchResult) {
212     logger.warning(" MinimizeOpenMM does not support updates at each optimization step.");
213     return false;
214   }
215 }