source: src/helpers.hpp@ 3ccc3e

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

BUGFIXES: CyclicStructureAnalysis() now compatible to disconnected subgraphs, AssignKeySetsToFragment() and FillBondStructureFromReference() memory cleanup corrected

+ molecule::DepthFirstSearchAnalysis() now just returns BackEdgeStack, not MinimumRingSize. CyclicStructureAnalysis() is called during FragmentMolecule(), after subgraphs bonds list have been filled by FillBondStructureFromReference().
+ new function molecule::PickLocalBackEdges(), as the BackEdgeStack returned by DepthFirstSearchAnalysis() co
ntains only global bonds, not the local ones for the subgraph, we have to step through it and pick the right
ones out.
+ molecule::FragmentMolecule() now calls molecule::CyclicStructureAnalysis() separately for each subgraph, along with a BackEdgeStack filled by PickLocalBackEdges(), and allocates&initialises MinimumRingSize array. Als
o AssignKeySetsToFragment() frees the LocalListOfAtoms now (FreeList=true), now longer after the following wh
ile
+ molecule::CyclicStructureAnalysis() takes a local BackEdgeStack and analysis the subgraphs cycles, returnin
g minimum ring size
+ MoleculeLeafClass::AssignKeySetsToFragment() now frees memory for ListOfLocalAtoms when FreeList is set. BUGFIX: test of first key was testing against ..->nr != -1. However, LocalListOfAtoms was not even initialised correctly to NULL, hence ...->nr pointed in some cases to nowhere. Now it test atom* against NULL.
+ MoleculeLeafClass::FillBondStructureFromReference() now frees memory for ListOfLocalAtoms when FreeList is set correctly (only free initial pointer when FragmentCounter == 0, also it was decreased not before but after freeing, hence we free'd the wrong list). Also, father replaced by GetTrueFather() (makes the function moregenerally useable, was not a bug).
+ ParseCommandLineOptions() option 'D': adapted to changes in DepthFirstSearchAnalysis() in a similar manner
to FragmentMolecule()
+ molecule::CountCyclicBonds() adapted but does not perform CyclicStructureAnalysis()
+ molecule::CreateAdjacencyList() counts the bonds that could not be brought to covalently corrected degree (i.e. the remaining ionic atoms)
+ molecule::CreateListOfBondsPerAtom() prints atom names and number, which is helpful as name contains global

and number contains local number (helped in finding above bugs)

+ CreateFatherLookupTable(): BUGFIX: LookupTable was not initialised to NULL (see above)

  • Property mode set to 100644
File size: 8.3 KB
Line 
1/** \file helpers.hpp
2 *
3 * Declaration of some auxiliary functions for memory dis-/allocation and so on
4 */
5
6#ifndef HELPERS_HPP_
7#define HELPERS_HPP_
8
9using namespace std;
10
11#include <iostream>
12#include <iomanip>
13#include <fstream>
14#include <sstream>
15#include <math.h>
16#include <string>
17#include <string.h>
18#include <stdio.h>
19#include <stdlib.h>
20#include <time.h>
21
22#include "defs.hpp"
23
24// include config.h
25#ifdef HAVE_CONFIG_H
26#include <config.h>
27#endif
28
29/********************************************** helpful functions *********************************/
30
31// taken out of TREMOLO
32/*@-namechecks@*/
33#ifndef __GNUC__
34# undef __attribute__
35# define __attribute__(x)
36#endif
37/*@=namechecks@*/
38
39/* Behandelt aufgetretene Fehler. error ist der Fehlertyp(enum Errors)
40 void *SpecialData ist ein untypisierter Zeiger auf Spezielle Daten zur Fehlerbehandlung.
41 Man koennte auch noch einen Zeiger auf eine Funktion uebergeben */
42extern void /*@exits@*/ debug(const char *output);
43 //__attribute__ ((__return__));
44#define debug(data) debug_in((data), __FILE__, __LINE__)
45
46extern void /*@exits@*/ debug_in(const char *output,
47 const char *file, const int line);
48 //__attribute__ ((__return__));
49
50double ask_value(const char *text);
51bool check_bounds(double *x, double *cell_size);
52void bound(double *b, double lower_bound, double upper_bound);
53void flip(double *x, double *y);
54int pot(int base, int n);
55void * Malloc(size_t size, const char* output);
56void * Calloc(size_t size, const char* output);
57void * ReAlloc(void * OldPointer, size_t size, const char* output);
58char* MallocString(size_t size, const char* output);
59void Free(void ** buffer, const char* output);
60char *FixedDigitNumber(const int FragmentNumber, const int digits);
61
62/********************************************** helpful template functions *********************************/
63
64/** Creates a lookup table for true father's Atom::Nr -> atom ptr.
65 * \param *out output stream for debugging
66 * \param *start begin of chain list
67 * \paran *end end of chain list
68 * \param **Lookuptable pointer to return allocated lookup table (should be NULL on start)
69 * \param count optional predetermined count for table (otherwise we set the count to highest true father id)
70 * \return true - success, false - failure
71 */
72template <typename T> bool CreateFatherLookupTable(ofstream *out, T *start, T *end, T **&LookupTable, int count = 0)
73{
74 bool status = true;
75 T *Walker = NULL;
76 int AtomNo;
77
78 if (LookupTable != NULL) {
79 *out << "Pointer for Lookup table is not NULL! Aborting ..." <<endl;
80 return false;
81 }
82
83 // count them
84 if (count == 0) {
85 Walker = start;
86 while (Walker->next != end) { // create a lookup table (Atom::nr -> atom) used as a marker table lateron
87 Walker = Walker->next;
88 count = (count < Walker->GetTrueFather()->nr) ? Walker->GetTrueFather()->nr : count;
89 }
90 }
91 if (count <= 0) {
92 *out << "Count of lookup list is 0 or less." << endl;
93 return false;
94 }
95
96 // allocat and fill
97 LookupTable = (T **) Malloc(sizeof(T *)*count, "CreateFatherLookupTable - **LookupTable");
98 if (LookupTable == NULL) {
99 cerr << "LookupTable memory allocation failed!" << endl;
100 status = false;
101 } else {
102 for (int i=0;i<count;i++)
103 LookupTable[i] = NULL;
104 Walker = start;
105 while (Walker->next != end) { // create a lookup table (Atom::nr -> atom) used as a marker table lateron
106 Walker = Walker->next;
107 AtomNo = Walker->GetTrueFather()->nr;
108 if ((AtomNo >= 0) && (AtomNo < count)) {
109 //*out << "Setting LookupTable[" << AtomNo << "] to " << *Walker << endl;
110 LookupTable[AtomNo] = Walker;
111 } else {
112 *out << "Walker " << *Walker << " exceeded range of nuclear ids [0, " << count << ")." << endl;
113 status = false;
114 break;
115 }
116 }
117 }
118
119 return status;
120};
121
122/******************************** Some templates for list management ***********************************/
123
124/** Adds linking of an item to a list.
125 * \param *walker
126 * \return true - adding succeeded, false - error in list
127 */
128template <typename X> void link(X *walker, X *end)
129{
130 X *vorher = end->previous;
131 if (vorher != NULL)
132 vorher->next = walker;
133 end->previous = walker;
134 walker->previous = vorher;
135 walker->next = end;
136};
137
138/** Removes linking of an item in a list.
139 * \param *walker
140 * \return true - removing succeeded, false - given item not found in list
141 */
142template <typename X> void unlink(X *walker)
143{
144 if (walker->next != NULL)
145 walker->next->previous = walker->previous;
146 if (walker->previous != NULL)
147 walker->previous->next = walker->next;
148};
149
150/** Adds new item before an item \a *end in a list.
151 * \param *pointer item to be added
152 * \param *end end of list
153 * \return true - addition succeeded, false - unable to add item to list
154 */
155template <typename X> bool add(X *pointer, X *end)
156{
157 if (end != NULL) {
158 link(pointer, end);
159 } else {
160 pointer->previous = NULL;
161 pointer->next = NULL;
162 }
163 return true;
164};
165
166/** Finds item in list
167 * \param *suche search criteria
168 * \param *start begin of list
169 * \param *end end of list
170 * \return X - if found, NULL - if not found
171 */
172template <typename X, typename Y> X * find(Y *suche, X *start, X *end)
173{
174 X *walker = start;
175 while (walker->next != end) { // go through list
176 walker = walker->next; // step onward beforehand
177 if (*walker->sort == *suche) return (walker);
178 }
179 return NULL;
180};
181
182/** Removes an item from the list without check.
183 * \param *walker item to be removed
184 * \return true - removing succeeded, false - given item not found in list
185 */
186template <typename X> void removewithoutcheck(X *walker)
187{
188 if (walker != NULL) {
189 unlink(walker);
190 delete(walker);
191 walker = NULL;
192 }
193};
194
195/** Removes an item from the list, checks if exists.
196 * Checks beforehand if atom is really within molecule list.
197 * \param *pointer item to be removed
198 * \param *start begin of list
199 * \param *end end of list
200 * \return true - removing succeeded, false - given item not found in list
201 */
202template <typename X> bool remove(X *pointer, X *start, X *end)
203{
204 X *walker = find (pointer->sort, start, end);
205/* while (walker->next != pointer) { // search through list
206 walker = walker->next;
207 if (walker == end) return false; // item not found in list
208 }*/
209 // atom found, now unlink
210 if (walker != NULL)
211 removewithoutcheck(walker);
212 else
213 return false;
214 return true;
215};
216
217/** Cleans the whole list.
218 * \param *start begin of list
219 * \param *end end of list
220 * \return true - list was cleaned successfully, false - error in list structure
221 */
222template <typename X> bool cleanup(X *start, X *end)
223{
224 X *pointer = start->next;
225 X *walker;
226 while (pointer != end) { // go through list
227 walker = pointer; // mark current
228 pointer = pointer->next; // step onward beforehand
229 // remove walker
230 unlink(walker);
231 delete(walker);
232 walker = NULL;
233 }
234 return true;
235};
236
237/** Returns the first marker in a chain list.
238 * \param *me one arbitrary item in chain list
239 * \return poiner to first marker
240 */
241template <typename X> X *GetFirst(X *me)
242{
243 X *Binder = me;
244 while(Binder->previous != NULL)
245 Binder = Binder->previous;
246 return Binder;
247};
248
249/** Returns the last marker in a chain list.
250 * \param *me one arbitrary item in chain list
251 * \return poiner to last marker
252 */
253template <typename X> X *GetLast(X *me)
254{
255 X *Binder = me;
256 while(Binder->next != NULL)
257 Binder = Binder->next;
258 return Binder;
259};
260
261/** Frees a two-dimensional array.
262 * \param *ptr pointer to array
263 * \param dim first dim of array
264 */
265template <typename X> void Free2DArray(X **ptr, int dim)
266{
267 int i;
268 if (ptr != NULL) {
269 for(i=dim;i--;)
270 if (ptr[i] != NULL)
271 free(ptr[i]);
272 free(ptr);
273 }
274};
275
276/************************************* Class Verbose & Binary *******************************/
277
278/** Verbose is an IO manipulator, that writes tabs according to \a Verbosity level.
279 */
280class Verbose
281{
282 public:
283 Verbose(int value) : Verbosity(value) { }
284
285 ostream& print (ostream &ost) const;
286 private:
287 int Verbosity;
288};
289
290ostream& operator<<(ostream& ost,const Verbose& m);
291
292/** Binary is an IO manipulator, that writes 0 and 1 according to number \a Binary.
293 */
294class Binary
295{
296 public:
297 Binary(int value) : BinaryNumber(value) { }
298
299 ostream& print (ostream &ost) const;
300 private:
301 int BinaryNumber;
302};
303
304ostream& operator<<(ostream& ost,const Binary& m);
305
306
307
308#endif /*HELPERS_HPP_*/
Note: See TracBrowser for help on using the repository browser.