source: src/molecule.hpp@ 29f7c1

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

Molecule now has maps with old values for bond counts and element number per atom.

  • this allows to update the total bond count and the formula in an O(N log N) fashion.
  • Property mode set to 100755
File size: 14.5 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 doCountNoNonHydrogen() const;
138 int doCountBonds() const;
139 size_t getNoNonHydrogen() const{
140 return NoNonHydrogen;
141 }
142
143 int getBondCount() const{
144 return BondCount;
145 }
146 moleculeId_t getId() const;
147 void setId(moleculeId_t);
148 void setName(const std::string);
149 const Formula &getFormula() const;
150 unsigned int getElementCount() const;
151 bool hasElement(const element*) const;
152 bool hasElement(atomicNumber_t) const;
153 bool hasElement(const std::string&) const;
154
155 virtual bool changeId(atomId_t newId);
156
157 World::AtomComposite getAtomSet();
158 World::ConstAtomComposite getAtomSet() const;
159
160 // simply pass on all functions to AtomIdSet
161 iterator begin() {
162 return atomIds.begin();
163 }
164 const_iterator begin() const
165 {
166 return atomIds.begin();
167 }
168 iterator end()
169 {
170 return atomIds.end();
171 }
172 const_iterator end() const
173 {
174 return atomIds.end();
175 }
176 bool empty() const
177 {
178 return atomIds.empty();
179 }
180 size_t size() const
181 {
182 return atomIds.size();
183 }
184 const_iterator find(atom * key) const
185 {
186 return atomIds.find(key);
187 }
188
189 /** Returns the set of atomic ids contained in this molecule.
190 *
191 * @return set of atomic ids
192 */
193 const atomIdSet & getAtomIds() const {
194 return atomIds.getAtomIds();
195 }
196
197 std::pair<iterator, bool> insert(atom * const key);
198
199 /** Predicate whether given \a key is contained in this molecule.
200 *
201 * @param key atom to check
202 * @return true - is contained, false - else
203 */
204 bool containsAtom(const atom* key) const
205 {
206 return atomIds.contains(key);
207 }
208
209 /** Predicate whether given \a id is contained in this molecule.
210 *
211 * @param id atomic id to check
212 * @return true - is contained, false - else
213 */
214 bool containsAtom(const atomId_t id) const
215 {
216 return atomIds.contains(id);
217 }
218
219private:
220 friend void atom::removeFromMolecule();
221 /** Erase an atom from the list.
222 * \note This should only be called by atom::removeFromMolecule(),
223 * otherwise it is not assured that the atom knows about it.
224 *
225 * @param loc locator to atom in list
226 * @return iterator to just after removed item (compliant with standard)
227 */
228 const_iterator erase(const_iterator loc);
229
230 /** Erase an atom from the list.
231 * \note This should only be called by atom::removeFromMolecule(),
232 * otherwise it is not assured that the atom knows about it.
233 *
234 * @param *key key to atom in list
235 * @return iterator to just after removed item (compliant with standard)
236 */
237 const_iterator erase(atom * key);
238
239private:
240 friend bool atom::changeNr(int newId);
241 /**
242 * used when changing an ParticleInfo::Nr.
243 * Note that this number is local with this molecule.
244 * Unless you are calling this method from inside an atom don't fiddle with the third parameter.
245 *
246 * @param oldNr old Nr
247 * @param newNr new Nr to set
248 * @param *target ref to atom
249 * @return indicates wether the change could be done or not.
250 */
251 bool changeAtomNr(int oldNr, int newNr, atom* target=0);
252
253 friend bool atom::changeId(atomId_t newId);
254 /**
255 * used when changing an ParticleInfo::Id.
256 * Note that this number is global (and the molecule uses it to know which atoms belong to it)
257 *
258 * @param oldId old Id
259 * @param newId new Id to set
260 * @return indicates wether the change could be done or not.
261 */
262 bool changeAtomId(int oldId, int newId);
263
264 /** Updates the internal lookup fro local to global indices.
265 *
266 * \param pointer pointer to atom
267 */
268 void InsertLocalToGlobalId(atom * const pointer);
269
270 /** Sets the name of the atom.
271 *
272 * The name is set via its element symbol and its internal ParticleInfo::Nr.
273 *
274 * @param _atom atom whose name to set
275 */
276 void setAtomName(atom *_atom) const;
277
278 /** Resets the formula for this molecule.
279 *
280 * This is required in case an atom changes its element as we then don't
281 * have any knowledge about its previous element anymore.
282 */
283 void resetFormula();
284
285 //!> grant World (only) access to selection state changers
286 friend class World;
287
288 /** Sets the internal selection state to true.
289 *
290 */
291 void select();
292
293 /** Unsets the internal selection state to true.
294 *
295 */
296 void unselect();
297
298public:
299
300 /** Getter to internal selection status.
301 *
302 * \return true - molecule is selected, false - else
303 */
304 bool getSelected() const { return selected; }
305
306 /** Structure for the required information on the bounding box.
307 *
308 */
309 struct BoundingBoxInfo {
310 //!> position of center
311 Vector position;
312 //!> radius of sphere
313 double radius;
314
315 /** Equivalence operator for bounding box.
316 *
317 * \return true - both bounding boxes have same position and radius
318 */
319 bool operator==(const BoundingBoxInfo &_other) const
320 { return (radius == _other.radius) && (position == _other.position); }
321
322 /** Inequivalence operator for bounding box.
323 *
324 * \return true - bounding boxes have either different positions or different radii or both
325 */
326 bool operator!=(const BoundingBoxInfo &_other) const
327 { return !(*this == _other); }
328 };
329
330private:
331
332 /** Returns the current bounding box.
333 *
334 * \return Shape with center and extension of box
335 */
336 BoundingBoxInfo updateBoundingBox() const;
337
338 /** Returns the current center of the molecule.
339 *
340 * \return center
341 */
342 Vector updateMoleculeCenter() const;
343
344 // stuff for keeping bounding box up-to-date efficiently
345
346 //!> Cacheable for the bounding box, ptr such that
347 boost::shared_ptr< Cacheable<BoundingBoxInfo> > BoundingBox;
348
349 //!> Cacheable for the bounding box, ptr such that
350 boost::shared_ptr< Cacheable<Vector> > MoleculeCenter;
351
352 /** Bimap storing atomic ids and the component per axis.
353 *
354 * We need a bimap in order to have the components sorted and be able to
355 * access max and min values in linear time and also access the ids in
356 * constant time in order to update the map, when atoms move, are inserted,
357 * or removed.
358 */
359 typedef boost::bimaps::bimap<
360 boost::bimaps::unordered_set_of< atomId_t >,
361 boost::bimaps::multiset_of< double, std::greater<double> >
362 > AtomDistanceMap_t;
363 std::vector<AtomDistanceMap_t> BoundingBoxSweepingAxis;
364
365 //!> typedef for a map with current bond counts per atom
366 typedef std::map<atomId_t, size_t> BondCountsPerAtom_t;
367
368 //!> current bond counts per atom to update the BondCount
369 BondCountsPerAtom_t BondCountsPerAtom;
370
371 //!> typedef for a map with current element per atom
372 typedef std::map<atomId_t, atomicNumber_t> ElementPerAtom_t;
373
374 //!> current element per atom to update the BondCount
375 ElementPerAtom_t ElementPerAtom;
376
377 //!> make setMolecule friend to access associateAtomWithMolecule()
378 friend void atom::setMolecule(molecule *);
379
380 /** Helper function only to be called by specific atom function.
381 *
382 * \param _atom atom to be added to this molecule
383 */
384 void associateAtomWithMolecule(atom *_atom);
385
386 /** Helper function only to be called by specific atom function.
387 *
388 * \param _atom atom to be added to this molecule
389 */
390 void disassociateAtomWithMolecule(atom *_atom);
391
392public:
393
394 /** Returns the current bounding box of this molecule.
395 *
396 * \return bounding box info with center and radius
397 */
398 BoundingBoxInfo getBoundingBox() const;
399
400 /** Function to create a bounding spherical shape for the currently associated atoms.
401 *
402 * \param boundary extra boundary of shape around (i.e. distance between outermost atom
403 * and the shape's surface)
404 */
405 Shape getBoundingSphere(const double boundary = 0.) const;
406
407 /** Creates the bounding box by adding van der Waals-Spheres around every atom.
408 *
409 * \param scale extra scale parameter to enlarge the spheres artifically
410 */
411 Shape getBoundingShape(const double scale = 1.) const;
412
413 /** Returns the current center of this molecule.
414 *
415 * \return center of the molecule
416 */
417 Vector getMoleculeCenter() const;
418
419 /// remove atoms from molecule.
420 bool AddAtom(atom *pointer);
421 bool RemoveAtom(atom *pointer);
422 bool UnlinkAtom(atom *pointer);
423 bool CleanupMolecule();
424
425 /// Add/remove atoms to/from molecule.
426 atom * AddCopyAtom(atom *pointer);
427// bool AddHydrogenReplacementAtom(bond::ptr Bond, atom *BottomOrigin, atom *TopOrigin, atom *TopReplacement, bool IsAngstroem);
428 bond::ptr AddBond(atom *first, atom *second, int degree = 1);
429 bool hasBondStructure() const;
430
431 /// Find atoms.
432 atom * FindAtom(int Nr) const;
433 atom * AskAtom(std::string text);
434 bool isInMolecule(const atom * const _atom) const;
435
436 /// Count and change present atoms' coordination.
437 bool CenterInBox();
438 bool BoundInBox();
439 void CenterEdge();
440 void CenterOrigin();
441 void CenterPeriodic();
442 void CenterAtVector(const Vector &newcenter);
443 void Translate(const Vector &x);
444 void TranslatePeriodically(const Vector &trans);
445 void Mirror(const Vector &x);
446 void Align(const Vector &n);
447 void Scale(const double *factor);
448 void DeterminePeriodicCenter(Vector &center, const enum HydrogenTreatment _treatment = ExcludeHydrogen);
449 const Vector DetermineCenterOfGravity() const;
450 const Vector DetermineCenterOfAll() const;
451 void SetNameFromFilename(const char *filename);
452 bool ScanForPeriodicCorrection();
453 double VolumeOfConvexEnvelope(bool IsAngstroem);
454 RealSpaceMatrix getInertiaTensor() const;
455 void RotateToPrincipalAxisSystem(const Vector &Axis);
456
457 bool CheckBounds(const Vector *x) const;
458 void GetAlignvector(struct lsq_params * par) const;
459
460 /// Initialising routines in fragmentation
461 void OutputBondsList() const;
462
463 bond::ptr CopyBond(atom *left, atom *right, bond::ptr CopyBond);
464
465 molecule *CopyMolecule(const Vector &offset = zeroVec);
466 molecule* CopyMoleculeFromSubRegion(const Shape&);
467
468 /// Fragment molecule by two different approaches:
469 bool StoreBondsToFile(std::string filename, std::string path = "");
470 bool CreateFatherLookupTable(ListOfLocalAtoms_t &LookupTable, int count = 0);
471
472 // Recognize doubly appearing molecules in a list of them
473 int * GetFatherSonAtomicMap(const molecule * const OtherMolecule);
474 bool FillBondStructureFromReference(const molecule * const reference, ListOfLocalAtoms_t &ListOfLocalAtoms, bool FreeList = false);
475 bool FillListOfLocalAtoms(ListOfLocalAtoms_t &ListOfLocalAtoms, const int GlobalAtomCount);
476
477 // Output routines.
478 bool Output(std::ostream * const output) const;
479 void OutputListOfBonds() const;
480
481 // Manipulation routines
482 void flipActiveFlag();
483
484 virtual void update(Observable *publisher);
485 virtual void recieveNotification(Observable *publisher, Notification_ptr notification);
486 virtual void subjectKilled(Observable *publisher);
487
488private:
489 //!> id of last atom that signalled changed associated with this molecule
490 atomId_t _lastchangedatomid;
491
492 int last_atom; //!< number given to last atom
493
494 //!> center of the molecule
495 Vector molcenter;
496
497 //!> internal state whether atom is selected or not
498 bool selected;
499};
500
501molecule *NewMolecule();
502void DeleteMolecule(molecule* mol);
503
504
505
506#endif /*MOLECULES_HPP_*/
507
Note: See TracBrowser for help on using the repository browser.