From 278d5c863519c5b1bd5ff144202b9c6af0281b18 Mon Sep 17 00:00:00 2001 From: Peter Doak Date: Thu, 2 Aug 2018 12:11:28 -0400 Subject: [PATCH 1/8] Application of proposed QMCPACK .clang-format --- .clang-format => src/.clang-format | 84 +- src/Drivers/Mover.hpp | 108 +- src/Drivers/check_determinant.cpp | 46 +- src/Drivers/check_spo.cpp | 138 +- src/Drivers/check_wfc.cpp | 133 +- src/Drivers/miniqmc.cpp | 183 +- src/Drivers/miniqmc_sync_move.cpp | 237 +- src/Input/graphite.hpp | 94 +- src/Input/nio.hpp | 104 +- src/Input/pseudo.hpp | 34 +- src/Numerics/Blasf.h | 2 + src/Numerics/Containers.h | 98 +- src/Numerics/DeterminantOperators.h | 71 +- src/Numerics/Einspline/bspline_base.h | 12 +- src/Numerics/Einspline/bspline_structs.h | 24 +- .../Einspline/multi_bspline_structs.h | 32 +- src/Numerics/OhmmsBlas.h | 478 +- src/Numerics/OhmmsPETE/OhmmsArray.h | 84 +- src/Numerics/OhmmsPETE/OhmmsMatrix.h | 145 +- src/Numerics/OhmmsPETE/OhmmsMatrixOperators.h | 32 +- src/Numerics/OhmmsPETE/OhmmsVector.h | 91 +- src/Numerics/OhmmsPETE/OhmmsVectorOperators.h | 39 +- src/Numerics/OhmmsPETE/Tensor.h | 191 +- src/Numerics/OhmmsPETE/TensorOps.h | 120 +- src/Numerics/OhmmsPETE/TinyVector.h | 182 +- src/Numerics/OhmmsPETE/TinyVectorOps.h | 137 +- src/Numerics/OhmmsPETE/TinyVectorTensorOps.h | 186 +- src/Numerics/PETE/Combiners.h | 89 +- src/Numerics/PETE/CreateLeaf.h | 30 +- src/Numerics/PETE/ForEach.h | 69 +- src/Numerics/PETE/Functors.h | 148 +- src/Numerics/PETE/OperatorTags.h | 107 +- src/Numerics/PETE/PETE.h | 8 +- src/Numerics/PETE/Scalar.h | 32 +- src/Numerics/PETE/TreeNodes.h | 178 +- src/Numerics/PETE/TypeComputations.h | 161 +- src/Numerics/PosTransformer.h | 25 +- src/Numerics/Spline2/MultiBspline.hpp | 194 +- src/Numerics/Spline2/MultiBsplineData.cpp | 75 +- src/Numerics/Spline2/MultiBsplineData.hpp | 10 +- src/Numerics/Spline2/MultiBsplineRef.hpp | 190 +- src/Numerics/Spline2/bspline_allocator.cpp | 96 +- src/Numerics/Spline2/bspline_allocator.hpp | 112 +- src/Numerics/Spline2/bspline_traits.hpp | 32 +- src/Numerics/Spline2/einspline_allocator.cpp | 130 +- src/Numerics/Spline2/einspline_allocator.h | 4 +- src/Particle/DistanceTable.h | 8 +- src/Particle/DistanceTableAA.cpp | 11 +- src/Particle/DistanceTableAA.h | 44 +- src/Particle/DistanceTableAB.cpp | 14 +- src/Particle/DistanceTableBA.h | 47 +- src/Particle/DistanceTableData.h | 20 +- src/Particle/FastParticleOperators.h | 41 +- src/Particle/Lattice/CrystalLattice.cpp | 45 +- src/Particle/Lattice/CrystalLattice.h | 58 +- src/Particle/Lattice/LatticeAnalyzer.h | 78 +- src/Particle/Lattice/LatticeOperations.h | 30 +- src/Particle/Lattice/ParticleBConds.h | 69 +- src/Particle/ParticleAttrib.h | 16 +- src/Particle/ParticleIOUtility.h | 50 +- src/Particle/ParticleSet.BC.cpp | 19 +- src/Particle/ParticleSet.cpp | 108 +- src/Particle/ParticleSet.h | 58 +- src/Particle/ParticleSet_builder.cpp | 61 +- src/Particle/ParticleSet_builder.hpp | 14 +- src/Particle/Walker.h | 44 +- src/QMCWaveFunctions/Determinant.h | 104 +- src/QMCWaveFunctions/DeterminantRef.h | 106 +- src/QMCWaveFunctions/Jastrow/BsplineFunctor.h | 69 +- src/QMCWaveFunctions/Jastrow/OneBodyJastrow.h | 88 +- .../Jastrow/OneBodyJastrowRef.h | 88 +- .../Jastrow/PolynomialFunctor3D.h | 82 +- .../Jastrow/ThreeBodyJastrow.h | 288 +- .../Jastrow/ThreeBodyJastrowRef.h | 290 +- src/QMCWaveFunctions/Jastrow/TwoBodyJastrow.h | 171 +- .../Jastrow/TwoBodyJastrowRef.h | 172 +- src/QMCWaveFunctions/SPOSet.h | 43 +- src/QMCWaveFunctions/SPOSet_builder.cpp | 31 +- src/QMCWaveFunctions/SPOSet_builder.h | 17 +- src/QMCWaveFunctions/WaveFunction.cpp | 234 +- src/QMCWaveFunctions/WaveFunction.h | 104 +- src/QMCWaveFunctions/WaveFunctionComponent.h | 111 +- src/QMCWaveFunctions/einspline_spo.hpp | 94 +- src/QMCWaveFunctions/einspline_spo_ref.hpp | 95 +- src/Utilities/Clock.h | 2 +- src/Utilities/Communicate.cpp | 5 +- src/Utilities/Communicate.h | 5 +- src/Utilities/Configuration.h | 3 +- src/Utilities/InfoStream.cpp | 32 +- src/Utilities/InfoStream.h | 36 +- src/Utilities/NewTimer.cpp | 111 +- src/Utilities/NewTimer.h | 133 +- src/Utilities/OutputManager.cpp | 21 +- src/Utilities/OutputManager.h | 57 +- src/Utilities/PooledData.h | 101 +- src/Utilities/PrimeNumberSet.h | 26 +- src/Utilities/RandomGenerator.h | 11 +- src/Utilities/SIMD/Mallocator.hpp | 57 +- src/Utilities/SIMD/algorithm.hpp | 62 +- src/Utilities/SIMD/allocator.hpp | 24 +- src/Utilities/SpeciesSet.cpp | 19 +- src/Utilities/SpeciesSet.h | 36 +- src/Utilities/StdRandom.h | 53 +- src/Utilities/XMLWriter.cpp | 8 +- src/Utilities/XMLWriter.h | 5 +- src/Utilities/qmcpack_version.cpp | 3 +- src/Utilities/tinyxml/tinyxml2.cpp | 4154 +++++++++-------- src/Utilities/tinyxml/tinyxml2.h | 2698 ++++++----- src/config.h.cmake.in | 125 +- 109 files changed, 8104 insertions(+), 7480 deletions(-) rename .clang-format => src/.clang-format (53%) mode change 100755 => 100644 src/Utilities/tinyxml/tinyxml2.cpp mode change 100755 => 100644 src/Utilities/tinyxml/tinyxml2.h diff --git a/.clang-format b/src/.clang-format similarity index 53% rename from .clang-format rename to src/.clang-format index 648283c37..2be4f5f7f 100644 --- a/.clang-format +++ b/src/.clang-format @@ -1,91 +1,109 @@ --- Language: Cpp -BasedOnStyle: LLVM AccessModifierOffset: -2 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: true AlignConsecutiveDeclarations: false -AlignEscapedNewlinesLeft: true -AlignOperands: true +AlignEscapedNewlines: Left +AlignOperands: false AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: true +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: true +AllowShortIfStatementsOnASingleLine: false AllowShortLoopsOnASingleLine: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false -AlwaysBreakTemplateDeclarations: false -BinPackArguments: true -BinPackParameters: true +AlwaysBreakTemplateDeclarations: true +BinPackArguments: false +BinPackParameters: false +BreakBeforeBraces: Custom BraceWrapping: - AfterClass: false - AfterControlStatement: false - AfterEnum: false - AfterFunction: false - AfterNamespace: false + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: true AfterObjCDeclaration: true - AfterStruct: false - AfterUnion: false + AfterStruct: true + AfterUnion: true + AfterExternBlock: true BeforeCatch: true BeforeElse: true IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false BreakBeforeBinaryOperators: None -BreakBeforeBraces: Allman +BreakBeforeInheritanceComma: false BreakBeforeTernaryOperators: true BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon BreakAfterJavaFieldAnnotations: false BreakStringLiterals: true -ColumnLimit: 80 +ColumnLimit: 100 CommentPragmas: '^ IWYU pragma:' -ConstructorInitializerAllOnOneLineOrOnePerLine: false +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true DerivePointerAlignment: false DisableFormat: false ExperimentalAutoDetectBinPacking: false -ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve IncludeCategories: - Regex: '^"(llvm|llvm-c|clang|clang-c)/' Priority: 2 - - Regex: '^(<|"(gtest|isl|json)/)' + - Regex: '^(<|"(gtest|gmock|isl|json)/)' Priority: 3 - Regex: '.*' Priority: 1 -IncludeIsMainRegex: '$' +IncludeIsMainRegex: '(Test)?$' IndentCaseLabels: false +# @future IndentPPDirectives: BeforeHash IndentWidth: 2 -IndentWrappedFunctionNames: false +IndentWrappedFunctionNames: true JavaScriptQuotes: Leave JavaScriptWrapImports: true -KeepEmptyLinesAtTheStartOfBlocks: true +KeepEmptyLinesAtTheStartOfBlocks: false MacroBlockBegin: '' MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 +MaxEmptyLinesToKeep: 2 NamespaceIndentation: None ObjCBlockIndentWidth: 2 ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true -PenaltyBreakBeforeFirstCallParameter: 19 -PenaltyBreakComment: 300 +PenaltyBreakAssignment: 10 +PenaltyBreakBeforeFirstCallParameter: 100000 +PenaltyBreakComment: 20 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 60 -PointerAlignment: Right -ReflowComments: true +PenaltyExcessCharacter: 9 +PenaltyReturnTypeOnItsOwnLine: 8 +PointerAlignment: Left +ReflowComments: false SortIncludes: false +SortUsingDeclarations: false SpaceAfterCStyleCast: false -SpaceAfterTemplateKeyword: true +SpaceAfterTemplateKeyword: false SpaceBeforeAssignmentOperators: true SpaceBeforeParens: ControlStatements SpaceInEmptyParentheses: false SpacesBeforeTrailingComments: 1 SpacesInAngles: false SpacesInContainerLiterals: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false SpacesInCStyleCastParentheses: false SpacesInParentheses: false SpacesInSquareBrackets: false diff --git a/src/Drivers/Mover.hpp b/src/Drivers/Mover.hpp index 3013b858d..3356ab5c4 100644 --- a/src/Drivers/Mover.hpp +++ b/src/Drivers/Mover.hpp @@ -33,8 +33,7 @@ namespace qmcplusplus { - - /** +/** * @brief Container class includes all the classes required to operate walker moves * * Movers are distinct from walkers. Walkers are lightweight in memory, while @@ -44,67 +43,70 @@ namespace qmcplusplus * * This class is used only by QMC drivers. */ - struct Mover - { - using RealType = QMCTraits::RealType; - - /// random number generator - RandomGenerator rng; - /// electrons - ParticleSet els; - /// single particle orbitals - SPOSet *spo; - /// wavefunction container - WaveFunction wavefunction; - /// non-local pseudo-potentials - NonLocalPP nlpp; - - /// constructor - Mover(const uint32_t myPrime, - const ParticleSet &ions) - : spo(nullptr), rng(myPrime), nlpp(rng) - { - build_els(els, ions, rng); - } - - /// destructor - ~Mover() { if (spo!=nullptr) delete spo; } +struct Mover +{ + using RealType = QMCTraits::RealType; - }; + /// random number generator + RandomGenerator rng; + /// electrons + ParticleSet els; + /// single particle orbitals + SPOSet* spo; + /// wavefunction container + WaveFunction wavefunction; + /// non-local pseudo-potentials + NonLocalPP nlpp; - template - const std::vector filtered_list(const std::vector &input_list, const std::vector &chosen) + /// constructor + Mover(const uint32_t myPrime, const ParticleSet& ions) : spo(nullptr), rng(myPrime), nlpp(rng) { - std::vector final_list; - for(int iw=0; iw extract_els_list(const std::vector &mover_list) + /// destructor + ~Mover() { - std::vector els_list; - for(auto it=mover_list.begin(); it!=mover_list.end(); it++) - els_list.push_back(&(*it)->els); - return els_list; + if (spo != nullptr) + delete spo; } +}; - const std::vector extract_spo_list(const std::vector &mover_list) - { - std::vector spo_list; - for(auto it=mover_list.begin(); it!=mover_list.end(); it++) - spo_list.push_back((*it)->spo); - return spo_list; - } +template +const std::vector + filtered_list(const std::vector& input_list, const std::vector& chosen) +{ + std::vector final_list; + for (int iw = 0; iw < input_list.size(); iw++) + if (chosen[iw]) + final_list.push_back(input_list[iw]); + return final_list; +} - const std::vector extract_wf_list(const std::vector &mover_list) - { - std::vector wf_list; - for(auto it=mover_list.begin(); it!=mover_list.end(); it++) - wf_list.push_back(&(*it)->wavefunction); - return wf_list; - } +const std::vector extract_els_list(const std::vector& mover_list) +{ + std::vector els_list; + for (auto it = mover_list.begin(); it != mover_list.end(); it++) + els_list.push_back(&(*it)->els); + return els_list; +} +const std::vector extract_spo_list(const std::vector& mover_list) +{ + std::vector spo_list; + for (auto it = mover_list.begin(); it != mover_list.end(); it++) + spo_list.push_back((*it)->spo); + return spo_list; } +const std::vector extract_wf_list(const std::vector& mover_list) +{ + std::vector wf_list; + for (auto it = mover_list.begin(); it != mover_list.end(); it++) + wf_list.push_back(&(*it)->wavefunction); + return wf_list; +} + +} // namespace qmcplusplus + #endif diff --git a/src/Drivers/check_determinant.cpp b/src/Drivers/check_determinant.cpp index 1af1e76fd..e7236a49e 100644 --- a/src/Drivers/check_determinant.cpp +++ b/src/Drivers/check_determinant.cpp @@ -38,24 +38,22 @@ void print_help() { //clang-format off cout << "usage:" << '\n'; - cout << " check_determinant [-hvV] [-g \"n0 n1 n2\"] [-n steps]" << '\n'; - cout << " [-N substeps] [-s seed]" << '\n'; - cout << "options:" << '\n'; - cout << " -g set the 3D tiling. default: 1 1 1" << '\n'; - cout << " -h print help and exit" << '\n'; - cout << " -n number of MC steps default: 5" << '\n'; - cout << " -N number of MC substeps default: 1" << '\n'; - cout << " -s set the random seed. default: 11" << '\n'; - cout << " -v verbose output" << '\n'; - cout << " -V print version information and exit" << '\n'; + cout << " check_determinant [-hvV] [-g \"n0 n1 n2\"] [-n steps]" << '\n'; + cout << " [-N substeps] [-s seed]" << '\n'; + cout << "options:" << '\n'; + cout << " -g set the 3D tiling. default: 1 1 1" << '\n'; + cout << " -h print help and exit" << '\n'; + cout << " -n number of MC steps default: 5" << '\n'; + cout << " -N number of MC substeps default: 1" << '\n'; + cout << " -s set the random seed. default: 11" << '\n'; + cout << " -v verbose output" << '\n'; + cout << " -V print version information and exit" << '\n'; //clang-format on exit(1); // print help and exit } -int main(int argc, char **argv) +int main(int argc, char** argv) { - - // clang-format off typedef QMCTraits::RealType RealType; typedef ParticleSet::ParticlePos_t ParticlePos_t; @@ -75,7 +73,7 @@ int main(int argc, char **argv) bool verbose = false; int opt; - while(optind < argc) + while (optind < argc) { if ((opt = getopt(argc, argv, "hvVg:n:N:r:s:")) != -1) { @@ -84,7 +82,9 @@ int main(int argc, char **argv) case 'g': // tiling1 tiling2 tiling3 sscanf(optarg, "%d %d %d", &na, &nb, &nc); break; - case 'h': print_help(); break; + case 'h': + print_help(); + break; case 'n': nsteps = atoi(optarg); break; @@ -94,7 +94,9 @@ int main(int argc, char **argv) case 's': iseed = atoi(optarg); break; - case 'v': verbose = true; break; + case 'v': + verbose = true; + break; case 'V': print_version(true); return 1; @@ -126,7 +128,7 @@ int main(int argc, char **argv) double accumulated_error = 0.0; -#pragma omp parallel reduction(+:accumulated_error) +#pragma omp parallel reduction(+ : accumulated_error) { int ip = omp_get_thread_num(); @@ -178,7 +180,8 @@ int main(int argc, char **argv) PosType dr = sqrttau * delta[iel]; bool isValid = els.makeMoveAndCheck(iel, dr); - if (!isValid) continue; + if (!isValid) + continue; // Compute gradient at the trial position @@ -213,13 +216,12 @@ int main(int argc, char **argv) constexpr double small_err = std::numeric_limits::epsilon() * 6e8; - cout << "total accumulated error of " << accumulated_error << " for " << np - << " procs" << '\n'; + cout << "total accumulated error of " << accumulated_error << " for " << np << " procs" << '\n'; if (accumulated_error / np > small_err) { - cout << "Checking failed with accumulated error: " << accumulated_error / np - << " > " << small_err << '\n'; + cout << "Checking failed with accumulated error: " << accumulated_error / np << " > " + << small_err << '\n'; return 1; } else diff --git a/src/Drivers/check_spo.cpp b/src/Drivers/check_spo.cpp index 648437b79..c408e361f 100644 --- a/src/Drivers/check_spo.cpp +++ b/src/Drivers/check_spo.cpp @@ -36,26 +36,24 @@ void print_help() { //clang-format off app_summary() << "usage:" << '\n'; - app_summary() << " check_spo [-hvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; - app_summary() << " [-n steps] [-r rmax] [-s seed]" << '\n'; - app_summary() << "options:" << '\n'; - app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; - app_summary() << " -h print help and exit" << '\n'; - app_summary() << " -m meshfactor default: 1.0" << '\n'; - app_summary() << " -n number of MC steps default: 5" << '\n'; - app_summary() << " -r set the Rmax. default: 1.7" << '\n'; - app_summary() << " -s set the random seed. default: 11" << '\n'; - app_summary() << " -v verbose output" << '\n'; - app_summary() << " -V print version information and exit" << '\n'; + app_summary() << " check_spo [-hvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; + app_summary() << " [-n steps] [-r rmax] [-s seed]" << '\n'; + app_summary() << "options:" << '\n'; + app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; + app_summary() << " -h print help and exit" << '\n'; + app_summary() << " -m meshfactor default: 1.0" << '\n'; + app_summary() << " -n number of MC steps default: 5" << '\n'; + app_summary() << " -r set the Rmax. default: 1.7" << '\n'; + app_summary() << " -s set the random seed. default: 11" << '\n'; + app_summary() << " -v verbose output" << '\n'; + app_summary() << " -V print version information and exit" << '\n'; //clang-format on exit(1); // print help and exit } -int main(int argc, char **argv) +int main(int argc, char** argv) { - - // clang-format off typedef QMCTraits::RealType RealType; typedef ParticleSet::ParticlePos_t ParticlePos_t; @@ -66,17 +64,17 @@ int main(int argc, char **argv) // use the global generator - int na = 1; - int nb = 1; - int nc = 1; - int nsteps = 5; - int iseed = 11; + int na = 1; + int nb = 1; + int nc = 1; + int nsteps = 5; + int iseed = 11; RealType Rmax(1.7); int nx = 37, ny = 37, nz = 37; // thread blocking // int team_size=1; //default is 1 - int tileSize = -1; - int team_size = 1; + int tileSize = -1; + int team_size = 1; bool verbose = false; @@ -86,26 +84,32 @@ int main(int argc, char **argv) } int opt; - while(optind < argc) + while (optind < argc) { if ((opt = getopt(argc, argv, "hvVa:c:f:g:m:n:r:s:")) != -1) { switch (opt) { - case 'a': tileSize = atoi(optarg); break; + case 'a': + tileSize = atoi(optarg); + break; case 'c': // number of members per team team_size = atoi(optarg); break; case 'g': // tiling1 tiling2 tiling3 sscanf(optarg, "%d %d %d", &na, &nb, &nc); break; - case 'h': print_help(); break; - case 'm': - { - const RealType meshfactor = atof(optarg); - nx *= meshfactor; ny *= meshfactor; nz *= meshfactor; - } + case 'h': + print_help(); break; + case 'm': + { + const RealType meshfactor = atof(optarg); + nx *= meshfactor; + ny *= meshfactor; + nz *= meshfactor; + } + break; case 'n': nsteps = atoi(optarg); break; @@ -115,7 +119,9 @@ int main(int argc, char **argv) case 's': iseed = atoi(optarg); break; - case 'v': verbose = true; break; + case 'v': + verbose = true; + break; case 'V': print_version(true); return 1; @@ -156,12 +162,12 @@ int main(int argc, char **argv) { Tensor lattice_b; build_ions(ions, tmat, lattice_b); - const int norb = count_electrons(ions, 1) / 2; - tileSize = (tileSize > 0) ? tileSize : norb; - nTiles = norb / tileSize; + const int norb = count_electrons(ions, 1) / 2; + tileSize = (tileSize > 0) ? tileSize : norb; + nTiles = norb / tileSize; - const size_t SPO_coeff_size = static_cast(norb) - * (nx + 3) * (ny + 3) * (nz + 3) * sizeof(RealType); + const size_t SPO_coeff_size = + static_cast(norb) * (nx + 3) * (ny + 3) * (nz + 3) * sizeof(RealType); const double SPO_coeff_size_MB = SPO_coeff_size * 1.0 / 1024 / 1024; app_summary() << "Number of orbitals/splines = " << norb << endl @@ -174,8 +180,8 @@ int main(int argc, char **argv) app_summary() << "MPI processes = " << comm.size() << endl; #endif - app_summary() << "\nSPO coefficients size = " << SPO_coeff_size - << " bytes (" << SPO_coeff_size_MB << " MB)" << endl; + app_summary() << "\nSPO coefficients size = " << SPO_coeff_size << " bytes (" + << SPO_coeff_size_MB << " MB)" << endl; spo_main.set(nx, ny, nz, norb, nTiles); spo_main.Lattice.set(lattice_b); @@ -191,14 +197,14 @@ int main(int argc, char **argv) double evalVGH_g_err = 0.0; double evalVGH_h_err = 0.0; -// clang-format off + // clang-format off #pragma omp parallel reduction(+:ratio,nspheremoves,dNumVGHCalls) \ reduction(+:evalV_v_err,evalVGH_v_err,evalVGH_g_err,evalVGH_h_err) // clang-format on { - const int np = omp_get_num_threads(); - const int ip = omp_get_thread_num(); - const int team_id = ip / team_size; + const int np = omp_get_num_threads(); + const int ip = omp_get_thread_num(); + const int team_id = ip / team_size; const int member_id = ip % team_size; // create generator within the thread @@ -232,8 +238,7 @@ int main(int argc, char **argv) vector ur(nels); random_th.generate_uniform(ur.data(), nels); - const double zval = - 1.0 * static_cast(nels) / static_cast(nions); + const double zval = 1.0 * static_cast(nels) / static_cast(nions); int my_accepted = 0, my_vals = 0; @@ -253,28 +258,18 @@ int main(int argc, char **argv) for (int n = 0; n < spo.nSplinesPerBlock; n++) { // value - evalVGH_v_err += - std::fabs(spo.psi[ib][n] - spo_ref.psi[ib][n]); + evalVGH_v_err += std::fabs(spo.psi[ib][n] - spo_ref.psi[ib][n]); // grad - evalVGH_g_err += std::fabs(spo.grad[ib].data(0)[n] - - spo_ref.grad[ib].data(0)[n]); - evalVGH_g_err += std::fabs(spo.grad[ib].data(1)[n] - - spo_ref.grad[ib].data(1)[n]); - evalVGH_g_err += std::fabs(spo.grad[ib].data(2)[n] - - spo_ref.grad[ib].data(2)[n]); + evalVGH_g_err += std::fabs(spo.grad[ib].data(0)[n] - spo_ref.grad[ib].data(0)[n]); + evalVGH_g_err += std::fabs(spo.grad[ib].data(1)[n] - spo_ref.grad[ib].data(1)[n]); + evalVGH_g_err += std::fabs(spo.grad[ib].data(2)[n] - spo_ref.grad[ib].data(2)[n]); // hess - evalVGH_h_err += std::fabs(spo.hess[ib].data(0)[n] - - spo_ref.hess[ib].data(0)[n]); - evalVGH_h_err += std::fabs(spo.hess[ib].data(1)[n] - - spo_ref.hess[ib].data(1)[n]); - evalVGH_h_err += std::fabs(spo.hess[ib].data(2)[n] - - spo_ref.hess[ib].data(2)[n]); - evalVGH_h_err += std::fabs(spo.hess[ib].data(3)[n] - - spo_ref.hess[ib].data(3)[n]); - evalVGH_h_err += std::fabs(spo.hess[ib].data(4)[n] - - spo_ref.hess[ib].data(4)[n]); - evalVGH_h_err += std::fabs(spo.hess[ib].data(5)[n] - - spo_ref.hess[ib].data(5)[n]); + evalVGH_h_err += std::fabs(spo.hess[ib].data(0)[n] - spo_ref.hess[ib].data(0)[n]); + evalVGH_h_err += std::fabs(spo.hess[ib].data(1)[n] - spo_ref.hess[ib].data(1)[n]); + evalVGH_h_err += std::fabs(spo.hess[ib].data(2)[n] - spo_ref.hess[ib].data(2)[n]); + evalVGH_h_err += std::fabs(spo.hess[ib].data(3)[n] - spo_ref.hess[ib].data(3)[n]); + evalVGH_h_err += std::fabs(spo.hess[ib].data(4)[n] - spo_ref.hess[ib].data(4)[n]); + evalVGH_h_err += std::fabs(spo.hess[ib].data(5)[n] - spo_ref.hess[ib].data(5)[n]); } if (ur[iel] > accept) { @@ -302,8 +297,7 @@ int main(int argc, char **argv) // accumulate error for (int ib = 0; ib < spo.nBlocks; ib++) for (int n = 0; n < spo.nSplinesPerBlock; n++) - evalV_v_err += - std::fabs(spo.psi[ib][n] - spo_ref.psi[ib][n]); + evalV_v_err += std::fabs(spo.psi[ib][n] - spo_ref.psi[ib][n]); } } // els } // ions @@ -318,7 +312,7 @@ int main(int argc, char **argv) outputManager.resume(); - evalV_v_err /= nspheremoves; + evalV_v_err /= nspheremoves; evalVGH_v_err /= dNumVGHCalls; evalVGH_g_err /= dNumVGHCalls; evalVGH_h_err /= dNumVGHCalls; @@ -336,25 +330,23 @@ int main(int argc, char **argv) } if (evalVGH_v_err / np > small_v) { - app_log() << "Fail in evaluate_vgh, V error =" << evalVGH_v_err / np - << std::endl; + app_log() << "Fail in evaluate_vgh, V error =" << evalVGH_v_err / np << std::endl; nfail += 1; } if (evalVGH_g_err / np > small_g) { - app_log() << "Fail in evaluate_vgh, G error =" << evalVGH_g_err / np - << std::endl; + app_log() << "Fail in evaluate_vgh, G error =" << evalVGH_g_err / np << std::endl; nfail += 1; } if (evalVGH_h_err / np > small_h) { - app_log() << "Fail in evaluate_vgh, H error =" << evalVGH_h_err / np - << std::endl; + app_log() << "Fail in evaluate_vgh, H error =" << evalVGH_h_err / np << std::endl; nfail += 1; } comm.reduce(nfail); - if (nfail == 0) app_log() << "All checks passed for spo" << std::endl; + if (nfail == 0) + app_log() << "All checks passed for spo" << std::endl; return 0; } diff --git a/src/Drivers/check_wfc.cpp b/src/Drivers/check_wfc.cpp index cce3b037d..bb1aa5e90 100644 --- a/src/Drivers/check_wfc.cpp +++ b/src/Drivers/check_wfc.cpp @@ -46,26 +46,24 @@ void print_help() { //clang-format off cout << "usage:" << '\n'; - cout << " check_wfc [-hvV] [-f wfc_component] [-g \"n0 n1 n2\"]" << '\n'; - cout << " [-r rmax] [-s seed]" << '\n'; - cout << "options:" << '\n'; - cout << " -f specify wavefunction component to check" << '\n'; - cout << " one of: J1, J2, J3. default: J2" << '\n'; - cout << " -g set the 3D tiling. default: 1 1 1" << '\n'; - cout << " -h print help and exit" << '\n'; - cout << " -r set the Rmax. default: 1.7" << '\n'; - cout << " -s set the random seed. default: 11" << '\n'; - cout << " -v verbose output" << '\n'; - cout << " -V print version information and exit" << '\n'; + cout << " check_wfc [-hvV] [-f wfc_component] [-g \"n0 n1 n2\"]" << '\n'; + cout << " [-r rmax] [-s seed]" << '\n'; + cout << "options:" << '\n'; + cout << " -f specify wavefunction component to check" << '\n'; + cout << " one of: J1, J2, J3. default: J2" << '\n'; + cout << " -g set the 3D tiling. default: 1 1 1" << '\n'; + cout << " -h print help and exit" << '\n'; + cout << " -r set the Rmax. default: 1.7" << '\n'; + cout << " -s set the random seed. default: 11" << '\n'; + cout << " -v verbose output" << '\n'; + cout << " -V print version information and exit" << '\n'; //clang-format on exit(1); // print help and exit } -int main(int argc, char **argv) +int main(int argc, char** argv) { - - // clang-format off typedef QMCTraits::RealType RealType; typedef ParticleSet::ParticlePos_t ParticlePos_t; @@ -74,17 +72,17 @@ int main(int argc, char **argv) // use the global generator - int na = 1; - int nb = 1; - int nc = 1; - int iseed = 11; + int na = 1; + int nb = 1; + int nc = 1; + int iseed = 11; RealType Rmax(1.7); string wfc_name("J2"); bool verbose = false; int opt; - while(optind < argc) + while (optind < argc) { if ((opt = getopt(argc, argv, "hvVf:g:r:s:")) != -1) { @@ -96,14 +94,18 @@ int main(int argc, char **argv) case 'g': // tiling1 tiling2 tiling3 sscanf(optarg, "%d %d %d", &na, &nb, &nc); break; - case 'h': print_help(); break; + case 'h': + print_help(); + break; case 'r': // rmax Rmax = atof(optarg); break; case 's': iseed = atoi(optarg); break; - case 'v': verbose = true; break; + case 'v': + verbose = true; + break; case 'V': print_version(true); return 1; @@ -126,8 +128,7 @@ int main(int argc, char **argv) else outputManager.setVerbosity(Verbosity::LOW); - if (wfc_name != "J1" && wfc_name != "J2" && wfc_name != "J3" && - wfc_name != "JeeI") + if (wfc_name != "J1" && wfc_name != "J2" && wfc_name != "J3" && wfc_name != "JeeI") { cerr << "Uknown wave funciton component: " << wfc_name << endl << endl; print_help(); @@ -153,7 +154,7 @@ int main(int argc, char **argv) PrimeNumberSet myPrimes; - // clang-format off +// clang-format off #pragma omp parallel reduction(+:evaluateLog_v_err,evaluateLog_g_err,evaluateLog_l_err,evalGrad_g_err) \ reduction(+:ratioGrad_r_err,ratioGrad_g_err,evaluateGL_g_err,evaluateGL_l_err,ratio_err) // clang-format on @@ -190,42 +191,37 @@ int main(int argc, char **argv) WaveFunctionComponentPtr wfc_ref = nullptr; if (wfc_name == "J2") { - TwoBodyJastrow> *J = - new TwoBodyJastrow>(els); + TwoBodyJastrow>* J = new TwoBodyJastrow>(els); buildJ2(*J, els.Lattice.WignerSeitzRadius); wfc = dynamic_cast(J); cout << "Built J2" << endl; - miniqmcreference::TwoBodyJastrowRef> *J_ref = - new miniqmcreference::TwoBodyJastrowRef>( - els_ref); + miniqmcreference::TwoBodyJastrowRef>* J_ref = + new miniqmcreference::TwoBodyJastrowRef>(els_ref); buildJ2(*J_ref, els.Lattice.WignerSeitzRadius); wfc_ref = dynamic_cast(J_ref); cout << "Built J2_ref" << endl; } else if (wfc_name == "J1") { - OneBodyJastrow> *J = + OneBodyJastrow>* J = new OneBodyJastrow>(ions, els); buildJ1(*J, els.Lattice.WignerSeitzRadius); wfc = dynamic_cast(J); cout << "Built J1" << endl; - miniqmcreference::OneBodyJastrowRef> *J_ref = - new miniqmcreference::OneBodyJastrowRef>( - ions, els_ref); + miniqmcreference::OneBodyJastrowRef>* J_ref = + new miniqmcreference::OneBodyJastrowRef>(ions, els_ref); buildJ1(*J_ref, els.Lattice.WignerSeitzRadius); wfc_ref = dynamic_cast(J_ref); cout << "Built J1_ref" << endl; } else if (wfc_name == "JeeI" || wfc_name == "J3") { - ThreeBodyJastrow *J = - new ThreeBodyJastrow(ions, els); + ThreeBodyJastrow* J = new ThreeBodyJastrow(ions, els); buildJeeI(*J, els.Lattice.WignerSeitzRadius); wfc = dynamic_cast(J); cout << "Built JeeI" << endl; - miniqmcreference::ThreeBodyJastrowRef *J_ref = - new miniqmcreference::ThreeBodyJastrowRef( - ions, els_ref); + miniqmcreference::ThreeBodyJastrowRef* J_ref = + new miniqmcreference::ThreeBodyJastrowRef(ions, els_ref); buildJeeI(*J_ref, els.Lattice.WignerSeitzRadius); wfc_ref = dynamic_cast(J_ref); cout << "Built JeeI_ref" << endl; @@ -246,15 +242,12 @@ int main(int argc, char **argv) els_ref.L = czero; wfc_ref->evaluateLog(els_ref, els_ref.G, els_ref.L); - cout << "Check values " << wfc->LogValue << " " << els.G[12] << " " - << els.L[12] << endl; - cout << "Check values ref " << wfc_ref->LogValue << " " << els_ref.G[12] - << " " << els_ref.L[12] << endl + cout << "Check values " << wfc->LogValue << " " << els.G[12] << " " << els.L[12] << endl; + cout << "Check values ref " << wfc_ref->LogValue << " " << els_ref.G[12] << " " + << els_ref.L[12] << endl << endl; - cout << "evaluateLog::V Error = " - << (wfc->LogValue - wfc_ref->LogValue) / nels << endl; - evaluateLog_v_err += - std::fabs((wfc->LogValue - wfc_ref->LogValue) / nels); + cout << "evaluateLog::V Error = " << (wfc->LogValue - wfc_ref->LogValue) / nels << endl; + evaluateLog_v_err += std::fabs((wfc->LogValue - wfc_ref->LogValue) / nels); { double g_err = 0.0; for (int iel = 0; iel < nels; ++iel) @@ -292,11 +285,12 @@ int main(int argc, char **argv) PosType grad_ref = wfc_ref->evalGrad(els_ref, iel) - grad_soa; g_eval += sqrt(dot(grad_ref, grad_ref)); - PosType dr = sqrttau * delta[iel]; + PosType dr = sqrttau * delta[iel]; els.makeMoveAndCheck(iel, dr); bool good_ref = els_ref.makeMoveAndCheck(iel, dr); - if (!good_ref) continue; + if (!good_ref) + continue; grad_soa = 0; RealType r_soa = wfc->ratioGrad(els, iel, grad_soa); @@ -369,7 +363,7 @@ int main(int argc, char **argv) int nsphere = 0; for (int jel = 0; jel < els_ref.getTotalNum(); ++jel) { - const auto &dist = els_ref.DistTables[ei_TableID]->Distances[jel]; + const auto& dist = els_ref.DistTables[ei_TableID]->Distances[jel]; for (int iat = 0; iat < nions; ++iat) if (dist[iat] < Rmax) { @@ -388,8 +382,8 @@ int main(int argc, char **argv) } } } - cout << "ratio with SphereMove Error = " << r_ratio / nsphere - << " # of moves =" << nsphere << endl; + cout << "ratio with SphereMove Error = " << r_ratio / nsphere << " # of moves =" << nsphere + << endl; ratio_err += std::fabs(r_ratio / (nels * nknots)); } } // end of omp parallel @@ -400,59 +394,58 @@ int main(int argc, char **argv) cout << std::endl; if (evaluateLog_v_err / np > small) { - cout << "Fail in evaluateLog, V error =" << evaluateLog_v_err / np - << " for " << wfc_name << std::endl; + cout << "Fail in evaluateLog, V error =" << evaluateLog_v_err / np << " for " << wfc_name + << std::endl; fail = true; } if (evaluateLog_g_err / np > small) { - cout << "Fail in evaluateLog, G error =" << evaluateLog_g_err / np - << " for " << wfc_name << std::endl; + cout << "Fail in evaluateLog, G error =" << evaluateLog_g_err / np << " for " << wfc_name + << std::endl; fail = true; } if (evaluateLog_l_err / np > small) { - cout << "Fail in evaluateLog, L error =" << evaluateLog_l_err / np - << " for " << wfc_name << std::endl; + cout << "Fail in evaluateLog, L error =" << evaluateLog_l_err / np << " for " << wfc_name + << std::endl; fail = true; } if (evalGrad_g_err / np > small) { - cout << "Fail in evalGrad, G error =" << evalGrad_g_err / np << " for " - << wfc_name << std::endl; + cout << "Fail in evalGrad, G error =" << evalGrad_g_err / np << " for " << wfc_name << std::endl; fail = true; } if (ratioGrad_r_err / np > small) { - cout << "Fail in ratioGrad, ratio error =" << ratioGrad_r_err / np - << " for " << wfc_name << std::endl; + cout << "Fail in ratioGrad, ratio error =" << ratioGrad_r_err / np << " for " << wfc_name + << std::endl; fail = true; } if (ratioGrad_g_err / np > small) { - cout << "Fail in ratioGrad, G error =" << ratioGrad_g_err / np << " for " - << wfc_name << std::endl; + cout << "Fail in ratioGrad, G error =" << ratioGrad_g_err / np << " for " << wfc_name + << std::endl; fail = true; } if (evaluateGL_g_err / np > small) { - cout << "Fail in evaluateGL, G error =" << evaluateGL_g_err / np - << " for " << wfc_name << std::endl; + cout << "Fail in evaluateGL, G error =" << evaluateGL_g_err / np << " for " << wfc_name + << std::endl; fail = true; } if (evaluateGL_l_err / np > small) { - cout << "Fail in evaluateGL, L error =" << evaluateGL_l_err / np - << " for " << wfc_name << std::endl; + cout << "Fail in evaluateGL, L error =" << evaluateGL_l_err / np << " for " << wfc_name + << std::endl; fail = true; } if (ratio_err / np > small) { - cout << "Fail in ratio, ratio error =" << ratio_err / np << " for " - << wfc_name << std::endl; + cout << "Fail in ratio, ratio error =" << ratio_err / np << " for " << wfc_name << std::endl; fail = true; } - if (!fail) cout << "All checks passed for " << wfc_name << std::endl; + if (!fail) + cout << "All checks passed for " << wfc_name << std::endl; return 0; } diff --git a/src/Drivers/miniqmc.cpp b/src/Drivers/miniqmc.cpp index 8e50def49..f18990640 100644 --- a/src/Drivers/miniqmc.cpp +++ b/src/Drivers/miniqmc.cpp @@ -148,31 +148,29 @@ void print_help() { //clang-format off app_summary() << "usage:" << '\n'; - app_summary() << " miniqmc [-hjvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; - app_summary() << " [-n steps] [-N substeps] [-r rmax] [-s seed]" << '\n'; - app_summary() << " [-w walkers] [-a tile_size] [-t timer_level]" << '\n'; - app_summary() << "options:" << '\n'; - app_summary() << " -a size of each spline tile default: num of orbs" << '\n'; - app_summary() << " -b use reference implementations default: off" << '\n'; - app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; - app_summary() << " -h print help and exit" << '\n'; - app_summary() << " -j enable three body Jastrow default: off" << '\n'; - app_summary() << " -m meshfactor default: 1.0" << '\n'; - app_summary() << " -n number of MC steps default: 5" << '\n'; - app_summary() << " -N number of MC substeps default: 1" << '\n'; - app_summary() << " -r set the Rmax. default: 1.7" << '\n'; - app_summary() << " -s set the random seed. default: 11" << '\n'; - app_summary() << " -t timer level: coarse or fine default: fine" << '\n'; - app_summary() << " -w number of walker(movers) default: num of threads"<< '\n'; - app_summary() << " -v verbose output" << '\n'; - app_summary() << " -V print version information and exit" << '\n'; + app_summary() << " miniqmc [-hjvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; + app_summary() << " [-n steps] [-N substeps] [-r rmax] [-s seed]" << '\n'; + app_summary() << " [-w walkers] [-a tile_size] [-t timer_level]" << '\n'; + app_summary() << "options:" << '\n'; + app_summary() << " -a size of each spline tile default: num of orbs" << '\n'; + app_summary() << " -b use reference implementations default: off" << '\n'; + app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; + app_summary() << " -h print help and exit" << '\n'; + app_summary() << " -j enable three body Jastrow default: off" << '\n'; + app_summary() << " -m meshfactor default: 1.0" << '\n'; + app_summary() << " -n number of MC steps default: 5" << '\n'; + app_summary() << " -N number of MC substeps default: 1" << '\n'; + app_summary() << " -r set the Rmax. default: 1.7" << '\n'; + app_summary() << " -s set the random seed. default: 11" << '\n'; + app_summary() << " -t timer level: coarse or fine default: fine" << '\n'; + app_summary() << " -w number of walker(movers) default: num of threads" << '\n'; + app_summary() << " -v verbose output" << '\n'; + app_summary() << " -V print version information and exit" << '\n'; //clang-format on } -int main(int argc, char **argv) +int main(int argc, char** argv) { - - // clang-format off typedef QMCTraits::RealType RealType; typedef ParticleSet::ParticlePos_t ParticlePos_t; @@ -183,11 +181,11 @@ int main(int argc, char **argv) // use the global generator - int na = 1; - int nb = 1; - int nc = 1; - int nsteps = 5; - int iseed = 11; + int na = 1; + int nb = 1; + int nc = 1; + int nsteps = 5; + int iseed = 11; int nx = 37, ny = 37, nz = 37; int nmovers = omp_get_max_threads(); // thread blocking @@ -196,12 +194,12 @@ int main(int argc, char **argv) int nsubsteps = 1; // Set cutoff for NLPP use. RealType Rmax(1.7); - bool useRef = false; + bool useRef = false; bool enableJ3 = false; PrimeNumberSet myPrimes; - bool verbose = false; + bool verbose = false; std::string timer_level_name = "fine"; if (!comm.root()) @@ -210,13 +208,15 @@ int main(int argc, char **argv) } int opt; - while(optind < argc) + while (optind < argc) { if ((opt = getopt(argc, argv, "bhjvVa:c:g:m:n:N:r:s:w:t:")) != -1) { switch (opt) { - case 'a': tileSize = atoi(optarg); break; + case 'a': + tileSize = atoi(optarg); + break; case 'b': useRef = true; break; @@ -234,11 +234,13 @@ int main(int argc, char **argv) enableJ3 = true; break; case 'm': - { - const RealType meshfactor = atof(optarg); - nx *= meshfactor; ny *= meshfactor; nz *= meshfactor; - } - break; + { + const RealType meshfactor = atof(optarg); + nx *= meshfactor; + ny *= meshfactor; + nz *= meshfactor; + } + break; case 'n': nsteps = atoi(optarg); break; @@ -254,7 +256,9 @@ int main(int argc, char **argv) case 't': timer_level_name = std::string(optarg); break; - case 'v': verbose = true; break; + case 'v': + verbose = true; + break; case 'V': print_version(true); return 1; @@ -279,10 +283,14 @@ int main(int argc, char **argv) Tensor tmat(na, 0, 0, 0, nb, 0, 0, 0, nc); timer_levels timer_level = timer_level_fine; - if (timer_level_name == "coarse") { + if (timer_level_name == "coarse") + { timer_level = timer_level_coarse; - } else if (timer_level_name != "fine") { - app_error() << "Timer level should be 'coarse' or 'fine', name given: " << timer_level_name << endl; + } + else if (timer_level_name != "fine") + { + app_error() << "Timer level should be 'coarse' or 'fine', name given: " << timer_level_name + << endl; return 1; } @@ -300,7 +308,7 @@ int main(int argc, char **argv) print_version(verbose); - SPOSet *spo_main; + SPOSet* spo_main; int nTiles = 1; ParticleSet ions; @@ -308,15 +316,15 @@ int main(int argc, char **argv) { Tensor lattice_b; build_ions(ions, tmat, lattice_b); - const int nels = count_electrons(ions, 1); - const int norb = nels / 2; - tileSize = (tileSize > 0) ? tileSize : norb; - nTiles = norb / tileSize; + const int nels = count_electrons(ions, 1); + const int norb = nels / 2; + tileSize = (tileSize > 0) ? tileSize : norb; + nTiles = norb / tileSize; number_of_electrons = nels; - const size_t SPO_coeff_size = static_cast(norb) - * (nx + 3) * (ny + 3) * (nz + 3) * sizeof(RealType); + const size_t SPO_coeff_size = + static_cast(norb) * (nx + 3) * (ny + 3) * (nz + 3) * sizeof(RealType); const double SPO_coeff_size_MB = SPO_coeff_size * 1.0 / 1024 / 1024; app_summary() << "Number of orbitals/splines = " << norb << endl @@ -330,35 +338,34 @@ int main(int argc, char **argv) app_summary() << "MPI processes = " << comm.size() << endl; #endif - app_summary() << "\nSPO coefficients size = " << SPO_coeff_size - << " bytes (" << SPO_coeff_size_MB << " MB)" << endl; + app_summary() << "\nSPO coefficients size = " << SPO_coeff_size << " bytes (" + << SPO_coeff_size_MB << " MB)" << endl; spo_main = build_SPOSet(useRef, nx, ny, nz, norb, nTiles, lattice_b); } if (!useRef) app_summary() << "Using SoA distance table, Jastrow + einspline, " << endl - << "and determinant update." << endl; + << "and determinant update." << endl; else app_summary() << "Using the reference implementation for Jastrow, " << endl - << "determinant update, and distance table + einspline of the " - << endl - << "reference implementation " << endl; + << "determinant update, and distance table + einspline of the " << endl + << "reference implementation " << endl; Timers[Timer_Total]->start(); Timers[Timer_Init]->start(); - std::vector mover_list(nmovers, nullptr); - // prepare movers - #pragma omp parallel for - for(int iw = 0; iw mover_list(nmovers, nullptr); +// prepare movers +#pragma omp parallel for + for (int iw = 0; iw < nmovers; iw++) { - const int ip = omp_get_thread_num(); + const int ip = omp_get_thread_num(); const int member_id = ip % team_size; // create and initialize movers - Mover *thiswalker = new Mover(myPrimes[ip], ions); - mover_list[iw] = thiswalker; + Mover* thiswalker = new Mover(myPrimes[ip], ions); + mover_list[iw] = thiswalker; // create a spo view in each Mover thiswalker->spo = build_SPOSet_view(useRef, spo_main, team_size, member_id); @@ -387,14 +394,14 @@ int main(int argc, char **argv) RealType sqrttau = std::sqrt(tau); RealType accept = 0.5; - #pragma omp parallel for - for(int iw = 0; iwels; - auto &spo = *mover_list[iw]->spo; - auto &random_th = mover_list[iw]->rng; - auto &wavefunction = mover_list[iw]->wavefunction; - auto &ecp = mover_list[iw]->nlpp; + auto& els = mover_list[iw]->els; + auto& spo = *mover_list[iw]->spo; + auto& random_th = mover_list[iw]->rng; + auto& wavefunction = mover_list[iw]->wavefunction; + auto& ecp = mover_list[iw]->nlpp; ParticlePos_t delta(nels); ParticlePos_t rOnSphere(nknots); @@ -419,10 +426,11 @@ int main(int argc, char **argv) Timers[Timer_evalGrad]->stop(); // Construct trial move - PosType dr = sqrttau * delta[iel]; + PosType dr = sqrttau * delta[iel]; bool isValid = els.makeMoveAndCheck(iel, dr); - if (!isValid) continue; + if (!isValid) + continue; // Compute gradient at the trial position Timers[Timer_ratioGrad]->start(); @@ -462,13 +470,13 @@ int main(int argc, char **argv) // Compute NLPP energy using integral over spherical points ecp.randomize(rOnSphere); // pick random sphere - const DistanceTableData *d_ie = els.DistTables[wavefunction.get_ei_TableID()]; + const DistanceTableData* d_ie = els.DistTables[wavefunction.get_ei_TableID()]; Timers[Timer_ECP]->start(); for (int jel = 0; jel < els.getTotalNum(); ++jel) { - const auto &dist = d_ie->Distances[jel]; - const auto &displ = d_ie->Displacements[jel]; + const auto& dist = d_ie->Distances[jel]; + const auto& displ = d_ie->Displacements[jel]; for (int iat = 0; iat < nions; ++iat) if (dist[iat] < Rmax) for (int k = 0; k < nknots; k++) @@ -492,9 +500,9 @@ int main(int argc, char **argv) } // end of mover loop Timers[Timer_Total]->stop(); - // free all movers - #pragma omp parallel for - for(int iw = 0; iwInsertEndChild(hardware); doc.InsertEndChild(resources); - XMLNode *timing = TimerManager.output_timing(doc); + XMLNode* timing = TimerManager.output_timing(doc); resources->InsertEndChild(timing); - XMLNode *particle_info = doc.NewElement("particles"); + XMLNode* particle_info = doc.NewElement("particles"); resources->InsertEndChild(particle_info); - XMLNode *electron_info = doc.NewElement("particle"); - electron_info->InsertEndChild(MakeTextElement(doc,"name","e")); - electron_info->InsertEndChild(MakeTextElement(doc,"size",std::to_string(number_of_electrons))); + XMLNode* electron_info = doc.NewElement("particle"); + electron_info->InsertEndChild(MakeTextElement(doc, "name", "e")); + electron_info->InsertEndChild(MakeTextElement(doc, "size", std::to_string(number_of_electrons))); particle_info->InsertEndChild(electron_info); - XMLNode *run_info = doc.NewElement("run"); - XMLNode *driver_info = doc.NewElement("driver"); - driver_info->InsertEndChild(MakeTextElement(doc,"name","miniqmc")); - driver_info->InsertEndChild(MakeTextElement(doc,"steps",std::to_string(nsteps))); - driver_info->InsertEndChild(MakeTextElement(doc,"substeps",std::to_string(nsubsteps))); + XMLNode* run_info = doc.NewElement("run"); + XMLNode* driver_info = doc.NewElement("driver"); + driver_info->InsertEndChild(MakeTextElement(doc, "name", "miniqmc")); + driver_info->InsertEndChild(MakeTextElement(doc, "steps", std::to_string(nsteps))); + driver_info->InsertEndChild(MakeTextElement(doc, "substeps", std::to_string(nsubsteps))); run_info->InsertEndChild(driver_info); resources->InsertEndChild(run_info); - std::string info_name = "info_" + std::to_string(na) + "_" + std::to_string(nb) + "_" + std::to_string(nc) + ".xml"; + std::string info_name = + "info_" + std::to_string(na) + "_" + std::to_string(nb) + "_" + std::to_string(nc) + ".xml"; doc.SaveFile(info_name.c_str()); } diff --git a/src/Drivers/miniqmc_sync_move.cpp b/src/Drivers/miniqmc_sync_move.cpp index 9cb591938..f77ff6d1f 100644 --- a/src/Drivers/miniqmc_sync_move.cpp +++ b/src/Drivers/miniqmc_sync_move.cpp @@ -148,31 +148,29 @@ void print_help() { //clang-format off app_summary() << "usage:" << '\n'; - app_summary() << " miniqmc [-hjvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; - app_summary() << " [-n steps] [-N substeps] [-r rmax] [-s seed]" << '\n'; - app_summary() << " [-w walkers] [-a tile_size] [-t timer_level]" << '\n'; - app_summary() << "options:" << '\n'; - app_summary() << " -a size of each spline tile default: num of orbs" << '\n'; - app_summary() << " -b use reference implementations default: off" << '\n'; - app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; - app_summary() << " -h print help and exit" << '\n'; - app_summary() << " -j enable three body Jastrow default: off" << '\n'; - app_summary() << " -m meshfactor default: 1.0" << '\n'; - app_summary() << " -n number of MC steps default: 5" << '\n'; - app_summary() << " -N number of MC substeps default: 1" << '\n'; - app_summary() << " -r set the Rmax. default: 1.7" << '\n'; - app_summary() << " -s set the random seed. default: 11" << '\n'; - app_summary() << " -t timer level: coarse or fine default: fine" << '\n'; - app_summary() << " -w number of walker(movers) default: num of threads"<< '\n'; - app_summary() << " -v verbose output" << '\n'; - app_summary() << " -V print version information and exit" << '\n'; + app_summary() << " miniqmc [-hjvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; + app_summary() << " [-n steps] [-N substeps] [-r rmax] [-s seed]" << '\n'; + app_summary() << " [-w walkers] [-a tile_size] [-t timer_level]" << '\n'; + app_summary() << "options:" << '\n'; + app_summary() << " -a size of each spline tile default: num of orbs" << '\n'; + app_summary() << " -b use reference implementations default: off" << '\n'; + app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; + app_summary() << " -h print help and exit" << '\n'; + app_summary() << " -j enable three body Jastrow default: off" << '\n'; + app_summary() << " -m meshfactor default: 1.0" << '\n'; + app_summary() << " -n number of MC steps default: 5" << '\n'; + app_summary() << " -N number of MC substeps default: 1" << '\n'; + app_summary() << " -r set the Rmax. default: 1.7" << '\n'; + app_summary() << " -s set the random seed. default: 11" << '\n'; + app_summary() << " -t timer level: coarse or fine default: fine" << '\n'; + app_summary() << " -w number of walker(movers) default: num of threads" << '\n'; + app_summary() << " -v verbose output" << '\n'; + app_summary() << " -V print version information and exit" << '\n'; //clang-format on } -int main(int argc, char **argv) +int main(int argc, char** argv) { - - // clang-format off typedef QMCTraits::RealType RealType; typedef ParticleSet::ParticlePos_t ParticlePos_t; @@ -185,11 +183,11 @@ int main(int argc, char **argv) // use the global generator - int na = 1; - int nb = 1; - int nc = 1; - int nsteps = 5; - int iseed = 11; + int na = 1; + int nb = 1; + int nc = 1; + int nsteps = 5; + int iseed = 11; int nx = 37, ny = 37, nz = 37; int nmovers = omp_get_max_threads(); // thread blocking @@ -198,12 +196,12 @@ int main(int argc, char **argv) int nsubsteps = 1; // Set cutoff for NLPP use. RealType Rmax(1.7); - bool useRef = false; + bool useRef = false; bool enableJ3 = false; PrimeNumberSet myPrimes; - bool verbose = false; + bool verbose = false; std::string timer_level_name = "fine"; if (!comm.root()) @@ -212,13 +210,15 @@ int main(int argc, char **argv) } int opt; - while(optind < argc) + while (optind < argc) { if ((opt = getopt(argc, argv, "bhjvVa:c:g:m:n:N:r:s:w:t:")) != -1) { switch (opt) { - case 'a': tileSize = atoi(optarg); break; + case 'a': + tileSize = atoi(optarg); + break; case 'b': useRef = true; break; @@ -236,11 +236,13 @@ int main(int argc, char **argv) enableJ3 = true; break; case 'm': - { - const RealType meshfactor = atof(optarg); - nx *= meshfactor; ny *= meshfactor; nz *= meshfactor; - } - break; + { + const RealType meshfactor = atof(optarg); + nx *= meshfactor; + ny *= meshfactor; + nz *= meshfactor; + } + break; case 'n': nsteps = atoi(optarg); break; @@ -256,7 +258,9 @@ int main(int argc, char **argv) case 't': timer_level_name = std::string(optarg); break; - case 'v': verbose = true; break; + case 'v': + verbose = true; + break; case 'V': print_version(true); return 1; @@ -281,10 +285,14 @@ int main(int argc, char **argv) Tensor tmat(na, 0, 0, 0, nb, 0, 0, 0, nc); timer_levels timer_level = timer_level_fine; - if (timer_level_name == "coarse") { + if (timer_level_name == "coarse") + { timer_level = timer_level_coarse; - } else if (timer_level_name != "fine") { - app_error() << "Timer level should be 'coarse' or 'fine', name given: " << timer_level_name << endl; + } + else if (timer_level_name != "fine") + { + app_error() << "Timer level should be 'coarse' or 'fine', name given: " << timer_level_name + << endl; return 1; } @@ -302,7 +310,7 @@ int main(int argc, char **argv) print_version(verbose); - SPOSet *spo_main; + SPOSet* spo_main; int nTiles = 1; ParticleSet ions; @@ -310,15 +318,15 @@ int main(int argc, char **argv) { Tensor lattice_b; build_ions(ions, tmat, lattice_b); - const int nels = count_electrons(ions, 1); - const int norb = nels / 2; - tileSize = (tileSize > 0) ? tileSize : norb; - nTiles = norb / tileSize; + const int nels = count_electrons(ions, 1); + const int norb = nels / 2; + tileSize = (tileSize > 0) ? tileSize : norb; + nTiles = norb / tileSize; number_of_electrons = nels; - const size_t SPO_coeff_size = static_cast(norb) - * (nx + 3) * (ny + 3) * (nz + 3) * sizeof(RealType); + const size_t SPO_coeff_size = + static_cast(norb) * (nx + 3) * (ny + 3) * (nz + 3) * sizeof(RealType); const double SPO_coeff_size_MB = SPO_coeff_size * 1.0 / 1024 / 1024; app_summary() << "Number of orbitals/splines = " << norb << endl @@ -332,35 +340,34 @@ int main(int argc, char **argv) app_summary() << "MPI processes = " << comm.size() << endl; #endif - app_summary() << "\nSPO coefficients size = " << SPO_coeff_size - << " bytes (" << SPO_coeff_size_MB << " MB)" << endl; + app_summary() << "\nSPO coefficients size = " << SPO_coeff_size << " bytes (" + << SPO_coeff_size_MB << " MB)" << endl; spo_main = build_SPOSet(useRef, nx, ny, nz, norb, nTiles, lattice_b); } if (!useRef) app_summary() << "Using SoA distance table, Jastrow + einspline, " << endl - << "and determinant update." << endl; + << "and determinant update." << endl; else app_summary() << "Using the reference implementation for Jastrow, " << endl - << "determinant update, and distance table + einspline of the " - << endl - << "reference implementation " << endl; + << "determinant update, and distance table + einspline of the " << endl + << "reference implementation " << endl; Timers[Timer_Total]->start(); Timers[Timer_Init]->start(); - std::vector mover_list(nmovers, nullptr); - // prepare movers - #pragma omp parallel for - for(int iw = 0; iw mover_list(nmovers, nullptr); +// prepare movers +#pragma omp parallel for + for (int iw = 0; iw < nmovers; iw++) { - const int ip = omp_get_thread_num(); + const int ip = omp_get_thread_num(); const int member_id = ip % team_size; // create and initialize movers - Mover *thiswalker = new Mover(myPrimes[ip], ions); - mover_list[iw] = thiswalker; + Mover* thiswalker = new Mover(myPrimes[ip], ions); + mover_list[iw] = thiswalker; // create a spo view in each Mover thiswalker->spo = build_SPOSet_view(useRef, spo_main, team_size, member_id); @@ -373,15 +380,15 @@ int main(int argc, char **argv) } { // initial computing - const std::vector P_list(extract_els_list(mover_list)); - const std::vector WF_list(extract_wf_list(mover_list)); + const std::vector P_list(extract_els_list(mover_list)); + const std::vector WF_list(extract_wf_list(mover_list)); mover_list[0]->wavefunction.multi_evaluateLog(WF_list, P_list); } Timers[Timer_Init]->stop(); - const int nions = ions.getTotalNum(); - const int nels = mover_list[0]->els.getTotalNum(); - const int nels3 = 3 * nels; + const int nions = ions.getTotalNum(); + const int nels = mover_list[0]->els.getTotalNum(); + const int nels3 = 3 * nels; const int nmovers3 = 3 * nmovers; // this is the number of qudrature points for the non-local PP @@ -410,17 +417,17 @@ int main(int argc, char **argv) { Timers[Timer_Diffusion]->start(); - const std::vector P_list(extract_els_list(mover_list)); - const std::vector WF_list(extract_wf_list(mover_list)); - const Mover &anon_mover = *mover_list[0]; + const std::vector P_list(extract_els_list(mover_list)); + const std::vector WF_list(extract_wf_list(mover_list)); + const Mover& anon_mover = *mover_list[0]; for (int l = 0; l < nsubsteps; ++l) // drift-and-diffusion { for (int iel = 0; iel < nels; ++iel) { - // Operate on electron with index iel - #pragma omp parallel for - for(int iw = 0; iwels.setActive(iel); // Compute gradient at the current position @@ -432,44 +439,44 @@ int main(int argc, char **argv) mover_list[0]->rng.generate_uniform(ur.data(), nmovers); mover_list[0]->rng.generate_normal(&delta[0][0], nmovers3); - #pragma omp parallel for - for(int iw = 0; iwels.makeMoveAndCheck(iel, dr); } - std::vector valid_mover_list(filtered_list(mover_list,isValid)); + std::vector valid_mover_list(filtered_list(mover_list, isValid)); std::vector isAccepted(valid_mover_list.size()); - const std::vector valid_P_list(extract_els_list(valid_mover_list)); - const std::vector valid_spo_list(extract_spo_list(valid_mover_list)); - const std::vector valid_WF_list(extract_wf_list(valid_mover_list)); + const std::vector valid_P_list(extract_els_list(valid_mover_list)); + const std::vector valid_spo_list(extract_spo_list(valid_mover_list)); + const std::vector valid_WF_list(extract_wf_list(valid_mover_list)); // Compute gradient at the trial position Timers[Timer_ratioGrad]->start(); anon_mover.wavefunction.multi_ratioGrad(valid_WF_list, valid_P_list, iel, ratios, grad_new); - for(int iw = 0; iwels.R[iel]; anon_mover.spo->multi_evaluate_vgh(valid_spo_list, pos_list); Timers[Timer_ratioGrad]->stop(); // Accept/reject the trial move - for(int iw = 0; iwaccept) - isAccepted[iw]=true; + for (int iw = 0; iw < valid_mover_list.size(); iw++) + if (ur[iw] > accept) + isAccepted[iw] = true; else - isAccepted[iw]=false; + isAccepted[iw] = false; Timers[Timer_Update]->start(); // update WF storage anon_mover.wavefunction.multi_acceptrestoreMove(valid_WF_list, valid_P_list, isAccepted, iel); Timers[Timer_Update]->stop(); - // Update position - #pragma omp parallel for - for(int iw = 0; iwels.acceptMove(iel); @@ -477,10 +484,10 @@ int main(int argc, char **argv) valid_mover_list[iw]->els.rejectMove(iel); } } // iel - } // substeps + } // substeps - #pragma omp parallel for - for(int iw = 0; iwels.donePbyP(); // evaluate Kinetic Energy @@ -492,22 +499,22 @@ int main(int argc, char **argv) // Compute NLPP energy using integral over spherical points // Ye: I have not found a strategy for NLPP Timers[Timer_ECP]->start(); - #pragma omp parallel for - for(int iw = 0; iwels; - auto &spo = *mover_list[iw]->spo; - auto &wavefunction = mover_list[iw]->wavefunction; - auto &ecp = mover_list[iw]->nlpp; - + auto& els = mover_list[iw]->els; + auto& spo = *mover_list[iw]->spo; + auto& wavefunction = mover_list[iw]->wavefunction; + auto& ecp = mover_list[iw]->nlpp; + ParticlePos_t rOnSphere(nknots); ecp.randomize(rOnSphere); // pick random sphere - const DistanceTableData *d_ie = els.DistTables[wavefunction.get_ei_TableID()]; + const DistanceTableData* d_ie = els.DistTables[wavefunction.get_ei_TableID()]; for (int jel = 0; jel < els.getTotalNum(); ++jel) { - const auto &dist = d_ie->Distances[jel]; - const auto &displ = d_ie->Displacements[jel]; + const auto& dist = d_ie->Distances[jel]; + const auto& displ = d_ie->Displacements[jel]; for (int iat = 0; iat < nions; ++iat) if (dist[iat] < Rmax) for (int k = 0; k < nknots; k++) @@ -527,13 +534,12 @@ int main(int argc, char **argv) } Timers[Timer_ECP]->stop(); } // nsteps - } Timers[Timer_Total]->stop(); - // free all movers - #pragma omp parallel for - for(int iw = 0; iwInsertEndChild(hardware); doc.InsertEndChild(resources); - XMLNode *timing = TimerManager.output_timing(doc); + XMLNode* timing = TimerManager.output_timing(doc); resources->InsertEndChild(timing); - XMLNode *particle_info = doc.NewElement("particles"); + XMLNode* particle_info = doc.NewElement("particles"); resources->InsertEndChild(particle_info); - XMLNode *electron_info = doc.NewElement("particle"); - electron_info->InsertEndChild(MakeTextElement(doc,"name","e")); - electron_info->InsertEndChild(MakeTextElement(doc,"size",std::to_string(number_of_electrons))); + XMLNode* electron_info = doc.NewElement("particle"); + electron_info->InsertEndChild(MakeTextElement(doc, "name", "e")); + electron_info->InsertEndChild(MakeTextElement(doc, "size", std::to_string(number_of_electrons))); particle_info->InsertEndChild(electron_info); - XMLNode *run_info = doc.NewElement("run"); - XMLNode *driver_info = doc.NewElement("driver"); - driver_info->InsertEndChild(MakeTextElement(doc,"name","miniqmc")); - driver_info->InsertEndChild(MakeTextElement(doc,"steps",std::to_string(nsteps))); - driver_info->InsertEndChild(MakeTextElement(doc,"substeps",std::to_string(nsubsteps))); + XMLNode* run_info = doc.NewElement("run"); + XMLNode* driver_info = doc.NewElement("driver"); + driver_info->InsertEndChild(MakeTextElement(doc, "name", "miniqmc")); + driver_info->InsertEndChild(MakeTextElement(doc, "steps", std::to_string(nsteps))); + driver_info->InsertEndChild(MakeTextElement(doc, "substeps", std::to_string(nsubsteps))); run_info->InsertEndChild(driver_info); resources->InsertEndChild(run_info); - std::string info_name = "info_" + std::to_string(na) + "_" + std::to_string(nb) + "_" + std::to_string(nc) + ".xml"; + std::string info_name = + "info_" + std::to_string(na) + "_" + std::to_string(nb) + "_" + std::to_string(nc) + ".xml"; doc.SaveFile(info_name.c_str()); } diff --git a/src/Input/graphite.hpp b/src/Input/graphite.hpp index f1c3bdc21..91a900453 100644 --- a/src/Input/graphite.hpp +++ b/src/Input/graphite.hpp @@ -13,8 +13,8 @@ namespace qmcplusplus { - -template T count_electrons(const ParticleSet &ions, T scale) +template +T count_electrons(const ParticleSet& ions, T scale) { return ions.getTotalNum() * scale * 4; } @@ -24,11 +24,10 @@ template T count_electrons(const ParticleSet &ions, T scale) * @param tmat tiling matrix * @param scale scaling factor */ -template -Tensor tile_cell(ParticleSet &ions, const Tensor &tmat, T scale) +template +Tensor tile_cell(ParticleSet& ions, const Tensor& tmat, T scale) { - Tensor graphite = {4.65099, 0.0, 0.0, -2.3255, 4.02788, - 0.0, 0.0, 0.0, 12.67609393}; + Tensor graphite = {4.65099, 0.0, 0.0, -2.3255, 4.02788, 0.0, 0.0, 0.0, 12.67609393}; ions.Lattice.BoxBConds = 1; ions.Lattice.set(graphite); ions.create(4); @@ -38,7 +37,7 @@ Tensor tile_cell(ParticleSet &ions, const Tensor &tmat, T scale) ions.R[2] = {0.0, 0.0, 6.33805}; ions.R[3] = {2.3255, 1.34263, 6.33805}; - SpeciesSet &species(ions.getSpeciesSet()); + SpeciesSet& species(ions.getSpeciesSet()); int icharge = species.addAttribute("charge"); // charge_tag); species.addSpecies("C"); @@ -49,7 +48,8 @@ Tensor tile_cell(ParticleSet &ions, const Tensor &tmat, T scale) return graphite; } -template void graphite_4x4(PT &R) +template +void graphite_4x4(PT& R) { typedef typename PT::Type_t postype; @@ -119,22 +119,24 @@ template void graphite_4x4(PT &R) R[63] = postype(9.301988, 13.426263, 6.338047); } -template void buildJeeI(JeeIType &JeeI, double rcut) +template +void buildJeeI(JeeIType& JeeI, double rcut) { using Func = typename JeeIType::FuncType; using RealType = typename Func::real_type; rcut = std::min(rcut, 6.0); { - std::vector params = { - 8.227710241e-06, 2.480817653e-06, -5.354068112e-06, -1.112644787e-05, - -2.208006078e-06, 5.213121933e-06, -1.537865869e-05, 8.899030233e-06, - 6.257255156e-06, 3.214580988e-06, -7.716743107e-06, -5.275682077e-06, - -1.778457637e-06, 7.926231121e-06, 1.767406868e-06, 5.451359059e-08, - 2.801423724e-06, 4.577282736e-06, 7.634608083e-06, -9.510673173e-07, - -2.344131575e-06, -1.878777219e-06, 3.937363358e-07, 5.065353773e-07, - 5.086724869e-07, -1.358768154e-07}; - Func *functor = new Func; - functor->cutoff_radius = rcut; + std::vector params = {8.227710241e-06, 2.480817653e-06, -5.354068112e-06, + -1.112644787e-05, -2.208006078e-06, 5.213121933e-06, + -1.537865869e-05, 8.899030233e-06, 6.257255156e-06, + 3.214580988e-06, -7.716743107e-06, -5.275682077e-06, + -1.778457637e-06, 7.926231121e-06, 1.767406868e-06, + 5.451359059e-08, 2.801423724e-06, 4.577282736e-06, + 7.634608083e-06, -9.510673173e-07, -2.344131575e-06, + -1.878777219e-06, 3.937363358e-07, 5.065353773e-07, + 5.086724869e-07, -1.358768154e-07}; + Func* functor = new Func; + functor->cutoff_radius = rcut; functor->resize(3, 3); functor->Parameters = params; functor->reset_gamma(); @@ -142,16 +144,17 @@ template void buildJeeI(JeeIType &JeeI, double rcut) JeeI.addFunc(0, 0, 0, functor); } { - std::vector params = { - -6.939530224e-06, 2.634169299e-05, 4.046077477e-05, -8.002682388e-06, - -5.396795988e-06, 6.697370507e-06, 5.433953051e-05, -6.336849668e-06, - 3.680471431e-05, -2.996059772e-05, 1.99365828e-06, -3.222705626e-05, - -8.091669063e-06, 4.15738535e-06, 4.843939112e-06, 3.563650208e-07, - 3.786332474e-05, -1.418336941e-05, 2.282691374e-05, 1.29239286e-06, - -4.93580873e-06, -3.052539228e-06, 9.870288001e-08, 1.844286407e-06, - 2.970561871e-07, -4.364303677e-08}; - Func *functor = new Func; - functor->cutoff_radius = rcut; + std::vector params = {-6.939530224e-06, 2.634169299e-05, 4.046077477e-05, + -8.002682388e-06, -5.396795988e-06, 6.697370507e-06, + 5.433953051e-05, -6.336849668e-06, 3.680471431e-05, + -2.996059772e-05, 1.99365828e-06, -3.222705626e-05, + -8.091669063e-06, 4.15738535e-06, 4.843939112e-06, + 3.563650208e-07, 3.786332474e-05, -1.418336941e-05, + 2.282691374e-05, 1.29239286e-06, -4.93580873e-06, + -3.052539228e-06, 9.870288001e-08, 1.844286407e-06, + 2.970561871e-07, -4.364303677e-08}; + Func* functor = new Func; + functor->cutoff_radius = rcut; functor->resize(3, 3); functor->Parameters = params; functor->reset_gamma(); @@ -161,50 +164,49 @@ template void buildJeeI(JeeIType &JeeI, double rcut) JeeI.check_complete(); } -template void buildJ2(J2Type &J2, double rcut) +template +void buildJ2(J2Type& J2, double rcut) { using Func = typename J2Type::FuncType; using RealType = typename Func::real_type; const int npts = 10; std::string optimize("no"); - rcut = std::min(rcut, 6.4); + rcut = std::min(rcut, 6.4); { // add uu/dd - std::vector Y = {0.4711f, 0.3478f, 0.2445f, 0.1677f, - 0.1118f, 0.0733f, 0.0462f, 0.0273f, - 0.0145f, 0.0063f, 0.0f}; + std::vector Y = + {0.4711f, 0.3478f, 0.2445f, 0.1677f, 0.1118f, 0.0733f, 0.0462f, 0.0273f, 0.0145f, 0.0063f, 0.0f}; // 0.0733f, 0.0462f, 0.0273f, 0.0145f, 0.0063f, 0.0f}; std::string suu("uu"); - Func *f = new Func; + Func* f = new Func; f->setupParameters(npts, rcut, -0.25, Y); J2.addFunc(0, 0, f); } { // add ud/du - std::vector Y = {0.6715f, 0.4433f, 0.2901f, 0.1889f, - 0.1227f, 0.0793f, 0.0496f, 0.0292f, - 0.0152f, 0.0061f, 0.0f}; + std::vector Y = + {0.6715f, 0.4433f, 0.2901f, 0.1889f, 0.1227f, 0.0793f, 0.0496f, 0.0292f, 0.0152f, 0.0061f, 0.0f}; std::string suu("ud"); - Func *f = new Func; + Func* f = new Func; f->setupParameters(npts, rcut, -0.25, Y); J2.addFunc(0, 1, f); } } -template void buildJ1(J1Type &J1, double rcut) +template +void buildJ1(J1Type& J1, double rcut) { using Func = typename J1Type::FuncType; using RealType = typename Func::real_type; const int npts = 10; std::string optimize("no"); - rcut = std::min(rcut, 6.4); + rcut = std::min(rcut, 6.4); - std::vector Y = {0.4711f, 0.3478f, 0.2445f, 0.1677f, - 0.1118f, 0.0733f, 0.0462f, 0.0273f, - 0.0145f, 0.0063f, 0.0f}; + std::vector Y = + {0.4711f, 0.3478f, 0.2445f, 0.1677f, 0.1118f, 0.0733f, 0.0462f, 0.0273f, 0.0145f, 0.0063f, 0.0f}; std::string suu("C"); - Func *f = new Func; + Func* f = new Func; f->setupParameters(npts, rcut, -0.25, Y); J1.addFunc(0, f); } -} +} // namespace qmcplusplus diff --git a/src/Input/nio.hpp b/src/Input/nio.hpp index 90092f368..3cc5b3139 100644 --- a/src/Input/nio.hpp +++ b/src/Input/nio.hpp @@ -13,18 +13,16 @@ namespace qmcplusplus { - -template T count_electrons(const ParticleSet &ions, T scale) +template +T count_electrons(const ParticleSet& ions, T scale) { return ions.getTotalNum() * scale * 12; } -template -Tensor tile_cell(ParticleSet &ions, const Tensor &tmat, T scale) +template +Tensor tile_cell(ParticleSet& ions, const Tensor& tmat, T scale) { - - Tensor nio_cell = {7.8811, 7.8811, 0.0, -7.8811, 7.8811, - 0.0, 0.0, 0.0, 15.7622}; + Tensor nio_cell = {7.8811, 7.8811, 0.0, -7.8811, 7.8811, 0.0, 0.0, 0.0, 15.7622}; // set PBC in x,y,z directions ions.Lattice.BoxBConds = 1; // set the lattice @@ -69,7 +67,7 @@ Tensor tile_cell(ParticleSet &ions, const Tensor &tmat, T scale) ions.R[30] = {0.25, 0.75, 0.25}; ions.R[31] = {0.75, 0.75, 0.75}; - SpeciesSet &species(ions.getSpeciesSet()); + SpeciesSet& species(ions.getSpeciesSet()); species.addSpecies("O"); species.addSpecies("Ni"); @@ -80,7 +78,8 @@ Tensor tile_cell(ParticleSet &ions, const Tensor &tmat, T scale) return nio_cell; } -template void buildJ2(J2Type &J2, double rcut) +template +void buildJ2(J2Type& J2, double rcut) { using Func = typename J2Type::FuncType; using RealType = typename Func::real_type; @@ -101,7 +100,7 @@ template void buildJ2(J2Type &J2, double rcut) 0.002827476478, 0.0}; std::string suu("uu"); - Func *f = new Func; + Func* f = new Func; f->setupParameters(npts, rcut, 0.0, Y); J2.addFunc(0, 0, f); } @@ -118,13 +117,14 @@ template void buildJ2(J2Type &J2, double rcut) 0.002864695148, 0.0}; std::string suu("ud"); - Func *f = new Func; + Func* f = new Func; f->setupParameters(npts, rcut, 0.0, Y); J2.addFunc(0, 1, f); } } -template void buildJ1(J1Type &J1, double rcut) +template +void buildJ1(J1Type& J1, double rcut) { using Func = typename J1Type::FuncType; using RealType = typename Func::real_type; @@ -145,7 +145,7 @@ template void buildJ1(J1Type &J1, double rcut) -0.001101691898, 0.0}; std::string suu("O"); - Func *f = new Func; + Func* f = new Func; f->setupParameters(npts, rcut, -0.25, Y); J1.addFunc(0, f); @@ -167,7 +167,8 @@ template void buildJ1(J1Type &J1, double rcut) J1.addFunc(1, f); } -template void buildJeeI(JeeIType &JeeI, double rcut) +template +void buildJeeI(JeeIType& JeeI, double rcut) { using Func = typename JeeIType::FuncType; using RealType = typename Func::real_type; @@ -175,18 +176,15 @@ template void buildJeeI(JeeIType &JeeI, double rcut) rcut = std::min(rcut, 4.8261684030); { // add uuNi - std::vector Y = { - -0.003356164484, 0.002412623253, 0.01653623839, - 0.0008341346169, -0.002808360734, 0.000710697475, - 0.01076942152, 0.0009228283355, 0.01576022161, - -0.003585259096, 0.003323106938, -0.02282975998, - -0.002246144403, -0.007196992871, -0.00404316239, - 0.001465337212, 0.02026982926, -0.03528735393, - 0.04594087928, -0.008776410679, -0.001552528476, - -0.005554407743, 0.001858594451, 0.002001634408, - 0.0009302256139, -0.0006304447229}; + std::vector Y = {-0.003356164484, 0.002412623253, 0.01653623839, 0.0008341346169, + -0.002808360734, 0.000710697475, 0.01076942152, 0.0009228283355, + 0.01576022161, -0.003585259096, 0.003323106938, -0.02282975998, + -0.002246144403, -0.007196992871, -0.00404316239, 0.001465337212, + 0.02026982926, -0.03528735393, 0.04594087928, -0.008776410679, + -0.001552528476, -0.005554407743, 0.001858594451, 0.002001634408, + 0.0009302256139, -0.0006304447229}; std::string suu("uuNi"); - Func *f = new Func; + Func* f = new Func; f->cutoff_radius = rcut; f->resize(3, 3); f->Parameters = Y; @@ -194,18 +192,15 @@ template void buildJeeI(JeeIType &JeeI, double rcut) JeeI.addFunc(0, 0, 0, f); } { // add udNi - std::vector Y = { - -0.006861627197, 0.003278047306, 0.03324006545, - 0.003097361067, -0.004710623571, 9.652180317e-06, - 0.02212708787, -0.003718893286, 0.03390124932, - -0.00710566395, 0.008807743592, -0.04281661568, - -0.008463011294, -0.01269994613, -0.002005229447, - 0.002186590944, 0.03350196472, -0.05677253817, - 0.07810604648, -0.009629896208, -0.006372643712, - -0.01056861605, 0.002485188615, 0.008392442289, - 1.073423014e-05, -0.0004812466328}; + std::vector Y = {-0.006861627197, 0.003278047306, 0.03324006545, 0.003097361067, + -0.004710623571, 9.652180317e-06, 0.02212708787, -0.003718893286, + 0.03390124932, -0.00710566395, 0.008807743592, -0.04281661568, + -0.008463011294, -0.01269994613, -0.002005229447, 0.002186590944, + 0.03350196472, -0.05677253817, 0.07810604648, -0.009629896208, + -0.006372643712, -0.01056861605, 0.002485188615, 0.008392442289, + 1.073423014e-05, -0.0004812466328}; std::string suu("udNi"); - Func *f = new Func; + Func* f = new Func; f->cutoff_radius = rcut; f->resize(3, 3); f->Parameters = Y; @@ -213,18 +208,15 @@ template void buildJeeI(JeeIType &JeeI, double rcut) JeeI.addFunc(0, 0, 1, f); } { // add uuO - std::vector Y = { - -0.003775082438, -0.00169971229, 0.02162925441, - 0.005674020544, -0.0008296047161, 0.00128057705, - 0.005487203215, 0.001637322446, 0.02976838198, - -0.0003207100945, 0.01143855436, -0.05336741304, - -0.00732359381, -0.01556942626, 0.0001149478453, - 0.001838601199, 0.02570154203, -0.0675325214, - 0.1080671614, -0.01258358969, 0.001839834045, - -0.02422400426, 0.005154953014, 0.003510582598, - 0.007464427016, -0.002454817757}; + std::vector Y = {-0.003775082438, -0.00169971229, 0.02162925441, 0.005674020544, + -0.0008296047161, 0.00128057705, 0.005487203215, 0.001637322446, + 0.02976838198, -0.0003207100945, 0.01143855436, -0.05336741304, + -0.00732359381, -0.01556942626, 0.0001149478453, 0.001838601199, + 0.02570154203, -0.0675325214, 0.1080671614, -0.01258358969, + 0.001839834045, -0.02422400426, 0.005154953014, 0.003510582598, + 0.007464427016, -0.002454817757}; std::string suu("uuO"); - Func *f = new Func; + Func* f = new Func; f->cutoff_radius = rcut; f->resize(3, 3); f->Parameters = Y; @@ -232,17 +224,15 @@ template void buildJeeI(JeeIType &JeeI, double rcut) JeeI.addFunc(1, 0, 0, f); } { // add udO - std::vector Y = {-0.009590393593, 0.002498010871, 0.04225872633, - 0.00460311261, -0.01071033503, 0.001253155062, - 0.02934351285, -0.01823794726, 0.07224890393, - -0.01020046849, 0.006310807929, -0.05655009412, - -0.0363775247, 0.002062411388, 0.02037856173, - 0.003372676617, 0.03915277249, -0.02680556816, - 0.08648136635, 0.01499088063, -0.02231984329, - -0.02399792096, 0.001105720128, 0.02196005181, + std::vector Y = {-0.009590393593, 0.002498010871, 0.04225872633, 0.00460311261, + -0.01071033503, 0.001253155062, 0.02934351285, -0.01823794726, + 0.07224890393, -0.01020046849, 0.006310807929, -0.05655009412, + -0.0363775247, 0.002062411388, 0.02037856173, 0.003372676617, + 0.03915277249, -0.02680556816, 0.08648136635, 0.01499088063, + -0.02231984329, -0.02399792096, 0.001105720128, 0.02196005181, 0.003162638982, -0.00119645772}; std::string suu("udO"); - Func *f = new Func; + Func* f = new Func; f->cutoff_radius = rcut; f->resize(3, 3); f->Parameters = Y; @@ -250,4 +240,4 @@ template void buildJeeI(JeeIType &JeeI, double rcut) JeeI.addFunc(1, 0, 1, f); } } -} +} // namespace qmcplusplus diff --git a/src/Input/pseudo.hpp b/src/Input/pseudo.hpp index 9fb024ca3..04e7f96e6 100644 --- a/src/Input/pseudo.hpp +++ b/src/Input/pseudo.hpp @@ -21,7 +21,8 @@ namespace qmcplusplus { -template struct NonLocalPP +template +struct NonLocalPP { /** dimension */ enum @@ -40,14 +41,14 @@ template struct NonLocalPP /** positions on a sphere */ std::vector sgridxyz_m; /** default constructor with knots=12 */ - NonLocalPP(const RandomGenerator &rng) : myRNG(rng) + NonLocalPP(const RandomGenerator& rng) : myRNG(rng) { // use fixed seed myRNG.init(0, 1, 11); weight_m.resize(12); sgridxyz_m.resize(12); const RealType w = RealType(1.0 / 12.0); - for (int i = 0; i < 12; ++i) + for (int i = 0; i < 12; ++i) weight_m[i] = w; // clang-format off @@ -68,22 +69,27 @@ template struct NonLocalPP inline int size() const { return sgridxyz_m.size(); } - template inline void randomize(PA &rrotsgrid) + template + inline void randomize(PA& rrotsgrid) { // const RealType twopi(6.28318530718); // RealType phi(twopi*Random()),psi(twopi*Random()),cth(Random()-0.5), - RealType phi(TWOPI * (myRNG())), psi(TWOPI * (myRNG())), - cth((myRNG()) - 0.5); - RealType sph(std::sin(phi)), cph(std::cos(phi)), - sth(std::sqrt(1.0 - cth * cth)), sps(std::sin(psi)), cps(std::cos(psi)); - TensorType rmat(cph * cth * cps - sph * sps, sph * cth * cps + cph * sps, - -sth * cps, -cph * cth * sps - sph * cps, - -sph * cth * sps + cph * cps, sth * sps, cph * sth, - sph * sth, cth); + RealType phi(TWOPI * (myRNG())), psi(TWOPI * (myRNG())), cth((myRNG()) - 0.5); + RealType sph(std::sin(phi)), cph(std::cos(phi)), sth(std::sqrt(1.0 - cth * cth)), + sps(std::sin(psi)), cps(std::cos(psi)); + TensorType rmat(cph * cth * cps - sph * sps, + sph * cth * cps + cph * sps, + -sth * cps, + -cph * cth * sps - sph * cps, + -sph * cth * sps + cph * cps, + sth * sps, + cph * sth, + sph * sth, + cth); const int n = sgridxyz_m.size(); - for (int i = 0; i < n; ++i) + for (int i = 0; i < n; ++i) rrotsgrid[i] = dot(rmat, sgridxyz_m[i]); } }; -} +} // namespace qmcplusplus #endif diff --git a/src/Numerics/Blasf.h b/src/Numerics/Blasf.h index 61766db69..dd703c4a2 100644 --- a/src/Numerics/Blasf.h +++ b/src/Numerics/Blasf.h @@ -92,6 +92,7 @@ #endif +// clang-format off // declaring Fortran interfaces extern "C" { @@ -333,4 +334,5 @@ void dtgevc(const char *SIDE, const char *HOWMNY, const bool *SELECT, double *VL, const int *LDVL, double *VR, const int *LDVR, const int *MM, int *M, double *WORK, int *INFO); } +// clang-format on #endif diff --git a/src/Numerics/Containers.h b/src/Numerics/Containers.h index 83f4cef35..3658b6f37 100644 --- a/src/Numerics/Containers.h +++ b/src/Numerics/Containers.h @@ -35,7 +35,8 @@ namespace qmcplusplus /** SoA adaptor class for ParticleAttrib > * @tparm T data type, float, double, complex, complex */ -template struct VectorSoAContainer +template +struct VectorSoAContainer { #if (__cplusplus >= 201103L) using Type_t = TinyVector; @@ -53,7 +54,7 @@ template struct VectorSoAContainer /// number of elements allocated by myAlloc size_t nAllocated; /// pointer: what type???? - T *myData; + T* myData; /// allocator aligned_allocator myAlloc; /// default constructor @@ -61,11 +62,12 @@ template struct VectorSoAContainer /// destructor ~VectorSoAContainer() { - if (nAllocated > 0) myAlloc.deallocate(myData, nAllocated); + if (nAllocated > 0) + myAlloc.deallocate(myData, nAllocated); } /// default copy constructor - VectorSoAContainer(const VectorSoAContainer &in) + VectorSoAContainer(const VectorSoAContainer& in) { setDefaults(); resize(in.nLocal); @@ -73,7 +75,7 @@ template struct VectorSoAContainer } /// default copy operator - VectorSoAContainer &operator=(const VectorSoAContainer &in) + VectorSoAContainer& operator=(const VectorSoAContainer& in) { if (myData != in.myData) { @@ -85,8 +87,7 @@ template struct VectorSoAContainer #if (__cplusplus >= 201103L) /// move constructor - VectorSoAContainer(VectorSoAContainer &&in) - : nLocal(in.nLocal), nGhosts(in.nGhosts) + VectorSoAContainer(VectorSoAContainer&& in) : nLocal(in.nLocal), nGhosts(in.nGhosts) { nAllocated = in.nAllocated; myData = in.myData; @@ -105,25 +106,27 @@ template struct VectorSoAContainer } /** constructor with ParticleAttrib */ - template - VectorSoAContainer(const ParticleAttrib> &in) + template + VectorSoAContainer(const ParticleAttrib>& in) { setDefaults(); resize(in.size()); copyIn(in); } - template - VectorSoAContainer &operator=(const ParticleAttrib> &in) + template + VectorSoAContainer& operator=(const ParticleAttrib>& in) { - if (nLocal != in.size()) resize(in.size()); + if (nLocal != in.size()) + resize(in.size()); copyIn(in); return *this; } /** need A=0.0; */ - template VectorSoAContainer &operator=(T1 in) + template + VectorSoAContainer& operator=(T1 in) { std::fill(myData, myData + nGhosts * D, static_cast(in)); return *this; @@ -145,7 +148,8 @@ template struct VectorSoAContainer */ __forceinline void resize(size_t n) { - if (nAllocated) myAlloc.deallocate(myData, nAllocated); + if (nAllocated) + myAlloc.deallocate(myData, nAllocated); nLocal = n; nGhosts = getAlignedSize(n); nAllocated = nGhosts * D; @@ -159,9 +163,11 @@ template struct VectorSoAContainer * * Free existing memory and reset the internal variables */ - __forceinline void attachReference(size_t n, size_t n_padded, T *ptr) + __forceinline void attachReference(size_t n, size_t n_padded, T* ptr) { - if(nAllocated) throw std::runtime_error("Pointer attaching is not allowed on VectorSoAContainer with allocated memory."); + if (nAllocated) + throw std::runtime_error( + "Pointer attaching is not allowed on VectorSoAContainer with allocated memory."); nAllocated = 0; nLocal = n; nGhosts = n_padded; @@ -177,51 +183,47 @@ template struct VectorSoAContainer * * The same sizes are assumed. */ - template - void copyIn(const ParticleAttrib> &in) + template + void copyIn(const ParticleAttrib>& in) { // if(nLocal!=in.size()) resize(in.size()); - PosAoS2SoA(nLocal, D, reinterpret_cast(in.first_address()), D, - myData, nGhosts); + PosAoS2SoA(nLocal, D, reinterpret_cast(in.first_address()), D, myData, nGhosts); } /** SoA to AoS : copy to ParticleAttrib<> * * The same sizes are assumed. */ - template - void copyOut(ParticleAttrib> &out) const + template + void copyOut(ParticleAttrib>& out) const { - PosSoA2AoS(nLocal, D, myData, nGhosts, - reinterpret_cast(out.first_address()), D); + PosSoA2AoS(nLocal, D, myData, nGhosts, reinterpret_cast(out.first_address()), D); } /** return TinyVector */ - __forceinline const Type_t operator[](size_t i) const - { - return Type_t(myData + i, nGhosts); - } + __forceinline const Type_t operator[](size_t i) const { return Type_t(myData + i, nGhosts); } /// helper class for operator ()(size_t i) to assign a value struct Accessor { size_t M; - T *_base; - __forceinline Accessor(T *a, size_t ng) : _base(a), M(ng) {} - __forceinline Accessor &operator=(const TinyVector &rhs) + T* _base; + __forceinline Accessor(T* a, size_t ng) : _base(a), M(ng) {} + __forceinline Accessor& operator=(const TinyVector& rhs) { - #pragma unroll - for (size_t i = 0; i < D; ++i) +#pragma unroll + for (size_t i = 0; i < D; ++i) *(_base + M * i) = rhs[i]; return *this; } /** asign value */ - template __forceinline Accessor &operator=(T1 rhs) + template + __forceinline Accessor& operator=(T1 rhs) { - #pragma unroll - for (size_t i = 0; i < D; ++i) +#pragma unroll + for (size_t i = 0; i < D; ++i) *(_base + M * i) = rhs; return *this; } @@ -231,33 +233,27 @@ template struct VectorSoAContainer * * Use for (*this)[i]=TinyVector; */ - __forceinline Accessor operator()(size_t i) - { - return Accessor(myData + i, nGhosts); - } + __forceinline Accessor operator()(size_t i) { return Accessor(myData + i, nGhosts); } /// return the base - __forceinline T *data() { return myData; } + __forceinline T* data() { return myData; } /// return the base - __forceinline const T *data() const { return myData; } + __forceinline const T* data() const { return myData; } /// return the pointer of the i-th components - __forceinline T *restrict data(size_t i) { return myData + i * nGhosts; } + __forceinline T* restrict data(size_t i) { return myData + i * nGhosts; } /// return the const pointer of the i-th components - __forceinline const T *restrict data(size_t i) const - { - return myData + i * nGhosts; - } + __forceinline const T* restrict data(size_t i) const { return myData + i * nGhosts; } /** serialization function */ - template - void serialize(Archive &ar, const unsigned int version) + template + void serialize(Archive& ar, const unsigned int version) { // ar & m_data; - ar &nLocal &nGhosts &myData; + ar& nLocal& nGhosts& myData; } }; // Incorrect: provide wrapper class // BOOST_CLASS_TRACKING(Pos3DSoA, boost::serialization::track_never) // BOOST_CLASS_TRACKING(Pos3DSoA, boost::serialization::track_never) -} +} // namespace qmcplusplus #endif diff --git a/src/Numerics/DeterminantOperators.h b/src/Numerics/DeterminantOperators.h index 1453433f9..239eb8223 100644 --- a/src/Numerics/DeterminantOperators.h +++ b/src/Numerics/DeterminantOperators.h @@ -35,58 +35,60 @@ namespace qmcplusplus { - /** LU factorization of double */ -inline void LUFactorization(int n, int m, double *restrict a, int n0, - int *restrict piv) +inline void LUFactorization(int n, int m, double* restrict a, int n0, int* restrict piv) { int status; dgetrf(n, m, a, n0, piv, status); } /** LU factorization of float */ -inline void LUFactorization(int n, int m, float *restrict a, const int &n0, - int *restrict piv) +inline void LUFactorization(int n, int m, float* restrict a, const int& n0, int* restrict piv) { int status; sgetrf(n, m, a, n0, piv, status); } /** LU factorization of std::complex */ -inline void LUFactorization(int n, int m, std::complex *restrict a, - int n0, int *restrict piv) +inline void LUFactorization(int n, int m, std::complex* restrict a, int n0, int* restrict piv) { int status; zgetrf(n, m, a, n0, piv, status); } /** LU factorization of complex */ -inline void LUFactorization(int n, int m, std::complex *restrict a, - int n0, int *restrict piv) +inline void LUFactorization(int n, int m, std::complex* restrict a, int n0, int* restrict piv) { int status; cgetrf(n, m, a, n0, piv, status); } /** Inversion of a double matrix after LU factorization*/ -inline void InvertLU(int n, double *restrict a, int n0, int *restrict piv, - double *restrict work, int n1) +inline void + InvertLU(int n, double* restrict a, int n0, int* restrict piv, double* restrict work, int n1) { int status; dgetri(n, a, n0, piv, work, n1, status); } /** Inversion of a float matrix after LU factorization*/ -inline void InvertLU(const int &n, float *restrict a, const int &n0, - int *restrict piv, float *restrict work, const int &n1) +inline void InvertLU(const int& n, + float* restrict a, + const int& n0, + int* restrict piv, + float* restrict work, + const int& n1) { int status; sgetri(n, a, n0, piv, work, n1, status); } /** Inversion of a std::complex matrix after LU factorization*/ -inline void InvertLU(int n, std::complex *restrict a, int n0, - int *restrict piv, std::complex *restrict work, +inline void InvertLU(int n, + std::complex* restrict a, + int n0, + int* restrict piv, + std::complex* restrict work, int n1) { int status; @@ -94,17 +96,19 @@ inline void InvertLU(int n, std::complex *restrict a, int n0, } /** Inversion of a complex matrix after LU factorization*/ -inline void InvertLU(int n, std::complex *restrict a, int n0, - int *restrict piv, std::complex *restrict work, +inline void InvertLU(int n, + std::complex* restrict a, + int n0, + int* restrict piv, + std::complex* restrict work, int n1) { int status; cgetri(n, a, n0, piv, work, n1, status); } -template -inline T InvertWithLog(T *restrict x, int n, int m, T *restrict work, - int *restrict pivot, T &phase) +template +inline T InvertWithLog(T* restrict x, int n, int m, T* restrict work, int* restrict pivot, T& phase) { T logdet(0.0); LUFactorization(n, m, x, n, pivot); @@ -120,10 +124,13 @@ inline T InvertWithLog(T *restrict x, int n, int m, T *restrict work, return logdet; } -template -inline T InvertWithLog(std::complex *restrict x, int n, int m, - std::complex *restrict work, int *restrict pivot, - T &phase) +template +inline T InvertWithLog(std::complex* restrict x, + int n, + int m, + std::complex* restrict work, + int* restrict pivot, + T& phase) { T logdet(0.0); LUFactorization(n, m, x, n, pivot); @@ -132,9 +139,9 @@ inline T InvertWithLog(std::complex *restrict x, int n, int m, { int ii = i * m + i; phase += std::arg(x[ii]); - if (pivot[i] != i + 1) phase += M_PI; - logdet += - std::log(x[ii].real() * x[ii].real() + x[ii].imag() * x[ii].imag()); + if (pivot[i] != i + 1) + phase += M_PI; + logdet += std::log(x[ii].real() * x[ii].real() + x[ii].imag() * x[ii].imag()); // slightly smaller error with the following // logdet+=2.0*std::log(std::abs(x[ii]); } @@ -149,9 +156,8 @@ inline T InvertWithLog(std::complex *restrict x, int n, int m, * \param getdet bool, if true, calculate the determinant * \return the determinant */ -template -inline typename MatrixA::value_type invert_matrix(MatrixA &M, - bool getdet = true) +template +inline typename MatrixA::value_type invert_matrix(MatrixA& M, bool getdet = true) { typedef typename MatrixA::value_type value_type; const int n = M.rows(); @@ -165,7 +171,8 @@ inline typename MatrixA::value_type invert_matrix(MatrixA &M, int sign = 1; for (int i = 0; i < n; ++i) { - if (pivot[i] != i + 1) sign *= -1; + if (pivot[i] != i + 1) + sign *= -1; det0 *= M(i, i); } det0 *= static_cast(sign); @@ -173,5 +180,5 @@ inline typename MatrixA::value_type invert_matrix(MatrixA &M, InvertLU(n, M.data(), n, pivot, work, n); return det0; } -} +} // namespace qmcplusplus #endif diff --git a/src/Numerics/Einspline/bspline_base.h b/src/Numerics/Einspline/bspline_base.h index 6d8d44e1b..daae5c99f 100644 --- a/src/Numerics/Einspline/bspline_base.h +++ b/src/Numerics/Einspline/bspline_base.h @@ -40,7 +40,15 @@ typedef std::complex complex_double; //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// -typedef enum { PERIODIC, DERIV1, DERIV2, FLAT, NATURAL, ANTIPERIODIC } bc_code; +typedef enum +{ + PERIODIC, + DERIV1, + DERIV2, + FLAT, + NATURAL, + ANTIPERIODIC +} bc_code; // clang-format off typedef enum { U1D , U2D , U3D , NU1D , NU2D , NU3D , @@ -88,7 +96,7 @@ typedef struct { spline_code sp_code; type_code t_code; - void *restrict coefs; + void* restrict coefs; } Bspline; #endif diff --git a/src/Numerics/Einspline/bspline_structs.h b/src/Numerics/Einspline/bspline_structs.h index 94769e7dc..24097e940 100644 --- a/src/Numerics/Einspline/bspline_structs.h +++ b/src/Numerics/Einspline/bspline_structs.h @@ -29,7 +29,7 @@ typedef struct { spline_code spcode; type_code tcode; - float *restrict coefs; + float* restrict coefs; Ugrid x_grid; BCtype_s xBC; } UBspline_1d_s; @@ -38,7 +38,7 @@ typedef struct { spline_code spcode; type_code tcode; - float *restrict coefs; + float* restrict coefs; int x_stride; Ugrid x_grid, y_grid; BCtype_s xBC, yBC; @@ -48,7 +48,7 @@ typedef struct { spline_code spcode; type_code tcode; - float *restrict coefs; + float* restrict coefs; int x_stride, y_stride; Ugrid x_grid, y_grid, z_grid; BCtype_s xBC, yBC, zBC; @@ -62,7 +62,7 @@ typedef struct { spline_code spcode; type_code tcode; - double *restrict coefs; + double* restrict coefs; Ugrid x_grid; BCtype_d xBC; } UBspline_1d_d; @@ -71,7 +71,7 @@ typedef struct { spline_code spcode; type_code tcode; - double *restrict coefs; + double* restrict coefs; int x_stride; Ugrid x_grid, y_grid; BCtype_d xBC, yBC; @@ -81,7 +81,7 @@ typedef struct { spline_code spcode; type_code tcode; - double *restrict coefs; + double* restrict coefs; int x_stride, y_stride; Ugrid x_grid, y_grid, z_grid; BCtype_d xBC, yBC, zBC; @@ -95,7 +95,7 @@ typedef struct { spline_code spcode; type_code tcode; - complex_float *restrict coefs; + complex_float* restrict coefs; Ugrid x_grid; BCtype_c xBC; } UBspline_1d_c; @@ -104,7 +104,7 @@ typedef struct { spline_code spcode; type_code tcode; - complex_float *restrict coefs; + complex_float* restrict coefs; int x_stride; Ugrid x_grid, y_grid; BCtype_c xBC, yBC; @@ -114,7 +114,7 @@ typedef struct { spline_code spcode; type_code tcode; - complex_float *restrict coefs; + complex_float* restrict coefs; int x_stride, y_stride; Ugrid x_grid, y_grid, z_grid; BCtype_c xBC, yBC, zBC; @@ -128,7 +128,7 @@ typedef struct { spline_code spcode; type_code tcode; - complex_double *restrict coefs; + complex_double* restrict coefs; Ugrid x_grid; BCtype_z xBC; } UBspline_1d_z; @@ -137,7 +137,7 @@ typedef struct { spline_code spcode; type_code tcode; - complex_double *restrict coefs; + complex_double* restrict coefs; int x_stride; Ugrid x_grid, y_grid; BCtype_z xBC, yBC; @@ -147,7 +147,7 @@ typedef struct { spline_code spcode; type_code tcode; - complex_double *restrict coefs; + complex_double* restrict coefs; int x_stride, y_stride; Ugrid x_grid, y_grid, z_grid; BCtype_z xBC, yBC, zBC; diff --git a/src/Numerics/Einspline/multi_bspline_structs.h b/src/Numerics/Einspline/multi_bspline_structs.h index 0e2829d8b..25ee7cc93 100644 --- a/src/Numerics/Einspline/multi_bspline_structs.h +++ b/src/Numerics/Einspline/multi_bspline_structs.h @@ -31,7 +31,7 @@ typedef struct { spline_code spcode; type_code tcode; - float *restrict coefs; + float* restrict coefs; intptr_t x_stride; Ugrid x_grid; BCtype_s xBC; @@ -43,7 +43,7 @@ typedef struct { spline_code spcode; type_code tcode; - float *restrict coefs; + float* restrict coefs; intptr_t x_stride, y_stride; Ugrid x_grid, y_grid; BCtype_s xBC, yBC; @@ -54,7 +54,7 @@ typedef struct { spline_code spcode; type_code tcode; - float *restrict coefs; + float* restrict coefs; intptr_t x_stride, y_stride, z_stride; Ugrid x_grid, y_grid, z_grid; BCtype_s xBC, yBC, zBC; @@ -69,7 +69,7 @@ typedef struct { spline_code spcode; type_code tcode; - double *restrict coefs; + double* restrict coefs; intptr_t x_stride; Ugrid x_grid; BCtype_d xBC; @@ -81,7 +81,7 @@ typedef struct { spline_code spcode; type_code tcode; - double *restrict coefs; + double* restrict coefs; intptr_t x_stride, y_stride; Ugrid x_grid, y_grid; BCtype_d xBC, yBC; @@ -92,7 +92,7 @@ typedef struct { spline_code spcode; type_code tcode; - double *restrict coefs; + double* restrict coefs; intptr_t x_stride, y_stride, z_stride; Ugrid x_grid, y_grid, z_grid; BCtype_d xBC, yBC, zBC; @@ -107,7 +107,7 @@ typedef struct { spline_code spcode; type_code tcode; - complex_float *restrict coefs; + complex_float* restrict coefs; intptr_t x_stride; Ugrid x_grid; BCtype_c xBC; @@ -119,27 +119,27 @@ typedef struct { spline_code spcode; type_code tcode; - complex_float *restrict coefs; + complex_float* restrict coefs; intptr_t x_stride, y_stride; Ugrid x_grid, y_grid; BCtype_c xBC, yBC; int num_splines; // temporary storage for laplacian components - complex_float *restrict lapl2; + complex_float* restrict lapl2; } multi_UBspline_2d_c; typedef struct { spline_code spcode; type_code tcode; - complex_float *restrict coefs; + complex_float* restrict coefs; intptr_t x_stride, y_stride, z_stride; Ugrid x_grid, y_grid, z_grid; BCtype_c xBC, yBC, zBC; int num_splines; size_t coefs_size; // temporary storage for laplacian components - complex_float *restrict lapl3; + complex_float* restrict lapl3; } multi_UBspline_3d_c; ////////////////////////////// @@ -149,7 +149,7 @@ typedef struct { spline_code spcode; type_code tcode; - complex_double *restrict coefs; + complex_double* restrict coefs; intptr_t x_stride; Ugrid x_grid; BCtype_z xBC; @@ -161,27 +161,27 @@ typedef struct { spline_code spcode; type_code tcode; - complex_double *restrict coefs; + complex_double* restrict coefs; intptr_t x_stride, y_stride; Ugrid x_grid, y_grid; BCtype_z xBC, yBC; int num_splines; // temporary storage for laplacian components - complex_double *restrict lapl2; + complex_double* restrict lapl2; } multi_UBspline_2d_z; typedef struct { spline_code spcode; type_code tcode; - complex_double *restrict coefs; + complex_double* restrict coefs; intptr_t x_stride, y_stride, z_stride; Ugrid x_grid, y_grid, z_grid; BCtype_z xBC, yBC, zBC; int num_splines; size_t coefs_size; // temporary storage for laplacian components - complex_double *restrict lapl3; + complex_double* restrict lapl3; } multi_UBspline_3d_z; #endif diff --git a/src/Numerics/OhmmsBlas.h b/src/Numerics/OhmmsBlas.h index 4c7a1ec29..a4fa6102b 100644 --- a/src/Numerics/OhmmsBlas.h +++ b/src/Numerics/OhmmsBlas.h @@ -44,7 +44,6 @@ */ struct BLAS { - static const int INCX = 1; static const int INCY = 1; static const char UPLO = 'L'; @@ -59,209 +58,272 @@ struct BLAS static const std::complex zone; static const std::complex zzero; - inline static void axpy(int n, double x, const double *a, double *b) + inline static void axpy(int n, double x, const double* a, double* b) { daxpy(n, x, a, INCX, b, INCY); } - inline static void axpy(int n, double x, const double *a, int incx, double *b, - int incy) + inline static void axpy(int n, double x, const double* a, int incx, double* b, int incy) { daxpy(n, x, a, incx, b, incy); } - inline static void axpy(int n, const double *a, double *b) - { - daxpy(n, done, a, INCX, b, INCY); - } + inline static void axpy(int n, const double* a, double* b) { daxpy(n, done, a, INCX, b, INCY); } - inline static void axpy(int n, float x, const float *a, int incx, float *b, - int incy) + inline static void axpy(int n, float x, const float* a, int incx, float* b, int incy) { saxpy(n, x, a, incx, b, incy); } - inline static void axpy(int n, const std::complex x, - const std::complex *a, int incx, - std::complex *b, int incy) + inline static void axpy(int n, + const std::complex x, + const std::complex* a, + int incx, + std::complex* b, + int incy) { caxpy(n, x, a, incx, b, incy); } - inline static void axpy(int n, const std::complex x, - const std::complex *a, int incx, - std::complex *b, int incy) + inline static void axpy(int n, + const std::complex x, + const std::complex* a, + int incx, + std::complex* b, + int incy) { zaxpy(n, x, a, incx, b, incy); } - inline static double norm2(int n, const double *a, int incx = 1) - { - return dnrm2(n, a, incx); - } + inline static double norm2(int n, const double* a, int incx = 1) { return dnrm2(n, a, incx); } - inline static double norm2(int n, const std::complex *a, int incx = 1) + inline static double norm2(int n, const std::complex* a, int incx = 1) { return dznrm2(n, a, incx); } - inline static float norm2(int n, const float *a, int incx = 1) - { - return snrm2(n, a, incx); - } + inline static float norm2(int n, const float* a, int incx = 1) { return snrm2(n, a, incx); } - inline static void scal(int n, double alpha, double *x) - { - dscal(n, alpha, x, INCX); - } + inline static void scal(int n, double alpha, double* x) { dscal(n, alpha, x, INCX); } // inline static // void gemv(char trans, int n, int m, const double* amat, const double* x, // double* y) { // dgemv(trans, n, m, done, amat, n, x, INCX, dzero, y, INCY); //} - inline static void gemv(int n, int m, const double *restrict amat, - const double *restrict x, double *restrict y) + inline static void + gemv(int n, int m, const double* restrict amat, const double* restrict x, double* restrict y) { dgemv(NOTRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void gemv(int n, int m, const float *restrict amat, - const float *restrict x, float *restrict y) + inline static void + gemv(int n, int m, const float* restrict amat, const float* restrict x, float* restrict y) { sgemv(NOTRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void gemv_trans(int n, int m, const double *restrict amat, - const double *restrict x, double *restrict y) + inline static void + gemv_trans(int n, int m, const double* restrict amat, const double* restrict x, double* restrict y) { dgemv(TRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void gemv_trans(int n, int m, const float *restrict amat, - const float *restrict x, float *restrict y) + inline static void + gemv_trans(int n, int m, const float* restrict amat, const float* restrict x, float* restrict y) { sgemv(TRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void gemv_trans(int n, int m, - const std::complex *restrict amat, - const std::complex *restrict x, - std::complex *restrict y) + inline static void gemv_trans(int n, + int m, + const std::complex* restrict amat, + const std::complex* restrict x, + std::complex* restrict y) { zgemv(TRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void gemv_trans(int n, int m, - const std::complex *restrict amat, - const std::complex *restrict x, - std::complex *restrict y) + inline static void gemv_trans(int n, + int m, + const std::complex* restrict amat, + const std::complex* restrict x, + std::complex* restrict y) { cgemv(TRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void gemv(int n, int m, - const std::complex *restrict amat, - const std::complex *restrict x, - std::complex *restrict y) + inline static void gemv(int n, + int m, + const std::complex* restrict amat, + const std::complex* restrict x, + std::complex* restrict y) { zgemv(NOTRANS, m, n, zone, amat, m, x, INCX, zzero, y, INCY); } - inline static void gemv(char trans_in, int n, int m, double alpha, - const double *restrict amat, int lda, const double *x, - int incx, double beta, double *y, int incy) + inline static void gemv(char trans_in, + int n, + int m, + double alpha, + const double* restrict amat, + int lda, + const double* x, + int incx, + double beta, + double* y, + int incy) { dgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } - inline static void gemv(char trans_in, int n, int m, float alpha, - const float *restrict amat, int lda, const float *x, - int incx, float beta, float *y, int incy) + inline static void gemv(char trans_in, + int n, + int m, + float alpha, + const float* restrict amat, + int lda, + const float* x, + int incx, + float beta, + float* y, + int incy) { sgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } - inline static void gemv(char trans_in, int n, int m, - const std::complex &alpha, - const std::complex *restrict amat, int lda, - const std::complex *restrict x, int incx, - const std::complex &beta, - std::complex *y, int incy) + inline static void gemv(char trans_in, + int n, + int m, + const std::complex& alpha, + const std::complex* restrict amat, + int lda, + const std::complex* restrict x, + int incx, + const std::complex& beta, + std::complex* y, + int incy) { zgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } - inline static void gemv(char trans_in, int n, int m, - const std::complex &alpha, - const std::complex *restrict amat, int lda, - const std::complex *restrict x, int incx, - const std::complex &beta, - std::complex *y, int incy) + inline static void gemv(char trans_in, + int n, + int m, + const std::complex& alpha, + const std::complex* restrict amat, + int lda, + const std::complex* restrict x, + int incx, + const std::complex& beta, + std::complex* y, + int incy) { cgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } #if defined(HAVE_MKL) - inline static void gemv(char trans_in, int n, int m, - const std::complex &alpha, - const double *restrict amat, int lda, - const std::complex *restrict x, int incx, - const std::complex &beta, - std::complex *y, int incy) + inline static void gemv(char trans_in, + int n, + int m, + const std::complex& alpha, + const double* restrict amat, + int lda, + const std::complex* restrict x, + int incx, + const std::complex& beta, + std::complex* y, + int incy) { dzgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } - inline static void gemv(char trans_in, int n, int m, - const std::complex &alpha, - const float *restrict amat, int lda, - const std::complex *restrict x, int incx, - const std::complex &beta, - std::complex *y, int incy) + inline static void gemv(char trans_in, + int n, + int m, + const std::complex& alpha, + const float* restrict amat, + int lda, + const std::complex* restrict x, + int incx, + const std::complex& beta, + std::complex* y, + int incy) { scgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } #endif - inline static void gemm(char Atrans, char Btrans, int M, int N, int K, - double alpha, const double *A, int lda, - const double *restrict B, int ldb, double beta, - double *restrict C, int ldc) + inline static void gemm(char Atrans, + char Btrans, + int M, + int N, + int K, + double alpha, + const double* A, + int lda, + const double* restrict B, + int ldb, + double beta, + double* restrict C, + int ldc) { dgemm(Atrans, Btrans, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } - inline static void gemm(char Atrans, char Btrans, int M, int N, int K, - float alpha, const float *A, int lda, - const float *restrict B, int ldb, float beta, - float *restrict C, int ldc) + inline static void gemm(char Atrans, + char Btrans, + int M, + int N, + int K, + float alpha, + const float* A, + int lda, + const float* restrict B, + int ldb, + float beta, + float* restrict C, + int ldc) { sgemm(Atrans, Btrans, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } - inline static void gemm(char Atrans, char Btrans, int M, int N, int K, + inline static void gemm(char Atrans, + char Btrans, + int M, + int N, + int K, std::complex alpha, - const std::complex *A, int lda, - const std::complex *restrict B, int ldb, + const std::complex* A, + int lda, + const std::complex* restrict B, + int ldb, std::complex beta, - std::complex *restrict C, int ldc) + std::complex* restrict C, + int ldc) { zgemm(Atrans, Btrans, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } - inline static void gemm(char Atrans, char Btrans, int M, int N, int K, + inline static void gemm(char Atrans, + char Btrans, + int M, + int N, + int K, std::complex alpha, - const std::complex *A, int lda, - const std::complex *restrict B, int ldb, + const std::complex* A, + int lda, + const std::complex* restrict B, + int ldb, std::complex beta, - std::complex *restrict C, int ldc) + std::complex* restrict C, + int ldc) { cgemm(Atrans, Btrans, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } - template - inline static T dot(int n, const T *restrict a, const T *restrict b) + template + inline static T dot(int n, const T* restrict a, const T* restrict b) { T res = T(0); for (int i = 0; i < n; ++i) @@ -269,9 +331,8 @@ struct BLAS return res; } - template - inline static std::complex dot(int n, const std::complex *restrict a, - const T *restrict b) + template + inline static std::complex dot(int n, const std::complex* restrict a, const T* restrict b) { std::complex res = T(0); for (int i = 0; i < n; ++i) @@ -279,9 +340,9 @@ struct BLAS return res; } - template - inline static std::complex dot(int n, const std::complex *restrict a, - const std::complex *restrict b) + template + inline static std::complex + dot(int n, const std::complex* restrict a, const std::complex* restrict b) { std::complex res = 0.0; for (int i = 0; i < n; ++i) @@ -289,9 +350,8 @@ struct BLAS return res; } - template - inline static std::complex dot(int n, const T *restrict a, - const std::complex *restrict b) + template + inline static std::complex dot(int n, const T* restrict a, const std::complex* restrict b) { std::complex res = 0.0; for (int i = 0; i < n; ++i) @@ -299,8 +359,8 @@ struct BLAS return res; } - template - inline static void copy(int n, const T *restrict a, T *restrict b) + template + inline static void copy(int n, const T* restrict a, T* restrict b) { memcpy(b, a, sizeof(T) * n); } @@ -310,61 +370,68 @@ struct BLAS * @param source starting address of the source * @param number of elements to copy */ - template - inline static void copy(T *restrict target, const T *restrict source, int n) + template + inline static void copy(T* restrict target, const T* restrict source, int n) { memcpy(target, source, sizeof(T) * n); } - template - inline static void copy(int n, const std::complex *restrict a, - T *restrict b) + template + inline static void copy(int n, const std::complex* restrict a, T* restrict b) { for (int i = 0; i < n; ++i) - b[i] = a[i].real(); + b[i] = a[i].real(); } - template - inline static void copy(int n, const T *restrict a, - std::complex *restrict b) + template + inline static void copy(int n, const T* restrict a, std::complex* restrict b) { for (int i = 0; i < n; ++i) - b[i] = a[i]; + b[i] = a[i]; } - template - inline static void copy(int n, const T *restrict x, int incx, T *restrict y, - int incy) + template + inline static void copy(int n, const T* restrict x, int incx, T* restrict y, int incy) { const int xmax = incx * n; for (int ic = 0, jc = 0; ic < xmax; ic += incx, jc += incy) y[jc] = x[ic]; } - inline static void ger(int m, int n, double alpha, const double *x, int incx, - const double *y, int incy, double *a, int lda) + inline static void + ger(int m, int n, double alpha, const double* x, int incx, const double* y, int incy, double* a, int lda) { dger(&m, &n, &alpha, x, &incx, y, &incy, a, &lda); } - inline static void ger(int m, int n, float alpha, const float *x, int incx, - const float *y, int incy, float *a, int lda) + inline static void + ger(int m, int n, float alpha, const float* x, int incx, const float* y, int incy, float* a, int lda) { sger(&m, &n, &alpha, x, &incx, y, &incy, a, &lda); } - inline static void ger(int m, int n, const std::complex &alpha, - const std::complex *x, int incx, - const std::complex *y, int incy, - std::complex *a, int lda) + inline static void ger(int m, + int n, + const std::complex& alpha, + const std::complex* x, + int incx, + const std::complex* y, + int incy, + std::complex* a, + int lda) { zgeru(&m, &n, &alpha, x, &incx, y, &incy, a, &lda); } - inline static void ger(int m, int n, const std::complex &alpha, - const std::complex *x, int incx, - const std::complex *y, int incy, - std::complex *a, int lda) + inline static void ger(int m, + int n, + const std::complex& alpha, + const std::complex* x, + int incx, + const std::complex* y, + int incy, + std::complex* a, + int lda) { cgeru(&m, &n, &alpha, x, &incx, y, &incy, a, &lda); } @@ -372,55 +439,118 @@ struct BLAS struct LAPACK { - - inline static void gesvd(char *jobu, char *jobvt, int *m, int *n, float *a, - int *lda, float *s, float *u, int *ldu, float *vt, - int *ldvt, float *work, int *lwork, int *info) + inline static void gesvd(char* jobu, + char* jobvt, + int* m, + int* n, + float* a, + int* lda, + float* s, + float* u, + int* ldu, + float* vt, + int* ldvt, + float* work, + int* lwork, + int* info) { sgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info); } - inline static void gesvd(char *jobu, char *jobvt, int *m, int *n, double *a, - int *lda, double *s, double *u, int *ldu, double *vt, - int *ldvt, double *work, int *lwork, int *info) + inline static void gesvd(char* jobu, + char* jobvt, + int* m, + int* n, + double* a, + int* lda, + double* s, + double* u, + int* ldu, + double* vt, + int* ldvt, + double* work, + int* lwork, + int* info) { dgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info); } - inline static void geev(char *jobvl, char *jobvr, int *n, double *a, int *lda, - double *alphar, double *alphai, double *vl, int *ldvl, - double *vr, int *ldvr, double *work, int *lwork, - int *info) - { - dgeev(jobvl, jobvr, n, a, lda, alphar, alphai, vl, ldvl, vr, ldvr, work, - lwork, info); - } - - inline static void geev(char *jobvl, char *jobvr, int *n, float *a, int *lda, - float *alphar, float *alphai, float *vl, int *ldvl, - float *vr, int *ldvr, float *work, int *lwork, - int *info) - { - sgeev(jobvl, jobvr, n, a, lda, alphar, alphai, vl, ldvl, vr, ldvr, work, - lwork, info); - } - - inline static void ggev(char *jobvl, char *jobvr, int *n, double *a, int *lda, - double *b, int *ldb, double *alphar, double *alphai, - double *beta, double *vl, int *ldvl, double *vr, - int *ldvr, double *work, int *lwork, int *info) - { - dggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, - ldvr, work, lwork, info); - } - - inline static void ggev(char *jobvl, char *jobvr, int *n, float *a, int *lda, - float *b, int *ldb, float *alphar, float *alphai, - float *beta, float *vl, int *ldvl, float *vr, - int *ldvr, float *work, int *lwork, int *info) - { - sggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, - ldvr, work, lwork, info); + inline static void geev(char* jobvl, + char* jobvr, + int* n, + double* a, + int* lda, + double* alphar, + double* alphai, + double* vl, + int* ldvl, + double* vr, + int* ldvr, + double* work, + int* lwork, + int* info) + { + dgeev(jobvl, jobvr, n, a, lda, alphar, alphai, vl, ldvl, vr, ldvr, work, lwork, info); + } + + inline static void geev(char* jobvl, + char* jobvr, + int* n, + float* a, + int* lda, + float* alphar, + float* alphai, + float* vl, + int* ldvl, + float* vr, + int* ldvr, + float* work, + int* lwork, + int* info) + { + sgeev(jobvl, jobvr, n, a, lda, alphar, alphai, vl, ldvl, vr, ldvr, work, lwork, info); + } + + inline static void ggev(char* jobvl, + char* jobvr, + int* n, + double* a, + int* lda, + double* b, + int* ldb, + double* alphar, + double* alphai, + double* beta, + double* vl, + int* ldvl, + double* vr, + int* ldvr, + double* work, + int* lwork, + int* info) + { + dggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info); + } + + inline static void ggev(char* jobvl, + char* jobvr, + int* n, + float* a, + int* lda, + float* b, + int* ldb, + float* alphar, + float* alphai, + float* beta, + float* vl, + int* ldvl, + float* vr, + int* ldvr, + float* work, + int* lwork, + int* info) + { + sggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info); } }; diff --git a/src/Numerics/OhmmsPETE/OhmmsArray.h b/src/Numerics/OhmmsPETE/OhmmsArray.h index 080881b73..de5faa994 100644 --- a/src/Numerics/OhmmsPETE/OhmmsArray.h +++ b/src/Numerics/OhmmsPETE/OhmmsArray.h @@ -27,9 +27,9 @@ #include #include -template struct Array +template +struct Array { - typedef T Type_t; typedef std::vector Container_t; typedef Array This_t; @@ -40,11 +40,12 @@ template struct Array // default constructor Array() { - for (int i = 0; i < D; i++) Length[i] = 0; + for (int i = 0; i < D; i++) + Length[i] = 0; } // copy constructor - Array(const Array &rhs) + Array(const Array& rhs) { resize(rhs); std::copy(rhs.begin(), rhs.end(), X.begin()); @@ -63,29 +64,38 @@ template struct Array Array(size_t l, size_t m, size_t n, size_t o) { resize(l, m, n, o); } // specialized for something like TinyVector - template Array(ST1 *dims) { resize(dims); } + template + Array(ST1* dims) + { + resize(dims); + } // do nothing Destructor ~Array() {} inline unsigned dim() const { return D; } - inline size_t *shape() const { return &Length[0]; } + inline size_t* shape() const { return &Length[0]; } inline size_t size() const { return X.size(); } inline size_t size(int i) const { return Length[i]; } - Container_t &storage() { return X; } + Container_t& storage() { return X; } - template void resize(const Array &rhs) + template + void resize(const Array& rhs) { X.resize(rhs.size()); - for (int i = 0; i < D; i++) Length[i] = rhs.Length[i]; + for (int i = 0; i < D; i++) + Length[i] = rhs.Length[i]; } - template void resize(ST1 *newdims) + template + void resize(ST1* newdims) { int ntot = 1; - for (int i = 0; i < D; ++i) ntot *= Length[i] = newdims[i]; - if (ntot == 0) return; + for (int i = 0; i < D; ++i) + ntot *= Length[i] = newdims[i]; + if (ntot == 0) + return; X.resize(ntot); } @@ -97,31 +107,28 @@ template struct Array inline typename Container_t::iterator begin() { return X.begin(); } inline typename Container_t::iterator end() { return X.end(); } - inline typename Container_t::const_iterator begin() const - { - return X.begin(); - } + inline typename Container_t::const_iterator begin() const { return X.begin(); } inline typename Container_t::const_iterator end() const { return X.end(); } - inline Type_t *data() { return &(X[0]); } + inline Type_t* data() { return &(X[0]); } - inline const Type_t *data() const { return &(X[0]); } + inline const Type_t* data() const { return &(X[0]); } - inline const Type_t *first_address() const { return &(X[0]); } + inline const Type_t* first_address() const { return &(X[0]); } - inline const Type_t *last_address() const { return &(X[0]) + X.size(); } + inline const Type_t* last_address() const { return &(X[0]) + X.size(); } - inline Type_t *first_address() { return &(X[0]); } + inline Type_t* first_address() { return &(X[0]); } - inline Type_t *last_address() { return &(X[0]) + X.size(); } + inline Type_t* last_address() { return &(X[0]) + X.size(); } - This_t &operator=(const T &rhs) + This_t& operator=(const T& rhs) { std::fill(X.begin(), X.end(), rhs); return *this; } - This_t &operator=(const Array &rhs) + This_t& operator=(const Array& rhs) { if (&rhs != this) { @@ -131,7 +138,8 @@ template struct Array return *this; } - template This_t &operator=(const Array &rhs) + template + This_t& operator=(const Array& rhs) { resize(rhs); std::copy(rhs.begin(), rhs.end(), X.begin()); @@ -139,15 +147,12 @@ template struct Array } // Get and Set Operations - inline Type_t &operator()(size_t i) { return X[i]; } + inline Type_t& operator()(size_t i) { return X[i]; } inline Type_t operator()(size_t i) const { return X[i]; } - inline Type_t &operator()(size_t i, size_t j) { return X[j + Length[1] * i]; } - inline Type_t operator()(size_t i, size_t j) const - { - return X[j + Length[1] * i]; - } - inline Type_t &operator()(size_t i, size_t j, size_t k) + inline Type_t& operator()(size_t i, size_t j) { return X[j + Length[1] * i]; } + inline Type_t operator()(size_t i, size_t j) const { return X[j + Length[1] * i]; } + inline Type_t& operator()(size_t i, size_t j, size_t k) { return X[k + Length[2] * (j + Length[1] * i)]; } @@ -155,7 +160,7 @@ template struct Array { return X[k + Length[2] * (j + Length[1] * i)]; } - inline Type_t &operator()(size_t i, size_t j, size_t k, size_t l) + inline Type_t& operator()(size_t i, size_t j, size_t k, size_t l) { return X[l + Length[3] * (k + Length[2] * (j + Length[1] * i))]; } @@ -167,26 +172,29 @@ template struct Array inline Type_t sum() { Type_t s = 0; - for (int i = 0; i < X.size(); ++i) s += X[i]; + for (int i = 0; i < X.size(); ++i) + s += X[i]; return s; } }; // need to assert -template void Array::resize(size_t n) +template +void Array::resize(size_t n) { Length[0] = n; X.resize(n, T()); } -template void Array::resize(size_t n, size_t m) +template +void Array::resize(size_t n, size_t m) { Length[0] = n; Length[1] = m; X.resize(n * m, T()); } -template +template void Array::resize(size_t l, size_t m, size_t n) { Length[0] = l; @@ -195,7 +203,7 @@ void Array::resize(size_t l, size_t m, size_t n) X.resize(l * m * n); //,T()); } -template +template void Array::resize(size_t l, size_t m, size_t n, size_t o) { Length[0] = l; diff --git a/src/Numerics/OhmmsPETE/OhmmsMatrix.h b/src/Numerics/OhmmsPETE/OhmmsMatrix.h index 4be5ae4d8..76b5559ed 100644 --- a/src/Numerics/OhmmsPETE/OhmmsMatrix.h +++ b/src/Numerics/OhmmsPETE/OhmmsMatrix.h @@ -25,21 +25,20 @@ namespace qmcplusplus { - -template > class Matrix +template> +class Matrix { public: typedef T Type_t; typedef T value_type; - typedef T *pointer; - typedef const T *const_pointer; + typedef T* pointer; + typedef const T* const_pointer; typedef Vector Container_t; typedef typename Container_t::size_type size_type; typedef typename Container_t::iterator iterator; typedef Matrix This_t; - Matrix() - : D1(0), D2(0), TotSize(0) {} // Default Constructor initializes to zero. + Matrix() : D1(0), D2(0), TotSize(0) {} // Default Constructor initializes to zero. Matrix(size_type n) { @@ -54,13 +53,10 @@ template > class Matrix } /** constructor with an initialized ref */ - inline Matrix(T *ref, size_type n, size_type m) - : D1(n), D2(m), TotSize(n * m), X(ref, n * m) - { - } + inline Matrix(T* ref, size_type n, size_type m) : D1(n), D2(m), TotSize(n * m), X(ref, n * m) {} // Copy Constructor - Matrix(const Matrix &rhs) { copy(rhs); } + Matrix(const Matrix& rhs) { copy(rhs); } // Destructor ~Matrix() {} @@ -80,20 +76,11 @@ template > class Matrix inline typename Container_t::iterator begin() { return X.begin(); } inline typename Container_t::iterator end() { return X.end(); } - inline typename Container_t::const_iterator begin() const - { - return X.begin(); - } + inline typename Container_t::const_iterator begin() const { return X.begin(); } inline typename Container_t::const_iterator end() const { return X.end(); } - inline typename Container_t::iterator begin(int i) - { - return X.begin() + i * D2; - } - inline typename Container_t::const_iterator begin(int i) const - { - return X.begin() + i * D2; - } + inline typename Container_t::iterator begin(int i) { return X.begin() + i * D2; } + inline typename Container_t::const_iterator begin(int i) const { return X.begin() + i * D2; } inline void resize(size_type n, size_type m) { @@ -107,9 +94,9 @@ template > class Matrix inline void free() { X.free(); } // Attach to pre-allocated memory - inline void attachReference(T *ref) { X.attachReference(ref, TotSize); } + inline void attachReference(T* ref) { X.attachReference(ref, TotSize); } - inline void attachReference(T *ref, size_type n, size_type m) + inline void attachReference(T* ref, size_type n, size_type m) { D1 = n; D2 = m; @@ -123,25 +110,23 @@ template > class Matrix D1 += n; } - inline void copy(const Matrix &rhs) + inline void copy(const Matrix& rhs) { resize(rhs.D1, rhs.D2); assign(*this, rhs); } // Assignment Operators - inline This_t &operator=(const Matrix &rhs) + inline This_t& operator=(const Matrix& rhs) { resize(rhs.D1, rhs.D2); return assign(*this, rhs); } - inline const This_t &operator=(const Matrix &rhs) const - { - return assign(*this, rhs); - } + inline const This_t& operator=(const Matrix& rhs) const { return assign(*this, rhs); } - template This_t &operator=(const RHS &rhs) + template + This_t& operator=(const RHS& rhs) { return assign(*this, rhs); } @@ -154,10 +139,10 @@ template > class Matrix inline const_pointer data() const { return X.data(); } // returns a const pointer of i-th row - inline const Type_t *data(size_type i) const { return X.data() + i * D2; } + inline const Type_t* data(size_type i) const { return X.data() + i * D2; } /// returns a pointer of i-th row, g++ iterator problem - inline Type_t *data(size_type i) { return X.data() + i * D2; } + inline Type_t* data(size_type i) { return X.data() + i * D2; } inline pointer first_address() { return X.data(); } @@ -167,29 +152,23 @@ template > class Matrix inline pointer last_address() { return X.data() + TotSize; } // returns a pointer of i-th row - inline const Type_t *last_address() const { return X.data() + TotSize; } + inline const Type_t* last_address() const { return X.data() + TotSize; } // returns a const pointer of i-th row - inline const Type_t *operator[](size_type i) const - { - return X.data() + i * D2; - } + inline const Type_t* operator[](size_type i) const { return X.data() + i * D2; } /// returns a pointer of i-th row, g++ iterator problem - inline Type_t *operator[](size_type i) { return X.data() + i * D2; } + inline Type_t* operator[](size_type i) { return X.data() + i * D2; } - inline Type_t &operator()(size_type i) { return X[i]; } + inline Type_t& operator()(size_type i) { return X[i]; } // returns the i-th value in D1*D2 vector inline Type_t operator()(size_type i) const { return X[i]; } // returns val(i,j) - inline Type_t &operator()(size_type i, size_type j) { return X[i * D2 + j]; } + inline Type_t& operator()(size_type i, size_type j) { return X[i * D2 + j]; } // returns val(i,j) - inline Type_t operator()(size_type i, size_type j) const - { - return X[i * D2 + j]; - } + inline Type_t operator()(size_type i, size_type j) const { return X[i * D2 + j]; } inline void swap_rows(int r1, int r2) { @@ -211,19 +190,22 @@ template > class Matrix } } - template inline void replaceRow(IT first, size_type i) + template + inline void replaceRow(IT first, size_type i) { std::copy(first, first + D2, X.begin() + i * D2); } - template inline void replaceColumn(IT first, size_type j) + template + inline void replaceColumn(IT first, size_type j) { typename Container_t::iterator ii(X.begin() + j); for (int i = 0; i < D1; i++, ii += D2) *ii = *first++; } - template inline void add2Column(IT first, size_type j) + template + inline void add2Column(IT first, size_type j) { typename Container_t::iterator ii(X.begin() + j); for (int i = 0; i < D1; i++, ii += D2) @@ -237,9 +219,8 @@ template > class Matrix * \param i0 starting row where the copying is done * \param j0 starting column where the copying is done */ - template - inline void add(const T1 *sub, size_type d1, size_type d2, size_type i0, - size_type j0) + template + inline void add(const T1* sub, size_type d1, size_type d2, size_type i0, size_type j0) { int ii = 0; for (int i = 0; i < d1; i++) @@ -252,9 +233,8 @@ template > class Matrix } } - template - inline void add(const T1 *sub, size_type d1, size_type d2, size_type i0, - size_type j0, const T &phi) + template + inline void add(const T1* sub, size_type d1, size_type d2, size_type i0, size_type j0, const T& phi) { size_type ii = 0; for (size_type i = 0; i < d1; i++) @@ -266,8 +246,8 @@ template > class Matrix } } } - template - inline void add(const SubMat_t &sub, unsigned int i0, unsigned int j0) + template + inline void add(const SubMat_t& sub, unsigned int i0, unsigned int j0) { size_type ii = 0; for (size_type i = 0; i < sub.rows(); i++) @@ -279,7 +259,7 @@ template > class Matrix } } } - inline void add(const This_t &sub, unsigned int i0, unsigned int j0) + inline void add(const This_t& sub, unsigned int i0, unsigned int j0) { size_type ii = 0; for (size_type i = 0; i < sub.rows(); i++) @@ -292,13 +272,15 @@ template > class Matrix } } - template inline Msg &putMessage(Msg &m) + template + inline Msg& putMessage(Msg& m) { m.Pack(X.data(), D1 * D2); return m; } - template inline Msg &getMessage(Msg &m) + template + inline Msg& getMessage(Msg& m) { m.Unpack(X.data(), D1 * D2); return m; @@ -311,8 +293,8 @@ template > class Matrix }; // I/O -template -std::ostream &operator<<(std::ostream &out, const Matrix &rhs) +template +std::ostream& operator<<(std::ostream& out, const Matrix& rhs) { typedef typename Matrix::size_type size_type; size_type ii = 0; @@ -325,8 +307,8 @@ std::ostream &operator<<(std::ostream &out, const Matrix &rhs) return out; } -template -std::istream &operator>>(std::istream &is, Matrix &rhs) +template +std::istream& operator>>(std::istream& is, Matrix& rhs) { typedef typename Matrix::size_type size_type; size_type ii = 0; @@ -340,10 +322,11 @@ std::istream &operator>>(std::istream &is, Matrix &rhs) // We need to specialize CreateLeaf for our class, so that operators // know what to stick in the leaves of the expression tree. //----------------------------------------------------------------------------- -template struct CreateLeaf> +template +struct CreateLeaf> { typedef Reference> Leaf_t; - inline static Leaf_t make(const Matrix &a) { return Leaf_t(a); } + inline static Leaf_t make(const Matrix& a) { return Leaf_t(a); } }; //----------------------------------------------------------------------------- @@ -357,34 +340,30 @@ class SizeLeaf2 typedef int size_type; SizeLeaf2(size_type s, size_type p) : size_m(s), size_n(p) {} - SizeLeaf2(const SizeLeaf2 &model) : size_m(model.size_m), size_n(model.size_n) - { - } + SizeLeaf2(const SizeLeaf2& model) : size_m(model.size_m), size_n(model.size_n) {} - bool operator()(size_type s, size_type p) const - { - return ((size_m == s) && (size_n == p)); - } + bool operator()(size_type s, size_type p) const { return ((size_m == s) && (size_n == p)); } private: size_type size_m, size_n; }; -template struct LeafFunctor, SizeLeaf2> +template +struct LeafFunctor, SizeLeaf2> { typedef bool Type_t; - inline static bool apply(const Scalar &, const SizeLeaf2 &) + inline static bool apply(const Scalar&, const SizeLeaf2&) { // Scalars always conform. return true; } }; -template +template struct LeafFunctor, SizeLeaf2> { typedef bool Type_t; - inline static bool apply(const Matrix &v, const SizeLeaf2 &s) + inline static bool apply(const Matrix& v, const SizeLeaf2& s) { return s(v.rows(), v.cols()); } @@ -408,11 +387,11 @@ struct LeafFunctor, SizeLeaf2> // EvalLeaf2 is used to evaluate expression with matrices. // (It's already defined for Scalar values.) //----------------------------------------------------------------------------- -template +template struct LeafFunctor, EvalLeaf2> { typedef T Type_t; - inline static Type_t apply(const Matrix &mat, const EvalLeaf2 &f) + inline static Type_t apply(const Matrix& mat, const EvalLeaf2& f) { return mat(f.val1(), f.val2()); } @@ -421,9 +400,8 @@ struct LeafFunctor, EvalLeaf2> /////////////////////////////////////////////////////////////////////////////// // LOOP is done by evaluate function /////////////////////////////////////////////////////////////////////////////// -template -inline void evaluate(Matrix &lhs, const Op &op, - const Expression &rhs) +template +inline void evaluate(Matrix& lhs, const Op& op, const Expression& rhs) { if (forEach(rhs, SizeLeaf2(lhs.rows(), lhs.cols()), AndCombine())) { @@ -440,8 +418,7 @@ inline void evaluate(Matrix &lhs, const Op &op, } else { - std::cerr << "Error: LHS and RHS don't conform in OhmmsMatrix." - << std::endl; + std::cerr << "Error: LHS and RHS don't conform in OhmmsMatrix." << std::endl; abort(); } } diff --git a/src/Numerics/OhmmsPETE/OhmmsMatrixOperators.h b/src/Numerics/OhmmsPETE/OhmmsMatrixOperators.h index a3eda1bb9..3f2e53c89 100644 --- a/src/Numerics/OhmmsPETE/OhmmsMatrixOperators.h +++ b/src/Numerics/OhmmsPETE/OhmmsMatrixOperators.h @@ -19,44 +19,38 @@ namespace qmcplusplus { - -template -inline Matrix &assign(Matrix &lhs, const RHS &rhs) +template +inline Matrix& assign(Matrix& lhs, const RHS& rhs) { typedef typename CreateLeaf::Leaf_t Leaf_t; - evaluate(lhs, OpAssign(), - MakeReturn::make(CreateLeaf::make(rhs))); + evaluate(lhs, OpAssign(), MakeReturn::make(CreateLeaf::make(rhs))); return lhs; } -template -inline Matrix &operator+=(Matrix &lhs, const RHS &rhs) +template +inline Matrix& operator+=(Matrix& lhs, const RHS& rhs) { typedef typename CreateLeaf::Leaf_t Leaf_t; - evaluate(lhs, OpAddAssign(), - MakeReturn::make(CreateLeaf::make(rhs))); + evaluate(lhs, OpAddAssign(), MakeReturn::make(CreateLeaf::make(rhs))); return lhs; } -template -inline Matrix &operator-=(Matrix &lhs, const RHS &rhs) +template +inline Matrix& operator-=(Matrix& lhs, const RHS& rhs) { typedef typename CreateLeaf::Leaf_t Leaf_t; - evaluate(lhs, OpSubtractAssign(), - MakeReturn::make(CreateLeaf::make(rhs))); + evaluate(lhs, OpSubtractAssign(), MakeReturn::make(CreateLeaf::make(rhs))); return lhs; } -template -inline Matrix &operator*=(Matrix &lhs, const RHS &rhs) +template +inline Matrix& operator*=(Matrix& lhs, const RHS& rhs) { typedef typename CreateLeaf::Leaf_t Leaf_t; - evaluate(lhs, OpMultiplyAssign(), - MakeReturn::make(CreateLeaf::make(rhs))); + evaluate(lhs, OpMultiplyAssign(), MakeReturn::make(CreateLeaf::make(rhs))); return lhs; } -} +} // namespace qmcplusplus #endif // OHMMS_MATRIXOPERATOR_H - diff --git a/src/Numerics/OhmmsPETE/OhmmsVector.h b/src/Numerics/OhmmsPETE/OhmmsVector.h index f9f1cfc54..fa6d5305b 100644 --- a/src/Numerics/OhmmsPETE/OhmmsVector.h +++ b/src/Numerics/OhmmsPETE/OhmmsVector.h @@ -28,21 +28,20 @@ namespace qmcplusplus { - -template > class Vector +template> +class Vector { public: typedef T Type_t; - typedef T *iterator; - typedef const T *const_iterator; + typedef T* iterator; + typedef const T* const_iterator; typedef typename Alloc::size_type size_type; typedef typename Alloc::pointer pointer; typedef typename Alloc::const_pointer const_pointer; typedef Vector This_t; /** constructor with size n*/ - explicit inline Vector(size_t n = 0, Type_t val = Type_t()) - : nLocal(n), nAllocated(0), X(nullptr) + explicit inline Vector(size_t n = 0, Type_t val = Type_t()) : nLocal(n), nAllocated(0), X(nullptr) { if (n) { @@ -52,38 +51,42 @@ template > class Vector } /** constructor with an initialized ref */ - explicit inline Vector(T *ref, size_t n) : nLocal(n), nAllocated(0), X(ref) {} + explicit inline Vector(T* ref, size_t n) : nLocal(n), nAllocated(0), X(ref) {} /** copy constructor */ - Vector(const Vector &rhs) : nLocal(rhs.nLocal), nAllocated(0), X(nullptr) + Vector(const Vector& rhs) : nLocal(rhs.nLocal), nAllocated(0), X(nullptr) { resize_impl(rhs.nLocal); std::copy_n(rhs.data(), nLocal, X); } // default assignment operator - inline Vector &operator=(const Vector &rhs) + inline Vector& operator=(const Vector& rhs) { - if (this == &rhs) return *this; - if (nLocal != rhs.nLocal) resize(rhs.nLocal); + if (this == &rhs) + return *this; + if (nLocal != rhs.nLocal) + resize(rhs.nLocal); std::copy_n(rhs.data(), nLocal, X); return *this; } // assignment operator from anther Vector class - template - inline Vector &operator=(const Vector &rhs) + template + inline Vector& operator=(const Vector& rhs) { if (std::is_convertible::value) { - if (nLocal != rhs.nLocal) resize(rhs.nLocal); + if (nLocal != rhs.nLocal) + resize(rhs.nLocal); std::copy_n(rhs.data(), nLocal, X); } return *this; } // assigment operator to enable PETE - template inline Vector &operator=(const RHS &rhs) + template + inline Vector& operator=(const RHS& rhs) { assign(*this, rhs); return *this; @@ -99,11 +102,10 @@ template > class Vector } // Attach to pre-allocated memory - inline void attachReference(T *ref, size_t n) + inline void attachReference(T* ref, size_t n) { if (nAllocated) - throw std::runtime_error( - "Pointer attaching is not allowed on Vector with allocated memory."); + throw std::runtime_error("Pointer attaching is not allowed on Vector with allocated memory."); nLocal = n; nAllocated = 0; X = ref; @@ -116,8 +118,7 @@ template > class Vector inline void resize(size_t n, Type_t val = Type_t()) { if (nLocal > nAllocated) - throw std::runtime_error( - "Resize not allowed on Vector constructed by initialized memory."); + throw std::runtime_error("Resize not allowed on Vector constructed by initialized memory."); if (n > nAllocated) { resize_impl(n); @@ -149,9 +150,9 @@ template > class Vector } // Get and Set Operations - inline Type_t &operator[](size_t i) { return X[i]; } + inline Type_t& operator[](size_t i) { return X[i]; } - inline const Type_t &operator[](size_t i) const { return X[i]; } + inline const Type_t& operator[](size_t i) const { return X[i]; } // inline Type_t& operator()(size_t i) //{ @@ -184,7 +185,7 @@ template > class Vector /// The number of allocated size_t nAllocated; /// pointer to the data managed by this object - T *X; + T* X; /// allocator Alloc mAllocator; @@ -210,10 +211,11 @@ namespace qmcplusplus // We need to specialize CreateLeaf for our class, so that operators // know what to stick in the leaves of the expression tree. //----------------------------------------------------------------------------- -template struct CreateLeaf> +template +struct CreateLeaf> { typedef Reference> Leaf_t; - inline static Leaf_t make(const Vector &a) { return Leaf_t(a); } + inline static Leaf_t make(const Vector& a) { return Leaf_t(a); } }; //----------------------------------------------------------------------------- @@ -225,30 +227,29 @@ class SizeLeaf { public: SizeLeaf(int s) : size_m(s) {} - SizeLeaf(const SizeLeaf &model) : size_m(model.size_m) {} + SizeLeaf(const SizeLeaf& model) : size_m(model.size_m) {} bool operator()(int s) const { return size_m == s; } private: int size_m; }; -template struct LeafFunctor, SizeLeaf> +template +struct LeafFunctor, SizeLeaf> { typedef bool Type_t; - inline static bool apply(const Scalar &, const SizeLeaf &) + inline static bool apply(const Scalar&, const SizeLeaf&) { // Scalars always conform. return true; } }; -template struct LeafFunctor, SizeLeaf> +template +struct LeafFunctor, SizeLeaf> { typedef bool Type_t; - inline static bool apply(const Vector &v, const SizeLeaf &s) - { - return s(v.size()); - } + inline static bool apply(const Vector& v, const SizeLeaf& s) { return s(v.size()); } }; //----------------------------------------------------------------------------- @@ -256,21 +257,18 @@ template struct LeafFunctor, SizeLeaf> // (It's already defined for Scalar values.) //----------------------------------------------------------------------------- -template struct LeafFunctor, EvalLeaf1> +template +struct LeafFunctor, EvalLeaf1> { typedef T Type_t; - inline static Type_t apply(const Vector &vec, const EvalLeaf1 &f) - { - return vec[f.val1()]; - } + inline static Type_t apply(const Vector& vec, const EvalLeaf1& f) { return vec[f.val1()]; } }; ////////////////////////////////////////////////////////////////////////////////// // LOOP is done by evaluate function ////////////////////////////////////////////////////////////////////////////////// -template -inline void evaluate(Vector &lhs, const Op &op, - const Expression &rhs) +template +inline void evaluate(Vector& lhs, const Op& op, const Expression& rhs) { if (forEach(rhs, SizeLeaf(lhs.size()), AndCombine())) { @@ -290,22 +288,21 @@ inline void evaluate(Vector &lhs, const Op &op, } else { - std::cerr << "Error: LHS and RHS don't conform in OhmmsVector." - << std::endl; + std::cerr << "Error: LHS and RHS don't conform in OhmmsVector." << std::endl; abort(); } } // I/O -template -std::ostream &operator<<(std::ostream &out, const Vector &rhs) +template +std::ostream& operator<<(std::ostream& out, const Vector& rhs) { for (int i = 0; i < rhs.size(); i++) out << rhs[i] << std::endl; return out; } -template -std::istream &operator>>(std::istream &is, Vector &rhs) +template +std::istream& operator>>(std::istream& is, Vector& rhs) { // printTinyVector >::print(out,rhs); for (int i = 0; i < rhs.size(); i++) diff --git a/src/Numerics/OhmmsPETE/OhmmsVectorOperators.h b/src/Numerics/OhmmsPETE/OhmmsVectorOperators.h index eb616e240..8455f6a4a 100644 --- a/src/Numerics/OhmmsPETE/OhmmsVectorOperators.h +++ b/src/Numerics/OhmmsPETE/OhmmsVectorOperators.h @@ -18,53 +18,46 @@ namespace qmcplusplus { - -template -inline -Vector& assign(Vector& lhs,const RHS& rhs) +template +inline Vector& assign(Vector& lhs, const RHS& rhs) { typedef typename CreateLeaf::Leaf_t Leaf_t; - evaluate(lhs,OpAssign(),MakeReturn::make(CreateLeaf::make(rhs))); + evaluate(lhs, OpAssign(), MakeReturn::make(CreateLeaf::make(rhs))); return lhs; } -template -inline -Vector& operator+=(Vector& lhs,const RHS& rhs) +template +inline Vector& operator+=(Vector& lhs, const RHS& rhs) { typedef typename CreateLeaf::Leaf_t Leaf_t; - evaluate(lhs,OpAddAssign(),MakeReturn::make(CreateLeaf::make(rhs))); + evaluate(lhs, OpAddAssign(), MakeReturn::make(CreateLeaf::make(rhs))); return lhs; } -template -inline -Vector& operator-=(Vector& lhs,const RHS& rhs) +template +inline Vector& operator-=(Vector& lhs, const RHS& rhs) { typedef typename CreateLeaf::Leaf_t Leaf_t; - evaluate(lhs,OpSubtractAssign(),MakeReturn::make(CreateLeaf::make(rhs))); + evaluate(lhs, OpSubtractAssign(), MakeReturn::make(CreateLeaf::make(rhs))); return lhs; } -template -inline -Vector& operator*=(Vector& lhs,const RHS& rhs) +template +inline Vector& operator*=(Vector& lhs, const RHS& rhs) { typedef typename CreateLeaf::Leaf_t Leaf_t; - evaluate(lhs,OpMultiplyAssign(),MakeReturn::make(CreateLeaf::make(rhs))); + evaluate(lhs, OpMultiplyAssign(), MakeReturn::make(CreateLeaf::make(rhs))); return lhs; } -template -inline -Vector& operator/=(Vector& lhs,const RHS& rhs) +template +inline Vector& operator/=(Vector& lhs, const RHS& rhs) { typedef typename CreateLeaf::Leaf_t Leaf_t; - evaluate(lhs,OpDivideAssign(),MakeReturn::make(CreateLeaf::make(rhs))); + evaluate(lhs, OpDivideAssign(), MakeReturn::make(CreateLeaf::make(rhs))); return lhs; } -} +} // namespace qmcplusplus #endif // GENERATED_OPERATORS_H - diff --git a/src/Numerics/OhmmsPETE/Tensor.h b/src/Numerics/OhmmsPETE/Tensor.h index dc7edcde3..d2c3b8d81 100644 --- a/src/Numerics/OhmmsPETE/Tensor.h +++ b/src/Numerics/OhmmsPETE/Tensor.h @@ -44,13 +44,13 @@ namespace qmcplusplus { - /** Tensor class for D by D tensor * * @tparam T datatype * @tparm D dimension */ -template class Tensor +template +class Tensor { public: typedef T Type_t; @@ -64,40 +64,39 @@ template class Tensor }; // Default Constructor - Tensor() - { - OTAssign, T, OpAssign>::apply(*this, T(0), OpAssign()); - } + Tensor() { OTAssign, T, OpAssign>::apply(*this, T(0), OpAssign()); } // A noninitializing ctor. class DontInitialize - { - }; + {}; Tensor(DontInitialize) {} // Copy Constructor - Tensor(const Tensor &rhs) + Tensor(const Tensor& rhs) { - OTAssign, Tensor, OpAssign>::apply(*this, rhs, - OpAssign()); + OTAssign, Tensor, OpAssign>::apply(*this, rhs, OpAssign()); } // constructor from a single T - Tensor(const T &x00) - { - OTAssign, T, OpAssign>::apply(*this, x00, OpAssign()); - } + Tensor(const T& x00) { OTAssign, T, OpAssign>::apply(*this, x00, OpAssign()); } // constructors for fixed dimension - Tensor(const T &x00, const T &x10, const T &x01, const T &x11) + Tensor(const T& x00, const T& x10, const T& x01, const T& x11) { X[0] = x00; X[1] = x10; X[2] = x01; X[3] = x11; } - Tensor(const T &x00, const T &x10, const T &x20, const T &x01, const T &x11, - const T &x21, const T &x02, const T &x12, const T &x22) + Tensor(const T& x00, + const T& x10, + const T& x20, + const T& x01, + const T& x11, + const T& x21, + const T& x02, + const T& x12, + const T& x22) { X[0] = x00; X[1] = x10; @@ -114,90 +113,88 @@ template class Tensor ~Tensor(){}; // assignment operators - inline Tensor &operator=(const Tensor &rhs) + inline Tensor& operator=(const Tensor& rhs) { - OTAssign, Tensor, OpAssign>::apply(*this, rhs, - OpAssign()); + OTAssign, Tensor, OpAssign>::apply(*this, rhs, OpAssign()); return *this; } - template inline Tensor &operator=(const Tensor &rhs) + template + inline Tensor& operator=(const Tensor& rhs) { - OTAssign, Tensor, OpAssign>::apply(*this, rhs, - OpAssign()); + OTAssign, Tensor, OpAssign>::apply(*this, rhs, OpAssign()); return *this; } - inline Tensor &operator=(const T &rhs) + inline Tensor& operator=(const T& rhs) { OTAssign, T, OpAssign>::apply(*this, rhs, OpAssign()); return *this; } // accumulation operators - template inline Tensor &operator+=(const Tensor &rhs) + template + inline Tensor& operator+=(const Tensor& rhs) { - OTAssign, Tensor, OpAddAssign>::apply(*this, rhs, - OpAddAssign()); + OTAssign, Tensor, OpAddAssign>::apply(*this, rhs, OpAddAssign()); return *this; } - inline Tensor &operator+=(const T &rhs) + inline Tensor& operator+=(const T& rhs) { OTAssign, T, OpAddAssign>::apply(*this, rhs, OpAddAssign()); return *this; } - template inline Tensor &operator-=(const Tensor &rhs) + template + inline Tensor& operator-=(const Tensor& rhs) { - OTAssign, Tensor, OpSubtractAssign>::apply( - *this, rhs, OpSubtractAssign()); + OTAssign, Tensor, OpSubtractAssign>::apply(*this, rhs, OpSubtractAssign()); return *this; } - inline Tensor &operator-=(const T &rhs) + inline Tensor& operator-=(const T& rhs) { - OTAssign, T, OpSubtractAssign>::apply(*this, rhs, - OpSubtractAssign()); + OTAssign, T, OpSubtractAssign>::apply(*this, rhs, OpSubtractAssign()); return *this; } - template inline Tensor &operator*=(const Tensor &rhs) + template + inline Tensor& operator*=(const Tensor& rhs) { - OTAssign, Tensor, OpMultiplyAssign>::apply( - *this, rhs, OpMultiplyAssign()); + OTAssign, Tensor, OpMultiplyAssign>::apply(*this, rhs, OpMultiplyAssign()); return *this; } - inline Tensor &operator*=(const T &rhs) + inline Tensor& operator*=(const T& rhs) { - OTAssign, T, OpMultiplyAssign>::apply(*this, rhs, - OpMultiplyAssign()); + OTAssign, T, OpMultiplyAssign>::apply(*this, rhs, OpMultiplyAssign()); return *this; } - template inline Tensor &operator/=(const Tensor &rhs) + template + inline Tensor& operator/=(const Tensor& rhs) { - OTAssign, Tensor, OpDivideAssign>::apply( - *this, rhs, OpDivideAssign()); + OTAssign, Tensor, OpDivideAssign>::apply(*this, rhs, OpDivideAssign()); return *this; } - inline Tensor &operator/=(const T &rhs) + inline Tensor& operator/=(const T& rhs) { - OTAssign, T, OpDivideAssign>::apply(*this, rhs, - OpDivideAssign()); + OTAssign, T, OpDivideAssign>::apply(*this, rhs, OpDivideAssign()); return *this; } // Methods - inline void diagonal(const T &rhs) + inline void diagonal(const T& rhs) { - for (int i = 0; i < D; i++) (*this)(i, i) = rhs; + for (int i = 0; i < D; i++) + (*this)(i, i) = rhs; } inline void add2diagonal(T rhs) { - for (int i = 0; i < D; i++) (*this)(i, i) += rhs; + for (int i = 0; i < D; i++) + (*this)(i, i) += rhs; } /// return the size @@ -208,7 +205,7 @@ template class Tensor /** return the i-th value or assign * @param i index [0,D*D) */ - inline Type_t &operator[](unsigned int i) { return X[i]; } + inline Type_t& operator[](unsigned int i) { return X[i]; } /** return the i-th value * @param i index [0,D*D) @@ -217,7 +214,7 @@ template class Tensor // TJW: add these 12/16/97 to help with NegReflectAndZeroFace BC: // These are the same as operator[] but with () instead: - inline Type_t &operator()(unsigned int i) { return X[i]; } + inline Type_t& operator()(unsigned int i) { return X[i]; } inline Type_t operator()(unsigned int i) const { return X[i]; } // TJW. @@ -226,40 +223,36 @@ template class Tensor * @param i index [0,D) * @param j index [0,D) */ - inline Type_t operator()(unsigned int i, unsigned int j) const - { - return X[i * D + j]; - } + inline Type_t operator()(unsigned int i, unsigned int j) const { return X[i * D + j]; } /** return/assign the (i,j) component * @param i index [0,D) * @param j index [0,D) */ - inline Type_t &operator()(unsigned int i, unsigned int j) - { - return X[i * D + j]; - } + inline Type_t& operator()(unsigned int i, unsigned int j) { return X[i * D + j]; } inline TinyVector getRow(unsigned int i) { TinyVector res; - for (int j = 0; j < D; j++) res[j] = X[i * D + j]; + for (int j = 0; j < D; j++) + res[j] = X[i * D + j]; return res; } inline TinyVector getColumn(unsigned int i) { TinyVector res; - for (int j = 0; j < D; j++) res[j] = X[j * D + i]; + for (int j = 0; j < D; j++) + res[j] = X[j * D + i]; return res; } - inline Type_t *data() { return X; } - inline const Type_t *data() const { return X; } - inline Type_t *begin() { return X; } - inline const Type_t *begin() const { return X; } - inline Type_t *end() { return X + Size; } - inline const Type_t *end() const { return X + Size; } + inline Type_t* data() { return X; } + inline const Type_t* data() const { return X; } + inline Type_t* begin() { return X; } + inline const Type_t* begin() const { return X; } + inline Type_t* end() { return X + Size; } + inline const Type_t* end() const { return X + Size; } private: // The elements themselves. @@ -275,54 +268,60 @@ template class Tensor /** trace \f$ result = \sum_k rhs(k,k)\f$ * @param rhs a tensor */ -template inline T trace(const Tensor &rhs) +template +inline T trace(const Tensor& rhs) { T result = 0.0; - for (int i = 0; i < D; i++) result += rhs(i, i); + for (int i = 0; i < D; i++) + result += rhs(i, i); return result; } /** transpose a tensor */ -template -inline Tensor transpose(const Tensor &rhs) +template +inline Tensor transpose(const Tensor& rhs) { Tensor result; // = Tensor::DontInitialize(); for (int j = 0; j < D; j++) - for (int i = 0; i < D; i++) result(i, j) = rhs(j, i); + for (int i = 0; i < D; i++) + result(i, j) = rhs(j, i); return result; } /** Tr(a*b), \f$ \sum_i\sum_j a(i,j)*b(j,i) \f$ */ -template -inline T1 trace(const Tensor &a, const Tensor &b) +template +inline T1 trace(const Tensor& a, const Tensor& b) { T1 result = 0.0; for (int i = 0; i < D; i++) - for (int j = 0; j < D; j++) result += a(i, j) * b(j, i); + for (int j = 0; j < D; j++) + result += a(i, j) * b(j, i); return result; } /** Tr(a^t *b), \f$ \sum_i\sum_j a(i,j)*b(i,j) \f$ */ -template -inline T traceAtB(const Tensor &a, const Tensor &b) +template +inline T traceAtB(const Tensor& a, const Tensor& b) { T result = 0.0; - for (int i = 0; i < D * D; i++) result += a(i) * b(i); + for (int i = 0; i < D * D; i++) + result += a(i) * b(i); return result; } /** Tr(a^t *b), \f$ \sum_i\sum_j a(i,j)*b(i,j) \f$ */ -template +template inline typename BinaryReturn::Type_t -traceAtB(const Tensor &a, const Tensor &b) + traceAtB(const Tensor& a, const Tensor& b) { typedef typename BinaryReturn::Type_t T; T result = 0.0; - for (int i = 0; i < D * D; i++) result += a(i) * b(i); + for (int i = 0; i < D * D; i++) + result += a(i) * b(i); return result; } @@ -336,9 +335,9 @@ OHMMS_META_BINARY_OPERATORS(Tensor, operator/, OpDivide) * @param lhs a tensor * @param rhs a tensor */ -template +template inline Tensor::Type_t, D> -dot(const Tensor &lhs, const Tensor &rhs) + dot(const Tensor& lhs, const Tensor& rhs) { return OTDot, Tensor>::apply(lhs, rhs); } @@ -347,9 +346,9 @@ dot(const Tensor &lhs, const Tensor &rhs) * @param lhs a vector * @param rhs a tensor */ -template +template inline TinyVector::Type_t, D> -dot(const TinyVector &lhs, const Tensor &rhs) + dot(const TinyVector& lhs, const Tensor& rhs) { return OTDot, Tensor>::apply(lhs, rhs); } @@ -358,17 +357,17 @@ dot(const TinyVector &lhs, const Tensor &rhs) * @param lhs a tensor * @param rhs a vector */ -template +template inline TinyVector::Type_t, D> -dot(const Tensor &lhs, const TinyVector &rhs) + dot(const Tensor& lhs, const TinyVector& rhs) { return OTDot, TinyVector>::apply(lhs, rhs); } //---------------------------------------------------------------------- // I/O -template -std::ostream &operator<<(std::ostream &out, const Tensor &rhs) +template +std::ostream& operator<<(std::ostream& out, const Tensor& rhs) { if (D >= 1) { @@ -379,7 +378,8 @@ std::ostream &operator<<(std::ostream &out, const Tensor &rhs) out << rhs(i, j) << " "; } out << rhs(i, D - 1) << " "; - if (i < D - 1) out << std::endl; + if (i < D - 1) + out << std::endl; } } else @@ -389,12 +389,13 @@ std::ostream &operator<<(std::ostream &out, const Tensor &rhs) return out; } -template -std::istream &operator>>(std::istream &is, Tensor &rhs) +template +std::istream& operator>>(std::istream& is, Tensor& rhs) { - for (int i = 0; i < D * D; i++) is >> rhs[i]; + for (int i = 0; i < D * D; i++) + is >> rhs[i]; return is; } -} +} // namespace qmcplusplus #endif // OHMMS_TENSOR_H diff --git a/src/Numerics/OhmmsPETE/TensorOps.h b/src/Numerics/OhmmsPETE/TensorOps.h index 55d7a54ef..8525bc119 100644 --- a/src/Numerics/OhmmsPETE/TensorOps.h +++ b/src/Numerics/OhmmsPETE/TensorOps.h @@ -20,22 +20,23 @@ */ namespace qmcplusplus { - -template +template struct OTAssign, Tensor, OP> { - inline static void apply(Tensor &lhs, const Tensor &rhs, OP op) + inline static void apply(Tensor& lhs, const Tensor& rhs, OP op) { - for (unsigned d = 0; d < D * D; ++d) op(lhs[d], rhs[d]); + for (unsigned d = 0; d < D * D; ++d) + op(lhs[d], rhs[d]); } }; -template +template struct OTAssign, T2, OP> { - inline static void apply(Tensor &lhs, T2 rhs, OP op) + inline static void apply(Tensor& lhs, T2 rhs, OP op) { - for (unsigned d = 0; d < D * D; ++d) op(lhs[d], rhs); + for (unsigned d = 0; d < D * D; ++d) + op(lhs[d], rhs); } }; @@ -46,39 +47,41 @@ struct OTAssign, T2, OP> // ////////////////////////////////////////////////////////////////////// -template +template struct OTBinary, Tensor, OP> { typedef typename BinaryReturn::Type_t Type_t; - inline static Tensor apply(const Tensor &lhs, - const Tensor &rhs, OP op) + inline static Tensor apply(const Tensor& lhs, const Tensor& rhs, OP op) { Tensor ret; - for (unsigned d = 0; d < D * D; ++d) ret[d] = op(lhs[d], rhs[d]); + for (unsigned d = 0; d < D * D; ++d) + ret[d] = op(lhs[d], rhs[d]); return ret; } }; -template +template struct OTBinary, T2, OP> { typedef typename BinaryReturn::Type_t Type_t; - inline static Tensor apply(const Tensor &lhs, T2 rhs, OP op) + inline static Tensor apply(const Tensor& lhs, T2 rhs, OP op) { Tensor ret; - for (unsigned d = 0; d < D * D; ++d) ret[d] = op(lhs[d], rhs); + for (unsigned d = 0; d < D * D; ++d) + ret[d] = op(lhs[d], rhs); return ret; } }; -template +template struct OTBinary, OP> { typedef typename BinaryReturn::Type_t Type_t; - inline static Tensor apply(T1 lhs, const Tensor &rhs, OP op) + inline static Tensor apply(T1 lhs, const Tensor& rhs, OP op) { Tensor ret; - for (unsigned d = 0; d < D * D; ++d) ret[d] = op(lhs, rhs[d]); + for (unsigned d = 0; d < D * D; ++d) + ret[d] = op(lhs, rhs[d]); return ret; } }; @@ -88,8 +91,8 @@ struct OTBinary, OP> // determinant: generalized // ////////////////////////////////////////////////////// -template -inline typename Tensor::Type_t det(const Tensor &a) +template +inline typename Tensor::Type_t det(const Tensor& a) { // to implement the general case here return 0; @@ -98,8 +101,8 @@ inline typename Tensor::Type_t det(const Tensor &a) ////////////////////////////////////////////////////// // specialized for D=1 ////////////////////////////////////////////////////// -template -inline typename Tensor::Type_t det(const Tensor &a) +template +inline typename Tensor::Type_t det(const Tensor& a) { return a(0, 0); } @@ -107,8 +110,8 @@ inline typename Tensor::Type_t det(const Tensor &a) ////////////////////////////////////////////////////// // specialized for D=2 ////////////////////////////////////////////////////// -template -inline typename Tensor::Type_t det(const Tensor &a) +template +inline typename Tensor::Type_t det(const Tensor& a) { return a(0, 0) * a(1, 1) - a(0, 1) * a(1, 0); } @@ -116,12 +119,12 @@ inline typename Tensor::Type_t det(const Tensor &a) ////////////////////////////////////////////////////// // specialized for D=3 ////////////////////////////////////////////////////// -template -inline typename Tensor::Type_t det(const Tensor &a) +template +inline typename Tensor::Type_t det(const Tensor& a) { return a(0, 0) * (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1)) + - a(0, 1) * (a(1, 2) * a(2, 0) - a(1, 0) * a(2, 2)) + - a(0, 2) * (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0)); + a(0, 1) * (a(1, 2) * a(2, 0) - a(1, 0) * a(2, 2)) + + a(0, 2) * (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0)); } ////////////////////////////////////////////////////// @@ -130,8 +133,8 @@ inline typename Tensor::Type_t det(const Tensor &a) // A*B = I, * being the matrix multiplication I(i,j) = sum_k A(i,k)*B(k,j) // ////////////////////////////////////////////////////// -template -inline Tensor inverse(const Tensor &a) +template +inline Tensor inverse(const Tensor& a) { return Tensor(); } @@ -139,7 +142,8 @@ inline Tensor inverse(const Tensor &a) ////////////////////////////////////////////////////// // specialized for D=1 ////////////////////////////////////////////////////// -template inline Tensor inverse(const Tensor &a) +template +inline Tensor inverse(const Tensor& a) { return Tensor(1.0 / a(0, 0)); } @@ -147,17 +151,18 @@ template inline Tensor inverse(const Tensor &a) ////////////////////////////////////////////////////// // specialized for D=2 ////////////////////////////////////////////////////// -template inline Tensor inverse(const Tensor &a) +template +inline Tensor inverse(const Tensor& a) { T vinv = 1 / det(a); - return Tensor(vinv * a(1, 1), -vinv * a(0, 1), -vinv * a(1, 0), - vinv * a(0, 0)); + return Tensor(vinv * a(1, 1), -vinv * a(0, 1), -vinv * a(1, 0), vinv * a(0, 0)); } ////////////////////////////////////////////////////// // specialized for D=3 ////////////////////////////////////////////////////// -template inline Tensor inverse(const Tensor &a) +template +inline Tensor inverse(const Tensor& a) { T vinv = 1 / det(a); return Tensor(vinv * (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1)), @@ -177,40 +182,40 @@ template inline Tensor inverse(const Tensor &a) // ////////////////////////////////////////////////////////////////////// -template +template struct OTDot, Tensor> { typedef typename BinaryReturn::Type_t Type_t; - inline static Tensor apply(const Tensor &lhs, - const Tensor &rhs) + inline static Tensor apply(const Tensor& lhs, const Tensor& rhs) { Tensor res = Tensor::DontInitialize(); for (unsigned int i = 0; i < D; ++i) for (unsigned int j = 0; j < D; ++j) { Type_t sum = lhs(i, 0) * rhs(0, j); - for (unsigned int k = 1; k < D; ++k) sum += lhs(i, k) * rhs(k, j); + for (unsigned int k = 1; k < D; ++k) + sum += lhs(i, k) * rhs(k, j); res(i, j) = sum; } return res; } }; -template struct OTDot, Tensor> +template +struct OTDot, Tensor> { typedef typename BinaryReturn::Type_t Type_t; - inline static Tensor apply(const Tensor &lhs, - const Tensor &rhs) + inline static Tensor apply(const Tensor& lhs, const Tensor& rhs) { return Tensor(lhs[0] * rhs[0]); } }; -template struct OTDot, Tensor> +template +struct OTDot, Tensor> { typedef typename BinaryReturn::Type_t Type_t; - inline static Tensor apply(const Tensor &lhs, - const Tensor &rhs) + inline static Tensor apply(const Tensor& lhs, const Tensor& rhs) { return Tensor(lhs(0, 0) * rhs(0, 0) + lhs(0, 1) * rhs(1, 0), lhs(0, 0) * rhs(0, 1) + lhs(0, 1) * rhs(1, 1), @@ -219,24 +224,23 @@ template struct OTDot, Tensor> } }; -template struct OTDot, Tensor> +template +struct OTDot, Tensor> { typedef typename BinaryReturn::Type_t Type_t; - inline static Tensor apply(const Tensor &lhs, - const Tensor &rhs) + inline static Tensor apply(const Tensor& lhs, const Tensor& rhs) { - return Tensor( - lhs(0, 0) * rhs(0, 0) + lhs(0, 1) * rhs(1, 0) + lhs(0, 2) * rhs(2, 0), - lhs(0, 0) * rhs(0, 1) + lhs(0, 1) * rhs(1, 1) + lhs(0, 2) * rhs(2, 1), - lhs(0, 0) * rhs(0, 2) + lhs(0, 1) * rhs(1, 2) + lhs(0, 2) * rhs(2, 2), - lhs(1, 0) * rhs(0, 0) + lhs(1, 1) * rhs(1, 0) + lhs(1, 2) * rhs(2, 0), - lhs(1, 0) * rhs(0, 1) + lhs(1, 1) * rhs(1, 1) + lhs(1, 2) * rhs(2, 1), - lhs(1, 0) * rhs(0, 2) + lhs(1, 1) * rhs(1, 2) + lhs(1, 2) * rhs(2, 2), - lhs(2, 0) * rhs(0, 0) + lhs(2, 1) * rhs(1, 0) + lhs(2, 2) * rhs(2, 0), - lhs(2, 0) * rhs(0, 1) + lhs(2, 1) * rhs(1, 1) + lhs(2, 2) * rhs(2, 1), - lhs(2, 0) * rhs(0, 2) + lhs(2, 1) * rhs(1, 2) + lhs(2, 2) * rhs(2, 2)); + return Tensor(lhs(0, 0) * rhs(0, 0) + lhs(0, 1) * rhs(1, 0) + lhs(0, 2) * rhs(2, 0), + lhs(0, 0) * rhs(0, 1) + lhs(0, 1) * rhs(1, 1) + lhs(0, 2) * rhs(2, 1), + lhs(0, 0) * rhs(0, 2) + lhs(0, 1) * rhs(1, 2) + lhs(0, 2) * rhs(2, 2), + lhs(1, 0) * rhs(0, 0) + lhs(1, 1) * rhs(1, 0) + lhs(1, 2) * rhs(2, 0), + lhs(1, 0) * rhs(0, 1) + lhs(1, 1) * rhs(1, 1) + lhs(1, 2) * rhs(2, 1), + lhs(1, 0) * rhs(0, 2) + lhs(1, 1) * rhs(1, 2) + lhs(1, 2) * rhs(2, 2), + lhs(2, 0) * rhs(0, 0) + lhs(2, 1) * rhs(1, 0) + lhs(2, 2) * rhs(2, 0), + lhs(2, 0) * rhs(0, 1) + lhs(2, 1) * rhs(1, 1) + lhs(2, 2) * rhs(2, 1), + lhs(2, 0) * rhs(0, 2) + lhs(2, 1) * rhs(1, 2) + lhs(2, 2) * rhs(2, 2)); } }; -} +} // namespace qmcplusplus #endif // OHMMS_TENSOR_OPERATORS_H diff --git a/src/Numerics/OhmmsPETE/TinyVector.h b/src/Numerics/OhmmsPETE/TinyVector.h index 372fb19e0..b3484e4b5 100644 --- a/src/Numerics/OhmmsPETE/TinyVector.h +++ b/src/Numerics/OhmmsPETE/TinyVector.h @@ -46,7 +46,8 @@ namespace qmcplusplus { /** Fixed-size array. candidate for array */ -template struct TinyVector +template +struct TinyVector { typedef T Type_t; enum @@ -56,50 +57,46 @@ template struct TinyVector T X[Size]; // Default Constructor initializes to zero. - inline TinyVector() - { - OTAssign, T, OpAssign>::apply(*this, T(0), OpAssign()); - } + inline TinyVector() { OTAssign, T, OpAssign>::apply(*this, T(0), OpAssign()); } // A noninitializing ctor. class DontInitialize - { - }; + {}; inline TinyVector(DontInitialize) {} // Copy Constructor - inline TinyVector(const TinyVector &rhs) + inline TinyVector(const TinyVector& rhs) { - OTAssign, TinyVector, OpAssign>::apply(*this, rhs, - OpAssign()); + OTAssign, TinyVector, OpAssign>::apply(*this, rhs, OpAssign()); } // Templated TinyVector constructor. - template - inline TinyVector(const TinyVector &rhs) + template + inline TinyVector(const TinyVector& rhs) { - for (unsigned d = 0; d < D; ++d) X[d] = (d < D1) ? rhs[d] : T1(0); + for (unsigned d = 0; d < D; ++d) + X[d] = (d < D1) ? rhs[d] : T1(0); } // Constructor from a single T - inline TinyVector(const T &x00) + inline TinyVector(const T& x00) { OTAssign, T, OpAssign>::apply(*this, x00, OpAssign()); } // Constructors for fixed dimension - inline TinyVector(const T &x00, const T &x01) + inline TinyVector(const T& x00, const T& x01) { X[0] = x00; X[1] = x01; } - inline TinyVector(const T &x00, const T &x01, const T &x02) + inline TinyVector(const T& x00, const T& x01, const T& x02) { X[0] = x00; X[1] = x01; X[2] = x02; } - inline TinyVector(const T &x00, const T &x01, const T &x02, const T &x03) + inline TinyVector(const T& x00, const T& x01, const T& x02, const T& x03) { X[0] = x00; X[1] = x01; @@ -107,10 +104,22 @@ template struct TinyVector X[3] = x03; } - inline TinyVector(const T &x00, const T &x01, const T &x02, const T &x03, - const T &x10, const T &x11, const T &x12, const T &x13, - const T &x20, const T &x21, const T &x22, const T &x23, - const T &x30, const T &x31, const T &x32, const T &x33) + inline TinyVector(const T& x00, + const T& x01, + const T& x02, + const T& x03, + const T& x10, + const T& x11, + const T& x12, + const T& x13, + const T& x20, + const T& x21, + const T& x22, + const T& x23, + const T& x30, + const T& x31, + const T& x32, + const T& x33) { X[0] = x00; X[1] = x01; @@ -130,10 +139,11 @@ template struct TinyVector X[15] = x33; } - inline TinyVector(const T *restrict base, int offset) + inline TinyVector(const T* restrict base, int offset) { - #pragma unroll - for (int i = 0; i < D; ++i) X[i] = base[i * offset]; +#pragma unroll + for (int i = 0; i < D; ++i) + X[i] = base[i * offset]; } // Destructor @@ -143,47 +153,47 @@ template struct TinyVector inline int byteSize() const { return D * sizeof(T); } - inline TinyVector &operator=(const TinyVector &rhs) + inline TinyVector& operator=(const TinyVector& rhs) { - OTAssign, TinyVector, OpAssign>::apply(*this, rhs, - OpAssign()); + OTAssign, TinyVector, OpAssign>::apply(*this, rhs, OpAssign()); return *this; } - template - inline TinyVector &operator=(const TinyVector &rhs) + template + inline TinyVector& operator=(const TinyVector& rhs) { - OTAssign, TinyVector, OpAssign>::apply(*this, rhs, - OpAssign()); + OTAssign, TinyVector, OpAssign>::apply(*this, rhs, OpAssign()); return *this; } - inline TinyVector &operator=(const T &rhs) + inline TinyVector& operator=(const T& rhs) { OTAssign, T, OpAssign>::apply(*this, rhs, OpAssign()); return *this; } // Get and Set Operations - inline Type_t &operator[](unsigned int i) { return X[i]; } + inline Type_t& operator[](unsigned int i) { return X[i]; } inline Type_t operator[](unsigned int i) const { return X[i]; } - inline Type_t &operator()(unsigned int i) { return X[i]; } + inline Type_t& operator()(unsigned int i) { return X[i]; } inline Type_t operator()(unsigned int i) const { return X[i]; } - inline Type_t *data() { return X; } - inline const Type_t *data() const { return X; } - inline Type_t *begin() { return X; } - inline const Type_t *begin() const { return X; } - inline Type_t *end() { return X + D; } - inline const Type_t *end() const { return X + D; } + inline Type_t* data() { return X; } + inline const Type_t* data() const { return X; } + inline Type_t* begin() { return X; } + inline const Type_t* begin() const { return X; } + inline Type_t* end() { return X + D; } + inline const Type_t* end() const { return X + D; } - template inline Msg &putMessage(Msg &m) + template + inline Msg& putMessage(Msg& m) { m.Pack(X, Size); return m; } - template inline Msg &getMessage(Msg &m) + template + inline Msg& getMessage(Msg& m) { m.Unpack(X, Size); return m; @@ -204,9 +214,9 @@ OHMMS_META_BINARY_OPERATORS(TinyVector, operator/, OpDivide) //---------------------------------------------------------------------- // dot product //---------------------------------------------------------------------- -template +template inline typename BinaryReturn::Type_t -dot(const TinyVector &lhs, const TinyVector &rhs) + dot(const TinyVector& lhs, const TinyVector& rhs) { return OTDot, TinyVector>::apply(lhs, rhs); } @@ -215,9 +225,9 @@ dot(const TinyVector &lhs, const TinyVector &rhs) // cross product //---------------------------------------------------------------------- -template +template inline TinyVector::Type_t, D> -cross(const TinyVector &lhs, const TinyVector &rhs) + cross(const TinyVector& lhs, const TinyVector& rhs) { return OTCross, TinyVector>::apply(lhs, rhs); } @@ -226,53 +236,53 @@ cross(const TinyVector &lhs, const TinyVector &rhs) // cross product //---------------------------------------------------------------------- -template +template inline Tensor::Type_t, D> -outerProduct(const TinyVector &lhs, const TinyVector &rhs) + outerProduct(const TinyVector& lhs, const TinyVector& rhs) { return OuterProduct, TinyVector>::apply(lhs, rhs); } -template -inline TinyVector, D> outerdot(const TinyVector &lhs, - const TinyVector &mhs, - const TinyVector &rhs) +template +inline TinyVector, D> + outerdot(const TinyVector& lhs, const TinyVector& mhs, const TinyVector& rhs) { TinyVector, D> ret; - Tensor tmp = - OuterProduct, TinyVector>::apply(lhs, mhs); - for (unsigned i(0); i < D; i++) ret[i] = rhs[i] * tmp; + Tensor tmp = OuterProduct, TinyVector>::apply(lhs, mhs); + for (unsigned i(0); i < D; i++) + ret[i] = rhs[i] * tmp; return ret; } -template -inline TinyVector::Type_t, D>, - D> -symouterdot(const TinyVector &lhs, const TinyVector &mhs, - const TinyVector &rhs) +template +inline TinyVector::Type_t, D>, D> + symouterdot(const TinyVector& lhs, const TinyVector& mhs, const TinyVector& rhs) { - TinyVector::Type_t, D>, D> - ret; + TinyVector::Type_t, D>, D> ret; Tensor::Type_t, D> tmp = OuterProduct, TinyVector>::apply(lhs, mhs); - for (unsigned i(0); i < D; i++) ret[i] = rhs[i] * tmp; + for (unsigned i(0); i < D; i++) + ret[i] = rhs[i] * tmp; tmp = OuterProduct, TinyVector>::apply(mhs, rhs); - for (unsigned i(0); i < D; i++) ret[i] += lhs[i] * tmp; + for (unsigned i(0); i < D; i++) + ret[i] += lhs[i] * tmp; tmp = OuterProduct, TinyVector>::apply(lhs, rhs); - for (unsigned i(0); i < D; i++) ret[i] += mhs[i] * tmp; + for (unsigned i(0); i < D; i++) + ret[i] += mhs[i] * tmp; return ret; } //---------------------------------------------------------------------- // I/O -template struct printTinyVector -{ -}; +template +struct printTinyVector +{}; // specialized for Vector > -template struct printTinyVector> +template +struct printTinyVector> { - inline static void print(std::ostream &os, const TinyVector &r) + inline static void print(std::ostream& os, const TinyVector& r) { for (int d = 0; d < D; d++) os << std::setw(18) << std::setprecision(10) << r[d]; @@ -280,40 +290,42 @@ template struct printTinyVector> }; // specialized for Vector > -template struct printTinyVector> +template +struct printTinyVector> { - inline static void print(std::ostream &os, const TinyVector &r) + inline static void print(std::ostream& os, const TinyVector& r) { - os << std::setw(18) << std::setprecision(10) << r[0] << std::setw(18) - << std::setprecision(10) << r[1]; + os << std::setw(18) << std::setprecision(10) << r[0] << std::setw(18) << std::setprecision(10) + << r[1]; } }; // specialized for Vector > -template struct printTinyVector> +template +struct printTinyVector> { - inline static void print(std::ostream &os, const TinyVector &r) + inline static void print(std::ostream& os, const TinyVector& r) { - os << std::setw(18) << std::setprecision(10) << r[0] << std::setw(18) - << std::setprecision(10) << r[1] << std::setw(18) - << std::setprecision(10) << r[2]; + os << std::setw(18) << std::setprecision(10) << r[0] << std::setw(18) << std::setprecision(10) + << r[1] << std::setw(18) << std::setprecision(10) << r[2]; } }; -template -std::ostream &operator<<(std::ostream &out, const TinyVector &rhs) +template +std::ostream& operator<<(std::ostream& out, const TinyVector& rhs) { printTinyVector>::print(out, rhs); return out; } -template -std::istream &operator>>(std::istream &is, TinyVector &rhs) +template +std::istream& operator>>(std::istream& is, TinyVector& rhs) { // printTinyVector >::print(out,rhs); - for (int i = 0; i < D; i++) is >> rhs[i]; + for (int i = 0; i < D; i++) + is >> rhs[i]; return is; } -} +} // namespace qmcplusplus #endif // VEKTOR_H diff --git a/src/Numerics/OhmmsPETE/TinyVectorOps.h b/src/Numerics/OhmmsPETE/TinyVectorOps.h index 0e3ccb330..d49e72278 100644 --- a/src/Numerics/OhmmsPETE/TinyVectorOps.h +++ b/src/Numerics/OhmmsPETE/TinyVectorOps.h @@ -19,15 +19,14 @@ namespace qmcplusplus { - template -struct BinaryReturn, OpMultiply > +struct BinaryReturn, OpMultiply> { typedef std::complex Type_t; }; template -struct BinaryReturn, T1, OpMultiply > +struct BinaryReturn, T1, OpMultiply> { typedef std::complex Type_t; }; @@ -43,24 +42,22 @@ struct BinaryReturn, T1, OpMultiply > // Specializations for TinyVectors of arbitrary size. ////////////////////////////////////////////////////////////////////// template -struct OTAssign< TinyVector , TinyVector , OP > +struct OTAssign, TinyVector, OP> { - inline static void - apply( TinyVector& lhs, const TinyVector& rhs, OP op) + inline static void apply(TinyVector& lhs, const TinyVector& rhs, OP op) { - for (unsigned d=0; d -struct OTAssign< TinyVector , T2 , OP > +struct OTAssign, T2, OP> { - inline static void - apply( TinyVector& lhs, const T2& rhs, OP op ) + inline static void apply(TinyVector& lhs, const T2& rhs, OP op) { - for (unsigned d=0; d , T2 , OP > ////////////////////////////////////////////////////////////////////// template -struct OTBinary< TinyVector , TinyVector , OP > +struct OTBinary, TinyVector, OP> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const TinyVector& lhs, const TinyVector& rhs, OP op) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector + apply(const TinyVector& lhs, const TinyVector& rhs, OP op) { - TinyVector ret; - for (unsigned d=0; d ret; + for (unsigned d = 0; d < D; ++d) + ret[d] = op(lhs[d], rhs[d]); return ret; } }; template -struct OTBinary< TinyVector , T2 , OP > +struct OTBinary, T2, OP> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const TinyVector& lhs, const T2& rhs, OP op) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const TinyVector& lhs, const T2& rhs, OP op) { - TinyVector ret; - for (unsigned d=0 ; d ret; + for (unsigned d = 0; d < D; ++d) + ret[d] = op(lhs[d], rhs); return ret; } }; template -struct OTBinary< T1, TinyVector , OP > +struct OTBinary, OP> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const T1& lhs, const TinyVector& rhs, OP op) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const T1& lhs, const TinyVector& rhs, OP op) { - TinyVector ret; - for (unsigned d=0; d ret; + for (unsigned d = 0; d < D; ++d) + ret[d] = op(lhs, rhs[d]); return ret; } }; @@ -126,57 +121,54 @@ struct OTBinary< T1, TinyVector , OP > ////////////////////////////////////////////////////////////////////// template -struct OTDot< TinyVector , TinyVector > +struct OTDot, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - inline static Type_t - apply(const TinyVector& lhs, const TinyVector& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static Type_t apply(const TinyVector& lhs, const TinyVector& rhs) { - Type_t res = lhs[0]*rhs[0]; - for (unsigned d=1; d -struct OTDot< TinyVector , TinyVector,3> > +struct OTDot, TinyVector, 3>> { typedef T1 Type_t; - inline static Type_t - apply(const TinyVector& lhs, const TinyVector,3>& rhs) + inline static Type_t apply(const TinyVector& lhs, const TinyVector, 3>& rhs) { - return lhs[0]*rhs[0].real() + lhs[1]*rhs[1].real() + lhs[2]*rhs[2].real(); + return lhs[0] * rhs[0].real() + lhs[1] * rhs[1].real() + lhs[2] * rhs[2].real(); } }; /** specialization for complex-real TinyVector */ template -struct OTDot< TinyVector,3> , TinyVector > +struct OTDot, 3>, TinyVector> { typedef T1 Type_t; - inline static Type_t - apply(const TinyVector,3>& lhs, const TinyVector& rhs) + inline static Type_t apply(const TinyVector, 3>& lhs, const TinyVector& rhs) { - return lhs[0].real()*rhs[0] + lhs[1].real()*rhs[1] + lhs[2].real()*rhs[2]; + return lhs[0].real() * rhs[0] + lhs[1].real() * rhs[1] + lhs[2].real() * rhs[2]; } }; /** specialization for complex-complex TinyVector */ template -struct OTDot< TinyVector,3> , TinyVector,3> > +struct OTDot, 3>, TinyVector, 3>> { typedef typename BinaryReturn, std::complex, OpMultiply>::Type_t Type_t; inline static Type_t - apply(const TinyVector,3>& lhs, const TinyVector,3>& rhs) + apply(const TinyVector, 3>& lhs, const TinyVector, 3>& rhs) { - return std::complex(lhs[0].real()*rhs[0].real() - lhs[0].imag()*rhs[0].imag() + - lhs[1].real()*rhs[1].real() - lhs[1].imag()*rhs[1].imag() + - lhs[2].real()*rhs[2].real() - lhs[2].imag()*rhs[2].imag() , - lhs[0].real()*rhs[0].imag() + lhs[0].imag()*rhs[0].real() + - lhs[1].real()*rhs[1].imag() + lhs[1].imag()*rhs[1].real() + - lhs[2].real()*rhs[2].imag() + lhs[2].imag()*rhs[2].real() ); + return std::complex(lhs[0].real() * rhs[0].real() - lhs[0].imag() * rhs[0].imag() + + lhs[1].real() * rhs[1].real() - lhs[1].imag() * rhs[1].imag() + + lhs[2].real() * rhs[2].real() - lhs[2].imag() * rhs[2].imag(), + lhs[0].real() * rhs[0].imag() + lhs[0].imag() * rhs[0].real() + + lhs[1].real() * rhs[1].imag() + lhs[1].imag() * rhs[1].real() + + lhs[2].real() * rhs[2].imag() + lhs[2].imag() * rhs[2].real()); } }; @@ -186,7 +178,9 @@ struct OTDot< TinyVector,3> , TinyVector,3> > // ////////////////////////////////////////////////////////////////////// -template struct OTCross {}; +template +struct OTCross +{}; ////////////////////////////////////////////////////////////////////// // @@ -195,33 +189,30 @@ template struct OTCross {}; ////////////////////////////////////////////////////////////////////// template -struct OTCross< TinyVector , TinyVector > +struct OTCross, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const TinyVector& a, const TinyVector& b) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const TinyVector& a, const TinyVector& b) { - TinyVector bogusCross(-99999); + TinyVector bogusCross(-99999); return bogusCross; } }; template -struct OTCross< TinyVector , TinyVector > +struct OTCross, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const TinyVector& a, const TinyVector& b) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const TinyVector& a, const TinyVector& b) { - TinyVector cross; - cross[0] = a[1]*b[2] - a[2]*b[1]; - cross[1] = a[2]*b[0] - a[0]*b[2]; - cross[2] = a[0]*b[1] - a[1]*b[0]; + TinyVector cross; + cross[0] = a[1] * b[2] - a[2] * b[1]; + cross[1] = a[2] * b[0] - a[0] * b[2]; + cross[2] = a[0] * b[1] - a[1] * b[0]; return cross; } }; -} +} // namespace qmcplusplus #endif // OHMMS_TINYVECTOR_OPERATORS_H - diff --git a/src/Numerics/OhmmsPETE/TinyVectorTensorOps.h b/src/Numerics/OhmmsPETE/TinyVectorTensorOps.h index e2b723093..0a429b914 100644 --- a/src/Numerics/OhmmsPETE/TinyVectorTensorOps.h +++ b/src/Numerics/OhmmsPETE/TinyVectorTensorOps.h @@ -30,18 +30,17 @@ namespace qmcplusplus ////////////////////////////////////////////////////////////////////// template -struct OTDot< Tensor , TinyVector > +struct OTDot, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const Tensor& lhs, const TinyVector& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const Tensor& lhs, const TinyVector& rhs) { - TinyVector ret= TinyVector::DontInitialize(); - for (unsigned int i=0; i ret = TinyVector::DontInitialize(); + for (unsigned int i = 0; i < D; ++i) { - Type_t sum = lhs(i,0)*rhs[0]; - for (unsigned int j=1; j , TinyVector > template -struct OTDot< Tensor , TinyVector > +struct OTDot, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const Tensor& lhs, const TinyVector& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const Tensor& lhs, const TinyVector& rhs) { - return TinyVector( lhs[0]*rhs[0] ); + return TinyVector(lhs[0] * rhs[0]); } }; template -struct OTDot< Tensor , TinyVector > +struct OTDot, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const Tensor& lhs, const TinyVector& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const Tensor& lhs, const TinyVector& rhs) { - return TinyVector( lhs[0]*rhs[0] + lhs[1]*rhs[1] , - lhs[2]*rhs[0] + lhs[3]*rhs[1] ); + return TinyVector(lhs[0] * rhs[0] + lhs[1] * rhs[1], lhs[2] * rhs[0] + lhs[3] * rhs[1]); } }; template -struct OTDot< Tensor , TinyVector > +struct OTDot, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const Tensor& lhs, const TinyVector& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const Tensor& lhs, const TinyVector& rhs) { - return TinyVector( lhs[0]*rhs[0] + lhs[1]*rhs[1] + lhs[2]*rhs[2], - lhs[3]*rhs[0] + lhs[4]*rhs[1] + lhs[5]*rhs[2], - lhs[6]*rhs[0] + lhs[7]*rhs[1] + lhs[8]*rhs[2] ); + return TinyVector(lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2], + lhs[3] * rhs[0] + lhs[4] * rhs[1] + lhs[5] * rhs[2], + lhs[6] * rhs[0] + lhs[7] * rhs[1] + lhs[8] * rhs[2]); } }; template -struct OTDot< Tensor , TinyVector > +struct OTDot, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const Tensor& lhs, const TinyVector& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const Tensor& lhs, const TinyVector& rhs) { - return TinyVector( lhs[ 0]*rhs[0] + lhs[ 1]*rhs[1] + lhs[ 2]*rhs[2] + lhs[ 3]*rhs[3], - lhs[ 4]*rhs[0] + lhs[ 5]*rhs[1] + lhs[ 6]*rhs[2] + lhs[ 7]*rhs[3], - lhs[ 8]*rhs[0] + lhs[ 9]*rhs[1] + lhs[10]*rhs[2] + lhs[11]*rhs[3], - lhs[12]*rhs[0] + lhs[13]*rhs[1] + lhs[14]*rhs[2] + lhs[15]*rhs[3]); + return TinyVector(lhs[0] * rhs[0] + lhs[1] * rhs[1] + lhs[2] * rhs[2] + lhs[3] * rhs[3], + lhs[4] * rhs[0] + lhs[5] * rhs[1] + lhs[6] * rhs[2] + lhs[7] * rhs[3], + lhs[8] * rhs[0] + lhs[9] * rhs[1] + lhs[10] * rhs[2] + + lhs[11] * rhs[3], + lhs[12] * rhs[0] + lhs[13] * rhs[1] + lhs[14] * rhs[2] + + lhs[15] * rhs[3]); } }; @@ -106,18 +102,17 @@ struct OTDot< Tensor , TinyVector > ////////////////////////////////////////////////////////////////////// template -struct OTDot< TinyVector , Tensor > +struct OTDot, Tensor> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const TinyVector& lhs, const Tensor& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const TinyVector& lhs, const Tensor& rhs) { - TinyVector ret = TinyVector::DontInitialize(); - for (unsigned int i=0; i ret = TinyVector::DontInitialize(); + for (unsigned int i = 0; i < D; ++i) { - Type_t sum = lhs[0]*rhs(0,i); - for (unsigned int j=1; j , Tensor > template -struct OTDot< TinyVector , Tensor > +struct OTDot, Tensor> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const TinyVector& lhs, const Tensor& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const TinyVector& lhs, const Tensor& rhs) { - return TinyVector( lhs[0]*rhs[0] ); + return TinyVector(lhs[0] * rhs[0]); } }; template -struct OTDot< TinyVector , Tensor > +struct OTDot, Tensor> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const TinyVector& lhs, const Tensor& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const TinyVector& lhs, const Tensor& rhs) { - return TinyVector( lhs[0]*rhs(0,0) + lhs[1]*rhs(1,0) , - lhs[0]*rhs(0,1) + lhs[1]*rhs(1,1) ); + return TinyVector(lhs[0] * rhs(0, 0) + lhs[1] * rhs(1, 0), + lhs[0] * rhs(0, 1) + lhs[1] * rhs(1, 1)); } }; template -struct OTDot< TinyVector , Tensor > +struct OTDot, Tensor> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const TinyVector& lhs, const Tensor& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const TinyVector& lhs, const Tensor& rhs) { - return TinyVector( lhs[0]*rhs[0] + lhs[1]*rhs[3] + lhs[2]*rhs[6], - lhs[0]*rhs[1] + lhs[1]*rhs[4] + lhs[2]*rhs[7], - lhs[0]*rhs[2] + lhs[1]*rhs[5] + lhs[2]*rhs[8] ); + return TinyVector(lhs[0] * rhs[0] + lhs[1] * rhs[3] + lhs[2] * rhs[6], + lhs[0] * rhs[1] + lhs[1] * rhs[4] + lhs[2] * rhs[7], + lhs[0] * rhs[2] + lhs[1] * rhs[5] + lhs[2] * rhs[8]); } }; template -struct OTDot< TinyVector , Tensor > +struct OTDot, Tensor> { - typedef typename BinaryReturn::Type_t Type_t; - inline static TinyVector - apply(const TinyVector& lhs, const Tensor& rhs) + typedef typename BinaryReturn::Type_t Type_t; + inline static TinyVector apply(const TinyVector& lhs, const Tensor& rhs) { - return TinyVector( lhs[0]*rhs[0] + lhs[1]*rhs[4] + lhs[2]*rhs[ 8] + lhs[3]*rhs[12], - lhs[0]*rhs[1] + lhs[1]*rhs[5] + lhs[2]*rhs[ 9] + lhs[3]*rhs[13], - lhs[0]*rhs[2] + lhs[1]*rhs[6] + lhs[2]*rhs[10] + lhs[3]*rhs[14], - lhs[0]*rhs[3] + lhs[1]*rhs[7] + lhs[2]*rhs[11] + lhs[3]*rhs[15]); + return TinyVector(lhs[0] * rhs[0] + lhs[1] * rhs[4] + lhs[2] * rhs[8] + + lhs[3] * rhs[12], + lhs[0] * rhs[1] + lhs[1] * rhs[5] + lhs[2] * rhs[9] + + lhs[3] * rhs[13], + lhs[0] * rhs[2] + lhs[1] * rhs[6] + lhs[2] * rhs[10] + + lhs[3] * rhs[14], + lhs[0] * rhs[3] + lhs[1] * rhs[7] + lhs[2] * rhs[11] + + lhs[3] * rhs[15]); } }; @@ -182,7 +177,9 @@ struct OTDot< TinyVector , Tensor > // ////////////////////////////////////////////////////////////////////// -template struct OuterProduct {}; +template +struct OuterProduct +{}; ////////////////////////////////////////////////////////////////////// // @@ -191,44 +188,45 @@ template struct OuterProduct {}; ////////////////////////////////////////////////////////////////////// template -struct OuterProduct< TinyVector , TinyVector > +struct OuterProduct, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - typedef Tensor::Type_t,D> Return_t; - inline static Return_t - apply(const TinyVector& a, const TinyVector& b) + typedef typename BinaryReturn::Type_t Type_t; + typedef Tensor::Type_t, D> Return_t; + inline static Return_t apply(const TinyVector& a, const TinyVector& b) { return Return_t(); } }; template -struct OuterProduct< TinyVector , TinyVector > +struct OuterProduct, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - typedef Tensor::Type_t,2> Return_t; - inline static Return_t - apply(const TinyVector& a, const TinyVector& b) + typedef typename BinaryReturn::Type_t Type_t; + typedef Tensor::Type_t, 2> Return_t; + inline static Return_t apply(const TinyVector& a, const TinyVector& b) { - return Return_t(a[0]*b[0],a[0]*b[1], - a[1]*b[0],a[1]*b[1]); + return Return_t(a[0] * b[0], a[0] * b[1], a[1] * b[0], a[1] * b[1]); } }; template -struct OuterProduct< TinyVector , TinyVector > +struct OuterProduct, TinyVector> { - typedef typename BinaryReturn::Type_t Type_t; - typedef Tensor::Type_t,3> Return_t; - inline static Return_t - apply(const TinyVector& a, const TinyVector& b) + typedef typename BinaryReturn::Type_t Type_t; + typedef Tensor::Type_t, 3> Return_t; + inline static Return_t apply(const TinyVector& a, const TinyVector& b) { - return Return_t(a[0]*b[0],a[0]*b[1],a[0]*b[2], - a[1]*b[0],a[1]*b[1],a[1]*b[2], - a[2]*b[0],a[2]*b[1],a[2]*b[2]); + return Return_t(a[0] * b[0], + a[0] * b[1], + a[0] * b[2], + a[1] * b[0], + a[1] * b[1], + a[1] * b[2], + a[2] * b[0], + a[2] * b[1], + a[2] * b[2]); } }; -} -#endif // OHMMS_TINYVECTOR_DOTCROSS_H - +} // namespace qmcplusplus +#endif // OHMMS_TINYVECTOR_DOTCROSS_H diff --git a/src/Numerics/PETE/Combiners.h b/src/Numerics/PETE/Combiners.h index 6723951c4..95ef05364 100644 --- a/src/Numerics/PETE/Combiners.h +++ b/src/Numerics/PETE/Combiners.h @@ -82,29 +82,30 @@ namespace qmcplusplus // //----------------------------------------------------------------------------- -template struct Combine1 +template +struct Combine1 { typedef A Type_t; - inline static Type_t combine(const A &a, const Op &, const Tag &) - { - return a; - } + inline static Type_t combine(const A& a, const Op&, const Tag&) { return a; } }; -template struct Combine2 +template +struct Combine2 { // no default action. It's an error to not specialize this struct. }; -template struct Combine3 +template +struct Combine3 { typedef typename Combine2::Type_t Type1_t; typedef typename Combine2::Type_t Type_t; - inline static Type_t combine(const A &a, const B &b, const C &c, const Op &op, - const Tag &t) + inline static Type_t combine(const A& a, const B& b, const C& c, const Op& op, const Tag& t) { - return Combine2::combine( - Combine2::combine(a, b, op, t), c, op, t); + return Combine2::combine(Combine2::combine(a, b, op, t), + c, + op, + t); } }; @@ -125,23 +126,22 @@ template struct Combine3 // //----------------------------------------------------------------------------- -template -inline typename Combine1::Type_t -peteCombine(const A &a, const Op &op, const Tag &t) +template +inline typename Combine1::Type_t peteCombine(const A& a, const Op& op, const Tag& t) { return Combine1::combine(a, op, t); } -template +template inline typename Combine2::Type_t -peteCombine(const A &a, const B &b, const Op &op, const Tag &t) + peteCombine(const A& a, const B& b, const Op& op, const Tag& t) { return Combine2::combine(a, b, op, t); } -template +template inline typename Combine3::Type_t -peteCombine(const A &a, const B &b, const C &c, const Op &op, const Tag &t) + peteCombine(const A& a, const B& b, const C& c, const Op& op, const Tag& t) { return Combine3::combine(a, b, c, op, t); } @@ -170,31 +170,31 @@ struct TreeCombine PETE_EMPTY_CONSTRUCTORS(TreeCombine) }; -template struct Combine1 +template +struct Combine1 { typedef UnaryNode Type_t; - inline static Type_t combine(const A &a, const Op &op, const TreeCombine &t) + inline static Type_t combine(const A& a, const Op& op, const TreeCombine& t) { return Type_t(op, a); } }; -template struct Combine2 +template +struct Combine2 { typedef BinaryNode Type_t; - inline static Type_t combine(const A &a, const B &b, const Op &op, - const TreeCombine &t) + inline static Type_t combine(const A& a, const B& b, const Op& op, const TreeCombine& t) { return Type_t(op, a, b); } }; -template +template struct Combine3 { typedef TrinaryNode Type_t; - inline static Type_t combine(const A &a, const B &b, const C &c, const Op &op, - const TreeCombine &t) + inline static Type_t combine(const A& a, const B& b, const C& c, const Op& op, const TreeCombine& t) { return Type_t(op, a, b, c); } @@ -215,26 +215,25 @@ struct OpCombine PETE_EMPTY_CONSTRUCTORS(OpCombine) }; -template struct Combine1 +template +struct Combine1 { typedef typename UnaryReturn::Type_t Type_t; inline static Type_t combine(A a, Op op, OpCombine) { return op(a); } }; -template struct Combine2 +template +struct Combine2 { typedef typename BinaryReturn::Type_t Type_t; inline static Type_t combine(A a, B b, Op op, OpCombine) { return op(a, b); } }; -template +template struct Combine3 { typedef typename TrinaryReturn::Type_t Type_t; - inline static Type_t combine(A a, B b, C c, Op op, OpCombine) - { - return op(a, b, c); - } + inline static Type_t combine(A a, B b, C c, Op op, OpCombine) { return op(a, b, c); } }; //----------------------------------------------------------------------------- @@ -252,13 +251,11 @@ struct AndCombine PETE_EMPTY_CONSTRUCTORS(AndCombine) }; -template struct Combine2 +template +struct Combine2 { typedef bool Type_t; - inline static Type_t combine(bool a, bool b, Op, AndCombine) - { - return (a && b); - } + inline static Type_t combine(bool a, bool b, Op, AndCombine) { return (a && b); } }; //----------------------------------------------------------------------------- @@ -276,13 +273,11 @@ struct OrCombine PETE_EMPTY_CONSTRUCTORS(OrCombine) }; -template struct Combine2 +template +struct Combine2 { typedef bool Type_t; - inline static Type_t combine(bool a, bool b, Op, OrCombine) - { - return (a || b); - } + inline static Type_t combine(bool a, bool b, Op, OrCombine) { return (a || b); } }; //----------------------------------------------------------------------------- @@ -301,7 +296,8 @@ struct NullCombine PETE_EMPTY_CONSTRUCTORS(NullCombine) }; -template struct Combine2 +template +struct Combine2 { typedef int Type_t; inline static Type_t combine(int, int, Op, NullCombine) { return 0; } @@ -322,12 +318,13 @@ struct SumCombine PETE_EMPTY_CONSTRUCTORS(SumCombine) }; -template struct Combine2 +template +struct Combine2 { typedef int Type_t; inline static Type_t combine(int a, int b, Op, SumCombine) { return a + b; } }; -} +} // namespace qmcplusplus #endif // PETE_PETE_COMBINERS_H // ACL:rcsinfo diff --git a/src/Numerics/PETE/CreateLeaf.h b/src/Numerics/PETE/CreateLeaf.h index 3499bea77..e8db79398 100644 --- a/src/Numerics/PETE/CreateLeaf.h +++ b/src/Numerics/PETE/CreateLeaf.h @@ -42,11 +42,13 @@ namespace qmcplusplus #ifdef PETE_USER_DEFINED_EXPRESSION -template class Expression; +template +class Expression; #else -template class Expression +template +class Expression { public: // Type of the expression. @@ -55,11 +57,11 @@ template class Expression // Construct from an expression. - Expression(const T &expr) : expr_m(expr) {} + Expression(const T& expr) : expr_m(expr) {} // Accessor that returns the expression. - const Expression_t &expression() const { return expr_m; } + const Expression_t& expression() const { return expr_m; } private: // Store the expression by value since it is a temporary produced @@ -87,11 +89,12 @@ template class Expression // The general case is assumed to be a scalar, since users need to specialize // CreateLeaf for their container classes. -template struct CreateLeaf +template +struct CreateLeaf { typedef Scalar Leaf_t; - inline static Leaf_t make(const T &a) { return Scalar(a); } + inline static Leaf_t make(const T& a) { return Scalar(a); } }; #ifndef PETE_USER_DEFINED_EXPRESSION @@ -100,14 +103,12 @@ template struct CreateLeaf // to wrap the whole expression. (Expression>+Expression> // becomes Expression,BinaryNode<>>>) -template struct CreateLeaf> +template +struct CreateLeaf> { typedef typename Expression::Expression_t Leaf_t; - inline static const Leaf_t &make(const Expression &a) - { - return a.expression(); - } + inline static const Leaf_t& make(const Expression& a) { return a.expression(); } }; #endif // !PETE_USER_DEFINED_EXPRESSION @@ -124,12 +125,13 @@ template struct CreateLeaf> // Array+Array is another Array. //----------------------------------------------------------------------------- -template struct MakeReturn +template +struct MakeReturn { typedef Expression Expression_t; - inline static Expression_t make(const T &a) { return Expression_t(a); } + inline static Expression_t make(const T& a) { return Expression_t(a); } }; -} +} // namespace qmcplusplus #endif // PETE_PETE_CREATELEAF_H diff --git a/src/Numerics/PETE/ForEach.h b/src/Numerics/PETE/ForEach.h index caf9162b5..1a29ba95f 100644 --- a/src/Numerics/PETE/ForEach.h +++ b/src/Numerics/PETE/ForEach.h @@ -73,77 +73,82 @@ namespace qmcplusplus // Default behaviour assumes you're at a leaf. -template struct ForEach +template +struct ForEach { typedef typename LeafFunctor::Type_t Type_t; - inline static Type_t apply(const Expr &expr, const FTag &f, const CTag &) + inline static Type_t apply(const Expr& expr, const FTag& f, const CTag&) { return LeafFunctor::apply(expr, f); } }; -template -inline typename ForEach::Type_t -forEach(const Expr &e, const FTag &f, const CTag &c) +template +inline typename ForEach::Type_t forEach(const Expr& e, const FTag& f, const CTag& c) { return ForEach::apply(e, f, c); } -template +template struct ForEach, FTag, CTag> { typedef typename ForEach::Type_t TypeA_t; typedef typename Combine1::Type_t Type_t; - inline static Type_t apply(const UnaryNode &expr, const FTag &f, - const CTag &c) + inline static Type_t apply(const UnaryNode& expr, const FTag& f, const CTag& c) { - return Combine1::combine( - ForEach::apply(expr.child(), f, c), expr.operation(), c); + return Combine1::combine(ForEach::apply(expr.child(), f, c), + expr.operation(), + c); } }; -template +template struct ForEach, FTag, CTag> { typedef typename ForEach::Type_t TypeA_t; typedef typename ForEach::Type_t TypeB_t; typedef typename Combine2::Type_t Type_t; - inline static Type_t apply(const BinaryNode &expr, const FTag &f, - const CTag &c) + inline static Type_t apply(const BinaryNode& expr, const FTag& f, const CTag& c) { - return Combine2::combine( - ForEach::apply(expr.left(), f, c), - ForEach::apply(expr.right(), f, c), expr.operation(), c); + return Combine2::combine(ForEach::apply(expr.left(), + f, + c), + ForEach::apply(expr.right(), + f, + c), + expr.operation(), + c); } }; -template +template struct ForEach, FTag, CTag> { typedef typename ForEach::Type_t TypeA_t; typedef typename ForEach::Type_t TypeB_t; typedef typename ForEach::Type_t TypeC_t; typedef typename Combine3::Type_t Type_t; - inline static Type_t apply(const TrinaryNode &expr, - const FTag &f, const CTag &c) + inline static Type_t apply(const TrinaryNode& expr, const FTag& f, const CTag& c) { - return Combine3::combine( - ForEach::apply(expr.left(), f, c), - ForEach::apply(expr.middle(), f, c), - ForEach::apply(expr.right(), f, c), expr.operation(), c); + return Combine3:: + combine(ForEach::apply(expr.left(), f, c), + ForEach::apply(expr.middle(), f, c), + ForEach::apply(expr.right(), f, c), + expr.operation(), + c); } }; #ifndef PETE_USER_DEFINED_EXPRESSION -template class Expression; +template +class Expression; -template +template struct ForEach, FTag, CTag> { typedef typename ForEach::Type_t Type_t; - inline static Type_t apply(const Expression &expr, const FTag &f, - const CTag &c) + inline static Type_t apply(const Expression& expr, const FTag& f, const CTag& c) { return ForEach::apply(expr.expression(), f, c); } @@ -151,19 +156,19 @@ struct ForEach, FTag, CTag> #endif // !PETE_USER_DEFINED_EXPRESSION -template struct Reference; +template +struct Reference; -template +template struct ForEach, FTag, CTag> { typedef typename ForEach::Type_t Type_t; - inline static Type_t apply(const Reference &ref, const FTag &f, - const CTag &c) + inline static Type_t apply(const Reference& ref, const FTag& f, const CTag& c) { return ForEach::apply(ref.reference(), f, c); } }; -} +} // namespace qmcplusplus #endif // PETE_PETE_FOREACH_H diff --git a/src/Numerics/PETE/Functors.h b/src/Numerics/PETE/Functors.h index 473ab9de1..5b04892e9 100644 --- a/src/Numerics/PETE/Functors.h +++ b/src/Numerics/PETE/Functors.h @@ -72,9 +72,9 @@ namespace qmcplusplus // //----------------------------------------------------------------------------- -template struct LeafFunctor -{ -}; +template +struct LeafFunctor +{}; //----------------------------------------------------------------------------- // @@ -97,13 +97,11 @@ struct EvalLeaf1 inline int val1() const { return i1_m; } }; -template struct LeafFunctor, EvalLeaf1> +template +struct LeafFunctor, EvalLeaf1> { typedef T Type_t; - inline static const Type_t &apply(const Scalar &s, const EvalLeaf1 &) - { - return s.value(); - } + inline static const Type_t& apply(const Scalar& s, const EvalLeaf1&) { return s.value(); } }; // 2D @@ -116,13 +114,11 @@ struct EvalLeaf2 inline int val2() const { return i2_m; } }; -template struct LeafFunctor, EvalLeaf2> +template +struct LeafFunctor, EvalLeaf2> { typedef T Type_t; - inline static const Type_t &apply(const Scalar &s, const EvalLeaf2 &) - { - return s.value(); - } + inline static const Type_t& apply(const Scalar& s, const EvalLeaf2&) { return s.value(); } }; // 3D @@ -136,13 +132,11 @@ struct EvalLeaf3 inline int val3() const { return i3_m; } }; -template struct LeafFunctor, EvalLeaf3> +template +struct LeafFunctor, EvalLeaf3> { typedef T Type_t; - inline static const Type_t &apply(const Scalar &s, const EvalLeaf3 &) - { - return s.value(); - } + inline static const Type_t& apply(const Scalar& s, const EvalLeaf3&) { return s.value(); } }; // 4D @@ -150,23 +144,18 @@ template struct LeafFunctor, EvalLeaf3> struct EvalLeaf4 { int i1_m, i2_m, i3_m, i4_m; - inline EvalLeaf4(int i1, int i2, int i3, int i4) - : i1_m(i1), i2_m(i2), i3_m(i3), i4_m(i4) - { - } + inline EvalLeaf4(int i1, int i2, int i3, int i4) : i1_m(i1), i2_m(i2), i3_m(i3), i4_m(i4) {} inline int val1() const { return i1_m; } inline int val2() const { return i2_m; } inline int val3() const { return i3_m; } inline int val4() const { return i4_m; } }; -template struct LeafFunctor, EvalLeaf4> +template +struct LeafFunctor, EvalLeaf4> { typedef T Type_t; - inline static const Type_t &apply(const Scalar &s, const EvalLeaf4 &) - { - return s.value(); - } + inline static const Type_t& apply(const Scalar& s, const EvalLeaf4&) { return s.value(); } }; // 5D @@ -176,8 +165,7 @@ struct EvalLeaf5 int i1_m, i2_m, i3_m, i4_m, i5_m; inline EvalLeaf5(int i1, int i2, int i3, int i4, int i5) : i1_m(i1), i2_m(i2), i3_m(i3), i4_m(i4), i5_m(i5) - { - } + {} inline int val1() const { return i1_m; } inline int val2() const { return i2_m; } inline int val3() const { return i3_m; } @@ -185,13 +173,11 @@ struct EvalLeaf5 inline int val5() const { return i5_m; } }; -template struct LeafFunctor, EvalLeaf5> +template +struct LeafFunctor, EvalLeaf5> { typedef T Type_t; - inline static const Type_t &apply(const Scalar &s, const EvalLeaf5 &) - { - return s.value(); - } + inline static const Type_t& apply(const Scalar& s, const EvalLeaf5&) { return s.value(); } }; // 6D @@ -201,8 +187,7 @@ struct EvalLeaf6 int i1_m, i2_m, i3_m, i4_m, i5_m, i6_m; inline EvalLeaf6(int i1, int i2, int i3, int i4, int i5, int i6) : i1_m(i1), i2_m(i2), i3_m(i3), i4_m(i4), i5_m(i5), i6_m(i6) - { - } + {} inline int val1() const { return i1_m; } inline int val2() const { return i2_m; } inline int val3() const { return i3_m; } @@ -211,13 +196,11 @@ struct EvalLeaf6 inline int val6() const { return i6_m; } }; -template struct LeafFunctor, EvalLeaf6> +template +struct LeafFunctor, EvalLeaf6> { typedef T Type_t; - inline static const Type_t &apply(const Scalar &s, const EvalLeaf6 &) - { - return s.value(); - } + inline static const Type_t& apply(const Scalar& s, const EvalLeaf6&) { return s.value(); } }; // 7D @@ -227,8 +210,7 @@ struct EvalLeaf7 int i1_m, i2_m, i3_m, i4_m, i5_m, i6_m, i7_m; inline EvalLeaf7(int i1, int i2, int i3, int i4, int i5, int i6, int i7) : i1_m(i1), i2_m(i2), i3_m(i3), i4_m(i4), i5_m(i5), i6_m(i6), i7_m(i7) - { - } + {} inline int val1() const { return i1_m; } inline int val2() const { return i2_m; } inline int val3() const { return i3_m; } @@ -238,13 +220,11 @@ struct EvalLeaf7 inline int val7() const { return i7_m; } }; -template struct LeafFunctor, EvalLeaf7> +template +struct LeafFunctor, EvalLeaf7> { typedef T Type_t; - inline static const Type_t &apply(const Scalar &s, const EvalLeaf7 &) - { - return s.value(); - } + inline static const Type_t& apply(const Scalar& s, const EvalLeaf7&) { return s.value(); } }; //----------------------------------------------------------------------------- @@ -259,15 +239,15 @@ template struct LeafFunctor, EvalLeaf7> //----------------------------------------------------------------------------- struct IncrementLeaf -{ -}; +{}; -template struct LeafFunctor +template +struct LeafFunctor { typedef int Type_t; - inline static Type_t apply(const T &cl, const IncrementLeaf &) + inline static Type_t apply(const T& cl, const IncrementLeaf&) { - T &l = const_cast(cl); + T& l = const_cast(cl); ++l; return 0; } @@ -277,12 +257,13 @@ template struct LeafFunctor // Workaround for screwy CWPro 4.1 bug. -template struct LeafFunctor +template +struct LeafFunctor { typedef int Type_t; - inline static Type_t apply(const T *&const ci, const IncrementLeaf &) + inline static Type_t apply(const T*& const ci, const IncrementLeaf&) { - T *&i = const_cast(ci); + T*& i = const_cast(ci); ++i; return 0; } @@ -290,13 +271,11 @@ template struct LeafFunctor #endif -template struct LeafFunctor, IncrementLeaf> +template +struct LeafFunctor, IncrementLeaf> { typedef int Type_t; - inline static Type_t apply(const Scalar &, const IncrementLeaf &) - { - return 0; - } + inline static Type_t apply(const Scalar&, const IncrementLeaf&) { return 0; } }; //----------------------------------------------------------------------------- @@ -311,15 +290,15 @@ template struct LeafFunctor, IncrementLeaf> //----------------------------------------------------------------------------- struct DecrementLeaf -{ -}; +{}; -template struct LeafFunctor +template +struct LeafFunctor { typedef int Type_t; - inline static Type_t apply(const T &cl, const DecrementLeaf &) + inline static Type_t apply(const T& cl, const DecrementLeaf&) { - T &l = const_cast(cl); + T& l = const_cast(cl); --l; return 0; } @@ -327,25 +306,24 @@ template struct LeafFunctor #if defined(__MWERKS__) // Workaround for screwy CWPro 4.1 bug. -template struct LeafFunctor +template +struct LeafFunctor { typedef int Type_t; - inline static Type_t apply(const T *&const ci, const IncrementLeaf &) + inline static Type_t apply(const T*& const ci, const IncrementLeaf&) { - T *&i = const_cast(ci); + T*& i = const_cast(ci); --i; return 0; } }; #endif -template struct LeafFunctor, DecrementLeaf> +template +struct LeafFunctor, DecrementLeaf> { typedef int Type_t; - inline static Type_t apply(const Scalar &, const DecrementLeaf &) - { - return 0; - } + inline static Type_t apply(const Scalar&, const DecrementLeaf&) { return 0; } }; //----------------------------------------------------------------------------- @@ -360,37 +338,35 @@ template struct LeafFunctor, DecrementLeaf> //----------------------------------------------------------------------------- struct DereferenceLeaf -{ -}; +{}; -template +template struct LeafFunctor { typedef typename std::iterator_traits::value_type Type_t; - inline static Type_t apply(const ForwardIterator &i, const DereferenceLeaf &) - { - return *i; - } + inline static Type_t apply(const ForwardIterator& i, const DereferenceLeaf&) { return *i; } }; #if defined(__MWERKS__) // Workaround for screwy CWPro 4.1 bug. -template struct LeafFunctor +template +struct LeafFunctor { typedef T Type_t; - inline static Type_t apply(const T *i, const DereferenceLeaf &) { return *i; } + inline static Type_t apply(const T* i, const DereferenceLeaf&) { return *i; } }; #endif -template struct LeafFunctor, DereferenceLeaf> +template +struct LeafFunctor, DereferenceLeaf> { typedef T Type_t; - inline static const Type_t &apply(const Scalar &s, const DereferenceLeaf &) + inline static const Type_t& apply(const Scalar& s, const DereferenceLeaf&) { return s.value(); } }; -} +} // namespace qmcplusplus #endif // PETE_PETE_FUNCTORS_H diff --git a/src/Numerics/PETE/OperatorTags.h b/src/Numerics/PETE/OperatorTags.h index c8ebefe3f..7ef0938e0 100644 --- a/src/Numerics/PETE/OperatorTags.h +++ b/src/Numerics/PETE/OperatorTags.h @@ -34,13 +34,11 @@ namespace qmcplusplus { - struct OpAdd { PETE_EMPTY_CONSTRUCTORS(OpAdd) - template - inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + template + inline typename BinaryReturn::Type_t operator()(const T1& a, const T2& b) const { return (a + b); } @@ -49,9 +47,8 @@ struct OpAdd struct OpSubtract { PETE_EMPTY_CONSTRUCTORS(OpSubtract) - template - inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + template + inline typename BinaryReturn::Type_t operator()(const T1& a, const T2& b) const { return (a - b); } @@ -60,9 +57,8 @@ struct OpSubtract struct OpMultiply { PETE_EMPTY_CONSTRUCTORS(OpMultiply) - template - inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + template + inline typename BinaryReturn::Type_t operator()(const T1& a, const T2& b) const { return (a * b); } @@ -71,9 +67,8 @@ struct OpMultiply struct OpDivide { PETE_EMPTY_CONSTRUCTORS(OpDivide) - template - inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + template + inline typename BinaryReturn::Type_t operator()(const T1& a, const T2& b) const { return (a / b); } @@ -82,9 +77,8 @@ struct OpDivide struct OpMod { PETE_EMPTY_CONSTRUCTORS(OpMod) - template - inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + template + inline typename BinaryReturn::Type_t operator()(const T1& a, const T2& b) const { return (a % b); } @@ -94,104 +88,107 @@ struct OpMod struct OpAddAssign { PETE_EMPTY_CONSTRUCTORS(OpAddAssign) - template - inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + template + inline typename BinaryReturn::Type_t operator()(const T1& a, const T2& b) const { - (const_cast(a) += b); - return const_cast(a); + (const_cast(a) += b); + return const_cast(a); } }; -template struct BinaryReturn +template +struct BinaryReturn { - typedef T1 &Type_t; + typedef T1& Type_t; }; struct OpSubtractAssign { PETE_EMPTY_CONSTRUCTORS(OpSubtractAssign) - template + template inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + operator()(const T1& a, const T2& b) const { - (const_cast(a) -= b); - return const_cast(a); + (const_cast(a) -= b); + return const_cast(a); } }; -template struct BinaryReturn +template +struct BinaryReturn { - typedef T1 &Type_t; + typedef T1& Type_t; }; struct OpMultiplyAssign { PETE_EMPTY_CONSTRUCTORS(OpMultiplyAssign) - template + template inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + operator()(const T1& a, const T2& b) const { - (const_cast(a) *= b); - return const_cast(a); + (const_cast(a) *= b); + return const_cast(a); } }; -template struct BinaryReturn +template +struct BinaryReturn { - typedef T1 &Type_t; + typedef T1& Type_t; }; struct OpDivideAssign { PETE_EMPTY_CONSTRUCTORS(OpDivideAssign) - template + template inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + operator()(const T1& a, const T2& b) const { - (const_cast(a) /= b); - return const_cast(a); + (const_cast(a) /= b); + return const_cast(a); } }; -template struct BinaryReturn +template +struct BinaryReturn { - typedef T1 &Type_t; + typedef T1& Type_t; }; struct OpModAssign { PETE_EMPTY_CONSTRUCTORS(OpModAssign) - template - inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + template + inline typename BinaryReturn::Type_t operator()(const T1& a, const T2& b) const { - (const_cast(a) %= b); - return const_cast(a); + (const_cast(a) %= b); + return const_cast(a); } }; -template struct BinaryReturn +template +struct BinaryReturn { - typedef T1 &Type_t; + typedef T1& Type_t; }; struct OpAssign { PETE_EMPTY_CONSTRUCTORS(OpAssign) - template - inline typename BinaryReturn::Type_t - operator()(const T1 &a, const T2 &b) const + template + inline typename BinaryReturn::Type_t operator()(const T1& a, const T2& b) const { - return (const_cast(a) = b); + return (const_cast(a) = b); } }; -template struct BinaryReturn +template +struct BinaryReturn { - typedef T1 &Type_t; + typedef T1& Type_t; }; -} +} // namespace qmcplusplus #endif // PETE_PETE_OPERATORTAGS_H diff --git a/src/Numerics/PETE/PETE.h b/src/Numerics/PETE/PETE.h index 38ca20297..89c4292de 100644 --- a/src/Numerics/PETE/PETE.h +++ b/src/Numerics/PETE/PETE.h @@ -45,13 +45,13 @@ #define PETE_EMPTY_CONSTRUCTORS(CLASS) \ CLASS() {} \ - CLASS(const CLASS &) {} \ - CLASS &operator=(const CLASS &) { return *this; } + CLASS(const CLASS&) {} \ + CLASS& operator=(const CLASS&) { return *this; } #define PETE_EMPTY_CONSTRUCTORS_TEMPLATE(CLASS, ARG) \ CLASS() {} \ - CLASS(const CLASS &) {} \ - CLASS &operator=(const CLASS &) { return *this; } + CLASS(const CLASS&) {} \ + CLASS& operator=(const CLASS&) { return *this; } #else diff --git a/src/Numerics/PETE/Scalar.h b/src/Numerics/PETE/Scalar.h index f8718c28b..1153d7fc6 100644 --- a/src/Numerics/PETE/Scalar.h +++ b/src/Numerics/PETE/Scalar.h @@ -45,7 +45,8 @@ // //----------------------------------------------------------------------------- -template class Scalar +template +class Scalar { public: //--------------------------------------------------------------------------- @@ -56,46 +57,45 @@ template class Scalar //--------------------------------------------------------------------------- // Constructor from a single value. - inline Scalar(const T &t) : scalar_m(t) {} + inline Scalar(const T& t) : scalar_m(t) {} - template inline explicit Scalar(const T1 &t) : scalar_m(t) {} + template + inline explicit Scalar(const T1& t) : scalar_m(t) + {} //--------------------------------------------------------------------------- // Constructor with arbitary second/third arguments, which is/are ignored. // Needed for compatibility with tree node constructors taking an // arbitrary argument. - template - inline Scalar(const Scalar &s, const Arg &) : scalar_m(s.scalar_m) - { - } + template + inline Scalar(const Scalar& s, const Arg&) : scalar_m(s.scalar_m) + {} - template - inline Scalar(const Scalar &s, const Arg1 &, const Arg2 &) - : scalar_m(s.scalar_m) - { - } + template + inline Scalar(const Scalar& s, const Arg1&, const Arg2&) : scalar_m(s.scalar_m) + {} //--------------------------------------------------------------------------- // Copy constructor - inline Scalar(const Scalar &s) : scalar_m(s.scalar_m) {} + inline Scalar(const Scalar& s) : scalar_m(s.scalar_m) {} //--------------------------------------------------------------------------- // Return value. - inline const T &value() const { return scalar_m; } + inline const T& value() const { return scalar_m; } //--------------------------------------------------------------------------- // Assignment operators. - inline Scalar &operator=(const Scalar &rhs) + inline Scalar& operator=(const Scalar& rhs) { scalar_m = rhs.scalar_m; return *this; } - inline Scalar &operator=(const T &rhs) + inline Scalar& operator=(const T& rhs) { scalar_m = rhs; return *this; diff --git a/src/Numerics/PETE/TreeNodes.h b/src/Numerics/PETE/TreeNodes.h index 769f480f9..13c27d065 100644 --- a/src/Numerics/PETE/TreeNodes.h +++ b/src/Numerics/PETE/TreeNodes.h @@ -49,7 +49,8 @@ namespace qmcplusplus // //----------------------------------------------------------------------------- -template struct Reference +template +struct Reference { //--------------------------------------------------------------------------- // Export the type of thing we're referencing. @@ -59,27 +60,25 @@ template struct Reference //--------------------------------------------------------------------------- // Reference can be created from a const ref. - inline Reference(const T &reference) : reference_m(reference) {} + inline Reference(const T& reference) : reference_m(reference) {} //--------------------------------------------------------------------------- // Copy constructor - inline Reference(const Reference &model) : reference_m(model.reference()) - { - } + inline Reference(const Reference& model) : reference_m(model.reference()) {} //--------------------------------------------------------------------------- // Reference can be converted to a const ref - inline const T &reference() const { return reference_m; } + inline const T& reference() const { return reference_m; } //--------------------------------------------------------------------------- // Conversion operators. - operator const T &() const { return reference_m; } - operator T &() const { return const_cast(reference_m); } + operator const T&() const { return reference_m; } + operator T&() const { return const_cast(reference_m); } - const T &reference_m; + const T& reference_m; }; //----------------------------------------------------------------------------- @@ -95,18 +94,20 @@ template struct Reference // //----------------------------------------------------------------------------- -template struct DeReference +template +struct DeReference { - typedef const T &Return_t; + typedef const T& Return_t; typedef T Type_t; - static inline Return_t apply(const T &a) { return a; } + static inline Return_t apply(const T& a) { return a; } }; -template struct DeReference> +template +struct DeReference> { - typedef const T &Return_t; + typedef const T& Return_t; typedef T Type_t; - static inline Return_t apply(const Reference &a) { return a.reference(); } + static inline Return_t apply(const Reference& a) { return a.reference(); } }; //----------------------------------------------------------------------------- @@ -122,13 +123,14 @@ template struct DeReference> // //----------------------------------------------------------------------------- -template class UnaryNode +template +class UnaryNode { public: //--------------------------------------------------------------------------- // Accessors making the operation and child available to the outside. - inline const Op &operation() const { return op_m; } + inline const Op& operation() const { return op_m; } inline typename DeReference::Return_t child() const { @@ -138,31 +140,26 @@ template class UnaryNode //--------------------------------------------------------------------------- // Constructor using both a operation and the child. - inline UnaryNode(const Op &o, const Child &c) : op_m(o), child_m(c) {} + inline UnaryNode(const Op& o, const Child& c) : op_m(o), child_m(c) {} //--------------------------------------------------------------------------- // Constructor using just the child. - inline UnaryNode(const Child &c) : child_m(c) {} + inline UnaryNode(const Child& c) : child_m(c) {} //--------------------------------------------------------------------------- // Copy constructor. - inline UnaryNode(const UnaryNode &t) - : op_m(t.operation()), child_m(t.child()) - { - } + inline UnaryNode(const UnaryNode& t) : op_m(t.operation()), child_m(t.child()) {} //--------------------------------------------------------------------------- // Constructor using a UnaryNode with a different child and/or a different // storage tag. Note: for this to work, a Child must be constructable // from an OtherChild. - template - inline UnaryNode(const UnaryNode &t) - : op_m(t.operation()), child_m(t.child()) - { - } + template + inline UnaryNode(const UnaryNode& t) : op_m(t.operation()), child_m(t.child()) + {} //--------------------------------------------------------------------------- // Constructor using a UnaryNode with a different child, @@ -170,11 +167,10 @@ template class UnaryNode // Note: for this to work, a Child must be constructable // from an OtherChild and an Arg. - template - inline UnaryNode(const UnaryNode &t, const Arg &a) + template + inline UnaryNode(const UnaryNode& t, const Arg& a) : op_m(t.operation()), child_m(t.child(), a) - { - } + {} //--------------------------------------------------------------------------- // Constructor using a BinaryNode with a different Child and @@ -182,12 +178,10 @@ template class UnaryNode // Note: for this to work, a Child must be constructable // from an OtherChild and an Arg1 & Arg2. - template - inline UnaryNode(const UnaryNode &t, const Arg1 &a1, - const Arg2 &a2) + template + inline UnaryNode(const UnaryNode& t, const Arg1& a1, const Arg2& a2) : op_m(t.operation()), child_m(t.child(), a1, a2) - { - } + {} private: Op op_m; @@ -208,13 +202,14 @@ template class UnaryNode // //----------------------------------------------------------------------------- -template class BinaryNode +template +class BinaryNode { public: //--------------------------------------------------------------------------- // Accessors making the operation and children available to the outside. - inline const Op &operation() const { return op_m; } + inline const Op& operation() const { return op_m; } inline typename DeReference::Return_t left() const { @@ -229,34 +224,29 @@ template class BinaryNode //--------------------------------------------------------------------------- // Constructor using both the operation and the two children. - inline BinaryNode(const Op &o, const Left &l, const Right &r) - : op_m(o), left_m(l), right_m(r) - { - } + inline BinaryNode(const Op& o, const Left& l, const Right& r) : op_m(o), left_m(l), right_m(r) {} //--------------------------------------------------------------------------- // Constructor using just the two children. - inline BinaryNode(const Left &l, const Right &r) : left_m(l), right_m(r) {} + inline BinaryNode(const Left& l, const Right& r) : left_m(l), right_m(r) {} //--------------------------------------------------------------------------- // Copy constructor. - inline BinaryNode(const BinaryNode &t) + inline BinaryNode(const BinaryNode& t) : op_m(t.operation()), left_m(t.left()), right_m(t.right()) - { - } + {} //--------------------------------------------------------------------------- // Constructor using a BinaryNode with a different Left/Right. // Note: for this to work, the Left/Right must be constructable // from an OtherLeft/OtherRight. - template - inline BinaryNode(const BinaryNode &t) + template + inline BinaryNode(const BinaryNode& t) : op_m(t.operation()), left_m(t.left()), right_m(t.right()) - { - } + {} //--------------------------------------------------------------------------- // Constructor using a BinaryNode with a different Left/Right and @@ -264,12 +254,10 @@ template class BinaryNode // Note: for this to work, a Left/Right must be constructable // from an OtherLeft/OtherRight and an Arg. - template - inline BinaryNode(const BinaryNode &t, - const Arg &a) + template + inline BinaryNode(const BinaryNode& t, const Arg& a) : op_m(t.operation()), left_m(t.left(), a), right_m(t.right(), a) - { - } + {} //--------------------------------------------------------------------------- // Constructor using a BinaryNode with a different Left/Right and @@ -277,13 +265,10 @@ template class BinaryNode // Note: for this to work, a Left/Right must be constructable // from an OtherLeft/OtherRight and an Arg1 & Arg2. - template - inline BinaryNode(const BinaryNode &t, - const Arg1 &a1, const Arg2 &a2) - : op_m(t.operation()), left_m(t.left(), a1, a2), - right_m(t.right(), a1, a2) - { - } + template + inline BinaryNode(const BinaryNode& t, const Arg1& a1, const Arg2& a2) + : op_m(t.operation()), left_m(t.left(), a1, a2), right_m(t.right(), a1, a2) + {} private: //--------------------------------------------------------------------------- @@ -311,13 +296,14 @@ template class BinaryNode // //----------------------------------------------------------------------------- -template class TrinaryNode +template +class TrinaryNode { public: //--------------------------------------------------------------------------- // Accessors making the operation and children available to the outside. - inline const Op &operation() const { return op_m; } + inline const Op& operation() const { return op_m; } inline typename DeReference::Return_t left() const { @@ -337,41 +323,33 @@ template class TrinaryNode //--------------------------------------------------------------------------- // Constructor using the operation and three children. - inline TrinaryNode(const Op &o, const Left &l, const Middle &m, - const Right &r) + inline TrinaryNode(const Op& o, const Left& l, const Middle& m, const Right& r) : op_m(o), left_m(l), middle_m(m), right_m(r) - { - } + {} //--------------------------------------------------------------------------- // Constructor with just the three children. - inline TrinaryNode(const Left &l, const Middle &m, const Right &r) + inline TrinaryNode(const Left& l, const Middle& m, const Right& r) : left_m(l), middle_m(m), right_m(r) - { - } + {} //--------------------------------------------------------------------------- // Copy constructor. - inline TrinaryNode(const TrinaryNode &t) - : op_m(t.operation()), left_m(t.left()), middle_m(t.middle()), - right_m(t.right()) - { - } + inline TrinaryNode(const TrinaryNode& t) + : op_m(t.operation()), left_m(t.left()), middle_m(t.middle()), right_m(t.right()) + {} //--------------------------------------------------------------------------- // Constructor using a TrinaryNode with a different Left/Middle/Right. // Note: for this to work, the Left/Middle/Right must be constructable // from an OtherLeft/OtherMiddle/OtherRight. - template - inline TrinaryNode( - const TrinaryNode &t) - : op_m(t.operation()), left_m(t.left()), middle_m(t.middle()), - right_m(t.right()) - { - } + template + inline TrinaryNode(const TrinaryNode& t) + : op_m(t.operation()), left_m(t.left()), middle_m(t.middle()), right_m(t.right()) + {} //--------------------------------------------------------------------------- // Constructor using a TrinaryNode with a different Left/Middle/Right and @@ -379,14 +357,10 @@ template class TrinaryNode // Note: for this to work, a Left/Middle/Right must be constructable // from an OtherLeft/OtherMiddle/OtherRight and an Arg. - template - inline TrinaryNode( - const TrinaryNode &t, - const Arg &a) - : op_m(t.operation()), left_m(t.left(), a), middle_m(t.middle(), a), - right_m(t.right(), a) - { - } + template + inline TrinaryNode(const TrinaryNode& t, const Arg& a) + : op_m(t.operation()), left_m(t.left(), a), middle_m(t.middle(), a), right_m(t.right(), a) + {} //--------------------------------------------------------------------------- // Constructor using a TrinaryNode with a different Left/Middle/Right and @@ -394,15 +368,15 @@ template class TrinaryNode // Note: for this to work, a Left/Middle/Right must be constructable // from an OtherLeft/OtherMiddle/OtherRight and an Arg1 & Arg2. - template - inline TrinaryNode( - const TrinaryNode &t, - const Arg1 &a1, const Arg2 &a2) - : op_m(t.operation()), left_m(t.left(), a1, a2), - middle_m(t.middle(), a1, a2), right_m(t.right(), a1, a2) - { - } + template + inline TrinaryNode(const TrinaryNode& t, + const Arg1& a1, + const Arg2& a2) + : op_m(t.operation()), + left_m(t.left(), a1, a2), + middle_m(t.middle(), a1, a2), + right_m(t.right(), a1, a2) + {} private: //--------------------------------------------------------------------------- @@ -413,7 +387,7 @@ template class TrinaryNode Middle middle_m; Right right_m; }; -} +} // namespace qmcplusplus #endif // PETE_PETE_TREENODES_H // ACL:rcsinfo diff --git a/src/Numerics/PETE/TypeComputations.h b/src/Numerics/PETE/TypeComputations.h index 09d98331d..93976d67c 100644 --- a/src/Numerics/PETE/TypeComputations.h +++ b/src/Numerics/PETE/TypeComputations.h @@ -60,7 +60,8 @@ namespace qmcplusplus // //----------------------------------------------------------------------------- -template struct UnaryReturn +template +struct UnaryReturn { typedef T Type_t; }; @@ -78,266 +79,316 @@ template struct UnaryReturn // Base template: don't do anything by default. -template struct Promote +template +struct Promote { typedef T1 Type_t; }; // bool -template <> struct Promote +template<> +struct Promote { typedef bool Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef char Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef short Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef int Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef long Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; // char -template <> struct Promote +template<> +struct Promote { typedef char Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef char Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef short Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef int Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef long Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; // short -template <> struct Promote +template<> +struct Promote { typedef short Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef short Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef short Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef int Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef long Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; // int -template <> struct Promote +template<> +struct Promote { typedef int Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef int Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef int Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef int Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef long Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; // long -template <> struct Promote +template<> +struct Promote { typedef long Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef long Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef long Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef long Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef long Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; // float -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef float Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; // double -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; -template <> struct Promote +template<> +struct Promote { typedef double Type_t; }; @@ -375,7 +426,8 @@ template <> struct Promote // //----------------------------------------------------------------------------- -template struct BinaryReturn +template +struct BinaryReturn { typedef typename Promote::Type_t Type_t; }; @@ -397,11 +449,12 @@ template struct BinaryReturn // //----------------------------------------------------------------------------- -template struct TrinaryReturn +template +struct TrinaryReturn { typedef typename BinaryReturn::Type_t Type_t; }; -} +} // namespace qmcplusplus #endif // PETE_PETE_TYPE_COMPUTATIONS_H diff --git a/src/Numerics/PosTransformer.h b/src/Numerics/PosTransformer.h index 104e95995..c13e13145 100644 --- a/src/Numerics/PosTransformer.h +++ b/src/Numerics/PosTransformer.h @@ -19,7 +19,6 @@ namespace qmcplusplus { - /** General conversion function from AoS[nrows][ncols] to SoA[ncols][ldb] * @param nrows the first dimension * @param ncols the second dimension @@ -30,13 +29,12 @@ namespace qmcplusplus * * Modeled after blas/lapack for lda/ldb */ -template -void PosAoS2SoA(int nrows, int ncols, const T1 *restrict iptr, int lda, - T2 *restrict out, int ldb) +template +void PosAoS2SoA(int nrows, int ncols, const T1* restrict iptr, int lda, T2* restrict out, int ldb) { - T2 *restrict x = out; - T2 *restrict y = out + ldb; - T2 *restrict z = out + 2 * ldb; + T2* restrict x = out; + T2* restrict y = out + ldb; + T2* restrict z = out + 2 * ldb; #pragma omp simd aligned(x, y, z) for (int i = 0; i < nrows; ++i) { @@ -56,13 +54,12 @@ void PosAoS2SoA(int nrows, int ncols, const T1 *restrict iptr, int lda, * * Modeled after blas/lapack for lda/ldb */ -template -void PosSoA2AoS(int nrows, int ncols, const T1 *restrict iptr, int lda, - T2 *restrict out, int ldb) +template +void PosSoA2AoS(int nrows, int ncols, const T1* restrict iptr, int lda, T2* restrict out, int ldb) { - const T1 *restrict x = iptr; - const T1 *restrict y = iptr + lda; - const T1 *restrict z = iptr + 2 * lda; + const T1* restrict x = iptr; + const T1* restrict y = iptr + lda; + const T1* restrict z = iptr + 2 * lda; #pragma omp simd aligned(x, y, z) for (int i = 0; i < nrows; ++i) { @@ -72,5 +69,5 @@ void PosSoA2AoS(int nrows, int ncols, const T1 *restrict iptr, int lda, } } -} +} // namespace qmcplusplus #endif diff --git a/src/Numerics/Spline2/MultiBspline.hpp b/src/Numerics/Spline2/MultiBspline.hpp index f9a8d28f2..9009718ed 100644 --- a/src/Numerics/Spline2/MultiBspline.hpp +++ b/src/Numerics/Spline2/MultiBspline.hpp @@ -28,34 +28,53 @@ namespace qmcplusplus { - -template struct MultiBspline +template +struct MultiBspline { - /// define the einspline object type using spliner_type = typename bspline_traits::SplineType; MultiBspline() {} - MultiBspline(const MultiBspline &in) = delete; - MultiBspline &operator=(const MultiBspline &in) = delete; + MultiBspline(const MultiBspline& in) = delete; + MultiBspline& operator=(const MultiBspline& in) = delete; /** compute values vals[0,num_splines) * * The base address for vals, grads and lapl are set by the callers, e.g., * evaluate_vgh(r,psi,grad,hess,ip). */ - void evaluate_v(const spliner_type *restrict spline_m, T x, T y, T z, T *restrict vals, size_t num_splines) const; - - void evaluate_vgl(const spliner_type *restrict spline_m, T x, T y, T z, T *restrict vals, T *restrict grads, - T *restrict lapl, size_t num_splines) const; - - void evaluate_vgh(const spliner_type *restrict spline_m, T x, T y, T z, T *restrict vals, T *restrict grads, - T *restrict hess, size_t num_splines) const; + void evaluate_v(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, + size_t num_splines) const; + + void evaluate_vgl(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, + T* restrict grads, + T* restrict lapl, + size_t num_splines) const; + + void evaluate_vgh(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, + T* restrict grads, + T* restrict hess, + size_t num_splines) const; }; -template -inline void MultiBspline::evaluate_v(const spliner_type *restrict spline_m, - T x, T y, T z, T *restrict vals, +template +inline void MultiBspline::evaluate_v(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, size_t num_splines) const { x -= spline_m->x_grid.start; @@ -63,12 +82,9 @@ inline void MultiBspline::evaluate_v(const spliner_type *restrict spline_m, z -= spline_m->z_grid.start; T tx, ty, tz; int ix, iy, iz; - SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, - spline_m->x_grid.num - 1); - SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, - spline_m->y_grid.num - 1); - SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, - spline_m->z_grid.num - 1); + SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, spline_m->x_grid.num - 1); + SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, spline_m->y_grid.num - 1); + SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, spline_m->z_grid.num - 1); T a[4], b[4], c[4]; MultiBsplineData::compute_prefactors(a, tx); @@ -86,36 +102,35 @@ inline void MultiBspline::evaluate_v(const spliner_type *restrict spline_m, for (size_t i = 0; i < 4; i++) for (size_t j = 0; j < 4; j++) { - const T pre00 = a[i] * b[j]; - const T *restrict coefs = - spline_m->coefs + ((ix + i) * xs + (iy + j) * ys + iz * zs); + const T pre00 = a[i] * b[j]; + const T* restrict coefs = spline_m->coefs + ((ix + i) * xs + (iy + j) * ys + iz * zs); ASSUME_ALIGNED(coefs); //#pragma omp simd for (size_t n = 0; n < num_splines; n++) - vals[n] += - pre00 * (c[0] * coefs[n] + c[1] * coefs[n + zs] + - c[2] * coefs[n + 2 * zs] + c[3] * coefs[n + 3 * zs]); + vals[n] += pre00 * + (c[0] * coefs[n] + c[1] * coefs[n + zs] + c[2] * coefs[n + 2 * zs] + + c[3] * coefs[n + 3 * zs]); } } -template -inline void -MultiBspline::evaluate_vgl(const spliner_type *restrict spline_m, - T x, T y, T z, T *restrict vals, - T *restrict grads, T *restrict lapl, - size_t num_splines) const +template +inline void MultiBspline::evaluate_vgl(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, + T* restrict grads, + T* restrict lapl, + size_t num_splines) const { x -= spline_m->x_grid.start; y -= spline_m->y_grid.start; z -= spline_m->z_grid.start; T tx, ty, tz; int ix, iy, iz; - SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, - spline_m->x_grid.num - 1); - SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, - spline_m->y_grid.num - 1); - SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, - spline_m->z_grid.num - 1); + SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, spline_m->x_grid.num - 1); + SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, spline_m->y_grid.num - 1); + SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, spline_m->z_grid.num - 1); T a[4], b[4], c[4], da[4], db[4], dc[4], d2a[4], d2b[4], d2c[4]; @@ -130,17 +145,17 @@ MultiBspline::evaluate_vgl(const spliner_type *restrict spline_m, const size_t out_offset = spline_m->num_splines; ASSUME_ALIGNED(vals); - T *restrict gx = grads; + T* restrict gx = grads; ASSUME_ALIGNED(gx); - T *restrict gy = grads + out_offset; + T* restrict gy = grads + out_offset; ASSUME_ALIGNED(gy); - T *restrict gz = grads + 2 * out_offset; + T* restrict gz = grads + 2 * out_offset; ASSUME_ALIGNED(gz); - T *restrict lx = lapl; + T* restrict lx = lapl; ASSUME_ALIGNED(lx); - T *restrict ly = lapl + out_offset; + T* restrict ly = lapl + out_offset; ASSUME_ALIGNED(ly); - T *restrict lz = lapl + 2 * out_offset; + T* restrict lz = lapl + 2 * out_offset; ASSUME_ALIGNED(lz); std::fill(vals, vals + num_splines, T()); @@ -154,7 +169,6 @@ MultiBspline::evaluate_vgl(const spliner_type *restrict spline_m, for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { - const T pre20 = d2a[i] * b[j]; const T pre10 = da[i] * b[j]; const T pre00 = a[i] * b[j]; @@ -162,14 +176,13 @@ MultiBspline::evaluate_vgl(const spliner_type *restrict spline_m, const T pre01 = a[i] * db[j]; const T pre02 = a[i] * d2b[j]; - const T *restrict coefs = - spline_m->coefs + ((ix + i) * xs + (iy + j) * ys + iz * zs); + const T* restrict coefs = spline_m->coefs + ((ix + i) * xs + (iy + j) * ys + iz * zs); ASSUME_ALIGNED(coefs); - const T *restrict coefszs = coefs + zs; + const T* restrict coefszs = coefs + zs; ASSUME_ALIGNED(coefszs); - const T *restrict coefs2zs = coefs + 2 * zs; + const T* restrict coefs2zs = coefs + 2 * zs; ASSUME_ALIGNED(coefs2zs); - const T *restrict coefs3zs = coefs + 3 * zs; + const T* restrict coefs3zs = coefs + 3 * zs; ASSUME_ALIGNED(coefs3zs); #pragma noprefetch @@ -181,12 +194,9 @@ MultiBspline::evaluate_vgl(const spliner_type *restrict spline_m, const T coefsv2zs = coefs2zs[n]; const T coefsv3zs = coefs3zs[n]; - T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + - c[3] * coefsv3zs; - T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + - dc[3] * coefsv3zs; - T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + - d2c[3] * coefsv3zs; + T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + c[3] * coefsv3zs; + T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + dc[3] * coefsv3zs; + T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + d2c[3] * coefsv3zs; gx[n] += pre10 * sum0; gy[n] += pre01 * sum0; gz[n] += pre00 * sum1; @@ -215,14 +225,16 @@ MultiBspline::evaluate_vgl(const spliner_type *restrict spline_m, } } -template -inline void -MultiBspline::evaluate_vgh(const spliner_type *restrict spline_m, - T x, T y, T z, T *restrict vals, - T *restrict grads, T *restrict hess, - size_t num_splines) const +template +inline void MultiBspline::evaluate_vgh(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, + T* restrict grads, + T* restrict hess, + size_t num_splines) const { - int ix, iy, iz; T tx, ty, tz; T a[4], b[4], c[4], da[4], db[4], dc[4], d2a[4], d2b[4], d2c[4]; @@ -230,12 +242,9 @@ MultiBspline::evaluate_vgh(const spliner_type *restrict spline_m, x -= spline_m->x_grid.start; y -= spline_m->y_grid.start; z -= spline_m->z_grid.start; - SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, - spline_m->x_grid.num - 1); - SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, - spline_m->y_grid.num - 1); - SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, - spline_m->z_grid.num - 1); + SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, spline_m->x_grid.num - 1); + SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, spline_m->y_grid.num - 1); + SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, spline_m->z_grid.num - 1); MultiBsplineData::compute_prefactors(a, da, d2a, tx); MultiBsplineData::compute_prefactors(b, db, d2b, ty); @@ -248,24 +257,24 @@ MultiBspline::evaluate_vgh(const spliner_type *restrict spline_m, const size_t out_offset = spline_m->num_splines; ASSUME_ALIGNED(vals); - T *restrict gx = grads; + T* restrict gx = grads; ASSUME_ALIGNED(gx); - T *restrict gy = grads + out_offset; + T* restrict gy = grads + out_offset; ASSUME_ALIGNED(gy); - T *restrict gz = grads + 2 * out_offset; + T* restrict gz = grads + 2 * out_offset; ASSUME_ALIGNED(gz); - T *restrict hxx = hess; + T* restrict hxx = hess; ASSUME_ALIGNED(hxx); - T *restrict hxy = hess + out_offset; + T* restrict hxy = hess + out_offset; ASSUME_ALIGNED(hxy); - T *restrict hxz = hess + 2 * out_offset; + T* restrict hxz = hess + 2 * out_offset; ASSUME_ALIGNED(hxz); - T *restrict hyy = hess + 3 * out_offset; + T* restrict hyy = hess + 3 * out_offset; ASSUME_ALIGNED(hyy); - T *restrict hyz = hess + 4 * out_offset; + T* restrict hyz = hess + 4 * out_offset; ASSUME_ALIGNED(hyz); - T *restrict hzz = hess + 5 * out_offset; + T* restrict hzz = hess + 5 * out_offset; ASSUME_ALIGNED(hzz); std::fill(vals, vals + num_splines, T()); @@ -282,14 +291,13 @@ MultiBspline::evaluate_vgh(const spliner_type *restrict spline_m, for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { - const T *restrict coefs = - spline_m->coefs + ((ix + i) * xs + (iy + j) * ys + iz * zs); + const T* restrict coefs = spline_m->coefs + ((ix + i) * xs + (iy + j) * ys + iz * zs); ASSUME_ALIGNED(coefs); - const T *restrict coefszs = coefs + zs; + const T* restrict coefszs = coefs + zs; ASSUME_ALIGNED(coefszs); - const T *restrict coefs2zs = coefs + 2 * zs; + const T* restrict coefs2zs = coefs + 2 * zs; ASSUME_ALIGNED(coefs2zs); - const T *restrict coefs3zs = coefs + 3 * zs; + const T* restrict coefs3zs = coefs + 3 * zs; ASSUME_ALIGNED(coefs3zs); const T pre20 = d2a[i] * b[j]; @@ -303,18 +311,14 @@ MultiBspline::evaluate_vgh(const spliner_type *restrict spline_m, #pragma omp simd for (int n = 0; n < iSplitPoint; n++) { - T coefsv = coefs[n]; T coefsvzs = coefszs[n]; T coefsv2zs = coefs2zs[n]; T coefsv3zs = coefs3zs[n]; - T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + - c[3] * coefsv3zs; - T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + - dc[3] * coefsv3zs; - T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + - d2c[3] * coefsv3zs; + T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + c[3] * coefsv3zs; + T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + dc[3] * coefsv3zs; + T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + d2c[3] * coefsv3zs; hxx[n] += pre20 * sum0; hxy[n] += pre11 * sum0; @@ -342,9 +346,9 @@ MultiBspline::evaluate_vgh(const spliner_type *restrict spline_m, #pragma omp simd for (int n = 0; n < num_splines; n++) { - gx[n] *= dxInv; - gy[n] *= dyInv; - gz[n] *= dzInv; + gx[n] *= dxInv; + gy[n] *= dyInv; + gz[n] *= dzInv; hxx[n] *= dxx; hyy[n] *= dyy; hzz[n] *= dzz; @@ -354,5 +358,5 @@ MultiBspline::evaluate_vgh(const spliner_type *restrict spline_m, } } -} /** qmcplusplus namespace */ +} // namespace qmcplusplus #endif diff --git a/src/Numerics/Spline2/MultiBsplineData.cpp b/src/Numerics/Spline2/MultiBsplineData.cpp index 14d4855f0..ebcda29e5 100644 --- a/src/Numerics/Spline2/MultiBsplineData.cpp +++ b/src/Numerics/Spline2/MultiBsplineData.cpp @@ -20,37 +20,56 @@ namespace qmcplusplus { /** initialization of static data for MultiBsplineData */ -template <> -QMC_ALIGNAS const float MultiBsplineData::A44[16] = { - -1.0f / 6.0f, 3.0f / 6.0f, -3.0f / 6.0f, 1.0f / 6.0f, - 3.0f / 6.0f, -6.0f / 6.0f, 0.0f / 6.0f, 4.0f / 6.0f, - -3.0f / 6.0f, 3.0f / 6.0f, 3.0f / 6.0f, 1.0f / 6.0f, - 1.0f / 6.0f, 0.0f / 6.0f, 0.0f / 6.0f, 0.0f / 6.0f}; +template<> +QMC_ALIGNAS const float MultiBsplineData::A44[16] = {-1.0f / 6.0f, + 3.0f / 6.0f, + -3.0f / 6.0f, + 1.0f / 6.0f, + 3.0f / 6.0f, + -6.0f / 6.0f, + 0.0f / 6.0f, + 4.0f / 6.0f, + -3.0f / 6.0f, + 3.0f / 6.0f, + 3.0f / 6.0f, + 1.0f / 6.0f, + 1.0f / 6.0f, + 0.0f / 6.0f, + 0.0f / 6.0f, + 0.0f / 6.0f}; -template <> -QMC_ALIGNAS const float MultiBsplineData::dA44[16] = { - 0.0f, -0.5f, 1.0f, -0.5f, 0.0f, 1.5f, -2.0f, 0.0f, - 0.0f, -1.5f, 1.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}; +template<> +QMC_ALIGNAS const float MultiBsplineData::dA44[16] = + {0.0f, -0.5f, 1.0f, -0.5f, 0.0f, 1.5f, -2.0f, 0.0f, 0.0f, -1.5f, 1.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}; -template <> -QMC_ALIGNAS const float MultiBsplineData::d2A44[16] = { - 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 3.0f, -2.0f, - 0.0f, 0.0f, -3.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f}; +template<> +QMC_ALIGNAS const float MultiBsplineData::d2A44[16] = + {0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 3.0f, -2.0f, 0.0f, 0.0f, -3.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f}; /** initialization of static data for MultiBsplineData */ -template <> -QMC_ALIGNAS const double MultiBsplineData::A44[16] = { - -1.0 / 6.0, 3.0 / 6.0, -3.0 / 6.0, 1.0 / 6.0, 3.0 / 6.0, -6.0 / 6.0, - 0.0 / 6.0, 4.0 / 6.0, -3.0 / 6.0, 3.0 / 6.0, 3.0 / 6.0, 1.0 / 6.0, - 1.0 / 6.0, 0.0 / 6.0, 0.0 / 6.0, 0.0 / 6.0}; +template<> +QMC_ALIGNAS const double MultiBsplineData::A44[16] = {-1.0 / 6.0, + 3.0 / 6.0, + -3.0 / 6.0, + 1.0 / 6.0, + 3.0 / 6.0, + -6.0 / 6.0, + 0.0 / 6.0, + 4.0 / 6.0, + -3.0 / 6.0, + 3.0 / 6.0, + 3.0 / 6.0, + 1.0 / 6.0, + 1.0 / 6.0, + 0.0 / 6.0, + 0.0 / 6.0, + 0.0 / 6.0}; -template <> -QMC_ALIGNAS const double MultiBsplineData::dA44[16] = { - 0.0, -0.5, 1.0, -0.5, 0.0, 1.5, -2.0, 0.0, - 0.0, -1.5, 1.0, 0.5, 0.0, 0.5, 0.0, 0.0}; +template<> +QMC_ALIGNAS const double MultiBsplineData::dA44[16] = + {0.0, -0.5, 1.0, -0.5, 0.0, 1.5, -2.0, 0.0, 0.0, -1.5, 1.0, 0.5, 0.0, 0.5, 0.0, 0.0}; -template <> -QMC_ALIGNAS const double MultiBsplineData::d2A44[16] = { - 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 3.0, -2.0, - 0.0, 0.0, -3.0, 1.0, 0.0, 0.0, 1.0, 0.0}; -} +template<> +QMC_ALIGNAS const double MultiBsplineData::d2A44[16] = + {0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 3.0, -2.0, 0.0, 0.0, -3.0, 1.0, 0.0, 0.0, 1.0, 0.0}; +} // namespace qmcplusplus diff --git a/src/Numerics/Spline2/MultiBsplineData.hpp b/src/Numerics/Spline2/MultiBsplineData.hpp index f56c45bfb..5ed249e79 100644 --- a/src/Numerics/Spline2/MultiBsplineData.hpp +++ b/src/Numerics/Spline2/MultiBsplineData.hpp @@ -29,9 +29,10 @@ namespace qmcplusplus { -template struct SplineBound +template +struct SplineBound { - static inline void get(T x, T &dx, int &ind, int ng) + static inline void get(T x, T& dx, int& ind, int ng) { T ipart; dx = std::modf(x, &ipart); @@ -39,7 +40,8 @@ template struct SplineBound } }; -template struct MultiBsplineData +template +struct MultiBsplineData { static const T A44[16]; static const T dA44[16]; @@ -71,6 +73,6 @@ template struct MultiBsplineData } }; -} /** qmcplusplus namespace */ +} // namespace qmcplusplus #endif diff --git a/src/Numerics/Spline2/MultiBsplineRef.hpp b/src/Numerics/Spline2/MultiBsplineRef.hpp index 70a464f58..cc1551125 100644 --- a/src/Numerics/Spline2/MultiBsplineRef.hpp +++ b/src/Numerics/Spline2/MultiBsplineRef.hpp @@ -27,17 +27,17 @@ namespace miniqmcreference { - using namespace qmcplusplus; -template struct MultiBsplineRef +template +struct MultiBsplineRef { /// define the einsplie object type using spliner_type = typename bspline_traits::SplineType; MultiBsplineRef() {} - MultiBsplineRef(const MultiBsplineRef &in) = delete; - MultiBsplineRef &operator=(const MultiBsplineRef &in) = delete; + MultiBsplineRef(const MultiBsplineRef& in) = delete; + MultiBsplineRef& operator=(const MultiBsplineRef& in) = delete; /** compute values vals[0,num_splines) * @@ -45,19 +45,38 @@ template struct MultiBsplineRef * evaluate_vgh(r,psi,grad,hess,ip). */ - void evaluate_v(const spliner_type *restrict spline_m, T x, T y, T z, T *restrict vals, + void evaluate_v(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, size_t num_splines) const; - void evaluate_vgl(const spliner_type *restrict spline_m, T x, T y, T z, T *restrict vals, T *restrict grads, - T *restrict lapl, size_t num_splines) const; - - void evaluate_vgh(const spliner_type *restrict spline_m, T x, T y, T z, T *restrict vals, T *restrict grads, - T *restrict hess, size_t num_splines) const; + void evaluate_vgl(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, + T* restrict grads, + T* restrict lapl, + size_t num_splines) const; + + void evaluate_vgh(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, + T* restrict grads, + T* restrict hess, + size_t num_splines) const; }; -template -inline void MultiBsplineRef::evaluate_v(const spliner_type *restrict spline_m, - T x, T y, T z, T *restrict vals, +template +inline void MultiBsplineRef::evaluate_v(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, size_t num_splines) const { x -= spline_m->x_grid.start; @@ -65,12 +84,9 @@ inline void MultiBsplineRef::evaluate_v(const spliner_type *restrict spline_m z -= spline_m->z_grid.start; T tx, ty, tz; int ix, iy, iz; - SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, - spline_m->x_grid.num - 1); - SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, - spline_m->y_grid.num - 1); - SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, - spline_m->z_grid.num - 1); + SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, spline_m->x_grid.num - 1); + SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, spline_m->y_grid.num - 1); + SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, spline_m->z_grid.num - 1); T a[4], b[4], c[4]; MultiBsplineData::compute_prefactors(a, tx); @@ -87,34 +103,33 @@ inline void MultiBsplineRef::evaluate_v(const spliner_type *restrict spline_m for (size_t i = 0; i < 4; i++) for (size_t j = 0; j < 4; j++) { - const T pre00 = a[i] * b[j]; - const T *restrict coefs = - spline_m->coefs + (ix + i) * xs + (iy + j) * ys + iz * zs; + const T pre00 = a[i] * b[j]; + const T* restrict coefs = spline_m->coefs + (ix + i) * xs + (iy + j) * ys + iz * zs; for (size_t n = 0; n < num_splines; n++) - vals[n] += - pre00 * (c[0] * coefs[n] + c[1] * coefs[n + zs] + - c[2] * coefs[n + 2 * zs] + c[3] * coefs[n + 3 * zs]); + vals[n] += pre00 * + (c[0] * coefs[n] + c[1] * coefs[n + zs] + c[2] * coefs[n + 2 * zs] + + c[3] * coefs[n + 3 * zs]); } } -template -inline void -MultiBsplineRef::evaluate_vgl(const spliner_type *restrict spline_m, - T x, T y, T z, T *restrict vals, - T *restrict grads, T *restrict lapl, - size_t num_splines) const +template +inline void MultiBsplineRef::evaluate_vgl(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, + T* restrict grads, + T* restrict lapl, + size_t num_splines) const { x -= spline_m->x_grid.start; y -= spline_m->y_grid.start; z -= spline_m->z_grid.start; T tx, ty, tz; int ix, iy, iz; - SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, - spline_m->x_grid.num - 1); - SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, - spline_m->y_grid.num - 1); - SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, - spline_m->z_grid.num - 1); + SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, spline_m->x_grid.num - 1); + SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, spline_m->y_grid.num - 1); + SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, spline_m->z_grid.num - 1); T a[4], b[4], c[4], da[4], db[4], dc[4], d2a[4], d2b[4], d2c[4]; @@ -128,12 +143,12 @@ MultiBsplineRef::evaluate_vgl(const spliner_type *restrict spline_m, const size_t out_offset = spline_m->num_splines; - T *restrict gx = grads; - T *restrict gy = grads + out_offset; - T *restrict gz = grads + 2 * out_offset; - T *restrict lx = lapl; - T *restrict ly = lapl + out_offset; - T *restrict lz = lapl + 2 * out_offset; + T* restrict gx = grads; + T* restrict gy = grads + out_offset; + T* restrict gz = grads + 2 * out_offset; + T* restrict lx = lapl; + T* restrict ly = lapl + out_offset; + T* restrict lz = lapl + 2 * out_offset; std::fill(vals, vals + num_splines, T()); std::fill(gx, gx + num_splines, T()); @@ -146,7 +161,6 @@ MultiBsplineRef::evaluate_vgl(const spliner_type *restrict spline_m, for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { - const T pre20 = d2a[i] * b[j]; const T pre10 = da[i] * b[j]; const T pre00 = a[i] * b[j]; @@ -154,11 +168,10 @@ MultiBsplineRef::evaluate_vgl(const spliner_type *restrict spline_m, const T pre01 = a[i] * db[j]; const T pre02 = a[i] * d2b[j]; - const T *restrict coefs = - spline_m->coefs + (ix + i) * xs + (iy + j) * ys + iz * zs; - const T *restrict coefszs = coefs + zs; - const T *restrict coefs2zs = coefs + 2 * zs; - const T *restrict coefs3zs = coefs + 3 * zs; + const T* restrict coefs = spline_m->coefs + (ix + i) * xs + (iy + j) * ys + iz * zs; + const T* restrict coefszs = coefs + zs; + const T* restrict coefs2zs = coefs + 2 * zs; + const T* restrict coefs3zs = coefs + 3 * zs; for (int n = 0; n < num_splines; n++) { @@ -167,12 +180,9 @@ MultiBsplineRef::evaluate_vgl(const spliner_type *restrict spline_m, const T coefsv2zs = coefs2zs[n]; const T coefsv3zs = coefs3zs[n]; - T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + - c[3] * coefsv3zs; - T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + - dc[3] * coefsv3zs; - T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + - d2c[3] * coefsv3zs; + T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + c[3] * coefsv3zs; + T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + dc[3] * coefsv3zs; + T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + d2c[3] * coefsv3zs; gx[n] += pre10 * sum0; gy[n] += pre01 * sum0; gz[n] += pre00 * sum1; @@ -200,14 +210,16 @@ MultiBsplineRef::evaluate_vgl(const spliner_type *restrict spline_m, } } -template -inline void -MultiBsplineRef::evaluate_vgh(const spliner_type *restrict spline_m, - T x, T y, T z, T *restrict vals, - T *restrict grads, T *restrict hess, - size_t num_splines) const +template +inline void MultiBsplineRef::evaluate_vgh(const spliner_type* restrict spline_m, + T x, + T y, + T z, + T* restrict vals, + T* restrict grads, + T* restrict hess, + size_t num_splines) const { - int ix, iy, iz; T tx, ty, tz; T a[4], b[4], c[4], da[4], db[4], dc[4], d2a[4], d2b[4], d2c[4]; @@ -215,12 +227,9 @@ MultiBsplineRef::evaluate_vgh(const spliner_type *restrict spline_m, x -= spline_m->x_grid.start; y -= spline_m->y_grid.start; z -= spline_m->z_grid.start; - SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, - spline_m->x_grid.num - 1); - SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, - spline_m->y_grid.num - 1); - SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, - spline_m->z_grid.num - 1); + SplineBound::get(x * spline_m->x_grid.delta_inv, tx, ix, spline_m->x_grid.num - 1); + SplineBound::get(y * spline_m->y_grid.delta_inv, ty, iy, spline_m->y_grid.num - 1); + SplineBound::get(z * spline_m->z_grid.delta_inv, tz, iz, spline_m->z_grid.num - 1); MultiBsplineData::compute_prefactors(a, da, d2a, tx); MultiBsplineData::compute_prefactors(b, db, d2b, ty); @@ -232,16 +241,16 @@ MultiBsplineRef::evaluate_vgh(const spliner_type *restrict spline_m, const size_t out_offset = spline_m->num_splines; - T *restrict gx = grads; - T *restrict gy = grads + out_offset; - T *restrict gz = grads + 2 * out_offset; + T* restrict gx = grads; + T* restrict gy = grads + out_offset; + T* restrict gz = grads + 2 * out_offset; - T *restrict hxx = hess; - T *restrict hxy = hess + out_offset; - T *restrict hxz = hess + 2 * out_offset; - T *restrict hyy = hess + 3 * out_offset; - T *restrict hyz = hess + 4 * out_offset; - T *restrict hzz = hess + 5 * out_offset; + T* restrict hxx = hess; + T* restrict hxy = hess + out_offset; + T* restrict hxz = hess + 2 * out_offset; + T* restrict hyy = hess + 3 * out_offset; + T* restrict hyz = hess + 4 * out_offset; + T* restrict hzz = hess + 5 * out_offset; std::fill(vals, vals + num_splines, T()); std::fill(gx, gx + num_splines, T()); @@ -257,11 +266,10 @@ MultiBsplineRef::evaluate_vgh(const spliner_type *restrict spline_m, for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { - const T *restrict coefs = - spline_m->coefs + (ix + i) * xs + (iy + j) * ys + iz * zs; - const T *restrict coefszs = coefs + zs; - const T *restrict coefs2zs = coefs + 2 * zs; - const T *restrict coefs3zs = coefs + 3 * zs; + const T* restrict coefs = spline_m->coefs + (ix + i) * xs + (iy + j) * ys + iz * zs; + const T* restrict coefszs = coefs + zs; + const T* restrict coefs2zs = coefs + 2 * zs; + const T* restrict coefs3zs = coefs + 3 * zs; const T pre20 = d2a[i] * b[j]; const T pre10 = da[i] * b[j]; @@ -273,18 +281,14 @@ MultiBsplineRef::evaluate_vgh(const spliner_type *restrict spline_m, const int iSplitPoint = num_splines; for (int n = 0; n < iSplitPoint; n++) { - T coefsv = coefs[n]; T coefsvzs = coefszs[n]; T coefsv2zs = coefs2zs[n]; T coefsv3zs = coefs3zs[n]; - T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + - c[3] * coefsv3zs; - T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + - dc[3] * coefsv3zs; - T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + - d2c[3] * coefsv3zs; + T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + c[3] * coefsv3zs; + T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + dc[3] * coefsv3zs; + T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + d2c[3] * coefsv3zs; hxx[n] += pre20 * sum0; hxy[n] += pre11 * sum0; @@ -311,9 +315,9 @@ MultiBsplineRef::evaluate_vgh(const spliner_type *restrict spline_m, for (int n = 0; n < num_splines; n++) { - gx[n] *= dxInv; - gy[n] *= dyInv; - gz[n] *= dzInv; + gx[n] *= dxInv; + gy[n] *= dyInv; + gz[n] *= dzInv; hxx[n] *= dxx; hyy[n] *= dyy; hzz[n] *= dzz; @@ -323,5 +327,5 @@ MultiBsplineRef::evaluate_vgh(const spliner_type *restrict spline_m, } } -} /** qmcplusplus namespace */ +} // namespace miniqmcreference #endif diff --git a/src/Numerics/Spline2/bspline_allocator.cpp b/src/Numerics/Spline2/bspline_allocator.cpp index f169b5958..91d41e032 100644 --- a/src/Numerics/Spline2/bspline_allocator.cpp +++ b/src/Numerics/Spline2/bspline_allocator.cpp @@ -19,68 +19,86 @@ #include "Numerics/Spline2/einspline_allocator.h" - - -multi_UBspline_3d_s * -einspline_create_multi_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, - BCtype_s xBC, BCtype_s yBC, BCtype_s zBC, - int num_splines); - -UBspline_3d_s *einspline_create_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_s xBC, - BCtype_s yBC, BCtype_s zBC); - -multi_UBspline_3d_d * -einspline_create_multi_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, - BCtype_d xBC, BCtype_d yBC, BCtype_d zBC, - int num_splines); - -UBspline_3d_d *einspline_create_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_d xBC, - BCtype_d yBC, BCtype_d zBC); +multi_UBspline_3d_s* einspline_create_multi_UBspline_3d_s(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_s xBC, + BCtype_s yBC, + BCtype_s zBC, + int num_splines); + +UBspline_3d_s* einspline_create_UBspline_3d_s(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_s xBC, + BCtype_s yBC, + BCtype_s zBC); + +multi_UBspline_3d_d* einspline_create_multi_UBspline_3d_d(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_d xBC, + BCtype_d yBC, + BCtype_d zBC, + int num_splines); + +UBspline_3d_d* einspline_create_UBspline_3d_d(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_d xBC, + BCtype_d yBC, + BCtype_d zBC); namespace qmcplusplus { namespace einspline { - Allocator::Allocator() : Policy(0) {} Allocator::~Allocator() {} -multi_UBspline_3d_s *Allocator::allocateMultiBspline(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_s xBC, - BCtype_s yBC, BCtype_s zBC, +multi_UBspline_3d_s* Allocator::allocateMultiBspline(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_s xBC, + BCtype_s yBC, + BCtype_s zBC, int num_splines) { - return einspline_create_multi_UBspline_3d_s(x_grid, y_grid, z_grid, xBC, yBC, - zBC, num_splines); + return einspline_create_multi_UBspline_3d_s(x_grid, y_grid, z_grid, xBC, yBC, zBC, num_splines); } -multi_UBspline_3d_d *Allocator::allocateMultiBspline(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_d xBC, - BCtype_d yBC, BCtype_d zBC, +multi_UBspline_3d_d* Allocator::allocateMultiBspline(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_d xBC, + BCtype_d yBC, + BCtype_d zBC, int num_splines) { - return einspline_create_multi_UBspline_3d_d(x_grid, y_grid, z_grid, xBC, yBC, - zBC, num_splines); + return einspline_create_multi_UBspline_3d_d(x_grid, y_grid, z_grid, xBC, yBC, zBC, num_splines); } -UBspline_3d_d *Allocator::allocateUBspline(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_d xBC, - BCtype_d yBC, BCtype_d zBC) +UBspline_3d_d* Allocator::allocateUBspline(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_d xBC, + BCtype_d yBC, + BCtype_d zBC) { return einspline_create_UBspline_3d_d(x_grid, y_grid, z_grid, xBC, yBC, zBC); } -UBspline_3d_s *Allocator::allocateUBspline(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_s xBC, - BCtype_s yBC, BCtype_s zBC) +UBspline_3d_s* Allocator::allocateUBspline(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_s xBC, + BCtype_s yBC, + BCtype_s zBC) { return einspline_create_UBspline_3d_s(x_grid, y_grid, z_grid, xBC, yBC, zBC); } - -} -} +} // namespace einspline +} // namespace qmcplusplus diff --git a/src/Numerics/Spline2/bspline_allocator.hpp b/src/Numerics/Spline2/bspline_allocator.hpp index 702ef467c..37c3b72d2 100644 --- a/src/Numerics/Spline2/bspline_allocator.hpp +++ b/src/Numerics/Spline2/bspline_allocator.hpp @@ -24,7 +24,6 @@ namespace qmcplusplus { namespace einspline { - class Allocator { /// Setting the allocation policy: default is using aligned allocator @@ -35,57 +34,63 @@ class Allocator Allocator(); #if (__cplusplus >= 201103L) /// disable copy constructor - Allocator(const Allocator &) = delete; + Allocator(const Allocator&) = delete; /// disable assignement - Allocator &operator=(const Allocator &) = delete; + Allocator& operator=(const Allocator&) = delete; #endif /// destructor ~Allocator(); - template void destroy(SplineType *spline) + template + void destroy(SplineType* spline) { einspline_free(spline->coefs); free(spline); } /// allocate a single multi-bspline - multi_UBspline_3d_s *allocateMultiBspline(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_s xBC, - BCtype_s yBC, BCtype_s zBC, + multi_UBspline_3d_s* allocateMultiBspline(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_s xBC, + BCtype_s yBC, + BCtype_s zBC, int num_splines); /// allocate a double multi-bspline - multi_UBspline_3d_d *allocateMultiBspline(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_d xBC, - BCtype_d yBC, BCtype_d zBC, + multi_UBspline_3d_d* allocateMultiBspline(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_d xBC, + BCtype_d yBC, + BCtype_d zBC, int num_splines); /// allocate a single bspline - UBspline_3d_s *allocateUBspline(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, - BCtype_s xBC, BCtype_s yBC, BCtype_s zBC); + UBspline_3d_s* + allocateUBspline(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_s xBC, BCtype_s yBC, BCtype_s zBC); /// allocate a UBspline_3d_d - UBspline_3d_d *allocateUBspline(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, - BCtype_d xBC, BCtype_d yBC, BCtype_d zBC); + UBspline_3d_d* + allocateUBspline(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_d xBC, BCtype_d yBC, BCtype_d zBC); /** allocate a multi_UBspline_3d_(s,d) * @tparam T datatype * @tparam ValT 3D container for start and end * @tparam IntT 3D container for ng */ - template - typename bspline_traits::SplineType * - createMultiBspline(T dummy, ValT &start, ValT &end, IntT &ng, bc_code bc, - int num_splines); + template + typename bspline_traits::SplineType* + createMultiBspline(T dummy, ValT& start, ValT& end, IntT& ng, bc_code bc, int num_splines); /** allocate a UBspline_3d_(s,d) * @tparam T datatype * @tparam ValT 3D container for start and end * @tparam IntT 3D container for ng */ - template - typename bspline_traits::SingleSplineType * - createUBspline(ValT &start, ValT &end, IntT &ng, bc_code bc); + template + typename bspline_traits::SingleSplineType* + createUBspline(ValT& start, ValT& end, IntT& ng, bc_code bc); /** Set coefficients for a single orbital (band) * @param i index of the orbital @@ -93,7 +98,9 @@ class Allocator * @param spline target MultibsplineType */ template - void setCoefficientsForOneOrbital(int i, Array &coeff, typename bspline_traits::SplineType *spline); + void setCoefficientsForOneOrbital(int i, + Array& coeff, + typename bspline_traits::SplineType* spline); /** copy a UBSpline_3d_X to multi_UBspline_3d_X at i-th band * @param single UBspline_3d_X @@ -102,31 +109,34 @@ class Allocator * @param offset starting offset for AoSoA * @param N shape of AoSoA */ - template - void copy(UBT *single, MBT *multi, int i, const int *offset, const int *N); - + template + void copy(UBT* single, MBT* multi, int i, const int* offset, const int* N); }; template -void Allocator::setCoefficientsForOneOrbital(int i, Array &coeff, typename bspline_traits::SplineType *spline) +void Allocator::setCoefficientsForOneOrbital(int i, + Array& coeff, + typename bspline_traits::SplineType* spline) { - #pragma omp parallel for collapse(3) - for (int ix = 0; ix < spline->x_grid.num + 3; ix++) { - for (int iy = 0; iy < spline->y_grid.num + 3; iy++) { - for (int iz = 0; iz < spline->z_grid.num + 3; iz++) { - intptr_t xs = spline->x_stride; - intptr_t ys = spline->y_stride; - intptr_t zs = spline->z_stride; - spline->coefs[ix*xs + iy*ys + iz*zs + i] = coeff(ix,iy,iz); +#pragma omp parallel for collapse(3) + for (int ix = 0; ix < spline->x_grid.num + 3; ix++) + { + for (int iy = 0; iy < spline->y_grid.num + 3; iy++) + { + for (int iz = 0; iz < spline->z_grid.num + 3; iz++) + { + intptr_t xs = spline->x_stride; + intptr_t ys = spline->y_stride; + intptr_t zs = spline->z_stride; + spline->coefs[ix * xs + iy * ys + iz * zs + i] = coeff(ix, iy, iz); } } } } -template -typename bspline_traits::SplineType * -Allocator::createMultiBspline(T dummy, ValT &start, ValT &end, IntT &ng, - bc_code bc, int num_splines) +template +typename bspline_traits::SplineType* + Allocator::createMultiBspline(T dummy, ValT& start, ValT& end, IntT& ng, bc_code bc, int num_splines) { Ugrid x_grid, y_grid, z_grid; typename bspline_traits::BCType xBC, yBC, zBC; @@ -142,13 +152,12 @@ Allocator::createMultiBspline(T dummy, ValT &start, ValT &end, IntT &ng, xBC.lCode = xBC.rCode = bc; yBC.lCode = yBC.rCode = bc; zBC.lCode = zBC.rCode = bc; - return allocateMultiBspline(x_grid, y_grid, z_grid, xBC, yBC, zBC, - num_splines); + return allocateMultiBspline(x_grid, y_grid, z_grid, xBC, yBC, zBC, num_splines); } -template -typename bspline_traits::SingleSplineType * -Allocator::createUBspline(ValT &start, ValT &end, IntT &ng, bc_code bc) +template +typename bspline_traits::SingleSplineType* + Allocator::createUBspline(ValT& start, ValT& end, IntT& ng, bc_code bc) { Ugrid x_grid, y_grid, z_grid; typename bspline_traits::BCType xBC, yBC, zBC; @@ -167,9 +176,8 @@ Allocator::createUBspline(ValT &start, ValT &end, IntT &ng, bc_code bc) return allocateUBspline(x_grid, y_grid, z_grid, xBC, yBC, zBC); } -template -void Allocator::copy(UBT *single, MBT *multi, int i, const int *offset, - const int *N) +template +void Allocator::copy(UBT* single, MBT* multi, int i, const int* offset, const int* N) { typedef typename bspline_type::value_type out_type; typedef typename bspline_type::value_type in_type; @@ -186,17 +194,15 @@ void Allocator::copy(UBT *single, MBT *multi, int i, const int *offset, for (intptr_t ix = 0; ix < n0; ++ix) for (intptr_t iy = 0; iy < n1; ++iy) { - out_type *restrict out = - multi->coefs + ix * x_stride_out + iy * y_stride_out + istart; - const in_type *restrict in = single->coefs + - (ix + offset0) * x_stride_in + - (iy + offset1) * y_stride_in + offset2; + out_type* restrict out = multi->coefs + ix * x_stride_out + iy * y_stride_out + istart; + const in_type* restrict in = + single->coefs + (ix + offset0) * x_stride_in + (iy + offset1) * y_stride_in + offset2; for (intptr_t iz = 0; iz < n2; ++iz) { out[iz * z_stride_out] = static_cast(in[iz]); } } } -} -} +} // namespace einspline +} // namespace qmcplusplus #endif diff --git a/src/Numerics/Spline2/bspline_traits.hpp b/src/Numerics/Spline2/bspline_traits.hpp index 94e816b85..739789fae 100644 --- a/src/Numerics/Spline2/bspline_traits.hpp +++ b/src/Numerics/Spline2/bspline_traits.hpp @@ -22,11 +22,12 @@ namespace qmcplusplus { /** trait class to map (datatype,D) to Einspline engine type */ -template struct bspline_traits -{ -}; +template +struct bspline_traits +{}; -template <> struct bspline_traits +template<> +struct bspline_traits { typedef multi_UBspline_3d_s SplineType; typedef UBspline_3d_s SingleSplineType; @@ -35,7 +36,8 @@ template <> struct bspline_traits typedef float value_type; }; -template <> struct bspline_traits +template<> +struct bspline_traits { typedef multi_UBspline_3d_d SplineType; typedef UBspline_3d_d SingleSplineType; @@ -46,28 +48,32 @@ template <> struct bspline_traits /** helper class to determine the value_type of einspline objects */ -template struct bspline_type -{ -}; +template +struct bspline_type +{}; -template <> struct bspline_type +template<> +struct bspline_type { typedef float value_type; }; -template <> struct bspline_type +template<> +struct bspline_type { typedef double value_type; }; -template <> struct bspline_type +template<> +struct bspline_type { typedef float value_type; }; -template <> struct bspline_type +template<> +struct bspline_type { typedef double value_type; }; -} +} // namespace qmcplusplus #endif diff --git a/src/Numerics/Spline2/einspline_allocator.cpp b/src/Numerics/Spline2/einspline_allocator.cpp index dffa347a2..8a2d81891 100644 --- a/src/Numerics/Spline2/einspline_allocator.cpp +++ b/src/Numerics/Spline2/einspline_allocator.cpp @@ -31,54 +31,55 @@ #if defined(HAVE_POSIX_MEMALIGN) -int posix_memalign(void **memptr, size_t alignment, size_t size); +int posix_memalign(void** memptr, size_t alignment, size_t size); -void *einspline_alloc(size_t size, size_t alignment) +void* einspline_alloc(size_t size, size_t alignment) { - void *ptr; + void* ptr; int ret = posix_memalign(&ptr, alignment, size); return ptr; } -void einspline_free(void *ptr) { free(ptr); } +void einspline_free(void* ptr) { free(ptr); } #else -void *einspline_alloc(size_t size, size_t alignment) +void* einspline_alloc(size_t size, size_t alignment) { - size += (alignment - 1) + sizeof(void *); - void *ptr = malloc(size); + size += (alignment - 1) + sizeof(void*); + void* ptr = malloc(size); if (ptr == NULL) return NULL; else { - void *shifted = - (char *)ptr + sizeof(void *); // make room to save original pointer - size_t offset = alignment - (size_t)shifted % (size_t)alignment; - void *aligned = (char *)shifted + offset; - *((void **)aligned - 1) = ptr; + void* shifted = (char*)ptr + sizeof(void*); // make room to save original pointer + size_t offset = alignment - (size_t)shifted % (size_t)alignment; + void* aligned = (char*)shifted + offset; + *((void**)aligned - 1) = ptr; return aligned; } } -void einspline_free(void *aligned) +void einspline_free(void* aligned) { - void *ptr = *((void **)aligned - 1); + void* ptr = *((void**)aligned - 1); free(ptr); } #endif -multi_UBspline_3d_s * -einspline_create_multi_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, - BCtype_s xBC, BCtype_s yBC, BCtype_s zBC, - int num_splines) +multi_UBspline_3d_s* einspline_create_multi_UBspline_3d_s(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_s xBC, + BCtype_s yBC, + BCtype_s zBC, + int num_splines) { // Create new spline - multi_UBspline_3d_s *restrict spline = (multi_UBspline_3d_s *)malloc(sizeof(multi_UBspline_3d_s)); + multi_UBspline_3d_s* restrict spline = (multi_UBspline_3d_s*)malloc(sizeof(multi_UBspline_3d_s)); if (!spline) { - fprintf(stderr, - "Out of memory allocating spline in create_multi_UBspline_3d_s.\n"); + fprintf(stderr, "Out of memory allocating spline in create_multi_UBspline_3d_s.\n"); abort(); } spline->spcode = MULTI_U3D; @@ -96,7 +97,7 @@ einspline_create_multi_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx + 3; else - Nx = Mx + 2; + Nx = Mx + 2; x_grid.delta = (x_grid.end - x_grid.start) / (double)(Nx - 3); x_grid.delta_inv = 1.0 / x_grid.delta; spline->x_grid = x_grid; @@ -104,7 +105,7 @@ einspline_create_multi_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My + 3; else - Ny = My + 2; + Ny = My + 2; y_grid.delta = (y_grid.end - y_grid.start) / (double)(Ny - 3); y_grid.delta_inv = 1.0 / y_grid.delta; spline->y_grid = y_grid; @@ -112,7 +113,7 @@ einspline_create_multi_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz + 3; else - Nz = Mz + 2; + Nz = Mz + 2; z_grid.delta = (z_grid.end - z_grid.start) / (double)(Nz - 3); z_grid.delta_inv = 1.0 / z_grid.delta; spline->z_grid = z_grid; @@ -125,15 +126,15 @@ einspline_create_multi_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, spline->z_stride = N; spline->coefs_size = (size_t)Nx * spline->x_stride; - spline->coefs = - (float *)einspline_alloc(sizeof(float) * spline->coefs_size, QMC_CLINE); + spline->coefs = (float*)einspline_alloc(sizeof(float) * spline->coefs_size, QMC_CLINE); // printf("Einepline allocator %d %d %d %zd (%d) %zu // %d\n",Nx,Ny,Nz,N,num_splines,spline->coefs_size,QMC_CLINE); if (!spline->coefs) { - fprintf(stderr, "Out of memory allocating spline coefficients in " - "create_multi_UBspline_3d_s.\n"); + fprintf(stderr, + "Out of memory allocating spline coefficients in " + "create_multi_UBspline_3d_s.\n"); abort(); } @@ -158,18 +159,20 @@ einspline_create_multi_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, return spline; } -multi_UBspline_3d_d * -einspline_create_multi_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, - BCtype_d xBC, BCtype_d yBC, BCtype_d zBC, - int num_splines) +multi_UBspline_3d_d* einspline_create_multi_UBspline_3d_d(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_d xBC, + BCtype_d yBC, + BCtype_d zBC, + int num_splines) { // Create new spline - multi_UBspline_3d_d *restrict spline = (multi_UBspline_3d_d *)malloc(sizeof(multi_UBspline_3d_d)); + multi_UBspline_3d_d* restrict spline = (multi_UBspline_3d_d*)malloc(sizeof(multi_UBspline_3d_d)); if (!spline) { - fprintf(stderr, - "Out of memory allocating spline in create_multi_UBspline_3d_d.\n"); + fprintf(stderr, "Out of memory allocating spline in create_multi_UBspline_3d_d.\n"); abort(); } spline->spcode = MULTI_U3D; @@ -188,7 +191,7 @@ einspline_create_multi_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx + 3; else - Nx = Mx + 2; + Nx = Mx + 2; x_grid.delta = (x_grid.end - x_grid.start) / (double)(Nx - 3); x_grid.delta_inv = 1.0 / x_grid.delta; spline->x_grid = x_grid; @@ -196,7 +199,7 @@ einspline_create_multi_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My + 3; else - Ny = My + 2; + Ny = My + 2; y_grid.delta = (y_grid.end - y_grid.start) / (double)(Ny - 3); y_grid.delta_inv = 1.0 / y_grid.delta; spline->y_grid = y_grid; @@ -204,39 +207,41 @@ einspline_create_multi_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz + 3; else - Nz = Mz + 2; + Nz = Mz + 2; z_grid.delta = (z_grid.end - z_grid.start) / (double)(Nz - 3); z_grid.delta_inv = 1.0 / z_grid.delta; spline->z_grid = z_grid; const int ND = QMC_CLINE / sizeof(double); - int N = - (num_splines % ND) ? (num_splines + ND - num_splines % ND) : num_splines; + int N = (num_splines % ND) ? (num_splines + ND - num_splines % ND) : num_splines; spline->x_stride = (size_t)Ny * (size_t)Nz * (size_t)N; spline->y_stride = Nz * N; spline->z_stride = N; spline->coefs_size = (size_t)Nx * spline->x_stride; - spline->coefs = - (double *)einspline_alloc(sizeof(double) * spline->coefs_size, QMC_CLINE); + spline->coefs = (double*)einspline_alloc(sizeof(double) * spline->coefs_size, QMC_CLINE); if (!spline->coefs) { - fprintf(stderr, "Out of memory allocating spline coefficients in " - "create_multi_UBspline_3d_d.\n"); + fprintf(stderr, + "Out of memory allocating spline coefficients in " + "create_multi_UBspline_3d_d.\n"); abort(); } return spline; } -UBspline_3d_d *einspline_create_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_d xBC, - BCtype_d yBC, BCtype_d zBC) +UBspline_3d_d* einspline_create_UBspline_3d_d(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_d xBC, + BCtype_d yBC, + BCtype_d zBC) { // Create new spline - UBspline_3d_d *restrict spline = (UBspline_3d_d *)malloc(sizeof(UBspline_3d_d)); + UBspline_3d_d* restrict spline = (UBspline_3d_d*)malloc(sizeof(UBspline_3d_d)); spline->spcode = U3D; spline->tcode = DOUBLE_REAL; spline->xBC = xBC; @@ -252,7 +257,7 @@ UBspline_3d_d *einspline_create_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx + 3; else - Nx = Mx + 2; + Nx = Mx + 2; x_grid.delta = (x_grid.end - x_grid.start) / (double)(Nx - 3); x_grid.delta_inv = 1.0 / x_grid.delta; spline->x_grid = x_grid; @@ -260,7 +265,7 @@ UBspline_3d_d *einspline_create_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My + 3; else - Ny = My + 2; + Ny = My + 2; y_grid.delta = (y_grid.end - y_grid.start) / (double)(Ny - 3); y_grid.delta_inv = 1.0 / y_grid.delta; spline->y_grid = y_grid; @@ -268,7 +273,7 @@ UBspline_3d_d *einspline_create_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz + 3; else - Nz = Mz + 2; + Nz = Mz + 2; z_grid.delta = (z_grid.end - z_grid.start) / (double)(Nz - 3); z_grid.delta_inv = 1.0 / z_grid.delta; spline->z_grid = z_grid; @@ -278,18 +283,20 @@ UBspline_3d_d *einspline_create_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, spline->coefs_size = (size_t)Nx * (size_t)Ny * (size_t)Nz; - spline->coefs = - (double *)einspline_alloc(sizeof(double) * spline->coefs_size, QMC_CLINE); + spline->coefs = (double*)einspline_alloc(sizeof(double) * spline->coefs_size, QMC_CLINE); return spline; } -UBspline_3d_s *einspline_create_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, - Ugrid z_grid, BCtype_s xBC, - BCtype_s yBC, BCtype_s zBC) +UBspline_3d_s* einspline_create_UBspline_3d_s(Ugrid x_grid, + Ugrid y_grid, + Ugrid z_grid, + BCtype_s xBC, + BCtype_s yBC, + BCtype_s zBC) { // Create new spline - UBspline_3d_s *spline = (UBspline_3d_s *)malloc(sizeof(UBspline_3d_s)); + UBspline_3d_s* spline = (UBspline_3d_s*)malloc(sizeof(UBspline_3d_s)); spline->spcode = U3D; spline->tcode = SINGLE_REAL; spline->xBC = xBC; @@ -304,7 +311,7 @@ UBspline_3d_s *einspline_create_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, if (xBC.lCode == PERIODIC || xBC.lCode == ANTIPERIODIC) Nx = Mx + 3; else - Nx = Mx + 2; + Nx = Mx + 2; x_grid.delta = (x_grid.end - x_grid.start) / (double)(Nx - 3); x_grid.delta_inv = 1.0 / x_grid.delta; spline->x_grid = x_grid; @@ -312,7 +319,7 @@ UBspline_3d_s *einspline_create_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, if (yBC.lCode == PERIODIC || yBC.lCode == ANTIPERIODIC) Ny = My + 3; else - Ny = My + 2; + Ny = My + 2; y_grid.delta = (y_grid.end - y_grid.start) / (double)(Ny - 3); y_grid.delta_inv = 1.0 / y_grid.delta; spline->y_grid = y_grid; @@ -320,7 +327,7 @@ UBspline_3d_s *einspline_create_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, if (zBC.lCode == PERIODIC || zBC.lCode == ANTIPERIODIC) Nz = Mz + 3; else - Nz = Mz + 2; + Nz = Mz + 2; z_grid.delta = (z_grid.end - z_grid.start) / (double)(Nz - 3); z_grid.delta_inv = 1.0 / z_grid.delta; spline->z_grid = z_grid; @@ -329,8 +336,7 @@ UBspline_3d_s *einspline_create_UBspline_3d_s(Ugrid x_grid, Ugrid y_grid, spline->y_stride = Nz; spline->coefs_size = (size_t)Nx * (size_t)Ny * (size_t)Nz; - spline->coefs = - (float *)einspline_alloc(sizeof(float) * spline->coefs_size, QMC_CLINE); + spline->coefs = (float*)einspline_alloc(sizeof(float) * spline->coefs_size, QMC_CLINE); return spline; } diff --git a/src/Numerics/Spline2/einspline_allocator.h b/src/Numerics/Spline2/einspline_allocator.h index 484a8d6a4..45c0922fa 100644 --- a/src/Numerics/Spline2/einspline_allocator.h +++ b/src/Numerics/Spline2/einspline_allocator.h @@ -27,9 +27,9 @@ #define EINSPLINE_ALIGNED_ALLOC_H -void *einspline_alloc(size_t size, size_t alignment); +void* einspline_alloc(size_t size, size_t alignment); -void einspline_free(void *ptr); +void einspline_free(void* ptr); #endif diff --git a/src/Particle/DistanceTable.h b/src/Particle/DistanceTable.h index 93f8055d7..1d77de0dd 100644 --- a/src/Particle/DistanceTable.h +++ b/src/Particle/DistanceTable.h @@ -23,7 +23,6 @@ namespace qmcplusplus { - /** Class to manage multiple DistanceTableData objects. * * \date 2008-09-19 @@ -41,10 +40,9 @@ namespace qmcplusplus */ /// free function to create a distable table of s-s -DistanceTableData *createDistanceTable(ParticleSet &s, int dt_type); +DistanceTableData* createDistanceTable(ParticleSet& s, int dt_type); /// free function create a distable table of s-t -DistanceTableData *createDistanceTable(const ParticleSet &s, ParticleSet &t, - int dt_type); -} +DistanceTableData* createDistanceTable(const ParticleSet& s, ParticleSet& t, int dt_type); +} // namespace qmcplusplus #endif diff --git a/src/Particle/DistanceTableAA.cpp b/src/Particle/DistanceTableAA.cpp index 11e04d858..85dfe768e 100644 --- a/src/Particle/DistanceTableAA.cpp +++ b/src/Particle/DistanceTableAA.cpp @@ -28,12 +28,11 @@ namespace qmcplusplus { - /** Adding SymmetricDTD to the list, e.g., el-el distance table *\param s source/target particle set *\return index of the distance table with the name */ -DistanceTableData *createDistanceTable(ParticleSet &s, int dt_type) +DistanceTableData* createDistanceTable(ParticleSet& s, int dt_type) { typedef OHMMS_PRECISION RealType; enum @@ -41,15 +40,13 @@ DistanceTableData *createDistanceTable(ParticleSet &s, int dt_type) DIM = OHMMS_DIM }; int sc = s.Lattice.SuperCellEnum; - DistanceTableData *dt = 0; + DistanceTableData* dt = 0; std::ostringstream o; bool useSoA = (dt_type == DT_SOA || dt_type == DT_SOA_PREFERRED); - o << " Distance table for AA: source/target = " << s.getName() - << " useSoA =" << useSoA << "\n"; + o << " Distance table for AA: source/target = " << s.getName() << " useSoA =" << useSoA << "\n"; if (sc == SUPERCELL_BULK) { - o << " Using SoaDistanceTableAA of SoA layout " << PPPG - << std::endl; + o << " Using SoaDistanceTableAA of SoA layout " << PPPG << std::endl; dt = new DistanceTableAA(s); o << "\n Setting Rmax = " << s.Lattice.SimulationCellRadius; } diff --git a/src/Particle/DistanceTableAA.h b/src/Particle/DistanceTableAA.h index 1d60bbfa1..77e1f837a 100644 --- a/src/Particle/DistanceTableAA.h +++ b/src/Particle/DistanceTableAA.h @@ -21,26 +21,24 @@ namespace qmcplusplus { - /**@ingroup nnlist * @brief A derived classe from DistacneTableData, specialized for dense case */ -template +template struct DistanceTableAA : public DTD_BConds, public DistanceTableData { - int Ntargets; int Ntargets_padded; int BlockSize; - DistanceTableAA(ParticleSet &target) + DistanceTableAA(ParticleSet& target) : DTD_BConds(target.Lattice), DistanceTableData(target, target) { resize(target.getTotalNum()); } - DistanceTableAA() = delete; - DistanceTableAA(const DistanceTableAA &) = delete; + DistanceTableAA() = delete; + DistanceTableAA(const DistanceTableAA&) = delete; ~DistanceTableAA() {} size_t compute_size(int N) @@ -61,41 +59,48 @@ struct DistanceTableAA : public DTD_BConds, public DistanceTableData memoryPool.resize(total_size * D); Displacements.resize(Ntargets); for (int i = 0; i < Ntargets; ++i) - Displacements[i].attachReference(i, total_size, - memoryPool.data() + compute_size(i)); + Displacements[i].attachReference(i, total_size, memoryPool.data() + compute_size(i)); Temp_r.resize(Ntargets); Temp_dr.resize(Ntargets); } - inline void evaluate(ParticleSet &P) + inline void evaluate(ParticleSet& P) { constexpr T BigR = std::numeric_limits::max(); // P.RSoA.copyIn(P.R); for (int iat = 0; iat < Ntargets; ++iat) { - DTD_BConds::computeDistances(P.R[iat], P.RSoA, Distances[iat], - Displacements[iat], 0, Ntargets, + DTD_BConds::computeDistances(P.R[iat], + P.RSoA, + Distances[iat], + Displacements[iat], + 0, + Ntargets, iat); Distances[iat][iat] = BigR; // assign big distance } } - inline void evaluate(ParticleSet &P, IndexType jat) + inline void evaluate(ParticleSet& P, IndexType jat) { - DTD_BConds::computeDistances( - P.R[jat], P.RSoA, Distances[jat], Displacements[jat], 0, Ntargets, jat); + DTD_BConds::computeDistances(P.R[jat], + P.RSoA, + Distances[jat], + Displacements[jat], + 0, + Ntargets, + jat); Distances[jat][jat] = std::numeric_limits::max(); // assign a big number } - inline void moveOnSphere(const ParticleSet &P, const PosType &rnew) + inline void moveOnSphere(const ParticleSet& P, const PosType& rnew) { - DTD_BConds::computeDistances(rnew, P.RSoA, Temp_r.data(), Temp_dr, - 0, Ntargets, P.activePtcl); + DTD_BConds::computeDistances(rnew, P.RSoA, Temp_r.data(), Temp_dr, 0, Ntargets, P.activePtcl); } /// evaluate the temporary pair relations - inline void move(const ParticleSet &P, const PosType &rnew) + inline void move(const ParticleSet& P, const PosType& rnew) { //#pragma omp master moveOnSphere(P, rnew); @@ -104,7 +109,8 @@ struct DistanceTableAA : public DTD_BConds, public DistanceTableData /// update the iat-th row for iat=[0,iat-1) inline void update(IndexType iat) { - if (iat == 0) return; + if (iat == 0) + return; // update by a cache line const int nupdate = getAlignedSize(iat); simd::copy_n(Temp_r.data(), nupdate, Distances[iat]); diff --git a/src/Particle/DistanceTableAB.cpp b/src/Particle/DistanceTableAB.cpp index e41b6e71e..87538390c 100644 --- a/src/Particle/DistanceTableAB.cpp +++ b/src/Particle/DistanceTableAB.cpp @@ -29,28 +29,24 @@ namespace qmcplusplus { - /** Adding AsymmetricDTD to the list, e.g., el-el distance table *\param s source/target particle set *\return index of the distance table with the name */ -DistanceTableData *createDistanceTable(const ParticleSet &s, ParticleSet &t, - int dt_type) +DistanceTableData* createDistanceTable(const ParticleSet& s, ParticleSet& t, int dt_type) { typedef OHMMS_PRECISION RealType; enum { DIM = OHMMS_DIM }; - DistanceTableData *dt = 0; - int sc = t.Lattice.SuperCellEnum; + DistanceTableData* dt = 0; + int sc = t.Lattice.SuperCellEnum; std::ostringstream o; - o << " Distance table for AB: source = " << s.getName() - << " target = " << t.getName() << "\n"; + o << " Distance table for AB: source = " << s.getName() << " target = " << t.getName() << "\n"; if (sc == SUPERCELL_BULK) { - o << " Using SoaDistanceTableBA of SoA layout " << PPPG - << std::endl; + o << " Using SoaDistanceTableBA of SoA layout " << PPPG << std::endl; dt = new DistanceTableBA(s, t); o << " Setting Rmax = " << s.Lattice.SimulationCellRadius; } diff --git a/src/Particle/DistanceTableBA.h b/src/Particle/DistanceTableBA.h index 574e60cc7..9e60fbde2 100644 --- a/src/Particle/DistanceTableBA.h +++ b/src/Particle/DistanceTableBA.h @@ -24,14 +24,14 @@ namespace qmcplusplus * @brief A derived classe from DistacneTableData, specialized for AB using a * transposed form */ -template +template struct DistanceTableBA : public DTD_BConds, public DistanceTableData { int Nsources; int Ntargets; int BlockSize; - DistanceTableBA(const ParticleSet &source, ParticleSet &target) + DistanceTableBA(const ParticleSet& source, ParticleSet& target) : DTD_BConds(source.Lattice), DistanceTableData(source, target) { resize(source.getTotalNum(), target.getTotalNum()); @@ -41,7 +41,8 @@ struct DistanceTableBA : public DTD_BConds, public DistanceTableData { N[SourceIndex] = Nsources = ns; N[VisitorIndex] = Ntargets = nt; - if (Nsources * Ntargets == 0) return; + if (Nsources * Ntargets == 0) + return; int Ntargets_padded = getAlignedSize(Ntargets); int Nsources_padded = getAlignedSize(Nsources); @@ -52,49 +53,52 @@ struct DistanceTableBA : public DTD_BConds, public DistanceTableData memoryPool.resize(Ntargets * BlockSize); Displacements.resize(Ntargets); for (int i = 0; i < Ntargets; ++i) - Displacements[i].attachReference(Nsources, Nsources_padded, - memoryPool.data() + i * BlockSize); + Displacements[i].attachReference(Nsources, Nsources_padded, memoryPool.data() + i * BlockSize); Temp_r.resize(Nsources); Temp_dr.resize(Nsources); } - DistanceTableBA() = delete; - DistanceTableBA(const DistanceTableBA &) = delete; + DistanceTableBA() = delete; + DistanceTableBA(const DistanceTableBA&) = delete; ~DistanceTableBA() {} /** evaluate the full table */ - inline void evaluate(ParticleSet &P) + inline void evaluate(ParticleSet& P) { // be aware of the sign of Displacement for (int iat = 0; iat < Ntargets; ++iat) - DTD_BConds::computeDistances(P.R[iat], Origin->RSoA, - Distances[iat], Displacements[iat], - 0, Nsources); + DTD_BConds::computeDistances(P.R[iat], + Origin->RSoA, + Distances[iat], + Displacements[iat], + 0, + Nsources); } /** evaluate the iat-row with the current position * * Fill Temp_r and Temp_dr and copy them Distances & Displacements */ - inline void evaluate(ParticleSet &P, IndexType iat) + inline void evaluate(ParticleSet& P, IndexType iat) { - DTD_BConds::computeDistances(P.R[iat], Origin->RSoA, - Distances[iat], Displacements[iat], - 0, Nsources); + DTD_BConds::computeDistances(P.R[iat], + Origin->RSoA, + Distances[iat], + Displacements[iat], + 0, + Nsources); } - inline void moveOnSphere(const ParticleSet &P, const PosType &rnew) + inline void moveOnSphere(const ParticleSet& P, const PosType& rnew) { - DTD_BConds::computeDistances(rnew, Origin->RSoA, Temp_r.data(), - Temp_dr, 0, Nsources); + DTD_BConds::computeDistances(rnew, Origin->RSoA, Temp_r.data(), Temp_dr, 0, Nsources); } /// evaluate the temporary pair relations - inline void move(const ParticleSet &P, const PosType &rnew) + inline void move(const ParticleSet& P, const PosType& rnew) { - DTD_BConds::computeDistances(rnew, Origin->RSoA, Temp_r.data(), - Temp_dr, 0, Nsources); + DTD_BConds::computeDistances(rnew, Origin->RSoA, Temp_r.data(), Temp_dr, 0, Nsources); } /// update the stripe for jat-th particle @@ -104,7 +108,6 @@ struct DistanceTableBA : public DTD_BConds, public DistanceTableData for (int idim = 0; idim < D; ++idim) simd::copy_n(Temp_dr.data(idim), Nsources, Displacements[iat].data(idim)); } - }; } // namespace qmcplusplus #endif diff --git a/src/Particle/DistanceTableData.h b/src/Particle/DistanceTableData.h index 539dfebc3..55e1e8649 100644 --- a/src/Particle/DistanceTableData.h +++ b/src/Particle/DistanceTableData.h @@ -33,7 +33,6 @@ namespace qmcplusplus { - /** enumerator for DistanceTableData::DTType * * - DT_AOS Use original AoS type @@ -121,7 +120,7 @@ struct DistanceTableData /// name of the table std::string Name; /// constructor using source and target ParticleSet - DistanceTableData(const ParticleSet &source, const ParticleSet &target) + DistanceTableData(const ParticleSet& source, const ParticleSet& target) : Origin(&source), N(0), Need_full_table_loadWalker(false) {} @@ -131,11 +130,11 @@ struct DistanceTableData /// return the name of table inline std::string getName() const { return Name; } /// set the name of table - inline void setName(const std::string &tname) { Name = tname; } + inline void setName(const std::string& tname) { Name = tname; } /// returns the reference the origin particleset - const ParticleSet &origin() const { return *Origin; } - inline void reset(const ParticleSet *newcenter) { Origin = newcenter; } + const ParticleSet& origin() const { return *Origin; } + inline void reset(const ParticleSet* newcenter) { Origin = newcenter; } inline bool is_same_type(int dt_type) const { return DTType == dt_type; } @@ -149,22 +148,21 @@ struct DistanceTableData inline IndexType size(int i) const { return N[i]; } /// evaluate the Distance Table using only with position array - virtual void evaluate(ParticleSet &P) = 0; + virtual void evaluate(ParticleSet& P) = 0; /// evaluate the Distance Table - virtual void evaluate(ParticleSet &P, int jat) = 0; + virtual void evaluate(ParticleSet& P, int jat) = 0; /// evaluate the temporary pair relations - virtual void move(const ParticleSet &P, const PosType &rnew) = 0; + virtual void move(const ParticleSet& P, const PosType& rnew) = 0; /// evaluate the distance tables with a sphere move - virtual void moveOnSphere(const ParticleSet &P, const PosType &rnew) = 0; + virtual void moveOnSphere(const ParticleSet& P, const PosType& rnew) = 0; /// update the distance table by the pair relations virtual void update(IndexType jat) = 0; - const ParticleSet *Origin; - + const ParticleSet* Origin; }; } // namespace qmcplusplus #endif diff --git a/src/Particle/FastParticleOperators.h b/src/Particle/FastParticleOperators.h index 300c18cef..f08970fd8 100644 --- a/src/Particle/FastParticleOperators.h +++ b/src/Particle/FastParticleOperators.h @@ -32,22 +32,21 @@ namespace qmcplusplus * - T2 the transformation matrix * - ORTHO true, if only Diagonal Elements are used */ -template struct ConvertPosUnit -{ -}; +template +struct ConvertPosUnit +{}; -template +template struct ConvertPosUnit>, Tensor, 3, false> { - typedef ParticleAttrib> Array_t; typedef Tensor Transformer_t; - inline static void apply(const Array_t &pin, const Transformer_t &X, - Array_t &pout, int first, int last) + inline static void + apply(const Array_t& pin, const Transformer_t& X, Array_t& pout, int first, int last) { - T x00 = X[0], x01 = X[1], x02 = X[2], x10 = X[3], x11 = X[4], - x12 = X[5], x20 = X[6], x21 = X[7], x22 = X[8]; + T x00 = X[0], x01 = X[1], x02 = X[2], x10 = X[3], x11 = X[4], x12 = X[5], x20 = X[6], + x21 = X[7], x22 = X[8]; #pragma ivdep for (int i = first; i < last; i++) { @@ -57,11 +56,11 @@ struct ConvertPosUnit>, Tensor, 3, false> } } - inline static void apply(const Transformer_t &X, const Array_t &pin, - Array_t &pout, int first, int last) + inline static void + apply(const Transformer_t& X, const Array_t& pin, Array_t& pout, int first, int last) { - T x00 = X[0], x01 = X[1], x02 = X[2], x10 = X[3], x11 = X[4], - x12 = X[5], x20 = X[6], x21 = X[7], x22 = X[8]; + T x00 = X[0], x01 = X[1], x02 = X[2], x10 = X[3], x11 = X[4], x12 = X[5], x20 = X[6], + x21 = X[7], x22 = X[8]; #pragma ivdep for (int i = first; i < last; i++) { @@ -71,11 +70,10 @@ struct ConvertPosUnit>, Tensor, 3, false> } } - inline static void apply(Array_t &pinout, const Transformer_t &X, int first, - int last) + inline static void apply(Array_t& pinout, const Transformer_t& X, int first, int last) { - T x00 = X[0], x01 = X[1], x02 = X[2], x10 = X[3], x11 = X[4], - x12 = X[5], x20 = X[6], x21 = X[7], x22 = X[8]; + T x00 = X[0], x01 = X[1], x02 = X[2], x10 = X[3], x11 = X[4], x12 = X[5], x20 = X[6], + x21 = X[7], x22 = X[8]; #pragma ivdep for (int i = first; i < last; i++) { @@ -86,11 +84,10 @@ struct ConvertPosUnit>, Tensor, 3, false> } } - inline static void apply(const Transformer_t &X, Array_t &pinout, int first, - int last) + inline static void apply(const Transformer_t& X, Array_t& pinout, int first, int last) { - T x00 = X[0], x01 = X[1], x02 = X[2], x10 = X[3], x11 = X[4], - x12 = X[5], x20 = X[6], x21 = X[7], x22 = X[8]; + T x00 = X[0], x01 = X[1], x02 = X[2], x10 = X[3], x11 = X[4], x12 = X[5], x20 = X[6], + x21 = X[7], x22 = X[8]; #pragma ivdep for (int i = first; i < last; i++) { @@ -101,5 +98,5 @@ struct ConvertPosUnit>, Tensor, 3, false> } } }; -} +} // namespace qmcplusplus #endif diff --git a/src/Particle/Lattice/CrystalLattice.cpp b/src/Particle/Lattice/CrystalLattice.cpp index 1af525e34..1a74a3559 100644 --- a/src/Particle/Lattice/CrystalLattice.cpp +++ b/src/Particle/Lattice/CrystalLattice.cpp @@ -34,7 +34,7 @@ namespace qmcplusplus /*! \fn CrystalLattice::CrystalLattice() * Default constructor. Initialized to a \p 1x1x1 cubic supercell. */ -template +template CrystalLattice::CrystalLattice() { BoxBConds = 0; @@ -45,16 +45,16 @@ CrystalLattice::CrystalLattice() reset(); } -template -template -void CrystalLattice::set(const Tensor &lat) +template +template +void CrystalLattice::set(const Tensor& lat) { R = lat; reset(); } -template -void CrystalLattice::set(T sc, T *lat) +template +void CrystalLattice::set(T sc, T* lat) { if (lat) { @@ -71,9 +71,8 @@ void CrystalLattice::set(T sc, T *lat) reset(); } -template -void CrystalLattice::set(const CrystalLattice &oldlat, - int *uc) +template +void CrystalLattice::set(const CrystalLattice& oldlat, int* uc) { BoxBConds = oldlat.BoxBConds; R = oldlat.R; @@ -86,7 +85,7 @@ void CrystalLattice::set(const CrystalLattice &oldlat, reset(); } -template +template void CrystalLattice::reset() { G = inverse(R); // G = transpose(Inverse(R)); @@ -124,23 +123,23 @@ void CrystalLattice::reset() WignerSeitzRadius - SimulationCellRadius <= WignerSeitzRadius * std::numeric_limits::epsilon() * 2) WignerSeitzRadius = SimulationCellRadius; - CellRadiusSq = SimulationCellRadius * SimulationCellRadius; + CellRadiusSq = SimulationCellRadius * SimulationCellRadius; } /*! \fn CrystalLattice::operator*=(T sc) * \param sc A scaling factor. * \brief Rescale this supercell by a scalar. */ -template -CrystalLattice &CrystalLattice::operator*=(T sc) +template +CrystalLattice& CrystalLattice::operator*=(T sc) { R *= sc; reset(); return *this; } -template -void CrystalLattice::print(std::ostream &os, int level) const +template +void CrystalLattice::print(std::ostream& os, int level) const { /*\note level == 0: print only the lattice vectors * level == 1: lattice vectors, boundary conditions, grid @@ -193,9 +192,8 @@ void CrystalLattice::print(std::ostream &os, int level) const os << "" << std::endl; } -template -inline bool operator==(const CrystalLattice &lhs, - const CrystalLattice &rhs) +template +inline bool operator==(const CrystalLattice& lhs, const CrystalLattice& rhs) { for (int i = 0; i < D * D; ++i) if (std::abs(lhs.R[i] - rhs.R[i]) > std::numeric_limits::epsilon()) @@ -203,17 +201,16 @@ inline bool operator==(const CrystalLattice &lhs, return true; } -template -inline bool operator!=(const CrystalLattice &lhs, - const CrystalLattice &rhs) +template +inline bool operator!=(const CrystalLattice& lhs, const CrystalLattice& rhs) { return !(lhs == rhs); } // free function to check if a CrystalLattice is orthorhombic -template -inline bool orthorombic(const CrystalLattice &a) +template +inline bool orthorombic(const CrystalLattice& a) { return ORTHO; } -} +} // namespace qmcplusplus diff --git a/src/Particle/Lattice/CrystalLattice.h b/src/Particle/Lattice/CrystalLattice.h index 79c7a2952..f21fc7f37 100644 --- a/src/Particle/Lattice/CrystalLattice.h +++ b/src/Particle/Lattice/CrystalLattice.h @@ -47,7 +47,6 @@ namespace qmcplusplus { - /** enumeration to classify a CrystalLattice * * Use std::bitset<3> for all the dimension @@ -86,9 +85,9 @@ struct PosUnit *expression template operations with variable-cell algorithms. * */ -template struct CrystalLattice +template +struct CrystalLattice { - enum { IsOrthogonal = OHMMS_ORTHO @@ -183,14 +182,14 @@ template struct CrystalLattice /** Convert a cartesian vector to a unit vector. * Boundary conditions are not applied. */ - template - inline SingleParticlePos_t toUnit(const TinyVector &r) const + template + inline SingleParticlePos_t toUnit(const TinyVector& r) const { return dot(r, G); } - template - inline SingleParticlePos_t toUnit_floor(const TinyVector &r) const + template + inline SingleParticlePos_t toUnit_floor(const TinyVector& r) const { SingleParticlePos_t val_dot; val_dot = toUnit(r); @@ -205,13 +204,13 @@ template struct CrystalLattice /** Convert a unit vector to a cartesian vector. * Boundary conditions are not applied. */ - template - inline SingleParticlePos_t toCart(const TinyVector &c) const + template + inline SingleParticlePos_t toCart(const TinyVector& c) const { return dot(c, R); } - inline bool isValid(const TinyVector &u) const + inline bool isValid(const TinyVector& u) const { #if defined(USE_BOXBCONDS) return CheckBoxConds::inside(u, BoxBConds); @@ -223,10 +222,11 @@ template struct CrystalLattice #endif } - inline bool outOfBound(const TinyVector &u) const + inline bool outOfBound(const TinyVector& u) const { for (int i = 0; i < D; ++i) - if (std::abs(u[i]) > 0.5) return true; + if (std::abs(u[i]) > 0.5) + return true; return false; } @@ -238,8 +238,7 @@ template struct CrystalLattice @note The distance between two cartesian vectors are handled *by dot function defined in OhmmsPETE/TinyVector.h */ - inline T Dot(const SingleParticlePos_t &ra, - const SingleParticlePos_t &rb) const + inline T Dot(const SingleParticlePos_t& ra, const SingleParticlePos_t& rb) const { return dot(ra, dot(M, rb)); } @@ -248,7 +247,7 @@ template struct CrystalLattice *@param kin an input reciprocal vector in the Reciprocal-vector unit *@return k(reciprocal vector) in cartesian unit */ - inline SingleParticlePos_t k_cart(const SingleParticlePos_t &kin) const + inline SingleParticlePos_t k_cart(const SingleParticlePos_t& kin) const { return TWOPI * dot(G, kin); } @@ -257,7 +256,7 @@ template struct CrystalLattice *@param kin an input reciprocal vector in cartesian form *@return k(reciprocal vector) as unit vector */ - inline SingleParticlePos_t k_unit(const SingleParticlePos_t &kin) const + inline SingleParticlePos_t k_unit(const SingleParticlePos_t& kin) const { return dot(R, kin) / TWOPI; } @@ -267,15 +266,11 @@ template struct CrystalLattice *@param kin an input reciprocal vector in reciprocal-vector unit *@return \f$k_{in}^2\f$ */ - inline T ksq(const SingleParticlePos_t &kin) const - { - return dot(kin, dot(Mg, kin)); - } + inline T ksq(const SingleParticlePos_t& kin) const { return dot(kin, dot(Mg, kin)); } /// assignment operator - template - CrystalLattice & - operator=(const CrystalLattice &rhs) + template + CrystalLattice& operator=(const CrystalLattice& rhs) { BoxBConds = rhs.BoxBConds; R = rhs.R; @@ -286,8 +281,8 @@ template struct CrystalLattice /** assignment operator *@param rhs a tensor representing a unit cell */ - template - CrystalLattice &operator=(const Tensor &rhs) + template + CrystalLattice& operator=(const Tensor& rhs) { R = rhs; reset(); @@ -298,33 +293,34 @@ template struct CrystalLattice *@param sc the scaling value *@return a new CrystalLattice */ - CrystalLattice &operator*=(T sc); + CrystalLattice& operator*=(T sc); /** set the lattice vector by an array containing DxD T *@param sc a scalar to scale the input lattice parameters *@param lat the starting address of DxD T-elements representing a supercell */ - void set(T sc, T *lat = 0); + void set(T sc, T* lat = 0); /** set the lattice vector by a CrystalLattice and expand it by integers *@param oldlat An input supercell to be copied. *@param uc An array to expand a supercell. */ - void set(const CrystalLattice &oldlat, int *uc = 0); + void set(const CrystalLattice& oldlat, int* uc = 0); /** set the lattice vector from the command-line options *@param lat a tensor representing a supercell */ - template void set(const Tensor &lat); + template + void set(const Tensor& lat); /** Evaluate the reciprocal vectors, volume and metric tensor */ void reset(); //! Print out CrystalLattice Data - void print(std::ostream &, int level = 2) const; + void print(std::ostream&, int level = 2) const; }; -} +} // namespace qmcplusplus // including the definitions of the member functions #include "Particle/Lattice/CrystalLattice.cpp" diff --git a/src/Particle/Lattice/LatticeAnalyzer.h b/src/Particle/Lattice/LatticeAnalyzer.h index 11b25fb74..6910b763e 100644 --- a/src/Particle/Lattice/LatticeAnalyzer.h +++ b/src/Particle/Lattice/LatticeAnalyzer.h @@ -24,7 +24,6 @@ #include "Numerics/OhmmsPETE/TinyVector.h" namespace qmcplusplus { - /** enumeration for DTD_BConds specialization * * G = general cell with image-cell checks @@ -46,51 +45,48 @@ enum }; /// generic class to analyze a Lattice -template struct LatticeAnalyzer -{ -}; +template +struct LatticeAnalyzer +{}; /** specialization for 3D lattice */ -template struct LatticeAnalyzer +template +struct LatticeAnalyzer { - typedef TinyVector SingleParticlePos_t; typedef Tensor Tensor_t; /// SuperCell type int mySC; - inline int operator()(const TinyVector &box) + inline int operator()(const TinyVector& box) { return mySC = box[0] + 2 * (box[1] + box[2] * 2); } - inline bool isDiagonalOnly(const Tensor_t &R) const + inline bool isDiagonalOnly(const Tensor_t& R) const { - T offdiag = std::abs(R(0, 1)) + std::abs(R(0, 2)) + std::abs(R(1, 0)) + - std::abs(R(1, 2)) + std::abs(R(2, 0)) + std::abs(R(2, 1)); + T offdiag = std::abs(R(0, 1)) + std::abs(R(0, 2)) + std::abs(R(1, 0)) + std::abs(R(1, 2)) + + std::abs(R(2, 0)) + std::abs(R(2, 1)); return (offdiag < std::numeric_limits::epsilon()); } - inline SingleParticlePos_t - calcSolidAngles(const TinyVector &Rv, - const SingleParticlePos_t &OneOverLength) + inline SingleParticlePos_t calcSolidAngles(const TinyVector& Rv, + const SingleParticlePos_t& OneOverLength) { const T rad_to_deg = 180.0 / M_PI; - return SingleParticlePos_t( - rad_to_deg * - std::acos(dot(Rv[0], Rv[1]) * OneOverLength[0] * OneOverLength[1]), - rad_to_deg * - std::acos(dot(Rv[1], Rv[2]) * OneOverLength[1] * OneOverLength[2]), - rad_to_deg * - std::acos(dot(Rv[2], Rv[0]) * OneOverLength[2] * OneOverLength[0])); + return SingleParticlePos_t(rad_to_deg * + std::acos(dot(Rv[0], Rv[1]) * OneOverLength[0] * OneOverLength[1]), + rad_to_deg * + std::acos(dot(Rv[1], Rv[2]) * OneOverLength[1] * OneOverLength[2]), + rad_to_deg * + std::acos(dot(Rv[2], Rv[0]) * OneOverLength[2] * OneOverLength[0])); } - inline T calcWignerSeitzRadius(TinyVector &a) + inline T calcWignerSeitzRadius(TinyVector& a) { T rMin = 0.5 * std::numeric_limits::max(); - if (mySC == SUPERCELL_BULK || - mySC == SUPERCELL_BULK + SOA_OFFSET) // bulk type + if (mySC == SUPERCELL_BULK || mySC == SUPERCELL_BULK + SOA_OFFSET) // bulk type { for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) @@ -98,32 +94,28 @@ template struct LatticeAnalyzer if (i || j || k) { SingleParticlePos_t L = - (static_cast(i) * a[0] + static_cast(j) * a[1] + - static_cast(k) * a[2]); + (static_cast(i) * a[0] + static_cast(j) * a[1] + static_cast(k) * a[2]); rMin = std::min(rMin, dot(L, L)); } } - else if (mySC == SUPERCELL_SLAB || - mySC == SUPERCELL_SLAB + SOA_OFFSET) // slab type + else if (mySC == SUPERCELL_SLAB || mySC == SUPERCELL_SLAB + SOA_OFFSET) // slab type { for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (i || j) { - SingleParticlePos_t L = - (static_cast(i) * a[0] + static_cast(j) * a[1]); - rMin = std::min(rMin, dot(L, L)); + SingleParticlePos_t L = (static_cast(i) * a[0] + static_cast(j) * a[1]); + rMin = std::min(rMin, dot(L, L)); } } - else if (mySC == SUPERCELL_WIRE || - mySC == SUPERCELL_WIRE + SOA_OFFSET) // wire + else if (mySC == SUPERCELL_WIRE || mySC == SUPERCELL_WIRE + SOA_OFFSET) // wire { rMin = dot(a[0], a[0]); } return 0.5 * std::sqrt(rMin); } - inline T calcSimulationCellRadius(TinyVector &a) + inline T calcSimulationCellRadius(TinyVector& a) { T scr = 0.5 * std::numeric_limits::max(); for (int i = 0; i < 3; ++i) @@ -132,15 +124,15 @@ template struct LatticeAnalyzer SingleParticlePos_t B = a((i + 1) % 3); SingleParticlePos_t C = a((i + 2) % 3); SingleParticlePos_t BxC = cross(B, C); - T dist = 0.5 * std::abs(dot(A, BxC)) / std::sqrt(dot(BxC, BxC)); - scr = std::min(scr, dist); + T dist = 0.5 * std::abs(dot(A, BxC)) / std::sqrt(dot(BxC, BxC)); + scr = std::min(scr, dist); } return scr; } }; -template -inline bool found_shorter_base(TinyVector, 3> &rb) +template +inline bool found_shorter_base(TinyVector, 3>& rb) { const T eps = 10.0 * std::numeric_limits::epsilon(); int imax = 0; @@ -170,8 +162,8 @@ inline bool found_shorter_base(TinyVector, 3> &rb) } return false; } -template -inline void find_reduced_basis(TinyVector, 3> &rb) +template +inline void find_reduced_basis(TinyVector, 3>& rb) { do { @@ -182,10 +174,12 @@ inline void find_reduced_basis(TinyVector, 3> &rb) rb[i] = 0.0; changed = found_shorter_base(rb); rb[i] = saved[i]; - if (changed) break; + if (changed) + break; } - if (!changed && !found_shorter_base(rb)) return; + if (!changed && !found_shorter_base(rb)) + return; } while (1); } -} +} // namespace qmcplusplus #endif diff --git a/src/Particle/Lattice/LatticeOperations.h b/src/Particle/Lattice/LatticeOperations.h index 82d3498a8..af35d8ee3 100644 --- a/src/Particle/Lattice/LatticeOperations.h +++ b/src/Particle/Lattice/LatticeOperations.h @@ -21,10 +21,10 @@ namespace qmcplusplus { - -template struct CheckBoxConds +template +struct CheckBoxConds { - inline static bool inside(const TinyVector &u) + inline static bool inside(const TinyVector& u) { bool yes = (u[0] > 0.0 && u[0] < 1.0); for (int i = 1; i < D; ++i) @@ -32,31 +32,29 @@ template struct CheckBoxConds return yes; } - inline static bool inside(const TinyVector &u, TinyVector &ubox) + inline static bool inside(const TinyVector& u, TinyVector& ubox) { for (int i = 0; i < D; ++i) - ubox[i] = u[i] - std::floor(u[i]); + ubox[i] = u[i] - std::floor(u[i]); return true; } }; -template struct CheckBoxConds +template +struct CheckBoxConds { - inline static bool inside(const TinyVector &u) + inline static bool inside(const TinyVector& u) { - return (u[0] > 0.0 && u[0] < 1.0) && (u[1] > 0.0 && u[1] < 1.0) && - (u[2] > 0.0 && u[2] < 1.0); + return (u[0] > 0.0 && u[0] < 1.0) && (u[1] > 0.0 && u[1] < 1.0) && (u[2] > 0.0 && u[2] < 1.0); } - inline static bool inside(const TinyVector &u, - const TinyVector &bc) + inline static bool inside(const TinyVector& u, const TinyVector& bc) { - return (bc[0] || (u[0] > 0.0 && u[0] < 1.0)) && - (bc[1] || (u[1] > 0.0 && u[1] < 1.0)) && - (bc[2] || (u[2] > 0.0 && u[2] < 1.0)); + return (bc[0] || (u[0] > 0.0 && u[0] < 1.0)) && (bc[1] || (u[1] > 0.0 && u[1] < 1.0)) && + (bc[2] || (u[2] > 0.0 && u[2] < 1.0)); } - inline static bool inside(const TinyVector &u, TinyVector &ubox) + inline static bool inside(const TinyVector& u, TinyVector& ubox) { ubox[0] = u[0] - std::floor(u[0]); ubox[1] = u[1] - std::floor(u[1]); @@ -64,6 +62,6 @@ template struct CheckBoxConds return true; } }; -} +} // namespace qmcplusplus #endif diff --git a/src/Particle/Lattice/ParticleBConds.h b/src/Particle/Lattice/ParticleBConds.h index b554ba617..228faa503 100644 --- a/src/Particle/Lattice/ParticleBConds.h +++ b/src/Particle/Lattice/ParticleBConds.h @@ -27,7 +27,6 @@ namespace qmcplusplus { - // clang-format off /** generic Boundary condition handler * @@ -55,11 +54,11 @@ namespace qmcplusplus */ // clang-format on -template struct DTD_BConds +template +struct DTD_BConds { - /** constructor: doing nothing */ - inline DTD_BConds(const CrystalLattice &lat) + inline DTD_BConds(const CrystalLattice& lat) { APP_ABORT("qmcplusplus::DTD_BConds default DTD_BConds is not allowed in " "miniQMC!\n"); @@ -69,7 +68,7 @@ template struct DTD_BConds * @param displ a displacement vector in the Cartesian coordinate * @return \f$|displ|^2\f$ */ - inline T apply_bc(TinyVector &displ) const { return dot(displ, displ); } + inline T apply_bc(TinyVector& displ) const { return dot(displ, displ); } /** apply BC on dr and evaluate r and rinv * @param dr vector of displacements, in and out @@ -79,8 +78,7 @@ template struct DTD_BConds * The input displacement vectors are not modified with the open boundary * conditions. */ - inline void apply_bc(std::vector> &dr, std::vector &r, - std::vector &rinv) const + inline void apply_bc(std::vector>& dr, std::vector& r, std::vector& rinv) const { const int n = dr.size(); const T cone(1); @@ -93,19 +91,19 @@ template struct DTD_BConds }; - /** specialization for a periodic 3D general cell * * Wigner-Seitz cell radius > simulation cell radius * Need to check image cells */ -template struct DTD_BConds +template +struct DTD_BConds { T g00, g10, g20, g01, g11, g21, g02, g12, g22; T r00, r10, r20, r01, r11, r21, r02, r12, r22; VectorSoAContainer corners; - DTD_BConds(const CrystalLattice &lat) + DTD_BConds(const CrystalLattice& lat) { TinyVector, 3> rb; rb[0] = lat.a(0); @@ -126,17 +124,17 @@ template struct DTD_BConds Tensor rbt; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) - rbt(i, j) = rb[i][j]; + rbt(i, j) = rb[i][j]; Tensor g = inverse(rbt); - g00 = g(0); - g10 = g(3); - g20 = g(6); - g01 = g(1); - g11 = g(4); - g21 = g(7); - g02 = g(2); - g12 = g(5); - g22 = g(8); + g00 = g(0); + g10 = g(3); + g20 = g(6); + g01 = g(1); + g11 = g(4); + g21 = g(7); + g02 = g(2); + g12 = g(5); + g22 = g(8); constexpr T minusone(-1); constexpr T zero(0); @@ -152,27 +150,32 @@ template struct DTD_BConds corners(7) = minusone * (rb[0] + rb[1] + rb[2]); } - template - void computeDistances(const PT &pos, const RSoA &R0, T *restrict temp_r, - RSoA &temp_dr, int first, int last, int flip_ind = 0) + template + void computeDistances(const PT& pos, + const RSoA& R0, + T* restrict temp_r, + RSoA& temp_dr, + int first, + int last, + int flip_ind = 0) { const T x0 = pos[0]; const T y0 = pos[1]; const T z0 = pos[2]; - const T *restrict px = R0.data(0); - const T *restrict py = R0.data(1); - const T *restrict pz = R0.data(2); + const T* restrict px = R0.data(0); + const T* restrict py = R0.data(1); + const T* restrict pz = R0.data(2); - T *restrict dx = temp_dr.data(0); - T *restrict dy = temp_dr.data(1); - T *restrict dz = temp_dr.data(2); + T* restrict dx = temp_dr.data(0); + T* restrict dy = temp_dr.data(1); + T* restrict dz = temp_dr.data(2); - const T *restrict cellx = corners.data(0); + const T* restrict cellx = corners.data(0); ASSUME_ALIGNED(cellx); - const T *restrict celly = corners.data(1); + const T* restrict celly = corners.data(1); ASSUME_ALIGNED(celly); - const T *restrict cellz = corners.data(2); + const T* restrict cellz = corners.data(2); ASSUME_ALIGNED(cellz); constexpr T minusone(-1); @@ -214,6 +217,6 @@ template struct DTD_BConds } }; -} +} // namespace qmcplusplus #endif // OHMMS_PARTICLE_BCONDS_H diff --git a/src/Particle/ParticleAttrib.h b/src/Particle/ParticleAttrib.h index 42148cae9..8cb3b57af 100644 --- a/src/Particle/ParticleAttrib.h +++ b/src/Particle/ParticleAttrib.h @@ -21,7 +21,7 @@ namespace qmcplusplus { -template > +template> class ParticleAttrib : public Vector { typedef Vector __my_base; @@ -34,16 +34,14 @@ class ParticleAttrib : public Vector explicit inline ParticleAttrib(size_t n = 0) : __my_base(n), InUnit(0) {} /** constructor with an initialized ref */ - explicit inline ParticleAttrib(T *ref, size_t n) - : __my_base(ref, n), InUnit(0) - { - } + explicit inline ParticleAttrib(T* ref, size_t n) : __my_base(ref, n), InUnit(0) {} - ParticleAttrib(const ParticleAttrib &rhs) = default; - inline ParticleAttrib &operator=(const ParticleAttrib &rhs) = default; + ParticleAttrib(const ParticleAttrib& rhs) = default; + inline ParticleAttrib& operator=(const ParticleAttrib& rhs) = default; /** assignment operator to enable PETE */ - template inline ParticleAttrib &operator=(const RHS &rhs) + template + inline ParticleAttrib& operator=(const RHS& rhs) { assign(*this, rhs); return *this; @@ -54,6 +52,6 @@ class ParticleAttrib : public Vector inline int getUnit() const { return InUnit; } //@} }; -} +} // namespace qmcplusplus #endif // OHMMS_PARTICLEATTRIB_PEPE_H diff --git a/src/Particle/ParticleIOUtility.h b/src/Particle/ParticleIOUtility.h index 4c4532ac7..f553d437f 100644 --- a/src/Particle/ParticleIOUtility.h +++ b/src/Particle/ParticleIOUtility.h @@ -22,12 +22,12 @@ namespace qmcplusplus { - /** expand the particle set to the supercell size * @param ref_ initial particle set in primitive cell * @param tmat tiling matrix */ -template void expandSuperCell(PS &ref_, const Tensor &tmat) +template +void expandSuperCell(PS& ref_, const Tensor& tmat) { typedef typename PS::SingleParticlePos_t SingleParticlePos_t; @@ -39,14 +39,24 @@ template void expandSuperCell(PS &ref_, const Tensor &tmat identity = (I[ij] == tmat[ij]); ++ij; } - if (identity) return; - app_log() << " TileMatrix != Identity. Expanding a simulation cell for " - << ref_.getName() << std::endl; + if (identity) + return; + app_log() << " TileMatrix != Identity. Expanding a simulation cell for " << ref_.getName() + << std::endl; { char buff[500]; - snprintf(buff, 500, " tilematrix= %4d %4d %4d %4d %4d %4d %4d %4d %4d\n", - tmat[0], tmat[1], tmat[2], tmat[3], tmat[4], tmat[5], tmat[6], - tmat[7], tmat[8]); + snprintf(buff, + 500, + " tilematrix= %4d %4d %4d %4d %4d %4d %4d %4d %4d\n", + tmat[0], + tmat[1], + tmat[2], + tmat[3], + tmat[4], + tmat[5], + tmat[6], + tmat[7], + tmat[8]); app_log() << buff << std::endl; } // convert2unit @@ -70,22 +80,28 @@ template void expandSuperCell(PS &ref_, const Tensor &tmat for (int i2 = -maxCopies; i2 <= maxCopies; i2++) for (int iat = 0; iat < primPos.size(); iat++) { - if (primTypes[iat] != ns) continue; + if (primTypes[iat] != ns) + continue; SingleParticlePos_t uPrim = primPos[iat]; for (int i = 0; i < 3; i++) uPrim[i] -= std::floor(uPrim[i]); - SingleParticlePos_t r = - PrimCell.toCart(uPrim) + (double)i0 * PrimCell.a(0) + + SingleParticlePos_t r = PrimCell.toCart(uPrim) + (double)i0 * PrimCell.a(0) + (double)i1 * PrimCell.a(1) + (double)i2 * PrimCell.a(2); SingleParticlePos_t uSuper = ref_.Lattice.toUnit(r); - if ((uSuper[0] >= -1.0e-6) && (uSuper[0] < 0.9999) && - (uSuper[1] >= -1.0e-6) && (uSuper[1] < 0.9999) && - (uSuper[2] >= -1.0e-6) && (uSuper[2] < 0.9999)) + if ((uSuper[0] >= -1.0e-6) && (uSuper[0] < 0.9999) && (uSuper[1] >= -1.0e-6) && + (uSuper[1] < 0.9999) && (uSuper[2] >= -1.0e-6) && (uSuper[2] < 0.9999)) { char buff[500]; - snprintf(buff, 500, + snprintf(buff, + 500, " %10.4f %10.4f %10.4f %12.6f %12.6f %12.6f %d\n", - uSuper[0], uSuper[1], uSuper[2], r[0], r[1], r[2], ns); + uSuper[0], + uSuper[1], + uSuper[2], + r[0], + r[1], + r[2], + ns); app_log() << buff; ref_.R[index] = r; ref_.GroupID[index] = ns; // primTypes[iat]; @@ -99,5 +115,5 @@ template void expandSuperCell(PS &ref_, const Tensor &tmat ref_.Lattice.print(app_log()); app_log() << std::endl; } -} +} // namespace qmcplusplus #endif diff --git a/src/Particle/ParticleSet.BC.cpp b/src/Particle/ParticleSet.BC.cpp index 9fbcb9ba4..dbd9999ef 100644 --- a/src/Particle/ParticleSet.BC.cpp +++ b/src/Particle/ParticleSet.BC.cpp @@ -25,28 +25,31 @@ namespace qmcplusplus { - -void ParticleSet::convert2Unit(ParticlePos_t &pinout) +void ParticleSet::convert2Unit(ParticlePos_t& pinout) { if (pinout.getUnit() == PosUnit::LatticeUnit) return; else { pinout.setUnit(PosUnit::LatticeUnit); - ConvertPosUnit::apply( - pinout, Lattice.G, 0, pinout.size()); + ConvertPosUnit::apply(pinout, + Lattice.G, + 0, + pinout.size()); } } -void ParticleSet::convert2Cart(ParticlePos_t &pinout) +void ParticleSet::convert2Cart(ParticlePos_t& pinout) { if (pinout.getUnit() == PosUnit::CartesianUnit) return; else { pinout.setUnit(PosUnit::CartesianUnit); - ConvertPosUnit::apply( - pinout, Lattice.R, 0, pinout.size()); + ConvertPosUnit::apply(pinout, + Lattice.R, + 0, + pinout.size()); } } -} +} // namespace qmcplusplus diff --git a/src/Particle/ParticleSet.cpp b/src/Particle/ParticleSet.cpp index 36475dfcd..a4dc65754 100644 --- a/src/Particle/ParticleSet.cpp +++ b/src/Particle/ParticleSet.cpp @@ -42,7 +42,6 @@ namespace qmcplusplus { - enum DistanceTimers { Timer_makeMove, @@ -50,23 +49,25 @@ enum DistanceTimers Timer_acceptMove }; -TimerNameList_t DistanceTimerNames -{ - {Timer_makeMove, "Make move"}, - {Timer_setActive, "Set active"}, - {Timer_acceptMove, "Accept move"}, +TimerNameList_t DistanceTimerNames{ + {Timer_makeMove, "Make move"}, + {Timer_setActive, "Set active"}, + {Timer_acceptMove, "Accept move"}, }; ParticleSet::ParticleSet() - : UseBoundBox(true), IsGrouped(true), myName("none"), SameMass(true), - myTwist(0.0), activePtcl(-1) + : UseBoundBox(true), IsGrouped(true), myName("none"), SameMass(true), myTwist(0.0), activePtcl(-1) { setup_timers(timers, DistanceTimerNames, timer_level_coarse); } -ParticleSet::ParticleSet(const ParticleSet &p) - : UseBoundBox(p.UseBoundBox), IsGrouped(p.IsGrouped), - mySpecies(p.getSpeciesSet()), SameMass(true), myTwist(0.0), activePtcl(-1) +ParticleSet::ParticleSet(const ParticleSet& p) + : UseBoundBox(p.UseBoundBox), + IsGrouped(p.IsGrouped), + mySpecies(p.getSpeciesSet()), + SameMass(true), + myTwist(0.0), + activePtcl(-1) { //distance_timer = TimerManager.createTimer("Distance Tables", timer_level_coarse); setup_timers(timers, DistanceTimerNames, timer_level_coarse); @@ -77,13 +78,12 @@ ParticleSet::ParticleSet(const ParticleSet &p) Mass = p.Mass; Z = p.Z; this->setName(p.getName()); - app_log() << " Copying a particle set " << p.getName() << " to " - << this->getName() << " groups=" << groups() << std::endl; + app_log() << " Copying a particle set " << p.getName() << " to " << this->getName() + << " groups=" << groups() << std::endl; // construct the distance tables with the same order if (p.DistTables.size()) { - app_log() << " Cloning distance tables. It has " << p.DistTables.size() - << std::endl; + app_log() << " Cloning distance tables. It has " << p.DistTables.size() << std::endl; addTable(*this, p.DistTables[0]->DTType); // first is always for this-this pair for (int i = 1; i < p.DistTables.size(); ++i) @@ -92,8 +92,7 @@ ParticleSet::ParticleSet(const ParticleSet &p) for (int i = 0; i < p.DistTables.size(); ++i) { - DistTables[i]->Need_full_table_loadWalker = - p.DistTables[i]->Need_full_table_loadWalker; + DistTables[i]->Need_full_table_loadWalker = p.DistTables[i]->Need_full_table_loadWalker; } myTwist = p.myTwist; @@ -109,7 +108,7 @@ void ParticleSet::create(int numPtcl) R = RealType(0); } -void ParticleSet::create(const std::vector &agroup) +void ParticleSet::create(const std::vector& agroup) { SubPtcl.resize(agroup.size() + 1); SubPtcl[0] = 0; @@ -137,8 +136,8 @@ void ParticleSet::resetGroups() int qind = mySpecies.addAttribute("charge"); if (natt == qind) { - app_log() << " Missing charge attribute of the SpeciesSet " << myName - << " particleset" << std::endl; + app_log() << " Missing charge attribute of the SpeciesSet " << myName << " particleset" + << std::endl; app_log() << " Assume neutral particles Z=0.0 " << std::endl; for (int ig = 0; ig < nspecies; ig++) mySpecies(qind, ig) = 0.0; @@ -182,7 +181,8 @@ void ParticleSet::resetGroups() int new_id = 0; for (int i = 0; i < nspecies; ++i) for (int iat = 0; iat < GroupID.size(); ++iat) - if (GroupID[iat] == i) IndirectID[new_id++] = ID[iat]; + if (GroupID[iat] == i) + IndirectID[new_id++] = ID[iat]; IsGrouped = true; for (int iat = 0; iat < ID.size(); ++iat) IsGrouped &= (IndirectID[iat] == ID[iat]); @@ -195,7 +195,7 @@ void ParticleSet::resetGroups() } /// write to a std::ostream -bool ParticleSet::get(std::ostream &os) const +bool ParticleSet::get(std::ostream& os) const { os << " ParticleSet " << getName() << " : "; for (int i = 0; i < SubPtcl.size(); i++) @@ -211,29 +211,24 @@ bool ParticleSet::get(std::ostream &os) const if (numToPrint < TotalNum) { - os << " (... and " << (TotalNum - numToPrint) - << " more particle positions ...)" << std::endl; + os << " (... and " << (TotalNum - numToPrint) << " more particle positions ...)" << std::endl; } return true; } /// read from std::istream -bool ParticleSet::put(std::istream &is) { return true; } +bool ParticleSet::put(std::istream& is) { return true; } /// reset member data -void ParticleSet::reset() -{ - app_log() << "<<<< going to set properties >>>> " << std::endl; -} +void ParticleSet::reset() { app_log() << "<<<< going to set properties >>>> " << std::endl; } void ParticleSet::setBoundBox(bool yes) { UseBoundBox = yes; } -int ParticleSet::addTable(const ParticleSet &psrc, int dt_type) +int ParticleSet::addTable(const ParticleSet& psrc, int dt_type) { if (myName == "none") - APP_ABORT( - "ParticleSet::addTable needs a proper name for this particle set."); + APP_ABORT("ParticleSet::addTable needs a proper name for this particle set."); if (DistTables.empty()) { DistTables.reserve(4); @@ -241,14 +236,14 @@ int ParticleSet::addTable(const ParticleSet &psrc, int dt_type) // add this-this pair myDistTableMap.clear(); myDistTableMap[myName] = 0; - app_log() << " ... ParticleSet::addTable Create Table #0 " - << DistTables[0]->Name << std::endl; - if (psrc.getName() == myName) return 0; + app_log() << " ... ParticleSet::addTable Create Table #0 " << DistTables[0]->Name << std::endl; + if (psrc.getName() == myName) + return 0; } if (psrc.getName() == myName) { - app_log() << " ... ParticleSet::addTable Reuse Table #" << 0 << " " - << DistTables[0]->Name << std::endl; + app_log() << " ... ParticleSet::addTable Reuse Table #" << 0 << " " << DistTables[0]->Name + << std::endl; // if(!DistTables[0]->is_same_type(dt_type)) //{//itself is special, cannot mix them: some of the users do not check the // index @@ -264,22 +259,20 @@ int ParticleSet::addTable(const ParticleSet &psrc, int dt_type) tid = DistTables.size(); DistTables.push_back(createDistanceTable(psrc, *this, dt_type)); myDistTableMap[psrc.getName()] = tid; - app_log() << " ... ParticleSet::addTable Create Table #" << tid << " " - << DistTables[tid]->Name << std::endl; + app_log() << " ... ParticleSet::addTable Create Table #" << tid << " " << DistTables[tid]->Name + << std::endl; } else { tid = (*tit).second; - if (dt_type == DT_SOA_PREFERRED || - DistTables[tid]->is_same_type(dt_type)) // good to reuse + if (dt_type == DT_SOA_PREFERRED || DistTables[tid]->is_same_type(dt_type)) // good to reuse { app_log() << " ... ParticleSet::addTable Reuse Table #" << tid << " " << DistTables[tid]->Name << std::endl; } else { - APP_ABORT( - "ParticleSet::addTable Cannot mix AoS and SoA distance tables.\n"); + APP_ABORT("ParticleSet::addTable Cannot mix AoS and SoA distance tables.\n"); } // if(dt_type == DT_SOA || dt_type == DT_AOS) //not compatible //{ @@ -314,8 +307,7 @@ void ParticleSet::setActive(int iat) * Update activePtcl index and activePos position for the proposed move. * Evaluate the related distance table data DistanceTableData::Temp. */ -bool ParticleSet::makeMoveAndCheck(Index_t iat, - const SingleParticlePos_t &displ) +bool ParticleSet::makeMoveAndCheck(Index_t iat, const SingleParticlePos_t& displ) { ScopedTimer local_timer(timers[Timer_makeMove]); @@ -352,8 +344,7 @@ bool ParticleSet::makeMoveAndCheck(Index_t iat, * @param iat the particle that is moved on a sphere * @param displ displacement from the current position */ -void ParticleSet::makeMoveOnSphere(Index_t iat, - const SingleParticlePos_t &displ) +void ParticleSet::makeMoveOnSphere(Index_t iat, const SingleParticlePos_t& displ) { ScopedTimer local_timer(timers[Timer_makeMove]); @@ -393,12 +384,9 @@ void ParticleSet::acceptMove(Index_t iat) void ParticleSet::rejectMove(Index_t iat) { activePtcl = -1; } -void ParticleSet::donePbyP(bool skipSK) -{ - activePtcl = -1; -} +void ParticleSet::donePbyP(bool skipSK) { activePtcl = -1; } -void ParticleSet::loadWalker(Walker_t &awalker, bool pbyp) +void ParticleSet::loadWalker(Walker_t& awalker, bool pbyp) { R = awalker.R; RSoA.copyIn(R); @@ -411,7 +399,7 @@ void ParticleSet::loadWalker(Walker_t &awalker, bool pbyp) } } -void ParticleSet::saveWalker(Walker_t &awalker) { awalker.R = R; } +void ParticleSet::saveWalker(Walker_t& awalker) { awalker.R = R; } void ParticleSet::clearDistanceTables() { @@ -421,18 +409,20 @@ void ParticleSet::clearDistanceTables() DistTables.clear(); } -const std::vector extract_G_list(const std::vector &P_list) +const std::vector + extract_G_list(const std::vector& P_list) { - std::vector G_list; - for(auto it=P_list.begin(); it!=P_list.end(); it++) + std::vector G_list; + for (auto it = P_list.begin(); it != P_list.end(); it++) G_list.push_back(&(*it)->G); return G_list; } -const std::vector extract_L_list(const std::vector &P_list) +const std::vector + extract_L_list(const std::vector& P_list) { - std::vector L_list; - for(auto it=P_list.begin(); it!=P_list.end(); it++) + std::vector L_list; + for (auto it = P_list.begin(); it != P_list.end(); it++) L_list.push_back(&(*it)->L); return L_list; } diff --git a/src/Particle/ParticleSet.h b/src/Particle/ParticleSet.h index 78ec78eda..f84835485 100644 --- a/src/Particle/ParticleSet.h +++ b/src/Particle/ParticleSet.h @@ -40,7 +40,6 @@ namespace qmcplusplus { - /// forward declaration of DistanceTableData class DistanceTableData; @@ -53,7 +52,8 @@ class DistanceTableData; * - Variance variance * - LivingFraction fraction of walkers alive each step. */ -template struct MCDataType +template +struct MCDataType { T NumSamples; T RNSamples; @@ -139,7 +139,7 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits SpeciesSet mySpecies; /// distance tables that need to be updated by moving this ParticleSet - std::vector DistTables; + std::vector DistTables; /// current MC step int current_step; @@ -149,7 +149,7 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits ParticleSet(); /// copy constructor - ParticleSet(const ParticleSet &p); + ParticleSet(const ParticleSet& p); /// default destructor virtual ~ParticleSet(); @@ -161,13 +161,13 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits /** create grouped particles * @param agroup number of particles per group */ - void create(const std::vector &agroup); + void create(const std::vector& agroup); /// write to a std::ostream - bool get(std::ostream &) const; + bool get(std::ostream&) const; /// read from std::istream - bool put(std::istream &); + bool put(std::istream&); /// reset member data void reset(); @@ -180,7 +180,7 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits * * Ensure that the distance for this-this is always created first. */ - int addTable(const ParticleSet &psrc, int dt_type); + int addTable(const ParticleSet& psrc, int dt_type); /** update the internal data *@param skip SK update if skipSK is true @@ -188,14 +188,14 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits void update(bool skipSK = false); /// retrun the SpeciesSet of this particle set - inline SpeciesSet &getSpeciesSet() { return mySpecies; } + inline SpeciesSet& getSpeciesSet() { return mySpecies; } /// retrun the const SpeciesSet of this particle set - inline const SpeciesSet &getSpeciesSet() const { return mySpecies; } + inline const SpeciesSet& getSpeciesSet() const { return mySpecies; } - inline void setName(const std::string &aname) { myName = aname; } + inline void setName(const std::string& aname) { myName = aname; } /// return the name - inline const std::string &getName() const { return myName; } + inline const std::string& getName() const { return myName; } void resetGroups(); @@ -211,23 +211,20 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits * * activePtcl=-1 is used to flag non-physical moves */ - inline const PosType& activeR(int iat) const - { - return (activePtcl == iat)? activePos:R[iat]; - } + inline const PosType& activeR(int iat) const { return (activePtcl == iat) ? activePos : R[iat]; } /** move a particle * @param iat the index of the particle to be moved * @param displ random displacement of the iat-th particle * @return true, if the move is valid */ - bool makeMoveAndCheck(Index_t iat, const SingleParticlePos_t &displ); + bool makeMoveAndCheck(Index_t iat, const SingleParticlePos_t& displ); /** move a particle * @param iat the index of the particle to be moved * @param displ random displacement of the iat-th particle */ - void makeMoveOnSphere(Index_t iat, const SingleParticlePos_t &displ); + void makeMoveOnSphere(Index_t iat, const SingleParticlePos_t& displ); /** accept the move *@param iat the index of the particle whose position and other attributes to @@ -241,8 +238,8 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits void clearDistanceTables(); - void convert2Unit(ParticlePos_t &pout); - void convert2Cart(ParticlePos_t &pout); + void convert2Unit(ParticlePos_t& pout); + void convert2Cart(ParticlePos_t& pout); /** load a Walker_t to the current ParticleSet * @param awalker the reference to the walker to be loaded @@ -250,25 +247,22 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits * * PbyP requires the distance tables and Sk with awalker.R */ - void loadWalker(Walker_t &awalker, bool pbyp); + void loadWalker(Walker_t& awalker, bool pbyp); /** save this to awalker */ - void saveWalker(Walker_t &awalker); + void saveWalker(Walker_t& awalker); /** update the buffer *@param skip SK update if skipSK is true */ void donePbyP(bool skipSK = false); - inline void setTwist(SingleParticlePos_t &t) { myTwist = t; } + inline void setTwist(SingleParticlePos_t& t) { myTwist = t; } inline SingleParticlePos_t getTwist() const { return myTwist; } /** get species name of particle i */ - inline const std::string &species_from_index(int i) - { - return mySpecies.speciesName[GroupID[i]]; - } + inline const std::string& species_from_index(int i) { return mySpecies.speciesName[GroupID[i]]; } inline int getTotalNum() const { return TotalNum; } @@ -289,7 +283,7 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits RSoA.resize(numPtcl); } - inline void assign(const ParticleSet &ptclin) + inline void assign(const ParticleSet& ptclin) { resize(ptclin.getTotalNum()); Lattice = ptclin.Lattice; @@ -334,8 +328,10 @@ class ParticleSet : public QMCTraits, public PtclOnLatticeTraits TimerList_t timers; }; -const std::vector extract_G_list(const std::vector &P_list); -const std::vector extract_L_list(const std::vector &P_list); +const std::vector + extract_G_list(const std::vector& P_list); +const std::vector + extract_L_list(const std::vector& P_list); -} +} // namespace qmcplusplus #endif diff --git a/src/Particle/ParticleSet_builder.cpp b/src/Particle/ParticleSet_builder.cpp index 8b6d0dc49..75e9d6b8d 100644 --- a/src/Particle/ParticleSet_builder.cpp +++ b/src/Particle/ParticleSet_builder.cpp @@ -20,41 +20,36 @@ namespace qmcplusplus { +int build_ions(ParticleSet& ions, const Tensor& tmat, Tensor& lattice) +{ + ions.setName("ion"); + ions.Lattice.BoxBConds = 1; + lattice = tile_cell(ions, tmat, static_cast(1.0)); + ions.RSoA = ions.R; // fill the SoA - int build_ions(ParticleSet &ions, - const Tensor &tmat, - Tensor &lattice) - { - ions.setName("ion"); - ions.Lattice.BoxBConds = 1; - lattice = tile_cell(ions, tmat, static_cast(1.0)); - ions.RSoA = ions.R; // fill the SoA - - return ions.getTotalNum(); - } + return ions.getTotalNum(); +} - int build_els(ParticleSet &els, - const ParticleSet &ions, - RandomGenerator &rng) - { - els.setName("e"); - const int nels = count_electrons(ions, 1); - const int nels3 = 3 * nels; - - { // create up/down electrons - els.Lattice.BoxBConds = 1; - els.Lattice.set(ions.Lattice); - std::vector ud(2); - ud[0] = nels / 2; - ud[1] = nels - ud[0]; - els.create(ud); - els.R.InUnit = 1; - rng.generate_uniform(&els.R[0][0], nels3); - els.convert2Cart(els.R); // convert to Cartiesian - els.RSoA = els.R; - } - - return nels; +int build_els(ParticleSet& els, const ParticleSet& ions, RandomGenerator& rng) +{ + els.setName("e"); + const int nels = count_electrons(ions, 1); + const int nels3 = 3 * nels; + + { // create up/down electrons + els.Lattice.BoxBConds = 1; + els.Lattice.set(ions.Lattice); + std::vector ud(2); + ud[0] = nels / 2; + ud[1] = nels - ud[0]; + els.create(ud); + els.R.InUnit = 1; + rng.generate_uniform(&els.R[0][0], nels3); + els.convert2Cart(els.R); // convert to Cartiesian + els.RSoA = els.R; } + return nels; } + +} // namespace qmcplusplus diff --git a/src/Particle/ParticleSet_builder.hpp b/src/Particle/ParticleSet_builder.hpp index cfad51db5..5ae50ed4b 100644 --- a/src/Particle/ParticleSet_builder.hpp +++ b/src/Particle/ParticleSet_builder.hpp @@ -19,15 +19,11 @@ namespace qmcplusplus { - /// build the ParticleSet of ions - int build_ions(ParticleSet &ions, - const Tensor &tmat, - Tensor &lattice); +/// build the ParticleSet of ions +int build_ions(ParticleSet& ions, const Tensor& tmat, Tensor& lattice); - /// build the ParticleSet of electrons - int build_els(ParticleSet &els, - const ParticleSet &ions, - RandomGenerator &rng); -} +/// build the ParticleSet of electrons +int build_els(ParticleSet& els, const ParticleSet& ions, RandomGenerator& rng); +} // namespace qmcplusplus #endif diff --git a/src/Particle/Walker.h b/src/Particle/Walker.h index 0b3dc7173..8eb3c7e40 100644 --- a/src/Particle/Walker.h +++ b/src/Particle/Walker.h @@ -37,7 +37,6 @@ #include namespace qmcplusplus { - /** an enum denoting index of physical properties * * LOCALPOTENTIAL should be always the last enumeation @@ -55,8 +54,8 @@ enum DRIFTSCALE, /*!< scaling value for the drift */ ALTERNATEENERGY, /*!< alternatelocal energy, the sum of all the components */ LOCALENERGY, /*!< local energy, the sum of all the components */ - LOCALPOTENTIAL, /*!< local potential energy = local energy - kinetic energy */ - NUMPROPERTIES /*!< the number of properties */ + LOCALPOTENTIAL, /*!< local potential energy = local energy - kinetic energy */ + NUMPROPERTIES /*!< the number of properties */ }; /** A container class to represent a walker. @@ -75,7 +74,8 @@ enum * index and second index >=NUMPROPERTIES. * - DataSet : anonymous container. */ -template struct Walker +template +struct Walker { enum { @@ -137,17 +137,19 @@ template struct Walker Weight = 1.0; Multiplicity = 1.0; Properties.resize(1, NUMPROPERTIES); - if (nptcl > 0) resize(nptcl); + if (nptcl > 0) + resize(nptcl); } - inline Walker(const Walker &a) = default; + inline Walker(const Walker& a) = default; inline ~Walker() {} /// assignment operator - inline Walker &operator=(const Walker &a) + inline Walker& operator=(const Walker& a) { // make deep copy - if (this != &a) makeCopy(a); + if (this != &a) + makeCopy(a); return *this; } @@ -158,7 +160,7 @@ template struct Walker inline void resize(int nptcl) { R.resize(nptcl); } /// copy the content of a walker - inline void makeCopy(const Walker &a) + inline void makeCopy(const Walker& a) { ID = a.ID; ParentID = a.ParentID; @@ -166,7 +168,8 @@ template struct Walker Age = a.Age; Weight = a.Weight; Multiplicity = a.Multiplicity; - if (R.size() != a.R.size()) resize(a.R.size()); + if (R.size() != a.R.size()) + resize(a.R.size()); R = a.R; DataSet = a.DataSet; } @@ -181,20 +184,27 @@ template struct Walker return bsize; } - template inline Msg &putMessage(Msg &m) { return m; } + template + inline Msg& putMessage(Msg& m) + { + return m; + } - template inline Msg &getMessage(Msg &m) { return m; } + template + inline Msg& getMessage(Msg& m) + { + return m; + } }; -template -std::ostream &operator<<(std::ostream &out, const Walker &rhs) +template +std::ostream& operator<<(std::ostream& out, const Walker& rhs) { - copy(rhs.Properties.begin(), rhs.Properties.end(), - std::ostream_iterator(out, " ")); + copy(rhs.Properties.begin(), rhs.Properties.end(), std::ostream_iterator(out, " ")); out << std::endl; out << rhs.R; return out; } -} +} // namespace qmcplusplus #endif diff --git a/src/QMCWaveFunctions/Determinant.h b/src/QMCWaveFunctions/Determinant.h index 24c82c0a9..f8abd9f57 100644 --- a/src/QMCWaveFunctions/Determinant.h +++ b/src/QMCWaveFunctions/Determinant.h @@ -25,34 +25,40 @@ namespace qmcplusplus { /**@{Determinant utilities */ /** Inversion of a double matrix after LU factorization*/ -inline void getri(int n, double *restrict a, int lda, int *restrict piv, - double *restrict work, int &lwork) +inline void + getri(int n, double* restrict a, int lda, int* restrict piv, double* restrict work, int& lwork) { int status; dgetri(n, a, lda, piv, work, lwork, status); } /** Inversion of a float matrix after LU factorization*/ -inline void getri(int n, float *restrict a, int lda, int *restrict piv, - float *restrict work, int &lwork) +inline void + getri(int n, float* restrict a, int lda, int* restrict piv, float* restrict work, int& lwork) { int status; sgetri(n, a, lda, piv, work, lwork, status); } /** Inversion of a std::complex matrix after LU factorization*/ -inline void getri(int n, std::complex *restrict a, int lda, - int *restrict piv, std::complex *restrict work, - int &lwork) +inline void getri(int n, + std::complex* restrict a, + int lda, + int* restrict piv, + std::complex* restrict work, + int& lwork) { int status; zgetri(n, a, lda, piv, work, lwork, status); } /** Inversion of a complex matrix after LU factorization*/ -inline void getri(int n, std::complex *restrict a, int lda, - int *restrict piv, std::complex *restrict work, - int &lwork) +inline void getri(int n, + std::complex* restrict a, + int lda, + int* restrict piv, + std::complex* restrict work, + int& lwork) { int status; cgetri(n, a, lda, piv, work, lwork, status); @@ -60,8 +66,8 @@ inline void getri(int n, std::complex *restrict a, int lda, /** query the size of workspace for Xgetri after LU decompisiton */ -template -inline int getGetriWorkspace(T *restrict x, int n, int lda, int *restrict pivot) +template +inline int getGetriWorkspace(T* restrict x, int n, int lda, int* restrict pivot) { T work; int lwork = -1; @@ -74,9 +80,8 @@ inline int getGetriWorkspace(T *restrict x, int n, int lda, int *restrict pivot) * * Assume: in[n][lda] and out[n][lda] */ -template -inline void transpose(const TIN *restrict in, TOUT *restrict out, int n, - int lda) +template +inline void transpose(const TIN* restrict in, TOUT* restrict out, int n, int lda) { for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) @@ -84,9 +89,9 @@ inline void transpose(const TIN *restrict in, TOUT *restrict out, int n, } /// used only for debugging or walker move -template -inline T InvertWithLog(T *restrict x, int n, int lda, T *restrict work, - int lwork, int *restrict pivot, T &phase) +template +inline T + InvertWithLog(T* restrict x, int n, int lda, T* restrict work, int lwork, int* restrict pivot, T& phase) { T logdet(0.0); LUFactorization(n, n, x, lda, pivot); @@ -103,9 +108,8 @@ inline T InvertWithLog(T *restrict x, int n, int lda, T *restrict work, } /// inner product -template -inline T3 inner_product_n(const T1 *restrict a, const T2 *restrict b, int n, - T3 res) +template +inline T3 inner_product_n(const T1* restrict a, const T2* restrict b, int n, T3 res) { for (int i = 0; i < n; ++i) res += a[i] * b[i]; @@ -113,9 +117,9 @@ inline T3 inner_product_n(const T1 *restrict a, const T2 *restrict b, int n, } /// recompute inverse, do not evaluate log|det| -template -inline void InvertOnly(T *restrict x, int n, int lda, T *restrict work, - int *restrict pivot, int lwork) +template +inline void + InvertOnly(T* restrict x, int n, int lda, T* restrict work, int* restrict pivot, int lwork) { LUFactorization(n, n, x, lda, pivot); getri(n, x, lda, pivot, work, lwork); @@ -123,9 +127,9 @@ inline void InvertOnly(T *restrict x, int n, int lda, T *restrict work, /** update Row as implemented in the full code */ /** [UpdateRow] */ -template -inline void updateRow(T *restrict pinv, const T *restrict tv, int m, int lda, - int rowchanged, RT c_ratio_in) +template +inline void + updateRow(T* restrict pinv, const T* restrict tv, int m, int lda, int rowchanged, RT c_ratio_in) { constexpr T cone(1); constexpr T czero(0); @@ -140,8 +144,8 @@ inline void updateRow(T *restrict pinv, const T *restrict tv, int m, int lda, /**@}*/ // FIXME do we want to keep this in the miniapp? -template -void checkIdentity(const MT1 &a, const MT2 &b, const std::string &tag) +template +void checkIdentity(const MT1& a, const MT2& b, const std::string& tag) { constexpr double czero(0.0); constexpr double cone(1.0); @@ -162,8 +166,8 @@ void checkIdentity(const MT1 &a, const MT2 &b, const std::string &tag) } // FIXME do we want to keep this in the miniapp? -template -void checkDiff(const MT1 &a, const MT2 &b, const std::string &tag) +template +void checkDiff(const MT1& a, const MT2& b, const std::string& tag) { const int nrows = a.rows(); const int ncols = a.cols(); @@ -174,13 +178,14 @@ void checkDiff(const MT1 &a, const MT2 &b, const std::string &tag) error += std::abs(static_cast(a(i, j) - b(i, j))); #pragma omp master - std::cout << tag << " difference between matrices (average per element) = " << error / nrows / nrows << std::endl; + std::cout << tag << " difference between matrices (average per element) = " << error / nrows / nrows + << std::endl; } struct DiracDeterminant : public WaveFunctionComponent { - DiracDeterminant(int nels, const RandomGenerator &RNG, int First=0) - : FirstIndex(First), myRandom(RNG) + DiracDeterminant(int nels, const RandomGenerator& RNG, int First = 0) + : FirstIndex(First), myRandom(RNG) { psiMinv.resize(nels, nels); psiV.resize(nels); @@ -202,8 +207,7 @@ struct DiracDeterminant : public WaveFunctionComponent double phase; transpose(psiMsave.data(), psiM.data(), nels, nels); - LogValue = InvertWithLog(psiM.data(), nels, nels, work.data(), LWork, - pivot.data(), phase); + LogValue = InvertWithLog(psiM.data(), nels, nels, work.data(), LWork, pivot.data(), phase); std::copy_n(psiM.data(), nels * nels, psiMinv.data()); } @@ -217,20 +221,24 @@ struct DiracDeterminant : public WaveFunctionComponent } } - RealType evaluateLog(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L) + RealType evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L) { recompute(); // FIXME do we want remainder of evaluateLog? return 0.0; } - GradType evalGrad(ParticleSet &P, int iat) { return GradType();} + GradType evalGrad(ParticleSet& P, int iat) { return GradType(); } - ValueType ratioGrad(ParticleSet &P, int iat, GradType &grad) { return ratio(P, iat); } + ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad) { return ratio(P, iat); } - void evaluateGL(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, bool fromscratch = false) {} + void evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, + bool fromscratch = false) + {} /// recompute the inverse inline void recompute() @@ -244,23 +252,23 @@ struct DiracDeterminant : public WaveFunctionComponent /** return determinant ratio for the row replacement * @param iel the row (active particle) index */ - inline ValueType ratio(ParticleSet &P, int iel) + inline ValueType ratio(ParticleSet& P, int iel) { const int nels = psiV.size(); constexpr double shift(0.5); constexpr double czero(0); for (int j = 0; j < nels; ++j) psiV[j] = myRandom() - shift; - curRatio = inner_product_n(psiV.data(), psiMinv[iel-FirstIndex], nels, czero); + curRatio = inner_product_n(psiV.data(), psiMinv[iel - FirstIndex], nels, czero); return curRatio; } /** accept the row and update the inverse */ - inline void acceptMove(ParticleSet &P, int iel) + inline void acceptMove(ParticleSet& P, int iel) { const int nels = psiV.size(); - updateRow(psiMinv.data(), psiV.data(), nels, nels, iel-FirstIndex, curRatio); - std::copy_n(psiV.data(), nels, psiMsave[iel-FirstIndex]); + updateRow(psiMinv.data(), psiV.data(), nels, nels, iel - FirstIndex, curRatio); + std::copy_n(psiV.data(), nels, psiMsave[iel - FirstIndex]); } /** accessor functions for checking */ @@ -290,6 +298,6 @@ struct DiracDeterminant : public WaveFunctionComponent aligned_vector work; Matrix psiMsave; }; -} +} // namespace qmcplusplus #endif diff --git a/src/QMCWaveFunctions/DeterminantRef.h b/src/QMCWaveFunctions/DeterminantRef.h index 7c4154f49..5e869dce5 100644 --- a/src/QMCWaveFunctions/DeterminantRef.h +++ b/src/QMCWaveFunctions/DeterminantRef.h @@ -27,45 +27,50 @@ namespace miniqmcreference { - /**@{Determinant utilities */ /** Inversion of a double matrix after LU factorization*/ -inline void getri(int n, double *restrict a, int lda, int *restrict piv, - double *restrict work, int &lwork) +inline void + getri(int n, double* restrict a, int lda, int* restrict piv, double* restrict work, int& lwork) { int status; dgetri(n, a, lda, piv, work, lwork, status); } /** Inversion of a float matrix after LU factorization*/ -inline void getri(int n, float *restrict a, int lda, int *restrict piv, - float *restrict work, int &lwork) +inline void + getri(int n, float* restrict a, int lda, int* restrict piv, float* restrict work, int& lwork) { int status; sgetri(n, a, lda, piv, work, lwork, status); } /** Inversion of a std::complex matrix after LU factorization*/ -inline void getri(int n, std::complex *restrict a, int lda, - int *restrict piv, std::complex *restrict work, - int &lwork) +inline void getri(int n, + std::complex* restrict a, + int lda, + int* restrict piv, + std::complex* restrict work, + int& lwork) { int status; zgetri(n, a, lda, piv, work, lwork, status); } /** Inversion of a complex matrix after LU factorization*/ -inline void getri(int n, std::complex *restrict a, int lda, - int *restrict piv, std::complex *restrict work, - int &lwork) +inline void getri(int n, + std::complex* restrict a, + int lda, + int* restrict piv, + std::complex* restrict work, + int& lwork) { int status; cgetri(n, a, lda, piv, work, lwork, status); } /** query the size of workspace for Xgetri after LU decompisiton */ -template -inline int getGetriWorkspace(T *restrict x, int n, int lda, int *restrict pivot) +template +inline int getGetriWorkspace(T* restrict x, int n, int lda, int* restrict pivot) { T work; int lwork = -1; @@ -78,9 +83,8 @@ inline int getGetriWorkspace(T *restrict x, int n, int lda, int *restrict pivot) * * Assume: in[n][lda] and out[n][lda] */ -template -inline void transpose(const TIN *restrict in, TOUT *restrict out, int n, - int lda) +template +inline void transpose(const TIN* restrict in, TOUT* restrict out, int n, int lda) { for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) @@ -88,9 +92,9 @@ inline void transpose(const TIN *restrict in, TOUT *restrict out, int n, } /// used only for debugging or walker move -template -inline T InvertWithLog(T *restrict x, int n, int lda, T *restrict work, - int lwork, int *restrict pivot, T &phase) +template +inline T + InvertWithLog(T* restrict x, int n, int lda, T* restrict work, int lwork, int* restrict pivot, T& phase) { T logdet(0.0); qmcplusplus::LUFactorization(n, n, x, lda, pivot); @@ -107,9 +111,8 @@ inline T InvertWithLog(T *restrict x, int n, int lda, T *restrict work, } /// inner product -template -inline T3 inner_product_n(const T1 *restrict a, const T2 *restrict b, int n, - T3 res) +template +inline T3 inner_product_n(const T1* restrict a, const T2* restrict b, int n, T3 res) { for (int i = 0; i < n; ++i) res += a[i] * b[i]; @@ -117,18 +120,18 @@ inline T3 inner_product_n(const T1 *restrict a, const T2 *restrict b, int n, } /// recompute inverse, do not evaluate log|det| -template -inline void InvertOnly(T *restrict x, int n, int lda, T *restrict work, - int *restrict pivot, int lwork) +template +inline void + InvertOnly(T* restrict x, int n, int lda, T* restrict work, int* restrict pivot, int lwork) { qmcplusplus::LUFactorization(n, n, x, lda, pivot); getri(n, x, lda, pivot, work, lwork); } /** update Row as implemented in the full code */ -template -inline void updateRow(T *restrict pinv, const T *restrict tv, int m, int lda, - int rowchanged, RT c_ratio_in) +template +inline void + updateRow(T* restrict pinv, const T* restrict tv, int m, int lda, int rowchanged, RT c_ratio_in) { constexpr T cone(1); constexpr T czero(0); @@ -142,8 +145,8 @@ inline void updateRow(T *restrict pinv, const T *restrict tv, int m, int lda, /**@}*/ // FIXME do we want to keep this in the miniapp? -template -void checkIdentity(const MT1 &a, const MT2 &b, const std::string &tag) +template +void checkIdentity(const MT1& a, const MT2& b, const std::string& tag) { constexpr double czero(0.0); constexpr double cone(1.0); @@ -164,8 +167,8 @@ void checkIdentity(const MT1 &a, const MT2 &b, const std::string &tag) } // FIXME do we want to keep this in the miniapp? -template -void checkDiff(const MT1 &a, const MT2 &b, const std::string &tag) +template +void checkDiff(const MT1& a, const MT2& b, const std::string& tag) { const int nrows = a.rows(); const int ncols = a.cols(); @@ -176,16 +179,16 @@ void checkDiff(const MT1 &a, const MT2 &b, const std::string &tag) error += std::abs(static_cast(a(i, j) - b(i, j))); #pragma omp master - std::cout << tag << " difference between matrices (average per element) = " << error / nrows / nrows << std::endl; - + std::cout << tag << " difference between matrices (average per element) = " << error / nrows / nrows + << std::endl; } struct DiracDeterminantRef : public qmcplusplus::WaveFunctionComponent { using ParticleSet = qmcplusplus::ParticleSet; - DiracDeterminantRef(int nels, const qmcplusplus::RandomGenerator &RNG, int First=0) - : FirstIndex(First), myRandom(RNG) + DiracDeterminantRef(int nels, const qmcplusplus::RandomGenerator& RNG, int First = 0) + : FirstIndex(First), myRandom(RNG) { psiMinv.resize(nels, nels); psiV.resize(nels); @@ -207,8 +210,7 @@ struct DiracDeterminantRef : public qmcplusplus::WaveFunctionComponent double phase; transpose(psiMsave.data(), psiM.data(), nels, nels); - LogValue = InvertWithLog(psiM.data(), nels, nels, work.data(), LWork, - pivot.data(), phase); + LogValue = InvertWithLog(psiM.data(), nels, nels, work.data(), LWork, pivot.data(), phase); std::copy_n(psiM.data(), nels * nels, psiMinv.data()); } @@ -223,17 +225,21 @@ struct DiracDeterminantRef : public qmcplusplus::WaveFunctionComponent } } - RealType evaluateLog(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L) + RealType evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L) { recompute(); // FIXME do we want remainder of evaluateLog? return 0.0; } - GradType evalGrad(ParticleSet &P, int iat) {return GradType();} - ValueType ratioGrad(ParticleSet &P, int iat, GradType &grad) { return ratio(P, iat); } - void evaluateGL(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, bool fromscratch = false) {} + GradType evalGrad(ParticleSet& P, int iat) { return GradType(); } + ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad) { return ratio(P, iat); } + void evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, + bool fromscratch = false) + {} /// recompute the inverse inline void recompute() @@ -247,23 +253,23 @@ struct DiracDeterminantRef : public qmcplusplus::WaveFunctionComponent /** return determinant ratio for the row replacement * @param iel the row (active particle) index */ - inline ValueType ratio(ParticleSet &P, int iel) + inline ValueType ratio(ParticleSet& P, int iel) { const int nels = psiV.size(); constexpr double shift(0.5); constexpr double czero(0); for (int j = 0; j < nels; ++j) psiV[j] = myRandom() - shift; - curRatio = inner_product_n(psiV.data(), psiMinv[iel-FirstIndex], nels, czero); + curRatio = inner_product_n(psiV.data(), psiMinv[iel - FirstIndex], nels, czero); return curRatio; } /** accept the row and update the inverse */ - inline void acceptMove(ParticleSet &P, int iel) + inline void acceptMove(ParticleSet& P, int iel) { const int nels = psiV.size(); - updateRow(psiMinv.data(), psiV.data(), nels, nels, iel-FirstIndex, curRatio); - std::copy_n(psiV.data(), nels, psiMsave[iel-FirstIndex]); + updateRow(psiMinv.data(), psiV.data(), nels, nels, iel - FirstIndex, curRatio); + std::copy_n(psiV.data(), nels, psiMsave[iel - FirstIndex]); } /** accessor functions for checking */ @@ -293,6 +299,6 @@ struct DiracDeterminantRef : public qmcplusplus::WaveFunctionComponent qmcplusplus::aligned_vector work; qmcplusplus::Matrix psiMsave; }; -} // miniqmcreference +} // namespace miniqmcreference #endif diff --git a/src/QMCWaveFunctions/Jastrow/BsplineFunctor.h b/src/QMCWaveFunctions/Jastrow/BsplineFunctor.h index 448b0460d..c9726cb03 100644 --- a/src/QMCWaveFunctions/Jastrow/BsplineFunctor.h +++ b/src/QMCWaveFunctions/Jastrow/BsplineFunctor.h @@ -40,8 +40,8 @@ namespace qmcplusplus { - -template struct BsplineFunctor : public OptimizableFunctorBase +template +struct BsplineFunctor : public OptimizableFunctorBase { typedef real_type value_type; int NumParams; @@ -117,8 +117,7 @@ template struct BsplineFunctor : public OptimizableFunctorBase SplineCoefs[i + 1] = Parameters[i]; } - void setupParameters(int n, real_type rcut, real_type cusp, - std::vector ¶ms) + void setupParameters(int n, real_type rcut, real_type cusp, std::vector& params) { CuspValue = cusp; cutoff_radius = rcut; @@ -156,13 +155,16 @@ template struct BsplineFunctor : public OptimizableFunctorBase * @param distArrayCompressed temp storage to filter r_j < cutoff_radius * @return \f$\sum u(r_j)\f$ for r_j < cutoff_radius */ - T evaluateV(const int iat, const int iStart, const int iEnd, - const T *restrict _distArray, - T *restrict distArrayCompressed) const; + T evaluateV(const int iat, + const int iStart, + const int iEnd, + const T* restrict _distArray, + T* restrict distArrayCompressed) const; inline real_type evaluate(real_type r) { - if (r >= cutoff_radius) return 0.0; + if (r >= cutoff_radius) + return 0.0; r *= DeltaRInv; real_type ipart, t; t = std::modf(r, &ipart); @@ -181,7 +183,7 @@ template struct BsplineFunctor : public OptimizableFunctorBase // clang-format on } - inline real_type evaluate(real_type r, real_type &dudr, real_type &d2udr2) + inline real_type evaluate(real_type r, real_type& dudr, real_type& d2udr2) { if (r >= cutoff_radius) { @@ -215,16 +217,16 @@ template struct BsplineFunctor : public OptimizableFunctorBase SplineCoefs[i+3]*(A[12]*tp[0] + A[13]*tp[1] + A[14]*tp[2] + A[15]*tp[3])); // clang-format on } - }; -template -inline T BsplineFunctor::evaluateV(const int iat, const int iStart, +template +inline T BsplineFunctor::evaluateV(const int iat, + const int iStart, const int iEnd, - const T *restrict _distArray, - T *restrict distArrayCompressed) const + const T* restrict _distArray, + T* restrict distArrayCompressed) const { - const real_type *restrict distArray = _distArray + iStart; + const real_type* restrict distArray = _distArray + iStart; ASSUME_ALIGNED(distArrayCompressed); int iCount = 0; @@ -251,26 +253,26 @@ inline T BsplineFunctor::evaluateV(const int iat, const int iStart, real_type tp1 = t * t; real_type tp2 = t; - real_type d1 = - SplineCoefs[i + 0] * (A[0] * tp0 + A[1] * tp1 + A[2] * tp2 + A[3]); - real_type d2 = - SplineCoefs[i + 1] * (A[4] * tp0 + A[5] * tp1 + A[6] * tp2 + A[7]); - real_type d3 = - SplineCoefs[i + 2] * (A[8] * tp0 + A[9] * tp1 + A[10] * tp2 + A[11]); - real_type d4 = - SplineCoefs[i + 3] * (A[12] * tp0 + A[13] * tp1 + A[14] * tp2 + A[15]); + real_type d1 = SplineCoefs[i + 0] * (A[0] * tp0 + A[1] * tp1 + A[2] * tp2 + A[3]); + real_type d2 = SplineCoefs[i + 1] * (A[4] * tp0 + A[5] * tp1 + A[6] * tp2 + A[7]); + real_type d3 = SplineCoefs[i + 2] * (A[8] * tp0 + A[9] * tp1 + A[10] * tp2 + A[11]); + real_type d4 = SplineCoefs[i + 3] * (A[12] * tp0 + A[13] * tp1 + A[14] * tp2 + A[15]); d += (d1 + d2 + d3 + d4); } return d; } -template -inline void BsplineFunctor::evaluateVGL( - const int iat, const int iStart, const int iEnd, const T *_distArray, - T *restrict _valArray, T *restrict _gradArray, T *restrict _laplArray, - T *restrict distArrayCompressed, int *restrict distIndices) const +template +inline void BsplineFunctor::evaluateVGL(const int iat, + const int iStart, + const int iEnd, + const T* _distArray, + T* restrict _valArray, + T* restrict _gradArray, + T* restrict _laplArray, + T* restrict distArrayCompressed, + int* restrict distIndices) const { - real_type dSquareDeltaRinv = DeltaRInv * DeltaRInv; constexpr real_type cOne(1); @@ -280,10 +282,10 @@ inline void BsplineFunctor::evaluateVGL( ASSUME_ALIGNED(distArrayCompressed); int iCount = 0; int iLimit = iEnd - iStart; - const real_type *distArray = _distArray + iStart; - real_type *valArray = _valArray + iStart; - real_type *gradArray = _gradArray + iStart; - real_type *laplArray = _laplArray + iStart; + const real_type* distArray = _distArray + iStart; + real_type* valArray = _valArray + iStart; + real_type* gradArray = _gradArray + iStart; + real_type* laplArray = _laplArray + iStart; #pragma vector always for (int jat = 0; jat < iLimit; jat++) @@ -300,7 +302,6 @@ inline void BsplineFunctor::evaluateVGL( #pragma omp simd for (int j = 0; j < iCount; j++) { - real_type r = distArrayCompressed[j]; int iScatter = distIndices[j]; real_type rinv = cOne / r; diff --git a/src/QMCWaveFunctions/Jastrow/OneBodyJastrow.h b/src/QMCWaveFunctions/Jastrow/OneBodyJastrow.h index a617acdaf..30b8144b4 100644 --- a/src/QMCWaveFunctions/Jastrow/OneBodyJastrow.h +++ b/src/QMCWaveFunctions/Jastrow/OneBodyJastrow.h @@ -23,11 +23,11 @@ namespace qmcplusplus { - /** @ingroup WaveFunctionComponent * @brief Specialization for one-body Jastrow function using multiple functors */ -template struct OneBodyJastrow : public WaveFunctionComponent +template +struct OneBodyJastrow : public WaveFunctionComponent { /// alias FuncType using FuncType = FT; @@ -46,7 +46,7 @@ template struct OneBodyJastrow : public WaveFunctionComponent /// number of groups int NumGroups; /// reference to the sources (ions) - const ParticleSet &Ions; + const ParticleSet& Ions; valT curAt; valT curLap; @@ -60,25 +60,26 @@ template struct OneBodyJastrow : public WaveFunctionComponent Vector Grad; Vector Lap; /// Container for \f$F[ig*NumGroups+jg]\f$ - std::vector F; + std::vector F; - OneBodyJastrow(const ParticleSet &ions, ParticleSet &els) : Ions(ions) + OneBodyJastrow(const ParticleSet& ions, ParticleSet& els) : Ions(ions) { initalize(els); myTableID = els.addTable(ions, DT_SOA); WaveFunctionComponentName = "OneBodyJastrow"; } - OneBodyJastrow(const OneBodyJastrow &rhs) = delete; + OneBodyJastrow(const OneBodyJastrow& rhs) = delete; ~OneBodyJastrow() { for (int i = 0; i < F.size(); ++i) - if (F[i] != nullptr) delete F[i]; + if (F[i] != nullptr) + delete F[i]; } /* initialize storage */ - void initalize(ParticleSet &els) + void initalize(ParticleSet& els) { Nions = Ions.getTotalNum(); NumGroups = Ions.getSpeciesSet().getTotalNum(); @@ -99,39 +100,40 @@ template struct OneBodyJastrow : public WaveFunctionComponent DistIndice.resize(Nions); } - void addFunc(int source_type, FT *afunc, int target_type = -1) + void addFunc(int source_type, FT* afunc, int target_type = -1) { - if (F[source_type] != nullptr) delete F[source_type]; + if (F[source_type] != nullptr) + delete F[source_type]; F[source_type] = afunc; } - void recompute(ParticleSet &P) + void recompute(ParticleSet& P) { - const DistanceTableData &d_ie(*(P.DistTables[myTableID])); + const DistanceTableData& d_ie(*(P.DistTables[myTableID])); for (int iat = 0; iat < Nelec; ++iat) { computeU3(P, iat, d_ie.Distances[iat]); Vat[iat] = simd::accumulate_n(U.data(), Nions, valT()); - Lap[iat] = accumulateGL(dU.data(), d2U.data(), d_ie.Displacements[iat], - Grad[iat]); + Lap[iat] = accumulateGL(dU.data(), d2U.data(), d_ie.Displacements[iat], Grad[iat]); } } - RealType evaluateLog(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L) + RealType evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L) { evaluateGL(P, G, L, true); return LogValue; } - ValueType ratio(ParticleSet &P, int iat) + ValueType ratio(ParticleSet& P, int iat) { UpdateMode = ORB_PBYP_RATIO; curAt = computeU(P.DistTables[myTableID]->Temp_r.data()); return std::exp(Vat[iat] - curAt); } - inline valT computeU(const valT *dist) + inline valT computeU(const valT* dist) { valT curVat(0); if (NumGroups > 0) @@ -139,8 +141,7 @@ template struct OneBodyJastrow : public WaveFunctionComponent for (int jg = 0; jg < NumGroups; ++jg) { if (F[jg] != nullptr) - curVat += F[jg]->evaluateV(-1, Ions.first(jg), Ions.last(jg), dist, - DistCompressed.data()); + curVat += F[jg]->evaluateV(-1, Ions.first(jg), Ions.last(jg), dist, DistCompressed.data()); } } else @@ -148,17 +149,20 @@ template struct OneBodyJastrow : public WaveFunctionComponent for (int c = 0; c < Nions; ++c) { int gid = Ions.GroupID[c]; - if (F[gid] != nullptr) curVat += F[gid]->evaluate(dist[c]); + if (F[gid] != nullptr) + curVat += F[gid]->evaluate(dist[c]); } } return curVat; } - inline void evaluateGL(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, + inline void evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, bool fromscratch = false) { - if (fromscratch) recompute(P); + if (fromscratch) + recompute(P); for (size_t iat = 0; iat < Nelec; ++iat) G[iat] += Grad[iat]; @@ -170,8 +174,10 @@ template struct OneBodyJastrow : public WaveFunctionComponent /** compute gradient and lap * @return lap */ - inline valT accumulateGL(const valT *restrict du, const valT *restrict d2u, - const RowContainer &displ, posT &grad) const + inline valT accumulateGL(const valT* restrict du, + const valT* restrict d2u, + const RowContainer& displ, + posT& grad) const { valT lap(0); constexpr valT lapfac = OHMMS_DIM - RealType(1); @@ -179,7 +185,7 @@ template struct OneBodyJastrow : public WaveFunctionComponent lap += d2u[jat] + lapfac * du[jat]; for (int idim = 0; idim < OHMMS_DIM; ++idim) { - const valT *restrict dX = displ.data(idim); + const valT* restrict dX = displ.data(idim); valT s = valT(); for (int jat = 0; jat < Nions; ++jat) s += du[jat] * dX[jat]; @@ -194,7 +200,7 @@ template struct OneBodyJastrow : public WaveFunctionComponent * @param dist starting address of the distances of the ions wrt the iat-th * particle */ - inline void computeU3(ParticleSet &P, int iat, const valT *dist) + inline void computeU3(ParticleSet& P, int iat, const valT* dist) { if (NumGroups > 0) { // ions are grouped @@ -205,9 +211,16 @@ template struct OneBodyJastrow : public WaveFunctionComponent for (int jg = 0; jg < NumGroups; ++jg) { - if (F[jg] == nullptr) continue; - F[jg]->evaluateVGL(-1, Ions.first(jg), Ions.last(jg), dist, U.data(), - dU.data(), d2U.data(), DistCompressed.data(), + if (F[jg] == nullptr) + continue; + F[jg]->evaluateVGL(-1, + Ions.first(jg), + Ions.last(jg), + dist, + U.data(), + dU.data(), + d2U.data(), + DistCompressed.data(), DistIndice.data()); } } @@ -229,7 +242,7 @@ template struct OneBodyJastrow : public WaveFunctionComponent * @param P quantum particleset * @param iat particle index */ - GradType evalGrad(ParticleSet &P, int iat) { return GradType(Grad[iat]); } + GradType evalGrad(ParticleSet& P, int iat) { return GradType(Grad[iat]); } /** compute the gradient during particle-by-particle update * @param P quantum particleset @@ -237,27 +250,24 @@ template struct OneBodyJastrow : public WaveFunctionComponent * * Using Temp_r. curAt, curGrad and curLap are computed. */ - ValueType ratioGrad(ParticleSet &P, int iat, GradType &grad_iat) + ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat) { UpdateMode = ORB_PBYP_PARTIAL; computeU3(P, iat, P.DistTables[myTableID]->Temp_r.data()); - curLap = accumulateGL(dU.data(), d2U.data(), - P.DistTables[myTableID]->Temp_dr, curGrad); + curLap = accumulateGL(dU.data(), d2U.data(), P.DistTables[myTableID]->Temp_dr, curGrad); curAt = simd::accumulate_n(U.data(), Nions, valT()); grad_iat += curGrad; return std::exp(Vat[iat] - curAt); } /** Accpted move. Update Vat[iat],Grad[iat] and Lap[iat] */ - void acceptMove(ParticleSet &P, int iat) + void acceptMove(ParticleSet& P, int iat) { - if (UpdateMode == ORB_PBYP_RATIO) { computeU3(P, iat, P.DistTables[myTableID]->Temp_r.data()); - curLap = accumulateGL(dU.data(), d2U.data(), - P.DistTables[myTableID]->Temp_dr, curGrad); + curLap = accumulateGL(dU.data(), d2U.data(), P.DistTables[myTableID]->Temp_dr, curGrad); } LogValue += Vat[iat] - curAt; diff --git a/src/QMCWaveFunctions/Jastrow/OneBodyJastrowRef.h b/src/QMCWaveFunctions/Jastrow/OneBodyJastrowRef.h index 364f502ef..6922ad9a9 100644 --- a/src/QMCWaveFunctions/Jastrow/OneBodyJastrowRef.h +++ b/src/QMCWaveFunctions/Jastrow/OneBodyJastrowRef.h @@ -21,13 +21,13 @@ namespace miniqmcreference { - using namespace qmcplusplus; /** @ingroup WaveFunctionComponent * @brief Specialization for one-body Jastrow function using multiple functors */ -template struct OneBodyJastrowRef : public WaveFunctionComponent +template +struct OneBodyJastrowRef : public WaveFunctionComponent { /// alias FuncType using FuncType = FT; @@ -46,7 +46,7 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent /// number of groups int NumGroups; /// reference to the sources (ions) - const ParticleSet &Ions; + const ParticleSet& Ions; valT curAt; valT curLap; @@ -60,25 +60,26 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent Vector Grad; Vector Lap; /// Container for \f$F[ig*NumGroups+jg]\f$ - std::vector F; + std::vector F; - OneBodyJastrowRef(const ParticleSet &ions, ParticleSet &els) : Ions(ions) + OneBodyJastrowRef(const ParticleSet& ions, ParticleSet& els) : Ions(ions) { initalize(els); myTableID = els.addTable(ions, DT_SOA); WaveFunctionComponentName = "OneBodyJastrowRef"; } - OneBodyJastrowRef(const OneBodyJastrowRef &rhs) = delete; + OneBodyJastrowRef(const OneBodyJastrowRef& rhs) = delete; ~OneBodyJastrowRef() { for (int i = 0; i < F.size(); ++i) - if (F[i] != nullptr) delete F[i]; + if (F[i] != nullptr) + delete F[i]; } /* initialize storage */ - void initalize(ParticleSet &els) + void initalize(ParticleSet& els) { Nions = Ions.getTotalNum(); NumGroups = Ions.getSpeciesSet().getTotalNum(); @@ -99,39 +100,40 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent DistIndice.resize(Nions); } - void addFunc(int source_type, FT *afunc, int target_type = -1) + void addFunc(int source_type, FT* afunc, int target_type = -1) { - if (F[source_type] != nullptr) delete F[source_type]; + if (F[source_type] != nullptr) + delete F[source_type]; F[source_type] = afunc; } - void recompute(ParticleSet &P) + void recompute(ParticleSet& P) { - const DistanceTableData &d_ie(*(P.DistTables[myTableID])); + const DistanceTableData& d_ie(*(P.DistTables[myTableID])); for (int iat = 0; iat < Nelec; ++iat) { computeU3(P, iat, d_ie.Distances[iat]); Vat[iat] = std::accumulate(U.begin(), U.begin() + Nions, valT()); - Lap[iat] = accumulateGL(dU.data(), d2U.data(), d_ie.Displacements[iat], - Grad[iat]); + Lap[iat] = accumulateGL(dU.data(), d2U.data(), d_ie.Displacements[iat], Grad[iat]); } } - RealType evaluateLog(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L) + RealType evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L) { evaluateGL(P, G, L, true); return LogValue; } - ValueType ratio(ParticleSet &P, int iat) + ValueType ratio(ParticleSet& P, int iat) { UpdateMode = ORB_PBYP_RATIO; curAt = computeU(P.DistTables[myTableID]->Temp_r.data()); return std::exp(Vat[iat] - curAt); } - inline valT computeU(const valT *dist) + inline valT computeU(const valT* dist) { valT curVat(0); if (NumGroups > 0) @@ -139,8 +141,7 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent for (int jg = 0; jg < NumGroups; ++jg) { if (F[jg] != nullptr) - curVat += F[jg]->evaluateV(-1, Ions.first(jg), Ions.last(jg), dist, - DistCompressed.data()); + curVat += F[jg]->evaluateV(-1, Ions.first(jg), Ions.last(jg), dist, DistCompressed.data()); } } else @@ -148,17 +149,20 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent for (int c = 0; c < Nions; ++c) { int gid = Ions.GroupID[c]; - if (F[gid] != nullptr) curVat += F[gid]->evaluate(dist[c]); + if (F[gid] != nullptr) + curVat += F[gid]->evaluate(dist[c]); } } return curVat; } - inline void evaluateGL(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, + inline void evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, bool fromscratch = false) { - if (fromscratch) recompute(P); + if (fromscratch) + recompute(P); for (size_t iat = 0; iat < Nelec; ++iat) G[iat] += Grad[iat]; @@ -170,8 +174,10 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent /** compute gradient and lap * @return lap */ - inline valT accumulateGL(const valT *restrict du, const valT *restrict d2u, - const RowContainer &displ, posT &grad) const + inline valT accumulateGL(const valT* restrict du, + const valT* restrict d2u, + const RowContainer& displ, + posT& grad) const { valT lap(0); constexpr valT lapfac = OHMMS_DIM - RealType(1); @@ -179,7 +185,7 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent lap += d2u[jat] + lapfac * du[jat]; for (int idim = 0; idim < OHMMS_DIM; ++idim) { - const valT *restrict dX = displ.data(idim); + const valT* restrict dX = displ.data(idim); valT s = valT(); for (int jat = 0; jat < Nions; ++jat) s += du[jat] * dX[jat]; @@ -194,7 +200,7 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent * @param dist starting address of the distances of the ions wrt the iat-th * particle */ - inline void computeU3(ParticleSet &P, int iat, const valT *dist) + inline void computeU3(ParticleSet& P, int iat, const valT* dist) { if (NumGroups > 0) { // ions are grouped @@ -205,9 +211,16 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent for (int jg = 0; jg < NumGroups; ++jg) { - if (F[jg] == nullptr) continue; - F[jg]->evaluateVGL(-1, Ions.first(jg), Ions.last(jg), dist, U.data(), - dU.data(), d2U.data(), DistCompressed.data(), + if (F[jg] == nullptr) + continue; + F[jg]->evaluateVGL(-1, + Ions.first(jg), + Ions.last(jg), + dist, + U.data(), + dU.data(), + d2U.data(), + DistCompressed.data(), DistIndice.data()); } } @@ -229,7 +242,7 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent * @param P quantum particleset * @param iat particle index */ - GradType evalGrad(ParticleSet &P, int iat) { return GradType(Grad[iat]); } + GradType evalGrad(ParticleSet& P, int iat) { return GradType(Grad[iat]); } /** compute the gradient during particle-by-particle update * @param P quantum particleset @@ -237,27 +250,24 @@ template struct OneBodyJastrowRef : public WaveFunctionComponent * * Using Temp_r. curAt, curGrad and curLap are computed. */ - ValueType ratioGrad(ParticleSet &P, int iat, GradType &grad_iat) + ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat) { UpdateMode = ORB_PBYP_PARTIAL; computeU3(P, iat, P.DistTables[myTableID]->Temp_r.data()); - curLap = accumulateGL(dU.data(), d2U.data(), - P.DistTables[myTableID]->Temp_dr, curGrad); + curLap = accumulateGL(dU.data(), d2U.data(), P.DistTables[myTableID]->Temp_dr, curGrad); curAt = std::accumulate(U.begin(), U.begin() + Nions, valT()); grad_iat += curGrad; return std::exp(Vat[iat] - curAt); } /** Accpted move. Update Vat[iat],Grad[iat] and Lap[iat] */ - void acceptMove(ParticleSet &P, int iat) + void acceptMove(ParticleSet& P, int iat) { - if (UpdateMode == ORB_PBYP_RATIO) { computeU3(P, iat, P.DistTables[myTableID]->Temp_r.data()); - curLap = accumulateGL(dU.data(), d2U.data(), - P.DistTables[myTableID]->Temp_dr, curGrad); + curLap = accumulateGL(dU.data(), d2U.data(), P.DistTables[myTableID]->Temp_dr, curGrad); } LogValue += Vat[iat] - curAt; diff --git a/src/QMCWaveFunctions/Jastrow/PolynomialFunctor3D.h b/src/QMCWaveFunctions/Jastrow/PolynomialFunctor3D.h index 17a3455d4..27e30a8ea 100644 --- a/src/QMCWaveFunctions/Jastrow/PolynomialFunctor3D.h +++ b/src/QMCWaveFunctions/Jastrow/PolynomialFunctor3D.h @@ -31,7 +31,6 @@ namespace qmcplusplus { - struct PolynomialFunctor3D : public OptimizableFunctorBase { typedef real_type value_type; @@ -166,7 +165,8 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase max_abs = abs_val; } } - if (max_abs < 1.0e-6) IndepVar[col] = true; + if (max_abs < 1.0e-6) + IndepVar[col] = true; } while (max_abs < 1.0e-6); #if ((__INTEL_COMPILER == 1700) && (__cplusplus < 201103L)) // the swap_rows is sick with Intel compiler 17 update 1, c++11 off @@ -211,7 +211,8 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase // First, set all independent variables int var = 0; for (int i = 0; i < NumGamma; i++) - if (IndepVar[i]) GammaVec[i] = scale * Parameters[var++]; + if (IndepVar[i]) + GammaVec[i] = scale * Parameters[var++]; assert(var == Parameters.size()); // Now, set dependent variables var = 0; @@ -220,7 +221,8 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase { assert(std::abs(ConstraintMatrix(var, i) - 1.0) < 1.0e-6); for (int j = 0; j < NumGamma; j++) - if (i != j) GammaVec[i] -= ConstraintMatrix(var, j) * GammaVec[j]; + if (i != j) + GammaVec[i] -= ConstraintMatrix(var, j) * GammaVec[j]; var++; } int num = 0; @@ -262,9 +264,8 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase } if (std::abs(sum) > 1.0e-6) { - app_error() - << "e-e constraint not satisfied in PolynomialFunctor3D: k=" << k - << " sum=" << sum << std::endl; + app_error() << "e-e constraint not satisfied in PolynomialFunctor3D: k=" << k + << " sum=" << sum << std::endl; abort(); } } @@ -282,23 +283,22 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase } if (std::abs(sum) > 1.0e-6) { - app_error() - << "e-I constraint not satisfied in PolynomialFunctor3D: k=" << k - << " sum=" << sum << std::endl; + app_error() << "e-I constraint not satisfied in PolynomialFunctor3D: k=" << k + << " sum=" << sum << std::endl; abort(); } } } - inline real_type evaluate(real_type r_12, real_type r_1I, - real_type r_2I) const + inline real_type evaluate(real_type r_12, real_type r_1I, real_type r_2I) const { constexpr real_type czero(0); constexpr real_type cone(1); constexpr real_type chalf(0.5); const real_type L = chalf * cutoff_radius; - if (r_1I >= L || r_2I >= L) return czero; + if (r_1I >= L || r_2I >= L) + return czero; real_type val = czero; real_type r2l(cone); for (int l = 0; l <= N_eI; l++) @@ -322,9 +322,10 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase } // assume r_1I < L && r_2I < L, compression and screening is handled outside - inline real_type evaluateV(int Nptcl, const real_type *restrict r_12_array, - const real_type *restrict r_1I_array, - const real_type *restrict r_2I_array) const + inline real_type evaluateV(int Nptcl, + const real_type* restrict r_12_array, + const real_type* restrict r_1I_array, + const real_type* restrict r_2I_array) const { constexpr real_type czero(0); constexpr real_type cone(1); @@ -333,7 +334,7 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase const real_type L = chalf * cutoff_radius; real_type val_tot = czero; -#pragma omp simd aligned(r_12_array,r_1I_array,r_2I_array) reduction(+:val_tot) +#pragma omp simd aligned(r_12_array, r_1I_array, r_2I_array) reduction(+ : val_tot) for (int ptcl = 0; ptcl < Nptcl; ptcl++) { const real_type r_12 = r_12_array[ptcl]; @@ -365,9 +366,11 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase return val_tot; } - inline real_type evaluate(real_type r_12, real_type r_1I, real_type r_2I, - TinyVector &grad, - Tensor &hess) const + inline real_type evaluate(real_type r_12, + real_type r_1I, + real_type r_2I, + TinyVector& grad, + Tensor& hess) const { constexpr real_type czero(0); constexpr real_type cone(1); @@ -430,13 +433,11 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase const real_type both_minus_L = r_2I_minus_L * r_1I_minus_L; for (int i = 0; i < C; i++) { - hess(0, 0) = both_minus_L * hess(0, 0); hess(0, 1) = both_minus_L * hess(0, 1) + r_2I_minus_L * grad[0]; hess(0, 2) = both_minus_L * hess(0, 2) + r_1I_minus_L * grad[0]; hess(1, 1) = both_minus_L * hess(1, 1) + ctwo * r_2I_minus_L * grad[1]; - hess(1, 2) = both_minus_L * hess(1, 2) + r_1I_minus_L * grad[1] + - r_2I_minus_L * grad[2] + val; + hess(1, 2) = both_minus_L * hess(1, 2) + r_1I_minus_L * grad[1] + r_2I_minus_L * grad[2] + val; hess(2, 2) = both_minus_L * hess(2, 2) + ctwo * r_1I_minus_L * grad[2]; grad[0] = both_minus_L * grad[0]; grad[1] = both_minus_L * grad[1] + r_2I_minus_L * val; @@ -450,14 +451,19 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase } // assume r_1I < L && r_2I < L, compression and screening is handled outside - inline void evaluateVGL( - int Nptcl, const real_type *restrict r_12_array, - const real_type *restrict r_1I_array, - const real_type *restrict r_2I_array, real_type *restrict val_array, - real_type *restrict grad0_array, real_type *restrict grad1_array, - real_type *restrict grad2_array, real_type *restrict hess00_array, - real_type *restrict hess11_array, real_type *restrict hess22_array, - real_type *restrict hess01_array, real_type *restrict hess02_array) const + inline void evaluateVGL(int Nptcl, + const real_type* restrict r_12_array, + const real_type* restrict r_1I_array, + const real_type* restrict r_2I_array, + real_type* restrict val_array, + real_type* restrict grad0_array, + real_type* restrict grad1_array, + real_type* restrict grad2_array, + real_type* restrict hess00_array, + real_type* restrict hess11_array, + real_type* restrict hess22_array, + real_type* restrict hess01_array, + real_type* restrict hess02_array) const { constexpr real_type czero(0); constexpr real_type cone(1); @@ -465,9 +471,17 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase constexpr real_type ctwo(2); const real_type L = chalf * cutoff_radius; -#pragma omp simd aligned(r_12_array, r_1I_array, r_2I_array, val_array, \ - grad0_array, grad1_array, grad2_array, hess00_array, \ - hess11_array, hess22_array, hess01_array, \ +#pragma omp simd aligned(r_12_array, \ + r_1I_array, \ + r_2I_array, \ + val_array, \ + grad0_array, \ + grad1_array, \ + grad2_array, \ + hess00_array, \ + hess11_array, \ + hess22_array, \ + hess01_array, \ hess02_array) for (int ptcl = 0; ptcl < Nptcl; ptcl++) { diff --git a/src/QMCWaveFunctions/Jastrow/ThreeBodyJastrow.h b/src/QMCWaveFunctions/Jastrow/ThreeBodyJastrow.h index 2935cd1dc..81b2a8c1b 100644 --- a/src/QMCWaveFunctions/Jastrow/ThreeBodyJastrow.h +++ b/src/QMCWaveFunctions/Jastrow/ThreeBodyJastrow.h @@ -19,7 +19,6 @@ namespace qmcplusplus { - /** @ingroup WaveFunctionComponent * @brief Specialization for three-body Jastrow function using multiple *functors @@ -28,7 +27,8 @@ namespace qmcplusplus *For electrons, distinct pair correlation functions are used *for spins up-up/down-down and up-down/down-up. */ -template class ThreeBodyJastrow : public WaveFunctionComponent +template +class ThreeBodyJastrow : public WaveFunctionComponent { /// type of each component U, dU, d2U; using valT = typename FT::real_type; @@ -45,7 +45,7 @@ template class ThreeBodyJastrow : public WaveFunctionComponent // number of groups of the target particleset int eGroups, iGroups; /// reference to the sources (ions) - const ParticleSet &Ions; + const ParticleSet& Ions; /// diff value RealType DiffVal; @@ -60,7 +60,7 @@ template class ThreeBodyJastrow : public WaveFunctionComponent valT cur_Uat, cur_d2Uat; posT cur_dUat, dUat_temp; /// container for the Jastrow functions - Array F; + Array F; /// the cutoff for e-I pairs std::vector Ion_cutoff; @@ -85,19 +85,17 @@ template class ThreeBodyJastrow : public WaveFunctionComponent /// alias FuncType using FuncType = FT; - ThreeBodyJastrow(const ParticleSet &ions, ParticleSet &elecs, - bool is_master = false) - : Ions(ions) + ThreeBodyJastrow(const ParticleSet& ions, ParticleSet& elecs, bool is_master = false) : Ions(ions) { - WaveFunctionComponentName = "ThreeBodyJastrow"; - myTableID = elecs.addTable(Ions, DT_SOA); + WaveFunctionComponentName = "ThreeBodyJastrow"; + myTableID = elecs.addTable(Ions, DT_SOA); elecs.DistTables[myTableID]->Need_full_table_loadWalker = true; init(elecs); } ~ThreeBodyJastrow() {} - void init(ParticleSet &p) + void init(ParticleSet& p) { Nelec = p.getTotalNum(); Nelec_padded = getAlignedSize(Nelec); @@ -136,7 +134,7 @@ template class ThreeBodyJastrow : public WaveFunctionComponent DistIndice_k.resize(Nbuffer); } - void addFunc(int iSpecies, int eSpecies1, int eSpecies2, FT *j) + void addFunc(int iSpecies, int eSpecies1, int eSpecies2, FT* j) { if (eSpecies1 == eSpecies2) { @@ -145,7 +143,8 @@ template class ThreeBodyJastrow : public WaveFunctionComponent for (int eG1 = 0; eG1 < eGroups; eG1++) for (int eG2 = 0; eG2 < eGroups; eG2++) { - if (F(iSpecies, eG1, eG2) == 0) F(iSpecies, eG1, eG2) = j; + if (F(iSpecies, eG1, eG2) == 0) + F(iSpecies, eG1, eG2) = j; } } else @@ -157,7 +156,8 @@ template class ThreeBodyJastrow : public WaveFunctionComponent { RealType rcut = 0.5 * j->cutoff_radius; for (int i = 0; i < Nion; i++) - if (Ions.GroupID[i] == iSpecies) Ion_cutoff[i] = rcut; + if (Ions.GroupID[i] == iSpecies) + Ion_cutoff[i] = rcut; } else { @@ -177,7 +177,8 @@ template class ThreeBodyJastrow : public WaveFunctionComponent bool partial; for (int e1 = 0; e1 < eGroups; ++e1) for (int e2 = 0; e2 < eGroups; ++e2) - if (F(i, e1, e2) != 0) nfilled++; + if (F(i, e1, e2) != 0) + nfilled++; partial = nfilled > 0 && nfilled < eGroups * eGroups; if (partial) app_log() << "J3 eeI is missing correlation for ion " << i << std::endl; @@ -191,8 +192,9 @@ template class ThreeBodyJastrow : public WaveFunctionComponent // first set radii for (int i = 0; i < Nion; ++i) { - FT *f = F(Ions.GroupID[i], 0, 0); - if (f != 0) Ion_cutoff[i] = .5 * f->cutoff_radius; + FT* f = F(Ions.GroupID[i], 0, 0); + if (f != 0) + Ion_cutoff[i] = .5 * f->cutoff_radius; } // then check radii bool all_radii_match = true; @@ -206,8 +208,7 @@ template class ThreeBodyJastrow : public WaveFunctionComponent for (int e2 = 0; e2 < eGroups; ++e2) radii_match = radii_match && F(i, e1, e2)->cutoff_radius == rcut; if (!radii_match) - app_log() << "eeI functors for ion species " << i - << " have different radii" << std::endl; + app_log() << "eeI functors for ion species " << i << " have different radii" << std::endl; all_radii_match = all_radii_match && radii_match; } } @@ -218,9 +219,9 @@ template class ThreeBodyJastrow : public WaveFunctionComponent } } - void build_compact_list(ParticleSet &P) + void build_compact_list(ParticleSet& P) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); for (int iat = 0; iat < Nion; ++iat) for (int jg = 0; jg < eGroups; ++jg) @@ -237,59 +238,85 @@ template class ThreeBodyJastrow : public WaveFunctionComponent { elecs_inside(jg, iat).push_back(jel); elecs_inside_dist(jg, iat).push_back(eI_table.Distances[jel][iat]); - elecs_inside_displ(jg, iat).push_back( - eI_table.Displacements[jel][iat]); + elecs_inside_displ(jg, iat).push_back(eI_table.Displacements[jel][iat]); } } - RealType evaluateLog(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L) + RealType evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L) { evaluateGL(P, G, L, true); return LogValue; } - ValueType ratio(ParticleSet &P, int iat) + ValueType ratio(ParticleSet& P, int iat) { UpdateMode = ORB_PBYP_RATIO; - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); - const DistanceTableData &ee_table = (*P.DistTables[0]); - cur_Uat = computeU(P, iat, P.GroupID[iat], eI_table.Temp_r.data(), - ee_table.Temp_r.data()); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& ee_table = (*P.DistTables[0]); + cur_Uat = computeU(P, iat, P.GroupID[iat], eI_table.Temp_r.data(), ee_table.Temp_r.data()); DiffVal = Uat[iat] - cur_Uat; return std::exp(DiffVal); } - GradType evalGrad(ParticleSet &P, int iat) { return GradType(dUat[iat]); } + GradType evalGrad(ParticleSet& P, int iat) { return GradType(dUat[iat]); } - ValueType ratioGrad(ParticleSet &P, int iat, GradType &grad_iat) + ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat) { UpdateMode = ORB_PBYP_PARTIAL; - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); - const DistanceTableData &ee_table = (*P.DistTables[0]); - computeU3(P, iat, eI_table.Temp_r.data(), eI_table.Temp_dr, - ee_table.Temp_r.data(), ee_table.Temp_dr, cur_Uat, cur_dUat, - cur_d2Uat, newUk, newdUk, newd2Uk); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& ee_table = (*P.DistTables[0]); + computeU3(P, + iat, + eI_table.Temp_r.data(), + eI_table.Temp_dr, + ee_table.Temp_r.data(), + ee_table.Temp_dr, + cur_Uat, + cur_dUat, + cur_d2Uat, + newUk, + newdUk, + newd2Uk); DiffVal = Uat[iat] - cur_Uat; grad_iat += cur_dUat; return std::exp(DiffVal); } - void acceptMove(ParticleSet &P, int iat) + void acceptMove(ParticleSet& P, int iat) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); - const DistanceTableData &ee_table = (*P.DistTables[0]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& ee_table = (*P.DistTables[0]); // get the old value, grad, lapl - computeU3(P, iat, eI_table.Distances[iat], eI_table.Displacements[iat], - ee_table.Distances[iat], ee_table.Displacements[iat], Uat[iat], - dUat_temp, d2Uat[iat], oldUk, olddUk, oldd2Uk); + computeU3(P, + iat, + eI_table.Distances[iat], + eI_table.Displacements[iat], + ee_table.Distances[iat], + ee_table.Displacements[iat], + Uat[iat], + dUat_temp, + d2Uat[iat], + oldUk, + olddUk, + oldd2Uk); if (UpdateMode == ORB_PBYP_RATIO) { // ratio-only during the move; need to compute derivatives - computeU3(P, iat, eI_table.Temp_r.data(), eI_table.Temp_dr, - ee_table.Temp_r.data(), ee_table.Temp_dr, cur_Uat, cur_dUat, - cur_d2Uat, newUk, newdUk, newd2Uk); + computeU3(P, + iat, + eI_table.Temp_r.data(), + eI_table.Temp_dr, + ee_table.Temp_r.data(), + ee_table.Temp_dr, + cur_Uat, + cur_dUat, + cur_d2Uat, + newUk, + newdUk, + newd2Uk); } for (int jel = 0; jel < Nelec; jel++) @@ -299,9 +326,9 @@ template class ThreeBodyJastrow : public WaveFunctionComponent } for (int idim = 0; idim < OHMMS_DIM; ++idim) { - valT *restrict save_g = dUat.data(idim); - const valT *restrict new_g = newdUk.data(idim); - const valT *restrict old_g = olddUk.data(idim); + valT* restrict save_g = dUat.data(idim); + const valT* restrict new_g = newdUk.data(idim); + const valT* restrict old_g = olddUk.data(idim); for (int jel = 0; jel < Nelec; jel++) save_g[jel] += new_g[jel] - old_g[jel]; } @@ -316,12 +343,11 @@ template class ThreeBodyJastrow : public WaveFunctionComponent for (int jat = 0; jat < Nion; jat++) { bool inside = eI_table.Temp_r[jat] < Ion_cutoff[jat]; - auto iter = - find(elecs_inside(ig, jat).begin(), elecs_inside(ig, jat).end(), iat); - auto iter_dist = elecs_inside_dist(ig, jat).begin() + - std::distance(elecs_inside(ig, jat).begin(), iter); - auto iter_displ = elecs_inside_displ(ig, jat).begin() + - std::distance(elecs_inside(ig, jat).begin(), iter); + auto iter = find(elecs_inside(ig, jat).begin(), elecs_inside(ig, jat).end(), iat); + auto iter_dist = + elecs_inside_dist(ig, jat).begin() + std::distance(elecs_inside(ig, jat).begin(), iter); + auto iter_displ = + elecs_inside_displ(ig, jat).begin() + std::distance(elecs_inside(ig, jat).begin(), iter); if (inside) { if (iter == elecs_inside(ig, jat).end()) @@ -351,18 +377,28 @@ template class ThreeBodyJastrow : public WaveFunctionComponent } } - inline void recompute(ParticleSet &P) + inline void recompute(ParticleSet& P) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); - const DistanceTableData &ee_table = (*P.DistTables[0]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& ee_table = (*P.DistTables[0]); build_compact_list(P); for (int jel = 0; jel < Nelec; ++jel) { - computeU3(P, jel, eI_table.Distances[jel], eI_table.Displacements[jel], - ee_table.Distances[jel], ee_table.Displacements[jel], Uat[jel], - dUat_temp, d2Uat[jel], newUk, newdUk, newd2Uk, true); + computeU3(P, + jel, + eI_table.Distances[jel], + eI_table.Displacements[jel], + ee_table.Distances[jel], + ee_table.Displacements[jel], + Uat[jel], + dUat_temp, + d2Uat[jel], + newUk, + newdUk, + newd2Uk, + true); dUat(jel) = dUat_temp; // add the contribution from the upper triangle for (int kel = 0; kel < jel; kel++) @@ -372,22 +408,23 @@ template class ThreeBodyJastrow : public WaveFunctionComponent } for (int idim = 0; idim < OHMMS_DIM; ++idim) { - valT *restrict save_g = dUat.data(idim); - const valT *restrict new_g = newdUk.data(idim); + valT* restrict save_g = dUat.data(idim); + const valT* restrict new_g = newdUk.data(idim); for (int kel = 0; kel < jel; kel++) save_g[kel] += new_g[kel]; } } } - inline valT computeU(const ParticleSet &P, int jel, int jg, - const RealType *distjI, const RealType *distjk) + inline valT + computeU(const ParticleSet& P, int jel, int jg, const RealType* distjI, const RealType* distjk) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); ions_nearby.clear(); for (int iat = 0; iat < Nion; ++iat) - if (distjI[iat] < Ion_cutoff[iat]) ions_nearby.push_back(iat); + if (distjI[iat] < Ion_cutoff[iat]) + ions_nearby.push_back(iat); valT Uj = valT(0); for (int kg = 0; kg < eGroups; ++kg) @@ -409,20 +446,21 @@ template class ThreeBodyJastrow : public WaveFunctionComponent kel_counter++; if (kel_counter == Nbuffer) { - const FT &feeI(*F(ig, jg, kg)); - Uj += feeI.evaluateV(kel_counter, Distjk_Compressed.data(), + const FT& feeI(*F(ig, jg, kg)); + Uj += feeI.evaluateV(kel_counter, + Distjk_Compressed.data(), DistjI_Compressed.data(), DistkI_Compressed.data()); kel_counter = 0; } } } - if ((iind + 1 == ions_nearby.size() || - ig != Ions.GroupID[ions_nearby[iind + 1]]) && + if ((iind + 1 == ions_nearby.size() || ig != Ions.GroupID[ions_nearby[iind + 1]]) && kel_counter > 0) { - const FT &feeI(*F(ig, jg, kg)); - Uj += feeI.evaluateV(kel_counter, Distjk_Compressed.data(), + const FT& feeI(*F(ig, jg, kg)); + Uj += feeI.evaluateV(kel_counter, + Distjk_Compressed.data(), DistjI_Compressed.data(), DistkI_Compressed.data()); kel_counter = 0; @@ -432,31 +470,45 @@ template class ThreeBodyJastrow : public WaveFunctionComponent return Uj; } - inline void computeU3_engine(const ParticleSet &P, const FT &feeI, - int kel_counter, valT &Uj, posT &dUj, valT &d2Uj, - Vector &Uk, gContainer_type &dUk, - Vector &d2Uk) + inline void computeU3_engine(const ParticleSet& P, + const FT& feeI, + int kel_counter, + valT& Uj, + posT& dUj, + valT& d2Uj, + Vector& Uk, + gContainer_type& dUk, + Vector& d2Uk) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); constexpr valT czero(0); constexpr valT cone(1); constexpr valT ctwo(2); constexpr valT lapfac = OHMMS_DIM - cone; - valT *restrict val = mVGL.data(0); - valT *restrict gradF0 = mVGL.data(1); - valT *restrict gradF1 = mVGL.data(2); - valT *restrict gradF2 = mVGL.data(3); - valT *restrict hessF00 = mVGL.data(4); - valT *restrict hessF11 = mVGL.data(5); - valT *restrict hessF22 = mVGL.data(6); - valT *restrict hessF01 = mVGL.data(7); - valT *restrict hessF02 = mVGL.data(8); - - feeI.evaluateVGL(kel_counter, Distjk_Compressed.data(), - DistjI_Compressed.data(), DistkI_Compressed.data(), val, - gradF0, gradF1, gradF2, hessF00, hessF11, hessF22, hessF01, + valT* restrict val = mVGL.data(0); + valT* restrict gradF0 = mVGL.data(1); + valT* restrict gradF1 = mVGL.data(2); + valT* restrict gradF2 = mVGL.data(3); + valT* restrict hessF00 = mVGL.data(4); + valT* restrict hessF11 = mVGL.data(5); + valT* restrict hessF22 = mVGL.data(6); + valT* restrict hessF01 = mVGL.data(7); + valT* restrict hessF02 = mVGL.data(8); + + feeI.evaluateVGL(kel_counter, + Distjk_Compressed.data(), + DistjI_Compressed.data(), + DistkI_Compressed.data(), + val, + gradF0, + gradF1, + gradF2, + hessF00, + hessF11, + hessF22, + hessF01, hessF02); // compute the contribution to jel, kel @@ -469,9 +521,9 @@ template class ThreeBodyJastrow : public WaveFunctionComponent std::fill_n(hessF11, kel_counter, czero); for (int idim = 0; idim < OHMMS_DIM; ++idim) { - valT *restrict jk = Disp_jk_Compressed.data(idim); - valT *restrict jI = Disp_jI_Compressed.data(idim); - valT *restrict kI = Disp_kI_Compressed.data(idim); + valT* restrict jk = Disp_jk_Compressed.data(idim); + valT* restrict jI = Disp_jI_Compressed.data(idim); + valT* restrict kI = Disp_kI_Compressed.data(idim); valT dUj_x(0); for (int kel_index = 0; kel_index < kel_counter; kel_index++) { @@ -486,27 +538,27 @@ template class ThreeBodyJastrow : public WaveFunctionComponent } dUj[idim] += dUj_x; - valT *restrict jk0 = Disp_jk_Compressed.data(0); + valT* restrict jk0 = Disp_jk_Compressed.data(0); if (idim > 0) { for (int kel_index = 0; kel_index < kel_counter; kel_index++) jk0[kel_index] += jk[kel_index]; } - valT *restrict dUk_x = dUk.data(idim); + valT* restrict dUk_x = dUk.data(idim); for (int kel_index = 0; kel_index < kel_counter; kel_index++) dUk_x[DistIndice_k[kel_index]] += kI[kel_index]; } valT sum(0); - valT *restrict jk0 = Disp_jk_Compressed.data(0); + valT* restrict jk0 = Disp_jk_Compressed.data(0); for (int kel_index = 0; kel_index < kel_counter; kel_index++) sum += hessF01[kel_index] * jk0[kel_index]; d2Uj -= ctwo * sum; for (int kel_index = 0; kel_index < kel_counter; kel_index++) hessF00[kel_index] = hessF00[kel_index] + hessF22[kel_index] + - lapfac * (gradF0[kel_index] + gradF2[kel_index]) - - ctwo * hessF02[kel_index] * hessF11[kel_index]; + lapfac * (gradF0[kel_index] + gradF2[kel_index]) - + ctwo * hessF02[kel_index] * hessF11[kel_index]; for (int kel_index = 0; kel_index < kel_counter; kel_index++) { @@ -516,11 +568,19 @@ template class ThreeBodyJastrow : public WaveFunctionComponent } } - inline void computeU3(const ParticleSet &P, int jel, const RealType *distjI, - const RowContainer &displjI, const RealType *distjk, - const RowContainer &displjk, valT &Uj, posT &dUj, - valT &d2Uj, Vector &Uk, gContainer_type &dUk, - Vector &d2Uk, bool triangle = false) + inline void computeU3(const ParticleSet& P, + int jel, + const RealType* distjI, + const RowContainer& displjI, + const RealType* distjk, + const RowContainer& displjk, + valT& Uj, + posT& dUj, + valT& d2Uj, + Vector& Uk, + gContainer_type& dUk, + Vector& d2Uk, + bool triangle = false) { constexpr valT czero(0); @@ -538,7 +598,8 @@ template class ThreeBodyJastrow : public WaveFunctionComponent ions_nearby.clear(); for (int iat = 0; iat < Nion; ++iat) - if (distjI[iat] < Ion_cutoff[iat]) ions_nearby.push_back(iat); + if (distjI[iat] < Ion_cutoff[iat]) + ions_nearby.push_back(iat); for (int kg = 0; kg < eGroups; ++kg) { @@ -564,18 +625,16 @@ template class ThreeBodyJastrow : public WaveFunctionComponent kel_counter++; if (kel_counter == Nbuffer) { - const FT &feeI(*F(ig, jg, kg)); - computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, - d2Uk); + const FT& feeI(*F(ig, jg, kg)); + computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, d2Uk); kel_counter = 0; } } } - if ((iind + 1 == ions_nearby.size() || - ig != Ions.GroupID[ions_nearby[iind + 1]]) && + if ((iind + 1 == ions_nearby.size() || ig != Ions.GroupID[ions_nearby[iind + 1]]) && kel_counter > 0) { - const FT &feeI(*F(ig, jg, kg)); + const FT& feeI(*F(ig, jg, kg)); computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, d2Uk); kel_counter = 0; } @@ -583,10 +642,13 @@ template class ThreeBodyJastrow : public WaveFunctionComponent } } - void evaluateGL(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, bool fromscratch = false) + void evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, + bool fromscratch = false) { - if (fromscratch) recompute(P); + if (fromscratch) + recompute(P); LogValue = valT(0); for (int iat = 0; iat < Nelec; ++iat) { diff --git a/src/QMCWaveFunctions/Jastrow/ThreeBodyJastrowRef.h b/src/QMCWaveFunctions/Jastrow/ThreeBodyJastrowRef.h index ea8ffc836..55df90646 100644 --- a/src/QMCWaveFunctions/Jastrow/ThreeBodyJastrowRef.h +++ b/src/QMCWaveFunctions/Jastrow/ThreeBodyJastrowRef.h @@ -17,7 +17,6 @@ namespace miniqmcreference { - using namespace qmcplusplus; /** @ingroup WaveFunctionComponent @@ -28,7 +27,8 @@ using namespace qmcplusplus; *For electrons, distinct pair correlation functions are used *for spins up-up/down-down and up-down/down-up. */ -template class ThreeBodyJastrowRef : public WaveFunctionComponent +template +class ThreeBodyJastrowRef : public WaveFunctionComponent { /// type of each component U, dU, d2U; using valT = typename FT::real_type; @@ -45,7 +45,7 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent // number of groups of the target particleset int eGroups, iGroups; /// reference to the sources (ions) - const ParticleSet &Ions; + const ParticleSet& Ions; /// diff value RealType DiffVal; @@ -60,7 +60,7 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent valT cur_Uat, cur_d2Uat; posT cur_dUat, dUat_temp; /// container for the Jastrow functions - Array F; + Array F; /// the cutoff for e-I pairs std::vector Ion_cutoff; @@ -85,19 +85,18 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent /// alias FuncType using FuncType = FT; - ThreeBodyJastrowRef(const ParticleSet &ions, ParticleSet &elecs, - bool is_master = false) + ThreeBodyJastrowRef(const ParticleSet& ions, ParticleSet& elecs, bool is_master = false) : Ions(ions) { - WaveFunctionComponentName = "ThreeBodyJastrowRef"; - myTableID = elecs.addTable(Ions, DT_SOA); + WaveFunctionComponentName = "ThreeBodyJastrowRef"; + myTableID = elecs.addTable(Ions, DT_SOA); elecs.DistTables[myTableID]->Need_full_table_loadWalker = true; init(elecs); } ~ThreeBodyJastrowRef() {} - void init(ParticleSet &p) + void init(ParticleSet& p) { Nelec = p.getTotalNum(); Nelec_padded = getAlignedSize(Nelec); @@ -136,7 +135,7 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent DistIndice_k.resize(Nbuffer); } - void addFunc(int iSpecies, int eSpecies1, int eSpecies2, FT *j) + void addFunc(int iSpecies, int eSpecies1, int eSpecies2, FT* j) { if (eSpecies1 == eSpecies2) { @@ -145,7 +144,8 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent for (int eG1 = 0; eG1 < eGroups; eG1++) for (int eG2 = 0; eG2 < eGroups; eG2++) { - if (F(iSpecies, eG1, eG2) == 0) F(iSpecies, eG1, eG2) = j; + if (F(iSpecies, eG1, eG2) == 0) + F(iSpecies, eG1, eG2) = j; } } else @@ -157,12 +157,12 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent { RealType rcut = 0.5 * j->cutoff_radius; for (int i = 0; i < Nion; i++) - if (Ions.GroupID[i] == iSpecies) Ion_cutoff[i] = rcut; + if (Ions.GroupID[i] == iSpecies) + Ion_cutoff[i] = rcut; } else { - APP_ABORT( - "ThreeBodyJastrowRef::addFunc Jastrow function pointer is NULL"); + APP_ABORT("ThreeBodyJastrowRef::addFunc Jastrow function pointer is NULL"); } } @@ -178,7 +178,8 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent bool partial; for (int e1 = 0; e1 < eGroups; ++e1) for (int e2 = 0; e2 < eGroups; ++e2) - if (F(i, e1, e2) != 0) nfilled++; + if (F(i, e1, e2) != 0) + nfilled++; partial = nfilled > 0 && nfilled < eGroups * eGroups; if (partial) app_log() << "J3 eeI is missing correlation for ion " << i << std::endl; @@ -192,8 +193,9 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent // first set radii for (int i = 0; i < Nion; ++i) { - FT *f = F(Ions.GroupID[i], 0, 0); - if (f != 0) Ion_cutoff[i] = .5 * f->cutoff_radius; + FT* f = F(Ions.GroupID[i], 0, 0); + if (f != 0) + Ion_cutoff[i] = .5 * f->cutoff_radius; } // then check radii bool all_radii_match = true; @@ -207,8 +209,7 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent for (int e2 = 0; e2 < eGroups; ++e2) radii_match = radii_match && F(i, e1, e2)->cutoff_radius == rcut; if (!radii_match) - app_log() << "eeI functors for ion species " << i - << " have different radii" << std::endl; + app_log() << "eeI functors for ion species " << i << " have different radii" << std::endl; all_radii_match = all_radii_match && radii_match; } } @@ -219,9 +220,9 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent } } - void build_compact_list(ParticleSet &P) + void build_compact_list(ParticleSet& P) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); for (int iat = 0; iat < Nion; ++iat) for (int jg = 0; jg < eGroups; ++jg) @@ -238,59 +239,85 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent { elecs_inside(jg, iat).push_back(jel); elecs_inside_dist(jg, iat).push_back(eI_table.Distances[jel][iat]); - elecs_inside_displ(jg, iat).push_back( - eI_table.Displacements[jel][iat]); + elecs_inside_displ(jg, iat).push_back(eI_table.Displacements[jel][iat]); } } - RealType evaluateLog(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L) + RealType evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L) { evaluateGL(P, G, L, true); return LogValue; } - ValueType ratio(ParticleSet &P, int iat) + ValueType ratio(ParticleSet& P, int iat) { UpdateMode = ORB_PBYP_RATIO; - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); - const DistanceTableData &ee_table = (*P.DistTables[0]); - cur_Uat = computeU(P, iat, P.GroupID[iat], eI_table.Temp_r.data(), - ee_table.Temp_r.data()); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& ee_table = (*P.DistTables[0]); + cur_Uat = computeU(P, iat, P.GroupID[iat], eI_table.Temp_r.data(), ee_table.Temp_r.data()); DiffVal = Uat[iat] - cur_Uat; return std::exp(DiffVal); } - GradType evalGrad(ParticleSet &P, int iat) { return GradType(dUat[iat]); } + GradType evalGrad(ParticleSet& P, int iat) { return GradType(dUat[iat]); } - ValueType ratioGrad(ParticleSet &P, int iat, GradType &grad_iat) + ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat) { UpdateMode = ORB_PBYP_PARTIAL; - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); - const DistanceTableData &ee_table = (*P.DistTables[0]); - computeU3(P, iat, eI_table.Temp_r.data(), eI_table.Temp_dr, - ee_table.Temp_r.data(), ee_table.Temp_dr, cur_Uat, cur_dUat, - cur_d2Uat, newUk, newdUk, newd2Uk); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& ee_table = (*P.DistTables[0]); + computeU3(P, + iat, + eI_table.Temp_r.data(), + eI_table.Temp_dr, + ee_table.Temp_r.data(), + ee_table.Temp_dr, + cur_Uat, + cur_dUat, + cur_d2Uat, + newUk, + newdUk, + newd2Uk); DiffVal = Uat[iat] - cur_Uat; grad_iat += cur_dUat; return std::exp(DiffVal); } - void acceptMove(ParticleSet &P, int iat) + void acceptMove(ParticleSet& P, int iat) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); - const DistanceTableData &ee_table = (*P.DistTables[0]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& ee_table = (*P.DistTables[0]); // get the old value, grad, lapl - computeU3(P, iat, eI_table.Distances[iat], eI_table.Displacements[iat], - ee_table.Distances[iat], ee_table.Displacements[iat], Uat[iat], - dUat_temp, d2Uat[iat], oldUk, olddUk, oldd2Uk); + computeU3(P, + iat, + eI_table.Distances[iat], + eI_table.Displacements[iat], + ee_table.Distances[iat], + ee_table.Displacements[iat], + Uat[iat], + dUat_temp, + d2Uat[iat], + oldUk, + olddUk, + oldd2Uk); if (UpdateMode == ORB_PBYP_RATIO) { // ratio-only during the move; need to compute derivatives - computeU3(P, iat, eI_table.Temp_r.data(), eI_table.Temp_dr, - ee_table.Temp_r.data(), ee_table.Temp_dr, cur_Uat, cur_dUat, - cur_d2Uat, newUk, newdUk, newd2Uk); + computeU3(P, + iat, + eI_table.Temp_r.data(), + eI_table.Temp_dr, + ee_table.Temp_r.data(), + ee_table.Temp_dr, + cur_Uat, + cur_dUat, + cur_d2Uat, + newUk, + newdUk, + newd2Uk); } for (int jel = 0; jel < Nelec; jel++) @@ -300,9 +327,9 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent } for (int idim = 0; idim < OHMMS_DIM; ++idim) { - valT *restrict save_g = dUat.data(idim); - const valT *restrict new_g = newdUk.data(idim); - const valT *restrict old_g = olddUk.data(idim); + valT* restrict save_g = dUat.data(idim); + const valT* restrict new_g = newdUk.data(idim); + const valT* restrict old_g = olddUk.data(idim); for (int jel = 0; jel < Nelec; jel++) save_g[jel] += new_g[jel] - old_g[jel]; } @@ -317,12 +344,11 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent for (int jat = 0; jat < Nion; jat++) { bool inside = eI_table.Temp_r[jat] < Ion_cutoff[jat]; - auto iter = - find(elecs_inside(ig, jat).begin(), elecs_inside(ig, jat).end(), iat); - auto iter_dist = elecs_inside_dist(ig, jat).begin() + - std::distance(elecs_inside(ig, jat).begin(), iter); - auto iter_displ = elecs_inside_displ(ig, jat).begin() + - std::distance(elecs_inside(ig, jat).begin(), iter); + auto iter = find(elecs_inside(ig, jat).begin(), elecs_inside(ig, jat).end(), iat); + auto iter_dist = + elecs_inside_dist(ig, jat).begin() + std::distance(elecs_inside(ig, jat).begin(), iter); + auto iter_displ = + elecs_inside_displ(ig, jat).begin() + std::distance(elecs_inside(ig, jat).begin(), iter); if (inside) { if (iter == elecs_inside(ig, jat).end()) @@ -352,18 +378,28 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent } } - inline void recompute(ParticleSet &P) + inline void recompute(ParticleSet& P) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); - const DistanceTableData &ee_table = (*P.DistTables[0]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& ee_table = (*P.DistTables[0]); build_compact_list(P); for (int jel = 0; jel < Nelec; ++jel) { - computeU3(P, jel, eI_table.Distances[jel], eI_table.Displacements[jel], - ee_table.Distances[jel], ee_table.Displacements[jel], Uat[jel], - dUat_temp, d2Uat[jel], newUk, newdUk, newd2Uk, true); + computeU3(P, + jel, + eI_table.Distances[jel], + eI_table.Displacements[jel], + ee_table.Distances[jel], + ee_table.Displacements[jel], + Uat[jel], + dUat_temp, + d2Uat[jel], + newUk, + newdUk, + newd2Uk, + true); dUat(jel) = dUat_temp; // add the contribution from the upper triangle for (int kel = 0; kel < jel; kel++) @@ -373,22 +409,23 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent } for (int idim = 0; idim < OHMMS_DIM; ++idim) { - valT *restrict save_g = dUat.data(idim); - const valT *restrict new_g = newdUk.data(idim); + valT* restrict save_g = dUat.data(idim); + const valT* restrict new_g = newdUk.data(idim); for (int kel = 0; kel < jel; kel++) save_g[kel] += new_g[kel]; } } } - inline valT computeU(const ParticleSet &P, int jel, int jg, - const RealType *distjI, const RealType *distjk) + inline valT + computeU(const ParticleSet& P, int jel, int jg, const RealType* distjI, const RealType* distjk) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); ions_nearby.clear(); for (int iat = 0; iat < Nion; ++iat) - if (distjI[iat] < Ion_cutoff[iat]) ions_nearby.push_back(iat); + if (distjI[iat] < Ion_cutoff[iat]) + ions_nearby.push_back(iat); valT Uj = valT(0); for (int kg = 0; kg < eGroups; ++kg) @@ -410,20 +447,21 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent kel_counter++; if (kel_counter == Nbuffer) { - const FT &feeI(*F(ig, jg, kg)); - Uj += feeI.evaluateV(kel_counter, Distjk_Compressed.data(), + const FT& feeI(*F(ig, jg, kg)); + Uj += feeI.evaluateV(kel_counter, + Distjk_Compressed.data(), DistjI_Compressed.data(), DistkI_Compressed.data()); kel_counter = 0; } } } - if ((iind + 1 == ions_nearby.size() || - ig != Ions.GroupID[ions_nearby[iind + 1]]) && + if ((iind + 1 == ions_nearby.size() || ig != Ions.GroupID[ions_nearby[iind + 1]]) && kel_counter > 0) { - const FT &feeI(*F(ig, jg, kg)); - Uj += feeI.evaluateV(kel_counter, Distjk_Compressed.data(), + const FT& feeI(*F(ig, jg, kg)); + Uj += feeI.evaluateV(kel_counter, + Distjk_Compressed.data(), DistjI_Compressed.data(), DistkI_Compressed.data()); kel_counter = 0; @@ -433,31 +471,45 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent return Uj; } - inline void computeU3_engine(const ParticleSet &P, const FT &feeI, - int kel_counter, valT &Uj, posT &dUj, valT &d2Uj, - Vector &Uk, gContainer_type &dUk, - Vector &d2Uk) + inline void computeU3_engine(const ParticleSet& P, + const FT& feeI, + int kel_counter, + valT& Uj, + posT& dUj, + valT& d2Uj, + Vector& Uk, + gContainer_type& dUk, + Vector& d2Uk) { - const DistanceTableData &eI_table = (*P.DistTables[myTableID]); + const DistanceTableData& eI_table = (*P.DistTables[myTableID]); constexpr valT czero(0); constexpr valT cone(1); constexpr valT ctwo(2); constexpr valT lapfac = OHMMS_DIM - cone; - valT *restrict val = mVGL.data(0); - valT *restrict gradF0 = mVGL.data(1); - valT *restrict gradF1 = mVGL.data(2); - valT *restrict gradF2 = mVGL.data(3); - valT *restrict hessF00 = mVGL.data(4); - valT *restrict hessF11 = mVGL.data(5); - valT *restrict hessF22 = mVGL.data(6); - valT *restrict hessF01 = mVGL.data(7); - valT *restrict hessF02 = mVGL.data(8); - - feeI.evaluateVGL(kel_counter, Distjk_Compressed.data(), - DistjI_Compressed.data(), DistkI_Compressed.data(), val, - gradF0, gradF1, gradF2, hessF00, hessF11, hessF22, hessF01, + valT* restrict val = mVGL.data(0); + valT* restrict gradF0 = mVGL.data(1); + valT* restrict gradF1 = mVGL.data(2); + valT* restrict gradF2 = mVGL.data(3); + valT* restrict hessF00 = mVGL.data(4); + valT* restrict hessF11 = mVGL.data(5); + valT* restrict hessF22 = mVGL.data(6); + valT* restrict hessF01 = mVGL.data(7); + valT* restrict hessF02 = mVGL.data(8); + + feeI.evaluateVGL(kel_counter, + Distjk_Compressed.data(), + DistjI_Compressed.data(), + DistkI_Compressed.data(), + val, + gradF0, + gradF1, + gradF2, + hessF00, + hessF11, + hessF22, + hessF01, hessF02); // compute the contribution to jel, kel @@ -470,9 +522,9 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent std::fill_n(hessF11, kel_counter, czero); for (int idim = 0; idim < OHMMS_DIM; ++idim) { - valT *restrict jk = Disp_jk_Compressed.data(idim); - valT *restrict jI = Disp_jI_Compressed.data(idim); - valT *restrict kI = Disp_kI_Compressed.data(idim); + valT* restrict jk = Disp_jk_Compressed.data(idim); + valT* restrict jI = Disp_jI_Compressed.data(idim); + valT* restrict kI = Disp_kI_Compressed.data(idim); valT dUj_x(0); for (int kel_index = 0; kel_index < kel_counter; kel_index++) { @@ -487,27 +539,27 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent } dUj[idim] += dUj_x; - valT *restrict jk0 = Disp_jk_Compressed.data(0); + valT* restrict jk0 = Disp_jk_Compressed.data(0); if (idim > 0) { for (int kel_index = 0; kel_index < kel_counter; kel_index++) jk0[kel_index] += jk[kel_index]; } - valT *restrict dUk_x = dUk.data(idim); + valT* restrict dUk_x = dUk.data(idim); for (int kel_index = 0; kel_index < kel_counter; kel_index++) dUk_x[DistIndice_k[kel_index]] += kI[kel_index]; } valT sum(0); - valT *restrict jk0 = Disp_jk_Compressed.data(0); + valT* restrict jk0 = Disp_jk_Compressed.data(0); for (int kel_index = 0; kel_index < kel_counter; kel_index++) sum += hessF01[kel_index] * jk0[kel_index]; d2Uj -= ctwo * sum; for (int kel_index = 0; kel_index < kel_counter; kel_index++) hessF00[kel_index] = hessF00[kel_index] + hessF22[kel_index] + - lapfac * (gradF0[kel_index] + gradF2[kel_index]) - - ctwo * hessF02[kel_index] * hessF11[kel_index]; + lapfac * (gradF0[kel_index] + gradF2[kel_index]) - + ctwo * hessF02[kel_index] * hessF11[kel_index]; for (int kel_index = 0; kel_index < kel_counter; kel_index++) { @@ -517,11 +569,19 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent } } - inline void computeU3(const ParticleSet &P, int jel, const RealType *distjI, - const RowContainer &displjI, const RealType *distjk, - const RowContainer &displjk, valT &Uj, posT &dUj, - valT &d2Uj, Vector &Uk, gContainer_type &dUk, - Vector &d2Uk, bool triangle = false) + inline void computeU3(const ParticleSet& P, + int jel, + const RealType* distjI, + const RowContainer& displjI, + const RealType* distjk, + const RowContainer& displjk, + valT& Uj, + posT& dUj, + valT& d2Uj, + Vector& Uk, + gContainer_type& dUk, + Vector& d2Uk, + bool triangle = false) { constexpr valT czero(0); @@ -539,7 +599,8 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent ions_nearby.clear(); for (int iat = 0; iat < Nion; ++iat) - if (distjI[iat] < Ion_cutoff[iat]) ions_nearby.push_back(iat); + if (distjI[iat] < Ion_cutoff[iat]) + ions_nearby.push_back(iat); for (int kg = 0; kg < eGroups; ++kg) { @@ -565,18 +626,16 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent kel_counter++; if (kel_counter == Nbuffer) { - const FT &feeI(*F(ig, jg, kg)); - computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, - d2Uk); + const FT& feeI(*F(ig, jg, kg)); + computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, d2Uk); kel_counter = 0; } } } - if ((iind + 1 == ions_nearby.size() || - ig != Ions.GroupID[ions_nearby[iind + 1]]) && + if ((iind + 1 == ions_nearby.size() || ig != Ions.GroupID[ions_nearby[iind + 1]]) && kel_counter > 0) { - const FT &feeI(*F(ig, jg, kg)); + const FT& feeI(*F(ig, jg, kg)); computeU3_engine(P, feeI, kel_counter, Uj, dUj, d2Uj, Uk, dUk, d2Uk); kel_counter = 0; } @@ -584,10 +643,13 @@ template class ThreeBodyJastrowRef : public WaveFunctionComponent } } - void evaluateGL(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, bool fromscratch = false) + void evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, + bool fromscratch = false) { - if (fromscratch) recompute(P); + if (fromscratch) + recompute(P); LogValue = valT(0); for (int iat = 0; iat < Nelec; ++iat) { diff --git a/src/QMCWaveFunctions/Jastrow/TwoBodyJastrow.h b/src/QMCWaveFunctions/Jastrow/TwoBodyJastrow.h index 7c718d10b..01c4535db 100644 --- a/src/QMCWaveFunctions/Jastrow/TwoBodyJastrow.h +++ b/src/QMCWaveFunctions/Jastrow/TwoBodyJastrow.h @@ -26,7 +26,6 @@ namespace qmcplusplus { - /** @ingroup WaveFunctionComponent * @brief Specialization for two-body Jastrow function using multiple functors * @@ -42,7 +41,8 @@ namespace qmcplusplus * - double the loop counts * - Memory use is O(N). */ -template struct TwoBodyJastrow : public WaveFunctionComponent +template +struct TwoBodyJastrow : public WaveFunctionComponent { /// alias FuncType using FuncType = FT; @@ -78,46 +78,47 @@ template struct TwoBodyJastrow : public WaveFunctionComponent aligned_vector DistCompressed; aligned_vector DistIndice; /// Container for \f$F[ig*NumGroups+jg]\f$ - std::vector F; + std::vector F; /// Uniquue J2 set for cleanup - std::map J2Unique; + std::map J2Unique; - TwoBodyJastrow(ParticleSet &p); - TwoBodyJastrow(const TwoBodyJastrow &rhs) = delete; + TwoBodyJastrow(ParticleSet& p); + TwoBodyJastrow(const TwoBodyJastrow& rhs) = delete; ~TwoBodyJastrow(); /* initialize storage */ - void init(ParticleSet &p); + void init(ParticleSet& p); /** add functor for (ia,ib) pair */ - void addFunc(int ia, int ib, FT *j); + void addFunc(int ia, int ib, FT* j); - RealType evaluateLog(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L); + RealType evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L); /** recompute internal data assuming distance table is fully ready */ - void recompute(ParticleSet &P); + void recompute(ParticleSet& P); - ValueType ratio(ParticleSet &P, int iat); - GradType evalGrad(ParticleSet &P, int iat); - ValueType ratioGrad(ParticleSet &P, int iat, GradType &grad_iat); - void acceptMove(ParticleSet &P, int iat); + ValueType ratio(ParticleSet& P, int iat); + GradType evalGrad(ParticleSet& P, int iat); + ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat); + void acceptMove(ParticleSet& P, int iat); /** compute G and L after the sweep */ - void evaluateGL(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, + void evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, bool fromscratch = false); /*@{ internal compute engines*/ - inline valT computeU(const ParticleSet &P, int iat, - const RealType *restrict dist) + inline valT computeU(const ParticleSet& P, int iat, const RealType* restrict dist) { valT curUat(0); const int igt = P.GroupID[iat] * NumGroups; for (int jg = 0; jg < NumGroups; ++jg) { - const FuncType &f2(*F[igt + jg]); + const FuncType& f2(*F[igt + jg]); int iStart = P.first(jg); int iEnd = P.last(jg); curUat += f2.evaluateV(iat, iStart, iEnd, dist, DistCompressed.data()); @@ -125,20 +126,22 @@ template struct TwoBodyJastrow : public WaveFunctionComponent return curUat; } - inline void computeU3(const ParticleSet &P, int iat, - const RealType *restrict dist, RealType *restrict u, - RealType *restrict du, RealType *restrict d2u, + inline void computeU3(const ParticleSet& P, + int iat, + const RealType* restrict dist, + RealType* restrict u, + RealType* restrict du, + RealType* restrict d2u, bool triangle = false); /** compute gradient */ - inline posT accumulateG(const valT *restrict du, - const RowContainer &displ) const + inline posT accumulateG(const valT* restrict du, const RowContainer& displ) const { posT grad; for (int idim = 0; idim < OHMMS_DIM; ++idim) { - const valT *restrict dX = displ.data(idim); + const valT* restrict dX = displ.data(idim); valT s = valT(); for (int jat = 0; jat < N; ++jat) @@ -150,7 +153,8 @@ template struct TwoBodyJastrow : public WaveFunctionComponent /**@} */ }; -template TwoBodyJastrow::TwoBodyJastrow(ParticleSet &p) +template +TwoBodyJastrow::TwoBodyJastrow(ParticleSet& p) { init(p); FirstTime = true; @@ -158,7 +162,8 @@ template TwoBodyJastrow::TwoBodyJastrow(ParticleSet &p) WaveFunctionComponentName = "TwoBodyJastrow"; } -template TwoBodyJastrow::~TwoBodyJastrow() +template +TwoBodyJastrow::~TwoBodyJastrow() { auto it = J2Unique.begin(); while (it != J2Unique.end()) @@ -168,7 +173,8 @@ template TwoBodyJastrow::~TwoBodyJastrow() } } // need to clean up J2Unique -template void TwoBodyJastrow::init(ParticleSet &p) +template +void TwoBodyJastrow::init(ParticleSet& p) { N = p.getTotalNum(); N_padded = getAlignedSize(N); @@ -188,7 +194,8 @@ template void TwoBodyJastrow::init(ParticleSet &p) DistIndice.resize(N); } -template void TwoBodyJastrow::addFunc(int ia, int ib, FT *j) +template +void TwoBodyJastrow::addFunc(int ia, int ib, FT* j) { if (ia == ib) { @@ -197,7 +204,8 @@ template void TwoBodyJastrow::addFunc(int ia, int ib, FT *j) int ij = 0; for (int ig = 0; ig < NumGroups; ++ig) for (int jg = 0; jg < NumGroups; ++jg, ++ij) - if (F[ij] == nullptr) F[ij] = j; + if (F[ij] == nullptr) + F[ij] = j; } else F[ia * NumGroups + ib] = j; @@ -233,12 +241,14 @@ template void TwoBodyJastrow::addFunc(int ia, int ib, FT *j) * @param du starting first deriv * @param d2u starting second deriv */ -template -inline void TwoBodyJastrow::computeU3(const ParticleSet &P, int iat, - const RealType *restrict dist, - RealType *restrict u, - RealType *restrict du, - RealType *restrict d2u, bool triangle) +template +inline void TwoBodyJastrow::computeU3(const ParticleSet& P, + int iat, + const RealType* restrict dist, + RealType* restrict u, + RealType* restrict du, + RealType* restrict d2u, + bool triangle) { const int jelmax = triangle ? iat : N; constexpr valT czero(0); @@ -249,20 +259,18 @@ inline void TwoBodyJastrow::computeU3(const ParticleSet &P, int iat, const int igt = P.GroupID[iat] * NumGroups; for (int jg = 0; jg < NumGroups; ++jg) { - const FuncType &f2(*F[igt + jg]); + const FuncType& f2(*F[igt + jg]); int iStart = P.first(jg); int iEnd = std::min(jelmax, P.last(jg)); - f2.evaluateVGL(iat, iStart, iEnd, dist, u, du, d2u, DistCompressed.data(), - DistIndice.data()); + f2.evaluateVGL(iat, iStart, iEnd, dist, u, du, d2u, DistCompressed.data(), DistIndice.data()); } // u[iat]=czero; // du[iat]=czero; // d2u[iat]=czero; } -template -typename TwoBodyJastrow::ValueType TwoBodyJastrow::ratio(ParticleSet &P, - int iat) +template +typename TwoBodyJastrow::ValueType TwoBodyJastrow::ratio(ParticleSet& P, int iat) { // only ratio, ready to compute it again UpdateMode = ORB_PBYP_RATIO; @@ -270,35 +278,31 @@ typename TwoBodyJastrow::ValueType TwoBodyJastrow::ratio(ParticleSet &P, return std::exp(Uat[iat] - cur_Uat); } -template -typename TwoBodyJastrow::GradType -TwoBodyJastrow::evalGrad(ParticleSet &P, int iat) +template +typename TwoBodyJastrow::GradType TwoBodyJastrow::evalGrad(ParticleSet& P, int iat) { return GradType(dUat[iat]); } -template +template typename TwoBodyJastrow::ValueType -TwoBodyJastrow::ratioGrad(ParticleSet &P, int iat, GradType &grad_iat) + TwoBodyJastrow::ratioGrad(ParticleSet& P, int iat, GradType& grad_iat) { - UpdateMode = ORB_PBYP_PARTIAL; - computeU3(P, iat, P.DistTables[0]->Temp_r.data(), cur_u.data(), cur_du.data(), - cur_d2u.data()); + computeU3(P, iat, P.DistTables[0]->Temp_r.data(), cur_u.data(), cur_du.data(), cur_d2u.data()); cur_Uat = simd::accumulate_n(cur_u.data(), N, valT()); DiffVal = Uat[iat] - cur_Uat; grad_iat += accumulateG(cur_du.data(), P.DistTables[0]->Temp_dr); return std::exp(DiffVal); } -template -void TwoBodyJastrow::acceptMove(ParticleSet &P, int iat) +template +void TwoBodyJastrow::acceptMove(ParticleSet& P, int iat) { // get the old u, du, d2u - const DistanceTableData *d_table = P.DistTables[0]; - computeU3(P, iat, d_table->Distances[iat], old_u.data(), old_du.data(), - old_d2u.data()); + const DistanceTableData* d_table = P.DistTables[0]; + computeU3(P, iat, d_table->Distances[iat], old_u.data(), old_du.data(), old_d2u.data()); if (UpdateMode == ORB_PBYP_RATIO) { // ratio-only during the move; need to compute derivatives const auto dist = d_table->Temp_r.data(); @@ -306,8 +310,8 @@ void TwoBodyJastrow::acceptMove(ParticleSet &P, int iat) } valT cur_d2Uat(0); - const auto &new_dr = d_table->Temp_dr; - const auto &old_dr = d_table->Displacements[iat]; + const auto& new_dr = d_table->Temp_dr; + const auto& old_dr = d_table->Displacements[iat]; constexpr valT lapfac = OHMMS_DIM - RealType(1); for (int jat = 0; jat < N; jat++) { @@ -321,11 +325,11 @@ void TwoBodyJastrow::acceptMove(ParticleSet &P, int iat) posT cur_dUat; for (int idim = 0; idim < OHMMS_DIM; ++idim) { - const valT *restrict new_dX = new_dr.data(idim); - const valT *restrict old_dX = old_dr.data(idim); - const valT *restrict cur_du_pt = cur_du.data(); - const valT *restrict old_du_pt = old_du.data(); - valT *restrict save_g = dUat.data(idim); + const valT* restrict new_dX = new_dr.data(idim); + const valT* restrict old_dX = old_dr.data(idim); + const valT* restrict cur_du_pt = cur_du.data(); + const valT* restrict old_du_pt = old_du.data(); + valT* restrict save_g = dUat.data(idim); valT cur_g = cur_dUat[idim]; for (int jat = 0; jat < N; jat++) { @@ -342,29 +346,29 @@ void TwoBodyJastrow::acceptMove(ParticleSet &P, int iat) d2Uat[iat] = cur_d2Uat; } -template void TwoBodyJastrow::recompute(ParticleSet &P) +template +void TwoBodyJastrow::recompute(ParticleSet& P) { - const DistanceTableData *d_table = P.DistTables[0]; + const DistanceTableData* d_table = P.DistTables[0]; for (int ig = 0; ig < NumGroups; ++ig) { const int igt = ig * NumGroups; for (int iat = P.first(ig), last = P.last(ig); iat < last; ++iat) { - computeU3(P, iat, d_table->Distances[iat], cur_u.data(), cur_du.data(), - cur_d2u.data(), true); + computeU3(P, iat, d_table->Distances[iat], cur_u.data(), cur_du.data(), cur_d2u.data(), true); Uat[iat] = simd::accumulate_n(cur_u.data(), iat, valT()); posT grad; valT lap(0); - const valT *restrict u = cur_u.data(); - const valT *restrict du = cur_du.data(); - const valT *restrict d2u = cur_d2u.data(); - const RowContainer &displ = d_table->Displacements[iat]; + const valT* restrict u = cur_u.data(); + const valT* restrict du = cur_du.data(); + const valT* restrict d2u = cur_d2u.data(); + const RowContainer& displ = d_table->Displacements[iat]; constexpr valT lapfac = OHMMS_DIM - RealType(1); for (int jat = 0; jat < iat; ++jat) lap += d2u[jat] + lapfac * du[jat]; for (int idim = 0; idim < OHMMS_DIM; ++idim) { - const valT *restrict dX = displ.data(idim); + const valT* restrict dX = displ.data(idim); valT s = valT(); for (int jat = 0; jat < iat; ++jat) s += du[jat] * dX[jat]; @@ -380,8 +384,8 @@ template void TwoBodyJastrow::recompute(ParticleSet &P) } for (int idim = 0; idim < OHMMS_DIM; ++idim) { - valT *restrict save_g = dUat.data(idim); - const valT *restrict dX = displ.data(idim); + valT* restrict save_g = dUat.data(idim); + const valT* restrict dX = displ.data(idim); for (int jat = 0; jat < iat; jat++) save_g[jat] -= du[jat] * dX[jat]; } @@ -389,23 +393,24 @@ template void TwoBodyJastrow::recompute(ParticleSet &P) } } -template +template typename TwoBodyJastrow::RealType -TwoBodyJastrow::evaluateLog(ParticleSet &P, - ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L) + TwoBodyJastrow::evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L) { evaluateGL(P, G, L, true); return LogValue; } -template -void TwoBodyJastrow::evaluateGL(ParticleSet &P, - ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, +template +void TwoBodyJastrow::evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, bool fromscratch) { - if (fromscratch) recompute(P); + if (fromscratch) + recompute(P); LogValue = valT(0); for (int iat = 0; iat < N; ++iat) { diff --git a/src/QMCWaveFunctions/Jastrow/TwoBodyJastrowRef.h b/src/QMCWaveFunctions/Jastrow/TwoBodyJastrowRef.h index 4304987f0..348b7bb00 100644 --- a/src/QMCWaveFunctions/Jastrow/TwoBodyJastrowRef.h +++ b/src/QMCWaveFunctions/Jastrow/TwoBodyJastrowRef.h @@ -24,7 +24,6 @@ namespace miniqmcreference { - using namespace qmcplusplus; /** @ingroup WaveFunctionComponent @@ -42,7 +41,8 @@ using namespace qmcplusplus; * - double the loop counts * - Memory use is O(N). */ -template struct TwoBodyJastrowRef : public WaveFunctionComponent +template +struct TwoBodyJastrowRef : public WaveFunctionComponent { /// alias FuncType using FuncType = FT; @@ -78,46 +78,47 @@ template struct TwoBodyJastrowRef : public WaveFunctionComponent aligned_vector DistCompressed; aligned_vector DistIndice; /// Container for \f$F[ig*NumGroups+jg]\f$ - std::vector F; + std::vector F; /// Uniquue J2 set for cleanup - std::map J2Unique; + std::map J2Unique; - TwoBodyJastrowRef(ParticleSet &p); - TwoBodyJastrowRef(const TwoBodyJastrowRef &rhs) = delete; + TwoBodyJastrowRef(ParticleSet& p); + TwoBodyJastrowRef(const TwoBodyJastrowRef& rhs) = delete; ~TwoBodyJastrowRef(); /* initialize storage */ - void init(ParticleSet &p); + void init(ParticleSet& p); /** add functor for (ia,ib) pair */ - void addFunc(int ia, int ib, FT *j); + void addFunc(int ia, int ib, FT* j); - RealType evaluateLog(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L); + RealType evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L); /** recompute internal data assuming distance table is fully ready */ - void recompute(ParticleSet &P); + void recompute(ParticleSet& P); - ValueType ratio(ParticleSet &P, int iat); - GradType evalGrad(ParticleSet &P, int iat); - ValueType ratioGrad(ParticleSet &P, int iat, GradType &grad_iat); - void acceptMove(ParticleSet &P, int iat); + ValueType ratio(ParticleSet& P, int iat); + GradType evalGrad(ParticleSet& P, int iat); + ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat); + void acceptMove(ParticleSet& P, int iat); /** compute G and L after the sweep */ - void evaluateGL(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, + void evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, bool fromscratch = false); /*@{ internal compute engines*/ - inline valT computeU(const ParticleSet &P, int iat, - const RealType *restrict dist) + inline valT computeU(const ParticleSet& P, int iat, const RealType* restrict dist) { valT curUat(0); const int igt = P.GroupID[iat] * NumGroups; for (int jg = 0; jg < NumGroups; ++jg) { - const FuncType &f2(*F[igt + jg]); + const FuncType& f2(*F[igt + jg]); int iStart = P.first(jg); int iEnd = P.last(jg); curUat += f2.evaluateV(iat, iStart, iEnd, dist, DistCompressed.data()); @@ -125,20 +126,22 @@ template struct TwoBodyJastrowRef : public WaveFunctionComponent return curUat; } - inline void computeU3(const ParticleSet &P, int iat, - const RealType *restrict dist, RealType *restrict u, - RealType *restrict du, RealType *restrict d2u, + inline void computeU3(const ParticleSet& P, + int iat, + const RealType* restrict dist, + RealType* restrict u, + RealType* restrict du, + RealType* restrict d2u, bool triangle = false); /** compute gradient */ - inline posT accumulateG(const valT *restrict du, - const RowContainer &displ) const + inline posT accumulateG(const valT* restrict du, const RowContainer& displ) const { posT grad; for (int idim = 0; idim < OHMMS_DIM; ++idim) { - const valT *restrict dX = displ.data(idim); + const valT* restrict dX = displ.data(idim); valT s = valT(); for (int jat = 0; jat < N; ++jat) @@ -150,7 +153,8 @@ template struct TwoBodyJastrowRef : public WaveFunctionComponent /**@} */ }; -template TwoBodyJastrowRef::TwoBodyJastrowRef(ParticleSet &p) +template +TwoBodyJastrowRef::TwoBodyJastrowRef(ParticleSet& p) { init(p); FirstTime = true; @@ -158,7 +162,8 @@ template TwoBodyJastrowRef::TwoBodyJastrowRef(ParticleSet &p) WaveFunctionComponentName = "TwoBodyJastrowRef"; } -template TwoBodyJastrowRef::~TwoBodyJastrowRef() +template +TwoBodyJastrowRef::~TwoBodyJastrowRef() { auto it = J2Unique.begin(); while (it != J2Unique.end()) @@ -168,7 +173,8 @@ template TwoBodyJastrowRef::~TwoBodyJastrowRef() } } // need to clean up J2Unique -template void TwoBodyJastrowRef::init(ParticleSet &p) +template +void TwoBodyJastrowRef::init(ParticleSet& p) { N = p.getTotalNum(); N_padded = getAlignedSize(N); @@ -188,8 +194,8 @@ template void TwoBodyJastrowRef::init(ParticleSet &p) DistIndice.resize(N); } -template -void TwoBodyJastrowRef::addFunc(int ia, int ib, FT *j) +template +void TwoBodyJastrowRef::addFunc(int ia, int ib, FT* j) { if (ia == ib) { @@ -198,7 +204,8 @@ void TwoBodyJastrowRef::addFunc(int ia, int ib, FT *j) int ij = 0; for (int ig = 0; ig < NumGroups; ++ig) for (int jg = 0; jg < NumGroups; ++jg, ++ij) - if (F[ij] == nullptr) F[ij] = j; + if (F[ij] == nullptr) + F[ij] = j; } else F[ia * NumGroups + ib] = j; @@ -234,12 +241,14 @@ void TwoBodyJastrowRef::addFunc(int ia, int ib, FT *j) * @param du starting first deriv * @param d2u starting second deriv */ -template -inline void -TwoBodyJastrowRef::computeU3(const ParticleSet &P, int iat, - const RealType *restrict dist, - RealType *restrict u, RealType *restrict du, - RealType *restrict d2u, bool triangle) +template +inline void TwoBodyJastrowRef::computeU3(const ParticleSet& P, + int iat, + const RealType* restrict dist, + RealType* restrict u, + RealType* restrict du, + RealType* restrict d2u, + bool triangle) { const int jelmax = triangle ? iat : N; constexpr valT czero(0); @@ -250,20 +259,18 @@ TwoBodyJastrowRef::computeU3(const ParticleSet &P, int iat, const int igt = P.GroupID[iat] * NumGroups; for (int jg = 0; jg < NumGroups; ++jg) { - const FuncType &f2(*F[igt + jg]); + const FuncType& f2(*F[igt + jg]); int iStart = P.first(jg); int iEnd = std::min(jelmax, P.last(jg)); - f2.evaluateVGL(iat, iStart, iEnd, dist, u, du, d2u, DistCompressed.data(), - DistIndice.data()); + f2.evaluateVGL(iat, iStart, iEnd, dist, u, du, d2u, DistCompressed.data(), DistIndice.data()); } // u[iat]=czero; // du[iat]=czero; // d2u[iat]=czero; } -template -typename TwoBodyJastrowRef::ValueType -TwoBodyJastrowRef::ratio(ParticleSet &P, int iat) +template +typename TwoBodyJastrowRef::ValueType TwoBodyJastrowRef::ratio(ParticleSet& P, int iat) { // only ratio, ready to compute it again UpdateMode = ORB_PBYP_RATIO; @@ -271,35 +278,31 @@ TwoBodyJastrowRef::ratio(ParticleSet &P, int iat) return std::exp(Uat[iat] - cur_Uat); } -template -typename TwoBodyJastrowRef::GradType -TwoBodyJastrowRef::evalGrad(ParticleSet &P, int iat) +template +typename TwoBodyJastrowRef::GradType TwoBodyJastrowRef::evalGrad(ParticleSet& P, int iat) { return GradType(dUat[iat]); } -template +template typename TwoBodyJastrowRef::ValueType -TwoBodyJastrowRef::ratioGrad(ParticleSet &P, int iat, GradType &grad_iat) + TwoBodyJastrowRef::ratioGrad(ParticleSet& P, int iat, GradType& grad_iat) { - UpdateMode = ORB_PBYP_PARTIAL; - computeU3(P, iat, P.DistTables[0]->Temp_r.data(), cur_u.data(), cur_du.data(), - cur_d2u.data()); + computeU3(P, iat, P.DistTables[0]->Temp_r.data(), cur_u.data(), cur_du.data(), cur_d2u.data()); cur_Uat = std::accumulate(cur_u.begin(), cur_u.begin() + N, valT()); DiffVal = Uat[iat] - cur_Uat; grad_iat += accumulateG(cur_du.data(), P.DistTables[0]->Temp_dr); return std::exp(DiffVal); } -template -void TwoBodyJastrowRef::acceptMove(ParticleSet &P, int iat) +template +void TwoBodyJastrowRef::acceptMove(ParticleSet& P, int iat) { // get the old u, du, d2u - const DistanceTableData *d_table = P.DistTables[0]; - computeU3(P, iat, d_table->Distances[iat], old_u.data(), old_du.data(), - old_d2u.data()); + const DistanceTableData* d_table = P.DistTables[0]; + computeU3(P, iat, d_table->Distances[iat], old_u.data(), old_du.data(), old_d2u.data()); if (UpdateMode == ORB_PBYP_RATIO) { // ratio-only during the move; need to compute derivatives const auto dist = d_table->Temp_r.data(); @@ -307,8 +310,8 @@ void TwoBodyJastrowRef::acceptMove(ParticleSet &P, int iat) } valT cur_d2Uat(0); - const auto &new_dr = d_table->Temp_dr; - const auto &old_dr = d_table->Displacements[iat]; + const auto& new_dr = d_table->Temp_dr; + const auto& old_dr = d_table->Displacements[iat]; constexpr valT lapfac = OHMMS_DIM - RealType(1); for (int jat = 0; jat < N; jat++) { @@ -322,11 +325,11 @@ void TwoBodyJastrowRef::acceptMove(ParticleSet &P, int iat) posT cur_dUat; for (int idim = 0; idim < OHMMS_DIM; ++idim) { - const valT *restrict new_dX = new_dr.data(idim); - const valT *restrict old_dX = old_dr.data(idim); - const valT *restrict cur_du_pt = cur_du.data(); - const valT *restrict old_du_pt = old_du.data(); - valT *restrict save_g = dUat.data(idim); + const valT* restrict new_dX = new_dr.data(idim); + const valT* restrict old_dX = old_dr.data(idim); + const valT* restrict cur_du_pt = cur_du.data(); + const valT* restrict old_du_pt = old_du.data(); + valT* restrict save_g = dUat.data(idim); valT cur_g = cur_dUat[idim]; for (int jat = 0; jat < N; jat++) { @@ -343,29 +346,29 @@ void TwoBodyJastrowRef::acceptMove(ParticleSet &P, int iat) d2Uat[iat] = cur_d2Uat; } -template void TwoBodyJastrowRef::recompute(ParticleSet &P) +template +void TwoBodyJastrowRef::recompute(ParticleSet& P) { - const DistanceTableData *d_table = P.DistTables[0]; + const DistanceTableData* d_table = P.DistTables[0]; for (int ig = 0; ig < NumGroups; ++ig) { const int igt = ig * NumGroups; for (int iat = P.first(ig), last = P.last(ig); iat < last; ++iat) { - computeU3(P, iat, d_table->Distances[iat], cur_u.data(), cur_du.data(), - cur_d2u.data(), true); + computeU3(P, iat, d_table->Distances[iat], cur_u.data(), cur_du.data(), cur_d2u.data(), true); Uat[iat] = std::accumulate(cur_u.begin(), cur_u.begin() + iat, valT()); posT grad; valT lap(0); - const valT *restrict u = cur_u.data(); - const valT *restrict du = cur_du.data(); - const valT *restrict d2u = cur_d2u.data(); - const RowContainer &displ = d_table->Displacements[iat]; + const valT* restrict u = cur_u.data(); + const valT* restrict du = cur_du.data(); + const valT* restrict d2u = cur_d2u.data(); + const RowContainer& displ = d_table->Displacements[iat]; constexpr valT lapfac = OHMMS_DIM - RealType(1); for (int jat = 0; jat < iat; ++jat) lap += d2u[jat] + lapfac * du[jat]; for (int idim = 0; idim < OHMMS_DIM; ++idim) { - const valT *restrict dX = displ.data(idim); + const valT* restrict dX = displ.data(idim); valT s = valT(); for (int jat = 0; jat < iat; ++jat) s += du[jat] * dX[jat]; @@ -381,8 +384,8 @@ template void TwoBodyJastrowRef::recompute(ParticleSet &P) } for (int idim = 0; idim < OHMMS_DIM; ++idim) { - valT *restrict save_g = dUat.data(idim); - const valT *restrict dX = displ.data(idim); + valT* restrict save_g = dUat.data(idim); + const valT* restrict dX = displ.data(idim); for (int jat = 0; jat < iat; jat++) save_g[jat] -= du[jat] * dX[jat]; } @@ -390,23 +393,24 @@ template void TwoBodyJastrowRef::recompute(ParticleSet &P) } } -template +template typename TwoBodyJastrowRef::RealType -TwoBodyJastrowRef::evaluateLog(ParticleSet &P, - ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L) + TwoBodyJastrowRef::evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L) { evaluateGL(P, G, L, true); return LogValue; } -template -void TwoBodyJastrowRef::evaluateGL(ParticleSet &P, - ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, +template +void TwoBodyJastrowRef::evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, bool fromscratch) { - if (fromscratch) recompute(P); + if (fromscratch) + recompute(P); LogValue = valT(0); for (int iat = 0; iat < N; ++iat) { diff --git a/src/QMCWaveFunctions/SPOSet.h b/src/QMCWaveFunctions/SPOSet.h index c402296ba..c19169b24 100644 --- a/src/QMCWaveFunctions/SPOSet.h +++ b/src/QMCWaveFunctions/SPOSet.h @@ -17,7 +17,6 @@ namespace qmcplusplus { - /** base class for Single-particle orbital sets * * SPOSet stands for S(ingle)P(article)O(rbital)Set which contains @@ -33,48 +32,42 @@ class SPOSet : public QMCTraits public: /// return the size of the orbital set - inline int size() const - { - return OrbitalSetSize; - } + inline int size() const { return OrbitalSetSize; } /// destructor - virtual ~SPOSet() { } + virtual ~SPOSet() {} /// operates on a single walker /// evaluating SPOs - virtual void evaluate_v(const PosType &p) = 0; - virtual void evaluate_vgl(const PosType &p) = 0; - virtual void evaluate_vgh(const PosType &p) = 0; + virtual void evaluate_v(const PosType& p) = 0; + virtual void evaluate_vgl(const PosType& p) = 0; + virtual void evaluate_vgh(const PosType& p) = 0; /// operates on multiple walkers - virtual void multi_evaluate_v(const std::vector &spo_list, - const std::vector &pos_list) + virtual void + multi_evaluate_v(const std::vector& spo_list, const std::vector& pos_list) { - #pragma omp parallel for - for(int iw=0; iwevaluate_v(pos_list[iw]); } - virtual void multi_evaluate_vgl(const std::vector &spo_list, - const std::vector &pos_list) + virtual void + multi_evaluate_vgl(const std::vector& spo_list, const std::vector& pos_list) { - #pragma omp parallel for - for(int iw=0; iwevaluate_vgl(pos_list[iw]); } - virtual void multi_evaluate_vgh(const std::vector &spo_list, - const std::vector &pos_list) + virtual void + multi_evaluate_vgh(const std::vector& spo_list, const std::vector& pos_list) { - #pragma omp parallel for - for(int iw=0; iwevaluate_vgh(pos_list[iw]); } - }; -} +} // namespace qmcplusplus #endif - - diff --git a/src/QMCWaveFunctions/SPOSet_builder.cpp b/src/QMCWaveFunctions/SPOSet_builder.cpp index 5cccf5183..a53b01c28 100644 --- a/src/QMCWaveFunctions/SPOSet_builder.cpp +++ b/src/QMCWaveFunctions/SPOSet_builder.cpp @@ -16,46 +16,47 @@ namespace qmcplusplus { - SPOSet* build_SPOSet(bool useRef, - int nx, int ny, int nz, - int num_splines, int nblocks, - const Tensor &lattice_b, + int nx, + int ny, + int nz, + int num_splines, + int nblocks, + const Tensor& lattice_b, bool init_random) { if (useRef) { - auto *spo_main = new miniqmcreference::einspline_spo_ref; + auto* spo_main = new miniqmcreference::einspline_spo_ref; spo_main->set(nx, ny, nz, num_splines, nblocks); spo_main->Lattice.set(lattice_b); return dynamic_cast(spo_main); } else { - auto *spo_main = new einspline_spo; + auto* spo_main = new einspline_spo; spo_main->set(nx, ny, nz, num_splines, nblocks); spo_main->Lattice.set(lattice_b); return dynamic_cast(spo_main); } } -SPOSet* build_SPOSet_view(bool useRef, const SPOSet* SPOSet_main, - int team_size, int member_id) +SPOSet* build_SPOSet_view(bool useRef, const SPOSet* SPOSet_main, int team_size, int member_id) { if (useRef) { - auto *temp_ptr = dynamic_cast*>(SPOSet_main); - auto *spo_view = new miniqmcreference::einspline_spo_ref(*temp_ptr, team_size, member_id); + auto* temp_ptr = + dynamic_cast*>(SPOSet_main); + auto* spo_view = + new miniqmcreference::einspline_spo_ref(*temp_ptr, team_size, member_id); return dynamic_cast(spo_view); } else { - auto *temp_ptr = dynamic_cast*>(SPOSet_main); - auto *spo_view = new einspline_spo(*temp_ptr, team_size, member_id); + auto* temp_ptr = dynamic_cast*>(SPOSet_main); + auto* spo_view = new einspline_spo(*temp_ptr, team_size, member_id); return dynamic_cast(spo_view); } } -} - - +} // namespace qmcplusplus diff --git a/src/QMCWaveFunctions/SPOSet_builder.h b/src/QMCWaveFunctions/SPOSet_builder.h index 4dd6119d4..0dc073c73 100644 --- a/src/QMCWaveFunctions/SPOSet_builder.h +++ b/src/QMCWaveFunctions/SPOSet_builder.h @@ -16,19 +16,18 @@ namespace qmcplusplus { - /// build the einspline SPOSet. SPOSet* build_SPOSet(bool useRef, - int nx, int ny, int nz, - int num_splines, int nblocks, - const Tensor &lattice_b, + int nx, + int ny, + int nz, + int num_splines, + int nblocks, + const Tensor& lattice_b, bool init_random = true); /// build the einspline SPOSet as a view of the main one. -SPOSet* build_SPOSet_view(bool useRef, const SPOSet* SPOSet_main, - int team_size, int member_id); +SPOSet* build_SPOSet_view(bool useRef, const SPOSet* SPOSet_main, int team_size, int member_id); -} +} // namespace qmcplusplus #endif - - diff --git a/src/QMCWaveFunctions/WaveFunction.cpp b/src/QMCWaveFunctions/WaveFunction.cpp index d0152e549..d5400d2ff 100644 --- a/src/QMCWaveFunctions/WaveFunction.cpp +++ b/src/QMCWaveFunctions/WaveFunction.cpp @@ -30,33 +30,35 @@ namespace qmcplusplus { - enum WaveFunctionTimers { Timer_Det, Timer_GL, }; -TimerNameLevelList_t WaveFunctionTimerNames = { - {Timer_Det, "Determinant", timer_level_fine}, - {Timer_GL, "Kinetic Energy", timer_level_coarse} -}; +TimerNameLevelList_t WaveFunctionTimerNames = + {{Timer_Det, "Determinant", timer_level_fine}, {Timer_GL, "Kinetic Energy", timer_level_coarse}}; -void build_WaveFunction(bool useRef, WaveFunction &WF, ParticleSet &ions, ParticleSet &els, const RandomGenerator &RNG, bool enableJ3) +void build_WaveFunction(bool useRef, + WaveFunction& WF, + ParticleSet& ions, + ParticleSet& els, + const RandomGenerator& RNG, + bool enableJ3) { using valT = WaveFunction::valT; using posT = WaveFunction::posT; - if(WF.Is_built) + if (WF.Is_built) { app_log() << "The wavefunction was built before!" << std::endl; return; } - const int nelup = els.getTotalNum()/2; + const int nelup = els.getTotalNum() / 2; - if(useRef) + if (useRef) { using J1OrbType = miniqmcreference::OneBodyJastrowRef>; using J2OrbType = miniqmcreference::TwoBodyJastrowRef>; @@ -71,24 +73,24 @@ void build_WaveFunction(bool useRef, WaveFunction &WF, ParticleSet &ions, Partic WF.ei_TableID = els.addTable(ions, DT_SOA); // determinant component - WF.nelup = nelup; + WF.nelup = nelup; WF.Det_up = new DetType(nelup, RNG, 0); - WF.Det_dn = new DetType(els.getTotalNum()-nelup, RNG, nelup); + WF.Det_dn = new DetType(els.getTotalNum() - nelup, RNG, nelup); // J1 component - J1OrbType *J1 = new J1OrbType(ions, els); + J1OrbType* J1 = new J1OrbType(ions, els); buildJ1(*J1, els.Lattice.WignerSeitzRadius); WF.Jastrows.push_back(J1); // J2 component - J2OrbType *J2 = new J2OrbType(els); + J2OrbType* J2 = new J2OrbType(els); buildJ2(*J2, els.Lattice.WignerSeitzRadius); WF.Jastrows.push_back(J2); // J3 component - if(enableJ3) + if (enableJ3) { - J3OrbType *J3 = new J3OrbType(ions, els); + J3OrbType* J3 = new J3OrbType(ions, els); buildJeeI(*J3, els.Lattice.WignerSeitzRadius); WF.Jastrows.push_back(J3); } @@ -108,24 +110,24 @@ void build_WaveFunction(bool useRef, WaveFunction &WF, ParticleSet &ions, Partic WF.ei_TableID = els.addTable(ions, DT_SOA); // determinant component - WF.nelup = nelup; + WF.nelup = nelup; WF.Det_up = new DetType(nelup, RNG, 0); - WF.Det_dn = new DetType(els.getTotalNum()-nelup, RNG, nelup); + WF.Det_dn = new DetType(els.getTotalNum() - nelup, RNG, nelup); // J1 component - J1OrbType *J1 = new J1OrbType(ions, els); + J1OrbType* J1 = new J1OrbType(ions, els); buildJ1(*J1, els.Lattice.WignerSeitzRadius); WF.Jastrows.push_back(J1); // J2 component - J2OrbType *J2 = new J2OrbType(els); + J2OrbType* J2 = new J2OrbType(els); buildJ2(*J2, els.Lattice.WignerSeitzRadius); WF.Jastrows.push_back(J2); // J3 component - if(enableJ3) + if (enableJ3) { - J3OrbType *J3 = new J3OrbType(ions, els); + J3OrbType* J3 = new J3OrbType(ions, els); buildJeeI(*J3, els.Lattice.WignerSeitzRadius); WF.Jastrows.push_back(J3); } @@ -142,7 +144,7 @@ WaveFunction::~WaveFunction() { delete Det_up; delete Det_dn; - for(size_t i=0; iWaveFunctionComponentName, timer_level_fine)); + for (int i = 0; i < Jastrows.size(); i++) + { + jastrow_timers.push_back( + TimerManager.createTimer(Jastrows[i]->WaveFunctionComponentName, timer_level_fine)); } } -void WaveFunction::evaluateLog(ParticleSet &P) +void WaveFunction::evaluateLog(ParticleSet& P) { constexpr valT czero(0); if (FirstTime) { - P.G = czero; - P.L = czero; - LogValue = Det_up -> evaluateLog(P, P.G, P.L); - LogValue += Det_dn -> evaluateLog(P, P.G, P.L); - for(size_t i=0; ievaluateLog(P, P.G, P.L); + LogValue += Det_dn->evaluateLog(P, P.G, P.L); + for (size_t i = 0; i < Jastrows.size(); i++) LogValue += Jastrows[i]->evaluateLog(P, P.G, P.L); FirstTime = false; } } -WaveFunction::posT WaveFunction::evalGrad(ParticleSet &P, int iat) +WaveFunction::posT WaveFunction::evalGrad(ParticleSet& P, int iat) { timers[Timer_Det]->start(); - posT grad_iat = ( iatevalGrad(P, iat) : Det_dn->evalGrad(P, iat) ); + posT grad_iat = (iat < nelup ? Det_up->evalGrad(P, iat) : Det_dn->evalGrad(P, iat)); timers[Timer_Det]->stop(); - for(size_t i=0; istart(); grad_iat += Jastrows[i]->evalGrad(P, iat); jastrow_timers[i]->stop(); @@ -184,15 +189,15 @@ WaveFunction::posT WaveFunction::evalGrad(ParticleSet &P, int iat) return grad_iat; } -WaveFunction::valT WaveFunction::ratioGrad(ParticleSet &P, int iat, - posT &grad) +WaveFunction::valT WaveFunction::ratioGrad(ParticleSet& P, int iat, posT& grad) { timers[Timer_Det]->start(); - grad = valT(0); - valT ratio = ( iatratioGrad(P, iat, grad) : Det_dn->ratioGrad(P, iat, grad) ); + grad = valT(0); + valT ratio = (iat < nelup ? Det_up->ratioGrad(P, iat, grad) : Det_dn->ratioGrad(P, iat, grad)); timers[Timer_Det]->stop(); - for(size_t i=0; istart(); ratio *= Jastrows[i]->ratioGrad(P, iat, grad); jastrow_timers[i]->stop(); @@ -200,14 +205,13 @@ WaveFunction::valT WaveFunction::ratioGrad(ParticleSet &P, int iat, return ratio; } -WaveFunction::valT WaveFunction::ratio(ParticleSet &P, int iat) +WaveFunction::valT WaveFunction::ratio(ParticleSet& P, int iat) { - timers[Timer_Det]->start(); - valT ratio = ( iatratio(P, iat) : Det_dn->ratio(P, iat) ); + valT ratio = (iat < nelup ? Det_up->ratio(P, iat) : Det_dn->ratio(P, iat)); timers[Timer_Det]->stop(); - for(size_t i=0; istart(); ratio *= Jastrows[i]->ratio(P, iat); @@ -216,16 +220,16 @@ WaveFunction::valT WaveFunction::ratio(ParticleSet &P, int iat) return ratio; } -void WaveFunction::acceptMove(ParticleSet &P, int iat) +void WaveFunction::acceptMove(ParticleSet& P, int iat) { timers[Timer_Det]->start(); - if(iatacceptMove(P, iat); else Det_dn->acceptMove(P, iat); timers[Timer_Det]->stop(); - for(size_t i=0; istart(); Jastrows[i]->acceptMove(P, iat); @@ -235,7 +239,7 @@ void WaveFunction::acceptMove(ParticleSet &P, int iat) void WaveFunction::restore(int iat) {} -void WaveFunction::evaluateGL(ParticleSet &P) +void WaveFunction::evaluateGL(ParticleSet& P) { ScopedTimer local_timer(timers[Timer_GL]); @@ -248,7 +252,7 @@ void WaveFunction::evaluateGL(ParticleSet &P) LogValue = Det_up->LogValue + Det_dn->LogValue; timers[Timer_Det]->stop(); - for(size_t i=0; istart(); Jastrows[i]->evaluateGL(P, P.G, P.L); @@ -257,189 +261,193 @@ void WaveFunction::evaluateGL(ParticleSet &P) } } -void WaveFunction::multi_evaluateLog(const std::vector &WF_list, - const std::vector &P_list) const +void WaveFunction::multi_evaluateLog(const std::vector& WF_list, + const std::vector& P_list) const { if (WF_list[0]->FirstTime) { constexpr valT czero(0); - const std::vector G_list(extract_G_list(P_list)); - const std::vector L_list(extract_L_list(P_list)); + const std::vector G_list(extract_G_list(P_list)); + const std::vector L_list(extract_L_list(P_list)); ParticleSet::ParticleValue_t LogValues(P_list.size()); - for(int iw=0; iw up_list(extract_up_list(WF_list)); + std::vector up_list(extract_up_list(WF_list)); Det_up->multi_evaluateLog(up_list, P_list, G_list, L_list, LogValues); - for(int iw=0; iwLogValue = LogValues[iw]; - std::vector dn_list(extract_dn_list(WF_list)); + std::vector dn_list(extract_dn_list(WF_list)); Det_dn->multi_evaluateLog(dn_list, P_list, G_list, L_list, LogValues); - for(int iw=0; iwLogValue += LogValues[iw]; // Jastrow factors - for(size_t i=0; i jas_list(extract_jas_list(WF_list, i)); + std::vector jas_list(extract_jas_list(WF_list, i)); Jastrows[i]->multi_evaluateLog(jas_list, P_list, G_list, L_list, LogValues); - for(int iw=0; iwLogValue += LogValues[iw]; } - for(int iw=0; iwFirstTime = false; } - } -void WaveFunction::multi_evalGrad(const std::vector &WF_list, - const std::vector &P_list, int iat, - std::vector &grad_now) const +void WaveFunction::multi_evalGrad(const std::vector& WF_list, + const std::vector& P_list, + int iat, + std::vector& grad_now) const { timers[Timer_Det]->start(); std::vector grad_now_det(P_list.size()); - if(iat up_list(extract_up_list(WF_list)); + std::vector up_list(extract_up_list(WF_list)); Det_up->multi_evalGrad(up_list, P_list, iat, grad_now_det); } else { - std::vector dn_list(extract_dn_list(WF_list)); + std::vector dn_list(extract_dn_list(WF_list)); Det_dn->multi_evalGrad(dn_list, P_list, iat, grad_now_det); } - for(int iw=0; iwstop(); - for(size_t i=0; istart(); std::vector grad_now_jas(P_list.size()); - std::vector jas_list(extract_jas_list(WF_list, i)); + std::vector jas_list(extract_jas_list(WF_list, i)); Jastrows[i]->multi_evalGrad(jas_list, P_list, iat, grad_now_jas); - for(int iw=0; iwstop(); } } -void WaveFunction::multi_ratioGrad(const std::vector &WF_list, - const std::vector &P_list, int iat, - std::vector &ratios, - std::vector &grad_new) const +void WaveFunction::multi_ratioGrad(const std::vector& WF_list, + const std::vector& P_list, + int iat, + std::vector& ratios, + std::vector& grad_new) const { timers[Timer_Det]->start(); std::vector ratios_det(P_list.size()); - for(int iw=0; iw up_list(extract_up_list(WF_list)); + std::vector up_list(extract_up_list(WF_list)); Det_up->multi_ratioGrad(up_list, P_list, iat, ratios_det, grad_new); } else { - std::vector dn_list(extract_dn_list(WF_list)); + std::vector dn_list(extract_dn_list(WF_list)); Det_dn->multi_ratioGrad(dn_list, P_list, iat, ratios_det, grad_new); } - for(int iw=0; iwstop(); - for(size_t i=0; istart(); std::vector ratios_jas(P_list.size()); - std::vector jas_list(extract_jas_list(WF_list, i)); + std::vector jas_list(extract_jas_list(WF_list, i)); Jastrows[i]->multi_ratioGrad(jas_list, P_list, iat, ratios_jas, grad_new); - for(int iw=0; iwstop(); } } -void WaveFunction::multi_acceptrestoreMove(const std::vector &WF_list, - const std::vector &P_list, - const std::vector &isAccepted, +void WaveFunction::multi_acceptrestoreMove(const std::vector& WF_list, + const std::vector& P_list, + const std::vector& isAccepted, int iat) const { timers[Timer_Det]->start(); - if(iat up_list(extract_up_list(WF_list)); + std::vector up_list(extract_up_list(WF_list)); Det_up->multi_acceptrestoreMove(up_list, P_list, isAccepted, iat); } else { - std::vector dn_list(extract_dn_list(WF_list)); + std::vector dn_list(extract_dn_list(WF_list)); Det_dn->multi_acceptrestoreMove(dn_list, P_list, isAccepted, iat); } timers[Timer_Det]->stop(); - for(size_t i=0; istart(); - std::vector jas_list(extract_jas_list(WF_list, i)); + std::vector jas_list(extract_jas_list(WF_list, i)); Jastrows[i]->multi_acceptrestoreMove(jas_list, P_list, isAccepted, iat); jastrow_timers[i]->stop(); } } -void WaveFunction::multi_evaluateGL(const std::vector &WF_list, - const std::vector &P_list) const +void WaveFunction::multi_evaluateGL(const std::vector& WF_list, + const std::vector& P_list) const { constexpr valT czero(0); - const std::vector G_list(extract_G_list(P_list)); - const std::vector L_list(extract_L_list(P_list)); + const std::vector G_list(extract_G_list(P_list)); + const std::vector L_list(extract_L_list(P_list)); - for(int iw=0; iw up_list(extract_up_list(WF_list)); + std::vector up_list(extract_up_list(WF_list)); Det_up->multi_evaluateGL(up_list, P_list, G_list, L_list); - for(int iw=0; iwLogValue = up_list[iw]->LogValue; - std::vector dn_list(extract_dn_list(WF_list)); + std::vector dn_list(extract_dn_list(WF_list)); Det_dn->multi_evaluateGL(dn_list, P_list, G_list, L_list); - for(int iw=0; iwLogValue += dn_list[iw]->LogValue; // Jastrow factors - for(size_t i=0; i jas_list(extract_jas_list(WF_list, i)); + std::vector jas_list(extract_jas_list(WF_list, i)); Jastrows[i]->multi_evaluateGL(jas_list, P_list, G_list, L_list); - for(int iw=0; iwLogValue += jas_list[iw]->LogValue; } } -const std::vector extract_up_list(const std::vector &WF_list) +const std::vector extract_up_list(const std::vector& WF_list) { - std::vector up_list; - for(auto it=WF_list.begin(); it!=WF_list.end(); it++) + std::vector up_list; + for (auto it = WF_list.begin(); it != WF_list.end(); it++) up_list.push_back((*it)->Det_up); return up_list; } -const std::vector extract_dn_list(const std::vector &WF_list) +const std::vector extract_dn_list(const std::vector& WF_list) { - std::vector dn_list; - for(auto it=WF_list.begin(); it!=WF_list.end(); it++) + std::vector dn_list; + for (auto it = WF_list.begin(); it != WF_list.end(); it++) dn_list.push_back((*it)->Det_dn); return dn_list; } -const std::vector extract_jas_list(const std::vector &WF_list, int jas_id) +const std::vector + extract_jas_list(const std::vector& WF_list, int jas_id) { - std::vector jas_list; - for(auto it=WF_list.begin(); it!=WF_list.end(); it++) + std::vector jas_list; + for (auto it = WF_list.begin(); it != WF_list.end(); it++) jas_list.push_back((*it)->Jastrows[jas_id]); return jas_list; } -} // qmcplusplus +} // namespace qmcplusplus diff --git a/src/QMCWaveFunctions/WaveFunction.h b/src/QMCWaveFunctions/WaveFunction.h index 2e339554b..d32530e59 100644 --- a/src/QMCWaveFunctions/WaveFunction.h +++ b/src/QMCWaveFunctions/WaveFunction.h @@ -36,13 +36,13 @@ namespace qmcplusplus class WaveFunction { using RealType = OHMMS_PRECISION; - using valT = OHMMS_PRECISION; - using posT = TinyVector; + using valT = OHMMS_PRECISION; + using posT = TinyVector; - private: - std::vector Jastrows; - WaveFunctionComponent *Det_up; - WaveFunctionComponent *Det_dn; +private: + std::vector Jastrows; + WaveFunctionComponent* Det_up; + WaveFunctionComponent* Det_dn; valT LogValue; bool FirstTime, Is_built; @@ -51,55 +51,79 @@ class WaveFunction TimerList_t timers; TimerList_t jastrow_timers; - public: - WaveFunction(): FirstTime(true), Is_built(false), nelup(0), ei_TableID(1), Det_up(nullptr), Det_dn(nullptr), LogValue(0.0) {} +public: + WaveFunction() + : FirstTime(true), + Is_built(false), + nelup(0), + ei_TableID(1), + Det_up(nullptr), + Det_dn(nullptr), + LogValue(0.0) + {} ~WaveFunction(); /// operates on a single walker - void evaluateLog(ParticleSet &P); - posT evalGrad(ParticleSet &P, int iat); - valT ratioGrad(ParticleSet &P, int iat, posT &grad); - valT ratio(ParticleSet &P, int iat); - void acceptMove(ParticleSet &P, int iat); + void evaluateLog(ParticleSet& P); + posT evalGrad(ParticleSet& P, int iat); + valT ratioGrad(ParticleSet& P, int iat, posT& grad); + valT ratio(ParticleSet& P, int iat); + void acceptMove(ParticleSet& P, int iat); void restore(int iat); - void evaluateGL(ParticleSet &P); + void evaluateGL(ParticleSet& P); /// operates on multiple walkers - void multi_evaluateLog(const std::vector &WF_list, - const std::vector &P_list) const; - void multi_evalGrad(const std::vector &WF_list, - const std::vector &P_list, int iat, - std::vector &grad_now) const; - void multi_ratioGrad(const std::vector &WF_list, - const std::vector &P_list, int iat, - std::vector &ratio_list, - std::vector &grad_new) const; - void multi_ratio(const std::vector &P_list, int iat) const {}; - void multi_acceptrestoreMove(const std::vector &WF_list, - const std::vector &P_list, - const std::vector &isAccepted, + void multi_evaluateLog(const std::vector& WF_list, + const std::vector& P_list) const; + void multi_evalGrad(const std::vector& WF_list, + const std::vector& P_list, + int iat, + std::vector& grad_now) const; + void multi_ratioGrad(const std::vector& WF_list, + const std::vector& P_list, + int iat, + std::vector& ratio_list, + std::vector& grad_new) const; + void multi_ratio(const std::vector& P_list, int iat) const {}; + void multi_acceptrestoreMove(const std::vector& WF_list, + const std::vector& P_list, + const std::vector& isAccepted, int iat) const; - void multi_evaluateGL(const std::vector &WF_list, - const std::vector &P_list) const; + void multi_evaluateGL(const std::vector& WF_list, + const std::vector& P_list) const; // others - int get_ei_TableID() const {return ei_TableID;} - valT getLogValue() const {return LogValue;} + int get_ei_TableID() const { return ei_TableID; } + valT getLogValue() const { return LogValue; } void setupTimers(); // friends - friend void build_WaveFunction(bool useRef, WaveFunction &WF, ParticleSet &ions, ParticleSet &els, const RandomGenerator &RNG, bool enableJ3); - friend const std::vector extract_up_list(const std::vector &WF_list); - friend const std::vector extract_dn_list(const std::vector &WF_list); - friend const std::vector extract_jas_list(const std::vector &WF_list, int jas_id); + friend void build_WaveFunction(bool useRef, + WaveFunction& WF, + ParticleSet& ions, + ParticleSet& els, + const RandomGenerator& RNG, + bool enableJ3); + friend const std::vector + extract_up_list(const std::vector& WF_list); + friend const std::vector + extract_dn_list(const std::vector& WF_list); + friend const std::vector + extract_jas_list(const std::vector& WF_list, int jas_id); }; -void build_WaveFunction(bool useRef, WaveFunction &WF, ParticleSet &ions, ParticleSet &els, const RandomGenerator &RNG, bool enableJ3); +void build_WaveFunction(bool useRef, + WaveFunction& WF, + ParticleSet& ions, + ParticleSet& els, + const RandomGenerator& RNG, + bool enableJ3); -const std::vector extract_up_list(const std::vector &WF_list); -const std::vector extract_dn_list(const std::vector &WF_list); -const std::vector extract_jas_list(const std::vector &WF_list, int jas_id); +const std::vector extract_up_list(const std::vector& WF_list); +const std::vector extract_dn_list(const std::vector& WF_list); +const std::vector + extract_jas_list(const std::vector& WF_list, int jas_id); -} // qmcplusplus +} // namespace qmcplusplus #endif diff --git a/src/QMCWaveFunctions/WaveFunctionComponent.h b/src/QMCWaveFunctions/WaveFunctionComponent.h index 18a0917b2..4eda3cfb6 100644 --- a/src/QMCWaveFunctions/WaveFunctionComponent.h +++ b/src/QMCWaveFunctions/WaveFunctionComponent.h @@ -34,11 +34,10 @@ */ namespace qmcplusplus { - /// forward declaration of WaveFunctionComponent class WaveFunctionComponent; -typedef WaveFunctionComponent *WaveFunctionComponentPtr; +typedef WaveFunctionComponent* WaveFunctionComponentPtr; /**@defgroup WaveFunctionComponent Wavefunction Component group * @brief Classes which constitute a many-body trial wave function @@ -55,7 +54,6 @@ typedef WaveFunctionComponent *WaveFunctionComponentPtr; */ struct WaveFunctionComponent : public QMCTraits { - /// recasting enum of DistanceTableData to maintain consistency enum { @@ -67,8 +65,8 @@ struct WaveFunctionComponent : public QMCTraits /** enum for a update mode */ enum { - ORB_PBYP_RATIO, /*!< particle-by-particle ratio only */ - ORB_PBYP_ALL, /*!< particle-by-particle, update Value-Gradient-Laplacian */ + ORB_PBYP_RATIO, /*!< particle-by-particle ratio only */ + ORB_PBYP_ALL, /*!< particle-by-particle, update Value-Gradient-Laplacian */ ORB_PBYP_PARTIAL, /*!< particle-by-particle, update Value and Grdient */ ORB_WALKER, /*!< walker update */ ORB_ALLWALKER /*!< all walkers update */ @@ -106,9 +104,13 @@ struct WaveFunctionComponent : public QMCTraits /// default constructor WaveFunctionComponent() - : IsOptimizing(false), Optimizable(true), UpdateMode(ORB_WALKER), - LogValue(0.0), PhaseValue(0.0), WaveFunctionComponentName("WaveFunctionComponent") - { } + : IsOptimizing(false), + Optimizable(true), + UpdateMode(ORB_WALKER), + LogValue(0.0), + PhaseValue(0.0), + WaveFunctionComponentName("WaveFunctionComponent") + {} /// default destructor virtual ~WaveFunctionComponent() {} @@ -121,30 +123,30 @@ struct WaveFunctionComponent : public QMCTraits * @param L Laplacians, \f$\nabla^2\ln\Psi\f$ * */ - virtual RealType evaluateLog(ParticleSet &P, - ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L) = 0; + virtual RealType evaluateLog(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L) = 0; /** return the current gradient for the iat-th particle * @param Pquantum particle set * @param iat particle index * @return the gradient of the iat-th particle */ - virtual GradType evalGrad(ParticleSet &P, int iat) = 0; + virtual GradType evalGrad(ParticleSet& P, int iat) = 0; /** evaluate the ratio of the new to old wavefunction component value * @param P the active ParticleSet * @param iat the index of a particle * @param grad_iat Gradient for the active particle */ - virtual ValueType ratioGrad(ParticleSet &P, int iat, GradType &grad_iat) = 0; + virtual ValueType ratioGrad(ParticleSet& P, int iat, GradType& grad_iat) = 0; /** a move for iat-th particle is accepted. Update the content for the next * moves * @param P target ParticleSet * @param iat index of the particle whose new position was proposed */ - virtual void acceptMove(ParticleSet &P, int iat) = 0; + virtual void acceptMove(ParticleSet& P, int iat) = 0; /** evalaute the ratio of the new to old wavefunction component value *@param P the active ParticleSet @@ -153,7 +155,7 @@ struct WaveFunctionComponent : public QMCTraits * *Specialized for particle-by-particle move. */ - virtual ValueType ratio(ParticleSet &P, int iat) = 0; + virtual ValueType ratio(ParticleSet& P, int iat) = 0; /** compute G and L after the sweep * @param P active ParticleSet @@ -162,69 +164,74 @@ struct WaveFunctionComponent : public QMCTraits * @param fromscratch, recompute internal data if true * */ - virtual void evaluateGL(ParticleSet &P, ParticleSet::ParticleGradient_t &G, - ParticleSet::ParticleLaplacian_t &L, + virtual void evaluateGL(ParticleSet& P, + ParticleSet::ParticleGradient_t& G, + ParticleSet::ParticleLaplacian_t& L, bool fromscratch = false) = 0; /// operates on multiple walkers - virtual void multi_evaluateLog(const std::vector &WFC_list, - const std::vector &P_list, - const std::vector &G_list, - const std::vector &L_list, - ParticleSet::ParticleValue_t &values) + virtual void multi_evaluateLog(const std::vector& WFC_list, + const std::vector& P_list, + const std::vector& G_list, + const std::vector& L_list, + ParticleSet::ParticleValue_t& values) { - #pragma omp parallel for - for(int iw=0; iwevaluateLog(*P_list[iw], *G_list[iw], *L_list[iw]); }; - virtual void multi_evalGrad(const std::vector &WFC_list, - const std::vector &P_list, int iat, - std::vector &grad_now) + virtual void multi_evalGrad(const std::vector& WFC_list, + const std::vector& P_list, + int iat, + std::vector& grad_now) { //#pragma omp parallel for - for(int iw=0; iwevalGrad(*P_list[iw], iat); }; - virtual void multi_ratioGrad(const std::vector &WFC_list, - const std::vector &P_list, int iat, - std::vector &ratios, - std::vector &grad_new) + virtual void multi_ratioGrad(const std::vector& WFC_list, + const std::vector& P_list, + int iat, + std::vector& ratios, + std::vector& grad_new) { - #pragma omp parallel for - for(int iw=0; iwratioGrad(*P_list[iw], iat, grad_new[iw]); }; - virtual void multi_acceptrestoreMove(const std::vector &WFC_list, - const std::vector &P_list, - const std::vector &isAccepted, int iat) + virtual void multi_acceptrestoreMove(const std::vector& WFC_list, + const std::vector& P_list, + const std::vector& isAccepted, + int iat) { - #pragma omp parallel for - for(int iw=0; iwacceptMove(*P_list[iw], iat); + if (isAccepted[iw]) + WFC_list[iw]->acceptMove(*P_list[iw], iat); } }; - virtual void multi_ratio(const std::vector &WFC_list, - const std::vector &P_list, int iat, - ParticleSet::ParticleValue_t &ratio_list) - { - // TODO + virtual void multi_ratio(const std::vector& WFC_list, + const std::vector& P_list, + int iat, + ParticleSet::ParticleValue_t& ratio_list){ + // TODO }; - virtual void multi_evaluateGL(const std::vector &WFC_list, - const std::vector &P_list, - const std::vector &G_list, - const std::vector &L_list, + virtual void multi_evaluateGL(const std::vector& WFC_list, + const std::vector& P_list, + const std::vector& G_list, + const std::vector& L_list, bool fromscratch = false) { - #pragma omp parallel for - for(int iw=0; iwevaluateGL(*P_list[iw], *G_list[iw], *L_list[iw], fromscratch); }; }; -} +} // namespace qmcplusplus #endif diff --git a/src/QMCWaveFunctions/einspline_spo.hpp b/src/QMCWaveFunctions/einspline_spo.hpp index 5c4b5ef9e..449f237c9 100644 --- a/src/QMCWaveFunctions/einspline_spo.hpp +++ b/src/QMCWaveFunctions/einspline_spo.hpp @@ -31,11 +31,11 @@ namespace qmcplusplus { -template +template struct einspline_spo : public SPOSet { /// define the einsplie data object type - using spline_type = typename bspline_traits::SplineType; + using spline_type = typename bspline_traits::SplineType; using vContainer_type = aligned_vector; using gContainer_type = VectorSoAContainer; using hContainer_type = VectorSoAContainer; @@ -59,25 +59,24 @@ struct einspline_spo : public SPOSet /// compute engine MultiBspline compute_engine; - aligned_vector einsplines; + aligned_vector einsplines; aligned_vector psi; aligned_vector grad; aligned_vector hess; /// Timer - NewTimer *timer; + NewTimer* timer; /// default constructor - einspline_spo() - : nBlocks(0), nSplines(0), firstBlock(0), lastBlock(0), Owner(false) + einspline_spo() : nBlocks(0), nSplines(0), firstBlock(0), lastBlock(0), Owner(false) { timer = TimerManager.createTimer("Single-Particle Orbitals", timer_level_fine); } /// disable copy constructor - einspline_spo(const einspline_spo &in) = delete; + einspline_spo(const einspline_spo& in) = delete; /// disable copy operator - einspline_spo &operator=(const einspline_spo &in) = delete; + einspline_spo& operator=(const einspline_spo& in) = delete; /** copy constructor * @param in einspline_spo @@ -86,7 +85,7 @@ struct einspline_spo : public SPOSet * * Create a view of the big object. A simple blocking & padding method. */ - einspline_spo(const einspline_spo &in, int team_size, int member_id) + einspline_spo(const einspline_spo& in, int team_size, int member_id) : Owner(false), Lattice(in.Lattice) { nSplines = in.nSplines; @@ -125,8 +124,7 @@ struct einspline_spo : public SPOSet } // fix for general num_splines - void set(int nx, int ny, int nz, int num_splines, int nblocks, - bool init_random = true) + void set(int nx, int ny, int nz, int num_splines, int nblocks, bool init_random = true) { nSplines = num_splines; nBlocks = nblocks; @@ -141,12 +139,15 @@ struct einspline_spo : public SPOSet PosType end(1); einsplines.resize(nBlocks); RandomGenerator myrandom(11); - Array coef_data(nx+3, ny+3, nz+3); + Array coef_data(nx + 3, ny + 3, nz + 3); for (int i = 0; i < nBlocks; ++i) { - einsplines[i] = myAllocator.createMultiBspline(T(0), start, end, ng, PERIODIC, nSplinesPerBlock); - if (init_random) { - for (int j = 0; j < nSplinesPerBlock; ++j) { + einsplines[i] = + myAllocator.createMultiBspline(T(0), start, end, ng, PERIODIC, nSplinesPerBlock); + if (init_random) + { + for (int j = 0; j < nSplinesPerBlock; ++j) + { // Generate different coefficients for each orbital myrandom.generate_uniform(coef_data.data(), coef_data.size()); myAllocator.setCoefficientsForOneOrbital(j, coef_data, einsplines[i]); @@ -158,7 +159,7 @@ struct einspline_spo : public SPOSet } /** evaluate psi */ - inline void evaluate_v(const PosType &p) + inline void evaluate_v(const PosType& p) { ScopedTimer local_timer(timer); @@ -168,65 +169,84 @@ struct einspline_spo : public SPOSet } /** evaluate psi */ - inline void evaluate_v_pfor(const PosType &p) + inline void evaluate_v_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); - #pragma omp for nowait +#pragma omp for nowait for (int i = 0; i < nBlocks; ++i) compute_engine.evaluate_v(einsplines[i], u[0], u[1], u[2], psi[i].data(), nSplinesPerBlock); } /** evaluate psi, grad and lap */ - inline void evaluate_vgl(const PosType &p) + inline void evaluate_vgl(const PosType& p) { auto u = Lattice.toUnit_floor(p); for (int i = 0; i < nBlocks; ++i) - compute_engine.evaluate_vgl(einsplines[i], u[0], u[1], u[2], - psi[i].data(), grad[i].data(), hess[i].data(), + compute_engine.evaluate_vgl(einsplines[i], + u[0], + u[1], + u[2], + psi[i].data(), + grad[i].data(), + hess[i].data(), nSplinesPerBlock); } /** evaluate psi, grad and lap */ - inline void evaluate_vgl_pfor(const PosType &p) + inline void evaluate_vgl_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); - #pragma omp for nowait +#pragma omp for nowait for (int i = 0; i < nBlocks; ++i) - compute_engine.evaluate_vgl(einsplines[i], u[0], u[1], u[2], - psi[i].data(), grad[i].data(), hess[i].data(), + compute_engine.evaluate_vgl(einsplines[i], + u[0], + u[1], + u[2], + psi[i].data(), + grad[i].data(), + hess[i].data(), nSplinesPerBlock); } /** evaluate psi, grad and hess */ - inline void evaluate_vgh(const PosType &p) + inline void evaluate_vgh(const PosType& p) { ScopedTimer local_timer(timer); auto u = Lattice.toUnit_floor(p); for (int i = 0; i < nBlocks; ++i) - compute_engine.evaluate_vgh(einsplines[i], u[0], u[1], u[2], - psi[i].data(), grad[i].data(), hess[i].data(), + compute_engine.evaluate_vgh(einsplines[i], + u[0], + u[1], + u[2], + psi[i].data(), + grad[i].data(), + hess[i].data(), nSplinesPerBlock); } /** evaluate psi, grad and hess */ - inline void evaluate_vgh_pfor(const PosType &p) + inline void evaluate_vgh_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); - #pragma omp for nowait +#pragma omp for nowait for (int i = 0; i < nBlocks; ++i) - compute_engine.evaluate_vgh(einsplines[i], u[0], u[1], u[2], - psi[i].data(), grad[i].data(), hess[i].data(), + compute_engine.evaluate_vgh(einsplines[i], + u[0], + u[1], + u[2], + psi[i].data(), + grad[i].data(), + hess[i].data(), nSplinesPerBlock); } - void print(std::ostream &os) + void print(std::ostream& os) { - os << "SPO nBlocks=" << nBlocks << " firstBlock=" << firstBlock - << " lastBlock=" << lastBlock << " nSplines=" << nSplines - << " nSplinesPerBlock=" << nSplinesPerBlock << std::endl; + os << "SPO nBlocks=" << nBlocks << " firstBlock=" << firstBlock << " lastBlock=" << lastBlock + << " nSplines=" << nSplines << " nSplinesPerBlock=" << nSplinesPerBlock << std::endl; } }; -} +} // namespace qmcplusplus #endif diff --git a/src/QMCWaveFunctions/einspline_spo_ref.hpp b/src/QMCWaveFunctions/einspline_spo_ref.hpp index 425872c36..7c2c8bfe2 100644 --- a/src/QMCWaveFunctions/einspline_spo_ref.hpp +++ b/src/QMCWaveFunctions/einspline_spo_ref.hpp @@ -31,14 +31,13 @@ namespace miniqmcreference { - using namespace qmcplusplus; -template +template struct einspline_spo_ref : public SPOSet { /// define the einsplie data object type - using spline_type = typename bspline_traits::SplineType; + using spline_type = typename bspline_traits::SplineType; using vContainer_type = aligned_vector; using gContainer_type = VectorSoAContainer; using hContainer_type = VectorSoAContainer; @@ -62,25 +61,24 @@ struct einspline_spo_ref : public SPOSet /// compute engine MultiBsplineRef compute_engine; - aligned_vector einsplines; + aligned_vector einsplines; aligned_vector psi; aligned_vector grad; aligned_vector hess; /// Timer - NewTimer *timer; + NewTimer* timer; /// default constructor - einspline_spo_ref() - : nBlocks(0), nSplines(0), firstBlock(0), lastBlock(0), Owner(false) + einspline_spo_ref() : nBlocks(0), nSplines(0), firstBlock(0), lastBlock(0), Owner(false) { timer = TimerManager.createTimer("Single-Particle Orbitals Ref", timer_level_fine); } /// disable copy constructor - einspline_spo_ref(const einspline_spo_ref &in) = delete; + einspline_spo_ref(const einspline_spo_ref& in) = delete; /// disable copy operator - einspline_spo_ref &operator=(const einspline_spo_ref &in) = delete; + einspline_spo_ref& operator=(const einspline_spo_ref& in) = delete; /** copy constructor * @param in einspline_spo_ref @@ -89,7 +87,7 @@ struct einspline_spo_ref : public SPOSet * * Create a view of the big object. A simple blocking & padding method. */ - einspline_spo_ref(const einspline_spo_ref &in, int team_size, int member_id) + einspline_spo_ref(const einspline_spo_ref& in, int team_size, int member_id) : Owner(false), Lattice(in.Lattice) { nSplines = in.nSplines; @@ -128,8 +126,7 @@ struct einspline_spo_ref : public SPOSet } // fix for general num_splines - void set(int nx, int ny, int nz, int num_splines, int nblocks, - bool init_random = true) + void set(int nx, int ny, int nz, int num_splines, int nblocks, bool init_random = true) { nSplines = num_splines; nBlocks = nblocks; @@ -144,12 +141,15 @@ struct einspline_spo_ref : public SPOSet PosType end(1); einsplines.resize(nBlocks); RandomGenerator myrandom(11); - Array coef_data(nx+3, ny+3, nz+3); + Array coef_data(nx + 3, ny + 3, nz + 3); for (int i = 0; i < nBlocks; ++i) { - einsplines[i] = myAllocator.createMultiBspline(T(0), start, end, ng, PERIODIC, nSplinesPerBlock); - if (init_random) { - for (int j = 0; j < nSplinesPerBlock; ++j) { + einsplines[i] = + myAllocator.createMultiBspline(T(0), start, end, ng, PERIODIC, nSplinesPerBlock); + if (init_random) + { + for (int j = 0; j < nSplinesPerBlock; ++j) + { // Generate different coefficients for each orbital myrandom.generate_uniform(coef_data.data(), coef_data.size()); myAllocator.setCoefficientsForOneOrbital(j, coef_data, einsplines[i]); @@ -161,7 +161,7 @@ struct einspline_spo_ref : public SPOSet } /** evaluate psi */ - inline void evaluate_v(const PosType &p) + inline void evaluate_v(const PosType& p) { ScopedTimer local_timer(timer); @@ -171,65 +171,84 @@ struct einspline_spo_ref : public SPOSet } /** evaluate psi */ - inline void evaluate_v_pfor(const PosType &p) + inline void evaluate_v_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); - #pragma omp for nowait +#pragma omp for nowait for (int i = 0; i < nBlocks; ++i) compute_engine.evaluate_v(einsplines[i], u[0], u[1], u[2], psi[i].data(), nSplinesPerBlock); } /** evaluate psi, grad and lap */ - inline void evaluate_vgl(const PosType &p) + inline void evaluate_vgl(const PosType& p) { auto u = Lattice.toUnit_floor(p); for (int i = 0; i < nBlocks; ++i) - compute_engine.evaluate_vgl(einsplines[i], u[0], u[1], u[2], - psi[i].data(), grad[i].data(), hess[i].data(), + compute_engine.evaluate_vgl(einsplines[i], + u[0], + u[1], + u[2], + psi[i].data(), + grad[i].data(), + hess[i].data(), nSplinesPerBlock); } /** evaluate psi, grad and lap */ - inline void evaluate_vgl_pfor(const PosType &p) + inline void evaluate_vgl_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); - #pragma omp for nowait +#pragma omp for nowait for (int i = 0; i < nBlocks; ++i) - compute_engine.evaluate_vgl(einsplines[i], u[0], u[1], u[2], - psi[i].data(), grad[i].data(), hess[i].data(), + compute_engine.evaluate_vgl(einsplines[i], + u[0], + u[1], + u[2], + psi[i].data(), + grad[i].data(), + hess[i].data(), nSplinesPerBlock); } /** evaluate psi, grad and hess */ - inline void evaluate_vgh(const PosType &p) + inline void evaluate_vgh(const PosType& p) { ScopedTimer local_timer(timer); auto u = Lattice.toUnit_floor(p); for (int i = 0; i < nBlocks; ++i) - compute_engine.evaluate_vgh(einsplines[i], u[0], u[1], u[2], - psi[i].data(), grad[i].data(), hess[i].data(), + compute_engine.evaluate_vgh(einsplines[i], + u[0], + u[1], + u[2], + psi[i].data(), + grad[i].data(), + hess[i].data(), nSplinesPerBlock); } /** evaluate psi, grad and hess */ - inline void evaluate_vgh_pfor(const PosType &p) + inline void evaluate_vgh_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); - #pragma omp for nowait +#pragma omp for nowait for (int i = 0; i < nBlocks; ++i) - compute_engine.evaluate_vgh(einsplines[i], u[0], u[1], u[2], - psi[i].data(), grad[i].data(), hess[i].data(), + compute_engine.evaluate_vgh(einsplines[i], + u[0], + u[1], + u[2], + psi[i].data(), + grad[i].data(), + hess[i].data(), nSplinesPerBlock); } - void print(std::ostream &os) + void print(std::ostream& os) { - os << "SPO nBlocks=" << nBlocks << " firstBlock=" << firstBlock - << " lastBlock=" << lastBlock << " nSplines=" << nSplines - << " nSplinesPerBlock=" << nSplinesPerBlock << std::endl; + os << "SPO nBlocks=" << nBlocks << " firstBlock=" << firstBlock << " lastBlock=" << lastBlock + << " nSplines=" << nSplines << " nSplinesPerBlock=" << nSplinesPerBlock << std::endl; } }; -} +} // namespace miniqmcreference #endif diff --git a/src/Utilities/Clock.h b/src/Utilities/Clock.h index 38c7bf537..b2b3c805e 100644 --- a/src/Utilities/Clock.h +++ b/src/Utilities/Clock.h @@ -64,5 +64,5 @@ inline double cpu_clock() #endif // #endif #endif -} +} // namespace qmcplusplus #endif diff --git a/src/Utilities/Communicate.cpp b/src/Utilities/Communicate.cpp index 89314b618..9af864d6f 100644 --- a/src/Utilities/Communicate.cpp +++ b/src/Utilities/Communicate.cpp @@ -16,7 +16,7 @@ #include #include -Communicate::Communicate(int argc, char **argv) +Communicate::Communicate(int argc, char** argv) { #ifdef HAVE_MPI MPI_Init(&argc, &argv); @@ -36,8 +36,7 @@ Communicate::~Communicate() #endif } -void -Communicate::reduce(int &value) +void Communicate::reduce(int& value) { #ifdef HAVE_MPI int local_value = value; diff --git a/src/Utilities/Communicate.h b/src/Utilities/Communicate.h index 814251b59..1da8db3eb 100644 --- a/src/Utilities/Communicate.h +++ b/src/Utilities/Communicate.h @@ -25,7 +25,7 @@ class Communicate { public: - Communicate(int argc, char **argv); + Communicate(int argc, char** argv); virtual ~Communicate(); @@ -35,7 +35,8 @@ class Communicate #ifdef HAVE_MPI MPI_Comm world() { return m_world; } #endif - void reduce(int &value); + void reduce(int& value); + protected: int m_rank; int m_size; diff --git a/src/Utilities/Configuration.h b/src/Utilities/Configuration.h index e8f428566..34ff9a647 100644 --- a/src/Utilities/Configuration.h +++ b/src/Utilities/Configuration.h @@ -61,7 +61,6 @@ inline omp_int_t omp_get_num_threads() { return 1; } namespace qmcplusplus { - /** traits for the common particle attributes * *This is an alternative to the global typedefs. @@ -135,6 +134,6 @@ struct PtclOnLatticeTraits }; -} +} // namespace qmcplusplus #endif diff --git a/src/Utilities/InfoStream.cpp b/src/Utilities/InfoStream.cpp index 187286370..b112b1148 100644 --- a/src/Utilities/InfoStream.cpp +++ b/src/Utilities/InfoStream.cpp @@ -15,15 +15,18 @@ InfoStream::~InfoStream() { - if (currStream != nullStream) { + if (currStream != nullStream) + { delete nullStream; } - if (ownStream && currStream) { - delete(currStream); + if (ownStream && currStream) + { + delete (currStream); } } -void InfoStream::pause() { +void InfoStream::pause() +{ if (currStream != nullStream) { prevStream = currStream; @@ -31,26 +34,29 @@ void InfoStream::pause() { } } -void InfoStream::resume() { - if (prevStream) { +void InfoStream::resume() +{ + if (prevStream) + { currStream = prevStream; prevStream = NULL; - } + } } -void InfoStream::shutOff() { +void InfoStream::shutOff() +{ prevStream = NULL; currStream = nullStream; } -void InfoStream::redirectToFile(const std::string &fname) { +void InfoStream::redirectToFile(const std::string& fname) +{ currStream = new std::ofstream(fname); - ownStream = true; + ownStream = true; } -void InfoStream::redirectToSameStream(InfoStream &info) +void InfoStream::redirectToSameStream(InfoStream& info) { currStream = &info.getStream(); - ownStream = false; + ownStream = false; } - diff --git a/src/Utilities/InfoStream.h b/src/Utilities/InfoStream.h index d843ed275..89b9ba1d1 100644 --- a/src/Utilities/InfoStream.h +++ b/src/Utilities/InfoStream.h @@ -29,30 +29,26 @@ class InfoStream { public: - InfoStream(std::ostream *output_stream): prevStream(NULL), nullStream(new std::ostream(NULL)), - ownStream(false) { + InfoStream(std::ostream* output_stream) + : prevStream(NULL), nullStream(new std::ostream(NULL)), ownStream(false) + { currStream = output_stream; } - InfoStream(InfoStream &in): prevStream(NULL), nullStream(new std::ostream(NULL)), - ownStream(false) { + InfoStream(InfoStream& in) + : prevStream(NULL), nullStream(new std::ostream(NULL)), ownStream(false) + { redirectToSameStream(in); } ~InfoStream(); - std::ostream &getStream(const std::string &tag = "") { - return *currStream; - } + std::ostream& getStream(const std::string& tag = "") { return *currStream; } - void setStream(std::ostream *output_stream) { - currStream = output_stream; - } + void setStream(std::ostream* output_stream) { currStream = output_stream; } - void flush() { - currStream->flush(); - } + void flush() { currStream->flush(); } /// Stop output (redirect to a null stream) void pause(); @@ -61,31 +57,29 @@ class InfoStream void resume(); /// Open a file and output to that file - void redirectToFile(const std::string &fname); + void redirectToFile(const std::string& fname); /// Copy a stream - void redirectToSameStream(InfoStream &info); + void redirectToSameStream(InfoStream& info); /// Permanently turn off the stream void shutOff(); private: - // Keep track of whether we should delete the stream or not bool ownStream; - std::ostream *currStream; + std::ostream* currStream; // save stream during pause - std::ostream *prevStream; + std::ostream* prevStream; // Created at construction. Used during pause - std::ostream *nullStream; + std::ostream* nullStream; }; template -inline -InfoStream& operator<<(InfoStream& o, const T& val) +inline InfoStream& operator<<(InfoStream& o, const T& val) { o.getStream() << val; return o; diff --git a/src/Utilities/NewTimer.cpp b/src/Utilities/NewTimer.cpp index 1afc27e41..610311051 100644 --- a/src/Utilities/NewTimer.cpp +++ b/src/Utilities/NewTimer.cpp @@ -34,14 +34,13 @@ TimerManagerClass TimerManager; bool timer_max_level_exceeded = false; -void TimerManagerClass::addTimer(NewTimer *t) +void TimerManagerClass::addTimer(NewTimer* t) { #pragma omp critical { if (t->get_name().find(TIMER_STACK_SEPARATOR) != std::string::npos) { - app_log() << "Warning: Timer name (" << t->get_name() - << ") should not contain the character " + app_log() << "Warning: Timer name (" << t->get_name() << ") should not contain the character " << TIMER_STACK_SEPARATOR << std::endl; } @@ -55,8 +54,7 @@ void TimerManagerClass::addTimer(NewTimer *t) max_timers_exceeded = true; app_log() << "Number of timers exceeds limit (" << static_cast(std::numeric_limits::max()) - << "). Adjust timer_id_t in NewTimer.h and recompile." - << std::endl; + << "). Adjust timer_id_t in NewTimer.h and recompile." << std::endl; } else { @@ -73,10 +71,9 @@ void TimerManagerClass::addTimer(NewTimer *t) } } -NewTimer *TimerManagerClass::createTimer(const std::string &myname, - timer_levels mytimer) +NewTimer* TimerManagerClass::createTimer(const std::string& myname, timer_levels mytimer) { - NewTimer *t = new NewTimer(myname, mytimer); + NewTimer* t = new NewTimer(myname, mytimer); addTimer(t); return t; } @@ -96,11 +93,11 @@ void TimerManagerClass::set_timer_threshold(const timer_levels threshold) } } -void TimerManagerClass::collate_flat_profile(FlatProfileData &p) +void TimerManagerClass::collate_flat_profile(FlatProfileData& p) { for (int i = 0; i < TimerList.size(); ++i) { - NewTimer &timer = *TimerList[i]; + NewTimer& timer = *TimerList[i]; nameList_t::iterator it(p.nameList.find(timer.get_name())); if (it == p.nameList.end()) { @@ -123,7 +120,7 @@ struct ProfileData double time; double calls; - ProfileData &operator+=(const ProfileData &pd) + ProfileData& operator+=(const ProfileData& pd) { time += pd.time; calls += pd.calls; @@ -131,7 +128,7 @@ struct ProfileData } }; -int get_level(const std::string &stack_name) +int get_level(const std::string& stack_name) { int level = 0; for (int i = 0; i < stack_name.length(); i++) @@ -144,7 +141,7 @@ int get_level(const std::string &stack_name) return level; } -std::string get_leaf_name(const std::string &stack_name) +std::string get_leaf_name(const std::string& stack_name) { int pos = stack_name.find_last_of(TIMER_STACK_SEPARATOR); if (pos == std::string::npos) @@ -155,13 +152,13 @@ std::string get_leaf_name(const std::string &stack_name) return stack_name.substr(pos + 1, stack_name.length() - pos); } -void TimerManagerClass::get_stack_name_from_id(const StackKey &key, - std::string &stack_name) +void TimerManagerClass::get_stack_name_from_id(const StackKey& key, std::string& stack_name) { for (int i = 0; i < StackKey::max_level; i++) { - std::string &timer_name = timer_id_name[key.get_id(i)]; - if (key.get_id(i) == 0) break; + std::string& timer_name = timer_id_name[key.get_id(i)]; + if (key.get_id(i) == 0) + break; if (i > 0) { stack_name += TIMER_STACK_SEPARATOR; @@ -170,7 +167,7 @@ void TimerManagerClass::get_stack_name_from_id(const StackKey &key, } } -void TimerManagerClass::collate_stack_profile(StackProfileData &p) +void TimerManagerClass::collate_stack_profile(StackProfileData& p) { #ifdef USE_STACK_TIMERS // Put stacks from all timers into one data structure @@ -182,13 +179,12 @@ void TimerManagerClass::collate_stack_profile(StackProfileData &p) std::map all_stacks; for (int i = 0; i < TimerList.size(); ++i) { - NewTimer &timer = *TimerList[i]; - std::map::iterator stack_id_it = - timer.get_per_stack_total_time().begin(); + NewTimer& timer = *TimerList[i]; + std::map::iterator stack_id_it = timer.get_per_stack_total_time().begin(); for (; stack_id_it != timer.get_per_stack_total_time().end(); stack_id_it++) { ProfileData pd; - const StackKey &key = stack_id_it->first; + const StackKey& key = stack_id_it->first; std::string stack_name; get_stack_name_from_id(key, stack_name); pd.time = timer.get_total(key); @@ -200,7 +196,7 @@ void TimerManagerClass::collate_stack_profile(StackProfileData &p) // Fill in the output data structure (but don't compute exclusive time yet) std::map::iterator si = all_stacks.begin(); - int idx = 0; + int idx = 0; for (; si != all_stacks.end(); ++si) { std::string stack_name = si->first; @@ -255,16 +251,17 @@ void TimerManagerClass::print_flat() { #pragma omp master { - std::map::iterator it(p.nameList.begin()), - it_end(p.nameList.end()); + std::map::iterator it(p.nameList.begin()), it_end(p.nameList.end()); while (it != it_end) { int i = (*it).second; // if(callList[i]) //skip zeros printf("%-40s %9.4f %13ld %16.9f %12.6f TIMER\n", - (*it).first.c_str(), p.timeList[i], p.callList[i], - p.timeList[i] / (static_cast(p.callList[i]) + - std::numeric_limits::epsilon()), + (*it).first.c_str(), + p.timeList[i], + p.callList[i], + p.timeList[i] / + (static_cast(p.callList[i]) + std::numeric_limits::epsilon()), p.timeList[i] / static_cast(omp_get_max_threads())); ++it; } @@ -273,7 +270,7 @@ void TimerManagerClass::print_flat() #endif } -void pad_string(const std::string &in, std::string &out, int field_len) +void pad_string(const std::string& in, std::string& out, int field_len) { int len = in.size(); int pad_len = std::max(field_len - len, 0); @@ -310,8 +307,12 @@ void TimerManagerClass::print_stack() std::string timer_name; pad_string("Timer", timer_name, max_name_len); - printf("%s %-9s %-9s %-10s %-13s\n", timer_name.c_str(), - "Inclusive_time", "Exclusive_time", "Calls", "Time_per_call"); + printf("%s %-9s %-9s %-10s %-13s\n", + timer_name.c_str(), + "Inclusive_time", + "Exclusive_time", + "Calls", + "Time_per_call"); for (int i = 0; i < p.names.size(); i++) { std::string stack_name = p.names[i]; @@ -321,17 +322,19 @@ void TimerManagerClass::print_stack() std::string indented_str = indent_str + name; std::string padded_name_str; pad_string(indented_str, padded_name_str, max_name_len); - printf("%s %9.4f %9.4f %13ld %16.9f\n", padded_name_str.c_str(), - p.timeList[i], p.timeExclList[i], p.callList[i], - p.timeList[i] / (static_cast(p.callList[i]) + - std::numeric_limits::epsilon())); + printf("%s %9.4f %9.4f %13ld %16.9f\n", + padded_name_str.c_str(), + p.timeList[i], + p.timeExclList[i], + p.callList[i], + p.timeList[i] / + (static_cast(p.callList[i]) + std::numeric_limits::epsilon())); } } #endif } -XMLNode* -TimerManagerClass::output_timing(XMLDocument &doc) +XMLNode* TimerManagerClass::output_timing(XMLDocument& doc) { XMLNode* timing_root = doc.NewElement("timing"); #if ENABLE_TIMERS @@ -339,32 +342,34 @@ TimerManagerClass::output_timing(XMLDocument &doc) collate_stack_profile(p); - timing_root->InsertEndChild(MakeTextElement(doc,"max_stack_level_exceeded", timer_max_level_exceeded?"yes":"no")); - timing_root->InsertEndChild(MakeTextElement(doc,"max_timers_exceeded", max_timers_exceeded?"yes":"no")); + timing_root->InsertEndChild( + MakeTextElement(doc, "max_stack_level_exceeded", timer_max_level_exceeded ? "yes" : "no")); + timing_root->InsertEndChild( + MakeTextElement(doc, "max_timers_exceeded", max_timers_exceeded ? "yes" : "no")); - std::vector node_stack; + std::vector node_stack; node_stack.push_back(timing_root); - XMLNode *current_root = timing_root; + XMLNode* current_root = timing_root; for (int i = 0; i < p.names.size(); i++) { std::string stack_name = p.names[i]; - int level = get_level(stack_name); - std::string name = get_leaf_name(stack_name); + int level = get_level(stack_name); + std::string name = get_leaf_name(stack_name); - std::string indent_str(2*level, ' '); + std::string indent_str(2 * level, ' '); - XMLNode *timer = doc.NewElement("timer"); + XMLNode* timer = doc.NewElement("timer"); current_root->InsertEndChild(timer); - timer->InsertEndChild(MakeTextElement(doc,"name",name)); - timer->InsertEndChild(MakeTextElement(doc,"time_incl",std::to_string(p.timeList[i]))); - timer->InsertEndChild(MakeTextElement(doc,"time_excl",std::to_string(p.timeExclList[i]))); - timer->InsertEndChild(MakeTextElement(doc,"calls",std::to_string(p.callList[i]))); + timer->InsertEndChild(MakeTextElement(doc, "name", name)); + timer->InsertEndChild(MakeTextElement(doc, "time_incl", std::to_string(p.timeList[i]))); + timer->InsertEndChild(MakeTextElement(doc, "time_excl", std::to_string(p.timeExclList[i]))); + timer->InsertEndChild(MakeTextElement(doc, "calls", std::to_string(p.callList[i]))); int next_level = level; - if (i+1 < p.names.size()) + if (i + 1 < p.names.size()) { - next_level = get_level(p.names[i+1]); + next_level = get_level(p.names[i + 1]); } if (next_level > level) @@ -377,7 +382,7 @@ TimerManagerClass::output_timing(XMLDocument &doc) } if (next_level < level) { - for (int j = 0; j < level-next_level; j++) + for (int j = 0; j < level - next_level; j++) { node_stack.pop_back(); current_root = node_stack.back(); @@ -400,4 +405,4 @@ void NewTimer::set_active_by_timer_threshold(const timer_levels threshold) active = false; } } -} +} // namespace qmcplusplus diff --git a/src/Utilities/NewTimer.h b/src/Utilities/NewTimer.h index 203d2af2f..3c34d1aee 100644 --- a/src/Utilities/NewTimer.h +++ b/src/Utilities/NewTimer.h @@ -133,7 +133,6 @@ class Communicate; namespace qmcplusplus { - class NewTimer; enum timer_levels @@ -155,7 +154,8 @@ extern bool timer_max_level_exceeded; // Key for tracking time per stack. Parametered by size. -template class StackKeyParam +template +class StackKeyParam { public: // The union is for a performance hack @@ -165,7 +165,8 @@ template class StackKeyParam // If timer_id_t is char, there can be up to 254 timers. // N is the number of long ints to store timer nesting levels. // Each N gives (64 bits/long int) / (8 bits/char) = 8 levels - union { + union + { long int long_buckets[N]; timer_id_t short_buckets[sizeof(long int) * N / sizeof(timer_id_t)]; }; @@ -199,7 +200,7 @@ template class StackKeyParam timer_id_t get_id(int idx) const { return short_buckets[idx]; } - bool operator==(const StackKeyParam &rhs) + bool operator==(const StackKeyParam& rhs) { bool same = false; for (int j = 0; j < N; j++) @@ -209,7 +210,7 @@ template class StackKeyParam return same; } - bool operator<(const StackKeyParam &rhs) const + bool operator<(const StackKeyParam& rhs) const { for (int j = 0; j < N; j++) { @@ -228,8 +229,8 @@ typedef StackKeyParam<2> StackKey; class TimerManagerClass { protected: - std::vector TimerList; - std::vector CurrentTimerStack; + std::vector TimerList; + std::vector CurrentTimerStack; timer_levels timer_threshold; timer_id_t max_timer_id; bool max_timers_exceeded; @@ -238,22 +239,20 @@ class TimerManagerClass public: #ifdef USE_VTUNE_TASKS - __itt_domain *task_domain; + __itt_domain* task_domain; #endif TimerManagerClass() - : timer_threshold(timer_level_coarse), max_timer_id(1), - max_timers_exceeded(false) + : timer_threshold(timer_level_coarse), max_timer_id(1), max_timers_exceeded(false) { #ifdef USE_VTUNE_TASKS task_domain = __itt_domain_create("QMCPACK"); #endif } - void addTimer(NewTimer *t); - NewTimer *createTimer(const std::string &myname, - timer_levels mytimer = timer_level_fine); + void addTimer(NewTimer* t); + NewTimer* createTimer(const std::string& myname, timer_levels mytimer = timer_level_fine); - void push_timer(NewTimer *t) + void push_timer(NewTimer* t) { { CurrentTimerStack.push_back(t); @@ -267,9 +266,9 @@ class TimerManagerClass } } - NewTimer *current_timer() + NewTimer* current_timer() { - NewTimer *current = NULL; + NewTimer* current = NULL; if (CurrentTimerStack.size() > 0) { current = CurrentTimerStack.back(); @@ -286,7 +285,7 @@ class TimerManagerClass void print_flat(); void print_stack(); - XMLNode* output_timing(XMLDocument &doc); + XMLNode* output_timing(XMLDocument& doc); typedef std::map nameList_t; typedef std::vector timeList_t; @@ -309,14 +308,14 @@ class TimerManagerClass callList_t callList; }; - void collate_flat_profile(FlatProfileData &p); + void collate_flat_profile(FlatProfileData& p); - void collate_stack_profile(StackProfileData &p); + void collate_stack_profile(StackProfileData& p); // void output_timing(Communicate *comm, Libxml2Document &doc, xmlNodePtr // root); - void get_stack_name_from_id(const StackKey &key, std::string &name); + void get_stack_name_from_id(const StackKey& key, std::string& name); }; extern TimerManagerClass TimerManager; @@ -333,8 +332,8 @@ class NewTimer timer_levels timer_level; timer_id_t timer_id; #ifdef USE_STACK_TIMERS - TimerManagerClass *manager; - NewTimer *parent; + TimerManagerClass* manager; + NewTimer* parent; StackKey current_stack_key; std::map per_stack_total_time; @@ -342,7 +341,7 @@ class NewTimer #endif #ifdef USE_VTUNE_TASKS - __itt_string_handle *task_name; + __itt_string_handle* task_name; #endif public: @@ -357,8 +356,7 @@ class NewTimer #ifdef USE_VTUNE_TASKS __itt_id parent_task = __itt_null; - __itt_task_begin(manager->task_domain, __itt_null, parent_task, - task_name); + __itt_task_begin(manager->task_domain, __itt_null, parent_task, task_name); #endif #ifdef USE_STACK_TIMERS @@ -427,30 +425,21 @@ class NewTimer #endif #ifdef USE_STACK_TIMERS - std::map &get_per_stack_total_time() - { - return per_stack_total_time; - } + std::map& get_per_stack_total_time() { return per_stack_total_time; } - StackKey &get_stack_key() { return current_stack_key; } + StackKey& get_stack_key() { return current_stack_key; } #endif inline double get_total() const { return total_time; } #ifdef USE_STACK_TIMERS - inline double get_total(const StackKey &key) - { - return per_stack_total_time[key]; - } + inline double get_total(const StackKey& key) { return per_stack_total_time[key]; } #endif inline long get_num_calls() const { return num_calls; } #ifdef USE_STACK_TIMERS - inline long get_num_calls(const StackKey &key) - { - return per_stack_num_calls[key]; - } + inline long get_num_calls(const StackKey& key) { return per_stack_num_calls[key]; } #endif timer_id_t get_id() const { return timer_id; } @@ -465,12 +454,17 @@ class NewTimer total_time = 0.0; } - NewTimer(const std::string &myname, timer_levels mytimer = timer_level_fine) - : total_time(0.0), num_calls(0), name(myname), active(true), - timer_level(mytimer), timer_id(0) + NewTimer(const std::string& myname, timer_levels mytimer = timer_level_fine) + : total_time(0.0), + num_calls(0), + name(myname), + active(true), + timer_level(mytimer), + timer_id(0) #ifdef USE_STACK_TIMERS , - manager(NULL), parent(NULL) + manager(NULL), + parent(NULL) #endif { #ifdef USE_VTUNE_TASKS @@ -478,13 +472,13 @@ class NewTimer #endif } - void set_name(const std::string &myname) { name = myname; } + void set_name(const std::string& myname) { name = myname; } - void set_active(const bool &is_active) { active = is_active; } + void set_active(const bool& is_active) { active = is_active; } void set_active_by_timer_threshold(const timer_levels threshold); - void set_manager(TimerManagerClass *mymanager) + void set_manager(TimerManagerClass* mymanager) { #ifdef USE_STACK_TIMERS manager = mymanager; @@ -492,9 +486,9 @@ class NewTimer } #ifdef USE_STACK_TIMERS - NewTimer *get_parent() { return parent; } + NewTimer* get_parent() { return parent; } - void set_parent(NewTimer *new_parent) { parent = new_parent; } + void set_parent(NewTimer* new_parent) { parent = new_parent; } #endif }; @@ -502,32 +496,36 @@ class NewTimer class ScopedTimer { public: - ScopedTimer(NewTimer *t) : timer(t) + ScopedTimer(NewTimer* t) : timer(t) { - if (timer) timer->start(); + if (timer) + timer->start(); } ~ScopedTimer() { - if (timer) timer->stop(); + if (timer) + timer->stop(); } private: - NewTimer *timer; + NewTimer* timer; }; // Helpers to make it easier to define a set of timers // See tests/test_timer.cpp for an example -typedef std::vector TimerList_t; +typedef std::vector TimerList_t; -template struct TimerIDName_t +template +struct TimerIDName_t { T id; const std::string name; }; -template struct TimerIDNameLevel_t +template +struct TimerIDNameLevel_t { T id; const std::string name; @@ -536,40 +534,41 @@ template struct TimerIDNameLevel_t // C++ 11 type aliasing #if __cplusplus >= 201103L -template using TimerNameList_t = std::vector>; -template using TimerNameLevelList_t = std::vector>; - -template -void setup_timers(TimerList_t &timers, TimerNameList_t timer_list, +template +using TimerNameList_t = std::vector>; +template +using TimerNameLevelList_t = std::vector>; + +template +void setup_timers(TimerList_t& timers, + TimerNameList_t timer_list, timer_levels timer_level = timer_level_fine) { timers.resize(timer_list.size()); for (int i = 0; i < timer_list.size(); i++) { - timers[timer_list[i].id] = - TimerManager.createTimer(timer_list[i].name, timer_level); + timers[timer_list[i].id] = TimerManager.createTimer(timer_list[i].name, timer_level); } } -template -void setup_timers(TimerList_t &timers, TimerNameLevelList_t timer_list) +template +void setup_timers(TimerList_t& timers, TimerNameLevelList_t timer_list) { timers.resize(timer_list.size()); for (int i = 0; i < timer_list.size(); i++) { - timers[timer_list[i].id] = - TimerManager.createTimer(timer_list[i].name, timer_list[i].level); + timers[timer_list[i].id] = TimerManager.createTimer(timer_list[i].name, timer_list[i].level); } } #endif struct TimerComparator { - inline bool operator()(const NewTimer *a, const NewTimer *b) + inline bool operator()(const NewTimer* a, const NewTimer* b) { return a->get_name() < b->get_name(); } }; -} +} // namespace qmcplusplus #endif diff --git a/src/Utilities/OutputManager.cpp b/src/Utilities/OutputManager.cpp index 6d2bc83d8..22b049a9a 100644 --- a/src/Utilities/OutputManager.cpp +++ b/src/Utilities/OutputManager.cpp @@ -10,7 +10,6 @@ ////////////////////////////////////////////////////////////////////////////////////// - #include @@ -22,29 +21,30 @@ InfoStream infoDebug(&std::cout); OutputManagerClass outputManager(Verbosity::LOW); -void -OutputManagerClass::setVerbosity(Verbosity level) +void OutputManagerClass::setVerbosity(Verbosity level) { global_verbosity_level = level; - if (isActive(Verbosity::DEBUG)) { + if (isActive(Verbosity::DEBUG)) + { infoSummary.resume(); infoLog.resume(); infoDebug.resume(); - } else if (isActive(Verbosity::HIGH)) { + } + else if (isActive(Verbosity::HIGH)) + { infoSummary.resume(); infoLog.resume(); infoDebug.pause(); - } else if (isActive(Verbosity::LOW)) { + } + else if (isActive(Verbosity::LOW)) + { infoSummary.resume(); infoLog.pause(); infoDebug.pause(); } } -bool OutputManagerClass::isActive(Verbosity level) -{ - return level <= global_verbosity_level; -} +bool OutputManagerClass::isActive(Verbosity level) { return level <= global_verbosity_level; } void OutputManagerClass::pause() { @@ -65,4 +65,3 @@ void OutputManagerClass::shutOff() infoError.shutOff(); infoDebug.shutOff(); } - diff --git a/src/Utilities/OutputManager.h b/src/Utilities/OutputManager.h index dac942f64..97c955f58 100644 --- a/src/Utilities/OutputManager.h +++ b/src/Utilities/OutputManager.h @@ -19,8 +19,19 @@ #include -enum class Verbosity {LOW, HIGH, DEBUG}; -enum class LogType {SUMMARY, APP, ERROR, DEBUG}; +enum class Verbosity +{ + LOW, + HIGH, + DEBUG +}; +enum class LogType +{ + SUMMARY, + APP, + ERROR, + DEBUG +}; extern InfoStream infoSummary; extern InfoStream infoLog; @@ -32,24 +43,20 @@ class OutputManagerClass Verbosity global_verbosity_level; public: - OutputManagerClass(Verbosity level=Verbosity::LOW) { setVerbosity(level); } + OutputManagerClass(Verbosity level = Verbosity::LOW) { setVerbosity(level); } void setVerbosity(Verbosity level); bool isActive(Verbosity level); - bool isDebugActive() - { - return isActive(Verbosity::DEBUG); - } + bool isDebugActive() { return isActive(Verbosity::DEBUG); } - bool isHighActive() - { - return isActive(Verbosity::HIGH); - } + bool isHighActive() { return isActive(Verbosity::HIGH); } - std::ostream& getStream(LogType log) { - switch (log) { + std::ostream& getStream(LogType log) + { + switch (log) + { case LogType::SUMMARY: return infoSummary.getStream(); case LogType::APP: @@ -74,17 +81,11 @@ class OutputManagerClass extern OutputManagerClass outputManager; -namespace qmcplusplus { - -inline std::ostream& app_summary() +namespace qmcplusplus { - return outputManager.getStream(LogType::SUMMARY); -} +inline std::ostream& app_summary() { return outputManager.getStream(LogType::SUMMARY); } -inline std::ostream& app_log() -{ - return outputManager.getStream(LogType::APP); -} +inline std::ostream& app_log() { return outputManager.getStream(LogType::APP); } inline std::ostream& app_error() { @@ -98,15 +99,15 @@ inline std::ostream& app_warning() return outputManager.getStream(LogType::ERROR); } -inline std::ostream& app_debug_stream() -{ - return outputManager.getStream(LogType::DEBUG); -} +inline std::ostream& app_debug_stream() { return outputManager.getStream(LogType::DEBUG); } // From https://stackoverflow.com/questions/11826554/standard-no-op-output-stream // If debugging is not active, this skips evaluation of the arguments -#define app_debug if (!outputManager.isDebugActive()) {} else app_debug_stream +#define app_debug \ + if (!outputManager.isDebugActive()) {} \ + else \ + app_debug_stream -}; +}; // namespace qmcplusplus #endif diff --git a/src/Utilities/PooledData.h b/src/Utilities/PooledData.h index 31b86d1d3..b839b6dfc 100644 --- a/src/Utilities/PooledData.h +++ b/src/Utilities/PooledData.h @@ -35,7 +35,8 @@ using std::complex; -template struct PooledData +template +struct PooledData { typedef T value_type; typedef OHMMS_PRECISION_FULL fp_value_type; @@ -111,10 +112,11 @@ template struct PooledData /// return i-th value inline T operator[](size_type i) const { return myData[i]; } /// return i-th value to assign - inline T &operator[](size_type i) { return myData[i]; } + inline T& operator[](size_type i) { return myData[i]; } /*@}*/ - template inline void add(T1 x) + template + inline void add(T1 x) { Current++; myData.push_back(static_cast(x)); @@ -126,63 +128,65 @@ template struct PooledData myData.push_back(x); } - inline void add(std::complex &x) + inline void add(std::complex& x) { Current += 2; myData.push_back(x.real()); myData.push_back(x.imag()); } - template + template inline void add(_InputIterator first, _InputIterator last) { Current += last - first; myData.insert(myData.end(), first, last); } - inline void add(T *first, T *last) + inline void add(T* first, T* last) { Current += last - first; myData.insert(myData.end(), first, last); } - template inline void add(T1 *first, T1 *last) + template + inline void add(T1* first, T1* last) { Current_DP += last - first; myData_DP.insert(myData_DP.end(), first, last); } - inline void add(std::complex *first, std::complex *last) + inline void add(std::complex* first, std::complex* last) { size_type dn = 2 * (last - first); - T *t = reinterpret_cast(first); + T* t = reinterpret_cast(first); myData.insert(myData.end(), t, t + dn); Current += dn; } - template - inline void add(std::complex *first, std::complex *last) + template + inline void add(std::complex* first, std::complex* last) { size_type dn = 2 * (last - first); - T1 *t = reinterpret_cast(first); + T1* t = reinterpret_cast(first); myData_DP.insert(myData_DP.end(), t, t + dn); Current_DP += dn; } - template inline void get(T1 &x) + template + inline void get(T1& x) { x = static_cast(myData[Current++]); } - inline void get(T &x) { x = myData[Current++]; } + inline void get(T& x) { x = myData[Current++]; } - inline void get(std::complex &x) + inline void get(std::complex& x) { x = std::complex(myData[Current], myData[Current + 1]); Current += 2; } - template + template inline void get(_OutputIterator first, _OutputIterator last) { size_type now = Current; @@ -190,21 +194,22 @@ template struct PooledData copy(myData.begin() + now, myData.begin() + Current, first); } - inline void get(T *first, T *last) + inline void get(T* first, T* last) { size_type now = Current; Current += last - first; std::copy(myData.begin() + now, myData.begin() + Current, first); } - template inline void get(T1 *first, T1 *last) + template + inline void get(T1* first, T1* last) { size_type now = Current_DP; Current_DP += last - first; std::copy(myData_DP.begin() + now, myData_DP.begin() + Current_DP, first); } - inline void get(std::complex *first, std::complex *last) + inline void get(std::complex* first, std::complex* last) { while (first != last) { @@ -214,45 +219,45 @@ template struct PooledData } } - template - inline void get(std::complex *first, std::complex *last) + template + inline void get(std::complex* first, std::complex* last) { while (first != last) { - (*first) = - std::complex(myData_DP[Current_DP], myData_DP[Current_DP + 1]); + (*first) = std::complex(myData_DP[Current_DP], myData_DP[Current_DP + 1]); ++first; Current_DP += 2; } } inline void put(T x) { myData[Current++] = x; } - inline void put(std::complex &x) + inline void put(std::complex& x) { myData[Current++] = x.real(); myData[Current++] = x.imag(); } - template + template inline void put(_InputIterator first, _InputIterator last) { copy(first, last, myData.begin() + Current); Current += last - first; } - inline void put(T *first, T *last) + inline void put(T* first, T* last) { std::copy(first, last, myData.begin() + Current); Current += last - first; } - template inline void put(T1 *first, T1 *last) + template + inline void put(T1* first, T1* last) { std::copy(first, last, myData_DP.begin() + Current_DP); Current_DP += last - first; } - inline void put(std::complex *first, std::complex *last) + inline void put(std::complex* first, std::complex* last) { while (first != last) { @@ -262,8 +267,8 @@ template struct PooledData } } - template - inline void put(std::complex *first, std::complex *last) + template + inline void put(std::complex* first, std::complex* last) { while (first != last) { @@ -274,37 +279,39 @@ template struct PooledData } /** return the address of the first element **/ - inline T *data() { return &(myData[0]); } + inline T* data() { return &(myData[0]); } /** return the address of the first DP element **/ - inline fp_value_type *data_DP() { return &(myData_DP[0]); } + inline fp_value_type* data_DP() { return &(myData_DP[0]); } - inline void print(std::ostream &os) + inline void print(std::ostream& os) { copy(myData.begin(), myData.end(), std::ostream_iterator(os, " ")); } - template inline Msg &putMessage(Msg &m) + template + inline Msg& putMessage(Msg& m) { m.Pack(&(myData[0]), myData.size()); m.Pack(&(myData_DP[0]), myData_DP.size()); return m; } - template inline Msg &getMessage(Msg &m) + template + inline Msg& getMessage(Msg& m) { m.Unpack(&(myData[0]), myData.size()); m.Unpack(&(myData_DP[0]), myData_DP.size()); return m; } - inline PooledData &operator+=(const PooledData &s) + inline PooledData& operator+=(const PooledData& s) { for (int i = 0; i < myData.size(); ++i) myData[i] += s[i]; return *this; } - inline PooledData &operator*=(T scale) + inline PooledData& operator*=(T scale) { for (int i = 0; i < myData.size(); ++i) myData[i] *= scale; @@ -313,27 +320,31 @@ template struct PooledData }; /** operator to check if two buffers are identical */ -template -bool operator==(const PooledData &a, const PooledData &b) +template +bool operator==(const PooledData& a, const PooledData& b) { - if (a.size() != b.size()) return false; + if (a.size() != b.size()) + return false; // if(a.Current != b.Current) return false; for (typename PooledData::size_type i = 0; i < a.size(); ++i) { - if (std::abs(a[i] - b[i]) > std::numeric_limits::epsilon()) return false; + if (std::abs(a[i] - b[i]) > std::numeric_limits::epsilon()) + return false; } return true; } /** operator to check if two buffers are different */ -template -bool operator!=(const PooledData &a, const PooledData &b) +template +bool operator!=(const PooledData& a, const PooledData& b) { - if (a.size() != b.size()) return true; + if (a.size() != b.size()) + return true; // if(a.Current != b.Current) return true; for (typename PooledData::size_type i = 0; i < a.size(); ++i) { - if (std::abs(a[i] - b[i]) > std::numeric_limits::epsilon()) return true; + if (std::abs(a[i] - b[i]) > std::numeric_limits::epsilon()) + return true; } return false; } diff --git a/src/Utilities/PrimeNumberSet.h b/src/Utilities/PrimeNumberSet.h index 246ea6739..2c88069b4 100644 --- a/src/Utilities/PrimeNumberSet.h +++ b/src/Utilities/PrimeNumberSet.h @@ -26,12 +26,13 @@ #include /// dummy declaration -template struct PrimeConstants -{ -}; +template +struct PrimeConstants +{}; /// specialization for uint32_t -template <> struct PrimeConstants +template<> +struct PrimeConstants { enum { @@ -42,7 +43,8 @@ template <> struct PrimeConstants }; /// specialization for uint64_t -template <> struct PrimeConstants +template<> +struct PrimeConstants { enum { @@ -54,7 +56,7 @@ template <> struct PrimeConstants /** class to generate prime numbers */ -template +template struct PrimeNumberSet : public PrimeConstants { typedef UIntType result_type; @@ -110,14 +112,13 @@ struct PrimeNumberSet : public PrimeConstants * * For i=[0,n), primes_add[i]=primes[offset+i] */ - inline bool get(UIntType offset, int n, std::vector &primes_add) + inline bool get(UIntType offset, int n, std::vector& primes_add) { offset = offset % max_prime_offset; // roll back // have enough prime numbers, assign them in an array if (n + offset + 1 < primes.size()) { - primes_add.insert(primes_add.end(), primes.begin() + offset, - primes.begin() + offset + n); + primes_add.insert(primes_add.end(), primes.begin() + offset, primes.begin() + offset + n); return true; } UIntType largest = primes.back(); @@ -147,13 +148,12 @@ struct PrimeNumberSet : public PrimeConstants if (n2add) { std::ostringstream o; - o << " PrimeNumberSet::get Failed to generate " << n2add - << " prime numbers among " << n << " requested."; + o << " PrimeNumberSet::get Failed to generate " << n2add << " prime numbers among " << n + << " requested."; APP_ABORT(o.str()); return false; // to make compiler happy } - primes_add.insert(primes_add.end(), primes.begin() + offset, - primes.begin() + offset + n); + primes_add.insert(primes_add.end(), primes.begin() + offset, primes.begin() + offset + n); return true; } }; diff --git a/src/Utilities/RandomGenerator.h b/src/Utilities/RandomGenerator.h index ce1135b00..3c7773091 100644 --- a/src/Utilities/RandomGenerator.h +++ b/src/Utilities/RandomGenerator.h @@ -45,8 +45,8 @@ struct BoxMuller2 { - template - static inline void generate(RNG &rng, double *restrict a, int n) + template + static inline void generate(RNG& rng, double* restrict a, int n) { for (int i = 0; i + 1 < n; i += 2) { @@ -61,8 +61,8 @@ struct BoxMuller2 } } - template - static inline void generate(RNG &rng, float *restrict a, int n) + template + static inline void generate(RNG& rng, float* restrict a, int n) { for (int i = 0; i + 1 < n; i += 2) { @@ -87,7 +87,8 @@ inline uint32_t MakeSeed(int i, int n) #include "Utilities/StdRandom.h" namespace qmcplusplus { -template using RandomGenerator = StdRandom; +template +using RandomGenerator = StdRandom; } #endif diff --git a/src/Utilities/SIMD/Mallocator.hpp b/src/Utilities/SIMD/Mallocator.hpp index fa3ce0a40..197b59e2c 100644 --- a/src/Utilities/SIMD/Mallocator.hpp +++ b/src/Utilities/SIMD/Mallocator.hpp @@ -18,35 +18,48 @@ namespace qmcplusplus { - template - struct Mallocator - { - typedef T value_type; - typedef size_t size_type; - typedef T* pointer; - typedef const T* const_pointer; +template +struct Mallocator +{ + typedef T value_type; + typedef size_t size_type; + typedef T* pointer; + typedef const T* const_pointer; - Mallocator() = default; - template Mallocator(const Mallocator&) {} + Mallocator() = default; + template + Mallocator(const Mallocator&) + {} - template struct rebind { typedef Mallocator other; }; + template + struct rebind + { + typedef Mallocator other; + }; - T* allocate(std::size_t n) { + T* allocate(std::size_t n) + { #if __GLIBC__ == 2 && __GLIBC_MINOR__ >= 16 - return static_cast(aligned_alloc(Align,n*sizeof(T))); + return static_cast(aligned_alloc(Align, n * sizeof(T))); #else - void* pt; - posix_memalign(&pt, Align, n*sizeof(T)); - return static_cast(pt); + void* pt; + posix_memalign(&pt, Align, n * sizeof(T)); + return static_cast(pt); #endif - } - void deallocate(T* p, std::size_t) { free(p); } - }; + } + void deallocate(T* p, std::size_t) { free(p); } +}; - template - bool operator==(const Mallocator&, const Mallocator&) { return Align1==Align2; } - template - bool operator!=(const Mallocator&, const Mallocator&) { return Align1!=Align2; } +template +bool operator==(const Mallocator&, const Mallocator&) +{ + return Align1 == Align2; +} +template +bool operator!=(const Mallocator&, const Mallocator&) +{ + return Align1 != Align2; } +} // namespace qmcplusplus #endif diff --git a/src/Utilities/SIMD/algorithm.hpp b/src/Utilities/SIMD/algorithm.hpp index 76e72699b..0c3c98c58 100644 --- a/src/Utilities/SIMD/algorithm.hpp +++ b/src/Utilities/SIMD/algorithm.hpp @@ -4,7 +4,7 @@ // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // -// File developed by: +// File developed by: // // File created by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp. ////////////////////////////////////////////////////////////////////////////////////// @@ -16,41 +16,41 @@ #ifndef QMCPLUSPLUS_SIMD_ALGORITHM_HPP #define QMCPLUSPLUS_SIMD_ALGORITHM_HPP -namespace qmcplusplus { - - namespace simd - { - - /** simd version of copy_n( InputIt first, Size count, OutputIt result) +namespace qmcplusplus +{ +namespace simd +{ +/** simd version of copy_n( InputIt first, Size count, OutputIt result) * @param first starting address of the input * @param count number of elements to copy * @param result starting address of the output */ - template - inline void copy_n(const T1* restrict first, size_t count, T2* restrict result) - { -//#pragma omp simd - for(size_t i=0; i(first[i]); - } - - template - inline T2 accumulate_n(const T1* restrict in, size_t n, T2 res) - { -#pragma omp simd reduction(+:res) - for(int i=0; i +inline void copy_n(const T1* restrict first, size_t count, T2* restrict result) +{ + //#pragma omp simd + for (size_t i = 0; i < count; ++i) + result[i] = static_cast(first[i]); +} - ///inner product - template - inline T3 inner_product_n(const T1* restrict a, const T2* restrict b, int n, T3 res) - { - for(int i=0; i +inline T2 accumulate_n(const T1* restrict in, size_t n, T2 res) +{ +#pragma omp simd reduction(+ : res) + for (int i = 0; i < n; ++i) + res += in[i]; + return res; +} - } //simd namepsace +///inner product +template +inline T3 inner_product_n(const T1* restrict a, const T2* restrict b, int n, T3 res) +{ + for (int i = 0; i < n; ++i) + res += a[i] * b[i]; + return res; } + +} // namespace simd +} // namespace qmcplusplus #endif diff --git a/src/Utilities/SIMD/allocator.hpp b/src/Utilities/SIMD/allocator.hpp index 1a050b16f..8d3148bc9 100644 --- a/src/Utilities/SIMD/allocator.hpp +++ b/src/Utilities/SIMD/allocator.hpp @@ -4,7 +4,7 @@ // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // -// File developed by: +// File developed by: // // File created by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp. ////////////////////////////////////////////////////////////////////////////////////// @@ -22,22 +22,24 @@ namespace qmcplusplus { - template - using aligned_allocator=qmcplusplus::Mallocator; - template - using aligned_vector = std::vector >; +template +using aligned_allocator = qmcplusplus::Mallocator; +template +using aligned_vector = std::vector>; -} +} // namespace qmcplusplus -template inline size_t getAlignedSize(size_t n) +template +inline size_t getAlignedSize(size_t n) { - constexpr size_t ND=QMC_CLINE/sizeof(T); - return ((n+ND-1)/ND)*ND; + constexpr size_t ND = QMC_CLINE / sizeof(T); + return ((n + ND - 1) / ND) * ND; } -template inline size_t getAlignment() +template +inline size_t getAlignment() { - return QMC_CLINE/sizeof(T); + return QMC_CLINE / sizeof(T); } #endif diff --git a/src/Utilities/SpeciesSet.cpp b/src/Utilities/SpeciesSet.cpp index fd662d746..ee33b393b 100644 --- a/src/Utilities/SpeciesSet.cpp +++ b/src/Utilities/SpeciesSet.cpp @@ -51,7 +51,7 @@ void SpeciesSet::create(unsigned m) } } -int SpeciesSet::addSpecies(const std::string &aname) +int SpeciesSet::addSpecies(const std::string& aname) { int i = findSpecies(aname); // check if the name is registered if (i == TotalNum) @@ -63,12 +63,13 @@ int SpeciesSet::addSpecies(const std::string &aname) return i; // return an index for a species } -int SpeciesSet::addAttribute(const std::string &aname) +int SpeciesSet::addAttribute(const std::string& aname) { int i = 0; while (i < attribName.size()) { - if (attribName[i] == aname) return i; + if (attribName[i] == aname) + return i; i++; } attribName.push_back(aname); @@ -77,18 +78,18 @@ int SpeciesSet::addAttribute(const std::string &aname) return n; } -int SpeciesSet::getAttribute(const std::string &aname) +int SpeciesSet::getAttribute(const std::string& aname) { for (int i = 0; i < attribName.size(); i++) { - if (attribName[i] == aname) return i; + if (attribName[i] == aname) + return i; } return attribName.size(); } -SpeciesSet::SpeciesSet(const SpeciesSet &species) - : TotalNum(species.TotalNum), speciesName(species.speciesName), - attribName(species.attribName) +SpeciesSet::SpeciesSet(const SpeciesSet& species) + : TotalNum(species.TotalNum), speciesName(species.speciesName), attribName(species.attribName) { AttribList_t::const_iterator dit(species.d_attrib.begin()); AttribList_t::const_iterator dit_end(species.d_attrib.end()); @@ -99,7 +100,7 @@ SpeciesSet::SpeciesSet(const SpeciesSet &species) } } -SpeciesSet &SpeciesSet::operator=(const SpeciesSet &species) +SpeciesSet& SpeciesSet::operator=(const SpeciesSet& species) { if (this != &species) { diff --git a/src/Utilities/SpeciesSet.h b/src/Utilities/SpeciesSet.h index b2df48823..ac9250832 100644 --- a/src/Utilities/SpeciesSet.h +++ b/src/Utilities/SpeciesSet.h @@ -28,11 +28,10 @@ */ class SpeciesSet { - public: typedef double Scalar_t; typedef std::vector SpeciesAttrib_t; - typedef std::vector AttribList_t; + typedef std::vector AttribList_t; //! The number of species unsigned TotalNum; @@ -49,9 +48,9 @@ class SpeciesSet //! Constructor SpeciesSet(); - SpeciesSet(const SpeciesSet &species); + SpeciesSet(const SpeciesSet& species); - SpeciesSet &operator=(const SpeciesSet &species); + SpeciesSet& operator=(const SpeciesSet& species); //! Destructor virtual ~SpeciesSet(); @@ -70,31 +69,28 @@ class SpeciesSet * @return the index of the species * @brief When a name species does not exist, add a new species */ - int addSpecies(const std::string &aname); + int addSpecies(const std::string& aname); /** * @param aname a unique name of an attribute * @return the index of a new attribute * @brief for a new attribute, allocate the data */ - int addAttribute(const std::string &aname); + int addAttribute(const std::string& aname); /** * @param aname Unique name of the species to be looked up. * @return the index of the species * @brief When a name species does not exist, return attribute.size() */ - int getAttribute(const std::string &aname); + int getAttribute(const std::string& aname); /** * @param i attribute index * @param j species index * @return the value of i-th attribute for the j-th species */ - inline double operator()(int i, int j) const - { - return d_attrib[i]->operator[](j); - } + inline double operator()(int i, int j) const { return d_attrib[i]->operator[](j); } /** * assignment operator @@ -102,7 +98,7 @@ class SpeciesSet * @param j species index * @return the value of i-th attribute for the j-th species */ - inline double &operator()(int i, int j) { return d_attrib[i]->operator[](j); } + inline double& operator()(int i, int j) { return d_attrib[i]->operator[](j); } /** * @param m the number of species to be added @@ -114,29 +110,27 @@ class SpeciesSet * @return an ID for the species with name. * @brief if the input species is not found, add a new species */ - inline int findSpecies(const std::string &name) const + inline int findSpecies(const std::string& name) const { int i = 0; while (i < speciesName.size()) { - if (speciesName[i] == name) return i; + if (speciesName[i] == name) + return i; i++; } return i; } - inline int findAttribute(const std::string &name) const - { - return findIndex(name, attribName); - } + inline int findAttribute(const std::string& name) const { return findIndex(name, attribName); } - inline int findIndex(const std::string &name, - const std::vector &alist) const + inline int findIndex(const std::string& name, const std::vector& alist) const { int i = 0; while (i < alist.size()) { - if (alist[i] == name) return i; + if (alist[i] == name) + return i; i++; } return -1; diff --git a/src/Utilities/StdRandom.h b/src/Utilities/StdRandom.h index 127410c4d..655974879 100644 --- a/src/Utilities/StdRandom.h +++ b/src/Utilities/StdRandom.h @@ -16,7 +16,8 @@ #include #include "Utilities/Configuration.h" -template struct StdRandom +template +struct StdRandom { /// real result type typedef T result_type; @@ -41,42 +42,45 @@ template struct StdRandom /// normal generator normal_distribution_type normal; - StdRandom() - : nContexts(1), myContext(0), baseOffset(0), uniform(T(0), T(1)), - normal(T(0), T(1)) + StdRandom() : nContexts(1), myContext(0), baseOffset(0), uniform(T(0), T(1)), normal(T(0), T(1)) { myRNG.seed(MakeSeed(omp_get_thread_num(), omp_get_num_threads())); } - explicit StdRandom(uint_type iseed) - : nContexts(1), myContext(0), baseOffset(0) + explicit StdRandom(uint_type iseed) : nContexts(1), myContext(0), baseOffset(0) //, uniform(T(0),T(1)), normal(T(0),T(1)) { - if (iseed == 0) iseed = MakeSeed(0, 1); + if (iseed == 0) + iseed = MakeSeed(0, 1); myRNG.seed(iseed); } /** copy constructor */ - template - StdRandom(const StdRandom &rng) - : nContexts(1), myContext(0), baseOffset(0), myRNG(rng.myRNG), - uniform(T(0), T(1)), normal(T(0), T(1)) - { - } + template + StdRandom(const StdRandom& rng) + : nContexts(1), + myContext(0), + baseOffset(0), + myRNG(rng.myRNG), + uniform(T(0), T(1)), + normal(T(0), T(1)) + {} /** initialize the stream */ inline void init(int i, int nstr, int iseed_in, uint_type offset = 1) { - uint_type baseSeed = iseed_in; - myContext = i; - nContexts = nstr; - if (iseed_in <= 0) baseSeed = MakeSeed(i, nstr); - baseOffset = offset; + uint_type baseSeed = iseed_in; + myContext = i; + nContexts = nstr; + if (iseed_in <= 0) + baseSeed = MakeSeed(i, nstr); + baseOffset = offset; myRNG.seed(baseSeed); } - template inline void reset(const StdRandom &rng) + template + inline void reset(const StdRandom& rng) { myRNG = rng; // copy the state } @@ -84,7 +88,7 @@ template struct StdRandom /// get baseOffset inline int offset() const { return baseOffset; } /// assign baseOffset - inline int &offset() { return baseOffset; } + inline int& offset() { return baseOffset; } /// assign seed inline void seed(uint_type aseed) { myRNG.seed(aseed); } @@ -97,16 +101,13 @@ template struct StdRandom inline result_type operator()() { return uniform(myRNG); } /** generate a series of random numbers */ - inline void generate_uniform(T *restrict d, int n) + inline void generate_uniform(T* restrict d, int n) { for (int i = 0; i < n; ++i) - d[i] = uniform(myRNG); + d[i] = uniform(myRNG); } - inline void generate_normal(T *restrict d, int n) - { - BoxMuller2::generate(*this, d, n); - } + inline void generate_normal(T* restrict d, int n) { BoxMuller2::generate(*this, d, n); } /** return a random integer */ diff --git a/src/Utilities/XMLWriter.cpp b/src/Utilities/XMLWriter.cpp index f41fb0608..a438c9ba8 100644 --- a/src/Utilities/XMLWriter.cpp +++ b/src/Utilities/XMLWriter.cpp @@ -20,14 +20,12 @@ namespace qmcplusplus { - -XMLNode * -MakeTextElement(XMLDocument &doc, const std::string &name, const std::string &value) +XMLNode* MakeTextElement(XMLDocument& doc, const std::string& name, const std::string& value) { - XMLNode* name_node = doc.NewElement(name.c_str()); + XMLNode* name_node = doc.NewElement(name.c_str()); XMLText* value_node = doc.NewText(""); value_node->SetValue(value.c_str()); name_node->InsertEndChild(value_node); return name_node; } -} +} // namespace qmcplusplus diff --git a/src/Utilities/XMLWriter.h b/src/Utilities/XMLWriter.h index 5ea5a5aca..a3473ba4c 100644 --- a/src/Utilities/XMLWriter.h +++ b/src/Utilities/XMLWriter.h @@ -24,15 +24,14 @@ namespace qmcplusplus { - using tinyxml2::XMLNode; using tinyxml2::XMLDocument; using tinyxml2::XMLElement; using tinyxml2::XMLText; -XMLNode *MakeTextElement(XMLDocument &doc, const std::string &name, const std::string &value); +XMLNode* MakeTextElement(XMLDocument& doc, const std::string& name, const std::string& value); -} +} // namespace qmcplusplus #endif diff --git a/src/Utilities/qmcpack_version.cpp b/src/Utilities/qmcpack_version.cpp index 589b784a9..a41e2e4a5 100644 --- a/src/Utilities/qmcpack_version.cpp +++ b/src/Utilities/qmcpack_version.cpp @@ -38,7 +38,8 @@ void print_version(bool verbose) app_summary() << "miniqmc git branch: " << QMCPACK_GIT_BRANCH << endl; app_summary() << "miniqmc git commit: " << QMCPACK_GIT_HASH << endl; - if (verbose) { + if (verbose) + { app_summary() << "miniqmc git commit date: " << QMCPACK_GIT_COMMIT_LAST_CHANGED << endl; app_summary() << "miniqmc git commit subject: " << QMCPACK_GIT_COMMIT_SUBJECT << endl; } diff --git a/src/Utilities/tinyxml/tinyxml2.cpp b/src/Utilities/tinyxml/tinyxml2.cpp old mode 100755 new mode 100644 index 012f5803a..d394e4eaa --- a/src/Utilities/tinyxml/tinyxml2.cpp +++ b/src/Utilities/tinyxml/tinyxml2.cpp @@ -23,90 +23,93 @@ distribution. #include "tinyxml2.h" -#include // yes, this one new style header, is in the Android SDK. +#include // yes, this one new style header, is in the Android SDK. #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) -# include -# include +#include +#include #else -# include -# include +#include +#include #endif -#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) - // Microsoft Visual Studio, version 2005 and higher. Not WinCE. - /*int _snprintf_s( +#if defined(_MSC_VER) && (_MSC_VER >= 1400) && (!defined WINCE) +// Microsoft Visual Studio, version 2005 and higher. Not WinCE. +/*int _snprintf_s( char *buffer, size_t sizeOfBuffer, size_t count, const char *format [, argument] ... );*/ - static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) - { - va_list va; - va_start( va, format ); - int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); - va_end( va ); - return result; - } - - static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va ) - { - int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); - return result; - } - - #define TIXML_VSCPRINTF _vscprintf - #define TIXML_SSCANF sscanf_s +static inline int TIXML_SNPRINTF(char* buffer, size_t size, const char* format, ...) +{ + va_list va; + va_start(va, format); + int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va); + va_end(va); + return result; +} + +static inline int TIXML_VSNPRINTF(char* buffer, size_t size, const char* format, va_list va) +{ + int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va); + return result; +} + +#define TIXML_VSCPRINTF _vscprintf +#define TIXML_SSCANF sscanf_s #elif defined _MSC_VER - // Microsoft Visual Studio 2003 and earlier or WinCE - #define TIXML_SNPRINTF _snprintf - #define TIXML_VSNPRINTF _vsnprintf - #define TIXML_SSCANF sscanf - #if (_MSC_VER < 1400 ) && (!defined WINCE) - // Microsoft Visual Studio 2003 and not WinCE. - #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. - #else - // Microsoft Visual Studio 2003 and earlier or WinCE. - static inline int TIXML_VSCPRINTF( const char* format, va_list va ) - { - int len = 512; - for (;;) { - len = len*2; - char* str = new char[len](); - const int required = _vsnprintf(str, len, format, va); - delete[] str; - if ( required != -1 ) { - TIXMLASSERT( required >= 0 ); - len = required; - break; - } - } - TIXMLASSERT( len >= 0 ); - return len; - } - #endif +// Microsoft Visual Studio 2003 and earlier or WinCE +#define TIXML_SNPRINTF _snprintf +#define TIXML_VSNPRINTF _vsnprintf +#define TIXML_SSCANF sscanf +#if (_MSC_VER < 1400) && (!defined WINCE) +// Microsoft Visual Studio 2003 and not WinCE. +#define TIXML_VSCPRINTF \ + _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. #else - // GCC version 3 and higher - //#warning( "Using sn* functions." ) - #define TIXML_SNPRINTF snprintf - #define TIXML_VSNPRINTF vsnprintf - static inline int TIXML_VSCPRINTF( const char* format, va_list va ) - { - int len = vsnprintf( 0, 0, format, va ); - TIXMLASSERT( len >= 0 ); - return len; - } - #define TIXML_SSCANF sscanf +// Microsoft Visual Studio 2003 and earlier or WinCE. +static inline int TIXML_VSCPRINTF(const char* format, va_list va) +{ + int len = 512; + for (;;) + { + len = len * 2; + char* str = new char[len](); + const int required = _vsnprintf(str, len, format, va); + delete[] str; + if (required != -1) + { + TIXMLASSERT(required >= 0); + len = required; + break; + } + } + TIXMLASSERT(len >= 0); + return len; +} +#endif +#else +// GCC version 3 and higher +//#warning( "Using sn* functions." ) +#define TIXML_SNPRINTF snprintf +#define TIXML_VSNPRINTF vsnprintf +static inline int TIXML_VSCPRINTF(const char* format, va_list va) +{ + int len = vsnprintf(0, 0, format, va); + TIXMLASSERT(len >= 0); + return len; +} +#define TIXML_SSCANF sscanf #endif -static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF -static const char LF = LINE_FEED; -static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out -static const char CR = CARRIAGE_RETURN; -static const char SINGLE_QUOTE = '\''; -static const char DOUBLE_QUOTE = '\"'; +static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF +static const char LF = LINE_FEED; +static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out +static const char CR = CARRIAGE_RETURN; +static const char SINGLE_QUOTE = '\''; +static const char DOUBLE_QUOTE = '\"'; // Bunch of unicode info at: // http://www.unicode.org/faq/utf_bom.html @@ -118,255 +121,280 @@ static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; namespace tinyxml2 { - -struct Entity { - const char* pattern; - int length; - char value; +struct Entity +{ + const char* pattern; + int length; + char value; }; -static const int NUM_ENTITIES = 5; -static const Entity entities[NUM_ENTITIES] = { - { "quot", 4, DOUBLE_QUOTE }, - { "amp", 3, '&' }, - { "apos", 4, SINGLE_QUOTE }, - { "lt", 2, '<' }, - { "gt", 2, '>' } -}; +static const int NUM_ENTITIES = 5; +static const Entity entities[NUM_ENTITIES] = {{"quot", 4, DOUBLE_QUOTE}, + {"amp", 3, '&'}, + {"apos", 4, SINGLE_QUOTE}, + {"lt", 2, '<'}, + {"gt", 2, '>'}}; -StrPair::~StrPair() -{ - Reset(); -} +StrPair::~StrPair() { Reset(); } -void StrPair::TransferTo( StrPair* other ) +void StrPair::TransferTo(StrPair* other) { - if ( this == other ) { - return; - } - // This in effect implements the assignment operator by "moving" - // ownership (as in auto_ptr). + if (this == other) + { + return; + } + // This in effect implements the assignment operator by "moving" + // ownership (as in auto_ptr). - TIXMLASSERT( other != 0 ); - TIXMLASSERT( other->_flags == 0 ); - TIXMLASSERT( other->_start == 0 ); - TIXMLASSERT( other->_end == 0 ); + TIXMLASSERT(other != 0); + TIXMLASSERT(other->_flags == 0); + TIXMLASSERT(other->_start == 0); + TIXMLASSERT(other->_end == 0); - other->Reset(); + other->Reset(); - other->_flags = _flags; - other->_start = _start; - other->_end = _end; + other->_flags = _flags; + other->_start = _start; + other->_end = _end; - _flags = 0; - _start = 0; - _end = 0; + _flags = 0; + _start = 0; + _end = 0; } void StrPair::Reset() { - if ( _flags & NEEDS_DELETE ) { - delete [] _start; - } - _flags = 0; - _start = 0; - _end = 0; + if (_flags & NEEDS_DELETE) + { + delete[] _start; + } + _flags = 0; + _start = 0; + _end = 0; } -void StrPair::SetStr( const char* str, int flags ) +void StrPair::SetStr(const char* str, int flags) { - TIXMLASSERT( str ); - Reset(); - size_t len = strlen( str ); - TIXMLASSERT( _start == 0 ); - _start = new char[ len+1 ]; - memcpy( _start, str, len+1 ); - _end = _start + len; - _flags = flags | NEEDS_DELETE; + TIXMLASSERT(str); + Reset(); + size_t len = strlen(str); + TIXMLASSERT(_start == 0); + _start = new char[len + 1]; + memcpy(_start, str, len + 1); + _end = _start + len; + _flags = flags | NEEDS_DELETE; } -char* StrPair::ParseText( char* p, const char* endTag, int strFlags, int* curLineNumPtr ) +char* StrPair::ParseText(char* p, const char* endTag, int strFlags, int* curLineNumPtr) { - TIXMLASSERT( p ); - TIXMLASSERT( endTag && *endTag ); - TIXMLASSERT(curLineNumPtr); + TIXMLASSERT(p); + TIXMLASSERT(endTag && *endTag); + TIXMLASSERT(curLineNumPtr); - char* start = p; - char endChar = *endTag; - size_t length = strlen( endTag ); + char* start = p; + char endChar = *endTag; + size_t length = strlen(endTag); - // Inner loop of text parsing. - while ( *p ) { - if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { - Set( start, p, strFlags ); - return p + length; - } else if (*p == '\n') { - ++(*curLineNumPtr); - } - ++p; - TIXMLASSERT( p ); + // Inner loop of text parsing. + while (*p) + { + if (*p == endChar && strncmp(p, endTag, length) == 0) + { + Set(start, p, strFlags); + return p + length; } - return 0; + else if (*p == '\n') + { + ++(*curLineNumPtr); + } + ++p; + TIXMLASSERT(p); + } + return 0; } -char* StrPair::ParseName( char* p ) +char* StrPair::ParseName(char* p) { - if ( !p || !(*p) ) { - return 0; - } - if ( !XMLUtil::IsNameStartChar( *p ) ) { - return 0; - } + if (!p || !(*p)) + { + return 0; + } + if (!XMLUtil::IsNameStartChar(*p)) + { + return 0; + } - char* const start = p; + char* const start = p; + ++p; + while (*p && XMLUtil::IsNameChar(*p)) + { ++p; - while ( *p && XMLUtil::IsNameChar( *p ) ) { - ++p; - } + } - Set( start, p, 0 ); - return p; + Set(start, p, 0); + return p; } void StrPair::CollapseWhitespace() { - // Adjusting _start would cause undefined behavior on delete[] - TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 ); - // Trim leading space. - _start = XMLUtil::SkipWhiteSpace( _start, 0 ); - - if ( *_start ) { - const char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while( *p ) { - if ( XMLUtil::IsWhiteSpace( *p )) { - p = XMLUtil::SkipWhiteSpace( p, 0 ); - if ( *p == 0 ) { - break; // don't write to q; this trims the trailing space. - } - *q = ' '; - ++q; - } - *q = *p; - ++q; - ++p; + // Adjusting _start would cause undefined behavior on delete[] + TIXMLASSERT((_flags & NEEDS_DELETE) == 0); + // Trim leading space. + _start = XMLUtil::SkipWhiteSpace(_start, 0); + + if (*_start) + { + const char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while (*p) + { + if (XMLUtil::IsWhiteSpace(*p)) + { + p = XMLUtil::SkipWhiteSpace(p, 0); + if (*p == 0) + { + break; // don't write to q; this trims the trailing space. } - *q = 0; + *q = ' '; + ++q; + } + *q = *p; + ++q; + ++p; } + *q = 0; + } } const char* StrPair::GetStr() { - TIXMLASSERT( _start ); - TIXMLASSERT( _end ); - if ( _flags & NEEDS_FLUSH ) { - *_end = 0; - _flags ^= NEEDS_FLUSH; - - if ( _flags ) { - const char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while( p < _end ) { - if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { - // CR-LF pair becomes LF - // CR alone becomes LF - // LF-CR becomes LF - if ( *(p+1) == LF ) { - p += 2; - } - else { - ++p; - } - *q = LF; - ++q; - } - else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { - if ( *(p+1) == CR ) { - p += 2; - } - else { - ++p; - } - *q = LF; - ++q; - } - else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { - // Entities handled by tinyXML2: - // - special entities in the entity table [in/out] - // - numeric character reference [in] - // 中 or 中 - - if ( *(p+1) == '#' ) { - const int buflen = 10; - char buf[buflen] = { 0 }; - int len = 0; - char* adjusted = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); - if ( adjusted == 0 ) { - *q = *p; - ++p; - ++q; - } - else { - TIXMLASSERT( 0 <= len && len <= buflen ); - TIXMLASSERT( q + len <= adjusted ); - p = adjusted; - memcpy( q, buf, len ); - q += len; - } - } - else { - bool entityFound = false; - for( int i = 0; i < NUM_ENTITIES; ++i ) { - const Entity& entity = entities[i]; - if ( strncmp( p + 1, entity.pattern, entity.length ) == 0 - && *( p + entity.length + 1 ) == ';' ) { - // Found an entity - convert. - *q = entity.value; - ++q; - p += entity.length + 2; - entityFound = true; - break; - } - } - if ( !entityFound ) { - // fixme: treat as error? - ++p; - ++q; - } - } - } - else { - *q = *p; - ++p; - ++q; - } + TIXMLASSERT(_start); + TIXMLASSERT(_end); + if (_flags & NEEDS_FLUSH) + { + *_end = 0; + _flags ^= NEEDS_FLUSH; + + if (_flags) + { + const char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while (p < _end) + { + if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR) + { + // CR-LF pair becomes LF + // CR alone becomes LF + // LF-CR becomes LF + if (*(p + 1) == LF) + { + p += 2; + } + else + { + ++p; + } + *q = LF; + ++q; + } + else if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF) + { + if (*(p + 1) == CR) + { + p += 2; + } + else + { + ++p; + } + *q = LF; + ++q; + } + else if ((_flags & NEEDS_ENTITY_PROCESSING) && *p == '&') + { + // Entities handled by tinyXML2: + // - special entities in the entity table [in/out] + // - numeric character reference [in] + // 中 or 中 + + if (*(p + 1) == '#') + { + const int buflen = 10; + char buf[buflen] = {0}; + int len = 0; + char* adjusted = const_cast(XMLUtil::GetCharacterRef(p, buf, &len)); + if (adjusted == 0) + { + *q = *p; + ++p; + ++q; + } + else + { + TIXMLASSERT(0 <= len && len <= buflen); + TIXMLASSERT(q + len <= adjusted); + p = adjusted; + memcpy(q, buf, len); + q += len; + } + } + else + { + bool entityFound = false; + for (int i = 0; i < NUM_ENTITIES; ++i) + { + const Entity& entity = entities[i]; + if (strncmp(p + 1, entity.pattern, entity.length) == 0 && + *(p + entity.length + 1) == ';') + { + // Found an entity - convert. + *q = entity.value; + ++q; + p += entity.length + 2; + entityFound = true; + break; + } + } + if (!entityFound) + { + // fixme: treat as error? + ++p; + ++q; } - *q = 0; + } } - // The loop below has plenty going on, and this - // is a less useful mode. Break it out. - if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) { - CollapseWhitespace(); + else + { + *q = *p; + ++p; + ++q; } - _flags = (_flags & NEEDS_DELETE); + } + *q = 0; + } + // The loop below has plenty going on, and this + // is a less useful mode. Break it out. + if (_flags & NEEDS_WHITESPACE_COLLAPSING) + { + CollapseWhitespace(); } - TIXMLASSERT( _start ); - return _start; + _flags = (_flags & NEEDS_DELETE); + } + TIXMLASSERT(_start); + return _start; } - - // --------- XMLUtil ----------- // const char* XMLUtil::writeBoolTrue = "true"; @@ -374,1676 +402,1816 @@ const char* XMLUtil::writeBoolFalse = "false"; void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse) { - static const char* defTrue = "true"; - static const char* defFalse = "false"; - - writeBoolTrue = (writeTrue) ? writeTrue : defTrue; - writeBoolFalse = (writeFalse) ? writeFalse : defFalse; -} - - -const char* XMLUtil::ReadBOM( const char* p, bool* bom ) -{ - TIXMLASSERT( p ); - TIXMLASSERT( bom ); - *bom = false; - const unsigned char* pu = reinterpret_cast(p); - // Check for BOM: - if ( *(pu+0) == TIXML_UTF_LEAD_0 - && *(pu+1) == TIXML_UTF_LEAD_1 - && *(pu+2) == TIXML_UTF_LEAD_2 ) { - *bom = true; - p += 3; - } - TIXMLASSERT( p ); - return p; -} - - -void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) -{ - const unsigned long BYTE_MASK = 0xBF; - const unsigned long BYTE_MARK = 0x80; - const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - - if (input < 0x80) { - *length = 1; - } - else if ( input < 0x800 ) { - *length = 2; - } - else if ( input < 0x10000 ) { - *length = 3; - } - else if ( input < 0x200000 ) { - *length = 4; - } - else { - *length = 0; // This code won't convert this correctly anyway. - return; - } - - output += *length; - - // Scary scary fall throughs are annotated with carefully designed comments - // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc - switch (*length) { - case 4: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - //fall through - case 3: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - //fall through - case 2: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - //fall through - case 1: - --output; - *output = (char)(input | FIRST_BYTE_MARK[*length]); - break; - default: - TIXMLASSERT( false ); - } -} - + static const char* defTrue = "true"; + static const char* defFalse = "false"; + + writeBoolTrue = (writeTrue) ? writeTrue : defTrue; + writeBoolFalse = (writeFalse) ? writeFalse : defFalse; +} + + +const char* XMLUtil::ReadBOM(const char* p, bool* bom) +{ + TIXMLASSERT(p); + TIXMLASSERT(bom); + *bom = false; + const unsigned char* pu = reinterpret_cast(p); + // Check for BOM: + if (*(pu + 0) == TIXML_UTF_LEAD_0 && *(pu + 1) == TIXML_UTF_LEAD_1 && *(pu + 2) == TIXML_UTF_LEAD_2) + { + *bom = true; + p += 3; + } + TIXMLASSERT(p); + return p; +} + + +void XMLUtil::ConvertUTF32ToUTF8(unsigned long input, char* output, int* length) +{ + const unsigned long BYTE_MASK = 0xBF; + const unsigned long BYTE_MARK = 0x80; + const unsigned long FIRST_BYTE_MARK[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC}; + + if (input < 0x80) + { + *length = 1; + } + else if (input < 0x800) + { + *length = 2; + } + else if (input < 0x10000) + { + *length = 3; + } + else if (input < 0x200000) + { + *length = 4; + } + else + { + *length = 0; // This code won't convert this correctly anyway. + return; + } + + output += *length; + + // Scary scary fall throughs are annotated with carefully designed comments + // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc + switch (*length) + { + case 4: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 3: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 2: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 1: + --output; + *output = (char)(input | FIRST_BYTE_MARK[*length]); + break; + default: + TIXMLASSERT(false); + } +} + + +const char* XMLUtil::GetCharacterRef(const char* p, char* value, int* length) +{ + // Presume an entity, and pull it out. + *length = 0; + + if (*(p + 1) == '#' && *(p + 2)) + { + unsigned long ucs = 0; + TIXMLASSERT(sizeof(ucs) >= 4); + ptrdiff_t delta = 0; + unsigned mult = 1; + static const char SEMICOLON = ';'; + + if (*(p + 2) == 'x') + { + // Hexadecimal. + const char* q = p + 3; + if (!(*q)) + { + return 0; + } -const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) -{ - // Presume an entity, and pull it out. - *length = 0; + q = strchr(q, SEMICOLON); - if ( *(p+1) == '#' && *(p+2) ) { - unsigned long ucs = 0; - TIXMLASSERT( sizeof( ucs ) >= 4 ); - ptrdiff_t delta = 0; - unsigned mult = 1; - static const char SEMICOLON = ';'; + if (!q) + { + return 0; + } + TIXMLASSERT(*q == SEMICOLON); - if ( *(p+2) == 'x' ) { - // Hexadecimal. - const char* q = p+3; - if ( !(*q) ) { - return 0; - } + delta = q - p; + --q; - q = strchr( q, SEMICOLON ); + while (*q != 'x') + { + unsigned int digit = 0; - if ( !q ) { - return 0; - } - TIXMLASSERT( *q == SEMICOLON ); - - delta = q-p; - --q; - - while ( *q != 'x' ) { - unsigned int digit = 0; - - if ( *q >= '0' && *q <= '9' ) { - digit = *q - '0'; - } - else if ( *q >= 'a' && *q <= 'f' ) { - digit = *q - 'a' + 10; - } - else if ( *q >= 'A' && *q <= 'F' ) { - digit = *q - 'A' + 10; - } - else { - return 0; - } - TIXMLASSERT( digit < 16 ); - TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); - const unsigned int digitScaled = mult * digit; - TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); - ucs += digitScaled; - TIXMLASSERT( mult <= UINT_MAX / 16 ); - mult *= 16; - --q; - } + if (*q >= '0' && *q <= '9') + { + digit = *q - '0'; } - else { - // Decimal. - const char* q = p+2; - if ( !(*q) ) { - return 0; - } + else if (*q >= 'a' && *q <= 'f') + { + digit = *q - 'a' + 10; + } + else if (*q >= 'A' && *q <= 'F') + { + digit = *q - 'A' + 10; + } + else + { + return 0; + } + TIXMLASSERT(digit < 16); + TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT(ucs <= ULONG_MAX - digitScaled); + ucs += digitScaled; + TIXMLASSERT(mult <= UINT_MAX / 16); + mult *= 16; + --q; + } + } + else + { + // Decimal. + const char* q = p + 2; + if (!(*q)) + { + return 0; + } - q = strchr( q, SEMICOLON ); + q = strchr(q, SEMICOLON); - if ( !q ) { - return 0; - } - TIXMLASSERT( *q == SEMICOLON ); - - delta = q-p; - --q; - - while ( *q != '#' ) { - if ( *q >= '0' && *q <= '9' ) { - const unsigned int digit = *q - '0'; - TIXMLASSERT( digit < 10 ); - TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); - const unsigned int digitScaled = mult * digit; - TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); - ucs += digitScaled; - } - else { - return 0; - } - TIXMLASSERT( mult <= UINT_MAX / 10 ); - mult *= 10; - --q; - } + if (!q) + { + return 0; + } + TIXMLASSERT(*q == SEMICOLON); + + delta = q - p; + --q; + + while (*q != '#') + { + if (*q >= '0' && *q <= '9') + { + const unsigned int digit = *q - '0'; + TIXMLASSERT(digit < 10); + TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT(ucs <= ULONG_MAX - digitScaled); + ucs += digitScaled; + } + else + { + return 0; } - // convert the UCS to UTF-8 - ConvertUTF32ToUTF8( ucs, value, length ); - return p + delta + 1; + TIXMLASSERT(mult <= UINT_MAX / 10); + mult *= 10; + --q; + } } - return p+1; + // convert the UCS to UTF-8 + ConvertUTF32ToUTF8(ucs, value, length); + return p + delta + 1; + } + return p + 1; } -void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) +void XMLUtil::ToStr(int v, char* buffer, int bufferSize) { - TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); + TIXML_SNPRINTF(buffer, bufferSize, "%d", v); } -void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) +void XMLUtil::ToStr(unsigned v, char* buffer, int bufferSize) { - TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); + TIXML_SNPRINTF(buffer, bufferSize, "%u", v); } -void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) +void XMLUtil::ToStr(bool v, char* buffer, int bufferSize) { - TIXML_SNPRINTF( buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); + TIXML_SNPRINTF(buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); } /* ToStr() of a number is a very tricky topic. https://github.com/leethomason/tinyxml2/issues/106 */ -void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) +void XMLUtil::ToStr(float v, char* buffer, int bufferSize) { - TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v ); + TIXML_SNPRINTF(buffer, bufferSize, "%.8g", v); } -void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) +void XMLUtil::ToStr(double v, char* buffer, int bufferSize) { - TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v ); + TIXML_SNPRINTF(buffer, bufferSize, "%.17g", v); } void XMLUtil::ToStr(int64_t v, char* buffer, int bufferSize) { - // horrible syntax trick to make the compiler happy about %lld - TIXML_SNPRINTF(buffer, bufferSize, "%lld", (long long)v); + // horrible syntax trick to make the compiler happy about %lld + TIXML_SNPRINTF(buffer, bufferSize, "%lld", (long long)v); } -bool XMLUtil::ToInt( const char* str, int* value ) +bool XMLUtil::ToInt(const char* str, int* value) { - if ( TIXML_SSCANF( str, "%d", value ) == 1 ) { - return true; - } - return false; + if (TIXML_SSCANF(str, "%d", value) == 1) + { + return true; + } + return false; } -bool XMLUtil::ToUnsigned( const char* str, unsigned *value ) +bool XMLUtil::ToUnsigned(const char* str, unsigned* value) { - if ( TIXML_SSCANF( str, "%u", value ) == 1 ) { - return true; - } - return false; + if (TIXML_SSCANF(str, "%u", value) == 1) + { + return true; + } + return false; } -bool XMLUtil::ToBool( const char* str, bool* value ) +bool XMLUtil::ToBool(const char* str, bool* value) { - int ival = 0; - if ( ToInt( str, &ival )) { - *value = (ival==0) ? false : true; - return true; - } - if ( StringEqual( str, "true" ) ) { - *value = true; - return true; - } - else if ( StringEqual( str, "false" ) ) { - *value = false; - return true; - } - return false; + int ival = 0; + if (ToInt(str, &ival)) + { + *value = (ival == 0) ? false : true; + return true; + } + if (StringEqual(str, "true")) + { + *value = true; + return true; + } + else if (StringEqual(str, "false")) + { + *value = false; + return true; + } + return false; } -bool XMLUtil::ToFloat( const char* str, float* value ) +bool XMLUtil::ToFloat(const char* str, float* value) { - if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { - return true; - } - return false; + if (TIXML_SSCANF(str, "%f", value) == 1) + { + return true; + } + return false; } -bool XMLUtil::ToDouble( const char* str, double* value ) +bool XMLUtil::ToDouble(const char* str, double* value) { - if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { - return true; - } - return false; + if (TIXML_SSCANF(str, "%lf", value) == 1) + { + return true; + } + return false; } bool XMLUtil::ToInt64(const char* str, int64_t* value) { - long long v = 0; // horrible syntax trick to make the compiler happy about %lld - if (TIXML_SSCANF(str, "%lld", &v) == 1) { - *value = (int64_t)v; - return true; - } - return false; + long long v = 0; // horrible syntax trick to make the compiler happy about %lld + if (TIXML_SSCANF(str, "%lld", &v) == 1) + { + *value = (int64_t)v; + return true; + } + return false; } -char* XMLDocument::Identify( char* p, XMLNode** node ) +char* XMLDocument::Identify(char* p, XMLNode** node) { - TIXMLASSERT( node ); - TIXMLASSERT( p ); - char* const start = p; - int const startLine = _parseCurLineNum; - p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); - if( !*p ) { - *node = 0; - TIXMLASSERT( p ); - return p; - } - - // These strings define the matching patterns: - static const char* xmlHeader = { "( _commentPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += xmlHeaderLen; - } - else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) { - returnNode = CreateUnlinkedNode( _commentPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += commentHeaderLen; - } - else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) { - XMLText* text = CreateUnlinkedNode( _textPool ); - returnNode = text; - returnNode->_parseLineNum = _parseCurLineNum; - p += cdataHeaderLen; - text->SetCData( true ); - } - else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) { - returnNode = CreateUnlinkedNode( _commentPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += dtdHeaderLen; - } - else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) { - returnNode = CreateUnlinkedNode( _elementPool ); - returnNode->_parseLineNum = _parseCurLineNum; - p += elementHeaderLen; - } - else { - returnNode = CreateUnlinkedNode( _textPool ); - returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character - p = start; // Back it up, all the text counts. - _parseCurLineNum = startLine; - } - - TIXMLASSERT( returnNode ); - TIXMLASSERT( p ); - *node = returnNode; + TIXMLASSERT(node); + TIXMLASSERT(p); + char* const start = p; + int const startLine = _parseCurLineNum; + p = XMLUtil::SkipWhiteSpace(p, &_parseCurLineNum); + if (!*p) + { + *node = 0; + TIXMLASSERT(p); return p; -} - - -bool XMLDocument::Accept( XMLVisitor* visitor ) const -{ - TIXMLASSERT( visitor ); - if ( visitor->VisitEnter( *this ) ) { - for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { - if ( !node->Accept( visitor ) ) { - break; - } - } + } + + // These strings define the matching patterns: + static const char* xmlHeader = {"(_commentPool); + returnNode->_parseLineNum = _parseCurLineNum; + p += xmlHeaderLen; + } + else if (XMLUtil::StringEqual(p, commentHeader, commentHeaderLen)) + { + returnNode = CreateUnlinkedNode(_commentPool); + returnNode->_parseLineNum = _parseCurLineNum; + p += commentHeaderLen; + } + else if (XMLUtil::StringEqual(p, cdataHeader, cdataHeaderLen)) + { + XMLText* text = CreateUnlinkedNode(_textPool); + returnNode = text; + returnNode->_parseLineNum = _parseCurLineNum; + p += cdataHeaderLen; + text->SetCData(true); + } + else if (XMLUtil::StringEqual(p, dtdHeader, dtdHeaderLen)) + { + returnNode = CreateUnlinkedNode(_commentPool); + returnNode->_parseLineNum = _parseCurLineNum; + p += dtdHeaderLen; + } + else if (XMLUtil::StringEqual(p, elementHeader, elementHeaderLen)) + { + returnNode = CreateUnlinkedNode(_elementPool); + returnNode->_parseLineNum = _parseCurLineNum; + p += elementHeaderLen; + } + else + { + returnNode = CreateUnlinkedNode(_textPool); + returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character + p = start; // Back it up, all the text counts. + _parseCurLineNum = startLine; + } + + TIXMLASSERT(returnNode); + TIXMLASSERT(p); + *node = returnNode; + return p; +} + + +bool XMLDocument::Accept(XMLVisitor* visitor) const +{ + TIXMLASSERT(visitor); + if (visitor->VisitEnter(*this)) + { + for (const XMLNode* node = FirstChild(); node; node = node->NextSibling()) + { + if (!node->Accept(visitor)) + { + break; + } } - return visitor->VisitExit( *this ); + } + return visitor->VisitExit(*this); } // --------- XMLNode ----------- // -XMLNode::XMLNode( XMLDocument* doc ) : - _document( doc ), - _parent( 0 ), - _value(), - _parseLineNum( 0 ), - _firstChild( 0 ), _lastChild( 0 ), - _prev( 0 ), _next( 0 ), - _userData( 0 ), - _memPool( 0 ) -{ -} +XMLNode::XMLNode(XMLDocument* doc) + : _document(doc), + _parent(0), + _value(), + _parseLineNum(0), + _firstChild(0), + _lastChild(0), + _prev(0), + _next(0), + _userData(0), + _memPool(0) +{} XMLNode::~XMLNode() { - DeleteChildren(); - if ( _parent ) { - _parent->Unlink( this ); - } + DeleteChildren(); + if (_parent) + { + _parent->Unlink(this); + } } -const char* XMLNode::Value() const +const char* XMLNode::Value() const { - // Edge case: XMLDocuments don't have a Value. Return null. - if ( this->ToDocument() ) - return 0; - return _value.GetStr(); + // Edge case: XMLDocuments don't have a Value. Return null. + if (this->ToDocument()) + return 0; + return _value.GetStr(); } -void XMLNode::SetValue( const char* str, bool staticMem ) +void XMLNode::SetValue(const char* str, bool staticMem) { - if ( staticMem ) { - _value.SetInternedStr( str ); - } - else { - _value.SetStr( str ); - } + if (staticMem) + { + _value.SetInternedStr(str); + } + else + { + _value.SetStr(str); + } } XMLNode* XMLNode::DeepClone(XMLDocument* target) const { - XMLNode* clone = this->ShallowClone(target); - if (!clone) return 0; + XMLNode* clone = this->ShallowClone(target); + if (!clone) + return 0; - for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) { - XMLNode* childClone = child->DeepClone(target); - TIXMLASSERT(childClone); - clone->InsertEndChild(childClone); - } - return clone; + for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) + { + XMLNode* childClone = child->DeepClone(target); + TIXMLASSERT(childClone); + clone->InsertEndChild(childClone); + } + return clone; } void XMLNode::DeleteChildren() { - while( _firstChild ) { - TIXMLASSERT( _lastChild ); - DeleteChild( _firstChild ); - } - _firstChild = _lastChild = 0; + while (_firstChild) + { + TIXMLASSERT(_lastChild); + DeleteChild(_firstChild); + } + _firstChild = _lastChild = 0; } -void XMLNode::Unlink( XMLNode* child ) +void XMLNode::Unlink(XMLNode* child) { - TIXMLASSERT( child ); - TIXMLASSERT( child->_document == _document ); - TIXMLASSERT( child->_parent == this ); - if ( child == _firstChild ) { - _firstChild = _firstChild->_next; - } - if ( child == _lastChild ) { - _lastChild = _lastChild->_prev; - } + TIXMLASSERT(child); + TIXMLASSERT(child->_document == _document); + TIXMLASSERT(child->_parent == this); + if (child == _firstChild) + { + _firstChild = _firstChild->_next; + } + if (child == _lastChild) + { + _lastChild = _lastChild->_prev; + } - if ( child->_prev ) { - child->_prev->_next = child->_next; - } - if ( child->_next ) { - child->_next->_prev = child->_prev; - } - child->_next = 0; - child->_prev = 0; - child->_parent = 0; + if (child->_prev) + { + child->_prev->_next = child->_next; + } + if (child->_next) + { + child->_next->_prev = child->_prev; + } + child->_next = 0; + child->_prev = 0; + child->_parent = 0; } -void XMLNode::DeleteChild( XMLNode* node ) +void XMLNode::DeleteChild(XMLNode* node) { - TIXMLASSERT( node ); - TIXMLASSERT( node->_document == _document ); - TIXMLASSERT( node->_parent == this ); - Unlink( node ); - TIXMLASSERT(node->_prev == 0); - TIXMLASSERT(node->_next == 0); - TIXMLASSERT(node->_parent == 0); - DeleteNode( node ); + TIXMLASSERT(node); + TIXMLASSERT(node->_document == _document); + TIXMLASSERT(node->_parent == this); + Unlink(node); + TIXMLASSERT(node->_prev == 0); + TIXMLASSERT(node->_next == 0); + TIXMLASSERT(node->_parent == 0); + DeleteNode(node); } -XMLNode* XMLNode::InsertEndChild( XMLNode* addThis ) +XMLNode* XMLNode::InsertEndChild(XMLNode* addThis) { - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - InsertChildPreamble( addThis ); + TIXMLASSERT(addThis); + if (addThis->_document != _document) + { + TIXMLASSERT(false); + return 0; + } + InsertChildPreamble(addThis); + + if (_lastChild) + { + TIXMLASSERT(_firstChild); + TIXMLASSERT(_lastChild->_next == 0); + _lastChild->_next = addThis; + addThis->_prev = _lastChild; + _lastChild = addThis; + + addThis->_next = 0; + } + else + { + TIXMLASSERT(_firstChild == 0); + _firstChild = _lastChild = addThis; + + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; +} + + +XMLNode* XMLNode::InsertFirstChild(XMLNode* addThis) +{ + TIXMLASSERT(addThis); + if (addThis->_document != _document) + { + TIXMLASSERT(false); + return 0; + } + InsertChildPreamble(addThis); - if ( _lastChild ) { - TIXMLASSERT( _firstChild ); - TIXMLASSERT( _lastChild->_next == 0 ); - _lastChild->_next = addThis; - addThis->_prev = _lastChild; - _lastChild = addThis; + if (_firstChild) + { + TIXMLASSERT(_lastChild); + TIXMLASSERT(_firstChild->_prev == 0); - addThis->_next = 0; - } - else { - TIXMLASSERT( _firstChild == 0 ); - _firstChild = _lastChild = addThis; + _firstChild->_prev = addThis; + addThis->_next = _firstChild; + _firstChild = addThis; - addThis->_prev = 0; - addThis->_next = 0; - } - addThis->_parent = this; - return addThis; + addThis->_prev = 0; + } + else + { + TIXMLASSERT(_lastChild == 0); + _firstChild = _lastChild = addThis; + + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; } -XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis ) +XMLNode* XMLNode::InsertAfterChild(XMLNode* afterThis, XMLNode* addThis) { - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - InsertChildPreamble( addThis ); - - if ( _firstChild ) { - TIXMLASSERT( _lastChild ); - TIXMLASSERT( _firstChild->_prev == 0 ); - - _firstChild->_prev = addThis; - addThis->_next = _firstChild; - _firstChild = addThis; + TIXMLASSERT(addThis); + if (addThis->_document != _document) + { + TIXMLASSERT(false); + return 0; + } - addThis->_prev = 0; - } - else { - TIXMLASSERT( _lastChild == 0 ); - _firstChild = _lastChild = addThis; + TIXMLASSERT(afterThis); - addThis->_prev = 0; - addThis->_next = 0; - } - addThis->_parent = this; + if (afterThis->_parent != this) + { + TIXMLASSERT(false); + return 0; + } + if (afterThis == addThis) + { + // Current state: BeforeThis -> AddThis -> OneAfterAddThis + // Now AddThis must disappear from it's location and then + // reappear between BeforeThis and OneAfterAddThis. + // So just leave it where it is. return addThis; + } + + if (afterThis->_next == 0) + { + // The last node or the only node. + return InsertEndChild(addThis); + } + InsertChildPreamble(addThis); + addThis->_prev = afterThis; + addThis->_next = afterThis->_next; + afterThis->_next->_prev = addThis; + afterThis->_next = addThis; + addThis->_parent = this; + return addThis; } -XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ) +const XMLElement* XMLNode::FirstChildElement(const char* name) const { - TIXMLASSERT( addThis ); - if ( addThis->_document != _document ) { - TIXMLASSERT( false ); - return 0; - } - - TIXMLASSERT( afterThis ); - - if ( afterThis->_parent != this ) { - TIXMLASSERT( false ); - return 0; - } - if ( afterThis == addThis ) { - // Current state: BeforeThis -> AddThis -> OneAfterAddThis - // Now AddThis must disappear from it's location and then - // reappear between BeforeThis and OneAfterAddThis. - // So just leave it where it is. - return addThis; - } - - if ( afterThis->_next == 0 ) { - // The last node or the only node. - return InsertEndChild( addThis ); + for (const XMLNode* node = _firstChild; node; node = node->_next) + { + const XMLElement* element = node->ToElementWithName(name); + if (element) + { + return element; } - InsertChildPreamble( addThis ); - addThis->_prev = afterThis; - addThis->_next = afterThis->_next; - afterThis->_next->_prev = addThis; - afterThis->_next = addThis; - addThis->_parent = this; - return addThis; + } + return 0; } - - -const XMLElement* XMLNode::FirstChildElement( const char* name ) const +const XMLElement* XMLNode::LastChildElement(const char* name) const { - for( const XMLNode* node = _firstChild; node; node = node->_next ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; - } + for (const XMLNode* node = _lastChild; node; node = node->_prev) + { + const XMLElement* element = node->ToElementWithName(name); + if (element) + { + return element; } - return 0; + } + return 0; } -const XMLElement* XMLNode::LastChildElement( const char* name ) const +const XMLElement* XMLNode::NextSiblingElement(const char* name) const { - for( const XMLNode* node = _lastChild; node; node = node->_prev ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; - } + for (const XMLNode* node = _next; node; node = node->_next) + { + const XMLElement* element = node->ToElementWithName(name); + if (element) + { + return element; } - return 0; + } + return 0; } -const XMLElement* XMLNode::NextSiblingElement( const char* name ) const +const XMLElement* XMLNode::PreviousSiblingElement(const char* name) const { - for( const XMLNode* node = _next; node; node = node->_next ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; - } + for (const XMLNode* node = _prev; node; node = node->_prev) + { + const XMLElement* element = node->ToElementWithName(name); + if (element) + { + return element; + } + } + return 0; +} + + +char* XMLNode::ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) +{ + // This is a recursive method, but thinking about it "at the current level" + // it is a pretty simple flat list: + // + // + // + // With a special case: + // + // + // + // + // Where the closing element (/foo) *must* be the next thing after the opening + // element, and the names must match. BUT the tricky bit is that the closing + // element will be read by the child. + // + // 'endTag' is the end tag for this node, it is returned by a call to a child. + // 'parentEnd' is the end tag for the parent, which is filled in and returned. + + while (p && *p) + { + XMLNode* node = 0; + + p = _document->Identify(p, &node); + TIXMLASSERT(p); + if (node == 0) + { + break; } - return 0; -} + int initialLineNum = node->_parseLineNum; -const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const -{ - for( const XMLNode* node = _prev; node; node = node->_prev ) { - const XMLElement* element = node->ToElementWithName( name ); - if ( element ) { - return element; - } + StrPair endTag; + p = node->ParseDeep(p, &endTag, curLineNumPtr); + if (!p) + { + DeleteNode(node); + if (!_document->Error()) + { + _document->SetError(XML_ERROR_PARSING, initialLineNum, 0); + } + break; } - return 0; -} - -char* XMLNode::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) -{ - // This is a recursive method, but thinking about it "at the current level" - // it is a pretty simple flat list: - // - // - // - // With a special case: - // - // - // - // - // Where the closing element (/foo) *must* be the next thing after the opening - // element, and the names must match. BUT the tricky bit is that the closing - // element will be read by the child. - // - // 'endTag' is the end tag for this node, it is returned by a call to a child. - // 'parentEnd' is the end tag for the parent, which is filled in and returned. - - while( p && *p ) { - XMLNode* node = 0; - - p = _document->Identify( p, &node ); - TIXMLASSERT( p ); - if ( node == 0 ) { + XMLDeclaration* decl = node->ToDeclaration(); + if (decl) + { + // Declarations are only allowed at document level + bool wellLocated = (ToDocument() != 0); + if (wellLocated) + { + // Multiple declarations are allowed but all declarations + // must occur before anything else + for (const XMLNode* existingNode = _document->FirstChild(); existingNode; + existingNode = existingNode->NextSibling()) + { + if (!existingNode->ToDeclaration()) + { + wellLocated = false; break; + } } - - int initialLineNum = node->_parseLineNum; - - StrPair endTag; - p = node->ParseDeep( p, &endTag, curLineNumPtr ); - if ( !p ) { - DeleteNode( node ); - if ( !_document->Error() ) { - _document->SetError( XML_ERROR_PARSING, initialLineNum, 0); - } - break; + } + if (!wellLocated) + { + _document->SetError(XML_ERROR_PARSING_DECLARATION, + initialLineNum, + "XMLDeclaration value=%s", + decl->Value()); + DeleteNode(node); + break; + } + } + + XMLElement* ele = node->ToElement(); + if (ele) + { + // We read the end tag. Return it to the parent. + if (ele->ClosingType() == XMLElement::CLOSING) + { + if (parentEndTag) + { + ele->_value.TransferTo(parentEndTag); } - - XMLDeclaration* decl = node->ToDeclaration(); - if ( decl ) { - // Declarations are only allowed at document level - bool wellLocated = ( ToDocument() != 0 ); - if ( wellLocated ) { - // Multiple declarations are allowed but all declarations - // must occur before anything else - for ( const XMLNode* existingNode = _document->FirstChild(); existingNode; existingNode = existingNode->NextSibling() ) { - if ( !existingNode->ToDeclaration() ) { - wellLocated = false; - break; - } - } - } - if ( !wellLocated ) { - _document->SetError( XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value()); - DeleteNode( node ); - break; - } + node->_memPool->SetTracked(); // created and then immediately deleted. + DeleteNode(node); + return p; + } + + // Handle an end tag returned to this level. + // And handle a bunch of annoying errors. + bool mismatch = false; + if (endTag.Empty()) + { + if (ele->ClosingType() == XMLElement::OPEN) + { + mismatch = true; } - - XMLElement* ele = node->ToElement(); - if ( ele ) { - // We read the end tag. Return it to the parent. - if ( ele->ClosingType() == XMLElement::CLOSING ) { - if ( parentEndTag ) { - ele->_value.TransferTo( parentEndTag ); - } - node->_memPool->SetTracked(); // created and then immediately deleted. - DeleteNode( node ); - return p; - } - - // Handle an end tag returned to this level. - // And handle a bunch of annoying errors. - bool mismatch = false; - if ( endTag.Empty() ) { - if ( ele->ClosingType() == XMLElement::OPEN ) { - mismatch = true; - } - } - else { - if ( ele->ClosingType() != XMLElement::OPEN ) { - mismatch = true; - } - else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) { - mismatch = true; - } - } - if ( mismatch ) { - _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name()); - DeleteNode( node ); - break; - } + } + else + { + if (ele->ClosingType() != XMLElement::OPEN) + { + mismatch = true; } - InsertEndChild( node ); - } + else if (!XMLUtil::StringEqual(endTag.GetStr(), ele->Name())) + { + mismatch = true; + } + } + if (mismatch) + { + _document->SetError(XML_ERROR_MISMATCHED_ELEMENT, + initialLineNum, + "XMLElement name=%s", + ele->Name()); + DeleteNode(node); + break; + } + } + InsertEndChild(node); + } + return 0; +} + +/*static*/ void XMLNode::DeleteNode(XMLNode* node) +{ + if (node == 0) + { + return; + } + TIXMLASSERT(node->_document); + if (!node->ToDocument()) + { + node->_document->MarkInUse(node); + } + + MemPool* pool = node->_memPool; + node->~XMLNode(); + pool->Free(node); +} + +void XMLNode::InsertChildPreamble(XMLNode* insertThis) const +{ + TIXMLASSERT(insertThis); + TIXMLASSERT(insertThis->_document == _document); + + if (insertThis->_parent) + { + insertThis->_parent->Unlink(insertThis); + } + else + { + insertThis->_document->MarkInUse(insertThis); + insertThis->_memPool->SetTracked(); + } +} + +const XMLElement* XMLNode::ToElementWithName(const char* name) const +{ + const XMLElement* element = this->ToElement(); + if (element == 0) + { return 0; + } + if (name == 0) + { + return element; + } + if (XMLUtil::StringEqual(element->Name(), name)) + { + return element; + } + return 0; } -/*static*/ void XMLNode::DeleteNode( XMLNode* node ) -{ - if ( node == 0 ) { - return; - } - TIXMLASSERT(node->_document); - if (!node->ToDocument()) { - node->_document->MarkInUse(node); - } - - MemPool* pool = node->_memPool; - node->~XMLNode(); - pool->Free( node ); -} - -void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const -{ - TIXMLASSERT( insertThis ); - TIXMLASSERT( insertThis->_document == _document ); - - if (insertThis->_parent) { - insertThis->_parent->Unlink( insertThis ); - } - else { - insertThis->_document->MarkInUse(insertThis); - insertThis->_memPool->SetTracked(); - } -} - -const XMLElement* XMLNode::ToElementWithName( const char* name ) const +// --------- XMLText ---------- // +char* XMLText::ParseDeep(char* p, StrPair*, int* curLineNumPtr) { - const XMLElement* element = this->ToElement(); - if ( element == 0 ) { - return 0; - } - if ( name == 0 ) { - return element; + if (this->CData()) + { + p = _value.ParseText(p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr); + if (!p) + { + _document->SetError(XML_ERROR_PARSING_CDATA, _parseLineNum, 0); } - if ( XMLUtil::StringEqual( element->Name(), name ) ) { - return element; + return p; + } + else + { + int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT + : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; + if (_document->WhitespaceMode() == COLLAPSE_WHITESPACE) + { + flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; } - return 0; -} -// --------- XMLText ---------- // -char* XMLText::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) -{ - if ( this->CData() ) { - p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_CDATA, _parseLineNum, 0 ); - } - return p; + p = _value.ParseText(p, "<", flags, curLineNumPtr); + if (p && *p) + { + return p - 1; } - else { - int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; - if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { - flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; - } - - p = _value.ParseText( p, "<", flags, curLineNumPtr ); - if ( p && *p ) { - return p-1; - } - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_TEXT, _parseLineNum, 0 ); - } + if (!p) + { + _document->SetError(XML_ERROR_PARSING_TEXT, _parseLineNum, 0); } - return 0; + } + return 0; } -XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const +XMLNode* XMLText::ShallowClone(XMLDocument* doc) const { - if ( !doc ) { - doc = _document; - } - XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? - text->SetCData( this->CData() ); - return text; + if (!doc) + { + doc = _document; + } + XMLText* text = doc->NewText(Value()); // fixme: this will always allocate memory. Intern? + text->SetCData(this->CData()); + return text; } -bool XMLText::ShallowEqual( const XMLNode* compare ) const +bool XMLText::ShallowEqual(const XMLNode* compare) const { - TIXMLASSERT( compare ); - const XMLText* text = compare->ToText(); - return ( text && XMLUtil::StringEqual( text->Value(), Value() ) ); + TIXMLASSERT(compare); + const XMLText* text = compare->ToText(); + return (text && XMLUtil::StringEqual(text->Value(), Value())); } -bool XMLText::Accept( XMLVisitor* visitor ) const +bool XMLText::Accept(XMLVisitor* visitor) const { - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); + TIXMLASSERT(visitor); + return visitor->Visit(*this); } // --------- XMLComment ---------- // -XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) -{ -} +XMLComment::XMLComment(XMLDocument* doc) : XMLNode(doc) {} -XMLComment::~XMLComment() -{ -} +XMLComment::~XMLComment() {} -char* XMLComment::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +char* XMLComment::ParseDeep(char* p, StrPair*, int* curLineNumPtr) { - // Comment parses as text. - p = _value.ParseText( p, "-->", StrPair::COMMENT, curLineNumPtr ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_COMMENT, _parseLineNum, 0 ); - } - return p; + // Comment parses as text. + p = _value.ParseText(p, "-->", StrPair::COMMENT, curLineNumPtr); + if (p == 0) + { + _document->SetError(XML_ERROR_PARSING_COMMENT, _parseLineNum, 0); + } + return p; } -XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const +XMLNode* XMLComment::ShallowClone(XMLDocument* doc) const { - if ( !doc ) { - doc = _document; - } - XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? - return comment; + if (!doc) + { + doc = _document; + } + XMLComment* comment = doc->NewComment(Value()); // fixme: this will always allocate memory. Intern? + return comment; } -bool XMLComment::ShallowEqual( const XMLNode* compare ) const +bool XMLComment::ShallowEqual(const XMLNode* compare) const { - TIXMLASSERT( compare ); - const XMLComment* comment = compare->ToComment(); - return ( comment && XMLUtil::StringEqual( comment->Value(), Value() )); + TIXMLASSERT(compare); + const XMLComment* comment = compare->ToComment(); + return (comment && XMLUtil::StringEqual(comment->Value(), Value())); } -bool XMLComment::Accept( XMLVisitor* visitor ) const +bool XMLComment::Accept(XMLVisitor* visitor) const { - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); + TIXMLASSERT(visitor); + return visitor->Visit(*this); } // --------- XMLDeclaration ---------- // -XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) -{ -} +XMLDeclaration::XMLDeclaration(XMLDocument* doc) : XMLNode(doc) {} XMLDeclaration::~XMLDeclaration() { - //printf( "~XMLDeclaration\n" ); + //printf( "~XMLDeclaration\n" ); } -char* XMLDeclaration::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +char* XMLDeclaration::ParseDeep(char* p, StrPair*, int* curLineNumPtr) { - // Declaration parses as text. - p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); - if ( p == 0 ) { - _document->SetError( XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0 ); - } - return p; + // Declaration parses as text. + p = _value.ParseText(p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr); + if (p == 0) + { + _document->SetError(XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0); + } + return p; } -XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const +XMLNode* XMLDeclaration::ShallowClone(XMLDocument* doc) const { - if ( !doc ) { - doc = _document; - } - XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? - return dec; + if (!doc) + { + doc = _document; + } + XMLDeclaration* dec = doc->NewDeclaration(Value()); // fixme: this will always allocate memory. Intern? + return dec; } -bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const +bool XMLDeclaration::ShallowEqual(const XMLNode* compare) const { - TIXMLASSERT( compare ); - const XMLDeclaration* declaration = compare->ToDeclaration(); - return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() )); + TIXMLASSERT(compare); + const XMLDeclaration* declaration = compare->ToDeclaration(); + return (declaration && XMLUtil::StringEqual(declaration->Value(), Value())); } - -bool XMLDeclaration::Accept( XMLVisitor* visitor ) const +bool XMLDeclaration::Accept(XMLVisitor* visitor) const { - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); + TIXMLASSERT(visitor); + return visitor->Visit(*this); } // --------- XMLUnknown ---------- // -XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) -{ -} +XMLUnknown::XMLUnknown(XMLDocument* doc) : XMLNode(doc) {} -XMLUnknown::~XMLUnknown() -{ -} +XMLUnknown::~XMLUnknown() {} -char* XMLUnknown::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +char* XMLUnknown::ParseDeep(char* p, StrPair*, int* curLineNumPtr) { - // Unknown parses as text. - p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); - if ( !p ) { - _document->SetError( XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0 ); - } - return p; + // Unknown parses as text. + p = _value.ParseText(p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr); + if (!p) + { + _document->SetError(XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0); + } + return p; } -XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const +XMLNode* XMLUnknown::ShallowClone(XMLDocument* doc) const { - if ( !doc ) { - doc = _document; - } - XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? - return text; + if (!doc) + { + doc = _document; + } + XMLUnknown* text = doc->NewUnknown(Value()); // fixme: this will always allocate memory. Intern? + return text; } -bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const +bool XMLUnknown::ShallowEqual(const XMLNode* compare) const { - TIXMLASSERT( compare ); - const XMLUnknown* unknown = compare->ToUnknown(); - return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() )); + TIXMLASSERT(compare); + const XMLUnknown* unknown = compare->ToUnknown(); + return (unknown && XMLUtil::StringEqual(unknown->Value(), Value())); } -bool XMLUnknown::Accept( XMLVisitor* visitor ) const +bool XMLUnknown::Accept(XMLVisitor* visitor) const { - TIXMLASSERT( visitor ); - return visitor->Visit( *this ); + TIXMLASSERT(visitor); + return visitor->Visit(*this); } // --------- XMLAttribute ---------- // -const char* XMLAttribute::Name() const -{ - return _name.GetStr(); -} +const char* XMLAttribute::Name() const { return _name.GetStr(); } -const char* XMLAttribute::Value() const -{ - return _value.GetStr(); -} +const char* XMLAttribute::Value() const { return _value.GetStr(); } -char* XMLAttribute::ParseDeep( char* p, bool processEntities, int* curLineNumPtr ) +char* XMLAttribute::ParseDeep(char* p, bool processEntities, int* curLineNumPtr) { - // Parse using the name rules: bug fix, was using ParseText before - p = _name.ParseName( p ); - if ( !p || !*p ) { - return 0; - } + // Parse using the name rules: bug fix, was using ParseText before + p = _name.ParseName(p); + if (!p || !*p) + { + return 0; + } - // Skip white space before = - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - if ( *p != '=' ) { - return 0; - } + // Skip white space before = + p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); + if (*p != '=') + { + return 0; + } - ++p; // move up to opening quote - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - if ( *p != '\"' && *p != '\'' ) { - return 0; - } + ++p; // move up to opening quote + p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); + if (*p != '\"' && *p != '\'') + { + return 0; + } - char endTag[2] = { *p, 0 }; - ++p; // move past opening quote + char endTag[2] = {*p, 0}; + ++p; // move past opening quote - p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr ); - return p; + p = _value.ParseText(p, + endTag, + processEntities ? StrPair::ATTRIBUTE_VALUE + : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, + curLineNumPtr); + return p; } -void XMLAttribute::SetName( const char* n ) -{ - _name.SetStr( n ); -} +void XMLAttribute::SetName(const char* n) { _name.SetStr(n); } -XMLError XMLAttribute::QueryIntValue( int* value ) const +XMLError XMLAttribute::QueryIntValue(int* value) const { - if ( XMLUtil::ToInt( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if (XMLUtil::ToInt(Value(), value)) + { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const +XMLError XMLAttribute::QueryUnsignedValue(unsigned int* value) const { - if ( XMLUtil::ToUnsigned( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if (XMLUtil::ToUnsigned(Value(), value)) + { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } XMLError XMLAttribute::QueryInt64Value(int64_t* value) const { - if (XMLUtil::ToInt64(Value(), value)) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if (XMLUtil::ToInt64(Value(), value)) + { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -XMLError XMLAttribute::QueryBoolValue( bool* value ) const +XMLError XMLAttribute::QueryBoolValue(bool* value) const { - if ( XMLUtil::ToBool( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if (XMLUtil::ToBool(Value(), value)) + { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -XMLError XMLAttribute::QueryFloatValue( float* value ) const +XMLError XMLAttribute::QueryFloatValue(float* value) const { - if ( XMLUtil::ToFloat( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if (XMLUtil::ToFloat(Value(), value)) + { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -XMLError XMLAttribute::QueryDoubleValue( double* value ) const +XMLError XMLAttribute::QueryDoubleValue(double* value) const { - if ( XMLUtil::ToDouble( Value(), value )) { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if (XMLUtil::ToDouble(Value(), value)) + { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -void XMLAttribute::SetAttribute( const char* v ) -{ - _value.SetStr( v ); -} +void XMLAttribute::SetAttribute(const char* v) { _value.SetStr(v); } -void XMLAttribute::SetAttribute( int v ) +void XMLAttribute::SetAttribute(int v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); } -void XMLAttribute::SetAttribute( unsigned v ) +void XMLAttribute::SetAttribute(unsigned v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); } void XMLAttribute::SetAttribute(int64_t v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); } - -void XMLAttribute::SetAttribute( bool v ) +void XMLAttribute::SetAttribute(bool v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); } -void XMLAttribute::SetAttribute( double v ) +void XMLAttribute::SetAttribute(double v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); } -void XMLAttribute::SetAttribute( float v ) +void XMLAttribute::SetAttribute(float v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - _value.SetStr( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); } // --------- XMLElement ---------- // -XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), - _closingType( OPEN ), - _rootAttribute( 0 ) -{ -} +XMLElement::XMLElement(XMLDocument* doc) : XMLNode(doc), _closingType(OPEN), _rootAttribute(0) {} XMLElement::~XMLElement() { - while( _rootAttribute ) { - XMLAttribute* next = _rootAttribute->_next; - DeleteAttribute( _rootAttribute ); - _rootAttribute = next; - } + while (_rootAttribute) + { + XMLAttribute* next = _rootAttribute->_next; + DeleteAttribute(_rootAttribute); + _rootAttribute = next; + } } -const XMLAttribute* XMLElement::FindAttribute( const char* name ) const +const XMLAttribute* XMLElement::FindAttribute(const char* name) const { - for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) { - if ( XMLUtil::StringEqual( a->Name(), name ) ) { - return a; - } + for (XMLAttribute* a = _rootAttribute; a; a = a->_next) + { + if (XMLUtil::StringEqual(a->Name(), name)) + { + return a; } - return 0; + } + return 0; } -const char* XMLElement::Attribute( const char* name, const char* value ) const +const char* XMLElement::Attribute(const char* name, const char* value) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return 0; - } - if ( !value || XMLUtil::StringEqual( a->Value(), value )) { - return a->Value(); - } + const XMLAttribute* a = FindAttribute(name); + if (!a) + { return 0; + } + if (!value || XMLUtil::StringEqual(a->Value(), value)) + { + return a->Value(); + } + return 0; } -int XMLElement::IntAttribute(const char* name, int defaultValue) const +int XMLElement::IntAttribute(const char* name, int defaultValue) const { - int i = defaultValue; - QueryIntAttribute(name, &i); - return i; + int i = defaultValue; + QueryIntAttribute(name, &i); + return i; } -unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const +unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const { - unsigned i = defaultValue; - QueryUnsignedAttribute(name, &i); - return i; + unsigned i = defaultValue; + QueryUnsignedAttribute(name, &i); + return i; } -int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const +int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const { - int64_t i = defaultValue; - QueryInt64Attribute(name, &i); - return i; + int64_t i = defaultValue; + QueryInt64Attribute(name, &i); + return i; } -bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const +bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const { - bool b = defaultValue; - QueryBoolAttribute(name, &b); - return b; + bool b = defaultValue; + QueryBoolAttribute(name, &b); + return b; } -double XMLElement::DoubleAttribute(const char* name, double defaultValue) const +double XMLElement::DoubleAttribute(const char* name, double defaultValue) const { - double d = defaultValue; - QueryDoubleAttribute(name, &d); - return d; + double d = defaultValue; + QueryDoubleAttribute(name, &d); + return d; } -float XMLElement::FloatAttribute(const char* name, float defaultValue) const +float XMLElement::FloatAttribute(const char* name, float defaultValue) const { - float f = defaultValue; - QueryFloatAttribute(name, &f); - return f; + float f = defaultValue; + QueryFloatAttribute(name, &f); + return f; } const char* XMLElement::GetText() const { - if ( FirstChild() && FirstChild()->ToText() ) { - return FirstChild()->Value(); - } - return 0; + if (FirstChild() && FirstChild()->ToText()) + { + return FirstChild()->Value(); + } + return 0; } -void XMLElement::SetText( const char* inText ) +void XMLElement::SetText(const char* inText) { - if ( FirstChild() && FirstChild()->ToText() ) - FirstChild()->SetValue( inText ); - else { - XMLText* theText = GetDocument()->NewText( inText ); - InsertFirstChild( theText ); - } + if (FirstChild() && FirstChild()->ToText()) + FirstChild()->SetValue(inText); + else + { + XMLText* theText = GetDocument()->NewText(inText); + InsertFirstChild(theText); + } } -void XMLElement::SetText( int v ) +void XMLElement::SetText(int v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); } -void XMLElement::SetText( unsigned v ) +void XMLElement::SetText(unsigned v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); } void XMLElement::SetText(int64_t v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); } -void XMLElement::SetText( bool v ) +void XMLElement::SetText(bool v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); } -void XMLElement::SetText( float v ) +void XMLElement::SetText(float v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); } -void XMLElement::SetText( double v ) +void XMLElement::SetText(double v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - SetText( buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); } -XMLError XMLElement::QueryIntText( int* ival ) const +XMLError XMLElement::QueryIntText(int* ival) const { - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToInt( t, ival ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; + if (FirstChild() && FirstChild()->ToText()) + { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToInt(t, ival)) + { + return XML_SUCCESS; } - return XML_NO_TEXT_NODE; + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; } -XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const +XMLError XMLElement::QueryUnsignedText(unsigned* uval) const { - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToUnsigned( t, uval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; + if (FirstChild() && FirstChild()->ToText()) + { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToUnsigned(t, uval)) + { + return XML_SUCCESS; } - return XML_NO_TEXT_NODE; + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; } XMLError XMLElement::QueryInt64Text(int64_t* ival) const { - if (FirstChild() && FirstChild()->ToText()) { - const char* t = FirstChild()->Value(); - if (XMLUtil::ToInt64(t, ival)) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; + if (FirstChild() && FirstChild()->ToText()) + { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToInt64(t, ival)) + { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; } -XMLError XMLElement::QueryBoolText( bool* bval ) const +XMLError XMLElement::QueryBoolText(bool* bval) const { - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToBool( t, bval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; + if (FirstChild() && FirstChild()->ToText()) + { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToBool(t, bval)) + { + return XML_SUCCESS; } - return XML_NO_TEXT_NODE; + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; } -XMLError XMLElement::QueryDoubleText( double* dval ) const +XMLError XMLElement::QueryDoubleText(double* dval) const { - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToDouble( t, dval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; + if (FirstChild() && FirstChild()->ToText()) + { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToDouble(t, dval)) + { + return XML_SUCCESS; } - return XML_NO_TEXT_NODE; + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; } -XMLError XMLElement::QueryFloatText( float* fval ) const +XMLError XMLElement::QueryFloatText(float* fval) const { - if ( FirstChild() && FirstChild()->ToText() ) { - const char* t = FirstChild()->Value(); - if ( XMLUtil::ToFloat( t, fval ) ) { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; + if (FirstChild() && FirstChild()->ToText()) + { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToFloat(t, fval)) + { + return XML_SUCCESS; } - return XML_NO_TEXT_NODE; + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; } int XMLElement::IntText(int defaultValue) const { - int i = defaultValue; - QueryIntText(&i); - return i; + int i = defaultValue; + QueryIntText(&i); + return i; } unsigned XMLElement::UnsignedText(unsigned defaultValue) const { - unsigned i = defaultValue; - QueryUnsignedText(&i); - return i; + unsigned i = defaultValue; + QueryUnsignedText(&i); + return i; } int64_t XMLElement::Int64Text(int64_t defaultValue) const { - int64_t i = defaultValue; - QueryInt64Text(&i); - return i; + int64_t i = defaultValue; + QueryInt64Text(&i); + return i; } bool XMLElement::BoolText(bool defaultValue) const { - bool b = defaultValue; - QueryBoolText(&b); - return b; + bool b = defaultValue; + QueryBoolText(&b); + return b; } double XMLElement::DoubleText(double defaultValue) const { - double d = defaultValue; - QueryDoubleText(&d); - return d; + double d = defaultValue; + QueryDoubleText(&d); + return d; } float XMLElement::FloatText(float defaultValue) const { - float f = defaultValue; - QueryFloatText(&f); - return f; + float f = defaultValue; + QueryFloatText(&f); + return f; } -XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) +XMLAttribute* XMLElement::FindOrCreateAttribute(const char* name) { - XMLAttribute* last = 0; - XMLAttribute* attrib = 0; - for( attrib = _rootAttribute; - attrib; - last = attrib, attrib = attrib->_next ) { - if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { - break; - } + XMLAttribute* last = 0; + XMLAttribute* attrib = 0; + for (attrib = _rootAttribute; attrib; last = attrib, attrib = attrib->_next) + { + if (XMLUtil::StringEqual(attrib->Name(), name)) + { + break; + } + } + if (!attrib) + { + attrib = CreateAttribute(); + TIXMLASSERT(attrib); + if (last) + { + TIXMLASSERT(last->_next == 0); + last->_next = attrib; } - if ( !attrib ) { - attrib = CreateAttribute(); - TIXMLASSERT( attrib ); - if ( last ) { - TIXMLASSERT( last->_next == 0 ); - last->_next = attrib; - } - else { - TIXMLASSERT( _rootAttribute == 0 ); - _rootAttribute = attrib; - } - attrib->SetName( name ); + else + { + TIXMLASSERT(_rootAttribute == 0); + _rootAttribute = attrib; } - return attrib; + attrib->SetName(name); + } + return attrib; } -void XMLElement::DeleteAttribute( const char* name ) +void XMLElement::DeleteAttribute(const char* name) { - XMLAttribute* prev = 0; - for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { - if ( XMLUtil::StringEqual( name, a->Name() ) ) { - if ( prev ) { - prev->_next = a->_next; - } - else { - _rootAttribute = a->_next; - } - DeleteAttribute( a ); - break; - } - prev = a; + XMLAttribute* prev = 0; + for (XMLAttribute* a = _rootAttribute; a; a = a->_next) + { + if (XMLUtil::StringEqual(name, a->Name())) + { + if (prev) + { + prev->_next = a->_next; + } + else + { + _rootAttribute = a->_next; + } + DeleteAttribute(a); + break; } + prev = a; + } } -char* XMLElement::ParseAttributes( char* p, int* curLineNumPtr ) +char* XMLElement::ParseAttributes(char* p, int* curLineNumPtr) { - XMLAttribute* prevAttribute = 0; + XMLAttribute* prevAttribute = 0; - // Read the attributes. - while( p ) { - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - if ( !(*p) ) { - _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name() ); - return 0; - } + // Read the attributes. + while (p) + { + p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); + if (!(*p)) + { + _document->SetError(XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name()); + return 0; + } - // attribute. - if (XMLUtil::IsNameStartChar( *p ) ) { - XMLAttribute* attrib = CreateAttribute(); - TIXMLASSERT( attrib ); - attrib->_parseLineNum = _document->_parseCurLineNum; + // attribute. + if (XMLUtil::IsNameStartChar(*p)) + { + XMLAttribute* attrib = CreateAttribute(); + TIXMLASSERT(attrib); + attrib->_parseLineNum = _document->_parseCurLineNum; - int attrLineNum = attrib->_parseLineNum; + int attrLineNum = attrib->_parseLineNum; - p = attrib->ParseDeep( p, _document->ProcessEntities(), curLineNumPtr ); - if ( !p || Attribute( attrib->Name() ) ) { - DeleteAttribute( attrib ); - _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name() ); - return 0; - } - // There is a minor bug here: if the attribute in the source xml - // document is duplicated, it will not be detected and the - // attribute will be doubly added. However, tracking the 'prevAttribute' - // avoids re-scanning the attribute list. Preferring performance for - // now, may reconsider in the future. - if ( prevAttribute ) { - TIXMLASSERT( prevAttribute->_next == 0 ); - prevAttribute->_next = attrib; - } - else { - TIXMLASSERT( _rootAttribute == 0 ); - _rootAttribute = attrib; - } - prevAttribute = attrib; - } - // end of the tag - else if ( *p == '>' ) { - ++p; - break; - } - // end of the tag - else if ( *p == '/' && *(p+1) == '>' ) { - _closingType = CLOSED; - return p+2; // done; sealed element. - } - else { - _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0 ); - return 0; - } + p = attrib->ParseDeep(p, _document->ProcessEntities(), curLineNumPtr); + if (!p || Attribute(attrib->Name())) + { + DeleteAttribute(attrib); + _document->SetError(XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name()); + return 0; + } + // There is a minor bug here: if the attribute in the source xml + // document is duplicated, it will not be detected and the + // attribute will be doubly added. However, tracking the 'prevAttribute' + // avoids re-scanning the attribute list. Preferring performance for + // now, may reconsider in the future. + if (prevAttribute) + { + TIXMLASSERT(prevAttribute->_next == 0); + prevAttribute->_next = attrib; + } + else + { + TIXMLASSERT(_rootAttribute == 0); + _rootAttribute = attrib; + } + prevAttribute = attrib; + } + // end of the tag + else if (*p == '>') + { + ++p; + break; } - return p; + // end of the tag + else if (*p == '/' && *(p + 1) == '>') + { + _closingType = CLOSED; + return p + 2; // done; sealed element. + } + else + { + _document->SetError(XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0); + return 0; + } + } + return p; } -void XMLElement::DeleteAttribute( XMLAttribute* attribute ) +void XMLElement::DeleteAttribute(XMLAttribute* attribute) { - if ( attribute == 0 ) { - return; - } - MemPool* pool = attribute->_memPool; - attribute->~XMLAttribute(); - pool->Free( attribute ); + if (attribute == 0) + { + return; + } + MemPool* pool = attribute->_memPool; + attribute->~XMLAttribute(); + pool->Free(attribute); } XMLAttribute* XMLElement::CreateAttribute() { - TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); - XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); - TIXMLASSERT( attrib ); - attrib->_memPool = &_document->_attributePool; - attrib->_memPool->SetTracked(); - return attrib; + TIXMLASSERT(sizeof(XMLAttribute) == _document->_attributePool.ItemSize()); + XMLAttribute* attrib = new (_document->_attributePool.Alloc()) XMLAttribute(); + TIXMLASSERT(attrib); + attrib->_memPool = &_document->_attributePool; + attrib->_memPool->SetTracked(); + return attrib; } // // // foobar // -char* XMLElement::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) +char* XMLElement::ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) { - // Read the element name. - p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - - // The closing element is the form. It is - // parsed just like a regular element then deleted from - // the DOM. - if ( *p == '/' ) { - _closingType = CLOSING; - ++p; - } + // Read the element name. + p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); - p = _value.ParseName( p ); - if ( _value.Empty() ) { - return 0; - } + // The closing element is the form. It is + // parsed just like a regular element then deleted from + // the DOM. + if (*p == '/') + { + _closingType = CLOSING; + ++p; + } - p = ParseAttributes( p, curLineNumPtr ); - if ( !p || !*p || _closingType != OPEN ) { - return p; - } + p = _value.ParseName(p); + if (_value.Empty()) + { + return 0; + } - p = XMLNode::ParseDeep( p, parentEndTag, curLineNumPtr ); + p = ParseAttributes(p, curLineNumPtr); + if (!p || !*p || _closingType != OPEN) + { return p; -} + } + p = XMLNode::ParseDeep(p, parentEndTag, curLineNumPtr); + return p; +} -XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const +XMLNode* XMLElement::ShallowClone(XMLDocument* doc) const { - if ( !doc ) { - doc = _document; - } - XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? - for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { - element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? - } - return element; + if (!doc) + { + doc = _document; + } + XMLElement* element = doc->NewElement(Value()); // fixme: this will always allocate memory. Intern? + for (const XMLAttribute* a = FirstAttribute(); a; a = a->Next()) + { + element->SetAttribute(a->Name(), a->Value()); // fixme: this will always allocate memory. Intern? + } + return element; } -bool XMLElement::ShallowEqual( const XMLNode* compare ) const +bool XMLElement::ShallowEqual(const XMLNode* compare) const { - TIXMLASSERT( compare ); - const XMLElement* other = compare->ToElement(); - if ( other && XMLUtil::StringEqual( other->Name(), Name() )) { + TIXMLASSERT(compare); + const XMLElement* other = compare->ToElement(); + if (other && XMLUtil::StringEqual(other->Name(), Name())) + { + const XMLAttribute* a = FirstAttribute(); + const XMLAttribute* b = other->FirstAttribute(); - const XMLAttribute* a=FirstAttribute(); - const XMLAttribute* b=other->FirstAttribute(); - - while ( a && b ) { - if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { - return false; - } - a = a->Next(); - b = b->Next(); - } - if ( a || b ) { - // different count - return false; - } - return true; + while (a && b) + { + if (!XMLUtil::StringEqual(a->Value(), b->Value())) + { + return false; + } + a = a->Next(); + b = b->Next(); + } + if (a || b) + { + // different count + return false; } - return false; + return true; + } + return false; } -bool XMLElement::Accept( XMLVisitor* visitor ) const +bool XMLElement::Accept(XMLVisitor* visitor) const { - TIXMLASSERT( visitor ); - if ( visitor->VisitEnter( *this, _rootAttribute ) ) { - for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { - if ( !node->Accept( visitor ) ) { - break; - } - } + TIXMLASSERT(visitor); + if (visitor->VisitEnter(*this, _rootAttribute)) + { + for (const XMLNode* node = FirstChild(); node; node = node->NextSibling()) + { + if (!node->Accept(visitor)) + { + break; + } } - return visitor->VisitExit( *this ); + } + return visitor->VisitExit(*this); } // --------- XMLDocument ----------- // // Warning: List must match 'enum XMLError' -const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { - "XML_SUCCESS", - "XML_NO_ATTRIBUTE", - "XML_WRONG_ATTRIBUTE_TYPE", - "XML_ERROR_FILE_NOT_FOUND", - "XML_ERROR_FILE_COULD_NOT_BE_OPENED", - "XML_ERROR_FILE_READ_ERROR", - "UNUSED_XML_ERROR_ELEMENT_MISMATCH", - "XML_ERROR_PARSING_ELEMENT", - "XML_ERROR_PARSING_ATTRIBUTE", - "UNUSED_XML_ERROR_IDENTIFYING_TAG", - "XML_ERROR_PARSING_TEXT", - "XML_ERROR_PARSING_CDATA", - "XML_ERROR_PARSING_COMMENT", - "XML_ERROR_PARSING_DECLARATION", - "XML_ERROR_PARSING_UNKNOWN", - "XML_ERROR_EMPTY_DOCUMENT", - "XML_ERROR_MISMATCHED_ELEMENT", - "XML_ERROR_PARSING", - "XML_CAN_NOT_CONVERT_TEXT", - "XML_NO_TEXT_NODE" -}; - - -XMLDocument::XMLDocument( bool processEntities, Whitespace whitespaceMode ) : - XMLNode( 0 ), - _writeBOM( false ), - _processEntities( processEntities ), - _errorID(XML_SUCCESS), - _whitespaceMode( whitespaceMode ), - _errorStr(), - _errorLineNum( 0 ), - _charBuffer( 0 ), - _parseCurLineNum( 0 ), - _unlinked(), - _elementPool(), - _attributePool(), - _textPool(), - _commentPool() -{ - // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) - _document = this; -} - - -XMLDocument::~XMLDocument() -{ - Clear(); -} +const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = {"XML_SUCCESS", + "XML_NO_ATTRIBUTE", + "XML_WRONG_ATTRIBUTE_TYPE", + "XML_ERROR_FILE_NOT_FOUND", + "XML_ERROR_FILE_COULD_NOT_BE_OPENED", + "XML_ERROR_FILE_READ_ERROR", + "UNUSED_XML_ERROR_ELEMENT_MISMATCH", + "XML_ERROR_PARSING_ELEMENT", + "XML_ERROR_PARSING_ATTRIBUTE", + "UNUSED_XML_ERROR_IDENTIFYING_TAG", + "XML_ERROR_PARSING_TEXT", + "XML_ERROR_PARSING_CDATA", + "XML_ERROR_PARSING_COMMENT", + "XML_ERROR_PARSING_DECLARATION", + "XML_ERROR_PARSING_UNKNOWN", + "XML_ERROR_EMPTY_DOCUMENT", + "XML_ERROR_MISMATCHED_ELEMENT", + "XML_ERROR_PARSING", + "XML_CAN_NOT_CONVERT_TEXT", + "XML_NO_TEXT_NODE"}; + + +XMLDocument::XMLDocument(bool processEntities, Whitespace whitespaceMode) + : XMLNode(0), + _writeBOM(false), + _processEntities(processEntities), + _errorID(XML_SUCCESS), + _whitespaceMode(whitespaceMode), + _errorStr(), + _errorLineNum(0), + _charBuffer(0), + _parseCurLineNum(0), + _unlinked(), + _elementPool(), + _attributePool(), + _textPool(), + _commentPool() +{ + // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) + _document = this; +} + + +XMLDocument::~XMLDocument() { Clear(); } void XMLDocument::MarkInUse(XMLNode* node) { - TIXMLASSERT(node); - TIXMLASSERT(node->_parent == 0); + TIXMLASSERT(node); + TIXMLASSERT(node->_parent == 0); - for (int i = 0; i < _unlinked.Size(); ++i) { - if (node == _unlinked[i]) { - _unlinked.SwapRemove(i); - break; - } - } + for (int i = 0; i < _unlinked.Size(); ++i) + { + if (node == _unlinked[i]) + { + _unlinked.SwapRemove(i); + break; + } + } } void XMLDocument::Clear() { - DeleteChildren(); - while( _unlinked.Size()) { - DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. - } + DeleteChildren(); + while (_unlinked.Size()) + { + DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. + } #ifdef TINYXML2_DEBUG - const bool hadError = Error(); + const bool hadError = Error(); #endif - ClearError(); + ClearError(); - delete [] _charBuffer; - _charBuffer = 0; + delete[] _charBuffer; + _charBuffer = 0; #if 0 _textPool.Trace( "text" ); @@ -2051,115 +2219,123 @@ void XMLDocument::Clear() _commentPool.Trace( "comment" ); _attributePool.Trace( "attribute" ); #endif - + #ifdef TINYXML2_DEBUG - if ( !hadError ) { - TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); - TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); - TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); - TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); - } + if (!hadError) + { + TIXMLASSERT(_elementPool.CurrentAllocs() == _elementPool.Untracked()); + TIXMLASSERT(_attributePool.CurrentAllocs() == _attributePool.Untracked()); + TIXMLASSERT(_textPool.CurrentAllocs() == _textPool.Untracked()); + TIXMLASSERT(_commentPool.CurrentAllocs() == _commentPool.Untracked()); + } #endif } void XMLDocument::DeepCopy(XMLDocument* target) const { - TIXMLASSERT(target); - if (target == this) { - return; // technically success - a no-op. - } + TIXMLASSERT(target); + if (target == this) + { + return; // technically success - a no-op. + } - target->Clear(); - for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) { - target->InsertEndChild(node->DeepClone(target)); - } + target->Clear(); + for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) + { + target->InsertEndChild(node->DeepClone(target)); + } } -XMLElement* XMLDocument::NewElement( const char* name ) +XMLElement* XMLDocument::NewElement(const char* name) { - XMLElement* ele = CreateUnlinkedNode( _elementPool ); - ele->SetName( name ); - return ele; + XMLElement* ele = CreateUnlinkedNode(_elementPool); + ele->SetName(name); + return ele; } -XMLComment* XMLDocument::NewComment( const char* str ) +XMLComment* XMLDocument::NewComment(const char* str) { - XMLComment* comment = CreateUnlinkedNode( _commentPool ); - comment->SetValue( str ); - return comment; + XMLComment* comment = CreateUnlinkedNode(_commentPool); + comment->SetValue(str); + return comment; } -XMLText* XMLDocument::NewText( const char* str ) +XMLText* XMLDocument::NewText(const char* str) { - XMLText* text = CreateUnlinkedNode( _textPool ); - text->SetValue( str ); - return text; + XMLText* text = CreateUnlinkedNode(_textPool); + text->SetValue(str); + return text; } -XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) +XMLDeclaration* XMLDocument::NewDeclaration(const char* str) { - XMLDeclaration* dec = CreateUnlinkedNode( _commentPool ); - dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); - return dec; + XMLDeclaration* dec = CreateUnlinkedNode(_commentPool); + dec->SetValue(str ? str : "xml version=\"1.0\" encoding=\"UTF-8\""); + return dec; } -XMLUnknown* XMLDocument::NewUnknown( const char* str ) +XMLUnknown* XMLDocument::NewUnknown(const char* str) { - XMLUnknown* unk = CreateUnlinkedNode( _commentPool ); - unk->SetValue( str ); - return unk; + XMLUnknown* unk = CreateUnlinkedNode(_commentPool); + unk->SetValue(str); + return unk; } -static FILE* callfopen( const char* filepath, const char* mode ) +static FILE* callfopen(const char* filepath, const char* mode) { - TIXMLASSERT( filepath ); - TIXMLASSERT( mode ); -#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) - FILE* fp = 0; - errno_t err = fopen_s( &fp, filepath, mode ); - if ( err ) { - return 0; - } + TIXMLASSERT(filepath); + TIXMLASSERT(mode); +#if defined(_MSC_VER) && (_MSC_VER >= 1400) && (!defined WINCE) + FILE* fp = 0; + errno_t err = fopen_s(&fp, filepath, mode); + if (err) + { + return 0; + } #else - FILE* fp = fopen( filepath, mode ); + FILE* fp = fopen(filepath, mode); #endif - return fp; -} - -void XMLDocument::DeleteNode( XMLNode* node ) { - TIXMLASSERT( node ); - TIXMLASSERT(node->_document == this ); - if (node->_parent) { - node->_parent->DeleteChild( node ); - } - else { - // Isn't in the tree. - // Use the parent delete. - // Also, we need to mark it tracked: we 'know' - // it was never used. - node->_memPool->SetTracked(); - // Call the static XMLNode version: - XMLNode::DeleteNode(node); - } + return fp; +} + +void XMLDocument::DeleteNode(XMLNode* node) +{ + TIXMLASSERT(node); + TIXMLASSERT(node->_document == this); + if (node->_parent) + { + node->_parent->DeleteChild(node); + } + else + { + // Isn't in the tree. + // Use the parent delete. + // Also, we need to mark it tracked: we 'know' + // it was never used. + node->_memPool->SetTracked(); + // Call the static XMLNode version: + XMLNode::DeleteNode(node); + } } -XMLError XMLDocument::LoadFile( const char* filename ) +XMLError XMLDocument::LoadFile(const char* filename) { - Clear(); - FILE* fp = callfopen( filename, "rb" ); - if ( !fp ) { - SetError( XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename ? filename : ""); - return _errorID; - } - LoadFile( fp ); - fclose( fp ); + Clear(); + FILE* fp = callfopen(filename, "rb"); + if (!fp) + { + SetError(XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename ? filename : ""); return _errorID; + } + LoadFile(fp); + fclose(fp); + return _errorID; } // This is likely overengineered template art to have a check that unsigned long value incremented @@ -2168,627 +2344,667 @@ XMLError XMLDocument::LoadFile( const char* filename ) // -Wtype-limits warning. This piece makes the compiler select code with a check when a check // is useful and code with no check when a check is redundant depending on how size_t and unsigned long // types sizes relate to each other. -template -= sizeof(size_t))> -struct LongFitsIntoSizeTMinusOne { - static bool Fits( unsigned long value ) - { - return value < (size_t)-1; - } +template= sizeof(size_t))> +struct LongFitsIntoSizeTMinusOne +{ + static bool Fits(unsigned long value) { return value < (size_t)-1; } }; -template <> -struct LongFitsIntoSizeTMinusOne { - static bool Fits( unsigned long ) - { - return true; - } +template<> +struct LongFitsIntoSizeTMinusOne +{ + static bool Fits(unsigned long) { return true; } }; -XMLError XMLDocument::LoadFile( FILE* fp ) +XMLError XMLDocument::LoadFile(FILE* fp) { - Clear(); - - fseek( fp, 0, SEEK_SET ); - if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - - fseek( fp, 0, SEEK_END ); - const long filelength = ftell( fp ); - fseek( fp, 0, SEEK_SET ); - if ( filelength == -1L ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } - TIXMLASSERT( filelength >= 0 ); + Clear(); - if ( !LongFitsIntoSizeTMinusOne<>::Fits( filelength ) ) { - // Cannot handle files which won't fit in buffer together with null terminator - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } + fseek(fp, 0, SEEK_SET); + if (fgetc(fp) == EOF && ferror(fp) != 0) + { + SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); + return _errorID; + } + + fseek(fp, 0, SEEK_END); + const long filelength = ftell(fp); + fseek(fp, 0, SEEK_SET); + if (filelength == -1L) + { + SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); + return _errorID; + } + TIXMLASSERT(filelength >= 0); - if ( filelength == 0 ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } + if (!LongFitsIntoSizeTMinusOne<>::Fits(filelength)) + { + // Cannot handle files which won't fit in buffer together with null terminator + SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); + return _errorID; + } - const size_t size = filelength; - TIXMLASSERT( _charBuffer == 0 ); - _charBuffer = new char[size+1]; - size_t read = fread( _charBuffer, 1, size, fp ); - if ( read != size ) { - SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); - return _errorID; - } + if (filelength == 0) + { + SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0); + return _errorID; + } + + const size_t size = filelength; + TIXMLASSERT(_charBuffer == 0); + _charBuffer = new char[size + 1]; + size_t read = fread(_charBuffer, 1, size, fp); + if (read != size) + { + SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); + return _errorID; + } - _charBuffer[size] = 0; + _charBuffer[size] = 0; - Parse(); - return _errorID; + Parse(); + return _errorID; } -XMLError XMLDocument::SaveFile( const char* filename, bool compact ) +XMLError XMLDocument::SaveFile(const char* filename, bool compact) { - FILE* fp = callfopen( filename, "w" ); - if ( !fp ) { - SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename ? filename : ""); - return _errorID; - } - SaveFile(fp, compact); - fclose( fp ); + FILE* fp = callfopen(filename, "w"); + if (!fp) + { + SetError(XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename ? filename : ""); return _errorID; + } + SaveFile(fp, compact); + fclose(fp); + return _errorID; } -XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) +XMLError XMLDocument::SaveFile(FILE* fp, bool compact) { - // Clear any error from the last save, otherwise it will get reported - // for *this* call. - ClearError(); - XMLPrinter stream( fp, compact ); - Print( &stream ); - return _errorID; + // Clear any error from the last save, otherwise it will get reported + // for *this* call. + ClearError(); + XMLPrinter stream(fp, compact); + Print(&stream); + return _errorID; } -XMLError XMLDocument::Parse( const char* p, size_t len ) +XMLError XMLDocument::Parse(const char* p, size_t len) { - Clear(); + Clear(); - if ( len == 0 || !p || !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return _errorID; - } - if ( len == (size_t)(-1) ) { - len = strlen( p ); - } - TIXMLASSERT( _charBuffer == 0 ); - _charBuffer = new char[ len+1 ]; - memcpy( _charBuffer, p, len ); - _charBuffer[len] = 0; - - Parse(); - if ( Error() ) { - // clean up now essentially dangling memory. - // and the parse fail can put objects in the - // pools that are dead and inaccessible. - DeleteChildren(); - _elementPool.Clear(); - _attributePool.Clear(); - _textPool.Clear(); - _commentPool.Clear(); - } + if (len == 0 || !p || !*p) + { + SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0); return _errorID; + } + if (len == (size_t)(-1)) + { + len = strlen(p); + } + TIXMLASSERT(_charBuffer == 0); + _charBuffer = new char[len + 1]; + memcpy(_charBuffer, p, len); + _charBuffer[len] = 0; + + Parse(); + if (Error()) + { + // clean up now essentially dangling memory. + // and the parse fail can put objects in the + // pools that are dead and inaccessible. + DeleteChildren(); + _elementPool.Clear(); + _attributePool.Clear(); + _textPool.Clear(); + _commentPool.Clear(); + } + return _errorID; } -void XMLDocument::Print( XMLPrinter* streamer ) const +void XMLDocument::Print(XMLPrinter* streamer) const { - if ( streamer ) { - Accept( streamer ); - } - else { - XMLPrinter stdoutStreamer( stdout ); - Accept( &stdoutStreamer ); - } + if (streamer) + { + Accept(streamer); + } + else + { + XMLPrinter stdoutStreamer(stdout); + Accept(&stdoutStreamer); + } } -void XMLDocument::SetError( XMLError error, int lineNum, const char* format, ... ) +void XMLDocument::SetError(XMLError error, int lineNum, const char* format, ...) { - TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT ); - _errorID = error; - _errorLineNum = lineNum; - _errorStr.Reset(); + TIXMLASSERT(error >= 0 && error < XML_ERROR_COUNT); + _errorID = error; + _errorLineNum = lineNum; + _errorStr.Reset(); - size_t BUFFER_SIZE = 1000; - char* buffer = new char[BUFFER_SIZE]; + size_t BUFFER_SIZE = 1000; + char* buffer = new char[BUFFER_SIZE]; - TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum); + TIXML_SNPRINTF(buffer, + BUFFER_SIZE, + "Error=%s ErrorID=%d (0x%x) Line number=%d", + ErrorIDToName(error), + int(error), + int(error), + lineNum); - if (format) { - size_t len = strlen(buffer); - TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); - len = strlen(buffer); + if (format) + { + size_t len = strlen(buffer); + TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); + len = strlen(buffer); - va_list va; - va_start(va, format); - TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); - va_end(va); - } - _errorStr.SetStr(buffer); - delete[] buffer; + va_list va; + va_start(va, format); + TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); + va_end(va); + } + _errorStr.SetStr(buffer); + delete[] buffer; } /*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID) { - TIXMLASSERT( errorID >= 0 && errorID < XML_ERROR_COUNT ); - const char* errorName = _errorNames[errorID]; - TIXMLASSERT( errorName && errorName[0] ); - return errorName; + TIXMLASSERT(errorID >= 0 && errorID < XML_ERROR_COUNT); + const char* errorName = _errorNames[errorID]; + TIXMLASSERT(errorName && errorName[0]); + return errorName; } -const char* XMLDocument::ErrorStr() const -{ - return _errorStr.Empty() ? "" : _errorStr.GetStr(); -} +const char* XMLDocument::ErrorStr() const { return _errorStr.Empty() ? "" : _errorStr.GetStr(); } -void XMLDocument::PrintError() const -{ - printf("%s\n", ErrorStr()); -} +void XMLDocument::PrintError() const { printf("%s\n", ErrorStr()); } -const char* XMLDocument::ErrorName() const -{ - return ErrorIDToName(_errorID); -} +const char* XMLDocument::ErrorName() const { return ErrorIDToName(_errorID); } void XMLDocument::Parse() { - TIXMLASSERT( NoChildren() ); // Clear() must have been called previously - TIXMLASSERT( _charBuffer ); - _parseCurLineNum = 1; - _parseLineNum = 1; - char* p = _charBuffer; - p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); - p = const_cast( XMLUtil::ReadBOM( p, &_writeBOM ) ); - if ( !*p ) { - SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); - return; - } - ParseDeep(p, 0, &_parseCurLineNum ); -} - -XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) : - _elementJustOpened( false ), - _stack(), - _firstElement( true ), - _fp( file ), - _depth( depth ), - _textDepth( -1 ), - _processEntities( true ), - _compactMode( compact ), - _buffer() -{ - for( int i=0; i'] = true; // not required, but consistency is nice - _buffer.Push( 0 ); -} - - -void XMLPrinter::Print( const char* format, ... ) -{ - va_list va; - va_start( va, format ); - - if ( _fp ) { - vfprintf( _fp, format, va ); - } - else { - const int len = TIXML_VSCPRINTF( format, va ); - // Close out and re-start the va-args - va_end( va ); - TIXMLASSERT( len >= 0 ); - va_start( va, format ); - TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 ); - char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator. - TIXML_VSNPRINTF( p, len+1, format, va ); - } - va_end( va ); -} - - -void XMLPrinter::Write( const char* data, size_t size ) -{ - if ( _fp ) { - fwrite ( data , sizeof(char), size, _fp); - } - else { - char* p = _buffer.PushArr( static_cast(size) ) - 1; // back up over the null terminator. - memcpy( p, data, size ); - p[size] = 0; - } -} - - -void XMLPrinter::Putc( char ch ) -{ - if ( _fp ) { - fputc ( ch, _fp); - } - else { - char* p = _buffer.PushArr( sizeof(char) ) - 1; // back up over the null terminator. - p[0] = ch; - p[1] = 0; - } -} - - -void XMLPrinter::PrintSpace( int depth ) -{ - for( int i=0; i 0 && *q < ENTITY_RANGE ) { - // Check for entities. If one is found, flush - // the stream up until the entity, write the - // entity, and keep looking. - if ( flag[(unsigned char)(*q)] ) { - while ( p < q ) { - const size_t delta = q - p; - const int toPrint = ( INT_MAX < delta ) ? INT_MAX : (int)delta; - Write( p, toPrint ); - p += toPrint; - } - bool entityPatternPrinted = false; - for( int i=0; i(XMLUtil::ReadBOM(p, &_writeBOM)); + if (!*p) + { + SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0); + return; + } + ParseDeep(p, 0, &_parseCurLineNum); +} + +XMLPrinter::XMLPrinter(FILE* file, bool compact, int depth) + : _elementJustOpened(false), + _stack(), + _firstElement(true), + _fp(file), + _depth(depth), + _textDepth(-1), + _processEntities(true), + _compactMode(compact), + _buffer() +{ + for (int i = 0; i < ENTITY_RANGE; ++i) + { + _entityFlag[i] = false; + _restrictedEntityFlag[i] = false; + } + for (int i = 0; i < NUM_ENTITIES; ++i) + { + const char entityValue = entities[i].value; + const unsigned char flagIndex = (unsigned char)entityValue; + TIXMLASSERT(flagIndex < ENTITY_RANGE); + _entityFlag[flagIndex] = true; + } + _restrictedEntityFlag[(unsigned char)'&'] = true; + _restrictedEntityFlag[(unsigned char)'<'] = true; + _restrictedEntityFlag[(unsigned char)'>'] = true; // not required, but consistency is nice + _buffer.Push(0); +} + + +void XMLPrinter::Print(const char* format, ...) +{ + va_list va; + va_start(va, format); + + if (_fp) + { + vfprintf(_fp, format, va); + } + else + { + const int len = TIXML_VSCPRINTF(format, va); + // Close out and re-start the va-args + va_end(va); + TIXMLASSERT(len >= 0); + va_start(va, format); + TIXMLASSERT(_buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0); + char* p = _buffer.PushArr(len) - 1; // back up over the null terminator. + TIXML_VSNPRINTF(p, len + 1, format, va); + } + va_end(va); +} + + +void XMLPrinter::Write(const char* data, size_t size) +{ + if (_fp) + { + fwrite(data, sizeof(char), size, _fp); + } + else + { + char* p = _buffer.PushArr(static_cast(size)) - 1; // back up over the null terminator. + memcpy(p, data, size); + p[size] = 0; + } +} + + +void XMLPrinter::Putc(char ch) +{ + if (_fp) + { + fputc(ch, _fp); + } + else + { + char* p = _buffer.PushArr(sizeof(char)) - 1; // back up over the null terminator. + p[0] = ch; + p[1] = 0; + } +} + + +void XMLPrinter::PrintSpace(int depth) +{ + for (int i = 0; i < depth; ++i) + { + Write(" "); + } +} + + +void XMLPrinter::PrintString(const char* p, bool restricted) +{ + // Look for runs of bytes between entities to print. + const char* q = p; + + if (_processEntities) + { + const bool* flag = restricted ? _restrictedEntityFlag : _entityFlag; + while (*q) + { + TIXMLASSERT(p <= q); + // Remember, char is sometimes signed. (How many times has that bitten me?) + if (*q > 0 && *q < ENTITY_RANGE) + { + // Check for entities. If one is found, flush + // the stream up until the entity, write the + // entity, and keep looking. + if (flag[(unsigned char)(*q)]) + { + while (p < q) + { + const size_t delta = q - p; + const int toPrint = (INT_MAX < delta) ? INT_MAX : (int)delta; + Write(p, toPrint); + p += toPrint; + } + bool entityPatternPrinted = false; + for (int i = 0; i < NUM_ENTITIES; ++i) + { + if (entities[i].value == *q) + { + Putc('&'); + Write(entities[i].pattern, entities[i].length); + Putc(';'); + entityPatternPrinted = true; + break; } - ++q; - TIXMLASSERT( p <= q ); + } + if (!entityPatternPrinted) + { + // TIXMLASSERT( entityPatternPrinted ) causes gcc -Wunused-but-set-variable in release + TIXMLASSERT(false); + } + ++p; } + } + ++q; + TIXMLASSERT(p <= q); } - // Flush the remaining string. This will be the entire - // string if an entity wasn't found. - TIXMLASSERT( p <= q ); - if ( !_processEntities || ( p < q ) ) { - const size_t delta = q - p; - const int toPrint = ( INT_MAX < delta ) ? INT_MAX : (int)delta; - Write( p, toPrint ); - } + } + // Flush the remaining string. This will be the entire + // string if an entity wasn't found. + TIXMLASSERT(p <= q); + if (!_processEntities || (p < q)) + { + const size_t delta = q - p; + const int toPrint = (INT_MAX < delta) ? INT_MAX : (int)delta; + Write(p, toPrint); + } } -void XMLPrinter::PushHeader( bool writeBOM, bool writeDec ) +void XMLPrinter::PushHeader(bool writeBOM, bool writeDec) { - if ( writeBOM ) { - static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 }; - Write( reinterpret_cast< const char* >( bom ) ); - } - if ( writeDec ) { - PushDeclaration( "xml version=\"1.0\"" ); - } + if (writeBOM) + { + static const unsigned char bom[] = {TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0}; + Write(reinterpret_cast(bom)); + } + if (writeDec) + { + PushDeclaration("xml version=\"1.0\""); + } } -void XMLPrinter::OpenElement( const char* name, bool compactMode ) +void XMLPrinter::OpenElement(const char* name, bool compactMode) { - SealElementIfJustOpened(); - _stack.Push( name ); + SealElementIfJustOpened(); + _stack.Push(name); - if ( _textDepth < 0 && !_firstElement && !compactMode ) { - Putc( '\n' ); - } - if ( !compactMode ) { - PrintSpace( _depth ); - } + if (_textDepth < 0 && !_firstElement && !compactMode) + { + Putc('\n'); + } + if (!compactMode) + { + PrintSpace(_depth); + } - Write ( "<" ); - Write ( name ); + Write("<"); + Write(name); - _elementJustOpened = true; - _firstElement = false; - ++_depth; + _elementJustOpened = true; + _firstElement = false; + ++_depth; } -void XMLPrinter::PushAttribute( const char* name, const char* value ) +void XMLPrinter::PushAttribute(const char* name, const char* value) { - TIXMLASSERT( _elementJustOpened ); - Putc ( ' ' ); - Write( name ); - Write( "=\"" ); - PrintString( value, false ); - Putc ( '\"' ); + TIXMLASSERT(_elementJustOpened); + Putc(' '); + Write(name); + Write("=\""); + PrintString(value, false); + Putc('\"'); } -void XMLPrinter::PushAttribute( const char* name, int v ) +void XMLPrinter::PushAttribute(const char* name, int v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); } -void XMLPrinter::PushAttribute( const char* name, unsigned v ) +void XMLPrinter::PushAttribute(const char* name, unsigned v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); } void XMLPrinter::PushAttribute(const char* name, int64_t v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - PushAttribute(name, buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); } -void XMLPrinter::PushAttribute( const char* name, bool v ) +void XMLPrinter::PushAttribute(const char* name, bool v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); } -void XMLPrinter::PushAttribute( const char* name, double v ) +void XMLPrinter::PushAttribute(const char* name, double v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( v, buf, BUF_SIZE ); - PushAttribute( name, buf ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); } -void XMLPrinter::CloseElement( bool compactMode ) +void XMLPrinter::CloseElement(bool compactMode) { - --_depth; - const char* name = _stack.Pop(); + --_depth; + const char* name = _stack.Pop(); - if ( _elementJustOpened ) { - Write( "/>" ); - } - else { - if ( _textDepth < 0 && !compactMode) { - Putc( '\n' ); - PrintSpace( _depth ); - } - Write ( "" ); + if (_elementJustOpened) + { + Write("/>"); + } + else + { + if (_textDepth < 0 && !compactMode) + { + Putc('\n'); + PrintSpace(_depth); } + Write(""); + } - if ( _textDepth == _depth ) { - _textDepth = -1; - } - if ( _depth == 0 && !compactMode) { - Putc( '\n' ); - } - _elementJustOpened = false; + if (_textDepth == _depth) + { + _textDepth = -1; + } + if (_depth == 0 && !compactMode) + { + Putc('\n'); + } + _elementJustOpened = false; } void XMLPrinter::SealElementIfJustOpened() { - if ( !_elementJustOpened ) { - return; - } - _elementJustOpened = false; - Putc( '>' ); + if (!_elementJustOpened) + { + return; + } + _elementJustOpened = false; + Putc('>'); } -void XMLPrinter::PushText( const char* text, bool cdata ) +void XMLPrinter::PushText(const char* text, bool cdata) { - _textDepth = _depth-1; + _textDepth = _depth - 1; - SealElementIfJustOpened(); - if ( cdata ) { - Write( "" ); - } - else { - PrintString( text, true ); - } + SealElementIfJustOpened(); + if (cdata) + { + Write(""); + } + else + { + PrintString(text, true); + } } -void XMLPrinter::PushText( int64_t value ) +void XMLPrinter::PushText(int64_t value) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); } -void XMLPrinter::PushText( int value ) +void XMLPrinter::PushText(int value) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); } -void XMLPrinter::PushText( unsigned value ) +void XMLPrinter::PushText(unsigned value) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); } -void XMLPrinter::PushText( bool value ) +void XMLPrinter::PushText(bool value) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); } -void XMLPrinter::PushText( float value ) +void XMLPrinter::PushText(float value) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); } -void XMLPrinter::PushText( double value ) +void XMLPrinter::PushText(double value) { - char buf[BUF_SIZE]; - XMLUtil::ToStr( value, buf, BUF_SIZE ); - PushText( buf, false ); + char buf[BUF_SIZE]; + XMLUtil::ToStr(value, buf, BUF_SIZE); + PushText(buf, false); } -void XMLPrinter::PushComment( const char* comment ) +void XMLPrinter::PushComment(const char* comment) { - SealElementIfJustOpened(); - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Putc( '\n' ); - PrintSpace( _depth ); - } - _firstElement = false; + SealElementIfJustOpened(); + if (_textDepth < 0 && !_firstElement && !_compactMode) + { + Putc('\n'); + PrintSpace(_depth); + } + _firstElement = false; - Write( "" ); + Write(""); } -void XMLPrinter::PushDeclaration( const char* value ) +void XMLPrinter::PushDeclaration(const char* value) { - SealElementIfJustOpened(); - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Putc( '\n' ); - PrintSpace( _depth ); - } - _firstElement = false; + SealElementIfJustOpened(); + if (_textDepth < 0 && !_firstElement && !_compactMode) + { + Putc('\n'); + PrintSpace(_depth); + } + _firstElement = false; - Write( "" ); + Write(""); } -void XMLPrinter::PushUnknown( const char* value ) +void XMLPrinter::PushUnknown(const char* value) { - SealElementIfJustOpened(); - if ( _textDepth < 0 && !_firstElement && !_compactMode) { - Putc( '\n' ); - PrintSpace( _depth ); - } - _firstElement = false; + SealElementIfJustOpened(); + if (_textDepth < 0 && !_firstElement && !_compactMode) + { + Putc('\n'); + PrintSpace(_depth); + } + _firstElement = false; - Write( "' ); + Write("'); } -bool XMLPrinter::VisitEnter( const XMLDocument& doc ) +bool XMLPrinter::VisitEnter(const XMLDocument& doc) { - _processEntities = doc.ProcessEntities(); - if ( doc.HasBOM() ) { - PushHeader( true, false ); - } - return true; + _processEntities = doc.ProcessEntities(); + if (doc.HasBOM()) + { + PushHeader(true, false); + } + return true; } -bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) +bool XMLPrinter::VisitEnter(const XMLElement& element, const XMLAttribute* attribute) { - const XMLElement* parentElem = 0; - if ( element.Parent() ) { - parentElem = element.Parent()->ToElement(); - } - const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode; - OpenElement( element.Name(), compactMode ); - while ( attribute ) { - PushAttribute( attribute->Name(), attribute->Value() ); - attribute = attribute->Next(); - } - return true; + const XMLElement* parentElem = 0; + if (element.Parent()) + { + parentElem = element.Parent()->ToElement(); + } + const bool compactMode = parentElem ? CompactMode(*parentElem) : _compactMode; + OpenElement(element.Name(), compactMode); + while (attribute) + { + PushAttribute(attribute->Name(), attribute->Value()); + attribute = attribute->Next(); + } + return true; } -bool XMLPrinter::VisitExit( const XMLElement& element ) +bool XMLPrinter::VisitExit(const XMLElement& element) { - CloseElement( CompactMode(element) ); - return true; + CloseElement(CompactMode(element)); + return true; } -bool XMLPrinter::Visit( const XMLText& text ) +bool XMLPrinter::Visit(const XMLText& text) { - PushText( text.Value(), text.CData() ); - return true; + PushText(text.Value(), text.CData()); + return true; } -bool XMLPrinter::Visit( const XMLComment& comment ) +bool XMLPrinter::Visit(const XMLComment& comment) { - PushComment( comment.Value() ); - return true; + PushComment(comment.Value()); + return true; } -bool XMLPrinter::Visit( const XMLDeclaration& declaration ) +bool XMLPrinter::Visit(const XMLDeclaration& declaration) { - PushDeclaration( declaration.Value() ); - return true; + PushDeclaration(declaration.Value()); + return true; } -bool XMLPrinter::Visit( const XMLUnknown& unknown ) +bool XMLPrinter::Visit(const XMLUnknown& unknown) { - PushUnknown( unknown.Value() ); - return true; + PushUnknown(unknown.Value()); + return true; } -} // namespace tinyxml2 - +} // namespace tinyxml2 diff --git a/src/Utilities/tinyxml/tinyxml2.h b/src/Utilities/tinyxml/tinyxml2.h old mode 100755 new mode 100644 index a385fdb2b..82b4a41ac --- a/src/Utilities/tinyxml/tinyxml2.h +++ b/src/Utilities/tinyxml/tinyxml2.h @@ -25,20 +25,20 @@ distribution. #define TINYXML2_INCLUDED #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) -# include -# include -# include -# include -# include -# if defined(__PS3__) -# include -# endif +#include +#include +#include +#include +#include +#if defined(__PS3__) +#include +#endif #else -# include -# include -# include -# include -# include +#include +#include +#include +#include +#include #endif #include @@ -53,45 +53,54 @@ distribution. AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h */ -#if defined( _DEBUG ) || defined (__DEBUG__) -# ifndef TINYXML2_DEBUG -# define TINYXML2_DEBUG -# endif +#if defined(_DEBUG) || defined(__DEBUG__) +#ifndef TINYXML2_DEBUG +#define TINYXML2_DEBUG +#endif #endif #ifdef _MSC_VER -# pragma warning(push) -# pragma warning(disable: 4251) +#pragma warning(push) +#pragma warning(disable : 4251) #endif #ifdef _WIN32 -# ifdef TINYXML2_EXPORT -# define TINYXML2_LIB __declspec(dllexport) -# elif defined(TINYXML2_IMPORT) -# define TINYXML2_LIB __declspec(dllimport) -# else -# define TINYXML2_LIB -# endif +#ifdef TINYXML2_EXPORT +#define TINYXML2_LIB __declspec(dllexport) +#elif defined(TINYXML2_IMPORT) +#define TINYXML2_LIB __declspec(dllimport) +#else +#define TINYXML2_LIB +#endif #elif __GNUC__ >= 4 -# define TINYXML2_LIB __attribute__((visibility("default"))) +#define TINYXML2_LIB __attribute__((visibility("default"))) #else -# define TINYXML2_LIB +#define TINYXML2_LIB #endif #if defined(TINYXML2_DEBUG) -# if defined(_MSC_VER) -# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like -# define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); } -# elif defined (ANDROID_NDK) -# include -# define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } -# else -# include -# define TIXMLASSERT assert -# endif +#if defined(_MSC_VER) +#// "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like +#define TIXMLASSERT(x) \ + if (!((void)0, (x))) \ + { \ + __debugbreak(); \ + } +#elif defined(ANDROID_NDK) +#include +#define TIXMLASSERT(x) \ + if (!(x)) \ + { \ + __android_log_assert("assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__); \ + } +#else +#include +#define TIXMLASSERT assert +#endif #else -# define TIXMLASSERT( x ) {} +#define TIXMLASSERT(x) \ + {} #endif @@ -126,64 +135,66 @@ class XMLPrinter; class StrPair { public: - enum { - NEEDS_ENTITY_PROCESSING = 0x01, - NEEDS_NEWLINE_NORMALIZATION = 0x02, - NEEDS_WHITESPACE_COLLAPSING = 0x04, - - TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_NAME = 0, - ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - COMMENT = NEEDS_NEWLINE_NORMALIZATION - }; - - StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} - ~StrPair(); - - void Set( char* start, char* end, int flags ) { - TIXMLASSERT( start ); - TIXMLASSERT( end ); - Reset(); - _start = start; - _end = end; - _flags = flags | NEEDS_FLUSH; - } - - const char* GetStr(); - - bool Empty() const { - return _start == _end; - } - - void SetInternedStr( const char* str ) { - Reset(); - _start = const_cast(str); - } - - void SetStr( const char* str, int flags=0 ); - - char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr ); - char* ParseName( char* in ); - - void TransferTo( StrPair* other ); - void Reset(); + enum + { + NEEDS_ENTITY_PROCESSING = 0x01, + NEEDS_NEWLINE_NORMALIZATION = 0x02, + NEEDS_WHITESPACE_COLLAPSING = 0x04, + + TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_NAME = 0, + ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + COMMENT = NEEDS_NEWLINE_NORMALIZATION + }; + + StrPair() : _flags(0), _start(0), _end(0) {} + ~StrPair(); + + void Set(char* start, char* end, int flags) + { + TIXMLASSERT(start); + TIXMLASSERT(end); + Reset(); + _start = start; + _end = end; + _flags = flags | NEEDS_FLUSH; + } + + const char* GetStr(); + + bool Empty() const { return _start == _end; } + + void SetInternedStr(const char* str) + { + Reset(); + _start = const_cast(str); + } + + void SetStr(const char* str, int flags = 0); + + char* ParseText(char* in, const char* endTag, int strFlags, int* curLineNumPtr); + char* ParseName(char* in); + + void TransferTo(StrPair* other); + void Reset(); private: - void CollapseWhitespace(); + void CollapseWhitespace(); - enum { - NEEDS_FLUSH = 0x100, - NEEDS_DELETE = 0x200 - }; + enum + { + NEEDS_FLUSH = 0x100, + NEEDS_DELETE = 0x200 + }; - int _flags; - char* _start; - char* _end; + int _flags; + char* _start; + char* _end; - StrPair( const StrPair& other ); // not supported - void operator=( StrPair& other ); // not supported, use TransferTo() + StrPair(const StrPair& other); // not supported + void operator=(StrPair& other); // not supported, use TransferTo() }; @@ -192,124 +203,132 @@ class StrPair Has a small initial memory pool, so that low or no usage will not cause a call to new/delete */ -template +template class DynArray { public: - DynArray() : - _mem( _pool ), - _allocated( INITIAL_SIZE ), - _size( 0 ) - { - } - - ~DynArray() { - if ( _mem != _pool ) { - delete [] _mem; - } - } - - void Clear() { - _size = 0; - } - - void Push( T t ) { - TIXMLASSERT( _size < INT_MAX ); - EnsureCapacity( _size+1 ); - _mem[_size] = t; - ++_size; - } - - T* PushArr( int count ) { - TIXMLASSERT( count >= 0 ); - TIXMLASSERT( _size <= INT_MAX - count ); - EnsureCapacity( _size+count ); - T* ret = &_mem[_size]; - _size += count; - return ret; - } - - T Pop() { - TIXMLASSERT( _size > 0 ); - --_size; - return _mem[_size]; - } - - void PopArr( int count ) { - TIXMLASSERT( _size >= count ); - _size -= count; - } + DynArray() : _mem(_pool), _allocated(INITIAL_SIZE), _size(0) {} - bool Empty() const { - return _size == 0; - } - - T& operator[](int i) { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } - - const T& operator[](int i) const { - TIXMLASSERT( i>= 0 && i < _size ); - return _mem[i]; - } - - const T& PeekTop() const { - TIXMLASSERT( _size > 0 ); - return _mem[ _size - 1]; - } - - int Size() const { - TIXMLASSERT( _size >= 0 ); - return _size; - } - - int Capacity() const { - TIXMLASSERT( _allocated >= INITIAL_SIZE ); - return _allocated; - } - - void SwapRemove(int i) { - TIXMLASSERT(i >= 0 && i < _size); - TIXMLASSERT(_size > 0); - _mem[i] = _mem[_size - 1]; - --_size; - } - - const T* Mem() const { - TIXMLASSERT( _mem ); - return _mem; - } - - T* Mem() { - TIXMLASSERT( _mem ); - return _mem; - } + ~DynArray() + { + if (_mem != _pool) + { + delete[] _mem; + } + } + + void Clear() { _size = 0; } + + void Push(T t) + { + TIXMLASSERT(_size < INT_MAX); + EnsureCapacity(_size + 1); + _mem[_size] = t; + ++_size; + } + + T* PushArr(int count) + { + TIXMLASSERT(count >= 0); + TIXMLASSERT(_size <= INT_MAX - count); + EnsureCapacity(_size + count); + T* ret = &_mem[_size]; + _size += count; + return ret; + } + + T Pop() + { + TIXMLASSERT(_size > 0); + --_size; + return _mem[_size]; + } + + void PopArr(int count) + { + TIXMLASSERT(_size >= count); + _size -= count; + } + + bool Empty() const { return _size == 0; } + + T& operator[](int i) + { + TIXMLASSERT(i >= 0 && i < _size); + return _mem[i]; + } + + const T& operator[](int i) const + { + TIXMLASSERT(i >= 0 && i < _size); + return _mem[i]; + } + + const T& PeekTop() const + { + TIXMLASSERT(_size > 0); + return _mem[_size - 1]; + } + + int Size() const + { + TIXMLASSERT(_size >= 0); + return _size; + } + + int Capacity() const + { + TIXMLASSERT(_allocated >= INITIAL_SIZE); + return _allocated; + } + + void SwapRemove(int i) + { + TIXMLASSERT(i >= 0 && i < _size); + TIXMLASSERT(_size > 0); + _mem[i] = _mem[_size - 1]; + --_size; + } + + const T* Mem() const + { + TIXMLASSERT(_mem); + return _mem; + } + + T* Mem() + { + TIXMLASSERT(_mem); + return _mem; + } private: - DynArray( const DynArray& ); // not supported - void operator=( const DynArray& ); // not supported - - void EnsureCapacity( int cap ) { - TIXMLASSERT( cap > 0 ); - if ( cap > _allocated ) { - TIXMLASSERT( cap <= INT_MAX / 2 ); - int newAllocated = cap * 2; - T* newMem = new T[newAllocated]; - TIXMLASSERT( newAllocated >= _size ); - memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs - if ( _mem != _pool ) { - delete [] _mem; - } - _mem = newMem; - _allocated = newAllocated; - } - } + DynArray(const DynArray&); // not supported + void operator=(const DynArray&); // not supported - T* _mem; - T _pool[INITIAL_SIZE]; - int _allocated; // objects allocated - int _size; // number objects in use + void EnsureCapacity(int cap) + { + TIXMLASSERT(cap > 0); + if (cap > _allocated) + { + TIXMLASSERT(cap <= INT_MAX / 2); + int newAllocated = cap * 2; + T* newMem = new T[newAllocated]; + TIXMLASSERT(newAllocated >= _size); + memcpy(newMem, _mem, sizeof(T) * _size); // warning: not using constructors, only works for PODs + if (_mem != _pool) + { + delete[] _mem; + } + _mem = newMem; + _allocated = newAllocated; + } + } + + T* _mem; + T _pool[INITIAL_SIZE]; + int _allocated; // objects allocated + int _size; // number objects in use }; @@ -320,136 +339,145 @@ class DynArray class MemPool { public: - MemPool() {} - virtual ~MemPool() {} - - virtual int ItemSize() const = 0; - virtual void* Alloc() = 0; - virtual void Free( void* ) = 0; - virtual void SetTracked() = 0; - virtual void Clear() = 0; + MemPool() {} + virtual ~MemPool() {} + + virtual int ItemSize() const = 0; + virtual void* Alloc() = 0; + virtual void Free(void*) = 0; + virtual void SetTracked() = 0; + virtual void Clear() = 0; }; /* Template child class to create pools of the correct type. */ -template< int ITEM_SIZE > +template class MemPoolT : public MemPool { public: - MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} - ~MemPoolT() { - Clear(); - } - - void Clear() { - // Delete the blocks. - while( !_blockPtrs.Empty()) { - Block* lastBlock = _blockPtrs.Pop(); - delete lastBlock; - } - _root = 0; - _currentAllocs = 0; - _nAllocs = 0; - _maxAllocs = 0; - _nUntracked = 0; - } - - virtual int ItemSize() const { - return ITEM_SIZE; - } - int CurrentAllocs() const { - return _currentAllocs; + MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) + {} + ~MemPoolT() { Clear(); } + + void Clear() + { + // Delete the blocks. + while (!_blockPtrs.Empty()) + { + Block* lastBlock = _blockPtrs.Pop(); + delete lastBlock; + } + _root = 0; + _currentAllocs = 0; + _nAllocs = 0; + _maxAllocs = 0; + _nUntracked = 0; + } + + virtual int ItemSize() const { return ITEM_SIZE; } + int CurrentAllocs() const { return _currentAllocs; } + + virtual void* Alloc() + { + if (!_root) + { + // Need a new block. + Block* block = new Block(); + _blockPtrs.Push(block); + + Item* blockItems = block->items; + for (int i = 0; i < ITEMS_PER_BLOCK - 1; ++i) + { + blockItems[i].next = &(blockItems[i + 1]); + } + blockItems[ITEMS_PER_BLOCK - 1].next = 0; + _root = blockItems; + } + Item* const result = _root; + TIXMLASSERT(result != 0); + _root = _root->next; + + ++_currentAllocs; + if (_currentAllocs > _maxAllocs) + { + _maxAllocs = _currentAllocs; } + ++_nAllocs; + ++_nUntracked; + return result; + } - virtual void* Alloc() { - if ( !_root ) { - // Need a new block. - Block* block = new Block(); - _blockPtrs.Push( block ); - - Item* blockItems = block->items; - for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) { - blockItems[i].next = &(blockItems[i + 1]); - } - blockItems[ITEMS_PER_BLOCK - 1].next = 0; - _root = blockItems; - } - Item* const result = _root; - TIXMLASSERT( result != 0 ); - _root = _root->next; - - ++_currentAllocs; - if ( _currentAllocs > _maxAllocs ) { - _maxAllocs = _currentAllocs; - } - ++_nAllocs; - ++_nUntracked; - return result; + virtual void Free(void* mem) + { + if (!mem) + { + return; } - - virtual void Free( void* mem ) { - if ( !mem ) { - return; - } - --_currentAllocs; - Item* item = static_cast( mem ); + --_currentAllocs; + Item* item = static_cast(mem); #ifdef TINYXML2_DEBUG - memset( item, 0xfe, sizeof( *item ) ); + memset(item, 0xfe, sizeof(*item)); #endif - item->next = _root; - _root = item; - } - void Trace( const char* name ) { - printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", - name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, - ITEM_SIZE, _nAllocs, _blockPtrs.Size() ); - } - - void SetTracked() { - --_nUntracked; - } - - int Untracked() const { - return _nUntracked; - } - - // This number is perf sensitive. 4k seems like a good tradeoff on my machine. - // The test file is large, 170k. - // Release: VS2010 gcc(no opt) - // 1k: 4000 - // 2k: 4000 - // 4k: 3900 21000 - // 16k: 5200 - // 32k: 4300 - // 64k: 4000 21000 - // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK - // in private part if ITEMS_PER_BLOCK is private - enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; + item->next = _root; + _root = item; + } + void Trace(const char* name) + { + printf("Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", + name, + _maxAllocs, + _maxAllocs * ITEM_SIZE / 1024, + _currentAllocs, + ITEM_SIZE, + _nAllocs, + _blockPtrs.Size()); + } + + void SetTracked() { --_nUntracked; } + + int Untracked() const { return _nUntracked; } + + // This number is perf sensitive. 4k seems like a good tradeoff on my machine. + // The test file is large, 170k. + // Release: VS2010 gcc(no opt) + // 1k: 4000 + // 2k: 4000 + // 4k: 3900 21000 + // 16k: 5200 + // 32k: 4300 + // 64k: 4000 21000 + // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK + // in private part if ITEMS_PER_BLOCK is private + enum + { + ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE + }; private: - MemPoolT( const MemPoolT& ); // not supported - void operator=( const MemPoolT& ); // not supported - - union Item { - Item* next; - char itemData[ITEM_SIZE]; - }; - struct Block { - Item items[ITEMS_PER_BLOCK]; - }; - DynArray< Block*, 10 > _blockPtrs; - Item* _root; - - int _currentAllocs; - int _nAllocs; - int _maxAllocs; - int _nUntracked; + MemPoolT(const MemPoolT&); // not supported + void operator=(const MemPoolT&); // not supported + + union Item + { + Item* next; + char itemData[ITEM_SIZE]; + }; + struct Block + { + Item items[ITEMS_PER_BLOCK]; + }; + DynArray _blockPtrs; + Item* _root; + + int _currentAllocs; + int _nAllocs; + int _maxAllocs; + int _nUntracked; }; - /** Implements the interface to the "Visitor pattern" (see the Accept() method.) If you call the Accept() method, it requires being passed a XMLVisitor @@ -472,68 +500,56 @@ class MemPoolT : public MemPool class TINYXML2_LIB XMLVisitor { public: - virtual ~XMLVisitor() {} - - /// Visit a document. - virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { - return true; - } - /// Visit a document. - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } - - /// Visit an element. - virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { - return true; - } - /// Visit an element. - virtual bool VisitExit( const XMLElement& /*element*/ ) { - return true; - } - - /// Visit a declaration. - virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { - return true; - } - /// Visit a text node. - virtual bool Visit( const XMLText& /*text*/ ) { - return true; - } - /// Visit a comment node. - virtual bool Visit( const XMLComment& /*comment*/ ) { - return true; - } - /// Visit an unknown node. - virtual bool Visit( const XMLUnknown& /*unknown*/ ) { - return true; - } + virtual ~XMLVisitor() {} + + /// Visit a document. + virtual bool VisitEnter(const XMLDocument& /*doc*/) { return true; } + /// Visit a document. + virtual bool VisitExit(const XMLDocument& /*doc*/) { return true; } + + /// Visit an element. + virtual bool VisitEnter(const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/) + { + return true; + } + /// Visit an element. + virtual bool VisitExit(const XMLElement& /*element*/) { return true; } + + /// Visit a declaration. + virtual bool Visit(const XMLDeclaration& /*declaration*/) { return true; } + /// Visit a text node. + virtual bool Visit(const XMLText& /*text*/) { return true; } + /// Visit a comment node. + virtual bool Visit(const XMLComment& /*comment*/) { return true; } + /// Visit an unknown node. + virtual bool Visit(const XMLUnknown& /*unknown*/) { return true; } }; // WARNING: must match XMLDocument::_errorNames[] -enum XMLError { - XML_SUCCESS = 0, - XML_NO_ATTRIBUTE, - XML_WRONG_ATTRIBUTE_TYPE, - XML_ERROR_FILE_NOT_FOUND, - XML_ERROR_FILE_COULD_NOT_BE_OPENED, - XML_ERROR_FILE_READ_ERROR, - UNUSED_XML_ERROR_ELEMENT_MISMATCH, // remove at next major version - XML_ERROR_PARSING_ELEMENT, - XML_ERROR_PARSING_ATTRIBUTE, - UNUSED_XML_ERROR_IDENTIFYING_TAG, // remove at next major version - XML_ERROR_PARSING_TEXT, - XML_ERROR_PARSING_CDATA, - XML_ERROR_PARSING_COMMENT, - XML_ERROR_PARSING_DECLARATION, - XML_ERROR_PARSING_UNKNOWN, - XML_ERROR_EMPTY_DOCUMENT, - XML_ERROR_MISMATCHED_ELEMENT, - XML_ERROR_PARSING, - XML_CAN_NOT_CONVERT_TEXT, - XML_NO_TEXT_NODE, - - XML_ERROR_COUNT +enum XMLError +{ + XML_SUCCESS = 0, + XML_NO_ATTRIBUTE, + XML_WRONG_ATTRIBUTE_TYPE, + XML_ERROR_FILE_NOT_FOUND, + XML_ERROR_FILE_COULD_NOT_BE_OPENED, + XML_ERROR_FILE_READ_ERROR, + UNUSED_XML_ERROR_ELEMENT_MISMATCH, // remove at next major version + XML_ERROR_PARSING_ELEMENT, + XML_ERROR_PARSING_ATTRIBUTE, + UNUSED_XML_ERROR_IDENTIFYING_TAG, // remove at next major version + XML_ERROR_PARSING_TEXT, + XML_ERROR_PARSING_CDATA, + XML_ERROR_PARSING_COMMENT, + XML_ERROR_PARSING_DECLARATION, + XML_ERROR_PARSING_UNKNOWN, + XML_ERROR_EMPTY_DOCUMENT, + XML_ERROR_MISMATCHED_ELEMENT, + XML_ERROR_PARSING, + XML_CAN_NOT_CONVERT_TEXT, + XML_NO_TEXT_NODE, + + XML_ERROR_COUNT }; @@ -543,92 +559,98 @@ enum XMLError { class TINYXML2_LIB XMLUtil { public: - static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) { - TIXMLASSERT( p ); - - while( IsWhiteSpace(*p) ) { - if (curLineNumPtr && *p == '\n') { - ++(*curLineNumPtr); - } - ++p; - } - TIXMLASSERT( p ); - return p; - } - static char* SkipWhiteSpace( char* p, int* curLineNumPtr ) { - return const_cast( SkipWhiteSpace( const_cast(p), curLineNumPtr ) ); - } + static const char* SkipWhiteSpace(const char* p, int* curLineNumPtr) + { + TIXMLASSERT(p); - // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't - // correct, but simple, and usually works. - static bool IsWhiteSpace( char p ) { - return !IsUTF8Continuation(p) && isspace( static_cast(p) ); - } - - inline static bool IsNameStartChar( unsigned char ch ) { - if ( ch >= 128 ) { - // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() - return true; - } - if ( isalpha( ch ) ) { - return true; - } - return ch == ':' || ch == '_'; + while (IsWhiteSpace(*p)) + { + if (curLineNumPtr && *p == '\n') + { + ++(*curLineNumPtr); + } + ++p; + } + TIXMLASSERT(p); + return p; + } + static char* SkipWhiteSpace(char* p, int* curLineNumPtr) + { + return const_cast(SkipWhiteSpace(const_cast(p), curLineNumPtr)); + } + + // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't + // correct, but simple, and usually works. + static bool IsWhiteSpace(char p) + { + return !IsUTF8Continuation(p) && isspace(static_cast(p)); + } + + inline static bool IsNameStartChar(unsigned char ch) + { + if (ch >= 128) + { + // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() + return true; } - - inline static bool IsNameChar( unsigned char ch ) { - return IsNameStartChar( ch ) - || isdigit( ch ) - || ch == '.' - || ch == '-'; + if (isalpha(ch)) + { + return true; } + return ch == ':' || ch == '_'; + } - inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { - if ( p == q ) { - return true; - } - TIXMLASSERT( p ); - TIXMLASSERT( q ); - TIXMLASSERT( nChar >= 0 ); - return strncmp( p, q, nChar ) == 0; - } - - inline static bool IsUTF8Continuation( char p ) { - return ( p & 0x80 ) != 0; - } + inline static bool IsNameChar(unsigned char ch) + { + return IsNameStartChar(ch) || isdigit(ch) || ch == '.' || ch == '-'; + } - static const char* ReadBOM( const char* p, bool* hasBOM ); - // p is the starting location, - // the UTF-8 value of the entity will be placed in value, and length filled in. - static const char* GetCharacterRef( const char* p, char* value, int* length ); - static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); - - // converts primitive types to strings - static void ToStr( int v, char* buffer, int bufferSize ); - static void ToStr( unsigned v, char* buffer, int bufferSize ); - static void ToStr( bool v, char* buffer, int bufferSize ); - static void ToStr( float v, char* buffer, int bufferSize ); - static void ToStr( double v, char* buffer, int bufferSize ); - static void ToStr(int64_t v, char* buffer, int bufferSize); - - // converts strings to primitive types - static bool ToInt( const char* str, int* value ); - static bool ToUnsigned( const char* str, unsigned* value ); - static bool ToBool( const char* str, bool* value ); - static bool ToFloat( const char* str, float* value ); - static bool ToDouble( const char* str, double* value ); - static bool ToInt64(const char* str, int64_t* value); - - // Changes what is serialized for a boolean value. - // Default to "true" and "false". Shouldn't be changed - // unless you have a special testing or compatibility need. - // Be careful: static, global, & not thread safe. - // Be sure to set static const memory as parameters. - static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); + inline static bool StringEqual(const char* p, const char* q, int nChar = INT_MAX) + { + if (p == q) + { + return true; + } + TIXMLASSERT(p); + TIXMLASSERT(q); + TIXMLASSERT(nChar >= 0); + return strncmp(p, q, nChar) == 0; + } + + inline static bool IsUTF8Continuation(char p) { return (p & 0x80) != 0; } + + static const char* ReadBOM(const char* p, bool* hasBOM); + // p is the starting location, + // the UTF-8 value of the entity will be placed in value, and length filled in. + static const char* GetCharacterRef(const char* p, char* value, int* length); + static void ConvertUTF32ToUTF8(unsigned long input, char* output, int* length); + + // converts primitive types to strings + static void ToStr(int v, char* buffer, int bufferSize); + static void ToStr(unsigned v, char* buffer, int bufferSize); + static void ToStr(bool v, char* buffer, int bufferSize); + static void ToStr(float v, char* buffer, int bufferSize); + static void ToStr(double v, char* buffer, int bufferSize); + static void ToStr(int64_t v, char* buffer, int bufferSize); + + // converts strings to primitive types + static bool ToInt(const char* str, int* value); + static bool ToUnsigned(const char* str, unsigned* value); + static bool ToBool(const char* str, bool* value); + static bool ToFloat(const char* str, float* value); + static bool ToDouble(const char* str, double* value); + static bool ToInt64(const char* str, int64_t* value); + + // Changes what is serialized for a boolean value. + // Default to "true" and "false". Shouldn't be changed + // unless you have a special testing or compatibility need. + // Be careful: static, global, & not thread safe. + // Be sure to set static const memory as parameters. + static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); private: - static const char* writeBoolTrue; - static const char* writeBoolFalse; + static const char* writeBoolTrue; + static const char* writeBoolFalse; }; @@ -659,66 +681,44 @@ class TINYXML2_LIB XMLUtil */ class TINYXML2_LIB XMLNode { - friend class XMLDocument; - friend class XMLElement; -public: - - /// Get the XMLDocument that owns this XMLNode. - const XMLDocument* GetDocument() const { - TIXMLASSERT( _document ); - return _document; - } - /// Get the XMLDocument that owns this XMLNode. - XMLDocument* GetDocument() { - TIXMLASSERT( _document ); - return _document; - } + friend class XMLDocument; + friend class XMLElement; - /// Safely cast to an Element, or null. - virtual XMLElement* ToElement() { - return 0; - } - /// Safely cast to Text, or null. - virtual XMLText* ToText() { - return 0; - } - /// Safely cast to a Comment, or null. - virtual XMLComment* ToComment() { - return 0; - } - /// Safely cast to a Document, or null. - virtual XMLDocument* ToDocument() { - return 0; - } - /// Safely cast to a Declaration, or null. - virtual XMLDeclaration* ToDeclaration() { - return 0; - } - /// Safely cast to an Unknown, or null. - virtual XMLUnknown* ToUnknown() { - return 0; - } - - virtual const XMLElement* ToElement() const { - return 0; - } - virtual const XMLText* ToText() const { - return 0; - } - virtual const XMLComment* ToComment() const { - return 0; - } - virtual const XMLDocument* ToDocument() const { - return 0; - } - virtual const XMLDeclaration* ToDeclaration() const { - return 0; - } - virtual const XMLUnknown* ToUnknown() const { - return 0; - } - - /** The meaning of 'value' changes for the specific type. +public: + /// Get the XMLDocument that owns this XMLNode. + const XMLDocument* GetDocument() const + { + TIXMLASSERT(_document); + return _document; + } + /// Get the XMLDocument that owns this XMLNode. + XMLDocument* GetDocument() + { + TIXMLASSERT(_document); + return _document; + } + + /// Safely cast to an Element, or null. + virtual XMLElement* ToElement() { return 0; } + /// Safely cast to Text, or null. + virtual XMLText* ToText() { return 0; } + /// Safely cast to a Comment, or null. + virtual XMLComment* ToComment() { return 0; } + /// Safely cast to a Document, or null. + virtual XMLDocument* ToDocument() { return 0; } + /// Safely cast to a Declaration, or null. + virtual XMLDeclaration* ToDeclaration() { return 0; } + /// Safely cast to an Unknown, or null. + virtual XMLUnknown* ToUnknown() { return 0; } + + virtual const XMLElement* ToElement() const { return 0; } + virtual const XMLText* ToText() const { return 0; } + virtual const XMLComment* ToComment() const { return 0; } + virtual const XMLDocument* ToDocument() const { return 0; } + virtual const XMLDeclaration* ToDeclaration() const { return 0; } + virtual const XMLUnknown* ToUnknown() const { return 0; } + + /** The meaning of 'value' changes for the specific type. @verbatim Document: empty (NULL is returned, not an empty string) Element: name of the element @@ -727,119 +727,99 @@ class TINYXML2_LIB XMLNode Text: the text string @endverbatim */ - const char* Value() const; + const char* Value() const; - /** Set the Value of an XML node. + /** Set the Value of an XML node. @sa Value() */ - void SetValue( const char* val, bool staticMem=false ); + void SetValue(const char* val, bool staticMem = false); - /// Gets the line number the node is in, if the document was parsed from a file. - int GetLineNum() const { return _parseLineNum; } + /// Gets the line number the node is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } - /// Get the parent of this node on the DOM. - const XMLNode* Parent() const { - return _parent; - } + /// Get the parent of this node on the DOM. + const XMLNode* Parent() const { return _parent; } - XMLNode* Parent() { - return _parent; - } + XMLNode* Parent() { return _parent; } - /// Returns true if this node has no children. - bool NoChildren() const { - return !_firstChild; - } + /// Returns true if this node has no children. + bool NoChildren() const { return !_firstChild; } - /// Get the first child node, or null if none exists. - const XMLNode* FirstChild() const { - return _firstChild; - } + /// Get the first child node, or null if none exists. + const XMLNode* FirstChild() const { return _firstChild; } - XMLNode* FirstChild() { - return _firstChild; - } + XMLNode* FirstChild() { return _firstChild; } - /** Get the first child element, or optionally the first child + /** Get the first child element, or optionally the first child element with the specified name. */ - const XMLElement* FirstChildElement( const char* name = 0 ) const; + const XMLElement* FirstChildElement(const char* name = 0) const; - XMLElement* FirstChildElement( const char* name = 0 ) { - return const_cast(const_cast(this)->FirstChildElement( name )); - } + XMLElement* FirstChildElement(const char* name = 0) + { + return const_cast(const_cast(this)->FirstChildElement(name)); + } - /// Get the last child node, or null if none exists. - const XMLNode* LastChild() const { - return _lastChild; - } + /// Get the last child node, or null if none exists. + const XMLNode* LastChild() const { return _lastChild; } - XMLNode* LastChild() { - return _lastChild; - } + XMLNode* LastChild() { return _lastChild; } - /** Get the last child element or optionally the last child + /** Get the last child element or optionally the last child element with the specified name. */ - const XMLElement* LastChildElement( const char* name = 0 ) const; + const XMLElement* LastChildElement(const char* name = 0) const; - XMLElement* LastChildElement( const char* name = 0 ) { - return const_cast(const_cast(this)->LastChildElement(name) ); - } + XMLElement* LastChildElement(const char* name = 0) + { + return const_cast(const_cast(this)->LastChildElement(name)); + } - /// Get the previous (left) sibling node of this node. - const XMLNode* PreviousSibling() const { - return _prev; - } + /// Get the previous (left) sibling node of this node. + const XMLNode* PreviousSibling() const { return _prev; } - XMLNode* PreviousSibling() { - return _prev; - } + XMLNode* PreviousSibling() { return _prev; } - /// Get the previous (left) sibling element of this node, with an optionally supplied name. - const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; + /// Get the previous (left) sibling element of this node, with an optionally supplied name. + const XMLElement* PreviousSiblingElement(const char* name = 0) const; - XMLElement* PreviousSiblingElement( const char* name = 0 ) { - return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); - } + XMLElement* PreviousSiblingElement(const char* name = 0) + { + return const_cast(const_cast(this)->PreviousSiblingElement(name)); + } - /// Get the next (right) sibling node of this node. - const XMLNode* NextSibling() const { - return _next; - } + /// Get the next (right) sibling node of this node. + const XMLNode* NextSibling() const { return _next; } - XMLNode* NextSibling() { - return _next; - } + XMLNode* NextSibling() { return _next; } - /// Get the next (right) sibling element of this node, with an optionally supplied name. - const XMLElement* NextSiblingElement( const char* name = 0 ) const; + /// Get the next (right) sibling element of this node, with an optionally supplied name. + const XMLElement* NextSiblingElement(const char* name = 0) const; - XMLElement* NextSiblingElement( const char* name = 0 ) { - return const_cast(const_cast(this)->NextSiblingElement( name ) ); - } + XMLElement* NextSiblingElement(const char* name = 0) + { + return const_cast(const_cast(this)->NextSiblingElement(name)); + } - /** + /** Add a child node as the last (right) child. If the child node is already part of the document, it is moved from its old location to the new location. Returns the addThis argument or 0 if the node does not belong to the same document. */ - XMLNode* InsertEndChild( XMLNode* addThis ); + XMLNode* InsertEndChild(XMLNode* addThis); - XMLNode* LinkEndChild( XMLNode* addThis ) { - return InsertEndChild( addThis ); - } - /** + XMLNode* LinkEndChild(XMLNode* addThis) { return InsertEndChild(addThis); } + /** Add a child node as the first (left) child. If the child node is already part of the document, it is moved from its old location to the new location. Returns the addThis argument or 0 if the node does not belong to the same document. */ - XMLNode* InsertFirstChild( XMLNode* addThis ); - /** + XMLNode* InsertFirstChild(XMLNode* addThis); + /** Add a node after the specified child node. If the child node is already part of the document, it is moved from its old location to the new location. @@ -847,19 +827,19 @@ class TINYXML2_LIB XMLNode is not a child of this node, or if the node does not belong to the same document. */ - XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); + XMLNode* InsertAfterChild(XMLNode* afterThis, XMLNode* addThis); - /** + /** Delete all the children of this node. */ - void DeleteChildren(); + void DeleteChildren(); - /** + /** Delete a child of this node. */ - void DeleteChild( XMLNode* node ); + void DeleteChild(XMLNode* node); - /** + /** Make a copy of this node, but not its children. You may pass in a Document pointer that will be the owner of the new Node. If the 'document' is @@ -868,9 +848,9 @@ class TINYXML2_LIB XMLNode Note: if called on a XMLDocument, this will return null. */ - virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; + virtual XMLNode* ShallowClone(XMLDocument* document) const = 0; - /** + /** Make a copy of this node and all its children. If the 'target' is null, then the nodes will @@ -883,17 +863,17 @@ class TINYXML2_LIB XMLNode top level XMLNodes. You probably want to use XMLDocument::DeepCopy() */ - XMLNode* DeepClone( XMLDocument* target ) const; + XMLNode* DeepClone(XMLDocument* target) const; - /** + /** Test if 2 nodes are the same, but don't test children. The 2 nodes do not need to be in the same Document. Note: if called on a XMLDocument, this will return false. */ - virtual bool ShallowEqual( const XMLNode* compare ) const = 0; + virtual bool ShallowEqual(const XMLNode* compare) const = 0; - /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the + /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the XML tree will be conditionally visited and the host will be called back via the XMLVisitor interface. @@ -915,50 +895,50 @@ class TINYXML2_LIB XMLNode const char* xmlcstr = printer.CStr(); @endverbatim */ - virtual bool Accept( XMLVisitor* visitor ) const = 0; + virtual bool Accept(XMLVisitor* visitor) const = 0; - /** + /** Set user data into the XMLNode. TinyXML-2 in no way processes or interprets user data. It is initially 0. */ - void SetUserData(void* userData) { _userData = userData; } + void SetUserData(void* userData) { _userData = userData; } - /** + /** Get user data set into the XMLNode. TinyXML-2 in no way processes or interprets user data. It is initially 0. */ - void* GetUserData() const { return _userData; } + void* GetUserData() const { return _userData; } protected: - XMLNode( XMLDocument* ); - virtual ~XMLNode(); + XMLNode(XMLDocument*); + virtual ~XMLNode(); - virtual char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); + virtual char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); - XMLDocument* _document; - XMLNode* _parent; - mutable StrPair _value; - int _parseLineNum; + XMLDocument* _document; + XMLNode* _parent; + mutable StrPair _value; + int _parseLineNum; - XMLNode* _firstChild; - XMLNode* _lastChild; + XMLNode* _firstChild; + XMLNode* _lastChild; - XMLNode* _prev; - XMLNode* _next; + XMLNode* _prev; + XMLNode* _next; - void* _userData; + void* _userData; private: - MemPool* _memPool; - void Unlink( XMLNode* child ); - static void DeleteNode( XMLNode* node ); - void InsertChildPreamble( XMLNode* insertThis ) const; - const XMLElement* ToElementWithName( const char* name ) const; - - XMLNode( const XMLNode& ); // not supported - XMLNode& operator=( const XMLNode& ); // not supported + MemPool* _memPool; + void Unlink(XMLNode* child); + static void DeleteNode(XMLNode* node); + void InsertChildPreamble(XMLNode* insertThis) const; + const XMLElement* ToElementWithName(const char* name) const; + + XMLNode(const XMLNode&); // not supported + XMLNode& operator=(const XMLNode&); // not supported }; @@ -976,69 +956,59 @@ class TINYXML2_LIB XMLNode */ class TINYXML2_LIB XMLText : public XMLNode { - friend class XMLDocument; + friend class XMLDocument; + public: - virtual bool Accept( XMLVisitor* visitor ) const; + virtual bool Accept(XMLVisitor* visitor) const; - virtual XMLText* ToText() { - return this; - } - virtual const XMLText* ToText() const { - return this; - } + virtual XMLText* ToText() { return this; } + virtual const XMLText* ToText() const { return this; } - /// Declare whether this should be CDATA or standard text. - void SetCData( bool isCData ) { - _isCData = isCData; - } - /// Returns true if this is a CDATA text element. - bool CData() const { - return _isCData; - } + /// Declare whether this should be CDATA or standard text. + void SetCData(bool isCData) { _isCData = isCData; } + /// Returns true if this is a CDATA text element. + bool CData() const { return _isCData; } - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; protected: - XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} - virtual ~XMLText() {} + XMLText(XMLDocument* doc) : XMLNode(doc), _isCData(false) {} + virtual ~XMLText() {} - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); private: - bool _isCData; + bool _isCData; - XMLText( const XMLText& ); // not supported - XMLText& operator=( const XMLText& ); // not supported + XMLText(const XMLText&); // not supported + XMLText& operator=(const XMLText&); // not supported }; /** An XML Comment. */ class TINYXML2_LIB XMLComment : public XMLNode { - friend class XMLDocument; + friend class XMLDocument; + public: - virtual XMLComment* ToComment() { - return this; - } - virtual const XMLComment* ToComment() const { - return this; - } + virtual XMLComment* ToComment() { return this; } + virtual const XMLComment* ToComment() const { return this; } - virtual bool Accept( XMLVisitor* visitor ) const; + virtual bool Accept(XMLVisitor* visitor) const; - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; protected: - XMLComment( XMLDocument* doc ); - virtual ~XMLComment(); + XMLComment(XMLDocument* doc); + virtual ~XMLComment(); - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); private: - XMLComment( const XMLComment& ); // not supported - XMLComment& operator=( const XMLComment& ); // not supported + XMLComment(const XMLComment&); // not supported + XMLComment& operator=(const XMLComment&); // not supported }; @@ -1055,29 +1025,26 @@ class TINYXML2_LIB XMLComment : public XMLNode */ class TINYXML2_LIB XMLDeclaration : public XMLNode { - friend class XMLDocument; + friend class XMLDocument; + public: - virtual XMLDeclaration* ToDeclaration() { - return this; - } - virtual const XMLDeclaration* ToDeclaration() const { - return this; - } + virtual XMLDeclaration* ToDeclaration() { return this; } + virtual const XMLDeclaration* ToDeclaration() const { return this; } - virtual bool Accept( XMLVisitor* visitor ) const; + virtual bool Accept(XMLVisitor* visitor) const; - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; protected: - XMLDeclaration( XMLDocument* doc ); - virtual ~XMLDeclaration(); + XMLDeclaration(XMLDocument* doc); + virtual ~XMLDeclaration(); - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); private: - XMLDeclaration( const XMLDeclaration& ); // not supported - XMLDeclaration& operator=( const XMLDeclaration& ); // not supported + XMLDeclaration(const XMLDeclaration&); // not supported + XMLDeclaration& operator=(const XMLDeclaration&); // not supported }; @@ -1090,33 +1057,29 @@ class TINYXML2_LIB XMLDeclaration : public XMLNode */ class TINYXML2_LIB XMLUnknown : public XMLNode { - friend class XMLDocument; + friend class XMLDocument; + public: - virtual XMLUnknown* ToUnknown() { - return this; - } - virtual const XMLUnknown* ToUnknown() const { - return this; - } + virtual XMLUnknown* ToUnknown() { return this; } + virtual const XMLUnknown* ToUnknown() const { return this; } - virtual bool Accept( XMLVisitor* visitor ) const; + virtual bool Accept(XMLVisitor* visitor) const; - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; protected: - XMLUnknown( XMLDocument* doc ); - virtual ~XMLUnknown(); + XMLUnknown(XMLDocument* doc); + virtual ~XMLUnknown(); - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); private: - XMLUnknown( const XMLUnknown& ); // not supported - XMLUnknown& operator=( const XMLUnknown& ); // not supported + XMLUnknown(const XMLUnknown&); // not supported + XMLUnknown& operator=(const XMLUnknown&); // not supported }; - /** An attribute is a name-value pair. Elements have an arbitrary number of attributes, each with a unique name. @@ -1125,111 +1088,119 @@ class TINYXML2_LIB XMLUnknown : public XMLNode */ class TINYXML2_LIB XMLAttribute { - friend class XMLElement; + friend class XMLElement; + public: - /// The name of the attribute. - const char* Name() const; + /// The name of the attribute. + const char* Name() const; - /// The value of the attribute. - const char* Value() const; + /// The value of the attribute. + const char* Value() const; - /// Gets the line number the attribute is in, if the document was parsed from a file. - int GetLineNum() const { return _parseLineNum; } + /// Gets the line number the attribute is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } - /// The next attribute in the list. - const XMLAttribute* Next() const { - return _next; - } + /// The next attribute in the list. + const XMLAttribute* Next() const { return _next; } - /** IntValue interprets the attribute as an integer, and returns the value. + /** IntValue interprets the attribute as an integer, and returns the value. If the value isn't an integer, 0 will be returned. There is no error checking; use QueryIntValue() if you need error checking. */ - int IntValue() const { - int i = 0; - QueryIntValue(&i); - return i; - } - - int64_t Int64Value() const { - int64_t i = 0; - QueryInt64Value(&i); - return i; - } - - /// Query as an unsigned integer. See IntValue() - unsigned UnsignedValue() const { - unsigned i=0; - QueryUnsignedValue( &i ); - return i; - } - /// Query as a boolean. See IntValue() - bool BoolValue() const { - bool b=false; - QueryBoolValue( &b ); - return b; - } - /// Query as a double. See IntValue() - double DoubleValue() const { - double d=0; - QueryDoubleValue( &d ); - return d; - } - /// Query as a float. See IntValue() - float FloatValue() const { - float f=0; - QueryFloatValue( &f ); - return f; - } - - /** QueryIntValue interprets the attribute as an integer, and returns the value + int IntValue() const + { + int i = 0; + QueryIntValue(&i); + return i; + } + + int64_t Int64Value() const + { + int64_t i = 0; + QueryInt64Value(&i); + return i; + } + + /// Query as an unsigned integer. See IntValue() + unsigned UnsignedValue() const + { + unsigned i = 0; + QueryUnsignedValue(&i); + return i; + } + /// Query as a boolean. See IntValue() + bool BoolValue() const + { + bool b = false; + QueryBoolValue(&b); + return b; + } + /// Query as a double. See IntValue() + double DoubleValue() const + { + double d = 0; + QueryDoubleValue(&d); + return d; + } + /// Query as a float. See IntValue() + float FloatValue() const + { + float f = 0; + QueryFloatValue(&f); + return f; + } + + /** QueryIntValue interprets the attribute as an integer, and returns the value in the provided parameter. The function will return XML_SUCCESS on success, and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. */ - XMLError QueryIntValue( int* value ) const; - /// See QueryIntValue - XMLError QueryUnsignedValue( unsigned int* value ) const; - /// See QueryIntValue - XMLError QueryInt64Value(int64_t* value) const; - /// See QueryIntValue - XMLError QueryBoolValue( bool* value ) const; - /// See QueryIntValue - XMLError QueryDoubleValue( double* value ) const; - /// See QueryIntValue - XMLError QueryFloatValue( float* value ) const; - - /// Set the attribute to a string value. - void SetAttribute( const char* value ); - /// Set the attribute to value. - void SetAttribute( int value ); - /// Set the attribute to value. - void SetAttribute( unsigned value ); - /// Set the attribute to value. - void SetAttribute(int64_t value); - /// Set the attribute to value. - void SetAttribute( bool value ); - /// Set the attribute to value. - void SetAttribute( double value ); - /// Set the attribute to value. - void SetAttribute( float value ); + XMLError QueryIntValue(int* value) const; + /// See QueryIntValue + XMLError QueryUnsignedValue(unsigned int* value) const; + /// See QueryIntValue + XMLError QueryInt64Value(int64_t* value) const; + /// See QueryIntValue + XMLError QueryBoolValue(bool* value) const; + /// See QueryIntValue + XMLError QueryDoubleValue(double* value) const; + /// See QueryIntValue + XMLError QueryFloatValue(float* value) const; + + /// Set the attribute to a string value. + void SetAttribute(const char* value); + /// Set the attribute to value. + void SetAttribute(int value); + /// Set the attribute to value. + void SetAttribute(unsigned value); + /// Set the attribute to value. + void SetAttribute(int64_t value); + /// Set the attribute to value. + void SetAttribute(bool value); + /// Set the attribute to value. + void SetAttribute(double value); + /// Set the attribute to value. + void SetAttribute(float value); private: - enum { BUF_SIZE = 200 }; + enum + { + BUF_SIZE = 200 + }; - XMLAttribute() : _name(), _value(),_parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {} - virtual ~XMLAttribute() {} + XMLAttribute() : _name(), _value(), _parseLineNum(0), _next(0), _memPool(0) {} + virtual ~XMLAttribute() {} - XMLAttribute( const XMLAttribute& ); // not supported - void operator=( const XMLAttribute& ); // not supported - void SetName( const char* name ); + XMLAttribute(const XMLAttribute&); // not supported + void operator=(const XMLAttribute&); // not supported + void SetName(const char* name); - char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr ); + char* ParseDeep(char* p, bool processEntities, int* curLineNumPtr); - mutable StrPair _name; - mutable StrPair _value; - int _parseLineNum; - XMLAttribute* _next; - MemPool* _memPool; + mutable StrPair _name; + mutable StrPair _value; + int _parseLineNum; + XMLAttribute* _next; + MemPool* _memPool; }; @@ -1239,26 +1210,19 @@ class TINYXML2_LIB XMLAttribute */ class TINYXML2_LIB XMLElement : public XMLNode { - friend class XMLDocument; + friend class XMLDocument; + public: - /// Get the name of an element (which is the Value() of the node.) - const char* Name() const { - return Value(); - } - /// Set the name of the element. - void SetName( const char* str, bool staticMem=false ) { - SetValue( str, staticMem ); - } + /// Get the name of an element (which is the Value() of the node.) + const char* Name() const { return Value(); } + /// Set the name of the element. + void SetName(const char* str, bool staticMem = false) { SetValue(str, staticMem); } - virtual XMLElement* ToElement() { - return this; - } - virtual const XMLElement* ToElement() const { - return this; - } - virtual bool Accept( XMLVisitor* visitor ) const; + virtual XMLElement* ToElement() { return this; } + virtual const XMLElement* ToElement() const { return this; } + virtual bool Accept(XMLVisitor* visitor) const; - /** Given an attribute name, Attribute() returns the value + /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. For example: @@ -1281,27 +1245,27 @@ class TINYXML2_LIB XMLElement : public XMLNode } @endverbatim */ - const char* Attribute( const char* name, const char* value=0 ) const; + const char* Attribute(const char* name, const char* value = 0) const; - /** Given an attribute name, IntAttribute() returns the value + /** Given an attribute name, IntAttribute() returns the value of the attribute interpreted as an integer. The default value will be returned if the attribute isn't present, or if there is an error. (For a method with error checking, see QueryIntAttribute()). */ - int IntAttribute(const char* name, int defaultValue = 0) const; - /// See IntAttribute() - unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; - /// See IntAttribute() - int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; - /// See IntAttribute() - bool BoolAttribute(const char* name, bool defaultValue = false) const; - /// See IntAttribute() - double DoubleAttribute(const char* name, double defaultValue = 0) const; - /// See IntAttribute() - float FloatAttribute(const char* name, float defaultValue = 0) const; - - /** Given an attribute name, QueryIntAttribute() returns + int IntAttribute(const char* name, int defaultValue = 0) const; + /// See IntAttribute() + unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; + /// See IntAttribute() + int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; + /// See IntAttribute() + bool BoolAttribute(const char* name, bool defaultValue = false) const; + /// See IntAttribute() + double DoubleAttribute(const char* name, double defaultValue = 0) const; + /// See IntAttribute() + float FloatAttribute(const char* name, float defaultValue = 0) const; + + /** Given an attribute name, QueryIntAttribute() returns XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion can't be performed, or XML_NO_ATTRIBUTE if the attribute doesn't exist. If successful, the result of the conversion @@ -1314,70 +1278,83 @@ class TINYXML2_LIB XMLElement : public XMLNode QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 @endverbatim */ - XMLError QueryIntAttribute( const char* name, int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryIntValue( value ); + XMLError QueryIntAttribute(const char* name, int* value) const + { + const XMLAttribute* a = FindAttribute(name); + if (!a) + { + return XML_NO_ATTRIBUTE; } + return a->QueryIntValue(value); + } - /// See QueryIntAttribute() - XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryUnsignedValue( value ); + /// See QueryIntAttribute() + XMLError QueryUnsignedAttribute(const char* name, unsigned int* value) const + { + const XMLAttribute* a = FindAttribute(name); + if (!a) + { + return XML_NO_ATTRIBUTE; } + return a->QueryUnsignedValue(value); + } - /// See QueryIntAttribute() - XMLError QueryInt64Attribute(const char* name, int64_t* value) const { - const XMLAttribute* a = FindAttribute(name); - if (!a) { - return XML_NO_ATTRIBUTE; - } - return a->QueryInt64Value(value); - } - - /// See QueryIntAttribute() - XMLError QueryBoolAttribute( const char* name, bool* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryBoolValue( value ); - } - /// See QueryIntAttribute() - XMLError QueryDoubleAttribute( const char* name, double* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryDoubleValue( value ); + /// See QueryIntAttribute() + XMLError QueryInt64Attribute(const char* name, int64_t* value) const + { + const XMLAttribute* a = FindAttribute(name); + if (!a) + { + return XML_NO_ATTRIBUTE; } - /// See QueryIntAttribute() - XMLError QueryFloatAttribute( const char* name, float* value ) const { - const XMLAttribute* a = FindAttribute( name ); - if ( !a ) { - return XML_NO_ATTRIBUTE; - } - return a->QueryFloatValue( value ); + return a->QueryInt64Value(value); + } + + /// See QueryIntAttribute() + XMLError QueryBoolAttribute(const char* name, bool* value) const + { + const XMLAttribute* a = FindAttribute(name); + if (!a) + { + return XML_NO_ATTRIBUTE; + } + return a->QueryBoolValue(value); + } + /// See QueryIntAttribute() + XMLError QueryDoubleAttribute(const char* name, double* value) const + { + const XMLAttribute* a = FindAttribute(name); + if (!a) + { + return XML_NO_ATTRIBUTE; + } + return a->QueryDoubleValue(value); + } + /// See QueryIntAttribute() + XMLError QueryFloatAttribute(const char* name, float* value) const + { + const XMLAttribute* a = FindAttribute(name); + if (!a) + { + return XML_NO_ATTRIBUTE; } + return a->QueryFloatValue(value); + } - /// See QueryIntAttribute() - XMLError QueryStringAttribute(const char* name, const char** value) const { - const XMLAttribute* a = FindAttribute(name); - if (!a) { - return XML_NO_ATTRIBUTE; - } - *value = a->Value(); - return XML_SUCCESS; - } + /// See QueryIntAttribute() + XMLError QueryStringAttribute(const char* name, const char** value) const + { + const XMLAttribute* a = FindAttribute(name); + if (!a) + { + return XML_NO_ATTRIBUTE; + } + *value = a->Value(); + return XML_SUCCESS; + } - - /** Given an attribute name, QueryAttribute() returns + /** Given an attribute name, QueryAttribute() returns XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion can't be performed, or XML_NO_ATTRIBUTE if the attribute doesn't exist. It is overloaded for the primitive types, @@ -1394,81 +1371,89 @@ class TINYXML2_LIB XMLElement : public XMLNode QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 @endverbatim */ - int QueryAttribute( const char* name, int* value ) const { - return QueryIntAttribute( name, value ); - } - - int QueryAttribute( const char* name, unsigned int* value ) const { - return QueryUnsignedAttribute( name, value ); - } - - int QueryAttribute(const char* name, int64_t* value) const { - return QueryInt64Attribute(name, value); - } - - int QueryAttribute( const char* name, bool* value ) const { - return QueryBoolAttribute( name, value ); - } - - int QueryAttribute( const char* name, double* value ) const { - return QueryDoubleAttribute( name, value ); - } - - int QueryAttribute( const char* name, float* value ) const { - return QueryFloatAttribute( name, value ); - } - - /// Sets the named attribute to value. - void SetAttribute( const char* name, const char* value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, int value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, unsigned value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - - /// Sets the named attribute to value. - void SetAttribute(const char* name, int64_t value) { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } - - /// Sets the named attribute to value. - void SetAttribute( const char* name, bool value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, double value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - /// Sets the named attribute to value. - void SetAttribute( const char* name, float value ) { - XMLAttribute* a = FindOrCreateAttribute( name ); - a->SetAttribute( value ); - } - - /** + int QueryAttribute(const char* name, int* value) const { return QueryIntAttribute(name, value); } + + int QueryAttribute(const char* name, unsigned int* value) const + { + return QueryUnsignedAttribute(name, value); + } + + int QueryAttribute(const char* name, int64_t* value) const + { + return QueryInt64Attribute(name, value); + } + + int QueryAttribute(const char* name, bool* value) const + { + return QueryBoolAttribute(name, value); + } + + int QueryAttribute(const char* name, double* value) const + { + return QueryDoubleAttribute(name, value); + } + + int QueryAttribute(const char* name, float* value) const + { + return QueryFloatAttribute(name, value); + } + + /// Sets the named attribute to value. + void SetAttribute(const char* name, const char* value) + { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + /// Sets the named attribute to value. + void SetAttribute(const char* name, int value) + { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + /// Sets the named attribute to value. + void SetAttribute(const char* name, unsigned value) + { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + + /// Sets the named attribute to value. + void SetAttribute(const char* name, int64_t value) + { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + + /// Sets the named attribute to value. + void SetAttribute(const char* name, bool value) + { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + /// Sets the named attribute to value. + void SetAttribute(const char* name, double value) + { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + /// Sets the named attribute to value. + void SetAttribute(const char* name, float value) + { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + + /** Delete an attribute. */ - void DeleteAttribute( const char* name ); + void DeleteAttribute(const char* name); - /// Return the first attribute in the list. - const XMLAttribute* FirstAttribute() const { - return _rootAttribute; - } - /// Query a specific attribute in the list. - const XMLAttribute* FindAttribute( const char* name ) const; + /// Return the first attribute in the list. + const XMLAttribute* FirstAttribute() const { return _rootAttribute; } + /// Query a specific attribute in the list. + const XMLAttribute* FindAttribute(const char* name) const; - /** Convenience function for easy access to the text inside an element. Although easy + /** Convenience function for easy access to the text inside an element. Although easy and concise, GetText() is limited compared to getting the XMLText child and accessing it directly. @@ -1496,9 +1481,9 @@ class TINYXML2_LIB XMLElement : public XMLNode @endverbatim GetText() will return "This is ". */ - const char* GetText() const; + const char* GetText() const; - /** Convenience function for easy access to the text inside an element. Although easy + /** Convenience function for easy access to the text inside an element. Although easy and concise, SetText() is limited compared to creating an XMLText child and mutating it directly. @@ -1532,21 +1517,21 @@ class TINYXML2_LIB XMLElement : public XMLNode Hullaballoo! @endverbatim */ - void SetText( const char* inText ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( int value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( unsigned value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(int64_t value); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( bool value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( double value ); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText( float value ); - - /** + void SetText(const char* inText); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(int value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(unsigned value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(int64_t value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(bool value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(double value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(float value); + + /** Convenience method to query the value of a child text node. This is probably best shown by example. Given you have a document is this form: @verbatim @@ -1572,73 +1557,77 @@ class TINYXML2_LIB XMLElement : public XMLNode to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. */ - XMLError QueryIntText( int* ival ) const; - /// See QueryIntText() - XMLError QueryUnsignedText( unsigned* uval ) const; - /// See QueryIntText() - XMLError QueryInt64Text(int64_t* uval) const; - /// See QueryIntText() - XMLError QueryBoolText( bool* bval ) const; - /// See QueryIntText() - XMLError QueryDoubleText( double* dval ) const; - /// See QueryIntText() - XMLError QueryFloatText( float* fval ) const; - - int IntText(int defaultValue = 0) const; - - /// See QueryIntText() - unsigned UnsignedText(unsigned defaultValue = 0) const; - /// See QueryIntText() - int64_t Int64Text(int64_t defaultValue = 0) const; - /// See QueryIntText() - bool BoolText(bool defaultValue = false) const; - /// See QueryIntText() - double DoubleText(double defaultValue = 0) const; - /// See QueryIntText() - float FloatText(float defaultValue = 0) const; - - // internal: - enum ElementClosingType { - OPEN, // - CLOSED, // - CLOSING // - }; - ElementClosingType ClosingType() const { - return _closingType; - } - virtual XMLNode* ShallowClone( XMLDocument* document ) const; - virtual bool ShallowEqual( const XMLNode* compare ) const; + XMLError QueryIntText(int* ival) const; + /// See QueryIntText() + XMLError QueryUnsignedText(unsigned* uval) const; + /// See QueryIntText() + XMLError QueryInt64Text(int64_t* uval) const; + /// See QueryIntText() + XMLError QueryBoolText(bool* bval) const; + /// See QueryIntText() + XMLError QueryDoubleText(double* dval) const; + /// See QueryIntText() + XMLError QueryFloatText(float* fval) const; + + int IntText(int defaultValue = 0) const; + + /// See QueryIntText() + unsigned UnsignedText(unsigned defaultValue = 0) const; + /// See QueryIntText() + int64_t Int64Text(int64_t defaultValue = 0) const; + /// See QueryIntText() + bool BoolText(bool defaultValue = false) const; + /// See QueryIntText() + double DoubleText(double defaultValue = 0) const; + /// See QueryIntText() + float FloatText(float defaultValue = 0) const; + + // internal: + enum ElementClosingType + { + OPEN, // + CLOSED, // + CLOSING // + }; + ElementClosingType ClosingType() const { return _closingType; } + virtual XMLNode* ShallowClone(XMLDocument* document) const; + virtual bool ShallowEqual(const XMLNode* compare) const; protected: - char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); + char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); private: - XMLElement( XMLDocument* doc ); - virtual ~XMLElement(); - XMLElement( const XMLElement& ); // not supported - void operator=( const XMLElement& ); // not supported - - XMLAttribute* FindAttribute( const char* name ) { - return const_cast(const_cast(this)->FindAttribute( name )); - } - XMLAttribute* FindOrCreateAttribute( const char* name ); - //void LinkAttribute( XMLAttribute* attrib ); - char* ParseAttributes( char* p, int* curLineNumPtr ); - static void DeleteAttribute( XMLAttribute* attribute ); - XMLAttribute* CreateAttribute(); - - enum { BUF_SIZE = 200 }; - ElementClosingType _closingType; - // The attribute list is ordered; there is no 'lastAttribute' - // because the list needs to be scanned for dupes before adding - // a new attribute. - XMLAttribute* _rootAttribute; + XMLElement(XMLDocument* doc); + virtual ~XMLElement(); + XMLElement(const XMLElement&); // not supported + void operator=(const XMLElement&); // not supported + + XMLAttribute* FindAttribute(const char* name) + { + return const_cast(const_cast(this)->FindAttribute(name)); + } + XMLAttribute* FindOrCreateAttribute(const char* name); + //void LinkAttribute( XMLAttribute* attrib ); + char* ParseAttributes(char* p, int* curLineNumPtr); + static void DeleteAttribute(XMLAttribute* attribute); + XMLAttribute* CreateAttribute(); + + enum + { + BUF_SIZE = 200 + }; + ElementClosingType _closingType; + // The attribute list is ordered; there is no 'lastAttribute' + // because the list needs to be scanned for dupes before adding + // a new attribute. + XMLAttribute* _rootAttribute; }; -enum Whitespace { - PRESERVE_WHITESPACE, - COLLAPSE_WHITESPACE +enum Whitespace +{ + PRESERVE_WHITESPACE, + COLLAPSE_WHITESPACE }; @@ -1649,29 +1638,32 @@ enum Whitespace { */ class TINYXML2_LIB XMLDocument : public XMLNode { - friend class XMLElement; - // Gives access to SetError, but over-access for everything else. - // Wishing C++ had "internal" scope. - friend class XMLNode; - friend class XMLText; - friend class XMLComment; - friend class XMLDeclaration; - friend class XMLUnknown; -public: - /// constructor - XMLDocument( bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE ); - ~XMLDocument(); - - virtual XMLDocument* ToDocument() { - TIXMLASSERT( this == _document ); - return this; - } - virtual const XMLDocument* ToDocument() const { - TIXMLASSERT( this == _document ); - return this; - } + friend class XMLElement; + // Gives access to SetError, but over-access for everything else. + // Wishing C++ had "internal" scope. + friend class XMLNode; + friend class XMLText; + friend class XMLComment; + friend class XMLDeclaration; + friend class XMLUnknown; - /** +public: + /// constructor + XMLDocument(bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE); + ~XMLDocument(); + + virtual XMLDocument* ToDocument() + { + TIXMLASSERT(this == _document); + return this; + } + virtual const XMLDocument* ToDocument() const + { + TIXMLASSERT(this == _document); + return this; + } + + /** Parse an XML file from a character string. Returns XML_SUCCESS (0) on success, or an errorID. @@ -1681,16 +1673,16 @@ class TINYXML2_LIB XMLDocument : public XMLNode specified, TinyXML-2 will assume 'xml' points to a null terminated string. */ - XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); + XMLError Parse(const char* xml, size_t nBytes = (size_t)(-1)); - /** + /** Load an XML file from disk. Returns XML_SUCCESS (0) on success, or an errorID. */ - XMLError LoadFile( const char* filename ); + XMLError LoadFile(const char* filename); - /** + /** Load an XML file from disk. You are responsible for providing and closing the FILE*. @@ -1701,54 +1693,42 @@ class TINYXML2_LIB XMLDocument : public XMLNode Returns XML_SUCCESS (0) on success, or an errorID. */ - XMLError LoadFile( FILE* ); + XMLError LoadFile(FILE*); - /** + /** Save the XML file to disk. Returns XML_SUCCESS (0) on success, or an errorID. */ - XMLError SaveFile( const char* filename, bool compact = false ); + XMLError SaveFile(const char* filename, bool compact = false); - /** + /** Save the XML file to disk. You are responsible for providing and closing the FILE*. Returns XML_SUCCESS (0) on success, or an errorID. */ - XMLError SaveFile( FILE* fp, bool compact = false ); + XMLError SaveFile(FILE* fp, bool compact = false); - bool ProcessEntities() const { - return _processEntities; - } - Whitespace WhitespaceMode() const { - return _whitespaceMode; - } + bool ProcessEntities() const { return _processEntities; } + Whitespace WhitespaceMode() const { return _whitespaceMode; } - /** + /** Returns true if this document has a leading Byte Order Mark of UTF8. */ - bool HasBOM() const { - return _writeBOM; - } - /** Sets whether to write the BOM when writing the file. + bool HasBOM() const { return _writeBOM; } + /** Sets whether to write the BOM when writing the file. */ - void SetBOM( bool useBOM ) { - _writeBOM = useBOM; - } + void SetBOM(bool useBOM) { _writeBOM = useBOM; } - /** Return the root element of DOM. Equivalent to FirstChildElement(). + /** Return the root element of DOM. Equivalent to FirstChildElement(). To get the first node, use FirstChild(). */ - XMLElement* RootElement() { - return FirstChildElement(); - } - const XMLElement* RootElement() const { - return FirstChildElement(); - } + XMLElement* RootElement() { return FirstChildElement(); } + const XMLElement* RootElement() const { return FirstChildElement(); } - /** Print the Document. If the Printer is not provided, it will + /** Print the Document. If the Printer is not provided, it will print to stdout. If you provide Printer, this can print to a file: @verbatim XMLPrinter printer( fp ); @@ -1762,28 +1742,28 @@ class TINYXML2_LIB XMLDocument : public XMLNode // printer.CStr() has a const char* to the XML @endverbatim */ - void Print( XMLPrinter* streamer=0 ) const; - virtual bool Accept( XMLVisitor* visitor ) const; + void Print(XMLPrinter* streamer = 0) const; + virtual bool Accept(XMLVisitor* visitor) const; - /** + /** Create a new Element associated with this Document. The memory for the Element is managed by the Document. */ - XMLElement* NewElement( const char* name ); - /** + XMLElement* NewElement(const char* name); + /** Create a new Comment associated with this Document. The memory for the Comment is managed by the Document. */ - XMLComment* NewComment( const char* comment ); - /** + XMLComment* NewComment(const char* comment); + /** Create a new Text associated with this Document. The memory for the Text is managed by the Document. */ - XMLText* NewText( const char* text ); - /** + XMLText* NewText(const char* text); + /** Create a new Declaration associated with this Document. The memory for the object is managed by the Document. @@ -1794,120 +1774,107 @@ class TINYXML2_LIB XMLDocument : public XMLNode @endverbatim */ - XMLDeclaration* NewDeclaration( const char* text=0 ); - /** + XMLDeclaration* NewDeclaration(const char* text = 0); + /** Create a new Unknown associated with this Document. The memory for the object is managed by the Document. */ - XMLUnknown* NewUnknown( const char* text ); + XMLUnknown* NewUnknown(const char* text); - /** + /** Delete a node associated with this document. It will be unlinked from the DOM. */ - void DeleteNode( XMLNode* node ); + void DeleteNode(XMLNode* node); - void ClearError() { - SetError(XML_SUCCESS, 0, 0); - } + void ClearError() { SetError(XML_SUCCESS, 0, 0); } - /// Return true if there was an error parsing the document. - bool Error() const { - return _errorID != XML_SUCCESS; - } - /// Return the errorID. - XMLError ErrorID() const { - return _errorID; - } - const char* ErrorName() const; - static const char* ErrorIDToName(XMLError errorID); + /// Return true if there was an error parsing the document. + bool Error() const { return _errorID != XML_SUCCESS; } + /// Return the errorID. + XMLError ErrorID() const { return _errorID; } + const char* ErrorName() const; + static const char* ErrorIDToName(XMLError errorID); - /** Returns a "long form" error description. A hopefully helpful + /** Returns a "long form" error description. A hopefully helpful diagnostic with location, line number, and/or additional info. */ - const char* ErrorStr() const; + const char* ErrorStr() const; - /// A (trivial) utility function that prints the ErrorStr() to stdout. - void PrintError() const; + /// A (trivial) utility function that prints the ErrorStr() to stdout. + void PrintError() const; - /// Return the line where the error occured, or zero if unknown. - int ErrorLineNum() const - { - return _errorLineNum; - } - - /// Clear the document, resetting it to the initial state. - void Clear(); + /// Return the line where the error occured, or zero if unknown. + int ErrorLineNum() const { return _errorLineNum; } + + /// Clear the document, resetting it to the initial state. + void Clear(); - /** + /** Copies this document to a target document. The target will be completely cleared before the copy. If you want to copy a sub-tree, see XMLNode::DeepClone(). NOTE: that the 'target' must be non-null. */ - void DeepCopy(XMLDocument* target) const; + void DeepCopy(XMLDocument* target) const; - // internal - char* Identify( char* p, XMLNode** node ); + // internal + char* Identify(char* p, XMLNode** node); - // internal - void MarkInUse(XMLNode*); + // internal + void MarkInUse(XMLNode*); - virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { - return 0; - } - virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { - return false; - } + virtual XMLNode* ShallowClone(XMLDocument* /*document*/) const { return 0; } + virtual bool ShallowEqual(const XMLNode* /*compare*/) const { return false; } private: - XMLDocument( const XMLDocument& ); // not supported - void operator=( const XMLDocument& ); // not supported - - bool _writeBOM; - bool _processEntities; - XMLError _errorID; - Whitespace _whitespaceMode; - mutable StrPair _errorStr; - int _errorLineNum; - char* _charBuffer; - int _parseCurLineNum; - // Memory tracking does add some overhead. - // However, the code assumes that you don't - // have a bunch of unlinked nodes around. - // Therefore it takes less memory to track - // in the document vs. a linked list in the XMLNode, - // and the performance is the same. - DynArray _unlinked; - - MemPoolT< sizeof(XMLElement) > _elementPool; - MemPoolT< sizeof(XMLAttribute) > _attributePool; - MemPoolT< sizeof(XMLText) > _textPool; - MemPoolT< sizeof(XMLComment) > _commentPool; - - static const char* _errorNames[XML_ERROR_COUNT]; - - void Parse(); - - void SetError( XMLError error, int lineNum, const char* format, ... ); - - template - NodeType* CreateUnlinkedNode( MemPoolT& pool ); + XMLDocument(const XMLDocument&); // not supported + void operator=(const XMLDocument&); // not supported + + bool _writeBOM; + bool _processEntities; + XMLError _errorID; + Whitespace _whitespaceMode; + mutable StrPair _errorStr; + int _errorLineNum; + char* _charBuffer; + int _parseCurLineNum; + // Memory tracking does add some overhead. + // However, the code assumes that you don't + // have a bunch of unlinked nodes around. + // Therefore it takes less memory to track + // in the document vs. a linked list in the XMLNode, + // and the performance is the same. + DynArray _unlinked; + + MemPoolT _elementPool; + MemPoolT _attributePool; + MemPoolT _textPool; + MemPoolT _commentPool; + + static const char* _errorNames[XML_ERROR_COUNT]; + + void Parse(); + + void SetError(XMLError error, int lineNum, const char* format, ...); + + template + NodeType* CreateUnlinkedNode(MemPoolT& pool); }; template -inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT& pool ) +inline NodeType* XMLDocument::CreateUnlinkedNode(MemPoolT& pool) { - TIXMLASSERT( sizeof( NodeType ) == PoolElementSize ); - TIXMLASSERT( sizeof( NodeType ) == pool.ItemSize() ); - NodeType* returnNode = new (pool.Alloc()) NodeType( this ); - TIXMLASSERT( returnNode ); - returnNode->_memPool = &pool; - - _unlinked.Push(returnNode); - return returnNode; + TIXMLASSERT(sizeof(NodeType) == PoolElementSize); + TIXMLASSERT(sizeof(NodeType) == pool.ItemSize()); + NodeType* returnNode = new (pool.Alloc()) NodeType(this); + TIXMLASSERT(returnNode); + returnNode->_memPool = &pool; + + _unlinked.Push(returnNode); + return returnNode; } /** @@ -1968,77 +1935,61 @@ inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT& poo class TINYXML2_LIB XMLHandle { public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - XMLHandle( XMLNode* node ) : _node( node ) { - } - /// Create a handle from a node. - XMLHandle( XMLNode& node ) : _node( &node ) { - } - /// Copy constructor - XMLHandle( const XMLHandle& ref ) : _node( ref._node ) { - } - /// Assignment - XMLHandle& operator=( const XMLHandle& ref ) { - _node = ref._node; - return *this; - } - - /// Get the first child of this handle. - XMLHandle FirstChild() { - return XMLHandle( _node ? _node->FirstChild() : 0 ); - } - /// Get the first child element of this handle. - XMLHandle FirstChildElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); - } - /// Get the last child of this handle. - XMLHandle LastChild() { - return XMLHandle( _node ? _node->LastChild() : 0 ); - } - /// Get the last child element of this handle. - XMLHandle LastChildElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); - } - /// Get the previous sibling of this handle. - XMLHandle PreviousSibling() { - return XMLHandle( _node ? _node->PreviousSibling() : 0 ); - } - /// Get the previous sibling element of this handle. - XMLHandle PreviousSiblingElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); - } - /// Get the next sibling of this handle. - XMLHandle NextSibling() { - return XMLHandle( _node ? _node->NextSibling() : 0 ); - } - /// Get the next sibling element of this handle. - XMLHandle NextSiblingElement( const char* name = 0 ) { - return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); - } - - /// Safe cast to XMLNode. This can return null. - XMLNode* ToNode() { - return _node; - } - /// Safe cast to XMLElement. This can return null. - XMLElement* ToElement() { - return ( _node ? _node->ToElement() : 0 ); - } - /// Safe cast to XMLText. This can return null. - XMLText* ToText() { - return ( _node ? _node->ToText() : 0 ); - } - /// Safe cast to XMLUnknown. This can return null. - XMLUnknown* ToUnknown() { - return ( _node ? _node->ToUnknown() : 0 ); - } - /// Safe cast to XMLDeclaration. This can return null. - XMLDeclaration* ToDeclaration() { - return ( _node ? _node->ToDeclaration() : 0 ); - } + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + XMLHandle(XMLNode* node) : _node(node) {} + /// Create a handle from a node. + XMLHandle(XMLNode& node) : _node(&node) {} + /// Copy constructor + XMLHandle(const XMLHandle& ref) : _node(ref._node) {} + /// Assignment + XMLHandle& operator=(const XMLHandle& ref) + { + _node = ref._node; + return *this; + } + + /// Get the first child of this handle. + XMLHandle FirstChild() { return XMLHandle(_node ? _node->FirstChild() : 0); } + /// Get the first child element of this handle. + XMLHandle FirstChildElement(const char* name = 0) + { + return XMLHandle(_node ? _node->FirstChildElement(name) : 0); + } + /// Get the last child of this handle. + XMLHandle LastChild() { return XMLHandle(_node ? _node->LastChild() : 0); } + /// Get the last child element of this handle. + XMLHandle LastChildElement(const char* name = 0) + { + return XMLHandle(_node ? _node->LastChildElement(name) : 0); + } + /// Get the previous sibling of this handle. + XMLHandle PreviousSibling() { return XMLHandle(_node ? _node->PreviousSibling() : 0); } + /// Get the previous sibling element of this handle. + XMLHandle PreviousSiblingElement(const char* name = 0) + { + return XMLHandle(_node ? _node->PreviousSiblingElement(name) : 0); + } + /// Get the next sibling of this handle. + XMLHandle NextSibling() { return XMLHandle(_node ? _node->NextSibling() : 0); } + /// Get the next sibling element of this handle. + XMLHandle NextSiblingElement(const char* name = 0) + { + return XMLHandle(_node ? _node->NextSiblingElement(name) : 0); + } + + /// Safe cast to XMLNode. This can return null. + XMLNode* ToNode() { return _node; } + /// Safe cast to XMLElement. This can return null. + XMLElement* ToElement() { return (_node ? _node->ToElement() : 0); } + /// Safe cast to XMLText. This can return null. + XMLText* ToText() { return (_node ? _node->ToText() : 0); } + /// Safe cast to XMLUnknown. This can return null. + XMLUnknown* ToUnknown() { return (_node ? _node->ToUnknown() : 0); } + /// Safe cast to XMLDeclaration. This can return null. + XMLDeclaration* ToDeclaration() { return (_node ? _node->ToDeclaration() : 0); } private: - XMLNode* _node; + XMLNode* _node; }; @@ -2049,62 +2000,55 @@ class TINYXML2_LIB XMLHandle class TINYXML2_LIB XMLConstHandle { public: - XMLConstHandle( const XMLNode* node ) : _node( node ) { - } - XMLConstHandle( const XMLNode& node ) : _node( &node ) { - } - XMLConstHandle( const XMLConstHandle& ref ) : _node( ref._node ) { - } - - XMLConstHandle& operator=( const XMLConstHandle& ref ) { - _node = ref._node; - return *this; - } - - const XMLConstHandle FirstChild() const { - return XMLConstHandle( _node ? _node->FirstChild() : 0 ); - } - const XMLConstHandle FirstChildElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); - } - const XMLConstHandle LastChild() const { - return XMLConstHandle( _node ? _node->LastChild() : 0 ); - } - const XMLConstHandle LastChildElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); - } - const XMLConstHandle PreviousSibling() const { - return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); - } - const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); - } - const XMLConstHandle NextSibling() const { - return XMLConstHandle( _node ? _node->NextSibling() : 0 ); - } - const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { - return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); - } - - - const XMLNode* ToNode() const { - return _node; - } - const XMLElement* ToElement() const { - return ( _node ? _node->ToElement() : 0 ); - } - const XMLText* ToText() const { - return ( _node ? _node->ToText() : 0 ); - } - const XMLUnknown* ToUnknown() const { - return ( _node ? _node->ToUnknown() : 0 ); - } - const XMLDeclaration* ToDeclaration() const { - return ( _node ? _node->ToDeclaration() : 0 ); - } + XMLConstHandle(const XMLNode* node) : _node(node) {} + XMLConstHandle(const XMLNode& node) : _node(&node) {} + XMLConstHandle(const XMLConstHandle& ref) : _node(ref._node) {} + + XMLConstHandle& operator=(const XMLConstHandle& ref) + { + _node = ref._node; + return *this; + } + + const XMLConstHandle FirstChild() const + { + return XMLConstHandle(_node ? _node->FirstChild() : 0); + } + const XMLConstHandle FirstChildElement(const char* name = 0) const + { + return XMLConstHandle(_node ? _node->FirstChildElement(name) : 0); + } + const XMLConstHandle LastChild() const { return XMLConstHandle(_node ? _node->LastChild() : 0); } + const XMLConstHandle LastChildElement(const char* name = 0) const + { + return XMLConstHandle(_node ? _node->LastChildElement(name) : 0); + } + const XMLConstHandle PreviousSibling() const + { + return XMLConstHandle(_node ? _node->PreviousSibling() : 0); + } + const XMLConstHandle PreviousSiblingElement(const char* name = 0) const + { + return XMLConstHandle(_node ? _node->PreviousSiblingElement(name) : 0); + } + const XMLConstHandle NextSibling() const + { + return XMLConstHandle(_node ? _node->NextSibling() : 0); + } + const XMLConstHandle NextSiblingElement(const char* name = 0) const + { + return XMLConstHandle(_node ? _node->NextSiblingElement(name) : 0); + } + + + const XMLNode* ToNode() const { return _node; } + const XMLElement* ToElement() const { return (_node ? _node->ToElement() : 0); } + const XMLText* ToText() const { return (_node ? _node->ToText() : 0); } + const XMLUnknown* ToUnknown() const { return (_node ? _node->ToUnknown() : 0); } + const XMLDeclaration* ToDeclaration() const { return (_node ? _node->ToDeclaration() : 0); } private: - const XMLNode* _node; + const XMLNode* _node; }; @@ -2153,135 +2097,131 @@ class TINYXML2_LIB XMLConstHandle class TINYXML2_LIB XMLPrinter : public XMLVisitor { public: - /** Construct the printer. If the FILE* is specified, + /** Construct the printer. If the FILE* is specified, this will print to the FILE. Else it will print to memory, and the result is available in CStr(). If 'compact' is set to true, then output is created with only required whitespace and newlines. */ - XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); - virtual ~XMLPrinter() {} + XMLPrinter(FILE* file = 0, bool compact = false, int depth = 0); + virtual ~XMLPrinter() {} - /** If streaming, write the BOM and declaration. */ - void PushHeader( bool writeBOM, bool writeDeclaration ); - /** If streaming, start writing an element. + /** If streaming, write the BOM and declaration. */ + void PushHeader(bool writeBOM, bool writeDeclaration); + /** If streaming, start writing an element. The element must be closed with CloseElement() */ - void OpenElement( const char* name, bool compactMode=false ); - /// If streaming, add an attribute to an open element. - void PushAttribute( const char* name, const char* value ); - void PushAttribute( const char* name, int value ); - void PushAttribute( const char* name, unsigned value ); - void PushAttribute(const char* name, int64_t value); - void PushAttribute( const char* name, bool value ); - void PushAttribute( const char* name, double value ); - /// If streaming, close the Element. - virtual void CloseElement( bool compactMode=false ); - - /// Add a text node. - void PushText( const char* text, bool cdata=false ); - /// Add a text node from an integer. - void PushText( int value ); - /// Add a text node from an unsigned. - void PushText( unsigned value ); - /// Add a text node from an unsigned. - void PushText(int64_t value); - /// Add a text node from a bool. - void PushText( bool value ); - /// Add a text node from a float. - void PushText( float value ); - /// Add a text node from a double. - void PushText( double value ); - - /// Add a comment - void PushComment( const char* comment ); - - void PushDeclaration( const char* value ); - void PushUnknown( const char* value ); - - virtual bool VisitEnter( const XMLDocument& /*doc*/ ); - virtual bool VisitExit( const XMLDocument& /*doc*/ ) { - return true; - } - - virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); - virtual bool VisitExit( const XMLElement& element ); - - virtual bool Visit( const XMLText& text ); - virtual bool Visit( const XMLComment& comment ); - virtual bool Visit( const XMLDeclaration& declaration ); - virtual bool Visit( const XMLUnknown& unknown ); - - /** + void OpenElement(const char* name, bool compactMode = false); + /// If streaming, add an attribute to an open element. + void PushAttribute(const char* name, const char* value); + void PushAttribute(const char* name, int value); + void PushAttribute(const char* name, unsigned value); + void PushAttribute(const char* name, int64_t value); + void PushAttribute(const char* name, bool value); + void PushAttribute(const char* name, double value); + /// If streaming, close the Element. + virtual void CloseElement(bool compactMode = false); + + /// Add a text node. + void PushText(const char* text, bool cdata = false); + /// Add a text node from an integer. + void PushText(int value); + /// Add a text node from an unsigned. + void PushText(unsigned value); + /// Add a text node from an unsigned. + void PushText(int64_t value); + /// Add a text node from a bool. + void PushText(bool value); + /// Add a text node from a float. + void PushText(float value); + /// Add a text node from a double. + void PushText(double value); + + /// Add a comment + void PushComment(const char* comment); + + void PushDeclaration(const char* value); + void PushUnknown(const char* value); + + virtual bool VisitEnter(const XMLDocument& /*doc*/); + virtual bool VisitExit(const XMLDocument& /*doc*/) { return true; } + + virtual bool VisitEnter(const XMLElement& element, const XMLAttribute* attribute); + virtual bool VisitExit(const XMLElement& element); + + virtual bool Visit(const XMLText& text); + virtual bool Visit(const XMLComment& comment); + virtual bool Visit(const XMLDeclaration& declaration); + virtual bool Visit(const XMLUnknown& unknown); + + /** If in print to memory mode, return a pointer to the XML file in memory. */ - const char* CStr() const { - return _buffer.Mem(); - } - /** + const char* CStr() const { return _buffer.Mem(); } + /** If in print to memory mode, return the size of the XML file in memory. (Note the size returned includes the terminating null.) */ - int CStrSize() const { - return _buffer.Size(); - } - /** + int CStrSize() const { return _buffer.Size(); } + /** If in print to memory mode, reset the buffer to the beginning. */ - void ClearBuffer() { - _buffer.Clear(); - _buffer.Push(0); - _firstElement = true; - } + void ClearBuffer() + { + _buffer.Clear(); + _buffer.Push(0); + _firstElement = true; + } protected: - virtual bool CompactMode( const XMLElement& ) { return _compactMode; } + virtual bool CompactMode(const XMLElement&) { return _compactMode; } - /** Prints out the space before an element. You may override to change + /** Prints out the space before an element. You may override to change the space and tabs used. A PrintSpace() override should call Print(). */ - virtual void PrintSpace( int depth ); - void Print( const char* format, ... ); - void Write( const char* data, size_t size ); - inline void Write( const char* data ) { Write( data, strlen( data ) ); } - void Putc( char ch ); + virtual void PrintSpace(int depth); + void Print(const char* format, ...); + void Write(const char* data, size_t size); + inline void Write(const char* data) { Write(data, strlen(data)); } + void Putc(char ch); - void SealElementIfJustOpened(); - bool _elementJustOpened; - DynArray< const char*, 10 > _stack; + void SealElementIfJustOpened(); + bool _elementJustOpened; + DynArray _stack; private: - void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. - - bool _firstElement; - FILE* _fp; - int _depth; - int _textDepth; - bool _processEntities; - bool _compactMode; - - enum { - ENTITY_RANGE = 64, - BUF_SIZE = 200 - }; - bool _entityFlag[ENTITY_RANGE]; - bool _restrictedEntityFlag[ENTITY_RANGE]; - - DynArray< char, 20 > _buffer; - - // Prohibit cloning, intentionally not implemented - XMLPrinter( const XMLPrinter& ); - XMLPrinter& operator=( const XMLPrinter& ); + void PrintString(const char*, bool restrictedEntitySet); // prints out, after detecting entities. + + bool _firstElement; + FILE* _fp; + int _depth; + int _textDepth; + bool _processEntities; + bool _compactMode; + + enum + { + ENTITY_RANGE = 64, + BUF_SIZE = 200 + }; + bool _entityFlag[ENTITY_RANGE]; + bool _restrictedEntityFlag[ENTITY_RANGE]; + + DynArray _buffer; + + // Prohibit cloning, intentionally not implemented + XMLPrinter(const XMLPrinter&); + XMLPrinter& operator=(const XMLPrinter&); }; -} // tinyxml2 +} // namespace tinyxml2 #if defined(_MSC_VER) -# pragma warning(pop) +#pragma warning(pop) #endif #endif // TINYXML2_INCLUDED diff --git a/src/config.h.cmake.in b/src/config.h.cmake.in index 02f9009ed..41f5236ef 100644 --- a/src/config.h.cmake.in +++ b/src/config.h.cmake.in @@ -9,128 +9,127 @@ #define QMCPLUSPLUS_CONFIGURATION_H /* define the major version */ -#define QMCPACK_VERSION_MAJOR @QMCPACK_VERSION_MAJOR@ +#define QMCPACK_VERSION_MAJOR @QMCPACK_VERSION_MAJOR @ /* define the minor version */ -#define QMCPACK_VERSION_MINOR @QMCPACK_VERSION_MINOR@ +#define QMCPACK_VERSION_MINOR @QMCPACK_VERSION_MINOR @ /* define the patch version */ -#define QMCPACK_VERSION_PATCH @QMCPACK_VERSION_PATCH@ +#define QMCPACK_VERSION_PATCH @QMCPACK_VERSION_PATCH @ /* define the release version */ -#cmakedefine QMCPACK_RELEASE @QMCAPCK_RELEASE@ +#cmakedefine QMCPACK_RELEASE @QMCAPCK_RELEASE @ /* define the git last commit date */ // #cmakedefine QMCPLUSPLUS_LAST_CHANGED_DATE "@QMCPLUSPLUS_LAST_CHANGED_DATE@" /* define QMC_BUILD_LEVEL */ -#cmakedefine QMC_BUILD_LEVEL @QMC_BUILD_LEVEL@ +#cmakedefine QMC_BUILD_LEVEL @QMC_BUILD_LEVEL @ /* Enable OpenMP parallelization. */ -#cmakedefine ENABLE_OPENMP @ENABLE_OPENMP@ +#cmakedefine ENABLE_OPENMP @ENABLE_OPENMP @ /* Define to 1 if you have the `hdf5' library (-lhdf5). */ -#cmakedefine HAVE_LIBHDF5 @HAVE_LIBHDF5@ +#cmakedefine HAVE_LIBHDF5 @HAVE_LIBHDF5 @ /* Define to 1 if you want to use parallel hdf5 for frequent output */ -#cmakedefine ENABLE_PHDF5 @ENABLE_PHDF5@ +#cmakedefine ENABLE_PHDF5 @ENABLE_PHDF5 @ /* Define to 1 if you have MPI library */ -#cmakedefine HAVE_MPI @HAVE_MPI@ +#cmakedefine HAVE_MPI @HAVE_MPI @ /* Define the physical dimension of appliation. */ -#cmakedefine OHMMS_DIM @OHMMS_DIM@ +#cmakedefine OHMMS_DIM @OHMMS_DIM @ /* Define the index type: int, long */ -#cmakedefine OHMMS_INDEXTYPE @OHMMS_INDEXTYPE@ +#cmakedefine OHMMS_INDEXTYPE @OHMMS_INDEXTYPE @ /* Define the base precision: float, double */ -#cmakedefine OHMMS_PRECISION @OHMMS_PRECISION@ +#cmakedefine OHMMS_PRECISION @OHMMS_PRECISION @ /* Define the full precision: double, long double */ -#cmakedefine OHMMS_PRECISION_FULL @OHMMS_PRECISION_FULL@ +#cmakedefine OHMMS_PRECISION_FULL @OHMMS_PRECISION_FULL @ /* Define to 1 if precision is mixed, only for the CPU code */ -#cmakedefine MIXED_PRECISION @MIXED_PRECISION@ +#cmakedefine MIXED_PRECISION @MIXED_PRECISION @ /* Define to 1 if complex wavefunctions are used */ -#cmakedefine QMC_COMPLEX @QMC_COMPLEX@ +#cmakedefine QMC_COMPLEX @QMC_COMPLEX @ /* Define if the code is specialized for orthorhombic supercell */ -#define OHMMS_ORTHO @OHMMS_ORTHO@ +#define OHMMS_ORTHO @OHMMS_ORTHO @ /* Define if sincos function exists */ -#cmakedefine HAVE_SINCOS @HAVE_SINCOS@ +#cmakedefine HAVE_SINCOS @HAVE_SINCOS @ /* Define if posix_memalign function exists */ -#cmakedefine HAVE_POSIX_MEMALIGN @HAVE_POSIX_MEMALIGN@ +#cmakedefine HAVE_POSIX_MEMALIGN @HAVE_POSIX_MEMALIGN @ /* Find mkl library */ -#cmakedefine HAVE_MKL @HAVE_MKL@ +#cmakedefine HAVE_MKL @HAVE_MKL @ /* Find mkl/vml library */ -#cmakedefine HAVE_MKL_VML @HAVE_MKL_VML@ +#cmakedefine HAVE_MKL_VML @HAVE_MKL_VML @ /* Find essl library */ -#cmakedefine HAVE_ESSL @HAVE_ESSL@ +#cmakedefine HAVE_ESSL @HAVE_ESSL @ /* Fund acml library */ -#cmakedefine HAVE_ACML @HAVE_ACML@ +#cmakedefine HAVE_ACML @HAVE_ACML @ /* For AFQMC compilation */ -#cmakedefine BUILD_AFQMC @BUILD_AFQMC@ +#cmakedefine BUILD_AFQMC @BUILD_AFQMC @ /* For FCIQMC compilation */ -#cmakedefine BUILD_FCIQMC @BUILD_FCIQMC@ +#cmakedefine BUILD_FCIQMC @BUILD_FCIQMC @ -#cmakedefine DEBUG_PSIBUFFER_ON @DEBUG_PSIBUFFER_ON@ +#cmakedefine DEBUG_PSIBUFFER_ON @DEBUG_PSIBUFFER_ON @ #if (__cplusplus >= 201103L) - #if defined(__INTEL_COMPILER) - #if defined(__KNC__) || defined(__AVX512F__) - #define QMC_CLINE 64 - #define QMC_ALIGNAS alignas(64) - #define ASSUME_ALIGNED(x) __assume_aligned(x,64) - #else - #define QMC_CLINE 32 - #define QMC_ALIGNAS alignas(32) - #define ASSUME_ALIGNED(x) __assume_aligned(x,32) - #endif - #elif defined(__GNUC__) && !defined(__ibmxl__) - #if defined(__AVX512F__) - #define QMC_CLINE 64 - #define QMC_ALIGNAS alignas(64) - #define ASSUME_ALIGNED(x) (x) = (__typeof__(x)) __builtin_assume_aligned(x,64) - #else - #define QMC_CLINE 32 - #define QMC_ALIGNAS alignas(32) - #define ASSUME_ALIGNED(x) (x) = (__typeof__(x)) __builtin_assume_aligned(x,32) - #endif - #else - #define QMC_CLINE 32 - #define QMC_ALIGNAS - #define ASSUME_ALIGNED(x) - #endif +#if defined(__INTEL_COMPILER) +#if defined(__KNC__) || defined(__AVX512F__) +#define QMC_CLINE 64 +#define QMC_ALIGNAS alignas(64) +#define ASSUME_ALIGNED(x) __assume_aligned(x, 64) +#else +#define QMC_CLINE 32 +#define QMC_ALIGNAS alignas(32) +#define ASSUME_ALIGNED(x) __assume_aligned(x, 32) +#endif +#elif defined(__GNUC__) && !defined(__ibmxl__) +#if defined(__AVX512F__) +#define QMC_CLINE 64 +#define QMC_ALIGNAS alignas(64) +#define ASSUME_ALIGNED(x) (x) = (__typeof__(x))__builtin_assume_aligned(x, 64) +#else +#define QMC_CLINE 32 +#define QMC_ALIGNAS alignas(32) +#define ASSUME_ALIGNED(x) (x) = (__typeof__(x))__builtin_assume_aligned(x, 32) +#endif +#else +#define QMC_CLINE 32 +#define QMC_ALIGNAS +#define ASSUME_ALIGNED(x) +#endif #else //capture both C or non-c++11 - #if defined(__KNC__) || defined(__AVX512F__) - #define QMC_CLINE 64 - #else - #define QMC_CLINE 32 - #endif - #define QMC_ALIGNAS - #define ASSUME_ALIGNED(x) - #ifndef nullptr - #define nullptr NULL - #endif +#if defined(__KNC__) || defined(__AVX512F__) +#define QMC_CLINE 64 +#else +#define QMC_CLINE 32 +#endif +#define QMC_ALIGNAS +#define ASSUME_ALIGNED(x) +#ifndef nullptr +#define nullptr NULL +#endif #endif /* Internal timers */ -#cmakedefine ENABLE_TIMERS @ENABLE_TIMERS@ +#cmakedefine ENABLE_TIMERS @ENABLE_TIMERS @ /* Use VTune Task API with timers */ -#cmakedefine USE_VTUNE_TASKS @USE_VTUNE_TASKS@ +#cmakedefine USE_VTUNE_TASKS @USE_VTUNE_TASKS @ #endif // QMCPLUSPLUS_CONFIGURATION_H - From 11836187b20d5cafeb7b6e692b6414eb5d9228c1 Mon Sep 17 00:00:00 2001 From: Peter Doak Date: Thu, 2 Aug 2018 13:24:13 -0400 Subject: [PATCH 2/8] fixup of #pragma's not yet treated well by clang-format --- src/Drivers/check_determinant.cpp | 2 +- src/Drivers/miniqmc.cpp | 6 +++--- src/Drivers/miniqmc_sync_move.cpp | 18 +++++++++--------- src/Numerics/PosTransformer.h | 4 ++-- src/Numerics/Spline2/MultiBspline.hpp | 10 +++++----- src/Numerics/Spline2/bspline_allocator.hpp | 2 +- src/Numerics/Spline2/einspline_allocator.cpp | 2 +- src/Particle/Lattice/ParticleBConds.h | 2 +- src/QMCWaveFunctions/Determinant.h | 4 ++-- src/QMCWaveFunctions/DeterminantRef.h | 4 ++-- src/QMCWaveFunctions/Jastrow/BsplineFunctor.h | 4 ++-- .../Jastrow/PolynomialFunctor3D.h | 6 +++--- src/QMCWaveFunctions/SPOSet.h | 6 +++--- src/QMCWaveFunctions/WaveFunctionComponent.h | 8 ++++---- src/QMCWaveFunctions/einspline_spo.hpp | 6 +++--- src/QMCWaveFunctions/einspline_spo_ref.hpp | 6 +++--- src/Utilities/NewTimer.cpp | 4 ++-- src/Utilities/NewTimer.h | 2 +- src/Utilities/SIMD/algorithm.hpp | 2 +- 19 files changed, 49 insertions(+), 49 deletions(-) diff --git a/src/Drivers/check_determinant.cpp b/src/Drivers/check_determinant.cpp index e7236a49e..30a05bf16 100644 --- a/src/Drivers/check_determinant.cpp +++ b/src/Drivers/check_determinant.cpp @@ -128,7 +128,7 @@ int main(int argc, char** argv) double accumulated_error = 0.0; -#pragma omp parallel reduction(+ : accumulated_error) + #pragma omp parallel reduction(+ : accumulated_error) { int ip = omp_get_thread_num(); diff --git a/src/Drivers/miniqmc.cpp b/src/Drivers/miniqmc.cpp index f18990640..0f4415f3c 100644 --- a/src/Drivers/miniqmc.cpp +++ b/src/Drivers/miniqmc.cpp @@ -357,7 +357,7 @@ int main(int argc, char** argv) Timers[Timer_Init]->start(); std::vector mover_list(nmovers, nullptr); // prepare movers -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) { const int ip = omp_get_thread_num(); @@ -394,7 +394,7 @@ int main(int argc, char** argv) RealType sqrttau = std::sqrt(tau); RealType accept = 0.5; -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) { auto& els = mover_list[iw]->els; @@ -501,7 +501,7 @@ int main(int argc, char** argv) Timers[Timer_Total]->stop(); // free all movers -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) delete mover_list[iw]; mover_list.clear(); diff --git a/src/Drivers/miniqmc_sync_move.cpp b/src/Drivers/miniqmc_sync_move.cpp index f77ff6d1f..ff372f83b 100644 --- a/src/Drivers/miniqmc_sync_move.cpp +++ b/src/Drivers/miniqmc_sync_move.cpp @@ -359,7 +359,7 @@ int main(int argc, char** argv) Timers[Timer_Init]->start(); std::vector mover_list(nmovers, nullptr); // prepare movers -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) { const int ip = omp_get_thread_num(); @@ -426,7 +426,7 @@ int main(int argc, char** argv) for (int iel = 0; iel < nels; ++iel) { // Operate on electron with index iel -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) mover_list[iw]->els.setActive(iel); @@ -439,7 +439,7 @@ int main(int argc, char** argv) mover_list[0]->rng.generate_uniform(ur.data(), nmovers); mover_list[0]->rng.generate_normal(&delta[0][0], nmovers3); -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) { PosType dr = sqrttau * delta[iw]; @@ -474,8 +474,8 @@ int main(int argc, char** argv) anon_mover.wavefunction.multi_acceptrestoreMove(valid_WF_list, valid_P_list, isAccepted, iel); Timers[Timer_Update]->stop(); -// Update position -#pragma omp parallel for + // Update position + #pragma omp parallel for for (int iw = 0; iw < valid_mover_list.size(); iw++) { if (isAccepted[iw]) // MC @@ -486,7 +486,7 @@ int main(int argc, char** argv) } // iel } // substeps -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) { mover_list[iw]->els.donePbyP(); @@ -499,7 +499,7 @@ int main(int argc, char** argv) // Compute NLPP energy using integral over spherical points // Ye: I have not found a strategy for NLPP Timers[Timer_ECP]->start(); -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) { auto& els = mover_list[iw]->els; @@ -537,8 +537,8 @@ int main(int argc, char** argv) } Timers[Timer_Total]->stop(); -// free all movers -#pragma omp parallel for + // free all movers + #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) delete mover_list[iw]; mover_list.clear(); diff --git a/src/Numerics/PosTransformer.h b/src/Numerics/PosTransformer.h index c13e13145..35b435083 100644 --- a/src/Numerics/PosTransformer.h +++ b/src/Numerics/PosTransformer.h @@ -35,7 +35,7 @@ void PosAoS2SoA(int nrows, int ncols, const T1* restrict iptr, int lda, T2* rest T2* restrict x = out; T2* restrict y = out + ldb; T2* restrict z = out + 2 * ldb; -#pragma omp simd aligned(x, y, z) + #pragma omp simd aligned(x, y, z) for (int i = 0; i < nrows; ++i) { x[i] = iptr[i * ncols]; // x[i]=in[i][0]; @@ -60,7 +60,7 @@ void PosSoA2AoS(int nrows, int ncols, const T1* restrict iptr, int lda, T2* rest const T1* restrict x = iptr; const T1* restrict y = iptr + lda; const T1* restrict z = iptr + 2 * lda; -#pragma omp simd aligned(x, y, z) + #pragma omp simd aligned(x, y, z) for (int i = 0; i < nrows; ++i) { out[i * ldb] = x[i]; // out[i][0]=x[i]; diff --git a/src/Numerics/Spline2/MultiBspline.hpp b/src/Numerics/Spline2/MultiBspline.hpp index 9009718ed..f95922ee7 100644 --- a/src/Numerics/Spline2/MultiBspline.hpp +++ b/src/Numerics/Spline2/MultiBspline.hpp @@ -185,8 +185,8 @@ inline void MultiBspline::evaluate_vgl(const spliner_type* restrict spline_m, const T* restrict coefs3zs = coefs + 3 * zs; ASSUME_ALIGNED(coefs3zs); -#pragma noprefetch -#pragma omp simd + #pragma noprefetch + #pragma omp simd for (int n = 0; n < num_splines; n++) { const T coefsv = coefs[n]; @@ -215,7 +215,7 @@ inline void MultiBspline::evaluate_vgl(const spliner_type* restrict spline_m, const T dyInv2 = dyInv * dyInv; const T dzInv2 = dzInv * dzInv; -#pragma omp simd + #pragma omp simd for (int n = 0; n < num_splines; n++) { gx[n] *= dxInv; @@ -308,7 +308,7 @@ inline void MultiBspline::evaluate_vgh(const spliner_type* restrict spline_m, const T pre02 = a[i] * d2b[j]; const int iSplitPoint = num_splines; -#pragma omp simd + #pragma omp simd for (int n = 0; n < iSplitPoint; n++) { T coefsv = coefs[n]; @@ -343,7 +343,7 @@ inline void MultiBspline::evaluate_vgh(const spliner_type* restrict spline_m, const T dxz = dxInv * dzInv; const T dyz = dyInv * dzInv; -#pragma omp simd + #pragma omp simd for (int n = 0; n < num_splines; n++) { gx[n] *= dxInv; diff --git a/src/Numerics/Spline2/bspline_allocator.hpp b/src/Numerics/Spline2/bspline_allocator.hpp index 37c3b72d2..ec8c3325f 100644 --- a/src/Numerics/Spline2/bspline_allocator.hpp +++ b/src/Numerics/Spline2/bspline_allocator.hpp @@ -118,7 +118,7 @@ void Allocator::setCoefficientsForOneOrbital(int i, Array& coeff, typename bspline_traits::SplineType* spline) { -#pragma omp parallel for collapse(3) + #pragma omp parallel for collapse(3) for (int ix = 0; ix < spline->x_grid.num + 3; ix++) { for (int iy = 0; iy < spline->y_grid.num + 3; iy++) diff --git a/src/Numerics/Spline2/einspline_allocator.cpp b/src/Numerics/Spline2/einspline_allocator.cpp index 8a2d81891..9d774dd90 100644 --- a/src/Numerics/Spline2/einspline_allocator.cpp +++ b/src/Numerics/Spline2/einspline_allocator.cpp @@ -145,7 +145,7 @@ multi_UBspline_3d_s* einspline_create_multi_UBspline_3d_s(Ugrid x_grid, const size_t zs = spline->z_stride; const float czero=0; -#pragma omp parallel for collapse(3) + #pragma omp parallel for collapse(3) for(size_t i=0; i constexpr T minusone(-1); constexpr T one(1); -#pragma omp simd aligned(temp_r, px, py, pz, dx, dy, dz) + #pragma omp simd aligned(temp_r, px, py, pz, dx, dy, dz) for (int iat = first; iat < last; ++iat) { const T flip = iat < flip_ind ? one : minusone; diff --git a/src/QMCWaveFunctions/Determinant.h b/src/QMCWaveFunctions/Determinant.h index f8abd9f57..947241b9f 100644 --- a/src/QMCWaveFunctions/Determinant.h +++ b/src/QMCWaveFunctions/Determinant.h @@ -160,7 +160,7 @@ void checkIdentity(const MT1& a, const MT2& b, const std::string& tag) error += (i == j) ? std::abs(e - cone) : std::abs(e); } } -#pragma omp master + #pragma omp master std::cout << tag << " difference from identity (average per element) = " << error / nrows / nrows << std::endl; } @@ -177,7 +177,7 @@ void checkDiff(const MT1& a, const MT2& b, const std::string& tag) for (int j = 0; j < ncols; ++j) error += std::abs(static_cast(a(i, j) - b(i, j))); -#pragma omp master + #pragma omp master std::cout << tag << " difference between matrices (average per element) = " << error / nrows / nrows << std::endl; } diff --git a/src/QMCWaveFunctions/DeterminantRef.h b/src/QMCWaveFunctions/DeterminantRef.h index 5e869dce5..42d3b77fb 100644 --- a/src/QMCWaveFunctions/DeterminantRef.h +++ b/src/QMCWaveFunctions/DeterminantRef.h @@ -161,7 +161,7 @@ void checkIdentity(const MT1& a, const MT2& b, const std::string& tag) error += (i == j) ? std::abs(e - cone) : std::abs(e); } } -#pragma omp master + #pragma omp master std::cout << tag << " difference from identity (average per element) = " << error / nrows / nrows << std::endl; } @@ -178,7 +178,7 @@ void checkDiff(const MT1& a, const MT2& b, const std::string& tag) for (int j = 0; j < ncols; ++j) error += std::abs(static_cast(a(i, j) - b(i, j))); -#pragma omp master + #pragma omp master std::cout << tag << " difference between matrices (average per element) = " << error / nrows / nrows << std::endl; } diff --git a/src/QMCWaveFunctions/Jastrow/BsplineFunctor.h b/src/QMCWaveFunctions/Jastrow/BsplineFunctor.h index c9726cb03..a593d8600 100644 --- a/src/QMCWaveFunctions/Jastrow/BsplineFunctor.h +++ b/src/QMCWaveFunctions/Jastrow/BsplineFunctor.h @@ -242,7 +242,7 @@ inline T BsplineFunctor::evaluateV(const int iat, } real_type d = 0.0; -#pragma omp simd reduction(+ : d) + #pragma omp simd reduction(+ : d) for (int jat = 0; jat < iCount; jat++) { real_type r = distArrayCompressed[jat]; @@ -299,7 +299,7 @@ inline void BsplineFunctor::evaluateVGL(const int iat, } } -#pragma omp simd + #pragma omp simd for (int j = 0; j < iCount; j++) { real_type r = distArrayCompressed[j]; diff --git a/src/QMCWaveFunctions/Jastrow/PolynomialFunctor3D.h b/src/QMCWaveFunctions/Jastrow/PolynomialFunctor3D.h index 27e30a8ea..1fdc4b7f5 100644 --- a/src/QMCWaveFunctions/Jastrow/PolynomialFunctor3D.h +++ b/src/QMCWaveFunctions/Jastrow/PolynomialFunctor3D.h @@ -471,9 +471,9 @@ struct PolynomialFunctor3D : public OptimizableFunctorBase constexpr real_type ctwo(2); const real_type L = chalf * cutoff_radius; -#pragma omp simd aligned(r_12_array, \ - r_1I_array, \ - r_2I_array, \ + #pragma omp simd aligned(r_12_array, \ + r_1I_array, \ + r_2I_array, \ val_array, \ grad0_array, \ grad1_array, \ diff --git a/src/QMCWaveFunctions/SPOSet.h b/src/QMCWaveFunctions/SPOSet.h index c19169b24..7cac0a9fb 100644 --- a/src/QMCWaveFunctions/SPOSet.h +++ b/src/QMCWaveFunctions/SPOSet.h @@ -47,7 +47,7 @@ class SPOSet : public QMCTraits virtual void multi_evaluate_v(const std::vector& spo_list, const std::vector& pos_list) { -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < spo_list.size(); iw++) spo_list[iw]->evaluate_v(pos_list[iw]); } @@ -55,7 +55,7 @@ class SPOSet : public QMCTraits virtual void multi_evaluate_vgl(const std::vector& spo_list, const std::vector& pos_list) { -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < spo_list.size(); iw++) spo_list[iw]->evaluate_vgl(pos_list[iw]); } @@ -63,7 +63,7 @@ class SPOSet : public QMCTraits virtual void multi_evaluate_vgh(const std::vector& spo_list, const std::vector& pos_list) { -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < spo_list.size(); iw++) spo_list[iw]->evaluate_vgh(pos_list[iw]); } diff --git a/src/QMCWaveFunctions/WaveFunctionComponent.h b/src/QMCWaveFunctions/WaveFunctionComponent.h index 4eda3cfb6..b1bd0390a 100644 --- a/src/QMCWaveFunctions/WaveFunctionComponent.h +++ b/src/QMCWaveFunctions/WaveFunctionComponent.h @@ -176,7 +176,7 @@ struct WaveFunctionComponent : public QMCTraits const std::vector& L_list, ParticleSet::ParticleValue_t& values) { -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < P_list.size(); iw++) values[iw] = WFC_list[iw]->evaluateLog(*P_list[iw], *G_list[iw], *L_list[iw]); }; @@ -197,7 +197,7 @@ struct WaveFunctionComponent : public QMCTraits std::vector& ratios, std::vector& grad_new) { -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < P_list.size(); iw++) ratios[iw] = WFC_list[iw]->ratioGrad(*P_list[iw], iat, grad_new[iw]); }; @@ -207,7 +207,7 @@ struct WaveFunctionComponent : public QMCTraits const std::vector& isAccepted, int iat) { -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < P_list.size(); iw++) { if (isAccepted[iw]) @@ -228,7 +228,7 @@ struct WaveFunctionComponent : public QMCTraits const std::vector& L_list, bool fromscratch = false) { -#pragma omp parallel for + #pragma omp parallel for for (int iw = 0; iw < P_list.size(); iw++) WFC_list[iw]->evaluateGL(*P_list[iw], *G_list[iw], *L_list[iw], fromscratch); }; diff --git a/src/QMCWaveFunctions/einspline_spo.hpp b/src/QMCWaveFunctions/einspline_spo.hpp index 449f237c9..303348947 100644 --- a/src/QMCWaveFunctions/einspline_spo.hpp +++ b/src/QMCWaveFunctions/einspline_spo.hpp @@ -172,7 +172,7 @@ struct einspline_spo : public SPOSet inline void evaluate_v_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); -#pragma omp for nowait + #pragma omp for nowait for (int i = 0; i < nBlocks; ++i) compute_engine.evaluate_v(einsplines[i], u[0], u[1], u[2], psi[i].data(), nSplinesPerBlock); } @@ -196,7 +196,7 @@ struct einspline_spo : public SPOSet inline void evaluate_vgl_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); -#pragma omp for nowait + #pragma omp for nowait for (int i = 0; i < nBlocks; ++i) compute_engine.evaluate_vgl(einsplines[i], u[0], @@ -229,7 +229,7 @@ struct einspline_spo : public SPOSet inline void evaluate_vgh_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); -#pragma omp for nowait + #pragma omp for nowait for (int i = 0; i < nBlocks; ++i) compute_engine.evaluate_vgh(einsplines[i], u[0], diff --git a/src/QMCWaveFunctions/einspline_spo_ref.hpp b/src/QMCWaveFunctions/einspline_spo_ref.hpp index 7c2c8bfe2..562b2d53c 100644 --- a/src/QMCWaveFunctions/einspline_spo_ref.hpp +++ b/src/QMCWaveFunctions/einspline_spo_ref.hpp @@ -174,7 +174,7 @@ struct einspline_spo_ref : public SPOSet inline void evaluate_v_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); -#pragma omp for nowait + #pragma omp for nowait for (int i = 0; i < nBlocks; ++i) compute_engine.evaluate_v(einsplines[i], u[0], u[1], u[2], psi[i].data(), nSplinesPerBlock); } @@ -198,7 +198,7 @@ struct einspline_spo_ref : public SPOSet inline void evaluate_vgl_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); -#pragma omp for nowait + #pragma omp for nowait for (int i = 0; i < nBlocks; ++i) compute_engine.evaluate_vgl(einsplines[i], u[0], @@ -231,7 +231,7 @@ struct einspline_spo_ref : public SPOSet inline void evaluate_vgh_pfor(const PosType& p) { auto u = Lattice.toUnit_floor(p); -#pragma omp for nowait + #pragma omp for nowait for (int i = 0; i < nBlocks; ++i) compute_engine.evaluate_vgh(einsplines[i], u[0], diff --git a/src/Utilities/NewTimer.cpp b/src/Utilities/NewTimer.cpp index 610311051..b967b105c 100644 --- a/src/Utilities/NewTimer.cpp +++ b/src/Utilities/NewTimer.cpp @@ -36,7 +36,7 @@ bool timer_max_level_exceeded = false; void TimerManagerClass::addTimer(NewTimer* t) { -#pragma omp critical + #pragma omp critical { if (t->get_name().find(TIMER_STACK_SEPARATOR) != std::string::npos) { @@ -249,7 +249,7 @@ void TimerManagerClass::print_flat() collate_flat_profile(p); { -#pragma omp master + #pragma omp master { std::map::iterator it(p.nameList.begin()), it_end(p.nameList.end()); while (it != it_end) diff --git a/src/Utilities/NewTimer.h b/src/Utilities/NewTimer.h index 3c34d1aee..b8059b9e8 100644 --- a/src/Utilities/NewTimer.h +++ b/src/Utilities/NewTimer.h @@ -360,7 +360,7 @@ class NewTimer #endif #ifdef USE_STACK_TIMERS -#pragma omp master + #pragma omp master { if (manager) { diff --git a/src/Utilities/SIMD/algorithm.hpp b/src/Utilities/SIMD/algorithm.hpp index 0c3c98c58..0e490a8fe 100644 --- a/src/Utilities/SIMD/algorithm.hpp +++ b/src/Utilities/SIMD/algorithm.hpp @@ -36,7 +36,7 @@ inline void copy_n(const T1* restrict first, size_t count, T2* restrict result) template inline T2 accumulate_n(const T1* restrict in, size_t n, T2 res) { -#pragma omp simd reduction(+ : res) + #pragma omp simd reduction(+ : res) for (int i = 0; i < n; ++i) res += in[i]; return res; From 8848fe5cc66205cb42aad5074ce7d1edfd65efcc Mon Sep 17 00:00:00 2001 From: Peter Doak Date: Thu, 2 Aug 2018 14:32:50 -0400 Subject: [PATCH 3/8] fixing //clang-format must be // clang-format on/off --- src/Drivers/check_determinant.cpp | 24 ++++++++--------- src/Drivers/check_spo.cpp | 28 ++++++++++---------- src/Drivers/check_wfc.cpp | 28 ++++++++++---------- src/Drivers/miniqmc.cpp | 42 ++++++++++++++--------------- src/Drivers/miniqmc_sync_move.cpp | 44 +++++++++++++++---------------- 5 files changed, 83 insertions(+), 83 deletions(-) diff --git a/src/Drivers/check_determinant.cpp b/src/Drivers/check_determinant.cpp index 30a05bf16..3091fe86c 100644 --- a/src/Drivers/check_determinant.cpp +++ b/src/Drivers/check_determinant.cpp @@ -36,19 +36,19 @@ using namespace qmcplusplus; void print_help() { - //clang-format off + // clang-format off cout << "usage:" << '\n'; - cout << " check_determinant [-hvV] [-g \"n0 n1 n2\"] [-n steps]" << '\n'; - cout << " [-N substeps] [-s seed]" << '\n'; - cout << "options:" << '\n'; - cout << " -g set the 3D tiling. default: 1 1 1" << '\n'; - cout << " -h print help and exit" << '\n'; - cout << " -n number of MC steps default: 5" << '\n'; - cout << " -N number of MC substeps default: 1" << '\n'; - cout << " -s set the random seed. default: 11" << '\n'; - cout << " -v verbose output" << '\n'; - cout << " -V print version information and exit" << '\n'; - //clang-format on + cout << " check_determinant [-hvV] [-g \"n0 n1 n2\"] [-n steps]" << '\n'; + cout << " [-N substeps] [-s seed]" << '\n'; + cout << "options:" << '\n'; + cout << " -g set the 3D tiling. default: 1 1 1" << '\n'; + cout << " -h print help and exit" << '\n'; + cout << " -n number of MC steps default: 5" << '\n'; + cout << " -N number of MC substeps default: 1" << '\n'; + cout << " -s set the random seed. default: 11" << '\n'; + cout << " -v verbose output" << '\n'; + cout << " -V print version information and exit" << '\n'; + // clang-format on exit(1); // print help and exit } diff --git a/src/Drivers/check_spo.cpp b/src/Drivers/check_spo.cpp index c408e361f..b46ac9407 100644 --- a/src/Drivers/check_spo.cpp +++ b/src/Drivers/check_spo.cpp @@ -34,20 +34,20 @@ using namespace qmcplusplus; void print_help() { - //clang-format off + // clang-format off app_summary() << "usage:" << '\n'; - app_summary() << " check_spo [-hvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; - app_summary() << " [-n steps] [-r rmax] [-s seed]" << '\n'; - app_summary() << "options:" << '\n'; - app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; - app_summary() << " -h print help and exit" << '\n'; - app_summary() << " -m meshfactor default: 1.0" << '\n'; - app_summary() << " -n number of MC steps default: 5" << '\n'; - app_summary() << " -r set the Rmax. default: 1.7" << '\n'; - app_summary() << " -s set the random seed. default: 11" << '\n'; - app_summary() << " -v verbose output" << '\n'; - app_summary() << " -V print version information and exit" << '\n'; - //clang-format on + app_summary() << " check_spo [-hvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; + app_summary() << " [-n steps] [-r rmax] [-s seed]" << '\n'; + app_summary() << "options:" << '\n'; + app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; + app_summary() << " -h print help and exit" << '\n'; + app_summary() << " -m meshfactor default: 1.0" << '\n'; + app_summary() << " -n number of MC steps default: 5" << '\n'; + app_summary() << " -r set the Rmax. default: 1.7" << '\n'; + app_summary() << " -s set the random seed. default: 11" << '\n'; + app_summary() << " -v verbose output" << '\n'; + app_summary() << " -V print version information and exit" << '\n'; + // clang-format on exit(1); // print help and exit } @@ -304,7 +304,7 @@ int main(int argc, char** argv) } // steps. - ratio += RealType(my_accepted) / RealType(nels * nsteps); + ratio += RealType(my_accepted) / RealType(nels * nsteps); nspheremoves += RealType(my_vals) / RealType(nsteps); dNumVGHCalls += nels; diff --git a/src/Drivers/check_wfc.cpp b/src/Drivers/check_wfc.cpp index bb1aa5e90..1c8badb85 100644 --- a/src/Drivers/check_wfc.cpp +++ b/src/Drivers/check_wfc.cpp @@ -44,20 +44,20 @@ using namespace qmcplusplus; void print_help() { - //clang-format off + // clang-format off cout << "usage:" << '\n'; - cout << " check_wfc [-hvV] [-f wfc_component] [-g \"n0 n1 n2\"]" << '\n'; - cout << " [-r rmax] [-s seed]" << '\n'; - cout << "options:" << '\n'; - cout << " -f specify wavefunction component to check" << '\n'; - cout << " one of: J1, J2, J3. default: J2" << '\n'; - cout << " -g set the 3D tiling. default: 1 1 1" << '\n'; - cout << " -h print help and exit" << '\n'; - cout << " -r set the Rmax. default: 1.7" << '\n'; - cout << " -s set the random seed. default: 11" << '\n'; - cout << " -v verbose output" << '\n'; - cout << " -V print version information and exit" << '\n'; - //clang-format on + cout << " check_wfc [-hvV] [-f wfc_component] [-g \"n0 n1 n2\"]" << '\n'; + cout << " [-r rmax] [-s seed]" << '\n'; + cout << "options:" << '\n'; + cout << " -f specify wavefunction component to check" << '\n'; + cout << " one of: J1, J2, J3. default: J2" << '\n'; + cout << " -g set the 3D tiling. default: 1 1 1" << '\n'; + cout << " -h print help and exit" << '\n'; + cout << " -r set the Rmax. default: 1.7" << '\n'; + cout << " -s set the random seed. default: 11" << '\n'; + cout << " -v verbose output" << '\n'; + cout << " -V print version information and exit" << '\n'; + // clang-format on exit(1); // print help and exit } @@ -320,7 +320,7 @@ int main(int argc, char** argv) cout << "evalGrad::G Error = " << g_eval / nels << endl; cout << "ratioGrad::G Error = " << g_ratio / nels << endl; cout << "ratioGrad::Ratio Error = " << r_ratio / nels << endl; - evalGrad_g_err += std::fabs(g_eval / nels); + evalGrad_g_err += std::fabs(g_eval / nels); ratioGrad_g_err += std::fabs(g_ratio / nels); ratioGrad_r_err += std::fabs(r_ratio / nels); diff --git a/src/Drivers/miniqmc.cpp b/src/Drivers/miniqmc.cpp index 0f4415f3c..d5d6e0a52 100644 --- a/src/Drivers/miniqmc.cpp +++ b/src/Drivers/miniqmc.cpp @@ -146,27 +146,27 @@ TimerNameList_t MiniQMCTimerNames = { void print_help() { - //clang-format off + // clang-format off app_summary() << "usage:" << '\n'; - app_summary() << " miniqmc [-hjvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; - app_summary() << " [-n steps] [-N substeps] [-r rmax] [-s seed]" << '\n'; - app_summary() << " [-w walkers] [-a tile_size] [-t timer_level]" << '\n'; - app_summary() << "options:" << '\n'; - app_summary() << " -a size of each spline tile default: num of orbs" << '\n'; - app_summary() << " -b use reference implementations default: off" << '\n'; - app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; - app_summary() << " -h print help and exit" << '\n'; - app_summary() << " -j enable three body Jastrow default: off" << '\n'; - app_summary() << " -m meshfactor default: 1.0" << '\n'; - app_summary() << " -n number of MC steps default: 5" << '\n'; - app_summary() << " -N number of MC substeps default: 1" << '\n'; - app_summary() << " -r set the Rmax. default: 1.7" << '\n'; - app_summary() << " -s set the random seed. default: 11" << '\n'; - app_summary() << " -t timer level: coarse or fine default: fine" << '\n'; - app_summary() << " -w number of walker(movers) default: num of threads" << '\n'; - app_summary() << " -v verbose output" << '\n'; - app_summary() << " -V print version information and exit" << '\n'; - //clang-format on + app_summary() << " miniqmc [-hjvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; + app_summary() << " [-n steps] [-N substeps] [-r rmax] [-s seed]" << '\n'; + app_summary() << " [-w walkers] [-a tile_size] [-t timer_level]" << '\n'; + app_summary() << "options:" << '\n'; + app_summary() << " -a size of each spline tile default: num of orbs" << '\n'; + app_summary() << " -b use reference implementations default: off" << '\n'; + app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; + app_summary() << " -h print help and exit" << '\n'; + app_summary() << " -j enable three body Jastrow default: off" << '\n'; + app_summary() << " -m meshfactor default: 1.0" << '\n'; + app_summary() << " -n number of MC steps default: 5" << '\n'; + app_summary() << " -N number of MC substeps default: 1" << '\n'; + app_summary() << " -r set the Rmax. default: 1.7" << '\n'; + app_summary() << " -s set the random seed. default: 11" << '\n'; + app_summary() << " -t timer level: coarse or fine default: fine" << '\n'; + app_summary() << " -w number of walker(movers) default: num of threads"<< '\n'; + app_summary() << " -v verbose output" << '\n'; + app_summary() << " -V print version information and exit" << '\n'; + // clang-format on } int main(int argc, char** argv) @@ -500,7 +500,7 @@ int main(int argc, char** argv) } // end of mover loop Timers[Timer_Total]->stop(); -// free all movers + // free all movers #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) delete mover_list[iw]; diff --git a/src/Drivers/miniqmc_sync_move.cpp b/src/Drivers/miniqmc_sync_move.cpp index ff372f83b..99dd4514c 100644 --- a/src/Drivers/miniqmc_sync_move.cpp +++ b/src/Drivers/miniqmc_sync_move.cpp @@ -146,27 +146,27 @@ TimerNameList_t MiniQMCTimerNames = { void print_help() { - //clang-format off + // clang-format off app_summary() << "usage:" << '\n'; - app_summary() << " miniqmc [-hjvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; - app_summary() << " [-n steps] [-N substeps] [-r rmax] [-s seed]" << '\n'; - app_summary() << " [-w walkers] [-a tile_size] [-t timer_level]" << '\n'; - app_summary() << "options:" << '\n'; - app_summary() << " -a size of each spline tile default: num of orbs" << '\n'; - app_summary() << " -b use reference implementations default: off" << '\n'; - app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; - app_summary() << " -h print help and exit" << '\n'; - app_summary() << " -j enable three body Jastrow default: off" << '\n'; - app_summary() << " -m meshfactor default: 1.0" << '\n'; - app_summary() << " -n number of MC steps default: 5" << '\n'; - app_summary() << " -N number of MC substeps default: 1" << '\n'; - app_summary() << " -r set the Rmax. default: 1.7" << '\n'; - app_summary() << " -s set the random seed. default: 11" << '\n'; - app_summary() << " -t timer level: coarse or fine default: fine" << '\n'; - app_summary() << " -w number of walker(movers) default: num of threads" << '\n'; - app_summary() << " -v verbose output" << '\n'; - app_summary() << " -V print version information and exit" << '\n'; - //clang-format on + app_summary() << " miniqmc [-hjvV] [-g \"n0 n1 n2\"] [-m meshfactor]" << '\n'; + app_summary() << " [-n steps] [-N substeps] [-r rmax] [-s seed]" << '\n'; + app_summary() << " [-w walkers] [-a tile_size] [-t timer_level]" << '\n'; + app_summary() << "options:" << '\n'; + app_summary() << " -a size of each spline tile default: num of orbs" << '\n'; + app_summary() << " -b use reference implementations default: off" << '\n'; + app_summary() << " -g set the 3D tiling. default: 1 1 1" << '\n'; + app_summary() << " -h print help and exit" << '\n'; + app_summary() << " -j enable three body Jastrow default: off" << '\n'; + app_summary() << " -m meshfactor default: 1.0" << '\n'; + app_summary() << " -n number of MC steps default: 5" << '\n'; + app_summary() << " -N number of MC substeps default: 1" << '\n'; + app_summary() << " -r set the Rmax. default: 1.7" << '\n'; + app_summary() << " -s set the random seed. default: 11" << '\n'; + app_summary() << " -t timer level: coarse or fine default: fine" << '\n'; + app_summary() << " -w number of walker(movers) default: num of threads"<< '\n'; + app_summary() << " -v verbose output" << '\n'; + app_summary() << " -V print version information and exit" << '\n'; + // clang-format on } int main(int argc, char** argv) @@ -358,7 +358,7 @@ int main(int argc, char** argv) Timers[Timer_Init]->start(); std::vector mover_list(nmovers, nullptr); -// prepare movers + // prepare movers #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) { @@ -425,7 +425,7 @@ int main(int argc, char** argv) { for (int iel = 0; iel < nels; ++iel) { -// Operate on electron with index iel + // Operate on electron with index iel #pragma omp parallel for for (int iw = 0; iw < nmovers; iw++) mover_list[iw]->els.setActive(iel); From 3c3c9475a3edbf786edc8c41ddd627b7f6dc0966 Mon Sep 17 00:00:00 2001 From: Peter Doak Date: Thu, 2 Aug 2018 15:42:26 -0400 Subject: [PATCH 4/8] protecting Blasf.h from clang-format separate Numerics .clang-format --- src/Numerics/.clang-format | 112 ++++++++++++++++++++++ src/Numerics/Spline2/MultiBsplineData.cpp | 75 ++++++--------- 2 files changed, 140 insertions(+), 47 deletions(-) create mode 100644 src/Numerics/.clang-format diff --git a/src/Numerics/.clang-format b/src/Numerics/.clang-format new file mode 100644 index 000000000..f3012bd49 --- /dev/null +++ b/src/Numerics/.clang-format @@ -0,0 +1,112 @@ +--- +Language: Cpp +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: true +AlignConsecutiveDeclarations: false +AlignEscapedNewlines: Left +AlignOperands: false +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: true +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: true +BinPackArguments: true +BinPackParameters: true +BreakBeforeBraces: Custom +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: true + BeforeElse: true + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false +BreakBeforeBinaryOperators: None +BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: true +BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: BeforeColon +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: true +ColumnLimit: 100 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: true +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +# @future IndentPPDirectives: BeforeHash +IndentWidth: 2 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 2 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakAssignment: 0 +PenaltyBreakBeforeFirstCallParameter: 100000 +PenaltyBreakComment: 20 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 9 +PenaltyReturnTypeOnItsOwnLine: 8 +PointerAlignment: Left +ReflowComments: false +SortIncludes: false +SortUsingDeclarations: false +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeRangeBasedForLoopColon: true +SpaceInEmptyParentheses: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +TabWidth: 8 +UseTab: Never diff --git a/src/Numerics/Spline2/MultiBsplineData.cpp b/src/Numerics/Spline2/MultiBsplineData.cpp index ebcda29e5..14d4855f0 100644 --- a/src/Numerics/Spline2/MultiBsplineData.cpp +++ b/src/Numerics/Spline2/MultiBsplineData.cpp @@ -20,56 +20,37 @@ namespace qmcplusplus { /** initialization of static data for MultiBsplineData */ -template<> -QMC_ALIGNAS const float MultiBsplineData::A44[16] = {-1.0f / 6.0f, - 3.0f / 6.0f, - -3.0f / 6.0f, - 1.0f / 6.0f, - 3.0f / 6.0f, - -6.0f / 6.0f, - 0.0f / 6.0f, - 4.0f / 6.0f, - -3.0f / 6.0f, - 3.0f / 6.0f, - 3.0f / 6.0f, - 1.0f / 6.0f, - 1.0f / 6.0f, - 0.0f / 6.0f, - 0.0f / 6.0f, - 0.0f / 6.0f}; +template <> +QMC_ALIGNAS const float MultiBsplineData::A44[16] = { + -1.0f / 6.0f, 3.0f / 6.0f, -3.0f / 6.0f, 1.0f / 6.0f, + 3.0f / 6.0f, -6.0f / 6.0f, 0.0f / 6.0f, 4.0f / 6.0f, + -3.0f / 6.0f, 3.0f / 6.0f, 3.0f / 6.0f, 1.0f / 6.0f, + 1.0f / 6.0f, 0.0f / 6.0f, 0.0f / 6.0f, 0.0f / 6.0f}; -template<> -QMC_ALIGNAS const float MultiBsplineData::dA44[16] = - {0.0f, -0.5f, 1.0f, -0.5f, 0.0f, 1.5f, -2.0f, 0.0f, 0.0f, -1.5f, 1.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}; +template <> +QMC_ALIGNAS const float MultiBsplineData::dA44[16] = { + 0.0f, -0.5f, 1.0f, -0.5f, 0.0f, 1.5f, -2.0f, 0.0f, + 0.0f, -1.5f, 1.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}; -template<> -QMC_ALIGNAS const float MultiBsplineData::d2A44[16] = - {0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 3.0f, -2.0f, 0.0f, 0.0f, -3.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f}; +template <> +QMC_ALIGNAS const float MultiBsplineData::d2A44[16] = { + 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, 3.0f, -2.0f, + 0.0f, 0.0f, -3.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f}; /** initialization of static data for MultiBsplineData */ -template<> -QMC_ALIGNAS const double MultiBsplineData::A44[16] = {-1.0 / 6.0, - 3.0 / 6.0, - -3.0 / 6.0, - 1.0 / 6.0, - 3.0 / 6.0, - -6.0 / 6.0, - 0.0 / 6.0, - 4.0 / 6.0, - -3.0 / 6.0, - 3.0 / 6.0, - 3.0 / 6.0, - 1.0 / 6.0, - 1.0 / 6.0, - 0.0 / 6.0, - 0.0 / 6.0, - 0.0 / 6.0}; +template <> +QMC_ALIGNAS const double MultiBsplineData::A44[16] = { + -1.0 / 6.0, 3.0 / 6.0, -3.0 / 6.0, 1.0 / 6.0, 3.0 / 6.0, -6.0 / 6.0, + 0.0 / 6.0, 4.0 / 6.0, -3.0 / 6.0, 3.0 / 6.0, 3.0 / 6.0, 1.0 / 6.0, + 1.0 / 6.0, 0.0 / 6.0, 0.0 / 6.0, 0.0 / 6.0}; -template<> -QMC_ALIGNAS const double MultiBsplineData::dA44[16] = - {0.0, -0.5, 1.0, -0.5, 0.0, 1.5, -2.0, 0.0, 0.0, -1.5, 1.0, 0.5, 0.0, 0.5, 0.0, 0.0}; +template <> +QMC_ALIGNAS const double MultiBsplineData::dA44[16] = { + 0.0, -0.5, 1.0, -0.5, 0.0, 1.5, -2.0, 0.0, + 0.0, -1.5, 1.0, 0.5, 0.0, 0.5, 0.0, 0.0}; -template<> -QMC_ALIGNAS const double MultiBsplineData::d2A44[16] = - {0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 3.0, -2.0, 0.0, 0.0, -3.0, 1.0, 0.0, 0.0, 1.0, 0.0}; -} // namespace qmcplusplus +template <> +QMC_ALIGNAS const double MultiBsplineData::d2A44[16] = { + 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 3.0, -2.0, + 0.0, 0.0, -3.0, 1.0, 0.0, 0.0, 1.0, 0.0}; +} From 89bb65007b07effcf9e36db2a3ad3335eb1f3070 Mon Sep 17 00:00:00 2001 From: Peter Doak Date: Thu, 2 Aug 2018 15:55:20 -0400 Subject: [PATCH 5/8] updated Numerics .clang-format and protection where appropriate --- src/Numerics/.clang-format | 2 +- src/Numerics/Containers.h | 9 +- src/Numerics/DeterminantOperators.h | 8 +- src/Numerics/OhmmsBlas.h | 482 +++++++------------ src/Numerics/OhmmsPETE/OhmmsArray.h | 3 +- src/Numerics/OhmmsPETE/OhmmsVector.h | 24 +- src/Numerics/OhmmsPETE/Tensor.h | 11 +- src/Numerics/OhmmsPETE/TinyVector.h | 10 +- src/Numerics/OhmmsPETE/TinyVectorOps.h | 4 +- src/Numerics/PETE/Combiners.h | 4 +- src/Numerics/PETE/OperatorTags.h | 6 +- src/Numerics/PosTransformer.h | 4 +- src/Numerics/Spline2/MultiBspline.hpp | 98 ++-- src/Numerics/Spline2/MultiBsplineData.cpp | 4 +- src/Numerics/Spline2/MultiBsplineRef.hpp | 46 +- src/Numerics/Spline2/bspline_allocator.cpp | 50 +- src/Numerics/Spline2/bspline_allocator.hpp | 14 +- src/Numerics/Spline2/einspline_allocator.cpp | 36 +- 18 files changed, 294 insertions(+), 521 deletions(-) diff --git a/src/Numerics/.clang-format b/src/Numerics/.clang-format index f3012bd49..bc713601d 100644 --- a/src/Numerics/.clang-format +++ b/src/Numerics/.clang-format @@ -81,7 +81,7 @@ NamespaceIndentation: None ObjCBlockIndentWidth: 2 ObjCSpaceAfterProperty: false ObjCSpaceBeforeProtocolList: true -PenaltyBreakAssignment: 0 +PenaltyBreakAssignment: 1 PenaltyBreakBeforeFirstCallParameter: 100000 PenaltyBreakComment: 20 PenaltyBreakFirstLessLess: 120 diff --git a/src/Numerics/Containers.h b/src/Numerics/Containers.h index 3658b6f37..3c1b32cf6 100644 --- a/src/Numerics/Containers.h +++ b/src/Numerics/Containers.h @@ -62,8 +62,7 @@ struct VectorSoAContainer /// destructor ~VectorSoAContainer() { - if (nAllocated > 0) - myAlloc.deallocate(myData, nAllocated); + if (nAllocated > 0) myAlloc.deallocate(myData, nAllocated); } /// default copy constructor @@ -117,8 +116,7 @@ struct VectorSoAContainer template VectorSoAContainer& operator=(const ParticleAttrib>& in) { - if (nLocal != in.size()) - resize(in.size()); + if (nLocal != in.size()) resize(in.size()); copyIn(in); return *this; } @@ -148,8 +146,7 @@ struct VectorSoAContainer */ __forceinline void resize(size_t n) { - if (nAllocated) - myAlloc.deallocate(myData, nAllocated); + if (nAllocated) myAlloc.deallocate(myData, nAllocated); nLocal = n; nGhosts = getAlignedSize(n); nAllocated = nGhosts * D; diff --git a/src/Numerics/DeterminantOperators.h b/src/Numerics/DeterminantOperators.h index 239eb8223..998b01744 100644 --- a/src/Numerics/DeterminantOperators.h +++ b/src/Numerics/DeterminantOperators.h @@ -65,7 +65,7 @@ inline void LUFactorization(int n, int m, std::complex* restrict a, int n /** Inversion of a double matrix after LU factorization*/ inline void - InvertLU(int n, double* restrict a, int n0, int* restrict piv, double* restrict work, int n1) +InvertLU(int n, double* restrict a, int n0, int* restrict piv, double* restrict work, int n1) { int status; dgetri(n, a, n0, piv, work, n1, status); @@ -139,8 +139,7 @@ inline T InvertWithLog(std::complex* restrict x, { int ii = i * m + i; phase += std::arg(x[ii]); - if (pivot[i] != i + 1) - phase += M_PI; + if (pivot[i] != i + 1) phase += M_PI; logdet += std::log(x[ii].real() * x[ii].real() + x[ii].imag() * x[ii].imag()); // slightly smaller error with the following // logdet+=2.0*std::log(std::abs(x[ii]); @@ -171,8 +170,7 @@ inline typename MatrixA::value_type invert_matrix(MatrixA& M, bool getdet = true int sign = 1; for (int i = 0; i < n; ++i) { - if (pivot[i] != i + 1) - sign *= -1; + if (pivot[i] != i + 1) sign *= -1; det0 *= M(i, i); } det0 *= static_cast(sign); diff --git a/src/Numerics/OhmmsBlas.h b/src/Numerics/OhmmsBlas.h index a4fa6102b..2d621a6d0 100644 --- a/src/Numerics/OhmmsBlas.h +++ b/src/Numerics/OhmmsBlas.h @@ -42,8 +42,11 @@ * which BLAS routines are actually used. * Note that symv can be call in many ways. */ + +// clang-format off struct BLAS { + static const int INCX = 1; static const int INCY = 1; static const char UPLO = 'L'; @@ -58,272 +61,209 @@ struct BLAS static const std::complex zone; static const std::complex zzero; - inline static void axpy(int n, double x, const double* a, double* b) + inline static void axpy(int n, double x, const double *a, double *b) { daxpy(n, x, a, INCX, b, INCY); } - inline static void axpy(int n, double x, const double* a, int incx, double* b, int incy) + inline static void axpy(int n, double x, const double *a, int incx, double *b, + int incy) { daxpy(n, x, a, incx, b, incy); } - inline static void axpy(int n, const double* a, double* b) { daxpy(n, done, a, INCX, b, INCY); } + inline static void axpy(int n, const double *a, double *b) + { + daxpy(n, done, a, INCX, b, INCY); + } - inline static void axpy(int n, float x, const float* a, int incx, float* b, int incy) + inline static void axpy(int n, float x, const float *a, int incx, float *b, + int incy) { saxpy(n, x, a, incx, b, incy); } - inline static void axpy(int n, - const std::complex x, - const std::complex* a, - int incx, - std::complex* b, - int incy) + inline static void axpy(int n, const std::complex x, + const std::complex *a, int incx, + std::complex *b, int incy) { caxpy(n, x, a, incx, b, incy); } - inline static void axpy(int n, - const std::complex x, - const std::complex* a, - int incx, - std::complex* b, - int incy) + inline static void axpy(int n, const std::complex x, + const std::complex *a, int incx, + std::complex *b, int incy) { zaxpy(n, x, a, incx, b, incy); } - inline static double norm2(int n, const double* a, int incx = 1) { return dnrm2(n, a, incx); } + inline static double norm2(int n, const double *a, int incx = 1) + { + return dnrm2(n, a, incx); + } - inline static double norm2(int n, const std::complex* a, int incx = 1) + inline static double norm2(int n, const std::complex *a, int incx = 1) { return dznrm2(n, a, incx); } - inline static float norm2(int n, const float* a, int incx = 1) { return snrm2(n, a, incx); } + inline static float norm2(int n, const float *a, int incx = 1) + { + return snrm2(n, a, incx); + } - inline static void scal(int n, double alpha, double* x) { dscal(n, alpha, x, INCX); } + inline static void scal(int n, double alpha, double *x) + { + dscal(n, alpha, x, INCX); + } // inline static // void gemv(char trans, int n, int m, const double* amat, const double* x, // double* y) { // dgemv(trans, n, m, done, amat, n, x, INCX, dzero, y, INCY); //} - inline static void - gemv(int n, int m, const double* restrict amat, const double* restrict x, double* restrict y) + inline static void gemv(int n, int m, const double *restrict amat, + const double *restrict x, double *restrict y) { dgemv(NOTRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void - gemv(int n, int m, const float* restrict amat, const float* restrict x, float* restrict y) + inline static void gemv(int n, int m, const float *restrict amat, + const float *restrict x, float *restrict y) { sgemv(NOTRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void - gemv_trans(int n, int m, const double* restrict amat, const double* restrict x, double* restrict y) + inline static void gemv_trans(int n, int m, const double *restrict amat, + const double *restrict x, double *restrict y) { dgemv(TRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void - gemv_trans(int n, int m, const float* restrict amat, const float* restrict x, float* restrict y) + inline static void gemv_trans(int n, int m, const float *restrict amat, + const float *restrict x, float *restrict y) { sgemv(TRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void gemv_trans(int n, - int m, - const std::complex* restrict amat, - const std::complex* restrict x, - std::complex* restrict y) + inline static void gemv_trans(int n, int m, + const std::complex *restrict amat, + const std::complex *restrict x, + std::complex *restrict y) { zgemv(TRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void gemv_trans(int n, - int m, - const std::complex* restrict amat, - const std::complex* restrict x, - std::complex* restrict y) + inline static void gemv_trans(int n, int m, + const std::complex *restrict amat, + const std::complex *restrict x, + std::complex *restrict y) { cgemv(TRANS, m, n, done, amat, m, x, INCX, dzero, y, INCY); } - inline static void gemv(int n, - int m, - const std::complex* restrict amat, - const std::complex* restrict x, - std::complex* restrict y) + inline static void gemv(int n, int m, + const std::complex *restrict amat, + const std::complex *restrict x, + std::complex *restrict y) { zgemv(NOTRANS, m, n, zone, amat, m, x, INCX, zzero, y, INCY); } - inline static void gemv(char trans_in, - int n, - int m, - double alpha, - const double* restrict amat, - int lda, - const double* x, - int incx, - double beta, - double* y, - int incy) + inline static void gemv(char trans_in, int n, int m, double alpha, + const double *restrict amat, int lda, const double *x, + int incx, double beta, double *y, int incy) { dgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } - inline static void gemv(char trans_in, - int n, - int m, - float alpha, - const float* restrict amat, - int lda, - const float* x, - int incx, - float beta, - float* y, - int incy) + inline static void gemv(char trans_in, int n, int m, float alpha, + const float *restrict amat, int lda, const float *x, + int incx, float beta, float *y, int incy) { sgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } - inline static void gemv(char trans_in, - int n, - int m, - const std::complex& alpha, - const std::complex* restrict amat, - int lda, - const std::complex* restrict x, - int incx, - const std::complex& beta, - std::complex* y, - int incy) + inline static void gemv(char trans_in, int n, int m, + const std::complex &alpha, + const std::complex *restrict amat, int lda, + const std::complex *restrict x, int incx, + const std::complex &beta, + std::complex *y, int incy) { zgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } - inline static void gemv(char trans_in, - int n, - int m, - const std::complex& alpha, - const std::complex* restrict amat, - int lda, - const std::complex* restrict x, - int incx, - const std::complex& beta, - std::complex* y, - int incy) + inline static void gemv(char trans_in, int n, int m, + const std::complex &alpha, + const std::complex *restrict amat, int lda, + const std::complex *restrict x, int incx, + const std::complex &beta, + std::complex *y, int incy) { cgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } #if defined(HAVE_MKL) - inline static void gemv(char trans_in, - int n, - int m, - const std::complex& alpha, - const double* restrict amat, - int lda, - const std::complex* restrict x, - int incx, - const std::complex& beta, - std::complex* y, - int incy) + inline static void gemv(char trans_in, int n, int m, + const std::complex &alpha, + const double *restrict amat, int lda, + const std::complex *restrict x, int incx, + const std::complex &beta, + std::complex *y, int incy) { dzgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } - inline static void gemv(char trans_in, - int n, - int m, - const std::complex& alpha, - const float* restrict amat, - int lda, - const std::complex* restrict x, - int incx, - const std::complex& beta, - std::complex* y, - int incy) + inline static void gemv(char trans_in, int n, int m, + const std::complex &alpha, + const float *restrict amat, int lda, + const std::complex *restrict x, int incx, + const std::complex &beta, + std::complex *y, int incy) { scgemv(trans_in, n, m, alpha, amat, lda, x, incx, beta, y, incy); } #endif - inline static void gemm(char Atrans, - char Btrans, - int M, - int N, - int K, - double alpha, - const double* A, - int lda, - const double* restrict B, - int ldb, - double beta, - double* restrict C, - int ldc) + inline static void gemm(char Atrans, char Btrans, int M, int N, int K, + double alpha, const double *A, int lda, + const double *restrict B, int ldb, double beta, + double *restrict C, int ldc) { dgemm(Atrans, Btrans, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } - inline static void gemm(char Atrans, - char Btrans, - int M, - int N, - int K, - float alpha, - const float* A, - int lda, - const float* restrict B, - int ldb, - float beta, - float* restrict C, - int ldc) + inline static void gemm(char Atrans, char Btrans, int M, int N, int K, + float alpha, const float *A, int lda, + const float *restrict B, int ldb, float beta, + float *restrict C, int ldc) { sgemm(Atrans, Btrans, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } - inline static void gemm(char Atrans, - char Btrans, - int M, - int N, - int K, + inline static void gemm(char Atrans, char Btrans, int M, int N, int K, std::complex alpha, - const std::complex* A, - int lda, - const std::complex* restrict B, - int ldb, + const std::complex *A, int lda, + const std::complex *restrict B, int ldb, std::complex beta, - std::complex* restrict C, - int ldc) + std::complex *restrict C, int ldc) { zgemm(Atrans, Btrans, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } - inline static void gemm(char Atrans, - char Btrans, - int M, - int N, - int K, + inline static void gemm(char Atrans, char Btrans, int M, int N, int K, std::complex alpha, - const std::complex* A, - int lda, - const std::complex* restrict B, - int ldb, + const std::complex *A, int lda, + const std::complex *restrict B, int ldb, std::complex beta, - std::complex* restrict C, - int ldc) + std::complex *restrict C, int ldc) { cgemm(Atrans, Btrans, M, N, K, alpha, A, lda, B, ldb, beta, C, ldc); } - template - inline static T dot(int n, const T* restrict a, const T* restrict b) + template + inline static T dot(int n, const T *restrict a, const T *restrict b) { T res = T(0); for (int i = 0; i < n; ++i) @@ -331,8 +271,9 @@ struct BLAS return res; } - template - inline static std::complex dot(int n, const std::complex* restrict a, const T* restrict b) + template + inline static std::complex dot(int n, const std::complex *restrict a, + const T *restrict b) { std::complex res = T(0); for (int i = 0; i < n; ++i) @@ -340,9 +281,9 @@ struct BLAS return res; } - template - inline static std::complex - dot(int n, const std::complex* restrict a, const std::complex* restrict b) + template + inline static std::complex dot(int n, const std::complex *restrict a, + const std::complex *restrict b) { std::complex res = 0.0; for (int i = 0; i < n; ++i) @@ -350,8 +291,9 @@ struct BLAS return res; } - template - inline static std::complex dot(int n, const T* restrict a, const std::complex* restrict b) + template + inline static std::complex dot(int n, const T *restrict a, + const std::complex *restrict b) { std::complex res = 0.0; for (int i = 0; i < n; ++i) @@ -359,8 +301,8 @@ struct BLAS return res; } - template - inline static void copy(int n, const T* restrict a, T* restrict b) + template + inline static void copy(int n, const T *restrict a, T *restrict b) { memcpy(b, a, sizeof(T) * n); } @@ -370,68 +312,61 @@ struct BLAS * @param source starting address of the source * @param number of elements to copy */ - template - inline static void copy(T* restrict target, const T* restrict source, int n) + template + inline static void copy(T *restrict target, const T *restrict source, int n) { memcpy(target, source, sizeof(T) * n); } - template - inline static void copy(int n, const std::complex* restrict a, T* restrict b) + template + inline static void copy(int n, const std::complex *restrict a, + T *restrict b) { for (int i = 0; i < n; ++i) - b[i] = a[i].real(); + b[i] = a[i].real(); } - template - inline static void copy(int n, const T* restrict a, std::complex* restrict b) + template + inline static void copy(int n, const T *restrict a, + std::complex *restrict b) { for (int i = 0; i < n; ++i) - b[i] = a[i]; + b[i] = a[i]; } - template - inline static void copy(int n, const T* restrict x, int incx, T* restrict y, int incy) + template + inline static void copy(int n, const T *restrict x, int incx, T *restrict y, + int incy) { const int xmax = incx * n; for (int ic = 0, jc = 0; ic < xmax; ic += incx, jc += incy) y[jc] = x[ic]; } - inline static void - ger(int m, int n, double alpha, const double* x, int incx, const double* y, int incy, double* a, int lda) + inline static void ger(int m, int n, double alpha, const double *x, int incx, + const double *y, int incy, double *a, int lda) { dger(&m, &n, &alpha, x, &incx, y, &incy, a, &lda); } - inline static void - ger(int m, int n, float alpha, const float* x, int incx, const float* y, int incy, float* a, int lda) + inline static void ger(int m, int n, float alpha, const float *x, int incx, + const float *y, int incy, float *a, int lda) { sger(&m, &n, &alpha, x, &incx, y, &incy, a, &lda); } - inline static void ger(int m, - int n, - const std::complex& alpha, - const std::complex* x, - int incx, - const std::complex* y, - int incy, - std::complex* a, - int lda) + inline static void ger(int m, int n, const std::complex &alpha, + const std::complex *x, int incx, + const std::complex *y, int incy, + std::complex *a, int lda) { zgeru(&m, &n, &alpha, x, &incx, y, &incy, a, &lda); } - inline static void ger(int m, - int n, - const std::complex& alpha, - const std::complex* x, - int incx, - const std::complex* y, - int incy, - std::complex* a, - int lda) + inline static void ger(int m, int n, const std::complex &alpha, + const std::complex *x, int incx, + const std::complex *y, int incy, + std::complex *a, int lda) { cgeru(&m, &n, &alpha, x, &incx, y, &incy, a, &lda); } @@ -439,119 +374,56 @@ struct BLAS struct LAPACK { - inline static void gesvd(char* jobu, - char* jobvt, - int* m, - int* n, - float* a, - int* lda, - float* s, - float* u, - int* ldu, - float* vt, - int* ldvt, - float* work, - int* lwork, - int* info) + + inline static void gesvd(char *jobu, char *jobvt, int *m, int *n, float *a, + int *lda, float *s, float *u, int *ldu, float *vt, + int *ldvt, float *work, int *lwork, int *info) { sgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info); } - inline static void gesvd(char* jobu, - char* jobvt, - int* m, - int* n, - double* a, - int* lda, - double* s, - double* u, - int* ldu, - double* vt, - int* ldvt, - double* work, - int* lwork, - int* info) + inline static void gesvd(char *jobu, char *jobvt, int *m, int *n, double *a, + int *lda, double *s, double *u, int *ldu, double *vt, + int *ldvt, double *work, int *lwork, int *info) { dgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, work, lwork, info); } - inline static void geev(char* jobvl, - char* jobvr, - int* n, - double* a, - int* lda, - double* alphar, - double* alphai, - double* vl, - int* ldvl, - double* vr, - int* ldvr, - double* work, - int* lwork, - int* info) - { - dgeev(jobvl, jobvr, n, a, lda, alphar, alphai, vl, ldvl, vr, ldvr, work, lwork, info); - } - - inline static void geev(char* jobvl, - char* jobvr, - int* n, - float* a, - int* lda, - float* alphar, - float* alphai, - float* vl, - int* ldvl, - float* vr, - int* ldvr, - float* work, - int* lwork, - int* info) - { - sgeev(jobvl, jobvr, n, a, lda, alphar, alphai, vl, ldvl, vr, ldvr, work, lwork, info); - } - - inline static void ggev(char* jobvl, - char* jobvr, - int* n, - double* a, - int* lda, - double* b, - int* ldb, - double* alphar, - double* alphai, - double* beta, - double* vl, - int* ldvl, - double* vr, - int* ldvr, - double* work, - int* lwork, - int* info) - { - dggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info); - } - - inline static void ggev(char* jobvl, - char* jobvr, - int* n, - float* a, - int* lda, - float* b, - int* ldb, - float* alphar, - float* alphai, - float* beta, - float* vl, - int* ldvl, - float* vr, - int* ldvr, - float* work, - int* lwork, - int* info) - { - sggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, work, lwork, info); + inline static void geev(char *jobvl, char *jobvr, int *n, double *a, int *lda, + double *alphar, double *alphai, double *vl, int *ldvl, + double *vr, int *ldvr, double *work, int *lwork, + int *info) + { + dgeev(jobvl, jobvr, n, a, lda, alphar, alphai, vl, ldvl, vr, ldvr, work, + lwork, info); + } + + inline static void geev(char *jobvl, char *jobvr, int *n, float *a, int *lda, + float *alphar, float *alphai, float *vl, int *ldvl, + float *vr, int *ldvr, float *work, int *lwork, + int *info) + { + sgeev(jobvl, jobvr, n, a, lda, alphar, alphai, vl, ldvl, vr, ldvr, work, + lwork, info); + } + + inline static void ggev(char *jobvl, char *jobvr, int *n, double *a, int *lda, + double *b, int *ldb, double *alphar, double *alphai, + double *beta, double *vl, int *ldvl, double *vr, + int *ldvr, double *work, int *lwork, int *info) + { + dggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, + ldvr, work, lwork, info); } -}; + inline static void ggev(char *jobvl, char *jobvr, int *n, float *a, int *lda, + float *b, int *ldb, float *alphar, float *alphai, + float *beta, float *vl, int *ldvl, float *vr, + int *ldvr, float *work, int *lwork, int *info) + { + sggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, + ldvr, work, lwork, info); + } +}; +// clang-format on #endif // OHMMS_BLAS_H diff --git a/src/Numerics/OhmmsPETE/OhmmsArray.h b/src/Numerics/OhmmsPETE/OhmmsArray.h index de5faa994..fc8ee12e1 100644 --- a/src/Numerics/OhmmsPETE/OhmmsArray.h +++ b/src/Numerics/OhmmsPETE/OhmmsArray.h @@ -94,8 +94,7 @@ struct Array int ntot = 1; for (int i = 0; i < D; ++i) ntot *= Length[i] = newdims[i]; - if (ntot == 0) - return; + if (ntot == 0) return; X.resize(ntot); } diff --git a/src/Numerics/OhmmsPETE/OhmmsVector.h b/src/Numerics/OhmmsPETE/OhmmsVector.h index fa6d5305b..d2370c78a 100644 --- a/src/Numerics/OhmmsPETE/OhmmsVector.h +++ b/src/Numerics/OhmmsPETE/OhmmsVector.h @@ -63,10 +63,8 @@ class Vector // default assignment operator inline Vector& operator=(const Vector& rhs) { - if (this == &rhs) - return *this; - if (nLocal != rhs.nLocal) - resize(rhs.nLocal); + if (this == &rhs) return *this; + if (nLocal != rhs.nLocal) resize(rhs.nLocal); std::copy_n(rhs.data(), nLocal, X); return *this; } @@ -77,8 +75,7 @@ class Vector { if (std::is_convertible::value) { - if (nLocal != rhs.nLocal) - resize(rhs.nLocal); + if (nLocal != rhs.nLocal) resize(rhs.nLocal); std::copy_n(rhs.data(), nLocal, X); } return *this; @@ -95,10 +92,7 @@ class Vector //! Destructor virtual ~Vector() { - if (nAllocated) - { - mAllocator.deallocate(X, nAllocated); - } + if (nAllocated) { mAllocator.deallocate(X, nAllocated); } } // Attach to pre-allocated memory @@ -140,10 +134,7 @@ class Vector /// free inline void free() { - if (nAllocated) - { - mAllocator.deallocate(X, nAllocated); - } + if (nAllocated) { mAllocator.deallocate(X, nAllocated); } nLocal = 0; nAllocated = 0; X = nullptr; @@ -191,10 +182,7 @@ class Vector inline void resize_impl(size_t n) { - if (nAllocated) - { - mAllocator.deallocate(X, nAllocated); - } + if (nAllocated) { mAllocator.deallocate(X, nAllocated); } X = mAllocator.allocate(n); nLocal = n; nAllocated = n; diff --git a/src/Numerics/OhmmsPETE/Tensor.h b/src/Numerics/OhmmsPETE/Tensor.h index d2c3b8d81..eced67514 100644 --- a/src/Numerics/OhmmsPETE/Tensor.h +++ b/src/Numerics/OhmmsPETE/Tensor.h @@ -316,7 +316,7 @@ inline T traceAtB(const Tensor& a, const Tensor& b) */ template inline typename BinaryReturn::Type_t - traceAtB(const Tensor& a, const Tensor& b) +traceAtB(const Tensor& a, const Tensor& b) { typedef typename BinaryReturn::Type_t T; T result = 0.0; @@ -337,7 +337,7 @@ OHMMS_META_BINARY_OPERATORS(Tensor, operator/, OpDivide) */ template inline Tensor::Type_t, D> - dot(const Tensor& lhs, const Tensor& rhs) +dot(const Tensor& lhs, const Tensor& rhs) { return OTDot, Tensor>::apply(lhs, rhs); } @@ -348,7 +348,7 @@ inline Tensor::Type_t, D> */ template inline TinyVector::Type_t, D> - dot(const TinyVector& lhs, const Tensor& rhs) +dot(const TinyVector& lhs, const Tensor& rhs) { return OTDot, Tensor>::apply(lhs, rhs); } @@ -359,7 +359,7 @@ inline TinyVector::Type_t, D> */ template inline TinyVector::Type_t, D> - dot(const Tensor& lhs, const TinyVector& rhs) +dot(const Tensor& lhs, const TinyVector& rhs) { return OTDot, TinyVector>::apply(lhs, rhs); } @@ -378,8 +378,7 @@ std::ostream& operator<<(std::ostream& out, const Tensor& rhs) out << rhs(i, j) << " "; } out << rhs(i, D - 1) << " "; - if (i < D - 1) - out << std::endl; + if (i < D - 1) out << std::endl; } } else diff --git a/src/Numerics/OhmmsPETE/TinyVector.h b/src/Numerics/OhmmsPETE/TinyVector.h index b3484e4b5..5c2e87d4c 100644 --- a/src/Numerics/OhmmsPETE/TinyVector.h +++ b/src/Numerics/OhmmsPETE/TinyVector.h @@ -216,7 +216,7 @@ OHMMS_META_BINARY_OPERATORS(TinyVector, operator/, OpDivide) //---------------------------------------------------------------------- template inline typename BinaryReturn::Type_t - dot(const TinyVector& lhs, const TinyVector& rhs) +dot(const TinyVector& lhs, const TinyVector& rhs) { return OTDot, TinyVector>::apply(lhs, rhs); } @@ -227,7 +227,7 @@ inline typename BinaryReturn::Type_t template inline TinyVector::Type_t, D> - cross(const TinyVector& lhs, const TinyVector& rhs) +cross(const TinyVector& lhs, const TinyVector& rhs) { return OTCross, TinyVector>::apply(lhs, rhs); } @@ -238,14 +238,14 @@ inline TinyVector::Type_t, D> template inline Tensor::Type_t, D> - outerProduct(const TinyVector& lhs, const TinyVector& rhs) +outerProduct(const TinyVector& lhs, const TinyVector& rhs) { return OuterProduct, TinyVector>::apply(lhs, rhs); } template inline TinyVector, D> - outerdot(const TinyVector& lhs, const TinyVector& mhs, const TinyVector& rhs) +outerdot(const TinyVector& lhs, const TinyVector& mhs, const TinyVector& rhs) { TinyVector, D> ret; Tensor tmp = OuterProduct, TinyVector>::apply(lhs, mhs); @@ -256,7 +256,7 @@ inline TinyVector, D> template inline TinyVector::Type_t, D>, D> - symouterdot(const TinyVector& lhs, const TinyVector& mhs, const TinyVector& rhs) +symouterdot(const TinyVector& lhs, const TinyVector& mhs, const TinyVector& rhs) { TinyVector::Type_t, D>, D> ret; Tensor::Type_t, D> tmp = diff --git a/src/Numerics/OhmmsPETE/TinyVectorOps.h b/src/Numerics/OhmmsPETE/TinyVectorOps.h index d49e72278..f22c208a1 100644 --- a/src/Numerics/OhmmsPETE/TinyVectorOps.h +++ b/src/Numerics/OhmmsPETE/TinyVectorOps.h @@ -78,7 +78,7 @@ struct OTBinary, TinyVector, OP> { typedef typename BinaryReturn::Type_t Type_t; inline static TinyVector - apply(const TinyVector& lhs, const TinyVector& rhs, OP op) + apply(const TinyVector& lhs, const TinyVector& rhs, OP op) { TinyVector ret; for (unsigned d = 0; d < D; ++d) @@ -161,7 +161,7 @@ struct OTDot, 3>, TinyVector, 3>> { typedef typename BinaryReturn, std::complex, OpMultiply>::Type_t Type_t; inline static Type_t - apply(const TinyVector, 3>& lhs, const TinyVector, 3>& rhs) + apply(const TinyVector, 3>& lhs, const TinyVector, 3>& rhs) { return std::complex(lhs[0].real() * rhs[0].real() - lhs[0].imag() * rhs[0].imag() + lhs[1].real() * rhs[1].real() - lhs[1].imag() * rhs[1].imag() + diff --git a/src/Numerics/PETE/Combiners.h b/src/Numerics/PETE/Combiners.h index 95ef05364..4f625a96e 100644 --- a/src/Numerics/PETE/Combiners.h +++ b/src/Numerics/PETE/Combiners.h @@ -134,14 +134,14 @@ inline typename Combine1::Type_t peteCombine(const A& a, const Op& o template inline typename Combine2::Type_t - peteCombine(const A& a, const B& b, const Op& op, const Tag& t) +peteCombine(const A& a, const B& b, const Op& op, const Tag& t) { return Combine2::combine(a, b, op, t); } template inline typename Combine3::Type_t - peteCombine(const A& a, const B& b, const C& c, const Op& op, const Tag& t) +peteCombine(const A& a, const B& b, const C& c, const Op& op, const Tag& t) { return Combine3::combine(a, b, c, op, t); } diff --git a/src/Numerics/PETE/OperatorTags.h b/src/Numerics/PETE/OperatorTags.h index 7ef0938e0..b1972d00e 100644 --- a/src/Numerics/PETE/OperatorTags.h +++ b/src/Numerics/PETE/OperatorTags.h @@ -107,7 +107,7 @@ struct OpSubtractAssign PETE_EMPTY_CONSTRUCTORS(OpSubtractAssign) template inline typename BinaryReturn::Type_t - operator()(const T1& a, const T2& b) const + operator()(const T1& a, const T2& b) const { (const_cast(a) -= b); return const_cast(a); @@ -125,7 +125,7 @@ struct OpMultiplyAssign PETE_EMPTY_CONSTRUCTORS(OpMultiplyAssign) template inline typename BinaryReturn::Type_t - operator()(const T1& a, const T2& b) const + operator()(const T1& a, const T2& b) const { (const_cast(a) *= b); return const_cast(a); @@ -143,7 +143,7 @@ struct OpDivideAssign PETE_EMPTY_CONSTRUCTORS(OpDivideAssign) template inline typename BinaryReturn::Type_t - operator()(const T1& a, const T2& b) const + operator()(const T1& a, const T2& b) const { (const_cast(a) /= b); return const_cast(a); diff --git a/src/Numerics/PosTransformer.h b/src/Numerics/PosTransformer.h index 35b435083..c13e13145 100644 --- a/src/Numerics/PosTransformer.h +++ b/src/Numerics/PosTransformer.h @@ -35,7 +35,7 @@ void PosAoS2SoA(int nrows, int ncols, const T1* restrict iptr, int lda, T2* rest T2* restrict x = out; T2* restrict y = out + ldb; T2* restrict z = out + 2 * ldb; - #pragma omp simd aligned(x, y, z) +#pragma omp simd aligned(x, y, z) for (int i = 0; i < nrows; ++i) { x[i] = iptr[i * ncols]; // x[i]=in[i][0]; @@ -60,7 +60,7 @@ void PosSoA2AoS(int nrows, int ncols, const T1* restrict iptr, int lda, T2* rest const T1* restrict x = iptr; const T1* restrict y = iptr + lda; const T1* restrict z = iptr + 2 * lda; - #pragma omp simd aligned(x, y, z) +#pragma omp simd aligned(x, y, z) for (int i = 0; i < nrows; ++i) { out[i * ldb] = x[i]; // out[i][0]=x[i]; diff --git a/src/Numerics/Spline2/MultiBspline.hpp b/src/Numerics/Spline2/MultiBspline.hpp index f95922ee7..1f43a4d6e 100644 --- a/src/Numerics/Spline2/MultiBspline.hpp +++ b/src/Numerics/Spline2/MultiBspline.hpp @@ -43,39 +43,19 @@ struct MultiBspline * The base address for vals, grads and lapl are set by the callers, e.g., * evaluate_vgh(r,psi,grad,hess,ip). */ - void evaluate_v(const spliner_type* restrict spline_m, - T x, - T y, - T z, - T* restrict vals, + void evaluate_v(const spliner_type* restrict spline_m, T x, T y, T z, T* restrict vals, size_t num_splines) const; - void evaluate_vgl(const spliner_type* restrict spline_m, - T x, - T y, - T z, - T* restrict vals, - T* restrict grads, - T* restrict lapl, - size_t num_splines) const; - - void evaluate_vgh(const spliner_type* restrict spline_m, - T x, - T y, - T z, - T* restrict vals, - T* restrict grads, - T* restrict hess, - size_t num_splines) const; + void evaluate_vgl(const spliner_type* restrict spline_m, T x, T y, T z, T* restrict vals, + T* restrict grads, T* restrict lapl, size_t num_splines) const; + + void evaluate_vgh(const spliner_type* restrict spline_m, T x, T y, T z, T* restrict vals, + T* restrict grads, T* restrict hess, size_t num_splines) const; }; template -inline void MultiBspline::evaluate_v(const spliner_type* restrict spline_m, - T x, - T y, - T z, - T* restrict vals, - size_t num_splines) const +inline void MultiBspline::evaluate_v(const spliner_type* restrict spline_m, T x, T y, T z, + T* restrict vals, size_t num_splines) const { x -= spline_m->x_grid.start; y -= spline_m->y_grid.start; @@ -114,14 +94,9 @@ inline void MultiBspline::evaluate_v(const spliner_type* restrict spline_m, } template -inline void MultiBspline::evaluate_vgl(const spliner_type* restrict spline_m, - T x, - T y, - T z, - T* restrict vals, - T* restrict grads, - T* restrict lapl, - size_t num_splines) const +inline void +MultiBspline::evaluate_vgl(const spliner_type* restrict spline_m, T x, T y, T z, T* restrict vals, + T* restrict grads, T* restrict lapl, size_t num_splines) const { x -= spline_m->x_grid.start; y -= spline_m->y_grid.start; @@ -185,8 +160,8 @@ inline void MultiBspline::evaluate_vgl(const spliner_type* restrict spline_m, const T* restrict coefs3zs = coefs + 3 * zs; ASSUME_ALIGNED(coefs3zs); - #pragma noprefetch - #pragma omp simd +#pragma noprefetch +#pragma omp simd for (int n = 0; n < num_splines; n++) { const T coefsv = coefs[n]; @@ -197,12 +172,12 @@ inline void MultiBspline::evaluate_vgl(const spliner_type* restrict spline_m, T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + c[3] * coefsv3zs; T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + dc[3] * coefsv3zs; T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + d2c[3] * coefsv3zs; - gx[n] += pre10 * sum0; - gy[n] += pre01 * sum0; - gz[n] += pre00 * sum1; - lx[n] += pre20 * sum0; - ly[n] += pre02 * sum0; - lz[n] += pre00 * sum2; + gx[n] += pre10 * sum0; + gy[n] += pre01 * sum0; + gz[n] += pre00 * sum1; + lx[n] += pre20 * sum0; + ly[n] += pre02 * sum0; + lz[n] += pre00 * sum2; vals[n] += pre00 * sum0; } } @@ -215,7 +190,7 @@ inline void MultiBspline::evaluate_vgl(const spliner_type* restrict spline_m, const T dyInv2 = dyInv * dyInv; const T dzInv2 = dzInv * dzInv; - #pragma omp simd +#pragma omp simd for (int n = 0; n < num_splines; n++) { gx[n] *= dxInv; @@ -226,14 +201,9 @@ inline void MultiBspline::evaluate_vgl(const spliner_type* restrict spline_m, } template -inline void MultiBspline::evaluate_vgh(const spliner_type* restrict spline_m, - T x, - T y, - T z, - T* restrict vals, - T* restrict grads, - T* restrict hess, - size_t num_splines) const +inline void +MultiBspline::evaluate_vgh(const spliner_type* restrict spline_m, T x, T y, T z, T* restrict vals, + T* restrict grads, T* restrict hess, size_t num_splines) const { int ix, iy, iz; T tx, ty, tz; @@ -308,7 +278,7 @@ inline void MultiBspline::evaluate_vgh(const spliner_type* restrict spline_m, const T pre02 = a[i] * d2b[j]; const int iSplitPoint = num_splines; - #pragma omp simd +#pragma omp simd for (int n = 0; n < iSplitPoint; n++) { T coefsv = coefs[n]; @@ -320,15 +290,15 @@ inline void MultiBspline::evaluate_vgh(const spliner_type* restrict spline_m, T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + dc[3] * coefsv3zs; T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + d2c[3] * coefsv3zs; - hxx[n] += pre20 * sum0; - hxy[n] += pre11 * sum0; - hxz[n] += pre10 * sum1; - hyy[n] += pre02 * sum0; - hyz[n] += pre01 * sum1; - hzz[n] += pre00 * sum2; - gx[n] += pre10 * sum0; - gy[n] += pre01 * sum0; - gz[n] += pre00 * sum1; + hxx[n] += pre20 * sum0; + hxy[n] += pre11 * sum0; + hxz[n] += pre10 * sum1; + hyy[n] += pre02 * sum0; + hyz[n] += pre01 * sum1; + hzz[n] += pre00 * sum2; + gx[n] += pre10 * sum0; + gy[n] += pre01 * sum0; + gz[n] += pre00 * sum1; vals[n] += pre00 * sum0; } } @@ -343,7 +313,7 @@ inline void MultiBspline::evaluate_vgh(const spliner_type* restrict spline_m, const T dxz = dxInv * dzInv; const T dyz = dyInv * dzInv; - #pragma omp simd +#pragma omp simd for (int n = 0; n < num_splines; n++) { gx[n] *= dxInv; diff --git a/src/Numerics/Spline2/MultiBsplineData.cpp b/src/Numerics/Spline2/MultiBsplineData.cpp index 14d4855f0..b6a9a63af 100644 --- a/src/Numerics/Spline2/MultiBsplineData.cpp +++ b/src/Numerics/Spline2/MultiBsplineData.cpp @@ -19,6 +19,7 @@ namespace qmcplusplus { +// clang-format off /** initialization of static data for MultiBsplineData */ template <> QMC_ALIGNAS const float MultiBsplineData::A44[16] = { @@ -53,4 +54,5 @@ template <> QMC_ALIGNAS const double MultiBsplineData::d2A44[16] = { 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 3.0, -2.0, 0.0, 0.0, -3.0, 1.0, 0.0, 0.0, 1.0, 0.0}; -} +// clang-format on +} // namespace qmcplusplus diff --git a/src/Numerics/Spline2/MultiBsplineRef.hpp b/src/Numerics/Spline2/MultiBsplineRef.hpp index cc1551125..66e759b6b 100644 --- a/src/Numerics/Spline2/MultiBsplineRef.hpp +++ b/src/Numerics/Spline2/MultiBsplineRef.hpp @@ -45,12 +45,8 @@ struct MultiBsplineRef * evaluate_vgh(r,psi,grad,hess,ip). */ - void evaluate_v(const spliner_type* restrict spline_m, - T x, - T y, - T z, - T* restrict vals, - size_t num_splines) const; + void evaluate_v( + const spliner_type* restrict spline_m, T x, T y, T z, T* restrict vals, size_t num_splines) const; void evaluate_vgl(const spliner_type* restrict spline_m, T x, @@ -72,12 +68,8 @@ struct MultiBsplineRef }; template -inline void MultiBsplineRef::evaluate_v(const spliner_type* restrict spline_m, - T x, - T y, - T z, - T* restrict vals, - size_t num_splines) const +inline void MultiBsplineRef::evaluate_v( + const spliner_type* restrict spline_m, T x, T y, T z, T* restrict vals, size_t num_splines) const { x -= spline_m->x_grid.start; y -= spline_m->y_grid.start; @@ -183,12 +175,12 @@ inline void MultiBsplineRef::evaluate_vgl(const spliner_type* restrict spline T sum0 = c[0] * coefsv + c[1] * coefsvzs + c[2] * coefsv2zs + c[3] * coefsv3zs; T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + dc[3] * coefsv3zs; T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + d2c[3] * coefsv3zs; - gx[n] += pre10 * sum0; - gy[n] += pre01 * sum0; - gz[n] += pre00 * sum1; - lx[n] += pre20 * sum0; - ly[n] += pre02 * sum0; - lz[n] += pre00 * sum2; + gx[n] += pre10 * sum0; + gy[n] += pre01 * sum0; + gz[n] += pre00 * sum1; + lx[n] += pre20 * sum0; + ly[n] += pre02 * sum0; + lz[n] += pre00 * sum2; vals[n] += pre00 * sum0; } } @@ -290,15 +282,15 @@ inline void MultiBsplineRef::evaluate_vgh(const spliner_type* restrict spline T sum1 = dc[0] * coefsv + dc[1] * coefsvzs + dc[2] * coefsv2zs + dc[3] * coefsv3zs; T sum2 = d2c[0] * coefsv + d2c[1] * coefsvzs + d2c[2] * coefsv2zs + d2c[3] * coefsv3zs; - hxx[n] += pre20 * sum0; - hxy[n] += pre11 * sum0; - hxz[n] += pre10 * sum1; - hyy[n] += pre02 * sum0; - hyz[n] += pre01 * sum1; - hzz[n] += pre00 * sum2; - gx[n] += pre10 * sum0; - gy[n] += pre01 * sum0; - gz[n] += pre00 * sum1; + hxx[n] += pre20 * sum0; + hxy[n] += pre11 * sum0; + hxz[n] += pre10 * sum1; + hyy[n] += pre02 * sum0; + hyz[n] += pre01 * sum1; + hzz[n] += pre00 * sum2; + gx[n] += pre10 * sum0; + gy[n] += pre01 * sum0; + gz[n] += pre00 * sum1; vals[n] += pre00 * sum0; } } diff --git a/src/Numerics/Spline2/bspline_allocator.cpp b/src/Numerics/Spline2/bspline_allocator.cpp index 91d41e032..c3f577634 100644 --- a/src/Numerics/Spline2/bspline_allocator.cpp +++ b/src/Numerics/Spline2/bspline_allocator.cpp @@ -27,12 +27,8 @@ multi_UBspline_3d_s* einspline_create_multi_UBspline_3d_s(Ugrid x_grid, BCtype_s zBC, int num_splines); -UBspline_3d_s* einspline_create_UBspline_3d_s(Ugrid x_grid, - Ugrid y_grid, - Ugrid z_grid, - BCtype_s xBC, - BCtype_s yBC, - BCtype_s zBC); +UBspline_3d_s* einspline_create_UBspline_3d_s( + Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_s xBC, BCtype_s yBC, BCtype_s zBC); multi_UBspline_3d_d* einspline_create_multi_UBspline_3d_d(Ugrid x_grid, Ugrid y_grid, @@ -42,12 +38,8 @@ multi_UBspline_3d_d* einspline_create_multi_UBspline_3d_d(Ugrid x_grid, BCtype_d zBC, int num_splines); -UBspline_3d_d* einspline_create_UBspline_3d_d(Ugrid x_grid, - Ugrid y_grid, - Ugrid z_grid, - BCtype_d xBC, - BCtype_d yBC, - BCtype_d zBC); +UBspline_3d_d* einspline_create_UBspline_3d_d( + Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_d xBC, BCtype_d yBC, BCtype_d zBC); namespace qmcplusplus { @@ -57,44 +49,26 @@ Allocator::Allocator() : Policy(0) {} Allocator::~Allocator() {} -multi_UBspline_3d_s* Allocator::allocateMultiBspline(Ugrid x_grid, - Ugrid y_grid, - Ugrid z_grid, - BCtype_s xBC, - BCtype_s yBC, - BCtype_s zBC, - int num_splines) +multi_UBspline_3d_s* Allocator::allocateMultiBspline( + Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_s xBC, BCtype_s yBC, BCtype_s zBC, int num_splines) { return einspline_create_multi_UBspline_3d_s(x_grid, y_grid, z_grid, xBC, yBC, zBC, num_splines); } -multi_UBspline_3d_d* Allocator::allocateMultiBspline(Ugrid x_grid, - Ugrid y_grid, - Ugrid z_grid, - BCtype_d xBC, - BCtype_d yBC, - BCtype_d zBC, - int num_splines) +multi_UBspline_3d_d* Allocator::allocateMultiBspline( + Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_d xBC, BCtype_d yBC, BCtype_d zBC, int num_splines) { return einspline_create_multi_UBspline_3d_d(x_grid, y_grid, z_grid, xBC, yBC, zBC, num_splines); } -UBspline_3d_d* Allocator::allocateUBspline(Ugrid x_grid, - Ugrid y_grid, - Ugrid z_grid, - BCtype_d xBC, - BCtype_d yBC, - BCtype_d zBC) +UBspline_3d_d* Allocator::allocateUBspline( + Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_d xBC, BCtype_d yBC, BCtype_d zBC) { return einspline_create_UBspline_3d_d(x_grid, y_grid, z_grid, xBC, yBC, zBC); } -UBspline_3d_s* Allocator::allocateUBspline(Ugrid x_grid, - Ugrid y_grid, - Ugrid z_grid, - BCtype_s xBC, - BCtype_s yBC, - BCtype_s zBC) +UBspline_3d_s* Allocator::allocateUBspline( + Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_s xBC, BCtype_s yBC, BCtype_s zBC) { return einspline_create_UBspline_3d_s(x_grid, y_grid, z_grid, xBC, yBC, zBC); } diff --git a/src/Numerics/Spline2/bspline_allocator.hpp b/src/Numerics/Spline2/bspline_allocator.hpp index ec8c3325f..48f9ca819 100644 --- a/src/Numerics/Spline2/bspline_allocator.hpp +++ b/src/Numerics/Spline2/bspline_allocator.hpp @@ -68,11 +68,11 @@ class Allocator /// allocate a single bspline UBspline_3d_s* - allocateUBspline(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_s xBC, BCtype_s yBC, BCtype_s zBC); + allocateUBspline(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_s xBC, BCtype_s yBC, BCtype_s zBC); /// allocate a UBspline_3d_d UBspline_3d_d* - allocateUBspline(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_d xBC, BCtype_d yBC, BCtype_d zBC); + allocateUBspline(Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_d xBC, BCtype_d yBC, BCtype_d zBC); /** allocate a multi_UBspline_3d_(s,d) * @tparam T datatype @@ -81,7 +81,7 @@ class Allocator */ template typename bspline_traits::SplineType* - createMultiBspline(T dummy, ValT& start, ValT& end, IntT& ng, bc_code bc, int num_splines); + createMultiBspline(T dummy, ValT& start, ValT& end, IntT& ng, bc_code bc, int num_splines); /** allocate a UBspline_3d_(s,d) * @tparam T datatype @@ -90,7 +90,7 @@ class Allocator */ template typename bspline_traits::SingleSplineType* - createUBspline(ValT& start, ValT& end, IntT& ng, bc_code bc); + createUBspline(ValT& start, ValT& end, IntT& ng, bc_code bc); /** Set coefficients for a single orbital (band) * @param i index of the orbital @@ -118,7 +118,7 @@ void Allocator::setCoefficientsForOneOrbital(int i, Array& coeff, typename bspline_traits::SplineType* spline) { - #pragma omp parallel for collapse(3) +#pragma omp parallel for collapse(3) for (int ix = 0; ix < spline->x_grid.num + 3; ix++) { for (int iy = 0; iy < spline->y_grid.num + 3; iy++) @@ -136,7 +136,7 @@ void Allocator::setCoefficientsForOneOrbital(int i, template typename bspline_traits::SplineType* - Allocator::createMultiBspline(T dummy, ValT& start, ValT& end, IntT& ng, bc_code bc, int num_splines) +Allocator::createMultiBspline(T dummy, ValT& start, ValT& end, IntT& ng, bc_code bc, int num_splines) { Ugrid x_grid, y_grid, z_grid; typename bspline_traits::BCType xBC, yBC, zBC; @@ -157,7 +157,7 @@ typename bspline_traits::SplineType* template typename bspline_traits::SingleSplineType* - Allocator::createUBspline(ValT& start, ValT& end, IntT& ng, bc_code bc) +Allocator::createUBspline(ValT& start, ValT& end, IntT& ng, bc_code bc) { Ugrid x_grid, y_grid, z_grid; typename bspline_traits::BCType xBC, yBC, zBC; diff --git a/src/Numerics/Spline2/einspline_allocator.cpp b/src/Numerics/Spline2/einspline_allocator.cpp index 9d774dd90..ba4f43cd6 100644 --- a/src/Numerics/Spline2/einspline_allocator.cpp +++ b/src/Numerics/Spline2/einspline_allocator.cpp @@ -67,13 +67,8 @@ void einspline_free(void* aligned) } #endif -multi_UBspline_3d_s* einspline_create_multi_UBspline_3d_s(Ugrid x_grid, - Ugrid y_grid, - Ugrid z_grid, - BCtype_s xBC, - BCtype_s yBC, - BCtype_s zBC, - int num_splines) +multi_UBspline_3d_s* einspline_create_multi_UBspline_3d_s( + Ugrid x_grid, Ugrid y_grid, Ugrid z_grid, BCtype_s xBC, BCtype_s yBC, BCtype_s zBC, int num_splines) { // Create new spline multi_UBspline_3d_s* restrict spline = (multi_UBspline_3d_s*)malloc(sizeof(multi_UBspline_3d_s)); @@ -145,7 +140,7 @@ multi_UBspline_3d_s* einspline_create_multi_UBspline_3d_s(Ugrid x_grid, const size_t zs = spline->z_stride; const float czero=0; - #pragma omp parallel for collapse(3) +#pragma omp parallel for collapse(3) for(size_t i=0; i Date: Thu, 2 Aug 2018 21:43:37 -0400 Subject: [PATCH 6/8] clang-format mauls config.h.cmake.in --- src/config.h.cmake.in | 128 ++++++++++++++++++++++-------------------- 1 file changed, 66 insertions(+), 62 deletions(-) diff --git a/src/config.h.cmake.in b/src/config.h.cmake.in index 41f5236ef..77a9502af 100644 --- a/src/config.h.cmake.in +++ b/src/config.h.cmake.in @@ -8,128 +8,132 @@ #ifndef QMCPLUSPLUS_CONFIGURATION_H #define QMCPLUSPLUS_CONFIGURATION_H +// clang-format off + /* define the major version */ -#define QMCPACK_VERSION_MAJOR @QMCPACK_VERSION_MAJOR @ +#define QMCPACK_VERSION_MAJOR @QMCPACK_VERSION_MAJOR@ /* define the minor version */ -#define QMCPACK_VERSION_MINOR @QMCPACK_VERSION_MINOR @ +#define QMCPACK_VERSION_MINOR @QMCPACK_VERSION_MINOR@ /* define the patch version */ -#define QMCPACK_VERSION_PATCH @QMCPACK_VERSION_PATCH @ +#define QMCPACK_VERSION_PATCH @QMCPACK_VERSION_PATCH@ /* define the release version */ -#cmakedefine QMCPACK_RELEASE @QMCAPCK_RELEASE @ +#cmakedefine QMCPACK_RELEASE @QMCAPCK_RELEASE@ /* define the git last commit date */ // #cmakedefine QMCPLUSPLUS_LAST_CHANGED_DATE "@QMCPLUSPLUS_LAST_CHANGED_DATE@" /* define QMC_BUILD_LEVEL */ -#cmakedefine QMC_BUILD_LEVEL @QMC_BUILD_LEVEL @ +#cmakedefine QMC_BUILD_LEVEL @QMC_BUILD_LEVEL@ /* Enable OpenMP parallelization. */ -#cmakedefine ENABLE_OPENMP @ENABLE_OPENMP @ +#cmakedefine ENABLE_OPENMP @ENABLE_OPENMP@ /* Define to 1 if you have the `hdf5' library (-lhdf5). */ -#cmakedefine HAVE_LIBHDF5 @HAVE_LIBHDF5 @ +#cmakedefine HAVE_LIBHDF5 @HAVE_LIBHDF5@ /* Define to 1 if you want to use parallel hdf5 for frequent output */ -#cmakedefine ENABLE_PHDF5 @ENABLE_PHDF5 @ +#cmakedefine ENABLE_PHDF5 @ENABLE_PHDF5@ /* Define to 1 if you have MPI library */ -#cmakedefine HAVE_MPI @HAVE_MPI @ +#cmakedefine HAVE_MPI @HAVE_MPI@ /* Define the physical dimension of appliation. */ -#cmakedefine OHMMS_DIM @OHMMS_DIM @ +#cmakedefine OHMMS_DIM @OHMMS_DIM@ /* Define the index type: int, long */ -#cmakedefine OHMMS_INDEXTYPE @OHMMS_INDEXTYPE @ +#cmakedefine OHMMS_INDEXTYPE @OHMMS_INDEXTYPE@ /* Define the base precision: float, double */ -#cmakedefine OHMMS_PRECISION @OHMMS_PRECISION @ +#cmakedefine OHMMS_PRECISION @OHMMS_PRECISION@ /* Define the full precision: double, long double */ -#cmakedefine OHMMS_PRECISION_FULL @OHMMS_PRECISION_FULL @ +#cmakedefine OHMMS_PRECISION_FULL @OHMMS_PRECISION_FULL@ /* Define to 1 if precision is mixed, only for the CPU code */ -#cmakedefine MIXED_PRECISION @MIXED_PRECISION @ +#cmakedefine MIXED_PRECISION @MIXED_PRECISION@ /* Define to 1 if complex wavefunctions are used */ -#cmakedefine QMC_COMPLEX @QMC_COMPLEX @ +#cmakedefine QMC_COMPLEX @QMC_COMPLEX@ /* Define if the code is specialized for orthorhombic supercell */ -#define OHMMS_ORTHO @OHMMS_ORTHO @ +#define OHMMS_ORTHO @OHMMS_ORTHO@ /* Define if sincos function exists */ -#cmakedefine HAVE_SINCOS @HAVE_SINCOS @ +#cmakedefine HAVE_SINCOS @HAVE_SINCOS@ /* Define if posix_memalign function exists */ -#cmakedefine HAVE_POSIX_MEMALIGN @HAVE_POSIX_MEMALIGN @ +#cmakedefine HAVE_POSIX_MEMALIGN @HAVE_POSIX_MEMALIGN@ /* Find mkl library */ -#cmakedefine HAVE_MKL @HAVE_MKL @ +#cmakedefine HAVE_MKL @HAVE_MKL@ /* Find mkl/vml library */ -#cmakedefine HAVE_MKL_VML @HAVE_MKL_VML @ +#cmakedefine HAVE_MKL_VML @HAVE_MKL_VML@ /* Find essl library */ -#cmakedefine HAVE_ESSL @HAVE_ESSL @ +#cmakedefine HAVE_ESSL @HAVE_ESSL@ /* Fund acml library */ -#cmakedefine HAVE_ACML @HAVE_ACML @ +#cmakedefine HAVE_ACML @HAVE_ACML@ /* For AFQMC compilation */ -#cmakedefine BUILD_AFQMC @BUILD_AFQMC @ +#cmakedefine BUILD_AFQMC @BUILD_AFQMC@ /* For FCIQMC compilation */ -#cmakedefine BUILD_FCIQMC @BUILD_FCIQMC @ +#cmakedefine BUILD_FCIQMC @BUILD_FCIQMC@ -#cmakedefine DEBUG_PSIBUFFER_ON @DEBUG_PSIBUFFER_ON @ +#cmakedefine DEBUG_PSIBUFFER_ON @DEBUG_PSIBUFFER_ON@ #if (__cplusplus >= 201103L) -#if defined(__INTEL_COMPILER) -#if defined(__KNC__) || defined(__AVX512F__) -#define QMC_CLINE 64 -#define QMC_ALIGNAS alignas(64) -#define ASSUME_ALIGNED(x) __assume_aligned(x, 64) -#else -#define QMC_CLINE 32 -#define QMC_ALIGNAS alignas(32) -#define ASSUME_ALIGNED(x) __assume_aligned(x, 32) -#endif -#elif defined(__GNUC__) && !defined(__ibmxl__) -#if defined(__AVX512F__) -#define QMC_CLINE 64 -#define QMC_ALIGNAS alignas(64) -#define ASSUME_ALIGNED(x) (x) = (__typeof__(x))__builtin_assume_aligned(x, 64) -#else -#define QMC_CLINE 32 -#define QMC_ALIGNAS alignas(32) -#define ASSUME_ALIGNED(x) (x) = (__typeof__(x))__builtin_assume_aligned(x, 32) -#endif -#else -#define QMC_CLINE 32 -#define QMC_ALIGNAS -#define ASSUME_ALIGNED(x) -#endif + #if defined(__INTEL_COMPILER) + #if defined(__KNC__) || defined(__AVX512F__) + #define QMC_CLINE 64 + #define QMC_ALIGNAS alignas(64) + #define ASSUME_ALIGNED(x) __assume_aligned(x,64) + #else + #define QMC_CLINE 32 + #define QMC_ALIGNAS alignas(32) + #define ASSUME_ALIGNED(x) __assume_aligned(x,32) + #endif + #elif defined(__GNUC__) && !defined(__ibmxl__) + #if defined(__AVX512F__) + #define QMC_CLINE 64 + #define QMC_ALIGNAS alignas(64) + #define ASSUME_ALIGNED(x) (x) = (__typeof__(x)) __builtin_assume_aligned(x,64) + #else + #define QMC_CLINE 32 + #define QMC_ALIGNAS alignas(32) + #define ASSUME_ALIGNED(x) (x) = (__typeof__(x)) __builtin_assume_aligned(x,32) + #endif + #else + #define QMC_CLINE 32 + #define QMC_ALIGNAS + #define ASSUME_ALIGNED(x) + #endif #else //capture both C or non-c++11 -#if defined(__KNC__) || defined(__AVX512F__) -#define QMC_CLINE 64 -#else -#define QMC_CLINE 32 -#endif -#define QMC_ALIGNAS -#define ASSUME_ALIGNED(x) -#ifndef nullptr -#define nullptr NULL -#endif + #if defined(__KNC__) || defined(__AVX512F__) + #define QMC_CLINE 64 + #else + #define QMC_CLINE 32 + #endif + #define QMC_ALIGNAS + #define ASSUME_ALIGNED(x) + #ifndef nullptr + #define nullptr NULL + #endif #endif /* Internal timers */ -#cmakedefine ENABLE_TIMERS @ENABLE_TIMERS @ +#cmakedefine ENABLE_TIMERS @ENABLE_TIMERS@ /* Use VTune Task API with timers */ -#cmakedefine USE_VTUNE_TASKS @USE_VTUNE_TASKS @ +#cmakedefine USE_VTUNE_TASKS @USE_VTUNE_TASKS@ +// clang-format on #endif // QMCPLUSPLUS_CONFIGURATION_H + From 36eb64158b2cd49e7ece50a98156229bcfde6c93 Mon Sep 17 00:00:00 2001 From: Peter Doak Date: Fri, 3 Aug 2018 13:53:06 -0400 Subject: [PATCH 7/8] protecting tinyxml from clang-format --- src/Utilities/tinyxml/.clang-format | 5 + src/Utilities/tinyxml/tinyxml2.cpp | 4154 +++++++++++++-------------- src/Utilities/tinyxml/tinyxml2.h | 2698 ++++++++--------- 3 files changed, 3353 insertions(+), 3504 deletions(-) create mode 100644 src/Utilities/tinyxml/.clang-format mode change 100644 => 100755 src/Utilities/tinyxml/tinyxml2.cpp mode change 100644 => 100755 src/Utilities/tinyxml/tinyxml2.h diff --git a/src/Utilities/tinyxml/.clang-format b/src/Utilities/tinyxml/.clang-format new file mode 100644 index 000000000..f33eb8a03 --- /dev/null +++ b/src/Utilities/tinyxml/.clang-format @@ -0,0 +1,5 @@ +--- +Language: Cpp +DisableFormat: true +... + diff --git a/src/Utilities/tinyxml/tinyxml2.cpp b/src/Utilities/tinyxml/tinyxml2.cpp old mode 100644 new mode 100755 index d394e4eaa..012f5803a --- a/src/Utilities/tinyxml/tinyxml2.cpp +++ b/src/Utilities/tinyxml/tinyxml2.cpp @@ -23,93 +23,90 @@ distribution. #include "tinyxml2.h" -#include // yes, this one new style header, is in the Android SDK. +#include // yes, this one new style header, is in the Android SDK. #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) -#include -#include +# include +# include #else -#include -#include +# include +# include #endif -#if defined(_MSC_VER) && (_MSC_VER >= 1400) && (!defined WINCE) -// Microsoft Visual Studio, version 2005 and higher. Not WinCE. -/*int _snprintf_s( +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) + // Microsoft Visual Studio, version 2005 and higher. Not WinCE. + /*int _snprintf_s( char *buffer, size_t sizeOfBuffer, size_t count, const char *format [, argument] ... );*/ -static inline int TIXML_SNPRINTF(char* buffer, size_t size, const char* format, ...) -{ - va_list va; - va_start(va, format); - int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va); - va_end(va); - return result; -} - -static inline int TIXML_VSNPRINTF(char* buffer, size_t size, const char* format, va_list va) -{ - int result = vsnprintf_s(buffer, size, _TRUNCATE, format, va); - return result; -} - -#define TIXML_VSCPRINTF _vscprintf -#define TIXML_SSCANF sscanf_s + static inline int TIXML_SNPRINTF( char* buffer, size_t size, const char* format, ... ) + { + va_list va; + va_start( va, format ); + int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); + va_end( va ); + return result; + } + + static inline int TIXML_VSNPRINTF( char* buffer, size_t size, const char* format, va_list va ) + { + int result = vsnprintf_s( buffer, size, _TRUNCATE, format, va ); + return result; + } + + #define TIXML_VSCPRINTF _vscprintf + #define TIXML_SSCANF sscanf_s #elif defined _MSC_VER -// Microsoft Visual Studio 2003 and earlier or WinCE -#define TIXML_SNPRINTF _snprintf -#define TIXML_VSNPRINTF _vsnprintf -#define TIXML_SSCANF sscanf -#if (_MSC_VER < 1400) && (!defined WINCE) -// Microsoft Visual Studio 2003 and not WinCE. -#define TIXML_VSCPRINTF \ - _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. + // Microsoft Visual Studio 2003 and earlier or WinCE + #define TIXML_SNPRINTF _snprintf + #define TIXML_VSNPRINTF _vsnprintf + #define TIXML_SSCANF sscanf + #if (_MSC_VER < 1400 ) && (!defined WINCE) + // Microsoft Visual Studio 2003 and not WinCE. + #define TIXML_VSCPRINTF _vscprintf // VS2003's C runtime has this, but VC6 C runtime or WinCE SDK doesn't have. + #else + // Microsoft Visual Studio 2003 and earlier or WinCE. + static inline int TIXML_VSCPRINTF( const char* format, va_list va ) + { + int len = 512; + for (;;) { + len = len*2; + char* str = new char[len](); + const int required = _vsnprintf(str, len, format, va); + delete[] str; + if ( required != -1 ) { + TIXMLASSERT( required >= 0 ); + len = required; + break; + } + } + TIXMLASSERT( len >= 0 ); + return len; + } + #endif #else -// Microsoft Visual Studio 2003 and earlier or WinCE. -static inline int TIXML_VSCPRINTF(const char* format, va_list va) -{ - int len = 512; - for (;;) - { - len = len * 2; - char* str = new char[len](); - const int required = _vsnprintf(str, len, format, va); - delete[] str; - if (required != -1) - { - TIXMLASSERT(required >= 0); - len = required; - break; - } - } - TIXMLASSERT(len >= 0); - return len; -} -#endif -#else -// GCC version 3 and higher -//#warning( "Using sn* functions." ) -#define TIXML_SNPRINTF snprintf -#define TIXML_VSNPRINTF vsnprintf -static inline int TIXML_VSCPRINTF(const char* format, va_list va) -{ - int len = vsnprintf(0, 0, format, va); - TIXMLASSERT(len >= 0); - return len; -} -#define TIXML_SSCANF sscanf + // GCC version 3 and higher + //#warning( "Using sn* functions." ) + #define TIXML_SNPRINTF snprintf + #define TIXML_VSNPRINTF vsnprintf + static inline int TIXML_VSCPRINTF( const char* format, va_list va ) + { + int len = vsnprintf( 0, 0, format, va ); + TIXMLASSERT( len >= 0 ); + return len; + } + #define TIXML_SSCANF sscanf #endif -static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF -static const char LF = LINE_FEED; -static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out -static const char CR = CARRIAGE_RETURN; -static const char SINGLE_QUOTE = '\''; -static const char DOUBLE_QUOTE = '\"'; +static const char LINE_FEED = (char)0x0a; // all line endings are normalized to LF +static const char LF = LINE_FEED; +static const char CARRIAGE_RETURN = (char)0x0d; // CR gets filtered out +static const char CR = CARRIAGE_RETURN; +static const char SINGLE_QUOTE = '\''; +static const char DOUBLE_QUOTE = '\"'; // Bunch of unicode info at: // http://www.unicode.org/faq/utf_bom.html @@ -121,280 +118,255 @@ static const unsigned char TIXML_UTF_LEAD_2 = 0xbfU; namespace tinyxml2 { -struct Entity -{ - const char* pattern; - int length; - char value; + +struct Entity { + const char* pattern; + int length; + char value; }; -static const int NUM_ENTITIES = 5; -static const Entity entities[NUM_ENTITIES] = {{"quot", 4, DOUBLE_QUOTE}, - {"amp", 3, '&'}, - {"apos", 4, SINGLE_QUOTE}, - {"lt", 2, '<'}, - {"gt", 2, '>'}}; +static const int NUM_ENTITIES = 5; +static const Entity entities[NUM_ENTITIES] = { + { "quot", 4, DOUBLE_QUOTE }, + { "amp", 3, '&' }, + { "apos", 4, SINGLE_QUOTE }, + { "lt", 2, '<' }, + { "gt", 2, '>' } +}; -StrPair::~StrPair() { Reset(); } +StrPair::~StrPair() +{ + Reset(); +} -void StrPair::TransferTo(StrPair* other) +void StrPair::TransferTo( StrPair* other ) { - if (this == other) - { - return; - } - // This in effect implements the assignment operator by "moving" - // ownership (as in auto_ptr). + if ( this == other ) { + return; + } + // This in effect implements the assignment operator by "moving" + // ownership (as in auto_ptr). - TIXMLASSERT(other != 0); - TIXMLASSERT(other->_flags == 0); - TIXMLASSERT(other->_start == 0); - TIXMLASSERT(other->_end == 0); + TIXMLASSERT( other != 0 ); + TIXMLASSERT( other->_flags == 0 ); + TIXMLASSERT( other->_start == 0 ); + TIXMLASSERT( other->_end == 0 ); - other->Reset(); + other->Reset(); - other->_flags = _flags; - other->_start = _start; - other->_end = _end; + other->_flags = _flags; + other->_start = _start; + other->_end = _end; - _flags = 0; - _start = 0; - _end = 0; + _flags = 0; + _start = 0; + _end = 0; } void StrPair::Reset() { - if (_flags & NEEDS_DELETE) - { - delete[] _start; - } - _flags = 0; - _start = 0; - _end = 0; + if ( _flags & NEEDS_DELETE ) { + delete [] _start; + } + _flags = 0; + _start = 0; + _end = 0; } -void StrPair::SetStr(const char* str, int flags) +void StrPair::SetStr( const char* str, int flags ) { - TIXMLASSERT(str); - Reset(); - size_t len = strlen(str); - TIXMLASSERT(_start == 0); - _start = new char[len + 1]; - memcpy(_start, str, len + 1); - _end = _start + len; - _flags = flags | NEEDS_DELETE; + TIXMLASSERT( str ); + Reset(); + size_t len = strlen( str ); + TIXMLASSERT( _start == 0 ); + _start = new char[ len+1 ]; + memcpy( _start, str, len+1 ); + _end = _start + len; + _flags = flags | NEEDS_DELETE; } -char* StrPair::ParseText(char* p, const char* endTag, int strFlags, int* curLineNumPtr) +char* StrPair::ParseText( char* p, const char* endTag, int strFlags, int* curLineNumPtr ) { - TIXMLASSERT(p); - TIXMLASSERT(endTag && *endTag); - TIXMLASSERT(curLineNumPtr); + TIXMLASSERT( p ); + TIXMLASSERT( endTag && *endTag ); + TIXMLASSERT(curLineNumPtr); - char* start = p; - char endChar = *endTag; - size_t length = strlen(endTag); + char* start = p; + char endChar = *endTag; + size_t length = strlen( endTag ); - // Inner loop of text parsing. - while (*p) - { - if (*p == endChar && strncmp(p, endTag, length) == 0) - { - Set(start, p, strFlags); - return p + length; - } - else if (*p == '\n') - { - ++(*curLineNumPtr); + // Inner loop of text parsing. + while ( *p ) { + if ( *p == endChar && strncmp( p, endTag, length ) == 0 ) { + Set( start, p, strFlags ); + return p + length; + } else if (*p == '\n') { + ++(*curLineNumPtr); + } + ++p; + TIXMLASSERT( p ); } - ++p; - TIXMLASSERT(p); - } - return 0; + return 0; } -char* StrPair::ParseName(char* p) +char* StrPair::ParseName( char* p ) { - if (!p || !(*p)) - { - return 0; - } - if (!XMLUtil::IsNameStartChar(*p)) - { - return 0; - } + if ( !p || !(*p) ) { + return 0; + } + if ( !XMLUtil::IsNameStartChar( *p ) ) { + return 0; + } - char* const start = p; - ++p; - while (*p && XMLUtil::IsNameChar(*p)) - { + char* const start = p; ++p; - } + while ( *p && XMLUtil::IsNameChar( *p ) ) { + ++p; + } - Set(start, p, 0); - return p; + Set( start, p, 0 ); + return p; } void StrPair::CollapseWhitespace() { - // Adjusting _start would cause undefined behavior on delete[] - TIXMLASSERT((_flags & NEEDS_DELETE) == 0); - // Trim leading space. - _start = XMLUtil::SkipWhiteSpace(_start, 0); - - if (*_start) - { - const char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while (*p) - { - if (XMLUtil::IsWhiteSpace(*p)) - { - p = XMLUtil::SkipWhiteSpace(p, 0); - if (*p == 0) - { - break; // don't write to q; this trims the trailing space. + // Adjusting _start would cause undefined behavior on delete[] + TIXMLASSERT( ( _flags & NEEDS_DELETE ) == 0 ); + // Trim leading space. + _start = XMLUtil::SkipWhiteSpace( _start, 0 ); + + if ( *_start ) { + const char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( *p ) { + if ( XMLUtil::IsWhiteSpace( *p )) { + p = XMLUtil::SkipWhiteSpace( p, 0 ); + if ( *p == 0 ) { + break; // don't write to q; this trims the trailing space. + } + *q = ' '; + ++q; + } + *q = *p; + ++q; + ++p; } - *q = ' '; - ++q; - } - *q = *p; - ++q; - ++p; + *q = 0; } - *q = 0; - } } const char* StrPair::GetStr() { - TIXMLASSERT(_start); - TIXMLASSERT(_end); - if (_flags & NEEDS_FLUSH) - { - *_end = 0; - _flags ^= NEEDS_FLUSH; - - if (_flags) - { - const char* p = _start; // the read pointer - char* q = _start; // the write pointer - - while (p < _end) - { - if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR) - { - // CR-LF pair becomes LF - // CR alone becomes LF - // LF-CR becomes LF - if (*(p + 1) == LF) - { - p += 2; - } - else - { - ++p; - } - *q = LF; - ++q; - } - else if ((_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF) - { - if (*(p + 1) == CR) - { - p += 2; - } - else - { - ++p; - } - *q = LF; - ++q; - } - else if ((_flags & NEEDS_ENTITY_PROCESSING) && *p == '&') - { - // Entities handled by tinyXML2: - // - special entities in the entity table [in/out] - // - numeric character reference [in] - // 中 or 中 - - if (*(p + 1) == '#') - { - const int buflen = 10; - char buf[buflen] = {0}; - int len = 0; - char* adjusted = const_cast(XMLUtil::GetCharacterRef(p, buf, &len)); - if (adjusted == 0) - { - *q = *p; - ++p; - ++q; - } - else - { - TIXMLASSERT(0 <= len && len <= buflen); - TIXMLASSERT(q + len <= adjusted); - p = adjusted; - memcpy(q, buf, len); - q += len; - } - } - else - { - bool entityFound = false; - for (int i = 0; i < NUM_ENTITIES; ++i) - { - const Entity& entity = entities[i]; - if (strncmp(p + 1, entity.pattern, entity.length) == 0 && - *(p + entity.length + 1) == ';') - { - // Found an entity - convert. - *q = entity.value; - ++q; - p += entity.length + 2; - entityFound = true; - break; - } - } - if (!entityFound) - { - // fixme: treat as error? - ++p; - ++q; + TIXMLASSERT( _start ); + TIXMLASSERT( _end ); + if ( _flags & NEEDS_FLUSH ) { + *_end = 0; + _flags ^= NEEDS_FLUSH; + + if ( _flags ) { + const char* p = _start; // the read pointer + char* q = _start; // the write pointer + + while( p < _end ) { + if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == CR ) { + // CR-LF pair becomes LF + // CR alone becomes LF + // LF-CR becomes LF + if ( *(p+1) == LF ) { + p += 2; + } + else { + ++p; + } + *q = LF; + ++q; + } + else if ( (_flags & NEEDS_NEWLINE_NORMALIZATION) && *p == LF ) { + if ( *(p+1) == CR ) { + p += 2; + } + else { + ++p; + } + *q = LF; + ++q; + } + else if ( (_flags & NEEDS_ENTITY_PROCESSING) && *p == '&' ) { + // Entities handled by tinyXML2: + // - special entities in the entity table [in/out] + // - numeric character reference [in] + // 中 or 中 + + if ( *(p+1) == '#' ) { + const int buflen = 10; + char buf[buflen] = { 0 }; + int len = 0; + char* adjusted = const_cast( XMLUtil::GetCharacterRef( p, buf, &len ) ); + if ( adjusted == 0 ) { + *q = *p; + ++p; + ++q; + } + else { + TIXMLASSERT( 0 <= len && len <= buflen ); + TIXMLASSERT( q + len <= adjusted ); + p = adjusted; + memcpy( q, buf, len ); + q += len; + } + } + else { + bool entityFound = false; + for( int i = 0; i < NUM_ENTITIES; ++i ) { + const Entity& entity = entities[i]; + if ( strncmp( p + 1, entity.pattern, entity.length ) == 0 + && *( p + entity.length + 1 ) == ';' ) { + // Found an entity - convert. + *q = entity.value; + ++q; + p += entity.length + 2; + entityFound = true; + break; + } + } + if ( !entityFound ) { + // fixme: treat as error? + ++p; + ++q; + } + } + } + else { + *q = *p; + ++p; + ++q; + } } - } + *q = 0; } - else - { - *q = *p; - ++p; - ++q; + // The loop below has plenty going on, and this + // is a less useful mode. Break it out. + if ( _flags & NEEDS_WHITESPACE_COLLAPSING ) { + CollapseWhitespace(); } - } - *q = 0; - } - // The loop below has plenty going on, and this - // is a less useful mode. Break it out. - if (_flags & NEEDS_WHITESPACE_COLLAPSING) - { - CollapseWhitespace(); + _flags = (_flags & NEEDS_DELETE); } - _flags = (_flags & NEEDS_DELETE); - } - TIXMLASSERT(_start); - return _start; + TIXMLASSERT( _start ); + return _start; } + + // --------- XMLUtil ----------- // const char* XMLUtil::writeBoolTrue = "true"; @@ -402,1816 +374,1676 @@ const char* XMLUtil::writeBoolFalse = "false"; void XMLUtil::SetBoolSerialization(const char* writeTrue, const char* writeFalse) { - static const char* defTrue = "true"; - static const char* defFalse = "false"; - - writeBoolTrue = (writeTrue) ? writeTrue : defTrue; - writeBoolFalse = (writeFalse) ? writeFalse : defFalse; -} - - -const char* XMLUtil::ReadBOM(const char* p, bool* bom) -{ - TIXMLASSERT(p); - TIXMLASSERT(bom); - *bom = false; - const unsigned char* pu = reinterpret_cast(p); - // Check for BOM: - if (*(pu + 0) == TIXML_UTF_LEAD_0 && *(pu + 1) == TIXML_UTF_LEAD_1 && *(pu + 2) == TIXML_UTF_LEAD_2) - { - *bom = true; - p += 3; - } - TIXMLASSERT(p); - return p; -} - - -void XMLUtil::ConvertUTF32ToUTF8(unsigned long input, char* output, int* length) -{ - const unsigned long BYTE_MASK = 0xBF; - const unsigned long BYTE_MARK = 0x80; - const unsigned long FIRST_BYTE_MARK[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC}; - - if (input < 0x80) - { - *length = 1; - } - else if (input < 0x800) - { - *length = 2; - } - else if (input < 0x10000) - { - *length = 3; - } - else if (input < 0x200000) - { - *length = 4; - } - else - { - *length = 0; // This code won't convert this correctly anyway. - return; - } - - output += *length; - - // Scary scary fall throughs are annotated with carefully designed comments - // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc - switch (*length) - { - case 4: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - //fall through - case 3: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - //fall through - case 2: - --output; - *output = (char)((input | BYTE_MARK) & BYTE_MASK); - input >>= 6; - //fall through - case 1: - --output; - *output = (char)(input | FIRST_BYTE_MARK[*length]); - break; - default: - TIXMLASSERT(false); - } -} - - -const char* XMLUtil::GetCharacterRef(const char* p, char* value, int* length) -{ - // Presume an entity, and pull it out. - *length = 0; - - if (*(p + 1) == '#' && *(p + 2)) - { - unsigned long ucs = 0; - TIXMLASSERT(sizeof(ucs) >= 4); - ptrdiff_t delta = 0; - unsigned mult = 1; - static const char SEMICOLON = ';'; - - if (*(p + 2) == 'x') - { - // Hexadecimal. - const char* q = p + 3; - if (!(*q)) - { - return 0; - } + static const char* defTrue = "true"; + static const char* defFalse = "false"; - q = strchr(q, SEMICOLON); + writeBoolTrue = (writeTrue) ? writeTrue : defTrue; + writeBoolFalse = (writeFalse) ? writeFalse : defFalse; +} - if (!q) - { - return 0; - } - TIXMLASSERT(*q == SEMICOLON); - delta = q - p; - --q; +const char* XMLUtil::ReadBOM( const char* p, bool* bom ) +{ + TIXMLASSERT( p ); + TIXMLASSERT( bom ); + *bom = false; + const unsigned char* pu = reinterpret_cast(p); + // Check for BOM: + if ( *(pu+0) == TIXML_UTF_LEAD_0 + && *(pu+1) == TIXML_UTF_LEAD_1 + && *(pu+2) == TIXML_UTF_LEAD_2 ) { + *bom = true; + p += 3; + } + TIXMLASSERT( p ); + return p; +} + - while (*q != 'x') - { - unsigned int digit = 0; +void XMLUtil::ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ) +{ + const unsigned long BYTE_MASK = 0xBF; + const unsigned long BYTE_MARK = 0x80; + const unsigned long FIRST_BYTE_MARK[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - if (*q >= '0' && *q <= '9') - { - digit = *q - '0'; - } - else if (*q >= 'a' && *q <= 'f') - { - digit = *q - 'a' + 10; - } - else if (*q >= 'A' && *q <= 'F') - { - digit = *q - 'A' + 10; - } - else - { - return 0; - } - TIXMLASSERT(digit < 16); - TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit); - const unsigned int digitScaled = mult * digit; - TIXMLASSERT(ucs <= ULONG_MAX - digitScaled); - ucs += digitScaled; - TIXMLASSERT(mult <= UINT_MAX / 16); - mult *= 16; - --q; - } - } - else - { - // Decimal. - const char* q = p + 2; - if (!(*q)) - { - return 0; - } + if (input < 0x80) { + *length = 1; + } + else if ( input < 0x800 ) { + *length = 2; + } + else if ( input < 0x10000 ) { + *length = 3; + } + else if ( input < 0x200000 ) { + *length = 4; + } + else { + *length = 0; // This code won't convert this correctly anyway. + return; + } + + output += *length; + + // Scary scary fall throughs are annotated with carefully designed comments + // to suppress compiler warnings such as -Wimplicit-fallthrough in gcc + switch (*length) { + case 4: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 3: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 2: + --output; + *output = (char)((input | BYTE_MARK) & BYTE_MASK); + input >>= 6; + //fall through + case 1: + --output; + *output = (char)(input | FIRST_BYTE_MARK[*length]); + break; + default: + TIXMLASSERT( false ); + } +} - q = strchr(q, SEMICOLON); - if (!q) - { - return 0; - } - TIXMLASSERT(*q == SEMICOLON); - - delta = q - p; - --q; - - while (*q != '#') - { - if (*q >= '0' && *q <= '9') - { - const unsigned int digit = *q - '0'; - TIXMLASSERT(digit < 10); - TIXMLASSERT(digit == 0 || mult <= UINT_MAX / digit); - const unsigned int digitScaled = mult * digit; - TIXMLASSERT(ucs <= ULONG_MAX - digitScaled); - ucs += digitScaled; +const char* XMLUtil::GetCharacterRef( const char* p, char* value, int* length ) +{ + // Presume an entity, and pull it out. + *length = 0; + + if ( *(p+1) == '#' && *(p+2) ) { + unsigned long ucs = 0; + TIXMLASSERT( sizeof( ucs ) >= 4 ); + ptrdiff_t delta = 0; + unsigned mult = 1; + static const char SEMICOLON = ';'; + + if ( *(p+2) == 'x' ) { + // Hexadecimal. + const char* q = p+3; + if ( !(*q) ) { + return 0; + } + + q = strchr( q, SEMICOLON ); + + if ( !q ) { + return 0; + } + TIXMLASSERT( *q == SEMICOLON ); + + delta = q-p; + --q; + + while ( *q != 'x' ) { + unsigned int digit = 0; + + if ( *q >= '0' && *q <= '9' ) { + digit = *q - '0'; + } + else if ( *q >= 'a' && *q <= 'f' ) { + digit = *q - 'a' + 10; + } + else if ( *q >= 'A' && *q <= 'F' ) { + digit = *q - 'A' + 10; + } + else { + return 0; + } + TIXMLASSERT( digit < 16 ); + TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); + ucs += digitScaled; + TIXMLASSERT( mult <= UINT_MAX / 16 ); + mult *= 16; + --q; + } } - else - { - return 0; + else { + // Decimal. + const char* q = p+2; + if ( !(*q) ) { + return 0; + } + + q = strchr( q, SEMICOLON ); + + if ( !q ) { + return 0; + } + TIXMLASSERT( *q == SEMICOLON ); + + delta = q-p; + --q; + + while ( *q != '#' ) { + if ( *q >= '0' && *q <= '9' ) { + const unsigned int digit = *q - '0'; + TIXMLASSERT( digit < 10 ); + TIXMLASSERT( digit == 0 || mult <= UINT_MAX / digit ); + const unsigned int digitScaled = mult * digit; + TIXMLASSERT( ucs <= ULONG_MAX - digitScaled ); + ucs += digitScaled; + } + else { + return 0; + } + TIXMLASSERT( mult <= UINT_MAX / 10 ); + mult *= 10; + --q; + } } - TIXMLASSERT(mult <= UINT_MAX / 10); - mult *= 10; - --q; - } + // convert the UCS to UTF-8 + ConvertUTF32ToUTF8( ucs, value, length ); + return p + delta + 1; } - // convert the UCS to UTF-8 - ConvertUTF32ToUTF8(ucs, value, length); - return p + delta + 1; - } - return p + 1; + return p+1; } -void XMLUtil::ToStr(int v, char* buffer, int bufferSize) +void XMLUtil::ToStr( int v, char* buffer, int bufferSize ) { - TIXML_SNPRINTF(buffer, bufferSize, "%d", v); + TIXML_SNPRINTF( buffer, bufferSize, "%d", v ); } -void XMLUtil::ToStr(unsigned v, char* buffer, int bufferSize) +void XMLUtil::ToStr( unsigned v, char* buffer, int bufferSize ) { - TIXML_SNPRINTF(buffer, bufferSize, "%u", v); + TIXML_SNPRINTF( buffer, bufferSize, "%u", v ); } -void XMLUtil::ToStr(bool v, char* buffer, int bufferSize) +void XMLUtil::ToStr( bool v, char* buffer, int bufferSize ) { - TIXML_SNPRINTF(buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); + TIXML_SNPRINTF( buffer, bufferSize, "%s", v ? writeBoolTrue : writeBoolFalse); } /* ToStr() of a number is a very tricky topic. https://github.com/leethomason/tinyxml2/issues/106 */ -void XMLUtil::ToStr(float v, char* buffer, int bufferSize) +void XMLUtil::ToStr( float v, char* buffer, int bufferSize ) { - TIXML_SNPRINTF(buffer, bufferSize, "%.8g", v); + TIXML_SNPRINTF( buffer, bufferSize, "%.8g", v ); } -void XMLUtil::ToStr(double v, char* buffer, int bufferSize) +void XMLUtil::ToStr( double v, char* buffer, int bufferSize ) { - TIXML_SNPRINTF(buffer, bufferSize, "%.17g", v); + TIXML_SNPRINTF( buffer, bufferSize, "%.17g", v ); } void XMLUtil::ToStr(int64_t v, char* buffer, int bufferSize) { - // horrible syntax trick to make the compiler happy about %lld - TIXML_SNPRINTF(buffer, bufferSize, "%lld", (long long)v); + // horrible syntax trick to make the compiler happy about %lld + TIXML_SNPRINTF(buffer, bufferSize, "%lld", (long long)v); } -bool XMLUtil::ToInt(const char* str, int* value) +bool XMLUtil::ToInt( const char* str, int* value ) { - if (TIXML_SSCANF(str, "%d", value) == 1) - { - return true; - } - return false; + if ( TIXML_SSCANF( str, "%d", value ) == 1 ) { + return true; + } + return false; } -bool XMLUtil::ToUnsigned(const char* str, unsigned* value) +bool XMLUtil::ToUnsigned( const char* str, unsigned *value ) { - if (TIXML_SSCANF(str, "%u", value) == 1) - { - return true; - } - return false; + if ( TIXML_SSCANF( str, "%u", value ) == 1 ) { + return true; + } + return false; } -bool XMLUtil::ToBool(const char* str, bool* value) +bool XMLUtil::ToBool( const char* str, bool* value ) { - int ival = 0; - if (ToInt(str, &ival)) - { - *value = (ival == 0) ? false : true; - return true; - } - if (StringEqual(str, "true")) - { - *value = true; - return true; - } - else if (StringEqual(str, "false")) - { - *value = false; - return true; - } - return false; + int ival = 0; + if ( ToInt( str, &ival )) { + *value = (ival==0) ? false : true; + return true; + } + if ( StringEqual( str, "true" ) ) { + *value = true; + return true; + } + else if ( StringEqual( str, "false" ) ) { + *value = false; + return true; + } + return false; } -bool XMLUtil::ToFloat(const char* str, float* value) +bool XMLUtil::ToFloat( const char* str, float* value ) { - if (TIXML_SSCANF(str, "%f", value) == 1) - { - return true; - } - return false; + if ( TIXML_SSCANF( str, "%f", value ) == 1 ) { + return true; + } + return false; } -bool XMLUtil::ToDouble(const char* str, double* value) +bool XMLUtil::ToDouble( const char* str, double* value ) { - if (TIXML_SSCANF(str, "%lf", value) == 1) - { - return true; - } - return false; + if ( TIXML_SSCANF( str, "%lf", value ) == 1 ) { + return true; + } + return false; } bool XMLUtil::ToInt64(const char* str, int64_t* value) { - long long v = 0; // horrible syntax trick to make the compiler happy about %lld - if (TIXML_SSCANF(str, "%lld", &v) == 1) - { - *value = (int64_t)v; - return true; - } - return false; + long long v = 0; // horrible syntax trick to make the compiler happy about %lld + if (TIXML_SSCANF(str, "%lld", &v) == 1) { + *value = (int64_t)v; + return true; + } + return false; } -char* XMLDocument::Identify(char* p, XMLNode** node) +char* XMLDocument::Identify( char* p, XMLNode** node ) { - TIXMLASSERT(node); - TIXMLASSERT(p); - char* const start = p; - int const startLine = _parseCurLineNum; - p = XMLUtil::SkipWhiteSpace(p, &_parseCurLineNum); - if (!*p) - { - *node = 0; - TIXMLASSERT(p); + TIXMLASSERT( node ); + TIXMLASSERT( p ); + char* const start = p; + int const startLine = _parseCurLineNum; + p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); + if( !*p ) { + *node = 0; + TIXMLASSERT( p ); + return p; + } + + // These strings define the matching patterns: + static const char* xmlHeader = { "( _commentPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += xmlHeaderLen; + } + else if ( XMLUtil::StringEqual( p, commentHeader, commentHeaderLen ) ) { + returnNode = CreateUnlinkedNode( _commentPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += commentHeaderLen; + } + else if ( XMLUtil::StringEqual( p, cdataHeader, cdataHeaderLen ) ) { + XMLText* text = CreateUnlinkedNode( _textPool ); + returnNode = text; + returnNode->_parseLineNum = _parseCurLineNum; + p += cdataHeaderLen; + text->SetCData( true ); + } + else if ( XMLUtil::StringEqual( p, dtdHeader, dtdHeaderLen ) ) { + returnNode = CreateUnlinkedNode( _commentPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += dtdHeaderLen; + } + else if ( XMLUtil::StringEqual( p, elementHeader, elementHeaderLen ) ) { + returnNode = CreateUnlinkedNode( _elementPool ); + returnNode->_parseLineNum = _parseCurLineNum; + p += elementHeaderLen; + } + else { + returnNode = CreateUnlinkedNode( _textPool ); + returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character + p = start; // Back it up, all the text counts. + _parseCurLineNum = startLine; + } + + TIXMLASSERT( returnNode ); + TIXMLASSERT( p ); + *node = returnNode; return p; - } - - // These strings define the matching patterns: - static const char* xmlHeader = {"(_commentPool); - returnNode->_parseLineNum = _parseCurLineNum; - p += xmlHeaderLen; - } - else if (XMLUtil::StringEqual(p, commentHeader, commentHeaderLen)) - { - returnNode = CreateUnlinkedNode(_commentPool); - returnNode->_parseLineNum = _parseCurLineNum; - p += commentHeaderLen; - } - else if (XMLUtil::StringEqual(p, cdataHeader, cdataHeaderLen)) - { - XMLText* text = CreateUnlinkedNode(_textPool); - returnNode = text; - returnNode->_parseLineNum = _parseCurLineNum; - p += cdataHeaderLen; - text->SetCData(true); - } - else if (XMLUtil::StringEqual(p, dtdHeader, dtdHeaderLen)) - { - returnNode = CreateUnlinkedNode(_commentPool); - returnNode->_parseLineNum = _parseCurLineNum; - p += dtdHeaderLen; - } - else if (XMLUtil::StringEqual(p, elementHeader, elementHeaderLen)) - { - returnNode = CreateUnlinkedNode(_elementPool); - returnNode->_parseLineNum = _parseCurLineNum; - p += elementHeaderLen; - } - else - { - returnNode = CreateUnlinkedNode(_textPool); - returnNode->_parseLineNum = _parseCurLineNum; // Report line of first non-whitespace character - p = start; // Back it up, all the text counts. - _parseCurLineNum = startLine; - } - - TIXMLASSERT(returnNode); - TIXMLASSERT(p); - *node = returnNode; - return p; -} - - -bool XMLDocument::Accept(XMLVisitor* visitor) const -{ - TIXMLASSERT(visitor); - if (visitor->VisitEnter(*this)) - { - for (const XMLNode* node = FirstChild(); node; node = node->NextSibling()) - { - if (!node->Accept(visitor)) - { - break; - } +} + + +bool XMLDocument::Accept( XMLVisitor* visitor ) const +{ + TIXMLASSERT( visitor ); + if ( visitor->VisitEnter( *this ) ) { + for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) { + break; + } + } } - } - return visitor->VisitExit(*this); + return visitor->VisitExit( *this ); } // --------- XMLNode ----------- // -XMLNode::XMLNode(XMLDocument* doc) - : _document(doc), - _parent(0), - _value(), - _parseLineNum(0), - _firstChild(0), - _lastChild(0), - _prev(0), - _next(0), - _userData(0), - _memPool(0) -{} +XMLNode::XMLNode( XMLDocument* doc ) : + _document( doc ), + _parent( 0 ), + _value(), + _parseLineNum( 0 ), + _firstChild( 0 ), _lastChild( 0 ), + _prev( 0 ), _next( 0 ), + _userData( 0 ), + _memPool( 0 ) +{ +} XMLNode::~XMLNode() { - DeleteChildren(); - if (_parent) - { - _parent->Unlink(this); - } + DeleteChildren(); + if ( _parent ) { + _parent->Unlink( this ); + } } -const char* XMLNode::Value() const +const char* XMLNode::Value() const { - // Edge case: XMLDocuments don't have a Value. Return null. - if (this->ToDocument()) - return 0; - return _value.GetStr(); + // Edge case: XMLDocuments don't have a Value. Return null. + if ( this->ToDocument() ) + return 0; + return _value.GetStr(); } -void XMLNode::SetValue(const char* str, bool staticMem) +void XMLNode::SetValue( const char* str, bool staticMem ) { - if (staticMem) - { - _value.SetInternedStr(str); - } - else - { - _value.SetStr(str); - } + if ( staticMem ) { + _value.SetInternedStr( str ); + } + else { + _value.SetStr( str ); + } } XMLNode* XMLNode::DeepClone(XMLDocument* target) const { - XMLNode* clone = this->ShallowClone(target); - if (!clone) - return 0; + XMLNode* clone = this->ShallowClone(target); + if (!clone) return 0; - for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) - { - XMLNode* childClone = child->DeepClone(target); - TIXMLASSERT(childClone); - clone->InsertEndChild(childClone); - } - return clone; + for (const XMLNode* child = this->FirstChild(); child; child = child->NextSibling()) { + XMLNode* childClone = child->DeepClone(target); + TIXMLASSERT(childClone); + clone->InsertEndChild(childClone); + } + return clone; } void XMLNode::DeleteChildren() { - while (_firstChild) - { - TIXMLASSERT(_lastChild); - DeleteChild(_firstChild); - } - _firstChild = _lastChild = 0; + while( _firstChild ) { + TIXMLASSERT( _lastChild ); + DeleteChild( _firstChild ); + } + _firstChild = _lastChild = 0; } -void XMLNode::Unlink(XMLNode* child) +void XMLNode::Unlink( XMLNode* child ) { - TIXMLASSERT(child); - TIXMLASSERT(child->_document == _document); - TIXMLASSERT(child->_parent == this); - if (child == _firstChild) - { - _firstChild = _firstChild->_next; - } - if (child == _lastChild) - { - _lastChild = _lastChild->_prev; - } + TIXMLASSERT( child ); + TIXMLASSERT( child->_document == _document ); + TIXMLASSERT( child->_parent == this ); + if ( child == _firstChild ) { + _firstChild = _firstChild->_next; + } + if ( child == _lastChild ) { + _lastChild = _lastChild->_prev; + } - if (child->_prev) - { - child->_prev->_next = child->_next; - } - if (child->_next) - { - child->_next->_prev = child->_prev; - } - child->_next = 0; - child->_prev = 0; - child->_parent = 0; + if ( child->_prev ) { + child->_prev->_next = child->_next; + } + if ( child->_next ) { + child->_next->_prev = child->_prev; + } + child->_next = 0; + child->_prev = 0; + child->_parent = 0; } -void XMLNode::DeleteChild(XMLNode* node) +void XMLNode::DeleteChild( XMLNode* node ) { - TIXMLASSERT(node); - TIXMLASSERT(node->_document == _document); - TIXMLASSERT(node->_parent == this); - Unlink(node); - TIXMLASSERT(node->_prev == 0); - TIXMLASSERT(node->_next == 0); - TIXMLASSERT(node->_parent == 0); - DeleteNode(node); + TIXMLASSERT( node ); + TIXMLASSERT( node->_document == _document ); + TIXMLASSERT( node->_parent == this ); + Unlink( node ); + TIXMLASSERT(node->_prev == 0); + TIXMLASSERT(node->_next == 0); + TIXMLASSERT(node->_parent == 0); + DeleteNode( node ); } -XMLNode* XMLNode::InsertEndChild(XMLNode* addThis) +XMLNode* XMLNode::InsertEndChild( XMLNode* addThis ) { - TIXMLASSERT(addThis); - if (addThis->_document != _document) - { - TIXMLASSERT(false); - return 0; - } - InsertChildPreamble(addThis); - - if (_lastChild) - { - TIXMLASSERT(_firstChild); - TIXMLASSERT(_lastChild->_next == 0); - _lastChild->_next = addThis; - addThis->_prev = _lastChild; - _lastChild = addThis; - - addThis->_next = 0; - } - else - { - TIXMLASSERT(_firstChild == 0); - _firstChild = _lastChild = addThis; - - addThis->_prev = 0; - addThis->_next = 0; - } - addThis->_parent = this; - return addThis; -} - - -XMLNode* XMLNode::InsertFirstChild(XMLNode* addThis) -{ - TIXMLASSERT(addThis); - if (addThis->_document != _document) - { - TIXMLASSERT(false); - return 0; - } - InsertChildPreamble(addThis); - - if (_firstChild) - { - TIXMLASSERT(_lastChild); - TIXMLASSERT(_firstChild->_prev == 0); + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + InsertChildPreamble( addThis ); - _firstChild->_prev = addThis; - addThis->_next = _firstChild; - _firstChild = addThis; + if ( _lastChild ) { + TIXMLASSERT( _firstChild ); + TIXMLASSERT( _lastChild->_next == 0 ); + _lastChild->_next = addThis; + addThis->_prev = _lastChild; + _lastChild = addThis; - addThis->_prev = 0; - } - else - { - TIXMLASSERT(_lastChild == 0); - _firstChild = _lastChild = addThis; + addThis->_next = 0; + } + else { + TIXMLASSERT( _firstChild == 0 ); + _firstChild = _lastChild = addThis; - addThis->_prev = 0; - addThis->_next = 0; - } - addThis->_parent = this; - return addThis; + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; } -XMLNode* XMLNode::InsertAfterChild(XMLNode* afterThis, XMLNode* addThis) +XMLNode* XMLNode::InsertFirstChild( XMLNode* addThis ) { - TIXMLASSERT(addThis); - if (addThis->_document != _document) - { - TIXMLASSERT(false); - return 0; - } + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + InsertChildPreamble( addThis ); - TIXMLASSERT(afterThis); + if ( _firstChild ) { + TIXMLASSERT( _lastChild ); + TIXMLASSERT( _firstChild->_prev == 0 ); - if (afterThis->_parent != this) - { - TIXMLASSERT(false); - return 0; - } - if (afterThis == addThis) - { - // Current state: BeforeThis -> AddThis -> OneAfterAddThis - // Now AddThis must disappear from it's location and then - // reappear between BeforeThis and OneAfterAddThis. - // So just leave it where it is. - return addThis; - } + _firstChild->_prev = addThis; + addThis->_next = _firstChild; + _firstChild = addThis; - if (afterThis->_next == 0) - { - // The last node or the only node. - return InsertEndChild(addThis); - } - InsertChildPreamble(addThis); - addThis->_prev = afterThis; - addThis->_next = afterThis->_next; - afterThis->_next->_prev = addThis; - afterThis->_next = addThis; - addThis->_parent = this; - return addThis; + addThis->_prev = 0; + } + else { + TIXMLASSERT( _lastChild == 0 ); + _firstChild = _lastChild = addThis; + + addThis->_prev = 0; + addThis->_next = 0; + } + addThis->_parent = this; + return addThis; } -const XMLElement* XMLNode::FirstChildElement(const char* name) const +XMLNode* XMLNode::InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ) { - for (const XMLNode* node = _firstChild; node; node = node->_next) - { - const XMLElement* element = node->ToElementWithName(name); - if (element) - { - return element; + TIXMLASSERT( addThis ); + if ( addThis->_document != _document ) { + TIXMLASSERT( false ); + return 0; + } + + TIXMLASSERT( afterThis ); + + if ( afterThis->_parent != this ) { + TIXMLASSERT( false ); + return 0; + } + if ( afterThis == addThis ) { + // Current state: BeforeThis -> AddThis -> OneAfterAddThis + // Now AddThis must disappear from it's location and then + // reappear between BeforeThis and OneAfterAddThis. + // So just leave it where it is. + return addThis; } - } - return 0; + + if ( afterThis->_next == 0 ) { + // The last node or the only node. + return InsertEndChild( addThis ); + } + InsertChildPreamble( addThis ); + addThis->_prev = afterThis; + addThis->_next = afterThis->_next; + afterThis->_next->_prev = addThis; + afterThis->_next = addThis; + addThis->_parent = this; + return addThis; } -const XMLElement* XMLNode::LastChildElement(const char* name) const + + +const XMLElement* XMLNode::FirstChildElement( const char* name ) const { - for (const XMLNode* node = _lastChild; node; node = node->_prev) - { - const XMLElement* element = node->ToElementWithName(name); - if (element) - { - return element; + for( const XMLNode* node = _firstChild; node; node = node->_next ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } } - } - return 0; + return 0; } -const XMLElement* XMLNode::NextSiblingElement(const char* name) const +const XMLElement* XMLNode::LastChildElement( const char* name ) const { - for (const XMLNode* node = _next; node; node = node->_next) - { - const XMLElement* element = node->ToElementWithName(name); - if (element) - { - return element; + for( const XMLNode* node = _lastChild; node; node = node->_prev ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } } - } - return 0; + return 0; } -const XMLElement* XMLNode::PreviousSiblingElement(const char* name) const +const XMLElement* XMLNode::NextSiblingElement( const char* name ) const { - for (const XMLNode* node = _prev; node; node = node->_prev) - { - const XMLElement* element = node->ToElementWithName(name); - if (element) - { - return element; - } - } - return 0; -} - - -char* XMLNode::ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) -{ - // This is a recursive method, but thinking about it "at the current level" - // it is a pretty simple flat list: - // - // - // - // With a special case: - // - // - // - // - // Where the closing element (/foo) *must* be the next thing after the opening - // element, and the names must match. BUT the tricky bit is that the closing - // element will be read by the child. - // - // 'endTag' is the end tag for this node, it is returned by a call to a child. - // 'parentEnd' is the end tag for the parent, which is filled in and returned. - - while (p && *p) - { - XMLNode* node = 0; - - p = _document->Identify(p, &node); - TIXMLASSERT(p); - if (node == 0) - { - break; + for( const XMLNode* node = _next; node; node = node->_next ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } } + return 0; +} - int initialLineNum = node->_parseLineNum; - StrPair endTag; - p = node->ParseDeep(p, &endTag, curLineNumPtr); - if (!p) - { - DeleteNode(node); - if (!_document->Error()) - { - _document->SetError(XML_ERROR_PARSING, initialLineNum, 0); - } - break; +const XMLElement* XMLNode::PreviousSiblingElement( const char* name ) const +{ + for( const XMLNode* node = _prev; node; node = node->_prev ) { + const XMLElement* element = node->ToElementWithName( name ); + if ( element ) { + return element; + } } + return 0; +} - XMLDeclaration* decl = node->ToDeclaration(); - if (decl) - { - // Declarations are only allowed at document level - bool wellLocated = (ToDocument() != 0); - if (wellLocated) - { - // Multiple declarations are allowed but all declarations - // must occur before anything else - for (const XMLNode* existingNode = _document->FirstChild(); existingNode; - existingNode = existingNode->NextSibling()) - { - if (!existingNode->ToDeclaration()) - { - wellLocated = false; + +char* XMLNode::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) +{ + // This is a recursive method, but thinking about it "at the current level" + // it is a pretty simple flat list: + // + // + // + // With a special case: + // + // + // + // + // Where the closing element (/foo) *must* be the next thing after the opening + // element, and the names must match. BUT the tricky bit is that the closing + // element will be read by the child. + // + // 'endTag' is the end tag for this node, it is returned by a call to a child. + // 'parentEnd' is the end tag for the parent, which is filled in and returned. + + while( p && *p ) { + XMLNode* node = 0; + + p = _document->Identify( p, &node ); + TIXMLASSERT( p ); + if ( node == 0 ) { break; - } } - } - if (!wellLocated) - { - _document->SetError(XML_ERROR_PARSING_DECLARATION, - initialLineNum, - "XMLDeclaration value=%s", - decl->Value()); - DeleteNode(node); - break; - } - } - - XMLElement* ele = node->ToElement(); - if (ele) - { - // We read the end tag. Return it to the parent. - if (ele->ClosingType() == XMLElement::CLOSING) - { - if (parentEndTag) - { - ele->_value.TransferTo(parentEndTag); - } - node->_memPool->SetTracked(); // created and then immediately deleted. - DeleteNode(node); - return p; - } - - // Handle an end tag returned to this level. - // And handle a bunch of annoying errors. - bool mismatch = false; - if (endTag.Empty()) - { - if (ele->ClosingType() == XMLElement::OPEN) - { - mismatch = true; + + int initialLineNum = node->_parseLineNum; + + StrPair endTag; + p = node->ParseDeep( p, &endTag, curLineNumPtr ); + if ( !p ) { + DeleteNode( node ); + if ( !_document->Error() ) { + _document->SetError( XML_ERROR_PARSING, initialLineNum, 0); + } + break; } - } - else - { - if (ele->ClosingType() != XMLElement::OPEN) - { - mismatch = true; + + XMLDeclaration* decl = node->ToDeclaration(); + if ( decl ) { + // Declarations are only allowed at document level + bool wellLocated = ( ToDocument() != 0 ); + if ( wellLocated ) { + // Multiple declarations are allowed but all declarations + // must occur before anything else + for ( const XMLNode* existingNode = _document->FirstChild(); existingNode; existingNode = existingNode->NextSibling() ) { + if ( !existingNode->ToDeclaration() ) { + wellLocated = false; + break; + } + } + } + if ( !wellLocated ) { + _document->SetError( XML_ERROR_PARSING_DECLARATION, initialLineNum, "XMLDeclaration value=%s", decl->Value()); + DeleteNode( node ); + break; + } } - else if (!XMLUtil::StringEqual(endTag.GetStr(), ele->Name())) - { - mismatch = true; + + XMLElement* ele = node->ToElement(); + if ( ele ) { + // We read the end tag. Return it to the parent. + if ( ele->ClosingType() == XMLElement::CLOSING ) { + if ( parentEndTag ) { + ele->_value.TransferTo( parentEndTag ); + } + node->_memPool->SetTracked(); // created and then immediately deleted. + DeleteNode( node ); + return p; + } + + // Handle an end tag returned to this level. + // And handle a bunch of annoying errors. + bool mismatch = false; + if ( endTag.Empty() ) { + if ( ele->ClosingType() == XMLElement::OPEN ) { + mismatch = true; + } + } + else { + if ( ele->ClosingType() != XMLElement::OPEN ) { + mismatch = true; + } + else if ( !XMLUtil::StringEqual( endTag.GetStr(), ele->Name() ) ) { + mismatch = true; + } + } + if ( mismatch ) { + _document->SetError( XML_ERROR_MISMATCHED_ELEMENT, initialLineNum, "XMLElement name=%s", ele->Name()); + DeleteNode( node ); + break; + } } - } - if (mismatch) - { - _document->SetError(XML_ERROR_MISMATCHED_ELEMENT, - initialLineNum, - "XMLElement name=%s", - ele->Name()); - DeleteNode(node); - break; - } - } - InsertEndChild(node); - } - return 0; -} - -/*static*/ void XMLNode::DeleteNode(XMLNode* node) -{ - if (node == 0) - { - return; - } - TIXMLASSERT(node->_document); - if (!node->ToDocument()) - { - node->_document->MarkInUse(node); - } - - MemPool* pool = node->_memPool; - node->~XMLNode(); - pool->Free(node); -} - -void XMLNode::InsertChildPreamble(XMLNode* insertThis) const -{ - TIXMLASSERT(insertThis); - TIXMLASSERT(insertThis->_document == _document); - - if (insertThis->_parent) - { - insertThis->_parent->Unlink(insertThis); - } - else - { - insertThis->_document->MarkInUse(insertThis); - insertThis->_memPool->SetTracked(); - } -} - -const XMLElement* XMLNode::ToElementWithName(const char* name) const -{ - const XMLElement* element = this->ToElement(); - if (element == 0) - { + InsertEndChild( node ); + } return 0; - } - if (name == 0) - { - return element; - } - if (XMLUtil::StringEqual(element->Name(), name)) - { - return element; - } - return 0; } -// --------- XMLText ---------- // -char* XMLText::ParseDeep(char* p, StrPair*, int* curLineNumPtr) +/*static*/ void XMLNode::DeleteNode( XMLNode* node ) { - if (this->CData()) - { - p = _value.ParseText(p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr); - if (!p) - { - _document->SetError(XML_ERROR_PARSING_CDATA, _parseLineNum, 0); + if ( node == 0 ) { + return; } - return p; - } - else - { - int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT - : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; - if (_document->WhitespaceMode() == COLLAPSE_WHITESPACE) - { - flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; + TIXMLASSERT(node->_document); + if (!node->ToDocument()) { + node->_document->MarkInUse(node); + } + + MemPool* pool = node->_memPool; + node->~XMLNode(); + pool->Free( node ); +} + +void XMLNode::InsertChildPreamble( XMLNode* insertThis ) const +{ + TIXMLASSERT( insertThis ); + TIXMLASSERT( insertThis->_document == _document ); + + if (insertThis->_parent) { + insertThis->_parent->Unlink( insertThis ); + } + else { + insertThis->_document->MarkInUse(insertThis); + insertThis->_memPool->SetTracked(); + } +} + +const XMLElement* XMLNode::ToElementWithName( const char* name ) const +{ + const XMLElement* element = this->ToElement(); + if ( element == 0 ) { + return 0; } + if ( name == 0 ) { + return element; + } + if ( XMLUtil::StringEqual( element->Name(), name ) ) { + return element; + } + return 0; +} - p = _value.ParseText(p, "<", flags, curLineNumPtr); - if (p && *p) - { - return p - 1; +// --------- XMLText ---------- // +char* XMLText::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) +{ + if ( this->CData() ) { + p = _value.ParseText( p, "]]>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_CDATA, _parseLineNum, 0 ); + } + return p; } - if (!p) - { - _document->SetError(XML_ERROR_PARSING_TEXT, _parseLineNum, 0); + else { + int flags = _document->ProcessEntities() ? StrPair::TEXT_ELEMENT : StrPair::TEXT_ELEMENT_LEAVE_ENTITIES; + if ( _document->WhitespaceMode() == COLLAPSE_WHITESPACE ) { + flags |= StrPair::NEEDS_WHITESPACE_COLLAPSING; + } + + p = _value.ParseText( p, "<", flags, curLineNumPtr ); + if ( p && *p ) { + return p-1; + } + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_TEXT, _parseLineNum, 0 ); + } } - } - return 0; + return 0; } -XMLNode* XMLText::ShallowClone(XMLDocument* doc) const +XMLNode* XMLText::ShallowClone( XMLDocument* doc ) const { - if (!doc) - { - doc = _document; - } - XMLText* text = doc->NewText(Value()); // fixme: this will always allocate memory. Intern? - text->SetCData(this->CData()); - return text; + if ( !doc ) { + doc = _document; + } + XMLText* text = doc->NewText( Value() ); // fixme: this will always allocate memory. Intern? + text->SetCData( this->CData() ); + return text; } -bool XMLText::ShallowEqual(const XMLNode* compare) const +bool XMLText::ShallowEqual( const XMLNode* compare ) const { - TIXMLASSERT(compare); - const XMLText* text = compare->ToText(); - return (text && XMLUtil::StringEqual(text->Value(), Value())); + TIXMLASSERT( compare ); + const XMLText* text = compare->ToText(); + return ( text && XMLUtil::StringEqual( text->Value(), Value() ) ); } -bool XMLText::Accept(XMLVisitor* visitor) const +bool XMLText::Accept( XMLVisitor* visitor ) const { - TIXMLASSERT(visitor); - return visitor->Visit(*this); + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); } // --------- XMLComment ---------- // -XMLComment::XMLComment(XMLDocument* doc) : XMLNode(doc) {} +XMLComment::XMLComment( XMLDocument* doc ) : XMLNode( doc ) +{ +} -XMLComment::~XMLComment() {} +XMLComment::~XMLComment() +{ +} -char* XMLComment::ParseDeep(char* p, StrPair*, int* curLineNumPtr) +char* XMLComment::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) { - // Comment parses as text. - p = _value.ParseText(p, "-->", StrPair::COMMENT, curLineNumPtr); - if (p == 0) - { - _document->SetError(XML_ERROR_PARSING_COMMENT, _parseLineNum, 0); - } - return p; + // Comment parses as text. + p = _value.ParseText( p, "-->", StrPair::COMMENT, curLineNumPtr ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_COMMENT, _parseLineNum, 0 ); + } + return p; } -XMLNode* XMLComment::ShallowClone(XMLDocument* doc) const +XMLNode* XMLComment::ShallowClone( XMLDocument* doc ) const { - if (!doc) - { - doc = _document; - } - XMLComment* comment = doc->NewComment(Value()); // fixme: this will always allocate memory. Intern? - return comment; + if ( !doc ) { + doc = _document; + } + XMLComment* comment = doc->NewComment( Value() ); // fixme: this will always allocate memory. Intern? + return comment; } -bool XMLComment::ShallowEqual(const XMLNode* compare) const +bool XMLComment::ShallowEqual( const XMLNode* compare ) const { - TIXMLASSERT(compare); - const XMLComment* comment = compare->ToComment(); - return (comment && XMLUtil::StringEqual(comment->Value(), Value())); + TIXMLASSERT( compare ); + const XMLComment* comment = compare->ToComment(); + return ( comment && XMLUtil::StringEqual( comment->Value(), Value() )); } -bool XMLComment::Accept(XMLVisitor* visitor) const +bool XMLComment::Accept( XMLVisitor* visitor ) const { - TIXMLASSERT(visitor); - return visitor->Visit(*this); + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); } // --------- XMLDeclaration ---------- // -XMLDeclaration::XMLDeclaration(XMLDocument* doc) : XMLNode(doc) {} +XMLDeclaration::XMLDeclaration( XMLDocument* doc ) : XMLNode( doc ) +{ +} XMLDeclaration::~XMLDeclaration() { - //printf( "~XMLDeclaration\n" ); + //printf( "~XMLDeclaration\n" ); } -char* XMLDeclaration::ParseDeep(char* p, StrPair*, int* curLineNumPtr) +char* XMLDeclaration::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) { - // Declaration parses as text. - p = _value.ParseText(p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr); - if (p == 0) - { - _document->SetError(XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0); - } - return p; + // Declaration parses as text. + p = _value.ParseText( p, "?>", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); + if ( p == 0 ) { + _document->SetError( XML_ERROR_PARSING_DECLARATION, _parseLineNum, 0 ); + } + return p; } -XMLNode* XMLDeclaration::ShallowClone(XMLDocument* doc) const +XMLNode* XMLDeclaration::ShallowClone( XMLDocument* doc ) const { - if (!doc) - { - doc = _document; - } - XMLDeclaration* dec = doc->NewDeclaration(Value()); // fixme: this will always allocate memory. Intern? - return dec; + if ( !doc ) { + doc = _document; + } + XMLDeclaration* dec = doc->NewDeclaration( Value() ); // fixme: this will always allocate memory. Intern? + return dec; } -bool XMLDeclaration::ShallowEqual(const XMLNode* compare) const +bool XMLDeclaration::ShallowEqual( const XMLNode* compare ) const { - TIXMLASSERT(compare); - const XMLDeclaration* declaration = compare->ToDeclaration(); - return (declaration && XMLUtil::StringEqual(declaration->Value(), Value())); + TIXMLASSERT( compare ); + const XMLDeclaration* declaration = compare->ToDeclaration(); + return ( declaration && XMLUtil::StringEqual( declaration->Value(), Value() )); } -bool XMLDeclaration::Accept(XMLVisitor* visitor) const + +bool XMLDeclaration::Accept( XMLVisitor* visitor ) const { - TIXMLASSERT(visitor); - return visitor->Visit(*this); + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); } // --------- XMLUnknown ---------- // -XMLUnknown::XMLUnknown(XMLDocument* doc) : XMLNode(doc) {} +XMLUnknown::XMLUnknown( XMLDocument* doc ) : XMLNode( doc ) +{ +} -XMLUnknown::~XMLUnknown() {} +XMLUnknown::~XMLUnknown() +{ +} -char* XMLUnknown::ParseDeep(char* p, StrPair*, int* curLineNumPtr) +char* XMLUnknown::ParseDeep( char* p, StrPair*, int* curLineNumPtr ) { - // Unknown parses as text. - p = _value.ParseText(p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr); - if (!p) - { - _document->SetError(XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0); - } - return p; + // Unknown parses as text. + p = _value.ParseText( p, ">", StrPair::NEEDS_NEWLINE_NORMALIZATION, curLineNumPtr ); + if ( !p ) { + _document->SetError( XML_ERROR_PARSING_UNKNOWN, _parseLineNum, 0 ); + } + return p; } -XMLNode* XMLUnknown::ShallowClone(XMLDocument* doc) const +XMLNode* XMLUnknown::ShallowClone( XMLDocument* doc ) const { - if (!doc) - { - doc = _document; - } - XMLUnknown* text = doc->NewUnknown(Value()); // fixme: this will always allocate memory. Intern? - return text; + if ( !doc ) { + doc = _document; + } + XMLUnknown* text = doc->NewUnknown( Value() ); // fixme: this will always allocate memory. Intern? + return text; } -bool XMLUnknown::ShallowEqual(const XMLNode* compare) const +bool XMLUnknown::ShallowEqual( const XMLNode* compare ) const { - TIXMLASSERT(compare); - const XMLUnknown* unknown = compare->ToUnknown(); - return (unknown && XMLUtil::StringEqual(unknown->Value(), Value())); + TIXMLASSERT( compare ); + const XMLUnknown* unknown = compare->ToUnknown(); + return ( unknown && XMLUtil::StringEqual( unknown->Value(), Value() )); } -bool XMLUnknown::Accept(XMLVisitor* visitor) const +bool XMLUnknown::Accept( XMLVisitor* visitor ) const { - TIXMLASSERT(visitor); - return visitor->Visit(*this); + TIXMLASSERT( visitor ); + return visitor->Visit( *this ); } // --------- XMLAttribute ---------- // -const char* XMLAttribute::Name() const { return _name.GetStr(); } +const char* XMLAttribute::Name() const +{ + return _name.GetStr(); +} -const char* XMLAttribute::Value() const { return _value.GetStr(); } +const char* XMLAttribute::Value() const +{ + return _value.GetStr(); +} -char* XMLAttribute::ParseDeep(char* p, bool processEntities, int* curLineNumPtr) +char* XMLAttribute::ParseDeep( char* p, bool processEntities, int* curLineNumPtr ) { - // Parse using the name rules: bug fix, was using ParseText before - p = _name.ParseName(p); - if (!p || !*p) - { - return 0; - } + // Parse using the name rules: bug fix, was using ParseText before + p = _name.ParseName( p ); + if ( !p || !*p ) { + return 0; + } - // Skip white space before = - p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); - if (*p != '=') - { - return 0; - } + // Skip white space before = + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + if ( *p != '=' ) { + return 0; + } - ++p; // move up to opening quote - p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); - if (*p != '\"' && *p != '\'') - { - return 0; - } + ++p; // move up to opening quote + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + if ( *p != '\"' && *p != '\'' ) { + return 0; + } - char endTag[2] = {*p, 0}; - ++p; // move past opening quote + char endTag[2] = { *p, 0 }; + ++p; // move past opening quote - p = _value.ParseText(p, - endTag, - processEntities ? StrPair::ATTRIBUTE_VALUE - : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, - curLineNumPtr); - return p; + p = _value.ParseText( p, endTag, processEntities ? StrPair::ATTRIBUTE_VALUE : StrPair::ATTRIBUTE_VALUE_LEAVE_ENTITIES, curLineNumPtr ); + return p; } -void XMLAttribute::SetName(const char* n) { _name.SetStr(n); } +void XMLAttribute::SetName( const char* n ) +{ + _name.SetStr( n ); +} -XMLError XMLAttribute::QueryIntValue(int* value) const +XMLError XMLAttribute::QueryIntValue( int* value ) const { - if (XMLUtil::ToInt(Value(), value)) - { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if ( XMLUtil::ToInt( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -XMLError XMLAttribute::QueryUnsignedValue(unsigned int* value) const +XMLError XMLAttribute::QueryUnsignedValue( unsigned int* value ) const { - if (XMLUtil::ToUnsigned(Value(), value)) - { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if ( XMLUtil::ToUnsigned( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } XMLError XMLAttribute::QueryInt64Value(int64_t* value) const { - if (XMLUtil::ToInt64(Value(), value)) - { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if (XMLUtil::ToInt64(Value(), value)) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -XMLError XMLAttribute::QueryBoolValue(bool* value) const +XMLError XMLAttribute::QueryBoolValue( bool* value ) const { - if (XMLUtil::ToBool(Value(), value)) - { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if ( XMLUtil::ToBool( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -XMLError XMLAttribute::QueryFloatValue(float* value) const +XMLError XMLAttribute::QueryFloatValue( float* value ) const { - if (XMLUtil::ToFloat(Value(), value)) - { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if ( XMLUtil::ToFloat( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -XMLError XMLAttribute::QueryDoubleValue(double* value) const +XMLError XMLAttribute::QueryDoubleValue( double* value ) const { - if (XMLUtil::ToDouble(Value(), value)) - { - return XML_SUCCESS; - } - return XML_WRONG_ATTRIBUTE_TYPE; + if ( XMLUtil::ToDouble( Value(), value )) { + return XML_SUCCESS; + } + return XML_WRONG_ATTRIBUTE_TYPE; } -void XMLAttribute::SetAttribute(const char* v) { _value.SetStr(v); } +void XMLAttribute::SetAttribute( const char* v ) +{ + _value.SetStr( v ); +} -void XMLAttribute::SetAttribute(int v) +void XMLAttribute::SetAttribute( int v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); } -void XMLAttribute::SetAttribute(unsigned v) +void XMLAttribute::SetAttribute( unsigned v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); } void XMLAttribute::SetAttribute(int64_t v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + _value.SetStr(buf); } -void XMLAttribute::SetAttribute(bool v) + +void XMLAttribute::SetAttribute( bool v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); } -void XMLAttribute::SetAttribute(double v) +void XMLAttribute::SetAttribute( double v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); } -void XMLAttribute::SetAttribute(float v) +void XMLAttribute::SetAttribute( float v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - _value.SetStr(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + _value.SetStr( buf ); } // --------- XMLElement ---------- // -XMLElement::XMLElement(XMLDocument* doc) : XMLNode(doc), _closingType(OPEN), _rootAttribute(0) {} +XMLElement::XMLElement( XMLDocument* doc ) : XMLNode( doc ), + _closingType( OPEN ), + _rootAttribute( 0 ) +{ +} XMLElement::~XMLElement() { - while (_rootAttribute) - { - XMLAttribute* next = _rootAttribute->_next; - DeleteAttribute(_rootAttribute); - _rootAttribute = next; - } + while( _rootAttribute ) { + XMLAttribute* next = _rootAttribute->_next; + DeleteAttribute( _rootAttribute ); + _rootAttribute = next; + } } -const XMLAttribute* XMLElement::FindAttribute(const char* name) const +const XMLAttribute* XMLElement::FindAttribute( const char* name ) const { - for (XMLAttribute* a = _rootAttribute; a; a = a->_next) - { - if (XMLUtil::StringEqual(a->Name(), name)) - { - return a; + for( XMLAttribute* a = _rootAttribute; a; a = a->_next ) { + if ( XMLUtil::StringEqual( a->Name(), name ) ) { + return a; + } } - } - return 0; + return 0; } -const char* XMLElement::Attribute(const char* name, const char* value) const +const char* XMLElement::Attribute( const char* name, const char* value ) const { - const XMLAttribute* a = FindAttribute(name); - if (!a) - { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return 0; + } + if ( !value || XMLUtil::StringEqual( a->Value(), value )) { + return a->Value(); + } return 0; - } - if (!value || XMLUtil::StringEqual(a->Value(), value)) - { - return a->Value(); - } - return 0; } -int XMLElement::IntAttribute(const char* name, int defaultValue) const +int XMLElement::IntAttribute(const char* name, int defaultValue) const { - int i = defaultValue; - QueryIntAttribute(name, &i); - return i; + int i = defaultValue; + QueryIntAttribute(name, &i); + return i; } -unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const +unsigned XMLElement::UnsignedAttribute(const char* name, unsigned defaultValue) const { - unsigned i = defaultValue; - QueryUnsignedAttribute(name, &i); - return i; + unsigned i = defaultValue; + QueryUnsignedAttribute(name, &i); + return i; } -int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const +int64_t XMLElement::Int64Attribute(const char* name, int64_t defaultValue) const { - int64_t i = defaultValue; - QueryInt64Attribute(name, &i); - return i; + int64_t i = defaultValue; + QueryInt64Attribute(name, &i); + return i; } -bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const +bool XMLElement::BoolAttribute(const char* name, bool defaultValue) const { - bool b = defaultValue; - QueryBoolAttribute(name, &b); - return b; + bool b = defaultValue; + QueryBoolAttribute(name, &b); + return b; } -double XMLElement::DoubleAttribute(const char* name, double defaultValue) const +double XMLElement::DoubleAttribute(const char* name, double defaultValue) const { - double d = defaultValue; - QueryDoubleAttribute(name, &d); - return d; + double d = defaultValue; + QueryDoubleAttribute(name, &d); + return d; } -float XMLElement::FloatAttribute(const char* name, float defaultValue) const +float XMLElement::FloatAttribute(const char* name, float defaultValue) const { - float f = defaultValue; - QueryFloatAttribute(name, &f); - return f; + float f = defaultValue; + QueryFloatAttribute(name, &f); + return f; } const char* XMLElement::GetText() const { - if (FirstChild() && FirstChild()->ToText()) - { - return FirstChild()->Value(); - } - return 0; + if ( FirstChild() && FirstChild()->ToText() ) { + return FirstChild()->Value(); + } + return 0; } -void XMLElement::SetText(const char* inText) +void XMLElement::SetText( const char* inText ) { - if (FirstChild() && FirstChild()->ToText()) - FirstChild()->SetValue(inText); - else - { - XMLText* theText = GetDocument()->NewText(inText); - InsertFirstChild(theText); - } + if ( FirstChild() && FirstChild()->ToText() ) + FirstChild()->SetValue( inText ); + else { + XMLText* theText = GetDocument()->NewText( inText ); + InsertFirstChild( theText ); + } } -void XMLElement::SetText(int v) +void XMLElement::SetText( int v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); } -void XMLElement::SetText(unsigned v) +void XMLElement::SetText( unsigned v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); } void XMLElement::SetText(int64_t v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + SetText(buf); } -void XMLElement::SetText(bool v) +void XMLElement::SetText( bool v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); } -void XMLElement::SetText(float v) +void XMLElement::SetText( float v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); } -void XMLElement::SetText(double v) +void XMLElement::SetText( double v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - SetText(buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + SetText( buf ); } -XMLError XMLElement::QueryIntText(int* ival) const +XMLError XMLElement::QueryIntText( int* ival ) const { - if (FirstChild() && FirstChild()->ToText()) - { - const char* t = FirstChild()->Value(); - if (XMLUtil::ToInt(t, ival)) - { - return XML_SUCCESS; + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToInt( t, ival ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; + return XML_NO_TEXT_NODE; } -XMLError XMLElement::QueryUnsignedText(unsigned* uval) const +XMLError XMLElement::QueryUnsignedText( unsigned* uval ) const { - if (FirstChild() && FirstChild()->ToText()) - { - const char* t = FirstChild()->Value(); - if (XMLUtil::ToUnsigned(t, uval)) - { - return XML_SUCCESS; + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToUnsigned( t, uval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; + return XML_NO_TEXT_NODE; } XMLError XMLElement::QueryInt64Text(int64_t* ival) const { - if (FirstChild() && FirstChild()->ToText()) - { - const char* t = FirstChild()->Value(); - if (XMLUtil::ToInt64(t, ival)) - { - return XML_SUCCESS; - } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; + if (FirstChild() && FirstChild()->ToText()) { + const char* t = FirstChild()->Value(); + if (XMLUtil::ToInt64(t, ival)) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; + } + return XML_NO_TEXT_NODE; } -XMLError XMLElement::QueryBoolText(bool* bval) const +XMLError XMLElement::QueryBoolText( bool* bval ) const { - if (FirstChild() && FirstChild()->ToText()) - { - const char* t = FirstChild()->Value(); - if (XMLUtil::ToBool(t, bval)) - { - return XML_SUCCESS; + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToBool( t, bval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; + return XML_NO_TEXT_NODE; } -XMLError XMLElement::QueryDoubleText(double* dval) const +XMLError XMLElement::QueryDoubleText( double* dval ) const { - if (FirstChild() && FirstChild()->ToText()) - { - const char* t = FirstChild()->Value(); - if (XMLUtil::ToDouble(t, dval)) - { - return XML_SUCCESS; + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToDouble( t, dval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; + return XML_NO_TEXT_NODE; } -XMLError XMLElement::QueryFloatText(float* fval) const +XMLError XMLElement::QueryFloatText( float* fval ) const { - if (FirstChild() && FirstChild()->ToText()) - { - const char* t = FirstChild()->Value(); - if (XMLUtil::ToFloat(t, fval)) - { - return XML_SUCCESS; + if ( FirstChild() && FirstChild()->ToText() ) { + const char* t = FirstChild()->Value(); + if ( XMLUtil::ToFloat( t, fval ) ) { + return XML_SUCCESS; + } + return XML_CAN_NOT_CONVERT_TEXT; } - return XML_CAN_NOT_CONVERT_TEXT; - } - return XML_NO_TEXT_NODE; + return XML_NO_TEXT_NODE; } int XMLElement::IntText(int defaultValue) const { - int i = defaultValue; - QueryIntText(&i); - return i; + int i = defaultValue; + QueryIntText(&i); + return i; } unsigned XMLElement::UnsignedText(unsigned defaultValue) const { - unsigned i = defaultValue; - QueryUnsignedText(&i); - return i; + unsigned i = defaultValue; + QueryUnsignedText(&i); + return i; } int64_t XMLElement::Int64Text(int64_t defaultValue) const { - int64_t i = defaultValue; - QueryInt64Text(&i); - return i; + int64_t i = defaultValue; + QueryInt64Text(&i); + return i; } bool XMLElement::BoolText(bool defaultValue) const { - bool b = defaultValue; - QueryBoolText(&b); - return b; + bool b = defaultValue; + QueryBoolText(&b); + return b; } double XMLElement::DoubleText(double defaultValue) const { - double d = defaultValue; - QueryDoubleText(&d); - return d; + double d = defaultValue; + QueryDoubleText(&d); + return d; } float XMLElement::FloatText(float defaultValue) const { - float f = defaultValue; - QueryFloatText(&f); - return f; + float f = defaultValue; + QueryFloatText(&f); + return f; } -XMLAttribute* XMLElement::FindOrCreateAttribute(const char* name) +XMLAttribute* XMLElement::FindOrCreateAttribute( const char* name ) { - XMLAttribute* last = 0; - XMLAttribute* attrib = 0; - for (attrib = _rootAttribute; attrib; last = attrib, attrib = attrib->_next) - { - if (XMLUtil::StringEqual(attrib->Name(), name)) - { - break; - } - } - if (!attrib) - { - attrib = CreateAttribute(); - TIXMLASSERT(attrib); - if (last) - { - TIXMLASSERT(last->_next == 0); - last->_next = attrib; + XMLAttribute* last = 0; + XMLAttribute* attrib = 0; + for( attrib = _rootAttribute; + attrib; + last = attrib, attrib = attrib->_next ) { + if ( XMLUtil::StringEqual( attrib->Name(), name ) ) { + break; + } } - else - { - TIXMLASSERT(_rootAttribute == 0); - _rootAttribute = attrib; + if ( !attrib ) { + attrib = CreateAttribute(); + TIXMLASSERT( attrib ); + if ( last ) { + TIXMLASSERT( last->_next == 0 ); + last->_next = attrib; + } + else { + TIXMLASSERT( _rootAttribute == 0 ); + _rootAttribute = attrib; + } + attrib->SetName( name ); } - attrib->SetName(name); - } - return attrib; + return attrib; } -void XMLElement::DeleteAttribute(const char* name) +void XMLElement::DeleteAttribute( const char* name ) { - XMLAttribute* prev = 0; - for (XMLAttribute* a = _rootAttribute; a; a = a->_next) - { - if (XMLUtil::StringEqual(name, a->Name())) - { - if (prev) - { - prev->_next = a->_next; - } - else - { - _rootAttribute = a->_next; - } - DeleteAttribute(a); - break; + XMLAttribute* prev = 0; + for( XMLAttribute* a=_rootAttribute; a; a=a->_next ) { + if ( XMLUtil::StringEqual( name, a->Name() ) ) { + if ( prev ) { + prev->_next = a->_next; + } + else { + _rootAttribute = a->_next; + } + DeleteAttribute( a ); + break; + } + prev = a; } - prev = a; - } } -char* XMLElement::ParseAttributes(char* p, int* curLineNumPtr) +char* XMLElement::ParseAttributes( char* p, int* curLineNumPtr ) { - XMLAttribute* prevAttribute = 0; + XMLAttribute* prevAttribute = 0; - // Read the attributes. - while (p) - { - p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); - if (!(*p)) - { - _document->SetError(XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name()); - return 0; - } + // Read the attributes. + while( p ) { + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); + if ( !(*p) ) { + _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, "XMLElement name=%s", Name() ); + return 0; + } - // attribute. - if (XMLUtil::IsNameStartChar(*p)) - { - XMLAttribute* attrib = CreateAttribute(); - TIXMLASSERT(attrib); - attrib->_parseLineNum = _document->_parseCurLineNum; + // attribute. + if (XMLUtil::IsNameStartChar( *p ) ) { + XMLAttribute* attrib = CreateAttribute(); + TIXMLASSERT( attrib ); + attrib->_parseLineNum = _document->_parseCurLineNum; - int attrLineNum = attrib->_parseLineNum; + int attrLineNum = attrib->_parseLineNum; - p = attrib->ParseDeep(p, _document->ProcessEntities(), curLineNumPtr); - if (!p || Attribute(attrib->Name())) - { - DeleteAttribute(attrib); - _document->SetError(XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name()); - return 0; - } - // There is a minor bug here: if the attribute in the source xml - // document is duplicated, it will not be detected and the - // attribute will be doubly added. However, tracking the 'prevAttribute' - // avoids re-scanning the attribute list. Preferring performance for - // now, may reconsider in the future. - if (prevAttribute) - { - TIXMLASSERT(prevAttribute->_next == 0); - prevAttribute->_next = attrib; - } - else - { - TIXMLASSERT(_rootAttribute == 0); - _rootAttribute = attrib; - } - prevAttribute = attrib; - } - // end of the tag - else if (*p == '>') - { - ++p; - break; - } - // end of the tag - else if (*p == '/' && *(p + 1) == '>') - { - _closingType = CLOSED; - return p + 2; // done; sealed element. - } - else - { - _document->SetError(XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0); - return 0; + p = attrib->ParseDeep( p, _document->ProcessEntities(), curLineNumPtr ); + if ( !p || Attribute( attrib->Name() ) ) { + DeleteAttribute( attrib ); + _document->SetError( XML_ERROR_PARSING_ATTRIBUTE, attrLineNum, "XMLElement name=%s", Name() ); + return 0; + } + // There is a minor bug here: if the attribute in the source xml + // document is duplicated, it will not be detected and the + // attribute will be doubly added. However, tracking the 'prevAttribute' + // avoids re-scanning the attribute list. Preferring performance for + // now, may reconsider in the future. + if ( prevAttribute ) { + TIXMLASSERT( prevAttribute->_next == 0 ); + prevAttribute->_next = attrib; + } + else { + TIXMLASSERT( _rootAttribute == 0 ); + _rootAttribute = attrib; + } + prevAttribute = attrib; + } + // end of the tag + else if ( *p == '>' ) { + ++p; + break; + } + // end of the tag + else if ( *p == '/' && *(p+1) == '>' ) { + _closingType = CLOSED; + return p+2; // done; sealed element. + } + else { + _document->SetError( XML_ERROR_PARSING_ELEMENT, _parseLineNum, 0 ); + return 0; + } } - } - return p; + return p; } -void XMLElement::DeleteAttribute(XMLAttribute* attribute) +void XMLElement::DeleteAttribute( XMLAttribute* attribute ) { - if (attribute == 0) - { - return; - } - MemPool* pool = attribute->_memPool; - attribute->~XMLAttribute(); - pool->Free(attribute); + if ( attribute == 0 ) { + return; + } + MemPool* pool = attribute->_memPool; + attribute->~XMLAttribute(); + pool->Free( attribute ); } XMLAttribute* XMLElement::CreateAttribute() { - TIXMLASSERT(sizeof(XMLAttribute) == _document->_attributePool.ItemSize()); - XMLAttribute* attrib = new (_document->_attributePool.Alloc()) XMLAttribute(); - TIXMLASSERT(attrib); - attrib->_memPool = &_document->_attributePool; - attrib->_memPool->SetTracked(); - return attrib; + TIXMLASSERT( sizeof( XMLAttribute ) == _document->_attributePool.ItemSize() ); + XMLAttribute* attrib = new (_document->_attributePool.Alloc() ) XMLAttribute(); + TIXMLASSERT( attrib ); + attrib->_memPool = &_document->_attributePool; + attrib->_memPool->SetTracked(); + return attrib; } // // // foobar // -char* XMLElement::ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr) +char* XMLElement::ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ) { - // Read the element name. - p = XMLUtil::SkipWhiteSpace(p, curLineNumPtr); + // Read the element name. + p = XMLUtil::SkipWhiteSpace( p, curLineNumPtr ); - // The closing element is the form. It is - // parsed just like a regular element then deleted from - // the DOM. - if (*p == '/') - { - _closingType = CLOSING; - ++p; - } + // The closing element is the form. It is + // parsed just like a regular element then deleted from + // the DOM. + if ( *p == '/' ) { + _closingType = CLOSING; + ++p; + } - p = _value.ParseName(p); - if (_value.Empty()) - { - return 0; - } + p = _value.ParseName( p ); + if ( _value.Empty() ) { + return 0; + } - p = ParseAttributes(p, curLineNumPtr); - if (!p || !*p || _closingType != OPEN) - { - return p; - } + p = ParseAttributes( p, curLineNumPtr ); + if ( !p || !*p || _closingType != OPEN ) { + return p; + } - p = XMLNode::ParseDeep(p, parentEndTag, curLineNumPtr); - return p; + p = XMLNode::ParseDeep( p, parentEndTag, curLineNumPtr ); + return p; } -XMLNode* XMLElement::ShallowClone(XMLDocument* doc) const + +XMLNode* XMLElement::ShallowClone( XMLDocument* doc ) const { - if (!doc) - { - doc = _document; - } - XMLElement* element = doc->NewElement(Value()); // fixme: this will always allocate memory. Intern? - for (const XMLAttribute* a = FirstAttribute(); a; a = a->Next()) - { - element->SetAttribute(a->Name(), a->Value()); // fixme: this will always allocate memory. Intern? - } - return element; + if ( !doc ) { + doc = _document; + } + XMLElement* element = doc->NewElement( Value() ); // fixme: this will always allocate memory. Intern? + for( const XMLAttribute* a=FirstAttribute(); a; a=a->Next() ) { + element->SetAttribute( a->Name(), a->Value() ); // fixme: this will always allocate memory. Intern? + } + return element; } -bool XMLElement::ShallowEqual(const XMLNode* compare) const +bool XMLElement::ShallowEqual( const XMLNode* compare ) const { - TIXMLASSERT(compare); - const XMLElement* other = compare->ToElement(); - if (other && XMLUtil::StringEqual(other->Name(), Name())) - { - const XMLAttribute* a = FirstAttribute(); - const XMLAttribute* b = other->FirstAttribute(); + TIXMLASSERT( compare ); + const XMLElement* other = compare->ToElement(); + if ( other && XMLUtil::StringEqual( other->Name(), Name() )) { - while (a && b) - { - if (!XMLUtil::StringEqual(a->Value(), b->Value())) - { - return false; - } - a = a->Next(); - b = b->Next(); - } - if (a || b) - { - // different count - return false; + const XMLAttribute* a=FirstAttribute(); + const XMLAttribute* b=other->FirstAttribute(); + + while ( a && b ) { + if ( !XMLUtil::StringEqual( a->Value(), b->Value() ) ) { + return false; + } + a = a->Next(); + b = b->Next(); + } + if ( a || b ) { + // different count + return false; + } + return true; } - return true; - } - return false; + return false; } -bool XMLElement::Accept(XMLVisitor* visitor) const +bool XMLElement::Accept( XMLVisitor* visitor ) const { - TIXMLASSERT(visitor); - if (visitor->VisitEnter(*this, _rootAttribute)) - { - for (const XMLNode* node = FirstChild(); node; node = node->NextSibling()) - { - if (!node->Accept(visitor)) - { - break; - } + TIXMLASSERT( visitor ); + if ( visitor->VisitEnter( *this, _rootAttribute ) ) { + for ( const XMLNode* node=FirstChild(); node; node=node->NextSibling() ) { + if ( !node->Accept( visitor ) ) { + break; + } + } } - } - return visitor->VisitExit(*this); + return visitor->VisitExit( *this ); } // --------- XMLDocument ----------- // // Warning: List must match 'enum XMLError' -const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = {"XML_SUCCESS", - "XML_NO_ATTRIBUTE", - "XML_WRONG_ATTRIBUTE_TYPE", - "XML_ERROR_FILE_NOT_FOUND", - "XML_ERROR_FILE_COULD_NOT_BE_OPENED", - "XML_ERROR_FILE_READ_ERROR", - "UNUSED_XML_ERROR_ELEMENT_MISMATCH", - "XML_ERROR_PARSING_ELEMENT", - "XML_ERROR_PARSING_ATTRIBUTE", - "UNUSED_XML_ERROR_IDENTIFYING_TAG", - "XML_ERROR_PARSING_TEXT", - "XML_ERROR_PARSING_CDATA", - "XML_ERROR_PARSING_COMMENT", - "XML_ERROR_PARSING_DECLARATION", - "XML_ERROR_PARSING_UNKNOWN", - "XML_ERROR_EMPTY_DOCUMENT", - "XML_ERROR_MISMATCHED_ELEMENT", - "XML_ERROR_PARSING", - "XML_CAN_NOT_CONVERT_TEXT", - "XML_NO_TEXT_NODE"}; - - -XMLDocument::XMLDocument(bool processEntities, Whitespace whitespaceMode) - : XMLNode(0), - _writeBOM(false), - _processEntities(processEntities), - _errorID(XML_SUCCESS), - _whitespaceMode(whitespaceMode), - _errorStr(), - _errorLineNum(0), - _charBuffer(0), - _parseCurLineNum(0), - _unlinked(), - _elementPool(), - _attributePool(), - _textPool(), - _commentPool() -{ - // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) - _document = this; -} - - -XMLDocument::~XMLDocument() { Clear(); } +const char* XMLDocument::_errorNames[XML_ERROR_COUNT] = { + "XML_SUCCESS", + "XML_NO_ATTRIBUTE", + "XML_WRONG_ATTRIBUTE_TYPE", + "XML_ERROR_FILE_NOT_FOUND", + "XML_ERROR_FILE_COULD_NOT_BE_OPENED", + "XML_ERROR_FILE_READ_ERROR", + "UNUSED_XML_ERROR_ELEMENT_MISMATCH", + "XML_ERROR_PARSING_ELEMENT", + "XML_ERROR_PARSING_ATTRIBUTE", + "UNUSED_XML_ERROR_IDENTIFYING_TAG", + "XML_ERROR_PARSING_TEXT", + "XML_ERROR_PARSING_CDATA", + "XML_ERROR_PARSING_COMMENT", + "XML_ERROR_PARSING_DECLARATION", + "XML_ERROR_PARSING_UNKNOWN", + "XML_ERROR_EMPTY_DOCUMENT", + "XML_ERROR_MISMATCHED_ELEMENT", + "XML_ERROR_PARSING", + "XML_CAN_NOT_CONVERT_TEXT", + "XML_NO_TEXT_NODE" +}; + + +XMLDocument::XMLDocument( bool processEntities, Whitespace whitespaceMode ) : + XMLNode( 0 ), + _writeBOM( false ), + _processEntities( processEntities ), + _errorID(XML_SUCCESS), + _whitespaceMode( whitespaceMode ), + _errorStr(), + _errorLineNum( 0 ), + _charBuffer( 0 ), + _parseCurLineNum( 0 ), + _unlinked(), + _elementPool(), + _attributePool(), + _textPool(), + _commentPool() +{ + // avoid VC++ C4355 warning about 'this' in initializer list (C4355 is off by default in VS2012+) + _document = this; +} + + +XMLDocument::~XMLDocument() +{ + Clear(); +} void XMLDocument::MarkInUse(XMLNode* node) { - TIXMLASSERT(node); - TIXMLASSERT(node->_parent == 0); + TIXMLASSERT(node); + TIXMLASSERT(node->_parent == 0); - for (int i = 0; i < _unlinked.Size(); ++i) - { - if (node == _unlinked[i]) - { - _unlinked.SwapRemove(i); - break; - } - } + for (int i = 0; i < _unlinked.Size(); ++i) { + if (node == _unlinked[i]) { + _unlinked.SwapRemove(i); + break; + } + } } void XMLDocument::Clear() { - DeleteChildren(); - while (_unlinked.Size()) - { - DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. - } + DeleteChildren(); + while( _unlinked.Size()) { + DeleteNode(_unlinked[0]); // Will remove from _unlinked as part of delete. + } #ifdef TINYXML2_DEBUG - const bool hadError = Error(); + const bool hadError = Error(); #endif - ClearError(); + ClearError(); - delete[] _charBuffer; - _charBuffer = 0; + delete [] _charBuffer; + _charBuffer = 0; #if 0 _textPool.Trace( "text" ); @@ -2219,123 +2051,115 @@ void XMLDocument::Clear() _commentPool.Trace( "comment" ); _attributePool.Trace( "attribute" ); #endif - + #ifdef TINYXML2_DEBUG - if (!hadError) - { - TIXMLASSERT(_elementPool.CurrentAllocs() == _elementPool.Untracked()); - TIXMLASSERT(_attributePool.CurrentAllocs() == _attributePool.Untracked()); - TIXMLASSERT(_textPool.CurrentAllocs() == _textPool.Untracked()); - TIXMLASSERT(_commentPool.CurrentAllocs() == _commentPool.Untracked()); - } + if ( !hadError ) { + TIXMLASSERT( _elementPool.CurrentAllocs() == _elementPool.Untracked() ); + TIXMLASSERT( _attributePool.CurrentAllocs() == _attributePool.Untracked() ); + TIXMLASSERT( _textPool.CurrentAllocs() == _textPool.Untracked() ); + TIXMLASSERT( _commentPool.CurrentAllocs() == _commentPool.Untracked() ); + } #endif } void XMLDocument::DeepCopy(XMLDocument* target) const { - TIXMLASSERT(target); - if (target == this) - { - return; // technically success - a no-op. - } + TIXMLASSERT(target); + if (target == this) { + return; // technically success - a no-op. + } - target->Clear(); - for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) - { - target->InsertEndChild(node->DeepClone(target)); - } + target->Clear(); + for (const XMLNode* node = this->FirstChild(); node; node = node->NextSibling()) { + target->InsertEndChild(node->DeepClone(target)); + } } -XMLElement* XMLDocument::NewElement(const char* name) +XMLElement* XMLDocument::NewElement( const char* name ) { - XMLElement* ele = CreateUnlinkedNode(_elementPool); - ele->SetName(name); - return ele; + XMLElement* ele = CreateUnlinkedNode( _elementPool ); + ele->SetName( name ); + return ele; } -XMLComment* XMLDocument::NewComment(const char* str) +XMLComment* XMLDocument::NewComment( const char* str ) { - XMLComment* comment = CreateUnlinkedNode(_commentPool); - comment->SetValue(str); - return comment; + XMLComment* comment = CreateUnlinkedNode( _commentPool ); + comment->SetValue( str ); + return comment; } -XMLText* XMLDocument::NewText(const char* str) +XMLText* XMLDocument::NewText( const char* str ) { - XMLText* text = CreateUnlinkedNode(_textPool); - text->SetValue(str); - return text; + XMLText* text = CreateUnlinkedNode( _textPool ); + text->SetValue( str ); + return text; } -XMLDeclaration* XMLDocument::NewDeclaration(const char* str) +XMLDeclaration* XMLDocument::NewDeclaration( const char* str ) { - XMLDeclaration* dec = CreateUnlinkedNode(_commentPool); - dec->SetValue(str ? str : "xml version=\"1.0\" encoding=\"UTF-8\""); - return dec; + XMLDeclaration* dec = CreateUnlinkedNode( _commentPool ); + dec->SetValue( str ? str : "xml version=\"1.0\" encoding=\"UTF-8\"" ); + return dec; } -XMLUnknown* XMLDocument::NewUnknown(const char* str) +XMLUnknown* XMLDocument::NewUnknown( const char* str ) { - XMLUnknown* unk = CreateUnlinkedNode(_commentPool); - unk->SetValue(str); - return unk; + XMLUnknown* unk = CreateUnlinkedNode( _commentPool ); + unk->SetValue( str ); + return unk; } -static FILE* callfopen(const char* filepath, const char* mode) +static FILE* callfopen( const char* filepath, const char* mode ) { - TIXMLASSERT(filepath); - TIXMLASSERT(mode); -#if defined(_MSC_VER) && (_MSC_VER >= 1400) && (!defined WINCE) - FILE* fp = 0; - errno_t err = fopen_s(&fp, filepath, mode); - if (err) - { - return 0; - } + TIXMLASSERT( filepath ); + TIXMLASSERT( mode ); +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE) + FILE* fp = 0; + errno_t err = fopen_s( &fp, filepath, mode ); + if ( err ) { + return 0; + } #else - FILE* fp = fopen(filepath, mode); + FILE* fp = fopen( filepath, mode ); #endif - return fp; -} - -void XMLDocument::DeleteNode(XMLNode* node) -{ - TIXMLASSERT(node); - TIXMLASSERT(node->_document == this); - if (node->_parent) - { - node->_parent->DeleteChild(node); - } - else - { - // Isn't in the tree. - // Use the parent delete. - // Also, we need to mark it tracked: we 'know' - // it was never used. - node->_memPool->SetTracked(); - // Call the static XMLNode version: - XMLNode::DeleteNode(node); - } + return fp; +} + +void XMLDocument::DeleteNode( XMLNode* node ) { + TIXMLASSERT( node ); + TIXMLASSERT(node->_document == this ); + if (node->_parent) { + node->_parent->DeleteChild( node ); + } + else { + // Isn't in the tree. + // Use the parent delete. + // Also, we need to mark it tracked: we 'know' + // it was never used. + node->_memPool->SetTracked(); + // Call the static XMLNode version: + XMLNode::DeleteNode(node); + } } -XMLError XMLDocument::LoadFile(const char* filename) +XMLError XMLDocument::LoadFile( const char* filename ) { - Clear(); - FILE* fp = callfopen(filename, "rb"); - if (!fp) - { - SetError(XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename ? filename : ""); + Clear(); + FILE* fp = callfopen( filename, "rb" ); + if ( !fp ) { + SetError( XML_ERROR_FILE_NOT_FOUND, 0, "filename=%s", filename ? filename : ""); + return _errorID; + } + LoadFile( fp ); + fclose( fp ); return _errorID; - } - LoadFile(fp); - fclose(fp); - return _errorID; } // This is likely overengineered template art to have a check that unsigned long value incremented @@ -2344,667 +2168,627 @@ XMLError XMLDocument::LoadFile(const char* filename) // -Wtype-limits warning. This piece makes the compiler select code with a check when a check // is useful and code with no check when a check is redundant depending on how size_t and unsigned long // types sizes relate to each other. -template= sizeof(size_t))> -struct LongFitsIntoSizeTMinusOne -{ - static bool Fits(unsigned long value) { return value < (size_t)-1; } +template += sizeof(size_t))> +struct LongFitsIntoSizeTMinusOne { + static bool Fits( unsigned long value ) + { + return value < (size_t)-1; + } }; -template<> -struct LongFitsIntoSizeTMinusOne -{ - static bool Fits(unsigned long) { return true; } +template <> +struct LongFitsIntoSizeTMinusOne { + static bool Fits( unsigned long ) + { + return true; + } }; -XMLError XMLDocument::LoadFile(FILE* fp) +XMLError XMLDocument::LoadFile( FILE* fp ) { - Clear(); + Clear(); - fseek(fp, 0, SEEK_SET); - if (fgetc(fp) == EOF && ferror(fp) != 0) - { - SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); - return _errorID; - } - - fseek(fp, 0, SEEK_END); - const long filelength = ftell(fp); - fseek(fp, 0, SEEK_SET); - if (filelength == -1L) - { - SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); - return _errorID; - } - TIXMLASSERT(filelength >= 0); + fseek( fp, 0, SEEK_SET ); + if ( fgetc( fp ) == EOF && ferror( fp ) != 0 ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } - if (!LongFitsIntoSizeTMinusOne<>::Fits(filelength)) - { - // Cannot handle files which won't fit in buffer together with null terminator - SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); - return _errorID; - } + fseek( fp, 0, SEEK_END ); + const long filelength = ftell( fp ); + fseek( fp, 0, SEEK_SET ); + if ( filelength == -1L ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + TIXMLASSERT( filelength >= 0 ); - if (filelength == 0) - { - SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0); - return _errorID; - } - - const size_t size = filelength; - TIXMLASSERT(_charBuffer == 0); - _charBuffer = new char[size + 1]; - size_t read = fread(_charBuffer, 1, size, fp); - if (read != size) - { - SetError(XML_ERROR_FILE_READ_ERROR, 0, 0); - return _errorID; - } + if ( !LongFitsIntoSizeTMinusOne<>::Fits( filelength ) ) { + // Cannot handle files which won't fit in buffer together with null terminator + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } + + if ( filelength == 0 ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + + const size_t size = filelength; + TIXMLASSERT( _charBuffer == 0 ); + _charBuffer = new char[size+1]; + size_t read = fread( _charBuffer, 1, size, fp ); + if ( read != size ) { + SetError( XML_ERROR_FILE_READ_ERROR, 0, 0 ); + return _errorID; + } - _charBuffer[size] = 0; + _charBuffer[size] = 0; - Parse(); - return _errorID; + Parse(); + return _errorID; } -XMLError XMLDocument::SaveFile(const char* filename, bool compact) +XMLError XMLDocument::SaveFile( const char* filename, bool compact ) { - FILE* fp = callfopen(filename, "w"); - if (!fp) - { - SetError(XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename ? filename : ""); + FILE* fp = callfopen( filename, "w" ); + if ( !fp ) { + SetError( XML_ERROR_FILE_COULD_NOT_BE_OPENED, 0, "filename=%s", filename ? filename : ""); + return _errorID; + } + SaveFile(fp, compact); + fclose( fp ); return _errorID; - } - SaveFile(fp, compact); - fclose(fp); - return _errorID; } -XMLError XMLDocument::SaveFile(FILE* fp, bool compact) +XMLError XMLDocument::SaveFile( FILE* fp, bool compact ) { - // Clear any error from the last save, otherwise it will get reported - // for *this* call. - ClearError(); - XMLPrinter stream(fp, compact); - Print(&stream); - return _errorID; + // Clear any error from the last save, otherwise it will get reported + // for *this* call. + ClearError(); + XMLPrinter stream( fp, compact ); + Print( &stream ); + return _errorID; } -XMLError XMLDocument::Parse(const char* p, size_t len) +XMLError XMLDocument::Parse( const char* p, size_t len ) { - Clear(); + Clear(); - if (len == 0 || !p || !*p) - { - SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0); + if ( len == 0 || !p || !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return _errorID; + } + if ( len == (size_t)(-1) ) { + len = strlen( p ); + } + TIXMLASSERT( _charBuffer == 0 ); + _charBuffer = new char[ len+1 ]; + memcpy( _charBuffer, p, len ); + _charBuffer[len] = 0; + + Parse(); + if ( Error() ) { + // clean up now essentially dangling memory. + // and the parse fail can put objects in the + // pools that are dead and inaccessible. + DeleteChildren(); + _elementPool.Clear(); + _attributePool.Clear(); + _textPool.Clear(); + _commentPool.Clear(); + } return _errorID; - } - if (len == (size_t)(-1)) - { - len = strlen(p); - } - TIXMLASSERT(_charBuffer == 0); - _charBuffer = new char[len + 1]; - memcpy(_charBuffer, p, len); - _charBuffer[len] = 0; - - Parse(); - if (Error()) - { - // clean up now essentially dangling memory. - // and the parse fail can put objects in the - // pools that are dead and inaccessible. - DeleteChildren(); - _elementPool.Clear(); - _attributePool.Clear(); - _textPool.Clear(); - _commentPool.Clear(); - } - return _errorID; } -void XMLDocument::Print(XMLPrinter* streamer) const +void XMLDocument::Print( XMLPrinter* streamer ) const { - if (streamer) - { - Accept(streamer); - } - else - { - XMLPrinter stdoutStreamer(stdout); - Accept(&stdoutStreamer); - } + if ( streamer ) { + Accept( streamer ); + } + else { + XMLPrinter stdoutStreamer( stdout ); + Accept( &stdoutStreamer ); + } } -void XMLDocument::SetError(XMLError error, int lineNum, const char* format, ...) +void XMLDocument::SetError( XMLError error, int lineNum, const char* format, ... ) { - TIXMLASSERT(error >= 0 && error < XML_ERROR_COUNT); - _errorID = error; - _errorLineNum = lineNum; - _errorStr.Reset(); + TIXMLASSERT( error >= 0 && error < XML_ERROR_COUNT ); + _errorID = error; + _errorLineNum = lineNum; + _errorStr.Reset(); - size_t BUFFER_SIZE = 1000; - char* buffer = new char[BUFFER_SIZE]; + size_t BUFFER_SIZE = 1000; + char* buffer = new char[BUFFER_SIZE]; - TIXML_SNPRINTF(buffer, - BUFFER_SIZE, - "Error=%s ErrorID=%d (0x%x) Line number=%d", - ErrorIDToName(error), - int(error), - int(error), - lineNum); + TIXML_SNPRINTF(buffer, BUFFER_SIZE, "Error=%s ErrorID=%d (0x%x) Line number=%d", ErrorIDToName(error), int(error), int(error), lineNum); - if (format) - { - size_t len = strlen(buffer); - TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); - len = strlen(buffer); + if (format) { + size_t len = strlen(buffer); + TIXML_SNPRINTF(buffer + len, BUFFER_SIZE - len, ": "); + len = strlen(buffer); - va_list va; - va_start(va, format); - TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); - va_end(va); - } - _errorStr.SetStr(buffer); - delete[] buffer; + va_list va; + va_start(va, format); + TIXML_VSNPRINTF(buffer + len, BUFFER_SIZE - len, format, va); + va_end(va); + } + _errorStr.SetStr(buffer); + delete[] buffer; } /*static*/ const char* XMLDocument::ErrorIDToName(XMLError errorID) { - TIXMLASSERT(errorID >= 0 && errorID < XML_ERROR_COUNT); - const char* errorName = _errorNames[errorID]; - TIXMLASSERT(errorName && errorName[0]); - return errorName; + TIXMLASSERT( errorID >= 0 && errorID < XML_ERROR_COUNT ); + const char* errorName = _errorNames[errorID]; + TIXMLASSERT( errorName && errorName[0] ); + return errorName; } -const char* XMLDocument::ErrorStr() const { return _errorStr.Empty() ? "" : _errorStr.GetStr(); } +const char* XMLDocument::ErrorStr() const +{ + return _errorStr.Empty() ? "" : _errorStr.GetStr(); +} -void XMLDocument::PrintError() const { printf("%s\n", ErrorStr()); } +void XMLDocument::PrintError() const +{ + printf("%s\n", ErrorStr()); +} -const char* XMLDocument::ErrorName() const { return ErrorIDToName(_errorID); } +const char* XMLDocument::ErrorName() const +{ + return ErrorIDToName(_errorID); +} void XMLDocument::Parse() { - TIXMLASSERT(NoChildren()); // Clear() must have been called previously - TIXMLASSERT(_charBuffer); - _parseCurLineNum = 1; - _parseLineNum = 1; - char* p = _charBuffer; - p = XMLUtil::SkipWhiteSpace(p, &_parseCurLineNum); - p = const_cast(XMLUtil::ReadBOM(p, &_writeBOM)); - if (!*p) - { - SetError(XML_ERROR_EMPTY_DOCUMENT, 0, 0); - return; - } - ParseDeep(p, 0, &_parseCurLineNum); -} - -XMLPrinter::XMLPrinter(FILE* file, bool compact, int depth) - : _elementJustOpened(false), - _stack(), - _firstElement(true), - _fp(file), - _depth(depth), - _textDepth(-1), - _processEntities(true), - _compactMode(compact), - _buffer() -{ - for (int i = 0; i < ENTITY_RANGE; ++i) - { - _entityFlag[i] = false; - _restrictedEntityFlag[i] = false; - } - for (int i = 0; i < NUM_ENTITIES; ++i) - { - const char entityValue = entities[i].value; - const unsigned char flagIndex = (unsigned char)entityValue; - TIXMLASSERT(flagIndex < ENTITY_RANGE); - _entityFlag[flagIndex] = true; - } - _restrictedEntityFlag[(unsigned char)'&'] = true; - _restrictedEntityFlag[(unsigned char)'<'] = true; - _restrictedEntityFlag[(unsigned char)'>'] = true; // not required, but consistency is nice - _buffer.Push(0); -} - - -void XMLPrinter::Print(const char* format, ...) -{ - va_list va; - va_start(va, format); - - if (_fp) - { - vfprintf(_fp, format, va); - } - else - { - const int len = TIXML_VSCPRINTF(format, va); - // Close out and re-start the va-args - va_end(va); - TIXMLASSERT(len >= 0); - va_start(va, format); - TIXMLASSERT(_buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0); - char* p = _buffer.PushArr(len) - 1; // back up over the null terminator. - TIXML_VSNPRINTF(p, len + 1, format, va); - } - va_end(va); -} - - -void XMLPrinter::Write(const char* data, size_t size) -{ - if (_fp) - { - fwrite(data, sizeof(char), size, _fp); - } - else - { - char* p = _buffer.PushArr(static_cast(size)) - 1; // back up over the null terminator. - memcpy(p, data, size); - p[size] = 0; - } -} - - -void XMLPrinter::Putc(char ch) -{ - if (_fp) - { - fputc(ch, _fp); - } - else - { - char* p = _buffer.PushArr(sizeof(char)) - 1; // back up over the null terminator. - p[0] = ch; - p[1] = 0; - } -} - - -void XMLPrinter::PrintSpace(int depth) -{ - for (int i = 0; i < depth; ++i) - { - Write(" "); - } -} - - -void XMLPrinter::PrintString(const char* p, bool restricted) -{ - // Look for runs of bytes between entities to print. - const char* q = p; - - if (_processEntities) - { - const bool* flag = restricted ? _restrictedEntityFlag : _entityFlag; - while (*q) - { - TIXMLASSERT(p <= q); - // Remember, char is sometimes signed. (How many times has that bitten me?) - if (*q > 0 && *q < ENTITY_RANGE) - { - // Check for entities. If one is found, flush - // the stream up until the entity, write the - // entity, and keep looking. - if (flag[(unsigned char)(*q)]) - { - while (p < q) - { - const size_t delta = q - p; - const int toPrint = (INT_MAX < delta) ? INT_MAX : (int)delta; - Write(p, toPrint); - p += toPrint; - } - bool entityPatternPrinted = false; - for (int i = 0; i < NUM_ENTITIES; ++i) - { - if (entities[i].value == *q) - { - Putc('&'); - Write(entities[i].pattern, entities[i].length); - Putc(';'); - entityPatternPrinted = true; - break; + TIXMLASSERT( NoChildren() ); // Clear() must have been called previously + TIXMLASSERT( _charBuffer ); + _parseCurLineNum = 1; + _parseLineNum = 1; + char* p = _charBuffer; + p = XMLUtil::SkipWhiteSpace( p, &_parseCurLineNum ); + p = const_cast( XMLUtil::ReadBOM( p, &_writeBOM ) ); + if ( !*p ) { + SetError( XML_ERROR_EMPTY_DOCUMENT, 0, 0 ); + return; + } + ParseDeep(p, 0, &_parseCurLineNum ); +} + +XMLPrinter::XMLPrinter( FILE* file, bool compact, int depth ) : + _elementJustOpened( false ), + _stack(), + _firstElement( true ), + _fp( file ), + _depth( depth ), + _textDepth( -1 ), + _processEntities( true ), + _compactMode( compact ), + _buffer() +{ + for( int i=0; i'] = true; // not required, but consistency is nice + _buffer.Push( 0 ); +} + + +void XMLPrinter::Print( const char* format, ... ) +{ + va_list va; + va_start( va, format ); + + if ( _fp ) { + vfprintf( _fp, format, va ); + } + else { + const int len = TIXML_VSCPRINTF( format, va ); + // Close out and re-start the va-args + va_end( va ); + TIXMLASSERT( len >= 0 ); + va_start( va, format ); + TIXMLASSERT( _buffer.Size() > 0 && _buffer[_buffer.Size() - 1] == 0 ); + char* p = _buffer.PushArr( len ) - 1; // back up over the null terminator. + TIXML_VSNPRINTF( p, len+1, format, va ); + } + va_end( va ); +} + + +void XMLPrinter::Write( const char* data, size_t size ) +{ + if ( _fp ) { + fwrite ( data , sizeof(char), size, _fp); + } + else { + char* p = _buffer.PushArr( static_cast(size) ) - 1; // back up over the null terminator. + memcpy( p, data, size ); + p[size] = 0; + } +} + + +void XMLPrinter::Putc( char ch ) +{ + if ( _fp ) { + fputc ( ch, _fp); + } + else { + char* p = _buffer.PushArr( sizeof(char) ) - 1; // back up over the null terminator. + p[0] = ch; + p[1] = 0; + } +} + + +void XMLPrinter::PrintSpace( int depth ) +{ + for( int i=0; i 0 && *q < ENTITY_RANGE ) { + // Check for entities. If one is found, flush + // the stream up until the entity, write the + // entity, and keep looking. + if ( flag[(unsigned char)(*q)] ) { + while ( p < q ) { + const size_t delta = q - p; + const int toPrint = ( INT_MAX < delta ) ? INT_MAX : (int)delta; + Write( p, toPrint ); + p += toPrint; + } + bool entityPatternPrinted = false; + for( int i=0; i(bom)); - } - if (writeDec) - { - PushDeclaration("xml version=\"1.0\""); - } + if ( writeBOM ) { + static const unsigned char bom[] = { TIXML_UTF_LEAD_0, TIXML_UTF_LEAD_1, TIXML_UTF_LEAD_2, 0 }; + Write( reinterpret_cast< const char* >( bom ) ); + } + if ( writeDec ) { + PushDeclaration( "xml version=\"1.0\"" ); + } } -void XMLPrinter::OpenElement(const char* name, bool compactMode) +void XMLPrinter::OpenElement( const char* name, bool compactMode ) { - SealElementIfJustOpened(); - _stack.Push(name); + SealElementIfJustOpened(); + _stack.Push( name ); - if (_textDepth < 0 && !_firstElement && !compactMode) - { - Putc('\n'); - } - if (!compactMode) - { - PrintSpace(_depth); - } + if ( _textDepth < 0 && !_firstElement && !compactMode ) { + Putc( '\n' ); + } + if ( !compactMode ) { + PrintSpace( _depth ); + } - Write("<"); - Write(name); + Write ( "<" ); + Write ( name ); - _elementJustOpened = true; - _firstElement = false; - ++_depth; + _elementJustOpened = true; + _firstElement = false; + ++_depth; } -void XMLPrinter::PushAttribute(const char* name, const char* value) +void XMLPrinter::PushAttribute( const char* name, const char* value ) { - TIXMLASSERT(_elementJustOpened); - Putc(' '); - Write(name); - Write("=\""); - PrintString(value, false); - Putc('\"'); + TIXMLASSERT( _elementJustOpened ); + Putc ( ' ' ); + Write( name ); + Write( "=\"" ); + PrintString( value, false ); + Putc ( '\"' ); } -void XMLPrinter::PushAttribute(const char* name, int v) +void XMLPrinter::PushAttribute( const char* name, int v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - PushAttribute(name, buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); } -void XMLPrinter::PushAttribute(const char* name, unsigned v) +void XMLPrinter::PushAttribute( const char* name, unsigned v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - PushAttribute(name, buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); } void XMLPrinter::PushAttribute(const char* name, int64_t v) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - PushAttribute(name, buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr(v, buf, BUF_SIZE); + PushAttribute(name, buf); } -void XMLPrinter::PushAttribute(const char* name, bool v) +void XMLPrinter::PushAttribute( const char* name, bool v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - PushAttribute(name, buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); } -void XMLPrinter::PushAttribute(const char* name, double v) +void XMLPrinter::PushAttribute( const char* name, double v ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(v, buf, BUF_SIZE); - PushAttribute(name, buf); + char buf[BUF_SIZE]; + XMLUtil::ToStr( v, buf, BUF_SIZE ); + PushAttribute( name, buf ); } -void XMLPrinter::CloseElement(bool compactMode) +void XMLPrinter::CloseElement( bool compactMode ) { - --_depth; - const char* name = _stack.Pop(); + --_depth; + const char* name = _stack.Pop(); - if (_elementJustOpened) - { - Write("/>"); - } - else - { - if (_textDepth < 0 && !compactMode) - { - Putc('\n'); - PrintSpace(_depth); + if ( _elementJustOpened ) { + Write( "/>" ); + } + else { + if ( _textDepth < 0 && !compactMode) { + Putc( '\n' ); + PrintSpace( _depth ); + } + Write ( "" ); } - Write(""); - } - if (_textDepth == _depth) - { - _textDepth = -1; - } - if (_depth == 0 && !compactMode) - { - Putc('\n'); - } - _elementJustOpened = false; + if ( _textDepth == _depth ) { + _textDepth = -1; + } + if ( _depth == 0 && !compactMode) { + Putc( '\n' ); + } + _elementJustOpened = false; } void XMLPrinter::SealElementIfJustOpened() { - if (!_elementJustOpened) - { - return; - } - _elementJustOpened = false; - Putc('>'); + if ( !_elementJustOpened ) { + return; + } + _elementJustOpened = false; + Putc( '>' ); } -void XMLPrinter::PushText(const char* text, bool cdata) +void XMLPrinter::PushText( const char* text, bool cdata ) { - _textDepth = _depth - 1; + _textDepth = _depth-1; - SealElementIfJustOpened(); - if (cdata) - { - Write(""); - } - else - { - PrintString(text, true); - } + SealElementIfJustOpened(); + if ( cdata ) { + Write( "" ); + } + else { + PrintString( text, true ); + } } -void XMLPrinter::PushText(int64_t value) +void XMLPrinter::PushText( int64_t value ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(value, buf, BUF_SIZE); - PushText(buf, false); + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); } -void XMLPrinter::PushText(int value) +void XMLPrinter::PushText( int value ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(value, buf, BUF_SIZE); - PushText(buf, false); + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); } -void XMLPrinter::PushText(unsigned value) +void XMLPrinter::PushText( unsigned value ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(value, buf, BUF_SIZE); - PushText(buf, false); + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); } -void XMLPrinter::PushText(bool value) +void XMLPrinter::PushText( bool value ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(value, buf, BUF_SIZE); - PushText(buf, false); + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); } -void XMLPrinter::PushText(float value) +void XMLPrinter::PushText( float value ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(value, buf, BUF_SIZE); - PushText(buf, false); + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); } -void XMLPrinter::PushText(double value) +void XMLPrinter::PushText( double value ) { - char buf[BUF_SIZE]; - XMLUtil::ToStr(value, buf, BUF_SIZE); - PushText(buf, false); + char buf[BUF_SIZE]; + XMLUtil::ToStr( value, buf, BUF_SIZE ); + PushText( buf, false ); } -void XMLPrinter::PushComment(const char* comment) +void XMLPrinter::PushComment( const char* comment ) { - SealElementIfJustOpened(); - if (_textDepth < 0 && !_firstElement && !_compactMode) - { - Putc('\n'); - PrintSpace(_depth); - } - _firstElement = false; + SealElementIfJustOpened(); + if ( _textDepth < 0 && !_firstElement && !_compactMode) { + Putc( '\n' ); + PrintSpace( _depth ); + } + _firstElement = false; - Write(""); + Write( "" ); } -void XMLPrinter::PushDeclaration(const char* value) +void XMLPrinter::PushDeclaration( const char* value ) { - SealElementIfJustOpened(); - if (_textDepth < 0 && !_firstElement && !_compactMode) - { - Putc('\n'); - PrintSpace(_depth); - } - _firstElement = false; + SealElementIfJustOpened(); + if ( _textDepth < 0 && !_firstElement && !_compactMode) { + Putc( '\n' ); + PrintSpace( _depth ); + } + _firstElement = false; - Write(""); + Write( "" ); } -void XMLPrinter::PushUnknown(const char* value) +void XMLPrinter::PushUnknown( const char* value ) { - SealElementIfJustOpened(); - if (_textDepth < 0 && !_firstElement && !_compactMode) - { - Putc('\n'); - PrintSpace(_depth); - } - _firstElement = false; + SealElementIfJustOpened(); + if ( _textDepth < 0 && !_firstElement && !_compactMode) { + Putc( '\n' ); + PrintSpace( _depth ); + } + _firstElement = false; - Write("'); + Write( "' ); } -bool XMLPrinter::VisitEnter(const XMLDocument& doc) +bool XMLPrinter::VisitEnter( const XMLDocument& doc ) { - _processEntities = doc.ProcessEntities(); - if (doc.HasBOM()) - { - PushHeader(true, false); - } - return true; + _processEntities = doc.ProcessEntities(); + if ( doc.HasBOM() ) { + PushHeader( true, false ); + } + return true; } -bool XMLPrinter::VisitEnter(const XMLElement& element, const XMLAttribute* attribute) +bool XMLPrinter::VisitEnter( const XMLElement& element, const XMLAttribute* attribute ) { - const XMLElement* parentElem = 0; - if (element.Parent()) - { - parentElem = element.Parent()->ToElement(); - } - const bool compactMode = parentElem ? CompactMode(*parentElem) : _compactMode; - OpenElement(element.Name(), compactMode); - while (attribute) - { - PushAttribute(attribute->Name(), attribute->Value()); - attribute = attribute->Next(); - } - return true; + const XMLElement* parentElem = 0; + if ( element.Parent() ) { + parentElem = element.Parent()->ToElement(); + } + const bool compactMode = parentElem ? CompactMode( *parentElem ) : _compactMode; + OpenElement( element.Name(), compactMode ); + while ( attribute ) { + PushAttribute( attribute->Name(), attribute->Value() ); + attribute = attribute->Next(); + } + return true; } -bool XMLPrinter::VisitExit(const XMLElement& element) +bool XMLPrinter::VisitExit( const XMLElement& element ) { - CloseElement(CompactMode(element)); - return true; + CloseElement( CompactMode(element) ); + return true; } -bool XMLPrinter::Visit(const XMLText& text) +bool XMLPrinter::Visit( const XMLText& text ) { - PushText(text.Value(), text.CData()); - return true; + PushText( text.Value(), text.CData() ); + return true; } -bool XMLPrinter::Visit(const XMLComment& comment) +bool XMLPrinter::Visit( const XMLComment& comment ) { - PushComment(comment.Value()); - return true; + PushComment( comment.Value() ); + return true; } -bool XMLPrinter::Visit(const XMLDeclaration& declaration) +bool XMLPrinter::Visit( const XMLDeclaration& declaration ) { - PushDeclaration(declaration.Value()); - return true; + PushDeclaration( declaration.Value() ); + return true; } -bool XMLPrinter::Visit(const XMLUnknown& unknown) +bool XMLPrinter::Visit( const XMLUnknown& unknown ) { - PushUnknown(unknown.Value()); - return true; + PushUnknown( unknown.Value() ); + return true; } -} // namespace tinyxml2 +} // namespace tinyxml2 + diff --git a/src/Utilities/tinyxml/tinyxml2.h b/src/Utilities/tinyxml/tinyxml2.h old mode 100644 new mode 100755 index 82b4a41ac..a385fdb2b --- a/src/Utilities/tinyxml/tinyxml2.h +++ b/src/Utilities/tinyxml/tinyxml2.h @@ -25,20 +25,20 @@ distribution. #define TINYXML2_INCLUDED #if defined(ANDROID_NDK) || defined(__BORLANDC__) || defined(__QNXNTO__) -#include -#include -#include -#include -#include -#if defined(__PS3__) -#include -#endif +# include +# include +# include +# include +# include +# if defined(__PS3__) +# include +# endif #else -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include #endif #include @@ -53,54 +53,45 @@ distribution. AStyle.exe --style=1tbs --indent-switches --break-closing-brackets --indent-preprocessor tinyxml2.cpp tinyxml2.h */ -#if defined(_DEBUG) || defined(__DEBUG__) -#ifndef TINYXML2_DEBUG -#define TINYXML2_DEBUG -#endif +#if defined( _DEBUG ) || defined (__DEBUG__) +# ifndef TINYXML2_DEBUG +# define TINYXML2_DEBUG +# endif #endif #ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4251) +# pragma warning(push) +# pragma warning(disable: 4251) #endif #ifdef _WIN32 -#ifdef TINYXML2_EXPORT -#define TINYXML2_LIB __declspec(dllexport) -#elif defined(TINYXML2_IMPORT) -#define TINYXML2_LIB __declspec(dllimport) -#else -#define TINYXML2_LIB -#endif +# ifdef TINYXML2_EXPORT +# define TINYXML2_LIB __declspec(dllexport) +# elif defined(TINYXML2_IMPORT) +# define TINYXML2_LIB __declspec(dllimport) +# else +# define TINYXML2_LIB +# endif #elif __GNUC__ >= 4 -#define TINYXML2_LIB __attribute__((visibility("default"))) +# define TINYXML2_LIB __attribute__((visibility("default"))) #else -#define TINYXML2_LIB +# define TINYXML2_LIB #endif #if defined(TINYXML2_DEBUG) -#if defined(_MSC_VER) -#// "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like -#define TIXMLASSERT(x) \ - if (!((void)0, (x))) \ - { \ - __debugbreak(); \ - } -#elif defined(ANDROID_NDK) -#include -#define TIXMLASSERT(x) \ - if (!(x)) \ - { \ - __android_log_assert("assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__); \ - } -#else -#include -#define TIXMLASSERT assert -#endif +# if defined(_MSC_VER) +# // "(void)0," is for suppressing C4127 warning in "assert(false)", "assert(true)" and the like +# define TIXMLASSERT( x ) if ( !((void)0,(x))) { __debugbreak(); } +# elif defined (ANDROID_NDK) +# include +# define TIXMLASSERT( x ) if ( !(x)) { __android_log_assert( "assert", "grinliz", "ASSERT in '%s' at %d.", __FILE__, __LINE__ ); } +# else +# include +# define TIXMLASSERT assert +# endif #else -#define TIXMLASSERT(x) \ - {} +# define TIXMLASSERT( x ) {} #endif @@ -135,66 +126,64 @@ class XMLPrinter; class StrPair { public: - enum - { - NEEDS_ENTITY_PROCESSING = 0x01, - NEEDS_NEWLINE_NORMALIZATION = 0x02, - NEEDS_WHITESPACE_COLLAPSING = 0x04, - - TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_NAME = 0, - ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, - ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, - COMMENT = NEEDS_NEWLINE_NORMALIZATION - }; - - StrPair() : _flags(0), _start(0), _end(0) {} - ~StrPair(); - - void Set(char* start, char* end, int flags) - { - TIXMLASSERT(start); - TIXMLASSERT(end); - Reset(); - _start = start; - _end = end; - _flags = flags | NEEDS_FLUSH; - } - - const char* GetStr(); - - bool Empty() const { return _start == _end; } - - void SetInternedStr(const char* str) - { - Reset(); - _start = const_cast(str); - } - - void SetStr(const char* str, int flags = 0); - - char* ParseText(char* in, const char* endTag, int strFlags, int* curLineNumPtr); - char* ParseName(char* in); - - void TransferTo(StrPair* other); - void Reset(); + enum { + NEEDS_ENTITY_PROCESSING = 0x01, + NEEDS_NEWLINE_NORMALIZATION = 0x02, + NEEDS_WHITESPACE_COLLAPSING = 0x04, + + TEXT_ELEMENT = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + TEXT_ELEMENT_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_NAME = 0, + ATTRIBUTE_VALUE = NEEDS_ENTITY_PROCESSING | NEEDS_NEWLINE_NORMALIZATION, + ATTRIBUTE_VALUE_LEAVE_ENTITIES = NEEDS_NEWLINE_NORMALIZATION, + COMMENT = NEEDS_NEWLINE_NORMALIZATION + }; + + StrPair() : _flags( 0 ), _start( 0 ), _end( 0 ) {} + ~StrPair(); + + void Set( char* start, char* end, int flags ) { + TIXMLASSERT( start ); + TIXMLASSERT( end ); + Reset(); + _start = start; + _end = end; + _flags = flags | NEEDS_FLUSH; + } + + const char* GetStr(); + + bool Empty() const { + return _start == _end; + } + + void SetInternedStr( const char* str ) { + Reset(); + _start = const_cast(str); + } + + void SetStr( const char* str, int flags=0 ); + + char* ParseText( char* in, const char* endTag, int strFlags, int* curLineNumPtr ); + char* ParseName( char* in ); + + void TransferTo( StrPair* other ); + void Reset(); private: - void CollapseWhitespace(); + void CollapseWhitespace(); - enum - { - NEEDS_FLUSH = 0x100, - NEEDS_DELETE = 0x200 - }; + enum { + NEEDS_FLUSH = 0x100, + NEEDS_DELETE = 0x200 + }; - int _flags; - char* _start; - char* _end; + int _flags; + char* _start; + char* _end; - StrPair(const StrPair& other); // not supported - void operator=(StrPair& other); // not supported, use TransferTo() + StrPair( const StrPair& other ); // not supported + void operator=( StrPair& other ); // not supported, use TransferTo() }; @@ -203,132 +192,124 @@ class StrPair Has a small initial memory pool, so that low or no usage will not cause a call to new/delete */ -template +template class DynArray { public: - DynArray() : _mem(_pool), _allocated(INITIAL_SIZE), _size(0) {} - - ~DynArray() - { - if (_mem != _pool) + DynArray() : + _mem( _pool ), + _allocated( INITIAL_SIZE ), + _size( 0 ) { - delete[] _mem; - } - } - - void Clear() { _size = 0; } - - void Push(T t) - { - TIXMLASSERT(_size < INT_MAX); - EnsureCapacity(_size + 1); - _mem[_size] = t; - ++_size; - } - - T* PushArr(int count) - { - TIXMLASSERT(count >= 0); - TIXMLASSERT(_size <= INT_MAX - count); - EnsureCapacity(_size + count); - T* ret = &_mem[_size]; - _size += count; - return ret; - } - - T Pop() - { - TIXMLASSERT(_size > 0); - --_size; - return _mem[_size]; - } - - void PopArr(int count) - { - TIXMLASSERT(_size >= count); - _size -= count; - } - - bool Empty() const { return _size == 0; } - - T& operator[](int i) - { - TIXMLASSERT(i >= 0 && i < _size); - return _mem[i]; - } - - const T& operator[](int i) const - { - TIXMLASSERT(i >= 0 && i < _size); - return _mem[i]; - } - - const T& PeekTop() const - { - TIXMLASSERT(_size > 0); - return _mem[_size - 1]; - } - - int Size() const - { - TIXMLASSERT(_size >= 0); - return _size; - } - - int Capacity() const - { - TIXMLASSERT(_allocated >= INITIAL_SIZE); - return _allocated; - } - - void SwapRemove(int i) - { - TIXMLASSERT(i >= 0 && i < _size); - TIXMLASSERT(_size > 0); - _mem[i] = _mem[_size - 1]; - --_size; - } - - const T* Mem() const - { - TIXMLASSERT(_mem); - return _mem; - } - - T* Mem() - { - TIXMLASSERT(_mem); - return _mem; - } + } + + ~DynArray() { + if ( _mem != _pool ) { + delete [] _mem; + } + } + + void Clear() { + _size = 0; + } + + void Push( T t ) { + TIXMLASSERT( _size < INT_MAX ); + EnsureCapacity( _size+1 ); + _mem[_size] = t; + ++_size; + } + + T* PushArr( int count ) { + TIXMLASSERT( count >= 0 ); + TIXMLASSERT( _size <= INT_MAX - count ); + EnsureCapacity( _size+count ); + T* ret = &_mem[_size]; + _size += count; + return ret; + } + + T Pop() { + TIXMLASSERT( _size > 0 ); + --_size; + return _mem[_size]; + } + + void PopArr( int count ) { + TIXMLASSERT( _size >= count ); + _size -= count; + } + + bool Empty() const { + return _size == 0; + } + + T& operator[](int i) { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + const T& operator[](int i) const { + TIXMLASSERT( i>= 0 && i < _size ); + return _mem[i]; + } + + const T& PeekTop() const { + TIXMLASSERT( _size > 0 ); + return _mem[ _size - 1]; + } + + int Size() const { + TIXMLASSERT( _size >= 0 ); + return _size; + } + + int Capacity() const { + TIXMLASSERT( _allocated >= INITIAL_SIZE ); + return _allocated; + } + + void SwapRemove(int i) { + TIXMLASSERT(i >= 0 && i < _size); + TIXMLASSERT(_size > 0); + _mem[i] = _mem[_size - 1]; + --_size; + } + + const T* Mem() const { + TIXMLASSERT( _mem ); + return _mem; + } + + T* Mem() { + TIXMLASSERT( _mem ); + return _mem; + } private: - DynArray(const DynArray&); // not supported - void operator=(const DynArray&); // not supported + DynArray( const DynArray& ); // not supported + void operator=( const DynArray& ); // not supported + + void EnsureCapacity( int cap ) { + TIXMLASSERT( cap > 0 ); + if ( cap > _allocated ) { + TIXMLASSERT( cap <= INT_MAX / 2 ); + int newAllocated = cap * 2; + T* newMem = new T[newAllocated]; + TIXMLASSERT( newAllocated >= _size ); + memcpy( newMem, _mem, sizeof(T)*_size ); // warning: not using constructors, only works for PODs + if ( _mem != _pool ) { + delete [] _mem; + } + _mem = newMem; + _allocated = newAllocated; + } + } - void EnsureCapacity(int cap) - { - TIXMLASSERT(cap > 0); - if (cap > _allocated) - { - TIXMLASSERT(cap <= INT_MAX / 2); - int newAllocated = cap * 2; - T* newMem = new T[newAllocated]; - TIXMLASSERT(newAllocated >= _size); - memcpy(newMem, _mem, sizeof(T) * _size); // warning: not using constructors, only works for PODs - if (_mem != _pool) - { - delete[] _mem; - } - _mem = newMem; - _allocated = newAllocated; - } - } - - T* _mem; - T _pool[INITIAL_SIZE]; - int _allocated; // objects allocated - int _size; // number objects in use + T* _mem; + T _pool[INITIAL_SIZE]; + int _allocated; // objects allocated + int _size; // number objects in use }; @@ -339,145 +320,136 @@ class DynArray class MemPool { public: - MemPool() {} - virtual ~MemPool() {} - - virtual int ItemSize() const = 0; - virtual void* Alloc() = 0; - virtual void Free(void*) = 0; - virtual void SetTracked() = 0; - virtual void Clear() = 0; + MemPool() {} + virtual ~MemPool() {} + + virtual int ItemSize() const = 0; + virtual void* Alloc() = 0; + virtual void Free( void* ) = 0; + virtual void SetTracked() = 0; + virtual void Clear() = 0; }; /* Template child class to create pools of the correct type. */ -template +template< int ITEM_SIZE > class MemPoolT : public MemPool { public: - MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) - {} - ~MemPoolT() { Clear(); } - - void Clear() - { - // Delete the blocks. - while (!_blockPtrs.Empty()) - { - Block* lastBlock = _blockPtrs.Pop(); - delete lastBlock; - } - _root = 0; - _currentAllocs = 0; - _nAllocs = 0; - _maxAllocs = 0; - _nUntracked = 0; - } - - virtual int ItemSize() const { return ITEM_SIZE; } - int CurrentAllocs() const { return _currentAllocs; } - - virtual void* Alloc() - { - if (!_root) - { - // Need a new block. - Block* block = new Block(); - _blockPtrs.Push(block); - - Item* blockItems = block->items; - for (int i = 0; i < ITEMS_PER_BLOCK - 1; ++i) - { - blockItems[i].next = &(blockItems[i + 1]); - } - blockItems[ITEMS_PER_BLOCK - 1].next = 0; - _root = blockItems; - } - Item* const result = _root; - TIXMLASSERT(result != 0); - _root = _root->next; - - ++_currentAllocs; - if (_currentAllocs > _maxAllocs) - { - _maxAllocs = _currentAllocs; + MemPoolT() : _blockPtrs(), _root(0), _currentAllocs(0), _nAllocs(0), _maxAllocs(0), _nUntracked(0) {} + ~MemPoolT() { + Clear(); + } + + void Clear() { + // Delete the blocks. + while( !_blockPtrs.Empty()) { + Block* lastBlock = _blockPtrs.Pop(); + delete lastBlock; + } + _root = 0; + _currentAllocs = 0; + _nAllocs = 0; + _maxAllocs = 0; + _nUntracked = 0; } - ++_nAllocs; - ++_nUntracked; - return result; - } - virtual void Free(void* mem) - { - if (!mem) - { - return; + virtual int ItemSize() const { + return ITEM_SIZE; + } + int CurrentAllocs() const { + return _currentAllocs; + } + + virtual void* Alloc() { + if ( !_root ) { + // Need a new block. + Block* block = new Block(); + _blockPtrs.Push( block ); + + Item* blockItems = block->items; + for( int i = 0; i < ITEMS_PER_BLOCK - 1; ++i ) { + blockItems[i].next = &(blockItems[i + 1]); + } + blockItems[ITEMS_PER_BLOCK - 1].next = 0; + _root = blockItems; + } + Item* const result = _root; + TIXMLASSERT( result != 0 ); + _root = _root->next; + + ++_currentAllocs; + if ( _currentAllocs > _maxAllocs ) { + _maxAllocs = _currentAllocs; + } + ++_nAllocs; + ++_nUntracked; + return result; } - --_currentAllocs; - Item* item = static_cast(mem); + + virtual void Free( void* mem ) { + if ( !mem ) { + return; + } + --_currentAllocs; + Item* item = static_cast( mem ); #ifdef TINYXML2_DEBUG - memset(item, 0xfe, sizeof(*item)); + memset( item, 0xfe, sizeof( *item ) ); #endif - item->next = _root; - _root = item; - } - void Trace(const char* name) - { - printf("Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", - name, - _maxAllocs, - _maxAllocs * ITEM_SIZE / 1024, - _currentAllocs, - ITEM_SIZE, - _nAllocs, - _blockPtrs.Size()); - } - - void SetTracked() { --_nUntracked; } - - int Untracked() const { return _nUntracked; } - - // This number is perf sensitive. 4k seems like a good tradeoff on my machine. - // The test file is large, 170k. - // Release: VS2010 gcc(no opt) - // 1k: 4000 - // 2k: 4000 - // 4k: 3900 21000 - // 16k: 5200 - // 32k: 4300 - // 64k: 4000 21000 - // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK - // in private part if ITEMS_PER_BLOCK is private - enum - { - ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE - }; + item->next = _root; + _root = item; + } + void Trace( const char* name ) { + printf( "Mempool %s watermark=%d [%dk] current=%d size=%d nAlloc=%d blocks=%d\n", + name, _maxAllocs, _maxAllocs * ITEM_SIZE / 1024, _currentAllocs, + ITEM_SIZE, _nAllocs, _blockPtrs.Size() ); + } + + void SetTracked() { + --_nUntracked; + } + + int Untracked() const { + return _nUntracked; + } + + // This number is perf sensitive. 4k seems like a good tradeoff on my machine. + // The test file is large, 170k. + // Release: VS2010 gcc(no opt) + // 1k: 4000 + // 2k: 4000 + // 4k: 3900 21000 + // 16k: 5200 + // 32k: 4300 + // 64k: 4000 21000 + // Declared public because some compilers do not accept to use ITEMS_PER_BLOCK + // in private part if ITEMS_PER_BLOCK is private + enum { ITEMS_PER_BLOCK = (4 * 1024) / ITEM_SIZE }; private: - MemPoolT(const MemPoolT&); // not supported - void operator=(const MemPoolT&); // not supported - - union Item - { - Item* next; - char itemData[ITEM_SIZE]; - }; - struct Block - { - Item items[ITEMS_PER_BLOCK]; - }; - DynArray _blockPtrs; - Item* _root; - - int _currentAllocs; - int _nAllocs; - int _maxAllocs; - int _nUntracked; + MemPoolT( const MemPoolT& ); // not supported + void operator=( const MemPoolT& ); // not supported + + union Item { + Item* next; + char itemData[ITEM_SIZE]; + }; + struct Block { + Item items[ITEMS_PER_BLOCK]; + }; + DynArray< Block*, 10 > _blockPtrs; + Item* _root; + + int _currentAllocs; + int _nAllocs; + int _maxAllocs; + int _nUntracked; }; + /** Implements the interface to the "Visitor pattern" (see the Accept() method.) If you call the Accept() method, it requires being passed a XMLVisitor @@ -500,56 +472,68 @@ class MemPoolT : public MemPool class TINYXML2_LIB XMLVisitor { public: - virtual ~XMLVisitor() {} - - /// Visit a document. - virtual bool VisitEnter(const XMLDocument& /*doc*/) { return true; } - /// Visit a document. - virtual bool VisitExit(const XMLDocument& /*doc*/) { return true; } - - /// Visit an element. - virtual bool VisitEnter(const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/) - { - return true; - } - /// Visit an element. - virtual bool VisitExit(const XMLElement& /*element*/) { return true; } - - /// Visit a declaration. - virtual bool Visit(const XMLDeclaration& /*declaration*/) { return true; } - /// Visit a text node. - virtual bool Visit(const XMLText& /*text*/) { return true; } - /// Visit a comment node. - virtual bool Visit(const XMLComment& /*comment*/) { return true; } - /// Visit an unknown node. - virtual bool Visit(const XMLUnknown& /*unknown*/) { return true; } + virtual ~XMLVisitor() {} + + /// Visit a document. + virtual bool VisitEnter( const XMLDocument& /*doc*/ ) { + return true; + } + /// Visit a document. + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + /// Visit an element. + virtual bool VisitEnter( const XMLElement& /*element*/, const XMLAttribute* /*firstAttribute*/ ) { + return true; + } + /// Visit an element. + virtual bool VisitExit( const XMLElement& /*element*/ ) { + return true; + } + + /// Visit a declaration. + virtual bool Visit( const XMLDeclaration& /*declaration*/ ) { + return true; + } + /// Visit a text node. + virtual bool Visit( const XMLText& /*text*/ ) { + return true; + } + /// Visit a comment node. + virtual bool Visit( const XMLComment& /*comment*/ ) { + return true; + } + /// Visit an unknown node. + virtual bool Visit( const XMLUnknown& /*unknown*/ ) { + return true; + } }; // WARNING: must match XMLDocument::_errorNames[] -enum XMLError -{ - XML_SUCCESS = 0, - XML_NO_ATTRIBUTE, - XML_WRONG_ATTRIBUTE_TYPE, - XML_ERROR_FILE_NOT_FOUND, - XML_ERROR_FILE_COULD_NOT_BE_OPENED, - XML_ERROR_FILE_READ_ERROR, - UNUSED_XML_ERROR_ELEMENT_MISMATCH, // remove at next major version - XML_ERROR_PARSING_ELEMENT, - XML_ERROR_PARSING_ATTRIBUTE, - UNUSED_XML_ERROR_IDENTIFYING_TAG, // remove at next major version - XML_ERROR_PARSING_TEXT, - XML_ERROR_PARSING_CDATA, - XML_ERROR_PARSING_COMMENT, - XML_ERROR_PARSING_DECLARATION, - XML_ERROR_PARSING_UNKNOWN, - XML_ERROR_EMPTY_DOCUMENT, - XML_ERROR_MISMATCHED_ELEMENT, - XML_ERROR_PARSING, - XML_CAN_NOT_CONVERT_TEXT, - XML_NO_TEXT_NODE, - - XML_ERROR_COUNT +enum XMLError { + XML_SUCCESS = 0, + XML_NO_ATTRIBUTE, + XML_WRONG_ATTRIBUTE_TYPE, + XML_ERROR_FILE_NOT_FOUND, + XML_ERROR_FILE_COULD_NOT_BE_OPENED, + XML_ERROR_FILE_READ_ERROR, + UNUSED_XML_ERROR_ELEMENT_MISMATCH, // remove at next major version + XML_ERROR_PARSING_ELEMENT, + XML_ERROR_PARSING_ATTRIBUTE, + UNUSED_XML_ERROR_IDENTIFYING_TAG, // remove at next major version + XML_ERROR_PARSING_TEXT, + XML_ERROR_PARSING_CDATA, + XML_ERROR_PARSING_COMMENT, + XML_ERROR_PARSING_DECLARATION, + XML_ERROR_PARSING_UNKNOWN, + XML_ERROR_EMPTY_DOCUMENT, + XML_ERROR_MISMATCHED_ELEMENT, + XML_ERROR_PARSING, + XML_CAN_NOT_CONVERT_TEXT, + XML_NO_TEXT_NODE, + + XML_ERROR_COUNT }; @@ -559,98 +543,92 @@ enum XMLError class TINYXML2_LIB XMLUtil { public: - static const char* SkipWhiteSpace(const char* p, int* curLineNumPtr) - { - TIXMLASSERT(p); + static const char* SkipWhiteSpace( const char* p, int* curLineNumPtr ) { + TIXMLASSERT( p ); + + while( IsWhiteSpace(*p) ) { + if (curLineNumPtr && *p == '\n') { + ++(*curLineNumPtr); + } + ++p; + } + TIXMLASSERT( p ); + return p; + } + static char* SkipWhiteSpace( char* p, int* curLineNumPtr ) { + return const_cast( SkipWhiteSpace( const_cast(p), curLineNumPtr ) ); + } - while (IsWhiteSpace(*p)) - { - if (curLineNumPtr && *p == '\n') - { - ++(*curLineNumPtr); - } - ++p; - } - TIXMLASSERT(p); - return p; - } - static char* SkipWhiteSpace(char* p, int* curLineNumPtr) - { - return const_cast(SkipWhiteSpace(const_cast(p), curLineNumPtr)); - } - - // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't - // correct, but simple, and usually works. - static bool IsWhiteSpace(char p) - { - return !IsUTF8Continuation(p) && isspace(static_cast(p)); - } - - inline static bool IsNameStartChar(unsigned char ch) - { - if (ch >= 128) - { - // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() - return true; + // Anything in the high order range of UTF-8 is assumed to not be whitespace. This isn't + // correct, but simple, and usually works. + static bool IsWhiteSpace( char p ) { + return !IsUTF8Continuation(p) && isspace( static_cast(p) ); } - if (isalpha(ch)) - { - return true; + + inline static bool IsNameStartChar( unsigned char ch ) { + if ( ch >= 128 ) { + // This is a heuristic guess in attempt to not implement Unicode-aware isalpha() + return true; + } + if ( isalpha( ch ) ) { + return true; + } + return ch == ':' || ch == '_'; + } + + inline static bool IsNameChar( unsigned char ch ) { + return IsNameStartChar( ch ) + || isdigit( ch ) + || ch == '.' + || ch == '-'; } - return ch == ':' || ch == '_'; - } - inline static bool IsNameChar(unsigned char ch) - { - return IsNameStartChar(ch) || isdigit(ch) || ch == '.' || ch == '-'; - } + inline static bool StringEqual( const char* p, const char* q, int nChar=INT_MAX ) { + if ( p == q ) { + return true; + } + TIXMLASSERT( p ); + TIXMLASSERT( q ); + TIXMLASSERT( nChar >= 0 ); + return strncmp( p, q, nChar ) == 0; + } + + inline static bool IsUTF8Continuation( char p ) { + return ( p & 0x80 ) != 0; + } - inline static bool StringEqual(const char* p, const char* q, int nChar = INT_MAX) - { - if (p == q) - { - return true; - } - TIXMLASSERT(p); - TIXMLASSERT(q); - TIXMLASSERT(nChar >= 0); - return strncmp(p, q, nChar) == 0; - } - - inline static bool IsUTF8Continuation(char p) { return (p & 0x80) != 0; } - - static const char* ReadBOM(const char* p, bool* hasBOM); - // p is the starting location, - // the UTF-8 value of the entity will be placed in value, and length filled in. - static const char* GetCharacterRef(const char* p, char* value, int* length); - static void ConvertUTF32ToUTF8(unsigned long input, char* output, int* length); - - // converts primitive types to strings - static void ToStr(int v, char* buffer, int bufferSize); - static void ToStr(unsigned v, char* buffer, int bufferSize); - static void ToStr(bool v, char* buffer, int bufferSize); - static void ToStr(float v, char* buffer, int bufferSize); - static void ToStr(double v, char* buffer, int bufferSize); - static void ToStr(int64_t v, char* buffer, int bufferSize); - - // converts strings to primitive types - static bool ToInt(const char* str, int* value); - static bool ToUnsigned(const char* str, unsigned* value); - static bool ToBool(const char* str, bool* value); - static bool ToFloat(const char* str, float* value); - static bool ToDouble(const char* str, double* value); - static bool ToInt64(const char* str, int64_t* value); - - // Changes what is serialized for a boolean value. - // Default to "true" and "false". Shouldn't be changed - // unless you have a special testing or compatibility need. - // Be careful: static, global, & not thread safe. - // Be sure to set static const memory as parameters. - static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); + static const char* ReadBOM( const char* p, bool* hasBOM ); + // p is the starting location, + // the UTF-8 value of the entity will be placed in value, and length filled in. + static const char* GetCharacterRef( const char* p, char* value, int* length ); + static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); + + // converts primitive types to strings + static void ToStr( int v, char* buffer, int bufferSize ); + static void ToStr( unsigned v, char* buffer, int bufferSize ); + static void ToStr( bool v, char* buffer, int bufferSize ); + static void ToStr( float v, char* buffer, int bufferSize ); + static void ToStr( double v, char* buffer, int bufferSize ); + static void ToStr(int64_t v, char* buffer, int bufferSize); + + // converts strings to primitive types + static bool ToInt( const char* str, int* value ); + static bool ToUnsigned( const char* str, unsigned* value ); + static bool ToBool( const char* str, bool* value ); + static bool ToFloat( const char* str, float* value ); + static bool ToDouble( const char* str, double* value ); + static bool ToInt64(const char* str, int64_t* value); + + // Changes what is serialized for a boolean value. + // Default to "true" and "false". Shouldn't be changed + // unless you have a special testing or compatibility need. + // Be careful: static, global, & not thread safe. + // Be sure to set static const memory as parameters. + static void SetBoolSerialization(const char* writeTrue, const char* writeFalse); private: - static const char* writeBoolTrue; - static const char* writeBoolFalse; + static const char* writeBoolTrue; + static const char* writeBoolFalse; }; @@ -681,44 +659,66 @@ class TINYXML2_LIB XMLUtil */ class TINYXML2_LIB XMLNode { - friend class XMLDocument; - friend class XMLElement; - + friend class XMLDocument; + friend class XMLElement; public: - /// Get the XMLDocument that owns this XMLNode. - const XMLDocument* GetDocument() const - { - TIXMLASSERT(_document); - return _document; - } - /// Get the XMLDocument that owns this XMLNode. - XMLDocument* GetDocument() - { - TIXMLASSERT(_document); - return _document; - } - - /// Safely cast to an Element, or null. - virtual XMLElement* ToElement() { return 0; } - /// Safely cast to Text, or null. - virtual XMLText* ToText() { return 0; } - /// Safely cast to a Comment, or null. - virtual XMLComment* ToComment() { return 0; } - /// Safely cast to a Document, or null. - virtual XMLDocument* ToDocument() { return 0; } - /// Safely cast to a Declaration, or null. - virtual XMLDeclaration* ToDeclaration() { return 0; } - /// Safely cast to an Unknown, or null. - virtual XMLUnknown* ToUnknown() { return 0; } - - virtual const XMLElement* ToElement() const { return 0; } - virtual const XMLText* ToText() const { return 0; } - virtual const XMLComment* ToComment() const { return 0; } - virtual const XMLDocument* ToDocument() const { return 0; } - virtual const XMLDeclaration* ToDeclaration() const { return 0; } - virtual const XMLUnknown* ToUnknown() const { return 0; } - - /** The meaning of 'value' changes for the specific type. + + /// Get the XMLDocument that owns this XMLNode. + const XMLDocument* GetDocument() const { + TIXMLASSERT( _document ); + return _document; + } + /// Get the XMLDocument that owns this XMLNode. + XMLDocument* GetDocument() { + TIXMLASSERT( _document ); + return _document; + } + + /// Safely cast to an Element, or null. + virtual XMLElement* ToElement() { + return 0; + } + /// Safely cast to Text, or null. + virtual XMLText* ToText() { + return 0; + } + /// Safely cast to a Comment, or null. + virtual XMLComment* ToComment() { + return 0; + } + /// Safely cast to a Document, or null. + virtual XMLDocument* ToDocument() { + return 0; + } + /// Safely cast to a Declaration, or null. + virtual XMLDeclaration* ToDeclaration() { + return 0; + } + /// Safely cast to an Unknown, or null. + virtual XMLUnknown* ToUnknown() { + return 0; + } + + virtual const XMLElement* ToElement() const { + return 0; + } + virtual const XMLText* ToText() const { + return 0; + } + virtual const XMLComment* ToComment() const { + return 0; + } + virtual const XMLDocument* ToDocument() const { + return 0; + } + virtual const XMLDeclaration* ToDeclaration() const { + return 0; + } + virtual const XMLUnknown* ToUnknown() const { + return 0; + } + + /** The meaning of 'value' changes for the specific type. @verbatim Document: empty (NULL is returned, not an empty string) Element: name of the element @@ -727,99 +727,119 @@ class TINYXML2_LIB XMLNode Text: the text string @endverbatim */ - const char* Value() const; + const char* Value() const; - /** Set the Value of an XML node. + /** Set the Value of an XML node. @sa Value() */ - void SetValue(const char* val, bool staticMem = false); + void SetValue( const char* val, bool staticMem=false ); - /// Gets the line number the node is in, if the document was parsed from a file. - int GetLineNum() const { return _parseLineNum; } + /// Gets the line number the node is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } - /// Get the parent of this node on the DOM. - const XMLNode* Parent() const { return _parent; } + /// Get the parent of this node on the DOM. + const XMLNode* Parent() const { + return _parent; + } - XMLNode* Parent() { return _parent; } + XMLNode* Parent() { + return _parent; + } - /// Returns true if this node has no children. - bool NoChildren() const { return !_firstChild; } + /// Returns true if this node has no children. + bool NoChildren() const { + return !_firstChild; + } - /// Get the first child node, or null if none exists. - const XMLNode* FirstChild() const { return _firstChild; } + /// Get the first child node, or null if none exists. + const XMLNode* FirstChild() const { + return _firstChild; + } - XMLNode* FirstChild() { return _firstChild; } + XMLNode* FirstChild() { + return _firstChild; + } - /** Get the first child element, or optionally the first child + /** Get the first child element, or optionally the first child element with the specified name. */ - const XMLElement* FirstChildElement(const char* name = 0) const; + const XMLElement* FirstChildElement( const char* name = 0 ) const; - XMLElement* FirstChildElement(const char* name = 0) - { - return const_cast(const_cast(this)->FirstChildElement(name)); - } + XMLElement* FirstChildElement( const char* name = 0 ) { + return const_cast(const_cast(this)->FirstChildElement( name )); + } - /// Get the last child node, or null if none exists. - const XMLNode* LastChild() const { return _lastChild; } + /// Get the last child node, or null if none exists. + const XMLNode* LastChild() const { + return _lastChild; + } - XMLNode* LastChild() { return _lastChild; } + XMLNode* LastChild() { + return _lastChild; + } - /** Get the last child element or optionally the last child + /** Get the last child element or optionally the last child element with the specified name. */ - const XMLElement* LastChildElement(const char* name = 0) const; + const XMLElement* LastChildElement( const char* name = 0 ) const; - XMLElement* LastChildElement(const char* name = 0) - { - return const_cast(const_cast(this)->LastChildElement(name)); - } + XMLElement* LastChildElement( const char* name = 0 ) { + return const_cast(const_cast(this)->LastChildElement(name) ); + } - /// Get the previous (left) sibling node of this node. - const XMLNode* PreviousSibling() const { return _prev; } + /// Get the previous (left) sibling node of this node. + const XMLNode* PreviousSibling() const { + return _prev; + } - XMLNode* PreviousSibling() { return _prev; } + XMLNode* PreviousSibling() { + return _prev; + } - /// Get the previous (left) sibling element of this node, with an optionally supplied name. - const XMLElement* PreviousSiblingElement(const char* name = 0) const; + /// Get the previous (left) sibling element of this node, with an optionally supplied name. + const XMLElement* PreviousSiblingElement( const char* name = 0 ) const ; - XMLElement* PreviousSiblingElement(const char* name = 0) - { - return const_cast(const_cast(this)->PreviousSiblingElement(name)); - } + XMLElement* PreviousSiblingElement( const char* name = 0 ) { + return const_cast(const_cast(this)->PreviousSiblingElement( name ) ); + } - /// Get the next (right) sibling node of this node. - const XMLNode* NextSibling() const { return _next; } + /// Get the next (right) sibling node of this node. + const XMLNode* NextSibling() const { + return _next; + } - XMLNode* NextSibling() { return _next; } + XMLNode* NextSibling() { + return _next; + } - /// Get the next (right) sibling element of this node, with an optionally supplied name. - const XMLElement* NextSiblingElement(const char* name = 0) const; + /// Get the next (right) sibling element of this node, with an optionally supplied name. + const XMLElement* NextSiblingElement( const char* name = 0 ) const; - XMLElement* NextSiblingElement(const char* name = 0) - { - return const_cast(const_cast(this)->NextSiblingElement(name)); - } + XMLElement* NextSiblingElement( const char* name = 0 ) { + return const_cast(const_cast(this)->NextSiblingElement( name ) ); + } - /** + /** Add a child node as the last (right) child. If the child node is already part of the document, it is moved from its old location to the new location. Returns the addThis argument or 0 if the node does not belong to the same document. */ - XMLNode* InsertEndChild(XMLNode* addThis); + XMLNode* InsertEndChild( XMLNode* addThis ); - XMLNode* LinkEndChild(XMLNode* addThis) { return InsertEndChild(addThis); } - /** + XMLNode* LinkEndChild( XMLNode* addThis ) { + return InsertEndChild( addThis ); + } + /** Add a child node as the first (left) child. If the child node is already part of the document, it is moved from its old location to the new location. Returns the addThis argument or 0 if the node does not belong to the same document. */ - XMLNode* InsertFirstChild(XMLNode* addThis); - /** + XMLNode* InsertFirstChild( XMLNode* addThis ); + /** Add a node after the specified child node. If the child node is already part of the document, it is moved from its old location to the new location. @@ -827,19 +847,19 @@ class TINYXML2_LIB XMLNode is not a child of this node, or if the node does not belong to the same document. */ - XMLNode* InsertAfterChild(XMLNode* afterThis, XMLNode* addThis); + XMLNode* InsertAfterChild( XMLNode* afterThis, XMLNode* addThis ); - /** + /** Delete all the children of this node. */ - void DeleteChildren(); + void DeleteChildren(); - /** + /** Delete a child of this node. */ - void DeleteChild(XMLNode* node); + void DeleteChild( XMLNode* node ); - /** + /** Make a copy of this node, but not its children. You may pass in a Document pointer that will be the owner of the new Node. If the 'document' is @@ -848,9 +868,9 @@ class TINYXML2_LIB XMLNode Note: if called on a XMLDocument, this will return null. */ - virtual XMLNode* ShallowClone(XMLDocument* document) const = 0; + virtual XMLNode* ShallowClone( XMLDocument* document ) const = 0; - /** + /** Make a copy of this node and all its children. If the 'target' is null, then the nodes will @@ -863,17 +883,17 @@ class TINYXML2_LIB XMLNode top level XMLNodes. You probably want to use XMLDocument::DeepCopy() */ - XMLNode* DeepClone(XMLDocument* target) const; + XMLNode* DeepClone( XMLDocument* target ) const; - /** + /** Test if 2 nodes are the same, but don't test children. The 2 nodes do not need to be in the same Document. Note: if called on a XMLDocument, this will return false. */ - virtual bool ShallowEqual(const XMLNode* compare) const = 0; + virtual bool ShallowEqual( const XMLNode* compare ) const = 0; - /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the + /** Accept a hierarchical visit of the nodes in the TinyXML-2 DOM. Every node in the XML tree will be conditionally visited and the host will be called back via the XMLVisitor interface. @@ -895,50 +915,50 @@ class TINYXML2_LIB XMLNode const char* xmlcstr = printer.CStr(); @endverbatim */ - virtual bool Accept(XMLVisitor* visitor) const = 0; + virtual bool Accept( XMLVisitor* visitor ) const = 0; - /** + /** Set user data into the XMLNode. TinyXML-2 in no way processes or interprets user data. It is initially 0. */ - void SetUserData(void* userData) { _userData = userData; } + void SetUserData(void* userData) { _userData = userData; } - /** + /** Get user data set into the XMLNode. TinyXML-2 in no way processes or interprets user data. It is initially 0. */ - void* GetUserData() const { return _userData; } + void* GetUserData() const { return _userData; } protected: - XMLNode(XMLDocument*); - virtual ~XMLNode(); + XMLNode( XMLDocument* ); + virtual ~XMLNode(); - virtual char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); + virtual char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); - XMLDocument* _document; - XMLNode* _parent; - mutable StrPair _value; - int _parseLineNum; + XMLDocument* _document; + XMLNode* _parent; + mutable StrPair _value; + int _parseLineNum; - XMLNode* _firstChild; - XMLNode* _lastChild; + XMLNode* _firstChild; + XMLNode* _lastChild; - XMLNode* _prev; - XMLNode* _next; + XMLNode* _prev; + XMLNode* _next; - void* _userData; + void* _userData; private: - MemPool* _memPool; - void Unlink(XMLNode* child); - static void DeleteNode(XMLNode* node); - void InsertChildPreamble(XMLNode* insertThis) const; - const XMLElement* ToElementWithName(const char* name) const; - - XMLNode(const XMLNode&); // not supported - XMLNode& operator=(const XMLNode&); // not supported + MemPool* _memPool; + void Unlink( XMLNode* child ); + static void DeleteNode( XMLNode* node ); + void InsertChildPreamble( XMLNode* insertThis ) const; + const XMLElement* ToElementWithName( const char* name ) const; + + XMLNode( const XMLNode& ); // not supported + XMLNode& operator=( const XMLNode& ); // not supported }; @@ -956,59 +976,69 @@ class TINYXML2_LIB XMLNode */ class TINYXML2_LIB XMLText : public XMLNode { - friend class XMLDocument; - + friend class XMLDocument; public: - virtual bool Accept(XMLVisitor* visitor) const; + virtual bool Accept( XMLVisitor* visitor ) const; - virtual XMLText* ToText() { return this; } - virtual const XMLText* ToText() const { return this; } + virtual XMLText* ToText() { + return this; + } + virtual const XMLText* ToText() const { + return this; + } - /// Declare whether this should be CDATA or standard text. - void SetCData(bool isCData) { _isCData = isCData; } - /// Returns true if this is a CDATA text element. - bool CData() const { return _isCData; } + /// Declare whether this should be CDATA or standard text. + void SetCData( bool isCData ) { + _isCData = isCData; + } + /// Returns true if this is a CDATA text element. + bool CData() const { + return _isCData; + } - virtual XMLNode* ShallowClone(XMLDocument* document) const; - virtual bool ShallowEqual(const XMLNode* compare) const; + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; protected: - XMLText(XMLDocument* doc) : XMLNode(doc), _isCData(false) {} - virtual ~XMLText() {} + XMLText( XMLDocument* doc ) : XMLNode( doc ), _isCData( false ) {} + virtual ~XMLText() {} - char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); private: - bool _isCData; + bool _isCData; - XMLText(const XMLText&); // not supported - XMLText& operator=(const XMLText&); // not supported + XMLText( const XMLText& ); // not supported + XMLText& operator=( const XMLText& ); // not supported }; /** An XML Comment. */ class TINYXML2_LIB XMLComment : public XMLNode { - friend class XMLDocument; - + friend class XMLDocument; public: - virtual XMLComment* ToComment() { return this; } - virtual const XMLComment* ToComment() const { return this; } + virtual XMLComment* ToComment() { + return this; + } + virtual const XMLComment* ToComment() const { + return this; + } - virtual bool Accept(XMLVisitor* visitor) const; + virtual bool Accept( XMLVisitor* visitor ) const; - virtual XMLNode* ShallowClone(XMLDocument* document) const; - virtual bool ShallowEqual(const XMLNode* compare) const; + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; protected: - XMLComment(XMLDocument* doc); - virtual ~XMLComment(); + XMLComment( XMLDocument* doc ); + virtual ~XMLComment(); - char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr); private: - XMLComment(const XMLComment&); // not supported - XMLComment& operator=(const XMLComment&); // not supported + XMLComment( const XMLComment& ); // not supported + XMLComment& operator=( const XMLComment& ); // not supported }; @@ -1025,26 +1055,29 @@ class TINYXML2_LIB XMLComment : public XMLNode */ class TINYXML2_LIB XMLDeclaration : public XMLNode { - friend class XMLDocument; - + friend class XMLDocument; public: - virtual XMLDeclaration* ToDeclaration() { return this; } - virtual const XMLDeclaration* ToDeclaration() const { return this; } + virtual XMLDeclaration* ToDeclaration() { + return this; + } + virtual const XMLDeclaration* ToDeclaration() const { + return this; + } - virtual bool Accept(XMLVisitor* visitor) const; + virtual bool Accept( XMLVisitor* visitor ) const; - virtual XMLNode* ShallowClone(XMLDocument* document) const; - virtual bool ShallowEqual(const XMLNode* compare) const; + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; protected: - XMLDeclaration(XMLDocument* doc); - virtual ~XMLDeclaration(); + XMLDeclaration( XMLDocument* doc ); + virtual ~XMLDeclaration(); - char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); private: - XMLDeclaration(const XMLDeclaration&); // not supported - XMLDeclaration& operator=(const XMLDeclaration&); // not supported + XMLDeclaration( const XMLDeclaration& ); // not supported + XMLDeclaration& operator=( const XMLDeclaration& ); // not supported }; @@ -1057,29 +1090,33 @@ class TINYXML2_LIB XMLDeclaration : public XMLNode */ class TINYXML2_LIB XMLUnknown : public XMLNode { - friend class XMLDocument; - + friend class XMLDocument; public: - virtual XMLUnknown* ToUnknown() { return this; } - virtual const XMLUnknown* ToUnknown() const { return this; } + virtual XMLUnknown* ToUnknown() { + return this; + } + virtual const XMLUnknown* ToUnknown() const { + return this; + } - virtual bool Accept(XMLVisitor* visitor) const; + virtual bool Accept( XMLVisitor* visitor ) const; - virtual XMLNode* ShallowClone(XMLDocument* document) const; - virtual bool ShallowEqual(const XMLNode* compare) const; + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; protected: - XMLUnknown(XMLDocument* doc); - virtual ~XMLUnknown(); + XMLUnknown( XMLDocument* doc ); + virtual ~XMLUnknown(); - char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); private: - XMLUnknown(const XMLUnknown&); // not supported - XMLUnknown& operator=(const XMLUnknown&); // not supported + XMLUnknown( const XMLUnknown& ); // not supported + XMLUnknown& operator=( const XMLUnknown& ); // not supported }; + /** An attribute is a name-value pair. Elements have an arbitrary number of attributes, each with a unique name. @@ -1088,119 +1125,111 @@ class TINYXML2_LIB XMLUnknown : public XMLNode */ class TINYXML2_LIB XMLAttribute { - friend class XMLElement; - + friend class XMLElement; public: - /// The name of the attribute. - const char* Name() const; + /// The name of the attribute. + const char* Name() const; - /// The value of the attribute. - const char* Value() const; + /// The value of the attribute. + const char* Value() const; - /// Gets the line number the attribute is in, if the document was parsed from a file. - int GetLineNum() const { return _parseLineNum; } + /// Gets the line number the attribute is in, if the document was parsed from a file. + int GetLineNum() const { return _parseLineNum; } - /// The next attribute in the list. - const XMLAttribute* Next() const { return _next; } + /// The next attribute in the list. + const XMLAttribute* Next() const { + return _next; + } - /** IntValue interprets the attribute as an integer, and returns the value. + /** IntValue interprets the attribute as an integer, and returns the value. If the value isn't an integer, 0 will be returned. There is no error checking; use QueryIntValue() if you need error checking. */ - int IntValue() const - { - int i = 0; - QueryIntValue(&i); - return i; - } - - int64_t Int64Value() const - { - int64_t i = 0; - QueryInt64Value(&i); - return i; - } - - /// Query as an unsigned integer. See IntValue() - unsigned UnsignedValue() const - { - unsigned i = 0; - QueryUnsignedValue(&i); - return i; - } - /// Query as a boolean. See IntValue() - bool BoolValue() const - { - bool b = false; - QueryBoolValue(&b); - return b; - } - /// Query as a double. See IntValue() - double DoubleValue() const - { - double d = 0; - QueryDoubleValue(&d); - return d; - } - /// Query as a float. See IntValue() - float FloatValue() const - { - float f = 0; - QueryFloatValue(&f); - return f; - } - - /** QueryIntValue interprets the attribute as an integer, and returns the value + int IntValue() const { + int i = 0; + QueryIntValue(&i); + return i; + } + + int64_t Int64Value() const { + int64_t i = 0; + QueryInt64Value(&i); + return i; + } + + /// Query as an unsigned integer. See IntValue() + unsigned UnsignedValue() const { + unsigned i=0; + QueryUnsignedValue( &i ); + return i; + } + /// Query as a boolean. See IntValue() + bool BoolValue() const { + bool b=false; + QueryBoolValue( &b ); + return b; + } + /// Query as a double. See IntValue() + double DoubleValue() const { + double d=0; + QueryDoubleValue( &d ); + return d; + } + /// Query as a float. See IntValue() + float FloatValue() const { + float f=0; + QueryFloatValue( &f ); + return f; + } + + /** QueryIntValue interprets the attribute as an integer, and returns the value in the provided parameter. The function will return XML_SUCCESS on success, and XML_WRONG_ATTRIBUTE_TYPE if the conversion is not successful. */ - XMLError QueryIntValue(int* value) const; - /// See QueryIntValue - XMLError QueryUnsignedValue(unsigned int* value) const; - /// See QueryIntValue - XMLError QueryInt64Value(int64_t* value) const; - /// See QueryIntValue - XMLError QueryBoolValue(bool* value) const; - /// See QueryIntValue - XMLError QueryDoubleValue(double* value) const; - /// See QueryIntValue - XMLError QueryFloatValue(float* value) const; - - /// Set the attribute to a string value. - void SetAttribute(const char* value); - /// Set the attribute to value. - void SetAttribute(int value); - /// Set the attribute to value. - void SetAttribute(unsigned value); - /// Set the attribute to value. - void SetAttribute(int64_t value); - /// Set the attribute to value. - void SetAttribute(bool value); - /// Set the attribute to value. - void SetAttribute(double value); - /// Set the attribute to value. - void SetAttribute(float value); + XMLError QueryIntValue( int* value ) const; + /// See QueryIntValue + XMLError QueryUnsignedValue( unsigned int* value ) const; + /// See QueryIntValue + XMLError QueryInt64Value(int64_t* value) const; + /// See QueryIntValue + XMLError QueryBoolValue( bool* value ) const; + /// See QueryIntValue + XMLError QueryDoubleValue( double* value ) const; + /// See QueryIntValue + XMLError QueryFloatValue( float* value ) const; + + /// Set the attribute to a string value. + void SetAttribute( const char* value ); + /// Set the attribute to value. + void SetAttribute( int value ); + /// Set the attribute to value. + void SetAttribute( unsigned value ); + /// Set the attribute to value. + void SetAttribute(int64_t value); + /// Set the attribute to value. + void SetAttribute( bool value ); + /// Set the attribute to value. + void SetAttribute( double value ); + /// Set the attribute to value. + void SetAttribute( float value ); private: - enum - { - BUF_SIZE = 200 - }; + enum { BUF_SIZE = 200 }; - XMLAttribute() : _name(), _value(), _parseLineNum(0), _next(0), _memPool(0) {} - virtual ~XMLAttribute() {} + XMLAttribute() : _name(), _value(),_parseLineNum( 0 ), _next( 0 ), _memPool( 0 ) {} + virtual ~XMLAttribute() {} - XMLAttribute(const XMLAttribute&); // not supported - void operator=(const XMLAttribute&); // not supported - void SetName(const char* name); + XMLAttribute( const XMLAttribute& ); // not supported + void operator=( const XMLAttribute& ); // not supported + void SetName( const char* name ); - char* ParseDeep(char* p, bool processEntities, int* curLineNumPtr); + char* ParseDeep( char* p, bool processEntities, int* curLineNumPtr ); - mutable StrPair _name; - mutable StrPair _value; - int _parseLineNum; - XMLAttribute* _next; - MemPool* _memPool; + mutable StrPair _name; + mutable StrPair _value; + int _parseLineNum; + XMLAttribute* _next; + MemPool* _memPool; }; @@ -1210,19 +1239,26 @@ class TINYXML2_LIB XMLAttribute */ class TINYXML2_LIB XMLElement : public XMLNode { - friend class XMLDocument; - + friend class XMLDocument; public: - /// Get the name of an element (which is the Value() of the node.) - const char* Name() const { return Value(); } - /// Set the name of the element. - void SetName(const char* str, bool staticMem = false) { SetValue(str, staticMem); } + /// Get the name of an element (which is the Value() of the node.) + const char* Name() const { + return Value(); + } + /// Set the name of the element. + void SetName( const char* str, bool staticMem=false ) { + SetValue( str, staticMem ); + } - virtual XMLElement* ToElement() { return this; } - virtual const XMLElement* ToElement() const { return this; } - virtual bool Accept(XMLVisitor* visitor) const; + virtual XMLElement* ToElement() { + return this; + } + virtual const XMLElement* ToElement() const { + return this; + } + virtual bool Accept( XMLVisitor* visitor ) const; - /** Given an attribute name, Attribute() returns the value + /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. For example: @@ -1245,27 +1281,27 @@ class TINYXML2_LIB XMLElement : public XMLNode } @endverbatim */ - const char* Attribute(const char* name, const char* value = 0) const; + const char* Attribute( const char* name, const char* value=0 ) const; - /** Given an attribute name, IntAttribute() returns the value + /** Given an attribute name, IntAttribute() returns the value of the attribute interpreted as an integer. The default value will be returned if the attribute isn't present, or if there is an error. (For a method with error checking, see QueryIntAttribute()). */ - int IntAttribute(const char* name, int defaultValue = 0) const; - /// See IntAttribute() - unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; - /// See IntAttribute() - int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; - /// See IntAttribute() - bool BoolAttribute(const char* name, bool defaultValue = false) const; - /// See IntAttribute() - double DoubleAttribute(const char* name, double defaultValue = 0) const; - /// See IntAttribute() - float FloatAttribute(const char* name, float defaultValue = 0) const; - - /** Given an attribute name, QueryIntAttribute() returns + int IntAttribute(const char* name, int defaultValue = 0) const; + /// See IntAttribute() + unsigned UnsignedAttribute(const char* name, unsigned defaultValue = 0) const; + /// See IntAttribute() + int64_t Int64Attribute(const char* name, int64_t defaultValue = 0) const; + /// See IntAttribute() + bool BoolAttribute(const char* name, bool defaultValue = false) const; + /// See IntAttribute() + double DoubleAttribute(const char* name, double defaultValue = 0) const; + /// See IntAttribute() + float FloatAttribute(const char* name, float defaultValue = 0) const; + + /** Given an attribute name, QueryIntAttribute() returns XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion can't be performed, or XML_NO_ATTRIBUTE if the attribute doesn't exist. If successful, the result of the conversion @@ -1278,83 +1314,70 @@ class TINYXML2_LIB XMLElement : public XMLNode QueryIntAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 @endverbatim */ - XMLError QueryIntAttribute(const char* name, int* value) const - { - const XMLAttribute* a = FindAttribute(name); - if (!a) - { - return XML_NO_ATTRIBUTE; + XMLError QueryIntAttribute( const char* name, int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryIntValue( value ); } - return a->QueryIntValue(value); - } - /// See QueryIntAttribute() - XMLError QueryUnsignedAttribute(const char* name, unsigned int* value) const - { - const XMLAttribute* a = FindAttribute(name); - if (!a) - { - return XML_NO_ATTRIBUTE; + /// See QueryIntAttribute() + XMLError QueryUnsignedAttribute( const char* name, unsigned int* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryUnsignedValue( value ); } - return a->QueryUnsignedValue(value); - } - /// See QueryIntAttribute() - XMLError QueryInt64Attribute(const char* name, int64_t* value) const - { - const XMLAttribute* a = FindAttribute(name); - if (!a) - { - return XML_NO_ATTRIBUTE; + /// See QueryIntAttribute() + XMLError QueryInt64Attribute(const char* name, int64_t* value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + return a->QueryInt64Value(value); + } + + /// See QueryIntAttribute() + XMLError QueryBoolAttribute( const char* name, bool* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryBoolValue( value ); } - return a->QueryInt64Value(value); - } - - /// See QueryIntAttribute() - XMLError QueryBoolAttribute(const char* name, bool* value) const - { - const XMLAttribute* a = FindAttribute(name); - if (!a) - { - return XML_NO_ATTRIBUTE; - } - return a->QueryBoolValue(value); - } - /// See QueryIntAttribute() - XMLError QueryDoubleAttribute(const char* name, double* value) const - { - const XMLAttribute* a = FindAttribute(name); - if (!a) - { - return XML_NO_ATTRIBUTE; - } - return a->QueryDoubleValue(value); - } - /// See QueryIntAttribute() - XMLError QueryFloatAttribute(const char* name, float* value) const - { - const XMLAttribute* a = FindAttribute(name); - if (!a) - { - return XML_NO_ATTRIBUTE; + /// See QueryIntAttribute() + XMLError QueryDoubleAttribute( const char* name, double* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryDoubleValue( value ); } - return a->QueryFloatValue(value); - } - - /// See QueryIntAttribute() - XMLError QueryStringAttribute(const char* name, const char** value) const - { - const XMLAttribute* a = FindAttribute(name); - if (!a) - { - return XML_NO_ATTRIBUTE; + /// See QueryIntAttribute() + XMLError QueryFloatAttribute( const char* name, float* value ) const { + const XMLAttribute* a = FindAttribute( name ); + if ( !a ) { + return XML_NO_ATTRIBUTE; + } + return a->QueryFloatValue( value ); } - *value = a->Value(); - return XML_SUCCESS; - } + /// See QueryIntAttribute() + XMLError QueryStringAttribute(const char* name, const char** value) const { + const XMLAttribute* a = FindAttribute(name); + if (!a) { + return XML_NO_ATTRIBUTE; + } + *value = a->Value(); + return XML_SUCCESS; + } - /** Given an attribute name, QueryAttribute() returns + + + /** Given an attribute name, QueryAttribute() returns XML_SUCCESS, XML_WRONG_ATTRIBUTE_TYPE if the conversion can't be performed, or XML_NO_ATTRIBUTE if the attribute doesn't exist. It is overloaded for the primitive types, @@ -1371,89 +1394,81 @@ class TINYXML2_LIB XMLElement : public XMLNode QueryAttribute( "foo", &value ); // if "foo" isn't found, value will still be 10 @endverbatim */ - int QueryAttribute(const char* name, int* value) const { return QueryIntAttribute(name, value); } - - int QueryAttribute(const char* name, unsigned int* value) const - { - return QueryUnsignedAttribute(name, value); - } - - int QueryAttribute(const char* name, int64_t* value) const - { - return QueryInt64Attribute(name, value); - } - - int QueryAttribute(const char* name, bool* value) const - { - return QueryBoolAttribute(name, value); - } - - int QueryAttribute(const char* name, double* value) const - { - return QueryDoubleAttribute(name, value); - } - - int QueryAttribute(const char* name, float* value) const - { - return QueryFloatAttribute(name, value); - } - - /// Sets the named attribute to value. - void SetAttribute(const char* name, const char* value) - { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } - /// Sets the named attribute to value. - void SetAttribute(const char* name, int value) - { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } - /// Sets the named attribute to value. - void SetAttribute(const char* name, unsigned value) - { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } - - /// Sets the named attribute to value. - void SetAttribute(const char* name, int64_t value) - { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } - - /// Sets the named attribute to value. - void SetAttribute(const char* name, bool value) - { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } - /// Sets the named attribute to value. - void SetAttribute(const char* name, double value) - { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } - /// Sets the named attribute to value. - void SetAttribute(const char* name, float value) - { - XMLAttribute* a = FindOrCreateAttribute(name); - a->SetAttribute(value); - } - - /** + int QueryAttribute( const char* name, int* value ) const { + return QueryIntAttribute( name, value ); + } + + int QueryAttribute( const char* name, unsigned int* value ) const { + return QueryUnsignedAttribute( name, value ); + } + + int QueryAttribute(const char* name, int64_t* value) const { + return QueryInt64Attribute(name, value); + } + + int QueryAttribute( const char* name, bool* value ) const { + return QueryBoolAttribute( name, value ); + } + + int QueryAttribute( const char* name, double* value ) const { + return QueryDoubleAttribute( name, value ); + } + + int QueryAttribute( const char* name, float* value ) const { + return QueryFloatAttribute( name, value ); + } + + /// Sets the named attribute to value. + void SetAttribute( const char* name, const char* value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, int value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, unsigned value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + + /// Sets the named attribute to value. + void SetAttribute(const char* name, int64_t value) { + XMLAttribute* a = FindOrCreateAttribute(name); + a->SetAttribute(value); + } + + /// Sets the named attribute to value. + void SetAttribute( const char* name, bool value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, double value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + /// Sets the named attribute to value. + void SetAttribute( const char* name, float value ) { + XMLAttribute* a = FindOrCreateAttribute( name ); + a->SetAttribute( value ); + } + + /** Delete an attribute. */ - void DeleteAttribute(const char* name); + void DeleteAttribute( const char* name ); - /// Return the first attribute in the list. - const XMLAttribute* FirstAttribute() const { return _rootAttribute; } - /// Query a specific attribute in the list. - const XMLAttribute* FindAttribute(const char* name) const; + /// Return the first attribute in the list. + const XMLAttribute* FirstAttribute() const { + return _rootAttribute; + } + /// Query a specific attribute in the list. + const XMLAttribute* FindAttribute( const char* name ) const; - /** Convenience function for easy access to the text inside an element. Although easy + /** Convenience function for easy access to the text inside an element. Although easy and concise, GetText() is limited compared to getting the XMLText child and accessing it directly. @@ -1481,9 +1496,9 @@ class TINYXML2_LIB XMLElement : public XMLNode @endverbatim GetText() will return "This is ". */ - const char* GetText() const; + const char* GetText() const; - /** Convenience function for easy access to the text inside an element. Although easy + /** Convenience function for easy access to the text inside an element. Although easy and concise, SetText() is limited compared to creating an XMLText child and mutating it directly. @@ -1517,21 +1532,21 @@ class TINYXML2_LIB XMLElement : public XMLNode Hullaballoo! @endverbatim */ - void SetText(const char* inText); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(int value); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(unsigned value); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(int64_t value); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(bool value); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(double value); - /// Convenience method for setting text inside an element. See SetText() for important limitations. - void SetText(float value); - - /** + void SetText( const char* inText ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( int value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( unsigned value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText(int64_t value); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( bool value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( double value ); + /// Convenience method for setting text inside an element. See SetText() for important limitations. + void SetText( float value ); + + /** Convenience method to query the value of a child text node. This is probably best shown by example. Given you have a document is this form: @verbatim @@ -1557,77 +1572,73 @@ class TINYXML2_LIB XMLElement : public XMLNode to the requested type, and XML_NO_TEXT_NODE if there is no child text to query. */ - XMLError QueryIntText(int* ival) const; - /// See QueryIntText() - XMLError QueryUnsignedText(unsigned* uval) const; - /// See QueryIntText() - XMLError QueryInt64Text(int64_t* uval) const; - /// See QueryIntText() - XMLError QueryBoolText(bool* bval) const; - /// See QueryIntText() - XMLError QueryDoubleText(double* dval) const; - /// See QueryIntText() - XMLError QueryFloatText(float* fval) const; - - int IntText(int defaultValue = 0) const; - - /// See QueryIntText() - unsigned UnsignedText(unsigned defaultValue = 0) const; - /// See QueryIntText() - int64_t Int64Text(int64_t defaultValue = 0) const; - /// See QueryIntText() - bool BoolText(bool defaultValue = false) const; - /// See QueryIntText() - double DoubleText(double defaultValue = 0) const; - /// See QueryIntText() - float FloatText(float defaultValue = 0) const; - - // internal: - enum ElementClosingType - { - OPEN, // - CLOSED, // - CLOSING // - }; - ElementClosingType ClosingType() const { return _closingType; } - virtual XMLNode* ShallowClone(XMLDocument* document) const; - virtual bool ShallowEqual(const XMLNode* compare) const; + XMLError QueryIntText( int* ival ) const; + /// See QueryIntText() + XMLError QueryUnsignedText( unsigned* uval ) const; + /// See QueryIntText() + XMLError QueryInt64Text(int64_t* uval) const; + /// See QueryIntText() + XMLError QueryBoolText( bool* bval ) const; + /// See QueryIntText() + XMLError QueryDoubleText( double* dval ) const; + /// See QueryIntText() + XMLError QueryFloatText( float* fval ) const; + + int IntText(int defaultValue = 0) const; + + /// See QueryIntText() + unsigned UnsignedText(unsigned defaultValue = 0) const; + /// See QueryIntText() + int64_t Int64Text(int64_t defaultValue = 0) const; + /// See QueryIntText() + bool BoolText(bool defaultValue = false) const; + /// See QueryIntText() + double DoubleText(double defaultValue = 0) const; + /// See QueryIntText() + float FloatText(float defaultValue = 0) const; + + // internal: + enum ElementClosingType { + OPEN, // + CLOSED, // + CLOSING // + }; + ElementClosingType ClosingType() const { + return _closingType; + } + virtual XMLNode* ShallowClone( XMLDocument* document ) const; + virtual bool ShallowEqual( const XMLNode* compare ) const; protected: - char* ParseDeep(char* p, StrPair* parentEndTag, int* curLineNumPtr); + char* ParseDeep( char* p, StrPair* parentEndTag, int* curLineNumPtr ); private: - XMLElement(XMLDocument* doc); - virtual ~XMLElement(); - XMLElement(const XMLElement&); // not supported - void operator=(const XMLElement&); // not supported - - XMLAttribute* FindAttribute(const char* name) - { - return const_cast(const_cast(this)->FindAttribute(name)); - } - XMLAttribute* FindOrCreateAttribute(const char* name); - //void LinkAttribute( XMLAttribute* attrib ); - char* ParseAttributes(char* p, int* curLineNumPtr); - static void DeleteAttribute(XMLAttribute* attribute); - XMLAttribute* CreateAttribute(); - - enum - { - BUF_SIZE = 200 - }; - ElementClosingType _closingType; - // The attribute list is ordered; there is no 'lastAttribute' - // because the list needs to be scanned for dupes before adding - // a new attribute. - XMLAttribute* _rootAttribute; + XMLElement( XMLDocument* doc ); + virtual ~XMLElement(); + XMLElement( const XMLElement& ); // not supported + void operator=( const XMLElement& ); // not supported + + XMLAttribute* FindAttribute( const char* name ) { + return const_cast(const_cast(this)->FindAttribute( name )); + } + XMLAttribute* FindOrCreateAttribute( const char* name ); + //void LinkAttribute( XMLAttribute* attrib ); + char* ParseAttributes( char* p, int* curLineNumPtr ); + static void DeleteAttribute( XMLAttribute* attribute ); + XMLAttribute* CreateAttribute(); + + enum { BUF_SIZE = 200 }; + ElementClosingType _closingType; + // The attribute list is ordered; there is no 'lastAttribute' + // because the list needs to be scanned for dupes before adding + // a new attribute. + XMLAttribute* _rootAttribute; }; -enum Whitespace -{ - PRESERVE_WHITESPACE, - COLLAPSE_WHITESPACE +enum Whitespace { + PRESERVE_WHITESPACE, + COLLAPSE_WHITESPACE }; @@ -1638,32 +1649,29 @@ enum Whitespace */ class TINYXML2_LIB XMLDocument : public XMLNode { - friend class XMLElement; - // Gives access to SetError, but over-access for everything else. - // Wishing C++ had "internal" scope. - friend class XMLNode; - friend class XMLText; - friend class XMLComment; - friend class XMLDeclaration; - friend class XMLUnknown; - + friend class XMLElement; + // Gives access to SetError, but over-access for everything else. + // Wishing C++ had "internal" scope. + friend class XMLNode; + friend class XMLText; + friend class XMLComment; + friend class XMLDeclaration; + friend class XMLUnknown; public: - /// constructor - XMLDocument(bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE); - ~XMLDocument(); - - virtual XMLDocument* ToDocument() - { - TIXMLASSERT(this == _document); - return this; - } - virtual const XMLDocument* ToDocument() const - { - TIXMLASSERT(this == _document); - return this; - } - - /** + /// constructor + XMLDocument( bool processEntities = true, Whitespace whitespaceMode = PRESERVE_WHITESPACE ); + ~XMLDocument(); + + virtual XMLDocument* ToDocument() { + TIXMLASSERT( this == _document ); + return this; + } + virtual const XMLDocument* ToDocument() const { + TIXMLASSERT( this == _document ); + return this; + } + + /** Parse an XML file from a character string. Returns XML_SUCCESS (0) on success, or an errorID. @@ -1673,16 +1681,16 @@ class TINYXML2_LIB XMLDocument : public XMLNode specified, TinyXML-2 will assume 'xml' points to a null terminated string. */ - XMLError Parse(const char* xml, size_t nBytes = (size_t)(-1)); + XMLError Parse( const char* xml, size_t nBytes=(size_t)(-1) ); - /** + /** Load an XML file from disk. Returns XML_SUCCESS (0) on success, or an errorID. */ - XMLError LoadFile(const char* filename); + XMLError LoadFile( const char* filename ); - /** + /** Load an XML file from disk. You are responsible for providing and closing the FILE*. @@ -1693,42 +1701,54 @@ class TINYXML2_LIB XMLDocument : public XMLNode Returns XML_SUCCESS (0) on success, or an errorID. */ - XMLError LoadFile(FILE*); + XMLError LoadFile( FILE* ); - /** + /** Save the XML file to disk. Returns XML_SUCCESS (0) on success, or an errorID. */ - XMLError SaveFile(const char* filename, bool compact = false); + XMLError SaveFile( const char* filename, bool compact = false ); - /** + /** Save the XML file to disk. You are responsible for providing and closing the FILE*. Returns XML_SUCCESS (0) on success, or an errorID. */ - XMLError SaveFile(FILE* fp, bool compact = false); + XMLError SaveFile( FILE* fp, bool compact = false ); - bool ProcessEntities() const { return _processEntities; } - Whitespace WhitespaceMode() const { return _whitespaceMode; } + bool ProcessEntities() const { + return _processEntities; + } + Whitespace WhitespaceMode() const { + return _whitespaceMode; + } - /** + /** Returns true if this document has a leading Byte Order Mark of UTF8. */ - bool HasBOM() const { return _writeBOM; } - /** Sets whether to write the BOM when writing the file. + bool HasBOM() const { + return _writeBOM; + } + /** Sets whether to write the BOM when writing the file. */ - void SetBOM(bool useBOM) { _writeBOM = useBOM; } + void SetBOM( bool useBOM ) { + _writeBOM = useBOM; + } - /** Return the root element of DOM. Equivalent to FirstChildElement(). + /** Return the root element of DOM. Equivalent to FirstChildElement(). To get the first node, use FirstChild(). */ - XMLElement* RootElement() { return FirstChildElement(); } - const XMLElement* RootElement() const { return FirstChildElement(); } + XMLElement* RootElement() { + return FirstChildElement(); + } + const XMLElement* RootElement() const { + return FirstChildElement(); + } - /** Print the Document. If the Printer is not provided, it will + /** Print the Document. If the Printer is not provided, it will print to stdout. If you provide Printer, this can print to a file: @verbatim XMLPrinter printer( fp ); @@ -1742,28 +1762,28 @@ class TINYXML2_LIB XMLDocument : public XMLNode // printer.CStr() has a const char* to the XML @endverbatim */ - void Print(XMLPrinter* streamer = 0) const; - virtual bool Accept(XMLVisitor* visitor) const; + void Print( XMLPrinter* streamer=0 ) const; + virtual bool Accept( XMLVisitor* visitor ) const; - /** + /** Create a new Element associated with this Document. The memory for the Element is managed by the Document. */ - XMLElement* NewElement(const char* name); - /** + XMLElement* NewElement( const char* name ); + /** Create a new Comment associated with this Document. The memory for the Comment is managed by the Document. */ - XMLComment* NewComment(const char* comment); - /** + XMLComment* NewComment( const char* comment ); + /** Create a new Text associated with this Document. The memory for the Text is managed by the Document. */ - XMLText* NewText(const char* text); - /** + XMLText* NewText( const char* text ); + /** Create a new Declaration associated with this Document. The memory for the object is managed by the Document. @@ -1774,107 +1794,120 @@ class TINYXML2_LIB XMLDocument : public XMLNode @endverbatim */ - XMLDeclaration* NewDeclaration(const char* text = 0); - /** + XMLDeclaration* NewDeclaration( const char* text=0 ); + /** Create a new Unknown associated with this Document. The memory for the object is managed by the Document. */ - XMLUnknown* NewUnknown(const char* text); + XMLUnknown* NewUnknown( const char* text ); - /** + /** Delete a node associated with this document. It will be unlinked from the DOM. */ - void DeleteNode(XMLNode* node); + void DeleteNode( XMLNode* node ); - void ClearError() { SetError(XML_SUCCESS, 0, 0); } + void ClearError() { + SetError(XML_SUCCESS, 0, 0); + } - /// Return true if there was an error parsing the document. - bool Error() const { return _errorID != XML_SUCCESS; } - /// Return the errorID. - XMLError ErrorID() const { return _errorID; } - const char* ErrorName() const; - static const char* ErrorIDToName(XMLError errorID); + /// Return true if there was an error parsing the document. + bool Error() const { + return _errorID != XML_SUCCESS; + } + /// Return the errorID. + XMLError ErrorID() const { + return _errorID; + } + const char* ErrorName() const; + static const char* ErrorIDToName(XMLError errorID); - /** Returns a "long form" error description. A hopefully helpful + /** Returns a "long form" error description. A hopefully helpful diagnostic with location, line number, and/or additional info. */ - const char* ErrorStr() const; - - /// A (trivial) utility function that prints the ErrorStr() to stdout. - void PrintError() const; + const char* ErrorStr() const; - /// Return the line where the error occured, or zero if unknown. - int ErrorLineNum() const { return _errorLineNum; } + /// A (trivial) utility function that prints the ErrorStr() to stdout. + void PrintError() const; - /// Clear the document, resetting it to the initial state. - void Clear(); + /// Return the line where the error occured, or zero if unknown. + int ErrorLineNum() const + { + return _errorLineNum; + } + + /// Clear the document, resetting it to the initial state. + void Clear(); - /** + /** Copies this document to a target document. The target will be completely cleared before the copy. If you want to copy a sub-tree, see XMLNode::DeepClone(). NOTE: that the 'target' must be non-null. */ - void DeepCopy(XMLDocument* target) const; + void DeepCopy(XMLDocument* target) const; - // internal - char* Identify(char* p, XMLNode** node); + // internal + char* Identify( char* p, XMLNode** node ); - // internal - void MarkInUse(XMLNode*); + // internal + void MarkInUse(XMLNode*); - virtual XMLNode* ShallowClone(XMLDocument* /*document*/) const { return 0; } - virtual bool ShallowEqual(const XMLNode* /*compare*/) const { return false; } + virtual XMLNode* ShallowClone( XMLDocument* /*document*/ ) const { + return 0; + } + virtual bool ShallowEqual( const XMLNode* /*compare*/ ) const { + return false; + } private: - XMLDocument(const XMLDocument&); // not supported - void operator=(const XMLDocument&); // not supported - - bool _writeBOM; - bool _processEntities; - XMLError _errorID; - Whitespace _whitespaceMode; - mutable StrPair _errorStr; - int _errorLineNum; - char* _charBuffer; - int _parseCurLineNum; - // Memory tracking does add some overhead. - // However, the code assumes that you don't - // have a bunch of unlinked nodes around. - // Therefore it takes less memory to track - // in the document vs. a linked list in the XMLNode, - // and the performance is the same. - DynArray _unlinked; - - MemPoolT _elementPool; - MemPoolT _attributePool; - MemPoolT _textPool; - MemPoolT _commentPool; - - static const char* _errorNames[XML_ERROR_COUNT]; - - void Parse(); - - void SetError(XMLError error, int lineNum, const char* format, ...); - - template - NodeType* CreateUnlinkedNode(MemPoolT& pool); + XMLDocument( const XMLDocument& ); // not supported + void operator=( const XMLDocument& ); // not supported + + bool _writeBOM; + bool _processEntities; + XMLError _errorID; + Whitespace _whitespaceMode; + mutable StrPair _errorStr; + int _errorLineNum; + char* _charBuffer; + int _parseCurLineNum; + // Memory tracking does add some overhead. + // However, the code assumes that you don't + // have a bunch of unlinked nodes around. + // Therefore it takes less memory to track + // in the document vs. a linked list in the XMLNode, + // and the performance is the same. + DynArray _unlinked; + + MemPoolT< sizeof(XMLElement) > _elementPool; + MemPoolT< sizeof(XMLAttribute) > _attributePool; + MemPoolT< sizeof(XMLText) > _textPool; + MemPoolT< sizeof(XMLComment) > _commentPool; + + static const char* _errorNames[XML_ERROR_COUNT]; + + void Parse(); + + void SetError( XMLError error, int lineNum, const char* format, ... ); + + template + NodeType* CreateUnlinkedNode( MemPoolT& pool ); }; template -inline NodeType* XMLDocument::CreateUnlinkedNode(MemPoolT& pool) +inline NodeType* XMLDocument::CreateUnlinkedNode( MemPoolT& pool ) { - TIXMLASSERT(sizeof(NodeType) == PoolElementSize); - TIXMLASSERT(sizeof(NodeType) == pool.ItemSize()); - NodeType* returnNode = new (pool.Alloc()) NodeType(this); - TIXMLASSERT(returnNode); - returnNode->_memPool = &pool; - - _unlinked.Push(returnNode); - return returnNode; + TIXMLASSERT( sizeof( NodeType ) == PoolElementSize ); + TIXMLASSERT( sizeof( NodeType ) == pool.ItemSize() ); + NodeType* returnNode = new (pool.Alloc()) NodeType( this ); + TIXMLASSERT( returnNode ); + returnNode->_memPool = &pool; + + _unlinked.Push(returnNode); + return returnNode; } /** @@ -1935,61 +1968,77 @@ inline NodeType* XMLDocument::CreateUnlinkedNode(MemPoolT& pool class TINYXML2_LIB XMLHandle { public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - XMLHandle(XMLNode* node) : _node(node) {} - /// Create a handle from a node. - XMLHandle(XMLNode& node) : _node(&node) {} - /// Copy constructor - XMLHandle(const XMLHandle& ref) : _node(ref._node) {} - /// Assignment - XMLHandle& operator=(const XMLHandle& ref) - { - _node = ref._node; - return *this; - } - - /// Get the first child of this handle. - XMLHandle FirstChild() { return XMLHandle(_node ? _node->FirstChild() : 0); } - /// Get the first child element of this handle. - XMLHandle FirstChildElement(const char* name = 0) - { - return XMLHandle(_node ? _node->FirstChildElement(name) : 0); - } - /// Get the last child of this handle. - XMLHandle LastChild() { return XMLHandle(_node ? _node->LastChild() : 0); } - /// Get the last child element of this handle. - XMLHandle LastChildElement(const char* name = 0) - { - return XMLHandle(_node ? _node->LastChildElement(name) : 0); - } - /// Get the previous sibling of this handle. - XMLHandle PreviousSibling() { return XMLHandle(_node ? _node->PreviousSibling() : 0); } - /// Get the previous sibling element of this handle. - XMLHandle PreviousSiblingElement(const char* name = 0) - { - return XMLHandle(_node ? _node->PreviousSiblingElement(name) : 0); - } - /// Get the next sibling of this handle. - XMLHandle NextSibling() { return XMLHandle(_node ? _node->NextSibling() : 0); } - /// Get the next sibling element of this handle. - XMLHandle NextSiblingElement(const char* name = 0) - { - return XMLHandle(_node ? _node->NextSiblingElement(name) : 0); - } - - /// Safe cast to XMLNode. This can return null. - XMLNode* ToNode() { return _node; } - /// Safe cast to XMLElement. This can return null. - XMLElement* ToElement() { return (_node ? _node->ToElement() : 0); } - /// Safe cast to XMLText. This can return null. - XMLText* ToText() { return (_node ? _node->ToText() : 0); } - /// Safe cast to XMLUnknown. This can return null. - XMLUnknown* ToUnknown() { return (_node ? _node->ToUnknown() : 0); } - /// Safe cast to XMLDeclaration. This can return null. - XMLDeclaration* ToDeclaration() { return (_node ? _node->ToDeclaration() : 0); } + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + XMLHandle( XMLNode* node ) : _node( node ) { + } + /// Create a handle from a node. + XMLHandle( XMLNode& node ) : _node( &node ) { + } + /// Copy constructor + XMLHandle( const XMLHandle& ref ) : _node( ref._node ) { + } + /// Assignment + XMLHandle& operator=( const XMLHandle& ref ) { + _node = ref._node; + return *this; + } + + /// Get the first child of this handle. + XMLHandle FirstChild() { + return XMLHandle( _node ? _node->FirstChild() : 0 ); + } + /// Get the first child element of this handle. + XMLHandle FirstChildElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->FirstChildElement( name ) : 0 ); + } + /// Get the last child of this handle. + XMLHandle LastChild() { + return XMLHandle( _node ? _node->LastChild() : 0 ); + } + /// Get the last child element of this handle. + XMLHandle LastChildElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->LastChildElement( name ) : 0 ); + } + /// Get the previous sibling of this handle. + XMLHandle PreviousSibling() { + return XMLHandle( _node ? _node->PreviousSibling() : 0 ); + } + /// Get the previous sibling element of this handle. + XMLHandle PreviousSiblingElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); + } + /// Get the next sibling of this handle. + XMLHandle NextSibling() { + return XMLHandle( _node ? _node->NextSibling() : 0 ); + } + /// Get the next sibling element of this handle. + XMLHandle NextSiblingElement( const char* name = 0 ) { + return XMLHandle( _node ? _node->NextSiblingElement( name ) : 0 ); + } + + /// Safe cast to XMLNode. This can return null. + XMLNode* ToNode() { + return _node; + } + /// Safe cast to XMLElement. This can return null. + XMLElement* ToElement() { + return ( _node ? _node->ToElement() : 0 ); + } + /// Safe cast to XMLText. This can return null. + XMLText* ToText() { + return ( _node ? _node->ToText() : 0 ); + } + /// Safe cast to XMLUnknown. This can return null. + XMLUnknown* ToUnknown() { + return ( _node ? _node->ToUnknown() : 0 ); + } + /// Safe cast to XMLDeclaration. This can return null. + XMLDeclaration* ToDeclaration() { + return ( _node ? _node->ToDeclaration() : 0 ); + } private: - XMLNode* _node; + XMLNode* _node; }; @@ -2000,55 +2049,62 @@ class TINYXML2_LIB XMLHandle class TINYXML2_LIB XMLConstHandle { public: - XMLConstHandle(const XMLNode* node) : _node(node) {} - XMLConstHandle(const XMLNode& node) : _node(&node) {} - XMLConstHandle(const XMLConstHandle& ref) : _node(ref._node) {} - - XMLConstHandle& operator=(const XMLConstHandle& ref) - { - _node = ref._node; - return *this; - } - - const XMLConstHandle FirstChild() const - { - return XMLConstHandle(_node ? _node->FirstChild() : 0); - } - const XMLConstHandle FirstChildElement(const char* name = 0) const - { - return XMLConstHandle(_node ? _node->FirstChildElement(name) : 0); - } - const XMLConstHandle LastChild() const { return XMLConstHandle(_node ? _node->LastChild() : 0); } - const XMLConstHandle LastChildElement(const char* name = 0) const - { - return XMLConstHandle(_node ? _node->LastChildElement(name) : 0); - } - const XMLConstHandle PreviousSibling() const - { - return XMLConstHandle(_node ? _node->PreviousSibling() : 0); - } - const XMLConstHandle PreviousSiblingElement(const char* name = 0) const - { - return XMLConstHandle(_node ? _node->PreviousSiblingElement(name) : 0); - } - const XMLConstHandle NextSibling() const - { - return XMLConstHandle(_node ? _node->NextSibling() : 0); - } - const XMLConstHandle NextSiblingElement(const char* name = 0) const - { - return XMLConstHandle(_node ? _node->NextSiblingElement(name) : 0); - } - - - const XMLNode* ToNode() const { return _node; } - const XMLElement* ToElement() const { return (_node ? _node->ToElement() : 0); } - const XMLText* ToText() const { return (_node ? _node->ToText() : 0); } - const XMLUnknown* ToUnknown() const { return (_node ? _node->ToUnknown() : 0); } - const XMLDeclaration* ToDeclaration() const { return (_node ? _node->ToDeclaration() : 0); } + XMLConstHandle( const XMLNode* node ) : _node( node ) { + } + XMLConstHandle( const XMLNode& node ) : _node( &node ) { + } + XMLConstHandle( const XMLConstHandle& ref ) : _node( ref._node ) { + } + + XMLConstHandle& operator=( const XMLConstHandle& ref ) { + _node = ref._node; + return *this; + } + + const XMLConstHandle FirstChild() const { + return XMLConstHandle( _node ? _node->FirstChild() : 0 ); + } + const XMLConstHandle FirstChildElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->FirstChildElement( name ) : 0 ); + } + const XMLConstHandle LastChild() const { + return XMLConstHandle( _node ? _node->LastChild() : 0 ); + } + const XMLConstHandle LastChildElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->LastChildElement( name ) : 0 ); + } + const XMLConstHandle PreviousSibling() const { + return XMLConstHandle( _node ? _node->PreviousSibling() : 0 ); + } + const XMLConstHandle PreviousSiblingElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->PreviousSiblingElement( name ) : 0 ); + } + const XMLConstHandle NextSibling() const { + return XMLConstHandle( _node ? _node->NextSibling() : 0 ); + } + const XMLConstHandle NextSiblingElement( const char* name = 0 ) const { + return XMLConstHandle( _node ? _node->NextSiblingElement( name ) : 0 ); + } + + + const XMLNode* ToNode() const { + return _node; + } + const XMLElement* ToElement() const { + return ( _node ? _node->ToElement() : 0 ); + } + const XMLText* ToText() const { + return ( _node ? _node->ToText() : 0 ); + } + const XMLUnknown* ToUnknown() const { + return ( _node ? _node->ToUnknown() : 0 ); + } + const XMLDeclaration* ToDeclaration() const { + return ( _node ? _node->ToDeclaration() : 0 ); + } private: - const XMLNode* _node; + const XMLNode* _node; }; @@ -2097,131 +2153,135 @@ class TINYXML2_LIB XMLConstHandle class TINYXML2_LIB XMLPrinter : public XMLVisitor { public: - /** Construct the printer. If the FILE* is specified, + /** Construct the printer. If the FILE* is specified, this will print to the FILE. Else it will print to memory, and the result is available in CStr(). If 'compact' is set to true, then output is created with only required whitespace and newlines. */ - XMLPrinter(FILE* file = 0, bool compact = false, int depth = 0); - virtual ~XMLPrinter() {} + XMLPrinter( FILE* file=0, bool compact = false, int depth = 0 ); + virtual ~XMLPrinter() {} - /** If streaming, write the BOM and declaration. */ - void PushHeader(bool writeBOM, bool writeDeclaration); - /** If streaming, start writing an element. + /** If streaming, write the BOM and declaration. */ + void PushHeader( bool writeBOM, bool writeDeclaration ); + /** If streaming, start writing an element. The element must be closed with CloseElement() */ - void OpenElement(const char* name, bool compactMode = false); - /// If streaming, add an attribute to an open element. - void PushAttribute(const char* name, const char* value); - void PushAttribute(const char* name, int value); - void PushAttribute(const char* name, unsigned value); - void PushAttribute(const char* name, int64_t value); - void PushAttribute(const char* name, bool value); - void PushAttribute(const char* name, double value); - /// If streaming, close the Element. - virtual void CloseElement(bool compactMode = false); - - /// Add a text node. - void PushText(const char* text, bool cdata = false); - /// Add a text node from an integer. - void PushText(int value); - /// Add a text node from an unsigned. - void PushText(unsigned value); - /// Add a text node from an unsigned. - void PushText(int64_t value); - /// Add a text node from a bool. - void PushText(bool value); - /// Add a text node from a float. - void PushText(float value); - /// Add a text node from a double. - void PushText(double value); - - /// Add a comment - void PushComment(const char* comment); - - void PushDeclaration(const char* value); - void PushUnknown(const char* value); - - virtual bool VisitEnter(const XMLDocument& /*doc*/); - virtual bool VisitExit(const XMLDocument& /*doc*/) { return true; } - - virtual bool VisitEnter(const XMLElement& element, const XMLAttribute* attribute); - virtual bool VisitExit(const XMLElement& element); - - virtual bool Visit(const XMLText& text); - virtual bool Visit(const XMLComment& comment); - virtual bool Visit(const XMLDeclaration& declaration); - virtual bool Visit(const XMLUnknown& unknown); - - /** + void OpenElement( const char* name, bool compactMode=false ); + /// If streaming, add an attribute to an open element. + void PushAttribute( const char* name, const char* value ); + void PushAttribute( const char* name, int value ); + void PushAttribute( const char* name, unsigned value ); + void PushAttribute(const char* name, int64_t value); + void PushAttribute( const char* name, bool value ); + void PushAttribute( const char* name, double value ); + /// If streaming, close the Element. + virtual void CloseElement( bool compactMode=false ); + + /// Add a text node. + void PushText( const char* text, bool cdata=false ); + /// Add a text node from an integer. + void PushText( int value ); + /// Add a text node from an unsigned. + void PushText( unsigned value ); + /// Add a text node from an unsigned. + void PushText(int64_t value); + /// Add a text node from a bool. + void PushText( bool value ); + /// Add a text node from a float. + void PushText( float value ); + /// Add a text node from a double. + void PushText( double value ); + + /// Add a comment + void PushComment( const char* comment ); + + void PushDeclaration( const char* value ); + void PushUnknown( const char* value ); + + virtual bool VisitEnter( const XMLDocument& /*doc*/ ); + virtual bool VisitExit( const XMLDocument& /*doc*/ ) { + return true; + } + + virtual bool VisitEnter( const XMLElement& element, const XMLAttribute* attribute ); + virtual bool VisitExit( const XMLElement& element ); + + virtual bool Visit( const XMLText& text ); + virtual bool Visit( const XMLComment& comment ); + virtual bool Visit( const XMLDeclaration& declaration ); + virtual bool Visit( const XMLUnknown& unknown ); + + /** If in print to memory mode, return a pointer to the XML file in memory. */ - const char* CStr() const { return _buffer.Mem(); } - /** + const char* CStr() const { + return _buffer.Mem(); + } + /** If in print to memory mode, return the size of the XML file in memory. (Note the size returned includes the terminating null.) */ - int CStrSize() const { return _buffer.Size(); } - /** + int CStrSize() const { + return _buffer.Size(); + } + /** If in print to memory mode, reset the buffer to the beginning. */ - void ClearBuffer() - { - _buffer.Clear(); - _buffer.Push(0); - _firstElement = true; - } + void ClearBuffer() { + _buffer.Clear(); + _buffer.Push(0); + _firstElement = true; + } protected: - virtual bool CompactMode(const XMLElement&) { return _compactMode; } + virtual bool CompactMode( const XMLElement& ) { return _compactMode; } - /** Prints out the space before an element. You may override to change + /** Prints out the space before an element. You may override to change the space and tabs used. A PrintSpace() override should call Print(). */ - virtual void PrintSpace(int depth); - void Print(const char* format, ...); - void Write(const char* data, size_t size); - inline void Write(const char* data) { Write(data, strlen(data)); } - void Putc(char ch); + virtual void PrintSpace( int depth ); + void Print( const char* format, ... ); + void Write( const char* data, size_t size ); + inline void Write( const char* data ) { Write( data, strlen( data ) ); } + void Putc( char ch ); - void SealElementIfJustOpened(); - bool _elementJustOpened; - DynArray _stack; + void SealElementIfJustOpened(); + bool _elementJustOpened; + DynArray< const char*, 10 > _stack; private: - void PrintString(const char*, bool restrictedEntitySet); // prints out, after detecting entities. - - bool _firstElement; - FILE* _fp; - int _depth; - int _textDepth; - bool _processEntities; - bool _compactMode; - - enum - { - ENTITY_RANGE = 64, - BUF_SIZE = 200 - }; - bool _entityFlag[ENTITY_RANGE]; - bool _restrictedEntityFlag[ENTITY_RANGE]; - - DynArray _buffer; - - // Prohibit cloning, intentionally not implemented - XMLPrinter(const XMLPrinter&); - XMLPrinter& operator=(const XMLPrinter&); + void PrintString( const char*, bool restrictedEntitySet ); // prints out, after detecting entities. + + bool _firstElement; + FILE* _fp; + int _depth; + int _textDepth; + bool _processEntities; + bool _compactMode; + + enum { + ENTITY_RANGE = 64, + BUF_SIZE = 200 + }; + bool _entityFlag[ENTITY_RANGE]; + bool _restrictedEntityFlag[ENTITY_RANGE]; + + DynArray< char, 20 > _buffer; + + // Prohibit cloning, intentionally not implemented + XMLPrinter( const XMLPrinter& ); + XMLPrinter& operator=( const XMLPrinter& ); }; -} // namespace tinyxml2 +} // tinyxml2 #if defined(_MSC_VER) -#pragma warning(pop) +# pragma warning(pop) #endif #endif // TINYXML2_INCLUDED From 0ccf3123b26d1c776dcc7eb5d19cb285cc94b917 Mon Sep 17 00:00:00 2001 From: Peter Doak Date: Fri, 3 Aug 2018 16:54:52 -0400 Subject: [PATCH 8/8] No return alignment but () work. --- src/Numerics/OhmmsPETE/TensorOps.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Numerics/OhmmsPETE/TensorOps.h b/src/Numerics/OhmmsPETE/TensorOps.h index 8525bc119..68f4aefd1 100644 --- a/src/Numerics/OhmmsPETE/TensorOps.h +++ b/src/Numerics/OhmmsPETE/TensorOps.h @@ -122,9 +122,9 @@ inline typename Tensor::Type_t det(const Tensor& a) template inline typename Tensor::Type_t det(const Tensor& a) { - return a(0, 0) * (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1)) + - a(0, 1) * (a(1, 2) * a(2, 0) - a(1, 0) * a(2, 2)) + - a(0, 2) * (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0)); + return (a(0, 0) * (a(1, 1) * a(2, 2) - a(1, 2) * a(2, 1)) + + a(0, 1) * (a(1, 2) * a(2, 0) - a(1, 0) * a(2, 2)) + + a(0, 2) * (a(1, 0) * a(2, 1) - a(1, 1) * a(2, 0))); } //////////////////////////////////////////////////////