source: src/molecule.hpp@ db842b

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

FIX: molecule's BoundingBoxSweepingAxis used unordered set of atomids.

  • this needs to be an ordered set to prevent O(N) access on updating values.
  • Property mode set to 100755
File size: 14.2 KB
Line 
1/** \file molecule.hpp
2 *
3 * Class definitions of atom and molecule, element and periodentafel
4 */
5
6#ifndef MOLECULES_HPP_
7#define MOLECULES_HPP_
8
9/*********************************************** includes ***********************************/
10
11#ifdef HAVE_CONFIG_H
12#include <config.h>
13#endif
14
15//// STL headers
16#include <map>
17#include <set>
18#include <stack>
19#include <deque>
20#include <list>
21#include <vector>
22
23#include <string>
24
25#include <boost/bimap/bimap.hpp>
26#include <boost/bimap/unordered_set_of.hpp>
27#include <boost/bimap/multiset_of.hpp>
28#include <boost/optional.hpp>
29#include <boost/shared_ptr.hpp>
30
31#include "AtomIdSet.hpp"
32#include "Atom/AtomSet.hpp"
33#include "CodePatterns/Cacheable.hpp"
34#include "CodePatterns/Observer/Observable.hpp"
35#include "Descriptors/AtomIdDescriptor.hpp"
36#include "Fragmentation/HydrogenSaturation_enum.hpp"
37#include "Formula.hpp"
38#include "Helpers/defs.hpp"
39#include "IdPool_policy.hpp"
40#include "IdPool.hpp"
41#include "Shapes/Shape.hpp"
42#include "types.hpp"
43
44/****************************************** forward declarations *****************************/
45
46class atom;
47class bond;
48class BondedParticle;
49class BondGraph;
50class DepthFirstSearchAnalysis;
51class element;
52class ForceMatrix;
53class Graph;
54class LinkedCell_deprecated;
55class ListOfLocalAtoms_t;
56class molecule;
57class MoleculeLeafClass;
58class MoleculeUnittest;
59class RealSpaceMatrix;
60class Vector;
61
62/************************************* Class definitions ****************************************/
63
64/** External function to remove all atoms since this will also delete the molecule
65 *
66 * \param _mol ref pointer to molecule to destroy
67 */
68void removeAtomsinMolecule(molecule *&_mol);
69
70/** The complete molecule.
71 * Class incorporates number of types
72 */
73class molecule : public Observable
74{
75 //!> grant unit test access
76 friend class MoleculeUnittest;
77 //!> function may access cstor
78 friend molecule *NewMolecule();
79 //!> function may access dstor
80 friend void DeleteMolecule(molecule *);
81
82public:
83 typedef AtomIdSet::atomIdSet atomIdSet;
84 typedef AtomIdSet::iterator iterator;
85 typedef AtomIdSet::const_iterator const_iterator;
86
87 int MDSteps; //!< The number of MD steps in Trajectories
88 mutable int NoNonBonds; //!< number of non-hydrogen bonds in molecule
89 mutable int NoCyclicBonds; //!< number of cyclic bonds in molecule, by DepthFirstSearchAnalysis()
90 bool ActiveFlag; //!< in a MoleculeListClass used to discern active from inactive molecules
91 int IndexNr; //!< index of molecule in a MoleculeListClass
92 char name[MAXSTRINGSIZE]; //!< arbitrary name
93
94private:
95 Formula formula;
96 size_t NoNonHydrogen; //!< number of non-hydrogen atoms in molecule
97 int BondCount; //!< number of atoms, brought up-to-date by doCountBonds()
98 moleculeId_t id;
99 AtomIdSet atomIds; //<!set of atomic ids to check uniqueness of atoms
100 IdPool<atomId_t, uniqueId> atomIdPool; //!< pool of internal ids such that way may guarantee uniqueness
101 typedef std::map<atomId_t,atom *> LocalToGlobalId_t;
102 LocalToGlobalId_t LocalToGlobalId; //!< internal map to ease FindAtom
103
104protected:
105
106 molecule();
107 virtual ~molecule();
108
109public:
110
111 /******* Notifications *******/
112
113 //!> enumeration of present notification types: only insertion/removal of atoms or molecules
114 enum NotificationType {
115 AtomInserted,
116 AtomRemoved,
117 AtomNrChanged,
118 AtomMoved,
119 FormulaChanged,
120 MoleculeCenterChanged,
121 MoleculeNameChanged,
122 IndexChanged,
123 BoundingBoxChanged,
124 AboutToBeRemoved,
125 SelectionChanged,
126 NotificationType_MAX
127 };
128
129 //>! access to last changed element (atom)
130 const atomId_t lastChangedAtomId() const
131 { return _lastchangedatomid; }
132
133public:
134 //getter and setter
135 const std::string getName() const;
136 int getAtomCount() const;
137 size_t getNoNonHydrogen() const{
138 return NoNonHydrogen;
139 }
140
141 int getBondCount() const{
142 return BondCount;
143 }
144 moleculeId_t getId() const;
145 void setId(moleculeId_t);
146 void setName(const std::string);
147 const Formula &getFormula() const;
148 unsigned int getElementCount() const;
149 bool hasElement(const element*) const;
150 bool hasElement(atomicNumber_t) const;
151 bool hasElement(const std::string&) const;
152
153 virtual bool changeId(atomId_t newId);
154
155 World::AtomComposite getAtomSet();
156 World::ConstAtomComposite getAtomSet() const;
157
158 // simply pass on all functions to AtomIdSet
159 iterator begin() {
160 return atomIds.begin();
161 }
162 const_iterator begin() const
163 {
164 return atomIds.begin();
165 }
166 iterator end()
167 {
168 return atomIds.end();
169 }
170 const_iterator end() const
171 {
172 return atomIds.end();
173 }
174 bool empty() const
175 {
176 return atomIds.empty();
177 }
178 size_t size() const
179 {
180 return atomIds.size();
181 }
182 const_iterator find(atom * key) const
183 {
184 return atomIds.find(key);
185 }
186
187 /** Returns the set of atomic ids contained in this molecule.
188 *
189 * @return set of atomic ids
190 */
191 const atomIdSet & getAtomIds() const {
192 return atomIds.getAtomIds();
193 }
194
195 std::pair<iterator, bool> insert(atom * const key);
196
197 /** Predicate whether given \a key is contained in this molecule.
198 *
199 * @param key atom to check
200 * @return true - is contained, false - else
201 */
202 bool containsAtom(const atom* key) const
203 {
204 return atomIds.contains(key);
205 }
206
207 /** Predicate whether given \a id is contained in this molecule.
208 *
209 * @param id atomic id to check
210 * @return true - is contained, false - else
211 */
212 bool containsAtom(const atomId_t id) const
213 {
214 return atomIds.contains(id);
215 }
216
217private:
218 friend void atom::removeFromMolecule();
219 /** Erase an atom from the list.
220 * \note This should only be called by atom::removeFromMolecule(),
221 * otherwise it is not assured that the atom knows about it.
222 *
223 * @param loc locator to atom in list
224 * @return iterator to just after removed item (compliant with standard)
225 */
226 const_iterator erase(const_iterator loc);
227
228 /** Erase an atom from the list.
229 * \note This should only be called by atom::removeFromMolecule(),
230 * otherwise it is not assured that the atom knows about it.
231 *
232 * @param *key key to atom in list
233 * @return iterator to just after removed item (compliant with standard)
234 */
235 const_iterator erase(atom * key);
236
237private:
238 friend bool atom::changeNr(int newId);
239 /**
240 * used when changing an ParticleInfo::Nr.
241 * Note that this number is local with this molecule.
242 * Unless you are calling this method from inside an atom don't fiddle with the third parameter.
243 *
244 * @param oldNr old Nr
245 * @param newNr new Nr to set
246 * @param *target ref to atom
247 * @return indicates wether the change could be done or not.
248 */
249 bool changeAtomNr(int oldNr, int newNr, atom* target=0);
250
251 friend bool atom::changeId(atomId_t newId);
252 /**
253 * used when changing an ParticleInfo::Id.
254 * Note that this number is global (and the molecule uses it to know which atoms belong to it)
255 *
256 * @param oldId old Id
257 * @param newId new Id to set
258 * @return indicates wether the change could be done or not.
259 */
260 bool changeAtomId(int oldId, int newId);
261
262 /** Updates the internal lookup fro local to global indices.
263 *
264 * \param pointer pointer to atom
265 */
266 void InsertLocalToGlobalId(atom * const pointer);
267
268 /** Sets the name of the atom.
269 *
270 * The name is set via its element symbol and its internal ParticleInfo::Nr.
271 *
272 * @param _atom atom whose name to set
273 */
274 void setAtomName(atom *_atom) const;
275
276 //!> grant World (only) access to selection state changers
277 friend class World;
278
279 /** Sets the internal selection state to true.
280 *
281 */
282 void select();
283
284 /** Unsets the internal selection state to true.
285 *
286 */
287 void unselect();
288
289public:
290
291 /** Getter to internal selection status.
292 *
293 * \return true - molecule is selected, false - else
294 */
295 bool getSelected() const { return selected; }
296
297 /** Structure for the required information on the bounding box.
298 *
299 */
300 struct BoundingBoxInfo {
301 //!> position of center
302 Vector position;
303 //!> radius of sphere
304 double radius;
305
306 /** Equivalence operator for bounding box.
307 *
308 * \return true - both bounding boxes have same position and radius
309 */
310 bool operator==(const BoundingBoxInfo &_other) const
311 { return (radius == _other.radius) && (position == _other.position); }
312
313 /** Inequivalence operator for bounding box.
314 *
315 * \return true - bounding boxes have either different positions or different radii or both
316 */
317 bool operator!=(const BoundingBoxInfo &_other) const
318 { return !(*this == _other); }
319 };
320
321private:
322
323 /** Returns the current bounding box.
324 *
325 * \return Shape with center and extension of box
326 */
327 BoundingBoxInfo updateBoundingBox() const;
328
329 /** Returns the current center of the molecule.
330 *
331 * \return center
332 */
333 Vector updateMoleculeCenter() const;
334
335 // stuff for keeping bounding box up-to-date efficiently
336
337 //!> Cacheable for the bounding box, ptr such that
338 boost::shared_ptr< Cacheable<BoundingBoxInfo> > BoundingBox;
339
340 //!> Cacheable for the bounding box, ptr such that
341 boost::shared_ptr< Cacheable<Vector> > MoleculeCenter;
342
343 /** Bimap storing atomic ids and the component per axis.
344 *
345 * We need a bimap in order to have the components sorted and be able to
346 * access max and min values in linear time and also access the ids in
347 * constant time in order to update the map, when atoms move, are inserted,
348 * or removed.
349 */
350 typedef boost::bimaps::bimap<
351 boost::bimaps::set_of< atomId_t >,
352 boost::bimaps::multiset_of< double, std::greater<double> >
353 > AtomDistanceMap_t;
354 std::vector<AtomDistanceMap_t> BoundingBoxSweepingAxis;
355
356 //!> typedef for a map with current bond counts per atom
357 typedef std::map<atomId_t, size_t> BondCountsPerAtom_t;
358
359 //!> current bond counts per atom to update the BondCount
360 BondCountsPerAtom_t BondCountsPerAtom;
361
362 //!> typedef for a map with current element per atom
363 typedef std::map<atomId_t, atomicNumber_t> ElementPerAtom_t;
364
365 //!> current element per atom to update the BondCount
366 ElementPerAtom_t ElementPerAtom;
367
368 //!> make setMolecule friend to access associateAtomWithMolecule()
369 friend void atom::setMolecule(molecule *);
370
371 /** Helper function only to be called by specific atom function.
372 *
373 * \param _atom atom to be added to this molecule
374 */
375 void associateAtomWithMolecule(atom *_atom);
376
377 /** Helper function only to be called by specific atom function.
378 *
379 * \param _atom atom to be added to this molecule
380 */
381 void disassociateAtomWithMolecule(atom *_atom);
382
383public:
384
385 /** Returns the current bounding box of this molecule.
386 *
387 * \return bounding box info with center and radius
388 */
389 BoundingBoxInfo getBoundingBox() const;
390
391 /** Function to create a bounding spherical shape for the currently associated atoms.
392 *
393 * \param boundary extra boundary of shape around (i.e. distance between outermost atom
394 * and the shape's surface)
395 */
396 Shape getBoundingSphere(const double boundary = 0.) const;
397
398 /** Creates the bounding box by adding van der Waals-Spheres around every atom.
399 *
400 * \param scale extra scale parameter to enlarge the spheres artifically
401 */
402 Shape getBoundingShape(const double scale = 1.) const;
403
404 /** Returns the current center of this molecule.
405 *
406 * \return center of the molecule
407 */
408 Vector getMoleculeCenter() const;
409
410 /// remove atoms from molecule.
411 bool AddAtom(atom *pointer);
412 bool RemoveAtom(atom *pointer);
413 bool UnlinkAtom(atom *pointer);
414 bool CleanupMolecule();
415
416 /// Add/remove atoms to/from molecule.
417 atom * AddCopyAtom(atom *pointer);
418// bool AddHydrogenReplacementAtom(bond::ptr Bond, atom *BottomOrigin, atom *TopOrigin, atom *TopReplacement, bool IsAngstroem);
419 bond::ptr AddBond(atom *first, atom *second, int degree = 1);
420 bool hasBondStructure() const;
421
422 /// Find atoms.
423 atom * FindAtom(int Nr) const;
424 atom * AskAtom(std::string text);
425 bool isInMolecule(const atom * const _atom) const;
426
427 /// Count and change present atoms' coordination.
428 bool CenterInBox();
429 bool BoundInBox();
430 void CenterEdge();
431 void CenterOrigin();
432 void CenterPeriodic();
433 void CenterAtVector(const Vector &newcenter);
434 void Translate(const Vector &x);
435 void TranslatePeriodically(const Vector &trans);
436 void Mirror(const Vector &x);
437 void Align(const Vector &n);
438 void Scale(const double *factor);
439 void DeterminePeriodicCenter(Vector &center, const enum HydrogenTreatment _treatment = ExcludeHydrogen);
440 const Vector DetermineCenterOfGravity() const;
441 const Vector DetermineCenterOfAll() const;
442 void SetNameFromFilename(const char *filename);
443 bool ScanForPeriodicCorrection();
444 double VolumeOfConvexEnvelope(bool IsAngstroem);
445 RealSpaceMatrix getInertiaTensor() const;
446 void RotateToPrincipalAxisSystem(const Vector &Axis);
447
448 bool CheckBounds(const Vector *x) const;
449 void GetAlignvector(struct lsq_params * par) const;
450
451 /// Initialising routines in fragmentation
452 void OutputBondsList() const;
453
454 bond::ptr CopyBond(atom *left, atom *right, bond::ptr CopyBond);
455
456 molecule *CopyMolecule(const Vector &offset = zeroVec);
457 molecule* CopyMoleculeFromSubRegion(const Shape&);
458
459 /// Fragment molecule by two different approaches:
460 bool StoreBondsToFile(std::string filename, std::string path = "");
461 bool CreateFatherLookupTable(ListOfLocalAtoms_t &LookupTable, int count = 0);
462
463 // Recognize doubly appearing molecules in a list of them
464 int * GetFatherSonAtomicMap(const molecule * const OtherMolecule);
465 bool FillBondStructureFromReference(const molecule * const reference, ListOfLocalAtoms_t &ListOfLocalAtoms, bool FreeList = false);
466 bool FillListOfLocalAtoms(ListOfLocalAtoms_t &ListOfLocalAtoms, const int GlobalAtomCount);
467
468 // Output routines.
469 bool Output(std::ostream * const output) const;
470 void OutputListOfBonds() const;
471
472 // Manipulation routines
473 void flipActiveFlag();
474
475 virtual void update(Observable *publisher);
476 virtual void recieveNotification(Observable *publisher, Notification_ptr notification);
477 virtual void subjectKilled(Observable *publisher);
478
479private:
480 //!> id of last atom that signalled changed associated with this molecule
481 atomId_t _lastchangedatomid;
482
483 int last_atom; //!< number given to last atom
484
485 //!> center of the molecule
486 Vector molcenter;
487
488 //!> internal state whether atom is selected or not
489 bool selected;
490};
491
492molecule *NewMolecule();
493void DeleteMolecule(molecule* mol);
494
495
496
497#endif /*MOLECULES_HPP_*/
498
Note: See TracBrowser for help on using the repository browser.