source: src/molecule_graph.cpp@ 6d551c

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 6d551c was 6d551c, checked in by Frederik Heber <heber@…>, 13 years ago

ListOfLocalAtoms is now a map, inherited into a distinct class.

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