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

std::size_t countLeadingDashes (const std::string &s)
 Counts the leading dash ('-') characters in a string. More...
 
bool removeFromCommandline (int &argc, char *argv[], const std::string &varName, int nArgs)
 May be used to hide arguments from argc and argv. More...
 
bool readFromCommandLine (int argc, char *argv[], const std::string &varName)
 Returns true if command line arguments contain varName, false else. More...
 
template<typename T >
T readFromCommandLine (int argc, char *argv[], const std::string &varName, T value)
 
template<typename T , size_t n>
std::array< T, nreadArrayFromCommandLine (int argc, char *argv[], const std::string &varName, std::array< T, n > value)
 
template<typename T >
std::vector< TreadVectorFromCommandLine (int argc, char *argv[], const std::string &varName, size_t n, std::vector< T > values)
 
template<>
std::string readFromCommandLine< std::string > (int argc, char *argv[], const std::string &varName, std::string value)
 
bool writeToFile (const std::string &filename, const 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 (const std::string &filename, const std::string &filecontent)
 Adds a string to an existing file. More...
 
bool fileExists (const 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, const std::string &filename, std::fstream::openmode mode)
 Provides a simple interface for opening a file. More...
 
std::vector< doublereadArrayFromFile (const std::string &filename, int &n, int &m)
 
void more (const std::string &filename, unsigned nLines=constants::unsignedMax)
 
bool createDirectory (const std::string &directory, bool allowExists=false)
 Creates a directory. More...
 
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 >
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 getShearModulus (Mdouble youngsModulus, Mdouble poisson)
 Returns the shear modulus calculated from Young's modulus and Poisson's ratio. 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)
 Checks if the next argument in the input stream equals a certain string. When true, the current position is that of the next argument. When false, the current position remains unchanged. More...
 
MERCURYDPM_DEPRECATED bool compare (std::istream &is, const std::string &s)
 Checks if the next argument in the input stream is a certain string. More...
 
bool lookAhead (std::istream &is, const std::string &name, int number)
 Checks if the nth argument from the current position in the input stream equals a certain string. The current position remains unchanged. 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)
 
template<typename... Args>
std::string stringFormat (const std::string &format, Args... args)
 
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 ( const std::string &  filename,
const std::string &  filecontent 
)

Adds a string to an existing file.

Todo:
gmb Make this MPI compatible.
60 {
61  std::fstream file;
62  file.open(filename.c_str(), std::ios::app);
63  if (file.fail())
64  {
65  logger(INFO, "Error in writeToFile: file could not be opened");
66  return false;
67  }
68  file << filecontent;
69  file.close();
70  return true;
71 }
Logger< MERCURYDPM_LOGLEVEL > logger("MercuryKernel")
Definition of different loggers with certain modules. A user can define its own custom logger here.
#define INFO(i)
Definition: mumps_solver.h:54
string filename
Definition: MergeRestartFiles.py:39

References MergeRestartFiles::filename, 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 
)
32 {
33  checkTemplate(real, ideal, error, whatIsChecked);
34 }

References checkTemplate(), and calibrate::error.

◆ check() [3/4]

void helpers::check ( MatrixSymmetric3D  real,
MatrixSymmetric3D  ideal,
double  error,
std::string  errorMessage 
)
27 {
28  checkTemplate(real, ideal, error, whatIsChecked);
29 }

References checkTemplate(), and calibrate::error.

◆ check() [4/4]

void helpers::check ( Vec3D  real,
Vec3D  ideal,
double  error,
std::string  errorMessage 
)
22 {
23  checkTemplate(real, ideal, error, whatIsChecked);
24 }

References checkTemplate(), and calibrate::error.

◆ compare()

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

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

Deprecated:
70 {
71  logger(WARN, "helpers::compare() is deprecated. Use helpers::isNext() instead.");
72  // Get current position
73  //check if the next line starts with 'interactionFile'; otherwise, skip interaction
74  int len = is.tellg();
75  std::string dummy;
76  is >> dummy;
77  if (dummy != s)
78  {
79  is.seekg(len, std::ios_base::beg);
80  logger(VERBOSE, "helpers::compare: Next stream value (%) is not %", dummy, s);
81  return false;
82  }
83  return true;
84 }
LL< Log::VERBOSE > VERBOSE
Verbose information.
Definition: Logger.cc:36
LL< Log::WARN > WARN
Warning log level.
Definition: Logger.cc:33
RealScalar s
Definition: level1_cplx_impl.h:130
std::string string(const unsigned &i)
Definition: oomph_definitions.cc:286

References logger, s, oomph::Global_string_for_annotation::string(), VERBOSE, and WARN.

◆ 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?
33 {
35  ans.disp = -2.0 * mass * log(r) / tc;
36  ans.k = mass * (mathsFunc::square(constants::pi / tc) + mathsFunc::square(ans.disp / (2.0 * mass)));
37  ans.kt = 2.0 / 7.0 * ans.k * (mathsFunc::square(constants::pi) + mathsFunc::square(log(beta))) /
39  if (beta != 0.0)
40  ans.dispt = -2 * log(beta) *
41  sqrt(1.0 / 7.0 * mass * ans.kt / (mathsFunc::square(constants::pi) + mathsFunc::square(log(beta))));
42  else
43  ans.dispt = 2. * sqrt(1.0 / 7.0 * mass * ans.kt);
44  return ans;
45 }
AnnoyingScalar sqrt(const AnnoyingScalar &x)
Definition: AnnoyingScalar.h:134
Scalar beta
Definition: level2_cplx_impl.h:36
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 log(const bfloat16 &a)
Definition: BFloat16.h:618
r
Definition: UniformPSDSelfTest.py:20
const Mdouble pi
Definition: ExtendedMath.h:23
T square(const T val)
squares a number
Definition: ExtendedMath.h:86
return type specifically for fuctions returning k, disp, kt, dispt at once
Definition: FormulaHelpers.h:26
Mdouble disp
Definition: FormulaHelpers.h:28
Mdouble dispt
Definition: FormulaHelpers.h:30
Mdouble k
Definition: FormulaHelpers.h:27
Mdouble kt
Definition: FormulaHelpers.h:29

References beta, helpers::KAndDispAndKtAndDispt::disp, helpers::KAndDispAndKtAndDispt::dispt, helpers::KAndDispAndKtAndDispt::k, helpers::KAndDispAndKtAndDispt::kt, Eigen::bfloat16_impl::log(), constants::pi, UniformPSDSelfTest::r, sqrt(), and mathsFunc::square().

◆ countLeadingDashes()

std::size_t helpers::countLeadingDashes ( const std::string &  s)

Counts the leading dash ('-') characters in a string.

Parameters
[in]sString constaining dash ('-') characters.
Returns
Number of leading dashes ('-')
12  {
13  std::size_t counter = 0;
14 
15  for(char c : s){
16  if(c == '-'){
17  ++counter;
18  } else {
19  break;
20  }
21  }
22 
23  return counter;
24 }
int c
Definition: calibrate.py:100

References calibrate::c, and s.

Referenced by helpers::readFromCommandLine< std::string >(), readArrayFromCommandLine(), readFromCommandLine(), and readVectorFromCommandLine().

◆ createDirectory()

bool helpers::createDirectory ( const std::string &  directory,
bool  allowExists = false 
)

Creates a directory.

Parameters
directoryAbsoulte/relative path of the directory
allowExistsWon't fail if directory exists
Returns
Directory created
Parameters
directoryAbsoulte/relative path of the directory
allowExistsWon't fail if directory exists
Returns
true/false
178 {
179 #ifdef MERCURYDPM_USE_MPI
180  if (PROCESSOR_ID == 0)
181  {
182 #endif
183 
184  if (directory == ".") {
185  return true;
186  }
187 
188  errno = 0;
189  const int err = ::mkdir(directory.c_str(), 0777);
190  if (err == 0) {
191  return true;
192  } else if(errno == EEXIST && allowExists) {
193  return true;
194  } else {
195  logger(ERROR, "Unable to create directory `%`: % (%)", directory, strerror(errno), errno);
196  return false;
197  }
198 
199 #ifdef MERCURYDPM_USE_MPI
200  } else {
201  return true;
202  }
203 #endif
204 }
#define PROCESSOR_ID
Definition: GeneralDefine.h:42
LL< Log::ERROR > ERROR
Error log level.
Definition: Logger.cc:32

References ERROR, logger, and PROCESSOR_ID.

Referenced by DPMBase::initialiseVTK().

◆ fileExists()

bool helpers::fileExists ( const 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.

78 {
79  struct stat stFileInfo;
80  bool blnReturn;
81  int intStat;
82 
83  // Attempt to get the file attributes
84 
85  intStat = stat(strFilename.c_str(), &stFileInfo);
86  if (intStat == 0)
87  {
88  // We were able to get the file attributes
89  // so the file obviously exists.
90  blnReturn = true;
91  }
92  else
93  {
94  // We were not able to get the file attributes.
95  // This may mean that we don't have permission to
96  // access the folder which contains this file. If you
97  // need to do that level of checking, lookup the
98  // return values of stat which will give you
99  // more details on why stat failed.
100  blnReturn = false;
101  }
102 
103  return blnReturn;
104 }

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.
16 {
17  return mass0 * mass1 / (mass0 + mass1);
18 }

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)
42 {
43  std::string line_string;
44  getline(in, line_string);
45  out.str(std::move(line_string));
46  out.clear();
47 }
std::ofstream out("Result.txt")

References out(), and oomph::Global_string_for_annotation::string().

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
17 {
18 #ifdef MERCURYDPM_USE_OMP
19  return omp_get_max_threads();
20 #else
21  logger(WARN, "You are getting the maximum number of OMP threads, but OMP is not turned on");
22  return 1;
23 #endif
24 }

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?
48 {
49  // note: underestimate based on energy argument,
50  // Ekin = 2*1/2*m*(v/2)^2 = 1/2*k*(2*r)^2, gives
51  // return radius * sqrt(8.0*k/mass);
52 
53  // with dissipation, see S. Luding, Collisions & Contacts between two particles, eq 34
54  Mdouble w = sqrt(k / mass - mathsFunc::square(disp / (2.0 * mass)));
55  Mdouble w0 = sqrt(k / mass);
56  Mdouble DispCorrection = exp(-disp / mass / w) * asin(w / w0);
57  //std::cout << "DispCorrection" << DispCorrection << std::endl;
58  return radius * sqrt(8.0 * k / mass) / DispCorrection;
59 }
RowVector3d w
Definition: Matrix_resize_int.cpp:3
char char char int int * k
Definition: level2_impl.h:374
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 asin(const bfloat16 &a)
Definition: BFloat16.h:634
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 exp(const bfloat16 &a)
Definition: BFloat16.h:615
radius
Definition: UniformPSDSelfTest.py:15

References Eigen::bfloat16_impl::asin(), Eigen::bfloat16_impl::exp(), k, UniformPSDSelfTest::radius, sqrt(), mathsFunc::square(), and w.

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

◆ getPath()

std::string helpers::getPath ( )
207 {
208  char currentPath[FILENAME_MAX];
209  if (getcwd(currentPath, sizeof(currentPath)) == NULL) {
210  logger(WARN, "Get current dir failed: %", strerror(errno));
211  }
212  return std::string(currentPath);
213 }

References logger, oomph::Global_string_for_annotation::string(), 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.

54 {
55  size_t lower_ind = floor(perc * (nel - 1));
56  size_t upper_ind = ceil(perc * (nel - 1));
57  double lambda = (perc * (nel - 1)) - lower_ind;
58  double lower_x = array[lower_ind];
59  double upper_x = array[upper_ind];
60  double percentile = (1 - lambda) * lower_x + lambda * upper_x;
61  return percentile;
62 }
cout<< "The eigenvalues of A are:"<< endl<< ces.eigenvalues()<< endl;cout<< "The matrix of eigenvectors, V, is:"<< endl<< ces.eigenvectors()<< endl<< endl;complex< float > lambda
Definition: ComplexEigenSolver_compute.cpp:9
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 floor(const bfloat16 &a)
Definition: BFloat16.h:643
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 ceil(const bfloat16 &a)
Definition: BFloat16.h:644
std::array< T, N > array
Definition: EmulateArray.h:231

References Eigen::bfloat16_impl::ceil(), Eigen::bfloat16_impl::floor(), and lambda.

◆ 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]}

26 {
27  return constants::pi * radius * sqrt(density / shearModulus)/(0.1631 * poisson + 0.8766);
28 }
density
Definition: UniformPSDSelfTest.py:19

References UniformPSDSelfTest::density, constants::pi, UniformPSDSelfTest::radius, and sqrt().

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

◆ getRealTime()

Mdouble helpers::getRealTime ( )
31 {
32  // record start time
33  static auto start = std::chrono::steady_clock::now();
34  auto end = std::chrono::steady_clock::now();
35  std::chrono::duration<double> diff = end - start;
36  return diff.count();
37 }
static constexpr lastp1_t end
Definition: IndexedViewHelper.h:79
void start(const unsigned &i)
(Re-)start i-th timer
Definition: oomph_utilities.cc:243

References Eigen::placeholders::end, and oomph::CumulativeTimings::start().

◆ 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.
79 {
80  if (numberOfSaves > 0 && timeMax > 0 && timeStep > 0)
81  {
82  return static_cast<unsigned int>(ceil(
83  (timeMax + timeStep) / timeStep / static_cast<double>(numberOfSaves - 1)));
84  }
85  else
86  {
87  logger(ERROR,
88  "[Helpers::getSaveCountFromNumberOfSavesAndTimeMaxAndTimeStep()] numberOfSaves: %, timeMax: %, "
89  "timestep: %\n Arguments need to be positive",
90  numberOfSaves, timeMax, timeStep);
91  }
92  return 0;
93 }

References Eigen::bfloat16_impl::ceil(), 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().

◆ getShearModulus()

Mdouble helpers::getShearModulus ( Mdouble  youngsModulus,
Mdouble  poisson 
)

Returns the shear modulus calculated from Young's modulus and Poisson's ratio.

98  {
99  return youngsModulus / (2.0 * (1 + poisson));
100 }

◆ gnuplot()

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

Plots to a gnuplot window.

Note
Not used function.
18 {
19 #ifdef __CYGWIN__
20  logger(WARN, "[helpers::gnuplot] is not supported on Cygwin");
21 #elif _WIN32
22  logger(WARN, "[helpers::gnuplot] is not supported on Windows");
23 #else
24  FILE* pipe = popen("gnuplot -persist", "w");
25  fprintf(pipe, "%s", command.c_str());
26  fflush(pipe);
27 #endif
28 }

References logger, and WARN.

◆ isNext()

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

Checks if the next argument in the input stream equals a certain string. When true, the current position is that of the next argument. When false, the current position remains unchanged.

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
57  {
58  std::string dummy;
59  auto pos = is.tellg();
60  is >> dummy;
61  if (dummy != name) {
62  is.seekg(pos);
63  return false;
64  } else {
65  return true;
66  }
67 }
string name
Definition: plotDoE.py:33

References plotDoE::name, and oomph::Global_string_for_annotation::string().

Referenced by DropletBoundary::read(), BaseWall::read(), and DPMBase::read().

◆ linspace()

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

creates a 1D linear space partition

14 {
15  Mdouble dx = (Max - Min) / static_cast<Mdouble>(numberOfBins - 1);
16  Mdouble val;
17  std::vector<Mdouble> linearVector(numberOfBins);
18  typename std::vector<Mdouble>::iterator x;
19  for (x = linearVector.begin(), val = Min; x != linearVector.end(); ++x, val += dx)
20  {
21  *x = val;
22  }
23  // ensure that last value is equal to Max.
24  linearVector.pop_back();
25  linearVector.push_back(Max);
26  return linearVector;
27 }
val
Definition: calibrate.py:119
list x
Definition: plotDoE.py:28

References calibrate::val, and plotDoE::x.

Referenced by PSD::convertPdfPhiToPdfMeter(), PSD::setDistributionLogNormal(), PSD::setDistributionNormal(), and PSD::setDistributionUniform().

◆ lookAhead()

bool helpers::lookAhead ( std::istream &  is,
const std::string &  name,
int  number 
)

Checks if the nth argument from the current position in the input stream equals a certain string. The current position remains unchanged.

87 {
88  logger.assert_always(number > 0, "Error in helpers::lookAhead(). Number must be greater than 0.");
89  // Remember current position.
90  auto pos = is.tellg();
91  std::string dummy;
92  // Read the next n values, i.e. n-1 values are skipped.
93  for (int i = 0; i < number; i++)
94  is >> dummy;
95  // Set the position back.
96  is.seekg(pos);
97  // Return whether the nth value equals the searched name.
98  return dummy == name;
99 }
int i
Definition: BiCGSTAB_step_by_step.cpp:9

References i, logger, plotDoE::name, and oomph::Global_string_for_annotation::string().

Referenced by DropletBoundary::read().

◆ lower()

◆ more()

void helpers::more ( const std::string &  filename,
unsigned  nLines = constants::unsignedMax 
)
Todo:
gmb Make this MPI compatible.
152 {
153  if (nLines != constants::unsignedMax)
154  logger(INFO, "First % lines of %:\n", Flusher::NO_FLUSH, nLines, filename);
155  std::fstream file;
156  file.open(filename.c_str(), std::ios::in);
157  if (file.fail())
158  logger(ERROR, "Error in readArrayFromFile: file could not be opened");
160  for (unsigned i = 0; i < nLines; i++)
161  {
162  if (file.eof()) break;
163  getline(file, line);
164  logger(INFO, " %\n", line);
165  }
166  file.close();
167 }
line
Definition: calibrate.py:103
const unsigned unsignedMax
Definition: GeneralDefine.h:25

References ERROR, MergeRestartFiles::filename, i, INFO, calibrate::line, logger, NO_FLUSH, oomph::Global_string_for_annotation::string(), and constants::unsignedMax.

Referenced by commandLineCG(), and main().

◆ openFile()

bool helpers::openFile ( std::fstream &  file,
const 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?
116 {
117  file.open(filename.c_str(), mode);
118  if (file.fail())
119  return false;
120  else
121  return true;
122 }

References MergeRestartFiles::filename.

Referenced by main().

◆ qSortCompare()

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

For use with qsort.

40 {
41  double xx = *(double*) x, yy = *(double*) y;
42  if (xx < yy) return -1;
43  if (xx > yy) return 1;
44  return 0;
45 }
Scalar * y
Definition: level1_cplx_impl.h:128

References plotDoE::x, and y.

◆ readArrayFromCommandLine()

template<typename T , size_t n>
std::array<T,n> helpers::readArrayFromCommandLine ( int  argc,
char argv[],
const std::string &  varName,
std::array< T, n value 
)
45  {
46  const size_t nDashes = countLeadingDashes(varName);
47  for (int i = 0; i < argc-1; ++i) {
48  if (varName == argv[i]) {
49  int j = i + 1;
50  std::stringstream out;
51  for (auto& v : value) {
52  v = atof(argv[j]);
53  out << v << ' ';
54  ++j;
55  }
56  logger(INFO, "readArrayFromCommandLine: % set to % ", varName.substr(nDashes), out.str());
57  return value;
58  }
59  }
60  //if the variable is not found
61  std::stringstream out;
62  for (auto& v : value) out << v << ' ';
63  logger(INFO, "readArrayFromCommandLine: % set to default value % ", varName.substr(nDashes), out.str());
64  return value;
65  }
Array< int, Dynamic, 1 > v
Definition: Array_initializer_list_vector_cxx11.cpp:1
squared absolute value
Definition: GlobalFunctions.h:87
std::size_t countLeadingDashes(const std::string &s)
Counts the leading dash ('-') characters in a string.
Definition: CommandLineHelpers.cc:12
std::ptrdiff_t j
Definition: tut_arithmetic_redux_minmax.cpp:2

References countLeadingDashes(), i, INFO, j, logger, out(), v, and Eigen::value.

◆ readArrayFromFile()

std::vector< double > helpers::readArrayFromFile ( const std::string &  filename,
int n,
int m 
)
Todo:
gmb Make this MPI compatible.
Note
Not used function.
129 {
130  std::fstream file;
131  file.open(filename.c_str(), std::ios::in);
132  if (file.fail())
133  {
134  logger(ERROR, "Error in readArrayFromFile: file could not be opened");
135  }
136  file >> n >> m;
137  std::vector<double> v;
138  Mdouble val;
139  for (int i = 0; i < n * m; i++)
140  {
141  file >> val;
142  v.push_back(val);
143  }
144  file.close();
145  return v;
146 }
const unsigned n
Definition: CG3DPackingUnitTest.cpp:11
int * m
Definition: level2_cplx_impl.h:294

References ERROR, MergeRestartFiles::filename, i, logger, m, n, v, and calibrate::val.

◆ readFromCommandLine() [1/2]

bool helpers::readFromCommandLine ( int  argc,
char argv[],
const 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
100 {
101  const size_t nDashes = countLeadingDashes(varName);
102  for (int i = 0; i < argc; ++i) {
103  if (varName == argv[i]) {
104  logger(INFO, "readFromCommandLine: % set to true", varName.substr(nDashes));
105  return true;
106  }
107  }
108  //if the variable is not found
109  logger(INFO, "readFromCommandLine: % set to default value false", varName.substr(nDashes));
110  return false;
111 }

References countLeadingDashes(), i, INFO, and logger.

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

◆ readFromCommandLine() [2/2]

template<typename T >
T helpers::readFromCommandLine ( int  argc,
char argv[],
const std::string &  varName,
T  value 
)
29  {
30  const size_t nDashes = countLeadingDashes(varName);
31  for (int i = 0; i < argc-1; ++i) {
32  if (varName == argv[i]) {
33  value = atof(argv[i+1]);
34  logger(INFO, "readFromCommandLine: % set to % ", varName.substr(nDashes), value);
35  return value;
36  }
37  }
38  //if the variable is not found
39  logger(INFO, "readFromCommandLine: % set to default value % ", varName.substr(nDashes), value);
40  return value;
41  }

References countLeadingDashes(), i, INFO, logger, and Eigen::value.

◆ readFromCommandLine< std::string >()

template<>
std::string helpers::readFromCommandLine< std::string > ( int  argc,
char argv[],
const 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:107

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
108  {
109  //open filestream
110  std::ifstream is(fileName.c_str(), std::ios::in);
111  if (is.fail())
112  {
113  logger(INFO, "readFromFile: file % could not be opened, variable % set to default value %",
114  fileName, varName, defaultValue);
115  return defaultValue;
116  }
117 
118  //read in variables, until the right one is fount
119  std::string s;
120  while (!is.eof())
121  {
122  is >> s;
123  if (s == varName)
124  {
125  T value;
126  is >> value;
127  logger(INFO, "readFromFile: variable % set to % ", varName, value);
128  return value;
129  }
130  }
131 
132  //if the right variable is never found
133  logger(WARN, "readFromFile: variable % not set in file %, using default value % ", varName, fileName, defaultValue);
134  return defaultValue;
135  }
string fileName
Definition: UniformPSDSelfTest.py:10

References UniformPSDSelfTest::fileName, INFO, logger, s, oomph::Global_string_for_annotation::string(), Eigen::value, 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.
69  {
72  const auto pos = is.tellg();
73  std::string dummy;
74  is >> dummy;
75  if (dummy == name)
76  {
77  is >> variable;
78  return true;
79  } else {
80  is.seekg(pos);
81  return false;
82  }
83  }

References plotDoE::name, and oomph::Global_string_for_annotation::string().

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

◆ readVectorFromCommandLine()

template<typename T >
std::vector<T> helpers::readVectorFromCommandLine ( int  argc,
char argv[],
const std::string &  varName,
size_t  n,
std::vector< T values 
)
69  {
70  const size_t nDashes = countLeadingDashes(varName);
71  for (int i = 0; i < argc-1; ++i) {
72  if (varName == argv[i]) {
73  // read until the next argument starts
74  values.resize(0);
75  std::stringstream out;
76  for (int j = i+1; j < argc && argv[j][0] != '-'; ++j) {
77  values.push_back(atof(argv[j]));
78  out << values.back() << ' ';
79  }
80  logger(INFO, "readVectorFromCommandLine: % set to % ", varName.substr(nDashes), out.str());
81  return values;
82  }
83  }
84  //if the variable is not found
85  std::stringstream out;
86  for (auto& v: values) out << v << ' ';
87  logger(INFO, "readVectorFromCommandLine: % set to default value % ", varName.substr(nDashes), out.str());
88  return values;
89  }

References countLeadingDashes(), i, INFO, j, logger, out(), and v.

◆ removeFromCommandline()

bool helpers::removeFromCommandline ( int argc,
char argv[],
const 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.

42 {
43  for (int i = 0; i < argc; ++i) {
44  if (varName == argv[i])
45  {
46  char *tmp[nArgs + 1];
47 
48  for (int j = i; j < argc - 1 - nArgs; j++)
49  {
50  // Store the pointers of the handled argument
51  if (j < i + 1 + nArgs)
52  {
53  tmp[j-i] = argv[j];
54  }
55 
56  // Move the pointers after the argument to the front
57  argv[j] = argv[j + nArgs + 1];
58  }
59 
60  // Move the stored argument to the end
61  for (int j = argc - 1 - nArgs; j < argc; j++)
62  {
63  argv[j] = tmp[j + 1 + nArgs - argc];
64  }
65  argc -= nArgs + 1;
66 
67  return true;
68  }
69  }
70 
71  return false;
72 }
Eigen::Matrix< Scalar, Dynamic, Dynamic, ColMajor > tmp
Definition: level3_impl.h:365

References i, j, and tmp.

Referenced by main().

◆ round()

Mdouble helpers::round ( Mdouble  value,
unsigned int  precision 
)

rounds a floating point number with a given precision

8 {
9  const double n = std::pow(10, precision);
10  return std::round(value*n)/n;
11 }
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 pow(const bfloat16 &a, const bfloat16 &b)
Definition: BFloat16.h:625
EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC bfloat16 round(const bfloat16 &a)
Definition: BFloat16.h:646

References n, Eigen::bfloat16_impl::pow(), Eigen::bfloat16_impl::round(), and Eigen::value.

◆ stringFormat()

template<typename... Args>
std::string helpers::stringFormat ( const std::string &  format,
Args...  args 
)
70  {
71  int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'
72  if (size_s <= 0) {
73  logger(ERROR, "snprintf() failed");
74  }
75  auto size = static_cast<size_t>(size_s);
76  std::unique_ptr<char[]> buf(new char[size]);
77  std::snprintf(buf.get(), size, format.c_str(), args...);
78  return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
79  }
Scalar Scalar int size
Definition: benchVecAdd.cpp:17
args
Definition: compute_granudrum_aor.py:143
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
Definition: openglsupport.cpp:217

References compute_granudrum_aor::args, ERROR, format(), logger, size, and oomph::Global_string_for_annotation::string().

◆ toString() [1/3]

template<typename T >
std::string helpers::toString ( const std::vector< T > &  vec)
60  {
61  std::ostringstream stm;
62  for (const auto val : vec) {
63  stm << val << ' ';
64  }
65  return stm.str();
66  }

References calibrate::val.

◆ toString() [2/3]

template<typename T >
std::string helpers::toString ( const T n)
52  {
53  std::ostringstream stm;
54  stm << n;
55  return stm.str();
56  }

References n.

◆ toString() [3/3]

◆ 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.
48 {
49  std::stringstream ss;
50  for (int i=0; i<argc; ++i) {
51  ss << argv[i] << ' ';
52  }
53  writeToFile(filename,ss.str());
54 }
bool writeToFile(const std::string &filename, const std::string &filecontent)
Writes a string to a file.
Definition: FileIOHelpers.cc:29

References MergeRestartFiles::filename, i, and writeToFile().

◆ writeToFile()

bool helpers::writeToFile ( const std::string &  filename,
const 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.
30 {
31  std::fstream file;
32  file.open(filename.c_str(), std::ios::out);
33  if (file.fail())
34  {
35  logger(WARN, "Error in writeToFile: file could not be opened");
36  return false;
37  }
38  file << filecontent;
39  file.close();
40  return true;
41 }

References MergeRestartFiles::filename, logger, out(), 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(), RotatingDrumBidisperse::writeResults(), HorizontalMixer::writeScript(), LevelSetWall::writeToFile(), and Screw::writeVTK().