source: src/molecule_graph.cpp@ 936a02

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since 936a02 was 47d041, checked in by Frederik Heber <heber@…>, 13 years ago

HUGE: Removed all calls to Log(), eLog(), replaced by LOG() and ELOG().

  • Replaced DoLog(.) && (Log() << Verbose(.) << ... << std::endl) by Log(., ...).
  • Replaced Log() << Verbose(.) << .. << by Log(., ...)
  • on multiline used stringstream to generate and message which was finally used in LOG(., output.str())
  • there should be no more occurence of Log(). LOG() and ELOG() must be used instead.
  • Eventually, this will allow for storing all errors and re-printing them on program exit which would be very helpful to ascertain error-free runs for the user.
  • Property mode set to 100644
File size: 13.4 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * molecule_graph.cpp
10 *
11 * Created on: Oct 5, 2009
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include "CodePatterns/MemDebug.hpp"
21
22#include <stack>
23
24#include "atom.hpp"
25#include "Bond/bond.hpp"
26#include "Box.hpp"
27#include "CodePatterns/Assert.hpp"
28#include "CodePatterns/Info.hpp"
29#include "CodePatterns/Log.hpp"
30#include "CodePatterns/Verbose.hpp"
31#include "config.hpp"
32#include "Graph/DepthFirstSearchAnalysis.hpp"
33#include "Element/element.hpp"
34#include "Graph/BondGraph.hpp"
35#include "Helpers/defs.hpp"
36#include "Helpers/helpers.hpp"
37#include "LinearAlgebra/RealSpaceMatrix.hpp"
38#include "linkedcell.hpp"
39#include "molecule.hpp"
40#include "PointCloudAdaptor.hpp"
41#include "World.hpp"
42#include "WorldTime.hpp"
43
44
45/** Fills the bond structure of this chain list subgraphs that are derived from a complete \a *reference molecule.
46 * Calls this routine in each MoleculeLeafClass::next subgraph if it's not NULL.
47 * \param *reference reference molecule with the bond structure to be copied
48 * \param **&ListOfLocalAtoms Lookup table for this subgraph and index of each atom in \a *reference, may be NULL on start, then it is filled
49 * \param FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
50 * \return true - success, false - failure
51 */
52bool molecule::FillBondStructureFromReference(const molecule * const reference, atom **&ListOfLocalAtoms, bool FreeList)
53{
54 atom *OtherWalker = NULL;
55 atom *Father = NULL;
56 bool status = true;
57 int AtomNo;
58
59 LOG(1, "Begin of FillBondStructureFromReference.");
60 // fill ListOfLocalAtoms if NULL was given
61 if (!FillListOfLocalAtoms(ListOfLocalAtoms, reference->getAtomCount())) {
62 LOG(1, "Filling of ListOfLocalAtoms failed.");
63 return false;
64 }
65
66 if (status) {
67 LOG(1, "Creating adjacency list for molecule " << getName() << ".");
68 // remove every bond from the list
69 for_each(begin(), end(),
70 boost::bind(&BondedParticle::ClearBondsAtStep,_1,WorldTime::getTime()));
71
72
73 for(molecule::const_iterator iter = begin(); iter != end(); ++iter) {
74 Father = (*iter)->GetTrueFather();
75 AtomNo = Father->getNr(); // global id of the current walker
76 const BondList& ListOfBonds = Father->getListOfBonds();
77 for (BondList::const_iterator Runner = ListOfBonds.begin();
78 Runner != ListOfBonds.end();
79 ++Runner) {
80 OtherWalker = ListOfLocalAtoms[(*Runner)->GetOtherAtom((*iter)->GetTrueFather())->getNr()]; // local copy of current bond partner of walker
81 if (OtherWalker != NULL) {
82 if (OtherWalker->getNr() > (*iter)->getNr())
83 AddBond((*iter), OtherWalker, (*Runner)->BondDegree);
84 } else {
85 LOG(1, "OtherWalker = ListOfLocalAtoms[" << (*Runner)->GetOtherAtom((*iter)->GetTrueFather())->getNr() << "] is NULL!");
86 status = false;
87 }
88 }
89 }
90 }
91
92 if ((FreeList) && (ListOfLocalAtoms != NULL)) {
93 // free the index lookup list
94 delete[](ListOfLocalAtoms);
95 }
96 LOG(1, "End of FillBondStructureFromReference.");
97 return status;
98};
99
100/** Checks for presence of bonds within atom list.
101 * TODO: more sophisticated check for bond structure (e.g. connected subgraph, ...)
102 * \return true - bonds present, false - no bonds
103 */
104bool molecule::hasBondStructure() const
105{
106 for(molecule::const_iterator AtomRunner = begin(); AtomRunner != end(); ++AtomRunner) {
107 //LOG(0, "molecule::hasBondStructure() - checking bond list of atom " << (*AtomRunner)->getId() << ".");
108 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
109 if (!ListOfBonds.empty())
110 return true;
111 }
112 return false;
113}
114
115/** Prints a list of all bonds to \a *out.
116 */
117void molecule::OutputBondsList() const
118{
119 if (DoLog(1)) {
120 std::stringstream output;
121 output << std::endl << "From contents of bond chain list:";
122 for(molecule::const_iterator AtomRunner = molecule::begin(); AtomRunner != molecule::end(); ++AtomRunner) {
123 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
124 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
125 BondRunner != ListOfBonds.end();
126 ++BondRunner)
127 if ((*BondRunner)->leftatom == *AtomRunner) {
128 output << *(*BondRunner) << "\t";
129 }
130 }
131 LOG(1, output.str());
132 }
133}
134
135
136/** Storing the bond structure of a molecule to file.
137 * Simply stores Atom::Nr and then the Atom::Nr of all bond partners per line.
138 * \param &filename name of file
139 * \param path path to file, defaults to empty
140 * \return true - file written successfully, false - writing failed
141 */
142bool molecule::StoreAdjacencyToFile(std::string filename, std::string path)
143{
144 ofstream AdjacencyFile;
145 string line;
146 bool status = true;
147
148 if (path != "")
149 line = path + "/" + filename;
150 else
151 line = filename;
152 AdjacencyFile.open(line.c_str(), ios::out);
153 LOG(1, "Saving adjacency list ... ");
154 if (AdjacencyFile.good()) {
155 AdjacencyFile << "m\tn" << endl;
156 for_each(atoms.begin(),atoms.end(),bind2nd(mem_fun(&atom::OutputAdjacency),&AdjacencyFile));
157 AdjacencyFile.close();
158 LOG(1, "\t... done.");
159 } else {
160 LOG(1, "\t... failed to open file " << line << ".");
161 status = false;
162 }
163
164 return status;
165}
166;
167
168/** Storing the bond structure of a molecule to file.
169 * Simply stores Atom::Nr and then the Atom::Nr of all bond partners, one per line.
170 * \param &filename name of file
171 * \param path path to file, defaults to empty
172 * \return true - file written successfully, false - writing failed
173 */
174bool molecule::StoreBondsToFile(std::string filename, std::string path)
175{
176 ofstream BondFile;
177 string line;
178 bool status = true;
179
180 if (path != "")
181 line = path + "/" + filename;
182 else
183 line = filename;
184 BondFile.open(line.c_str(), ios::out);
185 LOG(1, "Saving adjacency list ... ");
186 if (BondFile.good()) {
187 BondFile << "m\tn" << endl;
188 for_each(atoms.begin(),atoms.end(),bind2nd(mem_fun(&atom::OutputBonds),&BondFile));
189 BondFile.close();
190 LOG(1, "\t... done.");
191 } else {
192 LOG(1, "\t... failed to open file " << line << ".");
193 status = false;
194 }
195
196 return status;
197}
198;
199
200/** Adds a bond as a copy to a given one
201 * \param *left leftatom of new bond
202 * \param *right rightatom of new bond
203 * \param *CopyBond rest of fields in bond are copied from this
204 * \return pointer to new bond
205 */
206bond * molecule::CopyBond(atom *left, atom *right, bond *CopyBond)
207{
208 bond *Binder = AddBond(left, right, CopyBond->BondDegree);
209 Binder->Cyclic = CopyBond->Cyclic;
210 Binder->Type = CopyBond->Type;
211 return Binder;
212}
213;
214
215/** Fills a lookup list of father's Atom::nr -> atom for each subgraph.
216 * \param **&ListOfLocalAtoms Lookup table for each subgraph and index of each atom in global molecule, may be NULL on start, then it is filled
217 * \param GlobalAtomCount number of atoms in the complete molecule
218 * \return true - success, false - failure (ListOfLocalAtoms != NULL)
219 */
220bool molecule::FillListOfLocalAtoms(atom **&ListOfLocalAtoms, const int GlobalAtomCount)
221{
222 bool status = true;
223
224 if (ListOfLocalAtoms == NULL) { // allocate and fill list of this fragment/subgraph
225 status = status && CreateFatherLookupTable(ListOfLocalAtoms, GlobalAtomCount);
226 } else
227 return false;
228
229 return status;
230}
231
232
233/** Creates a lookup table for true father's Atom::Nr -> atom ptr.
234 * \param *start begin of list (STL iterator, i.e. first item)
235 * \paran *end end of list (STL iterator, i.e. one past last item)
236 * \param **Lookuptable pointer to return allocated lookup table (should be NULL on start)
237 * \param count optional predetermined size for table (otherwise we set the count to highest true father id)
238 * \return true - success, false - failure
239 */
240bool molecule::CreateFatherLookupTable(atom **&LookupTable, int count)
241{
242 bool status = true;
243 int AtomNo;
244
245 if (LookupTable != NULL) {
246 ELOG(1, "Pointer for Lookup table is not NULL! Aborting ...");
247 return false;
248 }
249
250 // count them
251 if (count == 0) {
252 for (molecule::iterator iter = begin(); iter != end(); ++iter) { // create a lookup table (Atom::Nr -> atom) used as a marker table lateron
253 count = (count < (*iter)->GetTrueFather()->getNr()) ? (*iter)->GetTrueFather()->getNr() : count;
254 }
255 }
256 if (count <= 0) {
257 ELOG(1, "Count of lookup list is 0 or less.");
258 return false;
259 }
260
261 // allocate and fill
262 LookupTable = new atom *[count];
263 if (LookupTable == NULL) {
264 ELOG(0, "LookupTable memory allocation failed!");
265 performCriticalExit();
266 status = false;
267 } else {
268 for (int i=0;i<count;i++)
269 LookupTable[i] = NULL;
270 for (molecule::iterator iter = begin(); iter != end(); ++iter) {
271 AtomNo = (*iter)->GetTrueFather()->getNr();
272 if ((AtomNo >= 0) && (AtomNo < count)) {
273 //*out << "Setting LookupTable[" << AtomNo << "] to " << *(*iter) << endl;
274 LookupTable[AtomNo] = (*iter);
275 } else {
276 ELOG(1, "Walker " << *(*iter) << " exceeded range of nuclear ids [0, " << count << ").");
277 status = false;
278 break;
279 }
280 }
281 }
282
283 return status;
284};
285
286
287
288/** Corrects the nuclei position if the fragment was created over the cell borders.
289 * Scans all bonds, checks the distance, if greater than typical, we have a candidate for the correction.
290 * We remove the bond whereafter the graph probably separates. Then, we translate the one component periodically
291 * and re-add the bond. Looping on the distance check.
292 * \param *out ofstream for debugging messages
293 */
294bool molecule::ScanForPeriodicCorrection()
295{
296 bond *Binder = NULL;
297 //bond *OtherBinder = NULL;
298 atom *Walker = NULL;
299 atom *OtherWalker = NULL;
300 RealSpaceMatrix matrix = World::getInstance().getDomain().getM();
301 enum GraphEdge::Shading *ColorList = NULL;
302 double tmp;
303 //bool LastBond = true; // only needed to due list construct
304 Vector Translationvector;
305 //std::deque<atom *> *CompStack = NULL;
306 std::deque<atom *> *AtomStack = new std::deque<atom *>; // (getAtomCount());
307 bool flag = true;
308 BondGraph *BG = World::getInstance().getBondGraph();
309
310 LOG(2, "Begin of ScanForPeriodicCorrection.");
311
312 ColorList = new enum GraphEdge::Shading[getAtomCount()];
313 for (int i=0;i<getAtomCount();i++)
314 ColorList[i] = (enum GraphEdge::Shading)0;
315 if (flag) {
316 // remove bonds that are beyond bonddistance
317 Translationvector.Zero();
318 // scan all bonds
319 flag = false;
320 for(molecule::iterator AtomRunner = begin(); (!flag) && (AtomRunner != end()); ++AtomRunner) {
321 const BondList& ListOfBonds = (*AtomRunner)->getListOfBonds();
322 for(BondList::const_iterator BondRunner = ListOfBonds.begin();
323 (!flag) && (BondRunner != ListOfBonds.end());
324 ++BondRunner) {
325 Binder = (*BondRunner);
326 for (int i=NDIM;i--;) {
327 tmp = fabs(Binder->leftatom->at(i) - Binder->rightatom->at(i));
328 //LOG(3, "Checking " << i << "th distance of " << *Binder->leftatom << " to " << *Binder->rightatom << ": " << tmp << ".");
329 const range<double> MinMaxDistance(
330 BG->getMinMaxDistance(Binder->leftatom, Binder->rightatom));
331 if (!MinMaxDistance.isInRange(tmp)) {
332 LOG(2, "Correcting at bond " << *Binder << ".");
333 flag = true;
334 break;
335 }
336 }
337 }
338 }
339 //if (flag) {
340 if (0) {
341 // create translation vector from their periodically modified distance
342 for (int i=NDIM;i--;) {
343 tmp = Binder->leftatom->at(i) - Binder->rightatom->at(i);
344 const range<double> MinMaxDistance(
345 BG->getMinMaxDistance(Binder->leftatom, Binder->rightatom));
346 if (fabs(tmp) > MinMaxDistance.last) // check against Min is not useful for components
347 Translationvector[i] = (tmp < 0) ? +1. : -1.;
348 }
349 Translationvector *= matrix;
350 LOG(3, "INFO: Translation vector is " << Translationvector << ".");
351 // apply to all atoms of first component via BFS
352 for (int i=getAtomCount();i--;)
353 ColorList[i] = GraphEdge::white;
354 AtomStack->push_front(Binder->leftatom);
355 while (!AtomStack->empty()) {
356 Walker = AtomStack->front();
357 AtomStack->pop_front();
358 //LOG(3, "INFO: Current Walker is: " << *Walker << ".");
359 ColorList[Walker->getNr()] = GraphEdge::black; // mark as explored
360 *Walker += Translationvector; // translate
361 const BondList& ListOfBonds = Walker->getListOfBonds();
362 for (BondList::const_iterator Runner = ListOfBonds.begin();
363 Runner != ListOfBonds.end();
364 ++Runner) {
365 if ((*Runner) != Binder) {
366 OtherWalker = (*Runner)->GetOtherAtom(Walker);
367 if (ColorList[OtherWalker->getNr()] == GraphEdge::white) {
368 AtomStack->push_front(OtherWalker); // push if yet unexplored
369 }
370 }
371 }
372 }
373// // re-add bond
374// if (OtherBinder == NULL) { // is the only bond?
375// //Do nothing
376// } else {
377// if (!LastBond) {
378// link(Binder, OtherBinder); // no more implemented bond::previous ...
379// } else {
380// link(OtherBinder, Binder); // no more implemented bond::previous ...
381// }
382// }
383 } else {
384 LOG(3, "No corrections for this fragment.");
385 }
386 //delete(CompStack);
387 }
388 // free allocated space from ReturnFullMatrixforSymmetric()
389 delete(AtomStack);
390 delete[](ColorList);
391 LOG(2, "End of ScanForPeriodicCorrection.");
392
393 return flag;
394};
Note: See TracBrowser for help on using the repository browser.