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