source: src/helpers.cpp@ f66195

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

forward declarations used to untangle interdependet classes.

  • basically, everywhere in header files we removed '#include' lines were only pointer to the respective classes were used and the include line was moved to the implementation file.
  • as a sidenote, lots of funny errors happened because headers were included via a nesting over three other includes. Now, all should be declared directly as needed, as only very little include lines remain in header files.
  • Property mode set to 100644
File size: 4.9 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/** Returns a string with \a i prefixed with 0s to match order of total number of molecules in digits.
78 * \param FragmentNumber total number of fragments to determine necessary number of digits
79 * \param digits number to create with 0 prefixed
80 * \return allocated(!) char array with number in digits, ten base.
81 */
82char *FixedDigitNumber(const int FragmentNumber, const int digits)
83{
84 char *returnstring;
85 int number = FragmentNumber;
86 int order = 0;
87 while (number != 0) { // determine number of digits needed
88 number = (int)floor(((double)number / 10.));
89 order++;
90 //cout << "Number is " << number << ", order is " << order << "." << endl;
91 }
92 // allocate string
93 returnstring = Malloc<char>(order + 2, "FixedDigitNumber: *returnstring");
94 // terminate and fill string array from end backward
95 returnstring[order] = '\0';
96 number = digits;
97 for (int i=order;i--;) {
98 returnstring[i] = '0' + (char)(number % 10);
99 number = (int)floor(((double)number / 10.));
100 }
101 //cout << returnstring << endl;
102 return returnstring;
103};
104
105/** Tests whether a given string contains a valid number or not.
106 * \param *string
107 * \return true - is a number, false - is not a valid number
108 */
109bool IsValidNumber( const char *string)
110{
111 int ptr = 0;
112 if ((string[ptr] == '.') || (string[ptr] == '-')) // number may be negative or start with dot
113 ptr++;
114 if ((string[ptr] >= '0') && (string[ptr] <= '9'))
115 return true;
116 return false;
117};
118
119/** Blows the 6-dimensional \a cell_size array up to a full NDIM by NDIM matrix.
120 * \param *symm 6-dim array of unique symmetric matrix components
121 * \return allocated NDIM*NDIM array with the symmetric matrix
122 */
123double * ReturnFullMatrixforSymmetric(double *symm)
124{
125 double *matrix = Malloc<double>(NDIM * NDIM, "molecule::ReturnFullMatrixforSymmetric: *matrix");
126 matrix[0] = symm[0];
127 matrix[1] = symm[1];
128 matrix[2] = symm[3];
129 matrix[3] = symm[1];
130 matrix[4] = symm[2];
131 matrix[5] = symm[4];
132 matrix[6] = symm[3];
133 matrix[7] = symm[4];
134 matrix[8] = symm[5];
135 return matrix;
136};
137
138/** Comparison function for GSL heapsort on distances in two molecules.
139 * \param *a
140 * \param *b
141 * \return <0, \a *a less than \a *b, ==0 if equal, >0 \a *a greater than \a *b
142 */
143int CompareDoubles (const void * a, const void * b)
144{
145 if (*(double *)a > *(double *)b)
146 return -1;
147 else if (*(double *)a < *(double *)b)
148 return 1;
149 else
150 return 0;
151};
152
153
154/** Allocates a memory range using malloc().
155 * Prints the provided error message in case of a failure.
156 *
157 * \param number of memory slices of type X to allocate
158 * \param failure message which is printed if the allocation fails
159 * \return pointer to the allocated memory range, will be NULL if a failure occurred
160 */
161template <> char* Malloc<char>(size_t size, const char* output)
162{
163 char* buffer = NULL;
164 buffer = (char*) malloc(sizeof(char) * (size + 1));
165 for (size_t i = size; i--;)
166 buffer[i] = (i % 2 == 0) ? 'p': 'c';
167 buffer[size] = '\0';
168
169 if (buffer != NULL) {
170 MemoryUsageObserver::getInstance()->addMemory(buffer, size);
171 } else {
172 cout << Verbose(0) << "Malloc for datatype " << typeid(char).name()
173 << " failed - pointer is NULL: " << output << endl;
174 }
175
176 return buffer;
177};
178
Note: See TracBrowser for help on using the repository browser.