source: src/helpers.cpp@ b66c22

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 b66c22 was b66c22, checked in by metzler <metzler@…>, 15 years ago

#19 Observe memory usage

  • Property mode set to 100644
File size: 4.0 KB
RevLine 
[14de469]1/** \file helpers.cpp
2 *
[6ac7ee]3 * Implementation of some auxiliary functions for memory dis-/allocation and so on
[14de469]4 */
5
6
7#include "helpers.hpp"
[b66c22]8#include "memoryusageobserver.hpp"
[14de469]9
10/********************************************** helpful functions *********************************/
11
12
13/** Asks for a double value and checks input
14 * \param *text question
15 */
16double ask_value(const char *text)
17{
[042f82]18 double test = 0.1439851348959832147598734598273456723948652983045928346598365;
19 do {
20 cout << Verbose(0) << text;
21 cin >> test;
22 } while (test == 0.1439851348959832147598734598273456723948652983045928346598365);
23 return test;
[14de469]24};
25
[d3a46d]26/** Output of a debug message to stderr.
27 * \param *P Problem at hand, points to ParallelSimulationData#me
28 * \param output output string
29 */
30#ifdef HAVE_DEBUG
31void debug_in(const char *output, const char *file, const int line) {
[042f82]32 if (output) fprintf(stderr,"DEBUG: in %s at line %i: %s\n", file, line, output);
[d3a46d]33}
34#else
[042f82]35void debug_in(const char *output, const char *file, const int line) {} // print nothing
[d3a46d]36#endif
[14de469]37
38/** modulo operator for doubles.
39 * \param *b pointer to double
40 * \param lower_bound lower bound
41 * \param upper_bound upper bound
42 */
43void bound(double *b, double lower_bound, double upper_bound)
44{
[042f82]45 double step = (upper_bound - lower_bound);
46 while (*b >= upper_bound)
47 *b -= step;
48 while (*b < lower_bound)
49 *b += step;
[6ac7ee]50};
[14de469]51
52/** Flips two doubles.
53 * \param *x pointer to first double
54 * \param *y pointer to second double
55 */
56void flip(double *x, double *y)
57{
[042f82]58 double tmp;
59 tmp = *x;
60 *x = *y;
61 *y = tmp;
[14de469]62};
63
64/** Returns the power of \a n with respect to \a base.
65 * \param base basis
66 * \param n power
67 * \return \f$base^n\f$
68 */
69int pot(int base, int n)
70{
[042f82]71 int res = 1;
72 int j;
73 for (j=n;j--;)
74 res *= base;
75 return res;
[14de469]76};
77
78/** Returns a string with \a i prefixed with 0s to match order of total number of molecules in digits.
79 * \param FragmentNumber total number of fragments to determine necessary number of digits
80 * \param digits number to create with 0 prefixed
81 * \return allocated(!) char array with number in digits, ten base.
82 */
83char *FixedDigitNumber(const int FragmentNumber, const int digits)
84{
[042f82]85 char *returnstring;
86 int number = FragmentNumber;
87 int order = 0;
88 while (number != 0) { // determine number of digits needed
89 number = (int)floor(((double)number / 10.));
90 order++;
91 //cout << "Number is " << number << ", order is " << order << "." << endl;
92 }
93 // allocate string
[29812d]94 returnstring = Malloc<char>(order + 2, "FixedDigitNumber: *returnstring");
[042f82]95 // terminate and fill string array from end backward
96 returnstring[order] = '\0';
97 number = digits;
98 for (int i=order;i--;) {
99 returnstring[i] = '0' + (char)(number % 10);
100 number = (int)floor(((double)number / 10.));
101 }
102 //cout << returnstring << endl;
103 return returnstring;
[14de469]104};
105
[e198c7]106/** Tests whether a given string contains a valid number or not.
107 * \param *string
108 * \return true - is a number, false - is not a valid number
109 */
[6ac7ee]110bool IsValidNumber( const char *string)
[e198c7]111{
[042f82]112 int ptr = 0;
113 if ((string[ptr] == '.') || (string[ptr] == '-')) // number may be negative or start with dot
114 ptr++;
115 if ((string[ptr] >= '0') && (string[ptr] <= '9'))
116 return true;
117 return false;
[e198c7]118};
119
[29812d]120/**
121 * Allocates a memory range using malloc().
122 * Prints the provided error message in case of a failure.
123 *
124 * \param number of memory slices of type X to allocate
125 * \param failure message which is printed if the allocation fails
126 * \return pointer to the allocated memory range, will be NULL if a failure occurred
127 */
128template <> char* Malloc<char>(size_t size, const char* output)
129{
130 char* buffer = NULL;
131 buffer = (char*) malloc(sizeof(char) * (size + 1));
132 for (size_t i = size; i--;)
133 buffer[i] = (i % 2 == 0) ? 'p': 'c';
134 buffer[size] = '\0';
135
[b66c22]136 if (buffer != NULL) {
137 MemoryUsageObserver::getInstance()->addMemory(buffer, size);
138 } else {
[29812d]139 cout << Verbose(0) << "Malloc for datatype " << typeid(char).name()
140 << " failed - pointer is NULL: " << output << endl;
[b66c22]141 }
[29812d]142
143 return buffer;
144};
145
[e198c7]146
Note: See TracBrowser for help on using the repository browser.