source: src/Jobs/InterfaceVMGJob.cpp@ 5281ff

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 5281ff was e4721d3, checked in by Frederik Heber <heber@…>, 12 years ago

FIX: Average forces in InterfaceVMGJob only if there actually are some particles present.

  • otherwise we divide by zero.
  • Property mode set to 100644
File size: 12.4 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 bool _DoPrintDebug,
74 int coarseningSteps,
75 double alpha) :
76 VMG::Interface(boundary, levelMin, levelMax,
77 _box_begin, _box_end, coarseningSteps, alpha),
78 spl(near_field_cells, Extent(MaxLevel()).MeshWidth().Max()),
79 sampled_input(_sampled_input),
80 returndata(_returndata),
81 level(levelMax),
82 DoPrintDebug(_DoPrintDebug)
83{
84 for (size_t i=0;i<3;++i) {
85 box_begin[i] = _box_begin[i];
86 box_end[i] = _box_end;
87 }
88 std::vector< std::vector<double> >::const_iterator positer = _particle_positions.begin();
89 std::vector<double>::const_iterator chargeiter = _particle_charges.begin();
90 double pos[3];
91 for (; positer != _particle_positions.end(); ++positer, ++chargeiter) {
92 ASSERT( (*positer).size() == 3,
93 "InterfaceVMGJob::InterfaceVMGJob() - particle "
94 +toString(distance(_particle_positions.begin(), positer))+" has not exactly 3 coordinates.");
95 for (size_t i=0;i<3;++i)
96 pos[i] = (*positer)[i];
97 particles.push_back(Particle::Particle(pos, *chargeiter));
98 }
99}
100
101void InterfaceVMGJob::ImportRightHandSide(Multigrid& multigrid)
102{
103 Index i;
104 Vector pos;
105 // VMG::TempGrid *temp_grid = new VMG::TempGrid(129, 0, 0., 1.);
106
107 Grid& grid = multigrid(multigrid.MaxLevel());
108 grid.Clear();
109 //grid.ClearBoundary(); // we don't have a boundary under periodic boundary conditions
110
111 // print debugging info on grid size
112 LOG(1, "INFO: Mesh has extent " << grid.Extent().MeshWidth() << ".");
113 const int gridpoints = pow(2, level);
114 LOG(1, "INFO: gridpoints on finest level are " << gridpoints << ".");
115 LOG(1, "INFO: "
116 << "X in [" << grid.Local().Begin().X() << "," << grid.Local().End().X() << "],"
117 << "Y in [" << grid.Local().Begin().Y() << "," << grid.Local().End().Y() << "],"
118 << "Z in [" << grid.Local().Begin().Z() << "," << grid.Local().End().Z() << "].");
119
120 /// 1. assign nuclei as smeared-out charges to the grid
121
122 /*
123 * Charge assignment on the grid
124 */
125 Particle::CommMPI& comm = *dynamic_cast<Particle::CommMPI*>(MG::GetComm());
126 Grid& particle_grid = comm.GetParticleGrid();
127 particle_grid.Clear();
128
129 // distribute particles
130 particles.clear();
131 comm.CommParticles(grid, particles);
132
133 assert(particle_grid.Global().LocalSize().IsComponentwiseGreater(
134 VMG::MG::GetFactory().GetObjectStorageVal<int>("PARTICLE_NEAR_FIELD_CELLS")));
135
136 // create smeared-out particle charges on particle_grid via splines
137 LOG(1, "INFO: Creating particle grid for " << particles.size() << " particles.");
138 for (std::list<Particle::Particle>::iterator iter = particles.begin();
139 iter != particles.end(); ++iter) {
140 LOG(2, "DEBUG: Current particle is at " << (*iter).Pos()
141 << " with charge " << (*iter).Charge() << ".");
142 spl.SetSpline(particle_grid, *iter);
143 }
144
145 // Communicate charges over halo
146 comm.CommFromGhosts(particle_grid);
147
148 if (DoPrintDebug) {
149 // print nuclei grid to vtk
150 comm.PrintGrid(particle_grid, "Sampled Nuclei Density");
151 }
152
153 // add sampled electron charge density onto grid
154 WindowGrid_converter::addWindowOntoGrid(
155 grid,
156 sampled_input,
157 -1.);
158
159 if (DoPrintDebug) {
160 // print electron grid to vtk
161 comm.PrintGrid(grid, "Sampled Electron Density");
162 }
163
164 // add particle_grid onto grid
165 for (int i=0; i<grid.Local().Size().X(); ++i)
166 for (int j=0; j<grid.Local().Size().Y(); ++j)
167 for (int k=0; k<grid.Local().Size().Z(); ++k)
168 grid(grid.Local().Begin().X() + i,
169 grid.Local().Begin().Y() + j,
170 grid.Local().Begin().Z() + k) = 4.0 * VMG::Math::pi * (
171 grid(grid.Local().Begin().X() + i,
172 grid.Local().Begin().Y() + j,
173 grid.Local().Begin().Z() + k) +
174 particle_grid.GetVal(particle_grid.Local().Begin().X() + i,
175 particle_grid.Local().Begin().Y() + j,
176 particle_grid.Local().Begin().Z() + k));
177
178 // calculate sum over grid times h^3 as check, should be roughly zero
179 const double element_volume = grid.Extent().MeshWidth().Product();
180 double charge_sum = 0.0;
181 for (Grid::iterator grid_iter = grid.Iterators().Local().Begin();
182 grid_iter != grid.Iterators().Local().End();
183 ++grid_iter)
184 charge_sum += grid.GetVal(*grid_iter);
185 charge_sum = element_volume * comm.GlobalSum(charge_sum);
186 comm.PrintStringOnce("Grid charge integral: %e", charge_sum/(4.0 * VMG::Math::pi));
187
188 if (DoPrintDebug) {
189 // print total grid to vtk
190 comm.PrintGrid(grid, "Total Charge Density");
191 }
192
193// delete temp_grid;
194}
195
196void InterfaceVMGJob::ExportSolution(Grid& grid)
197{
198 /// sample the obtained potential to evaluate with the electron charge density
199
200 // grid now contains the sough-for potential
201 //Comm& comm = *MG::GetComm();
202 Particle::CommMPI& comm = *dynamic_cast<Particle::CommMPI*>(MG::GetComm());
203
204 const Index begin_local = grid.Global().LocalBegin() - grid.Local().HaloSize1();
205 Index i;
206
207 if (DoPrintDebug) {
208 // print output grid to vtk
209 comm.PrintGrid(grid, "Potential Solution");
210 }
211
212 // obtain sampled potential from grid
213 returndata.sampled_potential.setWindow(
214 box_begin,
215 box_end
216 );
217 WindowGrid_converter::addGridOntoWindow(
218 grid,
219 returndata.sampled_potential,
220 +1.
221 );
222
223 // calculate integral over potential as long-range energy contribution
224 const double element_volume =
225 grid.Extent().MeshWidth().X() * grid.Extent().MeshWidth().Y() * grid.Extent().MeshWidth().Z();
226 Grid::iterator grid_iter;
227 double potential_sum = 0.0;
228 for (grid_iter=grid.Iterators().Local().Begin(); grid_iter!=grid.Iterators().Local().End(); ++grid_iter)
229 potential_sum += grid.GetVal(*grid_iter);
230 potential_sum = element_volume * comm.GlobalSum(potential_sum);
231 comm.PrintStringOnce("Grid potential sum: %e", potential_sum);
232
233 {
234 Grid::iterator grid_iter = grid.Iterators().Local().Begin();
235 comm.PrintStringOnce("Grid potential at (0,0,0): %e", grid.GetVal(*grid_iter));
236 }
237
238 //Particle::CommMPI& comm = *dynamic_cast<Particle::CommMPI*>(MG::GetComm()); returndata.e_long = potential_sum;
239
240 /// Calculate potential energy of nuclei
241
242 vmg_float e = 0.0;
243 vmg_float e_long = 0.0;
244 vmg_float e_self = 0.0;
245 vmg_float e_short_peak = 0.0;
246 vmg_float e_short_spline = 0.0;
247
248 Factory& factory = MG::GetFactory();
249
250 /*
251 * Get parameters and arrays
252 */
253 const vmg_int& near_field_cells = factory.GetObjectStorageVal<int>("PARTICLE_NEAR_FIELD_CELLS");
254 const vmg_int& interpolation_degree = factory.GetObjectStorageVal<int>("PARTICLE_INTERPOLATION_DEGREE");
255
256 Particle::Interpolation ip(interpolation_degree);
257
258 const vmg_float r_cut = near_field_cells * grid.Extent().MeshWidth().Max();
259
260 /*
261 * Copy potential values to a grid with sufficiently large halo size.
262 * This may be optimized in future.
263 * The parameters of this grid have been set in the import step.
264 */
265 Grid& particle_grid = comm.GetParticleGrid();
266
267 for (i.X()=0; i.X()<grid.Local().Size().X(); ++i.X())
268 for (i.Y()=0; i.Y()<grid.Local().Size().Y(); ++i.Y())
269 for (i.Z()=0; i.Z()<grid.Local().Size().Z(); ++i.Z())
270 particle_grid(i + particle_grid.Local().Begin()) = grid.GetVal(i + grid.Local().Begin());
271
272 comm.CommToGhosts(particle_grid);
273
274 /*
275 * Compute potentials
276 */
277 Particle::LinkedCellList lc(particles, near_field_cells, grid);
278 Particle::LinkedCellList::iterator p1, p2;
279 Grid::iterator iter;
280
281 comm.CommLCListToGhosts(lc);
282
283 for (int i=lc.Local().Begin().X(); i<lc.Local().End().X(); ++i)
284 for (int j=lc.Local().Begin().Y(); j<lc.Local().End().Y(); ++j)
285 for (int k=lc.Local().Begin().Z(); k<lc.Local().End().Z(); ++k) {
286
287 if (lc(i,j,k).size() > 0)
288 ip.ComputeCoefficients(particle_grid, Index(i,j,k) - lc.Local().Begin() + particle_grid.Local().Begin());
289
290 for (p1=lc(i,j,k).begin(); p1!=lc(i,j,k).end(); ++p1) {
291
292 // Interpolate long-range part of potential and electric field
293 ip.Evaluate(**p1);
294
295 // Subtract self-induced potential
296 (*p1)->Pot() -= (*p1)->Charge() * spl.GetAntiDerivativeAtZero();
297
298 e_long += 0.5 * (*p1)->Charge() * ip.EvaluatePotentialLR(**p1);
299 e_self += 0.5 * (*p1)->Charge() * (*p1)->Charge() * spl.GetAntiDerivativeAtZero();
300
301 for (int dx=-1*near_field_cells; dx<=near_field_cells; ++dx)
302 for (int dy=-1*near_field_cells; dy<=near_field_cells; ++dy)
303 for (int dz=-1*near_field_cells; dz<=near_field_cells; ++dz) {
304
305 for (p2=lc(i+dx,j+dy,k+dz).begin(); p2!=lc(i+dx,j+dy,k+dz).end(); ++p2)
306
307 if (*p1 != *p2) {
308
309 const Vector dir = (*p1)->Pos() - (*p2)->Pos();
310 const vmg_float length = dir.Length();
311
312 if (length < r_cut) {
313
314 (*p1)->Pot() += (*p2)->Charge() / length * (1.0 + spl.EvaluatePotential(length));
315 (*p1)->Field() += (*p2)->Charge() * dir * spl.EvaluateField(length);
316
317 e_short_peak += 0.5 * (*p1)->Charge() * (*p2)->Charge() / length;
318 e_short_spline += 0.5 * (*p1)->Charge() * (*p2)->Charge() / length * spl.EvaluatePotential(length);
319 }
320 }
321 }
322 }
323 }
324
325 /* Remove average force term */
326 if (!particles.empty()) {
327 Vector average_force = 0.0;
328 for (std::list<Particle::Particle>::const_iterator iter=particles.begin(); iter!=particles.end(); ++iter)
329 average_force += iter->Charge() * iter->Field();
330 const vmg_int& npl = MG::GetFactory().GetObjectStorageVal<vmg_int>("PARTICLE_NUM_LOCAL");
331 const vmg_int num_particles_global = comm.GlobalSum(npl);
332 average_force /= num_particles_global;
333 comm.GlobalSumArray(average_force.vec(), 3);
334 for (std::list<Particle::Particle>::iterator iter=particles.begin(); iter!=particles.end(); ++iter)
335 iter->Field() -= average_force / iter->Charge();
336 }
337
338 comm.CommParticlesBack(particles);
339
340 vmg_float* q = factory.GetObjectStorageArray<vmg_float>("PARTICLE_CHARGE_ARRAY");
341 const vmg_int& num_particles_local = factory.GetObjectStorageVal<vmg_int>("PARTICLE_NUM_LOCAL");
342 const vmg_float* p = factory.GetObjectStorageArray<vmg_float>("PARTICLE_POTENTIAL_ARRAY");
343// const vmg_float* f = factory.GetObjectStorageArray<vmg_float>("PARTICLE_FIELD_ARRAY");
344
345
346 e_long = comm.GlobalSumRoot(e_long);
347 e_short_peak = comm.GlobalSumRoot(e_short_peak);
348 e_short_spline = comm.GlobalSumRoot(e_short_spline);
349 e_self = comm.GlobalSumRoot(e_self);
350
351 for (int j=0; j<num_particles_local; ++j)
352 e += 0.5 * p[j] * q[j];
353 e = comm.GlobalSumRoot(e);
354
355 comm.PrintStringOnce("E_long: %e", e_long);
356 comm.PrintStringOnce("E_short_peak: %e", e_short_peak);
357 comm.PrintStringOnce("E_short_spline: %e", e_short_spline);
358 comm.PrintStringOnce("E_self: %e", e_self);
359 comm.PrintStringOnce("E_total: %e", e);
360 comm.PrintStringOnce("E_total*: %e", e_long + e_short_peak + e_short_spline - e_self);
361
362 returndata.e_long = e;
363}
Note: See TracBrowser for help on using the repository browser.