source: src/Jobs/InterfaceVMGJob.cpp@ fb3485

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

Shifted functions to add window onto grid into own namespace.

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