source: src/Fragmentation/Fragmentation.cpp@ 336da8

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_StructOpt_integration_tests Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator 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_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion GeometryObjects Gui_displays_atomic_force_velocity IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks RotateToPrincipalAxisSystem_UndoRedo StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps Ubuntu_1604_changes stable
Last change on this file since 336da8 was 61fc12, checked in by Frederik Heber <heber@…>, 8 years ago

FIX: FragmentBOSSANOVA got full molecule as restricted keyset.

  • although only selected atoms are used to construct the AtomMask, still the full molecule was used for bond partners from the (restricted) set of root nodes. This lead to globalsaturationpositions missing spots for those atoms outside the selected set.
  • Property mode set to 100644
File size: 25.9 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 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/*
25 * Fragmentation.cpp
26 *
27 * Created on: Oct 18, 2011
28 * Author: heber
29 */
30
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include <boost/bimap.hpp>
36
37#include "CodePatterns/MemDebug.hpp"
38
39#include "Fragmentation.hpp"
40
41#include "CodePatterns/Assert.hpp"
42#include "CodePatterns/Info.hpp"
43#include "CodePatterns/IteratorAdaptors.hpp"
44#include "CodePatterns/Log.hpp"
45
46#include "Atom/atom.hpp"
47#include "Bond/bond.hpp"
48#include "Descriptors/MoleculeDescriptor.hpp"
49#include "Element/element.hpp"
50#include "Element/periodentafel.hpp"
51#include "Fragmentation/AdaptivityMap.hpp"
52#include "Fragmentation/AtomMask.hpp"
53#include "Fragmentation/fragmentation_helpers.hpp"
54#include "Fragmentation/Graph.hpp"
55#include "Fragmentation/helpers.hpp"
56#include "Fragmentation/KeySet.hpp"
57#include "Fragmentation/PowerSetGenerator.hpp"
58#include "Fragmentation/UniqueFragments.hpp"
59#include "Graph/BondGraph.hpp"
60#include "Graph/AdjacencyList.hpp"
61#include "Graph/ListOfLocalAtoms.hpp"
62#include "molecule.hpp"
63#include "World.hpp"
64
65
66/** Constructor of class Fragmentation.
67 *
68 * \param _mol molecule which we currently fragment
69 * \param _FileChecker instance contains adjacency parsed from elsewhere
70 * \param _treatment whether to treat hydrogen special and saturate dangling bonds or not
71 */
72Fragmentation::Fragmentation(molecule *_mol, AdjacencyList &_FileChecker, const enum HydrogenTreatment _treatment) :
73 mol(_mol),
74 treatment(_treatment),
75 FileChecker(_FileChecker)
76{}
77
78/** Destructor of class Fragmentation.
79 *
80 */
81Fragmentation::~Fragmentation()
82{}
83
84
85/** Performs a many-body bond order analysis for a given bond order.
86 *
87 * \note during fragmentation we switch to so-called local ids, atomic ids
88 * that are valid only for the specific molecule (representing a connected
89 * subgraph of the molecular system).
90 *
91 * -# create the local id to global id mapping
92 * -# parse the adjacency file and require the above mapping for translation
93 * -# initialize a mask for the molecule's atoms, telling which atoms are
94 * treated and which atoms neglected during fragmentation
95 * -# parse and orderatsite file and check whether there's something to do. This
96 allows for iterative calls to fragmentation
97 * -# fragments from the last fragmentation stored to file are converted into
98 * keysets (sets of atomic indices that describe one fragment)
99 * -# in a loop as long as order at site is not correct yet
100 * -# prepare a stack containing the initial ids where the fragmentation or
101 * rather the graph algorithms start from
102 * -# call fragmentBOSSANOVA()
103 * -# afterwards in case we don't saturate we remove single-atom fragments
104 * -# translate the local ids of the keysets into global ids.
105 * -# updated order at site file is written
106 *
107 * note that all created fragments or rather their describing key sets are
108 * contained in the Graph Fragmentation::FragmentList.
109 *
110 * \param atomids atomic ids (local to Fragmentation::mol) to fragment, used in AtomMask
111 * \param Order up to how many neighbouring bonds a fragment contains in BondOrderScheme::BottumUp scheme
112 * \param prefix prefix string for every fragment file name (may include path)
113 * \param ParsedFragmentList all already created key sets
114 * \return 1 - continue, 2 - stop (no fragmentation occured)
115 */
116int Fragmentation::FragmentMolecule(
117 const std::vector<atomId_t> &atomids,
118 int Order,
119 const std::string &prefix,
120 const Graph &ParsedFragmentList,
121 const bool _ParseStateFile)
122{
123 std::fstream File;
124 bool CheckOrder = false;
125 int TotalNumberOfKeySets = 0;
126
127 LOG(0, std::endl);
128 switch (treatment) {
129 case ExcludeHydrogen:
130 LOG(1, "INFO: I will treat hydrogen special.");
131 break;
132 case IncludeHydrogen:
133 LOG(1, "INFO: Hydrogen is treated just like the rest of the lot.");
134 break;
135 default:
136 ASSERT(0, "Fragmentation::FragmentMolecule() - there is a HydrogenTreatment setting which I have no idea about.");
137 break;
138 }
139
140 // ++++++++++++++++++++++++++++ INITIAL STUFF: Bond structure analysis, file parsing, ... ++++++++++++++++++++++++++++++++++++++++++
141 bool FragmentationToDo = true;
142
143 // ===== 1. Check whether bond structure is same as stored in files ====
144
145 // create a lookup global <-> local id for atomic ids valid in World and in molecule
146 Global_local_bimap_t Global_local_bimap;
147 for (std::vector<local_t>::const_iterator iter = atomids.begin();
148 iter != atomids.end();
149 ++iter) {
150 const atom * _atom = mol->FindAtom(*iter);
151 ASSERT( _atom != NULL,
152 "Fragmentation::FragmentMolecule() - could not find atom "+toString(*iter)+".");
153 Global_local_bimap.insert(
154 idpair_t(
155 (global_t)(_atom->getId()), (local_t)(*iter)
156 )
157 );
158 }
159
160 // === compare it with adjacency file ===
161 {
162 const std::vector<atomId_t> globalids(
163 MapKeyConstIterator<Global_local_bimap_t::left_const_iterator>(Global_local_bimap.left.begin()),
164 MapKeyConstIterator<Global_local_bimap_t::left_const_iterator>(Global_local_bimap.left.end())
165 );
166 AdjacencyList WorldAdjacency(globalids);
167 FragmentationToDo = FragmentationToDo && (FileChecker > WorldAdjacency);
168 }
169
170 // ===== 2. create AtomMask that takes Saturation condition into account
171 AtomMask_t AtomMask(atomids);
172 for (molecule::const_iterator iter = const_cast<const molecule *>(mol)->begin();
173 iter != const_cast<const molecule *>(mol)->end();
174 ++iter) {
175 // remove in hydrogen and we do saturate
176 if ((treatment == ExcludeHydrogen) && ((*iter)->getType()->getAtomicNumber() == 1)) // skip hydrogen
177 AtomMask.setFalse((*iter)->getNr());
178 }
179
180 // ===== 4. check globally whether there's something to do actually (first adaptivity check)
181 if (_ParseStateFile)
182 FragmentationToDo = FragmentationToDo && ParseOrderAtSiteFromFile(atomids, prefix, Global_local_bimap);
183
184 // =================================== Begin of FRAGMENTATION ===============================
185 // ===== 6a. assign each keyset to its respective subgraph =====
186 ListOfLocalAtoms_t ListOfLocalAtoms;
187 Graph FragmentList;
188 AssignKeySetsToFragment(ParsedFragmentList, ListOfLocalAtoms, FragmentList, true);
189
190 // ===== 6b. prepare and go into the adaptive (Order<0), single-step (Order==0) or incremental (Order>0) cycle
191 KeyStack RootStack;
192 FragmentationToDo = false; // if CheckOrderAtSite just ones recommends fragmentation, we will save fragments afterwards
193 bool LoopDoneAlready = false;
194 while ((CheckOrder = CheckOrderAtSite(AtomMask, ParsedFragmentList, Order, prefix, LoopDoneAlready))) {
195 FragmentationToDo = FragmentationToDo || CheckOrder;
196 LoopDoneAlready = true; // last plus one entry is used as marker that we have been through this loop once already in CheckOrderAtSite()
197 // ===== 6b. fill RootStack for each subgraph (second adaptivity check) =====
198 FillRootStackForSubgraphs(RootStack, AtomMask);
199
200 // call BOSSANOVA method
201 FragmentBOSSANOVA(mol, FragmentList, RootStack);
202 }
203 LOG(3, "DEBUG: CheckOrder is " << CheckOrder << ".");
204
205 // ==================================== End of FRAGMENTATION ============================================
206
207 // if hydrogen is not treated special, we may have single hydrogens and other
208 // fragments which are note single-determinant. These need to be removed
209 if (treatment == IncludeHydrogen) {
210 // remove all single atom fragments from FragmentList
211 Graph::iterator iter = FragmentList.begin();
212 while ( iter != FragmentList.end()) {
213 if ((*iter).first.size() == 1) {
214 LOG(1, "INFO: Removing KeySet " << (*iter).first << " as is not single-determinant.");
215 Graph::iterator eraseiter = iter++;
216 FragmentList.erase(eraseiter);
217 } else
218 ++iter;
219 }
220 }
221
222 // ===== 8a. translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
223 TranslateIndicesToGlobalIDs(FragmentList, TotalNumberOfKeySets, TotalGraph);
224
225 LOG(1, "STATUS: We have created " << TotalGraph.size() << " fragments.");
226
227
228 // store adaptive orders into file
229 StoreOrderAtSiteFile(prefix);
230
231 return ((int)(!FragmentationToDo)+1); // 1 - continue, 2 - stop (no fragmentation occured)
232};
233
234
235/** Performs BOSSANOVA decomposition at selected sites, increasing the cutoff by one at these sites.
236 * -# constructs a complete keyset of the molecule
237 * -# In a loop over all possible roots from the given rootstack
238 * -# increases order of root site
239 * -# calls PowerSetGenerator with this order, the complete keyset and the rootkeynr
240 * -# for all consecutive lower levels PowerSetGenerator is called with the suborder, the higher order keyset
241as the restricted one and each site in the set as the root)
242 * -# these are merged into a fragment list of keysets
243 * -# All fragment lists (for all orders, i.e. from all destination fields) are merged into one list for return
244 * Important only is that we create all fragments, it is not important if we create them more than once
245 * as these copies are filtered out via use of the hash table (KeySet).
246 * \param *out output stream for debugging
247 * \param Fragment&*List list of already present keystacks (adaptive scheme) or empty list
248 * \param &RootStack stack with all root candidates (unequal to each atom in complete molecule if adaptive scheme is applied)
249 * \return pointer to Graph list
250 */
251void Fragmentation::FragmentBOSSANOVA(molecule *mol, Graph &FragmentList, KeyStack &RootStack)
252{
253 Info FunctionInfo(__func__);
254 std::vector<Graph*> *FragmentLowerOrdersList = NULL;
255 size_t NumLevels = 0;
256// size_t NumMolecules = 0;
257 size_t TotalNumMolecules = 0;
258 int *NumMoleculesOfOrder = NULL;
259 int Order = 0;
260 int UpgradeCount = RootStack.size();
261 KeyStack FragmentRootStack;
262 int RootKeyNr = 0;
263 int RootNr = 0;
264
265 // FragmentLowerOrdersList is a 2D-array of pointer to vector of molecule objects, one dimension represents the ANOVA expansion of a single order (i.e. 5)
266 // with all needed lower orders that are subtracted, the other dimension is the BondOrder (i.e. from 1 to 5)
267 NumMoleculesOfOrder = new int[UpgradeCount];
268 FragmentLowerOrdersList = new std::vector<Graph*>[UpgradeCount];
269
270 for(int i=0;i<UpgradeCount;i++)
271 NumMoleculesOfOrder[i] = 0;
272
273 // Construct the restricted key set (contained in the root stack), i.e. which atoms take part
274 KeySet RestrictedKeyset;
275 for (KeyStack::const_iterator iter = RootStack.begin(); iter != RootStack.end(); ++iter)
276 RestrictedKeyset.insert(*iter);
277
278 // 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
279 // 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),
280 // hence we have overall four 2th order levels for splitting. This also allows for putting all into a single array (FragmentLowerOrdersList[])
281 // 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)
282 RootNr = 0; // counts through the roots in RootStack
283 while ((RootNr < UpgradeCount) && (!RootStack.empty())) {
284 RootKeyNr = RootStack.front();
285 RootStack.pop_front();
286 atom *Walker = mol->FindAtom(RootKeyNr);
287 // check cyclic lengths
288 //if ((MinimumRingSize[Walker->GetTrueFather()->getNr()] != -1) && (Walker->GetTrueFather()->AdaptiveOrder+1 > MinimumRingSize[Walker->GetTrueFather()->getNr()])) {
289 // LOG(0, "Bond order " << Walker->GetTrueFather()->AdaptiveOrder << " of Root " << *Walker << " greater than or equal to Minimum Ring size of " << MinimumRingSize << " found is not allowed.");
290 //} else
291 {
292 // set adaptive order to desired max order
293 Walker->GetTrueFather()->AdaptiveOrder = Walker->GetTrueFather()->MaxOrder;
294 Order = Walker->AdaptiveOrder = Walker->GetTrueFather()->AdaptiveOrder;
295
296 // allocate memory for all lower level orders
297 NumLevels = Order;
298 FragmentLowerOrdersList[RootNr].resize(NumLevels, NULL);
299 for( size_t i=0;i<NumLevels;++i)
300 FragmentLowerOrdersList[RootNr][i] = new Graph;
301
302 // initialise Order-dependent entries of UniqueFragments structure
303 UniqueFragments FragmentSearch(1., FragmentLowerOrdersList[RootNr], Walker);
304 PowerSetGenerator PSG(&FragmentSearch, Walker->AdaptiveOrder);
305
306 // create top order where nothing is reduced
307 LOG(0, "==============================================================================================================");
308 LOG(0, "Creating KeySets up till Bond Order " << Order << " for " << *Walker << ", " << (RootStack.size()-RootNr) << " Roots remaining."); // , NumLevels is " << NumLevels << "
309
310 // Create list of Graphs of current Bond Order (i.e. F_{ij})
311 NumMoleculesOfOrder[RootNr] = PSG(RestrictedKeyset, treatment);
312
313 // output resulting number
314 LOG(1, "INFO: Number of resulting KeySets is: " << NumMoleculesOfOrder[RootNr] << ".");
315// if (NumMoleculesOfOrder[RootNr] != 0) {
316// NumMolecules = 0;
317// }
318 // now, we have completely filled each cell of FragmentLowerOrdersList[] for the current Walker->AdaptiveOrder
319 //NumMoleculesOfOrder[Walker->AdaptiveOrder-1] = NumMolecules;
320 TotalNumMolecules += NumMoleculesOfOrder[RootNr];
321// LOG(1, "Number of resulting molecules for Order " << (int)Walker->GetTrueFather()->AdaptiveOrder << " is: " << NumMoleculesOfOrder[RootNr] << ".");
322 RootStack.push_back(RootKeyNr); // put back on stack
323 RootNr++;
324 }
325 }
326 LOG(0, "==============================================================================================================");
327 LOG(0, "\tTotal number of resulting fragments is: " << TotalNumMolecules << ".");
328 LOG(0, "==============================================================================================================");
329
330 // now, FragmentLowerOrdersList is complete, it looks - for BondOrder 5 - as this (number is the ANOVA Order of the terms therein)
331 // 5433222211111111
332 // 43221111
333 // 3211
334 // 21
335 // 1
336
337 // Subsequently, we combine all into a single list (FragmentList)
338 CombineAllOrderListIntoOne(FragmentList, FragmentLowerOrdersList, RootStack, mol);
339 FreeAllOrdersList(FragmentLowerOrdersList, RootStack, mol);
340 delete[](NumMoleculesOfOrder);
341};
342
343/** Estimates by educated guessing (using upper limit) the expected number of fragments.
344 * The upper limit is
345 * \f[
346 * n = N \cdot C^k
347 * \f]
348 * where \f$C=2^c\f$ and c is the maximum bond degree over N number of atoms.
349 * \param *out output stream for debugging
350 * \param order bond order k
351 * \return number n of fragments
352 */
353int Fragmentation::GuesstimateFragmentCount(int order)
354{
355 size_t c = 0;
356 int FragmentCount;
357 // get maximum bond degree
358 for (molecule::const_iterator iter = const_cast<const molecule *>(mol)->begin();
359 iter != const_cast<const molecule *>(mol)->end();
360 ++iter) {
361 const BondList& ListOfBonds = (*iter)->getListOfBonds();
362 c = (ListOfBonds.size() > c) ? ListOfBonds.size() : c;
363 }
364 FragmentCount = (treatment == ExcludeHydrogen ? mol->getNoNonHydrogen() : mol->getAtomCount()) *(1 << (c*order));
365 LOG(1, "INFO: Upper limit for this subgraph is " << FragmentCount << " for "
366 << mol->getNoNonHydrogen() << " non-H atoms with maximum bond degree of " << c << ".");
367 return FragmentCount;
368};
369
370
371/** Checks whether the OrderAtSite is still below \a Order at some site.
372 * \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
373 * \param *GlobalKeySetList list of keysets with global ids (valid in "this" molecule) needed for adaptive increase
374 * \param Order desired Order if positive, desired exponent in threshold criteria if negative (0 is single-step)
375 * \param path path to ENERGYPERFRAGMENT file (may be NULL if Order is non-negative)
376 * \param LoopDoneAlready indicate whether we have done a fragmentation loop already
377 * \return true - needs further fragmentation, false - does not need fragmentation
378 */
379bool Fragmentation::CheckOrderAtSite(AtomMask_t &AtomMask, const Graph &GlobalKeySetList, int Order, const std::string &path, bool LoopDoneAlready)
380{
381 bool status = false;
382
383 if (Order < 0) { // adaptive increase of BondOrder per site
384 if (LoopDoneAlready) // break after one step
385 return false;
386
387 // transmorph graph keyset list into indexed KeySetList
388 AdaptivityMap * IndexKeySetList = GlobalKeySetList.GraphToAdaptivityMap();
389
390 // parse the EnergyPerFragment file
391 IndexKeySetList->ScanAdaptiveFileIntoMap(path); // (Root No., (Value, Order)) !
392 // then map back onto (Value, (Root Nr., Order)) (i.e. sorted by value to pick the highest ones)
393 IndexKeySetList->ReMapAdaptiveCriteriaListToValue(mol);
394
395 // pick the ones still below threshold and mark as to be adaptively updated
396 if (IndexKeySetList->IsAdaptiveCriteriaListEmpty()) {
397 ELOG(2, "Unable to parse file, incrementing all.");
398 status = true;
399 } else {
400 // mark as false all sites that are below threshold already
401 status = IndexKeySetList->MarkUpdateCandidates(AtomMask, Order, mol);
402 }
403
404 delete[](IndexKeySetList);
405 } else { // global increase of Bond Order
406 for(molecule::iterator iter = mol->begin(); iter != mol->end(); ++iter) {
407 atom * const Walker = *iter;
408 if (AtomMask.isTrue(Walker->getNr())) { // skip masked out
409 Walker->MaxOrder = (Order != 0 ? Order : Walker->MaxOrder+1);
410 // remove all that have reached desired order
411 if (Walker->AdaptiveOrder >= Walker->MaxOrder) // && (Walker->AdaptiveOrder < MinimumRingSize[Walker->getNr()]))
412 AtomMask.setFalse(Walker->getNr());
413 else
414 status = true;
415 }
416 }
417 if ((!Order) && (!LoopDoneAlready)) // single stepping, just check
418 status = true;
419
420 if (!status) {
421 if (Order == 0)
422 LOG(1, "INFO: Single stepping done.");
423 else
424 LOG(1, "INFO: Order at every site is already equal or above desired order " << Order << ".");
425 }
426 }
427
428 PrintAtomMask(AtomMask, AtomMask.size()); // for debugging
429
430 return status;
431};
432
433/** Stores pairs (Atom::Nr, Atom::AdaptiveOrder) into file.
434 * Atoms not present in the file get "-1".
435 * \param &path path to file ORDERATSITEFILE
436 * \return true - file writable, false - not writable
437 */
438bool Fragmentation::StoreOrderAtSiteFile(
439 const std::string &path)
440{
441 string line;
442 ofstream file;
443
444 line = path + ORDERATSITEFILE;
445 file.open(line.c_str(), std::ofstream::out | std::ofstream::app);
446 std::stringstream output;
447 output << "INFO: Writing OrderAtSite " << ORDERATSITEFILE << " ... ";
448 if (file.good()) {
449 for (molecule::const_iterator iter = const_cast<const molecule *>(mol)->begin();
450 iter != const_cast<const molecule *>(mol)->end();
451 ++iter) {
452 file << (*iter)->getId()
453 << "\t" << (int)(*iter)->AdaptiveOrder
454 << "\t" << (int)(*iter)->MaxOrder << std::endl;
455 }
456 file.close();
457 output << "done.";
458 return true;
459 } else {
460 output << "failed to open file " << line << ".";
461 return false;
462 }
463 LOG(1, output.str());
464 return true;
465};
466
467
468/** Parses pairs(Atom::Nr, Atom::AdaptiveOrder) from file and stores in molecule's Atom's.
469 * Atoms not present in the file get "0".
470 * \param atomids atoms to fragment, used in AtomMask
471 * \param &path path to file ORDERATSITEFILE
472 * \param global_local_bimap translate global to local id
473 * \return true - file found and scanned, false - file not found
474 * \sa ParseKeySetFile() and CheckAdjacencyFileAgainstMolecule() as this is meant to be used in conjunction with the two
475 */
476bool Fragmentation::ParseOrderAtSiteFromFile(
477 const std::vector<atomId_t> &atomids,
478 const std::string &path,
479 const Global_local_bimap_t &global_local_bimap)
480{
481// Info FunctionInfo(__func__);
482 typedef unsigned char order_t;
483 typedef std::map<atomId_t, order_t> OrderArray_t;
484 OrderArray_t OrderArray;
485 AtomMask_t MaxArray(atomids);
486 bool status;
487 int AtomNr, ordervalue, maxvalue;
488 string line;
489 ifstream file;
490
491 line = path + ORDERATSITEFILE;
492 file.open(line.c_str());
493 if (file.good()) {
494 while (!file.eof()) { // parse from file
495 AtomNr = -1;
496 file >> AtomNr;
497 file >> ordervalue;
498 file >> maxvalue;
499 if (AtomNr != -1) { // test whether we really parsed something (this is necessary, otherwise last atom is set twice and to 0 on second time)
500 // parsed id is global, must be translated to local id
501 Global_local_bimap_t::left_const_iterator iter = global_local_bimap.left.find(AtomNr);
502 // skip global ids we don't know about, must be in other molecule
503 if (iter != global_local_bimap.left.end()) {
504 const int LocalId = iter->second;
505 OrderArray[LocalId] = ordervalue;
506 MaxArray.setValue(LocalId, (bool)maxvalue);
507 //LOG(2, "AtomNr " << LocalId << " with order " << (int)OrderArray[LocalId] << " and max order set to " << (int)MaxArray[LocalId] << ".");
508 }
509 }
510 }
511 file.close();
512
513 // set atom values
514 for(molecule::iterator iter=mol->begin();iter!=mol->end();++iter){
515 (*iter)->AdaptiveOrder = OrderArray[(*iter)->getNr()];
516 (*iter)->MaxOrder = OrderArray[(*iter)->getNr()]; //MaxArray.isTrue((*iter)->getNr());
517 }
518 //SetAtomValueToIndexedArray( OrderArray, &atom::getNr(), &atom::AdaptiveOrder );
519 //SetAtomValueToIndexedArray( MaxArray, &atom::getNr(), &atom::MaxOrder );
520
521 status = true;
522 } else {
523 ELOG(1, "Failed to open OrdersAtSite file " << line << ".");
524 status = false;
525 }
526
527 return status;
528};
529
530/** Fills the root stack for sites to be used as root in fragmentation depending on order or adaptivity criteria
531 * Again, as in \sa FillBondStructureFromReference steps recursively through each Leaf in this chain list of molecule's.
532 * \param &RootStack stack to be filled
533 * \param AtomMask defines true/false per global Atom::Nr to mask in/out each nuclear site
534 * \return true - stack is non-empty, fragmentation necessary, false - stack is empty, no more sites to update
535 */
536void Fragmentation::FillRootStackForSubgraphs(KeyStack &RootStack, const AtomMask_t &AtomMask)
537{
538 for(molecule::const_iterator iter = const_cast<const molecule *>(mol)->begin();
539 iter != const_cast<const molecule *>(mol)->end();
540 ++iter) {
541 const atom * const Father = (*iter)->GetTrueFather();
542 if (AtomMask.isTrue(Father->getNr())) // apply mask
543 if ((treatment == IncludeHydrogen) || ((*iter)->getType()->getAtomicNumber() != 1)) // skip hydrogen
544 RootStack.push_front((*iter)->getNr());
545 }
546}
547
548/** The indices per keyset are compared to the respective father's Atom::Nr in each subgraph and thus put into \a **&FragmentList.
549 * \param *KeySetList list with all keysets
550 * \param ListOfLocalAtoms Lookup table for each subgraph and index of each atom in global molecule, may be NULL on start, then it is filled
551 * \param **&FragmentList list to be allocated and returned
552 * \param FreeList true - ***ListOfLocalAtoms is free'd before return, false - it is not
553 * \retuen true - success, false - failure
554 */
555bool Fragmentation::AssignKeySetsToFragment(const Graph &KeySetList, ListOfLocalAtoms_t &ListOfLocalAtoms, Graph &FragmentList, bool FreeList)
556{
557// Info FunctionInfo(__func__);
558 bool status = true;
559 size_t KeySetCounter = 0;
560
561 // fill ListOfLocalAtoms if NULL was given
562 if (!mol->FillListOfLocalAtoms(ListOfLocalAtoms, mol->getAtomCount())) {
563 ELOG(1, "Filling of ListOfLocalAtoms failed.");
564 return false;
565 }
566
567 if (KeySetList.size() != 0) { // if there are some scanned keysets at all
568 // assign scanned keysets
569 KeySet TempSet;
570 for (Graph::const_iterator runner = KeySetList.begin(); runner != KeySetList.end(); runner++) { // key sets contain global numbers!
571 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
572 // translate keyset to local numbers
573 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
574 TempSet.insert(ListOfLocalAtoms[mol->FindAtom(*sprinter)->getNr()]->getNr());
575 // insert into FragmentList
576 FragmentList.insert(GraphPair(TempSet, pair<int, double> (KeySetCounter++, (*runner).second.second)));
577 }
578 TempSet.clear();
579 }
580 } else
581 ELOG(2, "KeySetList is NULL or empty.");
582
583 if (FreeList) {
584 // free the index lookup list
585 ListOfLocalAtoms.clear();
586 }
587 return status;
588}
589
590/** Translate list into global numbers (i.e. ones that are valid in "this" molecule, not in MolecularWalker->Leaf)
591 * \param &FragmentList Graph with local numbers per fragment
592 * \param &TotalNumberOfKeySets global key set counter
593 * \param &TotalGraph Graph to be filled with global numbers
594 */
595void Fragmentation::TranslateIndicesToGlobalIDs(Graph &FragmentList, int &TotalNumberOfKeySets, Graph &TotalGraph)
596{
597// Info FunctionInfo(__func__);
598 for (Graph::iterator runner = FragmentList.begin(); runner != FragmentList.end(); runner++) {
599 KeySet TempSet;
600 for (KeySet::iterator sprinter = (*runner).first.begin(); sprinter != (*runner).first.end(); sprinter++)
601 TempSet.insert((mol->FindAtom(*sprinter))->GetTrueFather()->getId());
602 TotalGraph.insert(GraphPair(TempSet, pair<int, double> (TotalNumberOfKeySets++, (*runner).second.second)));
603 }
604}
605
Note: See TracBrowser for help on using the repository browser.