source: src/Jobs/InterfaceVMGJob.cpp@ 48d20d

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 48d20d was e2925fd, checked in by Frederik Heber <heber@…>, 12 years ago

Split long-range calculations into two parts to overcome E-N-potential problems.

The general problem is that smeared-out nuclei charges cannot interact with
electron charge densities as they always overlap, hence we always make a large
error. The idea then is - as the potential energy is symmetric both
densities - to flip from N-E to E-N, i.\,e. to take the electron potential and
evaluate at nuclei positions instead of smeared-out nuclei charges with
eletronic charge distribution. However, then we need to make two calculations
for the four contributions: E-E, E-N and N-N, N-E (=E-N).

  • new enums SampleParticles_t eventually tells InterfaceVMGJob whether to sample the nuclei charges onto the grid or not.
  • TreatGrid_t tells InterfaceVMGJob whether to actually add the electronic charge onto the grid (this was added but is actually not required anymore).
  • FragmentationAutomationAction::performCall() now creates twice as many long-range jobs. This requires two variables in VMGData for storing integrated long-range energy: electron_long, nuclei_long, as both calculations are combined into a single VMGData instance per fragment.
  • Summation of long-range contributions is split into three instead of formerly two parts: electron (E-E), nuclei (N-N), and mixed (E-N). This allows to easierly check their cancellation. This needs new member in fusion map and name in printKeyNames.
  • naturally, the enums have to be passed a long way: VMGFragmentController, VMGJob, VMGData.
  • VMGData now has serialization version 1 due to new entry.
  • we enhanced documentation in FragmentationLongRangeResults::operator()() of how and what is summed per level.
  • FIX: InterfaceVMGJob::ImportRightHandSide() subtracted grid instead of adding it. Now, we set correct sign of electron charge distribution in MPQC.
  • TESTFIX: Regression test AnalyseFragmentResults now has short- and long-range part. Long-range part is only diff'ed when the compiled code has the capabilities.
  • Property mode set to 100644
File size: 12.6 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. 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 * InterfaceVMGJob.cpp
25 *
26 * Created on: 10.06.2012
27 * Author: Frederik Heber
28 */
29
30#ifdef HAVE_CONFIG_H
31#include <config.h>
32#endif
33
34#ifdef HAVE_MPI
35#include "mpi.h"
36#endif
37
38#include "base/vector.hpp"
39#include "base/math.hpp"
40#include "comm/comm.hpp"
41#include "grid/grid.hpp"
42#include "grid/multigrid.hpp"
43#include "units/particle/comm_mpi_particle.hpp"
44#include "units/particle/interpolation.hpp"
45#include "units/particle/linked_cell_list.hpp"
46#include "mg.hpp"
47
48#include "InterfaceVMGJob.hpp"
49
50#include "CodePatterns/MemDebug.hpp"
51
52#include <cmath>
53#include <iostream>
54#include <limits>
55
56#include "CodePatterns/Log.hpp"
57
58#include "Jobs/WindowGrid_converter.hpp"
59
60using namespace VMG;
61using VMGInterfaces::InterfaceVMGJob;
62
63InterfaceVMGJob::InterfaceVMGJob(const SamplingGrid &_sampled_input,
64 VMGData &_returndata,
65 const std::vector< std::vector<double> > &_particle_positions,
66 const std::vector< double > &_particle_charges,
67 VMG::Boundary boundary,
68 int levelMin,
69 int levelMax,
70 const VMG::Vector &_box_begin,
71 vmg_float _box_end,
72 const int& near_field_cells,
73 const ImportParticles_t _ImportParticles,
74 const bool _DoPrintDebug,
75 int coarseningSteps,
76 double alpha) :
77 VMG::Interface(boundary, levelMin, levelMax,
78 _box_begin, _box_end, coarseningSteps, alpha),
79 spl(near_field_cells, Extent(MaxLevel()).MeshWidth().Max()),
80 sampled_input(_sampled_input),
81 returndata(_returndata),
82 level(levelMax),
83 ImportParticles(_ImportParticles),
84 DoPrintDebug(_DoPrintDebug)
85{
86 for (size_t i=0;i<3;++i) {
87 box_begin[i] = _box_begin[i];
88 box_end[i] = _box_end;
89 }
90 std::vector< std::vector<double> >::const_iterator positer = _particle_positions.begin();
91 std::vector<double>::const_iterator chargeiter = _particle_charges.begin();
92 double pos[3];
93 for (; positer != _particle_positions.end(); ++positer, ++chargeiter) {
94 ASSERT( (*positer).size() == 3,
95 "InterfaceVMGJob::InterfaceVMGJob() - particle "
96 +toString(distance(_particle_positions.begin(), positer))+" has not exactly 3 coordinates.");
97 for (size_t i=0;i<3;++i)
98 pos[i] = (*positer)[i];
99 particles.push_back(Particle::Particle(pos, *chargeiter));
100 }
101}
102
103void InterfaceVMGJob::ImportRightHandSide(Multigrid& multigrid)
104{
105 Index i;
106 Vector pos;
107 // VMG::TempGrid *temp_grid = new VMG::TempGrid(129, 0, 0., 1.);
108
109 Grid& grid = multigrid(multigrid.MaxLevel());
110 grid.Clear();
111 //grid.ClearBoundary(); // we don't have a boundary under periodic boundary conditions
112
113 // print debugging info on grid size
114 LOG(1, "INFO: Mesh has extent " << grid.Extent().MeshWidth() << ".");
115 const int gridpoints = pow(2, level);
116 LOG(1, "INFO: gridpoints on finest level are " << gridpoints << ".");
117 LOG(1, "INFO: "
118 << "X in [" << grid.Local().Begin().X() << "," << grid.Local().End().X() << "],"
119 << "Y in [" << grid.Local().Begin().Y() << "," << grid.Local().End().Y() << "],"
120 << "Z in [" << grid.Local().Begin().Z() << "," << grid.Local().End().Z() << "].");
121
122 /// 1. assign nuclei as smeared-out charges to the grid
123
124 /*
125 * Charge assignment on the grid
126 */
127 Particle::CommMPI& comm = *dynamic_cast<Particle::CommMPI*>(MG::GetComm());
128 Grid& particle_grid = comm.GetParticleGrid();
129 particle_grid.Clear();
130
131 // distribute particles
132 particles.clear();
133 comm.CommParticles(grid, particles);
134
135 assert(particle_grid.Global().LocalSize().IsComponentwiseGreater(
136 VMG::MG::GetFactory().GetObjectStorageVal<int>("PARTICLE_NEAR_FIELD_CELLS")));
137
138 if (ImportParticles == DoImportParticles) {
139 // create smeared-out particle charges on particle_grid via splines
140 LOG(1, "INFO: Creating particle grid for " << particles.size() << " particles.");
141 for (std::list<Particle::Particle>::iterator iter = particles.begin();
142 iter != particles.end(); ++iter) {
143 LOG(2, "DEBUG: Current particle is at " << (*iter).Pos()
144 << " with charge " << (*iter).Charge() << ".");
145 spl.SetSpline(particle_grid, *iter);
146 }
147 }
148
149 // Communicate charges over halo
150 comm.CommFromGhosts(particle_grid);
151
152 if (DoPrintDebug) {
153 // print nuclei grid to vtk
154 comm.PrintGrid(particle_grid, "Sampled Nuclei Density");
155 }
156
157 // add sampled electron charge density onto grid
158 WindowGrid_converter::addWindowOntoGrid(
159 grid,
160 sampled_input,
161 1.);
162
163 if (DoPrintDebug) {
164 // print electron grid to vtk
165 comm.PrintGrid(grid, "Sampled Electron Density");
166 }
167
168 // add particle_grid onto grid
169 for (int i=0; i<grid.Local().Size().X(); ++i)
170 for (int j=0; j<grid.Local().Size().Y(); ++j)
171 for (int k=0; k<grid.Local().Size().Z(); ++k)
172 grid(grid.Local().Begin().X() + i,
173 grid.Local().Begin().Y() + j,
174 grid.Local().Begin().Z() + k) = 4.0 * VMG::Math::pi * (
175 grid(grid.Local().Begin().X() + i,
176 grid.Local().Begin().Y() + j,
177 grid.Local().Begin().Z() + k) +
178 particle_grid.GetVal(particle_grid.Local().Begin().X() + i,
179 particle_grid.Local().Begin().Y() + j,
180 particle_grid.Local().Begin().Z() + k));
181
182 // calculate sum over grid times h^3 as check, should be roughly zero
183 const double element_volume = grid.Extent().MeshWidth().Product();
184 double charge_sum = 0.0;
185 for (Grid::iterator grid_iter = grid.Iterators().Local().Begin();
186 grid_iter != grid.Iterators().Local().End();
187 ++grid_iter)
188 charge_sum += grid.GetVal(*grid_iter);
189 charge_sum = element_volume * comm.GlobalSum(charge_sum);
190 comm.PrintStringOnce("Grid charge integral: %e", charge_sum/(4.0 * VMG::Math::pi));
191
192 if (DoPrintDebug) {
193 // print total grid to vtk
194 comm.PrintGrid(grid, "Total Charge Density");
195 }
196
197// delete temp_grid;
198}
199
200void InterfaceVMGJob::ExportSolution(Grid& grid)
201{
202 /// sample the obtained potential to evaluate with the electron charge density
203
204 // grid now contains the sough-for potential
205 //Comm& comm = *MG::GetComm();
206 Particle::CommMPI& comm = *dynamic_cast<Particle::CommMPI*>(MG::GetComm());
207
208 const Index begin_local = grid.Global().LocalBegin() - grid.Local().HaloSize1();
209 Index i;
210
211 if (DoPrintDebug) {
212 // print output grid to vtk
213 comm.PrintGrid(grid, "Potential Solution");
214 }
215
216 // obtain sampled potential from grid
217 returndata.sampled_potential.setWindow(
218 box_begin,
219 box_end
220 );
221 WindowGrid_converter::addGridOntoWindow(
222 grid,
223 returndata.sampled_potential,
224 +1.
225 );
226
227 // calculate integral over potential as long-range energy contribution
228 const double element_volume =
229 grid.Extent().MeshWidth().X() * grid.Extent().MeshWidth().Y() * grid.Extent().MeshWidth().Z();
230 Grid::iterator grid_iter;
231 double potential_sum = 0.0;
232 for (grid_iter=grid.Iterators().Local().Begin(); grid_iter!=grid.Iterators().Local().End(); ++grid_iter)
233 potential_sum += grid.GetVal(*grid_iter);
234 potential_sum = element_volume * comm.GlobalSum(potential_sum);
235 comm.PrintStringOnce("Grid potential sum: %e", potential_sum);
236
237 {
238 Grid::iterator grid_iter = grid.Iterators().Local().Begin();
239 comm.PrintStringOnce("Grid potential at (0,0,0): %e", grid.GetVal(*grid_iter));
240 }
241
242 //Particle::CommMPI& comm = *dynamic_cast<Particle::CommMPI*>(MG::GetComm()); returndata.e_long = potential_sum;
243
244 /// Calculate potential energy of nuclei
245
246 vmg_float e = 0.0;
247 vmg_float e_long = 0.0;
248 vmg_float e_self = 0.0;
249 vmg_float e_short_peak = 0.0;
250 vmg_float e_short_spline = 0.0;
251
252 Factory& factory = MG::GetFactory();
253
254 /*
255 * Get parameters and arrays
256 */
257 const vmg_int& near_field_cells = factory.GetObjectStorageVal<int>("PARTICLE_NEAR_FIELD_CELLS");
258 const vmg_int& interpolation_degree = factory.GetObjectStorageVal<int>("PARTICLE_INTERPOLATION_DEGREE");
259
260 Particle::Interpolation ip(interpolation_degree);
261
262 const vmg_float r_cut = near_field_cells * grid.Extent().MeshWidth().Max();
263
264 /*
265 * Copy potential values to a grid with sufficiently large halo size.
266 * This may be optimized in future.
267 * The parameters of this grid have been set in the import step.
268 */
269 Grid& particle_grid = comm.GetParticleGrid();
270
271 for (i.X()=0; i.X()<grid.Local().Size().X(); ++i.X())
272 for (i.Y()=0; i.Y()<grid.Local().Size().Y(); ++i.Y())
273 for (i.Z()=0; i.Z()<grid.Local().Size().Z(); ++i.Z())
274 particle_grid(i + particle_grid.Local().Begin()) = grid.GetVal(i + grid.Local().Begin());
275
276 comm.CommToGhosts(particle_grid);
277
278 /*
279 * Compute potentials
280 */
281 Particle::LinkedCellList lc(particles, near_field_cells, grid);
282 Particle::LinkedCellList::iterator p1, p2;
283 Grid::iterator iter;
284
285 comm.CommLCListToGhosts(lc);
286
287 for (int i=lc.Local().Begin().X(); i<lc.Local().End().X(); ++i)
288 for (int j=lc.Local().Begin().Y(); j<lc.Local().End().Y(); ++j)
289 for (int k=lc.Local().Begin().Z(); k<lc.Local().End().Z(); ++k) {
290
291 if (lc(i,j,k).size() > 0)
292 ip.ComputeCoefficients(particle_grid, Index(i,j,k) - lc.Local().Begin() + particle_grid.Local().Begin());
293
294 for (p1=lc(i,j,k).begin(); p1!=lc(i,j,k).end(); ++p1) {
295
296 // Interpolate long-range part of potential and electric field
297 ip.Evaluate(**p1);
298
299 // Subtract self-induced potential
300 (*p1)->Pot() -= (*p1)->Charge() * spl.GetAntiDerivativeAtZero();
301
302 e_long += 0.5 * (*p1)->Charge() * ip.EvaluatePotentialLR(**p1);
303 e_self += 0.5 * (*p1)->Charge() * (*p1)->Charge() * spl.GetAntiDerivativeAtZero();
304
305 for (int dx=-1*near_field_cells; dx<=near_field_cells; ++dx)
306 for (int dy=-1*near_field_cells; dy<=near_field_cells; ++dy)
307 for (int dz=-1*near_field_cells; dz<=near_field_cells; ++dz) {
308
309 for (p2=lc(i+dx,j+dy,k+dz).begin(); p2!=lc(i+dx,j+dy,k+dz).end(); ++p2)
310
311 if (*p1 != *p2) {
312
313 const Vector dir = (*p1)->Pos() - (*p2)->Pos();
314 const vmg_float length = dir.Length();
315
316 if (length < r_cut) {
317
318 (*p1)->Pot() += (*p2)->Charge() / length * (1.0 + spl.EvaluatePotential(length));
319 (*p1)->Field() += (*p2)->Charge() * dir * spl.EvaluateField(length);
320
321 e_short_peak += 0.5 * (*p1)->Charge() * (*p2)->Charge() / length;
322 e_short_spline += 0.5 * (*p1)->Charge() * (*p2)->Charge() / length * spl.EvaluatePotential(length);
323 }
324 }
325 }
326 }
327 }
328
329 /* Remove average force term */
330 if (!particles.empty()) {
331 Vector average_force = 0.0;
332 for (std::list<Particle::Particle>::const_iterator iter=particles.begin(); iter!=particles.end(); ++iter)
333 average_force += iter->Charge() * iter->Field();
334 const vmg_int& npl = MG::GetFactory().GetObjectStorageVal<vmg_int>("PARTICLE_NUM_LOCAL");
335 const vmg_int num_particles_global = comm.GlobalSum(npl);
336 average_force /= num_particles_global;
337 comm.GlobalSumArray(average_force.vec(), 3);
338 for (std::list<Particle::Particle>::iterator iter=particles.begin(); iter!=particles.end(); ++iter)
339 iter->Field() -= average_force / iter->Charge();
340 }
341
342 comm.CommParticlesBack(particles);
343
344 vmg_float* q = factory.GetObjectStorageArray<vmg_float>("PARTICLE_CHARGE_ARRAY");
345 const vmg_int& num_particles_local = factory.GetObjectStorageVal<vmg_int>("PARTICLE_NUM_LOCAL");
346 const vmg_float* p = factory.GetObjectStorageArray<vmg_float>("PARTICLE_POTENTIAL_ARRAY");
347// const vmg_float* f = factory.GetObjectStorageArray<vmg_float>("PARTICLE_FIELD_ARRAY");
348
349
350 e_long = comm.GlobalSumRoot(e_long);
351 e_short_peak = comm.GlobalSumRoot(e_short_peak);
352 e_short_spline = comm.GlobalSumRoot(e_short_spline);
353 e_self = comm.GlobalSumRoot(e_self);
354
355 for (int j=0; j<num_particles_local; ++j)
356 e += 0.5 * p[j] * q[j];
357 e = comm.GlobalSumRoot(e);
358
359 comm.PrintStringOnce("E_long: %e", e_long);
360 comm.PrintStringOnce("E_short_peak: %e", e_short_peak);
361 comm.PrintStringOnce("E_short_spline: %e", e_short_spline);
362 comm.PrintStringOnce("E_self: %e", e_self);
363 comm.PrintStringOnce("E_total: %e", e);
364 comm.PrintStringOnce("E_total*: %e", e_long + e_short_peak + e_short_spline - e_self);
365
366 returndata.nuclei_long = e_long;
367 returndata.electron_long = e_long;
368}
Note: See TracBrowser for help on using the repository browser.