source: src/Actions/FragmentationAction/FragmentationAction.cpp@ d635829

Last change on this file since d635829 was d635829, checked in by Frederik Heber <heber@…>, 11 years ago

FragmentationAction now compiles global saturation positions information.

  • Property mode set to 100644
File size: 16.7 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 * FragmentationAction.cpp
26 *
27 * Created on: May 9, 2010
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36#include "CodePatterns/MemDebug.hpp"
37
38#include "Atom/atom.hpp"
39#include "CodePatterns/IteratorAdaptors.hpp"
40#include "CodePatterns/Log.hpp"
41#include "Descriptors/AtomSelectionDescriptor.hpp"
42#include "Fragmentation/Exporters/ExportGraph_ToFiles.hpp"
43#include "Fragmentation/Exporters/ExportGraph_ToJobs.hpp"
44#include "Fragmentation/Exporters/SaturatedFragment.hpp"
45#include "Fragmentation/Exporters/SphericalPointDistribution.hpp"
46#include "Fragmentation/Fragmentation.hpp"
47#include "Fragmentation/Graph.hpp"
48#include "Fragmentation/HydrogenSaturation_enum.hpp"
49#include "Fragmentation/Interfragmenter.hpp"
50#include "Fragmentation/KeySetsContainer.hpp"
51#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
52#include "Graph/AdjacencyList.hpp"
53#include "Graph/BondGraph.hpp"
54#include "Graph/CyclicStructureAnalysis.hpp"
55#include "Graph/DepthFirstSearchAnalysis.hpp"
56#include "Helpers/defs.hpp"
57#include "molecule.hpp"
58#include "World.hpp"
59
60#include <boost/shared_ptr.hpp>
61#include <boost/filesystem.hpp>
62#include <algorithm>
63#include <iostream>
64#include <map>
65#include <string>
66#include <vector>
67
68#include "Actions/FragmentationAction/FragmentationAction.hpp"
69
70using namespace MoleCuilder;
71
72// and construct the stuff
73#include "FragmentationAction.def"
74#include "Action_impl_pre.hpp"
75/** =========== define the function ====================== */
76ActionState::ptr FragmentationFragmentationAction::performCall() {
77 clock_t start,end;
78 int ExitFlag = -1;
79 World &world = World::getInstance();
80
81 // inform about used parameters
82 LOG(0, "STATUS: Fragmenting molecular system with current connection matrix up to "
83 << params.order.get() << " order. ");
84 if (params.types.get().size() != 0)
85 LOG(0, "STATUS: Fragment files begin with "
86 << params.prefix.get() << " and are stored as: "
87 << params.types.get() << "." << std::endl);
88
89 // check for selected atoms
90 if (world.beginAtomSelection() == world.endAtomSelection()) {
91 STATUS("There are no atoms selected for fragmentation.");
92 return Action::failure;
93 }
94
95 // go through all atoms, note down their molecules and group them
96 typedef std::multimap<molecule *, atom *> clusters_t;
97 typedef std::vector<atomId_t> atomids_t;
98 atomids_t atomids;
99 clusters_t clusters;
100 for (World::AtomSelectionConstIterator iter = world.beginAtomSelection();
101 iter != world.endAtomSelection(); ++iter) {
102 clusters.insert( std::make_pair(iter->second->getMolecule(), iter->second) );
103 atomids.push_back(iter->second->getId());
104 }
105 {
106 std::vector<molecule *> molecules;
107 molecules.insert( molecules.end(), MapKeyIterator<clusters_t::const_iterator>(clusters.begin()),
108 MapKeyIterator<clusters_t::const_iterator>(clusters.end()) );
109 molecules.erase( std::unique(molecules.begin(), molecules.end()), molecules.end() );
110 LOG(1, "INFO: There are " << molecules.size() << " molecules to consider.");
111 }
112
113 // parse in Adjacency file
114 boost::shared_ptr<AdjacencyList> FileChecker;
115 boost::filesystem::path filename(params.prefix.get() + std::string(ADJACENCYFILE));
116 if (boost::filesystem::exists(filename) && boost::filesystem::is_regular_file(filename)) {
117 std::ifstream File;
118 File.open(filename.string().c_str(), ios::out);
119 FileChecker.reset(new AdjacencyList(File));
120 File.close();
121 } else {
122 LOG(1, "INFO: Could not open default adjacency file " << filename.string() << ".");
123 FileChecker.reset(new AdjacencyList);
124 }
125
126 // make sure bond degree is correct
127 {
128 BondGraph *BG = World::getInstance().getBondGraph();
129 World::AtomComposite Set = World::getInstance().getAllAtoms(AtomsBySelection());
130 BG->CorrectBondDegree(Set);
131 }
132
133 // we parse in the keysets from last time if present
134 Graph StoredGraph;
135 StoredGraph.ParseKeySetFile(params.prefix.get());
136
137 start = clock();
138 // go through all keys (i.e. all molecules)
139 clusters_t::const_iterator advanceiter;
140 Graph TotalGraph;
141 int keysetcounter = 0;
142 for (clusters_t::const_iterator iter = clusters.begin();
143 iter != clusters.end();
144 iter = advanceiter) {
145 // get iterator to past last atom in this molecule
146 molecule * mol = iter->first;
147 advanceiter = clusters.upper_bound(mol);
148
149 // copy molecule's atoms' ids as parameters to Fragmentation's AtomMask
150 std::vector<atomId_t> mols_atomids;
151 std::transform(iter, advanceiter, std::back_inserter(mols_atomids),
152 boost::bind( &atom::getNr,
153 boost::bind( &clusters_t::value_type::second, _1 ))
154 );
155 LOG(2, "INFO: Fragmenting in molecule " << mol->getName() << " in " << clusters.count(mol)
156 << " atoms, out of " << mol->getAtomCount() << ".");
157 const enum HydrogenTreatment treatment = params.HowtoTreatHydrogen.get() ? ExcludeHydrogen : IncludeHydrogen;
158 Fragmentation Fragmenter(mol, *FileChecker, treatment);
159
160 // perform fragmentation
161 LOG(0, std::endl << " ========== Fragmentation of molecule " << mol->getName() << " ========================= ");
162 {
163 Graph StoredLocalGraph(StoredGraph.getLocalGraph(mol));
164 const int tempFlag = Fragmenter.FragmentMolecule(mols_atomids, params.order.get(), params.prefix.get(), StoredLocalGraph);
165 if ((ExitFlag == 2) && (tempFlag != 2))
166 ExitFlag = tempFlag; // if there is one molecule that needs further fragmentation, it overrides others
167 if (ExitFlag == -1)
168 ExitFlag = tempFlag; // if we are the first, we set the standard
169 }
170 if (TotalGraph.empty()) {
171 TotalGraph = Fragmenter.getGraph();
172 keysetcounter = TotalGraph.size();
173 } else
174 TotalGraph.InsertGraph(Fragmenter.getGraph(), keysetcounter);
175
176 }
177 // add full cycles if desired
178 if (params.DoCyclesFull.get()) {
179 // get the BackEdgeStack from somewhere
180 DepthFirstSearchAnalysis DFS;
181 DFS();
182 std::deque<bond::ptr> BackEdgeStack = DFS.getBackEdgeStack();
183 // then we analyse the cycles and get them
184 CyclicStructureAnalysis CycleAnalysis(params.HowtoTreatHydrogen.get() ? ExcludeHydrogen : IncludeHydrogen);
185 CycleAnalysis(&BackEdgeStack);
186 CyclicStructureAnalysis::cycles_t cycles = CycleAnalysis.getAllCycles();
187 // sort them according to KeySet::operator<()
188 std::sort(cycles.begin(), cycles.end());
189 // store all found cycles to file
190 {
191 boost::filesystem::path filename(params.prefix.get() + std::string(CYCLEKEYSETFILE));
192 std::ofstream File;
193 LOG(1, "INFO: Storing cycle keysets to " << filename.string() << ".");
194 File.open(filename.string().c_str(), ios::out);
195 for (CyclicStructureAnalysis::cycles_t::const_iterator iter = cycles.begin();
196 iter != cycles.end(); ++iter) {
197 for (CyclicStructureAnalysis::cycle_t::const_iterator cycleiter = (*iter).begin();
198 cycleiter != (*iter).end(); ++cycleiter) {
199 File << *cycleiter << "\t";
200 }
201 File << "\n";
202 }
203 File.close();
204 }
205 // ... and to result container
206 {
207 KeySetsContainer cyclekeys;
208 for (CyclicStructureAnalysis::cycles_t::const_iterator iter = cycles.begin();
209 iter != cycles.end(); ++iter) {
210 const CyclicStructureAnalysis::cycle_t &cycle = *iter;
211 const size_t order = cycle.size();
212 KeySetsContainer::IntVector temp_cycle(cycle.begin(), cycle.end());
213 cyclekeys.insert(temp_cycle, order);
214 }
215 FragmentationResultContainer::getInstance().addCycles(cyclekeys);
216 }
217 // Create graph and insert into TotalGraph
218 LOG(0, "STATUS: Adding " << cycles.size() << " cycles.");
219 {
220 Graph CycleGraph;
221 for (CyclicStructureAnalysis::cycles_t::const_iterator iter = cycles.begin();
222 iter != cycles.end(); ++iter) {
223 const CyclicStructureAnalysis::cycle_t &currentcycle = *iter;
224 LOG(2, "INFO: Inserting cycle " << currentcycle << ".");
225#ifndef NDEBUG
226 std::pair< Graph::iterator, bool > inserter =
227#endif
228 CycleGraph.insert( std::make_pair(currentcycle, NumberValuePair(1,1.)) );
229 ASSERT( inserter.second,
230 "FragmentationFragmentationAction::performCall() - keyset "
231 +toString(currentcycle)+" inserted twice into CycleGraph.");
232 }
233 TotalGraph.InsertGraph(CycleGraph, keysetcounter);
234 }
235 }
236
237 LOG(0, "STATUS: There are " << TotalGraph.size() << " fragments.");
238
239 {
240 // remove OrderAtSite file
241 std::string line;
242 std::ofstream file;
243 line = params.prefix.get() + ORDERATSITEFILE;
244 file.open(line.c_str(), std::ofstream::out | std::ofstream::trunc);
245 file << "";
246 file.close();
247 }
248
249 // now add interfragments
250 if (params.InterOrder.get() != 0) {
251 LOG(0, "STATUS: Putting fragments together up to order "
252 << params.InterOrder.get() << " and distance of "
253 << params.distance.get() << ".");
254 Interfragmenter fragmenter(TotalGraph);
255 const enum HydrogenTreatment treatment = params.HowtoTreatHydrogen.get() ? ExcludeHydrogen : IncludeHydrogen;
256 fragmenter(params.InterOrder.get(), params.distance.get(), treatment);
257 LOG(0, "STATUS: There are now " << TotalGraph.size() << " fragments after interfragmenting.");
258 }
259
260 // store keysets to file
261 {
262 TotalGraph.StoreKeySetFile(params.prefix.get());
263 }
264
265 // create global saturation positions map
266 SaturatedFragment::GlobalSaturationPositions_t globalsaturationpositions;
267 {
268 // go through each atom
269 for (World::AtomSelectionConstIterator iter = world.beginAtomSelection();
270 iter != world.endAtomSelection(); ++iter) {
271 const atom * const _atom = iter->second;
272
273 // skip hydrogens if treated special
274 const enum HydrogenTreatment treatment = params.HowtoTreatHydrogen.get() ? ExcludeHydrogen : IncludeHydrogen;
275 if ((treatment == ExcludeHydrogen) && (_atom->getType()->getAtomicNumber() == 1)) {
276 LOG(4, "DEBUG: Skipping hydrogen atom " << *_atom);
277 continue;
278 }
279
280 // gather the polygon
281 SphericalPointDistribution::WeightedPolygon_t polygon;
282 const BondList &bondlist = _atom->getListOfBonds();
283 for (BondList::const_iterator bonditer = bondlist.begin();
284 bonditer != bondlist.end(); ++bonditer) {
285 const atom * const _otheratom = (*bonditer)->GetOtherAtom(_atom);
286 Vector bondvector = _otheratom->getPosition() - _atom->getPosition();
287 bondvector.Normalize();
288 polygon.push_back(
289 std::make_pair(
290 bondvector,
291 (*bonditer)->getDegree()
292 ) );
293 }
294 LOG(3, "DEBUG: Polygon is " << polygon << " for this atom " << *_atom << ".");
295
296 // get the valence
297 unsigned int NumberOfPoints = _atom->getElement().getNoValenceOrbitals();
298 LOG(3, "DEBUG: There are " << NumberOfPoints
299 << " places to fill in in total for this atom " << *_atom << ".");
300
301 // check whether there are any bonds with degree larger than 1
302 unsigned int SumOfDegrees = 0;
303 bool PresentHigherBonds = false;
304 for (BondList::const_iterator bonditer = bondlist.begin();
305 bonditer != bondlist.end(); ++bonditer) {
306 SumOfDegrees += (*bonditer)->getDegree();
307 PresentHigherBonds |= (*bonditer)->getDegree() > 1;
308 }
309
310 // get the association for each bond neighbor
311 SphericalPointDistribution SPD;
312 SphericalPointDistribution::PolygonWithIndexTuples globalinfo;
313 if ((NumberOfPoints != SumOfDegrees) || (PresentHigherBonds))
314 globalinfo = SPD.getAssociatedPoints(polygon, NumberOfPoints);
315 else
316 globalinfo = SphericalPointDistribution::getIdentityAssociation(polygon);
317 LOG(3, "DEBUG: Original polygon was " << polygon << " for this atom " << *_atom << ".");
318 LOG(3, "DEBUG: Got global saturation polygon " << globalinfo.polygon
319 << " for atom " << *_atom);
320 LOG(3, "DEBUG: Associated matching is " << globalinfo.indices
321 << " for atom " << *_atom);
322
323 // convert into the desired entry in the map
324 SaturatedFragment::SaturationsPositionsPerNeighbor_t positions_per_neighbor;
325 BondList::const_iterator bonditer = bondlist.begin();
326 // same number of bonds and tuples
327 ASSERT( bondlist.size() == globalinfo.indices.size(),
328 "FragmentationAction::performCall() - number of bonds "
329 +toString(bondlist.size())+" unequal to number of tuples "
330 +toString(globalinfo.indices.size()));
331 for (SphericalPointDistribution::IndexTupleList_t::const_iterator tupleiter =
332 globalinfo.indices.begin();
333 tupleiter != globalinfo.indices.end(); ++tupleiter, ++bonditer) {
334 // note that we cannot check whether the designated vector matches with the
335 // normalized bond vector where it should have originated because the
336 // vector has been rotated.
337// Vector bondvector =
338// (*bonditer)->GetOtherAtom(_atom)->getPosition()-_atom->getPosition();
339// bondvector.Normalize();
340 // no go through all indices of the tuple (and positions)
341 for (SphericalPointDistribution::IndexList_t::const_iterator indexiter =
342 tupleiter->begin(); indexiter != tupleiter->end(); ++indexiter) {
343 // and add them, first trying with new list
344 std::pair<
345 SaturatedFragment::SaturationsPositionsPerNeighbor_t::iterator,
346 bool
347 > inserter =
348 positions_per_neighbor.insert(
349 std::make_pair(
350 (*bonditer)->GetOtherAtom(_atom)->getId(),
351 SaturatedFragment::SaturationsPositions_t(
352 1,
353 globalinfo.polygon[*indexiter])
354 )
355 );
356 // if already pressent, add to this present list
357 if (!inserter.second) {
358 inserter.first->second.push_back(globalinfo.polygon[*indexiter]);
359 }
360 }
361 }
362 // bonditer follows nicely
363 ASSERT( bonditer == bondlist.end(),
364 "FragmentationAction::performCall() - bonditer is out of step, it still points at bond "
365 +toString(*bonditer)+".");
366
367 // and insert
368 globalsaturationpositions.insert(
369 std::make_pair( _atom->getId(),
370 positions_per_neighbor
371 ));
372 }
373 }
374
375 {
376 const enum HydrogenSaturation saturation = params.DoSaturation.get() ? DoSaturate : DontSaturate;
377 const enum HydrogenTreatment treatment = params.HowtoTreatHydrogen.get() ? ExcludeHydrogen : IncludeHydrogen;
378 if (params.types.get().size() != 0) {
379 // store molecule's fragment to file
380 ExportGraph_ToFiles exporter(TotalGraph, treatment, saturation, globalsaturationpositions);
381 exporter.setPrefix(params.prefix.get());
382 exporter.setOutputTypes(params.types.get());
383 exporter();
384 } else {
385 // store molecule's fragment in FragmentJobQueue
386 ExportGraph_ToJobs exporter(TotalGraph, treatment, saturation, globalsaturationpositions);
387 exporter.setLevel(params.level.get());
388 exporter();
389 }
390 }
391
392 // store Adjacency to file
393 {
394 std::string filename = params.prefix.get() + ADJACENCYFILE;
395 std::ofstream AdjacencyFile;
396 AdjacencyFile.open(filename.c_str(), ios::out);
397 AdjacencyList adjacency(atomids);
398 adjacency.StoreToFile(AdjacencyFile);
399 AdjacencyFile.close();
400 }
401
402 World::getInstance().setExitFlag(ExitFlag);
403 end = clock();
404 LOG(0, "STATUS: Clocks for this operation: " << (end-start) << ", time: " << ((double)(end-start)/CLOCKS_PER_SEC) << "s.");
405
406 return Action::success;
407}
408
409ActionState::ptr FragmentationFragmentationAction::performUndo(ActionState::ptr _state) {
410 return Action::success;
411}
412
413ActionState::ptr FragmentationFragmentationAction::performRedo(ActionState::ptr _state){
414 return Action::success;
415}
416
417bool FragmentationFragmentationAction::canUndo() {
418 return true;
419}
420
421bool FragmentationFragmentationAction::shouldUndo() {
422 return true;
423}
424/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.