source: src/Jobs/InterfaceVMGJob.cpp@ ce9874

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

Added extraction of long-range forces from VMGData's array f.

  • Property mode set to 100644
File size: 13.2 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2012 University of Bonn. All rights reserved.
5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/*
25 * InterfaceVMGJob.cpp
26 *
27 * Created on: 10.06.2012
28 * Author: Frederik Heber
29 */
30
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#ifdef HAVE_MPI
36#include "mpi.h"
37#endif
38
39#include "base/vector.hpp"
40#include "base/math.hpp"
41#include "comm/comm.hpp"
42#include "grid/grid.hpp"
43#include "grid/multigrid.hpp"
44#include "units/particle/comm_mpi_particle.hpp"
45#include "units/particle/interpolation.hpp"
46#include "units/particle/linked_cell_list.hpp"
47#include "mg.hpp"
48
49#include "InterfaceVMGJob.hpp"
50
51#include "CodePatterns/MemDebug.hpp"
52
53#include <cmath>
54#include <iostream>
55#include <limits>
56
57#include "CodePatterns/Log.hpp"
58
59#include "Fragmentation/Summation/SetValues/FragmentForces.hpp"
60#include "Jobs/WindowGrid_converter.hpp"
61
62using namespace VMG;
63using VMGInterfaces::InterfaceVMGJob;
64
65InterfaceVMGJob::InterfaceVMGJob(const SamplingGrid &_sampled_input,
66 VMGData &_returndata,
67 const std::vector< std::vector<double> > &_particle_positions,
68 const std::vector< double > &_particle_charges,
69 VMG::Boundary boundary,
70 int levelMin,
71 int levelMax,
72 const VMG::Vector &_box_begin,
73 vmg_float _box_end,
74 const int& near_field_cells,
75 const ImportParticles_t _ImportParticles,
76 const bool _DoPrintDebug,
77 int coarseningSteps,
78 double alpha) :
79 VMG::Interface(boundary, levelMin, levelMax,
80 _box_begin, _box_end, coarseningSteps, alpha),
81 spl(near_field_cells, Extent(MaxLevel()).MeshWidth().Max()),
82 sampled_input(_sampled_input),
83 returndata(_returndata),
84 level(levelMax),
85 ImportParticles(_ImportParticles),
86 DoPrintDebug(_DoPrintDebug),
87 OpenBoundaryCondition(boundary[0] == VMG::Open)
88{
89 for (size_t i=0;i<3;++i) {
90 box_begin[i] = _box_begin[i];
91 box_end[i] = _box_end;
92 }
93 std::vector< std::vector<double> >::const_iterator positer = _particle_positions.begin();
94 std::vector<double>::const_iterator chargeiter = _particle_charges.begin();
95 double pos[3];
96 for (; positer != _particle_positions.end(); ++positer, ++chargeiter) {
97 ASSERT( (*positer).size() == 3,
98 "InterfaceVMGJob::InterfaceVMGJob() - particle "
99 +toString(distance(_particle_positions.begin(), positer))+" has not exactly 3 coordinates.");
100 for (size_t i=0;i<3;++i)
101 pos[i] = (*positer)[i];
102 particles.push_back(Particle::Particle(pos, *chargeiter));
103 }
104}
105
106void InterfaceVMGJob::ImportRightHandSide(Multigrid& multigrid)
107{
108 Index i;
109 Vector pos;
110 // VMG::TempGrid *temp_grid = new VMG::TempGrid(129, 0, 0., 1.);
111
112 Grid& grid = multigrid(multigrid.MaxLevel());
113 grid.Clear();
114 //grid.ClearBoundary(); // we don't have a boundary under periodic boundary conditions
115
116 // print debugging info on grid size
117 LOG(1, "INFO: Mesh has extent " << grid.Extent().MeshWidth() << ".");
118 const int gridpoints = pow(2, level);
119 LOG(1, "INFO: gridpoints on finest level are " << gridpoints << ".");
120 LOG(1, "INFO: "
121 << "X in [" << grid.Local().Begin().X() << "," << grid.Local().End().X() << "],"
122 << "Y in [" << grid.Local().Begin().Y() << "," << grid.Local().End().Y() << "],"
123 << "Z in [" << grid.Local().Begin().Z() << "," << grid.Local().End().Z() << "].");
124
125 /// 1. assign nuclei as smeared-out charges to the grid
126
127 /*
128 * Charge assignment on the grid
129 */
130 Particle::CommMPI& comm = *dynamic_cast<Particle::CommMPI*>(MG::GetComm());
131 Grid& particle_grid = comm.GetParticleGrid();
132 particle_grid.Clear();
133
134 // distribute particles
135 particles.clear();
136 comm.CommParticles(grid, particles);
137
138 assert(particle_grid.Global().LocalSize().IsComponentwiseGreater(
139 VMG::MG::GetFactory().GetObjectStorageVal<int>("PARTICLE_NEAR_FIELD_CELLS")));
140
141 if (ImportParticles == DoImportParticles) {
142 // create smeared-out particle charges on particle_grid via splines
143 LOG(1, "INFO: Creating particle grid for " << particles.size() << " particles.");
144 for (std::list<Particle::Particle>::iterator iter = particles.begin();
145 iter != particles.end(); ++iter) {
146 LOG(2, "DEBUG: Current particle is at " << (*iter).Pos()
147 << " with charge " << (*iter).Charge() << ".");
148 spl.SetSpline(particle_grid, *iter);
149 }
150 }
151
152 // Communicate charges over halo
153 comm.CommFromGhosts(particle_grid);
154
155 if (DoPrintDebug) {
156 // print nuclei grid to vtk
157 comm.PrintGrid(particle_grid, "Sampled Nuclei Density");
158 }
159
160 // add sampled electron charge density onto grid
161 WindowGrid_converter::addWindowOntoGrid(
162 grid,
163 sampled_input,
164 1.,
165 OpenBoundaryCondition);
166
167 if (DoPrintDebug) {
168 // print electron grid to vtk
169 comm.PrintGrid(grid, "Sampled Electron Density");
170 }
171
172 // add particle_grid onto grid
173 for (int i=0; i<grid.Local().Size().X(); ++i)
174 for (int j=0; j<grid.Local().Size().Y(); ++j)
175 for (int k=0; k<grid.Local().Size().Z(); ++k)
176 grid(grid.Local().Begin().X() + i,
177 grid.Local().Begin().Y() + j,
178 grid.Local().Begin().Z() + k) = 4.0 * VMG::Math::pi * (
179 grid(grid.Local().Begin().X() + i,
180 grid.Local().Begin().Y() + j,
181 grid.Local().Begin().Z() + k) +
182 particle_grid.GetVal(particle_grid.Local().Begin().X() + i,
183 particle_grid.Local().Begin().Y() + j,
184 particle_grid.Local().Begin().Z() + k));
185
186 // calculate sum over grid times h^3 as check, should be roughly zero
187 const double element_volume = grid.Extent().MeshWidth().Product();
188 double charge_sum = 0.0;
189 for (Grid::iterator grid_iter = grid.Iterators().Local().Begin();
190 grid_iter != grid.Iterators().Local().End();
191 ++grid_iter)
192 charge_sum += grid.GetVal(*grid_iter);
193 charge_sum = element_volume * comm.GlobalSum(charge_sum);
194 comm.PrintOnce(Debug, "Grid charge integral: %e", charge_sum/(4.0 * VMG::Math::pi));
195
196 if (DoPrintDebug) {
197 // print total grid to vtk
198 comm.PrintGrid(grid, "Total Charge Density");
199 }
200
201// delete temp_grid;
202}
203
204void InterfaceVMGJob::ExportSolution(Grid& grid)
205{
206 /// sample the obtained potential to evaluate with the electron charge density
207
208 // grid now contains the sough-for potential
209 //Comm& comm = *MG::GetComm();
210 Particle::CommMPI& comm = *dynamic_cast<Particle::CommMPI*>(MG::GetComm());
211
212
213 if (DoPrintDebug) {
214 // print output grid to vtk
215 comm.PrintGrid(grid, "Potential Solution");
216 }
217
218 // obtain sampled potential from grid
219 returndata.sampled_potential.setWindow(
220 box_begin,
221 box_end
222 );
223 WindowGrid_converter::addGridOntoWindow(
224 grid,
225 returndata.sampled_potential,
226 +1.,
227 OpenBoundaryCondition
228 );
229
230 // calculate integral over potential as long-range energy contribution
231 const double element_volume =
232 grid.Extent().MeshWidth().X() * grid.Extent().MeshWidth().Y() * grid.Extent().MeshWidth().Z();
233 Grid::iterator grid_iter;
234 double potential_sum = 0.0;
235 for (grid_iter=grid.Iterators().Local().Begin(); grid_iter!=grid.Iterators().Local().End(); ++grid_iter)
236 potential_sum += grid.GetVal(*grid_iter);
237 potential_sum = element_volume * comm.GlobalSum(potential_sum);
238 comm.PrintOnce(Debug, "Grid potential sum: %e", potential_sum);
239
240 {
241 Grid::iterator grid_iter = grid.Iterators().Local().Begin();
242 comm.PrintOnce(Debug, "Grid potential at (0,0,0): %e", grid.GetVal(*grid_iter));
243 }
244
245 //Particle::CommMPI& comm = *dynamic_cast<Particle::CommMPI*>(MG::GetComm()); returndata.e_long = potential_sum;
246
247 /// Calculate potential energy of nuclei
248
249 vmg_float e = 0.0;
250 vmg_float e_long = 0.0;
251 vmg_float e_self = 0.0;
252 vmg_float e_short_peak = 0.0;
253 vmg_float e_short_spline = 0.0;
254
255 Factory& factory = MG::GetFactory();
256
257 /*
258 * Get parameters and arrays
259 */
260 const vmg_int& near_field_cells = factory.GetObjectStorageVal<int>("PARTICLE_NEAR_FIELD_CELLS");
261 const vmg_int& interpolation_degree = factory.GetObjectStorageVal<int>("PARTICLE_INTERPOLATION_DEGREE");
262
263 Particle::Interpolation ip(interpolation_degree);
264
265 const vmg_float r_cut = near_field_cells * grid.Extent().MeshWidth().Max();
266
267 /*
268 * Copy potential values to a grid with sufficiently large halo size.
269 * This may be optimized in future.
270 * The parameters of this grid have been set in the import step.
271 */
272 Grid& particle_grid = comm.GetParticleGrid();
273
274 {
275 Index i;
276 for (i.X()=0; i.X()<grid.Local().Size().X(); ++i.X())
277 for (i.Y()=0; i.Y()<grid.Local().Size().Y(); ++i.Y())
278 for (i.Z()=0; i.Z()<grid.Local().Size().Z(); ++i.Z())
279 particle_grid(i + particle_grid.Local().Begin()) = grid.GetVal(i + grid.Local().Begin());
280 comm.CommToGhosts(particle_grid);
281 }
282
283 /*
284 * Compute potentials
285 */
286 Particle::LinkedCellList lc(particles, near_field_cells, grid);
287 Particle::LinkedCellList::iterator p1, p2;
288 Grid::iterator iter;
289
290 comm.CommLCListToGhosts(lc);
291
292 for (int i=lc.Local().Begin().X(); i<lc.Local().End().X(); ++i)
293 for (int j=lc.Local().Begin().Y(); j<lc.Local().End().Y(); ++j)
294 for (int k=lc.Local().Begin().Z(); k<lc.Local().End().Z(); ++k) {
295
296 if (lc(i,j,k).size() > 0)
297 ip.ComputeCoefficients(particle_grid, Index(i,j,k) - lc.Local().Begin() + particle_grid.Local().Begin());
298
299 for (p1=lc(i,j,k).begin(); p1!=lc(i,j,k).end(); ++p1) {
300
301 // Interpolate long-range part of potential and electric field
302 ip.Evaluate(**p1);
303
304 // Subtract self-induced potential
305 (*p1)->Pot() -= (*p1)->Charge() * spl.GetAntiDerivativeAtZero();
306
307 e_long += 0.5 * (*p1)->Charge() * ip.EvaluatePotentialLR(**p1);
308 e_self += 0.5 * (*p1)->Charge() * (*p1)->Charge() * spl.GetAntiDerivativeAtZero();
309
310 for (int dx=-1*near_field_cells; dx<=near_field_cells; ++dx)
311 for (int dy=-1*near_field_cells; dy<=near_field_cells; ++dy)
312 for (int dz=-1*near_field_cells; dz<=near_field_cells; ++dz) {
313
314 for (p2=lc(i+dx,j+dy,k+dz).begin(); p2!=lc(i+dx,j+dy,k+dz).end(); ++p2)
315
316 if (*p1 != *p2) {
317
318 const Vector dir = (*p1)->Pos() - (*p2)->Pos();
319 const vmg_float length = dir.Length();
320
321 if (length < r_cut) {
322
323 (*p1)->Pot() += (*p2)->Charge() / length * (1.0 + spl.EvaluatePotential(length));
324 (*p1)->Field() += (*p2)->Charge() * dir * spl.EvaluateField(length);
325
326 e_short_peak += 0.5 * (*p1)->Charge() * (*p2)->Charge() / length;
327 e_short_spline += 0.5 * (*p1)->Charge() * (*p2)->Charge() / length * spl.EvaluatePotential(length);
328 }
329 }
330 }
331 }
332 }
333
334 /* Remove average force term */
335 if (!particles.empty()) {
336 Vector average_force = 0.0;
337 for (std::list<Particle::Particle>::const_iterator iter=particles.begin(); iter!=particles.end(); ++iter)
338 average_force += iter->Charge() * iter->Field();
339 const vmg_int& npl = MG::GetFactory().GetObjectStorageVal<vmg_int>("PARTICLE_NUM_LOCAL");
340 const vmg_int num_particles_global = comm.GlobalSum(npl);
341 average_force /= num_particles_global;
342 comm.GlobalSumArray(average_force.vec(), 3);
343 for (std::list<Particle::Particle>::iterator iter=particles.begin(); iter!=particles.end(); ++iter)
344 iter->Field() -= average_force / iter->Charge();
345 }
346
347 comm.CommParticlesBack(particles);
348
349 vmg_float* q = factory.GetObjectStorageArray<vmg_float>("PARTICLE_CHARGE_ARRAY");
350 const vmg_int& num_particles_local = factory.GetObjectStorageVal<vmg_int>("PARTICLE_NUM_LOCAL");
351 const vmg_float* p = factory.GetObjectStorageArray<vmg_float>("PARTICLE_POTENTIAL_ARRAY");
352 const vmg_float* f = factory.GetObjectStorageArray<vmg_float>("PARTICLE_FIELD_ARRAY");
353
354 // extract forces
355 {
356 size_t index = 0;
357 returndata.particle_forces.resize(
358 num_particles_local, FragmentForces::force_t(3, 0.) );
359 for (FragmentForces::forces_t::iterator iter = returndata.particle_forces.begin();
360 iter != returndata.particle_forces.end(); ++iter)
361 for (size_t i=0;i<3;++i)
362 (*iter)[i] = f[index++];
363 }
364
365 e_long = comm.GlobalSumRoot(e_long);
366 e_short_peak = comm.GlobalSumRoot(e_short_peak);
367 e_short_spline = comm.GlobalSumRoot(e_short_spline);
368 e_self = comm.GlobalSumRoot(e_self);
369
370 for (int j=0; j<num_particles_local; ++j)
371 e += 0.5 * p[j] * q[j];
372 e = comm.GlobalSumRoot(e);
373
374 comm.PrintOnce(Debug, "E_long: %e", e_long);
375 comm.PrintOnce(Debug, "E_short_peak: %e", e_short_peak);
376 comm.PrintOnce(Debug, "E_short_spline: %e", e_short_spline);
377 comm.PrintOnce(Debug, "E_self: %e", e_self);
378 comm.PrintOnce(Debug, "E_total: %e", e);
379 comm.PrintOnce(Debug, "E_total*: %e", e_long + e_short_peak + e_short_spline - e_self);
380
381 returndata.nuclei_long = e_long;
382 returndata.electron_long = e_long;
383}
Note: See TracBrowser for help on using the repository browser.