source: src/Actions/FragmentationAction/FragmentationAction.cpp@ 5d5550

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

FragmentationAction now compiles global saturation positions information.

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