helpers Namespace Reference

Classes

struct  KAndDisp
 return type specifically for fuctions returning k and disp at once More...
 
struct  KAndDispAndKtAndDispt
 return type specifically for fuctions returning k, disp, kt, dispt at once More...
 

Functions

bool removeFromCommandline (int &argc, char *argv[], std::string varName, int nArgs)
 May be used to hide arguments from argc and argv. More...
 
bool readFromCommandLine (int argc, char *argv[], std::string varName)
 Returns true if command line arguments contain varName, false else. More...
 
template<typename T >
readFromCommandLine (int argc, char *argv[], std::string varName, T value)
 
template<typename T , size_t n>
std::array< T, nreadArrayFromCommandLine (int argc, char *argv[], std::string varName, std::array< T, n > value)
 
template<typename T >
std::vector< T > readVectorFromCommandLine (int argc, char *argv[], std::string varName, size_t n, std::vector< T > values)
 
template<>
std::string readFromCommandLine< std::string > (int argc, char *argv[], std::string varName, std::string value)
 
bool writeToFile (std::string filename, std::string filecontent)
 Writes a string to a file. More...
 
void writeCommandLineToFile (const std::string filename, const int argc, char *const argv[])
 Writes a string to a file. More...
 
bool addToFile (std::string filename, std::string filecontent)
 Adds a string to an existing file. More...
 
bool fileExists (std::string strFilename)
 Function to check if a file exists, is used to check if a run has already need done. More...
 
bool openFile (std::fstream &file, std::string filename, std::fstream::openmode mode)
 Provides a simple interface for opening a file. More...
 
std::vector< doublereadArrayFromFile (std::string filename, int &n, int &m)
 
void more (std::string filename, unsigned nLines=constants::unsignedMax)
 
bool createDirectory (std::string)
 
std::string getPath ()
 
template<typename T >
bool readOptionalVariable (std::istream &is, const std::string &name, T &variable)
 Reads optional variables in the restart file. More...
 
template<typename T >
readFromFile (const std::string fileName, const std::string varName, const T defaultValue)
 
MERCURYDPM_DEPRECATED KAndDispAndKtAndDispt computeDisptFromCollisionTimeAndRestitutionCoefficientAndTangentialRestitutionCoefficientAndEffectiveMass (Mdouble tc, Mdouble r, Mdouble beta, Mdouble mass)
 Set disp, k, dispt and kt such that is matches a given collision time tc and a normal and tangential restitution coefficient r, beta for a collision of effective/reduced mass m. From Deen...Kuipers2006, eq. 43 and 30. More...
 
MERCURYDPM_DEPRECATED Mdouble getMaximumVelocity (Mdouble k, Mdouble disp, Mdouble radius, Mdouble mass)
 Calculates the maximum relative velocity allowed for a normal collision of two particles of radius r and particle mass m (for higher velocities particles could pass through each other) More...
 
Mdouble getEffectiveMass (Mdouble mass0, Mdouble mass1)
 Calculates the effective mass of a particle pair, i.e. half the harmonic mean of two particle masses. More...
 
Mdouble getRayleighTime (Mdouble radius, Mdouble shearModulus, Mdouble poisson, Mdouble density)
 Returns the Rayleigh time step for a Hertz contact law. More...
 
unsigned int getSaveCountFromNumberOfSavesAndTimeMaxAndTimeStep (unsigned int numberOfSaves, Mdouble timeMax, Mdouble timeStep)
 Returns the correct saveCount if the total number of saves, the final time and the time step is known. More...
 
Mdouble round (Mdouble value, unsigned int precision)
 rounds a floating point number with a given precision More...
 
std::vector< Mdoublelinspace (Mdouble a, Mdouble b, int N)
 creates a 1D linear space partition More...
 
void gnuplot (std::string command)
 Plots to a gnuplot window. More...
 
Mdouble getRealTime ()
 
int qSortCompare (const void *x, const void *y)
 For use with qsort. More...
 
double getPercentile (const double *array, size_t nel, double perc)
 Returns the 100*perc-th percentile of array. More...
 
int getMaximumNumberOfOMPThreads ()
 Gets the maximum number of OpenMP threads. More...
 
std::string lower (std::string s)
 returns the input string after converting upper-case characters to lower case More...
 
void getLineFromStringStream (std::istream &in, std::stringstream &out)
 Reads a line from one stringstream into another, and prepares the latter for reading in. More...
 
bool isNext (std::istream &is, const std::string name)
 
bool compare (std::istream &is, std::string s)
 Checks if the next argument in the input stream is a certain string. More...
 
std::string toString (Mdouble value, unsigned precision)
 converts a floating point number into a string with a given precision More...
 
template<typename T >
std::string toString (const T &n)
 
template<typename T >
std::string toString (const std::vector< T > &vec)
 
void check (double real, double ideal, double error, std::string errorMessage)
 
void check (Vec3D real, Vec3D ideal, double error, std::string errorMessage)
 
void check (Matrix3D real, Matrix3D ideal, double error, std::string errorMessage)
 
void check (MatrixSymmetric3D real, MatrixSymmetric3D ideal, double error, std::string errorMessage)
 

Function Documentation

◆ addToFile()

bool helpers::addToFile ( std::string  filename,
std::string  filecontent 
)

Adds a string to an existing file.

Todo:
gmb Make this MPI compatible.
Note
Not used function.
90 {
91  std::fstream file;
92  file.open(filename.c_str(), std::ios::app);
93  if (file.fail())
94  {
95  logger(INFO, "Error in writeToFile: file could not be opened");
96  return false;
97  }
98  file << filecontent;
99  file.close();
100  return true;
101 }
LL< Log::INFO > INFO
Info log level.
Definition: Logger.cc:55
Logger< MERCURYDPM_LOGLEVEL > logger("MercuryKernel")
Definition of different loggers with certain modules. A user can define its own custom logger here.

References INFO, and logger.

◆ check() [1/4]

void helpers::check ( double  real,
double  ideal,
double  error,
std::string  errorMessage 
)

◆ check() [2/4]

void helpers::check ( Matrix3D  real,
Matrix3D  ideal,
double  error,
std::string  errorMessage 
)
53 {
54  checkTemplate(real, ideal, error, whatIsChecked);
55 }

References checkTemplate().

◆ check() [3/4]

void helpers::check ( MatrixSymmetric3D  real,
MatrixSymmetric3D  ideal,
double  error,
std::string  errorMessage 
)
48 {
49  checkTemplate(real, ideal, error, whatIsChecked);
50 }

References checkTemplate().

◆ check() [4/4]

void helpers::check ( Vec3D  real,
Vec3D  ideal,
double  error,
std::string  errorMessage 
)
43 {
44  checkTemplate(real, ideal, error, whatIsChecked);
45 }

References checkTemplate().

◆ compare()

bool helpers::compare ( std::istream &  is,
std::string  s 
)

Checks if the next argument in the input stream is a certain string.

91 {
92  // Get current position
93  //check if the next line starts with 'interactionFile'; otherwise, skip interaction
94  int len = is.tellg();
95  std::string dummy;
96  is >> dummy;
97  if (dummy != s)
98  {
99  is.seekg(len, std::ios_base::beg);
100  logger(INFO, "helpers::compare: Next stream value (%) is not %", dummy, s);
101  return false;
102  }
103  return true;
104 }

References INFO, and logger.

Referenced by DPMBase::read(), File::write(), and DPMBase::write().

◆ computeDisptFromCollisionTimeAndRestitutionCoefficientAndTangentialRestitutionCoefficientAndEffectiveMass()

helpers::KAndDispAndKtAndDispt helpers::computeDisptFromCollisionTimeAndRestitutionCoefficientAndTangentialRestitutionCoefficientAndEffectiveMass ( Mdouble  tc,
Mdouble  r,
Mdouble  beta,
Mdouble  mass 
)

Set disp, k, dispt and kt such that is matches a given collision time tc and a normal and tangential restitution coefficient r, beta for a collision of effective/reduced mass m. From Deen...Kuipers2006, eq. 43 and 30.

Todo:
what should be used instead of this function?
54 {
56  ans.disp = -2.0 * mass * log(r) / tc;
57  ans.k = mass * (mathsFunc::square(constants::pi / tc) + mathsFunc::square(ans.disp / (2.0 * mass)));
58  ans.kt = 2.0 / 7.0 * ans.k * (mathsFunc::square(constants::pi) + mathsFunc::square(log(beta))) /
60  if (beta != 0.0)
61  ans.dispt = -2 * log(beta) *
62  sqrt(1.0 / 7.0 * mass * ans.kt / (mathsFunc::square(constants::pi) + mathsFunc::square(log(beta))));
63  else
64  ans.dispt = 2. * sqrt(1.0 / 7.0 * mass * ans.kt);
65  return ans;
66 }
const Mdouble pi
Definition: ExtendedMath.h:45
Mdouble log(Mdouble Power)
Definition: ExtendedMath.cc:104
Mdouble beta(Mdouble z, Mdouble w)
This is the beta function, returns the approximation based on cmath's implementation of ln(gamma)
Definition: ExtendedMath.cc:164
T square(const T val)
squares a number
Definition: ExtendedMath.h:106
return type specifically for fuctions returning k, disp, kt, dispt at once
Definition: FormulaHelpers.h:47
Mdouble disp
Definition: FormulaHelpers.h:49
Mdouble dispt
Definition: FormulaHelpers.h:51
Mdouble k
Definition: FormulaHelpers.h:48
Mdouble kt
Definition: FormulaHelpers.h:50

References mathsFunc::beta(), helpers::KAndDispAndKtAndDispt::disp, helpers::KAndDispAndKtAndDispt::dispt, helpers::KAndDispAndKtAndDispt::k, helpers::KAndDispAndKtAndDispt::kt, mathsFunc::log(), constants::pi, and mathsFunc::square().

◆ createDirectory()

bool helpers::createDirectory ( std::string  path)
Todo:
gmb Make this MPI compatible.
Note
Not used function.
Note
Is this necessary? Don't we use WSL for Windows?
Todo:
gmb log error using strerror(errno)
203  {
204  //see https://stackoverflow.com/questions/20358455/cross-platform-way-to-make-a-directory
205  mode_t nMode = 0733; // UNIX style permissions
206  int nError = 0;
210 #if defined(_WIN32)
211  nError = _mkdir(path.c_str()); // can be used on Windows
212 #else
213  nError = mkdir(path.c_str(), nMode); // can be used on non-Windows
214 #endif
215  if (nError != 0) {
216  // handle your error here
220  }
221  return false;
222 }

◆ fileExists()

bool helpers::fileExists ( std::string  strFilename)

Function to check if a file exists, is used to check if a run has already need done.

This is a FileExist routine, which is used to test if a run have already need preformed, allows me to plug holes in parm studies.

108 {
109  struct stat stFileInfo;
110  bool blnReturn;
111  int intStat;
112 
113  // Attempt to get the file attributes
114 
115  intStat = stat(strFilename.c_str(), &stFileInfo);
116  if (intStat == 0)
117  {
118  // We were able to get the file attributes
119  // so the file obviously exists.
120  blnReturn = true;
121  }
122  else
123  {
124  // We were not able to get the file attributes.
125  // This may mean that we don't have permission to
126  // access the folder which contains this file. If you
127  // need to do that level of checking, lookup the
128  // return values of stat which will give you
129  // more details on why stat failed.
130  blnReturn = false;
131  }
132 
133  return blnReturn;
134 }

Referenced by ParameterStudy1DDemo::actionsBeforeTimeLoop(), ParameterStudy2DDemo::actionsBeforeTimeLoop(), ParameterStudy3DDemo::actionsBeforeTimeLoop(), main(), DPMBase::readRestartFile(), FlowRule::run(), AngleOfRepose::run(), and SegregationPeriodic::setupInitialConditions().

◆ getEffectiveMass()

Mdouble helpers::getEffectiveMass ( Mdouble  mass0,
Mdouble  mass1 
)

Calculates the effective mass of a particle pair, i.e. half the harmonic mean of two particle masses.

The effective mass is an important parameter in a collision. E.g. the collision time and the restitution coefficient are functions of the effective mass.

Parameters
[in]mass0The mass of the first particle.
[in]mass1The mass of the second particle.
Returns
the effective mass of the particle pair.
37 {
38  return mass0 * mass1 / (mass0 + mass1);
39 }

Referenced by main().

◆ getLineFromStringStream()

void helpers::getLineFromStringStream ( std::istream &  in,
std::stringstream &  out 
)

Reads a line from one stringstream into another, and prepares the latter for reading in.

This function is used to avoid errors from reading in old or manually modified restart files. Instead of reading variable by variable directly from the restart stringstream, a full line is read first, from which the variables are read. Thus, if a line has the wrong number of arguments, it might affect the reading of the current line, but correctly reads the next line.

Example of usage:

std::stringstream line; std::stringstream is = restartFile.getFStream(); helpers::getLineFromStringStream(is, line); std::string dummy; line >> dummy;

Parameters
[in]inthe stringstream from which a line is read out should be initialized as std::stringstream(std::stringstream::out)
[out]outthe stringstream into which the line is read; should be initialized as std::stringstream(std::stringstream::in | std::stringstream::out)
63 {
64  std::string line_string;
65  getline(in, line_string);
66  out.str(std::move(line_string));
67  out.clear();
68 }

Referenced by main(), BaseHandler< T >::read(), InteractionHandler::read(), DPMBase::read(), BaseCluster::read(), MercuryBase::read(), SpeciesHandler::readAndAddObject(), WallHandler::readAndCreateOldObject(), DPMBase::readNextDataFile(), BoundaryHandler::readOldObject(), and SpeciesHandler::readOldObject().

◆ getMaximumNumberOfOMPThreads()

int helpers::getMaximumNumberOfOMPThreads ( )

Gets the maximum number of OpenMP threads.

Gets the maximum number of OpenMP threads if MERCURYDPM_USE_OMP is enabled.

Returns
int maximum number of OpenMP threads
38 {
39 #ifdef MERCURYDPM_USE_OMP
40  return omp_get_max_threads();
41 #else
42  logger(WARN, "You are getting the maximum number of OMP threads, but OMP is not turned on");
43  return 1;
44 #endif
45 }
LL< Log::WARN > WARN
Warning log level.
Definition: Logger.cc:54

References logger, and WARN.

◆ getMaximumVelocity()

Mdouble helpers::getMaximumVelocity ( Mdouble  k,
Mdouble  disp,
Mdouble  radius,
Mdouble  mass 
)

Calculates the maximum relative velocity allowed for a normal collision of two particles of radius r and particle mass m (for higher velocities particles could pass through each other)

Todo:
what should be used instead of this function?
69 {
70  // note: underestimate based on energy argument,
71  // Ekin = 2*1/2*m*(v/2)^2 = 1/2*k*(2*r)^2, gives
72  // return radius * sqrt(8.0*k/mass);
73 
74  // with dissipation, see S. Luding, Collisions & Contacts between two particles, eq 34
75  Mdouble w = sqrt(k / mass - mathsFunc::square(disp / (2.0 * mass)));
76  Mdouble w0 = sqrt(k / mass);
77  Mdouble DispCorrection = exp(-disp / mass / w) * asin(w / w0);
78  //std::cout << "DispCorrection" << DispCorrection << std::endl;
79  return radius * sqrt(8.0 * k / mass) / DispCorrection;
80 }
double Mdouble
Definition: GeneralDefine.h:34
Mdouble exp(Mdouble Exponent)
Definition: ExtendedMath.cc:84

References mathsFunc::exp(), and mathsFunc::square().

Referenced by ChutePeriodic::setupInitialConditions(), Vreman::setupInitialConditions(), and SilbertPeriodic::setupInitialConditions().

◆ getPath()

std::string helpers::getPath ( )
Todo:
gmb log error using strerror(errno)
225 {
226  char cCurrentPath[FILENAME_MAX];
227  if (GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)) == NULL) {
228  logger(WARN, "Get current dir failed: %", cCurrentPath);
232  }
233  return std::string(cCurrentPath);
234 }
#define GetCurrentDir
Definition: FileIOHelpers.cc:40

References GetCurrentDir, logger, and WARN.

Referenced by DPMBase::writePythonFileForVTKVisualisation(), and HorizontalMixer::writeScript().

◆ getPercentile()

double helpers::getPercentile ( const double array,
size_t  nel,
double  perc 
)

Returns the 100*perc-th percentile of array.

array should be sorted, e.g. qsort(xs, n, sizeof(double), qSortCompare); and perc should be a number between 0 and 1.

75 {
76  size_t lower_ind = floor(perc * (nel - 1));
77  size_t upper_ind = ceil(perc * (nel - 1));
78  double lambda = (perc * (nel - 1)) - lower_ind;
79  double lower_x = array[lower_ind];
80  double upper_x = array[upper_ind];
81  double percentile = (1 - lambda) * lower_x + lambda * upper_x;
82  return percentile;
83 }

◆ getRayleighTime()

Mdouble helpers::getRayleighTime ( Mdouble  radius,
Mdouble  shearModulus,
Mdouble  poisson,
Mdouble  density 
)

Returns the Rayleigh time step for a Hertz contact law.

An accepted time step for Hertz is 10-20% of the Rayleigh time step. See [Marigo2015]

47 {
48  return constants::pi * radius * sqrt(density / shearModulus)/(0.1631 * poisson + 0.8766);
49 }

References constants::pi.

Referenced by NozzleDemo::setupInitialConditions(), and NozzleSelfTest::setupInitialConditions().

◆ getRealTime()

Mdouble helpers::getRealTime ( )
52 {
53  // record start time
54  static auto start = std::chrono::steady_clock::now();
55  auto end = std::chrono::steady_clock::now();
56  std::chrono::duration<double> diff = end - start;
57  return diff.count();
58 }

◆ getSaveCountFromNumberOfSavesAndTimeMaxAndTimeStep()

unsigned int helpers::getSaveCountFromNumberOfSavesAndTimeMaxAndTimeStep ( unsigned int  numberOfSaves,
Mdouble  timeMax,
Mdouble  timeStep 
)

Returns the correct saveCount if the total number of saves, the final time and the time step is known.

MercuryDPM uses the DPMBase::setSaveCount to determine how often output is written. However, if the user wants to set the total number of saves instead of the saveCount, he can use this function to calculate the correct saveCount, assuming that the final time and the mean time step is known.

Example of use:

setSaveCount(helpers::getSaveCountFromNumberOfSavesAndTimeMaxAndTimeStep(numberOfSaves, getTimeMax(), getTimeStep()));

Parameters
[in]numberOfSavesthe total number of output files the user wants at the end of the simulation.
[in]timeMaxthe final time of the simulation
[in]timeStepthe mean time step used during the simulation
Returns
the saveCount value that should be used to get the desired number of saves.
100 {
101  if (numberOfSaves > 0 && timeMax > 0 && timeStep > 0)
102  {
103  return static_cast<unsigned int>(ceil(
104  (timeMax + timeStep) / timeStep / static_cast<double>(numberOfSaves - 1)));
105  }
106  else
107  {
108  logger(ERROR,
109  "[Helpers::getSaveCountFromNumberOfSavesAndTimeMaxAndTimeStep()] numberOfSaves: %, timeMax: %, "
110  "timestep: %\n Arguments need to be positive",
111  numberOfSaves, timeMax, timeStep);
112  }
113  return 0;
114 }
LL< Log::ERROR > ERROR
Error log level.
Definition: Logger.cc:53

References ERROR, and logger.

Referenced by ChutePeriodicDemo::ChutePeriodicDemo(), ChuteWithWedge::ChuteWithWedge(), main(), ChutePeriodic::setup(), AxisymmetricHopper::setupInitialConditions(), MovingIntersectionOfWallsUnitTest_Basic::setupInitialConditions(), MovingWall::setupInitialConditions(), SeparateFilesSelfTest::setupInitialConditions(), Slide::Slide(), and statistics_while_running< T >::statistics_while_running().

◆ gnuplot()

void helpers::gnuplot ( std::string  command)

Plots to a gnuplot window.

Note
Not used function.
39 {
40 #ifdef __CYGWIN__
41  logger(WARN, "[helpers::gnuplot] is not supported on Cygwin");
42 #elif _WIN32
43  logger(WARN, "[helpers::gnuplot] is not supported on Windows");
44 #else
45  FILE* pipe = popen("gnuplot -persist", "w");
46  fprintf(pipe, "%s", command.c_str());
47  fflush(pipe);
48 #endif
49 }

References logger, and WARN.

◆ isNext()

bool helpers::isNext ( std::istream &  is,
const std::string  name 
)

reads next value in stream as a string and compares it with name. If name is equal to string, the function outputs true. If name is not equal to string, the function undoes the read by setting seekg, and outputs false.

Parameters
is
name
Returns
78  {
79  std::string dummy;
80  auto pos = is.tellg();
81  is >> dummy;
82  if (dummy != name) {
83  is.seekg(pos);
84  return false;
85  } else {
86  return true;
87  }
88 }
std::string name
Definition: MercuryProb.h:48

References units::name.

Referenced by BaseWall::read().

◆ linspace()

std::vector< Mdouble > helpers::linspace ( Mdouble  a,
Mdouble  b,
int  N 
)

creates a 1D linear space partition

35 {
36  Mdouble dx = (Max - Min) / static_cast<Mdouble>(numberOfBins - 1);
37  Mdouble val;
38  std::vector<Mdouble> linearVector(numberOfBins);
39  typename std::vector<Mdouble>::iterator x;
40  for (x = linearVector.begin(), val = Min; x != linearVector.end(); ++x, val += dx)
41  {
42  *x = val;
43  }
44  // ensure that last value is equal to Max.
45  linearVector.pop_back();
46  linearVector.push_back(Max);
47  return linearVector;
48 }

◆ lower()

std::string helpers::lower ( std::string  s)

returns the input string after converting upper-case characters to lower case

33 {
34  std::transform(s.begin(), s.end(), s.begin(), ::tolower);
35  return s;
36 }

Referenced by WallHandler::readTriangleWall().

◆ more()

void helpers::more ( std::string  filename,
unsigned  nLines = constants::unsignedMax 
)
Todo:
gmb Make this MPI compatible.
182 {
183  if (nLines != constants::unsignedMax)
184  logger(INFO, "First % lines of %:\n", Flusher::NO_FLUSH, nLines, filename);
185  std::fstream file;
186  file.open(filename.c_str(), std::ios::in);
187  if (file.fail())
188  logger(ERROR, "Error in readArrayFromFile: file could not be opened");
189  std::string line;
190  for (unsigned i = 0; i < nLines; i++)
191  {
192  if (file.eof()) break;
193  getline(file, line);
194  logger(INFO, " %\n", line);
195  }
196  file.close();
197 }
const std::complex< Mdouble > i
Definition: ExtendedMath.h:51
const unsigned unsignedMax
Definition: GeneralDefine.h:46

References ERROR, constants::i, INFO, logger, NO_FLUSH, and constants::unsignedMax.

Referenced by commandLineCG(), and main().

◆ openFile()

bool helpers::openFile ( std::fstream &  file,
std::string  filename,
std::fstream::openmode  mode 
)

Provides a simple interface for opening a file.

Provides a simple interface for opening a file, in order to avoid that the user has to learn the syntax for opening a file.

Parameters
[out]fileThe std::fstream object that the user can write to.
[in]filenameThe name of the file.
[in]modeThe openmode of the file, typically std::fstream::out or std::fstream::in.
Returns
true is the file was successfully opened, false else.
Todo:
gmb Make this MPI compatible. Is it used?
146 {
147  file.open(filename.c_str(), mode);
148  if (file.fail())
149  return false;
150  else
151  return true;
152 }

Referenced by main().

◆ qSortCompare()

int helpers::qSortCompare ( const void *  x,
const void *  y 
)

For use with qsort.

61 {
62  double xx = *(double*) x, yy = *(double*) y;
63  if (xx < yy) return -1;
64  if (xx > yy) return 1;
65  return 0;
66 }

◆ readArrayFromCommandLine()

template<typename T , size_t n>
std::array<T,n> helpers::readArrayFromCommandLine ( int  argc,
char argv[],
std::string  varName,
std::array< T, n value 
)
60  {
61  for (int i = 0; i < argc-1; ++i) {
62  if (varName == argv[i]) {
63  unsigned j = i+1;
64  std::stringstream out;
65  for (auto& v : value) {
66  v = atof(argv[j]);
67  out << v << ' ';
68  ++j;
69  }
70  logger(INFO, "readArrayFromCommandLine: % set to % ", varName.substr(1), out.str());
71  return value;
72  }
73  }
74  //if the variable is not found
75  std::stringstream out;
76  for (auto& v : value) out << v << ' ';
77  logger(INFO, "readArrayFromCommandLine: % set to default value % ", varName.substr(1), out.str());
78  return value;
79  }

References constants::i, INFO, and logger.

◆ readArrayFromFile()

std::vector< double > helpers::readArrayFromFile ( std::string  filename,
int &  n,
int &  m 
)
Todo:
gmb Make this MPI compatible.
Note
Not used function.
159 {
160  std::fstream file;
161  file.open(filename.c_str(), std::ios::in);
162  if (file.fail())
163  {
164  logger(ERROR, "Error in readArrayFromFile: file could not be opened");
165  }
166  file >> n >> m;
167  std::vector<double> v;
168  Mdouble val;
169  for (int i = 0; i < n * m; i++)
170  {
171  file >> val;
172  v.push_back(val);
173  }
174  file.close();
175  return v;
176 }
const unsigned n
Definition: CG3DPackingUnitTest.cpp:32

References ERROR, constants::i, logger, and n.

◆ readFromCommandLine() [1/2]

bool helpers::readFromCommandLine ( int  argc,
char argv[],
std::string  varName 
)

Returns true if command line arguments contain varName, false else.

Returns true if command line arguments contain varName, false else Usage example: if (readFromCommandLine(argc, argv, '-verbose')) ...

Parameters
argcpass through number of command line arguments
argvpass through values of command line arguments
varNamename of command line arguments that is required to return true
Returns
true or false
104 {
105  for (unsigned i=0; i<argc; ++i) {
106  if (varName == argv[i]) {
107  logger(INFO, "readFromCommandLine: % set to true",varName.substr(1));
108  return true;
109  }
110  }
111  //if the variable is not found
112  logger(INFO, "readFromCommandLine: % set to default value false",varName.substr(1));
113  return false;
114 }

References constants::i, INFO, and logger.

Referenced by Calibration::Calibration(), GranuDrum::GranuDrum(), GranuHeap::GranuHeap(), main(), Calibration::setSpecies(), Material::setSpecies(), and RotatingDrumWet::setupInitialConditions().

◆ readFromCommandLine() [2/2]

template<typename T >
T helpers::readFromCommandLine ( int  argc,
char argv[],
std::string  varName,
value 
)
45  {
46  for (int i = 0; i < argc-1; ++i) {
47  if (varName == argv[i]) {
48  value = atof(argv[i+1]);
49  logger(INFO, "readFromCommandLine: % set to % ", varName.substr(1), value);
50  return value;
51  }
52  }
53  //if the variable is not found
54  logger(INFO, "readFromCommandLine: % set to default value % ", varName.substr(1), value);
55  return value;
56  }

References constants::i, INFO, and logger.

◆ readFromCommandLine< std::string >()

template<>
std::string helpers::readFromCommandLine< std::string > ( int  argc,
char argv[],
std::string  varName,
std::string  value 
)

◆ readFromFile()

template<typename T >
T helpers::readFromFile ( const std::string  fileName,
const std::string  varName,
const T  defaultValue 
)

Allows a quick read-in from a parameter file.

For example, the following code reads in the variable time from the file in:

double time = readFromFile("in","time",24);
T readFromFile(const std::string fileName, const std::string varName, const T defaultValue)
Definition: FileIOHelpers.h:121

The in file needs to contain the string time, followed by the value, e.g.

time 20

If the file cannot be opened, or the parameter is not found, the variable is set to the default value specified by the third argument.

Parameters
fileNamename of input
varNamevariable name as it appears in the input file
defaultValuedefault value (used if the parameter could not be read)
Returns
value of variable
122  {
123  //open filestream
124  std::ifstream is(fileName.c_str(), std::ios::in);
125  if (is.fail())
126  {
127  logger(INFO, "readFromFile: file % could not be opened, variable % set to default value %",
128  fileName, varName, defaultValue);
129  return defaultValue;
130  }
131 
132  //read in variables, until the right one is fount
133  std::string s;
134  while (!is.eof())
135  {
136  is >> s;
137  if (s == varName)
138  {
139  T value;
140  is >> value;
141  logger(INFO, "readFromFile: variable % set to % ", varName, value);
142  return value;
143  }
144  }
145 
146  //if the right variable is never found
147  logger(WARN, "readFromFile: variable % not set in file %, using default value % ", varName, fileName, defaultValue);
148  return defaultValue;
149  }

References INFO, logger, and WARN.

Referenced by main().

◆ readOptionalVariable()

template<typename T >
bool helpers::readOptionalVariable ( std::istream &  is,
const std::string &  name,
T &  variable 
)

Reads optional variables in the restart file.

A variable is stored in the restart file by storing the variables name and value, e.g. " name value" If a variable is always written to the restart file, it can be read-in like this: is >> dummy >> variable; If a variable is optional, the variable name has to be checked, and should be read in like this: readOptionalVariable(is,"name",variable);

Todo:
readOptionalVariable should check the full variable name, not just the next value. However, I don't know how to put the location in the ifstream back.
83  {
86  const auto pos = is.tellg();
87  std::string dummy;
88  is >> dummy;
89  if (dummy == name)
90  {
91  is >> variable;
92  return true;
93  } else {
94  is.seekg(pos);
95  return false;
96  }
97  }

References units::name.

Referenced by LiquidMigrationLSSpecies::read(), LiquidMigrationWilletSpecies::read(), InsertionBoundary::read(), BaseInteraction::read(), BaseSpecies::read(), InfiniteWall::read(), and BaseObject::read().

◆ readVectorFromCommandLine()

template<typename T >
std::vector<T> helpers::readVectorFromCommandLine ( int  argc,
char argv[],
std::string  varName,
size_t  n,
std::vector< T >  values 
)
83  {
84  for (int i = 0; i < argc-1; ++i) {
85  if (varName == argv[i]) {
86  // read until the next argument starts
87  values.resize(0);
88  std::stringstream out;
89  for (int j = i+1; j<argc and argv[j][0]!='-'; ++j) {
90  values.push_back(atof(argv[j]));
91  out << values.back() << ' ';
92  }
93  logger(INFO, "readVectorFromCommandLine: % set to % ", varName.substr(1), out.str());
94  return values;
95  }
96  }
97  //if the variable is not found
98  std::stringstream out;
99  for (auto& v: values) out << v << ' ';
100  logger(INFO, "readVectorFromCommandLine: % set to default value % ", varName.substr(1), out.str());
101  return values;
102  }

References constants::i, INFO, and logger.

◆ removeFromCommandline()

bool helpers::removeFromCommandline ( int &  argc,
char argv[],
std::string  varName,
int  nArgs 
)

May be used to hide arguments from argc and argv.

Parameters
[in]argc
[in]argv
[in]varNameThe name of the commandline argument to be removed
[in]nArgsThe number of additional command line arguments to remove
Returns
boolean True if the argument was found and removed

This function does hide the desired argument from the supplied argv argc combination. It does it by moving the specified arguent to the end of the supplied argv and reducing argc by the coorect number. Other pieces of code that rely on argc should therefor no longer see the hidden argument.

If used in comination with readFromCommandLine(...), this function allows handling of arguments that are not seen by solve(), even if commandline arguments are passed.

44 {
45  int i, j;
46 
47  for (i=0; i<argc; ++i) {
48  if (varName == argv[i])
49  {
50  char *tmp[nArgs+1];
51 
52  for (j=i; j<argc-1-nArgs; j++)
53  {
54  // Store the pointers of the handled argument
55  if ( j < i + 1 + nArgs)
56  {
57  tmp[j-i] = argv[j];
58  }
59 
60  // Move the pointers after the argument to the front
61  argv[j] = argv[j + nArgs + 1];
62 
63  }
64 
65  // Move the stored argument to the end
66  for (j=argc-1-nArgs; j< argc; j++)
67  {
68  argv[j] = tmp[j + 1 + nArgs - argc];
69  }
70  argc -= nArgs + 1;
71 
72  return true;
73  }
74  }
75 
76  return false;
77 }

References constants::i.

Referenced by main().

◆ round()

◆ toString() [1/3]

template<typename T >
std::string helpers::toString ( const std::vector< T > &  vec)
67  {
68  std::ostringstream stm;
69  for (const auto val : vec) {
70  stm << val << ' ';
71  }
72  return stm.str();
73  }

◆ toString() [2/3]

template<typename T >
std::string helpers::toString ( const T &  n)
59  {
60  std::ostringstream stm;
61  stm << n;
62  return stm.str();
63  }

References n.

◆ toString() [3/3]

std::string helpers::toString ( Mdouble  value,
unsigned  precision 
)

converts a floating point number into a string with a given precision

39 {
40  std::ostringstream stm;
41  stm << round(value, precision);
42  return stm.str();
43 }

References round().

Referenced by ShearStage::actionsAfterSolve(), DeletionBoundary::checkBoundaryAfterParticleMoved(), computeFFc(), computeSimpleFFc(), Contact::Contact(), Indenter::Indenter(), main(), SingleParticle< SpeciesType >::setupInitialConditions(), SinterPair::SinterPair(), and GranuDrum::writeResults().

◆ writeCommandLineToFile()

void helpers::writeCommandLineToFile ( const std::string  filename,
const int  argc,
char *const  argv[] 
)

Writes a string to a file.

Todo:
gmb Make this MPI compatible.
Note
Not used function.
77 {
78  std::stringstream ss;
79  for (int i=0; i<argc; ++i) {
80  ss << argv[i] << ' ';
81  }
82  writeToFile(filename,ss.str());
83 }
bool writeToFile(std::string filename, std::string filecontent)
Writes a string to a file.
Definition: FileIOHelpers.cc:58

References constants::i, and writeToFile().

◆ writeToFile()

bool helpers::writeToFile ( std::string  filename,
std::string  filecontent 
)

Writes a string to a file.

Provides a simple interface for writing a string to a file. This function is mainly used to create ini or restart file that the code later reads back in.

Example of usage:

helpers::writeToFile("RestartUnitTest.ini", "1 0 0 0 0 1 1 1\n" "0.5 0.5 0 0 0 0.5 0 0 0 0 0 0 0 0\n");

Parameters
[in]filenamethe name of the file
[in]filecontentthe content
Returns
true on success.
Todo:
gmb Make this MPI compatible.
59 {
60  std::fstream file;
61  file.open(filename.c_str(), std::ios::out);
62  if (file.fail())
63  {
64  logger(WARN, "Error in writeToFile: file could not be opened");
65  return false;
66  }
67  file << filecontent;
68  file.close();
69  return true;
70 }

References logger, and WARN.

Referenced by ShearStage::actionsAfterSolve(), ScaleCoupledBeam::actionsBeforeSolve(), Beam::actionsBeforeSolve(), CoupledBeam::actionsBeforeSolve(), CoupledProblem::CoupledProblem(), statistics_while_running< T >::finishStatistics(), loadingTest(), main(), normalAndTangentialLoadingTest(), objectivenessTest(), LevelSetWall::setShapeFourSided(), GetDistanceAndNormalForIntersectionOfWalls::setupInitialConditions(), GetDistanceAndNormalForScrew::setupInitialConditions(), GetDistanceAndNormalForTriangleWall::setupInitialConditions(), GetDistanceAndNormalForTriangleWalls::setupInitialConditions(), SingleParticle< SpeciesType >::setupInitialConditions(), ShearStage::ShearStage(), SinterPair::SinterPair(), writeCommandLineToFile(), writeHelpers(), Calibration::writePSDToFile(), DPMBase::writePythonFileForVTKVisualisation(), GranuDrum::writeResults(), GranuHeap::writeResults(), HorizontalMixer::writeScript(), LevelSetWall::writeToFile(), and Screw::writeVTK().