source: src/Actions/PotentialAction/FitPartialChargesAction.cpp@ 0ba27c9

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults 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_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 0ba27c9 was 708ec1, checked in by Frederik Heber <heber@…>, 9 years ago

Modified FitPartialChargesAction to register fitted particles with ParticleRegistry.

  • removed unused parameter "potential-file", superceded by save/parse-particle- parameters.
  • extended fit-partial-charges regression test to use save-particle-parameters.
  • Property mode set to 100644
File size: 8.1 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/filesystem.hpp>
47#include <boost/foreach.hpp>
48#include <algorithm>
49#include <functional>
50#include <iostream>
51#include <string>
52
53#include "Actions/PotentialAction/FitPartialChargesAction.hpp"
54
55#include "Potentials/PartialNucleiChargeFitter.hpp"
56
57#include "Element/element.hpp"
58#include "Element/periodentafel.hpp"
59#include "Fragmentation/Homology/HomologyContainer.hpp"
60#include "Fragmentation/Homology/HomologyGraph.hpp"
61#include "Fragmentation/Summation/SetValues/SamplingGrid.hpp"
62#include "FunctionApproximation/Extractors.hpp"
63#include "Potentials/PartialNucleiChargeFitter.hpp"
64#include "Potentials/Particles/ParticleFactory.hpp"
65#include "Potentials/Particles/ParticleRegistry.hpp"
66#include "Potentials/SerializablePotential.hpp"
67#include "World.hpp"
68
69using namespace MoleCuilder;
70
71// and construct the stuff
72#include "FitPartialChargesAction.def"
73#include "Action_impl_pre.hpp"
74/** =========== define the function ====================== */
75
76inline
77HomologyGraph getFirstGraphwithSpecifiedElements(
78 const HomologyContainer &homologies,
79 const SerializablePotential::ParticleTypes_t &types)
80{
81 ASSERT( !types.empty(),
82 "getFirstGraphwithSpecifiedElements() - charges is empty?");
83 // create charges
84 Fragment::charges_t charges;
85 charges.resize(types.size());
86 std::transform(types.begin(), types.end(),
87 charges.begin(), boost::lambda::_1);
88 // convert into count map
89 Extractors::elementcounts_t counts_per_charge =
90 Extractors::_detail::getElementCounts(charges);
91 ASSERT( !counts_per_charge.empty(),
92 "getFirstGraphwithSpecifiedElements() - charge counts are empty?");
93 LOG(2, "DEBUG: counts_per_charge is " << counts_per_charge << ".");
94 // we want to check each (unique) key only once
95 HomologyContainer::const_key_iterator olditer = homologies.key_end();
96 for (HomologyContainer::const_key_iterator iter =
97 homologies.key_begin(); iter != homologies.key_end();
98 iter = homologies.getNextKey(iter)) {
99 // if it's the same as the old one, skip it
100 if (olditer == iter)
101 continue;
102 else
103 olditer = iter;
104 // if it's a new key, check if every element has the right number of counts
105 Extractors::elementcounts_t::const_iterator countiter = counts_per_charge.begin();
106 for (; countiter != counts_per_charge.end(); ++countiter)
107 if (!(*iter).hasTimesAtomicNumber(
108 static_cast<size_t>(countiter->first),
109 static_cast<size_t>(countiter->second))
110 )
111 break;
112 if( countiter == counts_per_charge.end())
113 return *iter;
114 }
115 return HomologyGraph();
116}
117
118ActionState::ptr PotentialFitPartialChargesAction::performCall() {
119
120 // fragment specifies the homology fragment to use
121 SerializablePotential::ParticleTypes_t fragmentnumbers;
122 {
123 const std::vector<const element *> &fragment = params.fragment.get();
124 std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers),
125 boost::bind(&element::getAtomicNumber, _1));
126 }
127
128 // parse homologies into container
129 HomologyContainer &homologies = World::getInstance().getHomologies();
130 const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragmentnumbers);
131 HomologyContainer::range_t range = homologies.getHomologousGraphs(graph);
132 // for the moment just use the very first fragment
133 if (range.first == range.second) {
134 STATUS("HomologyContainer does not contain specified fragment.");
135 return Action::failure;
136 }
137
138 // average partial charges over all fragments
139 HomologyContainer::const_iterator iter = range.first;
140 if (!iter->second.containsGrids) {
141 STATUS("This HomologyGraph does not contain sampled grids.");
142 return Action::failure;
143 }
144 PartialNucleiChargeFitter::charges_t averaged_charges;
145 averaged_charges.resize(iter->second.fragment.getCharges().size(), 0.);
146 size_t NoFragments = 0;
147 for (;
148 iter != range.second; ++iter, ++NoFragments) {
149 if (!iter->second.containsGrids) {
150 ELOG(2, "This HomologyGraph does not contain sampled grids,\ndid you forget to add '--store-grids 1' to AnalyseFragmentResults.");
151 return Action::failure;
152 }
153 const Fragment &fragment = iter->second.fragment;
154 // const double &energy = iter->second.energy;
155 // const SamplingGrid &charge = iter->second.charge_distribution;
156 const SamplingGrid &potential = iter->second.potential_distribution;
157 if ((potential.level == 0)
158 || ((potential.begin[0] == potential.end[0])
159 && (potential.begin[1] == potential.end[1])
160 && (potential.begin[2] == potential.end[2]))) {
161 ELOG(1, "Sampled grid contains grid made of zero points.");
162 return Action::failure;
163 }
164
165 // then we extract positions from fragment
166 PartialNucleiChargeFitter::positions_t positions;
167 Fragment::positions_t fragmentpositions = fragment.getPositions();
168 positions.reserve(fragmentpositions.size());
169 BOOST_FOREACH( Fragment::position_t pos, fragmentpositions) {
170 positions.push_back( Vector(pos[0], pos[1], pos[2]) );
171 }
172 PartialNucleiChargeFitter fitter(potential, positions, params.radius.get());
173 fitter();
174 PartialNucleiChargeFitter::charges_t return_charges = fitter.getSolutionAsCharges_t();
175 std::transform(
176 return_charges.begin(), return_charges.end(),
177 averaged_charges.begin(),
178 averaged_charges.begin(),
179 std::plus<PartialNucleiChargeFitter::charge_t>());
180 }
181 std::transform(averaged_charges.begin(),averaged_charges.end(),
182 averaged_charges.begin(),
183 std::bind1st(std::multiplies<PartialNucleiChargeFitter::charge_t>(),1./NoFragments)
184 );
185
186 // place all fitted charges into ParticleRegistry
187 const ParticleFactory &factory =
188 const_cast<const ParticleFactory&>(ParticleFactory::getInstance());
189 const periodentafel &periode = *World::getInstance().getPeriode();
190 ASSERT(averaged_charges.size() == fragmentnumbers.size(),
191 "PotentialFitPartialChargesAction::performCall() - charges and elements length mismatch.");
192 for (size_t i=0;i<averaged_charges.size(); ++i) {
193 const std::string name = Particle::findFreeName(periode, fragmentnumbers[i]);
194 LOG(2, "INFO: Adding particle " << name << " for element "
195 << fragmentnumbers[i] << ", charge " << averaged_charges[i]);
196 factory.createInstance(name, fragmentnumbers[i], averaged_charges[i]);
197 }
198
199 // output fitted charges
200 LOG(0, "STATUS: We have fitted the following charges " << averaged_charges
201 << ", averaged over " << NoFragments << " fragments.");
202
203 return Action::success;
204}
205
206ActionState::ptr PotentialFitPartialChargesAction::performUndo(ActionState::ptr _state) {
207 return Action::success;
208}
209
210ActionState::ptr PotentialFitPartialChargesAction::performRedo(ActionState::ptr _state){
211 return Action::success;
212}
213
214bool PotentialFitPartialChargesAction::canUndo() {
215 return false;
216}
217
218bool PotentialFitPartialChargesAction::shouldUndo() {
219 return false;
220}
221/** =========== end of function ====================== */
Note: See TracBrowser for help on using the repository browser.