source: src/helpers.cpp@ a2028e

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 a2028e was 5034e1, checked in by Frederik Heber <heber@…>, 15 years ago

First half of molecule_fragmentation.cpp refactoring.

  • Property mode set to 100755
File size: 6.0 KB
Line 
1/** \file helpers.cpp
2 *
3 * Implementation of some auxiliary functions for memory dis-/allocation and so on
4 */
5
6
7#include "helpers.hpp"
8
9/********************************************** helpful functions *********************************/
10
11
12/** Asks for a double value and checks input
13 * \param *text question
14 */
15double ask_value(const char *text)
16{
17 double test = 0.1439851348959832147598734598273456723948652983045928346598365;
18 do {
19 cout << Verbose(0) << text;
20 cin >> test;
21 } while (test == 0.1439851348959832147598734598273456723948652983045928346598365);
22 return test;
23};
24
25/** Output of a debug message to stderr.
26 * \param *P Problem at hand, points to ParallelSimulationData#me
27 * \param output output string
28 */
29#ifdef HAVE_DEBUG
30void debug_in(const char *output, const char *file, const int line) {
31 if (output) fprintf(stderr,"DEBUG: in %s at line %i: %s\n", file, line, output);
32}
33#else
34void debug_in(const char *output, const char *file, const int line) {} // print nothing
35#endif
36
37/** modulo operator for doubles.
38 * \param *b pointer to double
39 * \param lower_bound lower bound
40 * \param upper_bound upper bound
41 */
42void bound(double *b, double lower_bound, double upper_bound)
43{
44 double step = (upper_bound - lower_bound);
45 while (*b >= upper_bound)
46 *b -= step;
47 while (*b < lower_bound)
48 *b += step;
49};
50
51/** Flips two doubles.
52 * \param *x pointer to first double
53 * \param *y pointer to second double
54 */
55void flip(double *x, double *y)
56{
57 double tmp;
58 tmp = *x;
59 *x = *y;
60 *y = tmp;
61};
62
63/** Returns the power of \a n with respect to \a base.
64 * \param base basis
65 * \param n power
66 * \return \f$base^n\f$
67 */
68int pot(int base, int n)
69{
70 int res = 1;
71 int j;
72 for (j=n;j--;)
73 res *= base;
74 return res;
75};
76
77/** Counts lines in file.
78 * Note we are scanning lines from current position, not from beginning.
79 * \param InputFile file to be scanned.
80 */
81int CountLinesinFile(ifstream &InputFile)
82{
83 char *buffer = Malloc<char>(MAXSTRINGSIZE, "CountLinesinFile: *buffer");
84 int lines=0;
85
86 int PositionMarker = InputFile.tellg(); // not needed as Inputfile is copied, given by value, not by ref
87 // count the number of lines, i.e. the number of fragments
88 InputFile.getline(buffer, MAXSTRINGSIZE); // skip comment lines
89 InputFile.getline(buffer, MAXSTRINGSIZE);
90 while(!InputFile.eof()) {
91 InputFile.getline(buffer, MAXSTRINGSIZE);
92 lines++;
93 }
94 InputFile.seekg(PositionMarker, ios::beg);
95 Free(&buffer);
96 return lines;
97};
98
99/** Returns a string with \a i prefixed with 0s to match order of total number of molecules in digits.
100 * \param FragmentNumber total number of fragments to determine necessary number of digits
101 * \param digits number to create with 0 prefixed
102 * \return allocated(!) char array with number in digits, ten base.
103 */
104char *FixedDigitNumber(const int FragmentNumber, const int digits)
105{
106 char *returnstring;
107 int number = FragmentNumber;
108 int order = 0;
109 while (number != 0) { // determine number of digits needed
110 number = (int)floor(((double)number / 10.));
111 order++;
112 //cout << "Number is " << number << ", order is " << order << "." << endl;
113 }
114 // allocate string
115 returnstring = Malloc<char>(order + 2, "FixedDigitNumber: *returnstring");
116 // terminate and fill string array from end backward
117 returnstring[order] = '\0';
118 number = digits;
119 for (int i=order;i--;) {
120 returnstring[i] = '0' + (char)(number % 10);
121 number = (int)floor(((double)number / 10.));
122 }
123 //cout << returnstring << endl;
124 return returnstring;
125};
126
127/** Tests whether a given string contains a valid number or not.
128 * \param *string
129 * \return true - is a number, false - is not a valid number
130 */
131bool IsValidNumber( const char *string)
132{
133 int ptr = 0;
134 if ((string[ptr] == '.') || (string[ptr] == '-')) // number may be negative or start with dot
135 ptr++;
136 if ((string[ptr] >= '0') && (string[ptr] <= '9'))
137 return true;
138 return false;
139};
140
141/** Blows the 6-dimensional \a cell_size array up to a full NDIM by NDIM matrix.
142 * \param *symm 6-dim array of unique symmetric matrix components
143 * \return allocated NDIM*NDIM array with the symmetric matrix
144 */
145double * ReturnFullMatrixforSymmetric(double *symm)
146{
147 double *matrix = Malloc<double>(NDIM * NDIM, "molecule::ReturnFullMatrixforSymmetric: *matrix");
148 matrix[0] = symm[0];
149 matrix[1] = symm[1];
150 matrix[2] = symm[3];
151 matrix[3] = symm[1];
152 matrix[4] = symm[2];
153 matrix[5] = symm[4];
154 matrix[6] = symm[3];
155 matrix[7] = symm[4];
156 matrix[8] = symm[5];
157 return matrix;
158};
159
160/** Comparison function for GSL heapsort on distances in two molecules.
161 * \param *a
162 * \param *b
163 * \return <0, \a *a less than \a *b, ==0 if equal, >0 \a *a greater than \a *b
164 */
165int CompareDoubles (const void * a, const void * b)
166{
167 if (*(double *)a > *(double *)b)
168 return -1;
169 else if (*(double *)a < *(double *)b)
170 return 1;
171 else
172 return 0;
173};
174
175
176/** Allocates a memory range using malloc().
177 * Prints the provided error message in case of a failure.
178 *
179 * \param number of memory slices of type X to allocate
180 * \param failure message which is printed if the allocation fails
181 * \return pointer to the allocated memory range, will be NULL if a failure occurred
182 */
183template <> char* Malloc<char>(size_t size, const char* output)
184{
185 char* buffer = NULL;
186 buffer = (char*) malloc(sizeof(char) * (size + 1));
187 for (size_t i = size; i--;)
188 buffer[i] = (i % 2 == 0) ? 'p': 'c';
189 buffer[size] = '\0';
190
191 if (buffer != NULL) {
192 MemoryUsageObserver::getInstance()->addMemory(buffer, size);
193 } else {
194 cout << Verbose(0) << "Malloc for datatype " << typeid(char).name()
195 << " failed - pointer is NULL: " << output << endl;
196 }
197
198 return buffer;
199};
200
201/**
202 * Frees all memory registered by the memory observer and calls exit(225) afterwards.
203 */
204static void performCriticalExit() {
205 map<void*, size_t> pointers = MemoryUsageObserver::getInstance()->getPointersToAllocatedMemory();
206 for (map<void*, size_t>::iterator runner = pointers.begin(); runner != pointers.end(); runner++) {
207 Free(((void**) &runner->first));
208 }
209
210 exit(255);
211}
Note: See TracBrowser for help on using the repository browser.