ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/OpenMD/trunk/src/brains/SimCreator.cpp
(Generate patch)

Comparing trunk/src/brains/SimCreator.cpp (file contents):
Revision 397 by gezelter, Fri Mar 4 15:29:03 2005 UTC vs.
Revision 1880 by gezelter, Mon Jun 17 18:28:30 2013 UTC

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

Comparing trunk/src/brains/SimCreator.cpp (property svn:keywords):
Revision 397 by gezelter, Fri Mar 4 15:29:03 2005 UTC vs.
Revision 1880 by gezelter, Mon Jun 17 18:28:30 2013 UTC

# Line 0 | Line 1
1 + Author Id Revision Date

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines