Merge pull request #2157 from akohlmey/use-clang-format-demo

Demonstrate use of clang-format in LAMMPS
This commit is contained in:
Axel Kohlmeyer
2020-06-15 17:55:42 -04:00
committed by GitHub
50 changed files with 1788 additions and 1718 deletions

View File

@ -27,7 +27,7 @@ if (Python3_EXECUTABLE)
COMMENT "Fix whitespace errors")
add_custom_target(
fix-permissions
${Python3_EXECUTABLE} ${LAMMPS_TOOLS_DIR}/coding_standard/permission.py -f .
${Python3_EXECUTABLE} ${LAMMPS_TOOLS_DIR}/coding_standard/permissions.py -f .
WORKING_DIRECTORY ${LAMMPS_DIR}
COMMENT "Fix permission errors")
endif()

View File

@ -0,0 +1,46 @@
# Find clang-format
find_program(ClangFormat_EXECUTABLE NAMES clang-format
clang-format-10.0
clang-format-9.0
clang-format-8.0
clang-format-7.0
clang-format-6.0
DOC "clang-format executable")
mark_as_advanced(ClangFormat_EXECUTABLE)
if(ClangFormat_EXECUTABLE)
# find version
execute_process(COMMAND ${ClangFormat_EXECUTABLE} --version
OUTPUT_VARIABLE clang_format_version
ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE)
if(clang_format_version MATCHES "^clang-format version .*")
# Arch Linux
# clang-format version 10.0.0
# Ubuntu 18.04 LTS Output
# clang-format version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
string(REGEX REPLACE "clang-format version ([0-9.]+).*"
"\\1"
ClangFormat_VERSION
"${clang_format_version}")
elseif(clang_format_version MATCHES ".*LLVM version .*")
# CentOS 7 Output
# LLVM (http://llvm.org/):
# LLVM version 3.4.2
# Optimized build.
# Built Nov 1 2018 (15:06:24).
# Default target: x86_64-redhat-linux-gnu
# Host CPU: x86-64
string(REGEX REPLACE ".*LLVM version ([0-9.]+).*"
"\\1"
ClangFormat_VERSION
"${clang_format_version}")
else()
set(ClangFormat_VERSION "0.0")
endif()
endif()
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(ClangFormat REQUIRED_VARS ClangFormat_EXECUTABLE VERSION_VAR ClangFormat_VERSION)

View File

@ -95,9 +95,9 @@ The output of this command will be looking something like this::
25/26 Test #25: AngleStyle:harmonic ................. Passed 0.01 sec
Start 26: AngleStyle:zero
26/26 Test #26: AngleStyle:zero ..................... Passed 0.01 sec
100% tests passed, 0 tests failed out of 26
Total Test time (real) = 0.27 sec

0
examples/USER/atc/elastic/in.no_atoms Executable file → Normal file
View File

0
examples/USER/atc/elastic/in.no_atoms_cb Executable file → Normal file
View File

0
examples/USER/atc/elastic/in.no_atoms_cb_linear Executable file → Normal file
View File

0
examples/USER/atc/molecule/in.polarize Executable file → Normal file
View File

0
examples/USER/dpd/dpdrx-shardlow/in.dpdrx-shardlow Executable file → Normal file
View File

0
examples/USER/lb/confined_colloid/in.confined_colloids Executable file → Normal file
View File

0
examples/USER/lb/dragforce/in.defaultgamma_drag Executable file → Normal file
View File

0
examples/USER/lb/dragforce/in.setgamma_drag Executable file → Normal file
View File

View File

0
examples/USER/lb/fourspheres/in.fourspheres_set_gamma Executable file → Normal file
View File

View File

View File

0
examples/USER/lb/planewall/in.planewall_default_gamma Executable file → Normal file
View File

0
examples/USER/lb/planewall/in.planewall_set_gamma Executable file → Normal file
View File

View File

View File

View File

View File

@ -16,7 +16,7 @@ installed.
The person who created this package is Ilya Valuev at the JIHT in
Russia (valuev at physik.hu-berlin.de). Contact him directly if you
have questions.
----------------------
ACKNOWLEDGMENTS:

View File

@ -25,7 +25,7 @@ recommended over regular pppm.
The person who created this package is Axel Kohlmeyer at Temple U
(akohlmey at gmail.com). Contact him directly if you have questions.
---------------------------------
Thanks for contributions, support and testing goes to

View File

@ -3,7 +3,7 @@ polarizable systems in LAMMPS. The package provides the following
features:
* tagging particles as cores or Drude particles
* thermostating the Drude oscillators at a distinct temperature
* thermostating the Drude oscillators at a distinct temperature
using Langevin or Nosé-Hoover thermostats
* computation of the atom and dipole temperatures
* damping induced dipole interactions using Thole's function
@ -15,7 +15,7 @@ There are auxiliary tools for using this package in tools/drude.
There are example scripts for using this package in examples/USER/drude.
The person who created this package is Alain Dequidt at the
Chemistry Institute of Clermont-Ferrand, Clermont University, France
Chemistry Institute of Clermont-Ferrand, Clermont University, France
(alain.dequidt at uca.fr). Contact him directly if you have questions.
Co-authors: Julien Devémy, Agilio Padua.

View File

@ -1,11 +1,11 @@
#############################################################################
# Benchmarks
#
# in.intel.lj - Atomic fluid (LJ Benchmark)
# in.intel.lj - Atomic fluid (LJ Benchmark)
# in.intel.rhodo - Protein (Rhodopsin Benchmark)
# in.intel.lc - Liquid Crystal w/ Gay-Berne potential
# in.intel.eam - Copper benchmark with Embedded Atom Method
# in.intel.sw - Silicon benchmark with Stillinger-Weber
# in.intel.lc - Liquid Crystal w/ Gay-Berne potential
# in.intel.eam - Copper benchmark with Embedded Atom Method
# in.intel.sw - Silicon benchmark with Stillinger-Weber
# in.intel.tersoff - Silicon benchmark with Tersoff
# in.intel.water - Coarse-grain water benchmark using Stillinger-Weber
# in.intel.airebo - Polyethelene benchmark with AIREBO
@ -18,12 +18,12 @@
# - Compiled w/ Intel Parallel Studio 2017u2 and Makefile.intel_cpu_intelmpi
#
# Xeon E5-2697v4 Xeon Phi 7250 Xeon Gold 6148
#
#
# in.intel.lj - 199.5 282.3 317.3
# in.intel.rhodo - 12.4 17.5 24.4
# in.intel.lc - 19.0 25.7 26.8
# in.intel.eam - 59.4 92.8 105.6
# in.intel.sw - 132.4 161.9 213.8
# in.intel.lc - 19.0 25.7 26.8
# in.intel.eam - 59.4 92.8 105.6
# in.intel.sw - 132.4 161.9 213.8
# in.intel.tersoff - 83.3 101.1 109.6
# in.intel.water - 53.4 90.3 105.5
# in.intel.airebo - 7.3 11.8 17.6
@ -33,14 +33,14 @@
#############################################################################
# For Skylake server (Xeon) architectures, see notes in the USER-INTEL/README
# for build flags that should be used.
# for build flags that should be used.
#############################################################################
#############################################################################
# For Haswell (Xeon v3) architectures, depending on the compiler version,
# it may give better performance to compile for an AVX target (with -xAVX
# compiler option) instead of -xHost or -xCORE-AVX2 for some of the
# workloads. In most cases, FMA sensitive routines will still use AVX2
# For Haswell (Xeon v3) architectures, depending on the compiler version,
# it may give better performance to compile for an AVX target (with -xAVX
# compiler option) instead of -xHost or -xCORE-AVX2 for some of the
# workloads. In most cases, FMA sensitive routines will still use AVX2
# (MKL and SVML detect the processor at runtime). For Broadwell (Xeon v4)
# architectures, -xCORE-AVX2 or -xHost will work best for all.
#############################################################################
@ -50,40 +50,40 @@
# the Intel package. You can specify a multiplier for all of the benchmarks
# to increase or decrease the runtime. Example commandline arguments:
#
# -v m 2 # Run for twice as long
# -v m 0.5 # Run for half as long
# -v m 2 # Run for twice as long
# -v m 0.5 # Run for half as long
#############################################################################
#############################################################################
# The LAMMPS newton setting can be controlled from the commandline for the
# benchmarks with the N variable:
#
# -v N on # newton on
# -v N off # newton off
# -v N on # newton on
# -v N off # newton off
#
# The default is on for all of the benchmarks except for LJ where the off
# setting performs best with the USER-INTEL package
#############################################################################
# Example for running benchmarks (see run_benchmarks.sh for script):
# Example for running benchmarks (see run_benchmarks.sh for script):
# Number of physical cores per node not including hyperthreads
# Number of physical cores per node not including hyperthreads
export LMP_CORES=28
# If hyperthreading is enabled, number of hyperthreads to use per core
# (2 for Xeon; 2 or 4 for Xeon Phi)
export OMP_NUM_THREADS=2
# Name of the LAMMPS binary
export LMP_BIN=../../lmp_intel_cpu
# LAMMPS root directory
export LMP_ROOT=../../../
source source /opt/intel/parallel_studio_xe_2017.2.050/psxevars.sh
export KMP_BLOCKTIME=0
export I_MPI_PIN_DOMAIN=core
export I_MPI_FABRICS=shm # For single node
export I_MPI_FABRICS=shm # For single node
# ONLY FOR INTEL XEON PHI x200 SERIES PROCESSORS
export I_MPI_SHM_LMT=shm
@ -121,7 +121,7 @@ mpirun -np $LMP_CORES $LMP_BIN -in $bench -log none -pk intel 0 -sf intel
mpirun -np $LMP_CORES $LMP_BIN -in $bench -log none -pk intel 1 -sf intel
#############################################################################
# If using PPPM (e.g. in.intel.rhodo) on Intel Xeon Phi x200 series
# If using PPPM (e.g. in.intel.rhodo) on Intel Xeon Phi x200 series
# or Skylake processors
#############################################################################
export KMP_AFFINITY=none

View File

@ -1,7 +1,7 @@
This package provides OpenMP multi-threading support and other
optimizations of various LAMMPS pair styles, dihedral styles, and fix
styles.
See this section of the manual to get started:
doc/Section_accelerate.html, sub-section 5.2

View File

@ -1,56 +1,56 @@
This package contains 2 fix commands, "fix qtb" and
This package contains 2 fix commands, "fix qtb" and
"fix qbmsst" which involve quantum nuclear effects.
What is quantum nuclear effects (in molecular dynamics
What is quantum nuclear effects (in molecular dynamics
simulation)?
Quantum treatment of the vibrational modes will
introduce zero point energy into the system, alter
the energy power spectrum and bias the heat capacity
from the classical limit. classical MD leaves out
these effects completely and thus need to be corrected.
When should I consider quantum nuclear effects in
my simulation?
(1) When you want to model systems at temperatures
lower than their classical limits. This is especially
important for materials with a large population of
hydrogen atoms and thus higher classical limits.
Quantum treatment of the vibrational modes will
introduce zero point energy into the system, alter
the energy power spectrum and bias the heat capacity
from the classical limit. classical MD leaves out
these effects completely and thus need to be corrected.
(2) In MD simulations when temperatures ramp up
across (or starting from somewhere close to) the
classical limits, tiny differences between the
classical and quantum heat capacity can accumulate
and cause the final state to deviate (could be as
large as 30 %).
When should I consider quantum nuclear effects in
my simulation?
(1) When you want to model systems at temperatures
lower than their classical limits. This is especially
important for materials with a large population of
hydrogen atoms and thus higher classical limits.
(2) In MD simulations when temperatures ramp up
across (or starting from somewhere close to) the
classical limits, tiny differences between the
classical and quantum heat capacity can accumulate
and cause the final state to deviate (could be as
large as 30 %).
What command should I use regarding these two cases?
(1) "fix qtb" provides quantum nulcear correction
through a colored thermostat and can be used with
other time integration schemes like fix nve or
fix nph. In this case, you tell "fix qtb" the temperature
and the other time integration scheme either the
pressure ("fix nph") or the volume ("fix nve").
(1) "fix qtb" provides quantum nulcear correction
through a colored thermostat and can be used with
other time integration schemes like fix nve or
fix nph. In this case, you tell "fix qtb" the temperature
and the other time integration scheme either the
pressure ("fix nph") or the volume ("fix nve").
(2) "fix qbmsst" deals with shock MD simulations
in which cases the temperature may increase a lot.
It enables quantum nuclear correction of a multi-scale
shock technique simulation by coupling the quantum
thermal bath with the shocked system. It is an independent
command from "fix msst" and does not assume that
the SHOCK package has been installed.
(2) "fix qbmsst" deals with shock MD simulations
in which cases the temperature may increase a lot.
It enables quantum nuclear correction of a multi-scale
shock technique simulation by coupling the quantum
thermal bath with the shocked system. It is an independent
command from "fix msst" and does not assume that
the SHOCK package has been installed.
See the doc page for the fix qtb and fix qbmsst
command for detailed usage instructions.
See the doc page for the fix qtb and fix qbmsst
command for detailed usage instructions.
Where can I find examples of these two commands?
There are example scripts for using this package in
examples/USER/qtb, including one "fix qtb" and one
"fix qbmsst" example for each of alpha quartz and
methane. Running the alpha quartz example requires
installation of the kspace package while the methane
example requires the REAX package for the force field.
There are example scripts for using this package in
examples/USER/qtb, including one "fix qtb" and one
"fix qbmsst" example for each of alpha quartz and
methane. Running the alpha quartz example requires
installation of the kspace package while the methane
example requires the REAX package for the force field.
Authors Information and Contact
The person who created this package is Yuan Shen
(sy0302 at stanford.edu) at Stanford University.
Contact him directly if you have questions.
The person who created this package is Yuan Shen
(sy0302 at stanford.edu) at Stanford University.
Contact him directly if you have questions.

View File

@ -53,14 +53,14 @@ The reaxc files in this directory have the following header:
H. M. Aktulga, J. C. Fogarty, S. A. Pandit, A. Y. Grama,
"Parallel Reactive Molecular Dynamics: Numerical Methods and
Algorithmic Techniques", Parallel Computing, in press.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details:
<http://www.gnu.org/licenses/>.

View File

@ -1,11 +1,11 @@
USER-UEF is a LAMMPS package for non-equilibrium molecular dynamics
(NEMD) under diagonal flow fields, including uniaxial and biaxial
flow. With this package, simulations under extensional flow may be
(NEMD) under diagonal flow fields, including uniaxial and biaxial
flow. With this package, simulations under extensional flow may be
carried out for an indefinite amount of time. It is an implementation
of the boundary conditions developed by Matthew Dobson, and also uses
numerical lattice reduction as was proposed by Thomas Hunt. The
lattice reduction algorithm is from Igor Semaev. The package is
intended for simulations of homogeneous flows, and integrates the
numerical lattice reduction as was proposed by Thomas Hunt. The
lattice reduction algorithm is from Igor Semaev. The package is
intended for simulations of homogeneous flows, and integrates the
SLLOD equations of motion.
--
@ -19,7 +19,7 @@ The following commands are contained in this package:
fix npt/uef and fix nvt/uef:
These commands perform time-integration of the SLLOD equations of
motion under constant temperature/pressure with the proper
motion under constant temperature/pressure with the proper
boundary conditions for extensional flow fields.
compute pressure/uef and compute temp/uef:
@ -29,8 +29,8 @@ compute pressure/uef and compute temp/uef:
dump cfg/uef:
This command dumps coordinates in the reference frame corresponding
to the applied flow field.
For more information, visit the documentation page for fix nvt/uef
For more information, visit the documentation page for fix nvt/uef
and examine the example scripts in doc/USER/uef/.
--

23
unittest/.clang-format Normal file
View File

@ -0,0 +1,23 @@
---
Language: Cpp
BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignConsecutiveAssignments: true
AlignEscapedNewlines: Left
AllowShortFunctionsOnASingleLine: Inline
AllowShortLambdasOnASingleLine: None
AllowShortIfStatementsOnASingleLine: WithoutElse
BraceWrapping:
AfterFunction: true
BreakBeforeBraces: Custom
BreakInheritanceList: AfterColon
BreakConstructorInitializers: AfterColon
ColumnLimit: 100
IndentCaseLabels: true
IndentWidth: 4
ObjCBlockIndentWidth: 4
PenaltyBreakAssignment: 4
Standard: Cpp11
TabWidth: 4
UseTab: Never
...

View File

@ -5,3 +5,13 @@ add_subdirectory(force-styles)
add_subdirectory(utils)
add_subdirectory(formats)
find_package(ClangFormat 8.0)
if(ClangFormat_FOUND)
set(UNITTEST_SOURCES)
file(GLOB_RECURSE UNITTEST_SOURCES *.cpp *.h)
add_custom_target(format-tests
COMMAND ${ClangFormat_EXECUTABLE} --verbose -i -style=file ${UNITTEST_SOURCES}
DEPENDS ${UNITTEST_SOURCES})
endif()

View File

@ -8,6 +8,7 @@ endif()
set(TEST_INPUT_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}/tests)
add_library(style_tests STATIC yaml_writer.cpp error_stats.cpp test_config_reader.cpp test_main.cpp)
target_compile_definitions(style_tests PRIVATE TEST_INPUT_FOLDER=${TEST_INPUT_FOLDER})
target_include_directories(style_tests PRIVATE ${LAMMPS_SOURCE_DIR})
target_link_libraries(style_tests PUBLIC GTest::GTest GTest::GMock Yaml::Yaml)
if(BUILD_MPI)
target_link_libraries(style_tests PUBLIC MPI::MPI_CXX)
@ -17,6 +18,7 @@ endif()
# unit test for error stats class
add_executable(test_error_stats test_error_stats.cpp)
target_include_directories(test_error_stats PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${LAMMPS_SOURCE_DIR})
target_link_libraries(test_error_stats PRIVATE GTest::GTestMain GTest::GTest)
add_test(NAME ErrorStats COMMAND test_error_stats)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -12,49 +12,42 @@
------------------------------------------------------------------------- */
#include "error_stats.h"
#include "fmt/format.h"
#include <cmath>
#include <iostream>
#include <string>
#include <cmath>
void ErrorStats::reset() {
num = 0;
void ErrorStats::reset()
{
num = 0;
maxidx = -1;
sum = sumsq = maxerr =0.0;
sum = sumsq = maxerr = 0.0;
}
void ErrorStats::add(const double &val) {
void ErrorStats::add(const double &val)
{
++num;
if (val > maxerr) {
maxidx = num;
maxerr = val;
}
sum += val;
sumsq += val*val;
sumsq += val * val;
}
double ErrorStats::avg() const {
return (num > 0) ? sum/num : 0.0;
double ErrorStats::avg() const
{
return (num > 0) ? sum / num : 0.0;
}
double ErrorStats::dev() const {
return (num > 0) ? sqrt(sumsq/num - sum/num*sum/num) : 0.0;
double ErrorStats::dev() const
{
return (num > 0) ? sqrt(sumsq / num - sum / num * sum / num) : 0.0;
}
std::ostream &operator<<(std::ostream &out, const ErrorStats &stats)
{
const std::ios_base::fmtflags flags = out.flags();
const std::streamsize width = out.width(10);
const std::streamsize prec = out.precision(3);
out << std::scientific
<< "Average: " << stats.avg()
<< " StdDev: " << stats.dev()
<< " MaxErr: " << stats.max();
out.precision(prec);
out.width(width);
out.flags(flags);
return out << " @ item: " << stats.idx();
out << fmt::format("Average: {:10.3e} StdDev: {:10.3e} MaxErr: {:10.3e} @ item: {}",
stats.avg(), stats.dev(), stats.max(), stats.idx());
return out;
}

View File

@ -20,9 +20,7 @@ class ErrorStats {
public:
friend std::ostream &operator<<(std::ostream &out, const ErrorStats &stats);
ErrorStats() {
reset();
}
ErrorStats() { reset(); }
virtual ~ErrorStats() {}
void reset();
@ -33,8 +31,8 @@ public:
double idx() const { return maxidx; }
private:
double sum,sumsq,maxerr;
int num,maxidx;
double sum, sumsq, maxerr;
int num, maxidx;
};
extern std::ostream &operator<<(std::ostream &out, const ErrorStats &stats);

File diff suppressed because it is too large Load Diff

View File

@ -19,11 +19,11 @@
#include <vector>
struct coord_t {
double x,y,z;
double x, y, z;
};
struct stress_t {
double xx,yy,zz,xy,xz,yz;
double xx, yy, zz, xy, xz, yz;
};
class TestConfig {
@ -32,7 +32,7 @@ public:
std::string date_generated;
std::string basename;
double epsilon;
std::vector<std::pair<std::string,std::string>> prerequisites;
std::vector<std::pair<std::string, std::string>> prerequisites;
std::vector<std::string> pre_commands;
std::vector<std::string> post_commands;
std::string input_file;
@ -48,7 +48,7 @@ public:
std::vector<std::string> dihedral_coeff;
std::vector<std::string> improper_coeff;
std::vector<double> equilibrium;
std::vector<std::pair<std::string,int>> extract;
std::vector<std::pair<std::string, int>> extract;
int natoms;
double init_energy;
double run_energy;
@ -61,26 +61,13 @@ public:
std::vector<coord_t> init_forces;
std::vector<coord_t> run_forces;
TestConfig() : lammps_version(""),
date_generated(""),
basename(""),
epsilon(1.0e-14),
input_file(""),
pair_style("zero"),
bond_style("zero"),
angle_style("zero"),
dihedral_style("zero"),
improper_style("zero"),
kspace_style("none"),
natoms(0),
init_energy(0),
run_energy(0),
init_vdwl(0),
run_vdwl(0),
init_coul(0),
run_coul(0),
init_stress({0,0,0,0,0,0}),
run_stress({0,0,0,0,0,0}) {
TestConfig() :
lammps_version(""), date_generated(""), basename(""), epsilon(1.0e-14), input_file(""),
pair_style("zero"), bond_style("zero"), angle_style("zero"), dihedral_style("zero"),
improper_style("zero"), kspace_style("none"), natoms(0), init_energy(0), run_energy(0),
init_vdwl(0), run_vdwl(0), init_coul(0), run_coul(0), init_stress({0, 0, 0, 0, 0, 0}),
run_stress({0, 0, 0, 0, 0, 0})
{
prerequisites.clear();
pre_commands.clear();
post_commands.clear();
@ -93,10 +80,10 @@ public:
init_forces.clear();
run_forces.clear();
}
virtual ~TestConfig() {};
virtual ~TestConfig(){};
private:
TestConfig(const TestConfig &) {};
TestConfig(const TestConfig &){};
};
#endif

View File

@ -11,22 +11,22 @@
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include "test_config.h"
#include "test_config_reader.h"
#include "yaml_reader.h"
#include "test_config.h"
#include "yaml.h"
#include "yaml_reader.h"
#include <cstring>
#include <cstdlib>
#include <cstring>
#include <string>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
TestConfigReader::TestConfigReader(TestConfig & config)
: YamlReader(), config(config) {
TestConfigReader::TestConfigReader(TestConfig &config) : YamlReader(), config(config)
{
consumers["lammps_version"] = &TestConfigReader::lammps_version;
consumers["date_generated"] = &TestConfigReader::date_generated;
consumers["epsilon"] = &TestConfigReader::epsilon;
@ -41,45 +41,48 @@ TestConfigReader::TestConfigReader(TestConfig & config)
consumers["init_forces"] = &TestConfigReader::init_forces;
consumers["run_forces"] = &TestConfigReader::run_forces;
consumers["pair_style"] = &TestConfigReader::pair_style;
consumers["pair_coeff"] = &TestConfigReader::pair_coeff;
consumers["init_vdwl"] = &TestConfigReader::init_vdwl;
consumers["init_coul"] = &TestConfigReader::init_coul;
consumers["run_vdwl"] = &TestConfigReader::run_vdwl;
consumers["run_coul"] = &TestConfigReader::run_coul;
consumers["pair_style"] = &TestConfigReader::pair_style;
consumers["pair_coeff"] = &TestConfigReader::pair_coeff;
consumers["init_vdwl"] = &TestConfigReader::init_vdwl;
consumers["init_coul"] = &TestConfigReader::init_coul;
consumers["run_vdwl"] = &TestConfigReader::run_vdwl;
consumers["run_coul"] = &TestConfigReader::run_coul;
consumers["bond_style"] = &TestConfigReader::bond_style;
consumers["bond_coeff"] = &TestConfigReader::bond_coeff;
consumers["angle_style"] = &TestConfigReader::angle_style;
consumers["angle_coeff"] = &TestConfigReader::angle_coeff;
consumers["init_energy"] = &TestConfigReader::init_energy;
consumers["run_energy"] = &TestConfigReader::run_energy;
consumers["equilibrium"] = &TestConfigReader::equilibrium;
consumers["bond_style"] = &TestConfigReader::bond_style;
consumers["bond_coeff"] = &TestConfigReader::bond_coeff;
consumers["angle_style"] = &TestConfigReader::angle_style;
consumers["angle_coeff"] = &TestConfigReader::angle_coeff;
consumers["init_energy"] = &TestConfigReader::init_energy;
consumers["run_energy"] = &TestConfigReader::run_energy;
consumers["equilibrium"] = &TestConfigReader::equilibrium;
}
void TestConfigReader::prerequisites(const yaml_event_t & event) {
void TestConfigReader::prerequisites(const yaml_event_t &event)
{
config.prerequisites.clear();
std::stringstream data((char *)event.data.scalar.value);
std::string key, value;
while(1) {
while (1) {
data >> key >> value;
if (data.eof()) break;
config.prerequisites.push_back(std::make_pair(key,value));
config.prerequisites.push_back(std::make_pair(key, value));
}
}
void TestConfigReader::pre_commands(const yaml_event_t & event) {
void TestConfigReader::pre_commands(const yaml_event_t &event)
{
config.pre_commands.clear();
std::stringstream data((char *)event.data.scalar.value);
std::string line;
while(std::getline(data, line, '\n')) {
while (std::getline(data, line, '\n')) {
config.pre_commands.push_back(line);
}
}
void TestConfigReader::post_commands(const yaml_event_t & event) {
void TestConfigReader::post_commands(const yaml_event_t &event)
{
config.post_commands.clear();
std::stringstream data((char *)event.data.scalar.value);
std::string line;
@ -89,63 +92,68 @@ void TestConfigReader::post_commands(const yaml_event_t & event) {
}
}
void TestConfigReader::lammps_version(const yaml_event_t & event) {
void TestConfigReader::lammps_version(const yaml_event_t &event)
{
config.lammps_version = (char *)event.data.scalar.value;
}
void TestConfigReader::date_generated(const yaml_event_t & event) {
void TestConfigReader::date_generated(const yaml_event_t &event)
{
config.date_generated = (char *)event.data.scalar.value;
}
void TestConfigReader::epsilon(const yaml_event_t & event) {
void TestConfigReader::epsilon(const yaml_event_t &event)
{
config.epsilon = atof((char *)event.data.scalar.value);
}
void TestConfigReader::input_file(const yaml_event_t & event) {
void TestConfigReader::input_file(const yaml_event_t &event)
{
config.input_file = (char *)event.data.scalar.value;
}
void TestConfigReader::extract(const yaml_event_t & event) {
void TestConfigReader::extract(const yaml_event_t &event)
{
config.extract.clear();
std::stringstream data((char *)event.data.scalar.value);
std::string name;
int value;
while(1) {
while (1) {
data >> name >> value;
if (data.eof()) break;
config.extract.push_back(make_pair(name, value));
}
}
void TestConfigReader::natoms(const yaml_event_t & event) {
void TestConfigReader::natoms(const yaml_event_t &event)
{
config.natoms = atoi((char *)event.data.scalar.value);
}
void TestConfigReader::init_stress(const yaml_event_t & event) {
void TestConfigReader::init_stress(const yaml_event_t &event)
{
stress_t stress;
sscanf((char *)event.data.scalar.value,
"%lg %lg %lg %lg %lg %lg",
&stress.xx, &stress.yy, &stress.zz,
&stress.xy, &stress.xz, &stress.yz);
sscanf((char *)event.data.scalar.value, "%lg %lg %lg %lg %lg %lg", &stress.xx, &stress.yy,
&stress.zz, &stress.xy, &stress.xz, &stress.yz);
config.init_stress = stress;
}
void TestConfigReader::run_stress(const yaml_event_t & event) {
void TestConfigReader::run_stress(const yaml_event_t &event)
{
stress_t stress;
sscanf((char *)event.data.scalar.value,
"%lg %lg %lg %lg %lg %lg",
&stress.xx, &stress.yy, &stress.zz,
&stress.xy, &stress.xz, &stress.yz);
sscanf((char *)event.data.scalar.value, "%lg %lg %lg %lg %lg %lg", &stress.xx, &stress.yy,
&stress.zz, &stress.xy, &stress.xz, &stress.yz);
config.run_stress = stress;
}
void TestConfigReader::init_forces(const yaml_event_t & event) {
void TestConfigReader::init_forces(const yaml_event_t &event)
{
config.init_forces.clear();
config.init_forces.resize(config.natoms+1);
std::stringstream data((const char*)event.data.scalar.value);
config.init_forces.resize(config.natoms + 1);
std::stringstream data((const char *)event.data.scalar.value);
std::string line;
while(std::getline(data, line, '\n')) {
while (std::getline(data, line, '\n')) {
int tag = 0;
coord_t xyz;
sscanf(line.c_str(), "%d %lg %lg %lg", &tag, &xyz.x, &xyz.y, &xyz.z);
@ -153,13 +161,14 @@ void TestConfigReader::init_forces(const yaml_event_t & event) {
}
}
void TestConfigReader::run_forces(const yaml_event_t & event) {
void TestConfigReader::run_forces(const yaml_event_t &event)
{
config.run_forces.clear();
config.run_forces.resize(config.natoms+1);
config.run_forces.resize(config.natoms + 1);
std::stringstream data((char *)event.data.scalar.value);
std::string line;
while(std::getline(data, line, '\n')) {
while (std::getline(data, line, '\n')) {
int tag;
coord_t xyz;
sscanf(line.c_str(), "%d %lg %lg %lg", &tag, &xyz.x, &xyz.y, &xyz.z);
@ -167,11 +176,13 @@ void TestConfigReader::run_forces(const yaml_event_t & event) {
}
}
void TestConfigReader::pair_style(const yaml_event_t & event) {
void TestConfigReader::pair_style(const yaml_event_t &event)
{
config.pair_style = (char *)event.data.scalar.value;
}
void TestConfigReader::pair_coeff(const yaml_event_t & event) {
void TestConfigReader::pair_coeff(const yaml_event_t &event)
{
config.pair_coeff.clear();
std::stringstream data((char *)event.data.scalar.value);
std::string line;
@ -181,11 +192,13 @@ void TestConfigReader::pair_coeff(const yaml_event_t & event) {
}
}
void TestConfigReader::bond_style(const yaml_event_t & event) {
void TestConfigReader::bond_style(const yaml_event_t &event)
{
config.bond_style = (char *)event.data.scalar.value;
}
void TestConfigReader::bond_coeff(const yaml_event_t & event) {
void TestConfigReader::bond_coeff(const yaml_event_t &event)
{
config.bond_coeff.clear();
std::stringstream data((char *)event.data.scalar.value);
std::string line;
@ -195,11 +208,13 @@ void TestConfigReader::bond_coeff(const yaml_event_t & event) {
}
}
void TestConfigReader::angle_style(const yaml_event_t & event) {
void TestConfigReader::angle_style(const yaml_event_t &event)
{
config.angle_style = (char *)event.data.scalar.value;
}
void TestConfigReader::angle_coeff(const yaml_event_t & event) {
void TestConfigReader::angle_coeff(const yaml_event_t &event)
{
config.angle_coeff.clear();
std::stringstream data((char *)event.data.scalar.value);
std::string line;
@ -209,40 +224,46 @@ void TestConfigReader::angle_coeff(const yaml_event_t & event) {
}
}
void TestConfigReader::equilibrium(const yaml_event_t & event) {
void TestConfigReader::equilibrium(const yaml_event_t &event)
{
std::stringstream data((char *)event.data.scalar.value);
config.equilibrium.clear();
double value;
std::size_t num;
data >> num;
for (std::size_t i=0; i < num; ++i) {
for (std::size_t i = 0; i < num; ++i) {
data >> value;
if (data.eof()) break;
config.equilibrium.push_back(value);
}
}
void TestConfigReader::init_vdwl(const yaml_event_t & event) {
void TestConfigReader::init_vdwl(const yaml_event_t &event)
{
config.init_vdwl = atof((char *)event.data.scalar.value);
}
void TestConfigReader::init_coul(const yaml_event_t & event) {
void TestConfigReader::init_coul(const yaml_event_t &event)
{
config.init_coul = atof((char *)event.data.scalar.value);
}
void TestConfigReader::run_vdwl(const yaml_event_t & event) {
void TestConfigReader::run_vdwl(const yaml_event_t &event)
{
config.run_vdwl = atof((char *)event.data.scalar.value);
}
void TestConfigReader::run_coul(const yaml_event_t & event) {
void TestConfigReader::run_coul(const yaml_event_t &event)
{
config.run_coul = atof((char *)event.data.scalar.value);
}
void TestConfigReader::init_energy(const yaml_event_t & event) {
void TestConfigReader::init_energy(const yaml_event_t &event)
{
config.init_energy = atof((char *)event.data.scalar.value);
}
void TestConfigReader::run_energy(const yaml_event_t & event) {
void TestConfigReader::run_energy(const yaml_event_t &event)
{
config.run_energy = atof((char *)event.data.scalar.value);
}

View File

@ -14,40 +14,41 @@
#ifndef TEST_CONFIG_READER_H
#define TEST_CONFIG_READER_H
#include "test_config.h"
#include "yaml_reader.h"
class TestConfigReader : public YamlReader<TestConfigReader> {
TestConfig & config;
TestConfig &config;
public:
TestConfigReader(TestConfig & config);
TestConfigReader(TestConfig &config);
void prerequisites(const yaml_event_t & event);
void pre_commands(const yaml_event_t & event);
void post_commands(const yaml_event_t & event);
void lammps_version(const yaml_event_t & event);
void date_generated(const yaml_event_t & event);
void epsilon(const yaml_event_t & event);
void input_file(const yaml_event_t & event);
void extract(const yaml_event_t & event);
void natoms(const yaml_event_t & event);
void init_stress(const yaml_event_t & event);
void run_stress(const yaml_event_t & event);
void init_forces(const yaml_event_t & event);
void run_forces(const yaml_event_t & event);
void pair_style(const yaml_event_t & event);
void pair_coeff(const yaml_event_t & event);
void bond_style(const yaml_event_t & event);
void bond_coeff(const yaml_event_t & event);
void angle_style(const yaml_event_t & event);
void angle_coeff(const yaml_event_t & event);
void equilibrium(const yaml_event_t & event);
void init_vdwl(const yaml_event_t & event);
void init_coul(const yaml_event_t & event);
void run_vdwl(const yaml_event_t & event);
void run_coul(const yaml_event_t & event);
void init_energy(const yaml_event_t & event);
void run_energy(const yaml_event_t & event);
void prerequisites(const yaml_event_t &event);
void pre_commands(const yaml_event_t &event);
void post_commands(const yaml_event_t &event);
void lammps_version(const yaml_event_t &event);
void date_generated(const yaml_event_t &event);
void epsilon(const yaml_event_t &event);
void input_file(const yaml_event_t &event);
void extract(const yaml_event_t &event);
void natoms(const yaml_event_t &event);
void init_stress(const yaml_event_t &event);
void run_stress(const yaml_event_t &event);
void init_forces(const yaml_event_t &event);
void run_forces(const yaml_event_t &event);
void pair_style(const yaml_event_t &event);
void pair_coeff(const yaml_event_t &event);
void bond_style(const yaml_event_t &event);
void bond_coeff(const yaml_event_t &event);
void angle_style(const yaml_event_t &event);
void angle_coeff(const yaml_event_t &event);
void equilibrium(const yaml_event_t &event);
void init_vdwl(const yaml_event_t &event);
void init_coul(const yaml_event_t &event);
void run_vdwl(const yaml_event_t &event);
void run_coul(const yaml_event_t &event);
void init_energy(const yaml_event_t &event);
void run_energy(const yaml_event_t &event);
};
#endif

View File

@ -5,8 +5,9 @@
// include the implementation since ErrorStats is a standalone class
// this way we don't have to link against the style_tests and lammps libs
#include "error_stats.cpp"
#include "fmtlib_format.cpp"
#include "fmtlib_os.cpp"
TEST(ErrorStats, test)
{
@ -25,7 +26,7 @@ TEST(ErrorStats, test)
std::stringstream out;
out << stats;
ASSERT_EQ(out.str(), " Average: 5.800e-01 StdDev: 7.305e-01 MaxErr: 2.000e+00 @ item: 3");
ASSERT_EQ(out.str(), "Average: 5.800e-01 StdDev: 7.305e-01 MaxErr: 2.000e+00 @ item: 3.0");
stats.reset();
ASSERT_DOUBLE_EQ(stats.avg(), 0.0);

View File

@ -16,16 +16,15 @@
#include "test_config_reader.h"
#include "gtest/gtest.h"
#include <mpi.h>
#include <cstring>
#include <iostream>
#include <mpi.h>
// common read_yaml_file function
bool read_yaml_file(const char *infile, TestConfig &config)
{
auto reader = TestConfigReader(config);
if (reader.parse_file(infile))
return false;
if (reader.parse_file(infile)) return false;
config.basename = reader.get_basename();
return true;
@ -76,32 +75,32 @@ int main(int argc, char **argv)
return 2;
}
int iarg=2;
int iarg = 2;
while (iarg < argc) {
if (strcmp(argv[iarg],"-g") == 0) {
if (iarg+1 < argc) {
generate_yaml_file(argv[iarg+1], test_config);
if (strcmp(argv[iarg], "-g") == 0) {
if (iarg + 1 < argc) {
generate_yaml_file(argv[iarg + 1], test_config);
return 0;
} else {
usage(std::cerr,argv[0]);
usage(std::cerr, argv[0]);
return 1;
}
} else if (strcmp(argv[iarg],"-u") == 0) {
} else if (strcmp(argv[iarg], "-u") == 0) {
generate_yaml_file(argv[1], test_config);
return 0;
} else if (strcmp(argv[iarg],"-d") == 0) {
if (iarg+1 < argc) {
INPUT_FOLDER = argv[iarg+1];
} else if (strcmp(argv[iarg], "-d") == 0) {
if (iarg + 1 < argc) {
INPUT_FOLDER = argv[iarg + 1];
iarg += 2;
} else {
usage(std::cerr,argv[0]);
usage(std::cerr, argv[0]);
return 1;
}
} else if (strcmp(argv[iarg],"-s") == 0) {
} else if (strcmp(argv[iarg], "-s") == 0) {
print_stats = true;
++iarg;
} else if (strcmp(argv[iarg],"-v") == 0) {
} else if (strcmp(argv[iarg], "-v") == 0) {
verbose = true;
++iarg;
} else {

View File

@ -22,13 +22,13 @@ extern bool print_stats;
extern bool verbose;
extern std::string INPUT_FOLDER;
#define EXPECT_FP_LE_WITH_EPS(val1,val2,eps) \
do { \
const double diff = fabs(val1-val2); \
const double div = std::min(fabs(val1),fabs(val2)); \
const double err = (div == 0.0) ? diff : diff/div; \
stats.add(err); \
EXPECT_PRED_FORMAT2(::testing::DoubleLE, err, eps); \
#define EXPECT_FP_LE_WITH_EPS(val1, val2, eps) \
do { \
const double diff = fabs(val1 - val2); \
const double div = std::min(fabs(val1), fabs(val2)); \
const double err = (div == 0.0) ? diff : diff / div; \
stats.add(err); \
EXPECT_PRED_FORMAT2(::testing::DoubleLE, err, eps); \
} while (0);
#endif

View File

@ -17,11 +17,11 @@
#include "yaml.h"
#include <cstdio>
#include <iostream>
#include <map>
#include <string>
#include <iostream>
template<typename ConsumerClass> class YamlReader {
template <typename ConsumerClass> class YamlReader {
private:
enum StateValue {
START,
@ -37,7 +37,7 @@ private:
std::string basename;
protected:
typedef void (ConsumerClass::*EventConsumer)(const yaml_event_t & event);
typedef void (ConsumerClass::*EventConsumer)(const yaml_event_t &event);
std::map<std::string, EventConsumer> consumers;
public:
@ -46,20 +46,21 @@ public:
std::string get_basename() const { return basename; }
int parse_file(const std::string & infile) {
basename = infile;
int parse_file(const std::string &infile)
{
basename = infile;
std::size_t found = basename.rfind(".yaml");
if (found > 0) basename = basename.substr(0,found);
if (found > 0) basename = basename.substr(0, found);
found = basename.find_last_of("/\\");
if (found != std::string::npos) basename = basename.substr(found+1);
if (found != std::string::npos) basename = basename.substr(found + 1);
FILE *fp = fopen(infile.c_str(),"r");
FILE *fp = fopen(infile.c_str(), "r");
yaml_parser_t parser;
yaml_event_t event;
if (!fp) {
std::cerr << "Cannot open yaml file '" << infile
<< "': " << strerror(errno) << std::endl;
std::cerr << "Cannot open yaml file '" << infile << "': " << strerror(errno)
<< std::endl;
return 1;
}
yaml_parser_initialize(&parser);
@ -75,9 +76,9 @@ public:
}
if (accepted) {
if(!consume_key_value(key, event)) {
std::cerr << "Ignoring unknown key/value pair: " << key
<< " = " << event.data.scalar.value << std::endl;
if (!consume_key_value(key, event)) {
std::cerr << "Ignoring unknown key/value pair: " << key << " = "
<< event.data.scalar.value << std::endl;
}
}
yaml_event_delete(&event);
@ -89,13 +90,14 @@ public:
}
protected:
bool consume_key_value(const std::string & key, const yaml_event_t & event) {
auto it = consumers.find(key);
ConsumerClass *consumer = dynamic_cast<ConsumerClass*>(this);
bool consume_key_value(const std::string &key, const yaml_event_t &event)
{
auto it = consumers.find(key);
ConsumerClass *consumer = dynamic_cast<ConsumerClass *>(this);
if(consumer) {
if(it != consumers.end()) {
//std::cerr << "Loading: " << key << std::endl;
if (consumer) {
if (it != consumers.end()) {
// std::cerr << "Loading: " << key << std::endl;
(consumer->*(it->second))(event);
return true;
}
@ -106,69 +108,68 @@ protected:
return false;
}
bool consume_event(yaml_event_t & event) {
bool consume_event(yaml_event_t &event)
{
accepted = false;
switch (state) {
case START:
switch (event.type) {
case YAML_MAPPING_START_EVENT:
state = ACCEPT_KEY;
break;
case YAML_SCALAR_EVENT:
case YAML_SEQUENCE_START_EVENT:
state = ERROR;
break;
case YAML_STREAM_END_EVENT:
state = STOP;
break;
case YAML_STREAM_START_EVENT:
case YAML_DOCUMENT_START_EVENT:
case YAML_DOCUMENT_END_EVENT:
// ignore
break;
default:
std::cerr << "UNHANDLED YAML EVENT: " << event.type << std::endl;
state = ERROR;
break;
}
break;
case START:
switch (event.type) {
case YAML_MAPPING_START_EVENT:
state = ACCEPT_KEY;
break;
case YAML_SCALAR_EVENT:
case YAML_SEQUENCE_START_EVENT:
state = ERROR;
break;
case YAML_STREAM_END_EVENT:
state = STOP;
break;
case YAML_STREAM_START_EVENT:
case YAML_DOCUMENT_START_EVENT:
case YAML_DOCUMENT_END_EVENT:
// ignore
break;
default:
std::cerr << "UNHANDLED YAML EVENT: " << event.type << std::endl;
state = ERROR;
break;
}
break;
case ACCEPT_KEY:
switch (event.type) {
case YAML_SCALAR_EVENT:
key = (char *) event.data.scalar.value;
state = ACCEPT_VALUE;
break;
case YAML_MAPPING_END_EVENT:
state = STOP;
break;
default:
std::cerr << "UNHANDLED YAML EVENT (key): " << event.type
<< "\nVALUE: " << event.data.scalar.value
<< std::endl;
state = ERROR;
break;
}
break;
case ACCEPT_KEY:
switch (event.type) {
case YAML_SCALAR_EVENT:
key = (char *)event.data.scalar.value;
state = ACCEPT_VALUE;
break;
case YAML_MAPPING_END_EVENT:
state = STOP;
break;
default:
std::cerr << "UNHANDLED YAML EVENT (key): " << event.type
<< "\nVALUE: " << event.data.scalar.value << std::endl;
state = ERROR;
break;
}
break;
case ACCEPT_VALUE:
switch (event.type) {
case YAML_SCALAR_EVENT:
accepted = true;
state = ACCEPT_KEY;
break;
default:
std::cerr << "UNHANDLED YAML EVENT (value): " << event.type
<< "\nVALUE: " << event.data.scalar.value
<< std::endl;
state = ERROR;
break;
}
break;
case ACCEPT_VALUE:
switch (event.type) {
case YAML_SCALAR_EVENT:
accepted = true;
state = ACCEPT_KEY;
break;
default:
std::cerr << "UNHANDLED YAML EVENT (value): " << event.type
<< "\nVALUE: " << event.data.scalar.value << std::endl;
state = ERROR;
break;
}
break;
case ERROR:
case STOP:
break;
case ERROR:
case STOP:
break;
}
return (state != ERROR);
}

View File

@ -14,10 +14,11 @@
#include "yaml_writer.h"
#include "yaml.h"
#include <string>
#include <cstdio>
#include <string>
YamlWriter::YamlWriter(const char * outfile) {
YamlWriter::YamlWriter(const char *outfile)
{
yaml_emitter_initialize(&emitter);
fp = fopen(outfile, "w");
if (!fp) {
@ -31,13 +32,13 @@ YamlWriter::YamlWriter(const char * outfile) {
yaml_emitter_emit(&emitter, &event);
yaml_document_start_event_initialize(&event, NULL, NULL, NULL, 0);
yaml_emitter_emit(&emitter, &event);
yaml_mapping_start_event_initialize(&event, NULL,
(yaml_char_t *)YAML_MAP_TAG,
1, YAML_ANY_MAPPING_STYLE);
yaml_mapping_start_event_initialize(&event, NULL, (yaml_char_t *)YAML_MAP_TAG, 1,
YAML_ANY_MAPPING_STYLE);
yaml_emitter_emit(&emitter, &event);
}
YamlWriter::~YamlWriter() {
YamlWriter::~YamlWriter()
{
yaml_mapping_end_event_initialize(&event);
yaml_emitter_emit(&emitter, &event);
yaml_document_end_event_initialize(&event, 0);
@ -48,84 +49,65 @@ YamlWriter::~YamlWriter() {
fclose(fp);
}
void YamlWriter::emit(const std::string &key, const double value) {
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *) key.c_str(),
key.size(), 1, 0,
void YamlWriter::emit(const std::string &key, const double value)
{
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)key.c_str(), key.size(), 1, 0,
YAML_PLAIN_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
char buf[256];
snprintf(buf,256,"%.15g",value);
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)buf,
strlen(buf), 1, 0,
YAML_PLAIN_SCALAR_STYLE);
snprintf(buf, 256, "%.15g", value);
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf,
strlen(buf), 1, 0, YAML_PLAIN_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
}
void YamlWriter::emit(const std::string &key, const long value) {
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *) key.c_str(),
key.size(), 1, 0,
void YamlWriter::emit(const std::string &key, const long value)
{
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)key.c_str(), key.size(), 1, 0,
YAML_PLAIN_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
char buf[256];
snprintf(buf,256,"%ld",value);
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)buf,
strlen(buf), 1, 0,
YAML_PLAIN_SCALAR_STYLE);
snprintf(buf, 256, "%ld", value);
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf,
strlen(buf), 1, 0, YAML_PLAIN_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
}
void YamlWriter::emit(const std::string &key, const int value) {
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *) key.c_str(),
key.size(), 1, 0,
void YamlWriter::emit(const std::string &key, const int value)
{
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)key.c_str(), key.size(), 1, 0,
YAML_PLAIN_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
char buf[256];
snprintf(buf,256,"%d",value);
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)buf,
strlen(buf), 1, 0,
YAML_PLAIN_SCALAR_STYLE);
snprintf(buf, 256, "%d", value);
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG, (yaml_char_t *)buf,
strlen(buf), 1, 0, YAML_PLAIN_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
}
void YamlWriter::emit(const std::string &key, const std::string &value)
{
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *) key.c_str(),
key.size(), 1, 0,
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)key.c_str(), key.size(), 1, 0,
YAML_PLAIN_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)value.c_str(),
value.size(), 1, 0,
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)value.c_str(), value.size(), 1, 0,
YAML_PLAIN_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
}
void YamlWriter::emit_block(const std::string &key, const std::string &value) {
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *) key.c_str(),
key.size(), 1, 0,
void YamlWriter::emit_block(const std::string &key, const std::string &value)
{
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)key.c_str(), key.size(), 1, 0,
YAML_PLAIN_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
yaml_scalar_event_initialize(&event, NULL,
(yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)value.c_str(),
value.size(), 1, 0,
yaml_scalar_event_initialize(&event, NULL, (yaml_char_t *)YAML_STR_TAG,
(yaml_char_t *)value.c_str(), value.size(), 1, 0,
YAML_LITERAL_SCALAR_STYLE);
yaml_emitter_emit(&emitter, &event);
}

View File

@ -20,7 +20,7 @@
class YamlWriter {
public:
YamlWriter(const char * outfile);
YamlWriter(const char *outfile);
virtual ~YamlWriter();
// emitters
@ -33,11 +33,11 @@ public:
private:
FILE *fp;
yaml_emitter_t emitter;
yaml_event_t event;
yaml_event_t event;
private:
YamlWriter() {};
YamlWriter(const YamlWriter &) {};
YamlWriter(){};
YamlWriter(const YamlWriter &){};
};
#endif

View File

@ -11,11 +11,11 @@
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MANYBODY/pair_eim.h"
#include "lammps.h"
#include "utils.h"
#include "MANYBODY/pair_eim.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <mpi.h>
@ -23,64 +23,67 @@ using namespace LAMMPS_NS;
class EIMPotentialFileReaderTest : public ::testing::Test {
protected:
LAMMPS * lmp;
LAMMPS *lmp;
PairEIM::Setfl setfl;
static const int nelements = 9;
void SetUp() override {
const char *args[] = {"PotentialFileReaderTest", "-log", "none", "-echo", "screen", "-nocite" };
void SetUp() override
{
const char *args[] = {
"PotentialFileReaderTest", "-log", "none", "-echo", "screen", "-nocite"};
char **argv = (char **)args;
int argc = sizeof(args)/sizeof(char *);
int argc = sizeof(args) / sizeof(char *);
::testing::internal::CaptureStdout();
lmp = new LAMMPS(argc, argv, MPI_COMM_WORLD);
::testing::internal::GetCapturedStdout();
int npair = nelements*(nelements+1)/2;
setfl.ielement = new int[nelements];
setfl.mass = new double[nelements];
int npair = nelements * (nelements + 1) / 2;
setfl.ielement = new int[nelements];
setfl.mass = new double[nelements];
setfl.negativity = new double[nelements];
setfl.ra = new double[nelements];
setfl.ri = new double[nelements];
setfl.Ec = new double[nelements];
setfl.q0 = new double[nelements];
setfl.rcutphiA = new double[npair];
setfl.rcutphiR = new double[npair];
setfl.Eb = new double[npair];
setfl.r0 = new double[npair];
setfl.alpha = new double[npair];
setfl.beta = new double[npair];
setfl.rcutq = new double[npair];
setfl.Asigma = new double[npair];
setfl.rq = new double[npair];
setfl.rcutsigma = new double[npair];
setfl.Ac = new double[npair];
setfl.zeta = new double[npair];
setfl.rs = new double[npair];
setfl.tp = new int[npair];
setfl.ra = new double[nelements];
setfl.ri = new double[nelements];
setfl.Ec = new double[nelements];
setfl.q0 = new double[nelements];
setfl.rcutphiA = new double[npair];
setfl.rcutphiR = new double[npair];
setfl.Eb = new double[npair];
setfl.r0 = new double[npair];
setfl.alpha = new double[npair];
setfl.beta = new double[npair];
setfl.rcutq = new double[npair];
setfl.Asigma = new double[npair];
setfl.rq = new double[npair];
setfl.rcutsigma = new double[npair];
setfl.Ac = new double[npair];
setfl.zeta = new double[npair];
setfl.rs = new double[npair];
setfl.tp = new int[npair];
}
void TearDown() override {
delete [] setfl.ielement;
delete [] setfl.mass;
delete [] setfl.negativity;
delete [] setfl.ra;
delete [] setfl.ri;
delete [] setfl.Ec;
delete [] setfl.q0;
delete [] setfl.rcutphiA;
delete [] setfl.rcutphiR;
delete [] setfl.Eb;
delete [] setfl.r0;
delete [] setfl.alpha;
delete [] setfl.beta;
delete [] setfl.rcutq;
delete [] setfl.Asigma;
delete [] setfl.rq;
delete [] setfl.rcutsigma;
delete [] setfl.Ac;
delete [] setfl.zeta;
delete [] setfl.rs;
delete [] setfl.tp;
void TearDown() override
{
delete[] setfl.ielement;
delete[] setfl.mass;
delete[] setfl.negativity;
delete[] setfl.ra;
delete[] setfl.ri;
delete[] setfl.Ec;
delete[] setfl.q0;
delete[] setfl.rcutphiA;
delete[] setfl.rcutphiR;
delete[] setfl.Eb;
delete[] setfl.r0;
delete[] setfl.alpha;
delete[] setfl.beta;
delete[] setfl.rcutq;
delete[] setfl.Asigma;
delete[] setfl.rq;
delete[] setfl.rcutsigma;
delete[] setfl.Ac;
delete[] setfl.zeta;
delete[] setfl.rs;
delete[] setfl.tp;
::testing::internal::CaptureStdout();
delete lmp;
@ -88,7 +91,8 @@ protected:
}
};
TEST_F(EIMPotentialFileReaderTest, global_line) {
TEST_F(EIMPotentialFileReaderTest, global_line)
{
::testing::internal::CaptureStdout();
EIMPotentialFileReader reader(lmp, "ffield.eim");
::testing::internal::GetCapturedStdout();
@ -99,7 +103,8 @@ TEST_F(EIMPotentialFileReaderTest, global_line) {
ASSERT_DOUBLE_EQ(setfl.rsmall, 1.645);
}
TEST_F(EIMPotentialFileReaderTest, element_line_sequential) {
TEST_F(EIMPotentialFileReaderTest, element_line_sequential)
{
::testing::internal::CaptureStdout();
EIMPotentialFileReader reader(lmp, "ffield.eim");
::testing::internal::GetCapturedStdout();
@ -123,7 +128,8 @@ TEST_F(EIMPotentialFileReaderTest, element_line_sequential) {
ASSERT_DOUBLE_EQ(setfl.q0[1], 0.0000e+00);
}
TEST_F(EIMPotentialFileReaderTest, element_line_random) {
TEST_F(EIMPotentialFileReaderTest, element_line_random)
{
::testing::internal::CaptureStdout();
EIMPotentialFileReader reader(lmp, "ffield.eim");
::testing::internal::GetCapturedStdout();
@ -138,7 +144,8 @@ TEST_F(EIMPotentialFileReaderTest, element_line_random) {
ASSERT_DOUBLE_EQ(setfl.q0[0], 0.0000e+00);
}
TEST_F(EIMPotentialFileReaderTest, pair_line) {
TEST_F(EIMPotentialFileReaderTest, pair_line)
{
::testing::internal::CaptureStdout();
EIMPotentialFileReader reader(lmp, "ffield.eim");
::testing::internal::GetCapturedStdout();
@ -147,7 +154,7 @@ TEST_F(EIMPotentialFileReaderTest, pair_line) {
ASSERT_DOUBLE_EQ(setfl.rcutphiA[0], 6.0490e+00);
ASSERT_DOUBLE_EQ(setfl.rcutphiR[0], 6.0490e+00);
ASSERT_DOUBLE_EQ(setfl.Eb[0], -2.5330e-01);
ASSERT_DOUBLE_EQ(setfl.r0[0], 3.6176e+00);
ASSERT_DOUBLE_EQ(setfl.r0[0], 3.6176e+00);
ASSERT_DOUBLE_EQ(setfl.alpha[0], 7.5536e+00);
ASSERT_DOUBLE_EQ(setfl.beta[0], 3.5017e+00);
ASSERT_DOUBLE_EQ(setfl.rcutq[0], 0.0000e+00);
@ -160,7 +167,8 @@ TEST_F(EIMPotentialFileReaderTest, pair_line) {
ASSERT_EQ(setfl.tp[0], 1);
}
TEST_F(EIMPotentialFileReaderTest, pair_identical) {
TEST_F(EIMPotentialFileReaderTest, pair_identical)
{
::testing::internal::CaptureStdout();
EIMPotentialFileReader reader(lmp, "ffield.eim");
::testing::internal::GetCapturedStdout();

View File

@ -11,23 +11,23 @@
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "potential_file_reader.h"
#include "lammps.h"
#include "utils.h"
#include "MANYBODY/pair_sw.h"
#include "MANYBODY/pair_comb.h"
#include "MANYBODY/pair_comb3.h"
#include "MANYBODY/pair_eim.h"
#include "MANYBODY/pair_gw.h"
#include "MANYBODY/pair_gw_zbl.h"
#include "MANYBODY/pair_nb3b_harmonic.h"
#include "MANYBODY/pair_sw.h"
#include "MANYBODY/pair_tersoff.h"
#include "MANYBODY/pair_tersoff_mod.h"
#include "MANYBODY/pair_tersoff_mod_c.h"
#include "MANYBODY/pair_tersoff_zbl.h"
#include "MANYBODY/pair_gw.h"
#include "MANYBODY/pair_gw_zbl.h"
#include "MANYBODY/pair_nb3b_harmonic.h"
#include "MANYBODY/pair_vashishta.h"
#include "MANYBODY/pair_eim.h"
#include "lammps.h"
#include "potential_file_reader.h"
#include "utils.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <mpi.h>
@ -47,25 +47,29 @@ const int LAMMPS_NS::PairVashishta::NPARAMS_PER_LINE;
class PotentialFileReaderTest : public ::testing::Test {
protected:
LAMMPS * lmp;
LAMMPS *lmp;
void SetUp() override {
const char *args[] = {"PotentialFileReaderTest", "-log", "none", "-echo", "screen", "-nocite" };
void SetUp() override
{
const char *args[] = {
"PotentialFileReaderTest", "-log", "none", "-echo", "screen", "-nocite"};
char **argv = (char **)args;
int argc = sizeof(args)/sizeof(char *);
int argc = sizeof(args) / sizeof(char *);
::testing::internal::CaptureStdout();
lmp = new LAMMPS(argc, argv, MPI_COMM_WORLD);
::testing::internal::GetCapturedStdout();
}
void TearDown() override {
void TearDown() override
{
::testing::internal::CaptureStdout();
delete lmp;
::testing::internal::GetCapturedStdout();
}
};
TEST_F(PotentialFileReaderTest, Si) {
TEST_F(PotentialFileReaderTest, Si)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "Si.sw", "Stillinger-Weber");
::testing::internal::GetCapturedStdout();
@ -74,7 +78,8 @@ TEST_F(PotentialFileReaderTest, Si) {
ASSERT_EQ(utils::count_words(line), PairSW::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, Comb) {
TEST_F(PotentialFileReaderTest, Comb)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "ffield.comb", "COMB");
::testing::internal::GetCapturedStdout();
@ -83,7 +88,8 @@ TEST_F(PotentialFileReaderTest, Comb) {
ASSERT_EQ(utils::count_words(line), PairComb::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, Comb3) {
TEST_F(PotentialFileReaderTest, Comb3)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "ffield.comb3", "COMB3");
::testing::internal::GetCapturedStdout();
@ -92,7 +98,8 @@ TEST_F(PotentialFileReaderTest, Comb3) {
ASSERT_EQ(utils::count_words(line), PairComb3::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, Tersoff) {
TEST_F(PotentialFileReaderTest, Tersoff)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "Si.tersoff", "Tersoff");
::testing::internal::GetCapturedStdout();
@ -101,7 +108,8 @@ TEST_F(PotentialFileReaderTest, Tersoff) {
ASSERT_EQ(utils::count_words(line), PairTersoff::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, TersoffMod) {
TEST_F(PotentialFileReaderTest, TersoffMod)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "Si.tersoff.mod", "Tersoff/Mod");
::testing::internal::GetCapturedStdout();
@ -110,7 +118,8 @@ TEST_F(PotentialFileReaderTest, TersoffMod) {
ASSERT_EQ(utils::count_words(line), PairTersoffMOD::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, TersoffModC) {
TEST_F(PotentialFileReaderTest, TersoffModC)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "Si.tersoff.modc", "Tersoff/ModC");
::testing::internal::GetCapturedStdout();
@ -119,7 +128,8 @@ TEST_F(PotentialFileReaderTest, TersoffModC) {
ASSERT_EQ(utils::count_words(line), PairTersoffMODC::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, TersoffZBL) {
TEST_F(PotentialFileReaderTest, TersoffZBL)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "SiC.tersoff.zbl", "Tersoff/ZBL");
::testing::internal::GetCapturedStdout();
@ -128,7 +138,8 @@ TEST_F(PotentialFileReaderTest, TersoffZBL) {
ASSERT_EQ(utils::count_words(line), PairTersoffZBL::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, GW) {
TEST_F(PotentialFileReaderTest, GW)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "SiC.gw", "GW");
::testing::internal::GetCapturedStdout();
@ -137,7 +148,8 @@ TEST_F(PotentialFileReaderTest, GW) {
ASSERT_EQ(utils::count_words(line), PairGW::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, GWZBL) {
TEST_F(PotentialFileReaderTest, GWZBL)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "SiC.gw.zbl", "GW/ZBL");
::testing::internal::GetCapturedStdout();
@ -146,7 +158,8 @@ TEST_F(PotentialFileReaderTest, GWZBL) {
ASSERT_EQ(utils::count_words(line), PairGWZBL::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, Nb3bHarmonic) {
TEST_F(PotentialFileReaderTest, Nb3bHarmonic)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "MOH.nb3b.harmonic", "NB3B Harmonic");
::testing::internal::GetCapturedStdout();
@ -155,7 +168,8 @@ TEST_F(PotentialFileReaderTest, Nb3bHarmonic) {
ASSERT_EQ(utils::count_words(line), PairNb3bHarmonic::NPARAMS_PER_LINE);
}
TEST_F(PotentialFileReaderTest, Vashishta) {
TEST_F(PotentialFileReaderTest, Vashishta)
{
::testing::internal::CaptureStdout();
PotentialFileReader reader(lmp, "SiC.vashishta", "Vashishta");
::testing::internal::GetCapturedStdout();

View File

@ -11,114 +11,127 @@
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include "lmptype.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "fmt/format.h"
#include <string>
#include "lmptype.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <exception>
#include <string>
using namespace LAMMPS_NS;
using ::testing::Eq;
// this tests a subset of {fmt} that is most relevant to LAMMPS
TEST(FmtLib, insert_string) {
TEST(FmtLib, insert_string)
{
const char val[] = "word";
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word word"));
}
TEST(FmtLib, insert_int) {
TEST(FmtLib, insert_int)
{
const int val = 333;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word 333"));
}
TEST(FmtLib, insert_neg_int) {
TEST(FmtLib, insert_neg_int)
{
const int val = -333;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word -333"));
}
TEST(FmtLib, insert_bigint) {
TEST(FmtLib, insert_bigint)
{
#if defined(LAMMPS_BIGBIG) || defined(LAMMPS_SMALLBIG)
const bigint val = 9945234592L;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word 9945234592"));
#else
GTEST_SKIP();
#endif
}
TEST(FmtLib, insert_neg_bigint) {
TEST(FmtLib, insert_neg_bigint)
{
#if defined(LAMMPS_BIGBIG) || defined(LAMMPS_SMALLBIG)
const bigint val = -9945234592L;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word -9945234592"));
#else
GTEST_SKIP();
#endif
}
TEST(FmtLib, insert_tagint) {
TEST(FmtLib, insert_tagint)
{
#if defined(LAMMPS_BIGBIG)
const tagint val = 9945234592L;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word 9945234592"));
#else
GTEST_SKIP();
#endif
}
TEST(FmtLib, insert_neg_tagint) {
TEST(FmtLib, insert_neg_tagint)
{
#if defined(LAMMPS_BIGBIG)
const tagint val = -9945234592L;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word -9945234592"));
#else
GTEST_SKIP();
#endif
}
TEST(FmtLib, insert_imageint) {
TEST(FmtLib, insert_imageint)
{
#if defined(LAMMPS_BIGBIG)
const imageint val = 9945234592L;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word 9945234592"));
#else
GTEST_SKIP();
#endif
}
TEST(FmtLib, insert_neg_imageint) {
TEST(FmtLib, insert_neg_imageint)
{
#if defined(LAMMPS_BIGBIG)
const imageint val = -9945234592L;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word -9945234592"));
#else
GTEST_SKIP();
#endif
}
TEST(FmtLib, insert_double) {
TEST(FmtLib, insert_double)
{
const double val = 1.5;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word 1.5"));
}
TEST(FmtLib, insert_neg_double) {
TEST(FmtLib, insert_neg_double)
{
const double val = -1.5;
auto text = fmt::format("word {}",val);
auto text = fmt::format("word {}", val);
ASSERT_THAT(text, Eq("word -1.5"));
}
TEST(FmtLib, int_for_double) {
TEST(FmtLib, int_for_double)
{
const double val = -1.5;
ASSERT_THROW(fmt::format("word {:d}",val),std::exception);
ASSERT_THROW(fmt::format("word {:d}", val), std::exception);
}
TEST(FmtLib, double_for_int) {
TEST(FmtLib, double_for_int)
{
const int val = 15;
ASSERT_THROW(fmt::format("word {:g}",val),std::exception);
ASSERT_THROW(fmt::format("word {:g}", val), std::exception);
}

View File

@ -11,100 +11,117 @@
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "tokenizer.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using namespace LAMMPS_NS;
using ::testing::Eq;
TEST(Tokenizer, empty_string) {
TEST(Tokenizer, empty_string)
{
Tokenizer t("", " ");
ASSERT_EQ(t.count(), 0);
}
TEST(Tokenizer, whitespace_only) {
TEST(Tokenizer, whitespace_only)
{
Tokenizer t(" ", " ");
ASSERT_EQ(t.count(), 0);
}
TEST(Tokenizer, single_word) {
TEST(Tokenizer, single_word)
{
Tokenizer t("test", " ");
ASSERT_EQ(t.count(), 1);
}
TEST(Tokenizer, two_words) {
TEST(Tokenizer, two_words)
{
Tokenizer t("test word", " ");
ASSERT_EQ(t.count(), 2);
}
TEST(Tokenizer, prefix_separators) {
TEST(Tokenizer, prefix_separators)
{
Tokenizer t(" test word", " ");
ASSERT_EQ(t.count(), 2);
}
TEST(Tokenizer, postfix_separators) {
TEST(Tokenizer, postfix_separators)
{
Tokenizer t("test word ", " ");
ASSERT_EQ(t.count(), 2);
}
TEST(Tokenizer, iterate_words) {
TEST(Tokenizer, iterate_words)
{
Tokenizer t(" test word ", " ");
ASSERT_THAT(t.next(), Eq("test"));
ASSERT_THAT(t.next(), Eq("word"));
ASSERT_EQ(t.count(), 2);
}
TEST(Tokenizer, default_separators) {
TEST(Tokenizer, default_separators)
{
Tokenizer t(" \r\n test \t word \f");
ASSERT_THAT(t.next(), Eq("test"));
ASSERT_THAT(t.next(), Eq("word"));
ASSERT_EQ(t.count(), 2);
}
TEST(Tokenizer, as_vector) {
TEST(Tokenizer, as_vector)
{
Tokenizer t(" \r\n test \t word \f");
std::vector<std::string> list = t.as_vector();
ASSERT_THAT(list[0], Eq("test"));
ASSERT_THAT(list[1], Eq("word"));
}
TEST(ValueTokenizer, empty_string) {
TEST(ValueTokenizer, empty_string)
{
ValueTokenizer values("");
ASSERT_FALSE(values.has_next());
}
TEST(ValueTokenizer, bad_integer) {
TEST(ValueTokenizer, bad_integer)
{
ValueTokenizer values("f10");
ASSERT_THROW(values.next_int(), InvalidIntegerException);
}
TEST(ValueTokenizer, bad_double) {
TEST(ValueTokenizer, bad_double)
{
ValueTokenizer values("1a.0");
ASSERT_THROW(values.next_double(), InvalidFloatException);
}
TEST(ValueTokenizer, valid_int) {
TEST(ValueTokenizer, valid_int)
{
ValueTokenizer values("10");
ASSERT_EQ(values.next_int(), 10);
}
TEST(ValueTokenizer, valid_tagint) {
TEST(ValueTokenizer, valid_tagint)
{
ValueTokenizer values("42");
ASSERT_EQ(values.next_tagint(), 42);
}
TEST(ValueTokenizer, valid_bigint) {
TEST(ValueTokenizer, valid_bigint)
{
ValueTokenizer values("42");
ASSERT_EQ(values.next_bigint(), 42);
}
TEST(ValueTokenizer, valid_double) {
TEST(ValueTokenizer, valid_double)
{
ValueTokenizer values("3.14");
ASSERT_DOUBLE_EQ(values.next_double(), 3.14);
}
TEST(ValueTokenizer, valid_double_with_exponential) {
TEST(ValueTokenizer, valid_double_with_exponential)
{
ValueTokenizer values("3.14e22");
ASSERT_DOUBLE_EQ(values.next_double(), 3.14e22);
}

View File

@ -11,215 +11,265 @@
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "utils.h"
#include <string>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <string>
using namespace LAMMPS_NS;
using ::testing::Eq;
TEST(Utils, trim_comment) {
TEST(Utils, trim_comment)
{
auto trimmed = utils::trim_comment("some text # comment");
ASSERT_THAT(trimmed, Eq("some text "));
}
TEST(Utils, count_words) {
TEST(Utils, count_words)
{
ASSERT_EQ(utils::count_words("some text # comment"), 4);
}
TEST(Utils, count_words_non_default) {
TEST(Utils, count_words_non_default)
{
ASSERT_EQ(utils::count_words("some text # comment", " #"), 3);
}
TEST(Utils, trim_and_count_words) {
TEST(Utils, trim_and_count_words)
{
ASSERT_EQ(utils::trim_and_count_words("some text # comment"), 2);
}
TEST(Utils, count_words_with_extra_spaces) {
TEST(Utils, count_words_with_extra_spaces)
{
ASSERT_EQ(utils::count_words(" some text # comment "), 4);
}
TEST(Utils, valid_integer1) {
TEST(Utils, valid_integer1)
{
ASSERT_TRUE(utils::is_integer("10"));
}
TEST(Utils, valid_integer2) {
TEST(Utils, valid_integer2)
{
ASSERT_TRUE(utils::is_integer("-10"));
}
TEST(Utils, valid_integer3) {
TEST(Utils, valid_integer3)
{
ASSERT_TRUE(utils::is_integer("+10"));
}
TEST(Utils, valid_double1) {
TEST(Utils, valid_double1)
{
ASSERT_TRUE(utils::is_double("10.0"));
}
TEST(Utils, valid_double2) {
TEST(Utils, valid_double2)
{
ASSERT_TRUE(utils::is_double("1."));
}
TEST(Utils, valid_double3) {
TEST(Utils, valid_double3)
{
ASSERT_TRUE(utils::is_double(".0"));
}
TEST(Utils, valid_double4) {
TEST(Utils, valid_double4)
{
ASSERT_TRUE(utils::is_double("-10.0"));
}
TEST(Utils, valid_double5) {
TEST(Utils, valid_double5)
{
ASSERT_TRUE(utils::is_double("-1."));
}
TEST(Utils, valid_double6) {
TEST(Utils, valid_double6)
{
ASSERT_TRUE(utils::is_double("-.0"));
}
TEST(Utils, valid_double7) {
TEST(Utils, valid_double7)
{
ASSERT_TRUE(utils::is_double("+10.0"));
}
TEST(Utils, valid_double8) {
TEST(Utils, valid_double8)
{
ASSERT_TRUE(utils::is_double("+1."));
}
TEST(Utils, valid_double9) {
TEST(Utils, valid_double9)
{
ASSERT_TRUE(utils::is_double("+.0"));
}
TEST(Utils, empty_not_an_integer) {
TEST(Utils, empty_not_an_integer)
{
ASSERT_FALSE(utils::is_integer(""));
}
TEST(Utils, empty_not_a_double) {
TEST(Utils, empty_not_a_double)
{
ASSERT_FALSE(utils::is_double(""));
}
TEST(Utils, text_not_an_integer) {
TEST(Utils, text_not_an_integer)
{
ASSERT_FALSE(utils::is_integer("one"));
}
TEST(Utils, text_not_a_double) {
TEST(Utils, text_not_a_double)
{
ASSERT_FALSE(utils::is_double("half"));
}
TEST(Utils, double_not_an_integer1) {
TEST(Utils, double_not_an_integer1)
{
ASSERT_FALSE(utils::is_integer("10.0"));
}
TEST(Utils, double_not_an_integer2) {
TEST(Utils, double_not_an_integer2)
{
ASSERT_FALSE(utils::is_integer(".0"));
}
TEST(Utils, double_not_an_integer3) {
TEST(Utils, double_not_an_integer3)
{
ASSERT_FALSE(utils::is_integer("1."));
}
TEST(Utils, integer_is_double1) {
TEST(Utils, integer_is_double1)
{
ASSERT_TRUE(utils::is_double("10"));
}
TEST(Utils, integer_is_double2) {
TEST(Utils, integer_is_double2)
{
ASSERT_TRUE(utils::is_double("-10"));
}
TEST(Utils, is_double_with_exponential) {
TEST(Utils, is_double_with_exponential)
{
ASSERT_TRUE(utils::is_double("+1e02"));
}
TEST(Utils, is_double_with_neg_exponential) {
TEST(Utils, is_double_with_neg_exponential)
{
ASSERT_TRUE(utils::is_double("1.0e-22"));
}
TEST(Utils, is_double_with_pos_exponential) {
TEST(Utils, is_double_with_pos_exponential)
{
ASSERT_TRUE(utils::is_double(".1e+22"));
}
TEST(Utils, signed_double_and_exponential) {
TEST(Utils, signed_double_and_exponential)
{
ASSERT_TRUE(utils::is_double("-10E-22"));
}
TEST(Utils, is_double_with_d_exponential) {
TEST(Utils, is_double_with_d_exponential)
{
ASSERT_FALSE(utils::is_double("10d22"));
}
TEST(Utils, is_double_with_neg_d_exponential) {
TEST(Utils, is_double_with_neg_d_exponential)
{
ASSERT_FALSE(utils::is_double("10d-22"));
}
TEST(Utils, signed_double_and_d_exponential) {
TEST(Utils, signed_double_and_d_exponential)
{
ASSERT_FALSE(utils::is_double("-10D-22"));
}
TEST(Utils, strmatch_beg) {
ASSERT_TRUE(utils::strmatch("rigid/small/omp","^rigid"));
TEST(Utils, strmatch_beg)
{
ASSERT_TRUE(utils::strmatch("rigid/small/omp", "^rigid"));
}
TEST(Utils, strmatch_mid1) {
ASSERT_TRUE(utils::strmatch("rigid/small/omp","small"));
TEST(Utils, strmatch_mid1)
{
ASSERT_TRUE(utils::strmatch("rigid/small/omp", "small"));
}
TEST(Utils, strmatch_mid2) {
ASSERT_TRUE(utils::strmatch("rigid/small/omp","omp"));
TEST(Utils, strmatch_mid2)
{
ASSERT_TRUE(utils::strmatch("rigid/small/omp", "omp"));
}
TEST(Utils, strmatch_end) {
ASSERT_TRUE(utils::strmatch("rigid/small/omp","/omp$"));
TEST(Utils, strmatch_end)
{
ASSERT_TRUE(utils::strmatch("rigid/small/omp", "/omp$"));
}
TEST(Utils, no_strmatch_beg) {
ASSERT_FALSE(utils::strmatch("rigid/small/omp","^small"));
TEST(Utils, no_strmatch_beg)
{
ASSERT_FALSE(utils::strmatch("rigid/small/omp", "^small"));
}
TEST(Utils, no_strmatch_mid) {
ASSERT_FALSE(utils::strmatch("rigid/small/omp","none"));
TEST(Utils, no_strmatch_mid)
{
ASSERT_FALSE(utils::strmatch("rigid/small/omp", "none"));
}
TEST(Utils, no_strmatch_end) {
ASSERT_FALSE(utils::strmatch("rigid/small/omp","/opt$"));
TEST(Utils, no_strmatch_end)
{
ASSERT_FALSE(utils::strmatch("rigid/small/omp", "/opt$"));
}
TEST(Utils, strmatch_whole_line) {
ASSERT_TRUE(utils::strmatch("ITEM: UNITS\n","^\\s*ITEM: UNITS\\s*$"));
TEST(Utils, strmatch_whole_line)
{
ASSERT_TRUE(utils::strmatch("ITEM: UNITS\n", "^\\s*ITEM: UNITS\\s*$"));
}
TEST(Utils, no_strmatch_whole_line) {
ASSERT_FALSE(utils::strmatch("ITEM: UNITS\n","^\\s*ITEM: UNIT\\s*$"));
TEST(Utils, no_strmatch_whole_line)
{
ASSERT_FALSE(utils::strmatch("ITEM: UNITS\n", "^\\s*ITEM: UNIT\\s*$"));
}
TEST(Utils, strmatch_integer_in_line) {
ASSERT_TRUE(utils::strmatch(" 5 angles\n","^\\s*\\d+\\s+angles\\s"));
TEST(Utils, strmatch_integer_in_line)
{
ASSERT_TRUE(utils::strmatch(" 5 angles\n", "^\\s*\\d+\\s+angles\\s"));
}
TEST(Utils, strmatch_float_in_line) {
ASSERT_TRUE(utils::strmatch(" 5.0 angles\n","^\\s*\\f+\\s+angles\\s"));
TEST(Utils, strmatch_float_in_line)
{
ASSERT_TRUE(utils::strmatch(" 5.0 angles\n", "^\\s*\\f+\\s+angles\\s"));
}
TEST(Utils, strmatch_int_as_float_in_line) {
ASSERT_TRUE(utils::strmatch(" 5 angles\n","^\\s*\\f+\\s+angles\\s"));
TEST(Utils, strmatch_int_as_float_in_line)
{
ASSERT_TRUE(utils::strmatch(" 5 angles\n", "^\\s*\\f+\\s+angles\\s"));
}
TEST(Utils, strmatch_char_range) {
ASSERT_TRUE(utils::strmatch("rigid","^[ip-s]+gid"));
TEST(Utils, strmatch_char_range)
{
ASSERT_TRUE(utils::strmatch("rigid", "^[ip-s]+gid"));
}
TEST(Utils, strmatch_opt_range) {
ASSERT_TRUE(utils::strmatch("rigid","^[0-9]*[p-s]igid"));
TEST(Utils, strmatch_opt_range)
{
ASSERT_TRUE(utils::strmatch("rigid", "^[0-9]*[p-s]igid"));
}
TEST(Utils, path_join) {
TEST(Utils, path_join)
{
#if defined(_WIN32)
ASSERT_THAT(utils::path_join("c:\\parent\\folder", "filename"), Eq("c:\\parent\\folder\\filename"));
ASSERT_THAT(utils::path_join("c:\\parent\\folder", "filename"),
Eq("c:\\parent\\folder\\filename"));
#else
ASSERT_THAT(utils::path_join("/parent/folder", "filename"), Eq("/parent/folder/filename"));
#endif
}
TEST(Utils, path_basename) {
TEST(Utils, path_basename)
{
#if defined(_WIN32)
ASSERT_THAT(utils::path_basename("c:\\parent\\folder\\filename"), Eq("filename"));
#else
@ -227,9 +277,10 @@ TEST(Utils, path_basename) {
#endif
}
TEST(Utils, getsyserror) {
TEST(Utils, getsyserror)
{
#if defined(__linux__)
errno = ENOENT;
errno = ENOENT;
std::string errmesg = utils::getsyserror();
ASSERT_THAT(errmesg, Eq("No such file or directory"));
#else
@ -237,35 +288,36 @@ TEST(Utils, getsyserror) {
#endif
}
TEST(Utils, potential_file) {
TEST(Utils, potential_file)
{
FILE *fp;
fp = fopen("ctest1.txt","w");
ASSERT_NE(fp,nullptr);
fputs("# DATE: 2020-02-20 CONTRIBUTOR: Nessuno UNITS: real\n",fp);
fp = fopen("ctest1.txt", "w");
ASSERT_NE(fp, nullptr);
fputs("# DATE: 2020-02-20 UNITS: real CONTRIBUTOR: Nessuno\n", fp);
fclose(fp);
fp = fopen("ctest2.txt","w");
ASSERT_NE(fp,nullptr);
fputs("# CONTRIBUTOR: Pippo\n",fp);
fp = fopen("ctest2.txt", "w");
ASSERT_NE(fp, nullptr);
fputs("# CONTRIBUTOR: Pippo\n", fp);
fclose(fp);
ASSERT_TRUE(utils::file_is_readable("ctest1.txt"));
ASSERT_TRUE(utils::file_is_readable("ctest2.txt"));
ASSERT_FALSE(utils::file_is_readable("no_such_file.txt"));
ASSERT_THAT(utils::get_potential_file_path("ctest1.txt"),Eq("ctest1.txt"));
ASSERT_THAT(utils::get_potential_file_path("no_such_file.txt"),Eq(""));
ASSERT_THAT(utils::get_potential_file_path("ctest1.txt"), Eq("ctest1.txt"));
ASSERT_THAT(utils::get_potential_file_path("no_such_file.txt"), Eq(""));
const char *folder = getenv("LAMMPS_POTENTIALS");
if (folder != nullptr) {
std::string path=utils::path_join(folder,"Cu_u3.eam");
EXPECT_THAT(utils::get_potential_file_path("Cu_u3.eam"),Eq(path));
EXPECT_THAT(utils::get_potential_units(path,"EAM"),Eq("metal"));
std::string path = utils::path_join(folder, "Cu_u3.eam");
EXPECT_THAT(utils::get_potential_file_path("Cu_u3.eam"), Eq(path));
EXPECT_THAT(utils::get_potential_units(path, "EAM"), Eq("metal"));
}
ASSERT_THAT(utils::get_potential_date("ctest1.txt","Test"),Eq("2020-02-20"));
ASSERT_THAT(utils::get_potential_units("ctest1.txt","Test"),Eq("real"));
ASSERT_THAT(utils::get_potential_date("ctest2.txt","Test"),Eq(""));
ASSERT_THAT(utils::get_potential_units("ctest2.txt","Test"),Eq(""));
ASSERT_THAT(utils::get_potential_date("ctest1.txt", "Test"), Eq("2020-02-20"));
ASSERT_THAT(utils::get_potential_units("ctest1.txt", "Test"), Eq("real"));
ASSERT_THAT(utils::get_potential_date("ctest2.txt", "Test"), Eq(""));
ASSERT_THAT(utils::get_potential_units("ctest2.txt", "Test"), Eq(""));
remove("ctest1.txt");
remove("ctest2.txt");