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.manybody;
39  
40  import edu.rit.mp.DoubleBuf;
41  import edu.rit.pj.Comm;
42  import edu.rit.pj.IntegerSchedule;
43  import edu.rit.pj.MultipleParallelException;
44  import edu.rit.pj.WorkerIntegerForLoop;
45  import edu.rit.pj.WorkerRegion;
46  import ffx.algorithms.optimize.RotamerOptimization;
47  import ffx.potential.Utilities;
48  import ffx.potential.bonded.Residue;
49  import ffx.potential.bonded.Rotamer;
50  
51  import java.io.BufferedWriter;
52  import java.io.IOException;
53  import java.util.Collection;
54  import java.util.Map;
55  import java.util.Set;
56  import java.util.logging.Level;
57  import java.util.logging.Logger;
58  
59  import static java.lang.String.format;
60  
61  /** Compute residue self-energy values in parallel across nodes. */
62  public class SelfEnergyRegion extends WorkerRegion {
63  
64    private static final Logger logger = Logger.getLogger(SelfEnergyRegion.class.getName());
65    private final Residue[] residues;
66    private final RotamerOptimization rO;
67    private final EnergyExpansion eE;
68    private final EliminatedRotamers eR;
69    /** Map of self-energy values to compute. */
70    private final Map<Integer, Integer[]> selfEnergyMap;
71    /** Writes energies to restart file. */
72    private final BufferedWriter energyWriter;
73    /** World Parallel Java communicator. */
74    private final Comm world;
75    /** Number of Parallel Java processes. */
76    private final int numProc;
77    /** Flag to prune clashes. */
78    private final boolean pruneClashes;
79    /** Flag to indicate if this is the master process. */
80    private final boolean master;
81    /** Rank of this process. */
82    private final int rank;
83    /** Flag to indicate verbose logging. */
84    private final boolean verbose;
85    /** If true, write out an energy restart file. */
86    private final boolean writeEnergyRestart;
87    /**
88     * Sets whether files should be printed; true for standalone applications, false for some
89     * applications which use rotamer optimization as part of a larger process.
90     */
91    private final boolean printFiles;
92  
93    private Set<Integer> keySet;
94  
95    public SelfEnergyRegion(RotamerOptimization rO, EnergyExpansion eE, EliminatedRotamers eR,
96        Residue[] residues, BufferedWriter energyWriter, Comm world,
97        int numProc, boolean pruneClashes, boolean master, int rank, boolean verbose,
98        boolean writeEnergyRestart, boolean printFiles) {
99      this.rO = rO;
100     this.eE = eE;
101     this.eR = eR;
102     this.residues = residues;
103     this.energyWriter = energyWriter;
104     this.world = world;
105     this.numProc = numProc;
106     this.pruneClashes = pruneClashes;
107     this.master = master;
108     this.rank = rank;
109     this.verbose = verbose;
110     this.writeEnergyRestart = writeEnergyRestart;
111     this.printFiles = printFiles;
112 
113     this.selfEnergyMap = eE.getSelfEnergyMap();
114     logger.info(format("\n Number of self energies: %d", selfEnergyMap.size()));
115   }
116 
117   @Override
118   public void finish() {
119     // Pre-Prune if self-energy is Double.NaN.
120     eR.prePruneSelves(residues);
121 
122     // Prune clashes for all singles (not just the ones this node did).
123     if (pruneClashes) {
124       eR.pruneSingleClashes(residues);
125     }
126 
127     // Print what we've got so far.
128     if (master && verbose) {
129       for (int i = 0; i < residues.length; i++) {
130         Residue residue = residues[i];
131         Rotamer[] rotamers = residue.getRotamers();
132         for (int ri = 0; ri < rotamers.length; ri++) {
133           logger.info(format(" Self energy %8s %-2d: %s", residues[i].toString(rotamers[ri]), ri,
134               rO.formatEnergy(eE.getSelf(i, ri))));
135         }
136       }
137     }
138   }
139 
140   @Override
141   public void run() throws Exception {
142     if (!keySet.isEmpty()) {
143       try {
144         execute(0, keySet.size() - 1, new SelfEnergyLoop());
145       } catch (MultipleParallelException mpx) {
146         Collection<Throwable> subErrors = mpx.getExceptionMap().values();
147         logger.info(format(" MultipleParallelException caught: %s\n Stack trace:\n%s", mpx,
148             Utilities.stackTraceToString(mpx)));
149         for (Throwable subError : subErrors) {
150           logger.info(format(" Exception %s\n Stack trace:\n%s", subError,
151               Utilities.stackTraceToString(subError)));
152         }
153         throw mpx; // Or logger.severe.
154       } catch (Throwable t) {
155         Throwable cause = t.getCause();
156         logger.info(
157             format(" Throwable caught: %s\n Stack trace:\n%s", t, Utilities.stackTraceToString(t)));
158         if (cause != null) {
159           logger.info(
160               format(" Cause: %s\n Stack trace:\n%s", cause, Utilities.stackTraceToString(cause)));
161         }
162         throw t;
163       }
164     }
165   }
166 
167   @Override
168   public void start() {
169 
170     int numSelf = selfEnergyMap.size();
171     int remainder = numSelf % numProc;
172     // Set padded residue and rotamer to less than zero.
173     Integer[] padding = {-1, -1};
174 
175     int padKey = numSelf;
176     while (remainder != 0) {
177       selfEnergyMap.put(padKey++, padding);
178       remainder = selfEnergyMap.size() % numProc;
179     }
180 
181     numSelf = selfEnergyMap.size();
182     if (numSelf % numProc != 0) {
183       logger.severe(" Logic error padding self energies.");
184     }
185 
186     // Load the keySet of self energies.
187     keySet = selfEnergyMap.keySet();
188 
189     // Compute backbone energy.
190     double backboneEnergy = 0.0;
191     try {
192       backboneEnergy = rO.computeBackboneEnergy(residues);
193     } catch (ArithmeticException ex) {
194       logger.severe(format(" Error in calculation of backbone energy %s", ex.getMessage()));
195     }
196     rO.logIfRank0(format(" Backbone energy:  %s\n", rO.formatEnergy(backboneEnergy)));
197     eE.setBackboneEnergy(backboneEnergy);
198   }
199 
200   private class SelfEnergyLoop extends WorkerIntegerForLoop {
201 
202     final DoubleBuf[] resultBuffer;
203     final DoubleBuf myBuffer;
204 
205     SelfEnergyLoop() {
206       resultBuffer = new DoubleBuf[numProc];
207       for (int i = 0; i < numProc; i++) {
208         resultBuffer[i] = DoubleBuf.buffer(new double[3]);
209       }
210       myBuffer = resultBuffer[rank];
211     }
212 
213     @Override
214     public void run(int lb, int ub) {
215       for (int key = lb; key <= ub; key++) {
216         Integer[] job = selfEnergyMap.get(key);
217         int i = job[0];
218         int ri = job[1];
219         // Initialize result.
220         myBuffer.put(0, i);
221         myBuffer.put(1, ri);
222         myBuffer.put(2, 0.0);
223 
224         if (i >= 0 && ri >= 0) {
225           if (!eR.check(i, ri)) {
226             long time = -System.nanoTime();
227             Rotamer[] rotamers = residues[i].getRotamers();
228             double selfEnergy;
229             try {
230               selfEnergy = eE.computeSelfEnergy(residues, i, ri);
231               time += System.nanoTime();
232               logger.info(
233                   format(" Self %8s %-2d: %s in %6.4f (sec).", residues[i].toString(rotamers[ri]),
234                       ri, rO.formatEnergy(selfEnergy), time * 1.0e-9));
235             } catch (ArithmeticException ex) {
236               selfEnergy = Double.NaN;
237               time += System.nanoTime();
238               logger.info(format(" Self %8s %-2d:\t    pruned in %6.4f (sec).",
239                   residues[i].toString(rotamers[ri]), ri, time * 1.0e-9));
240             }
241             myBuffer.put(2, selfEnergy);
242           }
243         } else {
244           // allGather parallel command below requires resultBuffer
245           // to have no null elements. Therefore, the padded energies that
246           // enter this else statement must be given an energy of 0.
247           myBuffer.put(2, 0.0);
248         }
249 
250         // All to All communication
251         if (numProc > 1) {
252           try {
253             world.allGather(myBuffer, resultBuffer);
254           } catch (Exception e) {
255             logger.log(Level.SEVERE, " Exception communicating self energies.", e);
256           }
257         }
258 
259         // Process the self energy received from each process.
260         for (DoubleBuf doubleBuf : resultBuffer) {
261           int resI = (int) doubleBuf.get(0);
262           int rotI = (int) doubleBuf.get(1);
263           double energy = doubleBuf.get(2);
264           // Skip for padded result.
265           if (resI >= 0 && rotI >= 0) {
266             if (Double.isNaN(energy)) {
267               logger.info(" Rotamer  eliminated: " + resI + ", " + rotI);
268               eR.eliminateRotamer(residues, resI, rotI, false);
269             }
270             eE.setSelf(resI, rotI, energy);
271             if (rank == 0 && writeEnergyRestart && printFiles) {
272               try {
273                 energyWriter.append(format("Self %d %d: %16.8f", resI, rotI, energy));
274                 energyWriter.newLine();
275                 energyWriter.flush();
276               } catch (IOException ex) {
277                 logger.log(Level.SEVERE, " Exception writing energy restart file.", ex);
278               }
279             }
280           }
281         }
282       }
283     }
284 
285     @Override
286     public IntegerSchedule schedule() {
287       // The schedule must be fixed.
288       return IntegerSchedule.fixed();
289     }
290   }
291 }