source: src/molecule.hpp@ b71881

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

Added select() and unselect() functions to atom and molecule, also SelectionChanged channel.

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