source: src/Analysis/analysis_correlation.cpp@ 87d6bd

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

TESTFIX: Analysis' DipoleAngularCorrelation() and BinData() suffered numerical instabilities.

  • cut precision down to 6 digits which also matches with output precision.
  • TESTFIX: As we use floor() to round, the least digit changed in some cases, i.e. a change within 1e-6. Corrected in regression tests Analysis/ DipoleAngularCorrelation.
  • TESTFIX: same with AnalysisPairCorrelationUnitTest.
  • Property mode set to 100644
File size: 28.9 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-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 * analysis.cpp
25 *
26 * Created on: Oct 13, 2009
27 * Author: heber
28 */
29
30// include config.h
31#ifdef HAVE_CONFIG_H
32#include <config.h>
33#endif
34
35#include "CodePatterns/MemDebug.hpp"
36
37#include <algorithm>
38#include <iostream>
39#include <iomanip>
40#include <limits>
41
42#include "Atom/atom.hpp"
43#include "Bond/bond.hpp"
44#include "Tesselation/BoundaryTriangleSet.hpp"
45#include "Box.hpp"
46#include "Element/element.hpp"
47#include "CodePatterns/Info.hpp"
48#include "CodePatterns/Log.hpp"
49#include "CodePatterns/Verbose.hpp"
50#include "Descriptors/AtomOfMoleculeSelectionDescriptor.hpp"
51#include "Descriptors/MoleculeFormulaDescriptor.hpp"
52#include "Descriptors/MoleculeOfAtomSelectionDescriptor.hpp"
53#include "Formula.hpp"
54#include "LinearAlgebra/Vector.hpp"
55#include "LinearAlgebra/RealSpaceMatrix.hpp"
56#include "LinkedCell/LinkedCell_View.hpp"
57#include "molecule.hpp"
58#include "Tesselation/tesselation.hpp"
59#include "Tesselation/tesselationhelpers.hpp"
60#include "Tesselation/triangleintersectionlist.hpp"
61#include "World.hpp"
62#include "WorldTime.hpp"
63
64#include "analysis_correlation.hpp"
65
66/** Calculates the dipole vector of a given atomSet.
67 *
68 * Note that we use the following procedure as rule of thumb:
69 * -# go through every bond of the atom
70 * -# calculate the difference of electronegativities \f$\Delta\mathrm{EN}\f$
71 * -# if \f$\Delta\mathrm{EN} > 0.5\f$, we align the bond vector in direction of the more negative element
72 * -# sum up all vectors
73 * -# finally, divide by the number of summed vectors
74 *
75 * @param atomsbegin begin iterator of atomSet
76 * @param atomsend end iterator of atomset
77 * @return dipole vector
78 */
79Vector getDipole(molecule::const_iterator atomsbegin, molecule::const_iterator atomsend)
80{
81 Vector DipoleVector;
82 size_t SumOfVectors = 0;
83 Box &domain = World::getInstance().getDomain();
84
85 // go through all atoms
86 for (molecule::const_iterator atomiter = atomsbegin;
87 atomiter != atomsend;
88 ++atomiter) {
89 // go through all bonds
90 const BondList& ListOfBonds = (*atomiter)->getListOfBonds();
91 ASSERT(ListOfBonds.begin() != ListOfBonds.end(),
92 "getDipole() - no bonds in molecule!");
93 for (BondList::const_iterator bonditer = ListOfBonds.begin();
94 bonditer != ListOfBonds.end();
95 ++bonditer) {
96 const atom * Otheratom = (*bonditer)->GetOtherAtom(*atomiter);
97 if (Otheratom->getId() > (*atomiter)->getId()) {
98 const double DeltaEN = (*atomiter)->getType()->getElectronegativity()
99 -Otheratom->getType()->getElectronegativity();
100 // get distance and correct for boundary conditions
101 Vector BondDipoleVector = domain.periodicDistanceVector(
102 (*atomiter)->getPosition(),
103 Otheratom->getPosition());
104 // DeltaEN is always positive, gives correct orientation of vector
105 BondDipoleVector.Normalize();
106 BondDipoleVector *= DeltaEN;
107 LOG(3,"INFO: Dipole vector from bond " << **bonditer << " is " << BondDipoleVector);
108 DipoleVector += BondDipoleVector;
109 SumOfVectors++;
110 }
111 }
112 }
113 LOG(3,"INFO: Sum over all bond dipole vectors is "
114 << DipoleVector << " with " << SumOfVectors << " in total.");
115 if (SumOfVectors != 0)
116 DipoleVector *= 1./(double)SumOfVectors;
117 LOG(2, "INFO: Resulting dipole vector is " << DipoleVector);
118
119 return DipoleVector;
120};
121
122/** Calculate minimum and maximum amount of trajectory steps by going through given atomic trajectories.
123 * \param vector of atoms whose trajectories to check for [min,max]
124 * \return range with [min, max]
125 */
126range<size_t> getMaximumTrajectoryBounds(const std::vector<atom *> &atoms)
127{
128 // get highest trajectory size
129 LOG(0,"STATUS: Retrieving maximum amount of time steps ...");
130 if (atoms.size() == 0)
131 return range<size_t>(0,0);
132 size_t max_timesteps = std::numeric_limits<size_t>::min();
133 size_t min_timesteps = std::numeric_limits<size_t>::max();
134 BOOST_FOREACH(atom *_atom, atoms) {
135 if (_atom->getTrajectorySize() > max_timesteps)
136 max_timesteps = _atom->getTrajectorySize();
137 if (_atom->getTrajectorySize() < min_timesteps)
138 min_timesteps = _atom->getTrajectorySize();
139 }
140 LOG(1,"INFO: Minimum number of time steps found is " << min_timesteps);
141 LOG(1,"INFO: Maximum number of time steps found is " << max_timesteps);
142
143 return range<size_t>(min_timesteps, max_timesteps);
144}
145
146/** Calculates the angular dipole zero orientation from current time step.
147 * \param molecules vector of molecules to calculate dipoles of
148 * \return map with orientation vector for each atomic id given in \a atoms.
149 */
150std::map<atomId_t, Vector> CalculateZeroAngularDipole(const std::vector<molecule *> &molecules)
151{
152 // get zero orientation for each molecule.
153 LOG(0,"STATUS: Calculating dipoles for current time step ...");
154 std::map<atomId_t, Vector> ZeroVector;
155 BOOST_FOREACH(molecule *_mol, molecules) {
156 const Vector Dipole = getDipole(_mol->begin(), _mol->end());
157 for(molecule::const_iterator iter = _mol->begin(); iter != _mol->end(); ++iter)
158 ZeroVector[(*iter)->getId()] = Dipole;
159 LOG(2,"INFO: Zero alignment for molecule " << _mol->getId() << " is " << Dipole);
160 }
161 LOG(1,"INFO: We calculated zero orientation for a total of " << molecules.size() << " molecule(s).");
162
163 return ZeroVector;
164}
165
166/** Calculates the dipole angular correlation for given molecule type.
167 * Calculate the change of the dipole orientation angle over time.
168 * Note given element order is unimportant (i.e. g(Si, O) === g(O, Si))
169 * Angles are given in degrees.
170 * \param &atoms list of atoms of the molecules taking part (Note: molecules may
171 * change over time as bond structure is recalculated, hence we need the atoms)
172 * \param timestep time step to calculate angular correlation for (relative to
173 * \a ZeroVector)
174 * \param ZeroVector map with Zero orientation vector for each atom in \a atoms.
175 * \param DontResetTime don't reset time to old value (triggers re-creation of bond system)
176 * \return Map of doubles with values the pair of the two atoms.
177 */
178DipoleAngularCorrelationMap *DipoleAngularCorrelation(
179 const Formula &DipoleFormula,
180 const size_t timestep,
181 const std::map<atomId_t, Vector> &ZeroVector,
182 const enum ResetWorldTime DoTimeReset
183 )
184{
185 Info FunctionInfo(__func__);
186 DipoleAngularCorrelationMap *outmap = new DipoleAngularCorrelationMap;
187
188 unsigned int oldtime = 0;
189 if (DoTimeReset == DoResetTime) {
190 // store original time step
191 oldtime = WorldTime::getTime();
192 }
193
194 // set time step
195 LOG(0,"STATUS: Stepping onto to time step " << timestep << ".");
196 World::getInstance().setTime(timestep);
197
198 // get all molecules for this time step
199 World::getInstance().clearMoleculeSelection();
200 World::getInstance().selectAllMolecules(MoleculeByFormula(DipoleFormula));
201 std::vector<molecule *> molecules = World::getInstance().getSelectedMolecules();
202 LOG(1,"INFO: There are " << molecules.size() << " molecules for time step " << timestep << ".");
203
204 // calculate dipoles for each
205 LOG(0,"STATUS: Calculating dipoles for time step " << timestep << " ...");
206 size_t i=0;
207 size_t Counter_rejections = 0;
208 BOOST_FOREACH(molecule *_mol, molecules) {
209 const Vector Dipole = getDipole(_mol->begin(), _mol->end());
210 LOG(3,"INFO: Dipole vector at time step " << timestep << " for for molecule "
211 << _mol->getId() << " is " << Dipole);
212 // check that all atoms are valid (zeroVector known)
213 molecule::const_iterator iter = _mol->begin();
214 for(; iter != _mol->end(); ++iter) {
215 if (!ZeroVector.count((*iter)->getId()))
216 break;
217 }
218 if (iter != _mol->end()) {
219 ELOG(2, "Skipping molecule " << _mol->getName() << " as not all atoms have a valid zeroVector.");
220 ++Counter_rejections;
221 continue;
222 } else
223 iter = _mol->begin();
224 std::map<atomId_t, Vector>::const_iterator zeroValue = ZeroVector.find((*iter)->getId()); //due to iter is const
225 double angle = 0.;
226 LOG(2, "INFO: ZeroVector of first atom " << **iter << " is "
227 << zeroValue->second << ".");
228 LOG(4, "INFO: Squared norm of difference vector is "
229 << (zeroValue->second - Dipole).NormSquared() << ".");
230 if ((zeroValue->second - Dipole).NormSquared() > MYEPSILON)
231 angle = Dipole.Angle(zeroValue->second) * (180./M_PI);
232 else
233 LOG(2, "INFO: Both vectors (almost) coincide, numerically unstable, angle set to zero.");
234 // we print six digits, hence round up to six digit precision
235 const double precision = 1e-6;
236 angle = precision*floor(angle/precision);
237 LOG(1,"INFO: Resulting relative angle for molecule " << _mol->getName()
238 << " is " << angle << ".");
239 outmap->insert ( std::make_pair (angle, *iter ) );
240 ++i;
241 }
242 ASSERT(Counter_rejections <= molecules.size(),
243 "DipoleAngularCorrelation() - more rejections ("+toString(Counter_rejections)
244 +") than there are molecules ("+toString(molecules.size())+").");
245 LOG(1,"INFO: " << Counter_rejections << " molecules have been rejected in time step " << timestep << ".");
246
247 LOG(0,"STATUS: Done with calculating dipoles.");
248
249 if (DoTimeReset == DoResetTime) {
250 // re-set to original time step again
251 World::getInstance().setTime(oldtime);
252 }
253
254 // and return results
255 return outmap;
256};
257
258/** Calculates the dipole correlation for given molecule type.
259 * I.e. we calculate how the angle between any two given dipoles in the
260 * systems behaves. Sort of pair correlation but distance is replaced by
261 * the orientation distance, i.e. an angle.
262 * Note given element order is unimportant (i.e. g(Si, O) === g(O, Si))
263 * Angles are given in degrees.
264 * \param *molecules vector of molecules
265 * \return Map of doubles with values the pair of the two atoms.
266 */
267DipoleCorrelationMap *DipoleCorrelation(std::vector<molecule *> &molecules)
268{
269 Info FunctionInfo(__func__);
270 DipoleCorrelationMap *outmap = new DipoleCorrelationMap;
271// double distance = 0.;
272// Box &domain = World::getInstance().getDomain();
273//
274 if (molecules.empty()) {
275 ELOG(1, "No molecule given.");
276 return outmap;
277 }
278
279 for (std::vector<molecule *>::const_iterator MolWalker = molecules.begin();
280 MolWalker != molecules.end(); ++MolWalker) {
281 LOG(2, "INFO: Current molecule is " << (*MolWalker)->getId() << ".");
282 const Vector Dipole = getDipole((*MolWalker)->begin(), (*MolWalker)->end());
283 std::vector<molecule *>::const_iterator MolOtherWalker = MolWalker;
284 for (++MolOtherWalker;
285 MolOtherWalker != molecules.end();
286 ++MolOtherWalker) {
287 LOG(2, "INFO: Current other molecule is " << (*MolOtherWalker)->getId() << ".");
288 const Vector OtherDipole = getDipole((*MolOtherWalker)->begin(), (*MolOtherWalker)->end());
289 const double angle = Dipole.Angle(OtherDipole) * (180./M_PI);
290 LOG(1, "Angle is " << angle << ".");
291 outmap->insert ( make_pair (angle, make_pair ((*MolWalker), (*MolOtherWalker)) ) );
292 }
293 }
294 return outmap;
295};
296
297/** Calculates the pair correlation between given atom sets.
298 *
299 * Note we correlate each of the \a &atomsfirst with each of the second set
300 * \a &atoms_second. However, we are aware of double counting. If an atom is
301 * in either set, the pair is counted only once.
302 *
303 * \param &atoms_first vector of atoms
304 * \param &atoms_second vector of atoms
305 * \param max_distance maximum distance for the correlation
306 * \return Map of doubles with values the pair of the two atoms.
307 */
308PairCorrelationMap *PairCorrelation(
309 const World::AtomComposite &atoms_first,
310 const World::AtomComposite &atoms_second,
311 const double max_distance)
312{
313 Info FunctionInfo(__func__);
314 PairCorrelationMap *outmap = new PairCorrelationMap;
315 //double distance = 0.;
316 Box &domain = World::getInstance().getDomain();
317
318 if (atoms_first.empty() || atoms_second.empty()) {
319 ELOG(1, "No atoms given.");
320 return outmap;
321 }
322
323 //!> typedef for an unsorted container, (output) compatible with STL algorithms
324 typedef std::vector<const TesselPoint *> LinkedVector;
325
326 // create intersection (to know when to check for double-counting)
327 LinkedVector intersected_atoms(atoms_second.size(), NULL);
328 LinkedVector::iterator intersected_atoms_end =
329 std::set_intersection(
330 atoms_first.begin(),atoms_first.end(),
331 atoms_second.begin(), atoms_second.end(),
332 intersected_atoms.begin());
333 const LinkedCell::LinkedList intersected_atoms_set(intersected_atoms.begin(), intersected_atoms.end());
334
335 // create map
336 outmap = new PairCorrelationMap;
337
338 // get linked cell view
339 LinkedCell::LinkedCell_View LC = World::getInstance().getLinkedCell(max_distance);
340
341 // convert second to _sorted_ set
342 LinkedCell::LinkedList atoms_second_set(atoms_second.begin(), atoms_second.end());
343 LOG(2, "INFO: first set has " << atoms_first.size()
344 << " and second set has " << atoms_second_set.size() << " atoms.");
345
346 // fill map
347 for (World::AtomComposite::const_iterator iter = atoms_first.begin();
348 iter != atoms_first.end();
349 ++iter) {
350 const TesselPoint * const Walker = *iter;
351 LOG(3, "INFO: Current point is " << Walker->getName() << ".");
352 // obtain all possible neighbors (that is a sorted set)
353 LinkedCell::LinkedList ListOfNeighbors = LC.getPointsInsideSphere(
354 max_distance,
355 Walker->getPosition());
356 LOG(2, "INFO: There are " << ListOfNeighbors.size() << " neighbors.");
357
358 // create intersection with second set
359 // NOTE: STL algorithms do mostly not work on sorted container because reassignment
360 // of a value may also require changing its position.
361 LinkedVector intersected_set(atoms_second.size(), NULL);
362 LinkedVector::iterator intersected_end =
363 std::set_intersection(
364 ListOfNeighbors.begin(),ListOfNeighbors.end(),
365 atoms_second_set.begin(), atoms_second_set.end(),
366 intersected_set.begin());
367 // count remaining elements
368 LOG(2, "INFO: Intersection with second set has " << int(intersected_end - intersected_set.begin()) << " elements.");
369 // we have some possible candidates, go through each
370 for (LinkedVector::const_iterator neighboriter = intersected_set.begin();
371 neighboriter != intersected_end;
372 ++neighboriter) {
373 const TesselPoint * const OtherWalker = (*neighboriter);
374 LinkedCell::LinkedList::const_iterator equaliter = intersected_atoms_set.find(OtherWalker);
375 if ((equaliter != intersected_atoms_set.end()) && (OtherWalker <= Walker)) {
376 // present in both sets, assure that we are larger
377 continue;
378 }
379 LOG(3, "INFO: Current other point is " << *OtherWalker << ".");
380 const double distance = domain.periodicDistance(OtherWalker->getPosition(),Walker->getPosition());
381 LOG(3, "INFO: Resulting distance is " << distance << ".");
382 outmap->insert (
383 std::pair<double, std::pair <const TesselPoint *, const TesselPoint*> > (
384 distance,
385 std::make_pair (Walker, OtherWalker)
386 )
387 );
388 }
389 }
390 // and return
391 return outmap;
392};
393
394/** Calculates the distance (pair) correlation between a given element and a point.
395 * \param *molecules list of molecules structure
396 * \param &elements vector of elements to correlate with point
397 * \param *point vector to the correlation point
398 * \return Map of dobules with values as pairs of atom and the vector
399 */
400CorrelationToPointMap *CorrelationToPoint(std::vector<molecule *> &molecules, const std::vector<const element *> &elements, const Vector *point )
401{
402 Info FunctionInfo(__func__);
403 CorrelationToPointMap *outmap = new CorrelationToPointMap;
404 double distance = 0.;
405 Box &domain = World::getInstance().getDomain();
406
407 if (molecules.empty()) {
408 LOG(1, "No molecule given.");
409 return outmap;
410 }
411
412 outmap = new CorrelationToPointMap;
413 for (std::vector<molecule *>::const_iterator MolWalker = molecules.begin(); MolWalker != molecules.end(); MolWalker++) {
414 LOG(2, "Current molecule is " << *MolWalker << ".");
415 for (molecule::const_iterator iter = (*MolWalker)->begin(); iter != (*MolWalker)->end(); ++iter) {
416 LOG(3, "Current atom is " << **iter << ".");
417 for (vector<const element *>::const_iterator type = elements.begin(); type != elements.end(); ++type)
418 if ((*type == NULL) || ((*iter)->getType() == *type)) {
419 distance = domain.periodicDistance((*iter)->getPosition(),*point);
420 LOG(4, "Current distance is " << distance << ".");
421 outmap->insert (
422 std::pair<double, std::pair<const atom *, const Vector*> >(
423 distance,
424 std::pair<const atom *, const Vector*> (
425 (*iter),
426 point)
427 )
428 );
429 }
430 }
431 }
432
433 return outmap;
434};
435
436/** Calculates the distance (pair) correlation between a given element, all its periodic images and a point.
437 * \param *molecules list of molecules structure
438 * \param &elements vector of elements to correlate to point
439 * \param *point vector to the correlation point
440 * \param ranges[NDIM] interval boundaries for the periodic images to scan also
441 * \return Map of dobules with values as pairs of atom and the vector
442 */
443CorrelationToPointMap *PeriodicCorrelationToPoint(std::vector<molecule *> &molecules, const std::vector<const element *> &elements, const Vector *point, const int ranges[NDIM] )
444{
445 Info FunctionInfo(__func__);
446 CorrelationToPointMap *outmap = new CorrelationToPointMap;
447 double distance = 0.;
448 int n[NDIM];
449 Vector periodicX;
450 Vector checkX;
451
452 if (molecules.empty()) {
453 LOG(1, "No molecule given.");
454 return outmap;
455 }
456
457 outmap = new CorrelationToPointMap;
458 for (std::vector<molecule *>::const_iterator MolWalker = molecules.begin(); MolWalker != molecules.end(); MolWalker++) {
459 RealSpaceMatrix FullMatrix = World::getInstance().getDomain().getM();
460 RealSpaceMatrix FullInverseMatrix = World::getInstance().getDomain().getMinv();
461 LOG(2, "Current molecule is " << *MolWalker << ".");
462 for (molecule::const_iterator iter = (*MolWalker)->begin(); iter != (*MolWalker)->end(); ++iter) {
463 LOG(3, "Current atom is " << **iter << ".");
464 for (vector<const element *>::const_iterator type = elements.begin(); type != elements.end(); ++type)
465 if ((*type == NULL) || ((*iter)->getType() == *type)) {
466 periodicX = FullInverseMatrix * ((*iter)->getPosition()); // x now in [0,1)^3
467 // go through every range in xyz and get distance
468 for (n[0]=-ranges[0]; n[0] <= ranges[0]; n[0]++)
469 for (n[1]=-ranges[1]; n[1] <= ranges[1]; n[1]++)
470 for (n[2]=-ranges[2]; n[2] <= ranges[2]; n[2]++) {
471 checkX = FullMatrix * (Vector(n[0], n[1], n[2]) + periodicX);
472 distance = checkX.distance(*point);
473 LOG(4, "Current distance is " << distance << ".");
474 outmap->insert (
475 std::pair<double,
476 std::pair<const atom *, const Vector*> >(
477 distance,
478 std::pair<const atom *, const Vector*> (
479 *iter,
480 point)
481 )
482 );
483 }
484 }
485 }
486 }
487
488 return outmap;
489};
490
491/** Calculates the distance (pair) correlation between a given element and a surface.
492 * \param *molecules list of molecules structure
493 * \param &elements vector of elements to correlate to surface
494 * \param *Surface pointer to Tesselation class surface
495 * \param *LC LinkedCell_deprecated structure to quickly find neighbouring atoms
496 * \return Map of doubles with values as pairs of atom and the BoundaryTriangleSet that's closest
497 */
498CorrelationToSurfaceMap *CorrelationToSurface(std::vector<molecule *> &molecules, const std::vector<const element *> &elements, const Tesselation * const Surface, const LinkedCell_deprecated *LC )
499{
500 Info FunctionInfo(__func__);
501 CorrelationToSurfaceMap *outmap = new CorrelationToSurfaceMap;
502 double distance = 0;
503 class BoundaryTriangleSet *triangle = NULL;
504 Vector centroid;
505
506 if ((Surface == NULL) || (LC == NULL) || (molecules.empty())) {
507 ELOG(1, "No Tesselation, no LinkedCell or no molecule given.");
508 return outmap;
509 }
510
511 outmap = new CorrelationToSurfaceMap;
512 for (std::vector<molecule *>::const_iterator MolWalker = molecules.begin(); MolWalker != molecules.end(); MolWalker++) {
513 LOG(2, "Current molecule is " << (*MolWalker)->name << ".");
514 if ((*MolWalker)->empty())
515 LOG(2, "\t is empty.");
516 for (molecule::const_iterator iter = (*MolWalker)->begin(); iter != (*MolWalker)->end(); ++iter) {
517 LOG(3, "\tCurrent atom is " << *(*iter) << ".");
518 for (vector<const element *>::const_iterator type = elements.begin(); type != elements.end(); ++type)
519 if ((*type == NULL) || ((*iter)->getType() == *type)) {
520 TriangleIntersectionList Intersections((*iter)->getPosition(),Surface,LC);
521 distance = Intersections.GetSmallestDistance();
522 triangle = Intersections.GetClosestTriangle();
523 outmap->insert (
524 std::pair<double,
525 std::pair<const atom *, BoundaryTriangleSet*> >(
526 distance,
527 std::pair<const atom *, BoundaryTriangleSet*> (
528 (*iter),
529 triangle)
530 )
531 );
532 }
533 }
534 }
535
536 return outmap;
537};
538
539/** Calculates the distance (pair) correlation between a given element, all its periodic images and and a surface.
540 * Note that we also put all periodic images found in the cells given by [ -ranges[i], ranges[i] ] and i=0,...,NDIM-1.
541 * I.e. We multiply the atom::node with the inverse of the domain matrix, i.e. transform it to \f$[0,0^3\f$, then add per
542 * axis an integer from [ -ranges[i], ranges[i] ] onto it and multiply with the domain matrix to bring it back into
543 * the real space. Then, we Tesselation::FindClosestTriangleToPoint() and DistanceToTrianglePlane().
544 * \param *molecules list of molecules structure
545 * \param &elements vector of elements to correlate to surface
546 * \param *Surface pointer to Tesselation class surface
547 * \param *LC LinkedCell_deprecated structure to quickly find neighbouring atoms
548 * \param ranges[NDIM] interval boundaries for the periodic images to scan also
549 * \return Map of doubles with values as pairs of atom and the BoundaryTriangleSet that's closest
550 */
551CorrelationToSurfaceMap *PeriodicCorrelationToSurface(std::vector<molecule *> &molecules, const std::vector<const element *> &elements, const Tesselation * const Surface, const LinkedCell_deprecated *LC, const int ranges[NDIM] )
552{
553 Info FunctionInfo(__func__);
554 CorrelationToSurfaceMap *outmap = new CorrelationToSurfaceMap;
555 double distance = 0;
556 class BoundaryTriangleSet *triangle = NULL;
557 Vector centroid;
558 int n[NDIM];
559 Vector periodicX;
560 Vector checkX;
561
562 if ((Surface == NULL) || (LC == NULL) || (molecules.empty())) {
563 LOG(1, "No Tesselation, no LinkedCell or no molecule given.");
564 return outmap;
565 }
566
567 outmap = new CorrelationToSurfaceMap;
568 double ShortestDistance = 0.;
569 BoundaryTriangleSet *ShortestTriangle = NULL;
570 for (std::vector<molecule *>::const_iterator MolWalker = molecules.begin(); MolWalker != molecules.end(); MolWalker++) {
571 RealSpaceMatrix FullMatrix = World::getInstance().getDomain().getM();
572 RealSpaceMatrix FullInverseMatrix = World::getInstance().getDomain().getMinv();
573 LOG(2, "Current molecule is " << *MolWalker << ".");
574 for (molecule::const_iterator iter = (*MolWalker)->begin(); iter != (*MolWalker)->end(); ++iter) {
575 LOG(3, "Current atom is " << **iter << ".");
576 for (vector<const element *>::const_iterator type = elements.begin(); type != elements.end(); ++type)
577 if ((*type == NULL) || ((*iter)->getType() == *type)) {
578 periodicX = FullInverseMatrix * ((*iter)->getPosition()); // x now in [0,1)^3
579 // go through every range in xyz and get distance
580 ShortestDistance = -1.;
581 for (n[0]=-ranges[0]; n[0] <= ranges[0]; n[0]++)
582 for (n[1]=-ranges[1]; n[1] <= ranges[1]; n[1]++)
583 for (n[2]=-ranges[2]; n[2] <= ranges[2]; n[2]++) {
584 checkX = FullMatrix * (Vector(n[0], n[1], n[2]) + periodicX);
585 TriangleIntersectionList Intersections(checkX,Surface,LC);
586 distance = Intersections.GetSmallestDistance();
587 triangle = Intersections.GetClosestTriangle();
588 if ((ShortestDistance == -1.) || (distance < ShortestDistance)) {
589 ShortestDistance = distance;
590 ShortestTriangle = triangle;
591 }
592 }
593 // insert
594 outmap->insert (
595 std::pair<double,
596 std::pair<const atom *, BoundaryTriangleSet*> >(
597 ShortestDistance,
598 std::pair<const atom *, BoundaryTriangleSet*> (
599 *iter,
600 ShortestTriangle)
601 )
602 );
603 //LOG(1, "INFO: Inserting " << Walker << " with distance " << ShortestDistance << " to " << *ShortestTriangle << ".");
604 }
605 }
606 }
607
608 return outmap;
609};
610
611/** Returns the index of the bin for a given value.
612 * \param value value whose bin to look for
613 * \param BinWidth width of bin
614 * \param BinStart first bin
615 */
616int GetBin ( const double value, const double BinWidth, const double BinStart )
617{
618 //Info FunctionInfo(__func__);
619 int bin =(int) (floor((value - BinStart)/BinWidth));
620 return (bin);
621};
622
623
624/** Adds header part that is unique to BinPairMap.
625 *
626 * @param file stream to print to
627 */
628void OutputCorrelation_Header( ofstream * const file )
629{
630 *file << "\tCount";
631};
632
633/** Prints values stored in BinPairMap iterator.
634 *
635 * @param file stream to print to
636 * @param runner iterator pointing at values to print
637 */
638void OutputCorrelation_Value( ofstream * const file, BinPairMap::const_iterator &runner )
639{
640 *file << runner->second;
641};
642
643
644/** Adds header part that is unique to DipoleAngularCorrelationMap.
645 *
646 * @param file stream to print to
647 */
648void OutputDipoleAngularCorrelation_Header( ofstream * const file )
649{
650 *file << "\tFirstAtomOfMolecule";
651};
652
653/** Prints values stored in DipoleCorrelationMap iterator.
654 *
655 * @param file stream to print to
656 * @param runner iterator pointing at values to print
657 */
658void OutputDipoleAngularCorrelation_Value( ofstream * const file, DipoleAngularCorrelationMap::const_iterator &runner )
659{
660 *file << *(runner->second);
661};
662
663
664/** Adds header part that is unique to DipoleAngularCorrelationMap.
665 *
666 * @param file stream to print to
667 */
668void OutputDipoleCorrelation_Header( ofstream * const file )
669{
670 *file << "\tMolecule";
671};
672
673/** Prints values stored in DipoleCorrelationMap iterator.
674 *
675 * @param file stream to print to
676 * @param runner iterator pointing at values to print
677 */
678void OutputDipoleCorrelation_Value( ofstream * const file, DipoleCorrelationMap::const_iterator &runner )
679{
680 *file << runner->second.first->getId() << "\t" << runner->second.second->getId();
681};
682
683
684/** Adds header part that is unique to PairCorrelationMap.
685 *
686 * @param file stream to print to
687 */
688void OutputPairCorrelation_Header( ofstream * const file )
689{
690 *file << "\tAtom1\tAtom2";
691};
692
693/** Prints values stored in PairCorrelationMap iterator.
694 *
695 * @param file stream to print to
696 * @param runner iterator pointing at values to print
697 */
698void OutputPairCorrelation_Value( ofstream * const file, PairCorrelationMap::const_iterator &runner )
699{
700 *file << *(runner->second.first) << "\t" << *(runner->second.second);
701};
702
703
704/** Adds header part that is unique to CorrelationToPointMap.
705 *
706 * @param file stream to print to
707 */
708void OutputCorrelationToPoint_Header( ofstream * const file )
709{
710 *file << "\tAtom::x[i]-point.x[i]";
711};
712
713/** Prints values stored in CorrelationToPointMap iterator.
714 *
715 * @param file stream to print to
716 * @param runner iterator pointing at values to print
717 */
718void OutputCorrelationToPoint_Value( ofstream * const file, CorrelationToPointMap::const_iterator &runner )
719{
720 for (int i=0;i<NDIM;i++)
721 *file << "\t" << setprecision(8) << (runner->second.first->at(i) - runner->second.second->at(i));
722};
723
724
725/** Adds header part that is unique to CorrelationToSurfaceMap.
726 *
727 * @param file stream to print to
728 */
729void OutputCorrelationToSurface_Header( ofstream * const file )
730{
731 *file << "\tTriangle";
732};
733
734/** Prints values stored in CorrelationToSurfaceMap iterator.
735 *
736 * @param file stream to print to
737 * @param runner iterator pointing at values to print
738 */
739void OutputCorrelationToSurface_Value( ofstream * const file, CorrelationToSurfaceMap::const_iterator &runner )
740{
741 *file << *(runner->second.first) << "\t" << *(runner->second.second);
742};
Note: See TracBrowser for help on using the repository browser.