source: src/helpers.hpp@ d2a294

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

new function CreateFatherLookupTable

Creates a lookup table for true father's atom:nr -> atom, which is used during the molecule::FragmentMolecule lateron. Implemented as a template to be used not only for atoms but also for bonds and others

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