source: src/Fragmentation/Fragmentation.cpp@ 0fad93

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

Renamed CheckAgainstAdjacencyFile -> AdjacencyList.

  • Property mode set to 100644
File size: 23.4 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/helpers.hpp"
52#include "Fragmentation/KeySet.hpp"
53#include "Fragmentation/PowerSetGenerator.hpp"
54#include "Fragmentation/UniqueFragments.hpp"
55#include "Graph/BondGraph.hpp"
56#include "Graph/AdjacencyList.hpp"
57#include "Graph/ListOfLocalAtoms.hpp"
58#include "molecule.hpp"
59#include "World.hpp"
60
61
62/** Constructor of class Fragmentation.
63 *
64 * \param _mol molecule for internal use (looking up atoms)
65 * \param _FileChecker instance contains adjacency parsed from elsewhere
66 * \param _saturation whether to treat hydrogen special and saturate dangling bonds or not
67 */
68Fragmentation::Fragmentation(molecule *_mol, AdjacencyList &_FileChecker, const enum HydrogenSaturation _saturation) :
69 mol(_mol),
70 saturation(_saturation),
71 FileChecker(_FileChecker)
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 atomids atomic ids (local to Fragmentation::mol) to fragment, used in AtomMask
94 * \param Order up to how many neighbouring bonds a fragment contains in BondOrderScheme::BottumUp scheme
95 * \param prefix prefix string for every fragment file name (may include path)
96 * \param &DFS contains bond structure analysis data
97 * \return 1 - continue, 2 - stop (no fragmentation occured)
98 */
99int Fragmentation::FragmentMolecule(const std::vector<atomId_t> &atomids, int Order, std::string prefix, DepthFirstSearchAnalysis &DFS)
100{
101 std::fstream File;
102 bool FragmentationToDo = true;
103 bool CheckOrder = false;
104 int TotalNumberOfKeySets = 0;
105
106 LOG(0, std::endl);
107 switch (saturation) {
108 case DoSaturate:
109 LOG(0, "I will treat hydrogen special and saturate dangling bonds with it.");
110 break;
111 case DontSaturate:
112 LOG(0, "Hydrogen is treated just like the rest of the lot.");
113 break;
114 default:
115 ASSERT(0, "Fragmentation::FragmentMolecule() - there is a saturation setting which I have no idea about.");
116 break;
117 }
118
119 // ++++++++++++++++++++++++++++ INITIAL STUFF: Bond structure analysis, file parsing, ... ++++++++++++++++++++++++++++++++++++++++++
120
121 // ===== 1. Check whether bond structure is same as stored in files ====
122
123 // === compare it with adjacency file ===
124 {
125 const std::vector<atomId_t> globalids = getGlobalIdsFromLocalIds(*mol, atomids);
126 FragmentationToDo = FragmentationToDo && FileChecker.CheckAgainstSubset(globalids);
127 }
128
129 // ===== 2. create AtomMask that takes Saturation condition into account
130 AtomMask_t AtomMask(atomids);
131 for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
132 // remove in hydrogen and we do saturate
133 if ((saturation == DoSaturate) && ((*iter)->getType()->getAtomicNumber() == 1)) // skip hydrogen
134 AtomMask.setFalse((*iter)->getNr());
135 }
136
137 // ===== 3. if structure still valid, parse key set file and others =====
138 Graph ParsedFragmentList;
139 FragmentationToDo = FragmentationToDo && ParsedFragmentList.ParseKeySetFile(prefix);
140
141 // ===== 4. check globally whether there's something to do actually (first adaptivity check)
142 FragmentationToDo = FragmentationToDo && ParseOrderAtSiteFromFile(atomids, prefix);
143
144 // =================================== Begin of FRAGMENTATION ===============================
145 // ===== 6a. assign each keyset to its respective subgraph =====
146 ListOfLocalAtoms_t ListOfLocalAtoms;
147 Graph FragmentList;
148 AssignKeySetsToFragment(ParsedFragmentList, ListOfLocalAtoms, FragmentList, true);
149
150 // ===== 6b. prepare and go into the adaptive (Order<0), single-step (Order==0) or incremental (Order>0) cycle
151 KeyStack RootStack;
152 FragmentationToDo = false; // if CheckOrderAtSite just ones recommends fragmentation, we will save fragments afterwards
153 bool LoopDoneAlready = false;
154 while ((CheckOrder = CheckOrderAtSite(AtomMask, ParsedFragmentList, Order, prefix, LoopDoneAlready))) {
155 FragmentationToDo = FragmentationToDo || CheckOrder;
156 LoopDoneAlready = true; // last plus one entry is used as marker that we have been through this loop once already in CheckOrderAtSite()
157 // ===== 6b. fill RootStack for each subgraph (second adaptivity check) =====
158 FillRootStackForSubgraphs(RootStack, AtomMask);
159
160 // call BOSSANOVA method
161 FragmentBOSSANOVA(mol, FragmentList, RootStack);
162 }
163 LOG(2, "CheckOrder is " << CheckOrder << ".");
164
165 // ==================================== End of FRAGMENTATION ============================================
166
167 // ===== 8a. translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
168 TranslateIndicesToGlobalIDs(FragmentList, TotalNumberOfKeySets, TotalGraph);
169
170 LOG(1, "STATUS: We have created " << TotalGraph.size() << " fragments.");
171
172 {
173 // store Adjacency file
174 std::string filename = prefix + ADJACENCYFILE;
175 mol->StoreAdjacencyToFile(filename);
176 }
177
178 // store adaptive orders into file
179 StoreOrderAtSiteFile(prefix);
180
181 LOG(0, "End of bond fragmentation.");
182 return ((int)(!FragmentationToDo)+1); // 1 - continue, 2 - stop (no fragmentation occured)
183};
184
185
186/** Performs BOSSANOVA decomposition at selected sites, increasing the cutoff by one at these sites.
187 * -# constructs a complete keyset of the molecule
188 * -# In a loop over all possible roots from the given rootstack
189 * -# increases order of root site
190 * -# calls PowerSetGenerator with this order, the complete keyset and the rootkeynr
191 * -# for all consecutive lower levels PowerSetGenerator is called with the suborder, the higher order keyset
192as the restricted one and each site in the set as the root)
193 * -# these are merged into a fragment list of keysets
194 * -# All fragment lists (for all orders, i.e. from all destination fields) are merged into one list for return
195 * Important only is that we create all fragments, it is not important if we create them more than once
196 * as these copies are filtered out via use of the hash table (KeySet).
197 * \param *out output stream for debugging
198 * \param Fragment&*List list of already present keystacks (adaptive scheme) or empty list
199 * \param &RootStack stack with all root candidates (unequal to each atom in complete molecule if adaptive scheme is applied)
200 * \return pointer to Graph list
201 */
202void Fragmentation::FragmentBOSSANOVA(molecule *mol, Graph &FragmentList, KeyStack &RootStack)
203{
204 Info FunctionInfo(__func__);
205 Graph ***FragmentLowerOrdersList = NULL;
206 int NumLevels = 0;
207 int NumMolecules = 0;
208 int TotalNumMolecules = 0;
209 int *NumMoleculesOfOrder = NULL;
210 int Order = 0;
211 int UpgradeCount = RootStack.size();
212 KeyStack FragmentRootStack;
213 int RootKeyNr = 0;
214 int RootNr = 0;
215 UniqueFragments FragmentSearch;
216
217 // FragmentLowerOrdersList is a 2D-array of pointer to MoleculeListClass objects, one dimension represents the ANOVA expansion of a single order (i.e. 5)
218 // with all needed lower orders that are subtracted, the other dimension is the BondOrder (i.e. from 1 to 5)
219 NumMoleculesOfOrder = new int[UpgradeCount];
220 FragmentLowerOrdersList = new Graph**[UpgradeCount];
221
222 for(int i=0;i<UpgradeCount;i++) {
223 NumMoleculesOfOrder[i] = 0;
224 FragmentLowerOrdersList[i] = NULL;
225 }
226
227 FragmentSearch.Init(mol->FindAtom(RootKeyNr));
228
229 // Construct the complete KeySet which we need for topmost level only (but for all Roots)
230 KeySet CompleteMolecule;
231 for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
232 CompleteMolecule.insert((*iter)->GetTrueFather()->getNr());
233 }
234
235 // 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
236 // 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),
237 // hence we have overall four 2th order levels for splitting. This also allows for putting all into a single array (FragmentLowerOrdersList[])
238 // 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)
239 RootNr = 0; // counts through the roots in RootStack
240 while ((RootNr < UpgradeCount) && (!RootStack.empty())) {
241 RootKeyNr = RootStack.front();
242 RootStack.pop_front();
243 atom *Walker = mol->FindAtom(RootKeyNr);
244 // check cyclic lengths
245 //if ((MinimumRingSize[Walker->GetTrueFather()->getNr()] != -1) && (Walker->GetTrueFather()->AdaptiveOrder+1 > MinimumRingSize[Walker->GetTrueFather()->getNr()])) {
246 // LOG(0, "Bond order " << Walker->GetTrueFather()->AdaptiveOrder << " of Root " << *Walker << " greater than or equal to Minimum Ring size of " << MinimumRingSize << " found is not allowed.");
247 //} else
248 {
249 // increase adaptive order by one
250 Walker->GetTrueFather()->AdaptiveOrder++;
251 Order = Walker->AdaptiveOrder = Walker->GetTrueFather()->AdaptiveOrder;
252
253 // initialise Order-dependent entries of UniqueFragments structure
254 class PowerSetGenerator PSG(&FragmentSearch, Walker->AdaptiveOrder);
255
256 // allocate memory for all lower level orders in this 1D-array of ptrs
257 NumLevels = 1 << (Order-1); // (int)pow(2,Order);
258 FragmentLowerOrdersList[RootNr] = new Graph*[NumLevels];
259 for (int i=0;i<NumLevels;i++)
260 FragmentLowerOrdersList[RootNr][i] = NULL;
261
262 // create top order where nothing is reduced
263 LOG(0, "==============================================================================================================");
264 LOG(0, "Creating KeySets of Bond Order " << Order << " for " << *Walker << ", " << (RootStack.size()-RootNr) << " Roots remaining."); // , NumLevels is " << NumLevels << "
265
266 // Create list of Graphs of current Bond Order (i.e. F_{ij})
267 FragmentLowerOrdersList[RootNr][0] = new Graph;
268 FragmentSearch.PrepareForPowersetGeneration(1., FragmentLowerOrdersList[RootNr][0], Walker);
269 NumMoleculesOfOrder[RootNr] = PSG(CompleteMolecule, saturation);
270
271 // output resulting number
272 LOG(1, "Number of resulting KeySets is: " << NumMoleculesOfOrder[RootNr] << ".");
273 if (NumMoleculesOfOrder[RootNr] != 0) {
274 NumMolecules = 0;
275 } else {
276 Walker->GetTrueFather()->MaxOrder = true;
277 }
278 // now, we have completely filled each cell of FragmentLowerOrdersList[] for the current Walker->AdaptiveOrder
279 //NumMoleculesOfOrder[Walker->AdaptiveOrder-1] = NumMolecules;
280 TotalNumMolecules += NumMoleculesOfOrder[RootNr];
281// LOG(1, "Number of resulting molecules for Order " << (int)Walker->GetTrueFather()->AdaptiveOrder << " is: " << NumMoleculesOfOrder[RootNr] << ".");
282 RootStack.push_back(RootKeyNr); // put back on stack
283 RootNr++;
284 }
285 }
286 LOG(0, "==============================================================================================================");
287 LOG(1, "Total number of resulting molecules is: " << TotalNumMolecules << ".");
288 LOG(0, "==============================================================================================================");
289
290 // cleanup FragmentSearch structure
291 FragmentSearch.Cleanup();
292
293 // now, FragmentLowerOrdersList is complete, it looks - for BondOrder 5 - as this (number is the ANOVA Order of the terms therein)
294 // 5433222211111111
295 // 43221111
296 // 3211
297 // 21
298 // 1
299
300 // Subsequently, we combine all into a single list (FragmentList)
301 CombineAllOrderListIntoOne(FragmentList, FragmentLowerOrdersList, RootStack, mol);
302 FreeAllOrdersList(FragmentLowerOrdersList, RootStack, mol);
303 delete[](NumMoleculesOfOrder);
304};
305
306/** Estimates by educated guessing (using upper limit) the expected number of fragments.
307 * The upper limit is
308 * \f[
309 * n = N \cdot C^k
310 * \f]
311 * where \f$C=2^c\f$ and c is the maximum bond degree over N number of atoms.
312 * \param *out output stream for debugging
313 * \param order bond order k
314 * \return number n of fragments
315 */
316int Fragmentation::GuesstimateFragmentCount(int order)
317{
318 size_t c = 0;
319 int FragmentCount;
320 // get maximum bond degree
321 for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
322 const BondList& ListOfBonds = (*iter)->getListOfBonds();
323 c = (ListOfBonds.size() > c) ? ListOfBonds.size() : c;
324 }
325 FragmentCount = (saturation == DoSaturate ? mol->getNoNonHydrogen() : mol->getAtomCount()) *(1 << (c*order));
326 LOG(1, "Upper limit for this subgraph is " << FragmentCount << " for "
327 << mol->getNoNonHydrogen() << " non-H atoms with maximum bond degree of " << c << ".");
328 return FragmentCount;
329};
330
331
332/** Checks whether the OrderAtSite is still below \a Order at some site.
333 * \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
334 * \param *GlobalKeySetList list of keysets with global ids (valid in "this" molecule) needed for adaptive increase
335 * \param Order desired Order if positive, desired exponent in threshold criteria if negative (0 is single-step)
336 * \param path path to ENERGYPERFRAGMENT file (may be NULL if Order is non-negative)
337 * \param LoopDoneAlready indicate whether we have done a fragmentation loop already
338 * \return true - needs further fragmentation, false - does not need fragmentation
339 */
340bool Fragmentation::CheckOrderAtSite(AtomMask_t &AtomMask, const Graph &GlobalKeySetList, int Order, std::string path, bool LoopDoneAlready)
341{
342 bool status = false;
343
344 if (Order < 0) { // adaptive increase of BondOrder per site
345 if (LoopDoneAlready) // break after one step
346 return false;
347
348 // transmorph graph keyset list into indexed KeySetList
349 AdaptivityMap * IndexKeySetList = GlobalKeySetList.GraphToAdaptivityMap();
350
351 // parse the EnergyPerFragment file
352 IndexKeySetList->ScanAdaptiveFileIntoMap(path); // (Root No., (Value, Order)) !
353 // then map back onto (Value, (Root Nr., Order)) (i.e. sorted by value to pick the highest ones)
354 IndexKeySetList->ReMapAdaptiveCriteriaListToValue(mol);
355
356 // pick the ones still below threshold and mark as to be adaptively updated
357 if (IndexKeySetList->IsAdaptiveCriteriaListEmpty()) {
358 ELOG(2, "Unable to parse file, incrementing all.");
359 status = true;
360 } else {
361 // mark as false all sites that are below threshold already
362 status = IndexKeySetList->MarkUpdateCandidates(AtomMask, Order, mol);
363 }
364
365 delete[](IndexKeySetList);
366 } else { // global increase of Bond Order
367 for(molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
368 if (AtomMask.isTrue((*iter)->getNr())) { // skip masked out
369 // remove all that have reached desired order
370 if ((Order != 0) && ((*iter)->AdaptiveOrder >= Order)) // && ((*iter)->AdaptiveOrder < MinimumRingSize[(*iter)->getNr()]))
371 AtomMask.setFalse((*iter)->getNr());
372 else
373 status = true;
374 }
375 }
376 if ((!Order) && (!LoopDoneAlready)) // single stepping, just check
377 status = true;
378
379 if (!status) {
380 if (Order == 0)
381 LOG(1, "Single stepping done.");
382 else
383 LOG(1, "Order at every site is already equal or above desired order " << Order << ".");
384 }
385 }
386
387 PrintAtomMask(AtomMask, mol->getAtomCount()); // for debugging
388
389 return status;
390};
391
392/** Stores pairs (Atom::Nr, Atom::AdaptiveOrder) into file.
393 * Atoms not present in the file get "-1".
394 * \param &path path to file ORDERATSITEFILE
395 * \return true - file writable, false - not writable
396 */
397bool Fragmentation::StoreOrderAtSiteFile(std::string &path)
398{
399 string line;
400 ofstream file;
401
402 line = path + ORDERATSITEFILE;
403 file.open(line.c_str());
404 LOG(1, "Writing OrderAtSite " << ORDERATSITEFILE << " ... ");
405 if (file.good()) {
406 for_each(mol->begin(),mol->end(),bind2nd(mem_fun(&atom::OutputOrder), &file));
407 file.close();
408 LOG(1, "done.");
409 return true;
410 } else {
411 LOG(1, "failed to open file " << line << ".");
412 return false;
413 }
414};
415
416
417/** Parses pairs(Atom::Nr, Atom::AdaptiveOrder) from file and stores in molecule's Atom's.
418 * Atoms not present in the file get "0".
419 * \param atomids atoms to fragment, used in AtomMask
420 * \param &path path to file ORDERATSITEFILEe
421 * \return true - file found and scanned, false - file not found
422 * \sa ParseKeySetFile() and CheckAdjacencyFileAgainstMolecule() as this is meant to be used in conjunction with the two
423 */
424bool Fragmentation::ParseOrderAtSiteFromFile(const std::vector<atomId_t> &atomids, std::string &path)
425{
426 Info FunctionInfo(__func__);
427 typedef unsigned char order_t;
428 typedef std::map<atomId_t, order_t> OrderArray_t;
429 OrderArray_t OrderArray;
430 AtomMask_t MaxArray(atomids);
431 bool status;
432 int AtomNr, value;
433 string line;
434 ifstream file;
435
436 line = path + ORDERATSITEFILE;
437 file.open(line.c_str());
438 if (file.good()) {
439 while (!file.eof()) { // parse from file
440 AtomNr = -1;
441 file >> AtomNr;
442 if (AtomNr != -1) { // test whether we really parsed something (this is necessary, otherwise last atom is set twice and to 0 on second time)
443 file >> value;
444 OrderArray[AtomNr] = value;
445 file >> value;
446 MaxArray.setValue(AtomNr, (bool)value);
447 //LOG(2, "AtomNr " << AtomNr << " with order " << (int)OrderArray[AtomNr] << " and max order set to " << (int)MaxArray[AtomNr] << ".");
448 }
449 }
450 file.close();
451
452 // set atom values
453 for(molecule::iterator iter=mol->begin();iter!=mol->end();++iter){
454 (*iter)->AdaptiveOrder = OrderArray[(*iter)->getNr()];
455 (*iter)->MaxOrder = MaxArray.isTrue((*iter)->getNr());
456 }
457 //SetAtomValueToIndexedArray( OrderArray, &atom::getNr(), &atom::AdaptiveOrder );
458 //SetAtomValueToIndexedArray( MaxArray, &atom::getNr(), &atom::MaxOrder );
459
460 LOG(1, "\t ... done.");
461 status = true;
462 } else {
463 LOG(1, "\t ... failed to open file " << line << ".");
464 status = false;
465 }
466
467 return status;
468};
469
470/** Fills the root stack for sites to be used as root in fragmentation depending on order or adaptivity criteria
471 * Again, as in \sa FillBondStructureFromReference steps recursively through each Leaf in this chain list of molecule's.
472 * \param &RootStack stack to be filled
473 * \param AtomMask defines true/false per global Atom::Nr to mask in/out each nuclear site
474 * \return true - stack is non-empty, fragmentation necessary, false - stack is empty, no more sites to update
475 */
476void Fragmentation::FillRootStackForSubgraphs(KeyStack &RootStack, const AtomMask_t &AtomMask)
477{
478 for(molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
479 const atom * const Father = (*iter)->GetTrueFather();
480 if (AtomMask.isTrue(Father->getNr())) // apply mask
481 if ((saturation == DontSaturate) || ((*iter)->getType()->getAtomicNumber() != 1)) // skip hydrogen
482 RootStack.push_front((*iter)->getNr());
483 }
484}
485
486/** The indices per keyset are compared to the respective father's Atom::Nr in each subgraph and thus put into \a **&FragmentList.
487 * \param *KeySetList list with all keysets
488 * \param ListOfLocalAtoms Lookup table for each subgraph and index of each atom in global molecule, may be NULL on start, then it is filled
489 * \param **&FragmentList list to be allocated and returned
490 * \param FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
491 * \retuen true - success, false - failure
492 */
493bool Fragmentation::AssignKeySetsToFragment(Graph &KeySetList, ListOfLocalAtoms_t &ListOfLocalAtoms, Graph &FragmentList, bool FreeList)
494{
495 Info FunctionInfo(__func__);
496 bool status = true;
497 size_t KeySetCounter = 0;
498
499 // fill ListOfLocalAtoms if NULL was given
500 if (!mol->FillListOfLocalAtoms(ListOfLocalAtoms, mol->getAtomCount())) {
501 LOG(1, "Filling of ListOfLocalAtoms failed.");
502 return false;
503 }
504
505 if (KeySetList.size() != 0) { // if there are some scanned keysets at all
506 // assign scanned keysets
507 KeySet TempSet;
508 for (Graph::iterator runner = KeySetList.begin(); runner != KeySetList.end(); runner++) { // key sets contain global numbers!
509 if (ListOfLocalAtoms[mol->FindAtom(*((*runner).first.begin()))->getNr()] != NULL) {// as we may assume that that bond structure is unchanged, we only test the first key in each set
510 // translate keyset to local numbers
511 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
512 TempSet.insert(ListOfLocalAtoms[mol->FindAtom(*sprinter)->getNr()]->getNr());
513 // insert into FragmentList
514 FragmentList.insert(GraphPair(TempSet, pair<int, double> (KeySetCounter++, (*runner).second.second)));
515 }
516 TempSet.clear();
517 }
518 } else
519 LOG(1, "KeySetList is NULL or empty.");
520
521 if (FreeList) {
522 // free the index lookup list
523 ListOfLocalAtoms.clear();
524 }
525 return status;
526}
527
528/** Translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
529 * \param &FragmentList Graph with local numbers per fragment
530 * \param &TotalNumberOfKeySets global key set counter
531 * \param &TotalGraph Graph to be filled with global numbers
532 */
533void Fragmentation::TranslateIndicesToGlobalIDs(Graph &FragmentList, int &TotalNumberOfKeySets, Graph &TotalGraph)
534{
535 Info FunctionInfo(__func__);
536 for (Graph::iterator runner = FragmentList.begin(); runner != FragmentList.end(); runner++) {
537 KeySet TempSet;
538 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
539 TempSet.insert((mol->FindAtom(*sprinter))->GetTrueFather()->getId());
540 TotalGraph.insert(GraphPair(TempSet, pair<int, double> (TotalNumberOfKeySets++, (*runner).second.second)));
541 }
542}
543
Note: See TracBrowser for help on using the repository browser.