source: src/Fragmentation/Fragmentation.cpp@ e554d0

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

Removed SortIndex as (unused) parameter in OutputConfigForListOfFragments().

  • Property mode set to 100644
File size: 30.8 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
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/>.
21 */
22
23/*
24 * Fragmentation.cpp
25 *
26 * Created on: Oct 18, 2011
27 * Author: heber
28 */
29
30#ifdef HAVE_CONFIG_H
31#include <config.h>
32#endif
33
34#include "CodePatterns/MemDebug.hpp"
35
36#include "Fragmentation.hpp"
37
38#include "CodePatterns/Assert.hpp"
39#include "CodePatterns/Info.hpp"
40#include "CodePatterns/Log.hpp"
41
42#include "Atom/atom.hpp"
43#include "Bond/bond.hpp"
44#include "Descriptors/MoleculeDescriptor.hpp"
45#include "Element/element.hpp"
46#include "Element/periodentafel.hpp"
47#include "Fragmentation/AdaptivityMap.hpp"
48#include "Fragmentation/AtomMask.hpp"
49#include "Fragmentation/fragmentation_helpers.hpp"
50#include "Fragmentation/Graph.hpp"
51#include "Fragmentation/KeySet.hpp"
52#include "Fragmentation/PowerSetGenerator.hpp"
53#include "Fragmentation/UniqueFragments.hpp"
54#include "Graph/BondGraph.hpp"
55#include "Graph/CheckAgainstAdjacencyFile.hpp"
56#include "Graph/ListOfLocalAtoms.hpp"
57#include "molecule.hpp"
58#include "MoleculeLeafClass.hpp"
59#include "MoleculeListClass.hpp"
60#include "Parser/FormatParserStorage.hpp"
61#include "World.hpp"
62
63
64/** Constructor of class Fragmentation.
65 *
66 * \param _mol molecule for internal use (looking up atoms)
67 * \param _saturation whether to treat hydrogen special and saturate dangling bonds or not
68 */
69Fragmentation::Fragmentation(molecule *_mol, const enum HydrogenSaturation _saturation) :
70 mol(_mol),
71 saturation(_saturation)
72{}
73
74/** Destructor of class Fragmentation.
75 *
76 */
77Fragmentation::~Fragmentation()
78{}
79
80
81/** Performs a many-body bond order analysis for a given bond order.
82 * -# parses adjacency, keysets and orderatsite files
83 * -# RootStack is created for every subgraph (here, later we implement the "update 10 sites with highest energ
84y contribution", and that's why this consciously not done in the following loop)
85 * -# in a loop over all subgraphs
86 * -# calls FragmentBOSSANOVA with this RootStack and within the subgraph molecule structure
87 * -# creates molecule (fragment)s from the returned keysets (StoreFragmentFromKeySet)
88 * -# combines the generated molecule lists from all subgraphs
89 * -# saves to disk: fragment configs, adjacency, orderatsite, keyset files
90 * Note that as we split "this" molecule up into a list of subgraphs, i.e. a MoleculeListClass, we have two sets
91 * of vertex indices: Global always means the index in "this" molecule, whereas local refers to the molecule or
92 * subgraph in the MoleculeListClass.
93 * \param Order up to how many neighbouring bonds a fragment contains in BondOrderScheme::BottumUp scheme
94 * \param prefix prefix string for every fragment file name (may include path)
95 * \param &DFS contains bond structure analysis data
96 * \return 1 - continue, 2 - stop (no fragmentation occured)
97 */
98int Fragmentation::FragmentMolecule(int Order, std::string prefix, DepthFirstSearchAnalysis &DFS)
99{
100 MoleculeListClass *BondFragments = NULL;
101 int FragmentCounter;
102 MoleculeLeafClass *MolecularWalker = NULL;
103 MoleculeLeafClass *Subgraphs = NULL; // list of subgraphs from DFS analysis
104 fstream File;
105 bool FragmentationToDo = true;
106 bool CheckOrder = false;
107 Graph **FragmentList = NULL;
108 Graph TotalGraph; // graph with all keysets however local numbers
109 int TotalNumberOfKeySets = 0;
110 AtomMask_t AtomMask;
111
112 LOG(0, endl);
113 switch (saturation) {
114 case DoSaturate:
115 LOG(0, "I will treat hydrogen special and saturate dangling bonds with it.");
116 break;
117 case DontSaturate:
118 LOG(0, "Hydrogen is treated just like the rest of the lot.");
119 break;
120 default:
121 ASSERT(0, "Fragmentation::FragmentMolecule() - there is a saturation setting which I have no idea about.");
122 break;
123 }
124
125 // ++++++++++++++++++++++++++++ INITIAL STUFF: Bond structure analysis, file parsing, ... ++++++++++++++++++++++++++++++++++++++++++
126
127 // ===== 1. Check whether bond structure is same as stored in files ====
128
129 // === compare it with adjacency file ===
130 {
131 std::ifstream File;
132 std::string filename;
133 filename = prefix + ADJACENCYFILE;
134 File.open(filename.c_str(), ios::out);
135 LOG(1, "Looking at bond structure stored in adjacency file and comparing to present one ... ");
136
137 CheckAgainstAdjacencyFile FileChecker(World::getInstance().beginAtomSelection(), World::getInstance().endAtomSelection());
138 FragmentationToDo = FragmentationToDo && FileChecker(File);
139 }
140
141 // === reset bond degree and perform CorrectBondDegree ===
142 for(World::MoleculeIterator iter = World::getInstance().getMoleculeIter();
143 iter != World::getInstance().moleculeEnd();
144 ++iter) {
145 // correct bond degree
146 World::AtomComposite Set = (*iter)->getAtomSet();
147 World::getInstance().getBondGraph()->CorrectBondDegree(Set);
148 }
149
150 // ===== 2. perform a DFS analysis to gather info on cyclic structure and a list of disconnected subgraphs =====
151 // NOTE: We assume here that DFS has been performed and molecule structure is current.
152 Subgraphs = DFS.getMoleculeStructure();
153
154 // ===== 3. if structure still valid, parse key set file and others =====
155 Graph ParsedFragmentList;
156 FragmentationToDo = FragmentationToDo && ParsedFragmentList.ParseKeySetFile(prefix);
157
158 // ===== 4. check globally whether there's something to do actually (first adaptivity check)
159 FragmentationToDo = FragmentationToDo && ParseOrderAtSiteFromFile(prefix);
160
161 // =================================== Begin of FRAGMENTATION ===============================
162 // ===== 6a. assign each keyset to its respective subgraph =====
163 const int MolCount = World::getInstance().numMolecules();
164 FragmentCounter = 0;
165 {
166 ListOfLocalAtoms_t *ListOfLocalAtoms = new ListOfLocalAtoms_t[MolCount];
167 Subgraphs->next->AssignKeySetsToFragment(mol, &ParsedFragmentList, ListOfLocalAtoms, FragmentList, FragmentCounter, true);
168 delete[] ListOfLocalAtoms;
169 }
170
171 // ===== 6b. prepare and go into the adaptive (Order<0), single-step (Order==0) or incremental (Order>0) cycle
172 KeyStack *RootStack = new KeyStack[Subgraphs->next->Count()];
173 FragmentationToDo = false; // if CheckOrderAtSite just ones recommends fragmentation, we will save fragments afterwards
174 bool LoopDoneAlready = false;
175 while ((CheckOrder = CheckOrderAtSite(AtomMask, &ParsedFragmentList, Order, prefix, LoopDoneAlready))) {
176 FragmentationToDo = FragmentationToDo || CheckOrder;
177 LoopDoneAlready = true; // last plus one entry is used as marker that we have been through this loop once already in CheckOrderAtSite()
178 // ===== 6b. fill RootStack for each subgraph (second adaptivity check) =====
179 Subgraphs->next->FillRootStackForSubgraphs(RootStack, AtomMask, (FragmentCounter = 0), saturation);
180
181 // ===== 7. fill the bond fragment list =====
182 FragmentCounter = 0;
183 MolecularWalker = Subgraphs;
184 while (MolecularWalker->next != NULL) {
185 MolecularWalker = MolecularWalker->next;
186 LOG(1, "Fragmenting subgraph " << MolecularWalker << ".");
187 if (MolecularWalker->Leaf->hasBondStructure()) {
188 // call BOSSANOVA method
189 LOG(0, endl << " ========== BOND ENERGY of subgraph " << FragmentCounter << " ========================= ");
190 FragmentBOSSANOVA(MolecularWalker->Leaf, FragmentList[FragmentCounter], RootStack[FragmentCounter]);
191 } else {
192 ELOG(1, "Subgraph " << MolecularWalker << " has no atoms!");
193 }
194 FragmentCounter++; // next fragment list
195 }
196 }
197 LOG(2, "CheckOrder is " << CheckOrder << ".");
198 delete[](RootStack);
199
200 // ==================================== End of FRAGMENTATION ============================================
201
202 // ===== 8a. translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
203 Subgraphs->next->TranslateIndicesToGlobalIDs(FragmentList, (FragmentCounter = 0), TotalNumberOfKeySets, TotalGraph);
204
205 // free subgraph memory again
206 FragmentCounter = 0;
207 while (Subgraphs != NULL) {
208 // remove entry in fragment list
209 // remove subgraph fragment
210 MolecularWalker = Subgraphs->next;
211 Subgraphs->Leaf = NULL;
212 delete(Subgraphs);
213 Subgraphs = MolecularWalker;
214 }
215 // free fragment list
216 for (int i=0; i< FragmentCounter; ++i )
217 delete(FragmentList[i]);
218 delete[](FragmentList);
219
220 LOG(0, FragmentCounter << " subgraph fragments have been removed.");
221
222 // ===== 8b. gather keyset lists (graphs) from all subgraphs and transform into MoleculeListClass =====
223 //if (FragmentationToDo) { // we should always store the fragments again as coordination might have changed slightly without changing bond structure
224 // allocate memory for the pointer array and transmorph graphs into full molecular fragments
225 BondFragments = new MoleculeListClass(World::getPointer());
226 int k=0;
227 for(Graph::iterator runner = TotalGraph.begin(); runner != TotalGraph.end(); runner++) {
228 KeySet test = (*runner).first;
229 LOG(0, "Fragment No." << (*runner).second.first << " with TEFactor " << (*runner).second.second << ".");
230 BondFragments->insert(StoreFragmentFromKeySet(test, World::getInstance().getConfig()));
231 k++;
232 }
233 LOG(0, k << "/" << BondFragments->ListOfMolecules.size() << " fragments generated from the keysets.");
234
235 // ===== 9. Save fragments' configuration and keyset files et al to disk ===
236 if (BondFragments->ListOfMolecules.size() != 0) {
237 // create the SortIndex from BFS labels to order in the config file
238 std::map<atomId_t, int> SortIndex;
239 CreateMappingLabelsToConfigSequence(SortIndex);
240
241 LOG(1, "Writing " << BondFragments->ListOfMolecules.size() << " possible bond fragmentation configs");
242 bool write_status = true;
243 for (std::vector<std::string>::const_iterator iter = typelist.begin();
244 iter != typelist.end();
245 ++iter) {
246 LOG(2, "INFO: Writing bond fragments for type " << (*iter) << ".");
247 write_status = write_status
248 && BondFragments->OutputConfigForListOfFragments(
249 prefix,
250 FormatParserStorage::getInstance().getTypeFromName(*iter));
251 }
252 if (write_status)
253 LOG(1, "All configs written.");
254 else
255 LOG(1, "Some config writing failed.");
256
257 // store force index reference file
258 BondFragments->StoreForcesFile(prefix, SortIndex);
259
260 // store keysets file
261 TotalGraph.StoreKeySetFile(prefix);
262
263 {
264 // store Adjacency file
265 std::string filename = prefix + ADJACENCYFILE;
266 mol->StoreAdjacencyToFile(filename);
267 }
268
269 // store Hydrogen saturation correction file
270 BondFragments->AddHydrogenCorrection(prefix);
271
272 // store adaptive orders into file
273 StoreOrderAtSiteFile(prefix);
274
275 // restore orbital and Stop values
276 //CalculateOrbitals(*configuration);
277 } else {
278 LOG(1, "FragmentList is zero on return, splitting failed.");
279 }
280 // remove all create molecules again from the World including their atoms
281 for (MoleculeList::iterator iter = BondFragments->ListOfMolecules.begin();
282 !BondFragments->ListOfMolecules.empty();
283 iter = BondFragments->ListOfMolecules.begin()) {
284 // remove copied atoms and molecule again
285 molecule *mol = *iter;
286 mol->removeAtomsinMolecule();
287 World::getInstance().destroyMolecule(mol);
288 BondFragments->ListOfMolecules.erase(iter);
289 }
290 delete(BondFragments);
291 LOG(0, "End of bond fragmentation.");
292
293 return ((int)(!FragmentationToDo)+1); // 1 - continue, 2 - stop (no fragmentation occured)
294};
295
296
297/** Performs BOSSANOVA decomposition at selected sites, increasing the cutoff by one at these sites.
298 * -# constructs a complete keyset of the molecule
299 * -# In a loop over all possible roots from the given rootstack
300 * -# increases order of root site
301 * -# calls PowerSetGenerator with this order, the complete keyset and the rootkeynr
302 * -# for all consecutive lower levels PowerSetGenerator is called with the suborder, the higher order keyset
303as the restricted one and each site in the set as the root)
304 * -# these are merged into a fragment list of keysets
305 * -# All fragment lists (for all orders, i.e. from all destination fields) are merged into one list for return
306 * Important only is that we create all fragments, it is not important if we create them more than once
307 * as these copies are filtered out via use of the hash table (KeySet).
308 * \param *out output stream for debugging
309 * \param Fragment&*List list of already present keystacks (adaptive scheme) or empty list
310 * \param &RootStack stack with all root candidates (unequal to each atom in complete molecule if adaptive scheme is applied)
311 * \return pointer to Graph list
312 */
313void Fragmentation::FragmentBOSSANOVA(molecule *mol, Graph *&FragmentList, KeyStack &RootStack)
314{
315 Graph ***FragmentLowerOrdersList = NULL;
316 int NumLevels = 0;
317 int NumMolecules = 0;
318 int TotalNumMolecules = 0;
319 int *NumMoleculesOfOrder = NULL;
320 int Order = 0;
321 int UpgradeCount = RootStack.size();
322 KeyStack FragmentRootStack;
323 int RootKeyNr = 0;
324 int RootNr = 0;
325 UniqueFragments FragmentSearch;
326
327 LOG(0, "Begin of FragmentBOSSANOVA.");
328
329 // FragmentLowerOrdersList is a 2D-array of pointer to MoleculeListClass objects, one dimension represents the ANOVA expansion of a single order (i.e. 5)
330 // with all needed lower orders that are subtracted, the other dimension is the BondOrder (i.e. from 1 to 5)
331 NumMoleculesOfOrder = new int[UpgradeCount];
332 FragmentLowerOrdersList = new Graph**[UpgradeCount];
333
334 for(int i=0;i<UpgradeCount;i++) {
335 NumMoleculesOfOrder[i] = 0;
336 FragmentLowerOrdersList[i] = NULL;
337 }
338
339 FragmentSearch.Init(mol->FindAtom(RootKeyNr));
340
341 // Construct the complete KeySet which we need for topmost level only (but for all Roots)
342 KeySet CompleteMolecule;
343 for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
344 CompleteMolecule.insert((*iter)->GetTrueFather()->getNr());
345 }
346
347 // this can easily be seen: if Order is 5, then the number of levels for each lower order is the total sum of the number of levels above, as
348 // each has to be split up. E.g. for the second level we have one from 5th, one from 4th, two from 3th (which in turn is one from 5th, one from 4th),
349 // hence we have overall four 2th order levels for splitting. This also allows for putting all into a single array (FragmentLowerOrdersList[])
350 // with the order along the cells as this: 5433222211111111 for BondOrder 5 needing 16=pow(2,5-1) cells (only we use bit-shifting which is faster)
351 RootNr = 0; // counts through the roots in RootStack
352 while ((RootNr < UpgradeCount) && (!RootStack.empty())) {
353 RootKeyNr = RootStack.front();
354 RootStack.pop_front();
355 atom *Walker = mol->FindAtom(RootKeyNr);
356 // check cyclic lengths
357 //if ((MinimumRingSize[Walker->GetTrueFather()->getNr()] != -1) && (Walker->GetTrueFather()->AdaptiveOrder+1 > MinimumRingSize[Walker->GetTrueFather()->getNr()])) {
358 // LOG(0, "Bond order " << Walker->GetTrueFather()->AdaptiveOrder << " of Root " << *Walker << " greater than or equal to Minimum Ring size of " << MinimumRingSize << " found is not allowed.");
359 //} else
360 {
361 // increase adaptive order by one
362 Walker->GetTrueFather()->AdaptiveOrder++;
363 Order = Walker->AdaptiveOrder = Walker->GetTrueFather()->AdaptiveOrder;
364
365 // initialise Order-dependent entries of UniqueFragments structure
366 class PowerSetGenerator PSG(&FragmentSearch, Walker->AdaptiveOrder);
367
368 // allocate memory for all lower level orders in this 1D-array of ptrs
369 NumLevels = 1 << (Order-1); // (int)pow(2,Order);
370 FragmentLowerOrdersList[RootNr] = new Graph*[NumLevels];
371 for (int i=0;i<NumLevels;i++)
372 FragmentLowerOrdersList[RootNr][i] = NULL;
373
374 // create top order where nothing is reduced
375 LOG(0, "==============================================================================================================");
376 LOG(0, "Creating KeySets of Bond Order " << Order << " for " << *Walker << ", " << (RootStack.size()-RootNr) << " Roots remaining."); // , NumLevels is " << NumLevels << "
377
378 // Create list of Graphs of current Bond Order (i.e. F_{ij})
379 FragmentLowerOrdersList[RootNr][0] = new Graph;
380 FragmentSearch.PrepareForPowersetGeneration(1., FragmentLowerOrdersList[RootNr][0], Walker);
381 NumMoleculesOfOrder[RootNr] = PSG(CompleteMolecule, saturation);
382
383 // output resulting number
384 LOG(1, "Number of resulting KeySets is: " << NumMoleculesOfOrder[RootNr] << ".");
385 if (NumMoleculesOfOrder[RootNr] != 0) {
386 NumMolecules = 0;
387 } else {
388 Walker->GetTrueFather()->MaxOrder = true;
389 }
390 // now, we have completely filled each cell of FragmentLowerOrdersList[] for the current Walker->AdaptiveOrder
391 //NumMoleculesOfOrder[Walker->AdaptiveOrder-1] = NumMolecules;
392 TotalNumMolecules += NumMoleculesOfOrder[RootNr];
393// LOG(1, "Number of resulting molecules for Order " << (int)Walker->GetTrueFather()->AdaptiveOrder << " is: " << NumMoleculesOfOrder[RootNr] << ".");
394 RootStack.push_back(RootKeyNr); // put back on stack
395 RootNr++;
396 }
397 }
398 LOG(0, "==============================================================================================================");
399 LOG(1, "Total number of resulting molecules is: " << TotalNumMolecules << ".");
400 LOG(0, "==============================================================================================================");
401
402 // cleanup FragmentSearch structure
403 FragmentSearch.Cleanup();
404
405 // now, FragmentLowerOrdersList is complete, it looks - for BondOrder 5 - as this (number is the ANOVA Order of the terms therein)
406 // 5433222211111111
407 // 43221111
408 // 3211
409 // 21
410 // 1
411
412 // Subsequently, we combine all into a single list (FragmentList)
413 CombineAllOrderListIntoOne(FragmentList, FragmentLowerOrdersList, RootStack, mol);
414 FreeAllOrdersList(FragmentLowerOrdersList, RootStack, mol);
415 delete[](NumMoleculesOfOrder);
416
417 LOG(0, "End of FragmentBOSSANOVA.");
418};
419
420/** Stores a fragment from \a KeySet into \a molecule.
421 * First creates the minimal set of atoms from the KeySet, then creates the bond structure from the complete
422 * molecule and adds missing hydrogen where bonds were cut.
423 * \param *out output stream for debugging messages
424 * \param &Leaflet pointer to KeySet structure
425 * \param IsAngstroem whether we have Ansgtroem or bohrradius
426 * \return pointer to constructed molecule
427 */
428molecule * Fragmentation::StoreFragmentFromKeySet(KeySet &Leaflet, bool IsAngstroem)
429{
430 Info info(__func__);
431 ListOfLocalAtoms_t SonList;
432 molecule *Leaf = World::getInstance().createMolecule();
433
434 StoreFragmentFromKeySet_Init(mol, Leaf, Leaflet, SonList);
435 // create the bonds between all: Make it an induced subgraph and add hydrogen
436// LOG(2, "Creating bonds from father graph (i.e. induced subgraph creation).");
437 CreateInducedSubgraphOfFragment(mol, Leaf, SonList, IsAngstroem);
438
439 //Leaflet->Leaf->ScanForPeriodicCorrection(out);
440 return Leaf;
441};
442
443
444/** Estimates by educated guessing (using upper limit) the expected number of fragments.
445 * The upper limit is
446 * \f[
447 * n = N \cdot C^k
448 * \f]
449 * where \f$C=2^c\f$ and c is the maximum bond degree over N number of atoms.
450 * \param *out output stream for debugging
451 * \param order bond order k
452 * \return number n of fragments
453 */
454int Fragmentation::GuesstimateFragmentCount(int order)
455{
456 size_t c = 0;
457 int FragmentCount;
458 // get maximum bond degree
459 for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
460 const BondList& ListOfBonds = (*iter)->getListOfBonds();
461 c = (ListOfBonds.size() > c) ? ListOfBonds.size() : c;
462 }
463 FragmentCount = mol->getNoNonHydrogen()*(1 << (c*order));
464 LOG(1, "Upper limit for this subgraph is " << FragmentCount << " for "
465 << mol->getNoNonHydrogen() << " non-H atoms with maximum bond degree of " << c << ".");
466 return FragmentCount;
467};
468
469
470/** Checks whether the OrderAtSite is still below \a Order at some site.
471 * \param AtomMask defines true/false per global Atom::Nr to mask in/out each nuclear site, used to activate given number of site to increment order adaptively
472 * \param *GlobalKeySetList list of keysets with global ids (valid in "this" molecule) needed for adaptive increase
473 * \param Order desired Order if positive, desired exponent in threshold criteria if negative (0 is single-step)
474 * \param path path to ENERGYPERFRAGMENT file (may be NULL if Order is non-negative)
475 * \param LoopDoneAlready indicate whether we have done a fragmentation loop already
476 * \return true - needs further fragmentation, false - does not need fragmentation
477 */
478bool Fragmentation::CheckOrderAtSite(AtomMask_t &AtomMask, Graph *GlobalKeySetList, int Order, std::string path, bool LoopDoneAlready)
479{
480 bool status = false;
481
482 // initialize mask list
483 AtomMask.clear();
484
485 if (Order < 0) { // adaptive increase of BondOrder per site
486 if (LoopDoneAlready) // break after one step
487 return false;
488
489 // transmorph graph keyset list into indexed KeySetList
490 if (GlobalKeySetList == NULL) {
491 ELOG(1, "Given global key set list (graph) is NULL!");
492 return false;
493 }
494 AdaptivityMap * IndexKeySetList = GlobalKeySetList->GraphToAdaptivityMap();
495
496 // parse the EnergyPerFragment file
497 IndexKeySetList->ScanAdaptiveFileIntoMap(path); // (Root No., (Value, Order)) !
498 // then map back onto (Value, (Root Nr., Order)) (i.e. sorted by value to pick the highest ones)
499 IndexKeySetList->ReMapAdaptiveCriteriaListToValue(mol);
500
501 // pick the ones still below threshold and mark as to be adaptively updated
502 if (IndexKeySetList->IsAdaptiveCriteriaListEmpty()) {
503 ELOG(2, "Unable to parse file, incrementing all.");
504 for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
505 if ((saturation == DontSaturate) || ((*iter)->getType()->getAtomicNumber() != 1)) // skip hydrogen
506 {
507 AtomMask.setTrue((*iter)->getNr()); // include all (non-hydrogen) atoms
508 status = true;
509 }
510 }
511 } else {
512 IndexKeySetList->MarkUpdateCandidates(AtomMask, Order, mol);
513 }
514
515 delete[](IndexKeySetList);
516 } else { // global increase of Bond Order
517 for(molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
518 if ((saturation == DontSaturate) || ((*iter)->getType()->getAtomicNumber() != 1)) // skip hydrogen
519 {
520 AtomMask.setTrue((*iter)->getNr()); // include all (non-hydrogen) atoms
521 if ((Order != 0) && ((*iter)->AdaptiveOrder < Order)) // && ((*iter)->AdaptiveOrder < MinimumRingSize[(*iter)->getNr()]))
522 status = true;
523 }
524 }
525 if ((!Order) && (!LoopDoneAlready)) // single stepping, just check
526 status = true;
527
528 if (!status) {
529 if (Order == 0)
530 LOG(1, "Single stepping done.");
531 else
532 LOG(1, "Order at every site is already equal or above desired order " << Order << ".");
533 }
534 }
535
536 PrintAtomMask(AtomMask, mol->getAtomCount()); // for debugging
537
538 return status;
539};
540
541/** Stores pairs (Atom::Nr, Atom::AdaptiveOrder) into file.
542 * Atoms not present in the file get "-1".
543 * \param &path path to file ORDERATSITEFILE
544 * \return true - file writable, false - not writable
545 */
546bool Fragmentation::StoreOrderAtSiteFile(std::string &path)
547{
548 string line;
549 ofstream file;
550
551 line = path + ORDERATSITEFILE;
552 file.open(line.c_str());
553 LOG(1, "Writing OrderAtSite " << ORDERATSITEFILE << " ... ");
554 if (file.good()) {
555 for_each(mol->begin(),mol->end(),bind2nd(mem_fun(&atom::OutputOrder), &file));
556 file.close();
557 LOG(1, "done.");
558 return true;
559 } else {
560 LOG(1, "failed to open file " << line << ".");
561 return false;
562 }
563};
564
565
566/** Parses pairs(Atom::Nr, Atom::AdaptiveOrder) from file and stores in molecule's Atom's.
567 * Atoms not present in the file get "0".
568 * \param &path path to file ORDERATSITEFILEe
569 * \return true - file found and scanned, false - file not found
570 * \sa ParseKeySetFile() and CheckAdjacencyFileAgainstMolecule() as this is meant to be used in conjunction with the two
571 */
572bool Fragmentation::ParseOrderAtSiteFromFile(std::string &path)
573{
574 typedef unsigned char order_t;
575 typedef std::map<atomId_t, order_t> OrderArray_t;
576 OrderArray_t OrderArray;
577 AtomMask_t MaxArray;
578 bool status;
579 int AtomNr, value;
580 string line;
581 ifstream file;
582
583 LOG(1, "Begin of ParseOrderAtSiteFromFile");
584 line = path + ORDERATSITEFILE;
585 file.open(line.c_str());
586 if (file.good()) {
587 while (!file.eof()) { // parse from file
588 AtomNr = -1;
589 file >> AtomNr;
590 if (AtomNr != -1) { // test whether we really parsed something (this is necessary, otherwise last atom is set twice and to 0 on second time)
591 file >> value;
592 OrderArray[AtomNr] = value;
593 file >> value;
594 MaxArray.setValue(AtomNr, (bool)value);
595 //LOG(2, "AtomNr " << AtomNr << " with order " << (int)OrderArray[AtomNr] << " and max order set to " << (int)MaxArray[AtomNr] << ".");
596 }
597 }
598 file.close();
599
600 // set atom values
601 for(molecule::iterator iter=mol->begin();iter!=mol->end();++iter){
602 (*iter)->AdaptiveOrder = OrderArray[(*iter)->getNr()];
603 (*iter)->MaxOrder = MaxArray.isTrue((*iter)->getNr());
604 }
605 //SetAtomValueToIndexedArray( OrderArray, &atom::getNr(), &atom::AdaptiveOrder );
606 //SetAtomValueToIndexedArray( MaxArray, &atom::getNr(), &atom::MaxOrder );
607
608 LOG(1, "\t ... done.");
609 status = true;
610 } else {
611 LOG(1, "\t ... failed to open file " << line << ".");
612 status = false;
613 }
614
615 LOG(1, "End of ParseOrderAtSiteFromFile");
616 return status;
617};
618
619/** Create a SortIndex to map from atomic labels to the sequence in which the atoms are given in the config file.
620 * \param &SortIndex Mapping array of size molecule::AtomCount
621 * \return true - success, false - failure of SortIndex alloc
622 */
623bool Fragmentation::CreateMappingLabelsToConfigSequence(std::map<atomId_t, int> &SortIndex)
624{
625 if (!SortIndex.empty()) {
626 LOG(1, "SortIndex has " << SortIndex.size() << " entries and is not empty as expected.");
627 return false;
628 }
629
630 int AtomNo = 0;
631 for(molecule::const_iterator iter=mol->begin();iter!=mol->end();++iter){
632 const int id = (*iter)->getNr();
633#ifndef NDEBUG
634 std::pair<std::map<atomId_t, int>::const_iterator, bool> inserter =
635#endif
636 SortIndex.insert( std::make_pair(id, AtomNo++) );
637 ASSERT( inserter.second ,
638 "Fragmentation::CreateMappingLabelsToConfigSequence() - same SortIndex set twice.");
639 }
640
641 return true;
642};
643
644
645/** Initializes some value for putting fragment of \a *mol into \a *Leaf.
646 * \param *mol total molecule
647 * \param *Leaf fragment molecule
648 * \param &Leaflet pointer to KeySet structure
649 * \param SonList calloc'd list which atom of \a *Leaf is a son of which atom in \a *mol
650 * \return number of atoms in fragment
651 */
652int Fragmentation::StoreFragmentFromKeySet_Init(molecule *mol, molecule *Leaf, KeySet &Leaflet, ListOfLocalAtoms_t &SonList)
653{
654 atom *FatherOfRunner = NULL;
655
656 // first create the minimal set of atoms from the KeySet
657 int size = 0;
658 for(KeySet::iterator runner = Leaflet.begin(); runner != Leaflet.end(); runner++) {
659 FatherOfRunner = mol->FindAtom((*runner)); // find the id
660 SonList.insert( std::make_pair(FatherOfRunner->getNr(), Leaf->AddCopyAtom(FatherOfRunner) ) );
661 size++;
662 }
663 return size;
664};
665
666
667/** Creates an induced subgraph out of a fragmental key set, adding bonds and hydrogens (if treated specially).
668 * \param *out output stream for debugging messages
669 * \param *mol total molecule
670 * \param *Leaf fragment molecule
671 * \param IsAngstroem whether we have Ansgtroem or bohrradius
672 * \param SonList list which atom of \a *Leaf is a son of which atom in \a *mol
673 */
674void Fragmentation::CreateInducedSubgraphOfFragment(molecule *mol, molecule *Leaf, ListOfLocalAtoms_t &SonList, bool IsAngstroem)
675{
676 bool LonelyFlag = false;
677 atom *OtherFather = NULL;
678 atom *FatherOfRunner = NULL;
679
680 // we increment the iter just before skipping the hydrogen
681 // as we use AddBond, we cannot have a const_iterator here
682 for (molecule::iterator iter = Leaf->begin(); iter != Leaf->end();) {
683 LonelyFlag = true;
684 FatherOfRunner = (*iter)->father;
685 ASSERT(FatherOfRunner,"Atom without father found");
686 if (SonList.find(FatherOfRunner->getNr()) != SonList.end()) { // check if this, our father, is present in list
687 // create all bonds
688 const BondList& ListOfBonds = FatherOfRunner->getListOfBonds();
689 for (BondList::const_iterator BondRunner = ListOfBonds.begin();
690 BondRunner != ListOfBonds.end();
691 ++BondRunner) {
692 OtherFather = (*BondRunner)->GetOtherAtom(FatherOfRunner);
693 if (SonList.find(OtherFather->getNr()) != SonList.end()) {
694// LOG(2, "INFO: Father " << *FatherOfRunner << " of son " << *SonList[FatherOfRunner->getNr()]
695// << " is bound to " << *OtherFather << ", whose son is "
696// << *SonList[OtherFather->getNr()] << ".");
697 if (OtherFather->getNr() > FatherOfRunner->getNr()) { // add bond (Nr check is for adding only one of both variants: ab, ba)
698 std::stringstream output;
699// output << "ACCEPT: Adding Bond: "
700 output << Leaf->AddBond((*iter), SonList[OtherFather->getNr()], (*BondRunner)->BondDegree);
701// LOG(3, output.str());
702 //NumBonds[(*iter)->getNr()]++;
703 } else {
704// LOG(3, "REJECY: Not adding bond, labels in wrong order.");
705 }
706 LonelyFlag = false;
707 } else {
708// LOG(2, "INFO: Father " << *FatherOfRunner << " of son " << *SonList[FatherOfRunner->getNr()]
709// << " is bound to " << *OtherFather << ", who has no son in this fragment molecule.");
710 if (saturation == DoSaturate) {
711// LOG(3, "ACCEPT: Adding Hydrogen to " << (*iter)->Name << " and a bond in between.");
712 if (!Leaf->AddHydrogenReplacementAtom((*BondRunner), (*iter), FatherOfRunner, OtherFather, IsAngstroem))
713 exit(1);
714 }
715 //NumBonds[(*iter)->getNr()] += Binder->BondDegree;
716 }
717 }
718 } else {
719 ELOG(1, "Son " << (*iter)->getName() << " has father " << FatherOfRunner->getName() << " but its entry in SonList is " << SonList[FatherOfRunner->getNr()] << "!");
720 }
721 if ((LonelyFlag) && (Leaf->getAtomCount() > 1)) {
722 LOG(0, **iter << "has got bonds only to hydrogens!");
723 }
724 ++iter;
725 if (saturation == DoSaturate) {
726 while ((iter != Leaf->end()) && ((*iter)->getType()->getAtomicNumber() == 1)){ // skip added hydrogen
727 iter++;
728 }
729 }
730 }
731};
732
733/** Sets the desired output types of the fragment configurations.
734 *
735 * @param types vector of desired types.
736 */
737void Fragmentation::setOutputTypes(const std::vector<std::string> &types)
738{
739 typelist = types;
740}
Note: See TracBrowser for help on using the repository browser.