source: src/Actions/PotentialAction/FitPartialChargesAction.cpp@ 2082637

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 Candidate_v1.7.0 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 2082637 was 2082637, checked in by Frederik Heber <heber@…>, 9 years ago

Added Parse- and SaveParticleParametersAction to parse/save ParticleRegistry.

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