source: src/Actions/PotentialAction/FitPartialChargesAction.cpp@ 9cf1e2

Add_FitFragmentPartialChargesAction Fix_ChargeSampling_PBC Fix_FitPartialCharges
Last change on this file since 9cf1e2 was 9cf1e2, checked in by Frederik Heber <heber@…>, 9 years ago

First version of orthogonal summation of partial charges.

  • implemented directly in FitPartialChargesAction::performCall().
  • Property mode set to 100644
File size: 28.4 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2013 Frederik Heber. 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 * FitPartialChargesAction.cpp
25 *
26 * Created on: Jul 03, 2013
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35// needs to come before MemDebug due to placement new
36#include <boost/archive/text_iarchive.hpp>
37
38#include "CodePatterns/MemDebug.hpp"
39
40#include "Atom/atom.hpp"
41#include "CodePatterns/Log.hpp"
42#include "Fragmentation/Exporters/ExportGraph_ToFiles.hpp"
43#include "Fragmentation/Graph.hpp"
44#include "World.hpp"
45
46#include <boost/bimap.hpp>
47#include <boost/bimap/multiset_of.hpp>
48#include <boost/bind.hpp>
49#include <boost/filesystem.hpp>
50#include <boost/foreach.hpp>
51#include <boost/mpl/for_each.hpp>
52
53#include <algorithm>
54#include <functional>
55#include <iostream>
56#include <string>
57
58#include "Actions/PotentialAction/FitPartialChargesAction.hpp"
59
60#include "Potentials/PartialNucleiChargeFitter.hpp"
61
62#include "AtomIdSet.hpp"
63#include "Descriptors/AtomIdDescriptor.hpp"
64#include "Element/element.hpp"
65#include "Element/periodentafel.hpp"
66#include "Fragmentation/Homology/AtomFragmentsMap.hpp"
67#include "Fragmentation/Homology/HomologyContainer.hpp"
68#include "Fragmentation/Homology/HomologyGraph.hpp"
69#include "Fragmentation/Summation/Containers/PartialChargesFused.hpp"
70#include "Fragmentation/Summation/Containers/PartialChargesMap.hpp"
71#include "Fragmentation/Summation/SetValues/SamplingGrid.hpp"
72#include "Fragmentation/Summation/ZeroInstanceInitializer.hpp"
73#include "FunctionApproximation/Extractors.hpp"
74#include "Potentials/PartialNucleiChargeFitter.hpp"
75#include "Potentials/Particles/ParticleFactory.hpp"
76#include "Potentials/Particles/ParticleRegistry.hpp"
77#include "Potentials/SerializablePotential.hpp"
78#include "World.hpp"
79
80using namespace MoleCuilder;
81
82// and construct the stuff
83#include "FitPartialChargesAction.def"
84#include "Action_impl_pre.hpp"
85/** =========== define the function ====================== */
86
87namespace detail {
88 typedef std::map<KeySet, HomologyGraph> KeysetsToGraph_t;
89
90 typedef std::map<HomologyGraph, PartialNucleiChargeFitter::charges_t> GraphFittedChargeMap_t;
91
92 typedef std::map<atomId_t, double> fitted_charges_t;
93
94 typedef std::map<HomologyGraph, size_t> GraphIndex_t;
95
96 typedef std::set<size_t> AtomsGraphIndices_t;
97 typedef boost::bimaps::bimap<
98 boost::bimaps::multiset_of<AtomsGraphIndices_t>,
99 atomId_t > GraphIndices_t;
100
101 typedef std::map<std::set<size_t>, std::map<atomicNumber_t, std::string> > AtomParticleNames_t;
102
103 typedef std::map<std::set<size_t>, std::string> GraphToNameMap_t;
104};
105
106static void enforceZeroTotalCharge(
107 PartialNucleiChargeFitter::charges_t &_averaged_charges)
108{
109 double charge_sum = 0.;
110 charge_sum = std::accumulate(_averaged_charges.begin(), _averaged_charges.end(), charge_sum);
111 if (fabs(charge_sum) > MYEPSILON) {
112 std::transform(
113 _averaged_charges.begin(), _averaged_charges.end(),
114 _averaged_charges.begin(),
115 boost::bind(std::minus<double>(), _1, charge_sum/_averaged_charges.size()));
116 }
117 charge_sum = 0.;
118 charge_sum = std::accumulate(_averaged_charges.begin(), _averaged_charges.end(), charge_sum);
119 ASSERT( fabs(charge_sum) < MYEPSILON,
120 "enforceZeroTotalCharge() - enforcing neutral net charge failed, "
121 +toString(charge_sum)+" is the remaining net charge.");
122
123 LOG(2, "DEBUG: final charges with net zero charge are " << _averaged_charges);
124}
125
126static size_t obtainAverageChargesOverFragments(
127 PartialNucleiChargeFitter::charges_t &_average_charges,
128 const std::pair<
129 HomologyContainer::const_iterator,
130 HomologyContainer::const_iterator> &_range,
131 const double _radius
132 )
133{
134 HomologyContainer::const_iterator iter = _range.first;
135 if (!iter->second.containsGrids) {
136 ELOG(1, "This HomologyGraph does not contain sampled grids.");
137 return 0;
138 }
139 _average_charges.resize(iter->second.fragment.getCharges().size(), 0.);
140 size_t NoFragments = 0;
141 for (;
142 iter != _range.second; ++iter, ++NoFragments) {
143 if (!iter->second.containsGrids) {
144 ELOG(2, "This HomologyGraph does not contain sampled grids,\ndid you forget to add '--store-grids 1' to AnalyseFragmentResults.");
145 return 0;
146 }
147 const Fragment &fragment = iter->second.fragment;
148 // const double &energy = iter->second.energy;
149 // const SamplingGrid &charge = iter->second.charge_distribution;
150 const SamplingGrid &potential = iter->second.potential_distribution;
151 if ((potential.level == 0)
152 || ((potential.begin[0] == potential.end[0])
153 && (potential.begin[1] == potential.end[1])
154 && (potential.begin[2] == potential.end[2]))) {
155 ELOG(1, "Sampled grid contains grid made of zero points.");
156 return 0;
157 }
158
159 // then we extract positions from fragment
160 PartialNucleiChargeFitter::positions_t positions;
161 Fragment::positions_t fragmentpositions = fragment.getPositions();
162 positions.reserve(fragmentpositions.size());
163 BOOST_FOREACH( Fragment::position_t pos, fragmentpositions) {
164 positions.push_back( Vector(pos[0], pos[1], pos[2]) );
165 }
166 PartialNucleiChargeFitter fitter(potential, positions, _radius);
167 fitter();
168 PartialNucleiChargeFitter::charges_t return_charges = fitter.getSolutionAsCharges_t();
169 LOG(2, "DEBUG: fitted charges are " << return_charges);
170 std::transform(
171 return_charges.begin(), return_charges.end(),
172 _average_charges.begin(),
173 _average_charges.begin(),
174 std::plus<PartialNucleiChargeFitter::charge_t>());
175 }
176 if (NoFragments != 0)
177 std::transform(_average_charges.begin(), _average_charges.end(),
178 _average_charges.begin(),
179 std::bind1st(std::multiplies<PartialNucleiChargeFitter::charge_t>(),1./(double)NoFragments)
180 );
181 LOG(2, "DEBUG: final averaged charges are " << _average_charges);
182
183 return NoFragments;
184}
185
186inline SerializablePotential::ParticleTypes_t
187getParticleTypesForAtomIdSet(const AtomIdSet &_atoms)
188{
189 SerializablePotential::ParticleTypes_t particletypes;
190 particletypes.resize(_atoms.size());
191 std::transform(
192 _atoms.begin(), _atoms.end(),
193 particletypes.begin(),
194 boost::bind(&atom::getElementNo, _1));
195 return particletypes;
196}
197
198static
199std::set<KeySet> accumulateKeySetsForAtoms(
200 const AtomFragmentsMap::AtomFragmentsMap_t &_atommap,
201 const std::vector<const atom *> &_selected_atoms)
202{
203 std::set<KeySet> fragments;
204 for (std::vector<const atom *>::const_iterator iter = _selected_atoms.begin();
205 iter != _selected_atoms.end(); ++iter) {
206 const atomId_t atomid = (*iter)->getId();
207 const AtomFragmentsMap::AtomFragmentsMap_t::const_iterator atomiter =
208 _atommap.find(atomid);
209 if ((*iter)->getElementNo() != 1) {
210 if (atomiter == _atommap.end()) {
211 ELOG(2, "There are no fragments associated to " << atomid << ".");
212 continue;
213 }
214 const AtomFragmentsMap::keysets_t &keysets = atomiter->second;
215 LOG(2, "DEBUG: atom " << atomid << " has " << keysets.size() << " fragments.");
216 fragments.insert( keysets.begin(), keysets.end() );
217 } else {
218 LOG(3, "DEBUG: Skipping atom " << atomid << " as it's hydrogen.");
219 }
220 }
221 return fragments;
222}
223
224static
225void getKeySetsToGraphMapping(
226 detail::KeysetsToGraph_t &_keyset_graphs,
227 detail::GraphFittedChargeMap_t &_fittedcharges_per_fragment,
228 const std::set<KeySet> &_fragments,
229 const AtomFragmentsMap &_atomfragments)
230{
231 for (std::set<KeySet>::const_iterator fragmentiter = _fragments.begin();
232 fragmentiter != _fragments.end(); ++fragmentiter) {
233 const KeySet &keyset = *fragmentiter;
234 const AtomFragmentsMap::indices_t &forceindices = _atomfragments.getFullKeyset(keyset);
235 ASSERT( !forceindices.empty(),
236 "getKeySetsToGraphMapping() - force keyset to "+toString(keyset)+" is empty.");
237 KeySet forcekeyset;
238 forcekeyset.insert(forceindices.begin(), forceindices.end());
239 forcekeyset.erase(-1);
240 const HomologyGraph graph(forcekeyset);
241 LOG(2, "DEBUG: Associating keyset " << forcekeyset << " with graph " << graph);
242 _keyset_graphs.insert( std::make_pair(keyset, graph) );
243 _fittedcharges_per_fragment.insert( std::make_pair(graph, PartialNucleiChargeFitter::charges_t()) );
244 }
245}
246
247static
248bool getPartialChargesForAllGraphs(
249 detail::GraphFittedChargeMap_t &_fittedcharges_per_fragment,
250 const HomologyContainer &_homologies,
251 const double _mask_radius,
252 const bool enforceZeroCharge)
253{
254 for (detail::GraphFittedChargeMap_t::iterator graphiter = _fittedcharges_per_fragment.begin();
255 graphiter != _fittedcharges_per_fragment.end(); ++graphiter) {
256 const HomologyGraph &graph = graphiter->first;
257 LOG(2, "DEBUG: Now fitting charges to graph " << graph);
258 const HomologyContainer::range_t range = _homologies.getHomologousGraphs(graph);
259 if (range.first == range.second) {
260 ELOG(0, "HomologyContainer does not contain specified fragment.");
261 return false;
262 }
263
264 // fit and average partial charges over all homologous fragments
265 PartialNucleiChargeFitter::charges_t &averaged_charges = graphiter->second;
266 const size_t NoFragments =
267 obtainAverageChargesOverFragments(averaged_charges, range, _mask_radius);
268 if ((NoFragments == 0) && (range.first != range.second)) {
269 ELOG(0, "Fitting for fragment "+toString(*graphiter)+" failed.");
270 return false;
271 }
272
273 // make sum of charges zero if desired
274 if (enforceZeroCharge)
275 enforceZeroTotalCharge(averaged_charges);
276
277 // output status info fitted charges
278 LOG(2, "DEBUG: For fragment " << *graphiter << " we have fitted the following charges "
279 << averaged_charges << ", averaged over " << NoFragments << " fragments.");
280 }
281 return true;
282}
283
284const atom * getNonHydrogenSurrogate(const atom * const _walker)
285{
286 const atom * surrogate = _walker;
287 if (surrogate->getElementNo() == 1) {
288 // it's hydrogen, check its bonding and use its bond partner instead to request
289 // keysets
290 const BondList &ListOfBonds = surrogate->getListOfBonds();
291 if ( ListOfBonds.size() != 1) {
292 ELOG(1, "Solitary hydrogen in atom " << surrogate->getId() << " detected.");
293 return _walker;
294 }
295 surrogate = (*ListOfBonds.begin())->GetOtherAtom(surrogate);
296 }
297 return surrogate;
298}
299
300double fitAverageChargeToAtom(
301 const atom * const _walker,
302 const AtomFragmentsMap &_atomfragments,
303 const detail::KeysetsToGraph_t &_keyset_graphs,
304 const detail::GraphFittedChargeMap_t &_fittedcharges_per_fragment)
305{
306 const atom * const surrogate = getNonHydrogenSurrogate(_walker);
307 const atomId_t walkerid = surrogate->getId();
308 const AtomFragmentsMap::AtomFragmentsMap_t &atommap = _atomfragments.getMap();
309 const AtomFragmentsMap::AtomFragmentsMap_t::const_iterator keysetsiter =
310 atommap.find(walkerid);
311 ASSERT(keysetsiter != atommap.end(),
312 "fitAverageChargeToAtom() - we checked already that "+toString(walkerid)
313 +" should be present!");
314 const AtomFragmentsMap::keysets_t & keysets = keysetsiter->second;
315
316 double average_charge = 0.;
317 size_t NoFragments = 0;
318 // go over all fragments associated to this atom
319 for (AtomFragmentsMap::keysets_t::const_iterator keysetsiter = keysets.begin();
320 keysetsiter != keysets.end(); ++keysetsiter) {
321 const KeySet &keyset = *keysetsiter;
322
323 const AtomFragmentsMap::indices_t &forcekeyset = _atomfragments.getFullKeyset(keyset);
324 ASSERT( !forcekeyset.empty(),
325 "fitAverageChargeToAtom() - force keyset to "+toString(keyset)+" is empty.");
326
327 // find the associated charge in the charge vector
328 const std::map<KeySet, HomologyGraph>::const_iterator keysetgraphiter =
329 _keyset_graphs.find(keyset);
330 ASSERT( keysetgraphiter != _keyset_graphs.end(),
331 "fitAverageChargeToAtom() - keyset "+toString(keyset)
332 +" not contained in keyset_graphs.");
333 const HomologyGraph &graph = keysetgraphiter->second;
334 const detail::GraphFittedChargeMap_t::const_iterator chargesiter =
335 _fittedcharges_per_fragment.find(graph);
336 ASSERT(chargesiter != _fittedcharges_per_fragment.end(),
337 "fitAverageChargeToAtom() - no charge to "+toString(keyset)
338 +" any longer present in fittedcharges_per_fragment?");
339 const PartialNucleiChargeFitter::charges_t &charges = chargesiter->second;
340 ASSERT( charges.size() == forcekeyset.size(),
341 "fitAverageChargeToAtom() - charges "+toString(charges.size())+" and keyset "
342 +toString(forcekeyset.size())+" do not have the same length?");
343 PartialNucleiChargeFitter::charges_t::const_iterator chargeiter =
344 charges.begin();
345 const AtomFragmentsMap::indices_t::const_iterator forcekeysetiter =
346 std::find(forcekeyset.begin(), forcekeyset.end(), _walker->getId());
347 ASSERT( forcekeysetiter != forcekeyset.end(),
348 "fitAverageChargeToAtom() - atom "+toString(_walker->getId())
349 +" not contained in force keyset "+toString(forcekeyset));
350 std::advance(chargeiter, std::distance(forcekeyset.begin(), forcekeysetiter));
351
352 // and add onto charge sum
353 const double & charge_in_fragment = *chargeiter;
354 average_charge += charge_in_fragment;
355 ++NoFragments;
356 }
357 // average to obtain final partial charge for this atom
358 average_charge *= 1./(double)NoFragments;
359
360 return average_charge;
361}
362
363void addToParticleRegistry(
364 const ParticleFactory &factory,
365 const periodentafel &periode,
366 const detail::fitted_charges_t &_fitted_charges,
367 const detail::GraphIndices_t &_GraphIndices,
368 detail::AtomParticleNames_t &_atom_particlenames)
369{
370 for (detail::fitted_charges_t::const_iterator chargeiter = _fitted_charges.begin();
371 chargeiter != _fitted_charges.end(); ++chargeiter) {
372 const atomId_t &atomid = chargeiter->first;
373 const atom * const walker = World::getInstance().getAtom(AtomById(atomid));
374 ASSERT( walker != NULL,
375 "addToParticleRegistry() - atom "+toString(atomid)
376 +" not present in the World?");
377 const detail::GraphIndices_t::right_const_iterator graphiter =
378 _GraphIndices.right.find(atomid);
379 ASSERT(graphiter != _GraphIndices.right.end(),
380 "addToParticleRegistry() - atom #"+toString(atomid)
381 +" not contained in GraphIndices.");
382 const detail::AtomParticleNames_t::iterator nameiter =
383 _atom_particlenames.find(graphiter->second);
384 const atomicNumber_t elementno = walker->getElementNo();
385 std::string name;
386 if ((nameiter != _atom_particlenames.end()) && (nameiter->second.count(elementno))) {
387 name = (nameiter->second)[elementno];
388 } else {
389 if (nameiter == _atom_particlenames.end())
390 _atom_particlenames.insert(
391 std::make_pair(graphiter->second, std::map<atomicNumber_t, std::string>()) );
392 const double &charge = chargeiter->second;
393 name = Particle::findFreeName(periode, elementno);
394 _atom_particlenames[graphiter->second][elementno] = name;
395 LOG(1, "INFO: Adding particle " << name << " for atom "
396 << *walker << " with element " << elementno << ", charge " << charge);
397 factory.createInstance(name, elementno, charge);
398 }
399 }
400}
401
402bool isNotHydrogen(const atom * const _atom)
403{
404 return (_atom->getElementNo() != (atomicNumber_t) 1);
405}
406
407struct KeySetSizeComp {
408 bool operator() (const KeySet &a, const KeySet &b) { return a.size()<b.size(); }
409} keyset_comparator;
410
411#include <boost/fusion/sequence.hpp>
412#include <boost/mpl/for_each.hpp>
413
414#include "Fragmentation/Summation/AllLevelOrthogonalSummator.hpp"
415#include "Fragmentation/Summation/IndexSet.hpp"
416#include "Fragmentation/Summation/IndexSetContainer.hpp"
417#include "Fragmentation/Summation/SubsetMap.hpp"
418#include "Fragmentation/Summation/Containers/PartialChargesFused.hpp"
419#include "Fragmentation/Summation/Containers/PartialChargesMap.hpp"
420#include "Fragmentation/Summation/SetValues/IndexedPartialCharges.hpp"
421
422ActionState::ptr PotentialFitPartialChargesAction::performCall()
423{
424 // check for selected atoms
425 const World &world = World::getConstInstance();
426 const std::vector<const atom *> selected_atoms = world.getSelectedAtoms();
427 if (selected_atoms.empty()) {
428 STATUS("There are no atoms selected for fitting partial charges to.");
429 return Action::failure;
430 }
431 LOG(3, "There are " << selected_atoms.size() << " selected atoms.");
432
433 /// obtain possible fragments to each selected atom
434 const AtomFragmentsMap &atomfragments = AtomFragmentsMap::getConstInstance();
435 if (!atomfragments.checkCompleteness()) {
436 ELOG(0, "AtomFragmentsMap failed internal consistency check, missing forcekeysets?");
437 return Action::failure;
438 }
439 const std::set<KeySet> fragments =
440 accumulateKeySetsForAtoms( atomfragments.getMap(), selected_atoms);
441 const size_t NoNonHydrogens =
442 std::count_if(selected_atoms.begin(), selected_atoms.end(), isNotHydrogen);
443 if (fragments.size() < NoNonHydrogens) {
444 ELOG(0, "Obtained fewer fragments than there are atoms, has AtomFragments been loaded?");
445 return Action::failure;
446 }
447
448 // reduce given fragments to homologous graphs to avoid multiple fittings
449 detail::KeysetsToGraph_t keyset_graphs;
450 detail::GraphFittedChargeMap_t fittedcharges_per_fragment;
451 getKeySetsToGraphMapping(keyset_graphs, fittedcharges_per_fragment, fragments, atomfragments);
452
453 /// then go through all fragments and get partial charges for each
454 const HomologyContainer &homologies = World::getInstance().getHomologies();
455 const bool status = getPartialChargesForAllGraphs(
456 fittedcharges_per_fragment,
457 homologies,
458 params.radius.get(),
459 params.enforceZeroCharge.get());
460 if (!status)
461 return Action::failure;
462
463 /// obtain average charge for each atom the fitted charges over all its fragments
464 detail::fitted_charges_t fitted_charges;
465// for (std::vector<const atom *>::const_iterator atomiter = selected_atoms.begin();
466// atomiter != selected_atoms.end(); ++atomiter) {
467// const atomId_t walkerid = (*atomiter)->getId();
468// const double average_charge = fitAverageChargeToAtom(
469// *atomiter, atomfragments, keyset_graphs, fittedcharges_per_fragment);
470//
471// if (average_charge != 0.) {
472// LOG(2, "DEBUG: For atom " << **atomiter << " we have an average charge of "
473// << average_charge);
474//
475// fitted_charges.insert( std::make_pair(walkerid, average_charge) );
476// }
477// }
478 {
479 // TODO:: convert the data into boost::fusion::map format
480 std::map<JobId_t, PartialChargesMap_t> PartialCharges_fused;
481 std::vector<IndexSet> indexsets;
482 {
483 JobId_t counter = 0;
484 for (std::set<KeySet>::const_iterator iter = fragments.begin();
485 iter != fragments.end(); ++iter) {
486 const KeySet &currentset = *iter;
487 // place as IndexSet into container
488 {
489 IndexSet tempset;
490 tempset.insert(currentset.begin(), currentset.end());
491 indexsets.push_back(tempset);
492 }
493 const detail::KeysetsToGraph_t::const_iterator graphiter = keyset_graphs.find(currentset);
494 if (graphiter == keyset_graphs.end()) {
495 ELOG(1, "Could not find graph to keyset " << currentset);
496 return Action::failure;
497 }
498 const HomologyGraph &currentgraph = graphiter->second;
499 const detail::GraphFittedChargeMap_t::const_iterator fragmentiter =
500 fittedcharges_per_fragment.find(currentgraph);
501 if (fragmentiter == fittedcharges_per_fragment.end()) {
502 ELOG(1, "Could not find fragment to graph " << currentgraph);
503 return Action::failure;
504 }
505 const PartialNucleiChargeFitter::charges_t &charges = fragmentiter->second;
506 PartialChargesMap_t chargemap;
507 const AtomFragmentsMap::indices_t &full_currentset = atomfragments.getFullKeyset(currentset);
508 IndexedPartialCharges::indices_t indices(full_currentset.begin(), full_currentset.end());
509 IndexedPartialCharges::values_t values(charges.begin(), charges.end());
510 LOG(3, "Inserting " << indices << " with charges " << charges << " into chargemap instance.");
511 boost::fusion::at_key<PartialChargesFused::partial_charges_t>(chargemap) =
512 IndexedPartialCharges(indices, values);
513 PartialCharges_fused.insert( std::make_pair(counter++, chargemap) );
514 }
515 }
516 ASSERT( indexsets.size() == fragments.size(),
517 "PotentialFitPartialChargesAction::performCall() - not all fragments' keysets were created?");
518
519 // prepare index set hierarchy
520 std::map< JobId_t, size_t > IdentityLookup;
521 size_t MaxLevel = std::max_element(fragments.begin(), fragments.end(), keyset_comparator)->size();
522 LOG(3, "The maximum level is " << MaxLevel);
523 size_t max_indices = fragments.size();
524 LOG(3, "There are " << max_indices << " for the selected atoms.");
525 {
526 for (size_t index = 0; index < max_indices; ++index)
527 IdentityLookup.insert( std::make_pair( (JobId_t)index, index ) );
528 }
529 IndexSetContainer::ptr container(new IndexSetContainer(indexsets));
530 SubsetMap::ptr subsetmap(new SubsetMap(*container));
531
532 // and sum up
533 PartialChargesMap_t ZeroInstances;
534 ZeroInstanceInitializer<PartialChargesMap_t> initZeroInstance(ZeroInstances);
535 boost::mpl::for_each<PartialChargesVector_t>(boost::ref(initZeroInstance));
536 //!> results per level of summed up partial charges
537 std::vector<PartialChargesMap_t> Result_PartialCharges_fused(MaxLevel);
538 //!> results per index set in terms of value and contribution
539 std::map<
540 IndexSet::ptr,
541 std::pair<PartialChargesMap_t, PartialChargesMap_t> > Result_perIndexSet_PartialCharges;
542 AllLevelOrthogonalSummator<PartialChargesMap_t> partialchargeSummer(
543 subsetmap,
544 PartialCharges_fused,
545 container->getContainer(),
546 IdentityLookup,
547 Result_PartialCharges_fused,
548 Result_perIndexSet_PartialCharges,
549 ZeroInstances);
550 boost::mpl::for_each<PartialChargesVector_t>(boost::ref(partialchargeSummer));
551
552 // TODO: place results into fitted_charges
553 const IndexedPartialCharges::indexedvalues_t indexed_partial_charges =
554 boost::fusion::at_key<PartialChargesFused::partial_charges_t>(
555 Result_PartialCharges_fused.back()
556 ).getValues();
557 for (IndexedPartialCharges::indexedvalues_t::const_iterator iter = indexed_partial_charges.begin();
558 iter != indexed_partial_charges.end(); ++iter)
559 fitted_charges.insert( std::make_pair( iter->first, iter->second.charge));
560 LOG(3, "Summation has brought forth the following charges per atom index: " << fitted_charges);
561 }
562
563 /// make Particles be used for every atom that was fitted on the same number of graphs
564 detail::GraphIndex_t GraphIndex;
565 size_t index = 0;
566 for (HomologyContainer::const_key_iterator iter = homologies.key_begin();
567 iter != homologies.key_end(); iter = homologies.getNextKey(iter)) {
568 GraphIndex.insert( std::make_pair( *iter, index++));
569 }
570 LOG(2, "DEBUG: There are " << index << " unique graphs in the homology container.");
571
572 // go through every non-hydrogen atom, get all graphs, convert to GraphIndex and store
573 detail::GraphIndices_t GraphIndices;
574 const AtomFragmentsMap::AtomFragmentsMap_t &atommap = atomfragments.getMap();
575 for (std::vector<const atom *>::const_iterator atomiter = selected_atoms.begin();
576 atomiter != selected_atoms.end(); ++atomiter) {
577 // use the non-hydrogen here
578 const atomId_t walkerid = (*atomiter)->getId();
579 const atomId_t surrogateid = getNonHydrogenSurrogate(*atomiter)->getId();
580 if (surrogateid != walkerid)
581 continue;
582 const AtomFragmentsMap::AtomFragmentsMap_t::const_iterator keysetsiter =
583 atommap.find(walkerid);
584 ASSERT(keysetsiter != atommap.end(),
585 "PotentialFitPartialChargesAction::performCall() - we checked already that "
586 +toString(surrogateid)+" should be present!");
587 const AtomFragmentsMap::keysets_t & keysets = keysetsiter->second;
588
589 // go over all fragments associated to this atom
590 detail::AtomsGraphIndices_t AtomsGraphIndices;
591 for (AtomFragmentsMap::keysets_t::const_iterator keysetsiter = keysets.begin();
592 keysetsiter != keysets.end(); ++keysetsiter) {
593 const KeySet &keyset = *keysetsiter;
594 const std::map<KeySet, HomologyGraph>::const_iterator keysetgraphiter =
595 keyset_graphs.find(keyset);
596 ASSERT( keysetgraphiter != keyset_graphs.end(),
597 "PotentialFitPartialChargesAction::performCall() - keyset "+toString(keyset)
598 +" not contained in keyset_graphs.");
599 const HomologyGraph &graph = keysetgraphiter->second;
600 const detail::GraphIndex_t::const_iterator indexiter = GraphIndex.find(graph);
601 ASSERT( indexiter != GraphIndex.end(),
602 "PotentialFitPartialChargesAction::performCall() - graph "+toString(graph)
603 +" not contained in GraphIndex.");
604 AtomsGraphIndices.insert( indexiter->second );
605 }
606
607 GraphIndices.insert( detail::GraphIndices_t::value_type(AtomsGraphIndices, walkerid) );
608
609 LOG(2, "DEBUG: Atom #" << walkerid << "," << *atomiter << ". has graph indices "
610 << AtomsGraphIndices);
611 }
612 // then graphs from non-hydrogen bond partner for all hydrogens
613 for (std::vector<const atom *>::const_iterator atomiter = selected_atoms.begin();
614 atomiter != selected_atoms.end(); ++atomiter) {
615 // use the non-hydrogen here
616 const atomId_t walkerid = (*atomiter)->getId();
617 const atomId_t surrogateid = getNonHydrogenSurrogate((*atomiter))->getId();
618 if (surrogateid == walkerid)
619 continue;
620 detail::GraphIndices_t::right_const_iterator graphiter = GraphIndices.right.find(surrogateid);
621 ASSERT( graphiter != GraphIndices.right.end(),
622 "PotentialFitPartialChargesAction::performCall() - atom #"+toString(surrogateid)
623 +" not contained in GraphIndices.");
624 const detail::AtomsGraphIndices_t &AtomsGraphIndices = graphiter->second;
625 GraphIndices.insert( detail::GraphIndices_t::value_type(AtomsGraphIndices, walkerid) );
626 LOG(2, "DEBUG: Hydrogen #" << walkerid << ", " << *atomiter
627 << ", has graph indices " << AtomsGraphIndices);
628 }
629
630 /// place all fitted charges into ParticleRegistry
631 detail::AtomParticleNames_t atom_particlenames;
632 addToParticleRegistry(
633 ParticleFactory::getConstInstance(),
634 *World::getInstance().getPeriode(),
635 fitted_charges,
636 GraphIndices,
637 atom_particlenames);
638 for (World::AtomSelectionIterator atomiter = World::getInstance().beginAtomSelection();
639 atomiter != World::getInstance().endAtomSelection(); ++atomiter) {
640 atom * const walker = atomiter->second;
641 const atomId_t walkerid = atomiter->first;
642 const detail::GraphIndices_t::right_const_iterator graphiter =
643 GraphIndices.right.find(walkerid);
644 ASSERT( graphiter != GraphIndices.right.end(),
645 "PotentialFitPartialChargesAction::performCall() - cannot find "
646 +toString(walkerid)+" in GraphIndices.");
647 const detail::AtomsGraphIndices_t &graphindex = graphiter->second;
648 const detail::AtomParticleNames_t::const_iterator particlesetiter =
649 atom_particlenames.find(graphindex);
650 ASSERT( particlesetiter != atom_particlenames.end(),
651 "PotentialFitPartialChargesAction::performCall() - cannot find "
652 +toString(graphindex)+" in atom_particlenames.");
653 const std::map<atomicNumber_t, std::string>::const_iterator nameiter =
654 particlesetiter->second.find(walker->getElementNo());
655 ASSERT( nameiter != particlesetiter->second.end(),
656 "PotentialFitPartialChargesAction::performCall() - ");
657 walker->setParticleName(nameiter->second);
658 LOG(1, "INFO: atom " << *walker << " received the following particle "
659 << walker->getParticleName());
660 }
661
662 return Action::success;
663}
664
665ActionState::ptr PotentialFitPartialChargesAction::performUndo(ActionState::ptr _state) {
666 return Action::success;
667}
668
669ActionState::ptr PotentialFitPartialChargesAction::performRedo(ActionState::ptr _state){
670 return Action::success;
671}
672
673bool PotentialFitPartialChargesAction::canUndo() {
674 return false;
675}
676
677bool PotentialFitPartialChargesAction::shouldUndo() {
678 return false;
679}
680/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.