ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/OpenMD/branches/development/src/brains/SimCreator.cpp
Revision: 1827
Committed: Wed Jan 9 19:49:07 2013 UTC (12 years, 3 months ago) by gezelter
File size: 32653 byte(s)
Log Message:
More cleaning, removing non-C++ MPI calls

File Contents

# User Rev Content
1 gezelter 403 /*
2     * Copyright (c) 2005 The University of Notre Dame. All Rights Reserved.
3     *
4     * The University of Notre Dame grants you ("Licensee") a
5     * non-exclusive, royalty free, license to use, modify and
6     * redistribute this software in source and binary code form, provided
7     * that the following conditions are met:
8     *
9 gezelter 1390 * 1. Redistributions of source code must retain the above copyright
10 gezelter 403 * notice, this list of conditions and the following disclaimer.
11     *
12 gezelter 1390 * 2. Redistributions in binary form must reproduce the above copyright
13 gezelter 403 * notice, this list of conditions and the following disclaimer in the
14     * documentation and/or other materials provided with the
15     * distribution.
16     *
17     * This software is provided "AS IS," without a warranty of any
18     * kind. All express or implied conditions, representations and
19     * warranties, including any implied warranty of merchantability,
20     * fitness for a particular purpose or non-infringement, are hereby
21     * excluded. The University of Notre Dame and its licensors shall not
22     * be liable for any damages suffered by licensee as a result of
23     * using, modifying or distributing the software or its
24     * derivatives. In no event will the University of Notre Dame or its
25     * licensors be liable for any lost revenue, profit or data, or for
26     * direct, indirect, special, consequential, incidental or punitive
27     * damages, however caused and regardless of the theory of liability,
28     * arising out of the use of or inability to use software, even if the
29     * University of Notre Dame has been advised of the possibility of
30     * such damages.
31 gezelter 1390 *
32     * SUPPORT OPEN SCIENCE! If you use OpenMD or its source code in your
33     * research, please cite the appropriate papers when you publish your
34     * work. Good starting points are:
35     *
36     * [1] Meineke, et al., J. Comp. Chem. 26, 252-271 (2005).
37     * [2] Fennell & Gezelter, J. Chem. Phys. 124, 234104 (2006).
38     * [3] Sun, Lin & Gezelter, J. Chem. Phys. 128, 24107 (2008).
39 gezelter 1665 * [4] Kuang & Gezelter, J. Chem. Phys. 133, 164101 (2010).
40     * [5] Vardeman, Stocker & Gezelter, J. Chem. Theory Comput. 7, 834 (2011).
41 gezelter 403 */
42    
43     /**
44     * @file SimCreator.cpp
45     * @author tlin
46     * @date 11/03/2004
47     * @version 1.0
48     */
49 tim 845 #include <exception>
50 tim 770 #include <iostream>
51     #include <sstream>
52     #include <string>
53    
54 gezelter 403 #include "brains/MoleculeCreator.hpp"
55     #include "brains/SimCreator.hpp"
56     #include "brains/SimSnapshotManager.hpp"
57     #include "io/DumpReader.hpp"
58 gezelter 1725 #include "brains/ForceField.hpp"
59 gezelter 403 #include "utils/simError.h"
60     #include "utils/StringUtils.hpp"
61     #include "math/SeqRandNumGen.hpp"
62 tim 770 #include "mdParser/MDLexer.hpp"
63     #include "mdParser/MDParser.hpp"
64     #include "mdParser/MDTreeParser.hpp"
65     #include "mdParser/SimplePreprocessor.hpp"
66 tim 816 #include "antlr/ANTLRException.hpp"
67     #include "antlr/TokenStreamRecognitionException.hpp"
68     #include "antlr/TokenStreamIOException.hpp"
69     #include "antlr/TokenStreamException.hpp"
70     #include "antlr/RecognitionException.hpp"
71     #include "antlr/CharStreamException.hpp"
72 tim 770
73 tim 816 #include "antlr/MismatchedCharException.hpp"
74     #include "antlr/MismatchedTokenException.hpp"
75     #include "antlr/NoViableAltForCharException.hpp"
76     #include "antlr/NoViableAltException.hpp"
77 tim 770
78 gezelter 1710 #include "types/DirectionalAdapter.hpp"
79     #include "types/MultipoleAdapter.hpp"
80     #include "types/EAMAdapter.hpp"
81     #include "types/SuttonChenAdapter.hpp"
82     #include "types/PolarizableAdapter.hpp"
83     #include "types/FixedChargeAdapter.hpp"
84     #include "types/FluctuatingChargeAdapter.hpp"
85    
86 gezelter 403 #ifdef IS_MPI
87 gezelter 1627 #include "mpi.h"
88 gezelter 403 #include "math/ParallelRandNumGen.hpp"
89     #endif
90    
91 gezelter 1390 namespace OpenMD {
92 chrisfen 417
93 gezelter 1613 Globals* SimCreator::parseFile(std::istream& rawMetaDataStream, const std::string& filename, int mdFileVersion, int startOfMetaDataBlock ){
94 tim 1024 Globals* simParams = NULL;
95     try {
96 tim 770
97 tim 1024 // Create a preprocessor that preprocesses md file into an ostringstream
98     std::stringstream ppStream;
99 tim 770 #ifdef IS_MPI
100 tim 1024 int streamSize;
101     const int masterNode = 0;
102 gezelter 1827
103 tim 1024 if (worldRank == masterNode) {
104 gezelter 1827 MPI::COMM_WORLD.Bcast(&mdFileVersion, 1, MPI::INT, masterNode);
105 gezelter 1613 #endif
106 tim 1024 SimplePreprocessor preprocessor;
107     preprocessor.preprocess(rawMetaDataStream, filename, startOfMetaDataBlock, ppStream);
108 tim 770
109     #ifdef IS_MPI
110 tim 1024 //brocasting the stream size
111     streamSize = ppStream.str().size() +1;
112 gezelter 1827 MPI::COMM_WORLD.Bcast(&streamSize, 1, MPI::LONG, masterNode);
113     MPI::COMM_WORLD.Bcast(static_cast<void*>(const_cast<char*>(ppStream.str().c_str())), streamSize, MPI::CHAR, masterNode);
114    
115 tim 1024 } else {
116 gezelter 1827 MPI::COMM_WORLD.Bcast(&mdFileVersion, 1, MPI::INT, masterNode);
117 gezelter 1613
118 tim 1024 //get stream size
119 gezelter 1827 MPI::COMM_WORLD.Bcast(&streamSize, 1, MPI::LONG, masterNode);
120 gezelter 1313
121 tim 1024 char* buf = new char[streamSize];
122     assert(buf);
123 tim 770
124 tim 1024 //receive file content
125 gezelter 1827 MPI::COMM_WORLD.Bcast(buf, streamSize, MPI::CHAR, masterNode);
126 tim 770
127 tim 1024 ppStream.str(buf);
128 gezelter 1313 delete [] buf;
129 tim 1024 }
130 tim 770 #endif
131 tim 1024 // Create a scanner that reads from the input stream
132     MDLexer lexer(ppStream);
133     lexer.setFilename(filename);
134     lexer.initDeferredLineCount();
135 chrisfen 417
136 tim 1024 // Create a parser that reads from the scanner
137     MDParser parser(lexer);
138     parser.setFilename(filename);
139 tim 770
140 tim 1024 // Create an observer that synchorizes file name change
141     FilenameObserver observer;
142     observer.setLexer(&lexer);
143     observer.setParser(&parser);
144     lexer.setObserver(&observer);
145 chrisfen 417
146 tim 1024 antlr::ASTFactory factory;
147     parser.initializeASTFactory(factory);
148     parser.setASTFactory(&factory);
149     parser.mdfile();
150 tim 770
151 tim 1024 // Create a tree parser that reads information into Globals
152     MDTreeParser treeParser;
153     treeParser.initializeASTFactory(factory);
154     treeParser.setASTFactory(&factory);
155     simParams = treeParser.walkTree(parser.getAST());
156     }
157 tim 845
158 tim 816
159 tim 1024 catch(antlr::MismatchedCharException& e) {
160     sprintf(painCave.errMsg,
161     "parser exception: %s %s:%d:%d\n",
162     e.getMessage().c_str(),e.getFilename().c_str(), e.getLine(), e.getColumn());
163     painCave.isFatal = 1;
164     simError();
165     }
166     catch(antlr::MismatchedTokenException &e) {
167     sprintf(painCave.errMsg,
168     "parser exception: %s %s:%d:%d\n",
169     e.getMessage().c_str(),e.getFilename().c_str(), e.getLine(), e.getColumn());
170     painCave.isFatal = 1;
171     simError();
172     }
173     catch(antlr::NoViableAltForCharException &e) {
174     sprintf(painCave.errMsg,
175     "parser exception: %s %s:%d:%d\n",
176     e.getMessage().c_str(),e.getFilename().c_str(), e.getLine(), e.getColumn());
177     painCave.isFatal = 1;
178     simError();
179     }
180     catch(antlr::NoViableAltException &e) {
181     sprintf(painCave.errMsg,
182     "parser exception: %s %s:%d:%d\n",
183     e.getMessage().c_str(),e.getFilename().c_str(), e.getLine(), e.getColumn());
184     painCave.isFatal = 1;
185     simError();
186     }
187 tim 845
188 tim 1024 catch(antlr::TokenStreamRecognitionException& e) {
189     sprintf(painCave.errMsg,
190     "parser exception: %s %s:%d:%d\n",
191     e.getMessage().c_str(),e.getFilename().c_str(), e.getLine(), e.getColumn());
192     painCave.isFatal = 1;
193     simError();
194     }
195 tim 845
196 tim 1024 catch(antlr::TokenStreamIOException& e) {
197     sprintf(painCave.errMsg,
198     "parser exception: %s\n",
199     e.getMessage().c_str());
200     painCave.isFatal = 1;
201     simError();
202     }
203 tim 845
204 tim 1024 catch(antlr::TokenStreamException& e) {
205     sprintf(painCave.errMsg,
206     "parser exception: %s\n",
207     e.getMessage().c_str());
208     painCave.isFatal = 1;
209     simError();
210     }
211     catch (antlr::RecognitionException& e) {
212     sprintf(painCave.errMsg,
213     "parser exception: %s %s:%d:%d\n",
214     e.getMessage().c_str(),e.getFilename().c_str(), e.getLine(), e.getColumn());
215     painCave.isFatal = 1;
216     simError();
217     }
218     catch (antlr::CharStreamException& e) {
219     sprintf(painCave.errMsg,
220     "parser exception: %s\n",
221     e.getMessage().c_str());
222     painCave.isFatal = 1;
223     simError();
224     }
225 gezelter 1390 catch (OpenMDException& e) {
226 tim 1024 sprintf(painCave.errMsg,
227     "%s\n",
228     e.getMessage().c_str());
229     painCave.isFatal = 1;
230     simError();
231     }
232     catch (std::exception& e) {
233     sprintf(painCave.errMsg,
234     "parser exception: %s\n",
235     e.what());
236     painCave.isFatal = 1;
237     simError();
238     }
239 tim 770
240 gezelter 1613 simParams->setMDfileVersion(mdFileVersion);
241 tim 1024 return simParams;
242 gezelter 403 }
243 chrisfen 417
244 chrisfen 514 SimInfo* SimCreator::createSim(const std::string & mdFileName,
245     bool loadInitCoords) {
246 gezelter 1469
247 tim 1024 const int bufferSize = 65535;
248     char buffer[bufferSize];
249     int lineNo = 0;
250     std::string mdRawData;
251     int metaDataBlockStart = -1;
252     int metaDataBlockEnd = -1;
253 gezelter 1812 int i, j;
254 gezelter 1767 streamoff mdOffset;
255 gezelter 1613 int mdFileVersion;
256 tim 1024
257 gezelter 1812 // Create a string for embedding the version information in the MetaData
258     std::string version;
259     version.assign("## Last run using OpenMD Version: ");
260     version.append(OPENMD_VERSION_MAJOR);
261     version.append(".");
262     version.append(OPENMD_VERSION_MINOR);
263 gezelter 1794
264 gezelter 1812 std::string svnrev;
265     //convert a macro from compiler to a string in c++
266     STR_DEFINE(svnrev, SVN_REV );
267     version.append(" Revision: ");
268     // If there's no SVN revision, just call this the RELEASE revision.
269     if (!svnrev.empty()) {
270     version.append(svnrev);
271     } else {
272     version.append("RELEASE");
273     }
274    
275 tim 1024 #ifdef IS_MPI
276     const int masterNode = 0;
277     if (worldRank == masterNode) {
278     #endif
279    
280 gezelter 1794 std::ifstream mdFile_;
281     mdFile_.open(mdFileName.c_str(), ifstream::in | ifstream::binary);
282 tim 1024
283     if (mdFile_.fail()) {
284     sprintf(painCave.errMsg,
285     "SimCreator: Cannot open file: %s\n",
286     mdFileName.c_str());
287     painCave.isFatal = 1;
288     simError();
289     }
290    
291     mdFile_.getline(buffer, bufferSize);
292     ++lineNo;
293     std::string line = trimLeftCopy(buffer);
294 gezelter 1390 i = CaseInsensitiveFind(line, "<OpenMD");
295 gezelter 1287 if (static_cast<size_t>(i) == string::npos) {
296 gezelter 1390 // try the older file strings to see if that works:
297     i = CaseInsensitiveFind(line, "<OOPSE");
298     }
299    
300     if (static_cast<size_t>(i) == string::npos) {
301     // still no luck!
302 tim 1024 sprintf(painCave.errMsg,
303 gezelter 1390 "SimCreator: File: %s is not a valid OpenMD file!\n",
304 tim 1024 mdFileName.c_str());
305     painCave.isFatal = 1;
306     simError();
307     }
308 gezelter 1613
309     // found the correct opening string, now try to get the file
310     // format version number.
311 tim 1024
312 gezelter 1613 StringTokenizer tokenizer(line, "=<> \t\n\r");
313     std::string fileType = tokenizer.nextToken();
314     toUpper(fileType);
315    
316     mdFileVersion = 0;
317    
318     if (fileType == "OPENMD") {
319     while (tokenizer.hasMoreTokens()) {
320     std::string token(tokenizer.nextToken());
321     toUpper(token);
322     if (token == "VERSION") {
323     mdFileVersion = tokenizer.nextTokenAsInt();
324     break;
325     }
326     }
327     }
328    
329 tim 1024 //scan through the input stream and find MetaData tag
330     while(mdFile_.getline(buffer, bufferSize)) {
331     ++lineNo;
332    
333     std::string line = trimLeftCopy(buffer);
334     if (metaDataBlockStart == -1) {
335     i = CaseInsensitiveFind(line, "<MetaData>");
336     if (i != string::npos) {
337     metaDataBlockStart = lineNo;
338     mdOffset = mdFile_.tellg();
339     }
340     } else {
341     i = CaseInsensitiveFind(line, "</MetaData>");
342     if (i != string::npos) {
343     metaDataBlockEnd = lineNo;
344     }
345     }
346     }
347    
348     if (metaDataBlockStart == -1) {
349     sprintf(painCave.errMsg,
350     "SimCreator: File: %s did not contain a <MetaData> tag!\n",
351     mdFileName.c_str());
352     painCave.isFatal = 1;
353     simError();
354     }
355     if (metaDataBlockEnd == -1) {
356     sprintf(painCave.errMsg,
357     "SimCreator: File: %s did not contain a closed MetaData block!\n",
358     mdFileName.c_str());
359     painCave.isFatal = 1;
360     simError();
361     }
362    
363     mdFile_.clear();
364     mdFile_.seekg(0);
365     mdFile_.seekg(mdOffset);
366    
367     mdRawData.clear();
368    
369 gezelter 1812 bool foundVersion = false;
370    
371 tim 1024 for (int i = 0; i < metaDataBlockEnd - metaDataBlockStart - 1; ++i) {
372     mdFile_.getline(buffer, bufferSize);
373 gezelter 1812 std::string line = trimLeftCopy(buffer);
374     j = CaseInsensitiveFind(line, "## Last run using OpenMD Version");
375     if (static_cast<size_t>(j) != string::npos) {
376     foundVersion = true;
377     mdRawData += version;
378     } else {
379     mdRawData += buffer;
380     }
381 tim 1024 mdRawData += "\n";
382     }
383 gezelter 1812
384     if (!foundVersion) mdRawData += version + "\n";
385    
386 tim 1024 mdFile_.close();
387    
388     #ifdef IS_MPI
389     }
390     #endif
391    
392     std::stringstream rawMetaDataStream(mdRawData);
393    
394 gezelter 403 //parse meta-data file
395 gezelter 1613 Globals* simParams = parseFile(rawMetaDataStream, mdFileName, mdFileVersion,
396     metaDataBlockStart + 1);
397 chrisfen 417
398 gezelter 403 //create the force field
399 gezelter 1725 ForceField * ff = new ForceField(simParams->getForceField());
400 gezelter 1277
401 gezelter 403 if (ff == NULL) {
402 chrisfen 514 sprintf(painCave.errMsg,
403     "ForceField Factory can not create %s force field\n",
404 tim 665 simParams->getForceField().c_str());
405 gezelter 403 painCave.isFatal = 1;
406     simError();
407     }
408 chrisfen 417
409 gezelter 403 if (simParams->haveForceFieldFileName()) {
410     ff->setForceFieldFileName(simParams->getForceFieldFileName());
411     }
412    
413     std::string forcefieldFileName;
414     forcefieldFileName = ff->getForceFieldFileName();
415 chrisfen 417
416 gezelter 403 if (simParams->haveForceFieldVariant()) {
417     //If the force field has variant, the variant force field name will be
418     //Base.variant.frc. For exampel EAM.u6.frc
419 chrisfen 417
420 gezelter 403 std::string variant = simParams->getForceFieldVariant();
421 chrisfen 417
422 gezelter 403 std::string::size_type pos = forcefieldFileName.rfind(".frc");
423     variant = "." + variant;
424     if (pos != std::string::npos) {
425     forcefieldFileName.insert(pos, variant);
426     } else {
427     //If the default force field file name does not containt .frc suffix, just append the .variant
428     forcefieldFileName.append(variant);
429     }
430     }
431    
432     ff->parse(forcefieldFileName);
433     //create SimInfo
434 tim 770 SimInfo * info = new SimInfo(ff, simParams);
435 tim 1024
436     info->setRawMetaData(mdRawData);
437 tim 490
438 gezelter 945 //gather parameters (SimCreator only retrieves part of the
439     //parameters)
440 gezelter 403 gatherParameters(info, mdFileName);
441 chrisfen 417
442 gezelter 403 //divide the molecules and determine the global index of molecules
443     #ifdef IS_MPI
444     divideMolecules(info);
445     #endif
446 chrisfen 417
447 gezelter 403 //create the molecules
448     createMolecules(info);
449 chrisfen 417
450 gezelter 1710 //find the storage layout
451    
452     int storageLayout = computeStorageLayout(info);
453    
454 gezelter 945 //allocate memory for DataStorage(circular reference, need to
455     //break it)
456 gezelter 1710 info->setSnapshotManager(new SimSnapshotManager(info, storageLayout));
457 gezelter 403
458 gezelter 945 //set the global index of atoms, rigidbodies and cutoffgroups
459     //(only need to be set once, the global index will never change
460     //again). Local indices of atoms and rigidbodies are already set
461     //by MoleculeCreator class which actually delegates the
462     //responsibility to LocalIndexManager.
463 gezelter 403 setGlobalIndex(info);
464 chrisfen 417
465 gezelter 1287 //Although addInteractionPairs is called inside SimInfo's addMolecule
466 gezelter 945 //method, at that point atoms don't have the global index yet
467     //(their global index are all initialized to -1). Therefore we
468 gezelter 1287 //have to call addInteractionPairs explicitly here. A way to work
469 gezelter 945 //around is that we can determine the beginning global indices of
470     //atoms before they get created.
471 gezelter 403 SimInfo::MoleculeIterator mi;
472     Molecule* mol;
473     for (mol= info->beginMolecule(mi); mol != NULL; mol = info->nextMolecule(mi)) {
474 gezelter 1287 info->addInteractionPairs(mol);
475 gezelter 403 }
476    
477     if (loadInitCoords)
478 tim 1024 loadCoordinates(info, mdFileName);
479 gezelter 403 return info;
480     }
481 chrisfen 417
482 gezelter 403 void SimCreator::gatherParameters(SimInfo *info, const std::string& mdfile) {
483 chrisfen 417
484 tim 749 //figure out the output file names
485 gezelter 403 std::string prefix;
486 chrisfen 417
487 gezelter 403 #ifdef IS_MPI
488 chrisfen 417
489 gezelter 403 if (worldRank == 0) {
490     #endif // is_mpi
491     Globals * simParams = info->getSimParams();
492     if (simParams->haveFinalConfig()) {
493     prefix = getPrefix(simParams->getFinalConfig());
494     } else {
495     prefix = getPrefix(mdfile);
496     }
497 chrisfen 417
498 gezelter 403 info->setFinalConfigFileName(prefix + ".eor");
499     info->setDumpFileName(prefix + ".dump");
500     info->setStatFileName(prefix + ".stat");
501 chrisfen 417 info->setRestFileName(prefix + ".zang");
502    
503 gezelter 403 #ifdef IS_MPI
504 chrisfen 417
505 gezelter 403 }
506 chrisfen 417
507 gezelter 403 #endif
508 chrisfen 417
509 gezelter 403 }
510 chrisfen 417
511 gezelter 403 #ifdef IS_MPI
512     void SimCreator::divideMolecules(SimInfo *info) {
513 tim 963 RealType numerator;
514     RealType denominator;
515     RealType precast;
516     RealType x;
517     RealType y;
518     RealType a;
519 gezelter 403 int old_atoms;
520     int add_atoms;
521     int new_atoms;
522     int nTarget;
523     int done;
524     int i;
525     int loops;
526     int which_proc;
527     int nProcessors;
528     std::vector<int> atomsPerProc;
529     int nGlobalMols = info->getNGlobalMolecules();
530     std::vector<int> molToProcMap(nGlobalMols, -1); // default to an error condition:
531    
532 gezelter 1798 nProcessors = MPI::COMM_WORLD.Get_size();
533 chrisfen 417
534 gezelter 403 if (nProcessors > nGlobalMols) {
535     sprintf(painCave.errMsg,
536     "nProcessors (%d) > nMol (%d)\n"
537     "\tThe number of processors is larger than\n"
538     "\tthe number of molecules. This will not result in a \n"
539     "\tusable division of atoms for force decomposition.\n"
540     "\tEither try a smaller number of processors, or run the\n"
541 gezelter 1390 "\tsingle-processor version of OpenMD.\n", nProcessors, nGlobalMols);
542 chrisfen 417
543 gezelter 403 painCave.isFatal = 1;
544     simError();
545     }
546 chrisfen 417
547 gezelter 403 int seedValue;
548     Globals * simParams = info->getSimParams();
549     SeqRandNumGen* myRandom; //divide labor does not need Parallel random number generator
550     if (simParams->haveSeed()) {
551     seedValue = simParams->getSeed();
552     myRandom = new SeqRandNumGen(seedValue);
553     }else {
554     myRandom = new SeqRandNumGen();
555     }
556 chrisfen 417
557    
558 gezelter 403 a = 3.0 * nGlobalMols / info->getNGlobalAtoms();
559 chrisfen 417
560 gezelter 403 //initialize atomsPerProc
561     atomsPerProc.insert(atomsPerProc.end(), nProcessors, 0);
562 chrisfen 417
563 gezelter 403 if (worldRank == 0) {
564     numerator = info->getNGlobalAtoms();
565     denominator = nProcessors;
566     precast = numerator / denominator;
567     nTarget = (int)(precast + 0.5);
568 chrisfen 417
569 gezelter 403 for(i = 0; i < nGlobalMols; i++) {
570 gezelter 1803
571 gezelter 403 done = 0;
572     loops = 0;
573 chrisfen 417
574 gezelter 403 while (!done) {
575     loops++;
576 chrisfen 417
577 gezelter 403 // Pick a processor at random
578 chrisfen 417
579 gezelter 403 which_proc = (int) (myRandom->rand() * nProcessors);
580 chrisfen 417
581 gezelter 403 //get the molecule stamp first
582     int stampId = info->getMoleculeStampId(i);
583     MoleculeStamp * moleculeStamp = info->getMoleculeStamp(stampId);
584 chrisfen 417
585 gezelter 403 // How many atoms does this processor have so far?
586     old_atoms = atomsPerProc[which_proc];
587     add_atoms = moleculeStamp->getNAtoms();
588     new_atoms = old_atoms + add_atoms;
589 chrisfen 417
590 gezelter 403 // If we've been through this loop too many times, we need
591     // to just give up and assign the molecule to this processor
592     // and be done with it.
593 chrisfen 417
594 gezelter 403 if (loops > 100) {
595 gezelter 1803
596 gezelter 403 sprintf(painCave.errMsg,
597 gezelter 1803 "There have been 100 attempts to assign molecule %d to an\n"
598     "\tunderworked processor, but there's no good place to\n"
599     "\tleave it. OpenMD is assigning it at random to processor %d.\n",
600 gezelter 403 i, which_proc);
601 gezelter 1803
602 gezelter 403 painCave.isFatal = 0;
603 gezelter 1803 painCave.severity = OPENMD_INFO;
604 gezelter 403 simError();
605 chrisfen 417
606 gezelter 403 molToProcMap[i] = which_proc;
607     atomsPerProc[which_proc] += add_atoms;
608 chrisfen 417
609 gezelter 403 done = 1;
610     continue;
611     }
612 chrisfen 417
613 gezelter 403 // If we can add this molecule to this processor without sending
614     // it above nTarget, then go ahead and do it:
615 chrisfen 417
616 gezelter 403 if (new_atoms <= nTarget) {
617     molToProcMap[i] = which_proc;
618     atomsPerProc[which_proc] += add_atoms;
619 chrisfen 417
620 gezelter 403 done = 1;
621     continue;
622     }
623 chrisfen 417
624 gezelter 403 // The only situation left is when new_atoms > nTarget. We
625     // want to accept this with some probability that dies off the
626     // farther we are from nTarget
627 chrisfen 417
628 gezelter 403 // roughly: x = new_atoms - nTarget
629     // Pacc(x) = exp(- a * x)
630     // where a = penalty / (average atoms per molecule)
631 chrisfen 417
632 tim 963 x = (RealType)(new_atoms - nTarget);
633 gezelter 403 y = myRandom->rand();
634 chrisfen 417
635 gezelter 403 if (y < exp(- a * x)) {
636     molToProcMap[i] = which_proc;
637     atomsPerProc[which_proc] += add_atoms;
638 chrisfen 417
639 gezelter 403 done = 1;
640     continue;
641     } else {
642     continue;
643     }
644     }
645     }
646 chrisfen 417
647 gezelter 403 delete myRandom;
648 gezelter 1803
649 gezelter 403 // Spray out this nonsense to all other processors:
650 gezelter 1798 MPI::COMM_WORLD.Bcast(&molToProcMap[0], nGlobalMols, MPI::INT, 0);
651 gezelter 403 } else {
652 chrisfen 417
653 gezelter 403 // Listen to your marching orders from processor 0:
654 gezelter 1798 MPI::COMM_WORLD.Bcast(&molToProcMap[0], nGlobalMols, MPI::INT, 0);
655 gezelter 1803
656 gezelter 403 }
657 chrisfen 417
658 gezelter 403 info->setMolToProcMap(molToProcMap);
659     sprintf(checkPointMsg,
660     "Successfully divided the molecules among the processors.\n");
661 gezelter 1241 errorCheckPoint();
662 gezelter 403 }
663 chrisfen 417
664 gezelter 403 #endif
665 chrisfen 417
666 gezelter 403 void SimCreator::createMolecules(SimInfo *info) {
667     MoleculeCreator molCreator;
668     int stampId;
669 chrisfen 417
670 gezelter 403 for(int i = 0; i < info->getNGlobalMolecules(); i++) {
671 chrisfen 417
672 gezelter 403 #ifdef IS_MPI
673 chrisfen 417
674 gezelter 403 if (info->getMolToProc(i) == worldRank) {
675     #endif
676 chrisfen 417
677 gezelter 403 stampId = info->getMoleculeStampId(i);
678 gezelter 1600 Molecule * mol = molCreator.createMolecule(info->getForceField(),
679     info->getMoleculeStamp(stampId),
680     stampId, i,
681     info->getLocalIndexManager());
682 chrisfen 417
683 gezelter 403 info->addMolecule(mol);
684 chrisfen 417
685 gezelter 403 #ifdef IS_MPI
686 chrisfen 417
687 gezelter 403 }
688 chrisfen 417
689 gezelter 403 #endif
690 chrisfen 417
691 gezelter 403 } //end for(int i=0)
692     }
693 chrisfen 417
694 gezelter 1710 int SimCreator::computeStorageLayout(SimInfo* info) {
695    
696 gezelter 1711 Globals* simParams = info->getSimParams();
697 gezelter 1710 int nRigidBodies = info->getNGlobalRigidBodies();
698     set<AtomType*> atomTypes = info->getSimulatedAtomTypes();
699     set<AtomType*>::iterator i;
700     bool hasDirectionalAtoms = false;
701     bool hasFixedCharge = false;
702 gezelter 1794 bool hasDipoles = false;
703     bool hasQuadrupoles = false;
704 gezelter 1710 bool hasPolarizable = false;
705     bool hasFluctuatingCharge = false;
706     bool hasMetallic = false;
707     int storageLayout = 0;
708     storageLayout |= DataStorage::dslPosition;
709     storageLayout |= DataStorage::dslVelocity;
710     storageLayout |= DataStorage::dslForce;
711    
712     for (i = atomTypes.begin(); i != atomTypes.end(); ++i) {
713    
714     DirectionalAdapter da = DirectionalAdapter( (*i) );
715     MultipoleAdapter ma = MultipoleAdapter( (*i) );
716     EAMAdapter ea = EAMAdapter( (*i) );
717     SuttonChenAdapter sca = SuttonChenAdapter( (*i) );
718     PolarizableAdapter pa = PolarizableAdapter( (*i) );
719     FixedChargeAdapter fca = FixedChargeAdapter( (*i) );
720     FluctuatingChargeAdapter fqa = FluctuatingChargeAdapter( (*i) );
721    
722     if (da.isDirectional()){
723     hasDirectionalAtoms = true;
724     }
725 gezelter 1794 if (ma.isDipole()){
726     hasDipoles = true;
727 gezelter 1710 }
728 gezelter 1794 if (ma.isQuadrupole()){
729     hasQuadrupoles = true;
730     }
731 gezelter 1710 if (ea.isEAM() || sca.isSuttonChen()){
732     hasMetallic = true;
733     }
734     if ( fca.isFixedCharge() ){
735     hasFixedCharge = true;
736     }
737     if ( fqa.isFluctuatingCharge() ){
738     hasFluctuatingCharge = true;
739     }
740     if ( pa.isPolarizable() ){
741     hasPolarizable = true;
742     }
743     }
744    
745     if (nRigidBodies > 0 || hasDirectionalAtoms) {
746     storageLayout |= DataStorage::dslAmat;
747     if(storageLayout & DataStorage::dslVelocity) {
748     storageLayout |= DataStorage::dslAngularMomentum;
749     }
750     if (storageLayout & DataStorage::dslForce) {
751     storageLayout |= DataStorage::dslTorque;
752     }
753     }
754 gezelter 1794 if (hasDipoles) {
755     storageLayout |= DataStorage::dslDipole;
756     }
757     if (hasQuadrupoles) {
758     storageLayout |= DataStorage::dslQuadrupole;
759     }
760 gezelter 1710 if (hasFixedCharge || hasFluctuatingCharge) {
761     storageLayout |= DataStorage::dslSkippedCharge;
762     }
763     if (hasMetallic) {
764     storageLayout |= DataStorage::dslDensity;
765     storageLayout |= DataStorage::dslFunctional;
766     storageLayout |= DataStorage::dslFunctionalDerivative;
767     }
768     if (hasPolarizable) {
769     storageLayout |= DataStorage::dslElectricField;
770     }
771     if (hasFluctuatingCharge){
772     storageLayout |= DataStorage::dslFlucQPosition;
773     if(storageLayout & DataStorage::dslVelocity) {
774     storageLayout |= DataStorage::dslFlucQVelocity;
775     }
776     if (storageLayout & DataStorage::dslForce) {
777     storageLayout |= DataStorage::dslFlucQForce;
778     }
779     }
780 gezelter 1714
781     // if the user has asked for them, make sure we've got the memory for the
782     // objects defined.
783 gezelter 1711
784     if (simParams->getOutputParticlePotential()) {
785     storageLayout |= DataStorage::dslParticlePot;
786     }
787 gezelter 1723
788     if (simParams->havePrintHeatFlux()) {
789     if (simParams->getPrintHeatFlux()) {
790     storageLayout |= DataStorage::dslParticlePot;
791     }
792     }
793    
794 gezelter 1714 if (simParams->getOutputElectricField()) {
795     storageLayout |= DataStorage::dslElectricField;
796     }
797 gezelter 1787
798 gezelter 1714 if (simParams->getOutputFluctuatingCharges()) {
799     storageLayout |= DataStorage::dslFlucQPosition;
800     storageLayout |= DataStorage::dslFlucQVelocity;
801     storageLayout |= DataStorage::dslFlucQForce;
802     }
803 gezelter 1711
804 gezelter 1710 return storageLayout;
805     }
806    
807 gezelter 403 void SimCreator::setGlobalIndex(SimInfo *info) {
808     SimInfo::MoleculeIterator mi;
809     Molecule::AtomIterator ai;
810     Molecule::RigidBodyIterator ri;
811     Molecule::CutoffGroupIterator ci;
812 tim 1024 Molecule::IntegrableObjectIterator ioi;
813 gezelter 403 Molecule * mol;
814     Atom * atom;
815     RigidBody * rb;
816     CutoffGroup * cg;
817     int beginAtomIndex;
818     int beginRigidBodyIndex;
819     int beginCutoffGroupIndex;
820     int nGlobalAtoms = info->getNGlobalAtoms();
821 gezelter 1803 int nGlobalRigidBodies = info->getNGlobalRigidBodies();
822 chrisfen 417
823 gezelter 403 beginAtomIndex = 0;
824 gezelter 1757 //rigidbody's index begins right after atom's
825     beginRigidBodyIndex = info->getNGlobalAtoms();
826 gezelter 403 beginCutoffGroupIndex = 0;
827 gezelter 1600
828     for(int i = 0; i < info->getNGlobalMolecules(); i++) {
829 chrisfen 417
830 gezelter 1600 #ifdef IS_MPI
831     if (info->getMolToProc(i) == worldRank) {
832     #endif
833     // stuff to do if I own this molecule
834     mol = info->getMoleculeByGlobalIndex(i);
835    
836     //local index(index in DataStorge) of atom is important
837     for(atom = mol->beginAtom(ai); atom != NULL; atom = mol->nextAtom(ai)) {
838     atom->setGlobalIndex(beginAtomIndex++);
839     }
840    
841     for(rb = mol->beginRigidBody(ri); rb != NULL;
842     rb = mol->nextRigidBody(ri)) {
843     rb->setGlobalIndex(beginRigidBodyIndex++);
844     }
845    
846     //local index of cutoff group is trivial, it only depends on
847     //the order of travesing
848     for(cg = mol->beginCutoffGroup(ci); cg != NULL;
849     cg = mol->nextCutoffGroup(ci)) {
850     cg->setGlobalIndex(beginCutoffGroupIndex++);
851     }
852    
853     #ifdef IS_MPI
854     } else {
855    
856     // stuff to do if I don't own this molecule
857    
858     int stampId = info->getMoleculeStampId(i);
859     MoleculeStamp* stamp = info->getMoleculeStamp(stampId);
860    
861     beginAtomIndex += stamp->getNAtoms();
862     beginRigidBodyIndex += stamp->getNRigidBodies();
863     beginCutoffGroupIndex += stamp->getNCutoffGroups() + stamp->getNFreeAtoms();
864 gezelter 403 }
865 gezelter 1600 #endif
866    
867     } //end for(int i=0)
868    
869 gezelter 403 //fill globalGroupMembership
870 gezelter 1600 std::vector<int> globalGroupMembership(info->getNGlobalAtoms(), 0);
871 gezelter 403 for(mol = info->beginMolecule(mi); mol != NULL; mol = info->nextMolecule(mi)) {
872     for (cg = mol->beginCutoffGroup(ci); cg != NULL; cg = mol->nextCutoffGroup(ci)) {
873 chrisfen 417
874 gezelter 403 for(atom = cg->beginAtom(ai); atom != NULL; atom = cg->nextAtom(ai)) {
875     globalGroupMembership[atom->getGlobalIndex()] = cg->getGlobalIndex();
876     }
877 chrisfen 417
878 gezelter 403 }
879     }
880 gezelter 1577
881 gezelter 403 #ifdef IS_MPI
882     // Since the globalGroupMembership has been zero filled and we've only
883     // poked values into the atoms we know, we can do an Allreduce
884     // to get the full globalGroupMembership array (We think).
885     // This would be prettier if we could use MPI_IN_PLACE like the MPI-2
886     // docs said we could.
887 gezelter 1313 std::vector<int> tmpGroupMembership(info->getNGlobalAtoms(), 0);
888 gezelter 1798 MPI::COMM_WORLD.Allreduce(&globalGroupMembership[0],
889     &tmpGroupMembership[0], nGlobalAtoms,
890     MPI::INT, MPI::SUM);
891 gezelter 403 info->setGlobalGroupMembership(tmpGroupMembership);
892     #else
893     info->setGlobalGroupMembership(globalGroupMembership);
894     #endif
895 chrisfen 417
896 gezelter 403 //fill molMembership
897 gezelter 1803 std::vector<int> globalMolMembership(info->getNGlobalAtoms() +
898     info->getNGlobalRigidBodies(), 0);
899 gezelter 403
900 gezelter 1803 for(mol = info->beginMolecule(mi); mol != NULL;
901     mol = info->nextMolecule(mi)) {
902 gezelter 403 for(atom = mol->beginAtom(ai); atom != NULL; atom = mol->nextAtom(ai)) {
903     globalMolMembership[atom->getGlobalIndex()] = mol->getGlobalIndex();
904     }
905 gezelter 1803 for (rb = mol->beginRigidBody(ri); rb != NULL;
906     rb = mol->nextRigidBody(ri)) {
907     globalMolMembership[rb->getGlobalIndex()] = mol->getGlobalIndex();
908     }
909 gezelter 403 }
910 chrisfen 417
911 gezelter 403 #ifdef IS_MPI
912 gezelter 1803 std::vector<int> tmpMolMembership(info->getNGlobalAtoms() +
913     info->getNGlobalRigidBodies(), 0);
914 gezelter 1798 MPI::COMM_WORLD.Allreduce(&globalMolMembership[0], &tmpMolMembership[0],
915 gezelter 1803 nGlobalAtoms + nGlobalRigidBodies,
916 gezelter 1798 MPI::INT, MPI::SUM);
917 chrisfen 417
918 gezelter 403 info->setGlobalMolMembership(tmpMolMembership);
919     #else
920     info->setGlobalMolMembership(globalMolMembership);
921     #endif
922 tim 1024
923     // nIOPerMol holds the number of integrable objects per molecule
924     // here the molecules are listed by their global indices.
925    
926     std::vector<int> nIOPerMol(info->getNGlobalMolecules(), 0);
927 gezelter 1803 for (mol = info->beginMolecule(mi); mol != NULL;
928     mol = info->nextMolecule(mi)) {
929 tim 1024 nIOPerMol[mol->getGlobalIndex()] = mol->getNIntegrableObjects();
930     }
931 chrisfen 417
932 tim 1024 #ifdef IS_MPI
933     std::vector<int> numIntegrableObjectsPerMol(info->getNGlobalMolecules(), 0);
934 gezelter 1798 MPI::COMM_WORLD.Allreduce(&nIOPerMol[0], &numIntegrableObjectsPerMol[0],
935     info->getNGlobalMolecules(), MPI::INT, MPI::SUM);
936 tim 1024 #else
937     std::vector<int> numIntegrableObjectsPerMol = nIOPerMol;
938     #endif
939    
940 gezelter 1313 std::vector<int> startingIOIndexForMol(info->getNGlobalMolecules());
941    
942     int startingIndex = 0;
943     for (int i = 0; i < info->getNGlobalMolecules(); i++) {
944     startingIOIndexForMol[i] = startingIndex;
945     startingIndex += numIntegrableObjectsPerMol[i];
946     }
947    
948     std::vector<StuntDouble*> IOIndexToIntegrableObject(info->getNGlobalIntegrableObjects(), (StuntDouble*)NULL);
949 gezelter 1803 for (mol = info->beginMolecule(mi); mol != NULL;
950     mol = info->nextMolecule(mi)) {
951 tim 1024 int myGlobalIndex = mol->getGlobalIndex();
952     int globalIO = startingIOIndexForMol[myGlobalIndex];
953 gezelter 1769 for (StuntDouble* sd = mol->beginIntegrableObject(ioi); sd != NULL;
954     sd = mol->nextIntegrableObject(ioi)) {
955     sd->setGlobalIntegrableObjectIndex(globalIO);
956     IOIndexToIntegrableObject[globalIO] = sd;
957 gezelter 1313 globalIO++;
958 tim 1024 }
959     }
960 gezelter 1597
961 gezelter 1313 info->setIOIndexToIntegrableObject(IOIndexToIntegrableObject);
962    
963 gezelter 403 }
964 chrisfen 417
965 tim 1024 void SimCreator::loadCoordinates(SimInfo* info, const std::string& mdFileName) {
966 gezelter 403
967 tim 1024 DumpReader reader(info, mdFileName);
968 gezelter 403 int nframes = reader.getNFrames();
969 gezelter 1825
970 gezelter 403 if (nframes > 0) {
971     reader.readFrame(nframes - 1);
972     } else {
973     //invalid initial coordinate file
974 chrisfen 417 sprintf(painCave.errMsg,
975     "Initial configuration file %s should at least contain one frame\n",
976 tim 1024 mdFileName.c_str());
977 gezelter 403 painCave.isFatal = 1;
978     simError();
979     }
980     //copy the current snapshot to previous snapshot
981     info->getSnapshotManager()->advance();
982     }
983 chrisfen 417
984 gezelter 1390 } //end namespace OpenMD
985 gezelter 403
986    

Properties

Name Value
svn:keywords Author Id Revision Date