source: src/Actions/PotentialAction/FitFragmentPartialChargesAction.cpp@ eaf08f

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

Added calculation of l2 error of fitted charges against each full_potential level.

  • Property mode set to 100644
File size: 29.8 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2016 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 * FitFragmentPartialChargesAction.cpp
25 *
26 * Created on: Oct 09, 2016
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/FitFragmentPartialChargesAction.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/HomologyGraph.hpp"
68#include "Fragmentation/Summation/Containers/FragmentationResultContainer.hpp"
69#include "Fragmentation/Summation/Containers/PartialChargesFused.hpp"
70#include "Fragmentation/Summation/Containers/PartialChargesMap.hpp"
71#include "Fragmentation/Summation/SetValues/IndexedPartialCharges.hpp"
72#include "Fragmentation/Summation/SetValues/SamplingGrid.hpp"
73#include "Fragmentation/Summation/ZeroInstanceInitializer.hpp"
74#include "FunctionApproximation/Extractors.hpp"
75#include "Potentials/PartialNucleiChargeFitter.hpp"
76#include "Potentials/Particles/ParticleFactory.hpp"
77#include "Potentials/Particles/ParticleRegistry.hpp"
78#include "Potentials/SerializablePotential.hpp"
79#include "World.hpp"
80
81using namespace MoleCuilder;
82
83// and construct the stuff
84#include "FitFragmentPartialChargesAction.def"
85#include "Action_impl_pre.hpp"
86/** =========== define the function ====================== */
87
88namespace detail {
89 typedef std::map<KeySet, HomologyGraph> KeysetsToGraph_t;
90
91 typedef std::map<HomologyGraph, PartialNucleiChargeFitter::charges_t> GraphFittedChargeMap_t;
92
93 typedef std::map<atomId_t, double> fitted_charges_t;
94
95 typedef std::map<HomologyGraph, size_t> GraphIndex_t;
96
97 typedef std::set<size_t> AtomsGraphIndices_t;
98 typedef boost::bimaps::bimap<
99 boost::bimaps::multiset_of<AtomsGraphIndices_t>,
100 atomId_t > GraphIndices_t;
101
102 typedef std::map<std::set<size_t>, std::map<atomicNumber_t, std::string> > AtomParticleNames_t;
103
104 typedef std::map<std::set<size_t>, std::string> GraphToNameMap_t;
105
106 typedef std::map<KeySet, IndexedPartialCharges::values_t> fittedcharges_per_fragment_t;
107
108 typedef std::map<AtomFragmentsMap::indices_t, KeySet> indices_to_keysets_t;
109
110 typedef std::map< std::string, std::pair<double, size_t> > average_charge_map_t;
111};
112
113static void enforceZeroTotalCharge(
114 PartialNucleiChargeFitter::charges_t &_averaged_charges)
115{
116 double charge_sum = 0.;
117 charge_sum = std::accumulate(_averaged_charges.begin(), _averaged_charges.end(), charge_sum);
118 if (fabs(charge_sum) > MYEPSILON) {
119 std::transform(
120 _averaged_charges.begin(), _averaged_charges.end(),
121 _averaged_charges.begin(),
122 boost::bind(std::minus<double>(), _1, charge_sum/_averaged_charges.size()));
123 }
124 charge_sum = 0.;
125 charge_sum = std::accumulate(_averaged_charges.begin(), _averaged_charges.end(), charge_sum);
126 ASSERT( fabs(charge_sum) < MYEPSILON,
127 "enforceZeroTotalCharge() - enforcing neutral net charge failed, "
128 +toString(charge_sum)+" is the remaining net charge.");
129
130 LOG(2, "DEBUG: final charges with net zero charge are " << _averaged_charges);
131}
132
133static
134std::set<KeySet> accumulateKeySetsForAtoms(
135 const AtomFragmentsMap::AtomFragmentsMap_t &_atommap,
136 const std::vector<const atom *> &_selected_atoms)
137{
138 std::set<KeySet> fragments;
139 for (std::vector<const atom *>::const_iterator iter = _selected_atoms.begin();
140 iter != _selected_atoms.end(); ++iter) {
141 const atomId_t atomid = (*iter)->getId();
142 const AtomFragmentsMap::AtomFragmentsMap_t::const_iterator atomiter =
143 _atommap.find(atomid);
144 if ((*iter)->getElementNo() != 1) {
145 if (atomiter == _atommap.end()) {
146 ELOG(2, "There are no fragments associated to " << atomid << ".");
147 continue;
148 }
149 const AtomFragmentsMap::keysets_t &keysets = atomiter->second;
150 LOG(2, "DEBUG: atom " << atomid << " has " << keysets.size() << " fragments.");
151 fragments.insert( keysets.begin(), keysets.end() );
152 } else {
153 LOG(3, "DEBUG: Skipping atom " << atomid << " as it's hydrogen.");
154 }
155 }
156 return fragments;
157}
158
159static
160void getKeySetsToGraphMapping(
161 detail::KeysetsToGraph_t &_keyset_graphs,
162 const std::set<KeySet> &_fragments,
163 const AtomFragmentsMap &_atomfragments)
164{
165 for (std::set<KeySet>::const_iterator fragmentiter = _fragments.begin();
166 fragmentiter != _fragments.end(); ++fragmentiter) {
167 const KeySet &keyset = *fragmentiter;
168 const AtomFragmentsMap::indices_t &forceindices = _atomfragments.getFullKeyset(keyset);
169 ASSERT( !forceindices.empty(),
170 "getKeySetsToGraphMapping() - force keyset to "+toString(keyset)+" is empty.");
171 KeySet forcekeyset;
172 forcekeyset.insert(forceindices.begin(), forceindices.end());
173 forcekeyset.erase(-1);
174 const HomologyGraph graph(forcekeyset);
175 LOG(2, "DEBUG: Associating keyset " << forcekeyset << " with graph " << graph);
176 _keyset_graphs.insert( std::make_pair(keyset, graph) );
177 }
178}
179
180static
181bool getPartialChargesForAllIndexSets(
182 detail::fittedcharges_per_fragment_t &_fittedcharges_per_fragment,
183 const FragmentationResultContainer &_container,
184 const std::set<KeySet> &_fragments,
185 const double _mask_radius,
186 const bool enforceZeroCharge)
187{
188 const std::map<JobId_t, MPQCData> &shortrangedata = _container.getShortRangeResults();
189 const std::map<JobId_t, VMGData> &longrangedata = _container.getLongRangeResults();
190 const KeySetsContainer &keysets = _container.getKeySets();
191
192 std::map<JobId_t, MPQCData>::const_iterator shortiter = shortrangedata.begin();
193 std::map<JobId_t, VMGData>::const_iterator longiter = longrangedata.begin();
194 KeySetsContainer::ArrayOfIntVectors::const_iterator keysetiter = keysets.KeySets.begin();
195 for (; keysetiter != keysets.KeySets.end(); ++keysetiter, ++shortiter, ++longiter) {
196 // check whether its an allowed keyset (atomfragments has keyset, not forcekeyset)
197 KeySet currentset;
198 currentset.insert(keysetiter->begin(), keysetiter->end());
199 if (_fragments.find(currentset) == _fragments.end())
200 continue;
201
202 // obtain positions and sampled potential
203 const Fragment::positions_t &fragmentpositions = shortiter->second.positions;
204 const SamplingGrid &potential = longiter->second.both_sampled_potential;
205 if ((potential.level == 0)
206 || ((potential.begin[0] == potential.end[0])
207 && (potential.begin[1] == potential.end[1])
208 && (potential.begin[2] == potential.end[2]))) {
209 ELOG(1, "Sampled grid contains grid made of zero points.");
210 return 0;
211 }
212
213 // convert std::vector<double> to Vector
214 PartialNucleiChargeFitter::positions_t positions;
215 positions.reserve(fragmentpositions.size());
216 BOOST_FOREACH( Fragment::position_t pos, fragmentpositions) {
217 positions.push_back( Vector(pos[0], pos[1], pos[2]) );
218 }
219
220 // fit charges
221 PartialNucleiChargeFitter fitter(potential, positions, _mask_radius);
222 fitter();
223 PartialNucleiChargeFitter::charges_t return_charges = fitter.getSolutionAsCharges_t();
224 LOG(2, "DEBUG: fitted charges are " << return_charges);
225
226 // make sum of charges zero if desired
227 if (enforceZeroCharge)
228 enforceZeroTotalCharge(return_charges);
229
230 // output status info fitted charges
231 LOG(2, "DEBUG: For fragment " << *keysetiter
232 << " we have fitted the following charges " << return_charges << ".");
233
234 IndexedPartialCharges::values_t values;
235 for (PartialNucleiChargeFitter::charges_t::const_iterator chargeiter = return_charges.begin();
236 chargeiter != return_charges.end(); ++chargeiter) {
237 values.push_back(partial_charge_t(*chargeiter));
238 }
239 _fittedcharges_per_fragment.insert( std::make_pair(currentset, values) );
240 }
241 return true;
242}
243
244static const atom * getNonHydrogenSurrogate(const atom * const _walker)
245{
246 const atom * surrogate = _walker;
247 if (surrogate->getElementNo() == 1) {
248 // it's hydrogen, check its bonding and use its bond partner instead to request
249 // keysets
250 const BondList &ListOfBonds = surrogate->getListOfBonds();
251 if ( ListOfBonds.size() != 1) {
252 ELOG(1, "Solitary hydrogen in atom " << surrogate->getId() << " detected.");
253 return _walker;
254 }
255 surrogate = (*ListOfBonds.begin())->GetOtherAtom(surrogate);
256 }
257 return surrogate;
258}
259
260static void addToParticleRegistry(
261 const ParticleFactory &factory,
262 ParticleRegistry &registry,
263 const periodentafel &periode,
264 const detail::fitted_charges_t &_fitted_charges,
265 const detail::GraphIndices_t &_GraphIndices,
266 detail::AtomParticleNames_t &_atom_particlenames)
267{
268 /// We step here through the atoms and check for all atoms of the
269 /// same element and which belong to the same set of graphs (via the set
270 /// of their unique enumeration indices) then they get the same particle
271 detail::average_charge_map_t average_charge_map;
272 for (detail::fitted_charges_t::const_iterator chargeiter = _fitted_charges.begin();
273 chargeiter != _fitted_charges.end(); ++chargeiter) {
274 const atomId_t &atomid = chargeiter->first;
275 const double &charge = chargeiter->second;
276 const atom * const walker = World::getInstance().getAtom(AtomById(atomid));
277 ASSERT( walker != NULL,
278 "addToParticleRegistry() - atom "+toString(atomid)
279 +" not present in the World?");
280 const detail::GraphIndices_t::right_const_iterator graphiter =
281 _GraphIndices.right.find(atomid);
282 ASSERT(graphiter != _GraphIndices.right.end(),
283 "addToParticleRegistry() - atom #"+toString(atomid)
284 +" not contained in GraphIndices.");
285 const detail::AtomParticleNames_t::iterator nameiter =
286 _atom_particlenames.find(graphiter->second);
287 const atomicNumber_t elementno = walker->getElementNo();
288 std::string name;
289 if ((nameiter != _atom_particlenames.end()) && (nameiter->second.count(elementno))) {
290 name = (nameiter->second)[elementno];
291 detail::average_charge_map_t::iterator averageiter = average_charge_map.find(name);
292 ASSERT( averageiter != average_charge_map.end(),
293 "addToParticleRegistry() - could not find name "+toString(nameiter->second)
294 +" in average charge map.");
295 // add charge to particle
296 averageiter->second.first += charge;
297 ++(averageiter->second.second);
298 LOG(1, "INFO: Adding additional charge " << charge << " to particle " << name << " for atom "
299 << *walker << " with element " << elementno << ".");
300 } else {
301 if (nameiter == _atom_particlenames.end())
302 _atom_particlenames.insert(
303 std::make_pair(graphiter->second, std::map<atomicNumber_t, std::string>()) );
304 name = Particle::findFreeName(periode, elementno);
305 _atom_particlenames[graphiter->second][elementno] = name;
306 LOG(1, "INFO: Adding particle " << name << " for atom "
307 << *walker << " with element " << elementno << " and initial charge "
308 << charge << ".");
309 factory.createInstance(name, elementno, charge);
310#ifndef NDEBUG
311 std::pair< detail::average_charge_map_t::iterator, bool> inserter =
312#endif
313 average_charge_map.insert( std::make_pair(name, std::make_pair(charge,1)) );
314 ASSERT( inserter.second,
315 "addToParticleRegistry() - name "+name+" already present in average charge map?");
316 }
317 }
318
319 // go through map, average and insert average charge into factory
320 for (detail::average_charge_map_t::const_iterator averageiter = average_charge_map.begin();
321 averageiter != average_charge_map.end(); ++averageiter) {
322 const std::string &name = averageiter->first;
323 const double &charge = averageiter->second.first;
324 const size_t &times = averageiter->second.second;
325 ASSERT( times != 0,
326 "addToParticleRegistry() - zero times in average charge map is not allowed.");
327 Particle *particle = registry.getByName(name);
328 particle->charge = charge/(double)times;
329 }
330}
331
332static bool getFullPositions(
333 PartialNucleiChargeFitter::positions_t &positions,
334 PartialNucleiChargeFitter::charges_t &charges)
335{
336 /// \note we cannot use the summed up Fragment here, as the saturation hydrogens
337 /// are in the way and cannot be sorted out properly/in a simple fashion.
338 const World &world = const_cast<const World &>(World::getInstance());
339 const ParticleRegistry &registry = const_cast<const ParticleRegistry &>(ParticleRegistry::getInstance());
340 {
341 const World::ConstAtomComposite &atoms = world.getAllAtoms();
342 positions.reserve(atoms.size());
343 charges.reserve(atoms.size());
344 for (World::ConstAtomComposite::const_iterator iter = atoms.begin();
345 iter != atoms.end(); ++iter) {
346 // set position for this atom
347 const Vector &pos = (*iter)->getPosition();
348
349 // use the fitted charges
350 const atomId_t atomid = (*iter)->getId();
351 std::string particlename = (*iter)->getParticleName();
352 if (particlename.empty())
353 particlename = (*iter)->getElement().getSymbol();
354 if (registry.isPresentByName(particlename)) {
355 const Particle * const particle = registry.getByName(particlename);
356 LOG(3, "DEBUG: Using implicit charge " << particle->charge << " of particle "
357 << particle->getName() << " for atom " << atomid);
358 positions.push_back((1./AtomicLengthToAngstroem)*pos);
359 charges.push_back(particle->charge);
360 } else {
361 ELOG(1, "Could not find fitted charge for " << particlename);
362 return false;
363 }
364 }
365 }
366 return true;
367}
368
369
370static bool isNotHydrogen(const atom * const _atom)
371{
372 return (_atom->getElementNo() != (atomicNumber_t) 1);
373}
374
375static struct KeySetSizeComp {
376 bool operator() (const KeySet &a, const KeySet &b) { return a.size()<b.size(); }
377} keyset_comparator;
378
379#include <boost/fusion/sequence.hpp>
380#include <boost/mpl/for_each.hpp>
381
382#include "Fragmentation/Summation/AllLevelOrthogonalSummator.hpp"
383#include "Fragmentation/Summation/IndexSet.hpp"
384#include "Fragmentation/Summation/IndexSetContainer.hpp"
385#include "Fragmentation/Summation/SubsetMap.hpp"
386#include "Fragmentation/Summation/Containers/PartialChargesFused.hpp"
387#include "Fragmentation/Summation/Containers/PartialChargesMap.hpp"
388#include "Fragmentation/Summation/SetValues/IndexedPartialCharges.hpp"
389
390ActionState::ptr PotentialFitFragmentPartialChargesAction::performCall()
391{
392 // check for selected atoms
393 const World &world = World::getConstInstance();
394 const std::vector<const atom *> selected_atoms = world.getSelectedAtoms();
395 if (selected_atoms.empty()) {
396 STATUS("There are no atoms selected for fitting partial charges to.");
397 return Action::failure;
398 }
399 LOG(3, "There are " << selected_atoms.size() << " selected atoms.");
400
401 /// obtain possible fragments to each selected atom
402 const AtomFragmentsMap &atomfragments = AtomFragmentsMap::getConstInstance();
403 if (!atomfragments.checkCompleteness()) {
404 ELOG(0, "AtomFragmentsMap failed internal consistency check, missing forcekeysets?");
405 return Action::failure;
406 }
407 const std::set<KeySet> fragments =
408 accumulateKeySetsForAtoms( atomfragments.getMap(), selected_atoms);
409 const size_t NoNonHydrogens =
410 std::count_if(selected_atoms.begin(), selected_atoms.end(), isNotHydrogen);
411 if (fragments.size() < NoNonHydrogens) {
412 ELOG(0, "Obtained fewer fragments than there are atoms, has AtomFragments been loaded?");
413 return Action::failure;
414 }
415
416 // get results from container
417 FragmentationResultContainer& resultscontainer = FragmentationResultContainer::getInstance();
418#if defined(HAVE_JOBMARKET) && defined(HAVE_VMG)
419 const bool DoLongrange = resultscontainer.areFullRangeResultsPresent();
420 if (!DoLongrange) {
421 ELOG(1, "FragmentationResultContainer does not contain long-range results, cannot fit partial charges.");
422 return Action::failure;
423 }
424
425 if (resultscontainer.getKeySets().KeySets.empty()) {
426 STATUS("There are no results in the container.");
427 return Action::failure;
428 }
429
430 // reduce given fragments to homologous graphs for later lookup
431 detail::KeysetsToGraph_t keyset_graphs;
432 detail::fittedcharges_per_fragment_t fittedcharges_per_fragment;
433 getKeySetsToGraphMapping(keyset_graphs, fragments, atomfragments);
434
435 /// then go through all fragments and get partial charges for each
436 const bool status = getPartialChargesForAllIndexSets(
437 fittedcharges_per_fragment,
438 resultscontainer,
439 fragments,
440 params.radius.get(),
441 params.enforceZeroCharge.get());
442 if (!status)
443 return Action::failure;
444
445 /// obtain average charge for each atom the fitted charges over all its fragments
446 detail::fitted_charges_t fitted_charges;
447 {
448 // place all into boost::fusion map for summation
449 std::map<JobId_t, PartialChargesMap_t> PartialCharges_fused;
450 std::vector<IndexSet> indexsets;
451 JobId_t counter = 0;
452 for (detail::fittedcharges_per_fragment_t::const_iterator iter = fittedcharges_per_fragment.begin();
453 iter != fittedcharges_per_fragment.end(); ++iter) {
454 const KeySet &currentset = iter->first;
455 // place as IndexSet into container
456 {
457 IndexSet tempset;
458 tempset.insert(currentset.begin(), currentset.end());
459 indexsets.push_back(tempset);
460 }
461 LOG(3, "Inserting " << iter->first << " with charges " << iter->second << " into chargemap instance.");
462 PartialChargesMap_t chargemap;
463 const AtomFragmentsMap::indices_t &full_currentset = atomfragments.getFullKeyset(currentset);
464 IndexedPartialCharges::indices_t indices(full_currentset.begin(), full_currentset.end());
465 boost::fusion::at_key<PartialChargesFused::partial_charges_t>(chargemap) =
466 IndexedPartialCharges(full_currentset, iter->second);
467 PartialCharges_fused.insert( std::make_pair(counter++, chargemap) );
468 }
469 ASSERT( counter == fragments.size(),
470 "PotentialFitPartialChargesAction::performCall() - not all fragments' keysets were created?");
471 ASSERT( indexsets.size() == fragments.size(),
472 "PotentialFitPartialChargesAction::performCall() - not all fragments' keysets were created?");
473
474 // prepare index set hierarchy
475 std::map< JobId_t, size_t > IdentityLookup;
476 size_t MaxLevel = std::max_element(fragments.begin(), fragments.end(), keyset_comparator)->size();
477 LOG(3, "The maximum level is " << MaxLevel);
478 size_t max_indices = fragments.size();
479 LOG(3, "There are " << max_indices << " keysets for the selected atoms.");
480 {
481 for (size_t index = 0; index < max_indices; ++index)
482 IdentityLookup.insert( std::make_pair( (JobId_t)index, index ) );
483 }
484 IndexSetContainer::ptr container(new IndexSetContainer(indexsets));
485 SubsetMap::ptr subsetmap(new SubsetMap(*container));
486
487 // and sum up
488 PartialChargesMap_t ZeroInstances;
489 ZeroInstanceInitializer<PartialChargesMap_t> initZeroInstance(ZeroInstances);
490 boost::mpl::for_each<PartialChargesVector_t>(boost::ref(initZeroInstance));
491 //!> results per level of summed up partial charges
492 std::vector<PartialChargesMap_t> Result_PartialCharges_fused(MaxLevel);
493 //!> results per index set in terms of value and contribution
494 std::map<
495 IndexSet::ptr,
496 std::pair<PartialChargesMap_t, PartialChargesMap_t> > Result_perIndexSet_PartialCharges;
497 AllLevelOrthogonalSummator<PartialChargesMap_t> partialchargeSummer(
498 subsetmap,
499 PartialCharges_fused,
500 container->getContainer(),
501 IdentityLookup,
502 Result_PartialCharges_fused,
503 Result_perIndexSet_PartialCharges,
504 ZeroInstances);
505 boost::mpl::for_each<PartialChargesVector_t>(boost::ref(partialchargeSummer));
506
507 // TODO: place results into fitted_charges
508 const IndexedPartialCharges::indexedvalues_t indexed_partial_charges =
509 boost::fusion::at_key<PartialChargesFused::partial_charges_t>(
510 Result_PartialCharges_fused.back()
511 ).getValues();
512 for (IndexedPartialCharges::indexedvalues_t::const_iterator iter = indexed_partial_charges.begin();
513 iter != indexed_partial_charges.end(); ++iter)
514 fitted_charges.insert( std::make_pair( iter->first, iter->second.charge));
515 LOG(3, "Summation has brought forth the following charges per atom index: " << fitted_charges);
516 }
517
518 // make a unique list of the present HomologyGraphs
519 typedef std::set<HomologyGraph> unique_graphs_t;
520 unique_graphs_t unique_graphs;
521 for (detail::KeysetsToGraph_t::const_iterator keysetiter = keyset_graphs.begin();
522 keysetiter != keyset_graphs.end(); ++keysetiter)
523 unique_graphs.insert(keysetiter->second);
524
525 /// make Particles be used for every atom that was fitted on the same number of graphs
526 detail::GraphIndex_t GraphIndex;
527 size_t index = 0;
528 for (unique_graphs_t::const_iterator graphiter = unique_graphs.begin();
529 graphiter != unique_graphs.end(); ++graphiter) {
530 GraphIndex.insert( std::make_pair( *graphiter, index++));
531 }
532 LOG(2, "DEBUG: There are " << index << " unique graphs in the homology container.");
533 ASSERT( index == unique_graphs.size(),
534 "PotentialFitFragmentPartialChargesAction::performCall() - could not enumerate all unique graphs?");
535
536 // go through every non-hydrogen atom, get all graphs, convert to GraphIndex and store
537 detail::GraphIndices_t GraphIndices;
538 const AtomFragmentsMap::AtomFragmentsMap_t &atommap = atomfragments.getMap();
539 for (std::vector<const atom *>::const_iterator atomiter = selected_atoms.begin();
540 atomiter != selected_atoms.end(); ++atomiter) {
541 // use the non-hydrogen here
542 const atomId_t walkerid = (*atomiter)->getId();
543 const atomId_t surrogateid = getNonHydrogenSurrogate(*atomiter)->getId();
544 if (surrogateid != walkerid)
545 continue;
546 const AtomFragmentsMap::AtomFragmentsMap_t::const_iterator keysetsiter =
547 atommap.find(walkerid);
548 ASSERT(keysetsiter != atommap.end(),
549 "PotentialFitFragmentPartialChargesAction::performCall() - we checked already that "
550 +toString(surrogateid)+" should be present!");
551 const AtomFragmentsMap::keysets_t & keysets = keysetsiter->second;
552
553 // go over all fragments associated to this atom
554 detail::AtomsGraphIndices_t AtomsGraphIndices;
555 for (AtomFragmentsMap::keysets_t::const_iterator keysetsiter = keysets.begin();
556 keysetsiter != keysets.end(); ++keysetsiter) {
557 const KeySet &keyset = *keysetsiter;
558 const std::map<KeySet, HomologyGraph>::const_iterator keysetgraphiter =
559 keyset_graphs.find(keyset);
560 ASSERT( keysetgraphiter != keyset_graphs.end(),
561 "PotentialFitFragmentPartialChargesAction::performCall() - keyset "+toString(keyset)
562 +" not contained in keyset_graphs.");
563 const HomologyGraph &graph = keysetgraphiter->second;
564 const detail::GraphIndex_t::const_iterator indexiter = GraphIndex.find(graph);
565 ASSERT( indexiter != GraphIndex.end(),
566 "PotentialFitFragmentPartialChargesAction::performCall() - graph "+toString(graph)
567 +" not contained in GraphIndex.");
568 AtomsGraphIndices.insert( indexiter->second );
569 }
570
571 GraphIndices.insert( detail::GraphIndices_t::value_type(AtomsGraphIndices, walkerid) );
572
573 LOG(2, "DEBUG: Atom #" << walkerid << "," << **atomiter << ". has graph indices "
574 << AtomsGraphIndices);
575 }
576 // then graphs from non-hydrogen bond partner for all hydrogens
577 for (std::vector<const atom *>::const_iterator atomiter = selected_atoms.begin();
578 atomiter != selected_atoms.end(); ++atomiter) {
579 // use the non-hydrogen here
580 const atomId_t walkerid = (*atomiter)->getId();
581 const atomId_t surrogateid = getNonHydrogenSurrogate((*atomiter))->getId();
582 if (surrogateid == walkerid)
583 continue;
584 detail::GraphIndices_t::right_const_iterator graphiter = GraphIndices.right.find(surrogateid);
585 ASSERT( graphiter != GraphIndices.right.end(),
586 "PotentialFitFragmentPartialChargesAction::performCall() - atom #"+toString(surrogateid)
587 +" not contained in GraphIndices.");
588 const detail::AtomsGraphIndices_t &AtomsGraphIndices = graphiter->second;
589 GraphIndices.insert( detail::GraphIndices_t::value_type(AtomsGraphIndices, walkerid) );
590 LOG(2, "DEBUG: Hydrogen #" << walkerid << ", " << **atomiter
591 << ", has graph indices " << AtomsGraphIndices);
592 }
593
594 /// place all fitted (and now averaged) charges into ParticleRegistry
595 detail::AtomParticleNames_t atom_particlenames;
596 addToParticleRegistry(
597 ParticleFactory::getConstInstance(),
598 ParticleRegistry::getInstance(),
599 *World::getInstance().getPeriode(),
600 fitted_charges,
601 GraphIndices,
602 atom_particlenames);
603
604 for (World::AtomSelectionIterator atomiter = World::getInstance().beginAtomSelection();
605 atomiter != World::getInstance().endAtomSelection(); ++atomiter) {
606 atom * const walker = atomiter->second;
607 const atomId_t walkerid = atomiter->first;
608 const detail::GraphIndices_t::right_const_iterator graphiter =
609 GraphIndices.right.find(walkerid);
610 ASSERT( graphiter != GraphIndices.right.end(),
611 "PotentialFitFragmentPartialChargesAction::performCall() - cannot find "
612 +toString(walkerid)+" in GraphIndices.");
613 const detail::AtomsGraphIndices_t &graphindex = graphiter->second;
614 const detail::AtomParticleNames_t::const_iterator particlesetiter =
615 atom_particlenames.find(graphindex);
616 ASSERT( particlesetiter != atom_particlenames.end(),
617 "PotentialFitFragmentPartialChargesAction::performCall() - cannot find "
618 +toString(graphindex)+" in atom_particlenames.");
619 const std::map<atomicNumber_t, std::string>::const_iterator nameiter =
620 particlesetiter->second.find(walker->getElementNo());
621 ASSERT( nameiter != particlesetiter->second.end(),
622 "PotentialFitFragmentPartialChargesAction::performCall() - ");
623 walker->setParticleName(nameiter->second);
624 LOG(1, "INFO: atom " << *walker << " received the following particle "
625 << walker->getParticleName());
626 }
627
628 // compute the global error using the full solutions
629 {
630 FragmentationResultContainer::longrangedata_t longrangeData = resultscontainer.getLongRangeResults();
631 FragmentationResultContainer::longrangedata_t::iterator iter = longrangeData.end();
632 const size_t MaxLevel = std::max_element(fragments.begin(), fragments.end(), keyset_comparator)->size();
633 std::advance(iter, -MaxLevel);
634 FragmentationResultContainer::longrangedata_t::iterator remove_iter = iter;
635 std::vector<VMGData> fullsolutionData;
636 for (; iter != longrangeData.end(); ++iter)
637 fullsolutionData.push_back(iter->second);
638 if (longrangeData.size() > 1) // when there's just a single fragment, it corresponds to full solution
639 longrangeData.erase(remove_iter, longrangeData.end());
640
641 // extraction of all positions is not easy as we cannot use the summed up
642 // fragments due to saturated hydrogens. Also, we cannot easily removed the
643 // non-selected atoms from the set. Hence, the error is always calculated
644 // against all atoms.
645 PartialNucleiChargeFitter::positions_t fullpositions;
646 PartialNucleiChargeFitter::charges_t fullcharges;
647 getFullPositions(fullpositions, fullcharges);
648 LOG(4, "DEBUG: Full positions are " << fullpositions);
649 LOG(4, "DEBUG: Full (fitted) charges are " << fullcharges);
650
651 for (size_t i=0;i<fullsolutionData.size();++i) {
652 // get positions and potential
653 const SamplingGrid &fullpotential = fullsolutionData[i].both_sampled_potential;
654 if ((fullpotential.level == 0)
655 || ((fullpotential.begin[0] == fullpotential.end[0])
656 && (fullpotential.begin[1] == fullpotential.end[1])
657 && (fullpotential.begin[2] == fullpotential.end[2]))) {
658 ELOG(1, "Sampled grid contains grid made of zero points.");
659 return Action::failure;
660 }
661
662 // set up matrix and calculate residual
663 PartialNucleiChargeFitter fitter(fullpotential, fullpositions, params.radius.get());
664 if (!fitter.setCharges(fullcharges)) {
665 ELOG(1, "fullcharges and fullpositions do not coincide in size, internal error.");
666 return Action::failure;
667 }
668 VectorContent residuum = fitter.calculateResiduum();
669
670 LOG(1, "INFO: At order " << i+1 << " we have an error of " << residuum.Norm());
671 }
672 }
673
674 return Action::success;
675#else
676 ELOG(0, "Long-range support not compiled in, cannot fit partial charges to fragment's potential grids.");
677 return Action::failure;
678#endif
679}
680
681ActionState::ptr PotentialFitFragmentPartialChargesAction::performUndo(ActionState::ptr _state) {
682 return Action::success;
683}
684
685ActionState::ptr PotentialFitFragmentPartialChargesAction::performRedo(ActionState::ptr _state){
686 return Action::success;
687}
688
689bool PotentialFitFragmentPartialChargesAction::canUndo() {
690 return false;
691}
692
693bool PotentialFitFragmentPartialChargesAction::shouldUndo() {
694 return false;
695}
696/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.