From d80912ccb7aff5350dccd35e9196ad4125b1232e Mon Sep 17 00:00:00 2001 From: Daniele Rapetti Date: Fri, 4 Oct 2024 08:11:39 +0200 Subject: [PATCH] restyled v2.10 --- .astyle.options | 14 +- src/adjmat/AdjacencyMatrixBase.cpp | 441 +++- src/adjmat/AdjacencyMatrixBase.h | 23 +- src/adjmat/Bridge.cpp | 24 +- src/adjmat/BridgeMatrix.cpp | 59 +- src/adjmat/ContactMatrix.cpp | 45 +- src/adjmat/ContactMatrixShortcut.cpp | 67 +- src/adjmat/DistanceMatrix.cpp | 6 +- src/adjmat/HbondMatrix.cpp | 50 +- src/adjmat/Neighbors.cpp | 75 +- src/adjmat/TopologyMatrix.cpp | 107 +- src/adjmat/TorsionsMatrix.cpp | 135 +- src/annfunc/ANN.cpp | 33 +- src/astyle.sh | 64 +- src/bias/ABMD.cpp | 42 +- src/bias/Bias.cpp | 14 +- src/bias/Bias.h | 3 +- src/bias/BiasValue.cpp | 9 +- src/bias/ExtendedLagrangian.cpp | 27 +- src/bias/External.cpp | 33 +- src/bias/LWalls.cpp | 32 +- src/bias/MaxEnt.cpp | 139 +- src/bias/MetaD.cpp | 922 ++++--- src/bias/MovingRestraint.cpp | 66 +- src/bias/PBMetaD.cpp | 438 +++- src/bias/Restraint.cpp | 18 +- src/bias/RestraintShortcut.cpp | 102 +- src/bias/ReweightBase.cpp | 10 +- src/bias/ReweightBase.h | 15 +- src/bias/ReweightBias.cpp | 11 +- src/bias/ReweightMetad.cpp | 11 +- src/bias/ReweightTemperaturePressure.cpp | 55 +- src/bias/UWalls.cpp | 32 +- src/bias/Walls.cpp | 73 +- src/cltools/Benchmark.cpp | 189 +- src/cltools/Completion.cpp | 30 +- src/cltools/Driver.cpp | 705 ++++-- src/cltools/DriverFloat.cpp | 4 +- src/cltools/GenExample.cpp | 336 ++- src/cltools/GenJson.cpp | 107 +- src/cltools/GenTemplate.cpp | 10 +- src/cltools/Info.cpp | 75 +- src/cltools/Manual.cpp | 20 +- src/cltools/PdbRenumber.cpp | 14 +- src/cltools/ShowGraph.cpp | 200 +- src/cltools/SimpleMD.cpp | 205 +- src/cltools/SumHills.cpp | 165 +- src/cltools/SwitchingPlotter.cpp | 3 +- src/cltools/kT.cpp | 15 +- src/cltools/pesmd.cpp | 132 +- src/clusters/ClusterDiameter.cpp | 14 +- src/clusters/ClusterDistribution.cpp | 63 +- src/clusters/ClusterNatoms.cpp | 6 +- src/clusters/ClusterProperties.cpp | 9 +- src/clusters/ClusterWeights.cpp | 46 +- src/clusters/ClusterWithSurface.cpp | 15 +- src/clusters/ClusteringBase.cpp | 53 +- src/clusters/ClusteringBase.h | 8 +- src/clusters/DFSClustering.cpp | 32 +- src/clusters/OutputCluster.cpp | 21 +- src/colvar/Angle.cpp | 44 +- src/colvar/Cell.cpp | 52 +- src/colvar/ColvarShortcut.h | 29 +- src/colvar/ContactMap.cpp | 83 +- src/colvar/Coordination.cpp | 11 +- src/colvar/CoordinationBase.cpp | 77 +- src/colvar/DHEnergy.cpp | 7 +- src/colvar/DRMSD.cpp | 179 +- src/colvar/DihedralCorrelation.cpp | 36 +- src/colvar/Dimer.cpp | 62 +- src/colvar/Dipole.cpp | 69 +- src/colvar/Distance.cpp | 97 +- src/colvar/EEFSolv.cpp | 84 +- src/colvar/ERMSD.cpp | 29 +- src/colvar/Energy.cpp | 39 +- src/colvar/ExtraCV.cpp | 13 +- src/colvar/Fake.cpp | 7 +- src/colvar/GHBFIX.cpp | 10 +- src/colvar/Gyration.cpp | 200 +- src/colvar/GyrationShortcut.cpp | 132 +- src/colvar/MultiColvarTemplate.h | 117 +- src/colvar/MultiRMSD.cpp | 120 +- src/colvar/PCARMSD.cpp | 97 +- src/colvar/PathMSD.cpp | 15 +- src/colvar/PathMSDBase.cpp | 120 +- src/colvar/Plane.cpp | 41 +- src/colvar/Position.cpp | 68 +- src/colvar/ProjectionOnAxis.cpp | 39 +- src/colvar/PropertyMap.cpp | 14 +- src/colvar/Puckering.cpp | 152 +- src/colvar/RMSD.cpp | 38 +- src/colvar/RMSDShortcut.cpp | 108 +- src/colvar/RMSDVector.cpp | 286 ++- src/colvar/SelectMassCharge.cpp | 56 +- src/colvar/Template.cpp | 16 +- src/colvar/Torsion.cpp | 84 +- src/colvar/Volume.cpp | 6 +- src/config/Config.inc.in | 32 +- src/contour/ContourFindingBase.cpp | 15 +- src/contour/ContourFindingBase.h | 8 +- src/contour/DistanceFromContour.cpp | 131 +- src/contour/DistanceFromContourBase.cpp | 129 +- src/contour/DistanceFromContourBase.h | 11 +- src/contour/DistanceFromSphericalContour.cpp | 51 +- src/contour/DumpContour.cpp | 45 +- src/contour/FindContour.cpp | 58 +- src/contour/FindContour.h | 8 +- src/contour/FindContourSurface.cpp | 106 +- src/contour/FindSphericalContour.cpp | 57 +- src/core/Action.cpp | 180 +- src/core/Action.h | 117 +- src/core/ActionAnyorder.cpp | 3 +- src/core/ActionAtomistic.cpp | 284 ++- src/core/ActionAtomistic.h | 27 +- src/core/ActionForInterface.cpp | 10 +- src/core/ActionForInterface.h | 17 +- src/core/ActionPilot.cpp | 11 +- src/core/ActionPilot.h | 3 +- src/core/ActionRegister.cpp | 26 +- src/core/ActionRegister.h | 7 +- src/core/ActionSet.cpp | 19 +- src/core/ActionSet.h | 31 +- src/core/ActionSetup.cpp | 3 +- src/core/ActionShortcut.cpp | 198 +- src/core/ActionShortcut.h | 4 +- src/core/ActionToGetData.cpp | 59 +- src/core/ActionToGetData.h | 7 +- src/core/ActionToPutData.cpp | 178 +- src/core/ActionToPutData.h | 15 +- src/core/ActionWithArguments.cpp | 187 +- src/core/ActionWithArguments.h | 7 +- src/core/ActionWithMatrix.cpp | 183 +- src/core/ActionWithMatrix.h | 18 +- src/core/ActionWithValue.cpp | 148 +- src/core/ActionWithValue.h | 15 +- src/core/ActionWithVector.cpp | 673 ++++-- src/core/ActionWithVector.h | 15 +- src/core/ActionWithVirtualAtom.cpp | 79 +- src/core/ActionWithVirtualAtom.h | 11 +- src/core/CLTool.cpp | 79 +- src/core/CLTool.h | 24 +- src/core/CLToolMain.cpp | 64 +- src/core/CLToolMain.h | 3 +- src/core/CLToolRegister.cpp | 16 +- src/core/Colvar.cpp | 32 +- src/core/Colvar.h | 3 +- src/core/DataPassingObject.cpp | 144 +- src/core/DataPassingObject.h | 16 +- src/core/DataPassingTools.cpp | 27 +- src/core/DomainDecomposition.cpp | 366 ++- src/core/DomainDecomposition.h | 12 +- src/core/ExchangePatterns.cpp | 18 +- src/core/FlexibleBin.cpp | 24 +- src/core/GREX.cpp | 19 +- src/core/GREX.h | 3 +- src/core/GenericMolInfo.cpp | 132 +- src/core/Group.cpp | 34 +- src/core/PbcAction.cpp | 33 +- src/core/PbcAction.h | 4 +- src/core/PlumedMain.cpp | 607 +++-- src/core/PlumedMain.h | 21 +- src/core/PlumedMainInitializer.cpp | 285 ++- src/core/RegisterBase.cpp | 30 +- src/core/RegisterBase.h | 27 +- src/core/TargetDist.cpp | 16 +- src/core/Value.cpp | 254 +- src/core/Value.h | 57 +- src/core/WithCmd.h | 4 +- src/crystdistrib/BopsShortcut.cpp | 82 +- src/crystdistrib/DopsShortcut.cpp | 62 +- src/crystdistrib/Quaternion.cpp | 162 +- .../QuaternionBondProductMatrix.cpp | 315 ++- src/crystdistrib/QuaternionProductMatrix.cpp | 186 +- src/crystdistrib/RopsShortcut.cpp | 85 +- src/dimred/ArrangePoints.cpp | 228 +- .../ClassicalMultiDimensionalScaling.cpp | 44 +- src/dimred/PCA.cpp | 95 +- src/dimred/ProjectPoints.cpp | 172 +- src/dimred/SMACOF.cpp | 85 +- src/dimred/SketchMap.cpp | 127 +- src/dimred/SketchMapProjection.cpp | 44 +- src/drr/DRR.cpp | 41 +- src/drr/DRR.h | 49 +- src/drr/DynamicReferenceRestraining.cpp | 12 +- src/drr/colvar_UIestimator.h | 346 ++- src/drr/drrtool.cpp | 18 +- src/eds/EDS.cpp | 458 ++-- src/envsim/EnvironmentSimilarity.cpp | 223 +- src/fisst/FISST.cpp | 102 +- src/fisst/legendre_rule_fast.cpp | 55 +- src/fourier/FourierTransform.cpp | 86 +- src/function/Bessel.cpp | 23 +- src/function/Between.cpp | 36 +- src/function/Between.h | 4 +- src/function/Combine.cpp | 37 +- src/function/Combine.h | 3 +- src/function/Custom.cpp | 95 +- src/function/Ensemble.cpp | 90 +- src/function/FuncPathGeneral.cpp | 56 +- src/function/FuncPathMSD.cpp | 47 +- src/function/FuncSumHills.cpp | 262 +- src/function/Function.cpp | 13 +- src/function/Function.h | 7 +- src/function/FunctionOfMatrix.h | 278 ++- src/function/FunctionOfScalar.h | 88 +- src/function/FunctionOfVector.h | 233 +- src/function/FunctionShortcut.h | 69 +- src/function/FunctionTemplateBase.h | 65 +- src/function/Highest.cpp | 28 +- src/function/LessThan.cpp | 37 +- src/function/LessThan.h | 4 +- src/function/LocalEnsemble.cpp | 29 +- src/function/Moments.cpp | 74 +- src/function/MoreThan.cpp | 37 +- src/function/MoreThan.h | 4 +- src/function/Piecewise.cpp | 28 +- src/function/Product.cpp | 10 +- src/function/Sort.cpp | 38 +- src/function/Stats.cpp | 65 +- src/function/Sum.cpp | 17 +- src/funnel/FPS.cpp | 20 +- src/funnel/Funnel.cpp | 77 +- src/generic/Accumulate.cpp | 70 +- src/generic/Average.cpp | 49 +- src/generic/Collect.cpp | 114 +- src/generic/Committor.cpp | 40 +- src/generic/Constant.cpp | 106 +- src/generic/CreateMask.cpp | 104 +- src/generic/Debug.cpp | 42 +- src/generic/DumpAtoms.cpp | 149 +- src/generic/DumpDerivatives.cpp | 30 +- src/generic/DumpForces.cpp | 14 +- src/generic/DumpMassCharge.cpp | 37 +- src/generic/DumpPDB.cpp | 159 +- src/generic/DumpProjections.cpp | 14 +- src/generic/DumpVector.cpp | 71 +- src/generic/EffectiveEnergyDrift.cpp | 88 +- src/generic/EndPlumed.cpp | 6 +- src/generic/FitToTemplate.cpp | 94 +- src/generic/Flush.cpp | 9 +- src/generic/GatherReplicas.cpp | 74 +- src/generic/Include.cpp | 6 +- src/generic/MassChargeInput.cpp | 52 +- src/generic/Ones.cpp | 14 +- src/generic/PDB2Constant.cpp | 112 +- src/generic/Plumed.cpp | 207 +- src/generic/Print.cpp | 13 +- src/generic/PrintNDX.cpp | 62 +- src/generic/RandomExchanges.cpp | 10 +- src/generic/Read.cpp | 99 +- src/generic/ResetCell.cpp | 31 +- src/generic/Time.cpp | 10 +- src/generic/UpdateIf.cpp | 46 +- src/generic/WholeMolecules.cpp | 64 +- src/generic/WrapAround.cpp | 63 +- src/gridtools/ActionWithGrid.cpp | 14 +- src/gridtools/ConvertToFES.cpp | 32 +- src/gridtools/DumpGrid.cpp | 144 +- src/gridtools/EvaluateFunctionOnGrid.cpp | 47 +- src/gridtools/EvaluateGridFunction.cpp | 146 +- src/gridtools/EvaluateGridFunction.h | 4 +- src/gridtools/FindGridOptimum.cpp | 107 +- src/gridtools/FunctionOfGrid.h | 156 +- src/gridtools/Gradient.cpp | 44 +- src/gridtools/GridCoordinatesObject.cpp | 337 ++- src/gridtools/GridCoordinatesObject.h | 16 +- src/gridtools/GridSearch.h | 42 +- src/gridtools/Histogram.cpp | 52 +- src/gridtools/InterpolateGrid.cpp | 104 +- src/gridtools/Interpolator.cpp | 39 +- src/gridtools/KDE.cpp | 530 ++-- src/gridtools/KLEntropy.cpp | 16 +- src/gridtools/MultiColvarDensity.cpp | 89 +- src/gridtools/PairEntropies.cpp | 44 +- src/gridtools/PairEntropy.cpp | 49 +- src/gridtools/RDF.cpp | 84 +- src/gridtools/ReadGridInSetup.cpp | 163 +- src/isdb/CS2Backbone.cpp | 840 ++++--- src/isdb/Caliber.cpp | 115 +- src/isdb/EMMI.cpp | 503 ++-- src/isdb/EMMIVox.cpp | 442 ++-- src/isdb/FretEfficiency.cpp | 17 +- src/isdb/Jcoupling.cpp | 49 +- src/isdb/Metainference.cpp | 606 +++-- src/isdb/MetainferenceBase.cpp | 597 +++-- src/isdb/MetainferenceBase.h | 69 +- src/isdb/NOE.cpp | 101 +- src/isdb/PRE.cpp | 118 +- src/isdb/RDC.cpp | 134 +- src/isdb/Rescale.cpp | 130 +- src/isdb/SAXS.cpp | 1113 ++++++--- src/isdb/Select.cpp | 20 +- src/isdb/Selector.cpp | 6 +- src/isdb/Shadow.cpp | 36 +- src/landmarks/CollectFrames.cpp | 88 +- src/landmarks/FarthestPointSampling.cpp | 71 +- src/landmarks/LandmarkSelection.cpp | 90 +- src/landmarks/LogSumExp.cpp | 10 +- src/logmfd/LogMFD.cpp | 89 +- src/main/main.cpp | 20 +- src/mapping/AdaptivePath.cpp | 121 +- src/mapping/GeometricPath.cpp | 101 +- src/mapping/GeometricPathShortcut.cpp | 55 +- src/mapping/PCAVars.cpp | 159 +- src/mapping/Path.cpp | 139 +- src/mapping/PathDisplacements.cpp | 121 +- src/mapping/PathProjectionCalculator.cpp | 140 +- src/mapping/PathReparameterization.cpp | 132 +- src/mapping/PathTools.cpp | 511 +++- src/matrixtools/CovarianceMatrix.cpp | 30 +- src/matrixtools/Determinent.cpp | 6 +- src/matrixtools/DiagonalizeMatrix.cpp | 83 +- src/matrixtools/InvertMatrix.cpp | 44 +- src/matrixtools/MatrixOperationBase.cpp | 51 +- src/matrixtools/MatrixOperationBase.h | 3 +- src/matrixtools/MatrixTimesMatrix.cpp | 123 +- src/matrixtools/MatrixTimesVector.cpp | 207 +- src/matrixtools/OuterProduct.cpp | 125 +- src/matrixtools/TransposeMatrix.cpp | 110 +- src/matrixtools/Voronoi.cpp | 50 +- src/maze/Loss.cpp | 3 +- src/maze/Memetic.cpp | 3 +- src/maze/Memetic.h | 41 +- src/maze/Optimizer.cpp | 30 +- src/maze/Optimizer_Bias.cpp | 3 +- src/maze/Random_Acceleration_MD.cpp | 3 +- src/maze/Random_Walk.cpp | 3 +- src/maze/Simulated_Annealing.cpp | 18 +- src/maze/Steered_MD.cpp | 6 +- src/maze/Tools.h | 9 +- src/membranefusion/FusionPoreExpansionP.cpp | 206 +- src/membranefusion/FusionPoreNucleationP.cpp | 272 +-- src/membranefusion/MemFusionP.cpp | 202 +- src/multicolvar/AlphaBeta.cpp | 59 +- src/multicolvar/Angles.cpp | 70 +- src/multicolvar/CoordAngles.cpp | 55 +- src/multicolvar/Dihcor.cpp | 6 +- src/multicolvar/Distances.cpp | 139 +- src/multicolvar/DumpMultiColvar.cpp | 9 +- src/multicolvar/InPlaneDistances.cpp | 28 +- src/multicolvar/MFilterLess.cpp | 12 +- src/multicolvar/MFilterMore.cpp | 25 +- src/multicolvar/MultiColvarShortcuts.cpp | 131 +- src/multicolvar/Planes.cpp | 48 +- src/multicolvar/Torsions.cpp | 6 +- src/multicolvar/UWalls.cpp | 6 +- src/multicolvar/XAngle.cpp | 32 +- src/multicolvar/XYTorsions.cpp | 19 +- src/opes/ECVcustom.cpp | 94 +- src/opes/ECVlinear.cpp | 88 +- src/opes/ECVmultiThermal.cpp | 79 +- src/opes/ECVmultiThermalBaric.cpp | 229 +- src/opes/ECVumbrellasFile.cpp | 110 +- src/opes/ECVumbrellasLine.cpp | 113 +- src/opes/ExpansionCVs.cpp | 126 +- src/opes/ExpansionCVs.h | 16 +- src/opes/OPESexpanded.cpp | 448 ++-- src/opes/OPESmetad.cpp | 896 ++++--- src/pamm/HBPammMatrix.cpp | 232 +- src/pamm/PAMM.cpp | 59 +- src/piv/PIV.cpp | 116 +- src/pytorch/PytorchModel.cpp | 15 +- src/refdist/Difference.cpp | 41 +- src/refdist/Displacement.cpp | 50 +- src/refdist/EuclideanDistance.cpp | 27 +- src/refdist/Kernel.cpp | 180 +- src/refdist/MahalanobisDistance.cpp | 100 +- src/refdist/MatrixProductDiagonal.cpp | 88 +- src/refdist/NormalizedEuclideanDistance.cpp | 37 +- src/s2cm/S2ContactModel.cpp | 33 +- src/sasa/sasa_HASEL.cpp | 65 +- src/sasa/sasa_LCPO.cpp | 77 +- src/secondarystructure/AlphaRMSD.cpp | 65 +- src/secondarystructure/AntibetaRMSD.cpp | 112 +- src/secondarystructure/ParabetaRMSD.cpp | 114 +- .../SecondaryStructureRMSD.cpp | 191 +- src/setup/Load.cpp | 6 +- src/setup/Restart.cpp | 14 +- src/setup/Units.cpp | 56 +- src/sizeshape/mahadist.cpp | 176 +- src/sizeshape/pos_proj.cpp | 163 +- src/small_vector/small_vector.h | 2121 +++++++---------- src/sprint/Sprint.cpp | 45 +- src/symfunc/AngularTetra.cpp | 42 +- src/symfunc/AtomicSMAC.cpp | 48 +- src/symfunc/CoordShellVectorFunction.cpp | 50 +- src/symfunc/CoordinationNumbers.cpp | 79 +- src/symfunc/CylindricalHarmonic.cpp | 33 +- src/symfunc/Fccubic.cpp | 3 +- src/symfunc/HexaticParameter.cpp | 34 +- src/symfunc/LocalAverage.cpp | 52 +- src/symfunc/LocalCrystalinity.cpp | 33 +- src/symfunc/LocalSteinhardt.cpp | 82 +- src/symfunc/RadialTetra.cpp | 45 +- src/symfunc/SMAC.cpp | 64 +- src/symfunc/SphericalHarmonic.cpp | 114 +- src/symfunc/Steinhardt.cpp | 59 +- src/symfunc/ThreeBodyGFunctions.cpp | 127 +- src/tools/BiasRepresentation.cpp | 113 +- src/tools/Brent1DRootSearch.h | 73 +- src/tools/CheckInRange.cpp | 72 +- src/tools/Citations.cpp | 12 +- src/tools/Communicator.cpp | 165 +- src/tools/Communicator.h | 114 +- src/tools/ConjugateGradient.h | 26 +- src/tools/DLLoader.cpp | 16 +- src/tools/ERMSD.cpp | 16 +- src/tools/Exception.cpp | 40 +- src/tools/Exception.h | 21 +- src/tools/FileBase.cpp | 64 +- src/tools/FileBase.h | 4 +- src/tools/ForwardDecl.h | 3 +- src/tools/Grid.cpp | 476 +++- src/tools/Grid.h | 61 +- src/tools/HistogramBead.cpp | 123 +- src/tools/HistogramBead.h | 20 +- src/tools/IFile.cpp | 115 +- src/tools/KernelFunctions.cpp | 265 +- src/tools/KernelFunctions.h | 3 +- src/tools/Keywords.cpp | 446 +++- src/tools/Keywords.h | 54 +- src/tools/LatticeReduction.cpp | 83 +- src/tools/LeptonCall.cpp | 46 +- src/tools/LinkCells.cpp | 68 +- src/tools/Log.h | 3 +- src/tools/Matrix.h | 357 ++- src/tools/MergeVectorTools.h | 42 +- src/tools/Minimise1DBrent.h | 99 +- src/tools/MinimiseBase.h | 15 +- src/tools/MolDataClass.cpp | 482 ++-- src/tools/MultiValue.cpp | 66 +- src/tools/MultiValue.h | 30 +- src/tools/NeighborList.cpp | 21 +- src/tools/OFile.cpp | 124 +- src/tools/OpenMP.h | 7 +- src/tools/PDB.cpp | 570 +++-- src/tools/Pbc.cpp | 141 +- src/tools/Pbc.h | 20 +- src/tools/PlumedHandle.cpp | 24 +- src/tools/PlumedHandle.h | 6 +- src/tools/RMSD.cpp | 610 +++-- src/tools/RMSD.h | 86 +- src/tools/Random.cpp | 65 +- src/tools/Random.h | 10 +- src/tools/RootFindingBase.h | 4 +- src/tools/Stopwatch.cpp | 16 +- src/tools/Stopwatch.h | 35 +- src/tools/Subprocess.cpp | 72 +- src/tools/SwitchingFunction.cpp | 43 +- src/tools/Tensor.h | 88 +- src/tools/Tools.cpp | 257 +- src/tools/Tools.h | 85 +- src/tools/Tree.cpp | 29 +- src/tools/Tree.h | 3 +- src/tools/TypesafePtr.cpp | 8 +- src/tools/TypesafePtr.h | 92 +- src/tools/Units.cpp | 3 +- src/tools/Vector.h | 10 +- src/tools/h36.cpp | 103 +- src/valtools/Concatenate.cpp | 195 +- src/valtools/Flatten.cpp | 53 +- src/valtools/SelectComponents.cpp | 58 +- src/valtools/SelectWithMask.cpp | 176 +- src/valtools/VStack.cpp | 156 +- src/vatom/ArgsToVatom.cpp | 151 +- src/vatom/Center.cpp | 92 +- src/vatom/CenterShortcut.cpp | 75 +- src/vatom/FixedAtom.cpp | 22 +- src/vatom/Ghost.cpp | 22 +- src/ves/BF_Chebyshev.cpp | 9 +- src/ves/BF_Combined.cpp | 24 +- src/ves/BF_Cosine.cpp | 10 +- src/ves/BF_CubicBsplines.cpp | 23 +- src/ves/BF_Custom.cpp | 118 +- src/ves/BF_Fourier.cpp | 10 +- src/ves/BF_Gaussians.cpp | 24 +- src/ves/BF_Legendre.cpp | 16 +- src/ves/BF_Powers.cpp | 16 +- src/ves/BF_Sine.cpp | 10 +- src/ves/BF_Wavelets.cpp | 38 +- src/ves/BasisFunctions.cpp | 117 +- src/ves/BasisFunctions.h | 141 +- src/ves/CoeffsBase.cpp | 60 +- src/ves/CoeffsBase.h | 107 +- src/ves/CoeffsMatrix.cpp | 41 +- src/ves/CoeffsMatrix.h | 23 +- src/ves/CoeffsVector.cpp | 56 +- src/ves/CoeffsVector.h | 27 +- src/ves/FermiSwitchingFunction.cpp | 36 +- src/ves/GridIntegrationWeights.cpp | 13 +- src/ves/GridLinearInterpolation.cpp | 27 +- src/ves/GridLinearInterpolation.h | 3 +- src/ves/GridProjWeights.h | 21 +- src/ves/LinearBasisSetExpansion.cpp | 127 +- src/ves/LinearBasisSetExpansion.h | 112 +- src/ves/MD_LinearExpansionPES.cpp | 110 +- src/ves/Opt_Adam.cpp | 14 +- src/ves/Opt_BachAveragedSGD.cpp | 13 +- src/ves/Opt_Dummy.cpp | 6 +- src/ves/Opt_RobbinsMonroSGD.cpp | 3 +- src/ves/Optimizer.cpp | 180 +- src/ves/Optimizer.h | 186 +- src/ves/OutputBasisFunctions.cpp | 41 +- src/ves/OutputFesBias.cpp | 7 +- src/ves/OutputTargetDistribution.cpp | 27 +- src/ves/TD_Chi.cpp | 31 +- src/ves/TD_ChiSquared.cpp | 31 +- src/ves/TD_Custom.cpp | 44 +- src/ves/TD_Exponential.cpp | 19 +- src/ves/TD_ExponentiallyModifiedGaussian.cpp | 35 +- src/ves/TD_Gaussian.cpp | 33 +- src/ves/TD_GeneralizedExtremeValue.cpp | 30 +- src/ves/TD_GeneralizedNormal.cpp | 35 +- src/ves/TD_Grid.cpp | 34 +- src/ves/TD_LinearCombination.cpp | 43 +- src/ves/TD_Multicanonical.cpp | 74 +- src/ves/TD_MultithermalMultibaric.cpp | 38 +- src/ves/TD_ProductCombination.cpp | 34 +- src/ves/TD_ProductDistribution.cpp | 19 +- src/ves/TD_Uniform.cpp | 57 +- src/ves/TD_VonMises.cpp | 46 +- src/ves/TD_WellTempered.cpp | 3 +- src/ves/TargetDistribution.cpp | 68 +- src/ves/TargetDistribution.h | 125 +- src/ves/VesBias.cpp | 65 +- src/ves/VesBias.h | 266 ++- src/ves/VesDeltaF.cpp | 287 +-- src/ves/VesLinearExpansion.cpp | 23 +- src/ves/VesTools.cpp | 10 +- src/ves/VesTools.h | 14 +- src/ves/WaveletGrid.cpp | 41 +- src/volumes/ActionVolume.cpp | 138 +- src/volumes/ActionVolume.h | 4 +- src/volumes/Density.cpp | 9 +- src/volumes/VolumeAround.cpp | 61 +- src/volumes/VolumeBetweenContours.cpp | 105 +- src/volumes/VolumeCavity.cpp | 110 +- src/volumes/VolumeInCylinder.cpp | 64 +- src/volumes/VolumeInSphere.cpp | 35 +- src/volumes/VolumeShortcut.h | 46 +- src/volumes/VolumeTetrapore.cpp | 142 +- src/wham/Wham.cpp | 77 +- src/wham/WhamHistogram.cpp | 54 +- src/wham/WhamWeights.cpp | 29 +- src/wrapper/Plumed.h | 551 +++-- 545 files changed, 34537 insertions(+), 16698 deletions(-) diff --git a/.astyle.options b/.astyle.options index 0a17526e3b..5b9545ac1f 100644 --- a/.astyle.options +++ b/.astyle.options @@ -1 +1,13 @@ --n --indent=spaces=2 --keep-one-line-statements --keep-one-line-blocks +# long options can be written without the preceding '--' +suffix=none #equivalent to "-n" +style=attach +add-braces +indent=spaces=2 +break-one-line-headers + +# old options +#suffix=none +#indent=spaces=2 +#keep-one-line-statements +#keep-one-line-blocks +# end old options diff --git a/src/adjmat/AdjacencyMatrixBase.cpp b/src/adjmat/AdjacencyMatrixBase.cpp index 61d52a2fd0..1b3a953a7f 100644 --- a/src/adjmat/AdjacencyMatrixBase.cpp +++ b/src/adjmat/AdjacencyMatrixBase.cpp @@ -28,7 +28,8 @@ namespace PLMD { namespace adjmat { void AdjacencyMatrixBase::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords( keys ); keys.remove("ARG"); + ActionWithMatrix::registerKeywords( keys ); + keys.remove("ARG"); keys.add("atoms","GROUP","the atoms for which you would like to calculate the adjacency matrix"); keys.add("atoms","GROUPA",""); keys.add("atoms","GROUPB",""); @@ -53,68 +54,126 @@ AdjacencyMatrixBase::AdjacencyMatrixBase(const ActionOptions& ao): linkcells(comm), threecells(comm), maxcol(0), - natoms_per_list(0) -{ - std::vector shape(2); std::vector t; parseAtomList("GROUP", t ); + natoms_per_list(0) { + std::vector shape(2); + std::vector t; + parseAtomList("GROUP", t ); if( t.size()==0 ) { parseAtomList("ATOMS", t); - if( t.size()>0 ) warning("using depracated syntax for contact matrix. You are strongly recommended to use GROUP instead of ATOMS"); + if( t.size()>0 ) { + warning("using depracated syntax for contact matrix. You are strongly recommended to use GROUP instead of ATOMS"); + } } if( t.size()==0 ) { - std::vector ta; parseAtomList("GROUPA",ta); - if( ta.size()==0 && getName()=="HBOND_MATRIX") parseAtomList("DONORS",ta); - std::vector tb; parseAtomList("GROUPB",tb); - if( tb.size()==0 && getName()=="HBOND_MATRIX") parseAtomList("ACCEPTORS",tb); - if( ta.size()==0 || tb.size()==0 ) error("no atoms have been specified in input"); + std::vector ta; + parseAtomList("GROUPA",ta); + if( ta.size()==0 && getName()=="HBOND_MATRIX") { + parseAtomList("DONORS",ta); + } + std::vector tb; + parseAtomList("GROUPB",tb); + if( tb.size()==0 && getName()=="HBOND_MATRIX") { + parseAtomList("ACCEPTORS",tb); + } + if( ta.size()==0 || tb.size()==0 ) { + error("no atoms have been specified in input"); + } // Create list of tasks log.printf(" atoms in GROUPA "); - for(unsigned i=0; i tc; parseAtomList("GROUPC",tc); - if( tc.size()==0 ) error("no atoms in GROUPC specified"); - log.printf(" atoms in GROUPC "); setupThirdAtomBlock( tc, t ); + std::vector tc; + parseAtomList("GROUPC",tc); + if( tc.size()==0 ) { + error("no atoms in GROUPC specified"); + } + log.printf(" atoms in GROUPC "); + setupThirdAtomBlock( tc, t ); } else if( keywords.exists("BRIDGING_ATOMS") ) { - std::vector tc; parseAtomList("BRIDGING_ATOMS",tc); - if( tc.size()==0 ) error("no BRIDGING_ATOMS specified"); - log.printf(" bridging atoms are "); setupThirdAtomBlock( tc, t ); + std::vector tc; + parseAtomList("BRIDGING_ATOMS",tc); + if( tc.size()==0 ) { + error("no BRIDGING_ATOMS specified"); + } + log.printf(" bridging atoms are "); + setupThirdAtomBlock( tc, t ); } else if( keywords.exists("HYDROGENS") ) { - std::vector tc; parseAtomList("HYDROGENS",tc); - if( tc.size()==0 ) error("no HYDROGEN atoms specified"); - log.printf(" hydrogen atoms are "); setupThirdAtomBlock( tc, t ); + std::vector tc; + parseAtomList("HYDROGENS",tc); + if( tc.size()==0 ) { + error("no HYDROGEN atoms specified"); + } + log.printf(" hydrogen atoms are "); + setupThirdAtomBlock( tc, t ); } else if( keywords.exists("BACKGROUND_ATOMS") ) { - std::vector tc; parseAtomList("BACKGROUND_ATOMS",tc); - if( tc.size()==0 ) error("no ATOMS atoms specified"); - log.printf(" atoms for background density are "); setupThirdAtomBlock( tc, t ); + std::vector tc; + parseAtomList("BACKGROUND_ATOMS",tc); + if( tc.size()==0 ) { + error("no ATOMS atoms specified"); + } + log.printf(" atoms for background density are "); + setupThirdAtomBlock( tc, t ); } // Request the atoms from the ActionAtomistic - requestAtoms( t ); parseFlag("COMPONENTS",components); parseFlag("NOPBC",nopbc); - if( !components ) { addValue( shape ); setNotPeriodic(); } - else { addComponent( "w", shape ); componentIsNotPeriodic("w"); } + requestAtoms( t ); + parseFlag("COMPONENTS",components); + parseFlag("NOPBC",nopbc); + if( !components ) { + addValue( shape ); + setNotPeriodic(); + } else { + addComponent( "w", shape ); + componentIsNotPeriodic("w"); + } getPntrToComponent(0)->setDerivativeIsZeroWhenValueIsZero(); // Stuff for neighbor list - parse("NL_CUTOFF",nl_cut); nl_cut2=nl_cut*nl_cut; parse("NL_STRIDE",nl_stride); - if( nl_cut==0 && nl_stride>1 ) error("NL_CUTOFF must be set if NL_STRIDE is set greater than 1"); - if( nl_cut>0 ) log.printf(" using neighbor list with cutoff %f. List is updated every %u steps.\n",nl_cut,nl_stride); + parse("NL_CUTOFF",nl_cut); + nl_cut2=nl_cut*nl_cut; + parse("NL_STRIDE",nl_stride); + if( nl_cut==0 && nl_stride>1 ) { + error("NL_CUTOFF must be set if NL_STRIDE is set greater than 1"); + } + if( nl_cut>0 ) { + log.printf(" using neighbor list with cutoff %f. List is updated every %u steps.\n",nl_cut,nl_stride); + } if( components ) { - addComponent( "x", shape ); componentIsNotPeriodic("x"); - addComponent( "y", shape ); componentIsNotPeriodic("y"); - addComponent( "z", shape ); componentIsNotPeriodic("z"); + addComponent( "x", shape ); + componentIsNotPeriodic("x"); + addComponent( "y", shape ); + componentIsNotPeriodic("y"); + addComponent( "z", shape ); + componentIsNotPeriodic("z"); } log<<" Bibliography "<& tc, std::vector& t ) { - threeblocks.resize( tc.size() ); unsigned base=t.size(); - for(unsigned i=0; isetSymmetric( true ); - if( nl_cut>0 && lcut>nl_cut ) error("D_MAX for switching functions should be shorter than neighbor list cutoff"); + if( read_one_group && symmetric ) { + getPntrToComponent(0)->setSymmetric( true ); + } + if( nl_cut>0 && lcut>nl_cut ) { + error("D_MAX for switching functions should be shorter than neighbor list cutoff"); + } - if( tcut<0 ) tcut=lcut; - if( nl_cut>0 ) linkcells.setCutoff( nl_cut ); else linkcells.setCutoff( lcut ); - if( linkcells.getCutoff()::max() ) log.printf(" set link cell cutoff to %f \n", linkcells.getCutoff() ); + if( tcut<0 ) { + tcut=lcut; + } + if( nl_cut>0 ) { + linkcells.setCutoff( nl_cut ); + } else { + linkcells.setCutoff( lcut ); + } + if( linkcells.getCutoff()::max() ) { + log.printf(" set link cell cutoff to %f \n", linkcells.getCutoff() ); + } threecells.setCutoff( tcut ); } void AdjacencyMatrixBase::prepare() { - ActionWithVector::prepare(); neighbour_list_updated=false; + ActionWithVector::prepare(); + neighbour_list_updated=false; } void AdjacencyMatrixBase::updateNeighbourList() { @@ -149,7 +226,9 @@ void AdjacencyMatrixBase::updateNeighbourList() { if( getStep()%nl_stride==0 ) { // Build the link cells std::vector ltmp_pos( ablocks.size() ); - for(unsigned i=0; igetConstPntrToComponent(0)->getShape()[0] ) nt=getConstPntrToComponent(0)->getShape()[0]/stride/10; - if( nt==0 ) nt=1; + if( nt*stride*10>getConstPntrToComponent(0)->getShape()[0] ) { + nt=getConstPntrToComponent(0)->getShape()[0]/stride/10; + } + if( nt==0 ) { + nt=1; + } // Create a vector from the input set of tasks std::vector & pTaskList( getListOfActiveTasks(this) ); @@ -170,10 +257,14 @@ void AdjacencyMatrixBase::updateNeighbourList() { { // Get the number of tasks we have to deal with unsigned ntasks=getConstPntrToComponent(0)->getShape()[0]; - if( nl_stride==1 ) ntasks=pTaskList.size(); + if( nl_stride==1 ) { + ntasks=pTaskList.size(); + } // Build a tempory nlist so we can do omp parallelism std::vector omp_nlist; - if( nt>1 ) omp_nlist.resize( nlist.size(), 0 ); + if( nt>1 ) { + omp_nlist.resize( nlist.size(), 0 ); + } // Now run over all atoms and construct the link cells std::vector t_atoms( 1+ablocks.size() ); std::vector indices( 1+ablocks.size() ), cells_required( linkcells.getNumberOfCells() ); @@ -183,29 +274,52 @@ void AdjacencyMatrixBase::updateNeighbourList() { unsigned ncells_required=0; linkcells.addRequiredCells( linkcells.findMyCell( ActionAtomistic::getPosition(pTaskList[i]) ), ncells_required, cells_required ); // Now get the indices of the atoms in the link cells positions - unsigned natoms=1; indices[0]=pTaskList[i]; + unsigned natoms=1; + indices[0]=pTaskList[i]; linkcells.retrieveAtomsInCells( ncells_required, cells_required, natoms, indices ); if( nl_stride==1 ) { - if( nt>1 ) omp_nlist[indices[0]]=0; else nlist[indices[0]] = 0; + if( nt>1 ) { + omp_nlist[indices[0]]=0; + } else { + nlist[indices[0]] = 0; + } unsigned lstart = getConstPntrToComponent(0)->getShape()[0] + indices[0]*(1+natoms_per_list); for(unsigned j=0; j1 ) { omp_nlist[ lstart + omp_nlist[indices[0]] ] = indices[j]; omp_nlist[indices[0]]++; } - else { nlist[ lstart + nlist[indices[0]] ] = indices[j]; nlist[indices[0]]++; } + if( nt>1 ) { + omp_nlist[ lstart + omp_nlist[indices[0]] ] = indices[j]; + omp_nlist[indices[0]]++; + } else { + nlist[ lstart + nlist[indices[0]] ] = indices[j]; + nlist[indices[0]]++; + } } } else { // Get the positions of all the atoms in the link cells relative to the central atom - for(unsigned j=0; j1 ) omp_nlist[indices[0]] = 0; else nlist[indices[0]] = 0; + if( nt>1 ) { + omp_nlist[indices[0]] = 0; + } else { + nlist[indices[0]] = 0; + } unsigned lstart = getConstPntrToComponent(0)->getShape()[0] + indices[0]*(1+natoms_per_list); for(unsigned j=0; j1 ) { omp_nlist[ lstart + omp_nlist[indices[0]] ] = indices[j]; omp_nlist[indices[0]]++; } - else { nlist[ lstart + nlist[indices[0]] ] = indices[j]; nlist[indices[0]]++; } + if( nt>1 ) { + omp_nlist[ lstart + omp_nlist[indices[0]] ] = indices[j]; + omp_nlist[indices[0]]++; + } else { + nlist[ lstart + nlist[indices[0]] ] = indices[j]; + nlist[indices[0]]++; + } } } @@ -214,15 +328,21 @@ void AdjacencyMatrixBase::updateNeighbourList() { // Gather OMP stuff #pragma omp critical if(nt>1) { - for(unsigned i=0; igetShape()[0] + pTaskList[i]*(1+natoms_per_list); - for(unsigned j=0; j0 ) { std::vector ltmp_pos2( threeblocks.size() ); @@ -234,12 +354,16 @@ void AdjacencyMatrixBase::updateNeighbourList() { // And finally work out maximum number of columns to use maxcol = nlist[0]; for(unsigned i=1; igetShape()[0]; ++i) { - if( nlist[i]>maxcol ) maxcol = nlist[i]; + if( nlist[i]>maxcol ) { + maxcol = nlist[i]; + } } } void AdjacencyMatrixBase::getAdditionalTasksRequired( ActionWithVector* action, std::vector& atasks ) { - if( action==this ) return; + if( action==this ) { + return; + } // Update the neighbour list updateNeighbourList(); @@ -250,69 +374,112 @@ void AdjacencyMatrixBase::getAdditionalTasksRequired( ActionWithVector* action, for(unsigned j=0; j & indices ) const { - unsigned natoms=nlist[current]; indices[0]=current; - unsigned lstart = getConstPntrToComponent(0)->getShape()[0] + current*(1+natoms_per_list); plumed_dbg_assert( nlist[lstart]==current ); - for(unsigned i=1; igetShape()[0] + current*(1+natoms_per_list); + plumed_dbg_assert( nlist[lstart]==current ); + for(unsigned i=1; i & indices, MultiValue& myvals ) const { // Now retrieve bookeeping arrays - if( indices.size()!=(1+ablocks.size()+threeblocks.size()) ) indices.resize( 1+ablocks.size()+threeblocks.size() ); + if( indices.size()!=(1+ablocks.size()+threeblocks.size()) ) { + indices.resize( 1+ablocks.size()+threeblocks.size() ); + } // Now get the positions unsigned natoms=retrieveNeighbours( current, indices ); - unsigned ntwo_atoms=natoms; myvals.setSplitIndex( ntwo_atoms ); + unsigned ntwo_atoms=natoms; + myvals.setSplitIndex( ntwo_atoms ); // Now retrieve everything for the third atoms if( threeblocks.size()>0 ) { - unsigned ncells_required=0; std::vector cells_required( threecells.getNumberOfCells() ); + unsigned ncells_required=0; + std::vector cells_required( threecells.getNumberOfCells() ); threecells.addRequiredCells( threecells.findMyCell( ActionAtomistic::getPosition(current) ), ncells_required, cells_required ); threecells.retrieveAtomsInCells( ncells_required, cells_required, natoms, indices ); } myvals.setNumberOfIndices( natoms ); // Apply periodic boundary conditions to atom positions - std::vector > & t_atoms( myvals.getFirstAtomDerivativeVector() ); if( t_atoms.size()!=1 ) t_atoms.resize(1); - if( t_atoms[0].size() > & t_atoms( myvals.getFirstAtomDerivativeVector() ); + if( t_atoms.size()!=1 ) { + t_atoms.resize(1); + } + if( t_atoms[0].size() & atoms( myvals.getAtomVector() ); - if( atoms.size()getPositionInStream(); myvals.setValue( w_ind, weight ); - if( fabs(weight)getPositionInStream(); + myvals.setValue( w_ind, weight ); + if( fabs(weight) & indices( myvals.getIndices() ); for(unsigned i=myvals.getSplitIndex(); igetPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); - matrix_indices[nmat_ind+0]=3*index2+0; matrix_indices[nmat_ind+1]=3*index2+1; matrix_indices[nmat_ind+2]=3*index2+2; + matrix_indices[nmat_ind+0]=3*index2+0; + matrix_indices[nmat_ind+1]=3*index2+1; + matrix_indices[nmat_ind+2]=3*index2+2; myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind+3 ); } @@ -322,42 +489,81 @@ void AdjacencyMatrixBase::performTask( const std::string& controller, const unsi unsigned y_index = getConstPntrToComponent(2)->getPositionInStream(); unsigned z_index = getConstPntrToComponent(3)->getPositionInStream(); Vector atom = myvals.getAtomVector()[index2]; - myvals.setValue( x_index, atom[0] ); myvals.setValue( y_index, atom[1] ); myvals.setValue( z_index, atom[2] ); + myvals.setValue( x_index, atom[0] ); + myvals.setValue( y_index, atom[1] ); + myvals.setValue( z_index, atom[2] ); if( !doNotCalculateDerivatives() ) { - myvals.addDerivative( x_index, 3*index1+0, -1 ); myvals.addDerivative( x_index, 3*index2+0, +1 ); - myvals.addDerivative( x_index, 3*index1+1, 0 ); myvals.addDerivative( x_index, 3*index2+1, 0 ); - myvals.addDerivative( x_index, 3*index1+2, 0 ); myvals.addDerivative( x_index, 3*index2+2, 0 ); - myvals.addDerivative( y_index, 3*index1+0, 0 ); myvals.addDerivative( y_index, 3*index2+0, 0 ); - myvals.addDerivative( y_index, 3*index1+1, -1 ); myvals.addDerivative( y_index, 3*index2+1, +1 ); - myvals.addDerivative( y_index, 3*index1+2, 0 ); myvals.addDerivative( y_index, 3*index2+2, 0 ); - myvals.addDerivative( z_index, 3*index1+0, 0 ); myvals.addDerivative( z_index, 3*index2+0, 0 ); - myvals.addDerivative( z_index, 3*index1+1, 0 ); myvals.addDerivative( z_index, 3*index2+1, 0 ); - myvals.addDerivative( z_index, 3*index1+2, -1 ); myvals.addDerivative( z_index, 3*index2+2, +1 ); + myvals.addDerivative( x_index, 3*index1+0, -1 ); + myvals.addDerivative( x_index, 3*index2+0, +1 ); + myvals.addDerivative( x_index, 3*index1+1, 0 ); + myvals.addDerivative( x_index, 3*index2+1, 0 ); + myvals.addDerivative( x_index, 3*index1+2, 0 ); + myvals.addDerivative( x_index, 3*index2+2, 0 ); + myvals.addDerivative( y_index, 3*index1+0, 0 ); + myvals.addDerivative( y_index, 3*index2+0, 0 ); + myvals.addDerivative( y_index, 3*index1+1, -1 ); + myvals.addDerivative( y_index, 3*index2+1, +1 ); + myvals.addDerivative( y_index, 3*index1+2, 0 ); + myvals.addDerivative( y_index, 3*index2+2, 0 ); + myvals.addDerivative( z_index, 3*index1+0, 0 ); + myvals.addDerivative( z_index, 3*index2+0, 0 ); + myvals.addDerivative( z_index, 3*index1+1, 0 ); + myvals.addDerivative( z_index, 3*index2+1, 0 ); + myvals.addDerivative( z_index, 3*index1+2, -1 ); + myvals.addDerivative( z_index, 3*index2+2, +1 ); for(unsigned k=0; k<3; ++k) { // Update dynamic lists for central atom - myvals.updateIndex( x_index, 3*index1+k ); myvals.updateIndex( y_index, 3*index1+k ); myvals.updateIndex( z_index, 3*index1+k ); + myvals.updateIndex( x_index, 3*index1+k ); + myvals.updateIndex( y_index, 3*index1+k ); + myvals.updateIndex( z_index, 3*index1+k ); // Update dynamic lists for bonded atom - myvals.updateIndex( x_index, 3*index2+k ); myvals.updateIndex( y_index, 3*index2+k ); myvals.updateIndex( z_index, 3*index2+k ); + myvals.updateIndex( x_index, 3*index2+k ); + myvals.updateIndex( y_index, 3*index2+k ); + myvals.updateIndex( z_index, 3*index2+k ); } // Add derivatives of virial unsigned base = 3*getNumberOfAtoms(); // Virial for x - myvals.addDerivative( x_index, base+0, -atom[0] ); myvals.addDerivative( x_index, base+3, -atom[1] ); myvals.addDerivative( x_index, base+6, -atom[2] ); - myvals.addDerivative( x_index, base+1, 0 ); myvals.addDerivative( x_index, base+4, 0 ); myvals.addDerivative( x_index, base+7, 0 ); - myvals.addDerivative( x_index, base+2, 0 ); myvals.addDerivative( x_index, base+5, 0 ); myvals.addDerivative( x_index, base+8, 0 ); + myvals.addDerivative( x_index, base+0, -atom[0] ); + myvals.addDerivative( x_index, base+3, -atom[1] ); + myvals.addDerivative( x_index, base+6, -atom[2] ); + myvals.addDerivative( x_index, base+1, 0 ); + myvals.addDerivative( x_index, base+4, 0 ); + myvals.addDerivative( x_index, base+7, 0 ); + myvals.addDerivative( x_index, base+2, 0 ); + myvals.addDerivative( x_index, base+5, 0 ); + myvals.addDerivative( x_index, base+8, 0 ); // Virial for y - myvals.addDerivative( y_index, base+0, 0 ); myvals.addDerivative( y_index, base+3, 0 ); myvals.addDerivative( y_index, base+6, 0 ); - myvals.addDerivative( y_index, base+1, -atom[0] ); myvals.addDerivative( y_index, base+4, -atom[1] ); myvals.addDerivative( y_index, base+7, -atom[2] ); - myvals.addDerivative( y_index, base+2, 0 ); myvals.addDerivative( y_index, base+5, 0 ); myvals.addDerivative( y_index, base+8, 0 ); + myvals.addDerivative( y_index, base+0, 0 ); + myvals.addDerivative( y_index, base+3, 0 ); + myvals.addDerivative( y_index, base+6, 0 ); + myvals.addDerivative( y_index, base+1, -atom[0] ); + myvals.addDerivative( y_index, base+4, -atom[1] ); + myvals.addDerivative( y_index, base+7, -atom[2] ); + myvals.addDerivative( y_index, base+2, 0 ); + myvals.addDerivative( y_index, base+5, 0 ); + myvals.addDerivative( y_index, base+8, 0 ); // Virial for z - myvals.addDerivative( z_index, base+0, 0 ); myvals.addDerivative( z_index, base+3, 0 ); myvals.addDerivative( z_index, base+6, 0 ); - myvals.addDerivative( z_index, base+1, 0 ); myvals.addDerivative( z_index, base+4, 0 ); myvals.addDerivative( z_index, base+7, 0 ); - myvals.addDerivative( z_index, base+2, -atom[0] ); myvals.addDerivative( z_index, base+5, -atom[1] ); myvals.addDerivative( z_index, base+8, -atom[2] ); - for(unsigned k=0; k<9; ++k) { myvals.updateIndex( x_index, base+k ); myvals.updateIndex( y_index, base+k ); myvals.updateIndex( z_index, base+k ); } + myvals.addDerivative( z_index, base+0, 0 ); + myvals.addDerivative( z_index, base+3, 0 ); + myvals.addDerivative( z_index, base+6, 0 ); + myvals.addDerivative( z_index, base+1, 0 ); + myvals.addDerivative( z_index, base+4, 0 ); + myvals.addDerivative( z_index, base+7, 0 ); + myvals.addDerivative( z_index, base+2, -atom[0] ); + myvals.addDerivative( z_index, base+5, -atom[1] ); + myvals.addDerivative( z_index, base+8, -atom[2] ); + for(unsigned k=0; k<9; ++k) { + myvals.updateIndex( x_index, base+k ); + myvals.updateIndex( y_index, base+k ); + myvals.updateIndex( z_index, base+k ); + } for(unsigned k=1; k<4; ++k) { unsigned nmat = getConstPntrToComponent(k)->getPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); - matrix_indices[nmat_ind+0]=3*index2+0; matrix_indices[nmat_ind+1]=3*index2+1; matrix_indices[nmat_ind+2]=3*index2+2; + matrix_indices[nmat_ind+0]=3*index2+0; + matrix_indices[nmat_ind+1]=3*index2+1; + matrix_indices[nmat_ind+2]=3*index2+2; myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind+3 ); } } @@ -365,7 +571,9 @@ void AdjacencyMatrixBase::performTask( const std::string& controller, const unsi } void AdjacencyMatrixBase::runEndOfRowJobs( const unsigned& ind, const std::vector & indices, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } for(int k=0; kgetPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); @@ -382,8 +590,11 @@ void AdjacencyMatrixBase::runEndOfRowJobs( const unsigned& ind, const std::vecto nmat_ind+=3; } unsigned virbase = 3*getNumberOfAtoms(); - for(unsigned i=0; i<9; ++i) matrix_indices[nmat_ind+i]=virbase+i; - nmat_ind+=9; plumed_dbg_massert( nmat_ind<=3*getNumberOfAtoms() + 9, "found too many derivatives in " + getLabel() ); + for(unsigned i=0; i<9; ++i) { + matrix_indices[nmat_ind+i]=virbase+i; + } + nmat_ind+=9; + plumed_dbg_massert( nmat_ind<=3*getNumberOfAtoms() + 9, "found too many derivatives in " + getLabel() ); myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind ); } } diff --git a/src/adjmat/AdjacencyMatrixBase.h b/src/adjmat/AdjacencyMatrixBase.h index e529688d8d..167ec34cc8 100644 --- a/src/adjmat/AdjacencyMatrixBase.h +++ b/src/adjmat/AdjacencyMatrixBase.h @@ -50,7 +50,9 @@ class AdjacencyMatrixBase : public ActionWithMatrix { public: static void registerKeywords( Keywords& keys ); explicit AdjacencyMatrixBase(const ActionOptions&); - bool isAdjacencyMatrix() const override { return true; } + bool isAdjacencyMatrix() const override { + return true; + } unsigned getNumberOfDerivatives() override ; unsigned getNumberOfColumns() const override; void prepare() override; @@ -72,9 +74,14 @@ Vector AdjacencyMatrixBase::getPosition( const unsigned& indno, MultiValue& myva inline void AdjacencyMatrixBase::addAtomDerivatives( const unsigned& indno, const Vector& der, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() ) return; - plumed_dbg_assert( indno<2 ); unsigned index = myvals.getTaskIndex(); - if( indno==1 ) index = myvals.getSecondTaskIndex(); + if( doNotCalculateDerivatives() ) { + return; + } + plumed_dbg_assert( indno<2 ); + unsigned index = myvals.getTaskIndex(); + if( indno==1 ) { + index = myvals.getSecondTaskIndex(); + } unsigned w_index = getConstPntrToComponent(0)->getPositionInStream(); myvals.addDerivative( w_index, 3*index+0, der[0] ); myvals.addDerivative( w_index, 3*index+1, der[1] ); @@ -83,7 +90,9 @@ void AdjacencyMatrixBase::addAtomDerivatives( const unsigned& indno, const Vecto inline void AdjacencyMatrixBase::addThirdAtomDerivatives( const unsigned& indno, const Vector& der, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } unsigned index = myvals.getIndices()[ indno + myvals.getSplitIndex() ]; unsigned w_index = getConstPntrToComponent(0)->getPositionInStream(); myvals.addDerivative( w_index, 3*index+0, der[0] ); @@ -93,7 +102,9 @@ void AdjacencyMatrixBase::addThirdAtomDerivatives( const unsigned& indno, const inline void AdjacencyMatrixBase::addBoxDerivatives( const Tensor& vir, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } unsigned nbase = 3*getNumberOfAtoms(); unsigned w_index = getConstPntrToComponent(0)->getPositionInStream(); myvals.addDerivative( w_index, nbase+0, vir(0,0) ); diff --git a/src/adjmat/Bridge.cpp b/src/adjmat/Bridge.cpp index d018fb07b2..63b8540c1f 100644 --- a/src/adjmat/Bridge.cpp +++ b/src/adjmat/Bridge.cpp @@ -54,18 +54,30 @@ void Bridge::registerKeywords(Keywords& keys) { "group A"); keys.add("optional","SWITCHB","The switchingfunction on the distance between the bridging atoms and the atoms in " "group B"); - keys.needsAction("BRIDGE_MATRIX"); keys.needsAction("SUM"); + keys.needsAction("BRIDGE_MATRIX"); + keys.needsAction("SUM"); keys.setValueDescription("the number of bridging atoms between the two groups"); } Bridge::Bridge(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Need to read in switch - std::string s_inp, sfinput; parse("SWITCH",sfinput); if( sfinput.length()>0 ) s_inp += "SWITCH={" + sfinput +"} "; - std::string sfinputa; parse("SWITCHA",sfinputa); if( sfinputa.length()>0 ) s_inp += "SWITCHA={" + sfinputa +"} "; - std::string sfinputb; parse("SWITCHB",sfinputb); if( sfinputb.length()>0 ) s_inp += "SWITCHB={" + sfinputb +"} "; + std::string s_inp, sfinput; + parse("SWITCH",sfinput); + if( sfinput.length()>0 ) { + s_inp += "SWITCH={" + sfinput +"} "; + } + std::string sfinputa; + parse("SWITCHA",sfinputa); + if( sfinputa.length()>0 ) { + s_inp += "SWITCHA={" + sfinputa +"} "; + } + std::string sfinputb; + parse("SWITCHB",sfinputb); + if( sfinputb.length()>0 ) { + s_inp += "SWITCHB={" + sfinputb +"} "; + } // Create the matrix object readInputLine( getShortcutLabel() + "_mat: BRIDGE_MATRIX " + s_inp + convertInputLineToString() ); // Add all the elements of the matrix together diff --git a/src/adjmat/BridgeMatrix.cpp b/src/adjmat/BridgeMatrix.cpp index 7d049a8874..9d98b3e2c8 100644 --- a/src/adjmat/BridgeMatrix.cpp +++ b/src/adjmat/BridgeMatrix.cpp @@ -83,23 +83,37 @@ void BridgeMatrix::registerKeywords( Keywords& keys ) { BridgeMatrix::BridgeMatrix(const ActionOptions&ao): Action(ao), - AdjacencyMatrixBase(ao) -{ - bool oneswitch; std::string sfinput,errors; parse("SWITCH",sfinput); + AdjacencyMatrixBase(ao) { + bool oneswitch; + std::string sfinput,errors; + parse("SWITCH",sfinput); if( sfinput.length()>0 ) { - sf1.set(sfinput,errors); oneswitch=true; - if( errors.length()!=0 ) error("problem reading SWITCH keyword : " + errors ); + sf1.set(sfinput,errors); + oneswitch=true; + if( errors.length()!=0 ) { + error("problem reading SWITCH keyword : " + errors ); + } sf2.set(sfinput,errors); - if( errors.length()!=0 ) error("problem reading SWITCH keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading SWITCH keyword : " + errors ); + } } else { parse("SWITCHA",sfinput); if(sfinput.length()>0) { - sf1.set(sfinput,errors); oneswitch=false; - if( errors.length()!=0 ) error("problem reading SWITCHA keyword : " + errors ); - sfinput.clear(); parse("SWITCHB",sfinput); - if(sfinput.length()==0) error("found SWITCHA keyword without SWITCHB"); + sf1.set(sfinput,errors); + oneswitch=false; + if( errors.length()!=0 ) { + error("problem reading SWITCHA keyword : " + errors ); + } + sfinput.clear(); + parse("SWITCHB",sfinput); + if(sfinput.length()==0) { + error("found SWITCHA keyword without SWITCHB"); + } sf2.set(sfinput,errors); - if( errors.length()!=0 ) error("problem reading SWITCHB keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading SWITCHB keyword : " + errors ); + } } else { error("missing definition of switching functions"); } @@ -115,12 +129,25 @@ BridgeMatrix::BridgeMatrix(const ActionOptions&ao): } double BridgeMatrix::calculateWeight( const Vector& pos1, const Vector& pos2, const unsigned& natoms, MultiValue& myvals ) const { - double tot=0; if( pos2.modulo2()0 ) { switchingFunction.set( input, errors ); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } } else { - double r_0=-1.0, d_0; int nn, mm; - parse("NN",nn); parse("MM",mm); - parse("R_0",r_0); parse("D_0",d_0); - if( r_0<0.0 ) error("you must set a value for R_0"); + double r_0=-1.0, d_0; + int nn, mm; + parse("NN",nn); + parse("MM",mm); + parse("R_0",r_0); + parse("D_0",d_0); + if( r_0<0.0 ) { + error("you must set a value for R_0"); + } switchingFunction.set(nn,mm,r_0,d_0); } // And set the link cell cutoff @@ -109,11 +119,18 @@ ContactMatrix::ContactMatrix( const ActionOptions& ao ): } double ContactMatrix::calculateWeight( const Vector& pos1, const Vector& pos2, const unsigned& natoms, MultiValue& myvals ) const { - Vector distance = pos2; double mod2 = distance.modulo2(); - if( mod2 grp_str; std::string atomsstr=""; - std::vector atomsvec; parseVector("ATOMS",atomsvec); + ActionShortcut(ao) { + std::vector grp_str; + std::string atomsstr=""; + std::vector atomsvec; + parseVector("ATOMS",atomsvec); if( atomsvec.size()>0 ) { for(unsigned i=0; i( atomsvec[i] ); - if( gg ) grp_str.push_back( atomsvec[i] ); + if( gg ) { + grp_str.push_back( atomsvec[i] ); + } } if( grp_str.size()!=atomsvec.size() ) { grp_str.resize(0); - atomsstr = " ATOMS=" + atomsvec[0]; for(unsigned i=1; i9 ) error("cannot handle more than 9 groups"); - if( grp_str.size()==0 ) { readInputLine( getShortcutLabel() + ": CONTACT_MATRIX_PROPER " + atomsstr + " " + convertInputLineToString() ); return; } + if( grp_str.size()>9 ) { + error("cannot handle more than 9 groups"); + } + if( grp_str.size()==0 ) { + readInputLine( getShortcutLabel() + ": CONTACT_MATRIX_PROPER " + atomsstr + " " + convertInputLineToString() ); + return; + } for(unsigned i=0; ij ) join_matrices += " MATRIX" + inum + jnum + "=" + getShortcutLabel() + inum + jnum; - else join_matrices += " MATRIX" + inum + jnum + "=" + getShortcutLabel() + inum + jnum; + std::string jnum; + Tools::convert(j+1,jnum); + if( i>j ) { + join_matrices += " MATRIX" + inum + jnum + "=" + getShortcutLabel() + inum + jnum; + } else { + join_matrices += " MATRIX" + inum + jnum + "=" + getShortcutLabel() + inum + jnum; + } } } readInputLine( join_matrices ); diff --git a/src/adjmat/DistanceMatrix.cpp b/src/adjmat/DistanceMatrix.cpp index e224f2ee84..3d097bb347 100644 --- a/src/adjmat/DistanceMatrix.cpp +++ b/src/adjmat/DistanceMatrix.cpp @@ -58,8 +58,7 @@ void DistanceMatrix::registerKeywords( Keywords& keys ) { DistanceMatrix::DistanceMatrix( const ActionOptions& ao ): Action(ao), - AdjacencyMatrixBase(ao) -{ + AdjacencyMatrixBase(ao) { // And set the link cell cutoff log.printf(" weight is distance between atoms \n"); parse("CUTOFF",cutoff); @@ -72,7 +71,8 @@ DistanceMatrix::DistanceMatrix( const ActionOptions& ao ): } double DistanceMatrix::calculateWeight( const Vector& pos1, const Vector& pos2, const unsigned& natoms, MultiValue& myvals ) const { - Vector distance = pos2; double mod = distance.modulo(); + Vector distance = pos2; + double mod = distance.modulo(); if( cutoff<0 || modgetLabel()!=(getPntrToArgument(0)->getPntrToAction())->getLabel(); } + unsigned getNumberOfColumns() const override { + return number; + } + bool canBeAfterInChain( ActionWithVector* av ) { + return av->getLabel()!=(getPntrToArgument(0)->getPntrToAction())->getLabel(); + } void setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const ; void performTask( const std::string& controller, const unsigned& index1, const unsigned& index2, MultiValue& myvals ) const override; void runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const override {} @@ -52,7 +56,8 @@ class Neighbors : public ActionWithMatrix { PLUMED_REGISTER_ACTION(Neighbors,"NEIGHBORS") void Neighbors::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords( keys ); keys.use("ARG"); + ActionWithMatrix::registerKeywords( keys ); + keys.use("ARG"); keys.add("compulsory","NLOWEST","0","in each row of the output matrix set the elements that correspond to the n lowest elements in each row of the input matrix equal to one"); keys.add("compulsory","NHIGHEST","0","in each row of the output matrix set the elements that correspond to the n highest elements in each row of the input matrix equal to one"); keys.setValueDescription("a matrix in which the ij element is one if the ij-element of the input matrix is one of the NLOWEST/NHIGHEST elements on that row of the input matrix and zero otherwise"); @@ -60,28 +65,40 @@ void Neighbors::registerKeywords( Keywords& keys ) { Neighbors::Neighbors(const ActionOptions&ao): Action(ao), - ActionWithMatrix(ao) -{ - if( getNumberOfArguments()!=1 ) error("found wrong number of arguments in input"); - if( getPntrToArgument(0)->getRank()!=2 ) error("input argument should be a matrix"); + ActionWithMatrix(ao) { + if( getNumberOfArguments()!=1 ) { + error("found wrong number of arguments in input"); + } + if( getPntrToArgument(0)->getRank()!=2 ) { + error("input argument should be a matrix"); + } getPntrToArgument(0)->buildDataStore(); - unsigned nlow; parse("NLOWEST",nlow); - unsigned nhigh; parse("NHIGHEST",nhigh); - if( nlow==0 && nhigh==0 ) error("missing NLOWEST or NHIGHEST keyword one of these two keywords must be set in input"); - if( nlow>0 && nhigh>0 ) error("should only be one of NLOWEST or NHIGHEST set in input"); + unsigned nlow; + parse("NLOWEST",nlow); + unsigned nhigh; + parse("NHIGHEST",nhigh); + if( nlow==0 && nhigh==0 ) { + error("missing NLOWEST or NHIGHEST keyword one of these two keywords must be set in input"); + } + if( nlow>0 && nhigh>0 ) { + error("should only be one of NLOWEST or NHIGHEST set in input"); + } if( nlow>0 ) { - number=nlow; lowest=true; + number=nlow; + lowest=true; log.printf(" output matrix will have non-zero values for elements that correpsond to the %d lowest elements in each row of the input matrix\n",number); } if( nhigh>0 ) { - number=nhigh; lowest=false; + number=nhigh; + lowest=false; log.printf(" output matrix will have non-zero values for elements that correpsond to the %d highest elements in each row of the input matrix\n",number); } // And get the shape std::vector shape( getPntrToArgument(0)->getShape() ); - addValue( shape ); setNotPeriodic(); + addValue( shape ); + setNotPeriodic(); checkRead(); } @@ -95,27 +112,39 @@ unsigned Neighbors::getNumberOfDerivatives() { } void Neighbors::setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const { - const Value* wval = getPntrToArgument(0); unsigned nbonds = wval->getRowLength( task_index ), ncols = wval->getShape()[1]; - if( indices.size()!=1+number ) indices.resize( 1 + number ); + const Value* wval = getPntrToArgument(0); + unsigned nbonds = wval->getRowLength( task_index ), ncols = wval->getShape()[1]; + if( indices.size()!=1+number ) { + indices.resize( 1 + number ); + } myvals.setSplitIndex(1+number); unsigned nind=0; for(unsigned i=0; igetRowIndex( task_index, i ); double weighti = wval->get( ipos ); - if( weightinind ) plumed_merror("not enough matrix elements were stored"); + if( number>nind ) { + plumed_merror("not enough matrix elements were stored"); + } // Now build vectors for doing sorting - std::vector > rows( nind ); unsigned n=0; + std::vector > rows( nind ); + unsigned n=0; for(unsigned i=0; igetRowIndex( task_index, i ); unsigned ipos = ncols*task_index + iind; double weighti = wval->get( ipos ); - if( weighti& // And setup the lowest indices, which are the ones we need to calculate for(unsigned i=0; i::max() ); @@ -120,13 +141,20 @@ TopologyMatrix::TopologyMatrix(const ActionOptions&ao): double TopologyMatrix::calculateWeight( const Vector& pos1, const Vector& pos2, const unsigned& natoms, MultiValue& myvals ) const { // Compute switching function on distance between atoms - Vector distance = pbcDistance( pos1, pos2 ); double len2 = distance.modulo2(); - if( len2>switchingFunction.get_dmax2() ) return 0.0; + Vector distance = pbcDistance( pos1, pos2 ); + double len2 = distance.modulo2(); + if( len2>switchingFunction.get_dmax2() ) { + return 0.0; + } double dfuncl, sw = switchingFunction.calculateSqr( len2, dfuncl ); // Now run through all sea atoms - HistogramBead bead; bead.isNotPeriodic(); bead.setKernelType( kerneltype ); - Vector g1derivf,g2derivf,lderivf; Tensor vir; double binlength = maxbins * binw_mat; + HistogramBead bead; + bead.isNotPeriodic(); + bead.setKernelType( kerneltype ); + Vector g1derivf,g2derivf,lderivf; + Tensor vir; + double binlength = maxbins * binw_mat; MultiValue tvals( maxbins, myvals.getNumberOfDerivatives() ); for(unsigned i=0; iswitchingFunction.get_dmax() ) continue ; + if( d1_len>switchingFunction.get_dmax() ) { + continue ; + } // Ensure that the center of the bins are on the center of the bond connecting the two atoms - double start2atom = 0.5*(binlength-d1_len); Vector dstart = d20 - start2atom*d1; + double start2atom = 0.5*(binlength-d1_len); + Vector dstart = d20 - start2atom*d1; // Now calculate projection of axis of cylinder double proj=dotProduct(-dstart,d1); // Calculate length of vector connecting start of cylinder to first atom @@ -149,7 +182,9 @@ double TopologyMatrix::calculateWeight( const Vector& pos1, const Vector& pos2, // This tells us if we are outside the end of the cylinder double excess = proj_between - d1_len; // Return if we are outside of the cylinder as calculated based on excess - if( excess>low_sf.get_dmax() || -proj_between>low_sf.get_dmax() ) continue; + if( excess>low_sf.get_dmax() || -proj_between>low_sf.get_dmax() ) { + continue; + } // Calculate the excess swiching functions double edf1, eval1 = low_sf.calculate( excess, edf1 ); double edf2, eval2 = low_sf.calculate( -proj_between, edf2 ); @@ -191,8 +226,11 @@ double TopologyMatrix::calculateWeight( const Vector& pos1, const Vector& pos2, } for(unsigned bin=0; binbinw_mat*(bin+1)+bead.getCutoff() ) continue; - double der, contr=bead.calculateWithCutoff( proj, der ) / cell_volume; der /= cell_volume; + if( proj<(bin*binw_mat-bead.getCutoff()) || proj>binw_mat*(bin+1)+bead.getCutoff() ) { + continue; + } + double der, contr=bead.calculateWithCutoff( proj, der ) / cell_volume; + der /= cell_volume; tvals.addValue( bin, contr*val*eval1*eval2 ); if( !doNotCalculateDerivatives() ) { @@ -226,16 +264,24 @@ double TopologyMatrix::calculateWeight( const Vector& pos1, const Vector& pos2, } } // Find maximum density - double max = tvals.get(0); unsigned vout = 0; + double max = tvals.get(0); + unsigned vout = 0; for(unsigned i=1; imax ) { max=tvals.get(i); vout=i; } + if( tvals.get(i)>max ) { + max=tvals.get(i); + vout=i; + } } // Transform the density double df, tsw = threshold_switch.calculate( max, df ); - if( fabs(sw*tsw)getShape()[1]; } + unsigned getNumberOfColumns() const override { + return getConstPntrToComponent(0)->getShape()[1]; + } void setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const ; void performTask( const std::string& controller, const unsigned& index1, const unsigned& index2, MultiValue& myvals ) const override; void runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const override ; @@ -52,7 +54,8 @@ class TorsionsMatrix : public ActionWithMatrix { PLUMED_REGISTER_ACTION(TorsionsMatrix,"TORSIONS_MATRIX") void TorsionsMatrix::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords(keys); keys.use("ARG"); + ActionWithMatrix::registerKeywords(keys); + keys.use("ARG"); keys.add("atoms","POSITIONS1","the positions to use for the molecules specified using the first argument"); keys.add("atoms","POSITIONS2","the positions to use for the molecules specified using the second argument"); keys.setValueDescription("the matrix of torsions between the two vectors of input directors"); @@ -60,31 +63,55 @@ void TorsionsMatrix::registerKeywords( Keywords& keys ) { TorsionsMatrix::TorsionsMatrix(const ActionOptions&ao): Action(ao), - ActionWithMatrix(ao) -{ - if( getNumberOfArguments()!=2 ) error("should be two arguments to this action, a matrix and a vector"); - if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) error("first argument to this action should be a matrix"); - if( getPntrToArgument(1)->getRank()!=2 || getPntrToArgument(1)->hasDerivatives() ) error("second argument to this action should be a matrix"); - if( getPntrToArgument(0)->getShape()[1]!=3 || getPntrToArgument(1)->getShape()[0]!=3 ) error("number of columns in first matrix and number of rows in second matrix should equal 3"); - - std::vector atoms_a; parseAtomList("POSITIONS1", atoms_a ); - if( atoms_a.size()!=getPntrToArgument(0)->getShape()[0] ) error("mismatch between number of atoms specified using POSITIONS1 and number of arguments in vector input"); + ActionWithMatrix(ao) { + if( getNumberOfArguments()!=2 ) { + error("should be two arguments to this action, a matrix and a vector"); + } + if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) { + error("first argument to this action should be a matrix"); + } + if( getPntrToArgument(1)->getRank()!=2 || getPntrToArgument(1)->hasDerivatives() ) { + error("second argument to this action should be a matrix"); + } + if( getPntrToArgument(0)->getShape()[1]!=3 || getPntrToArgument(1)->getShape()[0]!=3 ) { + error("number of columns in first matrix and number of rows in second matrix should equal 3"); + } + + std::vector atoms_a; + parseAtomList("POSITIONS1", atoms_a ); + if( atoms_a.size()!=getPntrToArgument(0)->getShape()[0] ) { + error("mismatch between number of atoms specified using POSITIONS1 and number of arguments in vector input"); + } log.printf(" using positions of these atoms for vectors in first matrix \n"); for(unsigned int i=0; i atoms_b; parseAtomList("POSITIONS2", atoms_b ); - if( atoms_b.size()!=getPntrToArgument(1)->getShape()[1] ) error("mismatch between number of atoms specified using POSITIONS2 and number of arguments in vector input"); + log.printf("\n"); + std::vector atoms_b; + parseAtomList("POSITIONS2", atoms_b ); + if( atoms_b.size()!=getPntrToArgument(1)->getShape()[1] ) { + error("mismatch between number of atoms specified using POSITIONS2 and number of arguments in vector input"); + } log.printf(" using positions of these atoms for vectors in second matrix \n"); for(unsigned i=0; i shape(2); shape[0]=getPntrToArgument(0)->getShape()[0]; shape[1]=getPntrToArgument(1)->getShape()[1]; - addValue( shape ); setPeriodic("-pi","pi"); nderivatives = buildArgumentStore(0) + 3*getNumberOfAtoms() + 9; + log.printf("\n"); + requestAtoms( atoms_a, false ); + + std::vector shape(2); + shape[0]=getPntrToArgument(0)->getShape()[0]; + shape[1]=getPntrToArgument(1)->getShape()[1]; + addValue( shape ); + setPeriodic("-pi","pi"); + nderivatives = buildArgumentStore(0) + 3*getNumberOfAtoms() + 9; std::string headstr=getFirstActionInChain()->getLabel(); stored_matrix1 = getPntrToArgument(0)->ignoreStoredValue( headstr ); stored_matrix2 = getPntrToArgument(1)->ignoreStoredValue( headstr ); @@ -96,19 +123,27 @@ unsigned TorsionsMatrix::getNumberOfDerivatives() { void TorsionsMatrix::setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const { unsigned start_n = getPntrToArgument(0)->getShape()[0], size_v = getPntrToArgument(1)->getShape()[1]; - if( indices.size()!=size_v+1 ) indices.resize( size_v+1 ); - for(unsigned i=0; igetPositionInStream(), ind2=index2; - if( index2>=getPntrToArgument(0)->getShape()[0] ) ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + if( index2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + } Vector v1, v2, dv1, dv2, dconn; // Compute the distance connecting the two centers Vector conn=pbcDistance( getPosition(index1), getPosition(index2) ); - if( conn.modulo2()getNumberOfValues() + getPntrToArgument(1)->getNumberOfValues(); for(unsigned i=0; i<3; ++i) { - myvals.addDerivative( ostrn, narg_derivatives + 3*index1+i, -dconn[i] ); myvals.addDerivative( ostrn, narg_derivatives + 3*index2+i, dconn[i] ); - myvals.updateIndex( ostrn, narg_derivatives + 3*index1+i ); myvals.updateIndex( ostrn, narg_derivatives + 3*index2+i ); + myvals.addDerivative( ostrn, narg_derivatives + 3*index1+i, -dconn[i] ); + myvals.addDerivative( ostrn, narg_derivatives + 3*index2+i, dconn[i] ); + myvals.updateIndex( ostrn, narg_derivatives + 3*index1+i ); + myvals.updateIndex( ostrn, narg_derivatives + 3*index2+i ); } //And virial - Tensor vir( -extProduct( conn, dconn ) ); unsigned virbase = narg_derivatives + 3*getNumberOfAtoms(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j ) { myvals.addDerivative( ostrn, virbase+3*i+j, vir(i,j) ); myvals.updateIndex( ostrn, virbase+3*i+j ); } + Tensor vir( -extProduct( conn, dconn ) ); + unsigned virbase = narg_derivatives + 3*getNumberOfAtoms(); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j ) { + myvals.addDerivative( ostrn, virbase+3*i+j, vir(i,j) ); + myvals.updateIndex( ostrn, virbase+3*i+j ); + } } void TorsionsMatrix::runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() || !matrixChainContinues() ) return ; + if( doNotCalculateDerivatives() || !matrixChainContinues() ) { + return ; + } unsigned mat1s = 3*ival, ss = getPntrToArgument(1)->getShape()[1]; unsigned nmat = getConstPntrToComponent(0)->getPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); unsigned narg_derivatives = getPntrToArgument(0)->getNumberOfValues() + getPntrToArgument(1)->getNumberOfValues(); - std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); unsigned ntwo_atoms = myvals.getSplitIndex(); + std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); + unsigned ntwo_atoms = myvals.getSplitIndex(); for(unsigned j=0; j<3; ++j) { - matrix_indices[nmat_ind] = mat1s + j; nmat_ind++; - matrix_indices[nmat_ind] = narg_derivatives + mat1s + j; nmat_ind++; + matrix_indices[nmat_ind] = mat1s + j; + nmat_ind++; + matrix_indices[nmat_ind] = narg_derivatives + mat1s + j; + nmat_ind++; for(unsigned i=1; i=getPntrToArgument(0)->getShape()[0] ) ind2 = indices[i] - getPntrToArgument(0)->getShape()[0]; - matrix_indices[nmat_ind] = arg_deriv_starts[1] + j*ss + ind2; nmat_ind++; - matrix_indices[nmat_ind] = narg_derivatives + 3*indices[i] + j; nmat_ind++; + unsigned ind2 = indices[i]; + if( ind2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = indices[i] - getPntrToArgument(0)->getShape()[0]; + } + matrix_indices[nmat_ind] = arg_deriv_starts[1] + j*ss + ind2; + nmat_ind++; + matrix_indices[nmat_ind] = narg_derivatives + 3*indices[i] + j; + nmat_ind++; } } - unsigned base = narg_derivatives + 3*getNumberOfAtoms(); for(unsigned j=0; j<9; ++j) { matrix_indices[nmat_ind] = base + j; nmat_ind++; } + unsigned base = narg_derivatives + 3*getNumberOfAtoms(); + for(unsigned j=0; j<9; ++j) { + matrix_indices[nmat_ind] = base + j; + nmat_ind++; + } myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind ); } diff --git a/src/annfunc/ANN.cpp b/src/annfunc/ANN.cpp index 37a488f00c..5421645560 100644 --- a/src/annfunc/ANN.cpp +++ b/src/annfunc/ANN.cpp @@ -87,8 +87,7 @@ To access its components, we use "ann.node-0", "ann.node-1", ..., which represen */ //+ENDPLUMEDOC -class ANN : public Function -{ +class ANN : public Function { private: int num_layers; vector num_nodes; @@ -111,7 +110,8 @@ PLUMED_REGISTER_ACTION(ANN,"ANN") void ANN::registerKeywords( Keywords& keys ) { Function::registerKeywords(keys); - keys.use("ARG"); keys.use("PERIODIC"); + keys.use("ARG"); + keys.use("PERIODIC"); keys.add("compulsory", "NUM_LAYERS", "number of layers of the neural network"); keys.add("compulsory", "NUM_NODES", "numbers of nodes in each layer of the neural network"); keys.add("compulsory", "ACTIVATIONS", "activation functions for the neural network"); @@ -126,8 +126,7 @@ void ANN::registerKeywords( Keywords& keys ) { ANN::ANN(const ActionOptions&ao): Action(ao), - Function(ao) -{ + Function(ao) { parse("NUM_LAYERS", num_layers); num_nodes = vector(num_layers); activations = vector(num_layers - 1); @@ -229,13 +228,11 @@ void ANN::calculate_output_of_each_layer(const vector& input) { for(int jj = 0; jj < num_nodes[ii]; jj ++) { output_of_each_layer[ii][jj] = input_of_each_layer[ii][jj]; } - } - else if (activations[ii - 1] == string("Tanh")) { + } else if (activations[ii - 1] == string("Tanh")) { for(int jj = 0; jj < num_nodes[ii]; jj ++) { output_of_each_layer[ii][jj] = tanh(input_of_each_layer[ii][jj]); } - } - else if (activations[ii - 1] == string("Circular")) { + } else if (activations[ii - 1] == string("Circular")) { assert (num_nodes[ii] % 2 == 0); for(int jj = 0; jj < num_nodes[ii] / 2; jj ++) { double radius = sqrt(input_of_each_layer[ii][2 * jj] * input_of_each_layer[ii][2 * jj] @@ -244,8 +241,7 @@ void ANN::calculate_output_of_each_layer(const vector& input) { output_of_each_layer[ii][2 * jj + 1] = input_of_each_layer[ii][2 * jj + 1] / radius; } - } - else { + } else { printf("layer type not found!\n\n"); return; } @@ -258,8 +254,7 @@ void ANN::calculate_output_of_each_layer(const vector& input) { printf("layer[%d]: ", ii); if (ii != 0) { cout << activations[ii - 1] << "\t"; - } - else { + } else { cout << "input \t" ; } for (int jj = 0; jj < num_nodes[ii]; jj ++) { @@ -278,8 +273,7 @@ void ANN::back_prop(vector >& derivatives_of_each_layer, int inde for (int ii = 0; ii < num_nodes[num_nodes.size() - 1]; ii ++ ) { if (ii == index_of_output_component) { derivatives_of_each_layer[num_nodes.size() - 1][ii] = 1; - } - else { + } else { derivatives_of_each_layer[num_nodes.size() - 1][ii] = 0; } } @@ -323,8 +317,7 @@ void ANN::back_prop(vector >& derivatives_of_each_layer, int inde } } // TODO: should be fine, pass all tests, although there seems to be some problems here previously - } - else { + } else { for (int mm = 0; mm < num_nodes[jj]; mm ++) { derivatives_of_each_layer[jj][mm] = 0; for (int kk = 0; kk < num_nodes[jj + 1]; kk ++) { @@ -333,14 +326,12 @@ void ANN::back_prop(vector >& derivatives_of_each_layer, int inde derivatives_of_each_layer[jj][mm] += derivatives_of_each_layer[jj + 1][kk] \ * coeff[jj][kk][mm] \ * (1 - output_of_each_layer[jj + 1][kk] * output_of_each_layer[jj + 1][kk]); - } - else if (activations[jj] == string("Linear")) { + } else if (activations[jj] == string("Linear")) { // printf("linear\n"); derivatives_of_each_layer[jj][mm] += derivatives_of_each_layer[jj + 1][kk] \ * coeff[jj][kk][mm] \ * 1; - } - else { + } else { printf("layer type not found!\n\n"); return; } diff --git a/src/astyle.sh b/src/astyle.sh index c3239afac7..26a77d6568 100755 --- a/src/astyle.sh +++ b/src/astyle.sh @@ -1,50 +1,52 @@ #! /usr/bin/env bash - +#formatted with shfmt v3.6.0 DIRS=$1 # keep only dirname DIRS=${DIRS##*/} echo "$DIRS" - +# shellcheck disable=SC2125 test -z "$DIRS" && DIRS=* -for dir in $DIRS -do -test -d "$dir" || continue - -test "$dir" = lapack && continue -test "$dir" = blas && continue -test "$dir" = molfile && continue -test "$dir" = lepton && continue -test "$dir" = asmjit && continue -test "$dir" = xdrfile && continue +options=../../.astyle.options -cd $dir +for dir in $DIRS; do + test -d "$dir" || continue + test "$dir" = lapack && continue + test "$dir" = blas && continue + test "$dir" = molfile && continue + test "$dir" = lepton && continue + test "$dir" = asmjit && continue + test "$dir" = xdrfile && continue -for file in *.c *.cpp *.h *.inc.in -do + cd "$dir" || { + echo "Problem with 'cd $dir'" + exit 1 + } -test -f "$file" || continue + for file in *.c *.cpp *.h *.inc.in; do -echo -n "astyle $file" + test -f "$file" || continue -../../astyle/astyle --options=../../.astyle.options < $file > $file.tmp && { -if cmp -s $file $file.tmp ; then - echo -else - cp $file.tmp $file - echo " +++ PATCHED" - git add $file -fi -} + echo -n "astyle $file" -rm $file.tmp + ../../astyle/astyle --options="$options" <"$file" >"$file.tmp" && { + if cmp -s "$file" "$file.tmp"; then + echo + else + cp "$file.tmp" "$file" + echo " +++ PATCHED" + git add "$file" + fi + } -done + rm "$file.tmp" -cd - + done + cd - || { + echo "Problem with 'cd -' from '$dir'" + exit 1 + } done - - diff --git a/src/bias/ABMD.cpp b/src/bias/ABMD.cpp index 89ceb6f69a..a087c8e018 100644 --- a/src/bias/ABMD.cpp +++ b/src/bias/ABMD.cpp @@ -115,35 +115,50 @@ ABMD::ABMD(const ActionOptions&ao): kappa(getNumberOfArguments(),0.0), temp(getNumberOfArguments(),0.0), seed(getNumberOfArguments(),std::time(0)), - random(getNumberOfArguments()) -{ + random(getNumberOfArguments()) { // Note : parseVector will check that number of arguments is correct parseVector("KAPPA",kappa); parseVector("MIN",min); - if(min.size()==0) min.assign(getNumberOfArguments(),-1.0); - if(min.size()!=getNumberOfArguments()) error("MIN array should have the same size as ARG array"); + if(min.size()==0) { + min.assign(getNumberOfArguments(),-1.0); + } + if(min.size()!=getNumberOfArguments()) { + error("MIN array should have the same size as ARG array"); + } parseVector("NOISE",temp); parseVector("SEED",seed); parseVector("TO",to); checkRead(); log.printf(" min"); - for(unsigned i=0; igetName()+"_min"; - addComponent(str_min); componentIsNotPeriodic(str_min); - if(min[i]!=-1.0) getPntrToComponent(str_min)->set(min[i]); + addComponent(str_min); + componentIsNotPeriodic(str_min); + if(min[i]!=-1.0) { + getPntrToComponent(str_min)->set(min[i]); + } + } + for(unsigned i=0; i0) { noise = 2.*random[i].Gaussian()*diff; - if(cv2<=diff) { diff=0.; temp[i]=0.; } + if(cv2<=diff) { + diff=0.; + temp[i]=0.; + } } // min < 0 means that the variable has not been used in the input file, so the current position of the CV is used diff --git a/src/bias/Bias.cpp b/src/bias/Bias.cpp index 1577eba03d..8139adc4f6 100644 --- a/src/bias/Bias.cpp +++ b/src/bias/Bias.cpp @@ -30,8 +30,7 @@ Bias::Bias(const ActionOptions&ao): ActionPilot(ao), ActionWithValue(ao), ActionWithArguments(ao), - outputForces(getNumberOfArguments(),0.0) -{ + outputForces(getNumberOfArguments(),0.0) { addComponentWithDerivatives("bias"); componentIsNotPeriodic("bias"); valueBias=getPntrToComponent("bias"); @@ -74,13 +73,18 @@ void Bias::apply() { for(unsigned i=0; iapplyForce(forces)) { at_least_one_forced=true; - for(unsigned j=0; jaddForce(f[i]); } diff --git a/src/bias/Bias.h b/src/bias/Bias.h index 0da95bd6e7..c56d4eb5f6 100644 --- a/src/bias/Bias.h +++ b/src/bias/Bias.h @@ -40,8 +40,7 @@ information as to how to go about implementing a new bias. class Bias : public ActionPilot, public ActionWithValue, - public ActionWithArguments -{ + public ActionWithArguments { /// the vector of the forces std::vector outputForces; /// the pointer to the bias component diff --git a/src/bias/BiasValue.cpp b/src/bias/BiasValue.cpp index 7fa6ca2435..bc34c3edde 100644 --- a/src/bias/BiasValue.cpp +++ b/src/bias/BiasValue.cpp @@ -92,20 +92,21 @@ void BiasValue::registerKeywords(Keywords& keys) { } BiasValue::BiasValue(const ActionOptions&ao): - PLUMED_BIAS_INIT(ao) -{ + PLUMED_BIAS_INIT(ao) { checkRead(); // add one bias for each argument for(unsigned i=0; igetName()+"_bias"; - addComponent(ss); componentIsNotPeriodic(ss); + addComponent(ss); + componentIsNotPeriodic(ss); } } void BiasValue::calculate() { double bias=0.0; for(unsigned i=0; iset(val); setOutputForce(i,-1.); bias+=val; diff --git a/src/bias/ExtendedLagrangian.cpp b/src/bias/ExtendedLagrangian.cpp index ecb96ed113..239e99e9a8 100644 --- a/src/bias/ExtendedLagrangian.cpp +++ b/src/bias/ExtendedLagrangian.cpp @@ -154,27 +154,36 @@ ExtendedLagrangian::ExtendedLagrangian(const ActionOptions&ao): friction(getNumberOfArguments(),0.0), fictValue(getNumberOfArguments(),NULL), vfictValue(getNumberOfArguments(),NULL), - kbt(0.0) -{ + kbt(0.0) { parseVector("TAU",tau); parseVector("FRICTION",friction); parseVector("KAPPA",kappa); - kbt=getkBT(); checkRead(); + kbt=getkBT(); + checkRead(); log.printf(" with harmonic force constant"); - for(unsigned i=0; i0.0) hasFriction=true; + for(unsigned i=0; i0.0) { + hasFriction=true; + } if(hasFriction) { log.printf(" with friction"); - for(unsigned i=0; igetDomain(a,b); componentIsPeriodic(comp,a,b); - } else componentIsNotPeriodic(comp); + } else { + componentIsNotPeriodic(comp); + } fictValue[i]=getPntrToComponent(comp); comp=getPntrToArgument(i)->getName()+"_vfict"; addComponent(comp); diff --git a/src/bias/External.cpp b/src/bias/External.cpp index ce422c1682..3299a1466d 100644 --- a/src/bias/External.cpp +++ b/src/bias/External.cpp @@ -130,11 +130,12 @@ void External::registerKeywords(Keywords& keys) { } External::External(const ActionOptions& ao): - PLUMED_BIAS_INIT(ao) -{ + PLUMED_BIAS_INIT(ao) { std::string filename; parse("FILE",filename); - if( filename.length()==0 ) error("No external potential file was specified"); + if( filename.length()==0 ) { + error("No external potential file was specified"); + } bool sparsegrid=false; parseFlag("SPARSE",sparsegrid); bool nospline=false; @@ -146,25 +147,35 @@ External::External(const ActionOptions& ao): log.printf(" External potential from file %s\n",filename.c_str()); log.printf(" Multiplied by %lf\n",scale_); - if(spline) {log.printf(" External potential uses spline interpolation\n");} - if(sparsegrid) {log.printf(" External potential uses sparse grid\n");} + if(spline) { + log.printf(" External potential uses spline interpolation\n"); + } + if(sparsegrid) { + log.printf(" External potential uses sparse grid\n"); + } // read grid - IFile gridfile; gridfile.open(filename); + IFile gridfile; + gridfile.open(filename); std::string funcl=getLabel() + ".bias"; BiasGrid_=GridBase::create(funcl,getArguments(),gridfile,sparsegrid,spline,true); - if(BiasGrid_->getDimension()!=getNumberOfArguments()) error("mismatch between dimensionality of input grid and number of arguments"); + if(BiasGrid_->getDimension()!=getNumberOfArguments()) { + error("mismatch between dimensionality of input grid and number of arguments"); + } for(unsigned i=0; iisPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) error("periodicity mismatch between arguments and input bias"); + if( getPntrToArgument(i)->isPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) { + error("periodicity mismatch between arguments and input bias"); + } } } -void External::calculate() -{ +void External::calculate() { unsigned ncv=getNumberOfArguments(); std::vector cv(ncv), der(ncv); - for(unsigned i=0; igetValueAndDerivatives(cv,der); diff --git a/src/bias/LWalls.cpp b/src/bias/LWalls.cpp index d6553a3d86..a8ea6af348 100644 --- a/src/bias/LWalls.cpp +++ b/src/bias/LWalls.cpp @@ -86,8 +86,10 @@ class LWalls : public Bias { PLUMED_REGISTER_ACTION(LWalls,"LOWER_WALLS_SCALAR") void LWalls::registerKeywords(Keywords& keys) { - Bias::registerKeywords(keys); keys.setDisplayName("LOWER_WALLS"); - keys.use("ARG"); keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); + Bias::registerKeywords(keys); + keys.setDisplayName("LOWER_WALLS"); + keys.use("ARG"); + keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); keys.add("compulsory","AT","the positions of the wall. The a_i in the expression for a wall."); keys.add("compulsory","KAPPA","the force constant for the wall. The k_i in the expression for a wall."); keys.add("compulsory","OFFSET","0.0","the offset for the start of the wall. The o_i in the expression for a wall."); @@ -102,8 +104,7 @@ LWalls::LWalls(const ActionOptions&ao): kappa(getNumberOfArguments(),0.0), exp(getNumberOfArguments(),2.0), eps(getNumberOfArguments(),1.0), - offset(getNumberOfArguments(),0.0) -{ + offset(getNumberOfArguments(),0.0) { // Note sizes of these vectors are automatically checked by parseVector :-) parseVector("OFFSET",offset); parseVector("EPS",eps); @@ -113,22 +114,33 @@ LWalls::LWalls(const ActionOptions&ao): checkRead(); log.printf(" at"); - for(unsigned i=0; i= TSTART"); + if(tend<0 && tend != -1.0) { + error("TSTART should be a positive number"); + } + if(tend= TSTART"); + } lagmultfname=getLabel()+".LAGMULT"; parse("FILE",lagmultfname); parse("FMT",fmt); parse("PACE",pace_); - if(pace_<=0 ) error("frequency for Lagrangian multipliers update (PACE) is nonsensical"); + if(pace_<=0 ) { + error("frequency for Lagrangian multipliers update (PACE) is nonsensical"); + } stride_=pace_; //if no STRIDE is passed, then Lagrangian multipliers willbe printed at each update parse("PRINT_STRIDE",stride_); - if(stride_<=0 ) error("frequency for Lagrangian multipliers printing (STRIDE) is nonsensical"); + if(stride_<=0 ) { + error("frequency for Lagrangian multipliers printing (STRIDE) is nonsensical"); + } simtemp=getkBT(); parseFlag("REWEIGHT",reweight); - if(simtemp<=0 && reweight) error("Set the temperature (TEMP) if you want to do reweighting."); + if(simtemp<=0 && reweight) { + error("Set the temperature (TEMP) if you want to do reweighting."); + } checkRead(); log.printf(" at"); - for(unsigned i=0; i0) + if(fmt.length()>0) { log.printf("The format for real number in Lagrangian multipliers file is %s\n",fmt.c_str()); - if(tstart >-1.0 && tend>-1.0) + } + if(tstart >-1.0 && tend>-1.0) { log.printf("Lagrangian multipliers are averaged from %lf ps to %lf ps\n",tstart,tend); - if(no_broadcast) + } + if(no_broadcast) { log.printf("Using NO_BROADCAST options. Lagrangian multipliers will not be comunicated to other replicas.\n"); + } //for(int irep=0;irepgetName()+"_coupling"; - addComponent(comp); componentIsNotPeriodic(comp); + addComponent(comp); + componentIsNotPeriodic(comp); comp=getPntrToArgument(i)->getName()+"_work"; - addComponent(comp); componentIsNotPeriodic(comp); + addComponent(comp); + componentIsNotPeriodic(comp); work.push_back(0.); // initialize the work value comp=getPntrToArgument(i)->getName()+"_error"; - addComponent(comp); componentIsNotPeriodic(comp); + addComponent(comp); + componentIsNotPeriodic(comp); } std::string fname; fname=lagmultfname; @@ -316,24 +347,28 @@ MaxEnt::MaxEnt(const ActionOptions&ao): lagmultOfile_.link(*this); lagmultOfile_.open(fname); - if(fmt.length()>0) {fmt=" "+fmt; lagmultOfile_.fmtField(fmt);} + if(fmt.length()>0) { + fmt=" "+fmt; + lagmultOfile_.fmtField(fmt); + } } ////MEMBER FUNCTIONS -void MaxEnt::ReadLagrangians(IFile &ifile) -{ +void MaxEnt::ReadLagrangians(IFile &ifile) { double dummy; while(ifile.scanField("time",dummy)) { for(unsigned j=0; jgetName()+"_coupling",lambda[j]); - if(dummy>=tstart && dummy <=tend) + if(dummy>=tstart && dummy <=tend) { avglambda[j]+=lambda[j]; + } if(dummy>=tend) { avglambda[j]=lambda[j]; done_average[j]=true; } } - if(dummy>=tstart && dummy <=tend) + if(dummy>=tstart && dummy <=tend) { avg_counter++; + } ifile.scanField(); } } @@ -341,15 +376,17 @@ void MaxEnt::WriteLagrangians(std::vector &lagmult,OFile &file) { if(printFirstStep) { unsigned ncv=getNumberOfArguments(); file.printField("time",getTimeStep()*getStep()); - for(unsigned i=0; igetName()+"_coupling",lagmult[i]); + } file.printField(); } else { if(!isFirstStep) { unsigned ncv=getNumberOfArguments(); file.printField("time",getTimeStep()*getStep()); - for(unsigned i=0; igetName()+"_coupling",lagmult[i]); + } file.printField(); } } @@ -358,9 +395,9 @@ double MaxEnt::compute_error(const std::string &err_type,double l) { double sigma2=std::pow(sigma,2.0); double l2=convert_lambda(type,l); double return_error=0; - if(err_type=="GAUSSIAN" && sigma!=0.0) + if(err_type=="GAUSSIAN" && sigma!=0.0) { return_error=-l2*sigma2; - else { + } else { if(err_type=="LAPLACE" && sigma!=0) { return_error=-l2*sigma2/(1.0-l2*l2*sigma2/(alpha+1)); } @@ -369,21 +406,22 @@ double MaxEnt::compute_error(const std::string &err_type,double l) { } double MaxEnt::convert_lambda(const std::string &type,double lold) { double return_lambda=0; - if(type=="EQUAL") + if(type=="EQUAL") { return_lambda=lold; - else { + } else { if(type=="INEQUAL>") { - if(lold>0.0) + if(lold>0.0) { return_lambda=0.0; - else + } else { return_lambda=lold; - } - else { + } + } else { if(type=="INEQUAL<") { - if(lold<0.0) + if(lold<0.0) { return_lambda=0.0; - else + } else { return_lambda=lold; + } } } } @@ -410,18 +448,20 @@ void MaxEnt::update_lambda() { const double step=getStep(); double KbT=simtemp; double learning_rate; - if(reweight) + if(reweight) { BetaReweightBias=plumed.getBias()/KbT; - else + } else { BetaReweightBias=0.0; + } for(unsigned i=0; i=tstart && time <=tend && !done_average[i]) { @@ -432,17 +472,18 @@ void MaxEnt::update_lambda() { avglambda[i]=avglambda[i]/avg_counter; done_average[i]=true; lambda[i]=avglambda[i]; + } else { + lambda[i]=avglambda[i]; //keep Lagrangian multipliers fixed to the previously computed average. } - else - lambda[i]=avglambda[i]; //keep Lagrangian multipliers fixed to the previously computed average. } work[i]+=(convert_lambda(type,lambda[i])-oldlambda[i])*getArgument(i); //compute the work performed in updating lambda totalWork_+=work[i]; totalWork=totalWork_; oldlambda[i]=convert_lambda(type,lambda[i]); }; - if(time>=tstart && time <=tend) + if(time>=tstart && time <=tend) { avg_counter++; + } } void MaxEnt::calculate() { @@ -465,13 +506,15 @@ void MaxEnt::calculate() { void MaxEnt::update() { - if(getStep()%stride_ == 0) + if(getStep()%stride_ == 0) { WriteLagrangians(lambda,lagmultOfile_); + } if(getStep()%pace_ == 0) { update_lambda(); if(!no_broadcast) { - if(comm.Get_rank()==0) //Comunicate Lagrangian multipliers from reference replica to higher ones + if(comm.Get_rank()==0) { //Comunicate Lagrangian multipliers from reference replica to higher ones multi_sim_comm.Bcast(lambda,learn_replica); + } } comm.Bcast(lambda,0); } diff --git a/src/bias/MetaD.cpp b/src/bias/MetaD.cpp index f468de9261..f69c87810a 100644 --- a/src/bias/MetaD.cpp +++ b/src/bias/MetaD.cpp @@ -381,8 +381,11 @@ class MetaD : public Bias { multivariate(m),height(h),center(c),sigma(s),invsigma(s) { // to avoid troubles from zero element in flexible hills for(unsigned i=0; i1.e-20) invsigma[i]=1.0/invsigma[i] ; - else invsigma[i]=0.0; + if(std::abs(invsigma[i])>1.e-20) { + invsigma[i]=1.0/invsigma[i] ; + } else { + invsigma[i]=0.0; + } } } }; @@ -626,8 +629,7 @@ MetaD::MetaD(const ActionOptions& ao): work_(0), nlist_(false), nlist_update_(false), - nlist_steps_(0) -{ + nlist_steps_(0) { if(!dp2cutoffNoStretch()) { stretchA=dp2cutoffA; stretchB=dp2cutoffB; @@ -654,7 +656,9 @@ MetaD::MetaD(const ActionOptions& ao): parseVector("SIGMA",sigma0_); if(adaptive_==FlexibleBin::none) { // if you use normal sigma you need one sigma per argument - if( sigma0_.size()!=getNumberOfArguments() ) error("number of arguments does not match number of SIGMA parameters"); + if( sigma0_.size()!=getNumberOfArguments() ) { + error("number of arguments does not match number of SIGMA parameters"); + } } else { // if you use flexible hills you need one sigma if(sigma0_.size()!=1) { @@ -672,7 +676,9 @@ MetaD::MetaD(const ActionOptions& ao): error("the number of SIGMA_MIN values be the same of the number of the arguments"); } else if(sigma0min_.size()==0) { sigma0min_.resize(getNumberOfArguments()); - for(unsigned i=0; i(adaptive_,this,sigma0_[0],sigma0min_,sigma0max_); @@ -689,7 +697,9 @@ MetaD::MetaD(const ActionOptions& ao): // note: HEIGHT is not compulsory, since one could use the TAU keyword, see below parse("HEIGHT",height0_); parse("PACE",stride_); - if(stride_<=0) error("frequency for hill addition is nonsensical"); + if(stride_<=0) { + error("frequency for hill addition is nonsensical"); + } current_stride_ = stride_; std::string hillsfname="HILLS"; parse("FILE",hillsfname); @@ -704,21 +714,30 @@ MetaD::MetaD(const ActionOptions& ao): parseVector("RECT",rect_biasf_); if(rect_biasf_.size()>0) { int r=0; - if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank(); + if(comm.Get_rank()==0) { + r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); biasf_=rect_biasf_[r]; log<<" You are using RECT\n"; } else { parse("BIASFACTOR",biasf_); } - if( biasf_<1.0 && biasf_!=-1.0) error("well tempered bias factor is nonsensical"); - parse("DAMPFACTOR",dampfactor_); kbt_=getkBT(); + if( biasf_<1.0 && biasf_!=-1.0) { + error("well tempered bias factor is nonsensical"); + } + parse("DAMPFACTOR",dampfactor_); + kbt_=getkBT(); if(biasf_>=1.0) { - if(kbt_==0.0) error("Unless the MD engine passes the temperature to plumed, with well-tempered metad you must specify it using TEMP"); + if(kbt_==0.0) { + error("Unless the MD engine passes the temperature to plumed, with well-tempered metad you must specify it using TEMP"); + } welltemp_=true; } if(dampfactor_>0.0) { - if(kbt_==0.0) error("Unless the MD engine passes the temperature to plumed, with damped metad you must specify it using TEMP"); + if(kbt_==0.0) { + error("Unless the MD engine passes the temperature to plumed, with damped metad you must specify it using TEMP"); + } } parseFlag("CALC_WORK",calc_work_); @@ -726,14 +745,18 @@ MetaD::MetaD(const ActionOptions& ao): // Set transition tempering parameters. // Transition wells are read later via calc_transition_bias_. readTemperingSpecs(tt_specs_); - if (tt_specs_.is_active) calc_transition_bias_ = true; + if (tt_specs_.is_active) { + calc_transition_bias_ = true; + } // If any previous option specified to calculate a transition bias, // now read the transition wells for that quantity. if (calc_transition_bias_) { std::vector tempcoords(getNumberOfArguments()); for (unsigned i = 0; ; i++) { - if (!parseNumberedVector("TRANSITIONWELL", i, tempcoords) ) break; + if (!parseNumberedVector("TRANSITIONWELL", i, tempcoords) ) { + break; + } if (tempcoords.size() != getNumberOfArguments()) { error("incorrect number of coordinates for transition tempering well"); } @@ -742,53 +765,88 @@ MetaD::MetaD(const ActionOptions& ao): } parse("TARGET",targetfilename_); - if(targetfilename_.length()>0 && kbt_==0.0) error("with TARGET temperature must be specified"); + if(targetfilename_.length()>0 && kbt_==0.0) { + error("with TARGET temperature must be specified"); + } double tau=0.0; parse("TAU",tau); if(tau==0.0) { - if(height0_==std::numeric_limits::max()) error("At least one between HEIGHT and TAU should be specified"); + if(height0_==std::numeric_limits::max()) { + error("At least one between HEIGHT and TAU should be specified"); + } // if tau is not set, we compute it here from the other input parameters - if(welltemp_) tau=(kbt_*(biasf_-1.0))/height0_*getTimeStep()*stride_; - else if(dampfactor_>0.0) tau=(kbt_*dampfactor_)/height0_*getTimeStep()*stride_; + if(welltemp_) { + tau=(kbt_*(biasf_-1.0))/height0_*getTimeStep()*stride_; + } else if(dampfactor_>0.0) { + tau=(kbt_*dampfactor_)/height0_*getTimeStep()*stride_; + } } else { - if(height0_!=std::numeric_limits::max()) error("At most one between HEIGHT and TAU should be specified"); + if(height0_!=std::numeric_limits::max()) { + error("At most one between HEIGHT and TAU should be specified"); + } if(welltemp_) { - if(biasf_!=1.0) height0_=(kbt_*(biasf_-1.0))/tau*getTimeStep()*stride_; - else height0_=kbt_/tau*getTimeStep()*stride_; // special case for gamma=1 + if(biasf_!=1.0) { + height0_=(kbt_*(biasf_-1.0))/tau*getTimeStep()*stride_; + } else { + height0_=kbt_/tau*getTimeStep()*stride_; // special case for gamma=1 + } + } else if(dampfactor_>0.0) { + height0_=(kbt_*dampfactor_)/tau*getTimeStep()*stride_; + } else { + error("TAU only makes sense in well-tempered or damped metadynamics"); } - else if(dampfactor_>0.0) height0_=(kbt_*dampfactor_)/tau*getTimeStep()*stride_; - else error("TAU only makes sense in well-tempered or damped metadynamics"); } // Grid Stuff std::vector gmin(getNumberOfArguments()); parseVector("GRID_MIN",gmin); - if(gmin.size()!=getNumberOfArguments() && gmin.size()!=0) error("not enough values for GRID_MIN"); + if(gmin.size()!=getNumberOfArguments() && gmin.size()!=0) { + error("not enough values for GRID_MIN"); + } std::vector gmax(getNumberOfArguments()); parseVector("GRID_MAX",gmax); - if(gmax.size()!=getNumberOfArguments() && gmax.size()!=0) error("not enough values for GRID_MAX"); + if(gmax.size()!=getNumberOfArguments() && gmax.size()!=0) { + error("not enough values for GRID_MAX"); + } std::vector gbin(getNumberOfArguments()); std::vector gspacing; parseVector("GRID_BIN",gbin); - if(gbin.size()!=getNumberOfArguments() && gbin.size()!=0) error("not enough values for GRID_BIN"); + if(gbin.size()!=getNumberOfArguments() && gbin.size()!=0) { + error("not enough values for GRID_BIN"); + } parseVector("GRID_SPACING",gspacing); - if(gspacing.size()!=getNumberOfArguments() && gspacing.size()!=0) error("not enough values for GRID_SPACING"); - if(gmin.size()!=gmax.size()) error("GRID_MAX and GRID_MIN should be either present or absent"); - if(gspacing.size()!=0 && gmin.size()==0) error("If GRID_SPACING is present also GRID_MIN and GRID_MAX should be present"); - if(gbin.size()!=0 && gmin.size()==0) error("If GRID_BIN is present also GRID_MIN and GRID_MAX should be present"); + if(gspacing.size()!=getNumberOfArguments() && gspacing.size()!=0) { + error("not enough values for GRID_SPACING"); + } + if(gmin.size()!=gmax.size()) { + error("GRID_MAX and GRID_MIN should be either present or absent"); + } + if(gspacing.size()!=0 && gmin.size()==0) { + error("If GRID_SPACING is present also GRID_MIN and GRID_MAX should be present"); + } + if(gbin.size()!=0 && gmin.size()==0) { + error("If GRID_BIN is present also GRID_MIN and GRID_MAX should be present"); + } if(gmin.size()!=0) { if(gbin.size()==0 && gspacing.size()==0) { if(adaptive_==FlexibleBin::none) { log<<" Binsize not specified, 1/5 of sigma will be be used\n"; plumed_assert(sigma0_.size()==getNumberOfArguments()); gspacing.resize(getNumberOfArguments()); - for(unsigned i=0; i0) grid_=true; + if(gbin.size()>0) { + grid_=true; + } bool sparsegrid=false; parseFlag("GRID_SPARSE",sparsegrid); @@ -817,32 +882,39 @@ MetaD::MetaD(const ActionOptions& ao): parse("GRID_WFILE",gridfilename_); parseFlag("STORE_GRIDS",storeOldGrids_); if(grid_ && gridfilename_.length()>0) { - if(wgridstride_==0 ) error("frequency with which to output grid not specified use GRID_WSTRIDE"); + if(wgridstride_==0 ) { + error("frequency with which to output grid not specified use GRID_WSTRIDE"); + } } if(grid_ && wgridstride_>0) { - if(gridfilename_.length()==0) error("grid filename not specified use GRID_WFILE"); + if(gridfilename_.length()==0) { + error("grid filename not specified use GRID_WFILE"); + } } std::string gridreadfilename_; parse("GRID_RFILE",gridreadfilename_); - if(!grid_&&gridfilename_.length()> 0) error("To write a grid you need first to define it!"); - if(!grid_&&gridreadfilename_.length()>0) error("To read a grid you need first to define it!"); + if(!grid_&&gridfilename_.length()> 0) { + error("To write a grid you need first to define it!"); + } + if(!grid_&&gridreadfilename_.length()>0) { + error("To read a grid you need first to define it!"); + } /*setup neighbor list stuff*/ parseFlag("NLIST", nlist_); nlist_center_.resize(getNumberOfArguments()); nlist_dev2_.resize(getNumberOfArguments()); - if(nlist_&&grid_) error("NLIST and GRID cannot be combined!"); + if(nlist_&&grid_) { + error("NLIST and GRID cannot be combined!"); + } std::vector nlist_param; parseVector("NLIST_PARAMETERS",nlist_param); - if(nlist_param.size()==0) - { + if(nlist_param.size()==0) { nlist_param_[0]=6.0;//*DP2CUTOFF -> max distance of neighbors nlist_param_[1]=0.5;//*nlist_dev2_[i] -> condition for rebuilding - } - else - { + } else { plumed_massert(nlist_param.size()==2,"two cutoff parameters are needed for the neighbor list"); plumed_massert(nlist_param[0]>1.0,"the first of NLIST_PARAMETERS must be greater than 1. The smaller the first, the smaller should be the second as well"); const double min_PARAM_1=(1.-1./std::sqrt(nlist_param[0]/2))+0.16; @@ -854,17 +926,23 @@ MetaD::MetaD(const ActionOptions& ao): // Reweighting factor rct parseFlag("CALC_RCT",calc_rct_); - if (calc_rct_) plumed_massert(grid_,"CALC_RCT is supported only if bias is on a grid"); + if (calc_rct_) { + plumed_massert(grid_,"CALC_RCT is supported only if bias is on a grid"); + } parse("RCT_USTRIDE",rct_ustride_); if(dampfactor_>0.0) { - if(!grid_) error("With DAMPFACTOR you should use grids"); + if(!grid_) { + error("With DAMPFACTOR you should use grids"); + } } // Multiple walkers parse("WALKERS_N",mw_n_); parse("WALKERS_ID",mw_id_); - if(mw_n_<=mw_id_) error("walker ID should be a numerical value less than the total number of walkers"); + if(mw_n_<=mw_id_) { + error("walker ID should be a numerical value less than the total number of walkers"); + } parse("WALKERS_DIR",mw_dir_); parse("WALKERS_RSTRIDE",mw_rstride_); @@ -883,13 +961,20 @@ MetaD::MetaD(const ActionOptions& ao): // Inteval keyword std::vector tmpI(2); parseVector("INTERVAL",tmpI); - if(tmpI.size()!=2&&tmpI.size()!=0) error("both a lower and an upper limits must be provided with INTERVAL"); - else if(tmpI.size()==2) { + if(tmpI.size()!=2&&tmpI.size()!=0) { + error("both a lower and an upper limits must be provided with INTERVAL"); + } else if(tmpI.size()==2) { lowI_=tmpI.at(0); uppI_=tmpI.at(1); - if(getNumberOfArguments()!=1) error("INTERVAL limits correction works only for monodimensional metadynamics!"); - if(uppI_isPeriodic()) error("INTERVAL cannot be used with periodic variables!"); + if(getNumberOfArguments()!=1) { + error("INTERVAL limits correction works only for monodimensional metadynamics!"); + } + if(uppI_isPeriodic()) { + error("INTERVAL cannot be used with periodic variables!"); + } doInt_=true; } @@ -927,9 +1012,15 @@ MetaD::MetaD(const ActionOptions& ao): checkRead(); log.printf(" Gaussian width "); - if (adaptive_==FlexibleBin::diffusion)log.printf(" (Note: The units of sigma are in timesteps) "); - if (adaptive_==FlexibleBin::geometry)log.printf(" (Note: The units of sigma are in dist units) "); - for(unsigned i=0; i 0.0 || tt_specs_.is_active) { // Determine the number of active temperings. int n_active = 0; - if (welltemp_) n_active++; - if (dampfactor_ > 0.0) n_active++; - if (tt_specs_.is_active) n_active++; + if (welltemp_) { + n_active++; + } + if (dampfactor_ > 0.0) { + n_active++; + } + if (tt_specs_.is_active) { + n_active++; + } // Find the greatest alpha. double greatest_alpha = 0.0; - if (welltemp_) greatest_alpha = std::max(greatest_alpha, 1.0); - if (dampfactor_ > 0.0) greatest_alpha = std::max(greatest_alpha, 1.0); - if (tt_specs_.is_active) greatest_alpha = std::max(greatest_alpha, tt_specs_.alpha); + if (welltemp_) { + greatest_alpha = std::max(greatest_alpha, 1.0); + } + if (dampfactor_ > 0.0) { + greatest_alpha = std::max(greatest_alpha, 1.0); + } + if (tt_specs_.is_active) { + greatest_alpha = std::max(greatest_alpha, tt_specs_.alpha); + } // Find the least alpha. double least_alpha = 1.0; - if (welltemp_) least_alpha = std::min(least_alpha, 1.0); - if (dampfactor_ > 0.0) least_alpha = std::min(least_alpha, 1.0); - if (tt_specs_.is_active) least_alpha = std::min(least_alpha, tt_specs_.alpha); + if (welltemp_) { + least_alpha = std::min(least_alpha, 1.0); + } + if (dampfactor_ > 0.0) { + least_alpha = std::min(least_alpha, 1.0); + } + if (tt_specs_.is_active) { + least_alpha = std::min(least_alpha, tt_specs_.alpha); + } // Find the inverse harmonic average of the delta T parameters for all // of the temperings with the greatest alpha values. double total_governing_deltaT_inv = 0.0; - if (welltemp_ && 1.0 == greatest_alpha && biasf_ != 1.0) total_governing_deltaT_inv += 1.0 / (biasf_ - 1.0); - if (dampfactor_ > 0.0 && 1.0 == greatest_alpha) total_governing_deltaT_inv += 1.0 / (dampfactor_); - if (tt_specs_.is_active && tt_specs_.alpha == greatest_alpha) total_governing_deltaT_inv += 1.0 / (tt_specs_.biasf - 1.0); + if (welltemp_ && 1.0 == greatest_alpha && biasf_ != 1.0) { + total_governing_deltaT_inv += 1.0 / (biasf_ - 1.0); + } + if (dampfactor_ > 0.0 && 1.0 == greatest_alpha) { + total_governing_deltaT_inv += 1.0 / (dampfactor_); + } + if (tt_specs_.is_active && tt_specs_.alpha == greatest_alpha) { + total_governing_deltaT_inv += 1.0 / (tt_specs_.biasf - 1.0); + } // Give a newbie-friendly error message for people using one tempering if // only one is active. if (n_active == 1 && total_governing_deltaT_inv < 0.0) { @@ -995,33 +1110,53 @@ MetaD::MetaD(const ActionOptions& ao): } } - if(doInt_) log.printf(" Upper and Lower limits boundaries for the bias are activated at %f - %f\n", lowI_, uppI_); + if(doInt_) { + log.printf(" Upper and Lower limits boundaries for the bias are activated at %f - %f\n", lowI_, uppI_); + } if(grid_) { log.printf(" Grid min"); - for(unsigned i=0; i0) {log.printf(" Grid is written on file %s with stride %d\n",gridfilename_.c_str(),wgridstride_);} + if(spline) { + log.printf(" Grid uses spline interpolation\n"); + } + if(sparsegrid) { + log.printf(" Grid uses sparse grid\n"); + } + if(wgridstride_>0) { + log.printf(" Grid is written on file %s with stride %d\n",gridfilename_.c_str(),wgridstride_); + } } if(mw_n_>1) { - if(walkers_mpi_) error("MPI version of multiple walkers is not compatible with filesystem version of multiple walkers"); + if(walkers_mpi_) { + error("MPI version of multiple walkers is not compatible with filesystem version of multiple walkers"); + } log.printf(" %d multiple walkers active\n",mw_n_); log.printf(" walker id %d\n",mw_id_); log.printf(" reading stride %d\n",mw_rstride_); - if(mw_dir_!="")log.printf(" directory with hills files %s\n",mw_dir_.c_str()); + if(mw_dir_!="") { + log.printf(" directory with hills files %s\n",mw_dir_.c_str()); + } } else { if(walkers_mpi_) { log.printf(" Multiple walkers active using MPI communnication\n"); - if(mw_dir_!="")log.printf(" directory with hills files %s\n",mw_dir_.c_str()); + if(mw_dir_!="") { + log.printf(" directory with hills files %s\n",mw_dir_.c_str()); + } if(comm.Get_rank()==0) { // Only root of group can communicate with other walkers mpi_nw_=multi_sim_comm.Get_size(); @@ -1033,7 +1168,9 @@ MetaD::MetaD(const ActionOptions& ao): } if(flying_) { - if(!walkers_mpi_) error("Flying Gaussian method must be used with MPI version of multiple walkers"); + if(!walkers_mpi_) { + error("Flying Gaussian method must be used with MPI version of multiple walkers"); + } log.printf(" Flying Gaussian method with %d walkers active\n",mpi_nw_); } @@ -1045,20 +1182,26 @@ MetaD::MetaD(const ActionOptions& ao): } if(calc_rct_) { - addComponent("rbias"); componentIsNotPeriodic("rbias"); - addComponent("rct"); componentIsNotPeriodic("rct"); + addComponent("rbias"); + componentIsNotPeriodic("rbias"); + addComponent("rct"); + componentIsNotPeriodic("rct"); log.printf(" The c(t) reweighting factor will be calculated every %u hills\n",rct_ustride_); getPntrToComponent("rct")->set(reweight_factor_); } - if(calc_work_) { addComponent("work"); componentIsNotPeriodic("work"); } + if(calc_work_) { + addComponent("work"); + componentIsNotPeriodic("work"); + } if(acceleration_) { if (kbt_ == 0.0) { error("The calculation of the acceleration works only if simulation temperature has been defined"); } log.printf(" calculation on the fly of the acceleration factor\n"); - addComponent("acc"); componentIsNotPeriodic("acc"); + addComponent("acc"); + componentIsNotPeriodic("acc"); // Set the initial value of the the acceleration. // If this is not a restart, set to 1.0. if (acc_rfilename.length() == 0) { @@ -1092,7 +1235,9 @@ MetaD::MetaD(const ActionOptions& ao): acc_rfile.scanField(); found=true; } - if(!found) error("The ACCELERATION_RFILE file you want to read: " + acc_rfilename + ", does not contain a time field!"); + if(!found) { + error("The ACCELERATION_RFILE file you want to read: " + acc_rfilename + ", does not contain a time field!"); + } acc_restart_mean_ = acc_rmean; // Set component based on the read values. getPntrToComponent("acc")->set(acc_rmean); @@ -1101,33 +1246,45 @@ MetaD::MetaD(const ActionOptions& ao): } if (calc_max_bias_) { - if (!grid_) error("Calculating the maximum bias on the fly works only with a grid"); + if (!grid_) { + error("Calculating the maximum bias on the fly works only with a grid"); + } log.printf(" calculation on the fly of the maximum bias max(V(s,t)) \n"); addComponent("maxbias"); componentIsNotPeriodic("maxbias"); } if (calc_transition_bias_) { - if (!grid_) error("Calculating the transition bias on the fly works only with a grid"); + if (!grid_) { + error("Calculating the transition bias on the fly works only with a grid"); + } log.printf(" calculation on the fly of the transition bias V*(t)\n"); addComponent("transbias"); componentIsNotPeriodic("transbias"); log<<" Number of transition wells "< max) error(" transition well is not in grid"); + if (transitionwells_[i][j] < min || transitionwells_[i][j] > max) { + error(" transition well is not in grid"); + } } } } @@ -1153,7 +1310,8 @@ MetaD::MetaD(const ActionOptions& ao): if(fa_max_stride_!=0) { log.printf(" The hill addition frequency will not become larger than %d steps\n",fa_max_stride_); } - addComponent("pace"); componentIsNotPeriodic("pace"); + addComponent("pace"); + componentIsNotPeriodic("pace"); updateFrequencyAdaptiveStride(); } @@ -1168,22 +1326,35 @@ MetaD::MetaD(const ActionOptions& ao): Tools::convert(gmax[i],b); double mesh=(b-a)/((double)gbin[i]); if(adaptive_==FlexibleBin::none) { - if(mesh>0.5*sigma0_[i]) log<<" WARNING: Using a METAD with a Grid Spacing larger than half of the Gaussians width (SIGMA) can produce artifacts\n"; + if(mesh>0.5*sigma0_[i]) { + log<<" WARNING: Using a METAD with a Grid Spacing larger than half of the Gaussians width (SIGMA) can produce artifacts\n"; + } } else { - if(sigma0min_[i]<0.) error("When using ADAPTIVE Gaussians on a grid SIGMA_MIN must be specified"); - if(mesh>0.5*sigma0min_[i]) log<<" WARNING: to use a METAD with a GRID and ADAPTIVE you need to set a Grid Spacing lower than half of the Gaussians (SIGMA_MIN) \n"; + if(sigma0min_[i]<0.) { + error("When using ADAPTIVE Gaussians on a grid SIGMA_MIN must be specified"); + } + if(mesh>0.5*sigma0min_[i]) { + log<<" WARNING: to use a METAD with a GRID and ADAPTIVE you need to set a Grid Spacing lower than half of the Gaussians (SIGMA_MIN) \n"; + } } } std::string funcl=getLabel() + ".bias"; - if(!sparsegrid) {BiasGrid_=Tools::make_unique(funcl,getArguments(),gmin,gmax,gbin,spline,true);} - else {BiasGrid_=Tools::make_unique(funcl,getArguments(),gmin,gmax,gbin,spline,true);} + if(!sparsegrid) { + BiasGrid_=Tools::make_unique(funcl,getArguments(),gmin,gmax,gbin,spline,true); + } else { + BiasGrid_=Tools::make_unique(funcl,getArguments(),gmin,gmax,gbin,spline,true); + } std::vector actualmin=BiasGrid_->getMin(); std::vector actualmax=BiasGrid_->getMax(); for(unsigned i=0; igetDimension()!=getNumberOfArguments()) error("mismatch between dimensionality of input grid and number of arguments"); + if(BiasGrid_->getDimension()!=getNumberOfArguments()) { + error("mismatch between dimensionality of input grid and number of arguments"); + } for(unsigned i=0; iisPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) error("periodicity mismatch between arguments and input bias"); + if( getPntrToArgument(i)->isPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) { + error("periodicity mismatch between arguments and input bias"); + } double a, b; Tools::convert(gmin[i],a); Tools::convert(gmax[i],b); double mesh=(b-a)/((double)gbin[i]); - if(mesh>0.5*sigma0_[i]) log<<" WARNING: Using a METAD with a Grid Spacing larger than half of the Gaussians width can produce artifacts\n"; + if(mesh>0.5*sigma0_[i]) { + log<<" WARNING: Using a METAD with a Grid Spacing larger than half of the Gaussians width can produce artifacts\n"; + } } log.printf(" Restarting from %s\n",gridreadfilename_.c_str()); - if(getRestart()) restartedFromGrid=true; + if(getRestart()) { + restartedFromGrid=true; + } } } // if we are restarting from GRID and using WALKERS_MPI we can check that all walkers have actually read the grid if(getRestart()&&walkers_mpi_) { std::vector restarted(mpi_nw_,0); - if(comm.Get_rank()==0) multi_sim_comm.Allgather(int(restartedFromGrid), restarted); + if(comm.Get_rank()==0) { + multi_sim_comm.Allgather(int(restartedFromGrid), restarted); + } comm.Bcast(restarted,0); int result = std::accumulate(restarted.begin(),restarted.end(),0); - if(result!=0&&result!=mpi_nw_) error("in this WALKERS_MPI run some replica have restarted from GRID while other do not!"); + if(result!=0&&result!=mpi_nw_) { + error("in this WALKERS_MPI run some replica have restarted from GRID while other do not!"); + } } if(walkers_mpi_&&mw_dir_==""&&hillsfname.at(0)!='/') { @@ -1232,7 +1417,9 @@ MetaD::MetaD(const ActionOptions& ao): const std::string ret = std::filesystem::current_path(); mw_dir_ = ret; mw_dir_ = mw_dir_ + "/"; - if(comm.Get_rank()==0) multi_sim_comm.Bcast(mw_dir_,0); + if(comm.Get_rank()==0) { + multi_sim_comm.Bcast(mw_dir_,0); + } comm.Bcast(mw_dir_,0); } @@ -1243,7 +1430,8 @@ MetaD::MetaD(const ActionOptions& ao): std::string fname; if(mw_dir_!="") { if(mw_n_>1) { - std::stringstream out; out << i; + std::stringstream out; + out << i; fname = mw_dir_+"/"+hillsfname+"."+out.str(); } else if(walkers_mpi_) { fname = mw_dir_+"/"+hillsfname; @@ -1252,7 +1440,8 @@ MetaD::MetaD(const ActionOptions& ao): } } else { if(mw_n_>1) { - std::stringstream out; out << i; + std::stringstream out; + out << i; fname = hillsfname+"."+out.str(); } else { fname = hillsfname; @@ -1272,20 +1461,28 @@ MetaD::MetaD(const ActionOptions& ao): } ifiles_[i]->reset(false); // close only the walker own hills file for later writing - if(i==mw_id_) ifiles_[i]->close(); + if(i==mw_id_) { + ifiles_[i]->close(); + } } else { // in case a file does not exist and we are restarting, complain that the file was not found - if(getRestart()&&!restartedFromGrid) error("restart file "+fname+" not found"); + if(getRestart()&&!restartedFromGrid) { + error("restart file "+fname+" not found"); + } } } // if we are restarting from FILE and using WALKERS_MPI we can check that all walkers have actually read the FILE if(getRestart()&&walkers_mpi_) { std::vector restarted(mpi_nw_,0); - if(comm.Get_rank()==0) multi_sim_comm.Allgather(int(restartedFromHills), restarted); + if(comm.Get_rank()==0) { + multi_sim_comm.Allgather(int(restartedFromHills), restarted); + } comm.Bcast(restarted,0); int result = std::accumulate(restarted.begin(),restarted.end(),0); - if(result!=0&&result!=mpi_nw_) error("in this WALKERS_MPI run some replica have restarted from FILE while other do not!"); + if(result!=0&&result!=mpi_nw_) { + error("in this WALKERS_MPI run some replica have restarted from FILE while other do not!"); + } } comm.Barrier(); @@ -1296,23 +1493,34 @@ MetaD::MetaD(const ActionOptions& ao): // it would introduce troubles when using replicas without METAD // (e.g. in bias exchange with a neutral replica) // see issue #168 on github - if(comm.Get_rank()==0 && walkers_mpi_) multi_sim_comm.Barrier(); + if(comm.Get_rank()==0 && walkers_mpi_) { + multi_sim_comm.Barrier(); + } if(targetfilename_.length()>0) { - IFile gridfile; gridfile.open(targetfilename_); + IFile gridfile; + gridfile.open(targetfilename_); std::string funcl=getLabel() + ".target"; TargetGrid_=GridBase::create(funcl,getArguments(),gridfile,false,false,true); - if(TargetGrid_->getDimension()!=getNumberOfArguments()) error("mismatch between dimensionality of input grid and number of arguments"); + if(TargetGrid_->getDimension()!=getNumberOfArguments()) { + error("mismatch between dimensionality of input grid and number of arguments"); + } for(unsigned i=0; iisPeriodic()!=TargetGrid_->getIsPeriodic()[i] ) error("periodicity mismatch between arguments and input bias"); + if( getPntrToArgument(i)->isPeriodic()!=TargetGrid_->getIsPeriodic()[i] ) { + error("periodicity mismatch between arguments and input bias"); + } } } if(getRestart()) { // if this is a restart the neighbor list should be immediately updated - if(nlist_) nlist_update_=true; + if(nlist_) { + nlist_update_=true; + } // Calculate the Tiwary-Parrinello reweighting factor if we are restarting from previous hills - if(calc_rct_) computeReweightingFactor(); + if(calc_rct_) { + computeReweightingFactor(); + } // Calculate all special bias quantities desired if restarting with nonzero bias. if(calc_max_bias_) { max_bias_ = BiasGrid_->getMaxValue(); @@ -1329,12 +1537,18 @@ MetaD::MetaD(const ActionOptions& ao): gridfile_.link(*this); if(walkers_mpi_) { int r=0; - if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank(); + if(comm.Get_rank()==0) { + r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); - if(r>0) gridfilename_="/dev/null"; + if(r>0) { + gridfilename_="/dev/null"; + } + gridfile_.enforceSuffix(""); + } + if(mw_n_>1) { gridfile_.enforceSuffix(""); } - if(mw_n_>1) gridfile_.enforceSuffix(""); gridfile_.open(gridfilename_); } @@ -1342,14 +1556,22 @@ MetaD::MetaD(const ActionOptions& ao): hillsOfile_.link(*this); if(walkers_mpi_) { int r=0; - if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank(); + if(comm.Get_rank()==0) { + r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); - if(r>0) ifilesnames_[mw_id_]="/dev/null"; + if(r>0) { + ifilesnames_[mw_id_]="/dev/null"; + } + hillsOfile_.enforceSuffix(""); + } + if(mw_n_>1) { hillsOfile_.enforceSuffix(""); } - if(mw_n_>1) hillsOfile_.enforceSuffix(""); hillsOfile_.open(ifilesnames_[mw_id_]); - if(fmt_.length()>0) hillsOfile_.fmtField(fmt_); + if(fmt_.length()>0) { + hillsOfile_.fmtField(fmt_); + } hillsOfile_.addConstantField("multivariate"); hillsOfile_.addConstantField("kerneltype"); if(doInt_) { @@ -1358,12 +1580,20 @@ MetaD::MetaD(const ActionOptions& ao): } hillsOfile_.setHeavyFlush(); // output periodicities of variables - for(unsigned i=0; i(p.get())) { concurrent=true; break; } - if(concurrent) log<<" You are using concurrent metadynamics\n"; + for(const auto & p : actionSet) + if(dynamic_cast(p.get())) { + concurrent=true; + break; + } + if(concurrent) { + log<<" You are using concurrent metadynamics\n"; + } if(rect_biasf_.size()>0) { if(walkers_mpi_) { log<<" You are using RECT in its 'altruistic' implementation\n"; @@ -1373,29 +1603,46 @@ MetaD::MetaD(const ActionOptions& ao): } log<<" Bibliography "<1||walkers_mpi_) log<0) log<0 && walkers_mpi_) log<1||walkers_mpi_) { + log<0) { + log<0 && walkers_mpi_) { + log<0) { log< center(ncv); std::vector sigma(ncv); @@ -1435,20 +1684,22 @@ void MetaD::readGaussians(IFile *ifile) bool multivariate=false; std::vector tmpvalues; - for(unsigned j=0; jgetName(), false ) ); + for(unsigned j=0; jgetName(), false ) ); + } - while(scanOneHill(ifile,tmpvalues,center,sigma,height,multivariate)) - { + while(scanOneHill(ifile,tmpvalues,center,sigma,height,multivariate)) { nhills++; // note that for gamma=1 we store directly -F - if(welltemp_ && biasf_>1.0) height*=(biasf_-1.0)/biasf_; + if(welltemp_ && biasf_>1.0) { + height*=(biasf_-1.0)/biasf_; + } addGaussian(Gaussian(multivariate,height,center,sigma)); } log.printf(" %d Gaussians read\n",nhills); } -void MetaD::writeGaussian(const Gaussian& hill, OFile&file) -{ +void MetaD::writeGaussian(const Gaussian& hill, OFile&file) { unsigned ncv=getNumberOfArguments(); file.printField("time",getTimeStep()*getStep()); for(unsigned i=0; igetName(),hill.sigma[i]); + } } double height=hill.height; // note that for gamma=1 we store directly -F - if(welltemp_ && biasf_>1.0) height*=biasf_/(biasf_-1.0); + if(welltemp_ && biasf_>1.0) { + height*=biasf_/(biasf_-1.0); + } file.printField("height",height).printField("biasf",biasf_); - if(mw_n_>1) file.printField("clock",int(std::time(0))); + if(mw_n_>1) { + file.printField("clock",int(std::time(0))); + } file.printField(); } -void MetaD::addGaussian(const Gaussian& hill) -{ +void MetaD::addGaussian(const Gaussian& hill) { if(grid_) { size_t ncv=getNumberOfArguments(); std::vector nneighb=getGaussianSupport(hill); @@ -1511,7 +1766,9 @@ void MetaD::addGaussian(const Gaussian& hill) std::vector dp(ncv); for(size_t i=0; igetPoint(ineigh,xx); double bias=evaluateGaussianAndDerivatives(xx,hill,der,dp); BiasGrid_->addValueAndDerivatives(ineigh,bias,der); @@ -1526,24 +1783,31 @@ void MetaD::addGaussian(const Gaussian& hill) std::vector dp(ncv); for(unsigned i=rank; igetPoint(ineigh,xx); allbias[i]=evaluateGaussianAndDerivatives(xx,hill,n_der,dp); - for(unsigned j=0; jaddValueAndDerivatives(ineigh,allbias[i],der); } } - } else hills_.push_back(hill); + } else { + hills_.push_back(hill); + } } -std::vector MetaD::getGaussianSupport(const Gaussian& hill) -{ +std::vector MetaD::getGaussianSupport(const Gaussian& hill) { std::vector nneigh; std::vector cutoff; unsigned ncv=getNumberOfArguments(); @@ -1566,9 +1830,13 @@ std::vector MetaD::getGaussianSupport(const Gaussian& hill) std::vector myautoval(ncv); //should I take this or their square root? diagMat(myinv,myautoval,myautovec); double maxautoval=0.; - unsigned ind_maxautoval; ind_maxautoval=ncv; + unsigned ind_maxautoval; + ind_maxautoval=ncv; for(unsigned i=0; imaxautoval) {maxautoval=myautoval[i]; ind_maxautoval=i;} + if(myautoval[i]>maxautoval) { + maxautoval=myautoval[i]; + ind_maxautoval=i; + } } for(unsigned i=0; i MetaD::getGaussianSupport(const Gaussian& hill) return nneigh; } -double MetaD::getBias(const std::vector& cv) -{ +double MetaD::getBias(const std::vector& cv) { double bias=0.0; - if(grid_) bias = BiasGrid_->getValue(cv); - else { + if(grid_) { + bias = BiasGrid_->getValue(cv); + } else { unsigned nt=OpenMP::getNumThreads(); unsigned stride=comm.Get_size(); unsigned rank=comm.Get_rank(); @@ -1609,13 +1877,17 @@ double MetaD::getBias(const std::vector& cv) #pragma omp parallel num_threads(nt) { #pragma omp for reduction(+:bias) nowait - for(unsigned i=rank; i& cv) return bias; } -double MetaD::getBiasAndDerivatives(const std::vector& cv, std::vector& der) -{ +double MetaD::getBiasAndDerivatives(const std::vector& cv, std::vector& der) { unsigned ncv=getNumberOfArguments(); double bias=0.0; if(grid_) { std::vector vder(ncv); bias=BiasGrid_->getValueAndDerivatives(cv,vder); - for(unsigned i=0; i& cv, std::vector& cv, std::vector& cv, std::vector(ncv)/2.0); } -double MetaD::evaluateGaussian(const std::vector& cv, const Gaussian& hill) -{ +double MetaD::evaluateGaussian(const std::vector& cv, const Gaussian& hill) { unsigned ncv=cv.size(); // I use a pointer here because cv is const (and should be const) @@ -1720,12 +1998,18 @@ double MetaD::evaluateGaussian(const std::vector& cv, const Gaussian& hi // the upper/lower limit in case it is out of range double tmpcv[1]; const double *pcv=NULL; // pointer to cv - if(ncv>0) pcv=&cv[0]; + if(ncv>0) { + pcv=&cv[0]; + } if(doInt_) { plumed_assert(ncv==1); tmpcv[0]=cv[0]; - if(cv[0]uppI_) tmpcv[0]=uppI_; + if(cv[0]uppI_) { + tmpcv[0]=uppI_; + } pcv=&(tmpcv[0]); } @@ -1760,13 +2044,14 @@ double MetaD::evaluateGaussian(const std::vector& cv, const Gaussian& hi } double bias=0.0; - if(dp2& cv, const Gaussian& hill, std::vector& der, std::vector& dp_) -{ +double MetaD::evaluateGaussianAndDerivatives(const std::vector& cv, const Gaussian& hill, std::vector& der, std::vector& dp_) { unsigned ncv=cv.size(); // I use a pointer here because cv is const (and should be const) @@ -1774,18 +2059,26 @@ double MetaD::evaluateGaussianAndDerivatives(const std::vector& cv, cons // the upper/lower limit in case it is out of range const double *pcv=NULL; // pointer to cv double tmpcv[1]; // tmp array with cv (to be used with doInt_) - if(ncv>0) pcv=&cv[0]; + if(ncv>0) { + pcv=&cv[0]; + } if(doInt_) { plumed_assert(ncv==1); tmpcv[0]=cv[0]; - if(cv[0]uppI_) tmpcv[0]=uppI_; + if(cv[0]uppI_) { + tmpcv[0]=uppI_; + } pcv=&(tmpcv[0]); } bool int_der=false; if(doInt_) { - if(cv[0]uppI_) int_der=true; + if(cv[0]uppI_) { + int_der=true; + } } double dp2=0.0; @@ -1816,11 +2109,15 @@ double MetaD::evaluateGaussianAndDerivatives(const std::vector& cv, cons if(!int_der) { for(unsigned i=0; i& cv, cons if(dp2& cv, cons return bias; } -double MetaD::getHeight(const std::vector& cv) -{ +double MetaD::getHeight(const std::vector& cv) { double height=height0_; if(welltemp_) { double vbias = getBias(cv); @@ -1872,8 +2172,7 @@ double MetaD::getHeight(const std::vector& cv) return height; } -void MetaD::temperHeight(double& height, const TemperingSpecs& t_specs, const double tempering_bias) -{ +void MetaD::temperHeight(double& height, const TemperingSpecs& t_specs, const double tempering_bias) { if (t_specs.alpha == 1.0) { height *= std::exp(-std::max(0.0, tempering_bias - t_specs.threshold) / (kbt_ * (t_specs.biasf - 1.0))); } else { @@ -1881,37 +2180,54 @@ void MetaD::temperHeight(double& height, const TemperingSpecs& t_specs, const do } } -void MetaD::calculate() -{ +void MetaD::calculate() { // this is because presently there is no way to properly pass information // on adaptive hills (diff) after exchanges: - if(adaptive_==FlexibleBin::diffusion && getExchangeStep()) error("ADAPTIVE=DIFF is not compatible with replica exchange"); + if(adaptive_==FlexibleBin::diffusion && getExchangeStep()) { + error("ADAPTIVE=DIFF is not compatible with replica exchange"); + } const unsigned ncv=getNumberOfArguments(); std::vector cv(ncv); - for(unsigned i=0; inlist_param_[1]) {nlist_update_=true; break;} + if(nk_dist2>nlist_param_[1]) { + nlist_update_=true; + break; + } } } - if(nlist_update_) updateNlist(); + if(nlist_update_) { + updateNlist(); + } } double ene = 0.; std::vector der(ncv,0.); - if(biasf_!=1.0) ene = getBiasAndDerivatives(cv,der); + if(biasf_!=1.0) { + ene = getBiasAndDerivatives(cv,der); + } setBias(ene); - for(unsigned i=0; iset(work_); - if(calc_rct_) getPntrToComponent("rbias")->set(ene - reweight_factor_); + if(calc_work_) { + getPntrToComponent("work")->set(work_); + } + if(calc_rct_) { + getPntrToComponent("rbias")->set(ene - reweight_factor_); + } // calculate the acceleration factor if(acceleration_&&!isFirstStep_) { acc_ += static_cast(getStride()) * std::exp(ene/(kbt_)); @@ -1926,22 +2242,26 @@ void MetaD::calculate() } } -void MetaD::update() -{ +void MetaD::update() { // adding hills criteria (could be more complex though) bool nowAddAHill; - if(getStep()%current_stride_==0 && !isFirstStep_) nowAddAHill=true; - else { + if(getStep()%current_stride_==0 && !isFirstStep_) { + nowAddAHill=true; + } else { nowAddAHill=false; isFirstStep_=false; } unsigned ncv=getNumberOfArguments(); std::vector cv(ncv); - for(unsigned i=0; igetInverseMatrix(); + if(adaptive_!=FlexibleBin::none) { + thissigma=flexbin_->getInverseMatrix(); + } // returns normal sigma - else thissigma=sigma0_; + else { + thissigma=sigma0_; + } // In case we use walkers_mpi, it is now necessary to communicate with other replicas. if(walkers_mpi_) { @@ -1990,13 +2314,19 @@ void MetaD::update() // actually add hills one by one std::vector cv_now(ncv); std::vector sigma_now(thissigma.size()); - for(unsigned j=0; j1.0?(biasf_-1.0)/biasf_:1.0); Gaussian newhill=Gaussian(all_multivariate[i],all_height[i]*fact,cv_now,sigma_now); addGaussian(newhill); - if(!flying_) writeGaussian(newhill,hillsOfile_); + if(!flying_) { + writeGaussian(newhill,hillsOfile_); + } } } else { Gaussian newhill=Gaussian(multivariate,height,cv,thissigma); @@ -2005,15 +2335,21 @@ void MetaD::update() } // this is to update the hills neighbor list - if(nlist_) nlist_update_=true; + if(nlist_) { + nlist_update_=true; + } } // this should be outside of the if block in case // mw_rstride_ is not a multiple of stride_ - if(mw_n_>1 && getStep()%mw_rstride_==0) hillsOfile_.flush(); + if(mw_n_>1 && getStep()%mw_rstride_==0) { + hillsOfile_.flush(); + } if(calc_work_) { - if(nlist_) updateNlist(); + if(nlist_) { + updateNlist(); + } double vbias1=getBias(cv); work_+=vbias1-vbias; } @@ -2022,16 +2358,22 @@ void MetaD::update() if(wgridstride_>0&&(getStep()%wgridstride_==0||getCPT())) { // in case old grids are stored, a sequence of grids should appear // this call results in a repetition of the header: - if(storeOldGrids_) gridfile_.clearFields(); + if(storeOldGrids_) { + gridfile_.clearFields(); + } // in case only latest grid is stored, file should be rewound // this will overwrite previously written grids else { int r = 0; if(walkers_mpi_) { - if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank(); + if(comm.Get_rank()==0) { + r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); } - if(r==0) gridfile_.rewind(); + if(r==0) { + gridfile_.rewind(); + } } BiasGrid_->writeToFile(gridfile_); // if a single grid is stored, it is necessary to flush it, otherwise @@ -2040,14 +2382,18 @@ void MetaD::update() // on the other hand, if grids are stored one after the other this is // no necessary, and we leave the flushing control to the user as usual // (with FLUSH keyword) - if(!storeOldGrids_) gridfile_.flush(); + if(!storeOldGrids_) { + gridfile_.flush(); + } } // if multiple walkers and time to read Gaussians if(mw_n_>1 && getStep()%mw_rstride_==0) { for(int i=0; iisOpen())) { // check if it exists now and open it! @@ -2063,12 +2409,16 @@ void MetaD::update() } } // this is to update the hills neighbor list - if(nlist_) nlist_update_=true; + if(nlist_) { + nlist_update_=true; + } } // Recalculate special bias quantities whenever the bias has been changed by the update. bool bias_has_changed = (nowAddAHill || (mw_n_ > 1 && getStep() % mw_rstride_ == 0)); - if (calc_rct_ && bias_has_changed && getStep()%(stride_*rct_ustride_)==0) computeReweightingFactor(); + if (calc_rct_ && bias_has_changed && getStep()%(stride_*rct_ustride_)==0) { + computeReweightingFactor(); + } if (calc_max_bias_ && bias_has_changed) { max_bias_ = BiasGrid_->getMaxValue(); getPntrToComponent("maxbias")->set(max_bias_); @@ -2085,8 +2435,7 @@ void MetaD::update() } /// takes a pointer to the file and a template std::string with values v and gives back the next center, sigma and height -bool MetaD::scanOneHill(IFile* ifile, std::vector& tmpvalues, std::vector& center, std::vector& sigma, double& height, bool& multivariate) -{ +bool MetaD::scanOneHill(IFile* ifile, std::vector& tmpvalues, std::vector& center, std::vector& sigma, double& height, bool& multivariate) { double dummy; multivariate=false; if(ifile->scanField("time",dummy)) { @@ -2096,8 +2445,10 @@ bool MetaD::scanOneHill(IFile* ifile, std::vector& tmpvalues, std::vector if( tmpvalues[i].isPeriodic() && ! getPntrToArgument(i)->isPeriodic() ) { error("in hills file periodicity for variable " + tmpvalues[i].getName() + " does not match periodicity in input"); } else if( tmpvalues[i].isPeriodic() ) { - std::string imin, imax; tmpvalues[i].getDomain( imin, imax ); - std::string rmin, rmax; getPntrToArgument(i)->getDomain( rmin, rmax ); + std::string imin, imax; + tmpvalues[i].getDomain( imin, imax ); + std::string rmin, rmax; + getPntrToArgument(i)->getDomain( rmin, rmax ); if( imin!=rmin || imax!=rmax ) { error("in hills file periodicity for variable " + tmpvalues[i].getName() + " does not match periodicity in input"); } @@ -2106,7 +2457,9 @@ bool MetaD::scanOneHill(IFile* ifile, std::vector& tmpvalues, std::vector } // scan for kerneltype std::string ktype="stretched-gaussian"; - if( ifile->FieldExist("kerneltype") ) ifile->scanField("kerneltype",ktype); + if( ifile->FieldExist("kerneltype") ) { + ifile->scanField("kerneltype",ktype); + } if( ktype=="gaussian" ) { noStretchWarning(); } else if( ktype!="stretched-gaussian") { @@ -2115,9 +2468,13 @@ bool MetaD::scanOneHill(IFile* ifile, std::vector& tmpvalues, std::vector // scan for multivariate label: record the actual file position so to eventually rewind std::string sss; ifile->scanField("multivariate",sss); - if(sss=="true") multivariate=true; - else if(sss=="false") multivariate=false; - else plumed_merror("cannot parse multivariate = "+ sss); + if(sss=="true") { + multivariate=true; + } else if(sss=="false") { + multivariate=false; + } else { + plumed_merror("cannot parse multivariate = "+ sss); + } if(multivariate) { sigma.resize(ncv*(ncv+1)/2); Matrix upper(ncv,ncv); @@ -2149,9 +2506,15 @@ bool MetaD::scanOneHill(IFile* ifile, std::vector& tmpvalues, std::vector ifile->scanField("height",height); ifile->scanField("biasf",dummy); - if(ifile->FieldExist("clock")) ifile->scanField("clock",dummy); - if(ifile->FieldExist("lower_int")) ifile->scanField("lower_int",dummy); - if(ifile->FieldExist("upper_int")) ifile->scanField("upper_int",dummy); + if(ifile->FieldExist("clock")) { + ifile->scanField("clock",dummy); + } + if(ifile->FieldExist("lower_int")) { + ifile->scanField("lower_int",dummy); + } + if(ifile->FieldExist("upper_int")) { + ifile->scanField("upper_int",dummy); + } ifile->scanField(); return true; } else { @@ -2159,8 +2522,7 @@ bool MetaD::scanOneHill(IFile* ifile, std::vector& tmpvalues, std::vector } } -void MetaD::computeReweightingFactor() -{ +void MetaD::computeReweightingFactor() { if(biasf_==1.0) { // in this case we have no bias, so reweight factor is 0.0 getPntrToComponent("rct")->set(0.0); return; @@ -2190,8 +2552,7 @@ void MetaD::computeReweightingFactor() getPntrToComponent("rct")->set(reweight_factor_); } -double MetaD::getTransitionBarrierBias() -{ +double MetaD::getTransitionBarrierBias() { // If there is only one well of interest, return the bias at that well point. if (transitionwells_.size() == 1) { double tb_bias = getBias(transitionwells_[0]); @@ -2224,14 +2585,15 @@ double MetaD::getTransitionBarrierBias() } } -void MetaD::updateFrequencyAdaptiveStride() -{ +void MetaD::updateFrequencyAdaptiveStride() { plumed_massert(freq_adaptive_,"should only be used if frequency adaptive metadynamics is enabled"); plumed_massert(acceleration_,"frequency adaptive metadynamics can only be used if the acceleration factor is calculated"); const double mean_acc = acc_/((double) getStep()); int tmp_stride= stride_*floor((mean_acc/fa_min_acceleration_)+0.5); if(mean_acc >= fa_min_acceleration_) { - if(tmp_stride > current_stride_) {current_stride_ = tmp_stride;} + if(tmp_stride > current_stride_) { + current_stride_ = tmp_stride; + } } if(fa_max_stride_!=0 && current_stride_>fa_max_stride_) { current_stride_=fa_max_stride_; @@ -2239,37 +2601,44 @@ void MetaD::updateFrequencyAdaptiveStride() getPntrToComponent("pace")->set(current_stride_); } -bool MetaD::checkNeedsGradients()const -{ +bool MetaD::checkNeedsGradients()const { if(adaptive_==FlexibleBin::geometry) { - if(getStep()%stride_==0 && !isFirstStep_) return true; - else return false; - } else return false; + if(getStep()%stride_==0 && !isFirstStep_) { + return true; + } else { + return false; + } + } else { + return false; + } } -void MetaD::updateNlist() -{ +void MetaD::updateNlist() { // no need to check for neighbors - if(hills_.size()==0) return; + if(hills_.size()==0) { + return; + } // here we generate the neighbor list nlist_hills_.clear(); std::vector local_flat_nl; unsigned nt=OpenMP::getNumThreads(); - if(hills_.size()<2*nt) nt=1; + if(hills_.size()<2*nt) { + nt=1; + } #pragma omp parallel num_threads(nt) { std::vector private_flat_nl; #pragma omp for nowait - for(unsigned k=0; k dev2; dev2.resize(getNumberOfArguments(),0); - for(unsigned k=0; k0.) nlist_dev2_[i]=dev2[i]/static_cast(nlist_hills_.size()); - else nlist_dev2_[i]=hills_.back().sigma[i]*hills_.back().sigma[i]; + if(dev2[i]>0.) { + nlist_dev2_[i]=dev2[i]/static_cast(nlist_hills_.size()); + } else { + nlist_dev2_[i]=hills_.back().sigma[i]*hills_.back().sigma[i]; + } } // we are done diff --git a/src/bias/MovingRestraint.cpp b/src/bias/MovingRestraint.cpp index 029dc57005..e6898468a7 100644 --- a/src/bias/MovingRestraint.cpp +++ b/src/bias/MovingRestraint.cpp @@ -159,25 +159,33 @@ MovingRestraint::MovingRestraint(const ActionOptions&ao): kk(getNumberOfArguments()), aa(getNumberOfArguments()), f(getNumberOfArguments()), - dpotdk(getNumberOfArguments()) -{ + dpotdk(getNumberOfArguments()) { parseVector("VERSE",verse); - std::vector ss(1); ss[0]=-1; + std::vector ss(1); + ss[0]=-1; std::vector kk( getNumberOfArguments() ), aa( getNumberOfArguments() ); for(int i=0;; i++) { // Read in step - if( !parseNumberedVector("STEP",i,ss) ) break; + if( !parseNumberedVector("STEP",i,ss) ) { + break; + } for(unsigned j=0; jgetName()+"_cntr"; // each spring has its own center - addComponent(comp); componentIsNotPeriodic(comp); + addComponent(comp); + componentIsNotPeriodic(comp); valueCntr.push_back(getPntrToComponent(comp)); comp=getPntrToArgument(i)->getName()+"_work"; // each spring has its own work - addComponent(comp); componentIsNotPeriodic(comp); + addComponent(comp); + componentIsNotPeriodic(comp); valueWork.push_back(getPntrToComponent(comp)); comp=getPntrToArgument(i)->getName()+"_kappa"; // each spring has its own kappa - addComponent(comp); componentIsNotPeriodic(comp); + addComponent(comp); + componentIsNotPeriodic(comp); valueKappa.push_back(getPntrToComponent(comp)); work.push_back(0.); // initialize the work value } - addComponent("work"); componentIsNotPeriodic("work"); + addComponent("work"); + componentIsNotPeriodic("work"); valueTotWork=getPntrToComponent("work"); tot_work=0.0; @@ -237,10 +254,15 @@ void MovingRestraint::calculate() { aa=at[step.size()-1]; } else { unsigned i=0; - for(i=1; iset(aa[i]); const double k=kk[i]; f[i]=-k*cv; - if(verse[i]=="U" && cv<0) continue; - if(verse[i]=="L" && cv>0) continue; + if(verse[i]=="U" && cv<0) { + continue; + } + if(verse[i]=="L" && cv>0) { + continue; + } plumed_assert(verse[i]=="U" || verse[i]=="L" || verse[i]=="B"); dpotdk[i]=0.5*cv*cv; - if(oldaa.size()==aa.size() && oldf.size()==f.size()) work[i]+=0.5*(oldf[i]+f[i])*(aa[i]-oldaa[i]) + 0.5*( dpotdk[i]+olddpotdk[i] )*(kk[i]-oldk[i]); + if(oldaa.size()==aa.size() && oldf.size()==f.size()) { + work[i]+=0.5*(oldf[i]+f[i])*(aa[i]-oldaa[i]) + 0.5*( dpotdk[i]+olddpotdk[i] )*(kk[i]-oldk[i]); + } valueWork[i]->set(work[i]); valueKappa[i]->set(kk[i]); tot_work+=work[i]; diff --git a/src/bias/PBMetaD.cpp b/src/bias/PBMetaD.cpp index 3f7c4b1b8d..0d20a5078a 100644 --- a/src/bias/PBMetaD.cpp +++ b/src/bias/PBMetaD.cpp @@ -244,7 +244,12 @@ class PBMetaD : public Bias { Gaussian(const std::vector & center,const std::vector & sigma, double height, bool multivariate): center(center),sigma(sigma),height(height),multivariate(multivariate),invsigma(sigma) { // to avoid troubles from zero element in flexible hills - for(unsigned i=0; i1.e-20) invsigma[i]=1.0/invsigma[i] ; else invsigma[i]=0.0; + for(unsigned i=0; i1.e-20) { + invsigma[i]=1.0/invsigma[i] ; + } else { + invsigma[i]=0.0; + } } }; // general setup @@ -380,8 +385,7 @@ PBMetaD::PBMetaD(const ActionOptions& ao): pf_n_(0), do_pf_(false), mw_n_(1), mw_dir_(""), mw_id_(0), mw_rstride_(1), walkers_mpi_(false), mpi_nw_(0), - do_select_(false) -{ + do_select_(false) { // parse the flexible hills std::string adaptiveoption; @@ -407,7 +411,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): std::vector familyargs; for(int i = 0;; i++) { parseArgumentList("PF", i, familyargs); - if (familyargs.empty()) break; + if (familyargs.empty()) { + break; + } do_pf_ = true; log << " Identified Partitioned Family " << i << ":"; @@ -446,7 +452,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } else { // If we are doing PF, make sure each argument got assigned to a family. for (unsigned i = 0; i < getNumberOfArguments(); i++) { - if (pfs_[i] == -1) error(getPntrToArgument(i)->getName() + " was not assigned a PF"); + if (pfs_[i] == -1) { + error(getPntrToArgument(i)->getName() + " was not assigned a PF"); + } } } @@ -475,7 +483,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): error("the number of SIGMA_MIN values be the same of the number of the arguments/PF"); } else if(sigma0min_.size()==0) { sigma0min_.resize(pf_n_); - for(unsigned i=0; i1.0) { - if(kbt_==0.0) error("Unless the MD engine passes the temperature to plumed, with well-tempered metad you must specify it using TEMP"); + if(kbt_==0.0) { + error("Unless the MD engine passes the temperature to plumed, with well-tempered metad you must specify it using TEMP"); + } welltemp_=true; } double tau=0.0; parse("TAU",tau); if(tau==0.0) { - if(height0_==std::numeric_limits::max()) error("At least one between HEIGHT and TAU should be specified"); + if(height0_==std::numeric_limits::max()) { + error("At least one between HEIGHT and TAU should be specified"); + } // if tau is not set, we compute it here from the other input parameters - if(welltemp_) tau=(kbt_*(biasf_-1.0))/height0_*getTimeStep()*stride_; + if(welltemp_) { + tau=(kbt_*(biasf_-1.0))/height0_*getTimeStep()*stride_; + } } else { - if(!welltemp_)error("TAU only makes sense in well-tempered metadynamics"); - if(height0_!=std::numeric_limits::max()) error("At most one between HEIGHT and TAU should be specified"); + if(!welltemp_) { + error("TAU only makes sense in well-tempered metadynamics"); + } + if(height0_!=std::numeric_limits::max()) { + error("At most one between HEIGHT and TAU should be specified"); + } height0_=(kbt_*(biasf_-1.0))/tau*getTimeStep()*stride_; } @@ -534,7 +560,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): // Multiple walkers parse("WALKERS_N",mw_n_); parse("WALKERS_ID",mw_id_); - if(mw_n_<=mw_id_) error("walker ID should be a numerical value less than the total number of walkers"); + if(mw_n_<=mw_id_) { + error("walker ID should be a numerical value less than the total number of walkers"); + } parse("WALKERS_DIR",mw_dir_); parse("WALKERS_RSTRIDE",mw_rstride_); @@ -554,8 +582,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): gridfilenames_.push_back(name); } } - if(gridfilenames_.size() > 0 && hillsfname_.size() > 0 && gridfilenames_.size() != hillsfname_.size()) + if(gridfilenames_.size() > 0 && hillsfname_.size() > 0 && gridfilenames_.size() != hillsfname_.size()) { error("number of GRID_WFILES arguments does not match number of HILLS files"); + } // Read grid std::vector gridreadfilenames_; @@ -564,32 +593,53 @@ PBMetaD::PBMetaD(const ActionOptions& ao): // Grid Stuff std::vector gmin(pf_n_); parseVector("GRID_MIN",gmin); - if(gmin.size()!=pf_n_ && gmin.size()!=0) error("not enough values for GRID_MIN"); + if(gmin.size()!=pf_n_ && gmin.size()!=0) { + error("not enough values for GRID_MIN"); + } std::vector gmax(pf_n_); parseVector("GRID_MAX",gmax); - if(gmax.size()!=pf_n_ && gmax.size()!=0) error("not enough values for GRID_MAX"); + if(gmax.size()!=pf_n_ && gmax.size()!=0) { + error("not enough values for GRID_MAX"); + } std::vector gbin(pf_n_); std::vector gspacing; parseVector("GRID_BIN",gbin); - if(gbin.size()!=pf_n_ && gbin.size()!=0) error("not enough values for GRID_BIN"); + if(gbin.size()!=pf_n_ && gbin.size()!=0) { + error("not enough values for GRID_BIN"); + } parseVector("GRID_SPACING",gspacing); - if(gspacing.size()!=pf_n_ && gspacing.size()!=0) error("not enough values for GRID_SPACING"); - if(gmin.size()!=gmax.size()) error("GRID_MAX and GRID_MIN should be either present or absent"); - if(gspacing.size()!=0 && gmin.size()==0) error("If GRID_SPACING is present also GRID_MIN and GRID_MAX should be present"); - if(gbin.size()!=0 && gmin.size()==0) error("If GRID_BIN is present also GRID_MIN and GRID_MAX should be present"); + if(gspacing.size()!=pf_n_ && gspacing.size()!=0) { + error("not enough values for GRID_SPACING"); + } + if(gmin.size()!=gmax.size()) { + error("GRID_MAX and GRID_MIN should be either present or absent"); + } + if(gspacing.size()!=0 && gmin.size()==0) { + error("If GRID_SPACING is present also GRID_MIN and GRID_MAX should be present"); + } + if(gbin.size()!=0 && gmin.size()==0) { + error("If GRID_BIN is present also GRID_MIN and GRID_MAX should be present"); + } if(gmin.size()!=0) { if(gbin.size()==0 && gspacing.size()==0) { if(adaptive_==FlexibleBin::none) { log<<" Binsize not specified, 1/5 of sigma will be be used\n"; plumed_assert(sigma0_.size()==pf_n_); gspacing.resize(pf_n_); - for(unsigned i=0; i0) grid_=true; + if(gbin.size()>0) { + grid_=true; + } bool sparsegrid=false; parseFlag("GRID_SPARSE",sparsegrid); bool nospline=false; parseFlag("GRID_NOSPLINE",nospline); bool spline=!nospline; - if(!grid_&&gridfilenames_.size() > 0) error("To write a grid you need first to define it!"); - if(!grid_&&gridreadfilenames_.size() > 0) error("To read a grid you need first to define it!"); + if(!grid_&&gridfilenames_.size() > 0) { + error("To write a grid you need first to define it!"); + } + if(!grid_&&gridreadfilenames_.size() > 0) { + error("To read a grid you need first to define it!"); + } doInt_.resize(pf_n_,false); // Interval keyword parseVector("INTERVAL_MIN",lowI_); parseVector("INTERVAL_MAX",uppI_); // various checks - if(lowI_.size()!=uppI_.size()) error("both a lower and an upper limits must be provided with INTERVAL"); - if(lowI_.size()!=0 && lowI_.size()!=pf_n_) error("check number of argument of INTERVAL"); + if(lowI_.size()!=uppI_.size()) { + error("both a lower and an upper limits must be provided with INTERVAL"); + } + if(lowI_.size()!=0 && lowI_.size()!=pf_n_) { + error("check number of argument of INTERVAL"); + } for(unsigned i=0; iisPeriodic()) warning("INTERVAL is not used for periodic variables"); - else doInt_[i]=true; + if(uppI_[i]isPeriodic()) { + warning("INTERVAL is not used for periodic variables"); + } else { + doInt_[i]=true; + } } // parse selector stuff @@ -639,13 +709,21 @@ PBMetaD::PBMetaD(const ActionOptions& ao): checkRead(); log.printf(" Gaussian width "); - if (adaptive_==FlexibleBin::diffusion)log.printf(" (Note: The units of sigma are in timesteps) "); - if (adaptive_==FlexibleBin::geometry)log.printf(" (Note: The units of sigma are in dist units) "); - for(unsigned i=0; i1) { - if(walkers_mpi_) error("MPI version of multiple walkers is not compatible with filesystem version of multiple walkers"); + if(walkers_mpi_) { + error("MPI version of multiple walkers is not compatible with filesystem version of multiple walkers"); + } log.printf(" %d multiple walkers active\n",mw_n_); log.printf(" walker id %d\n",mw_id_); log.printf(" reading stride %d\n",mw_rstride_); - if(mw_dir_!="")log.printf(" directory with hills files %s\n",mw_dir_.c_str()); + if(mw_dir_!="") { + log.printf(" directory with hills files %s\n",mw_dir_.c_str()); + } } else { if(walkers_mpi_) { log.printf(" Multiple walkers active using MPI communnication\n"); - if(mw_dir_!="")log.printf(" directory with hills files %s\n",mw_dir_.c_str()); + if(mw_dir_!="") { + log.printf(" directory with hills files %s\n",mw_dir_.c_str()); + } if(comm.Get_rank()==0) { // Only root of group can communicate with other walkers mpi_nw_ = multi_sim_comm.Get_size(); @@ -681,20 +765,32 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } for(unsigned i=0; i0) { for(unsigned i=0; i0.5*sigma0_[i]) log<<" WARNING: Using a PBMETAD with a Grid Spacing larger than half of the Gaussians width can produce artifacts\n"; + if(mesh>0.5*sigma0_[i]) { + log<<" WARNING: Using a PBMETAD with a Grid Spacing larger than half of the Gaussians width can produce artifacts\n"; + } } else { - if(mesh>0.5*sigma0min_[i]||sigma0min_[i]<0.) log<<" WARNING: to use a PBMETAD with a GRID and ADAPTIVE you need to set a Grid Spacing larger than half of the Gaussians \n"; + if(mesh>0.5*sigma0min_[i]||sigma0min_[i]<0.) { + log<<" WARNING: to use a PBMETAD with a GRID and ADAPTIVE you need to set a Grid Spacing larger than half of the Gaussians \n"; + } } } std::string funcl=getLabel() + ".bias"; @@ -757,16 +857,25 @@ PBMetaD::PBMetaD(const ActionOptions& ao): error("periodicity mismatch between arguments and input bias"); } log.printf(" Restarting from %s:\n",gridreadfilenames_[i].c_str()); - if(getRestart()) restartedFromGrid=true; + if(getRestart()) { + restartedFromGrid=true; + } } else { - if(!sparsegrid) {BiasGrid_=Tools::make_unique(funcl,args,gmin_t,gmax_t,gbin_t,spline,true);} - else {BiasGrid_=Tools::make_unique(funcl,args,gmin_t,gmax_t,gbin_t,spline,true);} + if(!sparsegrid) { + BiasGrid_=Tools::make_unique(funcl,args,gmin_t,gmax_t,gbin_t,spline,true); + } else { + BiasGrid_=Tools::make_unique(funcl,args,gmin_t,gmax_t,gbin_t,spline,true); + } std::vector actualmin=BiasGrid_->getMin(); std::vector actualmax=BiasGrid_->getMax(); std::string is; Tools::convert(i,is); - if(gmin_t[0]!=actualmin[0]) error("GRID_MIN["+is+"] must be adjusted to "+actualmin[0]+" to fit periodicity"); - if(gmax_t[0]!=actualmax[0]) error("GRID_MAX["+is+"] must be adjusted to "+actualmax[0]+" to fit periodicity"); + if(gmin_t[0]!=actualmin[0]) { + error("GRID_MIN["+is+"] must be adjusted to "+actualmin[0]+" to fit periodicity"); + } + if(gmax_t[0]!=actualmax[0]) { + error("GRID_MAX["+is+"] must be adjusted to "+actualmax[0]+" to fit periodicity"); + } } BiasGrids_.emplace_back(std::move(BiasGrid_)); } @@ -783,7 +892,8 @@ PBMetaD::PBMetaD(const ActionOptions& ao): std::string fname; if(mw_dir_!="") { if(mw_n_>1) { - std::stringstream out; out << j; + std::stringstream out; + out << j; fname = mw_dir_+"/"+hillsfname_[i]+"."+out.str(); } else if(walkers_mpi_) { fname = mw_dir_+"/"+hillsfname_[i]; @@ -792,7 +902,8 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } } else { if(mw_n_>1) { - std::stringstream out; out << j; + std::stringstream out; + out << j; fname = hillsfname_[i]+"."+out.str(); } else { fname = hillsfname_[i]; @@ -811,16 +922,22 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } ifiles_[k]->reset(false); // close only the walker own hills file for later writing - if(j==mw_id_) ifiles_[k]->close(); + if(j==mw_id_) { + ifiles_[k]->close(); + } } else { // in case a file does not exist and we are restarting, complain that the file was not found - if(getRestart()) log<<" WARNING: restart file "<0) ifilesnames_[mw_id_*hillsfname_.size()+i]="/dev/null"; + if(r>0) { + ifilesnames_[mw_id_*hillsfname_.size()+i]="/dev/null"; + } + ofile->enforceSuffix(""); + } + if(mw_n_>1) { ofile->enforceSuffix(""); } - if(mw_n_>1) ofile->enforceSuffix(""); ofile->open(ifilesnames_[mw_id_*hillsfname_.size()+i]); - if(fmt_.length()>0) ofile->fmtField(fmt_); + if(fmt_.length()>0) { + ofile->fmtField(fmt_); + } ofile->addConstantField("multivariate"); ofile->addConstantField("kerneltype"); if(doInt_[i]) { @@ -867,7 +992,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } ofile->enforceSuffix(""); } - if(mw_n_>1) ofile->enforceSuffix(""); + if(mw_n_>1) { + ofile->enforceSuffix(""); + } ofile->open(gridfname_tmp); ofile->setHeavyFlush(); gridfiles_.emplace_back(std::move(ofile)); @@ -875,20 +1002,24 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } log<<" Bibliography "<1||walkers_mpi_) log<1||walkers_mpi_) + log< center(1); std::vector sigma(1); double height; @@ -902,14 +1033,15 @@ void PBMetaD::readGaussians(unsigned iarg, IFile *ifile) while(scanOneHill(iarg,ifile,tmpvalues,center,sigma,height,multivariate)) { ; nhills++; - if(welltemp_) {height*=(biasf_-1.0)/biasf_;} + if(welltemp_) { + height*=(biasf_-1.0)/biasf_; + } addGaussian(family, Gaussian(center,sigma,height,multivariate)); } log.printf(" %d Gaussians read\n",nhills); } -void PBMetaD::writeGaussian(unsigned iarg, const Gaussian& hill, OFile *ofile) -{ +void PBMetaD::writeGaussian(unsigned iarg, const Gaussian& hill, OFile *ofile) { int family=pfs_[iarg]; ofile->printField("time",getTimeStep()*getStep()); ofile->printField(pfhold_[family],hill.center[0]); @@ -925,17 +1057,21 @@ void PBMetaD::writeGaussian(unsigned iarg, const Gaussian& hill, OFile *ofile) ofile->printField("sigma_"+pfhold_[family]->getName(),hill.sigma[0]); } double height=hill.height; - if(welltemp_) height *= biasf_/(biasf_-1.0); + if(welltemp_) { + height *= biasf_/(biasf_-1.0); + } ofile->printField("height",height); ofile->printField("biasf",biasf_); - if(mw_n_>1) ofile->printField("clock",int(std::time(0))); + if(mw_n_>1) { + ofile->printField("clock",int(std::time(0))); + } ofile->printField(); } -void PBMetaD::addGaussian(unsigned iarg, const Gaussian& hill) -{ - if(!grid_) {hills_[iarg].push_back(hill);} - else { +void PBMetaD::addGaussian(unsigned iarg, const Gaussian& hill) { + if(!grid_) { + hills_[iarg].push_back(hill); + } else { std::vector nneighb=getGaussianSupport(iarg, hill); std::vector neighbors=BiasGrids_[iarg]->getNeighbors(hill.center,nneighb); std::vector der(1); @@ -969,8 +1105,7 @@ void PBMetaD::addGaussian(unsigned iarg, const Gaussian& hill) } } -std::vector PBMetaD::getGaussianSupport(unsigned iarg, const Gaussian& hill) -{ +std::vector PBMetaD::getGaussianSupport(unsigned iarg, const Gaussian& hill) { std::vector nneigh; double cutoff; if(hill.multivariate) { @@ -995,8 +1130,7 @@ std::vector PBMetaD::getGaussianSupport(unsigned iarg, const Gaussian& return nneigh; } -double PBMetaD::getBiasAndDerivatives(unsigned iarg, const std::vector& cv, double* der) -{ +double PBMetaD::getBiasAndDerivatives(unsigned iarg, const std::vector& cv, double* der) { double bias=0.0; int family = pfs_[iarg]; if(!grid_) { @@ -1006,7 +1140,9 @@ double PBMetaD::getBiasAndDerivatives(unsigned iarg, const std::vector& bias += evaluateGaussian(iarg,cv,hills_[family][i],der); } comm.Sum(bias); - if(der) comm.Sum(der,1); + if(der) { + comm.Sum(der,1); + } } else { if(der) { std::vector vder(1); @@ -1020,8 +1156,7 @@ double PBMetaD::getBiasAndDerivatives(unsigned iarg, const std::vector& return bias; } -double PBMetaD::evaluateGaussian(unsigned iarg, const std::vector& cv, const Gaussian& hill, double* der) -{ +double PBMetaD::evaluateGaussian(unsigned iarg, const std::vector& cv, const Gaussian& hill, double* der) { double bias=0.0; // I use a pointer here because cv is const (and should be const) // but when using doInt it is easier to locally replace cv[0] with @@ -1031,8 +1166,13 @@ double PBMetaD::evaluateGaussian(unsigned iarg, const std::vector& cv, c tmpcv[0]=cv[0]; bool isOutOfInt = false; if(doInt_[iarg]) { - if(cv[0]uppI_[iarg]) { tmpcv[0]=uppI_[iarg]; isOutOfInt = true; } + if(cv[0]uppI_[iarg]) { + tmpcv[0]=uppI_[iarg]; + isOutOfInt = true; + } } pcv=&(tmpcv[0]); @@ -1061,11 +1201,12 @@ double PBMetaD::evaluateGaussian(unsigned iarg, const std::vector& cv, c return bias; } -void PBMetaD::calculate() -{ +void PBMetaD::calculate() { // this is because presently there is no way to properly pass information // on adaptive hills (diff) after exchanges: - if(adaptive_==FlexibleBin::diffusion && getExchangeStep()) error("ADAPTIVE=DIFF is not compatible with replica exchange"); + if(adaptive_==FlexibleBin::diffusion && getExchangeStep()) { + error("ADAPTIVE=DIFF is not compatible with replica exchange"); + } std::vector cv(1); double der[1]; @@ -1079,7 +1220,9 @@ void PBMetaD::calculate() der[0] = 0.0; bias[i] = getBiasAndDerivatives(i, cv, der); deriv[i] = der[0]; - if(bias[i] < bmin) bmin = bias[i]; + if(bias[i] < bmin) { + bmin = bias[i]; + } } double ene = 0.; for(unsigned i=0; i(plumed.passMap[selector_]); + if(do_select_) { + current_value_ = static_cast(plumed.passMap[selector_]); + } if(!do_select_ || select_value_==current_value_) { for(unsigned i=0; i0 && (getStep()%wgridstride_==0 || getCPT())) { int r = 0; if(walkers_mpi_) { - if(comm.Get_rank()==0) r=multi_sim_comm.Get_rank(); + if(comm.Get_rank()==0) { + r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); } if(r==0) { @@ -1229,7 +1390,9 @@ void PBMetaD::update() for(unsigned i=0; iisOpen())) { // check if it exists now and open it! @@ -1250,8 +1413,7 @@ void PBMetaD::update() } /// takes a pointer to the file and a template string with values v and gives back the next center, sigma and height -bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpvalues, std::vector ¢er, std::vector &sigma, double &height, bool &multivariate) -{ +bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpvalues, std::vector ¢er, std::vector &sigma, double &height, bool &multivariate) { double dummy; multivariate=false; Value* argPtr = pfhold_[pfs_[iarg]]; @@ -1260,15 +1422,19 @@ bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpva if( tmpvalues[0].isPeriodic() && ! argPtr->isPeriodic() ) { error("in hills file periodicity for variable " + tmpvalues[0].getName() + " does not match periodicity in input"); } else if( tmpvalues[0].isPeriodic() ) { - std::string imin, imax; tmpvalues[0].getDomain( imin, imax ); - std::string rmin, rmax; argPtr->getDomain( rmin, rmax ); + std::string imin, imax; + tmpvalues[0].getDomain( imin, imax ); + std::string rmin, rmax; + argPtr->getDomain( rmin, rmax ); if( imin!=rmin || imax!=rmax ) { error("in hills file periodicity for variable " + tmpvalues[0].getName() + " does not match periodicity in input"); } } center[0]=tmpvalues[0].get(); std::string ktype="stretched-gaussian"; - if( ifile->FieldExist("kerneltype") ) ifile->scanField("kerneltype",ktype); + if( ifile->FieldExist("kerneltype") ) { + ifile->scanField("kerneltype",ktype); + } if( ktype=="gaussian" ) { noStretchWarning(); @@ -1278,9 +1444,13 @@ bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpva std::string sss; ifile->scanField("multivariate",sss); - if(sss=="true") multivariate=true; - else if(sss=="false") multivariate=false; - else plumed_merror("cannot parse multivariate = "+ sss); + if(sss=="true") { + multivariate=true; + } else if(sss=="false") { + multivariate=false; + } else { + plumed_merror("cannot parse multivariate = "+ sss); + } if(multivariate) { ifile->scanField("sigma_"+argPtr->getName()+"_"+ argPtr->getName(),sigma[0]); @@ -1290,9 +1460,15 @@ bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpva } ifile->scanField("height",height); ifile->scanField("biasf",dummy); - if(ifile->FieldExist("clock")) ifile->scanField("clock",dummy); - if(ifile->FieldExist("lower_int")) ifile->scanField("lower_int",dummy); - if(ifile->FieldExist("upper_int")) ifile->scanField("upper_int",dummy); + if(ifile->FieldExist("clock")) { + ifile->scanField("clock",dummy); + } + if(ifile->FieldExist("lower_int")) { + ifile->scanField("lower_int",dummy); + } + if(ifile->FieldExist("upper_int")) { + ifile->scanField("upper_int",dummy); + } ifile->scanField(); return true; } else { @@ -1301,12 +1477,16 @@ bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpva } -bool PBMetaD::checkNeedsGradients()const -{ +bool PBMetaD::checkNeedsGradients()const { if(adaptive_==FlexibleBin::geometry) { - if(getStep()%stride_==0 && !isFirstStep_) return true; - else return false; - } else return false; + if(getStep()%stride_==0 && !isFirstStep_) { + return true; + } else { + return false; + } + } else { + return false; + } } } diff --git a/src/bias/Restraint.cpp b/src/bias/Restraint.cpp index 481d07a93f..862f5e26be 100644 --- a/src/bias/Restraint.cpp +++ b/src/bias/Restraint.cpp @@ -80,7 +80,8 @@ PLUMED_REGISTER_ACTION(Restraint,"RESTRAINT_SCALAR") void Restraint::registerKeywords(Keywords& keys) { Bias::registerKeywords(keys); - keys.use("ARG"); keys.setDisplayName("RESTRAINT"); + keys.use("ARG"); + keys.setDisplayName("RESTRAINT"); keys.add("compulsory","SLOPE","0.0","specifies that the restraint is linear and what the values of the force constants on each of the variables are"); keys.add("compulsory","KAPPA","0.0","specifies that the restraint is harmonic and what the values of the force constants on each of the variables are"); keys.add("compulsory","AT","the position of the restraint"); @@ -91,21 +92,26 @@ Restraint::Restraint(const ActionOptions&ao): PLUMED_BIAS_INIT(ao), at(getNumberOfArguments()), kappa(getNumberOfArguments(),0.0), - slope(getNumberOfArguments(),0.0) -{ + slope(getNumberOfArguments(),0.0) { parseVector("SLOPE",slope); parseVector("KAPPA",kappa); parseVector("AT",at); checkRead(); log.printf(" at"); - for(unsigned i=0; i args; parseVector("ARG",args); - if( args.size()==0 ) error("found no input arguments"); - std::vector vals; ActionWithArguments::interpretArgumentList( args, plumed.getActionSet(), this, vals ); - if( vals.size()==0 ) error("found no input arguments"); + std::vector args; + parseVector("ARG",args); + if( args.size()==0 ) { + error("found no input arguments"); + } + std::vector vals; + ActionWithArguments::interpretArgumentList( args, plumed.getActionSet(), this, vals ); + if( vals.size()==0 ) { + error("found no input arguments"); + } // Find the rank unsigned rank=vals[0]->getRank(); for(unsigned i=0; igetRank()>0 && vals[i]->hasDerivatives() ) error("argument should not be function on grid"); - if( vals[i]->getRank()!=rank ) error("all arguments should have same rank"); + if( vals[i]->getRank()>0 && vals[i]->hasDerivatives() ) { + error("argument should not be function on grid"); + } + if( vals[i]->getRank()!=rank ) { + error("all arguments should have same rank"); + } } if( rank==0 ) { - std::vector slope(args.size()); parseVector("SLOPE",slope); std::string slopestr=""; - if( slope[0]!="0.0" ) { slopestr="SLOPE=" + slope[0]; for(unsigned i=1; i slope(args.size()); + parseVector("SLOPE",slope); + std::string slopestr=""; + if( slope[0]!="0.0" ) { + slopestr="SLOPE=" + slope[0]; + for(unsigned i=1; i at; parseVector("AT",at); - std::vector slope(at.size()); parseVector("SLOPE",slope); - std::vector kappa(at.size()); parseVector("KAPPA",kappa); - - std::string biasargs, forceargs; bool non_constant_force=false; + std::string stride; + parse("STRIDE",stride); + std::vector at; + parseVector("AT",at); + std::vector slope(at.size()); + parseVector("SLOPE",slope); + std::vector kappa(at.size()); + parseVector("KAPPA",kappa); + + std::string biasargs, forceargs; + bool non_constant_force=false; for(unsigned i=0; i0 ) { readInputLine( getShortcutLabel() + "_linear_" + argn + ": CUSTOM PERIODIC=NO FUNC=" + slope[i] + "*x ARG=" + getShortcutLabel() + "_cv_" + argn ); readInputLine( getShortcutLabel() + "_slope_" + argn + ": SUM PERIODIC=NO ARG=" + getShortcutLabel() + "_linear_" + argn ); - if( biasargs.length()==0 ) biasargs = "ARG=" + getShortcutLabel() + "_slope_" + argn; else biasargs += "," + getShortcutLabel() + "_slope_" + argn; + if( biasargs.length()==0 ) { + biasargs = "ARG=" + getShortcutLabel() + "_slope_" + argn; + } else { + biasargs += "," + getShortcutLabel() + "_slope_" + argn; + } } } // This is the bias readInputLine( getShortcutLabel() + "_bias: COMBINE PERIODIC=NO " + biasargs ); readInputLine( getShortcutLabel() + ": BIASVALUE ARG=" + getShortcutLabel() + "_bias STRIDE=" + stride ); - if( non_constant_force ) readInputLine( getShortcutLabel() + "_force2: COMBINE PERIODIC=NO " + forceargs ); + if( non_constant_force ) { + readInputLine( getShortcutLabel() + "_force2: COMBINE PERIODIC=NO " + forceargs ); + } } } diff --git a/src/bias/ReweightBase.cpp b/src/bias/ReweightBase.cpp index d06a2614b3..abaf820092 100644 --- a/src/bias/ReweightBase.cpp +++ b/src/bias/ReweightBase.cpp @@ -36,12 +36,14 @@ void ReweightBase::registerKeywords(Keywords& keys) { ReweightBase::ReweightBase(const ActionOptions&ao): Action(ao), ActionWithValue(ao), - ActionWithArguments(ao) -{ + ActionWithArguments(ao) { simtemp=getkBT(); - if(simtemp==0) error("The MD engine does not pass the temperature to plumed so you have to specify it using TEMP"); + if(simtemp==0) { + error("The MD engine does not pass the temperature to plumed so you have to specify it using TEMP"); + } // Create something to hold the weight - addValue(); setNotPeriodic(); + addValue(); + setNotPeriodic(); } void ReweightBase::calculate() { diff --git a/src/bias/ReweightBase.h b/src/bias/ReweightBase.h index ac690f8c39..34a5ff2c6f 100644 --- a/src/bias/ReweightBase.h +++ b/src/bias/ReweightBase.h @@ -30,20 +30,25 @@ namespace bias { class ReweightBase : public ActionWithValue, - public ActionWithArguments -{ + public ActionWithArguments { protected: /// The temperature at which you are running the simulation double simtemp; public: static void registerKeywords(Keywords&); explicit ReweightBase(const ActionOptions&ao); - unsigned getNumberOfDerivatives() override { return 0; } - virtual bool buildsWeightStore() const { return false; } + unsigned getNumberOfDerivatives() override { + return 0; + } + virtual bool buildsWeightStore() const { + return false; + } void calculate() override; virtual void calculateWeights( const unsigned& nframes ) {} virtual double getLogWeight() = 0; - virtual double getWeight( const unsigned& iweight ) const { plumed_error(); } + virtual double getWeight( const unsigned& iweight ) const { + plumed_error(); + } virtual void clearData() {} void apply() override {} }; diff --git a/src/bias/ReweightBias.cpp b/src/bias/ReweightBias.cpp index e394eb471c..4ace231443 100644 --- a/src/bias/ReweightBias.cpp +++ b/src/bias/ReweightBias.cpp @@ -78,20 +78,23 @@ class ReweightBias : public ReweightBase { PLUMED_REGISTER_ACTION(ReweightBias,"REWEIGHT_BIAS") void ReweightBias::registerKeywords(Keywords& keys ) { - ReweightBase::registerKeywords( keys ); keys.remove("ARG"); + ReweightBase::registerKeywords( keys ); + keys.remove("ARG"); keys.add("compulsory","ARG","*.bias","the biases that must be taken into account when reweighting"); keys.setValueDescription("the weight to use for this frame to negate the effect the bias"); } ReweightBias::ReweightBias(const ActionOptions&ao): Action(ao), - ReweightBase(ao) -{ + ReweightBase(ao) { } double ReweightBias::getLogWeight() { // Retrieve the bias - double bias=0.0; for(unsigned i=0; igetName().c_str()); + for(unsigned i=0; igetName().c_str()); + } log.printf("\n"); } //requestArguments(myenergy); @@ -222,7 +223,9 @@ ReweightTemperaturePressure::ReweightTemperaturePressure(const ActionOptions&ao) parseArgumentList("VOLUME",myvol); if(!myvol.empty()) { log.printf(" with volumes: "); - for(unsigned i=0; igetName().c_str()); + for(unsigned i=0; igetName().c_str()); + } log.printf("\n"); } @@ -238,27 +241,49 @@ ReweightTemperaturePressure::ReweightTemperaturePressure(const ActionOptions&ao) log.printf(" WARNING: If the simulation is performed at constant pressure add the keywords PRESSURE and VOLUME \n" ); } // Case 2) Reweight from T to T' with P=const (isothermal-isobaric) - else if (rtemp_>=0 && press_>=0 && rpress_<0 && !myenergy.empty() && !myvol.empty() ) log.printf(" reweighting simulation from temperature %f to temperature %f at constant pressure %f \n",simtemp/getKBoltzmann(),rtemp_/getKBoltzmann(), press_ ); + else if (rtemp_>=0 && press_>=0 && rpress_<0 && !myenergy.empty() && !myvol.empty() ) { + log.printf(" reweighting simulation from temperature %f to temperature %f at constant pressure %f \n",simtemp/getKBoltzmann(),rtemp_/getKBoltzmann(), press_ ); + } // Case 3) Reweight from P to P' with T=const (isothermal-isobaric) - else if (rtemp_<0 && press_>=0 && rpress_>=0 && myenergy.empty() && !myvol.empty() ) log.printf(" reweighting simulation from pressure %f to pressure %f at constant temperature %f\n",press_,rpress_,simtemp/getKBoltzmann() ); + else if (rtemp_<0 && press_>=0 && rpress_>=0 && myenergy.empty() && !myvol.empty() ) { + log.printf(" reweighting simulation from pressure %f to pressure %f at constant temperature %f\n",press_,rpress_,simtemp/getKBoltzmann() ); + } // Case 4) Reweight from T,P to T',P' (isothermal-isobaric) - else if (rtemp_>0 && press_>=0 && rpress_>=0 && !myenergy.empty() && !myvol.empty() ) log.printf(" reweighting simulation from temperature %f and pressure %f to temperature %f and pressure %f \n",simtemp/getKBoltzmann(), press_, rtemp_/getKBoltzmann(), rpress_); - else error("Combination of ENERGY, VOLUME, REWEIGHT_PRESSURE, PRESSURE and REWEIGHT_TEMP not supported. Please refer to the manual for supported combinations."); + else if (rtemp_>0 && press_>=0 && rpress_>=0 && !myenergy.empty() && !myvol.empty() ) { + log.printf(" reweighting simulation from temperature %f and pressure %f to temperature %f and pressure %f \n",simtemp/getKBoltzmann(), press_, rtemp_/getKBoltzmann(), rpress_); + } else { + error("Combination of ENERGY, VOLUME, REWEIGHT_PRESSURE, PRESSURE and REWEIGHT_TEMP not supported. Please refer to the manual for supported combinations."); + } } double ReweightTemperaturePressure::getLogWeight() { - double energy=0.0; for(unsigned i=0; i=0 && press_<0 && rpress_<0) return ((1.0/simtemp)- (1.0/rtemp_) )*energy; + if (rtemp_>=0 && press_<0 && rpress_<0) { + return ((1.0/simtemp)- (1.0/rtemp_) )*energy; + } // Case 2) Reweight from T to T' with P=const (isothermal-isobaric) - else if (rtemp_>=0 && press_>=0 && rpress_<0) return ((1.0/simtemp)- (1.0/rtemp_) )*energy + ((1.0/simtemp) - (1.0/rtemp_))*press_*volume; + else if (rtemp_>=0 && press_>=0 && rpress_<0) { + return ((1.0/simtemp)- (1.0/rtemp_) )*energy + ((1.0/simtemp) - (1.0/rtemp_))*press_*volume; + } // Case 3) Reweight from P to P' with T=const (isothermal-isobaric) - else if (rtemp_<0 && press_>=0 && rpress_>=0) return (1.0/simtemp)*(press_ - rpress_)*volume; + else if (rtemp_<0 && press_>=0 && rpress_>=0) { + return (1.0/simtemp)*(press_ - rpress_)*volume; + } // Case 4) Reweight from T,P to T',P' (isothermal-isobaric) - else if (rtemp_>0 && press_>=0 && rpress_>=0) return ((1.0/simtemp)- (1.0/rtemp_) )*energy + ((1.0/simtemp)*press_ - (1.0/rtemp_)*rpress_ )*volume; - else return 0; + else if (rtemp_>0 && press_>=0 && rpress_>=0) { + return ((1.0/simtemp)- (1.0/rtemp_) )*energy + ((1.0/simtemp)*press_ - (1.0/rtemp_)*rpress_ )*volume; + } else { + return 0; + } } } diff --git a/src/bias/UWalls.cpp b/src/bias/UWalls.cpp index 9bcb4b3ae0..91a177eb20 100644 --- a/src/bias/UWalls.cpp +++ b/src/bias/UWalls.cpp @@ -85,8 +85,10 @@ class UWalls : public Bias { PLUMED_REGISTER_ACTION(UWalls,"UPPER_WALLS_SCALAR") void UWalls::registerKeywords(Keywords& keys) { - Bias::registerKeywords(keys); keys.setDisplayName("UPPER_WALLS"); - keys.use("ARG"); keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); + Bias::registerKeywords(keys); + keys.setDisplayName("UPPER_WALLS"); + keys.use("ARG"); + keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); keys.add("compulsory","AT","the positions of the wall. The a_i in the expression for a wall."); keys.add("compulsory","KAPPA","the force constant for the wall. The k_i in the expression for a wall."); keys.add("compulsory","OFFSET","0.0","the offset for the start of the wall. The o_i in the expression for a wall."); @@ -101,8 +103,7 @@ UWalls::UWalls(const ActionOptions&ao): kappa(getNumberOfArguments(),0.0), exp(getNumberOfArguments(),2.0), eps(getNumberOfArguments(),1.0), - offset(getNumberOfArguments(),0.0) -{ + offset(getNumberOfArguments(),0.0) { // Note : the sizes of these vectors are checked automatically by parseVector parseVector("OFFSET",offset); parseVector("EPS",eps); @@ -112,22 +113,33 @@ UWalls::UWalls(const ActionOptions&ao): checkRead(); log.printf(" at"); - for(unsigned i=0; i args; parseVector("ARG",args); - if( args.size()==0 ) error("found no input arguments"); - std::string allargs=args[0]; for(unsigned i=1; i vals; ActionWithArguments::interpretArgumentList( args, plumed.getActionSet(), this, vals ); - if( vals.size()==0 ) error("found no input arguments"); + std::vector args; + parseVector("ARG",args); + if( args.size()==0 ) { + error("found no input arguments"); + } + std::string allargs=args[0]; + for(unsigned i=1; i vals; + ActionWithArguments::interpretArgumentList( args, plumed.getActionSet(), this, vals ); + if( vals.size()==0 ) { + error("found no input arguments"); + } // Find the rank unsigned rank=vals[0]->getRank(); for(unsigned i=0; igetRank()>0 && vals[i]->hasDerivatives() ) error("argument should not be function on grid"); - if( vals[i]->getRank()!=rank ) error("all arguments should have same rank"); + if( vals[i]->getRank()>0 && vals[i]->hasDerivatives() ) { + error("argument should not be function on grid"); + } + if( vals[i]->getRank()!=rank ) { + error("all arguments should have same rank"); + } } if( rank==0 ) { - if( getName()=="UPPER_WALLS") readInputLine( getShortcutLabel() + ": UPPER_WALLS_SCALAR ARG=" + allargs + " " + convertInputLineToString() ); - else if( getName()=="LOWER_WALLS") readInputLine( getShortcutLabel() + ": LOWER_WALLS_SCALAR ARG=" + allargs + " " + convertInputLineToString() ); - else plumed_merror( getName() + " is not valid"); + if( getName()=="UPPER_WALLS") { + readInputLine( getShortcutLabel() + ": UPPER_WALLS_SCALAR ARG=" + allargs + " " + convertInputLineToString() ); + } else if( getName()=="LOWER_WALLS") { + readInputLine( getShortcutLabel() + ": LOWER_WALLS_SCALAR ARG=" + allargs + " " + convertInputLineToString() ); + } else { + plumed_merror( getName() + " is not valid"); + } return; } // Note : the sizes of these vectors are checked automatically by parseVector - std::vector kappa(args.size()); parseVector("KAPPA",kappa); - std::vector offset(kappa.size()); parseVector("OFFSET",offset); - std::vector eps(kappa.size()); parseVector("EPS",eps); - std::vector exp(kappa.size()); parseVector("EXP",exp); - std::vector at(kappa.size()); parseVector("AT",at); + std::vector kappa(args.size()); + parseVector("KAPPA",kappa); + std::vector offset(kappa.size()); + parseVector("OFFSET",offset); + std::vector eps(kappa.size()); + parseVector("EPS",eps); + std::vector exp(kappa.size()); + parseVector("EXP",exp); + std::vector at(kappa.size()); + parseVector("AT",at); std::string biasinp, forceinp; for(unsigned i=0; i& box, unsigned natoms, unsigned /*step*/, Random&) override { const double rmax= 2.0*std::cbrt((3.0/(4.0*PLMD::pi)) * natoms); - box[0]=rmax; box[1]=0.0; box[2]=0.0; - box[3]=0.0; box[4]=rmax; box[5]=0.0; - box[6]=0.0; box[7]=0.0; box[8]=rmax; + box[0]=rmax; + box[1]=0.0; + box[2]=0.0; + box[3]=0.0; + box[4]=rmax; + box[5]=0.0; + box[6]=0.0; + box[7]=0.0; + box[8]=rmax; } }; @@ -352,9 +357,15 @@ struct twoGlobs: public AtomDistribution { virtual void box(std::vector& box, unsigned natoms, unsigned /*step*/, Random&) { const double rmax= 4.0 * std::cbrt ((3.0/(8.0*PLMD::pi)) * natoms); - box[0]=rmax; box[1]=0.0; box[2]=0.0; - box[3]=0.0; box[4]=rmax; box[5]=0.0; - box[6]=0.0; box[7]=0.0; box[8]=rmax; + box[0]=rmax; + box[1]=0.0; + box[2]=0.0; + box[3]=0.0; + box[4]=rmax; + box[5]=0.0; + box[6]=0.0; + box[7]=0.0; + box[8]=rmax; }; }; @@ -379,9 +390,15 @@ struct uniformCube:public AtomDistribution { void box(std::vector& box, unsigned natoms, unsigned /*step*/, Random&) override { //+0.05 to avoid overlap const double rmax= std::cbrt(natoms)+0.05; - box[0]=rmax; box[1]=0.0; box[2]=0.0; - box[3]=0.0; box[4]=rmax; box[5]=0.0; - box[6]=0.0; box[7]=0.0; box[8]=rmax; + box[0]=rmax; + box[1]=0.0; + box[2]=0.0; + box[3]=0.0; + box[4]=rmax; + box[5]=0.0; + box[6]=0.0; + box[7]=0.0; + box[8]=rmax; } }; @@ -408,9 +425,15 @@ struct tiledSimpleCubic:public AtomDistribution { } void box(std::vector& box, unsigned natoms, unsigned /*step*/, Random&) override { const double rmax= std::ceil(std::cbrt(static_cast(natoms)));; - box[0]=rmax; box[1]=0.0; box[2]=0.0; - box[3]=0.0; box[4]=rmax; box[5]=0.0; - box[6]=0.0; box[7]=0.0; box[8]=rmax; + box[0]=rmax; + box[1]=0.0; + box[2]=0.0; + box[3]=0.0; + box[4]=rmax; + box[5]=0.0; + box[6]=0.0; + box[7]=0.0; + box[8]=rmax; } }; @@ -434,8 +457,7 @@ std::unique_ptr getAtomDistribution(std::string_view atomicDis } } //anonymus namespace for benchmark distributions class Benchmark: - public CLTool -{ + public CLTool { public: static void registerKeywords( Keywords& keys ); explicit Benchmark(const CLToolOptions& co ); @@ -462,8 +484,7 @@ void Benchmark::registerKeywords( Keywords& keys ) { } Benchmark::Benchmark(const CLToolOptions& co ): - CLTool(co) -{ + CLTool(co) { inputdata=commandline; } @@ -476,7 +497,9 @@ int Benchmark::main(FILE* in, FILE*out,Communicator& pc) { struct FileDeleter { void operator()(FILE*f) const noexcept { - if(f) std::fclose(f); + if(f) { + std::fclose(f); + } } }; @@ -516,7 +539,8 @@ int Benchmark::main(FILE* in, FILE*out,Communicator& pc) { log<<"Single run, skipping comparative analysis\n"; } else if(size<10) { log<<"Too small sample, skipping comparative analysis\n"; - } else try { + } else + try { log<<"Running comparative analysis, "< distrib(0, numblocks-1); std::vector> blocks(f->size()); - { int i=0; + { + int i=0; for(auto it = f->rbegin(); it != f->rend(); ++it,++i) { size_t l=0; blocks[i].assign(numblocks,0); @@ -546,7 +571,9 @@ int Benchmark::main(FILE* in, FILE*out,Communicator& pc) { //B are the bootstrap iterations for(unsigned b=0; bempty()) f->pop_back(); + while(!f->empty()) { + f->pop_back(); + } }; std::unique_ptr kernels_deleter_obj(&kernels,kernels_deleter); @@ -611,7 +640,9 @@ int Benchmark::main(FILE* in, FILE*out,Communicator& pc) { // this check only works on MacOS #if defined(__APPLE__) // if any of the paths if different from "this", we check if libplumed was loaded locally to avoid conflicts. - if(std::any_of(allpaths.begin(),allpaths.end(),[](auto value) {return value != "this";})) { + if(std::any_of(allpaths.begin(),allpaths.end(),[](auto value) { + return value != "this"; + })) { if(DLLoader::isPlumedGlobal()) { plumed_error()<<"It looks like libplumed is loaded in the global namespace, you cannot load a different version of the kernel\n" <<"Please make sure you use the plumed-runtime executable and that the env var PLUMED_LOAD_NAMESPACE is not set to GLOBAL"; @@ -623,10 +654,18 @@ int Benchmark::main(FILE* in, FILE*out,Communicator& pc) { plumed_error() << "--kernel and --plumed should have either one element or the same number of elements"; } - if(allplumed.size()>1 && allpaths.size()==1) for(unsigned i=1; i1) for(unsigned i=1; i1 && allpaths.size()==1) + for(unsigned i=1; i1) + for(unsigned i=1; i1) domain_decomposition=true; - if(domain_decomposition) shuffled=true; + if(pc.Get_size()>1) { + domain_decomposition=true; + } + if(domain_decomposition) { + shuffled=true; + } double timeToSleep; parse("--sleep",timeToSleep); @@ -699,7 +747,9 @@ int Benchmark::main(FILE* in, FILE*out,Communicator& pc) { for(auto & k : kernels) { auto & p(k.handle); auto sw=k.stopwatch.startStop("A Initialization"); - if(Communicator::plumedHasMPI() && domain_decomposition) p.cmd("setMPIComm",&pc.Get_comm()); + if(Communicator::plumedHasMPI() && domain_decomposition) { + p.cmd("setMPIComm",&pc.Get_comm()); + } p.cmd("setRealPrecision",(int)sizeof(double)); p.cmd("setMDLengthUnits",1.0); p.cmd("setMDChargeUnits",1.0); @@ -718,13 +768,17 @@ int Benchmark::main(FILE* in, FILE*out,Communicator& pc) { if(shuffled) { shuffled_indexes.resize(natoms); - for(unsigned i=0; i kernels_ptr; - for(unsigned i=0; i(std::chrono::high_resolution_clock::now()-start).count()<(long long int)1e9*timeToSleep) k+=i*i; + while(std::chrono::duration_cast(std::chrono::high_resolution_clock::now()-start).count()<(long long int)1e9*timeToSleep) { + k+=i*i; + } std::fprintf(log_dev_null.get(),"%u",k); } @@ -814,11 +879,17 @@ int Benchmark::main(FILE* in, FILE*out,Communicator& pc) { p.cmd("performCalc"); } - if(kernels_ptr.size()>1 && part>1) kernels_ptr[i]->timings.push_back(kernels_ptr[i]->stopwatch.getLastCycle(sw_name)); - if(plumedStopCondition || signalReceived.load()) fast_finish=true; + if(kernels_ptr.size()>1 && part>1) { + kernels_ptr[i]->timings.push_back(kernels_ptr[i]->stopwatch.getLastCycle(sw_name)); + } + if(plumedStopCondition || signalReceived.load()) { + fast_finish=true; + } } auto elapsed=std::chrono::duration_cast(std::chrono::high_resolution_clock::now()-initial_time).count(); - if(part==0) part=1; + if(part==0) { + part=1; + } if(part<2) { if((maxtime>0 && elapsed>(long long int)(0.2*1e9*maxtime)) || (nf>0 && step+1>=nf/5) || (maxtime<0 && nf<0 && step+1>=100)) { part=2; @@ -832,14 +903,18 @@ int Benchmark::main(FILE* in, FILE*out,Communicator& pc) { } } - if(maxtime>0 && elapsed>(long long int)(1e9*maxtime)) fast_finish=true; + if(maxtime>0 && elapsed>(long long int)(1e9*maxtime)) { + fast_finish=true; + } { unsigned tmp=fast_finish; pc.Bcast(tmp,0); fast_finish=tmp; } - if(fast_finish) break; + if(fast_finish) { + break; + } } return 0; diff --git a/src/cltools/Completion.cpp b/src/cltools/Completion.cpp index 92c27bf0a1..e8d1a040e1 100644 --- a/src/cltools/Completion.cpp +++ b/src/cltools/Completion.cpp @@ -50,8 +50,7 @@ plumed completion //+ENDPLUMEDOC class Completion: - public CLTool -{ + public CLTool { public: static void registerKeywords( Keywords& keys ); explicit Completion(const CLToolOptions& co ); @@ -68,8 +67,7 @@ void Completion::registerKeywords( Keywords& keys ) { } Completion::Completion(const CLToolOptions& co ): - CLTool(co) -{ + CLTool(co) { inputdata=commandline; } @@ -86,11 +84,19 @@ int Completion::main(FILE* in, FILE*out,Communicator& pc) { std::vector tmp=Tools::ls(std::string(config::getPlumedRoot()+"/scripts")); for(unsigned j=0; j0) std::fprintf(out," %s",tmp[j].c_str()); + for(unsigned j=0; j0) { + std::fprintf(out," %s",tmp[j].c_str()); + } std::fprintf(out,"\"\n"); for(unsigned j=0; j void Driver::registerKeywords( Keywords& keys ) { - CLTool::registerKeywords( keys ); keys.isDriver(); + CLTool::registerKeywords( keys ); + keys.isDriver(); keys.addFlag("--help-debug",false,"print special options that can be used to create regtests"); keys.add("compulsory","--plumed","plumed.dat","specify the name of the plumed input file"); keys.add("compulsory","--timestep","1.0","the timestep that was used in the calculation that produced this trajectory in picoseconds"); @@ -259,12 +260,13 @@ void Driver::registerKeywords( Keywords& keys ) { } template Driver::Driver(const CLToolOptions& co ): - CLTool(co) -{ + CLTool(co) { inputdata=commandline; } template -std::string Driver::description()const { return "analyze trajectories with plumed"; } +std::string Driver::description()const { + return "analyze trajectories with plumed"; +} template int Driver::main(FILE* in,FILE*out,Communicator& pc) { @@ -273,7 +275,8 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { PDB pdb; // Parse everything - bool printhelpdebug; parseFlag("--help-debug",printhelpdebug); + bool printhelpdebug; + parseFlag("--help-debug",printhelpdebug); if( printhelpdebug ) { std::fprintf(out,"%s", "Additional options for debug (only to be used in regtest):\n" @@ -284,19 +287,28 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { return 0; } // Are we reading trajectory data - bool noatoms; parseFlag("--noatoms",noatoms); - bool parseOnly; parseFlag("--parse-only",parseOnly); - std::string full_outputfile; parse("--shortcut-ofile",full_outputfile); - std::string valuedict_file; parse("--valuedict-ofile",valuedict_file); - bool restart; parseFlag("--restart",restart); + bool noatoms; + parseFlag("--noatoms",noatoms); + bool parseOnly; + parseFlag("--parse-only",parseOnly); + std::string full_outputfile; + parse("--shortcut-ofile",full_outputfile); + std::string valuedict_file; + parse("--valuedict-ofile",valuedict_file); + bool restart; + parseFlag("--restart",restart); std::string fakein; bool debug_float=false; fakein=""; if(parse("--debug-float",fakein)) { - if(fakein=="yes") debug_float=true; - else if(fakein=="no") debug_float=false; - else error("--debug-float should have argument yes or no"); + if(fakein=="yes") { + debug_float=true; + } else if(fakein=="no") { + debug_float=false; + } else { + error("--debug-float should have argument yes or no"); + } } if(debug_float && sizeof(real)!=sizeof(float)) { @@ -309,23 +321,37 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { bool debug_pd=false; fakein=""; if(parse("--debug-pd",fakein)) { - if(fakein=="yes") debug_pd=true; - else if(fakein=="no") debug_pd=false; - else error("--debug-pd should have argument yes or no"); + if(fakein=="yes") { + debug_pd=true; + } else if(fakein=="no") { + debug_pd=false; + } else { + error("--debug-pd should have argument yes or no"); + } + } + if(debug_pd) { + std::fprintf(out,"DEBUGGING PARTICLE DECOMPOSITION\n"); } - if(debug_pd) std::fprintf(out,"DEBUGGING PARTICLE DECOMPOSITION\n"); bool debug_dd=false; fakein=""; if(parse("--debug-dd",fakein)) { - if(fakein=="yes") debug_dd=true; - else if(fakein=="no") debug_dd=false; - else error("--debug-dd should have argument yes or no"); + if(fakein=="yes") { + debug_dd=true; + } else if(fakein=="no") { + debug_dd=false; + } else { + error("--debug-dd should have argument yes or no"); + } + } + if(debug_dd) { + std::fprintf(out,"DEBUGGING DOMAIN DECOMPOSITION\n"); } - if(debug_dd) std::fprintf(out,"DEBUGGING DOMAIN DECOMPOSITION\n"); if( debug_pd || debug_dd ) { - if(noatoms) error("cannot debug without atoms"); + if(noatoms) { + error("cannot debug without atoms"); + } } // set up for multi replica driver: @@ -336,7 +362,9 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { if(multi) { int ntot=pc.Get_size(); int nintra=ntot/multi; - if(multi*nintra!=ntot) error("invalid number of processes for multi environment"); + if(multi*nintra!=ntot) { + error("invalid number of processes for multi environment"); + } pc.Split(pc.Get_rank()/nintra,pc.Get_rank(),intracomm); pc.Split(pc.Get_rank()%nintra,pc.Get_rank(),intercomm); } else { @@ -348,14 +376,23 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { int grex_stride=0; FILE*grex_log=NULL; // call fclose when fp goes out of scope - auto deleter=[](auto f) { if(f) std::fclose(f); }; + auto deleter=[](auto f) { + if(f) { + std::fclose(f); + } + }; std::unique_ptr grex_log_deleter(grex_log,deleter); if(debug_grex) { - if(noatoms) error("must have atoms to debug_grex"); - if(multi<2) error("--debug_grex needs --multi with at least two replicas"); + if(noatoms) { + error("must have atoms to debug_grex"); + } + if(multi<2) { + error("--debug_grex needs --multi with at least two replicas"); + } Tools::convert(fakein,grex_stride); - std::string n; Tools::convert(intercomm.Get_rank(),n); + std::string n; + Tools::convert(intercomm.Get_rank(),n); std::string file; parse("--debug-grex-log",file); if(file.length()>0) { @@ -366,12 +403,15 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { } // Read the plumed input file name - std::string plumedFile; parse("--plumed",plumedFile); + std::string plumedFile; + parse("--plumed",plumedFile); // the timestep - double t; parse("--timestep",t); + double t; + parse("--timestep",t); real timestep=real(t); // the stride - unsigned stride; parse("--trajectory-stride",stride); + unsigned stride; + parse("--trajectory-stride",stride); // are we writing forces std::string dumpforces(""), debugforces(""), dumpforcesFmt("%f");; bool dumpfullvirial=false; @@ -379,10 +419,18 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { parse("--dump-forces",dumpforces); parse("--debug-forces",debugforces); } - if(dumpforces!="" || debugforces!="" ) parse("--dump-forces-fmt",dumpforcesFmt); - if(dumpforces!="") parseFlag("--dump-full-virial",dumpfullvirial); - if( debugforces!="" && (debug_dd || debug_pd) ) error("cannot debug forces and domain/particle decomposition at same time"); - if( debugforces!="" && sizeof(real)!=sizeof(double) ) error("cannot debug forces in single precision mode"); + if(dumpforces!="" || debugforces!="" ) { + parse("--dump-forces-fmt",dumpforcesFmt); + } + if(dumpforces!="") { + parseFlag("--dump-full-virial",dumpfullvirial); + } + if( debugforces!="" && (debug_dd || debug_pd) ) { + error("cannot debug forces and domain/particle decomposition at same time"); + } + if( debugforces!="" && sizeof(real)!=sizeof(double) ) { + error("cannot debug forces in single precision mode"); + } real kt=-1.0; parse("--kt",kt); @@ -393,13 +441,17 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { // Read in an xyz file std::string trajectoryFile(""), pdbfile(""), mcfile(""); - bool pbc_cli_given=false; std::vector pbc_cli_box(9,0.0); + bool pbc_cli_given=false; + std::vector pbc_cli_box(9,0.0); int command_line_natoms=-1; if(!noatoms) { - std::string traj_xyz; parse("--ixyz",traj_xyz); - std::string traj_gro; parse("--igro",traj_gro); - std::string traj_dlp4; parse("--idlp4",traj_dlp4); + std::string traj_xyz; + parse("--ixyz",traj_xyz); + std::string traj_gro; + parse("--igro",traj_gro); + std::string traj_dlp4; + parse("--idlp4",traj_dlp4); std::string traj_xtc; std::string traj_trr; parse("--ixtc",traj_xtc); @@ -418,13 +470,24 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { } } #endif - { // check that only one fmt is specified + { + // check that only one fmt is specified int nn=0; - if(traj_xyz.length()>0) nn++; - if(traj_gro.length()>0) nn++; - if(traj_dlp4.length()>0) nn++; - if(traj_xtc.length()>0) nn++; - if(traj_trr.length()>0) nn++; + if(traj_xyz.length()>0) { + nn++; + } + if(traj_gro.length()>0) { + nn++; + } + if(traj_dlp4.length()>0) { + nn++; + } + if(traj_xtc.length()>0) { + nn++; + } + if(traj_trr.length()>0) { + nn++; + } if(nn>1) { std::fprintf(stderr,"ERROR: cannot provide more than one trajectory file\n"); return 1; @@ -454,29 +517,45 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { std::fprintf(stderr,"ERROR: missing trajectory data\n"); return 1; } - std::string lengthUnits(""); parse("--length-units",lengthUnits); - if(lengthUnits.length()>0) units.setLength(lengthUnits); - std::string chargeUnits(""); parse("--charge-units",chargeUnits); - if(chargeUnits.length()>0) units.setCharge(chargeUnits); - std::string massUnits(""); parse("--mass-units",massUnits); - if(massUnits.length()>0) units.setMass(massUnits); + std::string lengthUnits(""); + parse("--length-units",lengthUnits); + if(lengthUnits.length()>0) { + units.setLength(lengthUnits); + } + std::string chargeUnits(""); + parse("--charge-units",chargeUnits); + if(chargeUnits.length()>0) { + units.setCharge(chargeUnits); + } + std::string massUnits(""); + parse("--mass-units",massUnits); + if(massUnits.length()>0) { + units.setMass(massUnits); + } parse("--pdb",pdbfile); if(pdbfile.length()>0) { bool check=pdb.read(pdbfile,false,1.0); - if(!check) error("error reading pdb file"); + if(!check) { + error("error reading pdb file"); + } } parse("--mc",mcfile); - std::string pbc_cli_list; parse("--box",pbc_cli_list); + std::string pbc_cli_list; + parse("--box",pbc_cli_list); if(pbc_cli_list.length()>0) { pbc_cli_given=true; std::vector words=Tools::getWords(pbc_cli_list,","); if(words.size()==3) { - for(int i=0; i<3; i++) std::sscanf(words[i].c_str(),"%100lf",&(pbc_cli_box[4*i])); + for(int i=0; i<3; i++) { + std::sscanf(words[i].c_str(),"%100lf",&(pbc_cli_box[4*i])); + } } else if(words.size()==9) { - for(int i=0; i<9; i++) std::sscanf(words[i].c_str(),"%100lf",&(pbc_cli_box[i])); + for(int i=0; i<9; i++) { + std::sscanf(words[i].c_str(),"%100lf",&(pbc_cli_box[i])); + } } else { std::string msg="ERROR: cannot parse command-line box "+pbc_cli_list; std::fprintf(stderr,"%s\n",msg.c_str()); @@ -493,7 +572,9 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { auto mf_deleter=[api](void* h_in) { if(h_in) { std::unique_ptr> lck; - if(api->is_reentrant==VMDPLUGIN_THREADUNSAFE) lck=Tools::molfile_lock(); + if(api->is_reentrant==VMDPLUGIN_THREADUNSAFE) { + lck=Tools::molfile_lock(); + } api->close_file_read(h_in); } }; @@ -511,22 +592,33 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { - if(debug_dd && debug_pd) error("cannot use debug-dd and debug-pd at the same time"); + if(debug_dd && debug_pd) { + error("cannot use debug-dd and debug-pd at the same time"); + } if(debug_pd || debug_dd) { - if( !Communicator::initialized() ) error("needs mpi for debug-pd"); + if( !Communicator::initialized() ) { + error("needs mpi for debug-pd"); + } } - PlumedMain p; if( parseOnly ) p.activateParseOnlyMode(); + PlumedMain p; + if( parseOnly ) { + p.activateParseOnlyMode(); + } p.cmd("setRealPrecision",(int)sizeof(real)); int checknatoms=-1; long long int step=0; parse("--initial-step",step); - if(restart) p.cmd("setRestart",1); + if(restart) { + p.cmd("setRestart",1); + } if(Communicator::initialized()) { if(multi) { - if(intracomm.Get_rank()==0) p.cmd("GREX setMPIIntercomm",&intercomm.Get_comm()); + if(intracomm.Get_rank()==0) { + p.cmd("GREX setMPIIntercomm",&intercomm.Get_comm()); + } p.cmd("GREX setMPIIntracomm",&intracomm.Get_comm()); p.cmd("GREX init"); } @@ -537,7 +629,9 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { p.cmd("setMDMassUnits",units.getMass()); p.cmd("setMDEngine","driver"); p.cmd("setTimestep",timestep); - if( !parseOnly || full_outputfile.length()==0 ) p.cmd("setPlumedDat",plumedFile.c_str()); + if( !parseOnly || full_outputfile.length()==0 ) { + p.cmd("setPlumedDat",plumedFile.c_str()); + } p.cmd("setLog",out); int natoms; @@ -545,43 +639,59 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { int pb=1; if(parseOnly) { - if(command_line_natoms<0) error("--parseOnly requires setting the number of atoms with --natoms"); + if(command_line_natoms<0) { + error("--parseOnly requires setting the number of atoms with --natoms"); + } natoms=command_line_natoms; } - FILE* fp=NULL; FILE* fp_forces=NULL; OFile fp_dforces; + FILE* fp=NULL; + FILE* fp_forces=NULL; + OFile fp_dforces; std::unique_ptr fp_deleter(fp,deleter); std::unique_ptr fp_forces_deleter(fp_forces,deleter); - auto xdr_deleter=[](auto xd) { if(xd) xdrfile::xdrfile_close(xd); }; + auto xdr_deleter=[](auto xd) { + if(xd) { + xdrfile::xdrfile_close(xd); + } + }; xdrfile::XDRFILE* xd=NULL; std::unique_ptr xd_deleter(xd,xdr_deleter); if(!noatoms&&!parseOnly) { - if (trajectoryFile=="-") + if (trajectoryFile=="-") { fp=in; - else { + } else { if(multi) { std::string n; Tools::convert(intercomm.Get_rank(),n); std::string testfile=FileBase::appendSuffix(trajectoryFile,"."+n); FILE* tmp_fp=std::fopen(testfile.c_str(),"r"); // no exceptions here - if(tmp_fp) { std::fclose(tmp_fp); trajectoryFile=testfile;} + if(tmp_fp) { + std::fclose(tmp_fp); + trajectoryFile=testfile; + } } if(use_molfile==true) { #ifdef __PLUMED_HAS_MOLFILE_PLUGINS std::unique_ptr> lck; - if(api->is_reentrant==VMDPLUGIN_THREADUNSAFE) lck=Tools::molfile_lock(); + if(api->is_reentrant==VMDPLUGIN_THREADUNSAFE) { + lck=Tools::molfile_lock(); + } h_in = api->open_file_read(trajectoryFile.c_str(), trajectory_fmt.c_str(), &natoms); h_in_deleter.reset(h_in); if(natoms==MOLFILE_NUMATOMS_UNKNOWN) { - if(command_line_natoms>=0) natoms=command_line_natoms; - else error("this file format does not provide number of atoms; use --natoms on the command line"); + if(command_line_natoms>=0) { + natoms=command_line_natoms; + } else { + error("this file format does not provide number of atoms; use --natoms on the command line"); + } } ts_in_coords.resize(3*natoms); ts_in.coords = ts_in_coords.data(); @@ -594,8 +704,12 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { std::fprintf(stderr,"%s\n",msg.c_str()); return 1; } - if(trajectory_fmt=="xdr-xtc") xdrfile::read_xtc_natoms(&trajectoryFile[0],&natoms); - if(trajectory_fmt=="xdr-trr") xdrfile::read_trr_natoms(&trajectoryFile[0],&natoms); + if(trajectory_fmt=="xdr-xtc") { + xdrfile::read_xtc_natoms(&trajectoryFile[0],&natoms); + } + if(trajectory_fmt=="xdr-trr") { + xdrfile::read_trr_natoms(&trajectoryFile[0],&natoms); + } } else { fp=std::fopen(trajectoryFile.c_str(),"r"); fp_deleter.reset(fp); @@ -649,8 +763,12 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { Random rnd; if(trajectory_fmt=="dlp4") { - if(!Tools::getline(fp,line)) error("error reading title"); - if(!Tools::getline(fp,line)) error("error reading atoms"); + if(!Tools::getline(fp,line)) { + error("error reading title"); + } + if(!Tools::getline(fp,line)) { + error("error reading atoms"); + } std::sscanf(line.c_str(),"%d %d %d",&lvl,&pb,&natoms); } @@ -660,7 +778,9 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { if(use_molfile==true) { #ifdef __PLUMED_HAS_MOLFILE_PLUGINS std::unique_ptr> lck; - if(api->is_reentrant==VMDPLUGIN_THREADUNSAFE) lck=Tools::molfile_lock(); + if(api->is_reentrant==VMDPLUGIN_THREADUNSAFE) { + lck=Tools::molfile_lock(); + } int rc; rc = api->read_next_timestep(h_in, natoms, &ts_in); if(rc==MOLFILE_EOF) { @@ -668,13 +788,18 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { } #endif } else if(trajectory_fmt=="xyz" || trajectory_fmt=="gro" || trajectory_fmt=="dlp4") { - if(!Tools::getline(fp,line)) break; + if(!Tools::getline(fp,line)) { + break; + } } } bool first_step=false; if(!noatoms&&!parseOnly) { if(use_molfile==false && (trajectory_fmt=="xyz" || trajectory_fmt=="gro")) { - if(trajectory_fmt=="gro") if(!Tools::getline(fp,line)) error("premature end of trajectory file"); + if(trajectory_fmt=="gro") + if(!Tools::getline(fp,line)) { + error("premature end of trajectory file"); + } std::sscanf(line.c_str(),"%100d",&natoms); } if(use_molfile==false && trajectory_fmt=="dlp4") { @@ -699,7 +824,9 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { for(unsigned i=0; i=unsigned(natoms) ) error("atom index in pdb exceeds the number of atoms in trajectory"); + if( index>=unsigned(natoms) ) { + error("atom index in pdb exceeds the number of atoms in trajectory"); + } masses[index]=pdb.getOccupancy()[i]; charges[index]=pdb.getBeta()[i]; } @@ -707,7 +834,9 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { if(mcfile.length()>0) { IFile ifile; ifile.open(mcfile); - int index; double mass; double charge; + int index; + double mass; + double charge; while(ifile.scanField("index",index).scanField("mass",mass).scanField("charge",charge).scanField()) { masses[index]=mass; charges[index]=charge; @@ -728,77 +857,124 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { // Read in the plumed input file and store what is in there std::map > data; - IFile ifile; ifile.open(plumedFile); std::vector words; + IFile ifile; + ifile.open(plumedFile); + std::vector words; while( Tools::getParsedLine(ifile,words) && !p.getEndPlumed() ) { p.readInputWords(words,false); Action* aa=p.getActionSet()[p.getActionSet().size()-1].get(); plumed_assert(aa); // needed for following calls, see #1046 ActionWithValue* av=aa->castToActionWithValue(); if( av && aa->getDefaultString().length()>0 ) { - std::vector def; def.push_back( "defaults " + aa->getDefaultString() ); + std::vector def; + def.push_back( "defaults " + aa->getDefaultString() ); data[ aa->getLabel() ] = def; } ActionShortcut* as=aa->castToActionShortcut(); if( as ) { if( aa->getDefaultString().length()>0 ) { - std::vector def; def.push_back( "defaults " + aa->getDefaultString() ); + std::vector def; + def.push_back( "defaults " + aa->getDefaultString() ); data[ as->getShortcutLabel() ] = def; } - std::vector shortcut_commands = as->getSavedInputLines(); if( shortcut_commands.size()==0 ) continue; + std::vector shortcut_commands = as->getSavedInputLines(); + if( shortcut_commands.size()==0 ) { + continue; + } if( data.find( as->getShortcutLabel() )!=data.end() ) { - for(unsigned i=0; igetShortcutLabel() ].push_back( shortcut_commands[i] ); - } else data[ as->getShortcutLabel() ] = shortcut_commands; + for(unsigned i=0; igetShortcutLabel() ].push_back( shortcut_commands[i] ); + } + } else { + data[ as->getShortcutLabel() ] = shortcut_commands; + } } } ifile.close(); // Only output the full version of the input file if there are shortcuts if( data.size()>0 ) { - OFile long_file; long_file.open( full_outputfile ); long_file.printf("{\n"); bool firstpass=true; + OFile long_file; + long_file.open( full_outputfile ); + long_file.printf("{\n"); + bool firstpass=true; for(auto& x : data ) { - if( !firstpass ) long_file.printf(" },\n"); + if( !firstpass ) { + long_file.printf(" },\n"); + } long_file.printf(" \"%s\" : {\n", x.first.c_str() ); - plumed_assert( x.second.size()>0 ); unsigned sstart=0; + plumed_assert( x.second.size()>0 ); + unsigned sstart=0; if( x.second[0].find("defaults")!=std::string::npos ) { - sstart=1; long_file.printf(" \"defaults\" : \"%s\"", x.second[0].substr( 9 ).c_str() ); - if( x.second.size()>1 ) long_file.printf(",\n"); else long_file.printf("\n"); + sstart=1; + long_file.printf(" \"defaults\" : \"%s\"", x.second[0].substr( 9 ).c_str() ); + if( x.second.size()>1 ) { + long_file.printf(",\n"); + } else { + long_file.printf("\n"); + } } if( x.second.size()>sstart ) { long_file.printf(" \"expansion\" : \"%s", x.second[sstart].c_str() ); - for(unsigned j=sstart+1; j0 ) { - OFile valuefile; valuefile.open( valuedict_file ); valuefile.printf("{\n"); bool firsta=true; + OFile valuefile; + valuefile.open( valuedict_file ); + valuefile.printf("{\n"); + bool firsta=true; for(const auto & pp : p.getActionSet()) { - if( pp.get()->getName()=="CENTER" ) continue ; + if( pp.get()->getName()=="CENTER" ) { + continue ; + } ActionWithVirtualAtom* avv=dynamic_cast(pp.get()); if( avv || pp.get()->getName()=="GROUP" || pp.get()->getName()=="DENSITY" ) { Action* p(pp.get()); - if( firsta ) { valuefile.printf(" \"%s\" : {\n \"action\" : \"%s\"", p->getLabel().c_str(), p->getName().c_str() ); firsta=false; } - else valuefile.printf(",\n \"%s\" : {\n \"action\" : \"%s\"", p->getLabel().c_str(), p->getName().c_str() ); - if( avv ) valuefile.printf(",\n \"%s\" : { \"type\": \"atoms\", \"description\": \"virtual atom calculated by %s action\" }", avv->getLabel().c_str(), avv->getName().c_str() ); - else valuefile.printf(",\n \"%s\" : { \"type\": \"atoms\", \"description\": \"indices of atoms specified in GROUP\" }", p->getLabel().c_str() ); - valuefile.printf("\n }"); continue; + if( firsta ) { + valuefile.printf(" \"%s\" : {\n \"action\" : \"%s\"", p->getLabel().c_str(), p->getName().c_str() ); + firsta=false; + } else { + valuefile.printf(",\n \"%s\" : {\n \"action\" : \"%s\"", p->getLabel().c_str(), p->getName().c_str() ); + } + if( avv ) { + valuefile.printf(",\n \"%s\" : { \"type\": \"atoms\", \"description\": \"virtual atom calculated by %s action\" }", avv->getLabel().c_str(), avv->getName().c_str() ); + } else { + valuefile.printf(",\n \"%s\" : { \"type\": \"atoms\", \"description\": \"indices of atoms specified in GROUP\" }", p->getLabel().c_str() ); + } + valuefile.printf("\n }"); + continue; } ActionWithValue* av=dynamic_cast(pp.get()); if( av && av->getNumberOfComponents()>0 ) { - Keywords keys; p.getKeywordsForAction( av->getName(), keys ); - if( firsta ) { valuefile.printf(" \"%s\" : {\n \"action\" : \"%s\"", av->getLabel().c_str(), keys.getDisplayName().c_str() ); firsta=false; } - else valuefile.printf(",\n \"%s\" : {\n \"action\" : \"%s\"", av->getLabel().c_str(), keys.getDisplayName().c_str() ); + Keywords keys; + p.getKeywordsForAction( av->getName(), keys ); + if( firsta ) { + valuefile.printf(" \"%s\" : {\n \"action\" : \"%s\"", av->getLabel().c_str(), keys.getDisplayName().c_str() ); + firsta=false; + } else { + valuefile.printf(",\n \"%s\" : {\n \"action\" : \"%s\"", av->getLabel().c_str(), keys.getDisplayName().c_str() ); + } for(unsigned i=0; igetNumberOfComponents(); ++i) { - Value* myval = av->copyOutput(i); std::string compname = myval->getName(), description; + Value* myval = av->copyOutput(i); + std::string compname = myval->getName(), description; if( av->getLabel()==compname ) { description = keys.getOutputComponentDescription(".#!value"); } else { - std::size_t dot=compname.find(av->getLabel() + "."); std::string cname = compname.substr(dot + av->getLabel().length() + 1); + std::size_t dot=compname.find(av->getLabel() + "."); + std::string cname = compname.substr(dot + av->getLabel().length() + 1); description = av->getOutputComponentDescription( cname, keys ); } - if( description.find("\\")!=std::string::npos ) error("found invalid backslash character in documentation for component " + compname + " in action " + av->getName() + " with label " + av->getLabel() ); + if( description.find("\\")!=std::string::npos ) { + error("found invalid backslash character in documentation for component " + compname + " in action " + av->getName() + " with label " + av->getLabel() ); + } valuefile.printf(",\n \"%s\" : { \"type\": \"%s\", \"description\": \"%s\" }", myval->getName().c_str(), myval->getValueType().c_str(), description.c_str() ); } valuefile.printf("\n }"); @@ -806,30 +982,50 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { ActionShortcut* as=pp->castToActionShortcut(); if( as ) { std::vector cnames( as->getSavedOutputs() ); - if( cnames.size()==0 ) continue ; + if( cnames.size()==0 ) { + continue ; + } - if( firsta ) { valuefile.printf(" \"shortcut_%s\" : {\n \"action\" : \"%s\"", as->getShortcutLabel().c_str(), as->getName().c_str() ); firsta=false; } - else valuefile.printf(",\n \"shortcut_%s\" : {\n \"action\" : \"%s\"", as->getShortcutLabel().c_str(), as->getName().c_str() ); - Keywords keys; p.getKeywordsForAction( as->getName(), keys ); + if( firsta ) { + valuefile.printf(" \"shortcut_%s\" : {\n \"action\" : \"%s\"", as->getShortcutLabel().c_str(), as->getName().c_str() ); + firsta=false; + } else { + valuefile.printf(",\n \"shortcut_%s\" : {\n \"action\" : \"%s\"", as->getShortcutLabel().c_str(), as->getName().c_str() ); + } + Keywords keys; + p.getKeywordsForAction( as->getName(), keys ); for(unsigned i=0; i( cnames[i] ); - if( !av2 ) plumed_merror("could not find value created by shortcut with name " + cnames[i] ); + if( !av2 ) { + plumed_merror("could not find value created by shortcut with name " + cnames[i] ); + } if( av2->getNumberOfComponents()==1 ) { - Value* myval = av2->copyOutput(0); std::string compname = myval->getName(), description; - if( compname==as->getShortcutLabel() ) description = keys.getOutputComponentDescription(".#!value"); - else { std::size_t pp=compname.find(as->getShortcutLabel()); description = keys.getOutputComponentDescription( compname.substr(pp+as->getShortcutLabel().length()+1) ); } - if( description.find("\\")!=std::string::npos ) error("found invalid backslash character in documentation for component " + compname + " in action " + as->getName() + " with label " + as->getLabel() ); + Value* myval = av2->copyOutput(0); + std::string compname = myval->getName(), description; + if( compname==as->getShortcutLabel() ) { + description = keys.getOutputComponentDescription(".#!value"); + } else { + std::size_t pp=compname.find(as->getShortcutLabel()); + description = keys.getOutputComponentDescription( compname.substr(pp+as->getShortcutLabel().length()+1) ); + } + if( description.find("\\")!=std::string::npos ) { + error("found invalid backslash character in documentation for component " + compname + " in action " + as->getName() + " with label " + as->getLabel() ); + } valuefile.printf(",\n \"%s\" : { \"type\": \"%s\", \"description\": \"%s\" }", myval->getName().c_str(), myval->getValueType().c_str(), description.c_str() ); } else { for(unsigned j=0; jgetNumberOfComponents(); ++j) { - Value* myval = av2->copyOutput(j); std::string compname = myval->getName(), description; + Value* myval = av2->copyOutput(j); + std::string compname = myval->getName(), description; if( av2->getLabel()==compname ) { plumed_merror("should not be outputting description of value from action when using shortcuts"); } else { - std::size_t dot=compname.find(av2->getLabel() + "."); std::string cname = compname.substr(dot+av2->getLabel().length() + 1); + std::size_t dot=compname.find(av2->getLabel() + "."); + std::string cname = compname.substr(dot+av2->getLabel().length() + 1); description = av2->getOutputComponentDescription( cname, keys ); } - if( description.find("\\")!=std::string::npos ) error("found invalid backslash character in documentation for component " + compname + " in action " + av2->getName() + " with label " + av2->getLabel() ); + if( description.find("\\")!=std::string::npos ) { + error("found invalid backslash character in documentation for component " + compname + " in action " + av2->getName() + " with label " + av2->getLabel() ); + } valuefile.printf(",\n \"%s\" : { \"type\": \"%s\", \"description\": \"%s\" }", myval->getName().c_str(), myval->getValueType().c_str(), description.c_str() ); } } @@ -837,12 +1033,16 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { valuefile.printf("\n }"); } } - valuefile.printf("\n}\n"); valuefile.close(); + valuefile.printf("\n}\n"); + valuefile.close(); + } + if(parseOnly) { + break; } - if(parseOnly) break; } if(checknatoms!=natoms) { - std::string stepstr; Tools::convert(step,stepstr); + std::string stepstr; + Tools::convert(step,stepstr); error("number of atoms in frame " + stepstr + " does not match number of atoms in first frame"); } @@ -858,7 +1058,9 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { std::vector start(npe,0); for(int i=0; inatoms) cc=natoms-start[i]; + if(start[i]+cc>natoms) { + cc=natoms-start[i]; + } loc[i]=cc; start[i+1]=start[i]+loc[i]; } @@ -869,8 +1071,16 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { pd_start=start[intracomm.Get_rank()]; if(intracomm.Get_rank()==0) { std::fprintf(out,"\nDRIVER: Reassigning particle decomposition\n"); - std::fprintf(out,"DRIVER: "); for(int i=0; i::main(FILE* in,FILE*out,Communicator& pc) { dd_nlocal=0; for(int i=0; ir)break; + int n; + for(n=0; nr) { + break; + } plumed_assert(n::main(FILE* in,FILE*out,Communicator& pc) { real Cx=real(ts_in.C)*cosAC; real Cy=(real(ts_in.C)*real(ts_in.B)*cosBC-Cx*Bx)/By; real Cz=std::sqrt(real(ts_in.C)*real(ts_in.C)-Cx*Cx-Cy*Cy); - cell[0]=Ax/10.; cell[1]=0.; cell[2]=0.; - cell[3]=Bx/10.; cell[4]=By/10.; cell[5]=0.; - cell[6]=Cx/10.; cell[7]=Cy/10.; cell[8]=Cz/10.; + cell[0]=Ax/10.; + cell[1]=0.; + cell[2]=0.; + cell[3]=Bx/10.; + cell[4]=By/10.; + cell[5]=0.; + cell[6]=Cx/10.; + cell[7]=Cy/10.; + cell[8]=Cz/10.; } else { - cell[0]=0.0; cell[1]=0.0; cell[2]=0.0; - cell[3]=0.0; cell[4]=0.0; cell[5]=0.0; - cell[6]=0.0; cell[7]=0.0; cell[8]=0.0; + cell[0]=0.0; + cell[1]=0.0; + cell[2]=0.0; + cell[3]=0.0; + cell[4]=0.0; + cell[5]=0.0; + cell[6]=0.0; + cell[7]=0.0; + cell[8]=0.0; } } else { - for(unsigned i=0; i<9; i++)cell[i]=pbc_cli_box[i]; + for(unsigned i=0; i<9; i++) { + cell[i]=pbc_cli_box[i]; + } } // info on coords // the order is xyzxyz... @@ -949,17 +1177,34 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { auto pos=Tools::make_unique(natoms); float prec,lambda; int ret=xdrfile::exdrOK; - if(trajectory_fmt=="xdr-xtc") ret=xdrfile::read_xtc(xd,natoms,&localstep,&time,box,pos.get(),&prec); - if(trajectory_fmt=="xdr-trr") ret=xdrfile::read_trr(xd,natoms,&localstep,&time,&lambda,box,pos.get(),NULL,NULL); - if(stride==0) step=localstep; - if(ret==xdrfile::exdrENDOFFILE) break; - if(ret!=xdrfile::exdrOK) break; - for(unsigned i=0; i<3; i++) for(unsigned j=0; j<3; j++) cell[3*i+j]=box[i][j]; - for(int i=0; i celld(9,0.0); if(pbc_cli_given==false) { @@ -979,36 +1224,52 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { Tools::convert(words[6],celld[6]); Tools::convert(words[7],celld[7]); Tools::convert(words[8],celld[8]); - } else error("needed box in second line of xyz file"); + } else { + error("needed box in second line of xyz file"); + } } else { // from command line celld=pbc_cli_box; } - for(unsigned i=0; i<9; i++)cell[i]=real(celld[i]); + for(unsigned i=0; i<9; i++) { + cell[i]=real(celld[i]); + } } if(trajectory_fmt=="dlp4") { std::vector celld(9,0.0); if(pbc_cli_given==false) { - if(!Tools::getline(fp,line)) error("error reading vector a of cell"); + if(!Tools::getline(fp,line)) { + error("error reading vector a of cell"); + } std::sscanf(line.c_str(),"%lf %lf %lf",&celld[0],&celld[1],&celld[2]); - if(!Tools::getline(fp,line)) error("error reading vector b of cell"); + if(!Tools::getline(fp,line)) { + error("error reading vector b of cell"); + } std::sscanf(line.c_str(),"%lf %lf %lf",&celld[3],&celld[4],&celld[5]); - if(!Tools::getline(fp,line)) error("error reading vector c of cell"); + if(!Tools::getline(fp,line)) { + error("error reading vector c of cell"); + } std::sscanf(line.c_str(),"%lf %lf %lf",&celld[6],&celld[7],&celld[8]); } else { celld=pbc_cli_box; } - for(auto i=0; i<9; i++)cell[i]=real(celld[i])*0.1; + for(auto i=0; i<9; i++) { + cell[i]=real(celld[i])*0.1; + } } int ddist=0; // Read coordinates for(int i=0; i::main(FILE* in,FILE*out,Communicator& pc) { // const char *p1, *p2, *p3; p1 = std::strchr(line.c_str(), '.'); - if (p1 == NULL) error("seems there are no coordinates in the gro file"); + if (p1 == NULL) { + error("seems there are no coordinates in the gro file"); + } p2 = std::strchr(&p1[1], '.'); - if (p2 == NULL) error("seems there is only one coordinates in the gro file"); + if (p2 == NULL) { + error("seems there is only one coordinates in the gro file"); + } ddist = p2 - p1; p3 = std::strchr(&p2[1], '.'); - if (p3 == NULL)error("seems there are only two coordinates in the gro file"); - if (p3 - p2 != ddist)error("not uniform spacing in fields in the gro file"); + if (p3 == NULL) { + error("seems there are only two coordinates in the gro file"); + } + if (p3 - p2 != ddist) { + error("not uniform spacing in fields in the gro file"); + } } Tools::convert(line.substr(20,ddist),cc[0]); Tools::convert(line.substr(20+ddist,ddist),cc[1]); @@ -1035,18 +1304,26 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { std::sscanf(line.c_str(),"%8s %d %lf %lf",dummy,&idummy,&m,&c); masses[i]=real(m); charges[i]=real(c); - if(!Tools::getline(fp,line)) error("error reading coordinates"); + if(!Tools::getline(fp,line)) { + error("error reading coordinates"); + } std::sscanf(line.c_str(),"%lf %lf %lf",&cc[0],&cc[1],&cc[2]); cc[0]*=0.1; cc[1]*=0.1; cc[2]*=0.1; if(lvl>0) { - if(!Tools::getline(fp,line)) error("error skipping velocities"); + if(!Tools::getline(fp,line)) { + error("error skipping velocities"); + } } if(lvl>1) { - if(!Tools::getline(fp,line)) error("error skipping forces"); + if(!Tools::getline(fp,line)) { + error("error skipping forces"); + } } - } else plumed_error(); + } else { + plumed_error(); + } if(!debug_pd || ( i>=pd_start && i::main(FILE* in,FILE*out,Communicator& pc) { } } if(trajectory_fmt=="gro") { - if(!Tools::getline(fp,line)) error("premature end of trajectory file"); + if(!Tools::getline(fp,line)) { + error("premature end of trajectory file"); + } std::vector words=Tools::getWords(line); - if(words.size()<3) error("cannot understand box format"); + if(words.size()<3) { + error("cannot understand box format"); + } Tools::convert(words[0],cell[0]); Tools::convert(words[1],cell[4]); Tools::convert(words[2],cell[8]); - if(words.size()>3) Tools::convert(words[3],cell[1]); - if(words.size()>4) Tools::convert(words[4],cell[2]); - if(words.size()>5) Tools::convert(words[5],cell[3]); - if(words.size()>6) Tools::convert(words[6],cell[5]); - if(words.size()>7) Tools::convert(words[7],cell[6]); - if(words.size()>8) Tools::convert(words[8],cell[7]); + if(words.size()>3) { + Tools::convert(words[3],cell[1]); + } + if(words.size()>4) { + Tools::convert(words[4],cell[2]); + } + if(words.size()>5) { + Tools::convert(words[5],cell[3]); + } + if(words.size()>6) { + Tools::convert(words[6],cell[5]); + } + if(words.size()>7) { + Tools::convert(words[7],cell[6]); + } + if(words.size()>8) { + Tools::convert(words[8],cell[7]); + } } } @@ -1110,7 +1403,9 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { // this is necessary as only processor zero is adding to the virial: intracomm.Bcast(virial,0); - if(debug_pd) intracomm.Sum(forces); + if(debug_pd) { + intracomm.Sum(forces); + } if(debug_dd) { for(int i=0; i::main(FILE* in,FILE*out,Communicator& pc) { int r=intercomm.Get_rank(); int n=intercomm.Get_size(); int partner=r+(2*((r+step/grex_stride)%2))-1; - if(partner<0)partner=0; - if(partner>=n) partner=n-1; + if(partner<0) { + partner=0; + } + if(partner>=n) { + partner=n-1; + } p.cmd("GREX setPartner",partner); p.cmd("GREX calculate"); p.cmd("GREX shareAllDeltaBias"); for(int i=0; i::quiet_NaN(); s="GREX getDeltaBias "+s; p.cmd(s,&a); - if(grex_log) std::fprintf(grex_log," %f",a); + std::string s; + Tools::convert(i,s); + real a=std::numeric_limits::quiet_NaN(); + s="GREX getDeltaBias "+s; + p.cmd(s,&a); + if(grex_log) { + std::fprintf(grex_log," %f",a); + } + } + if(grex_log) { + std::fprintf(grex_log,"\n"); } - if(grex_log) std::fprintf(grex_log,"\n"); } } @@ -1153,14 +1459,18 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { std::fprintf(fp_forces,fmt.c_str(),virial[0],virial[4],virial[8]); } fmt="X "+fmt; - for(int i=0; i0) { // Now call the routine to work out the derivatives numerically - numder.assign(3*natoms+9,real(0.0)); real base=0; + numder.assign(3*natoms+9,real(0.0)); + real base=0; p.cmd("getBias",&base); - if( std::abs(base)::main(FILE* in,FILE*out,Communicator& pc) { } } - if(plumedStopCondition) break; + if(plumedStopCondition) { + break; + } step+=stride; } - if(!parseOnly) p.cmd("runFinalJobs"); + if(!parseOnly) { + p.cmd("runFinalJobs"); + } return 0; } @@ -1194,11 +1508,15 @@ void Driver::evaluateNumericalDerivatives( const long long int& step, Plum const std::vector& masses, const std::vector& charges, std::vector& cell, const double& base, std::vector& numder ) { - int natoms = coordinates.size() / 3; real delta = std::sqrt(epsilon); - std::vector pos(natoms); real bias=0; + int natoms = coordinates.size() / 3; + real delta = std::sqrt(epsilon); + std::vector pos(natoms); + real bias=0; std::vector fake_forces( 3*natoms ), fake_virial(9); for(int i=0; i::evaluateNumericalDerivatives( const long long int& step, Plum // Create the cell Tensor box( cell[0], cell[1], cell[2], cell[3], cell[4], cell[5], cell[6], cell[7], cell[8] ); // And the virial - Pbc pbc; pbc.setBox( box ); Tensor nvirial; - for(unsigned i=0; i<3; i++) for(unsigned k=0; k<3; k++) { + Pbc pbc; + pbc.setBox( box ); + Tensor nvirial; + for(unsigned i=0; i<3; i++) + for(unsigned k=0; k<3; k++) { double arg0=box(i,k); - for(int j=0; j::evaluateNumericalDerivatives( const long long int& step, Plum p.cmd("prepareCalc"); p.cmd("performCalcNoUpdate"); p.cmd("getBias",&bias); - cell[3*i+k]=box(i,k)=arg0; pbc.setBox(box); - for(int j=0; j DriverFloat; /// Specialized version template<> -std::string Driver::description()const { return "analyze trajectories with plumed (single precision version)"; } +std::string Driver::description()const { + return "analyze trajectories with plumed (single precision version)"; +} PLUMED_REGISTER_CLTOOL(DriverFloat,"driver-float") diff --git a/src/cltools/GenExample.cpp b/src/cltools/GenExample.cpp index 81a0a2a198..97779cb84b 100644 --- a/src/cltools/GenExample.cpp +++ b/src/cltools/GenExample.cpp @@ -60,8 +60,7 @@ plumed gen_example --plumed plumed.dat --status working //+ENDPLUMEDOC class GenExample: - public CLTool -{ + public CLTool { private: int multi; std::string status, version; @@ -93,8 +92,7 @@ GenExample::GenExample(const CLToolOptions& co ): CLTool(co), multi(0), status("nobadge"), - version("master") -{ + version("master") { inputdata=commandline; } @@ -103,32 +101,61 @@ int GenExample::main(FILE* in, FILE*out,Communicator& pc) { // set up for multi replica driver: parse("--multi",multi); if(multi) { - int ntot=pc.Get_size(); int nintra=ntot/multi; - if(multi*nintra!=ntot) error("invalid number of processes for multi environment"); + int ntot=pc.Get_size(); + int nintra=ntot/multi; + if(multi*nintra!=ntot) { + error("invalid number of processes for multi environment"); + } pc.Split(pc.Get_rank()/nintra,pc.Get_rank(),intracomm); pc.Split(pc.Get_rank()%nintra,pc.Get_rank(),intercomm); } else { intracomm.Set_comm(pc.Get_comm()); } - if( config::getVersionLong().find("dev")==std::string::npos ) version="v"+config::getVersion(); - std::string fname, egname, outfile; parse("--plumed",fname); - parse("--name",egname); parse("--out",outfile); parse("--status",status); + if( config::getVersionLong().find("dev")==std::string::npos ) { + version="v"+config::getVersion(); + } + std::string fname, egname, outfile; + parse("--plumed",fname); + parse("--name",egname); + parse("--out",outfile); + parse("--status",status); int r=0; - if(intracomm.Get_rank()==0) r=intercomm.Get_rank(); + if(intracomm.Get_rank()==0) { + r=intercomm.Get_rank(); + } intracomm.Bcast(r,0); - if(r>0) outfile="/dev/null"; + if(r>0) { + outfile="/dev/null"; + } - IFile ifile; ifile.open(fname); ifile.allowNoEOL(); std::ofstream ofile; ofile.open(outfile); std::vector shortcuts; - bool hasshortcuts=false, endplumed=false; std::vector > input; std::vector words; + IFile ifile; + ifile.open(fname); + ifile.allowNoEOL(); + std::ofstream ofile; + ofile.open(outfile); + std::vector shortcuts; + bool hasshortcuts=false, endplumed=false; + std::vector > input; + std::vector words; while( Tools::getParsedLine(ifile, words, false) ) { - input.push_back( words ); shortcuts.push_back( false ); - if( words.empty() || words[0].find("#")!=std::string::npos || endplumed ) continue; - std::vector interpreted( words ); Tools::interpretLabel(interpreted); - if( interpreted[0]=="ENDPLUMED" ) { endplumed=true; continue; } - Keywords keys; actionRegister().getKeywords( interpreted[0], keys ); - if( status=="working" && keys.exists("IS_SHORTCUT") ) hasshortcuts=shortcuts[shortcuts.size()-1]=true; + input.push_back( words ); + shortcuts.push_back( false ); + if( words.empty() || words[0].find("#")!=std::string::npos || endplumed ) { + continue; + } + std::vector interpreted( words ); + Tools::interpretLabel(interpreted); + if( interpreted[0]=="ENDPLUMED" ) { + endplumed=true; + continue; + } + Keywords keys; + actionRegister().getKeywords( interpreted[0], keys ); + if( status=="working" && keys.exists("IS_SHORTCUT") ) { + hasshortcuts=shortcuts[shortcuts.size()-1]=true; + } } ifile.close(); if( hasshortcuts ) { @@ -139,11 +166,17 @@ int GenExample::main(FILE* in, FILE*out,Communicator& pc) { } ofile<<"
"; ofile<<"\"tested
"; ofile.flush(); if( hasshortcuts ) { @@ -169,107 +202,204 @@ int GenExample::main(FILE* in, FILE*out,Communicator& pc) { std::vector > long_input = createLongInput( input ); printExampleInput( long_input, egname + "long", egname, ofile ); ofile<<""< > GenExample::createLongInput( const std::vector >& input ) { - std::vector > long_input; PlumedMain myplumed; int rr=sizeof(double), natoms=10000000; double kt=2.49; + std::vector > long_input; + PlumedMain myplumed; + int rr=sizeof(double), natoms=10000000; + double kt=2.49; myplumed.cmd("setRealPrecision",&rr); if(Communicator::initialized()) { if(multi) { - if(intracomm.Get_rank()==0) myplumed.cmd("GREX setMPIIntercomm",&intercomm.Get_comm()); - myplumed.cmd("GREX setMPIIntracomm",&intracomm.Get_comm()); myplumed.cmd("GREX init"); + if(intracomm.Get_rank()==0) { + myplumed.cmd("GREX setMPIIntercomm",&intercomm.Get_comm()); + } + myplumed.cmd("GREX setMPIIntracomm",&intracomm.Get_comm()); + myplumed.cmd("GREX init"); } myplumed.cmd("setMPIComm",&intracomm.Get_comm()); } - bool endplumed=false; myplumed.cmd("setNatoms",&natoms); myplumed.cmd("setKbT",&kt); myplumed.cmd("init"); + bool endplumed=false; + myplumed.cmd("setNatoms",&natoms); + myplumed.cmd("setKbT",&kt); + myplumed.cmd("init"); for(unsigned ll=0; ll interpreted( input[ll] ); Tools::interpretLabel(interpreted); - if( interpreted[0]=="ENDPLUMED" ) { endplumed=true; long_input.push_back( input[ll] ); continue; } - Keywords keys; plumed_assert( actionRegister().check( interpreted[0] ) ); - actionRegister().getKeywords( interpreted[0], keys ); std::string lab, myinputline; - if( Tools::parse(interpreted, "LABEL", lab ) ) myinputline = lab + ": "; - myinputline += interpreted[0] + " "; bool trailingcomment=false; + if( input[ll].empty() || endplumed ) { + long_input.push_back( input[ll] ); + continue; + } + if( input[ll][0].find("#")!=std::string::npos ) { + long_input.push_back( input[ll] ); + continue; + } + std::vector interpreted( input[ll] ); + Tools::interpretLabel(interpreted); + if( interpreted[0]=="ENDPLUMED" ) { + endplumed=true; + long_input.push_back( input[ll] ); + continue; + } + Keywords keys; + plumed_assert( actionRegister().check( interpreted[0] ) ); + actionRegister().getKeywords( interpreted[0], keys ); + std::string lab, myinputline; + if( Tools::parse(interpreted, "LABEL", lab ) ) { + myinputline = lab + ": "; + } + myinputline += interpreted[0] + " "; + bool trailingcomment=false; for(unsigned i=1; i( myplumed.getActionSet()[myplumed.getActionSet().size()-1].get() ); - plumed_assert( as ); std::vector shortcut_commands = as->getSavedInputLines(); + plumed_assert( as ); + std::vector shortcut_commands = as->getSavedInputLines(); for(unsigned i=0; i words = Tools::getWords( shortcut_commands[i] ); long_input.push_back( words ); + std::vector words = Tools::getWords( shortcut_commands[i] ); + long_input.push_back( words ); } - } else { long_input.push_back( input[ll] ); myplumed.readInputLine( myinputline ); } + } else { + long_input.push_back( input[ll] ); + myplumed.readInputLine( myinputline ); + } } return long_input; } void GenExample::printExampleInput( const std::vector >& input, const std::string& egname, const std::string& divname, std::ofstream& ofile ) { - PlumedMain myplumed; int rr=sizeof(double), natoms=10000000; double kt=2.49; + PlumedMain myplumed; + int rr=sizeof(double), natoms=10000000; + double kt=2.49; myplumed.cmd("setRealPrecision",&rr); if(Communicator::initialized()) { if(multi) { - if(intracomm.Get_rank()==0) myplumed.cmd("GREX setMPIIntercomm",&intercomm.Get_comm()); - myplumed.cmd("GREX setMPIIntracomm",&intracomm.Get_comm()); myplumed.cmd("GREX init"); + if(intracomm.Get_rank()==0) { + myplumed.cmd("GREX setMPIIntercomm",&intercomm.Get_comm()); + } + myplumed.cmd("GREX setMPIIntracomm",&intracomm.Get_comm()); + myplumed.cmd("GREX init"); } myplumed.cmd("setMPIComm",&intracomm.Get_comm()); } - myplumed.cmd("setNatoms",&natoms); myplumed.cmd("setKbT",&kt); myplumed.cmd("init"); - std::vector labellist; bool endplumed=false; + myplumed.cmd("setNatoms",&natoms); + myplumed.cmd("setKbT",&kt); + myplumed.cmd("init"); + std::vector labellist; + bool endplumed=false; ofile<<"
"<"<"< interpreted( input[ll] ); Tools::interpretLabel(interpreted); std::string lab, myinputline;
+      std::vector interpreted( input[ll] );
+      Tools::interpretLabel(interpreted);
+      std::string lab, myinputline;
       // Now read in the label
       if( Tools::parse(interpreted,"LABEL",lab) ) {
         ofile<<""<";
-        labellist.push_back(lab); myinputline = lab + ": ";
+        labellist.push_back(lab);
+        myinputline = lab + ": ";
       }
       // Print the keyword in use in the action
-      std::string action = interpreted[0]; myinputline += interpreted[0] + " ";
-      if( action=="ENDPLUMED" ) endplumed=true;
-      Keywords keys; actionRegister().getKeywords( interpreted[0], keys );
+      std::string action = interpreted[0];
+      myinputline += interpreted[0] + " ";
+      if( action=="ENDPLUMED" ) {
+        endplumed=true;
+      }
+      Keywords keys;
+      actionRegister().getKeywords( interpreted[0], keys );
       // Handle conversion of action names to links
-      std::transform(action.begin(), action.end(), action.begin(), [](unsigned char c) { return std::tolower(c); });
+      std::transform(action.begin(), action.end(), action.begin(), [](unsigned char c) {
+        return std::tolower(c);
+      });
       ofile<<""< ";
       // And write out everything else in the input line
       bool trailingcomment=false;
       for(unsigned i=1; i"; trailingcomment=false; }
-          if( interpreted[i+1]=="..." ) ofile<";
+            trailingcomment=false;
+          }
+          if( interpreted[i+1]=="..." ) {
+            ofile<__FILL__";
           continue;
-        } else if( interpreted[i]==action ) continue;
-        if( interpreted[i].find("#")!=std::string::npos ) { trailingcomment=true; ofile<<""; }
+        } else if( interpreted[i]==action ) {
+          continue;
+        }
+        if( interpreted[i].find("#")!=std::string::npos ) {
+          trailingcomment=true;
+          ofile<<"";
+        }
 
         if( !trailingcomment ) {
           std::size_t eq=interpreted[i].find_first_of("=");
@@ -277,22 +407,41 @@ void GenExample::printExampleInput( const std::vector >
             std::string keyword=interpreted[i].substr(0,eq), rest=interpreted[i].substr(eq+1);
             ofile<<"
"<"<
"; if( rest=="__FILL__" ) { - if( status!="incomplete" ) error("found __FILL__ statement but status is " + status); + if( status!="incomplete" ) { + error("found __FILL__ statement but status is " + status); + } ofile<<"=__FILL__"; } else if( rest.find_first_of("{")!=std::string::npos ) { - std::size_t pos = 0; while ((pos = rest.find("@newline",pos)) != std::string::npos) { rest.replace(pos, 8, "\n"); pos++; } - ofile<<"="< args=Tools::getWords(rest,"\t\n ,"); ofile<<"="; + std::vector args=Tools::getWords(rest,"\t\n ,"); + ofile<<"="; for(unsigned i=0; i"<"; + } else { + ofile<"<"; - else ofile< > } else if( interpreted[i]!="@newline" && interpreted[i]!="..." ) { myinputline += interpreted[i] + " "; ofile<<"
"<"<
"; - } else if( interpreted[i]=="..." ) ofile<<"..."; - } else ofile<"; } - if( trailingcomment ) ofile<<"
"; // This builds the hidden content that tells the user about what is calculated if( status=="working" ) { ofile<<""; @@ -311,14 +466,16 @@ void GenExample::printExampleInput( const std::vector > myplumed.readInputLine( myinputline ); ActionWithValue* av=myplumed.getActionSet().selectWithLabel(lab); if( av ) { - if( av->getNumberOfComponents()==1 ) { ofile<<" calculates a single scalar value"; } - else if( av->getNumberOfComponents()>0 ) { + if( av->getNumberOfComponents()==1 ) { + ofile<<" calculates a single scalar value"; + } else if( av->getNumberOfComponents()>0 ) { ofile<<" calculates the following quantities:"<"< Quantity Description "<getNumberOfComponents(); for(unsigned k=0; kcopyOutput(k)->getName(); std::size_t dot=myname.find_first_of("."); + std::string myname = av->copyOutput(k)->getName(); + std::size_t dot=myname.find_first_of("."); std::string tname=myname.substr(dot+1); ofile<<""<"<getOutputComponentDescription(tname,keys)<<""< > } } else { ActionWithVirtualAtom* avv=myplumed.getActionSet().selectWithLabel(lab); - if( avv ) ofile<<" calculates the position of a virtual atom"; - else if( interpreted[0]=="GROUP" ) ofile<<" defines a group of atoms so that they can be referred to later in the input"; + if( avv ) { + ofile<<" calculates the position of a virtual atom"; + } else if( interpreted[0]=="GROUP" ) { + ofile<<" defines a group of atoms so that they can be referred to later in the input"; + } } ofile<<""< action_map; while((stat=myfile.getline(line))) { - std::size_t col = line.find_first_of(":"); std::string docs = line.substr(col+1); - if( docs.find("\\")!=std::string::npos ) error("found invalid backslash character in first line of documentation for action " + line.substr(0,col) ); + std::size_t col = line.find_first_of(":"); + std::string docs = line.substr(col+1); + if( docs.find("\\")!=std::string::npos ) { + error("found invalid backslash character in first line of documentation for action " + line.substr(0,col) ); + } action_map.insert(std::pair( line.substr(0,col), docs ) ); } myfile.close(); @@ -95,34 +102,61 @@ int GenJson::main(FILE* in, FILE*out,Communicator& pc) { // Get the names of all the actions std::vector action_names( actionRegister().getActionNames() ); for(unsigned i=0; isecond<<"\",\n"; // Now output keyword information - Keywords keys; actionRegister().getKeywords( action_names[i], keys ); + Keywords keys; + actionRegister().getKeywords( action_names[i], keys ); std::cout<<" \"displayname\" : \""<0 ) { std::vector neededActions( keys.getNeededKeywords() ); std::cout<<" \"needs\" : ["<<"\""<getRank()>0 && v->hasDerivatives() ) ofile.printf("linkStyle %d stroke:green,color:green;\n", linkcount); - else if( v->getRank()==1 ) ofile.printf("linkStyle %d stroke:blue,color:blue;\n", linkcount); - else if ( v->getRank()==2 ) ofile.printf("linkStyle %d stroke:red,color:red;\n", linkcount); + if( v->getRank()>0 && v->hasDerivatives() ) { + ofile.printf("linkStyle %d stroke:green,color:green;\n", linkcount); + } else if( v->getRank()==1 ) { + ofile.printf("linkStyle %d stroke:blue,color:blue;\n", linkcount); + } else if ( v->getRank()==2 ) { + ofile.printf("linkStyle %d stroke:red,color:red;\n", linkcount); + } } void ShowGraph::printArgumentConnections( const ActionWithArguments* a, unsigned& linkcount, const bool& force, OFile& ofile ) { - if( !a ) return; + if( !a ) { + return; + } for(const auto & v : a->getArguments() ) { if( force && v->forcesWereAdded() ) { ofile.printf("%s -- %s --> %s\n", getLabel(a).c_str(), v->getName().c_str(), getLabel(v->getPntrToAction()).c_str() ); - printStyle( linkcount, v, ofile ); linkcount++; + printStyle( linkcount, v, ofile ); + linkcount++; } else if( !force ) { ofile.printf("%s -- %s --> %s\n", getLabel(v->getPntrToAction()).c_str(),v->getName().c_str(),getLabel(a).c_str() ); - printStyle( linkcount, v, ofile ); linkcount++; + printStyle( linkcount, v, ofile ); + linkcount++; } } } void ShowGraph::printAtomConnections( const ActionAtomistic* a, unsigned& linkcount, const bool& force, OFile& ofile ) { - if( !a ) return; + if( !a ) { + return; + } for(const auto & d : a->getDependencies() ) { ActionToPutData* dp=dynamic_cast(d); if( dp && dp->getLabel()=="posx" ) { if( force && (dp->copyOutput(0))->forcesWereAdded() ) { ofile.printf("%s --> MD\n", getLabel(a).c_str() ); - ofile.printf("linkStyle %d stroke:violet,color:violet;\n", linkcount); linkcount++; + ofile.printf("linkStyle %d stroke:violet,color:violet;\n", linkcount); + linkcount++; } else { ofile.printf("MD --> %s\n", getLabel(a).c_str() ); - ofile.printf("linkStyle %d stroke:violet,color:violet;\n", linkcount); linkcount++; + ofile.printf("linkStyle %d stroke:violet,color:violet;\n", linkcount); + linkcount++; } } else if( dp && dp->getLabel()!="posy" && dp->getLabel()!="posz" && dp->getLabel()!="Masses" && dp->getLabel()!="Charges" ) { if( force && (dp->copyOutput(0))->forcesWereAdded() ) { ofile.printf("%s -- %s --> %s\n",getLabel(a).c_str(), getLabel(d).c_str(), getLabel(d).c_str() ); - printStyle( linkcount, dp->copyOutput(0), ofile ); linkcount++; + printStyle( linkcount, dp->copyOutput(0), ofile ); + linkcount++; } else { ofile.printf("%s -- %s --> %s\n", getLabel(d).c_str(),getLabel(d).c_str(),getLabel(a).c_str() ); - printStyle( linkcount, dp->copyOutput(0), ofile ); linkcount++; + printStyle( linkcount, dp->copyOutput(0), ofile ); + linkcount++; } continue; } @@ -146,10 +162,12 @@ void ShowGraph::printAtomConnections( const ActionAtomistic* a, unsigned& linkco if( dv ) { if( force && (dv->copyOutput(0))->forcesWereAdded() ) { ofile.printf("%s -- %s --> %s\n", getLabel(a).c_str(),getLabel(d).c_str(),getLabel(d).c_str() ); - ofile.printf("linkStyle %d stroke:violet,color:violet;\n", linkcount); linkcount++; + ofile.printf("linkStyle %d stroke:violet,color:violet;\n", linkcount); + linkcount++; } else { ofile.printf("%s -- %s --> %s\n", getLabel(d).c_str(),getLabel(d).c_str(),getLabel(a).c_str() ); - ofile.printf("linkStyle %d stroke:violet,color:violet;\n", linkcount); linkcount++; + ofile.printf("linkStyle %d stroke:violet,color:violet;\n", linkcount); + linkcount++; } } } @@ -157,46 +175,67 @@ void ShowGraph::printAtomConnections( const ActionAtomistic* a, unsigned& linkco void ShowGraph::drawActionWithVectorNode( OFile& ofile, PlumedMain& p, Action* ag, const std::vector& mychain, std::vector& printed ) { ActionWithVector* agg=dynamic_cast(ag); - std::vector matchain; agg->getAllActionLabelsInMatrixChain( matchain ); + std::vector matchain; + agg->getAllActionLabelsInMatrixChain( matchain ); if( matchain.size()>0 ) { ofile.printf("subgraph sub%s_mat [%s]\n",getLabel(agg).c_str(), getLabel(agg).c_str()); for(unsigned j=0; j(matchain[j]); for(unsigned k=0; kwriteInGraph().c_str() ); } ofile.printf("end\n"); ofile.printf("style sub%s_mat fill:lightblue\n",getLabel(ag).c_str()); - } else ofile.printf("%s([\"label=%s \n %s \n\"])\n", getLabel(ag->getLabel()).c_str(), getLabel(ag->getLabel(),true).c_str(), ag->writeInGraph().c_str() ); + } else { + ofile.printf("%s([\"label=%s \n %s \n\"])\n", getLabel(ag->getLabel()).c_str(), getLabel(ag->getLabel(),true).c_str(), ag->writeInGraph().c_str() ); + } } int ShowGraph::main(FILE* in, FILE*out,Communicator& pc) { - std::string inpt; parse("--plumed",inpt); - std::string outp; parse("--out",outp); - bool forces; parseFlag("--force",forces); + std::string inpt; + parse("--plumed",inpt); + std::string outp; + parse("--out",outp); + bool forces; + parseFlag("--force",forces); // Create a plumed main object and initilize - PlumedMain p; int rr=sizeof(double); + PlumedMain p; + int rr=sizeof(double); p.cmd("setRealPrecision",&rr); - double lunit=1.0; p.cmd("setMDLengthUnits",&lunit); - double cunit=1.0; p.cmd("setMDChargeUnits",&cunit); - double munit=1.0; p.cmd("setMDMassUnits",&munit); + double lunit=1.0; + p.cmd("setMDLengthUnits",&lunit); + double cunit=1.0; + p.cmd("setMDChargeUnits",&cunit); + double munit=1.0; + p.cmd("setMDMassUnits",&munit); p.cmd("setPlumedDat",inpt.c_str()); p.cmd("setLog",out); - int natoms=1000000; p.cmd("setNatoms",&natoms); + int natoms=1000000; + p.cmd("setNatoms",&natoms); p.cmd("init"); - unsigned linkcount=0; OFile ofile; ofile.open(outp); + unsigned linkcount=0; + OFile ofile; + ofile.open(outp); if( forces ) { - unsigned step=1; p.cmd("setStep",step); + unsigned step=1; + p.cmd("setStep",step); p.cmd("prepareCalc"); - ofile.printf("flowchart BT \n"); std::vector drawn_nodes; std::set atom_force_set; + ofile.printf("flowchart BT \n"); + std::vector drawn_nodes; + std::set atom_force_set; for(auto pp=p.getActionSet().rbegin(); pp!=p.getActionSet().rend(); ++pp) { const auto & a(pp->get()); - if( a->getName()=="DOMAIN_DECOMPOSITION" || a->getLabel()=="posx" || a->getLabel()=="posy" || a->getLabel()=="posz" || a->getLabel()=="Masses" || a->getLabel()=="Charges" ) continue; + if( a->getName()=="DOMAIN_DECOMPOSITION" || a->getLabel()=="posx" || a->getLabel()=="posy" || a->getLabel()=="posz" || a->getLabel()=="Masses" || a->getLabel()=="Charges" ) { + continue; + } if(a->isActive()) { ActionToPutData* ap=dynamic_cast(a); @@ -205,55 +244,88 @@ int ShowGraph::main(FILE* in, FILE*out,Communicator& pc) { continue; } ActionWithValue* av=dynamic_cast(a); - if( !av ) continue ; + if( !av ) { + continue ; + } // Now apply the force if there is one a->apply(); bool hasforce=false; for(int i=0; igetNumberOfComponents(); ++i) { - if( (av->copyOutput(i))->forcesWereAdded() ) { hasforce=true; break; } + if( (av->copyOutput(i))->forcesWereAdded() ) { + hasforce=true; + break; + } } //Check if there are forces here ActionWithArguments* aaa=dynamic_cast(a); if( aaa ) { for(const auto & v : aaa->getArguments() ) { - if( v->forcesWereAdded() ) { hasforce=true; break; } + if( v->forcesWereAdded() ) { + hasforce=true; + break; + } } } - if( !hasforce ) continue; + if( !hasforce ) { + continue; + } ActionWithVector* avec=dynamic_cast(a); if( avec ) { ActionWithVector* head=avec->getFirstActionInChain(); - std::vector mychain; head->getAllActionLabelsInChain( mychain ); std::vector printed(mychain.size(),false); + std::vector mychain; + head->getAllActionLabelsInChain( mychain ); + std::vector printed(mychain.size(),false); ofile.printf("subgraph sub%s [%s]\n",getLabel(head).c_str(),getLabel(head).c_str()); for(unsigned i=0; i(mychain[i]); + plumed_assert( ag ); + drawn_nodes.push_back( mychain[i] ); + if( !printed[i] ) { + drawActionWithVectorNode( ofile, p, ag, mychain, printed ); + printed[i]=true; } - if( drawn ) continue; - ActionWithVector* ag=p.getActionSet().selectWithLabel(mychain[i]); plumed_assert( ag ); drawn_nodes.push_back( mychain[i] ); - if( !printed[i] ) { drawActionWithVectorNode( ofile, p, ag, mychain, printed ); printed[i]=true; } for(const auto & v : ag->getArguments() ) { bool chain_conn=false; for(unsigned j=0; jgetPntrToAction())->getLabel()==mychain[j] ) { chain_conn=true; break; } + if( (v->getPntrToAction())->getLabel()==mychain[j] ) { + chain_conn=true; + break; + } + } + if( !chain_conn ) { + continue; } - if( !chain_conn ) continue; ofile.printf("%s -. %s .-> %s\n", getLabel(v->getPntrToAction()).c_str(),v->getName().c_str(),getLabel(ag).c_str() ); - printStyle( linkcount, v, ofile ); linkcount++; + printStyle( linkcount, v, ofile ); + linkcount++; } } ofile.printf("end\n"); if( avec!=head ) { for(unsigned i=0; i( mychain[i] ); plumed_assert(c); + ActionWithVector* c = p.getActionSet().selectWithLabel( mychain[i] ); + plumed_assert(c); if( c->getNumberOfAtoms()>0 || c->hasStoredArguments() ) { for(unsigned j=0; jgetNumberOfComponents(); ++j ) { - if( avec->copyOutput(j)->getRank()>0 ) continue; + if( avec->copyOutput(j)->getRank()>0 ) { + continue; + } ofile.printf("%s == %s ==> %s\n", getLabel(avec).c_str(), avec->copyOutput(j)->getName().c_str(), getLabel(c).c_str() ); linkcount++; } - if( c->getNumberOfAtoms()>0 ) atom_force_set.insert( c->getLabel() ); + if( c->getNumberOfAtoms()>0 ) { + atom_force_set.insert( c->getLabel() ); + } } } } @@ -268,34 +340,43 @@ int ShowGraph::main(FILE* in, FILE*out,Communicator& pc) { // Now draw connections from action atomistic to relevant actions std::vector all_atoms = p.getActionSet().select(); for(const auto & at : all_atoms ) { - ActionWithValue* av=dynamic_cast(at); bool hasforce=false; + ActionWithValue* av=dynamic_cast(at); + bool hasforce=false; if( av ) { for(unsigned i=0; igetNumberOfComponents(); ++i ) { if( av->copyOutput(i)->forcesWereAdded() ) { printAtomConnections( at, linkcount, true, ofile ); - atom_force_set.erase( av->getLabel() ); break; + atom_force_set.erase( av->getLabel() ); + break; } } } } for(const auto & l : atom_force_set ) { ActionAtomistic* at = p.getActionSet().selectWithLabel(l); - plumed_assert(at); printAtomConnections( at, linkcount, true, ofile ); + plumed_assert(at); + printAtomConnections( at, linkcount, true, ofile ); } ofile.printf("MD(positions from MD)\n"); return 0; } - ofile.printf("flowchart TB \n"); ofile.printf("MD(positions from MD)\n"); + ofile.printf("flowchart TB \n"); + ofile.printf("MD(positions from MD)\n"); for(const auto & aa : p.getActionSet() ) { Action* a(aa.get()); - if( a->getName()=="DOMAIN_DECOMPOSITION" || a->getLabel()=="posx" || a->getLabel()=="posy" || a->getLabel()=="posz" || a->getLabel()=="Masses" || a->getLabel()=="Charges" ) continue; + if( a->getName()=="DOMAIN_DECOMPOSITION" || a->getLabel()=="posx" || a->getLabel()=="posy" || a->getLabel()=="posz" || a->getLabel()=="Masses" || a->getLabel()=="Charges" ) { + continue; + } ActionToPutData* ap=dynamic_cast(a); if( ap ) { ofile.printf("%s(\"label=%s \n %s \n\")\n", getLabel(a).c_str(), getLabel(a,true).c_str(), a->writeInGraph().c_str() ); continue; } - ActionShortcut* as=dynamic_cast(a); if( as ) continue ; + ActionShortcut* as=dynamic_cast(a); + if( as ) { + continue ; + } ActionWithValue* av=dynamic_cast(a); ActionWithArguments* aaa=dynamic_cast(a); ActionAtomistic* at=dynamic_cast(a); @@ -306,10 +387,15 @@ int ShowGraph::main(FILE* in, FILE*out,Communicator& pc) { // Print out the nodes if( avec && !avec->actionInChain() ) { ofile.printf("subgraph sub%s [%s]\n",getLabel(a).c_str(),getLabel(a).c_str()); - std::vector mychain; avec->getAllActionLabelsInChain( mychain ); std::vector printed(mychain.size(),false); + std::vector mychain; + avec->getAllActionLabelsInChain( mychain ); + std::vector printed(mychain.size(),false); for(unsigned i=0; i(mychain[i]); - if( !printed[i] ) { drawActionWithVectorNode( ofile, p, ag, mychain, printed ); printed[i]=true; } + if( !printed[i] ) { + drawActionWithVectorNode( ofile, p, ag, mychain, printed ); + printed[i]=true; + } } ofile.printf("end\n"); } else if( !av ) { diff --git a/src/cltools/SimpleMD.cpp b/src/cltools/SimpleMD.cpp index 586f986dc3..0d4979e563 100644 --- a/src/cltools/SimpleMD.cpp +++ b/src/cltools/SimpleMD.cpp @@ -76,11 +76,14 @@ plumed simplemd --help // simple static function to close a file // defined once here since it's used in many places in this file // in addition, this seems the only way to use it in the write_statistics_fp_deleter member -static void (*deleter)(FILE* f) = [](auto f) { if(f) std::fclose(f); }; +static void (*deleter)(FILE* f) = [](auto f) { + if(f) { + std::fclose(f); + } +}; class SimpleMD: - public PLMD::CLTool -{ + public PLMD::CLTool { std::string description()const override { return "run lj code"; } @@ -116,8 +119,7 @@ class SimpleMD: write_positions_first(true), write_statistics_first(true), write_statistics_last_time_reopened(0), - write_statistics_fp(NULL) - { + write_statistics_fp(NULL) { inputdata=ifile; } @@ -140,17 +142,22 @@ class SimpleMD: int& ndim, int& idum, double& epsilon, - double& sigma) - { + double& sigma) { // Read everything from input file char buffer1[256]; - std::string tempstr; parse("temperature",tempstr); - if( tempstr!="NVE" ) Tools::convert(tempstr,temperature); + std::string tempstr; + parse("temperature",tempstr); + if( tempstr!="NVE" ) { + Tools::convert(tempstr,temperature); + } parse("tstep",tstep); - std::string frictionstr; parse("friction",frictionstr); + std::string frictionstr; + parse("friction",frictionstr); if( tempstr!="NVE" ) { - if(frictionstr=="off") error("Specify friction for thermostat"); + if(frictionstr=="off") { + error("Specify friction for thermostat"); + } Tools::convert(frictionstr,friction); } parse("forcecutoff",forcecutoff); @@ -162,62 +169,90 @@ class SimpleMD: // Read in stuff with sanity checks parse("inputfile",inputfile); - if(inputfile.length()==0) error("Specify input file"); + if(inputfile.length()==0) { + error("Specify input file"); + } parse("outputfile",outputfile); - if(outputfile.length()==0) error("Specify output file"); - std::string nconfstr; parse("nconfig",nconfstr); + if(outputfile.length()==0) { + error("Specify output file"); + } + std::string nconfstr; + parse("nconfig",nconfstr); std::sscanf(nconfstr.c_str(),"%100d %255s",&nconfig,buffer1); trajfile=buffer1; - if(trajfile.length()==0) error("Specify traj file"); - std::string nstatstr; parse("nstat",nstatstr); + if(trajfile.length()==0) { + error("Specify traj file"); + } + std::string nstatstr; + parse("nstat",nstatstr); std::sscanf(nstatstr.c_str(),"%100d %255s",&nstat,buffer1); statfile=buffer1; - if(statfile.length()==0) error("Specify stat file"); + if(statfile.length()==0) { + error("Specify stat file"); + } parse("ndim",ndim); - if(ndim<1 || ndim>3) error("ndim should be 1,2 or 3"); + if(ndim<1 || ndim>3) { + error("ndim should be 1,2 or 3"); + } std::string w; parse("wrapatoms",w); wrapatoms=false; - if(w.length()>0 && (w[0]=='T' || w[0]=='t')) wrapatoms=true; + if(w.length()>0 && (w[0]=='T' || w[0]=='t')) { + wrapatoms=true; + } } void read_natoms(const std::string & inputfile,int & natoms) { // read the number of atoms in file "input.xyz" FILE* fp=std::fopen(inputfile.c_str(),"r"); - if(!fp) error(std::string("file ") + inputfile + std::string(" not found")); + if(!fp) { + error(std::string("file ") + inputfile + std::string(" not found")); + } // call fclose when fp goes out of scope std::unique_ptr fp_deleter(fp,deleter); int ret=std::fscanf(fp,"%1000d",&natoms); - if(ret==0) plumed_error() <<"Error reading number of atoms from file "<& positions,double cell[3]) { // read positions and cell from a file called inputfile // natoms (input variable) and number of atoms in the file should be consistent FILE* fp=std::fopen(inputfile.c_str(),"r"); - if(!fp) error(std::string("file ") + inputfile + std::string(" not found")); + if(!fp) { + error(std::string("file ") + inputfile + std::string(" not found")); + } // call fclose when fp goes out of scope std::unique_ptr fp_deleter(fp,deleter); char buffer[256]; char atomname[256]; char* cret=fgets(buffer,256,fp); - if(cret==nullptr) plumed_error() <<"Error reading buffer from file "<&masses,std::vector& velocities,Random&random) { // randomize the velocities according to the temperature - for(int iatom=0; iatom& positions,const std::vector&positions0,const double listcutoff, - const double forcecutoff,bool & recompute) - { + const double forcecutoff,bool & recompute) { // check if the neighbour list have to be recomputed recompute=false; auto delta2=(0.5*(listcutoff-forcecutoff))*(0.5*(listcutoff-forcecutoff)); // if ANY atom moved more than half of the skin thickness, recompute is set to .true. for(int iatom=0; iatomdelta2) recompute=true; + if(modulo2(positions[iatom]-positions0[iatom])>delta2) { + recompute=true; + } } } @@ -251,19 +287,23 @@ class SimpleMD: Vector distance_pbc; // minimum-image distance of the two atoms pbc(cell,distance,distance_pbc); // if the interparticle distance is larger than the cutoff, skip - if(modulo2(distance_pbc)>listcutoff2)continue; + if(modulo2(distance_pbc)>listcutoff2) { + continue; + } list[iatom].push_back(jatom); } } } void compute_forces(const int natoms,double epsilon, double sigma,const std::vector& positions,const double cell[3], - double forcecutoff,const std::vector >& list,std::vector& forces,double & engconf) - { + double forcecutoff,const std::vector >& list,std::vector& forces,double & engconf) { double forcecutoff2=forcecutoff*forcecutoff; // squared force cutoff engconf=0.0; double engconf_tmp=0.0; // separate variable for reduction (gcc 4.8 does not make reductions on references) - for(int i=0; iforcecutoff2) continue; + if(distance_pbc2>forcecutoff2) { + continue; + } auto distance_pbcm2=sigma*sigma/distance_pbc2; auto distance_pbcm6=distance_pbcm2*distance_pbcm2*distance_pbcm2; auto distance_pbcm8=distance_pbcm6*distance_pbcm2; @@ -290,15 +332,16 @@ class SimpleMD: } } # pragma omp critical - for(unsigned i=0; i& masses,const std::vector& velocities,double & engkin) - { + void compute_engkin(const int natoms,const std::vector& masses,const std::vector& velocities,double & engkin) { // calculate the kinetic energy from the velocities engkin=0.0; for(int iatom=0; iatom& positions,const double cell[3],const bool wrapatoms) - { + void write_positions(const std::string& trajfile,int natoms,const std::vector& positions,const double cell[3],const bool wrapatoms) { // write positions on file trajfile // positions are appended at the end of the file Vector pos; @@ -343,14 +385,16 @@ class SimpleMD: for(int iatom=0; iatom& positions,const double cell[3],const bool wrapatoms) - { + void write_final_positions(const std::string& outputfile,int natoms,const std::vector& positions,const double cell[3],const bool wrapatoms) { // write positions on file outputfile Vector pos; FILE*fp; @@ -363,8 +407,11 @@ class SimpleMD: for(int iatom=0; iatom(); - if(plumed) plumed->cmd("setRealPrecision",int(sizeof(double))); + if(plumed) { + plumed->cmd("setRealPrecision",int(sizeof(double))); + } read_input(temperature,tstep,friction,forcecutoff, listcutoff,nstep,nconfig,nstat, @@ -481,7 +530,9 @@ class SimpleMD: list.resize(natoms); // masses are hard-coded to 1 - for(int i=0; i1 // even if not necessary in principle in SimpleMD (which is part of plumed) // we leave the check here as a reference - if(pversion>1) plumed->cmd("setKbT",temperature); + if(pversion>1) { + plumed->cmd("setKbT",temperature); + } plumed->cmd("init"); } @@ -511,16 +564,23 @@ class SimpleMD: compute_list(natoms,positions,cell,listcutoff,list); int list_size=0; - for(int i=0; icmd("setStep",istep+1); plumed->cmd("setMasses",&masses[0]); plumed->cmd("setForces",&forces[0][0]); @@ -566,14 +637,20 @@ class SimpleMD: plumed->cmd("setBox",&cell9[0][0]); plumed->cmd("setStopFlag",&plumedWantsToStop); plumed->cmd("calc"); - if(plumedWantsToStop) nstep=istep; + if(plumedWantsToStop) { + nstep=istep; + } } // remove forces if ndim<3 if(ndim<3) - for(int iatom=0; iatom gmin(cvs.size()); if(parseVector("--min",gmin)) { - if(gmin.size()!=cvs.size() && gmin.size()!=0) plumed_merror("not enough values for --min"); + if(gmin.size()!=cvs.size() && gmin.size()!=0) { + plumed_merror("not enough values for --min"); + } grid_check++; } std::vector gmax(cvs.size() ); if(parseVector("--max",gmax)) { - if(gmax.size()!=cvs.size() && gmax.size()!=0) plumed_merror("not enough values for --max"); + if(gmax.size()!=cvs.size() && gmax.size()!=0) { + plumed_merror("not enough values for --max"); + } grid_check++; } std::vector gbin(cvs.size()); - bool grid_has_bin; grid_has_bin=false; + bool grid_has_bin; + grid_has_bin=false; if(parseVector("--bin",gbin)) { - if(gbin.size()!=cvs.size() && gbin.size()!=0) plumed_merror("not enough values for --bin"); + if(gbin.size()!=cvs.size() && gbin.size()!=0) { + plumed_merror("not enough values for --bin"); + } grid_has_bin=true; } std::vector gspacing(cvs.size()); - bool grid_has_spacing; grid_has_spacing=false; + bool grid_has_spacing; + grid_has_spacing=false; if(parseVector("--spacing",gspacing)) { - if(gspacing.size()!=cvs.size() && gspacing.size()!=0) plumed_merror("not enough values for --spacing"); + if(gspacing.size()!=cvs.size() && gspacing.size()!=0) { + plumed_merror("not enough values for --spacing"); + } grid_has_spacing=true; } // allowed: no grids only bin @@ -320,7 +333,9 @@ int CLToolSumHills::main(FILE* in,FILE*out,Communicator& pc) { unsigned nn=1; ss="setNatoms"; plumed.cmd(ss,&nn); - if(Communicator::initialized()) plumed.cmd("setMPIComm",&pc.Get_comm()); + if(Communicator::initialized()) { + plumed.cmd("setMPIComm",&pc.Get_comm()); + } plumed.cmd("init",&nn); std::vector isdone(cvs.size(),false); for(unsigned i=0; i1) { comps.push_back(cvs[j][1]); - periods.push_back(pmin[j]); periods.push_back(pmax[j]); - isdone[j]=true; inds.push_back(j); + periods.push_back(pmin[j]); + periods.push_back(pmax[j]); + isdone[j]=true; + inds.push_back(j); } } @@ -349,7 +372,9 @@ int CLToolSumHills::main(FILE* in,FILE*out,Communicator& pc) { std::string addme; if(comps.size()>0) { addme="COMPONENTS="; - for(unsigned i=0; i1) { - if(idw[i]==cvs[j][0]+"."+cvs[j][1])found=true; + if(idw[i]==cvs[j][0]+"."+cvs[j][1]) { + found=true; + } } else { - if(idw[i]==cvs[j][0])found=true; + if(idw[i]==cvs[j][0]) { + found=true; + } } } - if(!found)plumed_merror("variable "+idw[i]+" is not found in the bunch of cvs: revise your --idw option" ); + if(!found) { + plumed_merror("variable "+idw[i]+" is not found in the bunch of cvs: revise your --idw option" ); + } } plumed_massert( idw.size()<=cvs.size(),"the number of variables to be integrated should be at most equal to the total number of cvs "); // in this case you need a beta factor! } - std::string kt; kt=std::string("1.");// assign an arbitrary value just in case that idw.size()==cvs.size() + std::string kt; + kt=std::string("1.");// assign an arbitrary value just in case that idw.size()==cvs.size() if ( dohisto || idw.size()!=0 ) { plumed_massert(parse("--kt",kt),"if you make a dimensionality reduction (--idw) or a histogram (--histo) then you need to define --kt "); } @@ -448,25 +481,46 @@ int CLToolSumHills::main(FILE* in,FILE*out,Communicator& pc) { // cerr<<"AA "<1) {mm=cvs.back()[0]+"."+cvs.back()[1];} else {mm=cvs.back()[0];} + std::string mm; + if((cvs.back()).size()>1) { + mm=cvs.back()[0]+"."+cvs.back()[1]; + } else { + mm=cvs.back()[0]; + } if(ifile.FieldExist("min_"+mm)) { std::string val; ifile.scanField("min_"+mm,val); @@ -598,8 +678,11 @@ bool CLToolSumHills::findCvsAndPeriodic(const std::string & filename, std::vecto if(ifile.FieldExist("multivariate")) { ; ifile.scanField("multivariate",sss); - if(sss=="true") { multivariate=true;} - else if(sss=="false") { multivariate=false;} + if(sss=="true") { + multivariate=true; + } else if(sss=="false") { + multivariate=false; + } } // do interval? if(ifile.FieldExist("lower_int")) { diff --git a/src/cltools/SwitchingPlotter.cpp b/src/cltools/SwitchingPlotter.cpp index 58ab537a1e..0d2f069951 100644 --- a/src/cltools/SwitchingPlotter.cpp +++ b/src/cltools/SwitchingPlotter.cpp @@ -163,7 +163,8 @@ int SwitchingPlotter::main( FILE*, FILE*, Communicator& ) { return (r0-lowerLimit)/(interval *Nsteps); } return (upperLimit-lowerLimit)/double(Nsteps); - }(); + } + (); if (step <0.0) { error("I calculated a negative step"); } diff --git a/src/cltools/kT.cpp b/src/cltools/kT.cpp index edefb93596..45c19e942f 100644 --- a/src/cltools/kT.cpp +++ b/src/cltools/kT.cpp @@ -48,8 +48,7 @@ plumed kt --temp 300 --units eV //+ENDPLUMEDOC class kt: - public CLTool -{ + public CLTool { public: static void registerKeywords( Keywords& keys ); explicit kt(const CLToolOptions& co ); @@ -68,16 +67,18 @@ void kt::registerKeywords( Keywords& keys ) { } kt::kt(const CLToolOptions& co ): - CLTool(co) -{ + CLTool(co) { inputdata=commandline; } int kt::main(FILE* in, FILE*out,Communicator& pc) { - std::string unitname; parse("--units",unitname); - Units units; units.setEnergy( unitname ); - double temp; parse("--temp",temp); + std::string unitname; + parse("--units",unitname); + Units units; + units.setEnergy( unitname ); + double temp; + parse("--temp",temp); double kk=(kBoltzmann*temp)/units.getEnergy(); std::fprintf(out,"When the temperature is %f kelvin kT is equal to %f %s\n",temp,kk,unitname.c_str()); return 0; diff --git a/src/cltools/pesmd.cpp b/src/cltools/pesmd.cpp index e98e8da597..718edf5528 100644 --- a/src/cltools/pesmd.cpp +++ b/src/cltools/pesmd.cpp @@ -115,8 +115,7 @@ class PesMD : public PLMD::CLTool { } explicit PesMD( const CLToolOptions& co ) : - CLTool(co) - { + CLTool(co) { inputdata=ifile; } @@ -131,29 +130,43 @@ class PesMD : public PLMD::CLTool { int& nstep, bool& lperiod, std::vector& periods, - int& idum) - { + int& idum) { // Read everything from input file - std::string tempstr; parse("temperature",tempstr); - if( tempstr!="NVE" ) Tools::convert(tempstr,temperature); + std::string tempstr; + parse("temperature",tempstr); + if( tempstr!="NVE" ) { + Tools::convert(tempstr,temperature); + } parse("tstep",tstep); - std::string frictionstr; parse("friction",frictionstr); + std::string frictionstr; + parse("friction",frictionstr); if( tempstr!="NVE" ) { - if(frictionstr=="off") error("pecify friction for thermostat"); + if(frictionstr=="off") { + error("pecify friction for thermostat"); + } Tools::convert(frictionstr,friction); } - parse("plumed",plumedin); parse("dimension",dim); - parse("nstep",nstep); parse("idum",idum); - ipos.resize( dim ); parseVector("ipos",ipos); + parse("plumed",plumedin); + parse("dimension",dim); + parse("nstep",nstep); + parse("idum",idum); + ipos.resize( dim ); + parseVector("ipos",ipos); parseFlag("periodic",lperiod); if( lperiod ) { - if( dim>3 ) error("can only do three dimensional periodic functions"); - std::vector min( dim ); parseVector("min",min); - std::vector max( dim ); parseVector("max",max); + if( dim>3 ) { + error("can only do three dimensional periodic functions"); + } + std::vector min( dim ); + parseVector("min",min); + std::vector max( dim ); + parseVector("max",max); periods.resize( dim ); for(int i=0; i ipos; - double temp, tstep, friction; bool lperiod; - int dim, nsteps, seed; std::vector periods; + std::string plumedin; + std::vector ipos; + double temp, tstep, friction; + bool lperiod; + int dim, nsteps, seed; + std::vector periods; int plumedWantsToStop; Random random; @@ -175,16 +191,26 @@ class PesMD : public PLMD::CLTool { // Setup box if we have periodic domain std::vector box(9, 0.0); - if( lperiod && dim==1 ) { box[0]=box[4]=box[8]=periods[0]; } - else if( lperiod && dim==2 ) { box[0]=periods[0]; box[4]=box[8]=periods[1]; } - else if( lperiod && dim==3 ) { box[0]=periods[0]; box[4]=periods[1]; box[8]=periods[2]; } - else if( lperiod ) error("invalid dimension for periodic potential must be 1, 2 or 3"); + if( lperiod && dim==1 ) { + box[0]=box[4]=box[8]=periods[0]; + } else if( lperiod && dim==2 ) { + box[0]=periods[0]; + box[4]=box[8]=periods[1]; + } else if( lperiod && dim==3 ) { + box[0]=periods[0]; + box[4]=periods[1]; + box[8]=periods[2]; + } else if( lperiod ) { + error("invalid dimension for periodic potential must be 1, 2 or 3"); + } // Create plumed object and initialize auto plumed=Tools::make_unique(); int s=sizeof(double); plumed->cmd("setRealPrecision",&s); - if(Communicator::initialized()) plumed->cmd("setMPIComm",&pc.Get_comm()); + if(Communicator::initialized()) { + plumed->cmd("setMPIComm",&pc.Get_comm()); + } int natoms=( std::floor(dim/3) + 2 ); plumed->cmd("setNatoms",&natoms); plumed->cmd("setNoVirial"); @@ -198,30 +224,44 @@ class PesMD : public PLMD::CLTool { std::vector masses( 1+nat, 1 ); std::vector velocities( nat ), positions( nat+1 ), forces( nat+1 ); // Will set these properly eventually - int k=0; positions[0].zero(); // Atom zero is fixed at origin - for(int i=0; idim-1 ) break; + if( 3*i+j>dim-1 ) { + break; + } tke += 0.5*velocities[i][j]*velocities[i][j]; } } // Now call plumed to get initial forces - int istep=0; double zero=0; + int istep=0; + double zero=0; plumed->cmd("setStep",&istep); plumed->cmd("setMasses",&masses[0]); Tools::set_to_zero(forces); plumed->cmd("setForces",&forces[0][0]); plumed->cmd("setEnergy",&zero); - if( lperiod ) plumed->cmd("setBox",&box[0]); + if( lperiod ) { + plumed->cmd("setBox",&box[0]); + } plumed->cmd("setPositions",&positions[0][0]); plumed->cmd("calc"); @@ -230,14 +270,18 @@ class PesMD : public PLMD::CLTool { for(int istep=0; istepdim-1 ) break; + if( 3*j+k>dim-1 ) { + break; + } therm_eng=therm_eng+0.5*velocities[j][k]*velocities[j][k]; velocities[j][k]=lscale*velocities[j][k]+lrand*random.Gaussian(); therm_eng=therm_eng-0.5*velocities[j][k]*velocities[0][k]; @@ -247,7 +291,9 @@ class PesMD : public PLMD::CLTool { // First step of velocity verlet for(int j=0; jdim-1 ) break; + if( 3*j+k>dim-1 ) { + break; + } velocities[j][k] = velocities[j][k] + 0.5*tstep*forces[1+j][k]; positions[1+j][k] = positions[1+j][k] + tstep*velocities[j][k]; } @@ -265,12 +311,16 @@ class PesMD : public PLMD::CLTool { plumed->cmd("setStopFlag",&plumedWantsToStop); plumed->cmd("calc"); // if(istep%2000==0) plumed->cmd("writeCheckPointFile"); - if(plumedWantsToStop) nsteps=istep; + if(plumedWantsToStop) { + nsteps=istep; + } // Second step of velocity verlet for(int j=0; jdim-1 ) break; + if( 3*j+k>dim-1 ) { + break; + } velocities[j][k] = velocities[j][k] + 0.5*tstep*forces[1+j][k]; } } @@ -280,7 +330,9 @@ class PesMD : public PLMD::CLTool { lrand=std::sqrt((1.-lscale*lscale)*temp); for(int j=0; jdim-1) break; + if( 3*j+k>dim-1) { + break; + } therm_eng=therm_eng+0.5*velocities[j][k]*velocities[j][k]; velocities[j][k]=lscale*velocities[j][k]+lrand*random.Gaussian(); therm_eng=therm_eng-0.5*velocities[j][k]*velocities[j][k]; @@ -290,14 +342,18 @@ class PesMD : public PLMD::CLTool { tke=0; for(int i=0; idim-1 ) break; + if( 3*i+j>dim-1 ) { + break; + } tke += 0.5*velocities[i][j]*velocities[i][j]; } } // Print everything // conserved = potential+1.5*ttt+therm_eng; - if( pc.Get_rank()==0 ) std::fprintf(fp,"%i %f %f %f \n", istep, istep*tstep, tke, therm_eng ); + if( pc.Get_rank()==0 ) { + std::fprintf(fp,"%i %f %f %f \n", istep, istep*tstep, tke, therm_eng ); + } } fclose(fp); diff --git a/src/clusters/ClusterDiameter.cpp b/src/clusters/ClusterDiameter.cpp index 79318a62c9..bf6b4574a3 100644 --- a/src/clusters/ClusterDiameter.cpp +++ b/src/clusters/ClusterDiameter.cpp @@ -73,16 +73,20 @@ void ClusterDiameter::registerKeywords( Keywords& keys ) { keys.add("optional","ARG","calculate ths radius of the cluster that are in this particular cluster"); keys.add("compulsory","ATOMS","the atoms that were used to calculate the matrix that was clustered"); keys.setValueDescription("the largest of all the distances between the pairs of atom in the cluster"); - keys.needsAction("DISTANCE_MATRIX"); keys.needsAction("OUTER_PRODUCT"); keys.needsAction("CUSTOM"); - keys.needsAction("FLATTEN"); keys.needsAction("HIGHEST"); + keys.needsAction("DISTANCE_MATRIX"); + keys.needsAction("OUTER_PRODUCT"); + keys.needsAction("CUSTOM"); + keys.needsAction("FLATTEN"); + keys.needsAction("HIGHEST"); } ClusterDiameter::ClusterDiameter(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read in the argument - std::string arg_str, atdata; parse("ARG",arg_str); parse("ATOMS",atdata); + std::string arg_str, atdata; + parse("ARG",arg_str); + parse("ATOMS",atdata); // Distance matrix readInputLine( getShortcutLabel() + "_dmat: DISTANCE_MATRIX GROUP=" + atdata ); // Matrix of bonds in cluster diff --git a/src/clusters/ClusterDistribution.cpp b/src/clusters/ClusterDistribution.cpp index 7a38671a1c..7bca694b7a 100644 --- a/src/clusters/ClusterDistribution.cpp +++ b/src/clusters/ClusterDistribution.cpp @@ -98,8 +98,10 @@ PLUMED_REGISTER_ACTION(ClusterDistribution,"CLUSTER_DISTRIBUTION_CALC") void ClusterDistribution::registerKeywords( Keywords& keys ) { Action::registerKeywords( keys ); ActionWithArguments::registerKeywords( keys ); - ActionWithValue::registerKeywords( keys ); keys.remove("NUMERICAL_DERIVATIVES"); - keys.add("compulsory","CLUSTERS","the label of the action that does the clustering"); keys.setDisplayName("CLUSTER_DISTRIBUTION"); + ActionWithValue::registerKeywords( keys ); + keys.remove("NUMERICAL_DERIVATIVES"); + keys.add("compulsory","CLUSTERS","the label of the action that does the clustering"); + keys.setDisplayName("CLUSTER_DISTRIBUTION"); keys.add("optional","WEIGHTS","use the vector of values calculated by this action as weights rather than giving each atom a unit weight"); keys.setValueDescription("a vector containing the sum of a atomic-cv that is calculated for each of the identified clusters"); } @@ -107,19 +109,28 @@ void ClusterDistribution::registerKeywords( Keywords& keys ) { ClusterDistribution::ClusterDistribution(const ActionOptions&ao): Action(ao), ActionWithArguments(ao), - ActionWithValue(ao) -{ + ActionWithValue(ao) { // Read in the clustering object - std::vector clusters; parseArgumentList("CLUSTERS",clusters); - if( clusters.size()!=1 ) error("should pass only one matrix to clustering base"); + std::vector clusters; + parseArgumentList("CLUSTERS",clusters); + if( clusters.size()!=1 ) { + error("should pass only one matrix to clustering base"); + } ClusteringBase* cc = dynamic_cast( clusters[0]->getPntrToAction() ); - if( !cc ) error("input to CLUSTERS keyword should be a clustering action"); - std::vector weights; parseArgumentList("WEIGHTS",weights); + if( !cc ) { + error("input to CLUSTERS keyword should be a clustering action"); + } + std::vector weights; + parseArgumentList("WEIGHTS",weights); if( weights.size()==0 ) { log.printf(" using unit weights in cluster distribution \n"); } else if( weights.size()==1 ) { - if( weights[0]->getRank()!=1 ) error("input weights has wrong shape"); - if( weights[0]->getShape()[0]!=clusters[0]->getShape()[0] ) error("mismatch between number of weights and number of atoms"); + if( weights[0]->getRank()!=1 ) { + error("input weights has wrong shape"); + } + if( weights[0]->getShape()[0]!=clusters[0]->getShape()[0] ) { + error("mismatch between number of weights and number of atoms"); + } log.printf(" using weights from action with label %s in cluster distribution \n", weights[0]->getName().c_str() ); clusters.push_back( weights[0] ); } else { @@ -128,10 +139,15 @@ ClusterDistribution::ClusterDistribution(const ActionOptions&ao): // Request the arguments requestArguments( clusters ); getPntrToArgument(0)->buildDataStore(); - if( getNumberOfArguments()>1 ) getPntrToArgument(1)->buildDataStore(); + if( getNumberOfArguments()>1 ) { + getPntrToArgument(1)->buildDataStore(); + } // Now create the value - std::vector shape(1); shape[0]=clusters[0]->getShape()[0]; - addValue( shape ); setNotPeriodic(); getPntrToValue()->buildDataStore(); + std::vector shape(1); + shape[0]=clusters[0]->getShape()[0]; + addValue( shape ); + setNotPeriodic(); + getPntrToValue()->buildDataStore(); } unsigned ClusterDistribution::getNumberOfDerivatives() { @@ -140,17 +156,24 @@ unsigned ClusterDistribution::getNumberOfDerivatives() { void ClusterDistribution::calculate() { plumed_assert( getPntrToArgument(0)->valueHasBeenSet() ); - if( getNumberOfArguments()>1 ) plumed_assert( getPntrToArgument(1)->valueHasBeenSet() ); + if( getNumberOfArguments()>1 ) { + plumed_assert( getPntrToArgument(1)->valueHasBeenSet() ); + } double csize = getPntrToArgument(0)->get(0); for(unsigned i=1; igetShape()[0]; ++i) { - if( getPntrToArgument(0)->get(i)>csize ) csize = getPntrToArgument(0)->get(i); + if( getPntrToArgument(0)->get(i)>csize ) { + csize = getPntrToArgument(0)->get(i); + } } unsigned ntasks = static_cast( csize ); for(unsigned i=0; igetShape()[0]; ++j) { if( fabs(getPntrToArgument(0)->get(j)-i)add( i, getPntrToArgument(1)->get(j) ); - else getPntrToValue()->add( i, 1.0 ); + if( getNumberOfArguments()==2 ) { + getPntrToValue()->add( i, getPntrToArgument(1)->get(j) ); + } else { + getPntrToValue()->add( i, 1.0 ); + } } } } @@ -174,9 +197,9 @@ void ClusterDistributionShortcut::registerKeywords( Keywords& keys ) { ClusterDistributionShortcut::ClusterDistributionShortcut(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - std::map keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + ActionShortcut(ao) { + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); readInputLine( getShortcutLabel() + ": CLUSTER_DISTRIBUTION_CALC " + convertInputLineToString() ); multicolvar::MultiColvarShortcuts::expandFunctions( getShortcutLabel(), getShortcutLabel(), "", keymap, this ); } diff --git a/src/clusters/ClusterNatoms.cpp b/src/clusters/ClusterNatoms.cpp index ebe64c7167..d1d7eca06e 100644 --- a/src/clusters/ClusterNatoms.cpp +++ b/src/clusters/ClusterNatoms.cpp @@ -47,13 +47,13 @@ void ClusterNatoms::registerKeywords(Keywords& keys) { keys.add("compulsory","CLUSTERS","the label of the action that does the clustering"); keys.add("compulsory","CLUSTER","1","which cluster would you like to look at 1 is the largest cluster, 2 is the second largest, 3 is the the third largest and so on."); keys.setValueDescription("the number of atoms in the cluster"); - keys.needsAction("CLUSTER_WEIGHTS"); keys.needsAction("SUM"); + keys.needsAction("CLUSTER_WEIGHTS"); + keys.needsAction("SUM"); } ClusterNatoms::ClusterNatoms(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Create a cluster weights object readInputLine( getShortcutLabel() + "_weights: CLUSTER_WEIGHTS " + convertInputLineToString() ); // Add all the weights together (weights are 1 or 0) diff --git a/src/clusters/ClusterProperties.cpp b/src/clusters/ClusterProperties.cpp index 3799a1bbb3..e2169be1f3 100644 --- a/src/clusters/ClusterProperties.cpp +++ b/src/clusters/ClusterProperties.cpp @@ -75,12 +75,13 @@ void ClusterProperties::registerKeywords(Keywords& keys) { ClusterProperties::ClusterProperties(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read the property we are interested in - std::string argstr; parse("ARG",argstr); + std::string argstr; + parse("ARG",argstr); // Read in the shortcut keywords - std::map keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); // Create a cluster weights object readInputLine( getShortcutLabel() + ": CLUSTER_WEIGHTS " + convertInputLineToString() ); // Now do the multicolvar bit diff --git a/src/clusters/ClusterWeights.cpp b/src/clusters/ClusterWeights.cpp index e19bcd0bcb..9ff7543661 100644 --- a/src/clusters/ClusterWeights.cpp +++ b/src/clusters/ClusterWeights.cpp @@ -64,8 +64,10 @@ PLUMED_REGISTER_ACTION(ClusterWeights,"CLUSTER_WEIGHTS") void ClusterWeights::registerKeywords( Keywords& keys ) { Action::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.remove("ARG"); - ActionWithValue::registerKeywords( keys ); keys.remove("NUMERICAL_DERIVATIVES"); + ActionWithArguments::registerKeywords( keys ); + keys.remove("ARG"); + ActionWithValue::registerKeywords( keys ); + keys.remove("NUMERICAL_DERIVATIVES"); keys.add("compulsory","CLUSTERS","the label of the action that does the clustering"); keys.add("compulsory","CLUSTER","1","which cluster would you like to look at 1 is the largest cluster, 2 is the second largest, 3 is the the third largest and so on."); keys.addFlag("LOWMEM",false,"this flag does nothing and is present only to ensure back-compatibility"); @@ -76,24 +78,38 @@ void ClusterWeights::registerKeywords( Keywords& keys ) { ClusterWeights::ClusterWeights(const ActionOptions&ao): Action(ao), ActionWithArguments(ao), - ActionWithValue(ao) -{ - bool lowmem; parseFlag("LOWMEM",lowmem); - if( lowmem ) warning("LOWMEM flag is deprecated and is no longer required for this action"); + ActionWithValue(ao) { + bool lowmem; + parseFlag("LOWMEM",lowmem); + if( lowmem ) { + warning("LOWMEM flag is deprecated and is no longer required for this action"); + } // Read in the clustering object - std::vector clusters; parseArgumentList("CLUSTERS",clusters); - if( clusters.size()!=1 ) error("should pass only one matrix to clustering base"); + std::vector clusters; + parseArgumentList("CLUSTERS",clusters); + if( clusters.size()!=1 ) { + error("should pass only one matrix to clustering base"); + } ClusteringBase* cc = dynamic_cast( clusters[0]->getPntrToAction() ); - if( !cc ) error("input to CLUSTERS keyword should be a clustering action"); + if( !cc ) { + error("input to CLUSTERS keyword should be a clustering action"); + } // Request the arguments requestArguments( clusters ); // Now create the value - std::vector shape(1); shape[0]=clusters[0]->getShape()[0]; - addValue( shape ); setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); + std::vector shape(1); + shape[0]=clusters[0]->getShape()[0]; + addValue( shape ); + setNotPeriodic(); + getPntrToComponent(0)->buildDataStore(); // Find out which cluster we want parse("CLUSTER",clustr); - if( clustr<1 ) error("cannot look for a cluster larger than the largest cluster"); - if( clustr>clusters[0]->getShape()[0] ) error("cluster selected is invalid - too few atoms in system"); + if( clustr<1 ) { + error("cannot look for a cluster larger than the largest cluster"); + } + if( clustr>clusters[0]->getShape()[0] ) { + error("cluster selected is invalid - too few atoms in system"); + } log.printf(" atoms in %dth largest cluster calculated by %s are equal to one \n",clustr, cc->getLabel().c_str() ); } @@ -104,7 +120,9 @@ unsigned ClusterWeights::getNumberOfDerivatives() { void ClusterWeights::calculate() { plumed_assert( getPntrToArgument(0)->valueHasBeenSet() ); for(unsigned i=0; igetShape()[0]; ++i) { - if( fabs(getPntrToArgument(0)->get(i)-clustr)set( i, 1.0 ); + if( fabs(getPntrToArgument(0)->get(i)-clustr)set( i, 1.0 ); + } } } diff --git a/src/clusters/ClusterWithSurface.cpp b/src/clusters/ClusterWithSurface.cpp index 357f21fa2c..56d14546ae 100644 --- a/src/clusters/ClusterWithSurface.cpp +++ b/src/clusters/ClusterWithSurface.cpp @@ -50,19 +50,22 @@ void ClusterWithSurface::registerKeywords(Keywords& keys) { keys.add("compulsory","CLUSTERS","the label of the action that does the clustering"); keys.add("compulsory","CLUSTER","1","which cluster would you like to look at 1 is the largest cluster, 2 is the second largest, 3 is the the third largest and so on."); keys.setValueDescription("a vector that is one for those atoms that are within the cluster or that are within a cetain cutoff of one of the atoms in the cluster and zero otherwise"); - keys.needsAction("CLUSTER_WEIGHTS"); keys.needsAction("CONTACT_MATRIX"); - keys.needsAction("OUTER_PRODUCT"); keys.needsAction("CUSTOM"); + keys.needsAction("CLUSTER_WEIGHTS"); + keys.needsAction("CONTACT_MATRIX"); + keys.needsAction("OUTER_PRODUCT"); + keys.needsAction("CUSTOM"); keys.needsAction("DFSCLUSTERING"); } ClusterWithSurface::ClusterWithSurface(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read atoms for contact matrix - std::string atdata; parse("ATOMS",atdata); + std::string atdata; + parse("ATOMS",atdata); // Read rcut input - std::string rcut_surf_str; parse("RCUT_SURF",rcut_surf_str); + std::string rcut_surf_str; + parse("RCUT_SURF",rcut_surf_str); // Create a cluster weights object readInputLine( getShortcutLabel() + "_wnosurf: CLUSTER_WEIGHTS " + convertInputLineToString() ); // Now create a contact matrix diff --git a/src/clusters/ClusteringBase.cpp b/src/clusters/ClusteringBase.cpp index 5a0b6c00e6..45c995404a 100644 --- a/src/clusters/ClusteringBase.cpp +++ b/src/clusters/ClusteringBase.cpp @@ -26,32 +26,42 @@ namespace PLMD { namespace clusters { void ClusteringBase::registerKeywords( Keywords& keys ) { - matrixtools::MatrixOperationBase::registerKeywords( keys ); keys.use("ARG"); + matrixtools::MatrixOperationBase::registerKeywords( keys ); + keys.use("ARG"); keys.setValueDescription("vector with length that is equal to the number of rows in the input matrix. Elements of this vector are equal to the cluster that each node is a part of"); } ClusteringBase::ClusteringBase(const ActionOptions&ao): Action(ao), matrixtools::MatrixOperationBase(ao), - number_of_cluster(-1) -{ + number_of_cluster(-1) { // Do some checks on the input - if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(0)->getShape()[1] ) error("input matrix should be square"); + if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(0)->getShape()[1] ) { + error("input matrix should be square"); + } // Now create a value - this holds the data on which cluster each guy is in - std::vector shape(1); shape[0]=getPntrToArgument(0)->getShape()[0]; + std::vector shape(1); + shape[0]=getPntrToArgument(0)->getShape()[0]; // Build the store here to make sure that next action has all data - addValue( shape ); setNotPeriodic(); getPntrToValue()->buildDataStore(); + addValue( shape ); + setNotPeriodic(); + getPntrToValue()->buildDataStore(); // Resize local variables - which_cluster.resize( getPntrToArgument(0)->getShape()[0] ); cluster_sizes.resize( getPntrToArgument(0)->getShape()[0] ); + which_cluster.resize( getPntrToArgument(0)->getShape()[0] ); + cluster_sizes.resize( getPntrToArgument(0)->getShape()[0] ); } void ClusteringBase::retrieveAdjacencyLists( std::vector& nneigh, Matrix& adj_list ) { // Make sure we have the edges stored - std::vector > pairs; std::vector vals; - unsigned nedge; getPntrToArgument(0)->retrieveEdgeList( nedge, pairs, vals ); + std::vector > pairs; + std::vector vals; + unsigned nedge; + getPntrToArgument(0)->retrieveEdgeList( nedge, pairs, vals ); // Currently everything has zero neighbors - for(unsigned i=0; igetNumberOfColumns() ) { unsigned nrows = getPntrToArgument(0)->getShape()[0]; @@ -62,15 +72,22 @@ void ClusteringBase::retrieveAdjacencyLists( std::vector& nneigh, Matr for(unsigned i=0; i(cluster_sizes.size()-i); for(unsigned j=0; jset( j, this_size ); + if( which_cluster[j]==cluster_sizes[i].second ) { + getPntrToValue()->set( j, this_size ); + } } } } void ClusteringBase::apply() { - if( getPntrToComponent(0)->forcesWereAdded() ) error("forces on clustering actions cannot work as clustering is not differentiable"); + if( getPntrToComponent(0)->forcesWereAdded() ) { + error("forces on clustering actions cannot work as clustering is not differentiable"); + } } } diff --git a/src/clusters/ClusteringBase.h b/src/clusters/ClusteringBase.h index 65bf6d1fce..5451e7158d 100644 --- a/src/clusters/ClusteringBase.h +++ b/src/clusters/ClusteringBase.h @@ -46,14 +46,18 @@ class ClusteringBase : public matrixtools::MatrixOperationBase { /// Constructor explicit ClusteringBase(const ActionOptions&); /// - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } /// void calculate() override; /// virtual void performClustering()=0; /// Cannot apply forces on a clustering object void apply() override ; - double getForceOnMatrixElement( const unsigned& jrow, const unsigned& krow ) const override { plumed_error(); } + double getForceOnMatrixElement( const unsigned& jrow, const unsigned& krow ) const override { + plumed_error(); + } }; inline diff --git a/src/clusters/DFSClustering.cpp b/src/clusters/DFSClustering.cpp index 85aab665f6..13215c9664 100644 --- a/src/clusters/DFSClustering.cpp +++ b/src/clusters/DFSClustering.cpp @@ -96,19 +96,23 @@ void DFSClustering::registerKeywords( Keywords& keys ) { DFSClustering::DFSClustering(const ActionOptions&ao): Action(ao), - ClusteringBase(ao) -{ + ClusteringBase(ao) { #ifndef __PLUMED_HAS_BOOST_GRAPH - nneigh.resize( getNumberOfNodes() ); color.resize(getNumberOfNodes()); + nneigh.resize( getNumberOfNodes() ); + color.resize(getNumberOfNodes()); #endif - bool lowmem; parseFlag("LOWMEM",lowmem); - if( lowmem ) warning("LOWMEM flag is deprecated and is no longer required for this action"); + bool lowmem; + parseFlag("LOWMEM",lowmem); + if( lowmem ) { + warning("LOWMEM flag is deprecated and is no longer required for this action"); + } } void DFSClustering::performClustering() { #ifdef __PLUMED_HAS_BOOST_GRAPH // Get the list of edges - unsigned nedges=0; retrieveEdgeList( 0, nedges ); + unsigned nedges=0; + retrieveEdgeList( 0, nedges ); // Build the graph using boost boost::adjacency_list sg(&pairs[0],&pairs[nedges],getNumberOfNodes()); @@ -117,15 +121,21 @@ void DFSClustering::performClustering() { number_of_cluster=boost::connected_components(sg,&which_cluster[0]) - 1; // And work out the size of each cluster - for(unsigned i=0; i& atoms, Actio atoms[2]=atoms[1]; } else if(atoms.size()==4) { aa->log.printf(" between lines %d-%d and %d-%d\n",atoms[0].serial(),atoms[1].serial(),atoms[2].serial(),atoms[3].serial()); - } else if( num<0 || atoms.size()>0 ) aa->error("Number of specified atoms should be either 3 or 4"); + } else if( num<0 || atoms.size()>0 ) { + aa->error("Number of specified atoms should be either 3 or 4"); + } } unsigned Angle::getModeAndSetupValues( ActionWithValue* av ) { - av->addValueWithDerivatives(); av->setNotPeriodic(); return 0; + av->addValueWithDerivatives(); + av->setNotPeriodic(); + return 0; } Angle::Angle(const ActionOptions&ao): @@ -149,18 +154,22 @@ Angle::Angle(const ActionOptions&ao): pbc(true), value(1), derivs(1), - virial(1) -{ + virial(1) { derivs[0].resize(4); - std::vector atoms; parseAtomList( -1, atoms, this ); + std::vector atoms; + parseAtomList( -1, atoms, this ); bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); requestAtoms(atoms); checkRead(); } @@ -168,10 +177,14 @@ Angle::Angle(const ActionOptions&ao): // calculator void Angle::calculate() { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } calculateCV( 0, masses, charges, getPositions(), value, derivs, virial, this ); setValue( value[0] ); - for(unsigned i=0; i& masses Vector dij,dik; dij=delta(pos[2],pos[3]); dik=delta(pos[1],pos[0]); - Vector ddij,ddik; PLMD::Angle a; + Vector ddij,ddik; + PLMD::Angle a; vals[0]=a.compute(dij,dik,ddij,ddik); - derivs[0][0]=ddik; derivs[0][1]=-ddik; - derivs[0][2]=-ddij; derivs[0][3]=ddij; + derivs[0][0]=ddik; + derivs[0][1]=-ddik; + derivs[0][2]=-ddij; + derivs[0][3]=ddij; setBoxDerivativesNoPbc( pos, derivs, virial ); } diff --git a/src/colvar/Cell.cpp b/src/colvar/Cell.cpp index 9385e854a7..2d31f50d95 100644 --- a/src/colvar/Cell.cpp +++ b/src/colvar/Cell.cpp @@ -58,20 +58,37 @@ class Cell : public Colvar { PLUMED_REGISTER_ACTION(Cell,"CELL") Cell::Cell(const ActionOptions&ao): - PLUMED_COLVAR_INIT(ao) -{ + PLUMED_COLVAR_INIT(ao) { std::vector atoms; checkRead(); - addComponentWithDerivatives("ax"); componentIsNotPeriodic("ax"); components[0][0]=getPntrToComponent("ax"); - addComponentWithDerivatives("ay"); componentIsNotPeriodic("ay"); components[0][1]=getPntrToComponent("ay"); - addComponentWithDerivatives("az"); componentIsNotPeriodic("az"); components[0][2]=getPntrToComponent("az"); - addComponentWithDerivatives("bx"); componentIsNotPeriodic("bx"); components[1][0]=getPntrToComponent("bx"); - addComponentWithDerivatives("by"); componentIsNotPeriodic("by"); components[1][1]=getPntrToComponent("by"); - addComponentWithDerivatives("bz"); componentIsNotPeriodic("bz"); components[1][2]=getPntrToComponent("bz"); - addComponentWithDerivatives("cx"); componentIsNotPeriodic("cx"); components[2][0]=getPntrToComponent("cx"); - addComponentWithDerivatives("cy"); componentIsNotPeriodic("cy"); components[2][1]=getPntrToComponent("cy"); - addComponentWithDerivatives("cz"); componentIsNotPeriodic("cz"); components[2][2]=getPntrToComponent("cz"); + addComponentWithDerivatives("ax"); + componentIsNotPeriodic("ax"); + components[0][0]=getPntrToComponent("ax"); + addComponentWithDerivatives("ay"); + componentIsNotPeriodic("ay"); + components[0][1]=getPntrToComponent("ay"); + addComponentWithDerivatives("az"); + componentIsNotPeriodic("az"); + components[0][2]=getPntrToComponent("az"); + addComponentWithDerivatives("bx"); + componentIsNotPeriodic("bx"); + components[1][0]=getPntrToComponent("bx"); + addComponentWithDerivatives("by"); + componentIsNotPeriodic("by"); + components[1][1]=getPntrToComponent("by"); + addComponentWithDerivatives("bz"); + componentIsNotPeriodic("bz"); + components[1][2]=getPntrToComponent("bz"); + addComponentWithDerivatives("cx"); + componentIsNotPeriodic("cx"); + components[2][0]=getPntrToComponent("cx"); + addComponentWithDerivatives("cy"); + componentIsNotPeriodic("cy"); + components[2][1]=getPntrToComponent("cy"); + addComponentWithDerivatives("cz"); + componentIsNotPeriodic("cz"); + components[2][2]=getPntrToComponent("cz"); requestAtoms(atoms); } @@ -94,9 +111,16 @@ void Cell::registerKeywords( Keywords& keys ) { // calculator void Cell::calculate() { - for(int i=0; i<3; i++) for(int j=0; j<3; j++) components[i][j]->set(getBox()[i][j]); - for(int l=0; l<3; l++) for(int m=0; m<3; m++) { - Tensor der; for(int i=0; i<3; i++) der[i][m]=getBox()[l][i]; + for(int i=0; i<3; i++) + for(int j=0; j<3; j++) { + components[i][j]->set(getBox()[i][j]); + } + for(int l=0; l<3; l++) + for(int m=0; m<3; m++) { + Tensor der; + for(int i=0; i<3; i++) { + der[i][m]=getBox()[l][i]; + } setBoxDerivatives(components[l][m],-der); } } diff --git a/src/colvar/ColvarShortcut.h b/src/colvar/ColvarShortcut.h index 7ecd14b289..c25e9f61aa 100644 --- a/src/colvar/ColvarShortcut.h +++ b/src/colvar/ColvarShortcut.h @@ -36,22 +36,27 @@ class ColvarShortcut : public ActionShortcut { template void ColvarShortcut::registerKeywords(Keywords& keys ) { - T::registerKeywords( keys ); keys.remove("NO_ACTION_LOG"); + T::registerKeywords( keys ); + keys.remove("NO_ACTION_LOG"); unsigned nkeys = keys.size(); for(unsigned i=0; i ColvarShortcut::ColvarShortcut(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - bool scalar=true; unsigned nkeys = keywords.size(); + ActionShortcut(ao) { + bool scalar=true; + unsigned nkeys = keywords.size(); if( getName()=="MASS" || getName()=="CHARGE" || getName()=="POSITION" ) { - std::string inpt; parse("ATOMS",inpt); + std::string inpt; + parse("ATOMS",inpt); if( inpt.length()>0 ) { readInputLine( getShortcutLabel() + ": " + getName() + "_VECTOR ATOMS=" + inpt + " " + convertInputLineToString() ); scalar=false; @@ -59,14 +64,18 @@ ColvarShortcut::ColvarShortcut(const ActionOptions&ao): } for(unsigned i=0; i0 ) { readInputLine( getShortcutLabel() + ": " + getName() + "_VECTOR " + keywords.get(i) + "1=" + inpt + " " + convertInputLineToString() ); - scalar=false; break; + scalar=false; + break; } } } - if( scalar ) readInputLine( getShortcutLabel() + ": " + getName() + "_SCALAR " + convertInputLineToString() ); + if( scalar ) { + readInputLine( getShortcutLabel() + ": " + getName() + "_SCALAR " + convertInputLineToString() ); + } } } diff --git a/src/colvar/ContactMap.cpp b/src/colvar/ContactMap.cpp index 285554dcb9..2f71032e4d 100644 --- a/src/colvar/ContactMap.cpp +++ b/src/colvar/ContactMap.cpp @@ -147,12 +147,13 @@ ContactMap::ContactMap(const ActionOptions&ao): serial(false), docomp(true), dosum(false), - docmdist(false) -{ + docmdist(false) { parseFlag("SERIAL",serial); parseFlag("SUM",dosum); parseFlag("CMDIST",docmdist); - if(docmdist==true&&dosum==true) error("You cannot use SUM and CMDIST together"); + if(docmdist==true&&dosum==true) { + error("You cannot use SUM and CMDIST together"); + } bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; @@ -161,39 +162,61 @@ ContactMap::ContactMap(const ActionOptions&ao): std::vector t, ga_lista, gb_lista; for(int i=1;; ++i ) { parseAtomList("ATOMS", i, t ); - if( t.empty() ) break; + if( t.empty() ) { + break; + } if( t.size()!=2 ) { - std::string ss; Tools::convert(i,ss); + std::string ss; + Tools::convert(i,ss); error("ATOMS" + ss + " keyword has the wrong number of atoms"); } - ga_lista.push_back(t[0]); gb_lista.push_back(t[1]); + ga_lista.push_back(t[0]); + gb_lista.push_back(t[1]); t.resize(0); // Add a value for this contact - std::string num; Tools::convert(i,num); - if(!dosum&&!docmdist) {addComponentWithDerivatives("contact-"+num); componentIsNotPeriodic("contact-"+num);} + std::string num; + Tools::convert(i,num); + if(!dosum&&!docmdist) { + addComponentWithDerivatives("contact-"+num); + componentIsNotPeriodic("contact-"+num); + } } // Create neighbour lists nl=Tools::make_unique(ga_lista,gb_lista,serial,true,pbc,getPbc(),comm); // Read in switching functions - std::string errors; sfs.resize( ga_lista.size() ); unsigned nswitch=0; + std::string errors; + sfs.resize( ga_lista.size() ); + unsigned nswitch=0; for(unsigned i=0; i0) { switchingFunction.set(sw,errors); - if( errors.length()!=0 ) error("problem reading SWITCH keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading SWITCH keyword : " + errors ); + } } else { int nn=6; int mm=0; double d0=0.0; double r0=0.0; parse("R_0",r0); - if(r0<=0.0) error("R_0 should be explicitly specified and positive"); + if(r0<=0.0) { + error("R_0 should be explicitly specified and positive"); + } parse("D_0",d0); parse("NN",nn); parse("MM",mm); diff --git a/src/colvar/CoordinationBase.cpp b/src/colvar/CoordinationBase.cpp index e7ab51611c..e56c6fbfb0 100644 --- a/src/colvar/CoordinationBase.cpp +++ b/src/colvar/CoordinationBase.cpp @@ -43,8 +43,7 @@ CoordinationBase::CoordinationBase(const ActionOptions&ao): pbc(true), serial(false), invalidateList(true), - firsttime(true) -{ + firsttime(true) { parseFlag("SERIAL",serial); @@ -67,18 +66,29 @@ CoordinationBase::CoordinationBase(const ActionOptions&ao): parseFlag("NLIST",doneigh); if(doneigh) { parse("NL_CUTOFF",nl_cut); - if(nl_cut<=0.0) error("NL_CUTOFF should be explicitly specified and positive"); + if(nl_cut<=0.0) { + error("NL_CUTOFF should be explicitly specified and positive"); + } parse("NL_STRIDE",nl_st); - if(nl_st<=0) error("NL_STRIDE should be explicitly specified and positive"); + if(nl_st<=0) { + error("NL_STRIDE should be explicitly specified and positive"); + } } - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); if(gb_lista.size()>0) { - if(doneigh) nl=Tools::make_unique(ga_lista,gb_lista,serial,dopair,pbc,getPbc(),comm,nl_cut,nl_st); - else nl=Tools::make_unique(ga_lista,gb_lista,serial,dopair,pbc,getPbc(),comm); + if(doneigh) { + nl=Tools::make_unique(ga_lista,gb_lista,serial,dopair,pbc,getPbc(),comm,nl_cut,nl_st); + } else { + nl=Tools::make_unique(ga_lista,gb_lista,serial,dopair,pbc,getPbc(),comm); + } } else { - if(doneigh) nl=Tools::make_unique(ga_lista,serial,pbc,getPbc(),comm,nl_cut,nl_st); - else nl=Tools::make_unique(ga_lista,serial,pbc,getPbc(),comm); + if(doneigh) { + nl=Tools::make_unique(ga_lista,serial,pbc,getPbc(),comm,nl_cut,nl_st); + } else { + nl=Tools::make_unique(ga_lista,serial,pbc,getPbc(),comm); + } } requestAtoms(nl->getFullAtomList()); @@ -86,18 +96,27 @@ CoordinationBase::CoordinationBase(const ActionOptions&ao): log.printf(" between two groups of %u and %u atoms\n",static_cast(ga_lista.size()),static_cast(gb_lista.size())); log.printf(" first group:\n"); for(unsigned int i=0; igetReducedAtomList()); invalidateList=false; - if(getExchangeStep()) error("Neighbor lists should be updated on exchange steps - choose a NL_STRIDE which divides the exchange stride!"); + if(getExchangeStep()) { + error("Neighbor lists should be updated on exchange steps - choose a NL_STRIDE which divides the exchange stride!"); + } + } + if(getExchangeStep()) { + firsttime=true; } - if(getExchangeStep()) firsttime=true; } } // calculator -void CoordinationBase::calculate() -{ +void CoordinationBase::calculate() { double ncoord=0.; Tensor virial; @@ -147,7 +169,9 @@ void CoordinationBase::calculate() unsigned nt=OpenMP::getNumThreads(); const unsigned nn=nl->size(); - if(nt*stride*10>nn) nt=1; + if(nt*stride*10>nn) { + nt=1; + } const unsigned elementsPerRank = std::ceil(double(nn)/stride); const unsigned int start= rank*elementsPerRank; @@ -165,7 +189,9 @@ void CoordinationBase::calculate() const unsigned i0=nl->getClosePair(i).first; const unsigned i1=nl->getClosePair(i).second; - if(getAbsoluteIndex(i0)==getAbsoluteIndex(i1)) continue; + if(getAbsoluteIndex(i0)==getAbsoluteIndex(i1)) { + continue; + } if(pbc) { distance=pbcDistance(getPosition(i0),getPosition(i1)); @@ -191,19 +217,24 @@ void CoordinationBase::calculate() } #pragma omp critical if(nt>1) { - for(unsigned i=0; i0 ) break ; + PDB mypdb; + do_read=mypdb.readFromFilepointer(fp2,false,fake_unit); + if( !do_read && nframes>0 ) { + break ; + } nframes++; } fclose(fp2); // Get cutoff information - double lcut=0; parse("LOWER_CUTOFF",lcut); std::string drmsd_type; parse("TYPE",drmsd_type); - double ucut=std::numeric_limits::max(); parse("UPPER_CUTOFF",ucut); - bool nopbc; parseFlag("NOPBC",nopbc); std::string pbc_str; if(nopbc) pbc_str="NOPBC"; + double lcut=0; + parse("LOWER_CUTOFF",lcut); + std::string drmsd_type; + parse("TYPE",drmsd_type); + double ucut=std::numeric_limits::max(); + parse("UPPER_CUTOFF",ucut); + bool nopbc; + parseFlag("NOPBC",nopbc); + std::string pbc_str; + if(nopbc) { + pbc_str="NOPBC"; + } // Open the pdb file - FILE* fp=fopen(reference.c_str(),"r"); do_read=true; - if(!fp) error("could not open reference file " + reference ); unsigned n=0; std::string allpairs=""; - std::vector > upairs; std::vector refvals; + FILE* fp=fopen(reference.c_str(),"r"); + do_read=true; + if(!fp) { + error("could not open reference file " + reference ); + } + unsigned n=0; + std::string allpairs=""; + std::vector > upairs; + std::vector refvals; while ( do_read ) { - PDB mypdb; do_read=mypdb.readFromFilepointer(fp,false,fake_unit); - if( !do_read && n>0 ) break ; - std::vector pos( mypdb.getPositions() ); unsigned nn=1; - if( pos.size()==0 ) error("read no atoms from file named " + reference ); + PDB mypdb; + do_read=mypdb.readFromFilepointer(fp,false,fake_unit); + if( !do_read && n>0 ) { + break ; + } + std::vector pos( mypdb.getPositions() ); + unsigned nn=1; + if( pos.size()==0 ) { + error("read no atoms from file named " + reference ); + } // This is what we do for the first frame if( n==0 ) { std::vector atoms( mypdb.getAtomNumbers() ); if( drmsd_type=="DRMSD" ) { for(unsigned i=0; i lcut ) { - std::string num; Tools::convert( nn, num ); nn++; + std::string num; + Tools::convert( nn, num ); + nn++; // Add this pair to list of pairs upairs.push_back( std::pair(i,j) ); // Add this distance to list of reference values - std::string dstr; Tools::convert( distance, dstr ); refvals.push_back( dstr ); + std::string dstr; + Tools::convert( distance, dstr ); + refvals.push_back( dstr ); // Calculate this distance - if( nframes==1 ) allpairs += " ATOMS" + num + "=" + istr + "," + jstr; - else readInputLine( getShortcutLabel() + "_d" + num + ": DISTANCE ATOMS=" + istr + "," + jstr + " " + pbc_str ); + if( nframes==1 ) { + allpairs += " ATOMS" + num + "=" + istr + "," + jstr; + } else { + readInputLine( getShortcutLabel() + "_d" + num + ": DISTANCE ATOMS=" + istr + "," + jstr + " " + pbc_str ); + } } } } } else { - unsigned nblocks = mypdb.getNumberOfAtomBlocks(); std::vector blocks( 1 + nblocks ); - if( nblocks==1 ) { blocks[0]=0; blocks[1]=atoms.size(); } - else { blocks[0]=0; for(unsigned i=0; i blocks( 1 + nblocks ); + if( nblocks==1 ) { + blocks[0]=0; + blocks[1]=atoms.size(); + } else { + blocks[0]=0; + for(unsigned i=0; i lcut ) { - std::string num; Tools::convert( nn, num ); nn++; + std::string num; + Tools::convert( nn, num ); + nn++; // Add this pair to list of pairs upairs.push_back( std::pair(iatom,jatom) ); // Add this distance to list of reference values - std::string dstr; Tools::convert( distance, dstr ); refvals.push_back( dstr ); + std::string dstr; + Tools::convert( distance, dstr ); + refvals.push_back( dstr ); // Calculate this distance - if( nframes==1 ) allpairs += " ATOMS" + num + "=" + istr + "," + jstr; - else readInputLine( getShortcutLabel() + "_d" + num + ": DISTANCE ATOMS=" + istr + "," + jstr + " " + pbc_str ); + if( nframes==1 ) { + allpairs += " ATOMS" + num + "=" + istr + "," + jstr; + } else { + readInputLine( getShortcutLabel() + "_d" + num + ": DISTANCE ATOMS=" + istr + "," + jstr + " " + pbc_str ); + } } } } @@ -207,30 +265,42 @@ DRMSD::DRMSD( const ActionOptions& ao ): for(unsigned i=1; i lcut ) { - std::string num; Tools::convert( nn, num ); nn++; + std::string num; + Tools::convert( nn, num ); + nn++; // Add this pair to list of pairs upairs.push_back( std::pair(iatom,jatom) ); // Add this distance to list of reference values - std::string dstr; Tools::convert( distance, dstr ); refvals.push_back( dstr ); + std::string dstr; + Tools::convert( distance, dstr ); + refvals.push_back( dstr ); // Calculate this distance - if( nframes==1 ) allpairs += " ATOMS" + num + "=" + istr + "," + jstr; - else readInputLine( getShortcutLabel() + "_d" + num + ": DISTANCE ATOMS=" + istr + "," + jstr + " " + pbc_str ); + if( nframes==1 ) { + allpairs += " ATOMS" + num + "=" + istr + "," + jstr; + } else { + readInputLine( getShortcutLabel() + "_d" + num + ": DISTANCE ATOMS=" + istr + "," + jstr + " " + pbc_str ); + } } } } } } - } else plumed_merror( drmsd_type + " is not valid input to TYPE keyword"); + } else { + plumed_merror( drmsd_type + " is not valid input to TYPE keyword"); + } } // This is for every subsequent frame } else { for(unsigned i=0; i DihedralCorrelationMulti; PLUMED_REGISTER_ACTION(DihedralCorrelationMulti,"DIHEDRAL_CORRELATION_VECTOR") void DihedralCorrelation::registerKeywords( Keywords& keys ) { - Colvar::registerKeywords( keys ); keys.setDisplayName("DIHEDRAL_CORRELATION"); + Colvar::registerKeywords( keys ); + keys.setDisplayName("DIHEDRAL_CORRELATION"); keys.add("atoms","ATOMS","the set of 8 atoms that are being used to calculate this quantity"); keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); keys.setValueDescription("the DIHEDRAL_CORRELATION for these atoms"); @@ -96,23 +97,30 @@ DihedralCorrelation::DihedralCorrelation(const ActionOptions&ao): pbc(true), value(1), derivs(1), - virial(1) -{ - derivs[0].resize(8); std::vector atoms; + virial(1) { + derivs[0].resize(8); + std::vector atoms; parseAtomList(-1,atoms,this); - if( atoms.size()!=8 ) error("Number of specified atoms should be 8"); + if( atoms.size()!=8 ) { + error("Number of specified atoms should be 8"); + } bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } } void DihedralCorrelation::parseAtomList( const int& num, std::vector& t, ActionAtomistic* aa ) { aa->parseAtomList("ATOMS",num,t); - if( num<0 && t.size()!=8 ) aa->error("Number of specified atoms should be 8"); + if( num<0 && t.size()!=8 ) { + aa->error("Number of specified atoms should be 8"); + } if( t.size()==8 ) { aa->log.printf(" correlation between dihedral angle for atoms %d %d %d %d and atoms %d %d %d %d\n", t[0].serial(),t[1].serial(),t[2].serial(),t[3].serial(),t[4].serial(),t[5].serial(),t[6].serial(),t[7].serial()); @@ -120,15 +128,21 @@ void DihedralCorrelation::parseAtomList( const int& num, std::vector } unsigned DihedralCorrelation::getModeAndSetupValues( ActionWithValue* av ) { - av->addValueWithDerivatives(); av->setNotPeriodic(); return 0; + av->addValueWithDerivatives(); + av->setNotPeriodic(); + return 0; } void DihedralCorrelation::calculate() { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } calculateCV( 0, masses, charges, getPositions(), value, derivs, virial, this ); setValue( value[0] ); - for(unsigned i=0; i derivatives; std::vector my_pos=getPositions(); int atms = my_pos.size(); std::vector der_b2; - for(int i=0; i1) + if(qexp<0.5 || qexp>1) { warning("Dimer CV is meant to be used with q-exponents between 0.5 and 1. We are not responsible for any black hole. :-)"); + } - if(dsigma<0) + if(dsigma<0) { error("Please use positive sigma values for the Dimer strength constant"); + } - if(temperature<0) + if(temperature<0) { error("Please, use a positive value for the temperature..."); + } // if dsigmas has only one element means that either // you are using different plumed.x.dat files or a plumed.dat with a single replica - if(dsigmas.size()!=nranks && dsigmas.size()!=1) + if(dsigmas.size()!=nranks && dsigmas.size()!=1) { error("Mismatch between provided sigmas and number of replicas"); + } } diff --git a/src/colvar/Dipole.cpp b/src/colvar/Dipole.cpp index e0a9212455..37c1bba561 100644 --- a/src/colvar/Dipole.cpp +++ b/src/colvar/Dipole.cpp @@ -106,7 +106,8 @@ typedef MultiColvarTemplate DipoleMulti; PLUMED_REGISTER_ACTION(DipoleMulti,"DIPOLE_VECTOR") void Dipole::registerKeywords(Keywords& keys) { - Colvar::registerKeywords(keys); keys.setDisplayName("DIPOLE"); + Colvar::registerKeywords(keys); + keys.setDisplayName("DIPOLE"); keys.add("atoms","GROUP","the group of atoms we are calculating the dipole moment for"); keys.addFlag("COMPONENTS",false,"calculate the x, y and z components of the dipole separately and store them as label.x, label.y and label.z"); keys.addOutputComponent("x","COMPONENTS","the x-component of the dipole"); @@ -121,22 +122,29 @@ Dipole::Dipole(const ActionOptions&ao): components(false), value(1), derivs(1), - virial(1) -{ - parseAtomList(-1,ga_lista,this); charges.resize(ga_lista.size()); + virial(1) { + parseAtomList(-1,ga_lista,this); + charges.resize(ga_lista.size()); components=(getModeAndSetupValues(this)==1); if( components ) { - value.resize(3); derivs.resize(3); virial.resize(3); + value.resize(3); + derivs.resize(3); + virial.resize(3); valuex=getPntrToComponent("x"); valuey=getPntrToComponent("y"); valuez=getPntrToComponent("z"); } - for(unsigned i=0; i& t, ActionAt } unsigned Dipole::getModeAndSetupValues( ActionWithValue* av ) { - bool c; av->parseFlag("COMPONENTS",c); + bool c; + av->parseFlag("COMPONENTS",c); if( c ) { - av->addComponentWithDerivatives("x"); av->componentIsNotPeriodic("x"); - av->addComponentWithDerivatives("y"); av->componentIsNotPeriodic("y"); - av->addComponentWithDerivatives("z"); av->componentIsNotPeriodic("z"); + av->addComponentWithDerivatives("x"); + av->componentIsNotPeriodic("x"); + av->addComponentWithDerivatives("y"); + av->componentIsNotPeriodic("y"); + av->addComponentWithDerivatives("z"); + av->componentIsNotPeriodic("z"); return 1; } - av->addValueWithDerivatives(); av->setNotPeriodic(); return 0; + av->addValueWithDerivatives(); + av->setNotPeriodic(); + return 0; } // calculator -void Dipole::calculate() -{ - if(!nopbc) makeWhole(); +void Dipole::calculate() { + if(!nopbc) { + makeWhole(); + } unsigned N=getNumberOfAtoms(); - for(unsigned i=0; i& masses, std::vector& charges, const std::vector& pos, std::vector& vals, std::vector >& derivs, std::vector& virial, const ActionAtomistic* aa ) { - unsigned N=pos.size(); double ctot=0.; - for(unsigned i=0; i& masse derivs[1][i]=charges[i]*Vector(0.0,1.0,0.0); derivs[2][i]=charges[i]*Vector(0.0,0.0,1.0); } - for(unsigned i=0; i<3; ++i ) vals[i] = dipje[i]; + for(unsigned i=0; i<3; ++i ) { + vals[i] = dipje[i]; + } } else { vals[0] = dipje.modulo(); double idip = 1./vals[0]; diff --git a/src/colvar/Distance.cpp b/src/colvar/Distance.cpp index b2d75a27fe..c0e1050581 100644 --- a/src/colvar/Distance.cpp +++ b/src/colvar/Distance.cpp @@ -150,7 +150,8 @@ typedef MultiColvarTemplate DistanceMulti; PLUMED_REGISTER_ACTION(DistanceMulti,"DISTANCE_VECTOR") void Distance::registerKeywords( Keywords& keys ) { - Colvar::registerKeywords( keys ); keys.setDisplayName("DISTANCE"); + Colvar::registerKeywords( keys ); + keys.setDisplayName("DISTANCE"); keys.add("atoms","ATOMS","the pair of atom that we are calculating the distance between"); keys.addFlag("COMPONENTS",false,"calculate the x, y and z components of the distance separately and store them as label.x, label.y and label.z"); keys.addFlag("SCALED_COMPONENTS",false,"calculate the a, b and c scaled components of the distance separately and store them as label.a, label.b and label.c"); @@ -171,60 +172,86 @@ Distance::Distance(const ActionOptions&ao): pbc(true), value(1), derivs(1), - virial(1) -{ + virial(1) { derivs[0].resize(2); std::vector atoms; parseAtomList(-1,atoms,this); - if(atoms.size()!=2) + if(atoms.size()!=2) { error("Number of specified atoms should be 2"); + } bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } unsigned mode = getModeAndSetupValues( this ); - if(mode==1) components=true; else if(mode==2) scaled_components=true; + if(mode==1) { + components=true; + } else if(mode==2) { + scaled_components=true; + } if( components || scaled_components ) { - value.resize(3); derivs.resize(3); virial.resize(3); - for(unsigned i=0; i<3; ++i) derivs[i].resize(2); + value.resize(3); + derivs.resize(3); + virial.resize(3); + for(unsigned i=0; i<3; ++i) { + derivs[i].resize(2); + } } requestAtoms(atoms); } void Distance::parseAtomList( const int& num, std::vector& t, ActionAtomistic* aa ) { aa->parseAtomList("ATOMS",num,t); - if( t.size()==2 ) aa->log.printf(" between atoms %d %d\n",t[0].serial(),t[1].serial()); + if( t.size()==2 ) { + aa->log.printf(" between atoms %d %d\n",t[0].serial(),t[1].serial()); + } } unsigned Distance::getModeAndSetupValues( ActionWithValue* av ) { - bool c; av->parseFlag("COMPONENTS",c); - bool sc; av->parseFlag("SCALED_COMPONENTS",sc); - if( c && sc ) av->error("COMPONENTS and SCALED_COMPONENTS are not compatible"); + bool c; + av->parseFlag("COMPONENTS",c); + bool sc; + av->parseFlag("SCALED_COMPONENTS",sc); + if( c && sc ) { + av->error("COMPONENTS and SCALED_COMPONENTS are not compatible"); + } if(c) { - av->addComponentWithDerivatives("x"); av->componentIsNotPeriodic("x"); - av->addComponentWithDerivatives("y"); av->componentIsNotPeriodic("y"); - av->addComponentWithDerivatives("z"); av->componentIsNotPeriodic("z"); + av->addComponentWithDerivatives("x"); + av->componentIsNotPeriodic("x"); + av->addComponentWithDerivatives("y"); + av->componentIsNotPeriodic("y"); + av->addComponentWithDerivatives("z"); + av->componentIsNotPeriodic("z"); av->log<<" WARNING: components will not have the proper periodicity - see manual\n"; return 1; } else if(sc) { - av->addComponentWithDerivatives("a"); av->componentIsPeriodic("a","-0.5","+0.5"); - av->addComponentWithDerivatives("b"); av->componentIsPeriodic("b","-0.5","+0.5"); - av->addComponentWithDerivatives("c"); av->componentIsPeriodic("c","-0.5","+0.5"); + av->addComponentWithDerivatives("a"); + av->componentIsPeriodic("a","-0.5","+0.5"); + av->addComponentWithDerivatives("b"); + av->componentIsPeriodic("b","-0.5","+0.5"); + av->addComponentWithDerivatives("c"); + av->componentIsPeriodic("c","-0.5","+0.5"); return 2; } - av->addValueWithDerivatives(); av->setNotPeriodic(); + av->addValueWithDerivatives(); + av->setNotPeriodic(); return 0; } // calculator void Distance::calculate() { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } if( components ) { calculateCV( 1, masses, charges, getPositions(), value, derivs, virial, this ); @@ -232,15 +259,21 @@ void Distance::calculate() { Value* valuey=getPntrToComponent("y"); Value* valuez=getPntrToComponent("z"); - for(unsigned i=0; i<2; ++i) setAtomsDerivatives(valuex,i,derivs[0][i] ); + for(unsigned i=0; i<2; ++i) { + setAtomsDerivatives(valuex,i,derivs[0][i] ); + } setBoxDerivatives(valuex,virial[0]); valuex->set(value[0]); - for(unsigned i=0; i<2; ++i) setAtomsDerivatives(valuey,i,derivs[1][i] ); + for(unsigned i=0; i<2; ++i) { + setAtomsDerivatives(valuey,i,derivs[1][i] ); + } setBoxDerivatives(valuey,virial[1]); valuey->set(value[1]); - for(unsigned i=0; i<2; ++i) setAtomsDerivatives(valuez,i,derivs[2][i] ); + for(unsigned i=0; i<2; ++i) { + setAtomsDerivatives(valuez,i,derivs[2][i] ); + } setBoxDerivatives(valuez,virial[2]); valuez->set(value[2]); } else if( scaled_components ) { @@ -249,15 +282,23 @@ void Distance::calculate() { Value* valuea=getPntrToComponent("a"); Value* valueb=getPntrToComponent("b"); Value* valuec=getPntrToComponent("c"); - for(unsigned i=0; i<2; ++i) setAtomsDerivatives(valuea,i,derivs[0][i] ); + for(unsigned i=0; i<2; ++i) { + setAtomsDerivatives(valuea,i,derivs[0][i] ); + } valuea->set(value[0]); - for(unsigned i=0; i<2; ++i) setAtomsDerivatives(valueb,i,derivs[1][i] ); + for(unsigned i=0; i<2; ++i) { + setAtomsDerivatives(valueb,i,derivs[1][i] ); + } valueb->set(value[1]); - for(unsigned i=0; i<2; ++i) setAtomsDerivatives(valuec,i,derivs[2][i] ); + for(unsigned i=0; i<2; ++i) { + setAtomsDerivatives(valuec,i,derivs[2][i] ); + } valuec->set(value[2]); } else { calculateCV( 0, masses, charges, getPositions(), value, derivs, virial, this ); - for(unsigned i=0; i<2; ++i) setAtomsDerivatives(i,derivs[0][i] ); + for(unsigned i=0; i<2; ++i) { + setAtomsDerivatives(i,derivs[0][i] ); + } setBoxDerivatives(virial[0]); setValue (value[0]); } diff --git a/src/colvar/EEFSolv.cpp b/src/colvar/EEFSolv.cpp index 5d460ad977..08eeaa8e64 100644 --- a/src/colvar/EEFSolv.cpp +++ b/src/colvar/EEFSolv.cpp @@ -119,8 +119,7 @@ EEFSolv::EEFSolv(const ActionOptions&ao): delta_g_ref(0.), nl_buffer(0.1), nl_stride(40), - nl_update(0) -{ + nl_update(0) { std::vector atoms; parseAtomList("ATOMS", atoms); const unsigned size = atoms.size(); @@ -137,7 +136,8 @@ EEFSolv::EEFSolv(const ActionOptions&ao): checkRead(); - log << " Bibliography " << plumed.cite("Lazaridis T, Karplus M, Proteins Struct. Funct. Genet. 35, 133 (1999)"); log << "\n"; + log << " Bibliography " << plumed.cite("Lazaridis T, Karplus M, Proteins Struct. Funct. Genet. 35, 133 (1999)"); + log << "\n"; nl.resize(size); nlexpo.resize(size); @@ -159,7 +159,9 @@ void EEFSolv::update_neighb() { const Vector posi = getPosition(i); // Loop through neighboring atoms, add the ones below cutoff for (unsigned j=i+1; j mlambda) mlambda = 1./parameter[j][2]; + if (1./parameter[j][2] > mlambda) { + mlambda = 1./parameter[j][2]; + } const double c2 = (2. * mlambda + nl_buffer) * (2. * mlambda + nl_buffer); if (d2 < c2 ) { nl[i].push_back(j); if(parameter[i][2] == parameter[j][2] && parameter[i][3] == parameter[j][3]) { nlexpo[i].push_back(true); - } else nlexpo[i].push_back(false); + } else { + nlexpo[i].push_back(false); + } } } } } void EEFSolv::calculate() { - if(pbc) makeWhole(); - if(getExchangeStep()) nl_update = 0; - if(nl_update==0) update_neighb(); + if(pbc) { + makeWhole(); + } + if(getExchangeStep()) { + nl_update = 0; + } + if(nl_update==0) { + update_neighb(); + } const unsigned size=getNumberOfAtoms(); double bias = 0.0; @@ -200,7 +212,9 @@ void EEFSolv::calculate() { } unsigned nt=OpenMP::getNumThreads(); - if(nt*stride*10>size) nt=1; + if(nt*stride*10>size) { + nt=1; + } #pragma omp parallel num_threads(nt) { @@ -233,8 +247,7 @@ void EEFSolv::calculate() { // in this case we can calculate a single exponential if(!nlexpo[i][i_nl]) { // i-j interaction - if(inv_rij > 0.5*inv_lambda_i && delta_g_free_i!=0.) - { + if(inv_rij > 0.5*inv_lambda_i && delta_g_free_i!=0.) { const double e_arg = (rij - vdw_radius_i)*inv_lambda_i; const double expo = std::exp(-e_arg*e_arg); const double fact = expo*fact_ij; @@ -242,13 +255,15 @@ void EEFSolv::calculate() { const Vector dd = e_deriv*dist; fedensity += fact; deriv_i += dd; - if(nt>1) deriv_omp[j] -= dd; - else deriv[j] -= dd; + if(nt>1) { + deriv_omp[j] -= dd; + } else { + deriv[j] -= dd; + } } // j-i interaction - if(inv_rij > 0.5*inv_lambda_j && delta_g_free_j!=0.) - { + if(inv_rij > 0.5*inv_lambda_j && delta_g_free_j!=0.) { const double e_arg = (rij - vdw_radius_j)*inv_lambda_j; const double expo = std::exp(-e_arg*e_arg); const double fact = expo*fact_ji; @@ -256,13 +271,15 @@ void EEFSolv::calculate() { const Vector dd = e_deriv*dist; fedensity += fact; deriv_i += dd; - if(nt>1) deriv_omp[j] -= dd; - else deriv[j] -= dd; + if(nt>1) { + deriv_omp[j] -= dd; + } else { + deriv[j] -= dd; + } } } else { // i-j interaction - if(inv_rij > 0.5*inv_lambda_i) - { + if(inv_rij > 0.5*inv_lambda_i) { const double e_arg = (rij - vdw_radius_i)*inv_lambda_i; const double expo = std::exp(-e_arg*e_arg); const double fact = expo*(fact_ij + fact_ji); @@ -270,23 +287,34 @@ void EEFSolv::calculate() { const Vector dd = e_deriv*dist; fedensity += fact; deriv_i += dd; - if(nt>1) deriv_omp[j] -= dd; - else deriv[j] -= dd; + if(nt>1) { + deriv_omp[j] -= dd; + } else { + deriv[j] -= dd; + } } } } - if(nt>1) deriv_omp[i] += deriv_i; - else deriv[i] += deriv_i; + if(nt>1) { + deriv_omp[i] += deriv_i; + } else { + deriv[i] += deriv_i; + } bias += 0.5*fedensity; } #pragma omp critical - if(nt>1) for(unsigned i=0; i1) + for(unsigned i=0; i &atoms, std::vector > EEFSolv::setupTypeMap() { diff --git a/src/colvar/ERMSD.cpp b/src/colvar/ERMSD.cpp index b5027ea0a3..dc08786821 100644 --- a/src/colvar/ERMSD.cpp +++ b/src/colvar/ERMSD.cpp @@ -125,8 +125,7 @@ void ERMSD::registerKeywords(Keywords& keys) { } ERMSD::ERMSD(const ActionOptions&ao): - PLUMED_COLVAR_INIT(ao), pbc(true) -{ + PLUMED_COLVAR_INIT(ao), pbc(true) { std::string reference; parse("REFERENCE",reference); double cutoff=2.4; @@ -144,11 +143,18 @@ ERMSD::ERMSD(const ActionOptions&ao): parseVector("PAIRS",pairs_); checkRead(); - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); - if(atoms_.size()<6) error("at least six atoms should be specified"); - if(atoms_.size()%3!=0) error("Atoms are not multiple of 3"); - if(pairs_.size()%2!=0) error("pairs are not multiple of 2"); + if(atoms_.size()<6) { + error("at least six atoms should be specified"); + } + if(atoms_.size()%3!=0) { + error("Atoms are not multiple of 3"); + } + if(pairs_.size()%2!=0) { + error("pairs are not multiple of 2"); + } //checkRead(); @@ -158,8 +164,9 @@ ERMSD::ERMSD(const ActionOptions&ao): // read everything in ang and transform to nm if we are not in natural units PDB pdb; - if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) + if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) { error("missing input file " + reference ); + } // store target_ distance std::vector reference_positions; unsigned natoms = atoms_.size(); @@ -172,7 +179,9 @@ ERMSD::ERMSD(const ActionOptions&ao): } // shift to count from zero - for(unsigned i=0; i shape; - addValue( shape ); setNotPeriodic(); setUnit( "energy", "default" ); + interface(NULL) { + plumed.setEnergyValue( getLabel() ); + std::vector shape; + addValue( shape ); + setNotPeriodic(); + setUnit( "energy", "default" ); ActionToPutData* px=plumed.getActionSet().selectWithLabel< ActionToPutData*>("posx"); - plumed_assert(px); forces_to_scale.push_back(px); addDependency( px ); + plumed_assert(px); + forces_to_scale.push_back(px); + addDependency( px ); ActionToPutData* py=plumed.getActionSet().selectWithLabel< ActionToPutData*>("posy"); - plumed_assert(py); forces_to_scale.push_back(py); addDependency( py ); + plumed_assert(py); + forces_to_scale.push_back(py); + addDependency( py ); ActionToPutData* pz=plumed.getActionSet().selectWithLabel< ActionToPutData*>("posz"); - plumed_assert(pz); forces_to_scale.push_back(pz); addDependency( pz ); + plumed_assert(pz); + forces_to_scale.push_back(pz); + addDependency( pz ); ActionToPutData* bx=plumed.getActionSet().selectWithLabel< ActionToPutData*>("Box"); - plumed_assert(bx); forces_to_scale.push_back(bx); addDependency( bx ); + plumed_assert(bx); + forces_to_scale.push_back(bx); + addDependency( bx ); log<<" Bibliography "; log< allput=plumed.getActionSet().select(); - if( allput.size()>1 ) warning("found more than one interface so don't know how to sum energy"); + if( allput.size()>1 ) { + warning("found more than one interface so don't know how to sum energy"); + } interface = allput[0]; } - ActionToPutData::wait(); if( interface ) interface->sumOverDomains( copyOutput(0) ); + ActionToPutData::wait(); + if( interface ) { + interface->sumOverDomains( copyOutput(0) ); + } } void Energy::apply() { if( getPntrToValue()->forcesWereAdded() ) { - for(unsigned i=0; irescaleForces( 1.- getPntrToValue()->getForce(0)); + for(unsigned i=0; irescaleForces( 1.- getPntrToValue()->getForce(0)); + } } } diff --git a/src/colvar/ExtraCV.cpp b/src/colvar/ExtraCV.cpp index 5360a0201b..ab29eb6da1 100644 --- a/src/colvar/ExtraCV.cpp +++ b/src/colvar/ExtraCV.cpp @@ -59,18 +59,21 @@ PLUMED_REGISTER_ACTION(ExtraCV,"EXTRACV") ExtraCV::ExtraCV(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - std::vector argn(1); parse("NAME",argn[0]); + ActionShortcut(ao) { + std::vector argn(1); + parse("NAME",argn[0]); readInputLine( argn[0] + ": PUT UNIT=number SHAPE=0 MUTABLE PERIODIC=NO"); - if( getShortcutLabel()!=argn[0] ) readInputLine( getShortcutLabel() + ": COMBINE ARG=" + argn[0] + " PERIODIC=NO"); + if( getShortcutLabel()!=argn[0] ) { + readInputLine( getShortcutLabel() + ": COMBINE ARG=" + argn[0] + " PERIODIC=NO"); + } } void ExtraCV::registerKeywords( Keywords& keys ) { ActionShortcut::registerKeywords( keys ); keys.add("compulsory","NAME","name of the CV as computed by the MD engine"); keys.setValueDescription("the value of the CV that was passed from the MD code to PLUMED"); - keys.needsAction("PUT"); keys.needsAction("COMBINE"); + keys.needsAction("PUT"); + keys.needsAction("COMBINE"); } } diff --git a/src/colvar/Fake.cpp b/src/colvar/Fake.cpp index a799f2987f..cb1ccd3b4f 100644 --- a/src/colvar/Fake.cpp +++ b/src/colvar/Fake.cpp @@ -43,7 +43,9 @@ class ColvarFake : public Colvar { public: static void registerKeywords( Keywords& keys ); explicit ColvarFake(const ActionOptions&); - std::string getOutputComponentDescription( const std::string& cname, const Keywords& keys ) const override { plumed_error(); } + std::string getOutputComponentDescription( const std::string& cname, const Keywords& keys ) const override { + plumed_error(); + } // active methods: void calculate() override; }; @@ -60,8 +62,7 @@ void ColvarFake::registerKeywords( Keywords& keys ) { } ColvarFake::ColvarFake(const ActionOptions&ao): - PLUMED_COLVAR_INIT(ao) -{ + PLUMED_COLVAR_INIT(ao) { std::vector atoms; parseAtomList("ATOMS",atoms); diff --git a/src/colvar/GHBFIX.cpp b/src/colvar/GHBFIX.cpp index c21acf9af1..499813ecee 100644 --- a/src/colvar/GHBFIX.cpp +++ b/src/colvar/GHBFIX.cpp @@ -97,8 +97,7 @@ void GHBFIX::registerKeywords( Keywords& keys ) { GHBFIX::GHBFIX(const ActionOptions&ao): Action(ao), - CoordinationBase(ao) -{ + CoordinationBase(ao) { std::string types; std::string params; std::string energy_units ="plumed" ; @@ -130,8 +129,7 @@ GHBFIX::GHBFIX(const ActionOptions&ao): if (MapTypesTable.empty()) { MapTypesTable.insert({itype, 0}); - } - else if (MapTypesTable.count(itype) == 0) { + } else if (MapTypesTable.count(itype) == 0) { unsigned currentMax = 0; for(auto it = MapTypesTable.cbegin(); it != MapTypesTable.cend(); ++it ) { if (it ->second > currentMax) { @@ -162,7 +160,9 @@ GHBFIX::GHBFIX(const ActionOptions&ao): if(energy_units!="plumed") { Units units; units.setEnergy(energy_units); - for(auto i=0; i atoms; parseAtomList("ATOMS",atoms); - if(atoms.size()==0) error("no atoms specified"); + if(atoms.size()==0) { + error("no atoms specified"); + } parseFlag("MASS_WEIGHTED",use_masses); std::string Type; parse("TYPE",Type); parseFlag("NOPBC",nopbc); checkRead(); - if(Type=="RADIUS") rg_type=RADIUS; - else if(Type=="TRACE") rg_type=TRACE; - else if(Type=="GTPC_1") rg_type=GTPC_1; - else if(Type=="GTPC_2") rg_type=GTPC_2; - else if(Type=="GTPC_3") rg_type=GTPC_3; - else if(Type=="ASPHERICITY") rg_type=ASPHERICITY; - else if(Type=="ACYLINDRICITY") rg_type=ACYLINDRICITY; - else if(Type=="KAPPA2") rg_type=KAPPA2; - else if(Type=="RGYR_3") rg_type=GYRATION_3; - else if(Type=="RGYR_2") rg_type=GYRATION_2; - else if(Type=="RGYR_1") rg_type=GYRATION_1; - else error("Unknown GYRATION type"); - - switch(rg_type) - { - case RADIUS: log.printf(" GYRATION RADIUS (Rg);"); break; - case TRACE: log.printf(" TRACE OF THE GYRATION TENSOR;"); break; - case GTPC_1: log.printf(" THE LARGEST PRINCIPAL MOMENT OF THE GYRATION TENSOR (S'_1);"); break; - case GTPC_2: log.printf(" THE MIDDLE PRINCIPAL MOMENT OF THE GYRATION TENSOR (S'_2);"); break; - case GTPC_3: log.printf(" THE SMALLEST PRINCIPAL MOMENT OF THE GYRATION TENSOR (S'_3);"); break; - case ASPHERICITY: log.printf(" THE ASPHERICITY (b');"); break; - case ACYLINDRICITY: log.printf(" THE ACYLINDRICITY (c');"); break; - case KAPPA2: log.printf(" THE RELATIVE SHAPE ANISOTROPY (kappa^2);"); break; - case GYRATION_3: log.printf(" THE SMALLEST PRINCIPAL RADIUS OF GYRATION (r_g3);"); break; - case GYRATION_2: log.printf(" THE MIDDLE PRINCIPAL RADIUS OF GYRATION (r_g2);"); break; - case GYRATION_1: log.printf(" THE LARGEST PRINCIPAL RADIUS OF GYRATION (r_g1);"); break; + if(Type=="RADIUS") { + rg_type=RADIUS; + } else if(Type=="TRACE") { + rg_type=TRACE; + } else if(Type=="GTPC_1") { + rg_type=GTPC_1; + } else if(Type=="GTPC_2") { + rg_type=GTPC_2; + } else if(Type=="GTPC_3") { + rg_type=GTPC_3; + } else if(Type=="ASPHERICITY") { + rg_type=ASPHERICITY; + } else if(Type=="ACYLINDRICITY") { + rg_type=ACYLINDRICITY; + } else if(Type=="KAPPA2") { + rg_type=KAPPA2; + } else if(Type=="RGYR_3") { + rg_type=GYRATION_3; + } else if(Type=="RGYR_2") { + rg_type=GYRATION_2; + } else if(Type=="RGYR_1") { + rg_type=GYRATION_1; + } else { + error("Unknown GYRATION type"); + } + + switch(rg_type) { + case RADIUS: + log.printf(" GYRATION RADIUS (Rg);"); + break; + case TRACE: + log.printf(" TRACE OF THE GYRATION TENSOR;"); + break; + case GTPC_1: + log.printf(" THE LARGEST PRINCIPAL MOMENT OF THE GYRATION TENSOR (S'_1);"); + break; + case GTPC_2: + log.printf(" THE MIDDLE PRINCIPAL MOMENT OF THE GYRATION TENSOR (S'_2);"); + break; + case GTPC_3: + log.printf(" THE SMALLEST PRINCIPAL MOMENT OF THE GYRATION TENSOR (S'_3);"); + break; + case ASPHERICITY: + log.printf(" THE ASPHERICITY (b');"); + break; + case ACYLINDRICITY: + log.printf(" THE ACYLINDRICITY (c');"); + break; + case KAPPA2: + log.printf(" THE RELATIVE SHAPE ANISOTROPY (kappa^2);"); + break; + case GYRATION_3: + log.printf(" THE SMALLEST PRINCIPAL RADIUS OF GYRATION (r_g3);"); + break; + case GYRATION_2: + log.printf(" THE MIDDLE PRINCIPAL RADIUS OF GYRATION (r_g2);"); + break; + case GYRATION_1: + log.printf(" THE LARGEST PRINCIPAL RADIUS OF GYRATION (r_g1);"); + break; + } + if(rg_type>TRACE) { + log<<" Bibliography "<TRACE) log<<" Bibliography "<0.0001) error("Plumed Error: Cannot diagonalize gyration tensor\n"); + if(std::abs(det-1.)>0.0001) { + error("Plumed Error: Cannot diagonalize gyration tensor\n"); + } switch(rg_type) { case GTPC_1: case GTPC_2: - case GTPC_3: - { + case GTPC_3: { int pc_index = rg_type-2; //index of principal component rgyr=std::sqrt(princ_comp[pc_index]/totmass); double rm = rgyr*totmass; - if(rm>1e-6) prefactor[pc_index]=1.0/rm; //some parts of derivate + if(rm>1e-6) { + prefactor[pc_index]=1.0/rm; //some parts of derivate + } break; } - case GYRATION_3: //the smallest principal radius of gyration - { + case GYRATION_3: { //the smallest principal radius of gyration rgyr=std::sqrt((princ_comp[1]+princ_comp[2])/totmass); double rm = rgyr*totmass; if (rm>1e-6) { @@ -284,8 +351,7 @@ void Gyration::calculate() { } break; } - case GYRATION_2: //the midle principal radius of gyration - { + case GYRATION_2: { //the midle principal radius of gyration rgyr=std::sqrt((princ_comp[0]+princ_comp[2])/totmass); double rm = rgyr*totmass; if (rm>1e-6) { @@ -294,8 +360,7 @@ void Gyration::calculate() { } break; } - case GYRATION_1: //the largest principal radius of gyration - { + case GYRATION_1: { //the largest principal radius of gyration rgyr=std::sqrt((princ_comp[0]+princ_comp[1])/totmass); double rm = rgyr*totmass; if (rm>1e-6) { @@ -304,8 +369,7 @@ void Gyration::calculate() { } break; } - case ASPHERICITY: - { + case ASPHERICITY: { rgyr=std::sqrt((princ_comp[0]-0.5*(princ_comp[1]+princ_comp[2]))/totmass); double rm = rgyr*totmass; if (rm>1e-6) { @@ -315,8 +379,7 @@ void Gyration::calculate() { } break; } - case ACYLINDRICITY: - { + case ACYLINDRICITY: { rgyr=std::sqrt((princ_comp[1]-princ_comp[2])/totmass); double rm = rgyr*totmass; if (rm>1e-6) { //avoid division by zero @@ -325,8 +388,7 @@ void Gyration::calculate() { } break; } - case KAPPA2: // relative shape anisotropy - { + case KAPPA2: { // relative shape anisotropy double trace = princ_comp[0]+princ_comp[1]+princ_comp[2]; double tmp=princ_comp[0]*princ_comp[1]+ princ_comp[1]*princ_comp[2]+ princ_comp[0]*princ_comp[2]; rgyr=1.0-3*(tmp/(trace*trace)); @@ -344,10 +406,13 @@ void Gyration::calculate() { Vector tX; const Vector diff=delta( com,getPosition(i) ); //project atomic postional vectors to diagonalized frame - for(unsigned j=0; j<3; j++) tX[j]=transf[0][j]*diff[0]+transf[1][j]*diff[1]+transf[2][j]*diff[2]; - for(unsigned j=0; j<3; j++) derivatives[i][j]=getMass(i)*(prefactor[0]*transf[j][0]*tX[0]+ - prefactor[1]*transf[j][1]*tX[1]+ - prefactor[2]*transf[j][2]*tX[2]); + for(unsigned j=0; j<3; j++) { + tX[j]=transf[0][j]*diff[0]+transf[1][j]*diff[1]+transf[2][j]*diff[2]; + } + for(unsigned j=0; j<3; j++) + derivatives[i][j]=getMass(i)*(prefactor[0]*transf[j][0]*tX[0]+ + prefactor[1]*transf[j][1]*tX[1]+ + prefactor[2]*transf[j][2]*tX[2]); setAtomsDerivatives(i,derivatives[i]); } } else { @@ -355,10 +420,13 @@ void Gyration::calculate() { Vector tX; const Vector diff=delta( com,getPosition(i) ); //project atomic postional vectors to diagonalized frame - for(unsigned j=0; j<3; j++) tX[j]=transf[0][j]*diff[0]+transf[1][j]*diff[1]+transf[2][j]*diff[2]; - for(unsigned j=0; j<3; j++) derivatives[i][j]=prefactor[0]*transf[j][0]*tX[0]+ - prefactor[1]*transf[j][1]*tX[1]+ - prefactor[2]*transf[j][2]*tX[2]; + for(unsigned j=0; j<3; j++) { + tX[j]=transf[0][j]*diff[0]+transf[1][j]*diff[1]+transf[2][j]*diff[2]; + } + for(unsigned j=0; j<3; j++) + derivatives[i][j]=prefactor[0]*transf[j][0]*tX[0]+ + prefactor[1]*transf[j][1]*tX[1]+ + prefactor[2]*transf[j][2]*tX[2]; setAtomsDerivatives(i,derivatives[i]); } } diff --git a/src/colvar/GyrationShortcut.cpp b/src/colvar/GyrationShortcut.cpp index de87555798..0831bda7ef 100644 --- a/src/colvar/GyrationShortcut.cpp +++ b/src/colvar/GyrationShortcut.cpp @@ -67,70 +67,124 @@ void GyrationShortcut::registerKeywords( Keywords& keys ) { keys.addFlag("MASS_WEIGHTED",false,"set the masses of all the atoms equal to one"); keys.addFlag("UNORMALIZED",false,"do not divide by the sum of the weights"); keys.setValueDescription("the radius that was computed from the weights"); - keys.addActionNameSuffix("_FAST"); keys.needsAction("CENTER"); keys.needsAction("CONSTANT"); - keys.needsAction("ONES"); keys.needsAction("MASS"); keys.needsAction("DISTANCE"); - keys.needsAction("COVARIANCE_MATRIX"); keys.needsAction("SELECT_COMPONENTS"); - keys.needsAction("SUM"); keys.needsAction("CUSTOM"); keys.needsAction("DIAGONALIZE"); + keys.addActionNameSuffix("_FAST"); + keys.needsAction("CENTER"); + keys.needsAction("CONSTANT"); + keys.needsAction("ONES"); + keys.needsAction("MASS"); + keys.needsAction("DISTANCE"); + keys.needsAction("COVARIANCE_MATRIX"); + keys.needsAction("SELECT_COMPONENTS"); + keys.needsAction("SUM"); + keys.needsAction("CUSTOM"); + keys.needsAction("DIAGONALIZE"); } GyrationShortcut::GyrationShortcut(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - bool usemass, phases; parseFlag("MASS",usemass); parseFlag("PHASES",phases); - std::vector str_weights; parseVector("WEIGHTS",str_weights); std::string wflab; + ActionShortcut(ao) { + bool usemass, phases; + parseFlag("MASS",usemass); + parseFlag("PHASES",phases); + std::vector str_weights; + parseVector("WEIGHTS",str_weights); + std::string wflab; if( !phases ) { if( usemass || str_weights.size()==0 || (str_weights.size()==1 && str_weights[0]=="@Masses") ) { std::string wt_str; if( str_weights.size()>0 ) { - wt_str="WEIGHTS=" + str_weights[0]; for(unsigned i=1; i atoms; parseVector("ATOMS",atoms); Tools::interpretRanges(atoms); - std::string gtype, atlist=atoms[0]; for(unsigned i=1; i atoms; + parseVector("ATOMS",atoms); + Tools::interpretRanges(atoms); + std::string gtype, atlist=atoms[0]; + for(unsigned i=1; i( wflab ); - if( !av ) { wflab = str_weights[0]; } + if( !av ) { + wflab = str_weights[0]; + } } // Check for normalisation - bool unorm; parseFlag("UNORMALIZED",unorm); + bool unorm; + parseFlag("UNORMALIZED",unorm); // Find out the type if( getName()!="GYRATION_TENSOR" ) { parse("TYPE",gtype); if( gtype!="RADIUS" && gtype!="TRACE" && gtype!="GTPC_1" && gtype!="GTPC_2" && gtype!="GTPC_3" && gtype!="ASPHERICITY" && gtype!="ACYLINDRICITY" - && gtype!= "KAPPA2" && gtype!="RGYR_1" && gtype!="RGYR_2" && gtype!="RGYR_3" ) error("type " + gtype + " is invalid"); + && gtype!= "KAPPA2" && gtype!="RGYR_1" && gtype!="RGYR_2" && gtype!="RGYR_3" ) { + error("type " + gtype + " is invalid"); + } // Check if we need to calculate the unormlised radius - if( gtype=="TRACE" || gtype=="KAPPA2" ) unorm=true; + if( gtype=="TRACE" || gtype=="KAPPA2" ) { + unorm=true; + } } // Compute all the vectors separating all the positions from the center std::string distance_act = getShortcutLabel() + "_dists: DISTANCE COMPONENTS" + pbcstr; - for(unsigned i=0; i::registerKeywords(Keywords& keys ) { T::registerKeywords( keys ); unsigned nkeys = keys.size(); for(unsigned i=0; i @@ -65,42 +69,60 @@ MultiColvarTemplate::MultiColvarTemplate(const ActionOptions&ao): ActionWithVector(ao), mode(0), usepbc(true), - wholemolecules(false) -{ + wholemolecules(false) { std::vector all_atoms; - if( getName()=="POSITION_VECTOR" || getName()=="MASS_VECTOR" || getName()=="CHARGE_VECTOR" ) parseAtomList( "ATOMS", all_atoms ); + if( getName()=="POSITION_VECTOR" || getName()=="MASS_VECTOR" || getName()=="CHARGE_VECTOR" ) { + parseAtomList( "ATOMS", all_atoms ); + } if( all_atoms.size()>0 ) { - ablocks.resize(1); ablocks[0].resize( all_atoms.size() ); - for(unsigned i=0; i t; for(int i=1;; ++i ) { T::parseAtomList( i, t, this ); - if( t.empty() ) break; + if( t.empty() ) { + break; + } - if( i==1 ) { ablocks.resize(t.size()); } + if( i==1 ) { + ablocks.resize(t.size()); + } if( t.size()!=ablocks.size() ) { - std::string ss; Tools::convert(i,ss); + std::string ss; + Tools::convert(i,ss); error("ATOMS" + ss + " keyword has the wrong number of atoms"); } for(unsigned j=0; j::calculate() { template void MultiColvarTemplate::addValueWithDerivatives( const std::vector& shape ) { - std::vector s(1); s[0]=ablocks[0].size(); addValue( s ); + std::vector s(1); + s[0]=ablocks[0].size(); + addValue( s ); } template void MultiColvarTemplate::addComponentWithDerivatives( const std::string& name, const std::vector& shape ) { - std::vector s(1); s[0]=ablocks[0].size(); addComponent( name, s ); + std::vector s(1); + s[0]=ablocks[0].size(); + addComponent( name, s ); } template void MultiColvarTemplate::setupStreamedComponents( const std::string& headstr, unsigned& nquants, unsigned& nmat, unsigned& maxcol, unsigned& nbookeeping ) { - if( wholemolecules ) makeWhole(); + if( wholemolecules ) { + makeWhole(); + } ActionWithVector::setupStreamedComponents( headstr, nquants, nmat, maxcol, nbookeeping ); } @@ -136,38 +164,60 @@ template void MultiColvarTemplate::performTask( const unsigned& task_index, MultiValue& myvals ) const { // Retrieve the positions std::vector & fpositions( myvals.getFirstAtomVector() ); - if( fpositions.size()!=ablocks.size() ) fpositions.resize( ablocks.size() ); - for(unsigned i=0; i & mass( myvals.getTemporyVector(0) ); std::vector & charge( myvals.getTemporyVector(1) ); - if( mass.size()!=ablocks.size() ) { mass.resize(ablocks.size()); charge.resize(ablocks.size()); } - for(unsigned i=0; i values( getNumberOfComponents() ); std::vector & virial( myvals.getFirstAtomVirialVector() ); std::vector > & derivs( myvals.getFirstAtomDerivativeVector() ); - if( derivs.size()!=values.size() ) { derivs.resize( values.size() ); virial.resize( values.size() ); } + if( derivs.size()!=values.size() ) { + derivs.resize( values.size() ); + virial.resize( values.size() ); + } for(unsigned i=0; igetPositionInStream(), values[i] ); + for(unsigned i=0; igetPositionInStream(), values[i] ); + } // Finish if there are no derivatives - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } // Now transfer the derivatives to the underlying MultiValue for(unsigned i=0; i::performTask( const unsigned& task_index, MultiValue // Check for duplicated indices during update to avoid double counting bool newi=true; for(unsigned j=0; jgetPositionInStream(); myvals.updateIndex( jval, base ); diff --git a/src/colvar/MultiRMSD.cpp b/src/colvar/MultiRMSD.cpp index f2d934e68c..f14f8a080c 100644 --- a/src/colvar/MultiRMSD.cpp +++ b/src/colvar/MultiRMSD.cpp @@ -59,72 +59,132 @@ void MultiRMSD::registerKeywords(Keywords& keys) { keys.addFlag("SQUARED",false," This should be set if you want the mean squared displacement instead of the root mean squared displacement"); keys.addFlag("NOPBC",false,"don't use periodic boundary conditions"); keys.setValueDescription("the sum of the multiple RMSD distances"); - keys.needsAction("CONSTANT"); keys.needsAction("WHOLEMOLECULES"); keys.needsAction("POSITION"); - keys.needsAction("CONCATENATE"); keys.needsAction("RMSD_VECTOR"); keys.needsAction("COMBINE"); keys.needsAction("CUSTOM"); + keys.needsAction("CONSTANT"); + keys.needsAction("WHOLEMOLECULES"); + keys.needsAction("POSITION"); + keys.needsAction("CONCATENATE"); + keys.needsAction("RMSD_VECTOR"); + keys.needsAction("COMBINE"); + keys.needsAction("CUSTOM"); } MultiRMSD::MultiRMSD(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { warning("this action is depracated. look at the log to see how it is implemented using the new syntax"); - std::string type; parse("TYPE",type); bool nopbc; parseFlag("NOPBC",nopbc); + std::string type; + parse("TYPE",type); + bool nopbc; + parseFlag("NOPBC",nopbc); std::size_t dash=type.find_first_of("-"); if( dash!=std::string::npos ) { - if( type.substr(0,dash)=="MULTI" ) warning("MULTI is deprecated. You can just use OPTIMAL/SIMPLE"); - else error("cannot understand type " + type ); + if( type.substr(0,dash)=="MULTI" ) { + warning("MULTI is deprecated. You can just use OPTIMAL/SIMPLE"); + } else { + error("cannot understand type " + type ); + } type = type.substr(dash+1); } - std::string reference; parse("REFERENCE",reference); PDB pdb; - if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) error("missing input file " + reference ); + std::string reference; + parse("REFERENCE",reference); + PDB pdb; + if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) { + error("missing input file " + reference ); + } unsigned nblocks = pdb.getNumberOfAtomBlocks(); - if( nblocks<2 ) error("multidomain RMSD only has one block of atoms"); - std::string num; std::vector blocks( nblocks+1 ); blocks[0]=0; - for(unsigned i=0; i blocks( nblocks+1 ); + blocks[0]=0; + for(unsigned i=0; i vals; for(unsigned k=0; k<3; ++k) { - for(unsigned j=blocks[i-1]; j(); bool remove_com=true; bool normalize_weights=true; // here align and displace are a simple vector of ones - std::vector align; align=pdb.getOccupancy(); for(unsigned i=0; i displace; displace=pdb.getBeta(); for(unsigned i=0; i align; + align=pdb.getOccupancy(); + for(unsigned i=0; i displace; + displace=pdb.getBeta(); + for(unsigned i=0; iset(align,displace,pdb.getPositions(),type,remove_com,normalize_weights); requestAtoms( pdb.getAtomNumbers() ); - addComponentWithDerivatives("residual"); componentIsNotPeriodic("residual"); + addComponentWithDerivatives("residual"); + componentIsNotPeriodic("residual"); log.printf(" average from file %s\n",f_average.c_str()); log.printf(" which contains %d atoms\n",getNumberOfAtoms()); log.printf(" with indices : "); for(unsigned i=0; ifopen(f_eigenvectors.c_str(),"r")) - { + if (FILE* fp=this->fopen(f_eigenvectors.c_str(),"r")) { // call fclose when exiting this block - auto deleter=[this](FILE* f) { this->fclose(f); }; + auto deleter=[this](FILE* f) { + this->fclose(f); + }; std::unique_ptr fp_deleter(fp,deleter); std::vector aaa; @@ -179,25 +197,42 @@ PCARMSD::PCARMSD(const ActionOptions&ao): do_read=mypdb.readFromFilepointer(fp,usingNaturalUnits(),0.1/getUnits().getLength()); if(do_read) { neigenvects++; - if(mypdb.getAtomNumbers().size()==0) error("number of atoms in a frame should be more than zero"); - if(nat==0) nat=mypdb.getAtomNumbers().size(); - if(nat!=mypdb.getAtomNumbers().size()) error("frames should have the same number of atoms"); - if(aaa.empty()) aaa=mypdb.getAtomNumbers(); - if(aaa!=mypdb.getAtomNumbers()) error("frames should contain same atoms in same order"); + if(mypdb.getAtomNumbers().size()==0) { + error("number of atoms in a frame should be more than zero"); + } + if(nat==0) { + nat=mypdb.getAtomNumbers().size(); + } + if(nat!=mypdb.getAtomNumbers().size()) { + error("frames should have the same number of atoms"); + } + if(aaa.empty()) { + aaa=mypdb.getAtomNumbers(); + } + if(aaa!=mypdb.getAtomNumbers()) { + error("frames should contain same atoms in same order"); + } log<<" Found eigenvector: "< > drotdpos(3,3); std::vector alignedpos; @@ -227,9 +264,11 @@ void PCARMSD::calculate() { for(unsigned i=0; iset(val); // here the loop is reversed to better suit the structure of the derivative of the rotation matrix @@ -255,7 +294,9 @@ void PCARMSD::calculate() { } } - for(int i=0; i v; v.push_back(i); - indexvec.push_back(v); i+=1.; + std::vector v; + v.push_back(i); + indexvec.push_back(v); + i+=1.; } } diff --git a/src/colvar/PathMSDBase.cpp b/src/colvar/PathMSDBase.cpp index a1a9b1af1d..65c99b78bd 100644 --- a/src/colvar/PathMSDBase.cpp +++ b/src/colvar/PathMSDBase.cpp @@ -51,8 +51,7 @@ PathMSDBase::PathMSDBase(const ActionOptions&ao): debugClose(0), logClose(0), computeRefClose(false), - nframes(0) -{ + nframes(0) { parse("LAMBDA",lambda); parse("NEIGH_SIZE",neigh_size); parse("NEIGH_STRIDE",neigh_stride); @@ -63,10 +62,11 @@ PathMSDBase::PathMSDBase(const ActionOptions&ao): parseFlag("NOPBC",nopbc); // open the file - if (FILE* fp=this->fopen(reference.c_str(),"r")) - { + if (FILE* fp=this->fopen(reference.c_str(),"r")) { // call fclose when exiting this block - auto deleter=[this](FILE* f) { this->fclose(f); }; + auto deleter=[this](FILE* f) { + this->fclose(f); + }; std::unique_ptr fp_deleter(fp,deleter); std::vector aaa; @@ -79,30 +79,44 @@ PathMSDBase::PathMSDBase(const ActionOptions&ao): do_read=mypdb.readFromFilepointer(fp,usingNaturalUnits(),0.1/getUnits().getLength()); if(do_read) { nframes++; - if(mypdb.getAtomNumbers().size()==0) error("number of atoms in a frame should be more than zero"); - if(nat==0) nat=mypdb.getAtomNumbers().size(); - if(nat!=mypdb.getAtomNumbers().size()) error("frames should have the same number of atoms"); + if(mypdb.getAtomNumbers().size()==0) { + error("number of atoms in a frame should be more than zero"); + } + if(nat==0) { + nat=mypdb.getAtomNumbers().size(); + } + if(nat!=mypdb.getAtomNumbers().size()) { + error("frames should have the same number of atoms"); + } if(aaa.empty()) { aaa=mypdb.getAtomNumbers(); log.printf(" found %zu atoms in input \n",aaa.size()); log.printf(" with indices : "); for(unsigned i=0; i 0) { log.printf(" Computing with the close structure, epsilon = %lf\n", epsilonClose); log << " Bibliography " << plumed.cite("Pazurikova J, Krenek A, Spiwok V, Simkova M J. Chem. Phys. 146, 115101 (2017)") << "\n"; - } - else { + } else { debugClose = 0; logClose = 0; } - if (debugClose) + if (debugClose) { log.printf(" Extensive debug info regarding close structure turned on\n"); + } rotationRefClose.resize(nframes); savedIndices = std::vector(nframes); - if(nopbc) log.printf(" without periodic boundary conditions\n"); - else log.printf(" using periodic boundary conditions\n"); + if(nopbc) { + log.printf(" without periodic boundary conditions\n"); + } else { + log.printf(" using periodic boundary conditions\n"); + } } @@ -142,11 +159,15 @@ PathMSDBase::~PathMSDBase() { void PathMSDBase::calculate() { - if(neigh_size>0 && getExchangeStep()) error("Neighbor lists for this collective variable are not compatible with replica exchange, sorry for that!"); + if(neigh_size>0 && getExchangeStep()) { + error("Neighbor lists for this collective variable are not compatible with replica exchange, sorry for that!"); + } //log.printf("NOW CALCULATE! \n"); - if(!nopbc) makeWhole(); + if(!nopbc) { + makeWhole(); + } // resize the list to full @@ -175,8 +196,9 @@ void PathMSDBase::calculate() { //if we compute for the first time or the existing close structure is too far from current structure if (firstPosClose || (posclose > epsilonClose)) { //set the current structure as close one for a few next steps - if (logClose) + if (logClose) { log << "PLUMED_CLOSE: new close structure, rmsd pos close " << posclose << "\n"; + } rmsdPosClose.clear(); rmsdPosClose.setReference(getPositions()); //as this is a new close structure, we need to save the rotation matrices fitted to the reference structures @@ -188,11 +210,11 @@ void PathMSDBase::calculate() { imgVec[i].index=i; } firstPosClose = false; - } - else { + } else { //the current structure is pretty close to the close structure, so we use saved rotation matrices to decrease the complexity of rmsd comuptation - if (debugClose) + if (debugClose) { log << "PLUMED-CLOSE: old close structure, rmsd pos close " << posclose << "\n"; + } computeRefClose = false; } } @@ -210,16 +232,19 @@ void PathMSDBase::calculate() { tmp_distances[i] = msdv[imgVec[i].index].calc_Rot(getPositions(), tmp_derivs, tmp_rotationRefClose[imgVec[i].index], true); plumed_assert(tmp_derivs.size()==nat); #pragma omp simd - for(unsigned j=0; j val_s_path; if(labels.size()>0) { - for(unsigned i=0; i s_path(val_s_path.size()); for(unsigned i=0; i s_path(val_s_path.size()); + for(unsigned i=0; iset(s_path[i]) ;} + for(unsigned i=0; iset(s_path[i]) ; + } val_z_path->set(-(1./lambda)*std::log(partition) + min_distance); // clean vector @@ -297,18 +333,26 @@ void PathMSDBase::calculate() { double expval=it.similarity; tmp=lambda*expval*(s_path[j]-it.property[j])/partition; #pragma omp simd - for(unsigned i=0; i< derivs_s.size(); i++) { derivs_s[i]+=tmp*it.distder[i] ;} + for(unsigned i=0; i< derivs_s.size(); i++) { + derivs_s[i]+=tmp*it.distder[i] ; + } if(j==0) { #pragma omp simd - for(unsigned i=0; i< derivs_z.size(); i++) { derivs_z[i]+=it.distder[i]*expval/partition;} + for(unsigned i=0; i< derivs_z.size(); i++) { + derivs_z[i]+=it.distder[i]*expval/partition; + } } } for(unsigned i=0; i< derivs_s.size(); i++) { setAtomsDerivatives (val_s_path[j],i,derivs_s[i]); - if(j==0) {setAtomsDerivatives (val_z_path,i,derivs_z[i]);} + if(j==0) { + setAtomsDerivatives (val_z_path,i,derivs_z[i]); + } } } - for(unsigned i=0; i PlaneMulti; PLUMED_REGISTER_ACTION(PlaneMulti,"PLANE_VECTOR") void Plane::registerKeywords( Keywords& keys ) { - Colvar::registerKeywords( keys ); keys.setDisplayName("PLANE"); + Colvar::registerKeywords( keys ); + keys.setDisplayName("PLANE"); keys.add("atoms","ATOMS","the three or four atoms whose plane we are computing"); keys.addOutputComponent("x","default","the x-component of the vector that is normal to the plane containing the atoms"); keys.addOutputComponent("y","default","the y-component of the vector that is normal to the plane containing the atoms"); @@ -101,13 +102,18 @@ void Plane::parseAtomList( const int& num, std::vector& atoms, Actio atoms[2]=atoms[1]; } else if(atoms.size()==4) { aa->log.printf(" containing lines %d-%d and %d-%d\n",atoms[0].serial(),atoms[1].serial(),atoms[2].serial(),atoms[3].serial()); - } else if( num<0 || atoms.size()>0 ) aa->error("Number of specified atoms should be either 3 or 4"); + } else if( num<0 || atoms.size()>0 ) { + aa->error("Number of specified atoms should be either 3 or 4"); + } } unsigned Plane::getModeAndSetupValues( ActionWithValue* av ) { - av->addComponentWithDerivatives("x"); av->componentIsNotPeriodic("x"); - av->addComponentWithDerivatives("y"); av->componentIsNotPeriodic("y"); - av->addComponentWithDerivatives("z"); av->componentIsNotPeriodic("z"); + av->addComponentWithDerivatives("x"); + av->componentIsNotPeriodic("x"); + av->addComponentWithDerivatives("y"); + av->componentIsNotPeriodic("y"); + av->addComponentWithDerivatives("z"); + av->componentIsNotPeriodic("z"); return 0; } @@ -116,16 +122,21 @@ Plane::Plane(const ActionOptions&ao): pbc(true), value(3), derivs(3), - virial(3) -{ - for(unsigned i=0; i<3; ++i) derivs[i].resize(4); - std::vector atoms; parseAtomList(-1,atoms,this); + virial(3) { + for(unsigned i=0; i<3; ++i) { + derivs[i].resize(4); + } + std::vector atoms; + parseAtomList(-1,atoms,this); bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } unsigned mode = getModeAndSetupValues( this ); requestAtoms(atoms); @@ -134,10 +145,14 @@ Plane::Plane(const ActionOptions&ao): void Plane::calculate() { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } calculateCV( 0, masses, charges, getPositions(), value, derivs, virial, this ); setValue( value[0] ); - for(unsigned i=0; i PositionMulti; PLUMED_REGISTER_ACTION(PositionMulti,"POSITION_VECTOR") void Position::registerKeywords( Keywords& keys ) { - Colvar::registerKeywords( keys ); keys.setDisplayName("POSITION"); + Colvar::registerKeywords( keys ); + keys.setDisplayName("POSITION"); keys.add("atoms","ATOM","the atom number"); keys.add("atoms","ATOMS","the atom numbers that you would like to use the positions of"); keys.addFlag("WHOLEMOLECULES",false,"if this is a vector of positions do you want to make the positions into a whole before"); @@ -135,41 +136,58 @@ Position::Position(const ActionOptions&ao): pbc(true), value(3), derivs(3), - virial(3) -{ - for(unsigned i=0; i<3; ++i) derivs[i].resize(1); - std::vector atoms; parseAtomList(-1,atoms,this); + virial(3) { + for(unsigned i=0; i<3; ++i) { + derivs[i].resize(1); + } + std::vector atoms; + parseAtomList(-1,atoms,this); unsigned mode=getModeAndSetupValues(this); - if( mode==1 ) scaled_components=true; + if( mode==1 ) { + scaled_components=true; + } bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; checkRead(); - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } requestAtoms(atoms); } void Position::parseAtomList( const int& num, std::vector& t, ActionAtomistic* aa ) { aa->parseAtomList("ATOM",num,t); - if( t.size()==1 ) aa->log.printf(" for atom %d\n",t[0].serial()); - else if( num<0 || t.size()!=0 ) aa->error("Number of specified atoms should be 1"); + if( t.size()==1 ) { + aa->log.printf(" for atom %d\n",t[0].serial()); + } else if( num<0 || t.size()!=0 ) { + aa->error("Number of specified atoms should be 1"); + } } unsigned Position::getModeAndSetupValues( ActionWithValue* av ) { - bool sc; av->parseFlag("SCALED_COMPONENTS",sc); + bool sc; + av->parseFlag("SCALED_COMPONENTS",sc); if(sc) { - av->addComponentWithDerivatives("a"); av->componentIsPeriodic("a","-0.5","+0.5"); - av->addComponentWithDerivatives("b"); av->componentIsPeriodic("b","-0.5","+0.5"); - av->addComponentWithDerivatives("c"); av->componentIsPeriodic("c","-0.5","+0.5"); + av->addComponentWithDerivatives("a"); + av->componentIsPeriodic("a","-0.5","+0.5"); + av->addComponentWithDerivatives("b"); + av->componentIsPeriodic("b","-0.5","+0.5"); + av->addComponentWithDerivatives("c"); + av->componentIsPeriodic("c","-0.5","+0.5"); return 1; } - av->addComponentWithDerivatives("x"); av->componentIsNotPeriodic("x"); - av->addComponentWithDerivatives("y"); av->componentIsNotPeriodic("y"); - av->addComponentWithDerivatives("z"); av->componentIsNotPeriodic("z"); + av->addComponentWithDerivatives("x"); + av->componentIsNotPeriodic("x"); + av->addComponentWithDerivatives("y"); + av->componentIsNotPeriodic("y"); + av->addComponentWithDerivatives("z"); + av->componentIsNotPeriodic("z"); av->log<<" WARNING: components will not have the proper periodicity - see manual\n"; return 0; } @@ -220,14 +238,22 @@ void Position::calculateCV( const unsigned& mode, const std::vector& mas std::vector& virial, const ActionAtomistic* aa ) { if( mode==1 ) { Vector d=aa->getPbc().realToScaled(pos[0]); - vals[0]=Tools::pbc(d[0]); vals[1]=Tools::pbc(d[1]); vals[2]=Tools::pbc(d[2]); + vals[0]=Tools::pbc(d[0]); + vals[1]=Tools::pbc(d[1]); + vals[2]=Tools::pbc(d[2]); derivs[0][0]=matmul(aa->getPbc().getInvBox(),Vector(+1,0,0)); derivs[1][0]=matmul(aa->getPbc().getInvBox(),Vector(0,+1,0)); derivs[2][0]=matmul(aa->getPbc().getInvBox(),Vector(0,0,+1)); } else { - for(unsigned i=0; i<3; ++i) vals[i]=pos[0][i]; - derivs[0][0]=Vector(+1,0,0); derivs[1][0]=Vector(0,+1,0); derivs[2][0]=Vector(0,0,+1); - virial[0]=Tensor(pos[0],Vector(-1,0,0)); virial[1]=Tensor(pos[0],Vector(0,-1,0)); virial[2]=Tensor(pos[0],Vector(0,0,-1)); + for(unsigned i=0; i<3; ++i) { + vals[i]=pos[0][i]; + } + derivs[0][0]=Vector(+1,0,0); + derivs[1][0]=Vector(0,+1,0); + derivs[2][0]=Vector(0,0,+1); + virial[0]=Tensor(pos[0],Vector(-1,0,0)); + virial[1]=Tensor(pos[0],Vector(0,-1,0)); + virial[2]=Tensor(pos[0],Vector(0,0,-1)); } } diff --git a/src/colvar/ProjectionOnAxis.cpp b/src/colvar/ProjectionOnAxis.cpp index a549c0ebad..6beb44201f 100644 --- a/src/colvar/ProjectionOnAxis.cpp +++ b/src/colvar/ProjectionOnAxis.cpp @@ -89,26 +89,34 @@ void ProjectionOnAxis::registerKeywords( Keywords& keys ) { ProjectionOnAxis::ProjectionOnAxis(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), - pbc(true) -{ + pbc(true) { std::vector axis_atoms; parseAtomList("AXIS_ATOMS",axis_atoms); - if( axis_atoms.size()!=2 ) error("There should only be two atoms specified to AXIS_ATOMS keyword"); + if( axis_atoms.size()!=2 ) { + error("There should only be two atoms specified to AXIS_ATOMS keyword"); + } std::vector atom; parseAtomList("ATOM",atom); - if( atom.size()!=1 ) error("There should only be one atom specified to ATOM keyword"); + if( atom.size()!=1 ) { + error("There should only be one atom specified to ATOM keyword"); + } log.printf(" calculating projection of vector connecting atom %d and atom %d on vector connecting atom %d and atom %d \n", axis_atoms[0].serial(), atom[0].serial(), axis_atoms[0].serial(), axis_atoms[1].serial() ); bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" not using periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" not using periodic boundary conditions\n"); + } // Add values to store data - addComponentWithDerivatives("proj"); componentIsNotPeriodic("proj"); - addComponentWithDerivatives("ext"); componentIsNotPeriodic("ext"); + addComponentWithDerivatives("proj"); + componentIsNotPeriodic("proj"); + addComponentWithDerivatives("ext"); + componentIsNotPeriodic("ext"); // Get all the atom positions axis_atoms.push_back( atom[0] ); requestAtoms(axis_atoms); @@ -126,8 +134,10 @@ void ProjectionOnAxis::calculate() { rik = delta( getPosition(2), getPosition(0) ); rjk = delta( getPosition(2), getPosition(1) ); } - Vector rij = delta( rik, rjk ); double dij = rij.modulo(); - Vector nij = (1.0/dij)*rij; Tensor dij_a1; + Vector rij = delta( rik, rjk ); + double dij = rij.modulo(); + Vector nij = (1.0/dij)*rij; + Tensor dij_a1; // Derivative of director connecting atom1 - atom2 wrt the position of atom 1 dij_a1(0,0) = ( -(nij[1]*nij[1]+nij[2]*nij[2])/dij ); // dx/dx dij_a1(0,1) = ( nij[0]*nij[1]/dij ); // dx/dy @@ -144,19 +154,22 @@ void ProjectionOnAxis::calculate() { Vector dd1 = matmul(-rik, dij_a1) - nij; Vector dd2 = matmul(rik, dij_a1); Vector dd3 = nij; - Value* pval=getPntrToComponent("proj"); pval->set( d ); + Value* pval=getPntrToComponent("proj"); + pval->set( d ); setAtomsDerivatives( pval, 0, dd1 ); setAtomsDerivatives( pval, 1, dd2 ); setAtomsDerivatives( pval, 2, dd3 ); setBoxDerivatives( pval, -Tensor( rik, dd1 ) - Tensor( rjk, dd2 ) ); // Calculate derivatives of perpendicular distance from axis - double c = std::sqrt( rik.modulo2() - d*d ); double invc = (1.0/c); + double c = std::sqrt( rik.modulo2() - d*d ); + double invc = (1.0/c); // Calculate derivatives of the other thing Vector der1 = invc*(rik - d*dd1); Vector der2 = invc*(-d*dd2); Vector der3 = invc*(-rik - d*dd3); - Value* cval=getPntrToComponent("ext"); cval->set( c ); + Value* cval=getPntrToComponent("ext"); + cval->set( c ); setAtomsDerivatives( cval, 0, der1 ); setAtomsDerivatives( cval, 1, der2 ); setAtomsDerivatives( cval, 2, der3 ); diff --git a/src/colvar/PropertyMap.cpp b/src/colvar/PropertyMap.cpp index 347ac5a856..8b10c89392 100644 --- a/src/colvar/PropertyMap.cpp +++ b/src/colvar/PropertyMap.cpp @@ -106,8 +106,7 @@ void PropertyMap::registerKeywords(Keywords& keys) { PropertyMap::PropertyMap(const ActionOptions&ao): Action(ao), - PathMSDBase(ao) -{ + PathMSDBase(ao) { // this is the only additional keyword needed parseVector("PROPERTY",labels); checkRead(); @@ -122,18 +121,21 @@ PropertyMap::PropertyMap(const ActionOptions&ao): } else { for(unsigned i=0; i labelvals; for(unsigned j=0; j val(1); - if( pdbv[i].getArgumentValue(labels[j],val) ) {labelvals.push_back(val[0]);} - else { + if( pdbv[i].getArgumentValue(labels[j],val) ) { + labelvals.push_back(val[0]); + } else { const std::size_t buflen=500; char buf[buflen]; std::snprintf(buf,buflen,"PROPERTY LABEL \" %s \" NOT FOUND IN REMARK FOR FRAME %u \n",labels[j].c_str(),i); diff --git a/src/colvar/Puckering.cpp b/src/colvar/Puckering.cpp index 08be02dc0e..6847cd19fc 100644 --- a/src/colvar/Puckering.cpp +++ b/src/colvar/Puckering.cpp @@ -97,36 +97,53 @@ void Puckering::registerKeywords(Keywords& keys) { } Puckering::Puckering(const ActionOptions&ao): - PLUMED_COLVAR_INIT(ao) -{ + PLUMED_COLVAR_INIT(ao) { std::vector atoms; parseAtomList("ATOMS",atoms); - if(atoms.size()!=5 && atoms.size()!=6) error("only for 5 or 6-membered rings"); + if(atoms.size()!=5 && atoms.size()!=6) { + error("only for 5 or 6-membered rings"); + } checkRead(); if(atoms.size()==5) { log.printf(" between atoms %d %d %d %d %d\n",atoms[0].serial(),atoms[1].serial(),atoms[2].serial(),atoms[3].serial(),atoms[4].serial()); } else if(atoms.size()==6) { log.printf(" between atoms %d %d %d %d %d %d\n",atoms[0].serial(),atoms[1].serial(),atoms[2].serial(),atoms[3].serial(),atoms[4].serial(),atoms[5].serial()); - } else error("ATOMS should specify 5 atoms"); + } else { + error("ATOMS should specify 5 atoms"); + } if(atoms.size()==5) { - addComponentWithDerivatives("phs"); componentIsPeriodic("phs","-pi","pi"); - addComponentWithDerivatives("amp"); componentIsNotPeriodic("amp"); - addComponentWithDerivatives("Zx"); componentIsNotPeriodic("Zx"); - addComponentWithDerivatives("Zy"); componentIsNotPeriodic("Zy"); + addComponentWithDerivatives("phs"); + componentIsPeriodic("phs","-pi","pi"); + addComponentWithDerivatives("amp"); + componentIsNotPeriodic("amp"); + addComponentWithDerivatives("Zx"); + componentIsNotPeriodic("Zx"); + addComponentWithDerivatives("Zy"); + componentIsNotPeriodic("Zy"); } else if(atoms.size()==6) { - addComponentWithDerivatives("qx"); componentIsNotPeriodic("qx"); - addComponentWithDerivatives("qy"); componentIsNotPeriodic("qy"); - addComponentWithDerivatives("qz"); componentIsNotPeriodic("qz"); - addComponentWithDerivatives("phi"); componentIsPeriodic("phi","0","2pi"); - addComponentWithDerivatives("theta"); componentIsNotPeriodic("theta"); - addComponentWithDerivatives("amplitude"); componentIsNotPeriodic("amplitude"); + addComponentWithDerivatives("qx"); + componentIsNotPeriodic("qx"); + addComponentWithDerivatives("qy"); + componentIsNotPeriodic("qy"); + addComponentWithDerivatives("qz"); + componentIsNotPeriodic("qz"); + addComponentWithDerivatives("phi"); + componentIsPeriodic("phi","0","2pi"); + addComponentWithDerivatives("theta"); + componentIsNotPeriodic("theta"); + addComponentWithDerivatives("amplitude"); + componentIsNotPeriodic("amplitude"); } log<<" Bibliography "; - if(atoms.size()==5) log<set(Zx); @@ -229,16 +257,26 @@ void Puckering::calculate5m() { void Puckering::calculate6m() { std::vector r(6); - for(unsigned i=0; i<6; i++) r[i]=getPosition(i); + for(unsigned i=0; i<6; i++) { + r[i]=getPosition(i); + } std::vector R(6); Vector center; - for(unsigned j=0; j<6; j++) center+=r[j]/6.0; - for(unsigned j=0; j<6; j++) R[j]=(r[j]-center); + for(unsigned j=0; j<6; j++) { + center+=r[j]/6.0; + } + for(unsigned j=0; j<6; j++) { + R[j]=(r[j]-center); + } Vector Rp,Rpp; - for(unsigned j=0; j<6; j++) Rp +=R[j]*std::sin(2.0/6.0*pi*j); - for(unsigned j=0; j<6; j++) Rpp+=R[j]*std::cos(2.0/6.0*pi*j); + for(unsigned j=0; j<6; j++) { + Rp +=R[j]*std::sin(2.0/6.0*pi*j); + } + for(unsigned j=0; j<6; j++) { + Rpp+=R[j]*std::cos(2.0/6.0*pi*j); + } Vector n=crossProduct(Rp,Rpp); Vector nhat=n/modulo(n); @@ -251,50 +289,78 @@ void Puckering::calculate6m() { Tensor dnhat_dRpp=matmul(dnhat_dn,dn_dRpp); std::vector z(6); - for(unsigned j=0; j<6; j++) z[j]=dotProduct(R[j],nhat); + for(unsigned j=0; j<6; j++) { + z[j]=dotProduct(R[j],nhat); + } std::vector > dz_dR(6); - for(unsigned j=0; j<6; j++) dz_dR[j].resize(6); + for(unsigned j=0; j<6; j++) { + dz_dR[j].resize(6); + } - for(unsigned i=0; i<6; i++) for(unsigned j=0; j<6; j++) { - if(i==j) dz_dR[i][j]+=nhat; + for(unsigned i=0; i<6; i++) + for(unsigned j=0; j<6; j++) { + if(i==j) { + dz_dR[i][j]+=nhat; + } dz_dR[i][j]+=matmul(R[i],dnhat_dRp)*std::sin(2.0/6.0*pi*j); dz_dR[i][j]+=matmul(R[i],dnhat_dRpp)*std::cos(2.0/6.0*pi*j); } double B=0.0; - for(unsigned j=0; j<6; j++) B+=z[j]*std::cos(4.0/6.0*pi*j); + for(unsigned j=0; j<6; j++) { + B+=z[j]*std::cos(4.0/6.0*pi*j); + } std::vector dB_dR(6); - for(unsigned i=0; i<6; i++) for(unsigned j=0; j<6; j++) { + for(unsigned i=0; i<6; i++) + for(unsigned j=0; j<6; j++) { dB_dR[i]+=dz_dR[j][i]*std::cos(4.0/6.0*pi*j); } Vector Bsum; - for(unsigned j=0; j<6; j++) Bsum+=dB_dR[j]; - for(unsigned j=0; j<6; j++) dB_dR[j]-=Bsum/6.0;; + for(unsigned j=0; j<6; j++) { + Bsum+=dB_dR[j]; + } + for(unsigned j=0; j<6; j++) { + dB_dR[j]-=Bsum/6.0; + }; double A=0.0; - for(unsigned j=0; j<6; j++) A+=z[j]*std::sin(4.0/6.0*pi*j); + for(unsigned j=0; j<6; j++) { + A+=z[j]*std::sin(4.0/6.0*pi*j); + } std::vector dA_dR(6); - for(unsigned i=0; i<6; i++) for(unsigned j=0; j<6; j++) { + for(unsigned i=0; i<6; i++) + for(unsigned j=0; j<6; j++) { dA_dR[i]+=dz_dR[j][i]*std::sin(4.0/6.0*pi*j); } Vector Asum; - for(unsigned j=0; j<6; j++) Asum+=dA_dR[j]; - for(unsigned j=0; j<6; j++) dA_dR[j]-=Asum/6.0;; + for(unsigned j=0; j<6; j++) { + Asum+=dA_dR[j]; + } + for(unsigned j=0; j<6; j++) { + dA_dR[j]-=Asum/6.0; + }; double C=0.0; - for(unsigned j=0; j<6; j++) C+=z[j]*Tools::fastpow(-1.0,(j)); + for(unsigned j=0; j<6; j++) { + C+=z[j]*Tools::fastpow(-1.0,(j)); + } std::vector dC_dR(6); - for(unsigned i=0; i<6; i++) for(unsigned j=0; j<6; j++) { + for(unsigned i=0; i<6; i++) + for(unsigned j=0; j<6; j++) { dC_dR[i]+=dz_dR[j][i]*Tools::fastpow(-1.0,(j)); } Vector Csum; - for(unsigned j=0; j<6; j++) Csum+=dC_dR[j]; - for(unsigned j=0; j<6; j++) dC_dR[j]-=Csum/6.0;; + for(unsigned j=0; j<6; j++) { + Csum+=dC_dR[j]; + } + for(unsigned j=0; j<6; j++) { + dC_dR[j]-=Csum/6.0; + }; // qx diff --git a/src/colvar/RMSD.cpp b/src/colvar/RMSD.cpp index 55ad012ebc..99716a5e1b 100644 --- a/src/colvar/RMSD.cpp +++ b/src/colvar/RMSD.cpp @@ -167,7 +167,8 @@ END PLUMED_REGISTER_ACTION(RMSD,"RMSD_SCALAR") void RMSD::registerKeywords(Keywords& keys) { - Colvar::registerKeywords(keys); keys.setDisplayName("RMSD"); + Colvar::registerKeywords(keys); + keys.setDisplayName("RMSD"); keys.add("compulsory","REFERENCE","a file in pdb format containing the reference structure and the atoms involved in the CV."); keys.add("compulsory","TYPE","SIMPLE","the manner in which RMSD alignment is performed. Should be OPTIMAL or SIMPLE."); keys.addFlag("SQUARED",false," This should be set if you want mean squared displacement instead of RMSD "); @@ -177,8 +178,7 @@ void RMSD::registerKeywords(Keywords& keys) { RMSD::RMSD(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), squared(false), - nopbc(false) -{ + nopbc(false) { std::string reference; parse("REFERENCE",reference); std::string type; @@ -188,39 +188,53 @@ RMSD::RMSD(const ActionOptions&ao): parseFlag("NOPBC",nopbc); checkRead(); - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); PDB pdb; // read everything in ang and transform to nm if we are not in natural units - if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) + if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) { error("missing input file " + reference ); + } myrmsd.set( pdb, type, true, true ); std::vector atoms( pdb.getAtomNumbers() ); - requestAtoms( atoms ); der.resize( atoms.size() ); + requestAtoms( atoms ); + der.resize( atoms.size() ); log.printf(" reference from file %s\n",reference.c_str()); log.printf(" which contains %d atoms\n",getNumberOfAtoms()); log.printf(" with indices : "); for(unsigned i=0; i0 ) break ; + PDB mypdb; + do_read=mypdb.readFromFilepointer(fp,plumed.usingNaturalUnits(),0.1/plumed.getUnits().getLength()); + if( !do_read && nf>0 ) { + break ; + } nf++; } } - bool nopbc; parseFlag("NOPBC",nopbc); + bool nopbc; + parseFlag("NOPBC",nopbc); // Now create the RMSD object std::string rmsd_line = getShortcutLabel() + ": "; if( nf==1 && !disp ) { - rmsd_line += "RMSD_SCALAR REFERENCE=" + reference; if(nopbc) rmsd_line += " NOPBC"; + rmsd_line += "RMSD_SCALAR REFERENCE=" + reference; + if(nopbc) { + rmsd_line += " NOPBC"; + } } else { - std::string ffnum; Tools::convert( frame, ffnum ); + std::string ffnum; + Tools::convert( frame, ffnum ); readInputLine( getShortcutLabel() + "_ref: PDB2CONSTANT REFERENCE=" + reference + " NUMBER=" + ffnum ); std::vector anum( pdb.getAtomNumbers() ); if( !nopbc ) { - std::string num; Tools::convert( anum[0].serial(), num ); std::string wm_line = "WHOLEMOLECULES ENTITY0=" + num; - for(unsigned i=1; i align( pdb.getOccupancy() ); Tools::convert( align[0], num ); rmsd_line += " ALIGN=" + num; - for(unsigned i=1; i align( pdb.getOccupancy() ); + Tools::convert( align[0], num ); + rmsd_line += " ALIGN=" + num; + for(unsigned i=1; i displace( pdb.getBeta() ); Tools::convert( displace[0], num ); rmsd_line += " DISPLACE=" + num; - for(unsigned i=1; i displace( pdb.getBeta() ); + Tools::convert( displace[0], num ); + rmsd_line += " DISPLACE=" + num; + for(unsigned i=1; igetRank()!=1 ) error("first argument should be vector"); - if( getPntrToArgument(1)->getRank()<1 ) error("second argument should be matrix or a vector"); + firststep(true) { + if( getPntrToArgument(0)->getRank()!=1 ) { + error("first argument should be vector"); + } + if( getPntrToArgument(1)->getRank()<1 ) { + error("second argument should be matrix or a vector"); + } if( getPntrToArgument(1)->getRank()==1 ) { - if( getPntrToArgument(0)->getNumberOfValues()!=getPntrToArgument(1)->getNumberOfValues() ) error("mismatch between sizes of input vectors"); + if( getPntrToArgument(0)->getNumberOfValues()!=getPntrToArgument(1)->getNumberOfValues() ) { + error("mismatch between sizes of input vectors"); + } } else if( getPntrToArgument(1)->getRank()==2 ) { - if( getPntrToArgument(0)->getNumberOfValues()!=getPntrToArgument(1)->getShape()[1] ) error("mismatch between sizes of input vectors"); + if( getPntrToArgument(0)->getNumberOfValues()!=getPntrToArgument(1)->getShape()[1] ) { + error("mismatch between sizes of input vectors"); + } + } + if( getPntrToArgument(0)->getNumberOfValues()%3!=0 ) { + error("number of components in input arguments should be multiple of three"); } - if( getPntrToArgument(0)->getNumberOfValues()%3!=0 ) error("number of components in input arguments should be multiple of three"); unsigned natoms = getPntrToArgument(0)->getNumberOfValues() / 3; - type.assign("SIMPLE"); parse("TYPE",type); parseFlag("SQUARED",squared); - align.resize( natoms ); parseVector("ALIGN",align); - displace.resize( natoms ); parseVector("DISPLACE",displace); - bool unorm=false; parseFlag("UNORMALIZED",unorm); norm_weights=!unorm; - double wa=0, wd=0; sqrtdisplace.resize( displace.size() ); - for(unsigned i=0; iepsilon ) { double iwa = 1. / wa; - for(unsigned i=0; iepsilon ) { - if( !norm_weights ) { wd = 1; } double iwd = 1. / wd; - for(unsigned i=0; igetRank()==1 || getPntrToArgument(1)->getShape()[0]<=1) ) { - addComponentWithDerivatives("dist"); componentIsNotPeriodic("dist"); + addComponentWithDerivatives("dist"); + componentIsNotPeriodic("dist"); std::vector shape( 1, getPntrToArgument(0)->getNumberOfValues() ); - addComponent( "disp", shape ); getPntrToComponent(1)->buildDataStore(); componentIsNotPeriodic("disp"); + addComponent( "disp", shape ); + getPntrToComponent(1)->buildDataStore(); + componentIsNotPeriodic("disp"); } else if( displacement ) { std::vector shape( 1, getPntrToArgument(1)->getShape()[0] ); - addComponent( "dist", shape ); getPntrToComponent(0)->buildDataStore(); + addComponent( "dist", shape ); + getPntrToComponent(0)->buildDataStore(); componentIsNotPeriodic("dist"); - shape.resize(2); shape[0] = getPntrToArgument(1)->getShape()[0]; shape[1] = getPntrToArgument(0)->getNumberOfValues(); - addComponent( "disp", shape ); getPntrToComponent(1)->buildDataStore(); getPntrToComponent(1)->reshapeMatrixStore( shape[1] ); + shape.resize(2); + shape[0] = getPntrToArgument(1)->getShape()[0]; + shape[1] = getPntrToArgument(0)->getNumberOfValues(); + addComponent( "disp", shape ); + getPntrToComponent(1)->buildDataStore(); + getPntrToComponent(1)->reshapeMatrixStore( shape[1] ); componentIsNotPeriodic("disp"); } else if( (getPntrToArgument(1)->getRank()==1 || getPntrToArgument(1)->getShape()[0]==1) ) { - addValue(); setNotPeriodic(); + addValue(); + setNotPeriodic(); } else { std::vector shape( 1, getPntrToArgument(1)->getShape()[0] ); - addValue( shape ); setNotPeriodic(); + addValue( shape ); + setNotPeriodic(); + } + if( getPntrToArgument(1)->getRank()==1 || getPntrToArgument(1)->getNumberOfValues()==0 ) { + myrmsd.resize(1); + } else { + myrmsd.resize( getPntrToArgument(1)->getShape()[0] ); } - if( getPntrToArgument(1)->getRank()==1 || getPntrToArgument(1)->getNumberOfValues()==0 ) myrmsd.resize(1); - else myrmsd.resize( getPntrToArgument(1)->getShape()[0] ); - if( getPntrToArgument(1)->getRank()==1 ) log.printf(" calculating RMSD distance between %d atoms. Distance between the avectors of atoms in %s and %s\n", - natoms, getPntrToArgument(0)->getName().c_str(), getPntrToArgument(1)->getName().c_str() ); - else log.printf(" calculating RMSD distance between %d sets of %d atoms. Distance between vector %s of atoms and matrix of configurations in %s\n", - getPntrToArgument(1)->getShape()[0], natoms, getPntrToArgument(0)->getName().c_str(), getPntrToArgument(1)->getName().c_str() ); + if( getPntrToArgument(1)->getRank()==1 ) + log.printf(" calculating RMSD distance between %d atoms. Distance between the avectors of atoms in %s and %s\n", + natoms, getPntrToArgument(0)->getName().c_str(), getPntrToArgument(1)->getName().c_str() ); + else + log.printf(" calculating RMSD distance between %d sets of %d atoms. Distance between vector %s of atoms and matrix of configurations in %s\n", + getPntrToArgument(1)->getShape()[0], natoms, getPntrToArgument(0)->getName().c_str(), getPntrToArgument(1)->getName().c_str() ); log.printf(" method for alignment : %s \n",type.c_str() ); - if(squared)log.printf(" chosen to use SQUARED option for MSD instead of RMSD\n"); - else log.printf(" using periodic boundary conditions\n"); + if(squared) { + log.printf(" chosen to use SQUARED option for MSD instead of RMSD\n"); + } else { + log.printf(" using periodic boundary conditions\n"); + } } unsigned RMSDVector::getNumberOfDerivatives() { @@ -126,64 +178,98 @@ unsigned RMSDVector::getNumberOfDerivatives() { void RMSDVector::setReferenceConfigurations() { unsigned natoms = getPntrToArgument(0)->getShape()[0] / 3; - Vector center; std::vector pos( natoms ); + Vector center; + std::vector pos( natoms ); for(unsigned jconf=0; jconfget( (3*jconf+j)*pos.size() + i ); + for(unsigned j=0; j<3; ++j) { + pos[i][j] = getPntrToArgument(1)->get( (3*jconf+j)*pos.size() + i ); + } center+=pos[i]*align[i]; } - for(unsigned i=0; i& pos, std::vector& der, std::vector& direction ) const { unsigned natoms = pos.size(); for(unsigned i=0; iget( j*natoms + i ); + for(unsigned j=0; j<3; ++j) { + pos[i][j] = getPntrToArgument(0)->get( j*natoms + i ); + } } if( displacement && type=="SIMPLE" ) { const Value* myval = getConstPntrToComponent(1); double r = myrmsd[current].simpleAlignment( align, displace, pos, myrmsd[current].getReference(), der, direction, squared ); if( !doNotCalculateDerivatives() && myval->forcesWereAdded() ) { - Vector comforce; comforce.zero(); + Vector comforce; + comforce.zero(); for(unsigned i=0; igetForce( (3*current+k)*natoms + i); + for(unsigned k=0; k<3; ++k) { + comforce[k] += align[i]*myval->getForce( (3*current+k)*natoms + i); + } } for(unsigned i=0; igetForce( (3*current+k)*natoms + i ) - comforce[k]; + for(unsigned k=0; k<3; ++k) { + direction[i][k] = myval->getForce( (3*current+k)*natoms + i ) - comforce[k]; + } } } return r; } else if( displacement ) { const Value* myval = getConstPntrToComponent(1); - Tensor rot; Matrix > DRotDPos(3,3); std::vector centeredpos( natoms ), centeredreference( natoms ); - double r = myrmsd[current].calc_PCAelements( pos, der, rot, DRotDPos, direction, centeredpos, centeredreference, squared ); std::vector ref( myrmsd[current].getReference() ); + Tensor rot; + Matrix > DRotDPos(3,3); + std::vector centeredpos( natoms ), centeredreference( natoms ); + double r = myrmsd[current].calc_PCAelements( pos, der, rot, DRotDPos, direction, centeredpos, centeredreference, squared ); + std::vector ref( myrmsd[current].getReference() ); if( !doNotCalculateDerivatives() && myval->forcesWereAdded() ) { - Tensor trot=rot.transpose(); double prefactor = 1 / static_cast( natoms ); Vector v1; v1.zero(); + Tensor trot=rot.transpose(); + double prefactor = 1 / static_cast( natoms ); + Vector v1; + v1.zero(); for(unsigned n=0; ngetForce( (3*current+k)*natoms + n ); + Vector ff; + for(unsigned k=0; k<3; ++k ) { + ff[k] = myval->getForce( (3*current+k)*natoms + n ); + } v1+=prefactor*matmul(trot,ff); } // Notice that we use centreredreference here to accumulate the true forces for(unsigned n=0; ngetForce( (3*current+k)*natoms + n ); + Vector ff; + for(unsigned k=0; k<3; ++k ) { + ff[k] = myval->getForce( (3*current+k)*natoms + n ); + } centeredreference[n] = sqrtdisplace[n]*( matmul(trot,ff) - v1 ); } for(unsigned a=0; a<3; a++) { for(unsigned b=0; b<3; b++) { - double tmp1=0.; for(unsigned m=0; mgetForce( (3*current+a)*natoms + m ); - for(unsigned i=0; igetForce( (3*current+a)*natoms + m ); + } + for(unsigned i=0; i& // calculator void RMSDVector::calculate() { - if( firststep || !getPntrToArgument(1)->isConstant() ) { setReferenceConfigurations(); firststep=false; } + if( firststep || !getPntrToArgument(1)->isConstant() ) { + setReferenceConfigurations(); + firststep=false; + } if( getPntrToComponent(0)->getRank()==0 ) { unsigned natoms = getPntrToArgument(0)->getShape()[0] / 3; @@ -203,29 +292,43 @@ void RMSDVector::calculate() { if( getNumberOfComponents()==2 ) { Value* mydisp = getPntrToComponent(1); for(unsigned i=0; iset( j*natoms+i, direction[i][j] ); + for(unsigned j=0; j<3; ++j ) { + mydisp->set( j*natoms+i, direction[i][j] ); + } } } - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } Value* myval = getPntrToComponent(0); for(unsigned i=0; isetDerivative( j*natoms+i, der[i][j] ); + for(unsigned j=0; j<3; ++j ) { + myval->setDerivative( j*natoms+i, der[i][j] ); + } } - } else runAllTasks(); + } else { + runAllTasks(); + } } bool RMSDVector::checkForTaskForce( const unsigned& itask, const Value* myval ) const { - if( myval->getRank()<2 ) return ActionWithVector::checkForTaskForce( itask, myval ); + if( myval->getRank()<2 ) { + return ActionWithVector::checkForTaskForce( itask, myval ); + } unsigned nelements = myval->getShape()[1], startr = itask*nelements; for(unsigned j=0; jgetForce( startr + j ) )>epsilon ) return true; + if( fabs( myval->getForce( startr + j ) )>epsilon ) { + return true; + } } return false; } void RMSDVector::apply() { - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } if( getPntrToComponent(0)->getRank()==0 ) { std::vector forces( getNumberOfDerivatives(), 0 ); @@ -236,50 +339,83 @@ void RMSDVector::apply() { std::vector pos( natoms ), der( natoms ), direction( natoms ); double r = calculateRMSD( 0, pos, der, direction ); for(unsigned i=0; igetShape()[0] / 3; std::vector& pos( myvals.getFirstAtomVector() ); std::vector > & allder( myvals.getFirstAtomDerivativeVector() ); - if( allder.size()!=2 ) allder.resize(2); - std::vector& der( allder[0] ); std::vector& direction( allder[1] ); - if( pos.size()!=natoms ) { pos.resize( natoms ); der.resize( natoms ); direction.resize( natoms ); } + if( allder.size()!=2 ) { + allder.resize(2); + } + std::vector& der( allder[0] ); + std::vector& direction( allder[1] ); + if( pos.size()!=natoms ) { + pos.resize( natoms ); + der.resize( natoms ); + direction.resize( natoms ); + } for(unsigned i=0; iget( j*natoms + i ); + for(unsigned j=0; j<3; ++j) { + pos[i][j] = getPntrToArgument(0)->get( j*natoms + i ); + } } double r = calculateRMSD( current, pos, der, direction ); unsigned ostrn = getConstPntrToComponent(0)->getPositionInStream(); myvals.setValue( ostrn, r ); - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } for(unsigned i=0; i& buffer ) const { - if( getConstPntrToComponent(valindex)->getRank()==1 ) { ActionWithVector::gatherStoredValue( valindex, code, myvals, bufstart, buffer ); return; } + if( getConstPntrToComponent(valindex)->getRank()==1 ) { + ActionWithVector::gatherStoredValue( valindex, code, myvals, bufstart, buffer ); + return; + } const std::vector& direction( myvals.getConstFirstAtomDerivativeVector()[1] ); - unsigned natoms = direction.size(); unsigned vindex = bufstart + 3*code*natoms; + unsigned natoms = direction.size(); + unsigned vindex = bufstart + 3*code*natoms; for(unsigned i=0; i& forces ) const { - if( myval->getRank()==1 ) { ActionWithVector::gatherForcesOnStoredValue( myval, itask, myvals, forces ); return; } - const std::vector& direction( myvals.getConstFirstAtomDerivativeVector()[1] ); unsigned natoms = direction.size(); + if( myval->getRank()==1 ) { + ActionWithVector::gatherForcesOnStoredValue( myval, itask, myvals, forces ); + return; + } + const std::vector& direction( myvals.getConstFirstAtomDerivativeVector()[1] ); + unsigned natoms = direction.size(); for(unsigned i=0; i atoms; parseAtomList(-1,atoms,this); + PLUMED_COLVAR_INIT(ao) { + std::vector atoms; + parseAtomList(-1,atoms,this); unsigned mode=getModeAndSetupValues(this); requestAtoms(atoms); } void SelectMassCharge::parseAtomList( const int& num, std::vector& t, ActionAtomistic* aa ) { aa->parseAtomList("ATOM",num,t); - if( t.size()==1 ) aa->log.printf(" for atom %d\n",t[0].serial()); - else if( num<0 || t.size()!=0 ) aa->error("Number of specified atoms should be 1"); + if( t.size()==1 ) { + aa->log.printf(" for atom %d\n",t[0].serial()); + } else if( num<0 || t.size()!=0 ) { + aa->error("Number of specified atoms should be 1"); + } } unsigned SelectMassCharge::getModeAndSetupValues( ActionWithValue* av ) { - av->addValueWithDerivatives(); av->setNotPeriodic(); bool constant=true; - ActionAtomistic* aa=dynamic_cast( av ); plumed_assert( aa ); + av->addValueWithDerivatives(); + av->setNotPeriodic(); + bool constant=true; + ActionAtomistic* aa=dynamic_cast( av ); + plumed_assert( aa ); for(unsigned i=0; igetNumberOfAtoms(); ++i) { std::pair p = aa->getValueIndices( aa->getAbsoluteIndex(i) ); - if( av->getName().find("MASS")!=std::string::npos && !aa->masv[p.first]->isConstant() ) constant=false; - if( av->getName().find("CHARGE")!=std::string::npos && !aa->chargev[p.first]->isConstant() ) constant=false; + if( av->getName().find("MASS")!=std::string::npos && !aa->masv[p.first]->isConstant() ) { + constant=false; + } + if( av->getName().find("CHARGE")!=std::string::npos && !aa->chargev[p.first]->isConstant() ) { + constant=false; + } + } + if( !constant ) { + av->error("cannot deal with non-constant " + av->getName() + " values"); } - if( !constant ) av->error("cannot deal with non-constant " + av->getName() + " values"); (av->copyOutput(0))->setConstant(); return 0; } @@ -144,15 +160,21 @@ unsigned SelectMassCharge::getModeAndSetupValues( ActionWithValue* av ) { // calculator void SelectMassCharge::calculate() { std::vector masses(1), charges(1), vals(1); - std::vector pos; std::vector > derivs; std::vector virial; - calculateCV( 0, masses, charges, pos, vals, derivs, virial, this ); setValue( vals[0] ); + std::vector pos; + std::vector > derivs; + std::vector virial; + calculateCV( 0, masses, charges, pos, vals, derivs, virial, this ); + setValue( vals[0] ); } void SelectMassCharge::calculateCV( const unsigned& mode, const std::vector& masses, const std::vector& charges, const std::vector& pos, std::vector& vals, std::vector >& derivs, std::vector& virial, const ActionAtomistic* aa ) { - if( aa->getName().find("MASSES")!=std::string::npos ) vals[0]=masses[0]; - else if( aa->chargesWereSet ) vals[0]=charges[0]; + if( aa->getName().find("MASSES")!=std::string::npos ) { + vals[0]=masses[0]; + } else if( aa->chargesWereSet ) { + vals[0]=charges[0]; + } } } diff --git a/src/colvar/Template.cpp b/src/colvar/Template.cpp index c507b96b1d..16b57eca1d 100644 --- a/src/colvar/Template.cpp +++ b/src/colvar/Template.cpp @@ -69,22 +69,26 @@ void Template::registerKeywords(Keywords& keys) { Template::Template(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), - pbc(true) -{ + pbc(true) { std::vector atoms; parseAtomList("ATOMS",atoms); - if(atoms.size()!=2) + if(atoms.size()!=2) { error("Number of specified atoms should be 2"); + } bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; checkRead(); log.printf(" between atoms %d %d\n",atoms[0].serial(),atoms[1].serial()); - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); requestAtoms(atoms); } diff --git a/src/colvar/Torsion.cpp b/src/colvar/Torsion.cpp index 710b1359eb..2da2b59ab8 100644 --- a/src/colvar/Torsion.cpp +++ b/src/colvar/Torsion.cpp @@ -132,7 +132,8 @@ typedef MultiColvarTemplate TorsionMulti; PLUMED_REGISTER_ACTION(TorsionMulti,"TORSION_VECTOR") void Torsion::registerKeywords(Keywords& keys) { - Colvar::registerKeywords( keys ); keys.setDisplayName("TORSION"); + Colvar::registerKeywords( keys ); + keys.setDisplayName("TORSION"); keys.add("atoms-1","ATOMS","the four atoms involved in the torsional angle"); keys.add("atoms-2","AXIS","two atoms that define an axis. You can use this to find the angle in the plane perpendicular to the axis between the vectors specified using the VECTORA and VECTORB keywords."); keys.add("atoms-2","VECTORA","two atoms that define a vector. You can use this in combination with VECTOR2 and AXIS"); @@ -150,14 +151,19 @@ Torsion::Torsion(const ActionOptions&ao): do_cosine(false), value(1), derivs(1), - virial(1) -{ - derivs[0].resize(6); std::vector atoms; - std::vector v1; ActionAtomistic::parseAtomList("VECTOR1",v1); + virial(1) { + derivs[0].resize(6); + std::vector atoms; + std::vector v1; + ActionAtomistic::parseAtomList("VECTOR1",v1); if( v1.size()>0 ) { - std::vector v2; ActionAtomistic::parseAtomList("VECTOR2",v2); - std::vector axis; ActionAtomistic::parseAtomList("AXIS",axis); - if( !(v1.size()==2 && v2.size()==2 && axis.size()==2)) error("VECTOR1, VECTOR2 and AXIS should specify 2 atoms each"); + std::vector v2; + ActionAtomistic::parseAtomList("VECTOR2",v2); + std::vector axis; + ActionAtomistic::parseAtomList("AXIS",axis); + if( !(v1.size()==2 && v2.size()==2 && axis.size()==2)) { + error("VECTOR1, VECTOR2 and AXIS should specify 2 atoms each"); + } atoms.resize(6); atoms[0]=v1[1]; atoms[1]=v1[0]; @@ -167,17 +173,24 @@ Torsion::Torsion(const ActionOptions&ao): atoms[5]=v2[1]; log.printf(" between lines %d-%d and %d-%d, projected on the plane orthogonal to line %d-%d\n", v1[0].serial(),v1[1].serial(),v2[0].serial(),v2[1].serial(),axis[0].serial(),axis[1].serial()); - } else parseAtomList(-1,atoms,this); + } else { + parseAtomList(-1,atoms,this); + } unsigned mode=getModeAndSetupValues(this); - if( mode==1 ) do_cosine=true; + if( mode==1 ) { + do_cosine=true; + } bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; checkRead(); - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } requestAtoms(atoms); } @@ -189,8 +202,9 @@ void Torsion::parseAtomList( const int& num, std::vector& t, ActionA aa->parseAtomList("AXIS",num,axis); if(t.size()==4) { - if(!(v1.empty() && v2.empty() && axis.empty())) + if(!(v1.empty() && v2.empty() && axis.empty())) { aa->error("ATOMS keyword is not compatible with VECTORA, VECTORB and AXIS keywords"); + } aa->log.printf(" between atoms %d %d %d %d\n",t[0].serial(),t[1].serial(),t[2].serial(),t[3].serial()); t.resize(6); t[5]=t[3]; @@ -198,9 +212,12 @@ void Torsion::parseAtomList( const int& num, std::vector& t, ActionA t[3]=t[2]; t[2]=t[1]; } else if(t.empty()) { - if( num>0 && v1.empty() && v2.empty() && axis.empty() ) return; - if(!(v1.size()==2 && v2.size()==2 && axis.size()==2)) + if( num>0 && v1.empty() && v2.empty() && axis.empty() ) { + return; + } + if(!(v1.size()==2 && v2.size()==2 && axis.size()==2)) { aa->error("VECTORA, VECTORB and AXIS should specify 2 atoms each"); + } aa->log.printf(" between lines %d-%d and %d-%d, projected on the plane orthogonal to line %d-%d\n", v1[0].serial(),v1[1].serial(),v2[0].serial(),v2[1].serial(),axis[0].serial(),axis[1].serial()); t.resize(6); @@ -210,25 +227,42 @@ void Torsion::parseAtomList( const int& num, std::vector& t, ActionA t[3]=axis[1]; t[4]=v2[0]; t[5]=v2[1]; - } else if( t.size()!=4 ) aa->error("ATOMS should specify 4 atoms"); + } else if( t.size()!=4 ) { + aa->error("ATOMS should specify 4 atoms"); + } } unsigned Torsion::getModeAndSetupValues( ActionWithValue* av ) { - bool do_cos; av->parseFlag("COSINE",do_cos); - if(do_cos) av->log.printf(" calculating cosine instead of torsion\n"); + bool do_cos; + av->parseFlag("COSINE",do_cos); + if(do_cos) { + av->log.printf(" calculating cosine instead of torsion\n"); + } av->addValueWithDerivatives(); - if(!do_cos) { av->setPeriodic("-pi","pi"); return 0; } - av->setNotPeriodic(); return 1; + if(!do_cos) { + av->setPeriodic("-pi","pi"); + return 0; + } + av->setNotPeriodic(); + return 1; } // calculator void Torsion::calculate() { - if(pbc) makeWhole(); - if(do_cosine) calculateCV( 1, masses, charges, getPositions(), value, derivs, virial, this ); - else calculateCV( 0, masses, charges, getPositions(), value, derivs, virial, this ); - for(unsigned i=0; i<6; ++i) setAtomsDerivatives(i,derivs[0][i] ); - setValue(value[0]); setBoxDerivatives( virial[0] ); + if(pbc) { + makeWhole(); + } + if(do_cosine) { + calculateCV( 1, masses, charges, getPositions(), value, derivs, virial, this ); + } else { + calculateCV( 0, masses, charges, getPositions(), value, derivs, virial, this ); + } + for(unsigned i=0; i<6; ++i) { + setAtomsDerivatives(i,derivs[0][i] ); + } + setValue(value[0]); + setBoxDerivatives( virial[0] ); } void Torsion::calculateCV( const unsigned& mode, const std::vector& masses, const std::vector& charges, diff --git a/src/colvar/Volume.cpp b/src/colvar/Volume.cpp index a5fc1f5d3e..7eb7377edf 100644 --- a/src/colvar/Volume.cpp +++ b/src/colvar/Volume.cpp @@ -54,12 +54,12 @@ class Volume : public Colvar { PLUMED_REGISTER_ACTION(Volume,"VOLUME") Volume::Volume(const ActionOptions&ao): - PLUMED_COLVAR_INIT(ao) -{ + PLUMED_COLVAR_INIT(ao) { std::vector atoms; checkRead(); - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); requestAtoms(atoms); } diff --git a/src/config/Config.inc.in b/src/config/Config.inc.in index 39ff6f0989..931ab252e8 100644 --- a/src/config/Config.inc.in +++ b/src/config/Config.inc.in @@ -48,11 +48,21 @@ std::string escapeForSingleQuote(const std::string& input) { // This is a fix to allow conda to correctly replace paths in binary files. // These functions should not be static or they will be optimized away! -const char* plumed_root() {return "@PLUMED_ROOT@";} -const char* plumed_soext() {return "@SOEXT@";} -const char* plumed_htmldir() {return "@htmldir@";} -const char* plumed_includedir() {return "@includedir@";} -const char* plumed_program_name() {return "@program_name@";} +const char* plumed_root() { + return "@PLUMED_ROOT@"; +} +const char* plumed_soext() { + return "@SOEXT@"; +} +const char* plumed_htmldir() { + return "@htmldir@"; +} +const char* plumed_includedir() { + return "@includedir@"; +} +const char* plumed_program_name() { + return "@program_name@"; +} std::string getSoExt() { return plumed_soext(); @@ -74,7 +84,9 @@ std::string getPlumedRoot() { } std::string getPlumedHtmldir() { - if(!isInstalled()) return getPlumedRoot(); + if(!isInstalled()) { + return getPlumedRoot(); + } char *env = std::getenv("PLUMED_HTMLDIR"); std::string ss; if( env == NULL) { @@ -86,7 +98,9 @@ std::string getPlumedHtmldir() { } std::string getPlumedIncludedir() { - if(!isInstalled()) return getPlumedRoot()+"/src/include"; + if(!isInstalled()) { + return getPlumedRoot()+"/src/include"; + } char *env = std::getenv("PLUMED_INCLUDEDIR"); std::string ss; if( env == NULL) { @@ -98,7 +112,9 @@ std::string getPlumedIncludedir() { } std::string getPlumedProgramName() { - if(!isInstalled()) return "plumed"; + if(!isInstalled()) { + return "plumed"; + } char *env = std::getenv("PLUMED_PROGRAM_NAME"); std::string ss; if( env == NULL) { diff --git a/src/contour/ContourFindingBase.cpp b/src/contour/ContourFindingBase.cpp index 85fea0fa80..11944a0601 100644 --- a/src/contour/ContourFindingBase.cpp +++ b/src/contour/ContourFindingBase.cpp @@ -25,22 +25,25 @@ namespace PLMD { namespace contour { void ContourFindingBase::registerKeywords( Keywords& keys ) { - gridtools::ActionWithGrid::registerKeywords( keys ); keys.use("ARG"); + gridtools::ActionWithGrid::registerKeywords( keys ); + keys.use("ARG"); keys.add("compulsory","CONTOUR","the value we would like to draw the contour at in the space"); - gridtools::EvaluateGridFunction gg; gg.registerKeywords(keys); + gridtools::EvaluateGridFunction gg; + gg.registerKeywords(keys); } ContourFindingBase::ContourFindingBase(const ActionOptions&ao): Action(ao), ActionWithGrid(ao), - mymin(this) -{ - parse("CONTOUR",contour); function.read( this ); + mymin(this) { + parse("CONTOUR",contour); + function.read( this ); log.printf(" calculating dividing surface along which function equals %f \n", contour); } void ContourFindingBase::setupOnFirstStep( const bool incalc ) { - function.setup( this ); setupValuesOnFirstStep(); + function.setup( this ); + setupValuesOnFirstStep(); } } diff --git a/src/contour/ContourFindingBase.h b/src/contour/ContourFindingBase.h index 726d9b6285..3c2e0e3b79 100644 --- a/src/contour/ContourFindingBase.h +++ b/src/contour/ContourFindingBase.h @@ -58,8 +58,12 @@ void ContourFindingBase::findContour( const std::vector& direction, std: inline double ContourFindingBase::getDifferenceFromContour( const std::vector& x, std::vector& der ) const { - std::vector vals(1); Matrix deriva( 1, x.size() ); function.calc( this, x, vals, deriva ); - for(unsigned i=0; i vals(1); + Matrix deriva( 1, x.size() ); + function.calc( this, x, vals, deriva ); + for(unsigned i=0; i shape; // Create the values - addComponent("thickness", shape ); componentIsNotPeriodic("thickness"); - addComponent("dist1", shape ); componentIsNotPeriodic("dist1"); - addComponent("dist2", shape ); componentIsNotPeriodic("dist2"); - addComponentWithDerivatives("qdist", shape ); componentIsNotPeriodic("qdist"); + addComponent("thickness", shape ); + componentIsNotPeriodic("thickness"); + addComponent("dist1", shape ); + componentIsNotPeriodic("dist1"); + addComponent("dist2", shape ); + componentIsNotPeriodic("dist2"); + addComponentWithDerivatives("qdist", shape ); + componentIsNotPeriodic("qdist"); } void DistanceFromContour::calculate() { // Check box is orthorhombic - if( !getPbc().isOrthorombic() ) error("cell box must be orthorhombic"); + if( !getPbc().isOrthorombic() ) { + error("cell box must be orthorhombic"); + } // The nanoparticle is at the origin of our coordinate system - pos1[0]=pos1[1]=pos1[2]=0.0; pos2[0]=pos2[1]=pos2[2]=0.0; + pos1[0]=pos1[1]=pos1[2]=0.0; + pos2[0]=pos2[1]=pos2[2]=0.0; // Set bracket as center of mass of membrane in active region - Vector myvec = pbcDistance( getPosition(getNumberOfAtoms()-1), getPosition(0) ); pos2[dir]=myvec[dir]; - nactive=1; active_list[0]=0; double d2, mindist = myvec.modulo2(); + Vector myvec = pbcDistance( getPosition(getNumberOfAtoms()-1), getPosition(0) ); + pos2[dir]=myvec[dir]; + nactive=1; + active_list[0]=0; + double d2, mindist = myvec.modulo2(); for(unsigned j=1; jepsilon ) { pos2[dir]=distance[dir]; mindist = d2; } - active_list[nactive]=j; nactive++; + if( d2epsilon ) { + pos2[dir]=distance[dir]; + mindist = d2; + } + active_list[nactive]=j; + nactive++; } } // pos1 position of the nanoparticle, in the first time @@ -154,8 +185,11 @@ void DistanceFromContour::calculate() { unsigned maxtries = std::floor( ( getBox()(dir,dir) ) / bw[dir] ); for(unsigned i=0; i0)? -1 : +1; // If the nanoparticle is inside the membrane push it out - pos1[dir] += sign*bw[dir]; fa = getDifferenceFromContour( pos1, faked ); - if( fa*fb<0 ) break; + pos1[dir] += sign*bw[dir]; + fa = getDifferenceFromContour( pos1, faked ); + if( fa*fb<0 ) { + break; + } // if fa*fb is less than zero the new pos 1 is outside the contour } } @@ -169,8 +203,11 @@ void DistanceFromContour::calculate() { unsigned maxtries = std::floor( ( getBox()(dir,dir) ) / bw[dir] ); for(unsigned i=0; i0)? +1 : -1; - pos2[dir] += sign*bw[dir]; fc = getDifferenceFromContour( pos2, faked ); - if( fc*fb<0 ) break; + pos2[dir] += sign*bw[dir]; + fc = getDifferenceFromContour( pos2, faked ); + if( fc*fb<0 ) { + break; + } } dirv2[dir] = ( pos1[dir] + dirv[dir] ) - pos2[dir]; } @@ -178,11 +215,17 @@ void DistanceFromContour::calculate() { // Now do a search for the two contours findContour( dirv, pos1 ); // Save the first value - Vector root1; root1.zero(); root1[dir] = pval[dir]; + Vector root1; + root1.zero(); + root1[dir] = pval[dir]; findContour( dirv2, pos2 ); // Calculate the separation between the two roots using PBC - Vector root2; root2.zero(); root2[dir] = pval[dir]; - Vector sep = pbcDistance( root1, root2 ); double spacing = fabs( sep[dir] ); plumed_assert( spacing>epsilon ); + Vector root2; + root2.zero(); + root2[dir] = pval[dir]; + Vector sep = pbcDistance( root1, root2 ); + double spacing = fabs( sep[dir] ); + plumed_assert( spacing>epsilon ); getPntrToComponent("thickness")->set( spacing ); // Make sure the sign is right @@ -203,15 +246,22 @@ void DistanceFromContour::calculate() { // Now calculate the derivatives if( !doNotCalculateDerivatives() ) { - evaluateDerivatives( root1, root2[dir] ); evaluateDerivatives( root2, root1[dir] ); + evaluateDerivatives( root1, root2[dir] ); + evaluateDerivatives( root2, root1[dir] ); } } void DistanceFromContour::evaluateDerivatives( const Vector& root1, const double& root2 ) { - if( getNumberOfArguments()>0 ) plumed_merror("derivatives for phase field distance from contour have not been implemented yet"); + if( getNumberOfArguments()>0 ) { + plumed_merror("derivatives for phase field distance from contour have not been implemented yet"); + } - Vector origind; origind.zero(); Tensor vir; vir.zero(); - double sumd = 0; std::vector pp(3), ddd(3,0); + Vector origind; + origind.zero(); + Tensor vir; + vir.zero(); + double sumd = 0; + std::vector pp(3), ddd(3,0); for(unsigned i=0; iaddDerivative( 3*active_list[i] + 0, -prefactor*atom_deriv[i][0] ); val->addDerivative( 3*active_list[i] + 1, -prefactor*atom_deriv[i][1] ); @@ -234,12 +288,19 @@ void DistanceFromContour::evaluateDerivatives( const Vector& root1, const double // Add derivatives to atoms at origin unsigned nbase = 3*(getNumberOfAtoms()-1); - val->addDerivative( nbase, -prefactor*origind[0] ); nbase++; - val->addDerivative( nbase, -prefactor*origind[1] ); nbase++; - val->addDerivative( nbase, -prefactor*origind[2] ); nbase++; + val->addDerivative( nbase, -prefactor*origind[0] ); + nbase++; + val->addDerivative( nbase, -prefactor*origind[1] ); + nbase++; + val->addDerivative( nbase, -prefactor*origind[2] ); + nbase++; // Add derivatives to virial - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) { val->addDerivative( nbase, -prefactor*vir(i,j) ); nbase++; } + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + val->addDerivative( nbase, -prefactor*vir(i,j) ); + nbase++; + } } } diff --git a/src/contour/DistanceFromContourBase.cpp b/src/contour/DistanceFromContourBase.cpp index 6444830865..c4ef6df28f 100644 --- a/src/contour/DistanceFromContourBase.cpp +++ b/src/contour/DistanceFromContourBase.cpp @@ -25,9 +25,12 @@ namespace PLMD { namespace contour { void DistanceFromContourBase::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); - ActionAtomistic::registerKeywords( keys ); ActionWithArguments::registerKeywords( keys ); - keys.remove("NUMERICAL_DERIVATIVES"); keys.use("ARG"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionAtomistic::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.remove("NUMERICAL_DERIVATIVES"); + keys.use("ARG"); keys.add("atoms","POSITIONS","the positions of the atoms that we are calculating the contour from"); keys.add("atoms","ATOM","The atom whose perpendicular distance we are calculating from the contour"); keys.add("compulsory","BANDWIDTH","the bandwidths for kernel density esimtation"); @@ -43,55 +46,92 @@ DistanceFromContourBase::DistanceFromContourBase( const ActionOptions& ao ): ActionAtomistic(ao), ActionWithArguments(ao), mymin(this), - nactive(0) -{ - if( getNumberOfArguments()>1 ) error("should only use one argument for this action"); + nactive(0) { + if( getNumberOfArguments()>1 ) { + error("should only use one argument for this action"); + } if( getNumberOfArguments()==1 ) { - if( getPntrToArgument(0)->getRank()!=1 ) error("ARG for distance from contour should be rank one"); + if( getPntrToArgument(0)->getRank()!=1 ) { + error("ARG for distance from contour should be rank one"); + } getPntrToArgument(0)->buildDataStore(); } // Read in the multicolvar/atoms - std::vector atoms; parseAtomList("POSITIONS",atoms); - std::vector origin; parseAtomList("ATOM",origin); - if( origin.size()!=1 ) error("should only specify one atom for origin keyword"); + std::vector atoms; + parseAtomList("POSITIONS",atoms); + std::vector origin; + parseAtomList("ATOM",origin); + if( origin.size()!=1 ) { + error("should only specify one atom for origin keyword"); + } std::vector center; if( keywords.exists("ORIGIN") ) { parseAtomList("ORIGIN",center); - if( center.size()!=1 ) error("should only specify one atom for center keyword"); + if( center.size()!=1 ) { + error("should only specify one atom for center keyword"); + } } - if( center.size()==1 ) log.printf(" calculating distance between atom %d and contour along vector connecting it to atom %d \n", origin[0].serial(),center[0].serial() ); - else log.printf(" calculating distance between atom %d and contour \n", origin[0].serial() ); + if( center.size()==1 ) { + log.printf(" calculating distance between atom %d and contour along vector connecting it to atom %d \n", origin[0].serial(),center[0].serial() ); + } else { + log.printf(" calculating distance between atom %d and contour \n", origin[0].serial() ); + } log.printf(" contour is in field constructed from positions of atoms : "); - for(unsigned i=0; igetShape()[0]!=atoms.size() ) error("mismatch between number of atoms and size of vector specified using ARG keyword"); + if( getPntrToArgument(0)->getShape()[0]!=atoms.size() ) { + error("mismatch between number of atoms and size of vector specified using ARG keyword"); + } log.printf("\n and weights from %s \n", getPntrToArgument(0)->getName().c_str() ); } else { log.printf("\n all weights are set equal to one \n"); } // Request everything we need active_list.resize( atoms.size(), 0 ); - std::vector args( getArguments() ); atoms.push_back( origin[0] ); - if( center.size()==1 ) atoms.push_back( center[0] ); - requestArguments( args ); requestAtoms( atoms ); + std::vector args( getArguments() ); + atoms.push_back( origin[0] ); + if( center.size()==1 ) { + atoms.push_back( center[0] ); + } + requestArguments( args ); + requestAtoms( atoms ); // Fix to request arguments - if( args.size()==1 ) addDependency( args[0]->getPntrToAction() ); + if( args.size()==1 ) { + addDependency( args[0]->getPntrToAction() ); + } // Read in details of phase field construction - parseVector("BANDWIDTH",bw); parse("KERNEL",kerneltype); parse("CONTOUR",contour); - std::string errors; switchingFunction.set( kerneltype + " R_0=1.0 NOSTRETCH", errors ); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); - double det=1; for(unsigned i=0; i pp( bw.size(),0 ); - double dp2cutoff; parse("CUTOFF",dp2cutoff); double rcut = sqrt(2*dp2cutoff)*bw[0]; + double dp2cutoff; + parse("CUTOFF",dp2cutoff); + double rcut = sqrt(2*dp2cutoff)*bw[0]; for(unsigned j=1; jrcut ) rcut=sqrt(2*dp2cutoff)*bw[j]; + if( sqrt(2*dp2cutoff)*bw[j]>rcut ) { + rcut=sqrt(2*dp2cutoff)*bw[j]; + } } rcut2=rcut*rcut; @@ -112,33 +152,52 @@ void DistanceFromContourBase::unlockRequests() { double DistanceFromContourBase::evaluateKernel( const Vector& cpos, const Vector& apos, std::vector& der ) const { Vector distance = pbcDistance( getPosition(getNumberOfAtoms()-1), cpos ); Vector dist2 = pbcDistance( distance, apos ); - double dval=0; for(unsigned j=0; j<3; ++j) { der[j] = dist2[j]/bw[j]; dval += der[j]*der[j]; } + double dval=0; + for(unsigned j=0; j<3; ++j) { + der[j] = dist2[j]/bw[j]; + dval += der[j]*der[j]; + } double dfunc, newval = switchingFunction.calculateSqr( dval, dfunc ) / gvol; - double tmp = dfunc / gvol; for(unsigned j=0; j<3; ++j) der[j] *= -tmp; + double tmp = dfunc / gvol; + for(unsigned j=0; j<3; ++j) { + der[j] *= -tmp; + } return newval; } double DistanceFromContourBase::getDifferenceFromContour( const std::vector& x, std::vector& der ) { // Transer the position to the local Vector - for(unsigned j=0; j<3; ++j) pval[j] = x[j]; + for(unsigned j=0; j<3; ++j) { + pval[j] = x[j]; + } // Now find the contour - double sumk = 0, sumd = 0; std::vector pp(3), ddd(3,0); + double sumk = 0, sumd = 0; + std::vector pp(3), ddd(3,0); for(unsigned i=0; iget(active_list[i])*newval; sumd += newval; - } else sumk += newval; + } else { + sumk += newval; + } + } + if( getNumberOfArguments()==0 ) { + return sumk - contour; + } + if( fabs(sumk) mymin; @@ -58,14 +57,18 @@ class DistanceFromContourBase : unsigned getNumberOfDerivatives() override ; void lockRequests(); void unlockRequests(); - void calculateNumericalDerivatives( ActionWithValue* a ) { plumed_merror("numerical derivatives are not implemented for this action"); } + void calculateNumericalDerivatives( ActionWithValue* a ) { + plumed_merror("numerical derivatives are not implemented for this action"); + } double getDifferenceFromContour( const std::vector& x, std::vector& der ); void apply(); }; inline unsigned DistanceFromContourBase::getNumberOfDerivatives() { - if( getNumberOfArguments()==1 ) return 4*getNumberOfAtoms() + 8; // One derivative for each weight hence four times the number of atoms - 1 + if( getNumberOfArguments()==1 ) { + return 4*getNumberOfAtoms() + 8; // One derivative for each weight hence four times the number of atoms - 1 + } return 3*getNumberOfAtoms() + 9; } diff --git a/src/contour/DistanceFromSphericalContour.cpp b/src/contour/DistanceFromSphericalContour.cpp index 97997d80c1..83c07d6c6d 100644 --- a/src/contour/DistanceFromSphericalContour.cpp +++ b/src/contour/DistanceFromSphericalContour.cpp @@ -53,40 +53,59 @@ void DistanceFromSphericalContour::registerKeywords( Keywords& keys ) { DistanceFromSphericalContour::DistanceFromSphericalContour( const ActionOptions& ao ): Action(ao), - DistanceFromContourBase(ao) -{ + DistanceFromContourBase(ao) { // Create the values std::vector shape; - addComponentWithDerivatives("dist", shape ); componentIsNotPeriodic("dist"); - addComponent("radius", shape ); componentIsNotPeriodic("radius"); + addComponentWithDerivatives("dist", shape ); + componentIsNotPeriodic("dist"); + addComponent("radius", shape ); + componentIsNotPeriodic("radius"); } void DistanceFromSphericalContour::calculate() { // Check box is orthorhombic - if( !getPbc().isOrthorombic() ) error("cell box must be orthorhombic"); + if( !getPbc().isOrthorombic() ) { + error("cell box must be orthorhombic"); + } // Calculate the director of the vector connecting the center of the sphere to the molecule of interest Vector dirv = pbcDistance( getPosition(getNumberOfAtoms()-1), getPosition(getNumberOfAtoms()-2) ); - double len=dirv.modulo(); dirv /= len; + double len=dirv.modulo(); + dirv /= len; // Now work out which atoms need to be considered explicitly Vector myvec = pbcDistance( getPosition(getNumberOfAtoms()-1), getPosition(0) ); - nactive=1; active_list[0]=0; + nactive=1; + active_list[0]=0; for(unsigned j=1; jget(j)get(j) pos1(3), dirv2(3); - for(unsigned k=0; k<3; ++k) { dirv2[k]=hbox*dirv[k]; pos1[k]=0; } + for(unsigned k=0; k<3; ++k) { + dirv2[k]=hbox*dirv[k]; + pos1[k]=0; + } // Now do a search for the contours findContour( dirv2, pos1 ); // Now find the distance between the center of the sphere and the contour @@ -97,7 +116,9 @@ void DistanceFromSphericalContour::calculate() { getPntrToComponent("dist")->set( len - rad ); // Now calculate the derivatives - if( !doNotCalculateDerivatives() ) plumed_merror("derivatives not implemented"); + if( !doNotCalculateDerivatives() ) { + plumed_merror("derivatives not implemented"); + } } void DistanceFromSphericalContour::evaluateDerivatives( const Vector& root1, const double& root2 ) { diff --git a/src/contour/DumpContour.cpp b/src/contour/DumpContour.cpp index 3377f38f45..60ac7b557c 100644 --- a/src/contour/DumpContour.cpp +++ b/src/contour/DumpContour.cpp @@ -57,7 +57,8 @@ PLUMED_REGISTER_ACTION(DumpContour,"DUMPCONTOUR") void DumpContour::registerKeywords( Keywords& keys ) { Action::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.use("ARG"); + ActionWithArguments::registerKeywords( keys ); + keys.use("ARG"); keys.add("compulsory","STRIDE","1","the frequency with which the grid should be output to the file."); keys.add("compulsory","FILE","density","the file on which to write the grid."); keys.add("optional","FMT","the format that should be used to output real numbers"); @@ -67,33 +68,51 @@ DumpContour::DumpContour(const ActionOptions&ao): Action(ao), ActionWithArguments(ao), ActionPilot(ao), - fmt("%f") -{ - if( getNumberOfArguments()!=1 ) error("should only be one argument"); + fmt("%f") { + if( getNumberOfArguments()!=1 ) { + error("should only be one argument"); + } FindContour* fc=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); - if( !fc ) error("can only use this action to print data from FIND_CONTOUR actions"); + if( !fc ) { + error("can only use this action to print data from FIND_CONTOUR actions"); + } parse("FILE",filename); - if(filename.length()==0) error("name out output file was not specified"); + if(filename.length()==0) { + error("name out output file was not specified"); + } log.printf(" outputting contour with label %s to file named %s",getPntrToArgument(0)->getName().c_str(), filename.c_str() ); - parse("FMT",fmt); log.printf(" with format %s \n", fmt.c_str() ); fmt = " " + fmt; + parse("FMT",fmt); + log.printf(" with format %s \n", fmt.c_str() ); + fmt = " " + fmt; } void DumpContour::update() { - OFile ofile; ofile.link(*this); + OFile ofile; + ofile.link(*this); ofile.setBackupString("analysis"); ofile.open( filename ); FindContour* fc=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); unsigned maxp = fc->active_cells.size(), ncomp = fc->getNumberOfComponents(); - unsigned ntasks = 0; for(unsigned i=0; iactive_cells[i]; + unsigned ntasks = 0; + for(unsigned i=0; iactive_cells[i]; + } - ofile.printf("%d\n", ntasks ); ofile.printf("Points found on isocontour\n"); + ofile.printf("%d\n", ntasks ); + ofile.printf("Points found on isocontour\n"); for(unsigned i=0; iactive_cells[i]==0 ) continue ; - const char* defname="X"; const char* name=defname; ofile.printf("%s", name); - for(unsigned j=0; jcopyOutput(j))->get(i) ); + if( fc->active_cells[i]==0 ) { + continue ; + } + const char* defname="X"; + const char* name=defname; + ofile.printf("%s", name); + for(unsigned j=0; jcopyOutput(j))->get(i) ); + } ofile.printf("\n"); } } diff --git a/src/contour/FindContour.cpp b/src/contour/FindContour.cpp index 0f5b8117e9..7aa21d551e 100644 --- a/src/contour/FindContour.cpp +++ b/src/contour/FindContour.cpp @@ -92,25 +92,30 @@ namespace contour { PLUMED_REGISTER_ACTION(FindContour,"FIND_CONTOUR") void FindContour::registerKeywords( Keywords& keys ) { - ContourFindingBase::registerKeywords( keys ); ActionWithValue::useCustomisableComponents(keys); + ContourFindingBase::registerKeywords( keys ); + ActionWithValue::useCustomisableComponents(keys); // We want a better way of doing this bit keys.add("compulsory","BUFFER","0","number of buffer grid points around location where grid was found on last step. If this is zero the full grid is calculated on each step"); } FindContour::FindContour(const ActionOptions&ao): Action(ao), - ContourFindingBase(ao) -{ + ContourFindingBase(ao) { parse("BUFFER",gbuffer); - if( gbuffer>0 ) log.printf(" after first step a subset of only %u grid points around where the countour was found will be checked\n",gbuffer); + if( gbuffer>0 ) { + log.printf(" after first step a subset of only %u grid points around where the countour was found will be checked\n",gbuffer); + } checkRead(); gridtools::ActionWithGrid* ag=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); std::vector argn( ag->getGridCoordinateNames() ); - std::vector shape(1); shape[0]=0; + std::vector shape(1); + shape[0]=0; for(unsigned i=0; ibuildDataStore(); + addComponent( argn[i], shape ); + componentIsNotPeriodic( argn[i] ); + getPntrToComponent(i)->buildDataStore(); } // Check for task reduction updateTaskListReductionStatus(); @@ -121,8 +126,11 @@ std::string FindContour::getOutputComponentDescription( const std::string& cname } void FindContour::setupValuesOnFirstStep() { - std::vector shape(1); shape[0] = getPntrToArgument(0)->getRank()*getPntrToArgument(0)->getNumberOfValues(); - for(unsigned i=0; isetShape( shape ); + std::vector shape(1); + shape[0] = getPntrToArgument(0)->getRank()*getPntrToArgument(0)->getNumberOfValues(); + for(unsigned i=0; isetShape( shape ); + } active_cells.resize( shape[0] ); } @@ -142,7 +150,8 @@ void FindContour::getNumberOfTasks( unsigned& ntasks ) { std::vector ind( gval->getRank() ); std::vector ones( gval->getRank(), 1 ); std::vector nbin( getInputGridObject().getNbin( false ) ); - unsigned num_neighbours; std::vector neighbours; + unsigned num_neighbours; + std::vector neighbours; std::fill( active_cells.begin(), active_cells.end(), 0 ); for(unsigned i=0; igetRank(); ++j) { // Make sure we don't search at the edge of the grid - if( !getInputGridObject().isPeriodic(j) && (ind[j]+1)==nbin[j] ) continue; - else if( (ind[j]+1)==nbin[j] ) { edge=true; ind[j]=0; } - else ind[j]+=1; + if( !getInputGridObject().isPeriodic(j) && (ind[j]+1)==nbin[j] ) { + continue; + } else if( (ind[j]+1)==nbin[j] ) { + edge=true; + ind[j]=0; + } else { + ind[j]+=1; + } double val2=gval->get( getInputGridObject().getIndex(ind) ) - contour; - if( val1*val2<0 ) active_cells[gval->getRank()*i + j] = 1; - if( getInputGridObject().isPeriodic(j) && edge ) { edge=false; ind[j]=nbin[j]-1; } - else ind[j]-=1; + if( val1*val2<0 ) { + active_cells[gval->getRank()*i + j] = 1; + } + if( getInputGridObject().isPeriodic(j) && edge ) { + edge=false; + ind[j]=nbin[j]-1; + } else { + ind[j]-=1; + } } } } int FindContour::checkTaskStatus( const unsigned& taskno, int& flag ) const { - if( active_cells[taskno]>0 ) return 1; + if( active_cells[taskno]>0 ) { + return 1; + } return 0; } @@ -184,7 +206,9 @@ void FindContour::performTask( const unsigned& current, MultiValue& myvals ) con // Now find the contour findContour( direction, point ); // And transfer to the store data vessel - for(unsigned i=0; igetRank(); ++i) myvals.setValue( getConstPntrToComponent(i)->getPositionInStream(), point[i] ); + for(unsigned i=0; igetRank(); ++i) { + myvals.setValue( getConstPntrToComponent(i)->getPositionInStream(), point[i] ); + } } } diff --git a/src/contour/FindContour.h b/src/contour/FindContour.h index 68f2b4f3ee..107a42cf85 100644 --- a/src/contour/FindContour.h +++ b/src/contour/FindContour.h @@ -41,8 +41,12 @@ class FindContour : public ContourFindingBase { void areAllTasksRequired( std::vector& task_reducing_actions ) override ; void getNumberOfTasks( unsigned& ntasks ) override ; int checkTaskStatus( const unsigned& taskno, int& flag ) const override ; - std::vector getGridCoordinateNames() const override { plumed_error(); } - const gridtools::GridCoordinatesObject& getGridCoordinatesObject() const override { plumed_error(); } + std::vector getGridCoordinateNames() const override { + plumed_error(); + } + const gridtools::GridCoordinatesObject& getGridCoordinatesObject() const override { + plumed_error(); + } void performTask( const unsigned& current, MultiValue& myvals ) const override; }; diff --git a/src/contour/FindContourSurface.cpp b/src/contour/FindContourSurface.cpp index 1a1d1eb28c..4cc3f5cd47 100644 --- a/src/contour/FindContourSurface.cpp +++ b/src/contour/FindContourSurface.cpp @@ -116,47 +116,66 @@ void FindContourSurface::registerKeywords( Keywords& keys ) { FindContourSurface::FindContourSurface(const ActionOptions&ao): Action(ao), ContourFindingBase(ao), - ones(getPntrToArgument(0)->getRank(),1) -{ - if( getPntrToArgument(0)->getRank()<2 ) error("cannot find dividing surface if input grid is one dimensional"); + ones(getPntrToArgument(0)->getRank(),1) { + if( getPntrToArgument(0)->getRank()<2 ) { + error("cannot find dividing surface if input grid is one dimensional"); + } - std::string dir; parse("SEARCHDIR",dir); + std::string dir; + parse("SEARCHDIR",dir); log.printf(" calculating location of contour on %d dimensional grid \n", getPntrToArgument(0)->getRank()-1 ); checkRead(); - Value* gval=getPntrToArgument(0); unsigned n=0; - gdirs.resize( gval->getRank()-1 ); gnames.resize( getPntrToArgument(0)->getRank()-1 ); + Value* gval=getPntrToArgument(0); + unsigned n=0; + gdirs.resize( gval->getRank()-1 ); + gnames.resize( getPntrToArgument(0)->getRank()-1 ); gridtools::ActionWithGrid* ag=dynamic_cast( gval->getPntrToAction() ); - if( !ag ) error("input argument must be a grid"); - if( getInputGridObject().getGridType()=="fibonacci") error("cannot search for contours in fibonacci grids"); + if( !ag ) { + error("input argument must be a grid"); + } + if( getInputGridObject().getGridType()=="fibonacci") { + error("cannot search for contours in fibonacci grids"); + } std::vector argn( ag->getGridCoordinateNames() ); for(unsigned i=0; igetRank(); ++i) { if( argn[i]==dir ) { dir_n=i; } else { - if( n==gdirs.size() ) error("could not find " + dir + " direction in input grid"); - gdirs[n]=i; gnames[n]=argn[i]; n++; + if( n==gdirs.size() ) { + error("could not find " + dir + " direction in input grid"); + } + gdirs[n]=i; + gnames[n]=argn[i]; + n++; } } - if( n!=(gval->getRank()-1) ) error("output of grid is not understood"); + if( n!=(gval->getRank()-1) ) { + error("output of grid is not understood"); + } std::vector ipbc( getInputGridObject().getDimension()-1 ); - for(unsigned i=0; i shape( getInputGridObject().getDimension()-1 ); - addValueWithDerivatives( shape ); setNotPeriodic(); + addValueWithDerivatives( shape ); + setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); } void FindContourSurface::setupValuesOnFirstStep() { - std::vector fspacing; std::vector snbins( gridcoords.getDimension() ); + std::vector fspacing; + std::vector snbins( gridcoords.getDimension() ); std::vector smin( gridcoords.getDimension() ), smax( gridcoords.getDimension() ); for(unsigned i=0; i find( gridcoords.getDimension() ); std::vector ind( gridcoords.getDimension() ); for(unsigned i=0; i neighbours; unsigned num_neighbours; unsigned nfound=0; double minv=0, minp; - std::vector bins_n( getInputGridObject().getNbin(false) ); unsigned shiftn=current; - std::vector ind( getInputGridObject().getDimension() ); std::vector point( getInputGridObject().getDimension() ); + std::vector neighbours; + unsigned num_neighbours; + unsigned nfound=0; + double minv=0, minp; + std::vector bins_n( getInputGridObject().getNbin(false) ); + unsigned shiftn=current; + std::vector ind( getInputGridObject().getDimension() ); + std::vector point( getInputGridObject().getDimension() ); #ifndef DNDEBUG - std::vector oind( gridcoords.getDimension() ); gridcoords.getIndices( current, oind ); + std::vector oind( gridcoords.getDimension() ); + gridcoords.getIndices( current, oind ); #endif for(unsigned i=0; i base_ind( getInputGridObject().getDimension() ); getInputGridObject().getIndices( shiftn, base_ind ); - for(unsigned j=0; j base_ind( getInputGridObject().getDimension() ); + getInputGridObject().getIndices( shiftn, base_ind ); + for(unsigned j=0; jget( shiftn ) - contour; double val2; - if( (ind[dir_n]+1)==bins_n[dir_n] ) val2 = getPntrToArgument(0)->get( current ) - contour; - else val2=getPntrToArgument(0)->get( shiftn + getInputGridObject().getStride()[dir_n] ) - contour; + double val1=getPntrToArgument(0)->get( shiftn ) - contour; + double val2; + if( (ind[dir_n]+1)==bins_n[dir_n] ) { + val2 = getPntrToArgument(0)->get( current ) - contour; + } else { + val2=getPntrToArgument(0)->get( shiftn + getInputGridObject().getStride()[dir_n] ) - contour; + } // Check if the minimum is bracketed if( val1*val2<0 ) { - getInputGridObject().getGridPointCoordinates( shiftn, point ); findContour( direction, point ); - minp=point[dir_n]; nfound++; break; + getInputGridObject().getGridPointCoordinates( shiftn, point ); + findContour( direction, point ); + minp=point[dir_n]; + nfound++; + break; } // This moves us on to the next point shiftn += getInputGridObject().getStride()[dir_n]; } if( nfound==0 ) { - std::string num; Tools::convert( getStep(), num ); + std::string num; + Tools::convert( getStep(), num ); error("On step " + num + " failed to find required grid point"); } myvals.setValue( getConstPntrToComponent(0)->getPositionInStream(), minp ); @@ -231,8 +271,10 @@ void FindContourSurface::performTask( const unsigned& current, MultiValue& myval void FindContourSurface::gatherStoredValue( const unsigned& valindex, const unsigned& code, const MultiValue& myvals, const unsigned& bufstart, std::vector& buffer ) const { - plumed_dbg_assert( valindex==0 ); unsigned istart = bufstart + (1+gridcoords.getDimension())*code; - unsigned valout = getConstPntrToComponent(0)->getPositionInStream(); buffer[istart] += myvals.get( valout ); + plumed_dbg_assert( valindex==0 ); + unsigned istart = bufstart + (1+gridcoords.getDimension())*code; + unsigned valout = getConstPntrToComponent(0)->getPositionInStream(); + buffer[istart] += myvals.get( valout ); } } diff --git a/src/contour/FindSphericalContour.cpp b/src/contour/FindSphericalContour.cpp index c4d731bae9..0514f3994e 100644 --- a/src/contour/FindSphericalContour.cpp +++ b/src/contour/FindSphericalContour.cpp @@ -138,20 +138,29 @@ void FindSphericalContour::registerKeywords( Keywords& keys ) { FindSphericalContour::FindSphericalContour(const ActionOptions&ao): Action(ao), - ContourFindingBase(ao) -{ - if( getPntrToArgument(0)->getRank()!=3 ) error("input grid must be three dimensional"); + ContourFindingBase(ao) { + if( getPntrToArgument(0)->getRank()!=3 ) { + error("input grid must be three dimensional"); + } - parse("NPOINTS",npoints); log.printf(" searching for %u points on dividing surface \n",npoints); - parse("INNER_RADIUS",min); parse("OUTER_RADIUS",max); parse("NBINS",nbins); + parse("NPOINTS",npoints); + log.printf(" searching for %u points on dividing surface \n",npoints); + parse("INNER_RADIUS",min); + parse("OUTER_RADIUS",max); + parse("NBINS",nbins); log.printf(" expecting to find dividing surface at radii between %f and %f \n",min,max); log.printf(" looking for contour in windows of length %f \n", (max-min)/nbins); // Set this here so the same set of grid points are used on every turn - std::vector ipbc( 3, false ); gridcoords.setup( "fibonacci", ipbc, npoints, 0.0 ); + std::vector ipbc( 3, false ); + gridcoords.setup( "fibonacci", ipbc, npoints, 0.0 ); // Now create a value - std::vector shape( 3 ); shape[0]=npoints; shape[1]=shape[2]=1; - addValueWithDerivatives( shape ); setNotPeriodic(); - getPntrToComponent(0)->buildDataStore(); checkRead(); + std::vector shape( 3 ); + shape[0]=npoints; + shape[1]=shape[2]=1; + addValueWithDerivatives( shape ); + setNotPeriodic(); + getPntrToComponent(0)->buildDataStore(); + checkRead(); } unsigned FindSphericalContour::getNumberOfDerivatives() { @@ -160,7 +169,8 @@ unsigned FindSphericalContour::getNumberOfDerivatives() { std::vector FindSphericalContour::getGridCoordinateNames() const { gridtools::ActionWithGrid* ag=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); - plumed_assert( ag ); return ag->getGridCoordinateNames(); + plumed_assert( ag ); + return ag->getGridCoordinateNames(); } const gridtools::GridCoordinatesObject& FindSphericalContour::getGridCoordinatesObject() const { @@ -180,23 +190,36 @@ void FindSphericalContour::performTask( const unsigned& current, MultiValue& myv bool found=false; for(unsigned k=0; kgetPositionInStream(), sqrt(norm) ); found=true; break; + double norm=0; + for(unsigned j=0; j<3; ++j) { + norm += contour_point[j]*contour_point[j]; + } + myvals.setValue( getConstPntrToComponent(0)->getPositionInStream(), sqrt(norm) ); + found=true; + break; } - for(unsigned j=0; j<3; ++j) contour_point[j] = tmp[j]; + for(unsigned j=0; j<3; ++j) { + contour_point[j] = tmp[j]; + } + } + if( !found ) { + error("range does not bracket the dividing surface"); } - if( !found ) error("range does not bracket the dividing surface"); } void FindSphericalContour::gatherStoredValue( const unsigned& valindex, const unsigned& code, const MultiValue& myvals, const unsigned& bufstart, std::vector& buffer ) const { - plumed_assert( valindex==0 ); unsigned istart = bufstart + (1+gridcoords.getDimension())*code; - unsigned valout = getConstPntrToComponent(0)->getPositionInStream(); buffer[istart] += myvals.get( valout ); + plumed_assert( valindex==0 ); + unsigned istart = bufstart + (1+gridcoords.getDimension())*code; + unsigned valout = getConstPntrToComponent(0)->getPositionInStream(); + buffer[istart] += myvals.get( valout ); } } diff --git a/src/core/Action.cpp b/src/core/Action.cpp index 0e1e24c8a4..8a463b82e6 100644 --- a/src/core/Action.cpp +++ b/src/core/Action.cpp @@ -43,15 +43,13 @@ Keywords ActionOptions::emptyKeys; ActionOptions::ActionOptions(PlumedMain&p,const std::vector&l): plumed(p), line(l), - keys(emptyKeys) -{ + keys(emptyKeys) { } ActionOptions::ActionOptions(const ActionOptions&ao,const Keywords&keys): plumed(ao.plumed), line(ao.line), - keys(keys) -{ + keys(keys) { } void Action::registerKeywords( Keywords& keys ) { @@ -76,15 +74,16 @@ Action::Action(const ActionOptions&ao): log(plumed.getLog()), comm(plumed.comm), multi_sim_comm(plumed.multi_sim_comm), - keywords(ao.keys) -{ + keywords(ao.keys) { // Retrieve the timestep and save it resetStoredTimestep(); line.erase(line.begin()); if( !keywords.exists("NO_ACTION_LOG") ) { log.printf("Action %s\n",name.c_str()); - if(ao.fullPath.length()>0) log<<" from library: "<0) { + log<<" from library: "<().size(),s); + std::string s; + Tools::convert(plumed.getActionSet().size()-plumed.getActionSet().select().size(),s); label="@"+s; - } else if ( label.find(".")!=std::string::npos ) warning("using full stop in an action label should be avaoided as . has a special meaning in PLUMED action labels"); - if( plumed.getActionSet().selectWithLabel(label) ) error("label " + label + " has been already used"); - if( !keywords.exists("NO_ACTION_LOG") ) log.printf(" with label %s\n",label.c_str()); - if ( keywords.exists("UPDATE_FROM") ) parse("UPDATE_FROM",update_from); - if( !keywords.exists("NO_ACTION_LOG") && update_from!=std::numeric_limits::max()) log.printf(" only update from time %f\n",update_from); - if ( keywords.exists("UPDATE_UNTIL") ) parse("UPDATE_UNTIL",update_until); - if( !keywords.exists("NO_ACTION_LOG") && update_until!=std::numeric_limits::max()) log.printf(" only update until time %f\n",update_until); + } else if ( label.find(".")!=std::string::npos ) { + warning("using full stop in an action label should be avaoided as . has a special meaning in PLUMED action labels"); + } + if( plumed.getActionSet().selectWithLabel(label) ) { + error("label " + label + " has been already used"); + } + if( !keywords.exists("NO_ACTION_LOG") ) { + log.printf(" with label %s\n",label.c_str()); + } + if ( keywords.exists("UPDATE_FROM") ) { + parse("UPDATE_FROM",update_from); + } + if( !keywords.exists("NO_ACTION_LOG") && update_from!=std::numeric_limits::max()) { + log.printf(" only update from time %f\n",update_from); + } + if ( keywords.exists("UPDATE_UNTIL") ) { + parse("UPDATE_UNTIL",update_until); + } + if( !keywords.exists("NO_ACTION_LOG") && update_until!=std::numeric_limits::max()) { + log.printf(" only update until time %f\n",update_until); + } if ( keywords.exists("RESTART") ) { std::string srestart="AUTO"; parse("RESTART",srestart); - if( plumed.parseOnlyMode() ) restart=false; - else if(srestart=="YES") restart=true; - else if(srestart=="NO") restart=false; - else if(srestart=="AUTO") { + if( plumed.parseOnlyMode() ) { + restart=false; + } else if(srestart=="YES") { + restart=true; + } else if(srestart=="NO") { + restart=false; + } else if(srestart=="AUTO") { // do nothing, this is the default - } else error("RESTART should be either YES, NO, or AUTO"); + } else { + error("RESTART should be either YES, NO, or AUTO"); + } } } void Action::resetStoredTimestep() { ActionWithValue* ts = plumed.getActionSet().selectWithLabel("timestep"); - if( ts ) timestep = (ts->copyOutput(0))->get(); + if( ts ) { + timestep = (ts->copyOutput(0))->get(); + } } Action::~Action() { @@ -128,10 +151,16 @@ Action::~Action() { FILE* Action::fopen(const char *path, const char *mode) { bool write(false); - for(const char*p=mode; *p; p++) if(*p=='w' || *p=='a' || *p=='+') write=true; + for(const char*p=mode; *p; p++) + if(*p=='w' || *p=='a' || *p=='+') { + write=true; + } FILE* fp; - if(write && comm.Get_rank()!=0) fp=plumed.fopen("/dev/null",mode); - else fp=plumed.fopen(path,mode); + if(write && comm.Get_rank()!=0) { + fp=plumed.fopen("/dev/null",mode); + } else { + fp=plumed.fopen(path,mode); + } files.insert(fp); return fp; } @@ -152,11 +181,15 @@ std::string Action::getKeyword(const std::string& key) { plumed_massert(keywords.exists(key), "keyword " + key + " has not been registered"); std::string outkey; - if( Tools::getKey(line,key,outkey ) ) return key + outkey; + if( Tools::getKey(line,key,outkey ) ) { + return key + outkey; + } if( keywords.style(key,"compulsory") ) { if( keywords.getDefaultValue(key,outkey) ) { - if( outkey.length()==0 ) error("keyword " + key + " has weird default value"); + if( outkey.length()==0 ) { + error("keyword " + key + " has weird default value"); + } return key + "=" + outkey; } else { error("keyword " + key + " is compulsory for this action"); @@ -187,22 +220,33 @@ void Action::parseFlag(const std::string&key,bool & t) { void Action::addDependency(Action*action) { bool found=false; for(const auto & d : after ) { - if( action==d ) { found=true; break; } + if( action==d ) { + found=true; + break; + } + } + if( !found ) { + after.push_back(action); } - if( !found ) after.push_back(action); } bool Action::checkForDependency( Action* action ) { for(const auto & d : after) { - if( action==d ) { return true; } - if( d->checkForDependency(action) ) { return true; } + if( action==d ) { + return true; + } + if( d->checkForDependency(action) ) { + return true; + } } return false; } void Action::activate() { // This is set to true if actions are only need to be computed in setup (during checkRead) - if( never_activate ) return; + if( never_activate ) { + return; + } // preparation step is called only the first time an Action is activated. // since it could change its dependences (e.g. in an ActionAtomistic which is // accessing to a virtual atom), this is done just before dependencies are @@ -211,15 +255,21 @@ void Action::activate() { this->unlockRequests(); prepare(); this->lockRequests(); - } else return; - for(const auto & p : after) p->activate(); + } else { + return; + } + for(const auto & p : after) { + p->activate(); + } active=true; } void Action::setOption(const std::string &s) { // This overloads the action and activate some options options.insert(s); - for(const auto & p : after) p->setOption(s); + for(const auto & p : after) { + p->setOption(s); + } } void Action::clearOptions() { @@ -236,7 +286,9 @@ void Action::checkRead() { if(!line.empty()) { std::string msg="cannot understand the following words from the input line : "; for(unsigned i=0; i0) msg = msg + ", "; + if(i>0) { + msg = msg + ", "; + } msg = msg + line[i]; } error(msg); @@ -253,12 +305,17 @@ void Action::setupConstantValues( const bool& have_atoms ) { if( at && av ) { never_activate=av->getNumberOfComponents()>0; for(unsigned i=0; igetNumberOfComponents(); ++i) { - if( !av->copyOutput(i)->isConstant() ) { never_activate=false; break; } + if( !av->copyOutput(i)->isConstant() ) { + never_activate=false; + break; + } } } } ActionWithArguments* aa = castToActionWithArguments(); - if( aa && aa->getNumberOfArguments()>0 && getName()!="BIASVALUE" ) never_activate = aa->calculateConstantValues( have_atoms ); + if( aa && aa->getNumberOfArguments()>0 && getName()!="BIASVALUE" ) { + never_activate = aa->calculateConstantValues( have_atoms ); + } } long long int Action::getStep()const { @@ -275,14 +332,23 @@ double Action::getTimeStep()const { double Action::getkBT() { double temp=-1.0; - if( keywords.exists("TEMP") ) parse("TEMP",temp); - if(temp>=0.0 && keywords.style("TEMP","optional") ) return getKBoltzmann()*temp; + if( keywords.exists("TEMP") ) { + parse("TEMP",temp); + } + if(temp>=0.0 && keywords.style("TEMP","optional") ) { + return getKBoltzmann()*temp; + } ActionForInterface* kb=plumed.getActionSet().selectWithLabel("kBT"); - double kbt=0; if(kb) kbt=(kb->copyOutput(0))->get(); + double kbt=0; + if(kb) { + kbt=(kb->copyOutput(0))->get(); + } if( temp>=0 && keywords.style("TEMP","compulsory") ) { double kB=getKBoltzmann(); if( kbt>0 && std::abs(kbt-kB*temp)>1e-4) { - std::string strt1, strt2; Tools::convert( temp, strt1 ); Tools::convert( kbt/kB, strt2 ); + std::string strt1, strt2; + Tools::convert( temp, strt1 ); + Tools::convert( kbt/kB, strt2 ); warning("using TEMP=" + strt1 + " while MD engine uses " + strt2 + "\n"); } kbt = kB*temp; @@ -305,7 +371,9 @@ void Action::prepare() { } [[noreturn]] void Action::error( const std::string & msg ) const { - if( !keywords.exists("NO_ACTION_LOG") ) log.printf("ERROR in input to action %s with label %s : %s \n \n", name.c_str(), label.c_str(), msg.c_str() ); + if( !keywords.exists("NO_ACTION_LOG") ) { + log.printf("ERROR in input to action %s with label %s : %s \n \n", name.c_str(), label.c_str(), msg.c_str() ); + } plumed_merror("ERROR in input to action " + name + " with label " + label + " : " + msg ); } @@ -317,7 +385,10 @@ void Action::calculateFromPDB( const PDB& pdb ) { activate(); for(const auto & p : after) { ActionWithValue*av=castToActionWithValue(); - if(av) { av->clearInputForces(); av->clearDerivatives(); } + if(av) { + av->clearInputForces(); + av->clearDerivatives(); + } p->readAtomsFromPDB( pdb ); p->calculate(); } @@ -336,8 +407,11 @@ std::string Action::cite(const std::string&s) { /// Check if action should be updated. bool Action::checkUpdate()const { double t=getTime(); - if(t::max() || t>=update_from)) return true; - else return false; + if(t::max() || t>=update_from)) { + return true; + } else { + return false; + } } bool Action::getCPT() const { @@ -353,14 +427,20 @@ bool Action::usingNaturalUnits() const { } double Action::getKBoltzmann() const { - if( usingNaturalUnits() ) return 1.0; - else return kBoltzmann/getUnits().getEnergy(); + if( usingNaturalUnits() ) { + return 1.0; + } else { + return kBoltzmann/getUnits().getEnergy(); + } } std::string Action::writeInGraph() const { std::string nam=getName(); - std::size_t u=nam.find_last_of("_"); std::string sub=nam.substr(u+1); - if( sub=="SCALAR" || sub=="VECTOR" || sub=="GRID" ) return nam.substr(0,u); + std::size_t u=nam.find_last_of("_"); + std::string sub=nam.substr(u+1); + if( sub=="SCALAR" || sub=="VECTOR" || sub=="GRID" ) { + return nam.substr(0,u); + } return nam; } diff --git a/src/core/Action.h b/src/core/Action.h index 08a5172190..acb9e749c8 100644 --- a/src/core/Action.h +++ b/src/core/Action.h @@ -292,13 +292,19 @@ class Action { bool isOptionOn(const std::string &s)const; /// Return dependencies - const Dependencies & getDependencies()const {return after;} + const Dependencies & getDependencies()const { + return after; + } /// Check if numerical derivatives should be performed - virtual bool checkNumericalDerivatives()const {return false;} + virtual bool checkNumericalDerivatives()const { + return false; + } /// Check if the action needs gradient - virtual bool checkNeedsGradients()const {return false;} + virtual bool checkNeedsGradients()const { + return false; + } /// Perform calculation using numerical derivatives /// N.B. only pass an ActionWithValue to this routine if you know exactly what you @@ -335,16 +341,36 @@ class Action { /// Get the info on what to calculate virtual std::string writeInGraph() const ; /// Specialized casts, to make PlumedMain run faster - virtual ActionWithValue* castToActionWithValue() noexcept { return nullptr; } - virtual ActionWithArguments* castToActionWithArguments() noexcept { return nullptr; } - virtual ActionAtomistic* castToActionAtomistic() noexcept { return nullptr; } - virtual ActionWithVirtualAtom* castToActionWithVirtualAtom() noexcept { return nullptr; } - virtual PbcAction* castToPbcAction() noexcept { return nullptr; } - virtual ActionToPutData* castToActionToPutData() noexcept { return nullptr; } - virtual ActionToGetData* castToActionToGetData() noexcept { return nullptr; } - virtual DomainDecomposition* castToDomainDecomposition() noexcept { return nullptr; } - virtual ActionForInterface* castToActionForInterface() noexcept { return nullptr; } - virtual ActionShortcut* castToActionShortcut() noexcept { return nullptr; } + virtual ActionWithValue* castToActionWithValue() noexcept { + return nullptr; + } + virtual ActionWithArguments* castToActionWithArguments() noexcept { + return nullptr; + } + virtual ActionAtomistic* castToActionAtomistic() noexcept { + return nullptr; + } + virtual ActionWithVirtualAtom* castToActionWithVirtualAtom() noexcept { + return nullptr; + } + virtual PbcAction* castToPbcAction() noexcept { + return nullptr; + } + virtual ActionToPutData* castToActionToPutData() noexcept { + return nullptr; + } + virtual ActionToGetData* castToActionToGetData() noexcept { + return nullptr; + } + virtual DomainDecomposition* castToDomainDecomposition() noexcept { + return nullptr; + } + virtual ActionForInterface* castToActionForInterface() noexcept { + return nullptr; + } + virtual ActionShortcut* castToActionShortcut() noexcept { + return nullptr; + } }; ///////////////////// @@ -369,7 +395,9 @@ void Action::parse(const std::string&key,T&t) { std::string def; bool present=Tools::findKeyword(line,key); bool found=Tools::parse(line,key,t,replica_index); - if(present && !found) error("keyword " + key +" could not be read correctly"); + if(present && !found) { + error("keyword " + key +" could not be read correctly"); + } // If it isn't read and it is compulsory see if a default value was specified if ( !found && (keywords.style(key,"compulsory") || keywords.style(key,"hidden")) ) { @@ -388,10 +416,13 @@ template bool Action::parseNumbered(const std::string&key, const int no, T&t) { // Check keyword has been registered plumed_massert(keywords.exists(key),"keyword " + key + " has not been registered"); - if( !keywords.numbered(key) ) error("numbered keywords are not allowed for " + key ); + if( !keywords.numbered(key) ) { + error("numbered keywords are not allowed for " + key ); + } // Now try to read the keyword - std::string num; Tools::convert(no,num); + std::string num; + Tools::convert(no,num); return Tools::parse(line,key+num,t,replica_index); } @@ -399,20 +430,28 @@ template void Action::parseVector(const std::string&key,std::vector&t) { // Check keyword has been registered plumed_massert(keywords.exists(key), "keyword " + key + " has not been registered"); - unsigned size=t.size(); bool skipcheck=false; - if(size==0) skipcheck=true; + unsigned size=t.size(); + bool skipcheck=false; + if(size==0) { + skipcheck=true; + } // Now try to read the keyword - std::string def; T val; + std::string def; + T val; bool present=Tools::findKeyword(line,key); bool found=Tools::parseVector(line,key,t,replica_index); - if(present && !found) error("keyword " + key +" could not be read correctly"); + if(present && !found) { + error("keyword " + key +" could not be read correctly"); + } // Check vectors size is correct (not if this is atoms or ARG) if( !keywords.style(key,"atoms") && found ) { // bool skipcheck=false; // if( keywords.style(key,"compulsory") ){ keywords.getDefaultValue(key,def); skipcheck=(def=="nosize"); } - if( !skipcheck && t.size()!=size ) error("vector read in for keyword " + key + " has the wrong size"); + if( !skipcheck && t.size()!=size ) { + error("vector read in for keyword " + key + " has the wrong size"); + } } // If it isn't read and it is compulsory see if a default value was specified @@ -422,9 +461,17 @@ void Action::parseVector(const std::string&key,std::vector&t) { plumed_error() <<"ERROR in action "<0) { - for(unsigned i=0; i&t) { template bool Action::parseNumberedVector(const std::string&key, const int no, std::vector&t) { plumed_massert(keywords.exists(key),"keyword " + key + " has not been registered"); - if( !keywords.numbered(key) ) error("numbered keywords are not allowed for " + key ); + if( !keywords.numbered(key) ) { + error("numbered keywords are not allowed for " + key ); + } - unsigned size=t.size(); bool skipcheck=false; - if(size==0) skipcheck=true; - std::string num; Tools::convert(no,num); + unsigned size=t.size(); + bool skipcheck=false; + if(size==0) { + skipcheck=true; + } + std::string num; + Tools::convert(no,num); bool present=Tools::findKeyword(line,key); bool found=Tools::parseVector(line,key+num,t,replica_index); - if(present && !found) error("keyword " + key +" could not be read correctly"); + if(present && !found) { + error("keyword " + key +" could not be read correctly"); + } if( keywords.style(key,"compulsory") ) { - if (!skipcheck && found && t.size()!=size ) error("vector read in for keyword " + key + num + " has the wrong size"); + if (!skipcheck && found && t.size()!=size ) { + error("vector read in for keyword " + key + num + " has the wrong size"); + } } else if ( !found ) { t.resize(0); } diff --git a/src/core/ActionAnyorder.cpp b/src/core/ActionAnyorder.cpp index b9b9991208..ed7d8a528f 100644 --- a/src/core/ActionAnyorder.cpp +++ b/src/core/ActionAnyorder.cpp @@ -27,8 +27,7 @@ namespace PLMD { ActionAnyorder::ActionAnyorder(const ActionOptions&ao): - Action(ao) -{ + Action(ao) { } void ActionAnyorder::registerKeywords( Keywords& keys ) { diff --git a/src/core/ActionAtomistic.cpp b/src/core/ActionAtomistic.cpp index dfd4dda8c7..8331190433 100644 --- a/src/core/ActionAtomistic.cpp +++ b/src/core/ActionAtomistic.cpp @@ -48,25 +48,30 @@ ActionAtomistic::ActionAtomistic(const ActionOptions&ao): donotretrieve(false), donotforce(false), massesWereSet(false), - chargesWereSet(false) -{ + chargesWereSet(false) { ActionWithValue* bv = plumed.getActionSet().selectWithLabel("Box"); - if( bv ) boxValue=bv->copyOutput(0); + if( bv ) { + boxValue=bv->copyOutput(0); + } // We now get all the information about atoms that are lying about getAtomValuesFromPlumedObject( plumed, xpos, ypos, zpos, masv, chargev ); - if( xpos.size()!=ypos.size() || xpos.size()!=zpos.size() || xpos.size()!=masv.size() || xpos.size()!=chargev.size() ) + if( xpos.size()!=ypos.size() || xpos.size()!=zpos.size() || xpos.size()!=masv.size() || xpos.size()!=chargev.size() ) { error("mismatch between value arrays"); + } } void ActionAtomistic::getAtomValuesFromPlumedObject( const PlumedMain& plumed, std::vector& xpos, std::vector& ypos, std::vector& zpos, std::vector& masv, std::vector& chargev ) { - std::vector shortcuts = plumed.getActionSet().select(); bool foundpdb=false; + std::vector shortcuts = plumed.getActionSet().select(); + bool foundpdb=false; for(const auto & ss : shortcuts ) { if( ss->getName()=="READMASSCHARGE" ) { foundpdb=true; ActionWithValue* mv = plumed.getActionSet().selectWithLabel( ss->getShortcutLabel() + "_mass"); - plumed_assert( mv ); masv.push_back( mv->copyOutput(0) ); + plumed_assert( mv ); + masv.push_back( mv->copyOutput(0) ); ActionWithValue* qv = plumed.getActionSet().selectWithLabel( ss->getShortcutLabel() + "_charges"); - plumed_assert( qv ); chargev.push_back( qv->copyOutput(0) ); + plumed_assert( qv ); + chargev.push_back( qv->copyOutput(0) ); } } std::vector vatoms = plumed.getActionSet().select(); @@ -74,11 +79,21 @@ void ActionAtomistic::getAtomValuesFromPlumedObject( const PlumedMain& plumed, s plumed_assert(vv); // needed for following calls, see #1046 ActionToPutData* ap = vv->castToActionToPutData(); if( ap ) { - if( ap->getRole()=="x" ) xpos.push_back( ap->copyOutput(0) ); - if( ap->getRole()=="y" ) ypos.push_back( ap->copyOutput(0) ); - if( ap->getRole()=="z" ) zpos.push_back( ap->copyOutput(0) ); - if( !foundpdb && ap->getRole()=="m" ) masv.push_back( ap->copyOutput(0) ); - if( !foundpdb && ap->getRole()=="q" ) chargev.push_back( ap->copyOutput(0) ); + if( ap->getRole()=="x" ) { + xpos.push_back( ap->copyOutput(0) ); + } + if( ap->getRole()=="y" ) { + ypos.push_back( ap->copyOutput(0) ); + } + if( ap->getRole()=="z" ) { + zpos.push_back( ap->copyOutput(0) ); + } + if( !foundpdb && ap->getRole()=="m" ) { + masv.push_back( ap->copyOutput(0) ); + } + if( !foundpdb && ap->getRole()=="q" ) { + chargev.push_back( ap->copyOutput(0) ); + } } ActionWithVirtualAtom* av = vv->castToActionWithVirtualAtom(); if( av || vv->getName()=="ARGS2VATOM" ) { @@ -106,14 +121,27 @@ void ActionAtomistic::requestAtoms(const std::vector & a, const bool charges.resize(nat); atom_value_ind.resize( a.size() ); int n=getTotAtoms(); - if(clearDep) clearDependencies(); - unique.clear(); std::vector requirements( xpos.size(), false ); - if( boxValue ) addDependency( boxValue->getPntrToAction() ); + if(clearDep) { + clearDependencies(); + } + unique.clear(); + std::vector requirements( xpos.size(), false ); + if( boxValue ) { + addDependency( boxValue->getPntrToAction() ); + } for(unsigned i=0; i=n) { std::string num; Tools::convert( indexes[i].serial(),num ); error("atom " + num + " out of range"); } - atom_value_ind[i] = getValueIndices( indexes[i] ); requirements[atom_value_ind[i].first] = true; - if( atom_value_ind[i].first==0 ) unique.push_back(indexes[i]); - else if( atom_value_ind[i].second>0 ) error("action atomistic is not set up to deal with multiple vectors in position input"); + if(indexes[i].index()>=n) { + std::string num; + Tools::convert( indexes[i].serial(),num ); + error("atom " + num + " out of range"); + } + atom_value_ind[i] = getValueIndices( indexes[i] ); + requirements[atom_value_ind[i].first] = true; + if( atom_value_ind[i].first==0 ) { + unique.push_back(indexes[i]); + } else if( atom_value_ind[i].second>0 ) { + error("action atomistic is not set up to deal with multiple vectors in position input"); + } } atom_value_ind_grouped.clear(); @@ -127,16 +155,20 @@ void ActionAtomistic::requestAtoms(const std::vector & a, const bool for(unsigned i=1; i>(nn, {})); + if(nn!=prev_nn) + atom_value_ind_grouped.push_back(std::pair>(nn, {})); atom_value_ind_grouped.back().second.push_back(kk); prev_nn=nn; } } // Add the dependencies to the actions that we require - Tools::removeDuplicates(unique); value_depends.resize(0); + Tools::removeDuplicates(unique); + value_depends.resize(0); for(unsigned i=0; igetPntrToAction() ); addDependency( ypos[i]->getPntrToAction() ); @@ -172,7 +204,8 @@ void ActionAtomistic::calculateAtomicNumericalDerivatives( ActionWithValue* a, c std::vector savedPositions(natoms); const double delta=std::sqrt(epsilon); - for(int i=0; icalculate(); @@ -182,17 +215,26 @@ void ActionAtomistic::calculateAtomicNumericalDerivatives( ActionWithValue* a, c } } Tensor box(pbc.getBox()); - for(int i=0; i<3; i++) for(int k=0; k<3; k++) { + for(int i=0; i<3; i++) + for(int k=0; k<3; k++) { double arg0=box(i,k); - for(int j=0; jcalculate(); box(i,k)=arg0; pbc.setBox(box); - for(int j=0; jgetOutputQuantity(j); + for(int j=0; jgetOutputQuantity(j); + } } a->calculate(); @@ -201,23 +243,34 @@ void ActionAtomistic::calculateAtomicNumericalDerivatives( ActionWithValue* a, c Value* v=a->copyOutput(j); double ref=v->get(); if(v->hasDerivatives()) { - for(int i=0; iaddDerivative(startnum+3*i+k,d); } Tensor virial; - for(int i=0; i<3; i++) for(int k=0; k<3; k++)virial(i,k)= (valuebox[j](i,k)-ref)/delta; + for(int i=0; i<3; i++) + for(int k=0; k<3; k++) { + virial(i,k)= (valuebox[j](i,k)-ref)/delta; + } // BE CAREFUL WITH NON ORTHOROMBIC CELL virial=-matmul(box.transpose(),virial); - for(int i=0; i<3; i++) for(int k=0; k<3; k++) v->addDerivative(startnum+3*natoms+3*k+i,virial(k,i)); + for(int i=0; i<3; i++) + for(int k=0; k<3; k++) { + v->addDerivative(startnum+3*natoms+3*k+i,virial(k,i)); + } } } } bool ActionAtomistic::actionHasForces() { ActionWithValue* av = castToActionWithValue(); - if( av ) return !av->doNotCalculateDerivatives(); - if( indexes.size()>0 ) plumed_merror("you have to overwrite the function actionHasForce to tell plumed if you method applies forces"); + if( av ) { + return !av->doNotCalculateDerivatives(); + } + if( indexes.size()>0 ) { + plumed_merror("you have to overwrite the function actionHasForce to tell plumed if you method applies forces"); + } return true; } @@ -230,11 +283,16 @@ void ActionAtomistic::parseAtomList(const std::string&key,const int num, std::ve std::vector strings; if( num<0 ) { parseVector(key,strings); - if(strings.empty()) return; + if(strings.empty()) { + return; + } } else { - if ( !parseNumberedVector(key,num,strings) ) return; + if ( !parseNumberedVector(key,num,strings) ) { + return; + } } - t.resize(0); interpretAtomList( strings, xpos, this, t ); + t.resize(0); + interpretAtomList( strings, xpos, this, t ); } void ActionAtomistic::interpretAtomList(std::vector& strings, std::vector &t) { @@ -246,18 +304,28 @@ void ActionAtomistic::interpretAtomList(std::vector& strings, const for(unsigned i=0; igetNumberOfValues(); - t.reserve(n); for(unsigned i=0; igetNumberOfValues(); + } + t.reserve(n); + for(unsigned i=0; igetNumberOfValues(); t.reserve(t.size()+n); - for(unsigned i=0; i& strings, const } else if(words.size()==2) { ndxfile=words[0]; ndxgroup=words[1]; - } else plumed_error()<<"Cannot intepret selection "<0) action->log<<" importing group '"+ndxgroup+"'"; - else action->log<<" importing first group"; + if(ndxgroup.size()>0) { + action->log<<" importing group '"+ndxgroup+"'"; + } else { + action->log<<" importing first group"; + } action->log<<" from index file "<& strings, const while(ifile.getline(line)) { std::vector words=Tools::getWords(line); if(words.size()>=3 && words[0]=="[" && words[2]=="]") { - if(groupname.length()>0) firstgroup=false; + if(groupname.length()>0) { + firstgroup=false; + } groupname=words[1]; - if(groupname==ndxgroup || ndxgroup.length()==0) groupfound=true; + if(groupname==ndxgroup || ndxgroup.length()==0) { + groupfound=true; + } } else if(groupname==ndxgroup || (firstgroup && ndxgroup.length()==0)) { for(unsigned i=0; iplumed.getActionSet().selectLatest(action); if( moldat ) { - std::vector atom_list; moldat->interpretSymbol( symbol, atom_list ); - if( atom_list.size()>0 ) { ok=true; t.insert(t.end(),atom_list.begin(),atom_list.end()); } - else { action->error(strings[i] + " is not a label plumed knows"); } + std::vector atom_list; + moldat->interpretSymbol( symbol, atom_list ); + if( atom_list.size()>0 ) { + ok=true; + t.insert(t.end(),atom_list.begin(),atom_list.end()); + } else { + action->error(strings[i] + " is not a label plumed knows"); + } } else { action->error("atoms specified using @ symbol but no MOLINFO was available"); } @@ -310,12 +395,14 @@ void ActionAtomistic::interpretAtomList(std::vector& strings, const Group* mygrp=action->plumed.getActionSet().selectWithLabel(strings[i]); if(mygrp) { std::vector grp_str( mygrp->getGroupAtoms() ); - interpretAtomList( grp_str, xpos, action, t ); ok=true; + interpretAtomList( grp_str, xpos, action, t ); + ok=true; } else { Group* mygrp2=action->plumed.getActionSet().selectWithLabel(strings[i]+"_grp"); if(mygrp2) { std::vector grp_str( mygrp2->getGroupAtoms() ); - interpretAtomList( grp_str, xpos, action, t ); ok=true; + interpretAtomList( grp_str, xpos, action, t ); + ok=true; } } } @@ -324,12 +411,16 @@ void ActionAtomistic::interpretAtomList(std::vector& strings, const unsigned ind = 0; for(unsigned j=0; jgetPntrToAction()->getLabel()==strings[i] ) { - t.push_back( AtomNumber::index(ind) ); ok=true; break; + t.push_back( AtomNumber::index(ind) ); + ok=true; + break; } ind = ind + xpos[j]->getNumberOfValues(); } } - if(!ok) action->error("it was not possible to interpret atom name " + strings[i]); + if(!ok) { + action->error("it was not possible to interpret atom name " + strings[i]); + } // plumed_massert(ok,"it was not possible to interpret atom name " + strings[i]); } } @@ -337,7 +428,10 @@ void ActionAtomistic::interpretAtomList(std::vector& strings, const std::pair ActionAtomistic::getValueIndices( const AtomNumber& i ) const { std::size_t valno=0, k = i.index(); for(unsigned j=0; jgetNumberOfValues() ) { valno=j; break; } + if( kgetNumberOfValues() ) { + valno=j; + break; + } k = k - xpos[j]->getNumberOfValues(); } return std::pair( valno, k ); @@ -348,19 +442,28 @@ void ActionAtomistic::retrieveAtoms( const bool& force ) { auto* ptr=boxValue->getPntrToAction(); plumed_assert(ptr); // needed for following calls, see #1046 PbcAction* pbca = ptr->castToPbcAction(); - plumed_assert( pbca ); pbc=pbca->pbc; + plumed_assert( pbca ); + pbc=pbca->pbc; + } + if( donotretrieve || indexes.size()==0 ) { + return; } - if( donotretrieve || indexes.size()==0 ) return; auto * mtr=masv[0]->getPntrToAction(); plumed_assert(mtr); // needed for following calls, see #1046 ActionToPutData* mv = mtr->castToActionToPutData(); - if(mv) massesWereSet=mv->hasBeenSet(); - else if( (masv[0]->getPntrToAction())->getName()=="CONSTANT" ) massesWereSet=true; // Read masses from PDB file + if(mv) { + massesWereSet=mv->hasBeenSet(); + } else if( (masv[0]->getPntrToAction())->getName()=="CONSTANT" ) { + massesWereSet=true; // Read masses from PDB file + } auto * ptr=chargev[0]->getPntrToAction(); plumed_assert(ptr); // needed for following calls, see #1046 ActionToPutData* cv = ptr->castToActionToPutData(); - if(cv) chargesWereSet=cv->hasBeenSet(); - else if( (chargev[0]->getPntrToAction())->getName()=="CONSTANT" ) chargesWereSet=true; // Read masses from PDB file + if(cv) { + chargesWereSet=cv->hasBeenSet(); + } else if( (chargev[0]->getPntrToAction())->getName()=="CONSTANT" ) { + chargesWereSet=true; // Read masses from PDB file + } unsigned j = 0; // for(const auto & a : atom_value_ind) { @@ -393,7 +496,9 @@ void ActionAtomistic::retrieveAtoms( const bool& force ) { } void ActionAtomistic::setForcesOnAtoms(const std::vector& forcesToApply, unsigned& ind) { - if( donotforce || (indexes.size()==0 && getName()!="FIXEDATOM") ) return; + if( donotforce || (indexes.size()==0 && getName()!="FIXEDATOM") ) { + return; + } for(unsigned i=0; ihasForce = true; ypos[value_depends[i]]->hasForce = true; @@ -415,9 +520,12 @@ void ActionAtomistic::setForcesOnAtoms(const std::vector& forcesToApply, auto & yp=ypos[nn]->inputForce; auto & zp=zpos[nn]->inputForce; for(const auto & kk : a.second) { - xp[kk] += forcesToApply[ind]; ind++; - yp[kk] += forcesToApply[ind]; ind++; - zp[kk] += forcesToApply[ind]; ind++; + xp[kk] += forcesToApply[ind]; + ind++; + yp[kk] += forcesToApply[ind]; + ind++; + zp[kk] += forcesToApply[ind]; + ind++; } } @@ -431,29 +539,44 @@ void ActionAtomistic::setForcesOnCell(const std::vector& forcesToApply, void ActionAtomistic::setForcesOnCell(const double* forcesToApply, std::size_t size, unsigned& ind) { for(unsigned i=0; i<9; ++i) { plumed_dbg_massert( indaddForce( i, forcesToApply[ind] ); ind++; + boxValue->addForce( i, forcesToApply[ind] ); + ind++; } } Tensor ActionAtomistic::getVirial() const { - Tensor vir; for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) vir[i][j] = boxValue->getForce(3*i+j); + Tensor vir; + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + vir[i][j] = boxValue->getForce(3*i+j); + } return vir; } void ActionAtomistic::readAtomsFromPDB(const PDB& pdb) { for(unsigned j=0; jpdb.size() ) error("there are not enough atoms in the input pdb file"); - if( pdb.getAtomNumbers()[j].index()!=indexes[j].index() ) error("there are atoms missing in the pdb file"); + if( indexes[j].index()>pdb.size() ) { + error("there are not enough atoms in the input pdb file"); + } + if( pdb.getAtomNumbers()[j].index()!=indexes[j].index() ) { + error("there are atoms missing in the pdb file"); + } positions[j]=pdb.getPositions()[indexes[j].index()]; } - for(unsigned j=0; jgetNumberOfValues(); + for(unsigned i=0; igetNumberOfValues(); + } return natoms; } @@ -467,18 +590,27 @@ void ActionAtomistic::makeWhole() { void ActionAtomistic::getGradient( const unsigned& ind, Vector& deriv, std::map& gradients ) const { std::size_t nn = atom_value_ind[ind].first; - if( nn==0 ) { gradients[indexes[ind]] += deriv; return; } + if( nn==0 ) { + gradients[indexes[ind]] += deriv; + return; + } xpos[nn]->passGradients( deriv[0], gradients ); ypos[nn]->passGradients( deriv[1], gradients ); zpos[nn]->passGradients( deriv[2], gradients ); } void ActionAtomistic::updateUniqueLocal( const bool& useunique, const std::vector& g2l ) { - if( useunique ) { unique_local=unique; return; } + if( useunique ) { + unique_local=unique; + return; + } // Update unique local if it needs an update - unique_local_needs_update=false; unique_local.clear(); + unique_local_needs_update=false; + unique_local.clear(); for(auto pp=unique.begin(); pp!=unique.end(); ++pp) { - if(g2l[pp->index()]>=0) unique_local.push_back(*pp); // already sorted + if(g2l[pp->index()]>=0) { + unique_local.push_back(*pp); // already sorted + } } } diff --git a/src/core/ActionAtomistic.h b/src/core/ActionAtomistic.h index 377d1c6ccb..bc49976563 100644 --- a/src/core/ActionAtomistic.h +++ b/src/core/ActionAtomistic.h @@ -42,8 +42,7 @@ class SelectMassCharge; /// \ingroup MULTIINHERIT /// Action used to create objects that access the positions of the atoms from the MD code class ActionAtomistic : - virtual public Action -{ + virtual public Action { friend class Group; friend class DomainDecomposition; friend class colvar::SelectMassCharge; @@ -126,7 +125,9 @@ class ActionAtomistic : /// Get a reference to force on energy double & modifyForceOnEnergy(); /// Get number of available atoms - unsigned getNumberOfAtoms()const {return indexes.size();} + unsigned getNumberOfAtoms()const { + return indexes.size(); + } /// Compute the pbc distance between two positions Vector pbcDistance(const Vector&,const Vector&)const; /// Applies PBCs to a seriens of positions or distances @@ -160,11 +161,15 @@ class ActionAtomistic : /// not going to be retrieved. Can be used for optimization. Notice that /// calling getPosition(int) in an Action where DoNotRetrieve() was called might /// lead to undefined behavior. - void doNotRetrieve() {donotretrieve=true;} + void doNotRetrieve() { + donotretrieve=true; + } /// Skip atom forces - use with care. /// If this function is called during initialization, then forces are /// not going to be propagated. Can be used for optimization. - void doNotForce() {donotforce=true;} + void doNotForce() { + donotforce=true; + } /// Make atoms whole, assuming they are in the proper order void makeWhole(); public: @@ -192,7 +197,9 @@ class ActionAtomistic : void readAtomsFromPDB( const PDB& pdb ) override; /// Transfer the gradients void getGradient( const unsigned& ind, Vector& deriv, std::map& gradients ) const ; - ActionAtomistic* castToActionAtomistic() noexcept final { return this; } + ActionAtomistic* castToActionAtomistic() noexcept final { + return this; + } virtual bool actionHasForces(); }; @@ -203,13 +210,17 @@ const Vector & ActionAtomistic::getPosition(int i)const { inline double ActionAtomistic::getMass(int i)const { - if( !massesWereSet ) log.printf("WARNING: masses were not passed to plumed\n"); + if( !massesWereSet ) { + log.printf("WARNING: masses were not passed to plumed\n"); + } return masses[i]; } inline double ActionAtomistic::getCharge(int i) const { - if( !chargesWereSet ) error("charges were not passed to plumed"); + if( !chargesWereSet ) { + error("charges were not passed to plumed"); + } return charges[i]; } diff --git a/src/core/ActionForInterface.cpp b/src/core/ActionForInterface.cpp index 6db02e8f0b..7ad5827f68 100644 --- a/src/core/ActionForInterface.cpp +++ b/src/core/ActionForInterface.cpp @@ -27,7 +27,8 @@ namespace PLMD { void ActionForInterface::registerKeywords(Keywords& keys) { - Action::registerKeywords(keys); ActionWithValue::registerKeywords( keys ); + Action::registerKeywords(keys); + ActionWithValue::registerKeywords( keys ); keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); keys.add("optional","ROLE","Get the role this value plays in the code can be x/y/z/m/q to signify that this is x, y, z positions of atoms or masses or charges of atoms"); } @@ -37,9 +38,10 @@ ActionForInterface::ActionForInterface(const ActionOptions&ao): ActionWithValue(ao), firststep(true), wasscaled(false), - wasset(false) -{ - if( keywords.exists("ROLE") && getName()!="DOMAIN_DECOMPOSITION") parse("ROLE",role); + wasset(false) { + if( keywords.exists("ROLE") && getName()!="DOMAIN_DECOMPOSITION") { + parse("ROLE",role); + } } std::string ActionForInterface::getRole() const { diff --git a/src/core/ActionForInterface.h b/src/core/ActionForInterface.h index 5322515534..22e56d3511 100644 --- a/src/core/ActionForInterface.h +++ b/src/core/ActionForInterface.h @@ -49,7 +49,9 @@ class ActionForInterface : public ActionWithValue { /// Check if the value has been set bool hasBeenSet() const ; /// The number of derivatives - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } /// virtual void resetForStepStart() = 0; /// Set the start point for the memory if needed @@ -61,7 +63,9 @@ class ActionForInterface : public ActionWithValue { /// Set the force to the value that contains this data virtual bool setForcePointer( const std::string& name, const TypesafePtr & ) = 0; /// This get the number of forces that need to be rescaled in rescale forces - virtual unsigned getNumberOfForcesToRescale() const { plumed_merror("no method for rescaling forces for this type of input"); } + virtual unsigned getNumberOfForcesToRescale() const { + plumed_merror("no method for rescaling forces for this type of input"); + } /// Overriding this method from ActionWithValue ensures that taskLists that are set during share are not updated during calculate loop // void setupForCalculation( const bool& force=false ) override {} /// Get the data @@ -70,7 +74,10 @@ class ActionForInterface : public ActionWithValue { /// Get the data to share virtual void wait() = 0; /// Actually set the values for the output - void calculate() override { firststep=false; wasscaled=false; } + void calculate() override { + firststep=false; + wasscaled=false; + } virtual void reset() {} virtual void Set_comm(Communicator& comm) = 0; /// For replica exchange @@ -78,7 +85,9 @@ class ActionForInterface : public ActionWithValue { virtual void readBinary(std::istream&i) = 0; virtual bool onStep() const = 0; std::string getRole() const ; - ActionForInterface* castToActionForInterface() noexcept final { return this; } + ActionForInterface* castToActionForInterface() noexcept final { + return this; + } }; inline diff --git a/src/core/ActionPilot.cpp b/src/core/ActionPilot.cpp index 69643eb70a..762dda9a78 100644 --- a/src/core/ActionPilot.cpp +++ b/src/core/ActionPilot.cpp @@ -27,18 +27,21 @@ void ActionPilot::registerKeywords(Keywords& keys) {} ActionPilot::ActionPilot(const ActionOptions&ao): Action(ao), - stride(1) -{ + stride(1) { if( keywords.exists("STRIDE") ) { parse("STRIDE",stride); - if( !keywords.style("STRIDE","hidden") ) log.printf(" with stride %d\n",stride); + if( !keywords.style("STRIDE","hidden") ) { + log.printf(" with stride %d\n",stride); + } } else { stride=0; } } bool ActionPilot::onStep()const { - if( stride>0 ) return getStep()%stride==0; + if( stride>0 ) { + return getStep()%stride==0; + } return false; } diff --git a/src/core/ActionPilot.h b/src/core/ActionPilot.h index 6c6c458a90..27b9610be1 100644 --- a/src/core/ActionPilot.h +++ b/src/core/ActionPilot.h @@ -37,8 +37,7 @@ it in order to run. This class is used in PLMD::Bias which is specified on the directive line with a STRIDE= keyword */ class ActionPilot: - public virtual Action -{ + public virtual Action { int stride; // multiple time step public: explicit ActionPilot(const ActionOptions&); diff --git a/src/core/ActionRegister.cpp b/src/core/ActionRegister.cpp index 9054effa76..3004c0b48e 100644 --- a/src/core/ActionRegister.cpp +++ b/src/core/ActionRegister.cpp @@ -36,10 +36,13 @@ std::unique_ptr ActionRegister::create(const ActionOptions&ao) { } std::unique_ptr ActionRegister::create(const std::vector & images,const ActionOptions&ao) { - if(ao.line.size()<1)return nullptr; + if(ao.line.size()<1) { + return nullptr; + } auto content=get(images,ao.line[0]); - Keywords keys; keys.thisactname = ao.line[0]; + Keywords keys; + keys.thisactname = ao.line[0]; content.keys(keys); ActionOptions nao( ao,keys ); auto fullPath=getFullPath(images,ao.line[0]); @@ -49,9 +52,12 @@ std::unique_ptr ActionRegister::create(const std::vector & images bool ActionRegister::printManual(const std::string& action, const bool& vimout, const bool& spellout) { if ( check(action) ) { - Keywords keys; getKeywords( action, keys ); + Keywords keys; + getKeywords( action, keys ); if( vimout ) { - printf("%s",action.c_str()); keys.print_vim(); printf("\n"); + printf("%s",action.c_str()); + keys.print_vim(); + printf("\n"); } else if( spellout ) { keys.print_spelling(); } else { @@ -65,7 +71,8 @@ bool ActionRegister::printManual(const std::string& action, const bool& vimout, bool ActionRegister::printTemplate(const std::string& action, bool include_optional) { if( check(action) ) { - Keywords keys; keys.thisactname = action; + Keywords keys; + keys.thisactname = action; get(action).keys(keys); keys.print_template(action, include_optional); return true; @@ -80,7 +87,10 @@ std::vector ActionRegister::getActionNames() const { ActionRegister::ID ActionRegister::add(std::string key,creator_pointer cp,keywords_pointer kp) { // this force each action to be registered as an uppercase string - if ( std::any_of( std::begin( key ), std::end( key ), []( char c ) { return ( std::islower( c ) ); } ) ) plumed_error() << "Action: " + key + " cannot be registered, use only UPPERCASE characters"; + if ( std::any_of( std::begin( key ), std::end( key ), []( char c ) { + return ( std::islower( c ) ) + ; + } ) ) plumed_error() << "Action: " + key + " cannot be registered, use only UPPERCASE characters"; return RegisterBase::add(key,Pointers{cp,kp}); } @@ -94,7 +104,9 @@ bool ActionRegister::getKeywords(const std::string& action, Keywords& keys) { } void ActionRegister::getKeywords(const std::vector & images, const std::string& action, Keywords& keys) { - auto content=get(images,action); keys.thisactname = action; content.keys(keys); + auto content=get(images,action); + keys.thisactname = action; + content.keys(keys); } } diff --git a/src/core/ActionRegister.h b/src/core/ActionRegister.h index 474505addc..dd6b0ce862 100644 --- a/src/core/ActionRegister.h +++ b/src/core/ActionRegister.h @@ -97,13 +97,14 @@ class ActionRegistration { public: ///On construction register the ActionClass with the wanted directive ActionRegistration(std::string_view directive): - id(actionRegister().add(directive.data(),create,ActionClass::registerKeywords)) - { + id(actionRegister().add(directive.data(),create,ActionClass::registerKeywords)) { static_assert(isActionType, "ActionRegistration accepts only class that inherit from Action"); } ///On destruction deregister the ActionClass (useful when you unload a shared object) - ~ActionRegistration() {actionRegister().remove(id);} + ~ActionRegistration() { + actionRegister().remove(id); + } }; } //PLMD diff --git a/src/core/ActionSet.cpp b/src/core/ActionSet.cpp index 84e3c37c38..e6c16dc537 100644 --- a/src/core/ActionSet.cpp +++ b/src/core/ActionSet.cpp @@ -28,14 +28,17 @@ ActionSet::ActionSet(PlumedMain&p): (void) plumed; // to suppress warning about "unused plumed" } -ActionSet::~ActionSet() -{ +ActionSet::~ActionSet() { // required in order to deallocate in reverse order: - for(int i=size()-1; i>=0; i--) (*this)[i].reset(); + for(int i=size()-1; i>=0; i--) { + (*this)[i].reset(); + } } void ActionSet::clearDelete() { - for(int i=size()-1; i>=0; i--) (*this)[i].reset(); + for(int i=size()-1; i>=0; i--) { + (*this)[i].reset(); + } clear(); } @@ -43,9 +46,13 @@ ActionShortcut* ActionSet::getShortcutActionWithLabel( const std::string& s ) co ActionShortcut* scf = NULL; for(const auto & p : (*this)) { ActionShortcut* sc=dynamic_cast(p.get()); - if( sc && sc->shortcutlabel==s ) scf = sc; + if( sc && sc->shortcutlabel==s ) { + scf = sc; + } + } + if( scf ) { + return scf; } - if( scf ) return scf; return NULL; } diff --git a/src/core/ActionSet.h b/src/core/ActionSet.h index 77c706ecf1..52d2951515 100644 --- a/src/core/ActionSet.h +++ b/src/core/ActionSet.h @@ -38,8 +38,7 @@ class PlumedMain; /// Finally, since it holds pointers, there is a clearDelete() function /// which deletes the pointers before deleting the vector class ActionSet: - public std::vector> -{ + public std::vector> { PlumedMain& plumed; public: explicit ActionSet(PlumedMain&p); @@ -88,7 +87,9 @@ std::vector ActionSet::select()const { std::vector ret; for(const auto & p : (*this)) { T t=dynamic_cast(p.get()); - if(t) ret.push_back(t); + if(t) { + ret.push_back(t); + } }; return ret; } @@ -97,7 +98,9 @@ template T ActionSet::selectWithLabel(const std::string&s)const { for(const auto & p : (*this)) { T t=dynamic_cast(p.get()); - if(t && t->getLabel()==s) return t; + if(t && t->getLabel()==s) { + return t; + } }; return NULL; } @@ -107,7 +110,9 @@ std::vector ActionSet::selectNot()const { std::vector ret; for(const auto & p : (*this)) { T t=dynamic_cast(p); - if(!t) ret.push_back(p.get()); + if(!t) { + ret.push_back(p.get()); + } }; return ret; } @@ -116,7 +121,9 @@ template std::string ActionSet::getLabelList() const { std::string outlist; for(const auto & p : (*this)) { - if(dynamic_cast(p.get())) outlist+=p->getLabel()+" "; + if(dynamic_cast(p.get())) { + outlist+=p->getLabel()+" "; + } }; return outlist; } @@ -126,7 +133,9 @@ template std::vector ActionSet::getLabelVector() const { std::vector outlist; for(const auto & p : (*this)) { - if(dynamic_cast(p.get())) outlist.push_back(p->getLabel()); + if(dynamic_cast(p.get())) { + outlist.push_back(p->getLabel()); + } }; return outlist; } @@ -135,9 +144,13 @@ template T ActionSet::selectLatest(const Action*action) const { T t=nullptr; for(const auto & p : (*this)) { - if(p.get()==action) return t; + if(p.get()==action) { + return t; + } T r=dynamic_cast(p.get()); - if(r) t=r; + if(r) { + t=r; + } } return t; } diff --git a/src/core/ActionSetup.cpp b/src/core/ActionSetup.cpp index b70515b3a7..a7e16faa3d 100644 --- a/src/core/ActionSetup.cpp +++ b/src/core/ActionSetup.cpp @@ -29,8 +29,7 @@ namespace PLMD { ActionSetup::ActionSetup(const ActionOptions&ao): - Action(ao) -{ + Action(ao) { const ActionSet& actionset(plumed.getActionSet()); for(const auto & p : actionset) { // check that all the preceding actions are ActionSetup diff --git a/src/core/ActionShortcut.cpp b/src/core/ActionShortcut.cpp index 29e5658155..f165db0af5 100644 --- a/src/core/ActionShortcut.cpp +++ b/src/core/ActionShortcut.cpp @@ -42,75 +42,112 @@ void ActionShortcut::readShortcutKeywords( const Keywords& keys, std::map(keyname,t)); } else if( keys.numbered( keyname ) ) { for(unsigned i=1;; ++i) { - std::string istr; Tools::convert( i, istr ); - if( !parseNumbered(keyname,i,t) ) break ; + std::string istr; + Tools::convert( i, istr ); + if( !parseNumbered(keyname,i,t) ) { + break ; + } keymap.insert(std::pair(keyname + istr,t)); } } } else if( keys.style( keyname, "flag") ) { - bool found=false; parseFlag(keyname,found); - if( found ) keymap.insert(std::pair(keyname,"")); - } else plumed_merror("shortcut keywords should be optional, compulsory or flags"); + bool found=false; + parseFlag(keyname,found); + if( found ) { + keymap.insert(std::pair(keyname,"")); + } + } else { + plumed_merror("shortcut keywords should be optional, compulsory or flags"); + } } } ActionShortcut::ActionShortcut(const ActionOptions&ao): Action(ao), - shortcutlabel(label) -{ - std::string s; Tools::convert(plumed.getActionSet().size(),s); + shortcutlabel(label) { + std::string s; + Tools::convert(plumed.getActionSet().size(),s); if( shortcutlabel==("@" + s) ) { - std::string t; Tools::convert(plumed.getActionSet().size(),t); + std::string t; + Tools::convert(plumed.getActionSet().size(),t); shortcutlabel="@" + t; - } else label = ("@s" + s); + } else { + label = ("@s" + s); + } } void ActionShortcut::readInputLine( const std::string& input, bool saveline ) { - std::vector words=Tools::getWords(input); Tools::interpretLabel(words); + std::vector words=Tools::getWords(input); + Tools::interpretLabel(words); // Check if this action name has been registered bool founds=false, found = std::find(keywords.neededActions.begin(), keywords.neededActions.end(), words[0] )!=keywords.neededActions.end(); // Check if we are just calling something like SUM_VECTOR using just SUM. if( !found && words[0].find(getName())!=std::string::npos ) { for(unsigned j=0 ; jget()->castToActionWithValue(); - if( !av ) continue ; - if( std::find(savedOutputs.begin(), savedOutputs.end(), av->getLabel() )!=savedOutputs.end() ) av=NULL; + if( !av ) { + continue ; + } + if( std::find(savedOutputs.begin(), savedOutputs.end(), av->getLabel() )!=savedOutputs.end() ) { + av=NULL; + } break; } if( av ) { std::string av_label = av->getLabel(); - if( av_label == getShortcutLabel() ) savedOutputs.push_back( av_label ); - else { + if( av_label == getShortcutLabel() ) { + savedOutputs.push_back( av_label ); + } else { for(unsigned i=0; icastToActionWithValue(); - if( !av ) error("shortcut is using suffix but action created is not ActionWithValue"); - Keywords thiskeys; actionRegister().getKeywords( av->getName(), thiskeys ); - if( thiskeys.getDisplayName()!=getName() ) error("mismatch between display name of hidden action " + thiskeys.getDisplayName() + " and shortcut that creates it " + getName() ); + if( !av ) { + error("shortcut is using suffix but action created is not ActionWithValue"); + } + Keywords thiskeys; + actionRegister().getKeywords( av->getName(), thiskeys ); + if( thiskeys.getDisplayName()!=getName() ) { + error("mismatch between display name of hidden action " + thiskeys.getDisplayName() + " and shortcut that creates it " + getName() ); + } } - } else error("requirement for action " + words[0] + " should be registered in registerKeywords function for shortcut action using keys.useAction"); + } else { + error("requirement for action " + words[0] + " should be registered in registerKeywords function for shortcut action using keys.useAction"); + } } void ActionShortcut::addCommentToShortcutOutput( const std::string& input ) { @@ -120,59 +157,93 @@ void ActionShortcut::addCommentToShortcutOutput( const std::string& input ) { std::string ActionShortcut::getUpdateLimits() const { std::string f_input=""; if( update_from!=std::numeric_limits::max() ) { - std::string ufrom; Tools::convert( update_from, ufrom ); f_input += " UPDATE_FROM=" + ufrom; + std::string ufrom; + Tools::convert( update_from, ufrom ); + f_input += " UPDATE_FROM=" + ufrom; } if( update_until!=std::numeric_limits::max() ) { - std::string util; Tools::convert( update_until, util ); f_input += " UPDATE_UNTIL=" + util; + std::string util; + Tools::convert( update_until, util ); + f_input += " UPDATE_UNTIL=" + util; } return f_input; } void ActionShortcut::addToSavedInputLines( const std::string& line ) { - std::vector words = Tools::getWords(line); std::string actname; - if( words[0].find_first_of(":")!=std::string::npos) actname = words[1]; else actname = words[0]; - if( !actionRegister().check(actname) ) error("found no action with name " + actname + " to create shortcut"); - Keywords thiskeys; actionRegister().getKeywords( actname, thiskeys ); std::vector numberedkeys; + std::vector words = Tools::getWords(line); + std::string actname; + if( words[0].find_first_of(":")!=std::string::npos) { + actname = words[1]; + } else { + actname = words[0]; + } + if( !actionRegister().check(actname) ) { + error("found no action with name " + actname + " to create shortcut"); + } + Keywords thiskeys; + actionRegister().getKeywords( actname, thiskeys ); + std::vector numberedkeys; for(unsigned i=0; i0 && actname!="CONCATENATE" ) { std::string reducedline; for(unsigned i=0; i ninstances( numberedkeys.size(), 0 ); for(unsigned j=0; j0 ) { outputcomment=true; break; } + if( ninstances[j]>0 ) { + outputcomment=true; + break; + } } if( outputcomment ) { reducedline += " # Action input conctinues with "; for(unsigned j=0; j0 ) reducedline += num + " further " + numberedkeys[j] + "n keywords, "; + std::string num; + Tools::convert( ninstances[j], num ); + if( ninstances[j]>0 ) { + reducedline += num + " further " + numberedkeys[j] + "n keywords, "; + } } } savedInputLines.push_back( reducedline ); - } else savedInputLines.push_back( line ); + } else { + savedInputLines.push_back( line ); + } } const std::string & ActionShortcut::getShortcutLabel() const { @@ -193,15 +264,21 @@ std::string ActionShortcut::convertInputLineToString() { if( (*p).find(" " )!=std::string::npos ) { std::size_t eq = (*p).find_first_of("="); output += " " + (*p).substr(0,eq) + "={" + (*p).substr(eq+1) + "}"; - } else output += " " + (*p); + } else { + output += " " + (*p); + } } - line.resize(0); return output; + line.resize(0); + return output; } void ActionShortcut::interpretDataLabel( const std::string& mystr, Action* myuser, std::vector& arg ) const { - std::size_t dot=mystr.find_first_of('.'); std::string a=mystr.substr(0,dot); std::string name=mystr.substr(dot+1); + std::size_t dot=mystr.find_first_of('.'); + std::string a=mystr.substr(0,dot); + std::string name=mystr.substr(dot+1); // Retrieve the keywords for the shortcut - Keywords skeys; actionRegister().getKeywords( getName(), skeys ); + Keywords skeys; + actionRegister().getKeywords( getName(), skeys ); std::vector out_comps( skeys.getOutputComponents() ); // Now get the output components if( name=="*" ) { @@ -209,21 +286,30 @@ void ActionShortcut::interpretDataLabel( const std::string& mystr, Action* myuse if( out_comps[k]=="" ) { ActionWithValue* action=plumed.getActionSet().selectWithLabel( a ); if( action ) { - if( action->getNumberOfComponents()!=1 ) myuser->error("action named " + a + " has more than one component"); + if( action->getNumberOfComponents()!=1 ) { + myuser->error("action named " + a + " has more than one component"); + } arg.push_back(action->copyOutput(0)); } } else { ActionWithValue* action=plumed.getActionSet().selectWithLabel( a + "_" + out_comps[k] ); if( action ) { - if( action->getNumberOfComponents()!=1 ) myuser->error("action named " + a + "_" + out_comps[k] + " has more than one component"); + if( action->getNumberOfComponents()!=1 ) { + myuser->error("action named " + a + "_" + out_comps[k] + " has more than one component"); + } arg.push_back(action->copyOutput(0)); } else { for(unsigned j=1;; ++j) { - std::string numstr; Tools::convert( j, numstr ); + std::string numstr; + Tools::convert( j, numstr ); ActionWithValue* act=plumed.getActionSet().selectWithLabel( a + "_" + out_comps[k] + "-" + numstr ); if( act ) { - for(unsigned n=0; ngetNumberOfComponents(); ++n ) arg.push_back(act->copyOutput(n)); - } else if( j>1 ) break; // This ensures that * syntax works with moments, which normally start from 2 + for(unsigned n=0; ngetNumberOfComponents(); ++n ) { + arg.push_back(act->copyOutput(n)); + } + } else if( j>1 ) { + break; // This ensures that * syntax works with moments, which normally start from 2 + } } } } @@ -231,12 +317,16 @@ void ActionShortcut::interpretDataLabel( const std::string& mystr, Action* myuse } else { // Check for an action that has action.component ActionWithValue* act=plumed.getActionSet().selectWithLabel( a ); - if( act && act->exists(mystr) ) return; + if( act && act->exists(mystr) ) { + return; + } // Get components that are actually actions for(unsigned k=0; k( a + "_" + name ); - if( action ) arg.push_back(action->copyOutput(a+"_"+name)); + if( action ) { + arg.push_back(action->copyOutput(a+"_"+name)); + } break; } } diff --git a/src/core/ActionShortcut.h b/src/core/ActionShortcut.h index be4ef136bb..b83907574a 100644 --- a/src/core/ActionShortcut.h +++ b/src/core/ActionShortcut.h @@ -63,7 +63,9 @@ class ActionShortcut : std::string convertInputLineToString(); /// This sorts out the reading of arguments from shortcuts void interpretDataLabel( const std::string& mystr, Action* myuser, std::vector& args ) const ; - ActionShortcut* castToActionShortcut() noexcept final { return this; } + ActionShortcut* castToActionShortcut() noexcept final { + return this; + } }; } diff --git a/src/core/ActionToGetData.cpp b/src/core/ActionToGetData.cpp index 8c363b1e61..6f16d36f5e 100644 --- a/src/core/ActionToGetData.cpp +++ b/src/core/ActionToGetData.cpp @@ -37,7 +37,9 @@ namespace PLMD { PLUMED_REGISTER_ACTION(ActionToGetData,"GET") void ActionToGetData::registerKeywords(Keywords& keys) { - Action::registerKeywords(keys); ActionPilot::registerKeywords(keys); ActionWithArguments::registerKeywords(keys); + Action::registerKeywords(keys); + ActionPilot::registerKeywords(keys); + ActionWithArguments::registerKeywords(keys); keys.add("compulsory","STRIDE","1","the frequency with which the quantities of interest should be stored"); keys.add("compulsory","TYPE","value","what do you want to collect for the value can be derivative/force"); keys.use("ARG"); @@ -48,30 +50,50 @@ ActionToGetData::ActionToGetData(const ActionOptions&ao): Action(ao), ActionPilot(ao), ActionWithArguments(ao), - mydata(DataPassingObject::create(plumed.getRealPrecision())) -{ - std::string type; parse("TYPE",type); - if( type=="value" ) gtype=val; - else if( type=="derivatives" ) gtype=deriv; - else if( type=="forces" ) gtype=force; - else plumed_merror("cannot get " + type + " for value TYPE should be value/derivative/force"); - - if( gtype!=val ) error("not implemented functionality to pass derviatives or forces to python. Email gareth.tribello@gmail.com if you want this."); - - if( getNumberOfArguments()!=1 ) error("python interface works best when you ask for one argument at a time"); - if( getPntrToArgument(0)->getNumberOfValues()==0 ) error("cannot get data as shape of value " + getPntrToArgument(0)->getName() + " has not been set"); - getPntrToArgument(0)->buildDataStore(); data.resize( getPntrToArgument(0)->getNumberOfValues() ); + mydata(DataPassingObject::create(plumed.getRealPrecision())) { + std::string type; + parse("TYPE",type); + if( type=="value" ) { + gtype=val; + } else if( type=="derivatives" ) { + gtype=deriv; + } else if( type=="forces" ) { + gtype=force; + } else { + plumed_merror("cannot get " + type + " for value TYPE should be value/derivative/force"); + } + + if( gtype!=val ) { + error("not implemented functionality to pass derviatives or forces to python. Email gareth.tribello@gmail.com if you want this."); + } + + if( getNumberOfArguments()!=1 ) { + error("python interface works best when you ask for one argument at a time"); + } + if( getPntrToArgument(0)->getNumberOfValues()==0 ) { + error("cannot get data as shape of value " + getPntrToArgument(0)->getName() + " has not been set"); + } + getPntrToArgument(0)->buildDataStore(); + data.resize( getPntrToArgument(0)->getNumberOfValues() ); } void ActionToGetData::get_rank( const TypesafePtr & dims ) { - if( getPntrToArgument(0)->getRank()==0 ) { dims.set(long(1)); return; } + if( getPntrToArgument(0)->getRank()==0 ) { + dims.set(long(1)); + return; + } dims.set(long(getPntrToArgument(0)->getRank())); } void ActionToGetData::get_shape( const TypesafePtr & dims ) { - if( getPntrToArgument(0)->getRank()==0 ) { dims.set(long(1)); return; } + if( getPntrToArgument(0)->getRank()==0 ) { + dims.set(long(1)); + return; + } auto dims_=dims.get( { getPntrToArgument(0)->getRank() } ); - for(unsigned j=0; jgetRank(); ++j) dims_[j] = getPntrToArgument(0)->getShape()[j]; + for(unsigned j=0; jgetRank(); ++j) { + dims_[j] = getPntrToArgument(0)->getShape()[j]; + } } void ActionToGetData::set_memory( const TypesafePtr & val ) { @@ -79,7 +101,8 @@ void ActionToGetData::set_memory( const TypesafePtr & val ) { } void ActionToGetData::calculate() { - plumed_assert( gtype==val ); mydata->setData( getPntrToArgument(0) ); + plumed_assert( gtype==val ); + mydata->setData( getPntrToArgument(0) ); } } diff --git a/src/core/ActionToGetData.h b/src/core/ActionToGetData.h index a6afbde6a0..04e285d4ca 100644 --- a/src/core/ActionToGetData.h +++ b/src/core/ActionToGetData.h @@ -30,8 +30,7 @@ namespace PLMD { class ActionToGetData : public ActionPilot, - public ActionWithArguments -{ + public ActionWithArguments { private: /// What do you want to collect to pass back to python enum {val,deriv,force} gtype; @@ -51,7 +50,9 @@ class ActionToGetData : /// Actually set the values for the output void calculate(); void apply() {} - ActionToGetData* castToActionToGetData() noexcept final { return this; } + ActionToGetData* castToActionToGetData() noexcept final { + return this; + } }; } diff --git a/src/core/ActionToPutData.cpp b/src/core/ActionToPutData.cpp index 06d75abf61..24b52e0d22 100644 --- a/src/core/ActionToPutData.cpp +++ b/src/core/ActionToPutData.cpp @@ -60,87 +60,150 @@ ActionToPutData::ActionToPutData(const ActionOptions&ao): resetable(false), dataCanBeSet(true), unit(n), - mydata(DataPassingObject::create(plumed.getRealPrecision())) -{ + mydata(DataPassingObject::create(plumed.getRealPrecision())) { if( getName()!="ENERGY" && getName()!="PBC" ) { - std::vector shape; parseVector("SHAPE",shape); - if( shape.size()==1 && shape[0]==0 ) { shape.resize(0); addValue( shape ); } - else { addValue( shape ); } - - std::string unitstr, funitstr; parse("UNIT",unitstr); - parse("FORCE_UNIT",funitstr); setUnit( unitstr, funitstr ); + std::vector shape; + parseVector("SHAPE",shape); + if( shape.size()==1 && shape[0]==0 ) { + shape.resize(0); + addValue( shape ); + } else { + addValue( shape ); + } + + std::string unitstr, funitstr; + parse("UNIT",unitstr); + parse("FORCE_UNIT",funitstr); + setUnit( unitstr, funitstr ); // Now sort out period - std::vector period; parseVector("PERIODIC",period); + std::vector period; + parseVector("PERIODIC",period); if( period.size()==1 ) { - if( period[0]!="NO") error("input to PERIODIC keyword does not make sense"); + if( period[0]!="NO") { + error("input to PERIODIC keyword does not make sense"); + } setNotPeriodic(); - } else if( period.size()==2 ) setPeriodic( period[0], period[1] ); - else error("input to PERIODIC keyword does not make sense"); - - parseFlag("CONSTANT",fixed); if( fixed ) { noforce=true; copyOutput(0)->setConstant(); } - parseFlag("FROM_DOMAINS",from_domains); parseFlag("MUTABLE",resetable); + } else if( period.size()==2 ) { + setPeriodic( period[0], period[1] ); + } else { + error("input to PERIODIC keyword does not make sense"); + } + + parseFlag("CONSTANT",fixed); + if( fixed ) { + noforce=true; + copyOutput(0)->setConstant(); + } + parseFlag("FROM_DOMAINS",from_domains); + parseFlag("MUTABLE",resetable); } } void ActionToPutData::setUnit( const std::string& unitstr, const std::string& funitstr ) { - if( unitstr=="number" ) unit=n; - else if( unitstr=="energy" ) unit=e; - else if( unitstr=="length" ) unit=l; - else if( unitstr=="mass" ) unit=m; - else if( unitstr=="charge" ) unit=q; - else if( unitstr=="time" ) unit=t; - else error( unitstr + " is not a valid input unit"); + if( unitstr=="number" ) { + unit=n; + } else if( unitstr=="energy" ) { + unit=e; + } else if( unitstr=="length" ) { + unit=l; + } else if( unitstr=="mass" ) { + unit=m; + } else if( unitstr=="charge" ) { + unit=q; + } else if( unitstr=="time" ) { + unit=t; + } else { + error( unitstr + " is not a valid input unit"); + } // Set the force units - if( funitstr=="default" ) funit=d; - else if( funitstr=="energy" ) funit=eng; - else error( funitstr + " is not a valid input force unit"); + if( funitstr=="default" ) { + funit=d; + } else if( funitstr=="energy" ) { + funit=eng; + } else { + error( funitstr + " is not a valid input force unit"); + } } std::string ActionToPutData::getUnitName() const { - if( unit==e ) return "energy"; - if( unit==l ) return "length"; - if( unit==m ) return "mass"; - if( unit==q ) return "charge"; - if( unit==t ) return "time"; + if( unit==e ) { + return "energy"; + } + if( unit==l ) { + return "length"; + } + if( unit==m ) { + return "mass"; + } + if( unit==q ) { + return "charge"; + } + if( unit==t ) { + return "time"; + } plumed_error(); } void ActionToPutData::setStart( const std::string& name, const unsigned& sss) { - plumed_assert( name==getLabel() ); mydata->setStart(sss); + plumed_assert( name==getLabel() ); + mydata->setStart(sss); } void ActionToPutData::setStride( const std::string& name, const unsigned& sss ) { - plumed_assert( name==getLabel() ); mydata->setStride(sss); + plumed_assert( name==getLabel() ); + mydata->setStride(sss); } void ActionToPutData::updateUnits( DataPassingTools* passtools ) { // Don't need to do anythign if this is just a number - if( unit==n ) return ; + if( unit==n ) { + return ; + } double vunits=passtools->getUnitConversion( getUnitName() ); - mydata->setUnit(vunits); if( fixed && wasset ) mydata->share_data( 0, getPntrToValue()->getNumberOfValues(), getPntrToValue() ); - if( funit==eng ) mydata->setForceUnit( 1/passtools->getUnitConversion("energy")); - else if( funit==d ) mydata->setForceUnit(1/passtools->getUnitConversion("energy")*vunits); + mydata->setUnit(vunits); + if( fixed && wasset ) { + mydata->share_data( 0, getPntrToValue()->getNumberOfValues(), getPntrToValue() ); + } + if( funit==eng ) { + mydata->setForceUnit( 1/passtools->getUnitConversion("energy")); + } else if( funit==d ) { + mydata->setForceUnit(1/passtools->getUnitConversion("energy")*vunits); + } } bool ActionToPutData::setValuePointer( const std::string& name, const TypesafePtr & val ) { - if( name!=getLabel() ) return false; - wasset=true; plumed_massert( dataCanBeSet, "set " + getLabel() + " cannot be set at this time"); + if( name!=getLabel() ) { + return false; + } + wasset=true; + plumed_massert( dataCanBeSet, "set " + getLabel() + " cannot be set at this time"); if( !from_domains ) { if( !resetable && getPntrToComponent(0)->getRank()==0 ) { mydata->saveValueAsDouble( val ); - if( fixed ) mydata->share_data( 0, getPntrToValue()->getNumberOfValues(), getPntrToValue() ); - } else mydata->setValuePointer(val,getPntrToComponent(0)->getShape(), !resetable); - } else mydata->setValuePointer(val,std::vector(), !resetable); + if( fixed ) { + mydata->share_data( 0, getPntrToValue()->getNumberOfValues(), getPntrToValue() ); + } + } else { + mydata->setValuePointer(val,getPntrToComponent(0)->getShape(), !resetable); + } + } else { + mydata->setValuePointer(val,std::vector(), !resetable); + } return true; } bool ActionToPutData::setForcePointer( const std::string& name, const TypesafePtr & val ) { - if( name!=getLabel() ) return false; + if( name!=getLabel() ) { + return false; + } plumed_massert( dataCanBeSet, "force on " + getLabel() + " cannot be set at this time"); - if( !from_domains ) mydata->setForcePointer(val,getPntrToComponent(0)->getShape()); - else mydata->setForcePointer(val,std::vector()); + if( !from_domains ) { + mydata->setForcePointer(val,getPntrToComponent(0)->getShape()); + } else { + mydata->setForcePointer(val,std::vector()); + } return true; } @@ -149,18 +212,26 @@ void ActionToPutData::getLocalValues( std::vector& vals ) const { } void ActionToPutData::wait() { - dataCanBeSet=false; if( fixed || !wasset ) { return; } plumed_assert( wasset ); + dataCanBeSet=false; + if( fixed || !wasset ) { + return; + } + plumed_assert( wasset ); mydata->share_data( 0, getPntrToValue()->getNumberOfValues(), getPntrToValue() ); } void ActionToPutData::apply() { if( getPntrToValue()->forcesWereAdded() && !noforce ) { - if( getName()=="ENERGY" || getDependencies().size()==0 ) mydata->add_force( getPntrToValue() ); + if( getName()=="ENERGY" || getDependencies().size()==0 ) { + mydata->add_force( getPntrToValue() ); + } } } unsigned ActionToPutData::getNumberOfForcesToRescale() const { - if( getName()!="ENERGY" || getDependencies().size()>0 ) return copyOutput(0)->getNumberOfValues(); + if( getName()!="ENERGY" || getDependencies().size()>0 ) { + return copyOutput(0)->getNumberOfValues(); + } plumed_assert( getDependencies().size()==1 ); plumed_assert(getDependencies()[0]); // needed for following calls, see #1046 ActionForInterface* ai = getDependencies()[0]->castToActionForInterface(); @@ -168,17 +239,24 @@ unsigned ActionToPutData::getNumberOfForcesToRescale() const { } void ActionToPutData::rescaleForces( const double& alpha ) { - if( noforce ) return; wasscaled=true; + if( noforce ) { + return; + } + wasscaled=true; mydata->rescale_force( getNumberOfForcesToRescale(), alpha, getPntrToValue() ); } void ActionToPutData::writeBinary(std::ostream&o) { - if(!fixed) getPntrToValue()->writeBinary(o); + if(!fixed) { + getPntrToValue()->writeBinary(o); + } } void ActionToPutData::readBinary(std::istream&i) { - if(!fixed) getPntrToValue()->readBinary(i); + if(!fixed) { + getPntrToValue()->readBinary(i); + } } } diff --git a/src/core/ActionToPutData.h b/src/core/ActionToPutData.h index dbbf96008d..6efe24cee4 100644 --- a/src/core/ActionToPutData.h +++ b/src/core/ActionToPutData.h @@ -30,8 +30,7 @@ namespace PLMD { class ActionToPutData : - public ActionForInterface -{ + public ActionForInterface { friend class PlumedMain; friend class TimeStep; friend class DomainDecomposition; @@ -67,7 +66,9 @@ class ActionToPutData : /// Update the units on the input data void updateUnits( DataPassingTools* passtools ); /// This is called at the start of the step - void resetForStepStart() override { dataCanBeSet = true; } + void resetForStepStart() override { + dataCanBeSet = true; + } /// These are the actions that set the pointers to the approrpiate values virtual bool setValuePointer( const std::string& name, const TypesafePtr & val ) override ; bool setForcePointer( const std::string& name, const TypesafePtr & val ) override ; @@ -88,8 +89,12 @@ class ActionToPutData : /// For replica exchange void writeBinary(std::ostream&o) override; virtual void readBinary(std::istream&i) override; - bool onStep() const override { return false; } - ActionToPutData* castToActionToPutData() noexcept final { return this; } + bool onStep() const override { + return false; + } + ActionToPutData* castToActionToPutData() noexcept final { + return this; + } }; } diff --git a/src/core/ActionWithArguments.cpp b/src/core/ActionWithArguments.cpp index a1b9208e6a..3bb5f61d52 100644 --- a/src/core/ActionWithArguments.cpp +++ b/src/core/ActionWithArguments.cpp @@ -48,10 +48,16 @@ void ActionWithArguments::registerKeywords(Keywords& keys) { } void ActionWithArguments::parseArgumentList(const std::string&key,std::vector&arg) { - std::string def; std::vector c; arg.clear(); parseVector(key,c); + std::string def; + std::vector c; + arg.clear(); + parseVector(key,c); if( c.size()==0 && (keywords.style(key,"compulsory") || keywords.style(key,"hidden")) ) { - if( keywords.getDefaultValue(key,def) ) c.push_back( def ); - else return; + if( keywords.getDefaultValue(key,def) ) { + c.push_back( def ); + } else { + return; + } } interpretArgumentList(c,plumed.getActionSet(),this,arg); } @@ -62,7 +68,9 @@ bool ActionWithArguments::parseArgumentList(const std::string&key,int i,std::vec if(parseNumberedVector(key,i,c)) { interpretArgumentList(c,plumed.getActionSet(),this,arg); return true; - } else return false; + } else { + return false; + } } void ActionWithArguments::interpretArgumentList(const std::vector& c, const ActionSet& as, Action* readact, std::vector&arg) { @@ -76,7 +84,9 @@ void ActionWithArguments::interpretArgumentList(const std::vector& // take the string enclosed in quotes and put in round brackets std::string myregex=c[i]; std::vector all=as.select(); - if( all.empty() ) readact->error("your input file is not telling plumed to calculate anything"); + if( all.empty() ) { + readact->error("your input file is not telling plumed to calculate anything"); + } try { std::regex txt_regex(myregex,std::regex::extended); @@ -93,7 +103,9 @@ void ActionWithArguments::interpretArgumentList(const std::vector& } catch(std::regex_error & e) { plumed_error()<<"Error parsing regular expression: "<& if(a=="*" && name=="*") { // Take all values from all actions std::vector all=as.select(); - if( all.empty() ) readact->error("your input file is not telling plumed to calculate anything"); + if( all.empty() ) { + readact->error("your input file is not telling plumed to calculate anything"); + } for(unsigned j=0; jcastToActionForInterface(); if( ap ) continue; - for(int k=0; kgetNumberOfComponents(); ++k) arg.push_back(all[j]->copyOutput(k)); + ActionForInterface* ap=all[j]->castToActionForInterface(); + if( ap ) { + continue; + } + for(int k=0; kgetNumberOfComponents(); ++k) { + arg.push_back(all[j]->copyOutput(k)); + } } } else if ( name=="*") { unsigned carg=arg.size(); // Take all the values from an action with a specific name ActionShortcut* shortcut=as.getShortcutActionWithLabel(a); - if( shortcut ) shortcut->interpretDataLabel( a + "." + name, readact, arg ); + if( shortcut ) { + shortcut->interpretDataLabel( a + "." + name, readact, arg ); + } if( arg.size()==carg ) { // Take all the values from an action with a specific name ActionWithValue* action=as.selectWithLabel(a); @@ -124,24 +145,36 @@ void ActionWithArguments::interpretArgumentList(const std::vector& str+=as.getLabelList()+")"; readact->error("cannot find action named " + a + str); } - if( action->getNumberOfComponents()==0 ) readact->error("found " + a +".* indicating use all components calculated by action with label " + a + " but this action has no components"); - for(int k=0; kgetNumberOfComponents(); ++k) arg.push_back(action->copyOutput(k)); + if( action->getNumberOfComponents()==0 ) { + readact->error("found " + a +".* indicating use all components calculated by action with label " + a + " but this action has no components"); + } + for(int k=0; kgetNumberOfComponents(); ++k) { + arg.push_back(action->copyOutput(k)); + } } } else if ( a=="*" ) { std::vector shortcuts=as.select(); // Take components from all actions with a specific name std::vector all=as.select(); - if( all.empty() ) readact->error("your input file is not telling plumed to calculate anything"); + if( all.empty() ) { + readact->error("your input file is not telling plumed to calculate anything"); + } unsigned carg=arg.size(); for(unsigned j=0; jinterpretDataLabel( shortcuts[j]->getShortcutLabel() + "." + name, readact, arg ); } unsigned nval=0; for(unsigned j=0; jgetLabel() + "." + name; - if( all[j]->exists(flab) ) { arg.push_back(all[j]->copyOutput(flab)); nval++; } + std::string flab; + flab=all[j]->getLabel() + "." + name; + if( all[j]->exists(flab) ) { + arg.push_back(all[j]->copyOutput(flab)); + nval++; + } + } + if(nval==0 && arg.size()==carg) { + readact->error("found no actions with a component called " + name ); } - if(nval==0 && arg.size()==carg) readact->error("found no actions with a component called " + name ); } else { // Take values with a specific name ActionWithValue* action=as.selectWithLabel(a); @@ -153,8 +186,11 @@ void ActionWithArguments::interpretArgumentList(const std::vector& } else if( action && action->exists(c[i]) ) { arg.push_back(action->copyOutput(c[i])); } else if( shortcut ) { - unsigned narg=arg.size(); shortcut->interpretDataLabel( a + "." + name, readact, arg ); - if( arg.size()==narg ) readact->error("found no element in " + a + " with label " + name ); + unsigned narg=arg.size(); + shortcut->interpretDataLabel( a + "." + name, readact, arg ); + if( arg.size()==narg ) { + readact->error("found no element in " + a + " with label " + name ); + } } else { std::string str=" (hint! the components in this actions are: "; str+=action->getComponentsList()+")"; @@ -165,12 +201,22 @@ void ActionWithArguments::interpretArgumentList(const std::vector& if(c[i]=="*") { // Take all values from all actions std::vector all=as.select(); - if( all.empty() ) readact->error("your input file is not telling plumed to calculate anything"); + if( all.empty() ) { + readact->error("your input file is not telling plumed to calculate anything"); + } for(unsigned j=0; jcastToActionWithVirtualAtom(); if( av ) continue; - ActionForInterface* ap=all[j]->castToActionForInterface(); if( ap && all[j]->getName()!="ENERGY" ) continue; - for(int k=0; kgetNumberOfComponents(); ++k) arg.push_back(all[j]->copyOutput(k)); + ActionWithVirtualAtom* av=all[j]->castToActionWithVirtualAtom(); + if( av ) { + continue; + } + ActionForInterface* ap=all[j]->castToActionForInterface(); + if( ap && all[j]->getName()!="ENERGY" ) { + continue; + } + for(int k=0; kgetNumberOfComponents(); ++k) { + arg.push_back(all[j]->copyOutput(k)); + } } } else { ActionWithValue* action=as.selectWithLabel(c[i]); @@ -218,7 +264,9 @@ void ActionWithArguments::requestArguments(const std::vector &arg) { addDependency(action); } ActionWithValue* av=dynamic_cast(this); - if(av) av->firststep=true; + if(av) { + av->firststep=true; + } } void ActionWithArguments::requestExtraDependencies(const std::vector &extra) { @@ -241,8 +289,7 @@ void ActionWithArguments::requestExtraDependencies(const std::vector &ex ActionWithArguments::ActionWithArguments(const ActionOptions&ao): Action(ao), - lockRequestArguments(false) -{ + lockRequestArguments(false) { if( keywords.exists("ARG") ) { std::vector arg; parseArgumentList("ARG",arg); @@ -250,11 +297,17 @@ ActionWithArguments::ActionWithArguments(const ActionOptions&ao): if(!arg.empty()) { log.printf(" with arguments : \n"); for(unsigned i=0; ihasDerivatives() && arg[i]->getRank()>0 ) log.printf(" function on grid with label %s \n",arg[i]->getName().c_str()); - else if( arg[i]->getRank()==2 ) log.printf(" matrix with label %s \n",arg[i]->getName().c_str()); - else if( arg[i]->getRank()==1 ) log.printf(" vector with label %s \n",arg[i]->getName().c_str()); - else if( arg[i]->getRank()==0 ) log.printf(" scalar with label %s \n",arg[i]->getName().c_str()); - else error("type of argument does not make sense"); + if( arg[i]->hasDerivatives() && arg[i]->getRank()>0 ) { + log.printf(" function on grid with label %s \n",arg[i]->getName().c_str()); + } else if( arg[i]->getRank()==2 ) { + log.printf(" matrix with label %s \n",arg[i]->getName().c_str()); + } else if( arg[i]->getRank()==1 ) { + log.printf(" vector with label %s \n",arg[i]->getName().c_str()); + } else if( arg[i]->getRank()==0 ) { + log.printf(" scalar with label %s \n",arg[i]->getName().c_str()); + } else { + error("type of argument does not make sense"); + } } } requestArguments(arg); @@ -283,7 +336,10 @@ void ActionWithArguments::calculateNumericalDerivatives( ActionWithValue* a ) { a->clearDerivatives(); for(int j=0; jcopyOutput(j); - if( v->hasDerivatives() ) for(int i=0; iaddDerivative(i,(value[i*nval+j]-a->getOutputQuantity(j))/std::sqrt(epsilon)); + if( v->hasDerivatives() ) + for(int i=0; iaddDerivative(i,(value[i*nval+j]-a->getOutputQuantity(j))/std::sqrt(epsilon)); + } } } @@ -297,36 +353,57 @@ double ActionWithArguments::getProjection(unsigned i,unsigned j)const { void ActionWithArguments::addForcesOnArguments( const unsigned& argstart, const std::vector& forces, unsigned& ind, const std::string& c ) { for(unsigned i=0; iignoreStoredValue(c) || arguments[i]->getRank()==0 || (arguments[i]->getRank()>0 && arguments[i]->hasDerivatives()) ) { unsigned nvals = arguments[i]->getNumberOfStoredValues(); - for(unsigned j=0; jaddForce( j, forces[ind], false ); ind++; } + for(unsigned j=0; jaddForce( j, forces[ind], false ); + ind++; + } } } } void ActionWithArguments::setGradients( Value* myval, unsigned& start ) const { - if( !myval->hasDeriv ) return; plumed_assert( myval->getRank()==0 ); + if( !myval->hasDeriv ) { + return; + } + plumed_assert( myval->getRank()==0 ); bool scalar=true; for(unsigned i=0; igetRank()!=0 ) { scalar=false; break; } + if( arguments[i]->getRank()!=0 ) { + scalar=false; + break; + } } if( !scalar ) { bool constant=true; for(unsigned i=0; iisConstant() ) { constant=false; break; } - else start += arguments[i]->getNumberOfValues(); + if( !arguments[i]->isConstant() ) { + constant=false; + break; + } else { + start += arguments[i]->getNumberOfValues(); + } + } + if( !constant ) { + error("cannot set gradient as unable to handle non-constant actions that take vectors/matrices/grids in input"); } - if( !constant ) error("cannot set gradient as unable to handle non-constant actions that take vectors/matrices/grids in input"); } // Now pass the gradients - for(unsigned i=0; ipassGradients( myval->getDerivative(i), myval->gradients ); + for(unsigned i=0; ipassGradients( myval->getDerivative(i), myval->gradients ); + } } bool ActionWithArguments::calculateConstantValues( const bool& haveatoms ) { ActionWithValue* av = castToActionWithValue(); - if( !av || arguments.size()==0 ) return false; + if( !av || arguments.size()==0 ) { + return false; + } bool constant = true, atoms=false; for(unsigned i=0; igetPntrToAction(); @@ -334,23 +411,39 @@ bool ActionWithArguments::calculateConstantValues( const bool& haveatoms ) { ActionAtomistic* aa=ptr->castToActionAtomistic(); if( aa ) { ActionWithVector* av=dynamic_cast( arguments[i]->getPntrToAction() ); - if( !av || aa->getNumberOfAtoms()>0 ) atoms=true; + if( !av || aa->getNumberOfAtoms()>0 ) { + atoms=true; + } + } + if( !arguments[i]->isConstant() ) { + constant=false; + break; } - if( !arguments[i]->isConstant() ) { constant=false; break; } } if( constant ) { // Set everything constant first as we need to set the shape - for(unsigned i=0; igetNumberOfComponents(); ++i) (av->copyOutput(i))->setConstant(); - if( !haveatoms ) log.printf(" values stored by this action are computed during startup and stay fixed during the simulation\n"); - if( atoms ) return haveatoms; + for(unsigned i=0; igetNumberOfComponents(); ++i) { + (av->copyOutput(i))->setConstant(); + } + if( !haveatoms ) { + log.printf(" values stored by this action are computed during startup and stay fixed during the simulation\n"); + } + if( atoms ) { + return haveatoms; + } } // Now do the calculation and store the values if we don't need anything from the atoms if( constant && !haveatoms ) { - plumed_assert( !atoms ); activate(); calculate(); deactivate(); + plumed_assert( !atoms ); + activate(); + calculate(); + deactivate(); for(unsigned i=0; igetNumberOfComponents(); ++i) { unsigned nv = av->copyOutput(i)->getNumberOfValues(); log.printf(" %d values stored in component labelled %s are : ", nv, (av->copyOutput(i))->getName().c_str() ); - for(unsigned j=0; jcopyOutput(i))->get(j) ); + for(unsigned j=0; jcopyOutput(i))->get(j) ); + } log.printf("\n"); } } diff --git a/src/core/ActionWithArguments.h b/src/core/ActionWithArguments.h index 21725fba6b..ef6bf26093 100644 --- a/src/core/ActionWithArguments.h +++ b/src/core/ActionWithArguments.h @@ -42,8 +42,7 @@ This is used in PLMD::Function and PLMD::Bias class ActionSet; class ActionWithArguments: - public virtual Action -{ + public virtual Action { std::vector arguments; bool lockRequestArguments; protected: @@ -90,7 +89,9 @@ class ActionWithArguments: virtual bool calculateConstantValues( const bool& have_atoms ); /// Get the gradient for this action void setGradients( Value* myval, unsigned& start ) const ; - ActionWithArguments* castToActionWithArguments() noexcept final { return this; } + ActionWithArguments* castToActionWithArguments() noexcept final { + return this; + } }; diff --git a/src/core/ActionWithMatrix.cpp b/src/core/ActionWithMatrix.cpp index bc0609f41b..77ea78f3ea 100644 --- a/src/core/ActionWithMatrix.cpp +++ b/src/core/ActionWithMatrix.cpp @@ -25,7 +25,8 @@ namespace PLMD { void ActionWithMatrix::registerKeywords( Keywords& keys ) { - ActionWithVector::registerKeywords( keys ); keys.use("ARG"); + ActionWithVector::registerKeywords( keys ); + keys.use("ARG"); } ActionWithMatrix::ActionWithMatrix(const ActionOptions&ao): @@ -34,21 +35,29 @@ ActionWithMatrix::ActionWithMatrix(const ActionOptions&ao): next_action_in_chain(NULL), matrix_to_do_before(NULL), matrix_to_do_after(NULL), - clearOnEachCycle(true) -{ + clearOnEachCycle(true) { } ActionWithMatrix::~ActionWithMatrix() { - if( matrix_to_do_before ) { matrix_to_do_before->matrix_to_do_after=NULL; matrix_to_do_before->next_action_in_chain=NULL; } + if( matrix_to_do_before ) { + matrix_to_do_before->matrix_to_do_after=NULL; + matrix_to_do_before->next_action_in_chain=NULL; + } } void ActionWithMatrix::getAllActionLabelsInMatrixChain( std::vector& mylabels ) const { bool found=false; for(unsigned i=0; igetAllActionLabelsInMatrixChain( mylabels ); } - if( !found ) mylabels.push_back( getLabel() ); - if( matrix_to_do_after ) matrix_to_do_after->getAllActionLabelsInMatrixChain( mylabels ); } void ActionWithMatrix::setupStreamedComponents( const std::string& headstr, unsigned& nquants, unsigned& nmat, unsigned& maxcol, unsigned& nbookeeping ) { @@ -56,10 +65,17 @@ void ActionWithMatrix::setupStreamedComponents( const std::string& headstr, unsi for(int i=0; igetRank()!=2 || myval->hasDerivatives() ) continue; - myval->setPositionInMatrixStash(nmat); nmat++; - if( !myval->valueIsStored() ) continue; - if( myval->getShape()[1]>maxcol ) maxcol=myval->getShape()[1]; + if( myval->getRank()!=2 || myval->hasDerivatives() ) { + continue; + } + myval->setPositionInMatrixStash(nmat); + nmat++; + if( !myval->valueIsStored() ) { + continue; + } + if( myval->getShape()[1]>maxcol ) { + maxcol=myval->getShape()[1]; + } myval->setMatrixBookeepingStart(nbookeeping); nbookeeping += myval->getShape()[0]*( 1 + myval->getNumberOfColumns() ); } @@ -67,47 +83,70 @@ void ActionWithMatrix::setupStreamedComponents( const std::string& headstr, unsi clearOnEachCycle = false; for(int i=0; igetRank()==2 && !myval->hasDerivatives() ) { clearOnEachCycle = true; break; } + if( myval->getRank()==2 && !myval->hasDerivatives() ) { + clearOnEachCycle = true; + break; + } } // Turn off clearing of derivatives if we have only the values of adjacency matrices - if( doNotCalculateDerivatives() && isAdjacencyMatrix() ) clearOnEachCycle = false; + if( doNotCalculateDerivatives() && isAdjacencyMatrix() ) { + clearOnEachCycle = false; + } } void ActionWithMatrix::finishChainBuild( ActionWithVector* act ) { - ActionWithMatrix* am=dynamic_cast(act); if( !am || act==this ) return; + ActionWithMatrix* am=dynamic_cast(act); + if( !am || act==this ) { + return; + } // Build the list that contains everything we are going to loop over in getTotalMatrixBookeepgin and updateAllNeighbourLists - if( next_action_in_chain ) next_action_in_chain->finishChainBuild( act ); - else { + if( next_action_in_chain ) { + next_action_in_chain->finishChainBuild( act ); + } else { next_action_in_chain=am; // Build the list of things we are going to loop over in runTask - if( am->isAdjacencyMatrix() || act->getName()=="VSTACK" ) return ; + if( am->isAdjacencyMatrix() || act->getName()=="VSTACK" ) { + return ; + } plumed_massert( !matrix_to_do_after, "cannot add " + act->getLabel() + " in " + getLabel() + " as have already added " + matrix_to_do_after->getLabel() ); - matrix_to_do_after=am; am->matrix_to_do_before=this; + matrix_to_do_after=am; + am->matrix_to_do_before=this; } } const ActionWithMatrix* ActionWithMatrix::getFirstMatrixInChain() const { - if( !actionInChain() ) return this; + if( !actionInChain() ) { + return this; + } return matrix_to_do_before->getFirstMatrixInChain(); } void ActionWithMatrix::getTotalMatrixBookeeping( unsigned& nbookeeping ) { for(int i=0; igetRank()!=2 || myval->hasDerivatives() || !myval->valueIsStored() ) continue; + if( myval->getRank()!=2 || myval->hasDerivatives() || !myval->valueIsStored() ) { + continue; + } myval->reshapeMatrixStore( getNumberOfColumns() ); nbookeeping += myval->getShape()[0]*( 1 + myval->getNumberOfColumns() ); } - if( next_action_in_chain ) next_action_in_chain->getTotalMatrixBookeeping( nbookeeping ); + if( next_action_in_chain ) { + next_action_in_chain->getTotalMatrixBookeeping( nbookeeping ); + } } void ActionWithMatrix::calculate() { - if( actionInChain() ) return ; + if( actionInChain() ) { + return ; + } // Update all the neighbour lists updateAllNeighbourLists(); // Setup the matrix indices - unsigned nbookeeping=0; getTotalMatrixBookeeping( nbookeeping ); - if( matrix_bookeeping.size()!=nbookeeping ) matrix_bookeeping.resize( nbookeeping ); + unsigned nbookeeping=0; + getTotalMatrixBookeeping( nbookeeping ); + if( matrix_bookeeping.size()!=nbookeeping ) { + matrix_bookeeping.resize( nbookeeping ); + } std::fill( matrix_bookeeping.begin(), matrix_bookeeping.end(), 0 ); // And run all the tasks runAllTasks(); @@ -115,7 +154,9 @@ void ActionWithMatrix::calculate() { void ActionWithMatrix::updateAllNeighbourLists() { updateNeighbourList(); - if( next_action_in_chain ) next_action_in_chain->updateAllNeighbourLists(); + if( next_action_in_chain ) { + next_action_in_chain->updateAllNeighbourLists(); + } } void ActionWithMatrix::performTask( const unsigned& task_index, MultiValue& myvals ) const { @@ -140,64 +181,97 @@ void ActionWithMatrix::performTask( const unsigned& task_index, MultiValue& myva } void ActionWithMatrix::runTask( const std::string& controller, const unsigned& current, const unsigned colno, MultiValue& myvals ) const { - double outval=0; myvals.setTaskIndex(current); myvals.setSecondTaskIndex( colno ); - if( isActive() ) performTask( controller, current, colno, myvals ); + double outval=0; + myvals.setTaskIndex(current); + myvals.setSecondTaskIndex( colno ); + if( isActive() ) { + performTask( controller, current, colno, myvals ); + } bool hasval = !isAdjacencyMatrix(); for(int i=0; igetPositionInStream()) )>0 ) { hasval=true; break; } + if( fabs(myvals.get( getConstPntrToComponent(i)->getPositionInStream()) )>0 ) { + hasval=true; + break; + } } if( hasval ) { for(int i=0; igetRank()!=2 || myval->hasDerivatives() || !myval->valueIsStored() ) continue; + if( myval->getRank()!=2 || myval->hasDerivatives() || !myval->valueIsStored() ) { + continue; + } unsigned matindex = myval->getPositionInMatrixStash(), matbook_start = myval->getMatrixBookeepingStart(), col_stash_index = colno; - if( colno>=myval->getShape()[0] ) col_stash_index = colno - myval->getShape()[0]; + if( colno>=myval->getShape()[0] ) { + col_stash_index = colno - myval->getShape()[0]; + } unsigned rowstart = matbook_start+current*(1+myval->getNumberOfColumns()); if( myval->forcesWereAdded() ) { unsigned sind = myval->getPositionInStream(), find = myvals.getMatrixBookeeping()[rowstart]; double fforce = myval->getForce( myvals.getTaskIndex()*myval->getNumberOfColumns() + find ); - if( getNumberOfColumns()>=myval->getShape()[1] ) fforce = myval->getForce( myvals.getTaskIndex()*myval->getShape()[1] + col_stash_index ); + if( getNumberOfColumns()>=myval->getShape()[1] ) { + fforce = myval->getForce( myvals.getTaskIndex()*myval->getShape()[1] + col_stash_index ); + } for(unsigned j=0; jgetPositionInStream() ); - if( fabs(finalval)>0 ) myvals.stashMatrixElement( matindex, rowstart, col_stash_index, finalval ); + if( fabs(finalval)>0 ) { + myvals.stashMatrixElement( matindex, rowstart, col_stash_index, finalval ); + } } } - if( matrix_to_do_after ) matrix_to_do_after->runTask( controller, current, colno, myvals ); + if( matrix_to_do_after ) { + matrix_to_do_after->runTask( controller, current, colno, myvals ); + } } void ActionWithMatrix::gatherThreads( const unsigned& nt, const unsigned& bufsize, const std::vector& omp_buffer, std::vector& buffer, MultiValue& myvals ) { ActionWithVector::gatherThreads( nt, bufsize, omp_buffer, buffer, myvals ); - for(unsigned i=0; i& buffer ) { ActionWithVector::gatherProcesses( buffer ); - if( matrix_bookeeping.size()>0 && !runInSerial() ) comm.Sum( matrix_bookeeping ); - unsigned nval=0; transferNonZeroMatrixElementsToValues( nval, matrix_bookeeping ); + if( matrix_bookeeping.size()>0 && !runInSerial() ) { + comm.Sum( matrix_bookeeping ); + } + unsigned nval=0; + transferNonZeroMatrixElementsToValues( nval, matrix_bookeeping ); } void ActionWithMatrix::transferNonZeroMatrixElementsToValues( unsigned& nval, const std::vector& matbook ) { for(int i=0; igetRank()!=2 || myval->hasDerivatives() || !myval->valueIsStored() || getNumberOfColumns()>=myval->getShape()[1] ) continue; + if( myval->getRank()!=2 || myval->hasDerivatives() || !myval->valueIsStored() || getNumberOfColumns()>=myval->getShape()[1] ) { + continue; + } unsigned nelements = myval->getShape()[0]*( 1 + myval->getNumberOfColumns() ); - for(unsigned j=0; jsetMatrixBookeepingElement( j, matbook[nval+j] ); + for(unsigned j=0; jsetMatrixBookeepingElement( j, matbook[nval+j] ); + } nval += nelements; } - if( next_action_in_chain ) next_action_in_chain->transferNonZeroMatrixElementsToValues( nval, matbook ); + if( next_action_in_chain ) { + next_action_in_chain->transferNonZeroMatrixElementsToValues( nval, matbook ); + } } void ActionWithMatrix::gatherStoredValue( const unsigned& valindex, const unsigned& code, const MultiValue& myvals, const unsigned& bufstart, std::vector& buffer ) const { - if( getConstPntrToComponent(valindex)->getRank()==1 ) { ActionWithVector::gatherStoredValue( valindex, code, myvals, bufstart, buffer ); return; } + if( getConstPntrToComponent(valindex)->getRank()==1 ) { + ActionWithVector::gatherStoredValue( valindex, code, myvals, bufstart, buffer ); + return; + } const Value* myval=getConstPntrToComponent(valindex); unsigned ncols = myval->getNumberOfColumns(), matind = myval->getPositionInMatrixStash(); unsigned matbook_start = myval->getMatrixBookeepingStart(), vindex = bufstart + code*myval->getNumberOfColumns(); - const std::vector & matbook( myvals.getMatrixBookeeping() ); unsigned nelements = matbook[matbook_start+code*(1+ncols)]; + const std::vector & matbook( myvals.getMatrixBookeeping() ); + unsigned nelements = matbook[matbook_start+code*(1+ncols)]; if( ncols>=myval->getShape()[1] ) { // In this case we store the full matrix for(unsigned j=0; jgetRank()<2 ) return ActionWithVector::checkForTaskForce( itask, myval ); + if( myval->getRank()<2 ) { + return ActionWithVector::checkForTaskForce( itask, myval ); + } unsigned nelements = myval->getRowLength(itask), startr = itask*myval->getNumberOfColumns(); for(unsigned j=0; jgetForce( startr + j ) )>epsilon ) return true; + if( fabs( myval->getForce( startr + j ) )>epsilon ) { + return true; + } } return false; } void ActionWithMatrix::gatherForcesOnStoredValue( const Value* myval, const unsigned& itask, const MultiValue& myvals, std::vector& forces ) const { - if( myval->getRank()==1 ) { ActionWithVector::gatherForcesOnStoredValue( myval, itask, myvals, forces ); return; } + if( myval->getRank()==1 ) { + ActionWithVector::gatherForcesOnStoredValue( myval, itask, myvals, forces ); + return; + } unsigned matind = myval->getPositionInMatrixStash(); - for(unsigned j=0; jgetRank()==2 && !myval->hasDerivatives() ) myvals.clearDerivatives( myval->getPositionInStream() ); + if( myval->getRank()==2 && !myval->hasDerivatives() ) { + myvals.clearDerivatives( myval->getPositionInStream() ); + } } } - if( matrix_to_do_after ) matrix_to_do_after->clearMatrixElements( myvals ); + if( matrix_to_do_after ) { + matrix_to_do_after->clearMatrixElements( myvals ); + } } } diff --git a/src/core/ActionWithMatrix.h b/src/core/ActionWithMatrix.h index 4cc4de4ee3..52d1e20674 100644 --- a/src/core/ActionWithMatrix.h +++ b/src/core/ActionWithMatrix.h @@ -61,7 +61,9 @@ class ActionWithMatrix : public ActionWithVector { explicit ActionWithMatrix(const ActionOptions&); virtual ~ActionWithMatrix(); /// - virtual bool isAdjacencyMatrix() const { return false; } + virtual bool isAdjacencyMatrix() const { + return false; + } /// void getAllActionLabelsInMatrixChain( std::vector& mylabels ) const override ; /// Get the first matrix in this chain @@ -103,14 +105,18 @@ bool ActionWithMatrix::matrixChainContinues() const { inline double ActionWithMatrix::getArgumentElement( const unsigned& ic, const unsigned& jelem, const MultiValue& myvals ) const { - if( !getPntrToArgument(ic)->valueHasBeenSet() ) return myvals.get( getPntrToArgument(ic)->getPositionInStream() ); + if( !getPntrToArgument(ic)->valueHasBeenSet() ) { + return myvals.get( getPntrToArgument(ic)->getPositionInStream() ); + } return getPntrToArgument(ic)->get( jelem ); } inline double ActionWithMatrix::getElementOfMatrixArgument( const unsigned& imat, const unsigned& irow, const unsigned& jcol, const MultiValue& myvals ) const { plumed_dbg_assert( imatgetRank()==2 && !getPntrToArgument(imat)->hasDerivatives() ); - if( !getPntrToArgument(imat)->valueHasBeenSet() ) return myvals.get( getPntrToArgument(imat)->getPositionInStream() ); + if( !getPntrToArgument(imat)->valueHasBeenSet() ) { + return myvals.get( getPntrToArgument(imat)->getPositionInStream() ); + } return getArgumentElement( imat, irow*getPntrToArgument(imat)->getShape()[1] + jcol, myvals ); } @@ -119,7 +125,8 @@ void ActionWithMatrix::addDerivativeOnVectorArgument( const bool& inchain, const plumed_dbg_massert( jarggetRank()<2, "failing in action " + getName() + " with label " + getLabel() ); unsigned ostrn = getConstPntrToComponent(ival)->getPositionInStream(), vstart=arg_deriv_starts[jarg]; if( !inchain ) { - myvals.addDerivative( ostrn, vstart + jelem, der ); myvals.updateIndex( ostrn, vstart + jelem ); + myvals.addDerivative( ostrn, vstart + jelem, der ); + myvals.updateIndex( ostrn, vstart + jelem ); } else { unsigned istrn = getPntrToArgument(jarg)->getPositionInStream(); for(unsigned k=0; kgetPositionInStream(), vstart=arg_deriv_starts[jarg]; if( !inchain ) { unsigned dloc = vstart + irow*getPntrToArgument(jarg)->getNumberOfColumns() + jcol; - myvals.addDerivative( ostrn, dloc, der ); myvals.updateIndex( ostrn, dloc ); + myvals.addDerivative( ostrn, dloc, der ); + myvals.updateIndex( ostrn, dloc ); } else { unsigned istrn = getPntrToArgument(jarg)->getPositionInStream(); for(unsigned k=0; kclearInputForce(); + for(unsigned i=0; iclearInputForce(); + } } void ActionWithValue::clearDerivatives( const bool& force ) { @@ -74,7 +81,9 @@ void ActionWithValue::clearDerivatives( const bool& force ) { #pragma omp parallel num_threads(nt) { #pragma omp for - for(unsigned i=0; iclearDerivatives(); + for(unsigned i=0; iclearDerivatives(); + } } } @@ -82,20 +91,29 @@ void ActionWithValue::clearDerivatives( const bool& force ) { bool ActionWithValue::exists( const std::string& name ) const { for(unsigned i=0; iname==name) return true; + if (values[i]->name==name) { + return true; + } } return false; } void ActionWithValue::getMatrixColumnTitles( std::vector& argnames ) const { plumed_assert( getNumberOfComponents()==1 && getConstPntrToComponent(0)->getRank()==2 ); - unsigned nargs = getConstPntrToComponent(0)->getShape()[1]; std::string aname = getConstPntrToComponent(0)->getName(); - for(unsigned j=0; jgetShape()[1]; + std::string aname = getConstPntrToComponent(0)->getName(); + for(unsigned j=0; jname==name) return values[i].get(); + if (values[i]->name==name) { + return values[i].get(); + } } plumed_merror("there is no pointer with name " + name); } @@ -108,13 +126,17 @@ Value* ActionWithValue::copyOutput( const unsigned& n ) const { // -- HERE WE HAVE THE STUFF FOR THE DEFAULT VALUE -- // void ActionWithValue::addValue( const std::vector& shape ) { - if( !keywords.outputComponentExists(".#!value") ) warning("documentation for the value calculated by this action has not been included"); + if( !keywords.outputComponentExists(".#!value") ) { + warning("documentation for the value calculated by this action has not been included"); + } plumed_massert(values.empty(),"You have already added the default value for this action"); values.emplace_back(Tools::make_unique(this,getLabel(), false, shape ) ); } void ActionWithValue::addValueWithDerivatives( const std::vector& shape ) { - if( !keywords.outputComponentExists(".#!value") ) warning("documentation for the value calculated by this action has not been included"); + if( !keywords.outputComponentExists(".#!value") ) { + warning("documentation for the value calculated by this action has not been included"); + } plumed_massert(values.empty(),"You have already added the default value for this action"); values.emplace_back(Tools::make_unique(this,getLabel(), true, shape ) ); } @@ -122,7 +144,8 @@ void ActionWithValue::addValueWithDerivatives( const std::vector& shap void ActionWithValue::setNotPeriodic() { plumed_massert(values.size()==1,"The number of components is not equal to one"); plumed_massert(values[0]->name==getLabel(), "The value you are trying to set is not the default"); - values[0]->min=0; values[0]->max=0; + values[0]->min=0; + values[0]->max=0; values[0]->setupPeriodicity(); } @@ -139,7 +162,8 @@ void ActionWithValue::addComponent( const std::string& name, const std::vectorname!=getLabel(),"Cannot mix single values with components"); plumed_massert(values[i]->name!=thename,"there is already a value with this name: "+thename); @@ -156,7 +180,8 @@ void ActionWithValue::addComponentWithDerivatives( const std::string& name, cons plumed_merror("a description of component " + name + " has not been added to the manual. Components should be registered like keywords in " "registerKeywords as described in the developer doc."); } - std::string thename; thename=getLabel() + "." + name; + std::string thename; + thename=getLabel() + "." + name; for(unsigned i=0; iname!=getLabel(),"Cannot mix single values with components"); plumed_massert(values[i]->name!=thename,"there is already a value with this name: "+thename); @@ -169,19 +194,29 @@ void ActionWithValue::addComponentWithDerivatives( const std::string& name, cons } std::string ActionWithValue::getOutputComponentDescription( const std::string& cname, const Keywords& keys ) const { - if( keys.outputComponentExists(".#!custom") ) return "a quantity calculated by the action " + getName() + " with label " + getLabel(); - std::size_t und=cname.find_last_of("_"); std::size_t hyph=cname.find_first_of("-"); - if( und!=std::string::npos ) return keys.getOutputComponentDescription(cname.substr(und)) + " This particular component measures this quantity for the input CV named " + cname.substr(0,und); - if( hyph!=std::string::npos ) return keys.getOutputComponentDescription(cname.substr(0,hyph)) + " This is the " + cname.substr(hyph+1) + "th of these quantities"; + if( keys.outputComponentExists(".#!custom") ) { + return "a quantity calculated by the action " + getName() + " with label " + getLabel(); + } + std::size_t und=cname.find_last_of("_"); + std::size_t hyph=cname.find_first_of("-"); + if( und!=std::string::npos ) { + return keys.getOutputComponentDescription(cname.substr(und)) + " This particular component measures this quantity for the input CV named " + cname.substr(0,und); + } + if( hyph!=std::string::npos ) { + return keys.getOutputComponentDescription(cname.substr(0,hyph)) + " This is the " + cname.substr(hyph+1) + "th of these quantities"; + } plumed_massert( keys.outputComponentExists(cname), "component " + cname + " does not exist in " + keys.getDisplayName() + " if the component names are customizable then you should override this function" ); return keys.getOutputComponentDescription( cname ); } int ActionWithValue::getComponent( const std::string& name ) const { plumed_massert( !exists( getLabel() ), "You should not be calling this routine if you are using a value"); - std::string thename; thename=getLabel() + "." + name; + std::string thename; + thename=getLabel() + "." + name; for(unsigned i=0; iname==thename) return i; + if (values[i]->name==thename) { + return i; + } } plumed_merror("there is no component with name " + name); } @@ -204,7 +239,8 @@ std::vector ActionWithValue::getComponentsVector( ) const { void ActionWithValue::componentIsNotPeriodic( const std::string& name ) { int kk=getComponent(name); - values[kk]->min=0; values[kk]->max=0; + values[kk]->min=0; + values[kk]->max=0; values[kk]->setupPeriodicity(); } @@ -217,11 +253,21 @@ void ActionWithValue::setGradientsIfNeeded() { if(isOptionOn("GRADIENTS")) { ActionAtomistic* aa=castToActionAtomistic(); if(aa) { - for(unsigned i=0; igradients.clear(); values[i]->setGradients( aa, start ); } + for(unsigned i=0; igradients.clear(); + values[i]->setGradients( aa, start ); + } } else { ActionWithArguments* aarg = castToActionWithArguments(); - if( !aarg ) plumed_merror( "failing in " + getLabel() ); - for(unsigned i=0; igradients.clear(); aarg->setGradients( values[i].get(), start ); } + if( !aarg ) { + plumed_merror( "failing in " + getLabel() ); + } + for(unsigned i=0; igradients.clear(); + aarg->setGradients( values[i].get(), start ); + } } } } @@ -230,11 +276,15 @@ void ActionWithValue::turnOnDerivatives() { // Turn on the derivatives noderiv=false; // Resize the derivatives - for(unsigned i=0; iresizeDerivatives( getNumberOfDerivatives() ); + for(unsigned i=0; iresizeDerivatives( getNumberOfDerivatives() ); + } // And turn on the derivatives in all actions on which we are dependent for(unsigned i=0; icastToActionWithValue(); - if(vv) vv->turnOnDerivatives(); + if(vv) { + vv->turnOnDerivatives(); + } } } @@ -260,7 +310,9 @@ bool ActionWithValue::calculateOnUpdate() { const std::vector & args(aa->getArguments()); for(const auto & p : args ) { if( p->calculateOnUpdate() ) { - for(unsigned i=0; isetValType("calcFromAverage"); + for(unsigned i=0; isetValType("calcFromAverage"); + } break; } } @@ -268,7 +320,9 @@ bool ActionWithValue::calculateOnUpdate() { firststep=false; } for(unsigned i=0; icalculateOnUpdate() ) return true; + if( values[i]->calculateOnUpdate() ) { + return true; + } } return false; } @@ -276,19 +330,26 @@ bool ActionWithValue::calculateOnUpdate() { bool ActionWithValue::checkForForces() { const unsigned ncp=getNumberOfComponents(); unsigned nder=getNumberOfDerivatives(); - if( ncp==0 || nder==0 ) return false; + if( ncp==0 || nder==0 ) { + return false; + } unsigned nvalsWithForce=0; valsToForce.resize(ncp); for(unsigned i=0; ihasForce && !values[i]->isConstant() ) { - valsToForce[nvalsWithForce]=i; nvalsWithForce++; + valsToForce[nvalsWithForce]=i; + nvalsWithForce++; } } - if( nvalsWithForce==0 ) return false; + if( nvalsWithForce==0 ) { + return false; + } // Make sure forces to apply is empty of forces - if( forcesForApply.size()!=nder ) forcesForApply.resize( nder ); + if( forcesForApply.size()!=nder ) { + forcesForApply.resize( nder ); + } std::fill(forcesForApply.begin(),forcesForApply.end(),0); unsigned stride=1; @@ -299,12 +360,16 @@ bool ActionWithValue::checkForForces() { } unsigned nt=OpenMP::getNumThreads(); - if(nt>ncp/(4*stride)) nt=1; + if(nt>ncp/(4*stride)) { + nt=1; + } #pragma omp parallel num_threads(nt) { std::vector omp_f; - if( nt>1 ) omp_f.resize(nder,0); + if( nt>1 ) { + omp_f.resize(nder,0); + } #pragma omp for for(unsigned i=rank; iinputForce[0]; @@ -312,8 +377,11 @@ bool ActionWithValue::checkForForces() { int nn=nder; int one1=1; int one2=1; - if( nt>1 ) plumed_blas_daxpy(&nn,&ff,thisderiv.data()+1,&one1,omp_f.data(),&one2); - else plumed_blas_daxpy(&nn,&ff,thisderiv.data()+1,&one1,forcesForApply.data(),&one2); + if( nt>1 ) { + plumed_blas_daxpy(&nn,&ff,thisderiv.data()+1,&one1,omp_f.data(),&one2); + } else { + plumed_blas_daxpy(&nn,&ff,thisderiv.data()+1,&one1,forcesForApply.data(),&one2); + } // if( nt>1 ) for(unsigned j=0; j4*comm.Get_size()) comm.Sum(&forcesForApply[0],nder); + if(ncp>4*comm.Get_size()) { + comm.Sum(&forcesForApply[0],nder); + } return true; } diff --git a/src/core/ActionWithValue.h b/src/core/ActionWithValue.h index 343115fb85..a6f52bfde3 100644 --- a/src/core/ActionWithValue.h +++ b/src/core/ActionWithValue.h @@ -65,8 +65,7 @@ PLMD::Action you should use the routines with the word component in the name */ class ActionWithValue : - public virtual Action -{ + public virtual Action { friend class ActionWithVector; friend class ActionWithArguments; private: @@ -178,7 +177,9 @@ class ActionWithValue : /// This forces the class to use numerical derivatives void useNumericalDerivatives(); // These are things for using vectors of values as fields - virtual void checkFieldsAllowed() { error("cannot use this action as a field"); } + virtual void checkFieldsAllowed() { + error("cannot use this action as a field"); + } virtual unsigned getNumberOfDerivatives()=0; /// Activate the calculation of derivatives virtual void turnOnDerivatives(); @@ -186,7 +187,9 @@ class ActionWithValue : virtual void getMatrixColumnTitles( std::vector& argnames ) const ; /// This is used to check if we run calculate during the update step virtual bool calculateOnUpdate(); - ActionWithValue* castToActionWithValue() noexcept final { return this; } + ActionWithValue* castToActionWithValue() noexcept final { + return this; + } }; inline @@ -202,7 +205,9 @@ double ActionWithValue::getOutputQuantity( const std::string& name ) const { const std::string & valname=values[i]->name; if(valname.size()>offset+1 && valname[offset]=='.' ) { plumed_dbg_assert(Tools::startWith(valname,getLabel())); - if(!std::strcmp(valname.c_str()+offset+1,name.c_str())) return values[i]->get(); + if(!std::strcmp(valname.c_str()+offset+1,name.c_str())) { + return values[i]->get(); + } } } return 0.0; diff --git a/src/core/ActionWithVector.cpp b/src/core/ActionWithVector.cpp index 8dbb9ecedd..670297a560 100644 --- a/src/core/ActionWithVector.cpp +++ b/src/core/ActionWithVector.cpp @@ -30,7 +30,8 @@ namespace PLMD { void ActionWithVector::registerKeywords( Keywords& keys ) { Action::registerKeywords( keys ); ActionAtomistic::registerKeywords( keys ); - ActionWithValue::registerKeywords( keys ); keys.remove("NUMERICAL_DERIVATIVES"); + ActionWithValue::registerKeywords( keys ); + keys.remove("NUMERICAL_DERIVATIVES"); ActionWithArguments::registerKeywords( keys ); keys.addFlag("SERIAL",false,"do the calculation in serial. Do not parallelize"); } @@ -46,13 +47,16 @@ ActionWithVector::ActionWithVector(const ActionOptions&ao): never_reduce_tasks(false), reduce_tasks(false), atomsWereRetrieved(false), - done_in_chain(false) -{ - if( keywords.exists("SERIAL") ) parseFlag("SERIAL",serial); + done_in_chain(false) { + if( keywords.exists("SERIAL") ) { + parseFlag("SERIAL",serial); + } } ActionWithVector::~ActionWithVector() { - if( action_to_do_before ) action_to_do_before->action_to_do_after=NULL; + if( action_to_do_before ) { + action_to_do_before->action_to_do_after=NULL; + } } void ActionWithVector::lockRequests() { @@ -70,47 +74,70 @@ void ActionWithVector::calculateNumericalDerivatives(ActionWithValue* av) { } void ActionWithVector::clearDerivatives( const bool& force ) { - if( !force && actionInChain() ) return; + if( !force && actionInChain() ) { + return; + } ActionWithValue::clearDerivatives(); - if( action_to_do_after ) action_to_do_after->clearDerivatives( true ); + if( action_to_do_after ) { + action_to_do_after->clearDerivatives( true ); + } } void ActionWithVector::clearInputForces( const bool& force ) { - if( !force && actionInChain() ) return; + if( !force && actionInChain() ) { + return; + } ActionWithValue::clearInputForces(); - if( action_to_do_after ) action_to_do_after->clearInputForces( true ); + if( action_to_do_after ) { + action_to_do_after->clearInputForces( true ); + } } const ActionWithVector* ActionWithVector::getFirstActionInChain() const { - if( !actionInChain() ) return this; + if( !actionInChain() ) { + return this; + } return action_to_do_before->getFirstActionInChain(); } ActionWithVector* ActionWithVector::getFirstActionInChain() { - if( !actionInChain() ) return this; + if( !actionInChain() ) { + return this; + } return action_to_do_before->getFirstActionInChain(); } void ActionWithVector::retrieveAtoms( const bool& force ) { - if( !force && actionInChain() || atomsWereRetrieved ) return; - ActionAtomistic::retrieveAtoms(); atomsWereRetrieved = !actionInChain(); - if( action_to_do_after ) action_to_do_after->retrieveAtoms( true ); + if( !force && actionInChain() || atomsWereRetrieved ) { + return; + } + ActionAtomistic::retrieveAtoms(); + atomsWereRetrieved = !actionInChain(); + if( action_to_do_after ) { + action_to_do_after->retrieveAtoms( true ); + } } bool ActionWithVector::hasStoredArguments() const { std::string headstr=getFirstActionInChain()->getLabel(); for(unsigned i=0; iignoreStoredValue(headstr) ) return true; + if( !getPntrToArgument(i)->ignoreStoredValue(headstr) ) { + return true; + } } return false; } bool ActionWithVector::argumentDependsOn( const std::string& headstr, ActionWithVector* faction, Value* thearg ) { for(unsigned i=0; i( getPntrToArgument(i)->getPntrToAction() ); if( av && (av->getFirstActionInChain())->getLabel()==headstr ) { - if( av->argumentDependsOn( headstr, faction, thearg ) ) return true;; + if( av->argumentDependsOn( headstr, faction, thearg ) ) { + return true; + }; } } return false; @@ -119,42 +146,72 @@ bool ActionWithVector::argumentDependsOn( const std::string& headstr, ActionWith unsigned ActionWithVector::buildArgumentStore( const unsigned& argstart ) { // Don't use chains for grids for(unsigned i=argstart; iisConstant() ) continue; + if( getPntrToArgument(i)->isConstant() ) { + continue; + } ActionWithVector* av=dynamic_cast(getPntrToArgument(i)->getPntrToAction()); - if( !av || getPntrToArgument(i)->getRank()>0 && getPntrToArgument(i)->hasDerivatives() ) { done_in_chain=false; break; } + if( !av || getPntrToArgument(i)->getRank()>0 && getPntrToArgument(i)->hasDerivatives() ) { + done_in_chain=false; + break; + } } if( done_in_chain ) { - std::vector alabels; std::vector f_actions; + std::vector alabels; + std::vector f_actions; for(unsigned i=argstart; igetPntrToAction())->getLabel(); + bool found=false; + std::string mylab = (getPntrToArgument(i)->getPntrToAction())->getLabel(); for(unsigned j=0; jisConstant() ) continue; + if( getPntrToArgument(i)->isConstant() ) { + continue; + } // Find the chain we need to add this to from the arguments - ActionWithVector* av=dynamic_cast(getPntrToArgument(i)->getPntrToAction()); plumed_assert( av ); - found=false; ActionWithVector* myact = av->getFirstActionInChain(); + ActionWithVector* av=dynamic_cast(getPntrToArgument(i)->getPntrToAction()); + plumed_assert( av ); + found=false; + ActionWithVector* myact = av->getFirstActionInChain(); if( getPntrToArgument(i)->getRank()==1 && getPntrToArgument(i)->storedata ) { for(unsigned j=argstart; j( getPntrToArgument(j)->getPntrToAction() ); - if( !aarg || i==j ) continue; + if( !aarg || i==j ) { + continue; + } for(unsigned k=0; kgetNumberOfArguments(); ++k) { - if( aarg->getPntrToArgument(k)==getPntrToArgument(i) ) { done_in_chain=false; return reallyBuildArgumentStore( argstart ); } + if( aarg->getPntrToArgument(k)==getPntrToArgument(i) ) { + done_in_chain=false; + return reallyBuildArgumentStore( argstart ); + } } } } for(unsigned j=0; j0 ) { - if( f_actions[0]->checkForDependency(myact) ) getPntrToArgument(i)->buildDataStore(); - if( myact->checkForDependency(f_actions[0]) ) error("cannot deal with arguments in this order. Try swapping argument order"); + if( f_actions[0]->checkForDependency(myact) ) { + getPntrToArgument(i)->buildDataStore(); + } + if( myact->checkForDependency(f_actions[0]) ) { + error("cannot deal with arguments in this order. Try swapping argument order"); + } + } + if( !getPntrToArgument(i)->storedata && getPntrToArgument(i)->getRank()>0 ) { + f_actions.push_back( myact ); } - if( !getPntrToArgument(i)->storedata && getPntrToArgument(i)->getRank()>0 ) f_actions.push_back( myact ); } } // Now make sure that everything we need is in the chain @@ -162,24 +219,42 @@ unsigned ActionWithVector::buildArgumentStore( const unsigned& argstart ) { // Check everything for later f_actions is done before f_actions[0] for(unsigned i=1; i( f_actions[i] ); - if( !aarg || aarg->getNumberOfArguments()==0 ) continue; + if( !aarg || aarg->getNumberOfArguments()==0 ) { + continue; + } for(unsigned j=0; jgetNumberOfArguments(); ++j) { - if( (aarg->getPntrToArgument(j))->isConstant() ) continue ; - bool found=false; std::string dep_argname = (aarg->getPntrToArgument(j))->getPntrToAction()->getLabel(); + if( (aarg->getPntrToArgument(j))->isConstant() ) { + continue ; + } + bool found=false; + std::string dep_argname = (aarg->getPntrToArgument(j))->getPntrToAction()->getLabel(); for(const auto & pp : plumed.getActionSet()) { Action* p(pp.get()); // Check if this is the dependency - if( p->getLabel()==dep_argname ) { found=true; break; } + if( p->getLabel()==dep_argname ) { + found=true; + break; + } // Check if this is the first of the arguments that will appear in this chain - else if( p->getLabel()==f_actions[0]->getLabel() ) break; + else if( p->getLabel()==f_actions[0]->getLabel() ) { + break; + } + } + if( !found ) { + done_in_chain=false; + break; } - if( !found ) { done_in_chain=false; break; } } // Stop trying to add things in the chain if we cannot - if( !done_in_chain ) return reallyBuildArgumentStore( argstart ); + if( !done_in_chain ) { + return reallyBuildArgumentStore( argstart ); + } + } + std::vector empty(1); + empty[0] = f_actions[0]->getLabel(); + for(unsigned i=1; iaddActionToChain( empty, f_actions[i] ); } - std::vector empty(1); empty[0] = f_actions[0]->getLabel(); - for(unsigned i=1; iaddActionToChain( empty, f_actions[i] ); } // Now add this argument to the chain bool added=false; @@ -187,34 +262,52 @@ unsigned ActionWithVector::buildArgumentStore( const unsigned& argstart ) { // Add this function to jobs to do in recursive loop in previous action if( getPntrToArgument(i)->getRank()>0 && !getPntrToArgument(i)->isConstant() ) { ActionWithVector* av=dynamic_cast( getPntrToArgument(i)->getPntrToAction() ); - if( av && av->addActionToChain( alabels, this ) ) { added=true; break; } + if( av && av->addActionToChain( alabels, this ) ) { + added=true; + break; + } } } plumed_massert(added, "could not add action " + getLabel() + " to chain of any of its arguments"); // And get the number of derivatives ActionWithVector* head=getFirstActionInChain(); - unsigned nder=0; arg_deriv_starts.resize( getNumberOfArguments() ); + unsigned nder=0; + arg_deriv_starts.resize( getNumberOfArguments() ); for(unsigned i=0; i(getPntrToArgument(i)->getPntrToAction()); if( actionInChain() && !getPntrToArgument(i)->ignoreStoredValue(head->getLabel()) ) { - arg_deriv_starts[i] = 0; head->getNumberOfStreamedDerivatives( arg_deriv_starts[i], getPntrToArgument(i) ); + arg_deriv_starts[i] = 0; + head->getNumberOfStreamedDerivatives( arg_deriv_starts[i], getPntrToArgument(i) ); } else if( iaction && iaction->isInSubChain(nder) ) { arg_deriv_starts[i] = nder; // Add the total number of derivatives that we have by this point in the chain to nder - if( iaction ) { nder=0; head->getNumberOfStreamedDerivatives( nder, getPntrToArgument(i) ); } + if( iaction ) { + nder=0; + head->getNumberOfStreamedDerivatives( nder, getPntrToArgument(i) ); + } } else { // Check if we have already found this action int k=-1; if( iaction ) { ActionWithVector* ider_action=iaction->getActionWithDerivatives( iaction ); for(unsigned j=0; j(getPntrToArgument(j)->getPntrToAction()); - if( jaction->getActionWithDerivatives(jaction)==ider_action || jaction->checkForDependency(ider_action) ) { k=j; break; } + if( jaction->getActionWithDerivatives(jaction)==ider_action || jaction->checkForDependency(ider_action) ) { + k=j; + break; + } + } + if( k>=0 ) { + arg_deriv_starts[i] = arg_deriv_starts[k]; + continue; } - if( k>=0 ) { arg_deriv_starts[i] = arg_deriv_starts[k]; continue; } } if( i>0 ) { @@ -229,8 +322,12 @@ unsigned ActionWithVector::buildArgumentStore( const unsigned& argstart ) { // mder is equal to the number of derivatives by the time you get to f minus the number of derivatives for c unsigned mder=0; ActionWithVector* jaction=dynamic_cast(getPntrToArgument(i-1)->getPntrToAction()); - if( jaction->action_to_do_after && !(jaction->action_to_do_after)->getNumberOfStoredValues( getPntrToArgument(i-1), mder, i, getArguments() ) ) mder=0; - if( mder>0 ) nder = nder + mder; + if( jaction->action_to_do_after && !(jaction->action_to_do_after)->getNumberOfStoredValues( getPntrToArgument(i-1), mder, i, getArguments() ) ) { + mder=0; + } + if( mder>0 ) { + nder = nder + mder; + } } arg_deriv_starts[i] = nder; @@ -242,29 +339,44 @@ unsigned ActionWithVector::buildArgumentStore( const unsigned& argstart ) { plumed_assert( aarg && aarg->getNumberOfArguments()==2 ); head->getNumberOfStreamedDerivatives( nder, aarg->getPntrToArgument(0) ); nder += (aarg->getPntrToArgument(1))->getNumberOfValues(); - } else head->getNumberOfStreamedDerivatives( nder, getPntrToArgument(i) ); + } else { + head->getNumberOfStreamedDerivatives( nder, getPntrToArgument(i) ); + } } } } - nder=0; head->getNumberOfStreamedDerivatives( nder, NULL ); + nder=0; + head->getNumberOfStreamedDerivatives( nder, NULL ); return nder; } return reallyBuildArgumentStore( argstart ); } unsigned ActionWithVector::reallyBuildArgumentStore( const unsigned& argstart ) { - for(unsigned i=argstart; igetRank()>0 ) getPntrToArgument(i)->buildDataStore(); } - unsigned nder=0; arg_deriv_starts.resize( getNumberOfArguments() ); - for(unsigned i=0; igetNumberOfValues(); } + for(unsigned i=argstart; igetRank()>0 ) { + getPntrToArgument(i)->buildDataStore(); + } + } + unsigned nder=0; + arg_deriv_starts.resize( getNumberOfArguments() ); + for(unsigned i=0; igetNumberOfValues(); + } return nder; } ActionWithVector* ActionWithVector::getActionWithDerivatives( ActionWithVector* depaction ) { if( depaction==this || depaction->checkForDependency(this) ) { - if( getNumberOfAtoms()>0 ) return this; + if( getNumberOfAtoms()>0 ) { + return this; + } std::string c=getFirstActionInChain()->getLabel(); for(unsigned i=0; iignoreStoredValue(c) && !getPntrToArgument(i)->isConstant() ) return this; + if( !getPntrToArgument(i)->ignoreStoredValue(c) && !getPntrToArgument(i)->isConstant() ) { + return this; + } } } plumed_assert( action_to_do_before ); @@ -272,47 +384,70 @@ ActionWithVector* ActionWithVector::getActionWithDerivatives( ActionWithVector* } bool ActionWithVector::addActionToChain( const std::vector& alabels, ActionWithVector* act ) { - if( action_to_do_after ) { bool state=action_to_do_after->addActionToChain( alabels, act ); return state; } + if( action_to_do_after ) { + bool state=action_to_do_after->addActionToChain( alabels, act ); + return state; + } // Check action is not already in chain - std::vector mylabels; getFirstActionInChain()->getAllActionLabelsInChain( mylabels ); + std::vector mylabels; + getFirstActionInChain()->getAllActionLabelsInChain( mylabels ); for(unsigned i=0; igetLabel()==mylabels[i] ) return true; + if( act->getLabel()==mylabels[i] ) { + return true; + } } // Check that everything that is required has been calculated for(unsigned i=0; i( alabels[i] ); - plumed_massert( av, "could not cast " + alabels[i] ); bool storingall=true; + plumed_massert( av, "could not cast " + alabels[i] ); + bool storingall=true; for(int j=0; jgetNumberOfComponents(); ++j) { - if( !(av->getPntrToComponent(j))->storedata ) storingall=false; + if( !(av->getPntrToComponent(j))->storedata ) { + storingall=false; + } + } + if( !storingall ) { + return false; } - if( !storingall ) return false; } } // This checks that there is nothing that will cause problems in the chain - mylabels.resize(0); getFirstActionInChain()->getAllActionLabelsInChain( mylabels ); + mylabels.resize(0); + getFirstActionInChain()->getAllActionLabelsInChain( mylabels ); for(unsigned i=0; i( mylabels[i] ); for(unsigned j=0; j( mylabels[j] ); - if( !av1->canBeAfterInChain( av2 ) ) error("must calculate " + mylabels[j] + " before " + mylabels[i] ); + if( !av1->canBeAfterInChain( av2 ) ) { + error("must calculate " + mylabels[j] + " before " + mylabels[i] ); + } } } - action_to_do_after=act; act->action_to_do_before=this; updateTaskListReductionStatus(); + action_to_do_after=act; + act->action_to_do_before=this; + updateTaskListReductionStatus(); ActionWithVector* head = getFirstActionInChain(); - head->broadcastThatTasksAreReduced( head ); head->finishChainBuild( act ); + head->broadcastThatTasksAreReduced( head ); + head->finishChainBuild( act ); return true; } void ActionWithVector::updateTaskListReductionStatus() { ActionWithVector* head = getFirstActionInChain(); - std::vector task_reducing_actions; head->canReduceTasks( task_reducing_actions ); - if( task_reducing_actions.size()>0 ) head->reduce_tasks=true; + std::vector task_reducing_actions; + head->canReduceTasks( task_reducing_actions ); + if( task_reducing_actions.size()>0 ) { + head->reduce_tasks=true; + } } void ActionWithVector::broadcastThatTasksAreReduced( ActionWithVector* aselect ) { @@ -324,15 +459,23 @@ void ActionWithVector::broadcastThatTasksAreReduced( ActionWithVector* aselect ) bool found=false; ActionWithVector* av_head = av->getFirstActionInChain(); for(unsigned i=0; itask_control_list.size(); ++i) { - if( aselect==av_head->task_control_list[i] ) { found=true; break; } + if( aselect==av_head->task_control_list[i] ) { + found=true; + break; + } + } + if( !found ) { + av_head->task_control_list.insert( av_head->task_control_list.begin(), aselect ); } - if( !found ) av_head->task_control_list.insert( av_head->task_control_list.begin(), aselect ); - av_head->reduce_tasks=true; av_head->updateTaskReductionFlag( av_head->reduce_tasks ); + av_head->reduce_tasks=true; + av_head->updateTaskReductionFlag( av_head->reduce_tasks ); } } } - if( action_to_do_after ) action_to_do_after->broadcastThatTasksAreReduced( aselect ); + if( action_to_do_after ) { + action_to_do_after->broadcastThatTasksAreReduced( aselect ); + } } void ActionWithVector::updateTaskReductionFlag( bool& head_reduce_tasks ) { @@ -340,56 +483,87 @@ void ActionWithVector::updateTaskReductionFlag( bool& head_reduce_tasks ) { plumed_assert( task_control_list.size()==0 ); } else { for(unsigned i=0; igetFirstActionInChain())->reduce_tasks ) head_reduce_tasks=false; + if( !(task_control_list[i]->getFirstActionInChain())->reduce_tasks ) { + head_reduce_tasks=false; + } } } broadcastThatTasksAreReduced( getFirstActionInChain() ); - if( action_to_do_after ) action_to_do_after->updateTaskReductionFlag( head_reduce_tasks ); + if( action_to_do_after ) { + action_to_do_after->updateTaskReductionFlag( head_reduce_tasks ); + } } void ActionWithVector::canReduceTasks( std::vector& task_reducing_actions ) { areAllTasksRequired( task_reducing_actions ); - if( action_to_do_after ) action_to_do_after->canReduceTasks( task_reducing_actions ); + if( action_to_do_after ) { + action_to_do_after->canReduceTasks( task_reducing_actions ); + } } void ActionWithVector::finishChainBuild( ActionWithVector* act ) { - if( action_to_do_after ) action_to_do_after->finishChainBuild( act ); + if( action_to_do_after ) { + action_to_do_after->finishChainBuild( act ); + } } void ActionWithVector::getAllActionLabelsInChain( std::vector& mylabels ) const { bool found = false ; for(unsigned i=0; igetAllActionLabelsInChain( mylabels ); } - if( !found ) mylabels.push_back( getLabel() ); - if( action_to_do_after ) action_to_do_after->getAllActionLabelsInChain( mylabels ); } void ActionWithVector::taskIsActive( const unsigned& current, int& flag ) const { - if( isActive() ) flag = checkTaskStatus( current, flag ); - if( flag<=0 && action_to_do_after ) action_to_do_after->taskIsActive( current, flag ); + if( isActive() ) { + flag = checkTaskStatus( current, flag ); + } + if( flag<=0 && action_to_do_after ) { + action_to_do_after->taskIsActive( current, flag ); + } } void ActionWithVector::getAdditionalTasksRequired( ActionWithVector* action, std::vector& atasks ) { - for(unsigned i=0; igetAdditionalTasksRequired( action, atasks ); + for(unsigned i=0; igetAdditionalTasksRequired( action, atasks ); + } } void ActionWithVector::prepare() { - active_tasks.resize(0); atomsWereRetrieved=false; + active_tasks.resize(0); + atomsWereRetrieved=false; } std::vector& ActionWithVector::getListOfActiveTasks( ActionWithVector* action ) { - if( active_tasks.size()>0 ) return active_tasks; - unsigned ntasks=0; getNumberOfTasks( ntasks ); + if( active_tasks.size()>0 ) { + return active_tasks; + } + unsigned ntasks=0; + getNumberOfTasks( ntasks ); unsigned stride=comm.Get_size(); unsigned rank=comm.Get_rank(); - if(serial) { stride=1; rank=0; } + if(serial) { + stride=1; + rank=0; + } // Get number of threads for OpenMP unsigned nt=OpenMP::getNumThreads(); - if( nt*stride*10>ntasks ) nt=ntasks/stride/10; - if( nt==0 ) nt=1; + if( nt*stride*10>ntasks ) { + nt=ntasks/stride/10; + } + if( nt==0 ) { + nt=1; + } if( !never_reduce_tasks && reduce_tasks ) { if( task_control_list.size()>0 ) { @@ -410,33 +584,50 @@ std::vector& ActionWithVector::getListOfActiveTasks( ActionWithVector* taskIsActive( i, taskFlags[i] ); } } - for(unsigned i=0; i=stride ) nt++; + if( taskFlags[i]>=stride ) { + nt++; + } } - active_tasks.resize(nt); nt=0; + active_tasks.resize(nt); + nt=0; for(unsigned i=0; i=stride ) { active_tasks[nt]=i; nt++; } + if( taskFlags[i]>=stride ) { + active_tasks[nt]=i; + nt++; + } } getAdditionalTasksRequired( this, active_tasks ); } } else { active_tasks.resize( ntasks ); - for(unsigned i=0; i & partialTaskList( getListOfActiveTasks( this ) ); @@ -444,8 +635,12 @@ void ActionWithVector::runAllTasks() { // Get number of threads for OpenMP unsigned nt=OpenMP::getNumThreads(); - if( nt*stride*10>nactive_tasks ) nt=nactive_tasks/stride/10; - if( nt==0 ) nt=1; + if( nt*stride*10>nactive_tasks ) { + nt=nactive_tasks/stride/10; + } + if( nt==0 ) { + nt=1; + } // Now do all preparations required to run all the tasks // prepareForTaskLoop(); @@ -454,19 +649,27 @@ void ActionWithVector::runAllTasks() { unsigned nquants=0, nmatrices=0, maxcol=0, nbooks=0; getNumberOfStreamedQuantities( getLabel(), nquants, nmatrices, maxcol, nbooks ); // Get size for buffer - unsigned bufsize=0; getSizeOfBuffer( nactive_tasks, bufsize ); - if( buffer.size()!=bufsize ) buffer.resize( bufsize ); + unsigned bufsize=0; + getSizeOfBuffer( nactive_tasks, bufsize ); + if( buffer.size()!=bufsize ) { + buffer.resize( bufsize ); + } // Clear buffer buffer.assign( buffer.size(), 0.0 ); // Recover the number of derivatives we require - unsigned nderivatives = 0; bool gridsInStream=checkForGrids(nderivatives); - if( !doNotCalculateDerivatives() && !gridsInStream ) getNumberOfStreamedDerivatives( nderivatives, NULL ); + unsigned nderivatives = 0; + bool gridsInStream=checkForGrids(nderivatives); + if( !doNotCalculateDerivatives() && !gridsInStream ) { + getNumberOfStreamedDerivatives( nderivatives, NULL ); + } #pragma omp parallel num_threads(nt) { std::vector omp_buffer; - if( nt>1 ) omp_buffer.resize( bufsize, 0.0 ); + if( nt>1 ) { + omp_buffer.resize( bufsize, 0.0 ); + } MultiValue myvals( nquants, nderivatives, nmatrices, maxcol, nbooks ); myvals.clearAll(); @@ -476,8 +679,11 @@ void ActionWithVector::runAllTasks() { runTask( partialTaskList[i], myvals ); // Now transfer the data to the actions that accumulate values from the calculated quantities - if( nt>1 ) gatherAccumulators( partialTaskList[i], myvals, omp_buffer ); - else gatherAccumulators( partialTaskList[i], myvals, buffer ); + if( nt>1 ) { + gatherAccumulators( partialTaskList[i], myvals, omp_buffer ); + } else { + gatherAccumulators( partialTaskList[i], myvals, buffer ); + } // Clear the value myvals.clearAll(); @@ -487,12 +693,17 @@ void ActionWithVector::runAllTasks() { } // MPI Gather everything - if( !serial && buffer.size()>0 ) gatherProcesses( buffer ); + if( !serial && buffer.size()>0 ) { + gatherProcesses( buffer ); + } finishComputations( buffer ); } void ActionWithVector::gatherThreads( const unsigned& nt, const unsigned& bufsize, const std::vector& omp_buffer, std::vector& buffer, MultiValue& myvals ) { - if( nt>1 ) for(unsigned i=0; i1 ) + for(unsigned i=0; i& buffer ) { @@ -502,92 +713,144 @@ void ActionWithVector::gatherProcesses( std::vector& buffer ) { bool ActionWithVector::checkForGrids( unsigned& nder ) const { for(int i=0; igetRank()>0 && getConstPntrToComponent(i)->hasDerivatives() ) { - nder=getConstPntrToComponent(i)->getNumberOfGridDerivatives(); return true; + nder=getConstPntrToComponent(i)->getNumberOfGridDerivatives(); + return true; } } - if( action_to_do_after ) return action_to_do_after->checkForGrids(nder); + if( action_to_do_after ) { + return action_to_do_after->checkForGrids(nder); + } return false; } void ActionWithVector::getNumberOfTasks( unsigned& ntasks ) { if( ntasks==0 ) { if( getNumberOfArguments()==1 && getNumberOfComponents()==1 && getPntrToComponent(0)->getRank()==0 ) { - if( !getPntrToArgument(0)->hasDerivatives() && getPntrToArgument(0)->getRank()==2 ) ntasks = getPntrToArgument(0)->getShape()[0]; - else ntasks = getPntrToArgument(0)->getNumberOfValues(); + if( !getPntrToArgument(0)->hasDerivatives() && getPntrToArgument(0)->getRank()==2 ) { + ntasks = getPntrToArgument(0)->getShape()[0]; + } else { + ntasks = getPntrToArgument(0)->getNumberOfValues(); + } } else { plumed_assert( getNumberOfComponents()>0 && getPntrToComponent(0)->getRank()>0 ); - if( getPntrToComponent(0)->hasDerivatives() ) ntasks = getPntrToComponent(0)->getNumberOfValues(); - else ntasks = getPntrToComponent(0)->getShape()[0]; + if( getPntrToComponent(0)->hasDerivatives() ) { + ntasks = getPntrToComponent(0)->getNumberOfValues(); + } else { + ntasks = getPntrToComponent(0)->getShape()[0]; + } } } for(int i=0; igetRank()==0 ) { - if( getNumberOfArguments()!=1 ) error("mismatched numbers of tasks in streamed quantities"); - if( getPntrToArgument(0)->hasDerivatives() && ntasks!=getPntrToArgument(0)->getNumberOfValues() ) error("mismatched numbers of tasks in streamed quantities"); - else if ( !getPntrToArgument(0)->hasDerivatives() && ntasks!=getPntrToArgument(0)->getShape()[0] ) error("mismatched numbers of tasks in streamed quantities"); - } else if( getPntrToComponent(i)->hasDerivatives() && ntasks!=getPntrToComponent(i)->getNumberOfValues() ) error("mismatched numbers of tasks in streamed quantities"); - else if( !getPntrToComponent(i)->hasDerivatives() && ntasks!=getPntrToComponent(i)->getShape()[0] ) error("mismatched numbers of tasks in streamed quantities"); + if( getNumberOfArguments()!=1 ) { + error("mismatched numbers of tasks in streamed quantities"); + } + if( getPntrToArgument(0)->hasDerivatives() && ntasks!=getPntrToArgument(0)->getNumberOfValues() ) { + error("mismatched numbers of tasks in streamed quantities"); + } else if ( !getPntrToArgument(0)->hasDerivatives() && ntasks!=getPntrToArgument(0)->getShape()[0] ) { + error("mismatched numbers of tasks in streamed quantities"); + } + } else if( getPntrToComponent(i)->hasDerivatives() && ntasks!=getPntrToComponent(i)->getNumberOfValues() ) { + error("mismatched numbers of tasks in streamed quantities"); + } else if( !getPntrToComponent(i)->hasDerivatives() && ntasks!=getPntrToComponent(i)->getShape()[0] ) { + error("mismatched numbers of tasks in streamed quantities"); + } + } + if( action_to_do_after ) { + action_to_do_after->getNumberOfTasks( ntasks ); } - if( action_to_do_after ) action_to_do_after->getNumberOfTasks( ntasks ); } void ActionWithVector::setupStreamedComponents( const std::string& headstr, unsigned& nquants, unsigned& nmat, unsigned& maxcol, unsigned& nbookeeping ) { for(unsigned i=0; iignoreStoredValue(headstr) ) { getPntrToArgument(i)->streampos=nquants; nquants++; } + if( !getPntrToArgument(i)->ignoreStoredValue(headstr) ) { + getPntrToArgument(i)->streampos=nquants; + nquants++; + } + } + for(int i=0; istreampos=nquants; + nquants++; } - for(int i=0; istreampos=nquants; nquants++; } } void ActionWithVector::getNumberOfStreamedQuantities( const std::string& headstr, unsigned& nquants, unsigned& nmat, unsigned& maxcol, unsigned& nbookeeping ) { setupStreamedComponents( headstr, nquants, nmat, maxcol, nbookeeping ); - if( action_to_do_after ) action_to_do_after->getNumberOfStreamedQuantities( headstr, nquants, nmat, maxcol, nbookeeping ); + if( action_to_do_after ) { + action_to_do_after->getNumberOfStreamedQuantities( headstr, nquants, nmat, maxcol, nbookeeping ); + } } void ActionWithVector::getSizeOfBuffer( const unsigned& nactive_tasks, unsigned& bufsize ) { - for(int i=0; ibufstart=bufsize; bufsize += getPntrToComponent(i)->data.size(); } - if( action_to_do_after ) action_to_do_after->getSizeOfBuffer( nactive_tasks, bufsize ); + for(int i=0; ibufstart=bufsize; + bufsize += getPntrToComponent(i)->data.size(); + } + if( action_to_do_after ) { + action_to_do_after->getSizeOfBuffer( nactive_tasks, bufsize ); + } } void ActionWithVector::getNumberOfStreamedDerivatives( unsigned& nderivatives, Value* stopat ) { std::string c=getFirstActionInChain()->getLabel(); for(unsigned i=0; iignoreStoredValue(c) ) { - if( getPntrToArgument(i)==stopat ) return; + if( getPntrToArgument(i)==stopat ) { + return; + } nderivatives += getPntrToArgument(i)->getNumberOfValues(); } } - if( getNumberOfAtoms()>0 ) nderivatives += 3*getNumberOfAtoms() + 9; + if( getNumberOfAtoms()>0 ) { + nderivatives += 3*getNumberOfAtoms() + 9; + } // Don't do the whole chain if we have been told to stop early - if( stopat && stopat->getPntrToAction()==this ) return; + if( stopat && stopat->getPntrToAction()==this ) { + return; + } - if( action_to_do_after ) action_to_do_after->getNumberOfStreamedDerivatives( nderivatives, stopat ); + if( action_to_do_after ) { + action_to_do_after->getNumberOfStreamedDerivatives( nderivatives, stopat ); + } } bool ActionWithVector::getNumberOfStoredValues( Value* startat, unsigned& nvals, const unsigned& astart, const std::vector& stopat ) { for(unsigned j=astart; jgetPntrToAction()==this || (stopat[j]->getPntrToAction())->checkForDependency(this)) ) return true; + if( stopat[j] && (stopat[j]->getPntrToAction()==this || (stopat[j]->getPntrToAction())->checkForDependency(this)) ) { + return true; + } } std::string c=getFirstActionInChain()->getLabel(); for(unsigned i=0; iignoreStoredValue(c) ) { for(unsigned j=astart; jgetNumberOfValues(); } } - if( startat->getPntrToAction()!=this && getNumberOfAtoms()>0 ) return false; + if( startat->getPntrToAction()!=this && getNumberOfAtoms()>0 ) { + return false; + } - if( action_to_do_after ) return action_to_do_after->getNumberOfStoredValues( startat, nvals, astart, stopat ); + if( action_to_do_after ) { + return action_to_do_after->getNumberOfStoredValues( startat, nvals, astart, stopat ); + } return false; } void ActionWithVector::runTask( const unsigned& current, MultiValue& myvals ) const { if( isActive() ) { - myvals.setTaskIndex(current); myvals.vector_call=true; performTask( current, myvals ); + myvals.setTaskIndex(current); + myvals.vector_call=true; + performTask( current, myvals ); + } + if( action_to_do_after ) { + action_to_do_after->runTask( current, myvals ); } - if( action_to_do_after ) action_to_do_after->runTask( current, myvals ); } void ActionWithVector::gatherAccumulators( const unsigned& taskCode, const MultiValue& myvals, std::vector& buffer ) const { @@ -597,7 +860,8 @@ void ActionWithVector::gatherAccumulators( const unsigned& taskCode, const Multi // This looks after storing of scalars that are summed from vectors/matrices if( getConstPntrToComponent(i)->getRank()==0 ) { plumed_dbg_massert( bufstartstreampos; buffer[bufstart] += myvals.get(sind); + unsigned sind = getConstPntrToComponent(i)->streampos; + buffer[bufstart] += myvals.get(sind); if( getConstPntrToComponent(i)->hasDerivatives() ) { for(unsigned k=0; kstoredata ) gatherStoredValue( i, taskCode, myvals, bufstart, buffer ); + } else if( getConstPntrToComponent(i)->storedata ) { + gatherStoredValue( i, taskCode, myvals, bufstart, buffer ); + } } } - if( action_to_do_after ) action_to_do_after->gatherAccumulators( taskCode, myvals, buffer ); + if( action_to_do_after ) { + action_to_do_after->gatherAccumulators( taskCode, myvals, buffer ); + } } void ActionWithVector::gatherStoredValue( const unsigned& valindex, const unsigned& taskCode, const MultiValue& myvals, const unsigned& bufstart, std::vector& buffer ) const { plumed_dbg_assert( getConstPntrToComponent(valindex)->getRank()==1 && !getConstPntrToComponent(valindex)->hasDeriv ); - unsigned vindex = getConstPntrToComponent(valindex)->bufstart + taskCode; plumed_dbg_massert( vindexbufstart + taskCode; + plumed_dbg_massert( vindexstreampos); } @@ -632,58 +901,87 @@ void ActionWithVector::finishComputations( const std::vector& buf ) { getPntrToComponent(i)->add( j, buf[bufstart+j] ); } // Make sure single values are set - } else if( getPntrToComponent(i)->getRank()==0 ) getPntrToComponent(i)->set( buf[bufstart] ); + } else if( getPntrToComponent(i)->getRank()==0 ) { + getPntrToComponent(i)->set( buf[bufstart] ); + } // This gathers derivatives of scalars if( !doNotCalculateDerivatives() && getPntrToComponent(i)->hasDeriv && getPntrToComponent(i)->getRank()==0 ) { - for(unsigned j=0; jgetNumberOfDerivatives(); ++j) getPntrToComponent(i)->setDerivative( j, buf[bufstart+1+j] ); + for(unsigned j=0; jgetNumberOfDerivatives(); ++j) { + getPntrToComponent(i)->setDerivative( j, buf[bufstart+1+j] ); + } } } } - if( action_to_do_after ) action_to_do_after->finishComputations( buf ); + if( action_to_do_after ) { + action_to_do_after->finishComputations( buf ); + } } bool ActionWithVector::checkChainForNonScalarForces() const { for(unsigned i=0; igetRank()>0 && getConstPntrToComponent(i)->forcesWereAdded() ) return true; + if( getConstPntrToComponent(i)->getRank()>0 && getConstPntrToComponent(i)->forcesWereAdded() ) { + return true; + } + } + if( action_to_do_after ) { + return action_to_do_after->checkChainForNonScalarForces(); } - if( action_to_do_after ) return action_to_do_after->checkChainForNonScalarForces(); return false; } bool ActionWithVector::checkForForces() { - if( getPntrToComponent(0)->getRank()==0 ) return ActionWithValue::checkForForces(); - else if( actionInChain() ) return false; + if( getPntrToComponent(0)->getRank()==0 ) { + return ActionWithValue::checkForForces(); + } else if( actionInChain() ) { + return false; + } // Check if there are any forces - if( !checkChainForNonScalarForces() ) return false; + if( !checkChainForNonScalarForces() ) { + return false; + } // Setup MPI parallel loop unsigned stride=comm.Get_size(); unsigned rank=comm.Get_rank(); - if(serial) { stride=1; rank=0; } + if(serial) { + stride=1; + rank=0; + } // Get the number of tasks - std::vector force_tasks; getForceTasks( force_tasks ); - Tools::removeDuplicates(force_tasks); unsigned nf_tasks=force_tasks.size(); + std::vector force_tasks; + getForceTasks( force_tasks ); + Tools::removeDuplicates(force_tasks); + unsigned nf_tasks=force_tasks.size(); // Get number of threads for OpenMP unsigned nt=OpenMP::getNumThreads(); - if( nt*stride*10>nf_tasks ) nt=nf_tasks/stride/10; - if( nt==0 ) nt=1; + if( nt*stride*10>nf_tasks ) { + nt=nf_tasks/stride/10; + } + if( nt==0 ) { + nt=1; + } // Now determine how big the multivalue needs to be unsigned nquants=0, nmatrices=0, maxcol=0, nbooks=0; getNumberOfStreamedQuantities( getLabel(), nquants, nmatrices, maxcol, nbooks ); // Recover the number of derivatives we require (this should be equal to the number of forces) - unsigned nderiv=0; getNumberOfStreamedDerivatives( nderiv, NULL ); - if( forcesForApply.size()!=nderiv ) forcesForApply.resize( nderiv ); + unsigned nderiv=0; + getNumberOfStreamedDerivatives( nderiv, NULL ); + if( forcesForApply.size()!=nderiv ) { + forcesForApply.resize( nderiv ); + } // Clear force buffer forcesForApply.assign( forcesForApply.size(), 0.0 ); #pragma omp parallel num_threads(nt) { std::vector omp_forces; - if( nt>1 ) omp_forces.resize( forcesForApply.size(), 0.0 ); + if( nt>1 ) { + omp_forces.resize( forcesForApply.size(), 0.0 ); + } MultiValue myvals( nquants, nderiv, nmatrices, maxcol, nbooks ); myvals.clearAll(); @@ -692,22 +990,32 @@ bool ActionWithVector::checkForForces() { runTask( force_tasks[i], myvals ); // Now get the forces - if( nt>1 ) gatherForces( force_tasks[i], myvals, omp_forces ); - else gatherForces( force_tasks[i], myvals, forcesForApply ); + if( nt>1 ) { + gatherForces( force_tasks[i], myvals, omp_forces ); + } else { + gatherForces( force_tasks[i], myvals, forcesForApply ); + } myvals.clearAll(); } #pragma omp critical - if(nt>1) for(unsigned i=0; i1) + for(unsigned i=0; iforcesWereAdded() ) return true; + if( getConstPntrToComponent(i)->forcesWereAdded() ) { + return true; + } } return false; } @@ -720,9 +1028,13 @@ bool ActionWithVector::checkForTaskForce( const unsigned& itask, const Value* my void ActionWithVector::updateForceTasksFromValue( const Value* myval, std::vector& force_tasks ) const { if( myval->getRank()>0 && myval->forcesWereAdded() ) { unsigned nt = myval->getNumberOfValues(); - if( !myval->hasDerivatives() ) nt = myval->getShape()[0]; + if( !myval->hasDerivatives() ) { + nt = myval->getShape()[0]; + } for(unsigned i=0; i& force_tasks ) const updateForceTasksFromValue( getConstPntrToComponent(k), force_tasks ); } } - if( action_to_do_after ) action_to_do_after->getForceTasks( force_tasks ); + if( action_to_do_after ) { + action_to_do_after->getForceTasks( force_tasks ); + } } void ActionWithVector::gatherForcesOnStoredValue( const Value* myval, const unsigned& itask, const MultiValue& myvals, std::vector& forces ) const { @@ -741,7 +1055,8 @@ void ActionWithVector::gatherForcesOnStoredValue( const Value* myval, const unsi double fforce = myval->getForce(itask); unsigned sspos = myval->getPositionInStream(); for(unsigned j=0; jgetRank()>0 && myval->forcesWereAdded() ) gatherForcesOnStoredValue( myval, itask, myvals, forces ); + if( myval->getRank()>0 && myval->forcesWereAdded() ) { + gatherForcesOnStoredValue( myval, itask, myvals, forces ); + } } } - if( action_to_do_after ) action_to_do_after->gatherForces( itask, myvals, forces ); + if( action_to_do_after ) { + action_to_do_after->gatherForces( itask, myvals, forces ); + } } void ActionWithVector::apply() { - if( !checkForForces() ) return; + if( !checkForForces() ) { + return; + } // Find the top of the chain and add forces - unsigned ind=0; getFirstActionInChain()->addForcesToInput( getForcesToApply(), ind ); + unsigned ind=0; + getFirstActionInChain()->addForcesToInput( getForcesToApply(), ind ); } void ActionWithVector::addForcesToInput( const std::vector& forcesToApply, unsigned& ind ) { - if( ind>=forcesToApply.size() ) return; - addForcesOnArguments( 0, forcesToApply, ind, getFirstActionInChain()->getLabel() ); setForcesOnAtoms( forcesToApply, ind ); - if( action_to_do_after ) action_to_do_after->addForcesToInput( forcesToApply, ind ); + if( ind>=forcesToApply.size() ) { + return; + } + addForcesOnArguments( 0, forcesToApply, ind, getFirstActionInChain()->getLabel() ); + setForcesOnAtoms( forcesToApply, ind ); + if( action_to_do_after ) { + action_to_do_after->addForcesToInput( forcesToApply, ind ); + } } } diff --git a/src/core/ActionWithVector.h b/src/core/ActionWithVector.h index c72e7d09bb..876b8643b8 100644 --- a/src/core/ActionWithVector.h +++ b/src/core/ActionWithVector.h @@ -33,8 +33,7 @@ namespace PLMD { class ActionWithVector: public ActionAtomistic, public ActionWithValue, - public ActionWithArguments -{ + public ActionWithArguments { friend class Value; private: /// Is the calculation to be done in serial @@ -139,15 +138,21 @@ class ActionWithVector: /// We override clearDerivatives here to prevent data in streams from being deleted void clearDerivatives( const bool& force=false ) override; /// Check if we can be after another ActionWithVector - virtual bool canBeAfterInChain( ActionWithVector* av ) { return true; } + virtual bool canBeAfterInChain( ActionWithVector* av ) { + return true; + } /// Do we always need to do all the tasks for this action virtual void areAllTasksRequired( std::vector& task_reducing_actions ) {} /// Find out how many tasks we need to perform in this loop virtual void getNumberOfTasks( unsigned& ntasks ); /// Check the status of the ith task - virtual int checkTaskStatus( const unsigned& taskno, int& flag ) const { return flag; } + virtual int checkTaskStatus( const unsigned& taskno, int& flag ) const { + return flag; + } /// Check if we are in a subchain - virtual bool isInSubChain( unsigned& nder ) { return false; } + virtual bool isInSubChain( unsigned& nder ) { + return false; + } /// Get the additional tasks that are required here virtual void getAdditionalTasksRequired( ActionWithVector* action, std::vector& atasks ); /// setup the streamed quantities diff --git a/src/core/ActionWithVirtualAtom.cpp b/src/core/ActionWithVirtualAtom.cpp index afd1a6e156..741e02cceb 100644 --- a/src/core/ActionWithVirtualAtom.cpp +++ b/src/core/ActionWithVirtualAtom.cpp @@ -39,29 +39,46 @@ void ActionWithVirtualAtom::registerKeywords(Keywords& keys) { ActionWithVirtualAtom::ActionWithVirtualAtom(const ActionOptions&ao): Action(ao), ActionAtomistic(ao), - ActionWithValue(ao) -{ - addComponentWithDerivatives("x"); componentIsNotPeriodic("x"); - addComponentWithDerivatives("y"); componentIsNotPeriodic("y"); - addComponentWithDerivatives("z"); componentIsNotPeriodic("z"); + ActionWithValue(ao) { + addComponentWithDerivatives("x"); + componentIsNotPeriodic("x"); + addComponentWithDerivatives("y"); + componentIsNotPeriodic("y"); + addComponentWithDerivatives("z"); + componentIsNotPeriodic("z"); // Store the derivatives with respect to the virial only even if there are no atoms - for(unsigned i=0; i<3; ++i) getPntrToComponent(i)->resizeDerivatives(9); - addComponent("mass"); componentIsNotPeriodic("mass"); getPntrToComponent("mass")->isConstant(); - addComponent("charge"); componentIsNotPeriodic("charge"); getPntrToComponent("charge")->isConstant(); + for(unsigned i=0; i<3; ++i) { + getPntrToComponent(i)->resizeDerivatives(9); + } + addComponent("mass"); + componentIsNotPeriodic("mass"); + getPntrToComponent("mass")->isConstant(); + addComponent("charge"); + componentIsNotPeriodic("charge"); + getPntrToComponent("charge")->isConstant(); } void ActionWithVirtualAtom::requestAtoms(const std::vector & a) { - ActionAtomistic::requestAtoms(a); for(unsigned i=0; i<3; ++i) getPntrToComponent(i)->resizeDerivatives(3*a.size()+9); + ActionAtomistic::requestAtoms(a); + for(unsigned i=0; i<3; ++i) { + getPntrToComponent(i)->resizeDerivatives(3*a.size()+9); + } } void ActionWithVirtualAtom::apply() { - if( !checkForForces() ) return ; + if( !checkForForces() ) { + return ; + } Value* xval=getPntrToComponent(0); Value* yval=getPntrToComponent(1); Value* zval=getPntrToComponent(2); - if( !xval->forcesWereAdded() && !yval->forcesWereAdded() && !zval->forcesWereAdded() ) return ; - if( xval->isConstant() && yval->isConstant() && zval->isConstant() ) return; + if( !xval->forcesWereAdded() && !yval->forcesWereAdded() && !zval->forcesWereAdded() ) { + return ; + } + if( xval->isConstant() && yval->isConstant() && zval->isConstant() ) { + return; + } for(unsigned i=0; ihasForce = true; @@ -84,15 +101,22 @@ void ActionWithVirtualAtom::apply() { auto & yp=ypos[nn]->inputForce; auto & zp=zpos[nn]->inputForce; for(const auto & kk : a.second) { - xp[kk] += xf*xval->data[1+k] + yf*yval->data[1+k] + zf*zval->data[1+k]; k++; - yp[kk] += xf*xval->data[1+k] + yf*yval->data[1+k] + zf*zval->data[1+k]; k++; - zp[kk] += xf*xval->data[1+k] + yf*yval->data[1+k] + zf*zval->data[1+k]; k++; + xp[kk] += xf*xval->data[1+k] + yf*yval->data[1+k] + zf*zval->data[1+k]; + k++; + yp[kk] += xf*xval->data[1+k] + yf*yval->data[1+k] + zf*zval->data[1+k]; + k++; + zp[kk] += xf*xval->data[1+k] + yf*yval->data[1+k] + zf*zval->data[1+k]; + k++; } } std::array virial; - for(unsigned i=0; i<9; ++i) { virial[i] = xf*xval->data[1+k] + yf*yval->data[1+k] + zf*zval->data[1+k]; k++; } - unsigned ind = 0; setForcesOnCell( virial.data(), virial.size(), ind ); + for(unsigned i=0; i<9; ++i) { + virial[i] = xf*xval->data[1+k] + yf*yval->data[1+k] + zf*zval->data[1+k]; + k++; + } + unsigned ind = 0; + setForcesOnCell( virial.data(), virial.size(), ind ); // The above can be achieved using the two functions below. The code above that is specialised for the ActionWithVirtualAtom // class runs faster than the general code below. // if( !checkForForces() ) return ; @@ -100,23 +124,34 @@ void ActionWithVirtualAtom::apply() { } void ActionWithVirtualAtom::setBoxDerivatives(const std::vector &d) { - plumed_assert(d.size()==3); unsigned nbase = 3*getNumberOfAtoms(); + plumed_assert(d.size()==3); + unsigned nbase = 3*getNumberOfAtoms(); for(unsigned i=0; i<3; ++i) { Value* myval = getPntrToComponent(i); for(unsigned j=0; j<3; ++j) { - for(unsigned k=0; k<3; ++k) myval->setDerivative( nbase + 3*j + k, d[i][j][k] ); + for(unsigned k=0; k<3; ++k) { + myval->setDerivative( nbase + 3*j + k, d[i][j][k] ); + } } } // Subtract the trivial part coming from a distorsion applied to the ghost atom first. // Notice that this part alone should exactly cancel the already accumulated virial // due to forces on this atom. - Vector pos; for(unsigned i=0; i<3; ++i) pos[i] = getPntrToComponent(i)->get(); - for(unsigned i=0; i<3; i++) for(unsigned j=0; j<3; j++) getPntrToComponent(j)->addDerivative( nbase + 3*i + j, pos[i] ); + Vector pos; + for(unsigned i=0; i<3; ++i) { + pos[i] = getPntrToComponent(i)->get(); + } + for(unsigned i=0; i<3; i++) + for(unsigned j=0; j<3; j++) { + getPntrToComponent(j)->addDerivative( nbase + 3*i + j, pos[i] ); + } } void ActionWithVirtualAtom::setBoxDerivativesNoPbc() { std::vector bd(3); - for(unsigned i=0; i<3; i++) for(unsigned j=0; j<3; j++) for(unsigned k=0; k<3; k++) { + for(unsigned i=0; i<3; i++) + for(unsigned j=0; j<3; j++) + for(unsigned k=0; k<3; k++) { // Notice that this expression is very similar to the one used in Colvar::setBoxDerivativesNoPbc(). // Indeed, we have the negative of a sum over dependent atoms (l) of the external product between positions // and derivatives. Notice that this only works only when Pbc have not been used to compute diff --git a/src/core/ActionWithVirtualAtom.h b/src/core/ActionWithVirtualAtom.h index 4075a24bc8..9ea8027116 100644 --- a/src/core/ActionWithVirtualAtom.h +++ b/src/core/ActionWithVirtualAtom.h @@ -39,8 +39,7 @@ Inherit from here if you are calculating the position of a virtual atom (eg a ce /// (it might be extended to add multiple virtual atoms). class ActionWithVirtualAtom: public ActionAtomistic, - public ActionWithValue -{ + public ActionWithValue { protected: /// Set position of the virtual atom void setPosition(const Vector &); @@ -76,7 +75,9 @@ class ActionWithVirtualAtom: static void registerKeywords(Keywords& keys); virtual unsigned getNumberOfDerivatives(); virtual void apply(); - ActionWithVirtualAtom* castToActionWithVirtualAtom() noexcept final { return this; } + ActionWithVirtualAtom* castToActionWithVirtualAtom() noexcept final { + return this; + } }; inline @@ -86,7 +87,9 @@ unsigned ActionWithVirtualAtom::getNumberOfDerivatives() { inline void ActionWithVirtualAtom::setPosition(const Vector & pos) { - for(unsigned i=0; i<3; ++i) getPntrToComponent(i)->set(pos[i]); + for(unsigned i=0; i<3; ++i) { + getPntrToComponent(i)->set(pos[i]); + } } inline diff --git a/src/core/CLTool.cpp b/src/core/CLTool.cpp index 1527cac7f4..b2ab576ffd 100644 --- a/src/core/CLTool.cpp +++ b/src/core/CLTool.cpp @@ -27,14 +27,12 @@ Keywords CLToolOptions::emptyKeys; CLToolOptions::CLToolOptions(const std::string &name): line(1,name), - keys(emptyKeys) -{ + keys(emptyKeys) { } CLToolOptions::CLToolOptions(const CLToolOptions& co, const Keywords& k): line(co.line), - keys(k) -{ + keys(k) { } void CLTool::registerKeywords( Keywords& keys ) { @@ -44,17 +42,20 @@ void CLTool::registerKeywords( Keywords& keys ) { CLTool::CLTool(const CLToolOptions& co ): name(co.line[0]), keywords(co.keys), - inputdata(unset) -{ + inputdata(unset) { } void CLTool::parseFlag( const std::string&key, bool&t ) { plumed_massert(keywords.exists(key),"keyword " + key + " has not been registered"); plumed_massert(keywords.style(key,"flag"),"keyword " + key + " has not been registered as a flag"); plumed_assert(inputData.count(key)>0); - if( inputData[key]=="true") t=true; - else if( inputData[key]=="false") t=false; - else plumed_error(); + if( inputData[key]=="true") { + t=true; + } else if( inputData[key]=="false") { + t=false; + } else { + plumed_error(); + } } bool CLTool::readInput( int argc, char**argv, FILE* in, FILE*out ) { @@ -62,8 +63,12 @@ bool CLTool::readInput( int argc, char**argv, FILE* in, FILE*out ) { "If it is from the command line (like driver) add inputdata=commandline to the " "tools constructor. If it reads everything from an input file (like simplemd) " "add inputdata=ifile to the tools constructor"); - if(inputdata==commandline) return readCommandLineArgs( argc, argv, out ); - if(inputdata==ifile) return readInputFile( argc, argv, in, out ); + if(inputdata==commandline) { + return readCommandLineArgs( argc, argv, out ); + } + if(inputdata==ifile) { + return readInputFile( argc, argv, in, out ); + } return true; } @@ -74,14 +79,18 @@ bool CLTool::readCommandLineArgs( int argc, char**argv, FILE*out ) { // Set all flags to default false for(unsigned k=0; k(thiskey,"false")); + if( keywords.style(thiskey,"flag") ) { + inputData.insert(std::pair(thiskey,"false")); + } } // Read command line arguments bool printhelp=false; for(int i=1; i(thiskey,"")); } else if(Tools::startWith(a,thiskey+"=")) { - a.erase(0,a.find("=")+1); prefix=""; found=true; + a.erase(0,a.find("=")+1); + prefix=""; + found=true; if(inputData.count(thiskey)==0) { inputData.insert(std::pair(thiskey,a)); } else { @@ -112,10 +127,14 @@ bool CLTool::readCommandLineArgs( int argc, char**argv, FILE*out ) { printhelp=true; } } - if(printhelp) break; + if(printhelp) { + break; + } } - if(!printhelp) setRemainingToDefault(out); + if(!printhelp) { + setRemainingToDefault(out); + } if(printhelp) { std::fprintf(out,"Usage: %s [options] \n\n", name.c_str() ); @@ -150,7 +169,9 @@ bool CLTool::readInputFile( int argc, char**argv, FILE* in, FILE*out ) { std::string a; for(int i=1; i fp_deleter(nullptr,deleter); if(argc==2) { @@ -178,14 +201,22 @@ bool CLTool::readInputFile( int argc, char**argv, FILE* in, FILE*out ) { plumed_assert(mystdin); - char buffer[256]; std::string line; line.resize(256); + char buffer[256]; + std::string line; + line.resize(256); while(fgets(buffer,256,mystdin)) { line=buffer; - for(unsigned i=0; i bool CLTool::parse(const std::string&key,T&t) { plumed_massert(keywords.exists(key),"keyword " + key + " has not been registered"); if(keywords.style(key,"compulsory") ) { - if(inputData.count(key)==0) error("missing data for keyword " + key); + if(inputData.count(key)==0) { + error("missing data for keyword " + key); + } bool check=Tools::convertNoexcept(inputData[key],t); - if(!check) error("data input for keyword " + key + " has wrong type"); + if(!check) { + error("data input for keyword " + key + " has wrong type"); + } return true; } - if( inputData.count(key)==0 ) return false; + if( inputData.count(key)==0 ) { + return false; + } Tools::convert(inputData[key],t); return true; } @@ -121,14 +129,18 @@ bool CLTool::parseVector(const std::string&key,std::vector&t) { // initial size unsigned size=t.size(); bool skipcheck=false; - if(size==0) skipcheck=true; // if the vector in input has size zero, skip the check if size of input vector is the same of argument read + if(size==0) { + skipcheck=true; // if the vector in input has size zero, skip the check if size of input vector is the same of argument read + } // check if there is some value plumed_massert(inputData[key]!="false","compulsory keyword "+std::string(key)+"has no data"); std::vector words=Tools::getWords(inputData[key],"\t\n ,"); t.resize(0); - if(words.size()==0)return false; + if(words.size()==0) { + return false; + } for(unsigned i=0; isecond; + if(it!=word_map.end()) { + iword=it->second; + } switch(iword) { case cmd_setArgc: CHECK_NULL(val,word); @@ -81,7 +82,9 @@ void CLToolMain::cmd(std::string_view word,const TypesafePtr & val) { case cmd_setArgv: CHECK_NULL(val,word); v=val.get({argc}); - for(int i=0; i args(n); std::vector vvv(argc); char* ptr=&args[0]; for(int i=0; i0) availableShell.push_back(tmp[j]); + for(unsigned j=0; j0) { + availableShell.push_back(tmp[j]); + } } if(printhelp) { @@ -261,7 +282,9 @@ int CLToolMain::run(int argc, char **argv,FILE*in,FILE*out,Communicator& pc) { auto cl=cltoolRegister().create(dlloader.getHandles(),CLToolOptions(command)); plumed_assert(cl); // Read the command line options (returns false if we are just printing help) - if( !cl->readInput( argc-i,&argv[i],in,out ) ) { return 0; } + if( !cl->readInput( argc-i,&argv[i],in,out ) ) { + return 0; + } int ret=cl->main(in,out,pc); return ret; } @@ -270,13 +293,18 @@ int CLToolMain::run(int argc, char **argv,FILE*in,FILE*out,Communicator& pc) { plumed_massert(in==stdin,"shell tools can only work on stdin"); plumed_massert(out==stdout,"shell tools can only work on stdin"); std::string cmd=config::getEnvCommand()+" \""+root+"/scripts/"+command+".sh\""; - for(int j=i+1; j CLToolRegister::create(const CLToolOptions&ao) { } std::unique_ptr CLToolRegister::create(const std::vector & images,const CLToolOptions&ao) { - if(ao.line.size()<1)return nullptr; + if(ao.line.size()<1) { + return nullptr; + } auto & content=get(images,ao.line[0]); CLToolOptions nao( ao,content.keys ); return content.create(nao); @@ -47,9 +49,13 @@ std::unique_ptr CLToolRegister::create(const std::vector & images CLToolRegister::ID CLToolRegister::add(std::string key,creator_pointer cp,keywords_pointer kp) { // this force each action to be registered as an uppercase string - if ( std::any_of( std::begin( key ), std::end( key ), []( char c ) { return ( std::isupper( c ) ); } ) ) plumed_error() << "CLTool: " + key + " cannot be registered, use only LOWERCASE characters"; + if ( std::any_of( std::begin( key ), std::end( key ), []( char c ) { + return ( std::isupper( c ) ) + ; + } ) ) plumed_error() << "CLTool: " + key + " cannot be registered, use only LOWERCASE characters"; - Keywords keys; kp(keys); + Keywords keys; + kp(keys); return RegisterBase::add(key,Pointers{cp,keys}); } @@ -72,7 +78,9 @@ std::vector CLToolRegister::getKeys(const std::string& cltool)const auto cl=get(cltool); auto k=cl.keys.getKeys(); std::cerr< empty; diff --git a/src/core/Colvar.cpp b/src/core/Colvar.cpp index da28e9d4bb..f90ac70511 100644 --- a/src/core/Colvar.cpp +++ b/src/core/Colvar.cpp @@ -29,8 +29,7 @@ namespace PLMD { Colvar::Colvar(const ActionOptions&ao): Action(ao), ActionAtomistic(ao), - ActionWithValue(ao) -{ + ActionWithValue(ao) { } void Colvar::registerKeywords( Keywords& keys ) { @@ -44,30 +43,41 @@ void Colvar::requestAtoms(const std::vector & a) { // Tell actionAtomistic what atoms we are getting ActionAtomistic::requestAtoms(a); // Resize the derivatives of all atoms - for(int i=0; iresizeDerivatives(3*a.size()+9); + for(int i=0; iresizeDerivatives(3*a.size()+9); + } } void Colvar::apply() { - if( !checkForForces() ) return ; + if( !checkForForces() ) { + return ; + } unsigned ind=0; - if( getNumberOfAtoms()>0 ) setForcesOnAtoms( getForcesToApply(), ind ); - else setForcesOnCell( getForcesToApply(), ind ); + if( getNumberOfAtoms()>0 ) { + setForcesOnAtoms( getForcesToApply(), ind ); + } else { + setForcesOnCell( getForcesToApply(), ind ); + } } void Colvar::setBoxDerivativesNoPbc( const std::vector& pos, std::vector >& derivs, std::vector& virial ) { unsigned nat=pos.size(); for(unsigned i=0; igetDerivative(3*i+0), - v->getDerivative(3*i+1), - v->getDerivative(3*i+2))); + for(unsigned i=0; igetDerivative(3*i+0), + v->getDerivative(3*i+1), + v->getDerivative(3*i+2))); setBoxDerivatives(v,virial); } } diff --git a/src/core/Colvar.h b/src/core/Colvar.h index ddf048b953..1d0533e34f 100644 --- a/src/core/Colvar.h +++ b/src/core/Colvar.h @@ -38,8 +38,7 @@ This is the abstract base class to use for implementing new collective variables class Colvar : public ActionAtomistic, - public ActionWithValue -{ + public ActionWithValue { private: protected: void requestAtoms(const std::vector & a); diff --git a/src/core/DataPassingObject.cpp b/src/core/DataPassingObject.cpp index d682d974b0..a92202004b 100644 --- a/src/core/DataPassingObject.cpp +++ b/src/core/DataPassingObject.cpp @@ -27,9 +27,14 @@ namespace PLMD { template static void getPointer(const TypesafePtr & p, const std::vector& shape, const unsigned& start, const unsigned& stride, T*&pp ) { - if( shape.size()==1 && stride==1 ) { pp=p.get( {shape[0]} ); } - else if( shape.size()==1 ) { auto p_=p.get( {shape[0],stride} ); pp = p_+start; } - else if( shape.size()==2 ) { pp=p.get( {shape[0],shape[1]} ); } + if( shape.size()==1 && stride==1 ) { + pp=p.get( {shape[0]} ); + } else if( shape.size()==1 ) { + auto p_=p.get( {shape[0],stride} ); + pp = p_+start; + } else if( shape.size()==2 ) { + pp=p.get( {shape[0],shape[1]} ); + } } template @@ -71,117 +76,184 @@ std::unique_ptr DataPassingObject::create(unsigned n) { } else if(n==sizeof(float)) { return std::make_unique>(); } - std::string pp; Tools::convert(n,pp); + std::string pp; + Tools::convert(n,pp); plumed_merror("cannot create an MD interface with sizeof(real)=="+ pp); return NULL; } template double DataPassingObjectTyped::MD2double(const TypesafePtr & m) const { - double d=double(m.template get()); return d; + double d=double(m.template get()); + return d; } template void DataPassingObjectTyped::saveValueAsDouble( const TypesafePtr & val ) { - hasbackup=true; bvalue=double(val.template get()); + hasbackup=true; + bvalue=double(val.template get()); } template void DataPassingObjectTyped::setValuePointer( const TypesafePtr & val, const std::vector& shape, const bool& isconst ) { if( shape.size()==0 ) { - if( isconst ) val.get(); else val.get(); // just check type and discard pointer + if( isconst ) { + val.get(); + } else { + val.get(); // just check type and discard pointer + } } else if( shape.size()==1 ) { - if( isconst ) val.get({shape[0]}); else val.get({shape[0]}); // just check type and discard pointer + if( isconst ) + val.get({shape[0]}); + else + val.get({shape[0]}); // just check type and discard pointer } else if( shape.size()==2 ) { - if( isconst ) val.get({shape[0],shape[1]}); else val.get({shape[0],shape[1]}); // just check type and discard pointer + if( isconst ) + val.get({shape[0],shape[1]}); + else + val.get({shape[0],shape[1]}); // just check type and discard pointer } v=val.copy(); } template void DataPassingObjectTyped::setForcePointer( const TypesafePtr & val, const std::vector& shape ) { - if( shape.size()==0 ) val.get(); // just check type and discard pointer - else if( shape.size()==1 ) val.get({shape[0]}); // just check type and discard pointer - else if( shape.size()==2 ) val.get({shape[0],shape[1]}); // just check type and discard pointer + if( shape.size()==0 ) { + val.get(); // just check type and discard pointer + } else if( shape.size()==1 ) + val.get({shape[0]}); // just check type and discard pointer + else if( shape.size()==2 ) + val.get({shape[0],shape[1]}); // just check type and discard pointer f=val.copy(); } template void DataPassingObjectTyped::setData( Value* value ) { - if( value->getRank()==0 ) { *v.template get() = static_cast(value->get()) / unit; return; } - T* pp; getPointer( v, value->getShape(), start, stride, pp ); unsigned nvals=value->getNumberOfValues(); - for(unsigned i=0; iget(i) ); + if( value->getRank()==0 ) { + *v.template get() = static_cast(value->get()) / unit; + return; + } + T* pp; + getPointer( v, value->getShape(), start, stride, pp ); + unsigned nvals=value->getNumberOfValues(); + for(unsigned i=0; iget(i) ); + } } template void DataPassingObjectTyped::share_data( const unsigned& j, const unsigned& k, Value* value ) { if( value->getRank()==0 ) { - if( hasbackup ) value->set( unit*bvalue ); - else value->set( unit*double(v.template get()) ); + if( hasbackup ) { + value->set( unit*bvalue ); + } else { + value->set( unit*double(v.template get()) ); + } return; } - std::vector s(value->getShape()); if( s.size()==1 ) s[0]=k-j; - const T* pp; getPointer( v, s, start, stride, pp ); + std::vector s(value->getShape()); + if( s.size()==1 ) { + s[0]=k-j; + } + const T* pp; + getPointer( v, s, start, stride, pp ); std::vector & d=value->data; #pragma omp parallel for num_threads(value->getGoodNumThreads(j,k)) - for(unsigned i=j; i void DataPassingObjectTyped::share_data( std::vector& values ) const { - std::vector maxel(1,values.size()); const T* pp; getPointer( v, maxel, start, stride, pp ); + std::vector maxel(1,values.size()); + const T* pp; + getPointer( v, maxel, start, stride, pp ); #pragma omp parallel for num_threads(OpenMP::getGoodNumThreads(values)) - for(unsigned i=0; i void DataPassingObjectTyped::share_data( const std::vector&index, const std::vector& i, Value* value ) { - plumed_dbg_assert( value->getRank()==1 ); std::vector maxel(1,index.size()); + plumed_dbg_assert( value->getRank()==1 ); + std::vector maxel(1,index.size()); #ifndef NDEBUG // bounds are only checked in debug mode since they require this extra step that is potentially expensive maxel[0]=(i.size()>0?*std::max_element(i.begin(),i.end())+1:0); #else maxel[0]=0; #endif - const T* pp; getPointer( v, maxel, start, stride, pp ); + const T* pp; + getPointer( v, maxel, start, stride, pp ); // cannot be parallelized with omp because access to data is not ordered - unsigned k=0; for(const auto & p : index) { value->data[p.index()]=unit*pp[i[k]*stride]; k++; } + unsigned k=0; + for(const auto & p : index) { + value->data[p.index()]=unit*pp[i[k]*stride]; + k++; + } } template void DataPassingObjectTyped::add_force( Value* value ) { - if( value->getRank()==0 ) { *f.template get() += funit*static_cast(value->getForce(0)); return; } - T* pp; getPointer( f, value->getShape(), start, stride, pp ); unsigned nvals=value->getNumberOfValues(); + if( value->getRank()==0 ) { + *f.template get() += funit*static_cast(value->getForce(0)); + return; + } + T* pp; + getPointer( f, value->getShape(), start, stride, pp ); + unsigned nvals=value->getNumberOfValues(); #pragma omp parallel for num_threads(OpenMP::getGoodNumThreads(pp,nvals)) - for(unsigned i=0; igetForce(i)); + for(unsigned i=0; igetForce(i)); + } } template void DataPassingObjectTyped::add_force( const std::vector& index, Value* value ) { - plumed_assert( value->getRank()==1 ); std::vector s(1,index.size()); T* pp; getPointer( f, s, start, stride, pp ); + plumed_assert( value->getRank()==1 ); + std::vector s(1,index.size()); + T* pp; + getPointer( f, s, start, stride, pp ); #pragma omp parallel for num_threads(OpenMP::getGoodNumThreads(pp,index.size())) - for(unsigned i=0; igetForce(index[i])); + for(unsigned i=0; igetForce(index[i])); + } } template void DataPassingObjectTyped::add_force( const std::vector& index, const std::vector& i, Value* value ) { - plumed_dbg_assert( value->getRank()==1 ); std::vector maxel(1,index.size()); + plumed_dbg_assert( value->getRank()==1 ); + std::vector maxel(1,index.size()); #ifndef NDEBUG // bounds are only checked in debug mode since they require this extra step that is potentially expensive maxel[0]=(i.size()>0?*std::max_element(i.begin(),i.end())+1:0); #else maxel[0]=0; #endif - T* pp; getPointer( f, maxel, start, stride, pp ); - unsigned k=0; for(const auto & p : index) { pp[stride*i[k]] += funit*T(value->getForce(p.index())); k++; } + T* pp; + getPointer( f, maxel, start, stride, pp ); + unsigned k=0; + for(const auto & p : index) { + pp[stride*i[k]] += funit*T(value->getForce(p.index())); + k++; + } } template void DataPassingObjectTyped::rescale_force( const unsigned& n, const double& factor, Value* value ) { - plumed_assert( value->getRank()>0 ); std::vector s( value->getShape() ); if( s.size()==1 ) s[0] = n; - T* pp; getPointer( f, s, start, stride, pp ); + plumed_assert( value->getRank()>0 ); + std::vector s( value->getShape() ); + if( s.size()==1 ) { + s[0] = n; + } + T* pp; + getPointer( f, s, start, stride, pp ); #pragma omp parallel for num_threads(OpenMP::getGoodNumThreads(pp,n)) - for(unsigned i=0; i DataPassingTools::create(unsigned n) { } else if(n==sizeof(float)) { return std::make_unique>(); } - std::string pp; Tools::convert(n,pp); + std::string pp; + Tools::convert(n,pp); plumed_merror("cannot create an MD interface with sizeof(real)=="+ pp); return NULL; } diff --git a/src/core/DomainDecomposition.cpp b/src/core/DomainDecomposition.cpp index f1916a68b2..a9a4de4e2f 100644 --- a/src/core/DomainDecomposition.cpp +++ b/src/core/DomainDecomposition.cpp @@ -45,10 +45,18 @@ namespace { enum class Option {automatic, no, yes }; Option interpretEnvString(const char* env,const char* str) { - if(!str) return Option::automatic; - if(!std::strcmp(str,"yes"))return Option::yes; - if(!std::strcmp(str,"no"))return Option::no; - if(!std::strcmp(str,"auto"))return Option::automatic; + if(!str) { + return Option::automatic; + } + if(!std::strcmp(str,"yes")) { + return Option::yes; + } + if(!std::strcmp(str,"no")) { + return Option::no; + } + if(!std::strcmp(str,"auto")) { + return Option::automatic; + } plumed_error()<<"Cannot understand env var "<(valname); ap->addDependency( this ); inputs.push_back( ap ); + ActionToPutData* ap=plumed.getActionSet().selectWithLabel(valname); + ap->addDependency( this ); + inputs.push_back( ap ); } - std::string pbclabel; parse("PBCLABEL",pbclabel); plumed.readInputLine(pbclabel + ": PBC",true); + std::string pbclabel; + parse("PBCLABEL",pbclabel); + plumed.readInputLine(pbclabel + ": PBC",true); // Turn on the domain decomposition - if( Communicator::initialized() ) Set_comm(comm); + if( Communicator::initialized() ) { + Set_comm(comm); + } } void DomainDecomposition::Set_comm(Communicator& comm) { - dd.enable(comm); setAtomsNlocal(getNumberOfAtoms()); setAtomsContiguous(0); + dd.enable(comm); + setAtomsNlocal(getNumberOfAtoms()); + setAtomsContiguous(0); if( dd.Get_rank()!=0 ) { - ActionToPutData* ap=plumed.getActionSet().selectWithLabel("Box"); ap->noforce=true; + ActionToPutData* ap=plumed.getActionSet().selectWithLabel("Box"); + ap->noforce=true; } } unsigned DomainDecomposition::getNumberOfAtoms() const { - if( inputs.size()==0 ) return 0; + if( inputs.size()==0 ) { + return 0; + } return (inputs[0]->getPntrToValue())->getShape()[0]; } void DomainDecomposition::resetForStepStart() { - for(const auto & pp : inputs) pp->resetForStepStart(); + for(const auto & pp : inputs) { + pp->resetForStepStart(); + } } void DomainDecomposition::setStart( const std::string& name, const unsigned& sss) { for(const auto & pp : inputs) { - if( pp->getLabel()==name ) { pp->setStart(name, sss); return; } + if( pp->getLabel()==name ) { + pp->setStart(name, sss); + return; + } } plumed_error(); } void DomainDecomposition::setStride( const std::string& name, const unsigned& sss) { for(const auto & pp : inputs) { - if( pp->getLabel()==name ) { pp->setStride(name, sss); return; } + if( pp->getLabel()==name ) { + pp->setStride(name, sss); + return; + } } plumed_error(); } @@ -162,14 +208,18 @@ void DomainDecomposition::setStride( const std::string& name, const unsigned& ss bool DomainDecomposition::setValuePointer( const std::string& name, const TypesafePtr & val ) { wasset=true; // Once the domain decomposition stuff is transferred moved the setting of this to where the g2l vector is setup for(const auto & pp : inputs) { - if( pp->setValuePointer( name, val ) ) return true; + if( pp->setValuePointer( name, val ) ) { + return true; + } } return false; } bool DomainDecomposition::setForcePointer( const std::string& name, const TypesafePtr & val ) { for(const auto & pp : inputs) { - if( pp->setForcePointer( name, val ) ) return true; + if( pp->setForcePointer( name, val ) ) { + return true; + } } return false; } @@ -182,7 +232,9 @@ void DomainDecomposition::setAtomsNlocal(int n) { // &dd.positionsToBeSent[0] // we make sure they are non-zero-sized so as to // avoid errors when doing boundary check - if(n==0) n++; + if(n==0) { + n++; + } std::size_t nvals = inputs.size(), natoms = getNumberOfAtoms(); dd.positionsToBeSent.resize(n*nvals,0.0); dd.positionsToBeReceived.resize(natoms*nvals,0.0); @@ -196,59 +248,99 @@ void DomainDecomposition::setAtomsGatindex(const TypesafePtr & g,bool fortran) { auto gg=g.get({gatindex.size()}); ddStep=getStep(); if(fortran) { - for(unsigned i=0; iunique_local_needs_update=true; - unique.clear(); forced_unique.clear(); + for(unsigned i=0; iunique_local_needs_update=true; + } + unique.clear(); + forced_unique.clear(); } void DomainDecomposition::setAtomsContiguous(int start) { ddStep=plumed.getStep(); - for(unsigned i=0; iunique_local_needs_update=true; - unique.clear(); forced_unique.clear(); + for(unsigned i=0; iunique_local_needs_update=true; + } + unique.clear(); + forced_unique.clear(); } void DomainDecomposition::shareAll() { - unique.clear(); forced_unique.clear(); int natoms = getNumberOfAtoms(); + unique.clear(); + forced_unique.clear(); + int natoms = getNumberOfAtoms(); if( dd && shuffledAtoms>0 ) { - for(int i=0; i=0 ) unique.push_back( AtomNumber::index(i) ); + for(int i=0; i=0 ) { + unique.push_back( AtomNumber::index(i) ); + } } else { unique.resize(natoms); - for(int i=0; ishare(); + bool atomsNeeded=false; + for(const auto & pp : inputs) { + pp->share(); + } // At first step I scatter all the atoms so as to store their mass and charge // Notice that this works with the assumption that charges and masses are // not changing during the simulation! if( firststep ) { actions = plumed.getActionSet().select(); - shareAll(); return; + shareAll(); + return; } if(getenvForceUnique()==Option::automatic) { @@ -256,11 +348,16 @@ void DomainDecomposition::share() { for(unsigned i=0; iisActive()) { auto l=actions[i]->getUnique().size(); - if(l>largest) largest=l; + if(l>largest) { + largest=l; + } } } - if(largest*2unique_local_needs_update ) actions[i]->updateUniqueLocal( !(dd && shuffledAtoms>0), g2l ); + if( actions[i]->unique_local_needs_update ) { + actions[i]->updateUniqueLocal( !(dd && shuffledAtoms>0), g2l ); + } } // Now reset unique for the new step gch::small_vector*,32> forced_vectors; gch::small_vector*,32> nonforced_vectors; - forced_vectors.reserve(actions.size()); nonforced_vectors.reserve(actions.size()); + forced_vectors.reserve(actions.size()); + nonforced_vectors.reserve(actions.size()); for(unsigned i=0; iisActive()) { if(!actions[i]->getUnique().empty()) { // unique are the local atoms - if( actions[i]->actionHasForces() ) forced_vectors.push_back(&actions[i]->getUniqueLocal()); - else nonforced_vectors.push_back(&actions[i]->getUniqueLocal()); + if( actions[i]->actionHasForces() ) { + forced_vectors.push_back(&actions[i]->getUniqueLocal()); + } else { + nonforced_vectors.push_back(&actions[i]->getUniqueLocal()); + } } } } - if( !(forced_vectors.empty() && nonforced_vectors.empty()) ) atomsNeeded=true; + if( !(forced_vectors.empty() && nonforced_vectors.empty()) ) { + atomsNeeded=true; + } // Merge the atoms from the atoms that have a force on - unique.clear(); forced_unique.clear(); + unique.clear(); + forced_unique.clear(); mergeVectorTools::mergeSortedVectors(forced_vectors,forced_unique); // Merge all the atoms nonforced_vectors.push_back( &forced_unique ); @@ -296,46 +402,72 @@ void DomainDecomposition::share() { } else { for(unsigned i=0; iisActive()) { - if(!actions[i]->getUnique().empty()) { atomsNeeded=true; } + if(!actions[i]->getUnique().empty()) { + atomsNeeded=true; + } } } } // Now we retrieve the atom numbers we need - if( atomsNeeded ) share( unique ); + if( atomsNeeded ) { + share( unique ); + } } void DomainDecomposition::share(const std::vector& unique) { // This retrieves what values we need to get - int ndata=0; std::vector values_to_get; + int ndata=0; + std::vector values_to_get; if(!(int(gatindex.size())==getNumberOfAtoms() && shuffledAtoms==0)) { uniq_index.resize(unique.size()); - for(unsigned i=0; ifixed || firststep) && ip->wasset ) { (ip->mydata)->share_data( unique, uniq_index, ip->copyOutput(0) ); values_to_get.push_back(ip->copyOutput(0)); ndata++; } + if( (!ip->fixed || firststep) && ip->wasset ) { + (ip->mydata)->share_data( unique, uniq_index, ip->copyOutput(0) ); + values_to_get.push_back(ip->copyOutput(0)); + ndata++; + } } } else if( unique_serial) { uniq_index.resize(unique.size()); - for(unsigned i=0; ifixed || firststep) && ip->wasset ) { (ip->mydata)->share_data( unique, uniq_index, ip->copyOutput(0) ); values_to_get.push_back(ip->copyOutput(0)); ndata++; } + if( (!ip->fixed || firststep) && ip->wasset ) { + (ip->mydata)->share_data( unique, uniq_index, ip->copyOutput(0) ); + values_to_get.push_back(ip->copyOutput(0)); + ndata++; + } } } else { // faster version, which retrieves all atoms for(const auto & ip : inputs) { - if( (!ip->fixed || firststep) && ip->wasset ) { (ip->mydata)->share_data( 0, getNumberOfAtoms(), ip->copyOutput(0) ); values_to_get.push_back(ip->copyOutput(0)); ndata++; } + if( (!ip->fixed || firststep) && ip->wasset ) { + (ip->mydata)->share_data( 0, getNumberOfAtoms(), ip->copyOutput(0) ); + values_to_get.push_back(ip->copyOutput(0)); + ndata++; + } } } if(dd && shuffledAtoms>0) { if(dd.async) { - for(unsigned i=0; iget(p.index()); dpoint++; @@ -359,16 +491,23 @@ void DomainDecomposition::share(const std::vector& unique) { std::vector displ5(n); dd.Allgather(count,counts); displ[0]=0; - for(int i=1; idata[dd.indexToBeReceived[i]] = dd.positionsToBeReceived[ndata*i+dpoint]; dpoint++; + values_to_get[j]->data[dd.indexToBeReceived[i]] = dd.positionsToBeReceived[ndata*i+dpoint]; + dpoint++; } } } @@ -376,12 +515,18 @@ void DomainDecomposition::share(const std::vector& unique) { } void DomainDecomposition::wait() { - for(const auto & ip : inputs) ip->dataCanBeSet=false; + for(const auto & ip : inputs) { + ip->dataCanBeSet=false; + } if(dd && shuffledAtoms>0) { - int ndata=0; std::vector values_to_set; + int ndata=0; + std::vector values_to_set; for(const auto & ip : inputs) { - if( (!ip->fixed || firststep) && ip->wasset ) { values_to_set.push_back(ip->copyOutput(0)); ndata++; } + if( (!ip->fixed || firststep) && ip->wasset ) { + values_to_set.push_back(ip->copyOutput(0)); + ndata++; + } } // receive toBeReceived @@ -413,41 +558,61 @@ unsigned DomainDecomposition::getNumberOfForcesToRescale() const { void DomainDecomposition::apply() { std::vector forced_uniq_index(forced_unique.size()); if(!(int(gatindex.size())==getNumberOfAtoms() && shuffledAtoms==0)) { - for(unsigned i=0; igetPntrToValue())->forcesWereAdded() || ip->noforce ) { continue; } else if( ip->wasscaled || (!unique_serial && int(gatindex.size())==getNumberOfAtoms() && shuffledAtoms==0) ) { (ip->mydata)->add_force( gatindex, ip->getPntrToValue() ); - } else { (ip->mydata)->add_force( forced_unique, forced_uniq_index, ip->getPntrToValue() ); } + } else { + (ip->mydata)->add_force( forced_unique, forced_uniq_index, ip->getPntrToValue() ); + } } } void DomainDecomposition::reset() { - if( !unique_serial && int(gatindex.size())==getNumberOfAtoms() && shuffledAtoms==0 ) return; + if( !unique_serial && int(gatindex.size())==getNumberOfAtoms() && shuffledAtoms==0 ) { + return; + } // This is an optimisation to ensure that we don't call std::fill over the whole forces // array if there are a small number of atoms passed between the MD code and PLUMED - if( dd && shuffledAtoms>0 ) getAllActiveAtoms( unique ); - for(const auto & ip : inputs) (ip->copyOutput(0))->clearInputForce( unique ); + if( dd && shuffledAtoms>0 ) { + getAllActiveAtoms( unique ); + } + for(const auto & ip : inputs) { + (ip->copyOutput(0))->clearInputForce( unique ); + } } void DomainDecomposition::writeBinary(std::ostream&o) { - for(const auto & ip : inputs) ip->writeBinary(o); + for(const auto & ip : inputs) { + ip->writeBinary(o); + } } void DomainDecomposition::readBinary(std::istream&i) { - for(const auto & ip : inputs) ip->readBinary(i); + for(const auto & ip : inputs) { + ip->readBinary(i); + } } void DomainDecomposition::broadcastToDomains( Value* val ) { - if( dd ) dd.Bcast( val->data, 0 ); + if( dd ) { + dd.Bcast( val->data, 0 ); + } } void DomainDecomposition::sumOverDomains( Value* val ) { - if( dd && shuffledAtoms>0 ) dd.Sum( val->data ); + if( dd && shuffledAtoms>0 ) { + dd.Sum( val->data ); + } } const long int& DomainDecomposition::getDdStep() const { @@ -476,23 +641,32 @@ void DomainDecomposition::getAllActiveAtoms( std::vector& u ) { void DomainDecomposition::createFullList(const TypesafePtr & n) { if( firststep ) { int natoms = getNumberOfAtoms(); - n.set(int(natoms)); fullList.resize(natoms); - for(unsigned i=0; i(); - if(!fullList.empty()) *xx=&fullList[0]; - else *xx=NULL; + if(!fullList.empty()) { + *xx=&fullList[0]; + } else { + *xx=NULL; + } } void DomainDecomposition::clearFullList() { diff --git a/src/core/DomainDecomposition.h b/src/core/DomainDecomposition.h index d9df5b8849..647d06b874 100644 --- a/src/core/DomainDecomposition.h +++ b/src/core/DomainDecomposition.h @@ -44,7 +44,9 @@ class DomainDecomposition : public ActionForInterface { std::vector positionsToBeReceived; std::vector indexToBeSent; std::vector indexToBeReceived; - operator bool() const {return on;} + operator bool() const { + return on; + } DomainComms(): on(false), async(false) {} void enable(Communicator& c); }; @@ -105,9 +107,13 @@ class DomainDecomposition : public ActionForInterface { void createFullList(const TypesafePtr & x); void getFullList(const TypesafePtr & x); void clearFullList(); - bool onStep() const override { return getNumberOfAtoms()>0; } + bool onStep() const override { + return getNumberOfAtoms()>0; + } unsigned getNumberOfAtoms() const; - DomainDecomposition* castToDomainDecomposition() noexcept final { return this; } + DomainDecomposition* castToDomainDecomposition() noexcept final { + return this; + } }; } diff --git a/src/core/ExchangePatterns.cpp b/src/core/ExchangePatterns.cpp index ee5af5993c..c39e07b8e6 100644 --- a/src/core/ExchangePatterns.cpp +++ b/src/core/ExchangePatterns.cpp @@ -43,28 +43,30 @@ void ExchangePatterns::getFlag(int &flag) { flag=PatternFlag; } -void ExchangePatterns::setSeed(const int seed) -{ +void ExchangePatterns::setSeed(const int seed) { random.setSeed(seed); } -void ExchangePatterns::getList(const TypesafePtr & ind) -{ +void ExchangePatterns::getList(const TypesafePtr & ind) { auto iind=ind.get({NumberOfReplicas}); - switch(PatternFlag) - { + switch(PatternFlag) { case RANDOM: for(int i=0; igetNumberOfArguments(); @@ -69,8 +68,7 @@ FlexibleBin::FlexibleBin(int type, ActionWithArguments *paction, double const &d /// Constructure for 1D FB for PBMETAD FlexibleBin::FlexibleBin(int type, ActionWithArguments *paction, unsigned iarg, double const &d, std::vector &smin, const std::vector &smax): - type(type),paction(paction),sigma(d),sigmamin(smin),sigmamax(smax) -{ + type(type),paction(paction),sigma(d),sigmamin(smin),sigmamax(smax) { // initialize the averages and the variance matrices if(type==diffusion) { std::vector average(1); @@ -117,10 +115,14 @@ void FlexibleBin::update(bool nowAddAHill) { // THE AVERAGE VALUE // beware: the pbc delta.resize(ncv); - for(unsigned i=0; igetArgument(i)); + for(unsigned i=0; igetArgument(i)); + } if(average.size()==0) { // initial time: just set the initial vector average.resize(ncv); - for(unsigned i=0; idifference(i,average[i],cv[i]); @@ -239,7 +241,9 @@ std::vector FlexibleBin::getInverseMatrix() const { std::vector eigenvals(ncv); //eigenvecs: first is eigenvec number, second is eigenvec component - if(diagMat( matrix, eigenvals, eigenvecs )!=0) {plumed_merror("diagonalization in FlexibleBin failed! This matrix is weird\n");}; + if(diagMat( matrix, eigenvals, eigenvecs )!=0) { + plumed_merror("diagonalization in FlexibleBin failed! This matrix is weird\n"); + }; for (i=0; i FlexibleBin::getInverseMatrix() const { for (j=0; jfmax) { - fmax=fact; imax=j; + fmax=fact; + imax=j; } } if(fmax FlexibleBin::getInverseMatrix() const { for(unsigned l=0; lsecond; + if(it!=word_map.end()) { + iword=it->second; + } switch(iword) { case cmd_initialized: CHECK_NOTNULL(val,key); @@ -105,7 +106,9 @@ void GREX::cmd(std::string_view key,const TypesafePtr & val) { break; case cmd_prepare: CHECK_INIT(initialized,key); - if(intracomm.Get_rank()==0) return; + if(intracomm.Get_rank()==0) { + return; + } intracomm.Bcast(partner,0); calculate(); break; @@ -119,7 +122,9 @@ void GREX::cmd(std::string_view key,const TypesafePtr & val) { break; case cmd_calculate: CHECK_INIT(initialized,key); - if(intracomm.Get_rank()!=0) return; + if(intracomm.Get_rank()!=0) { + return; + } intracomm.Bcast(partner,0); calculate(); break; @@ -151,7 +156,9 @@ void GREX::cmd(std::string_view key,const TypesafePtr & val) { break; case cmd_shareAllDeltaBias: CHECK_INIT(initialized,key); - if(intracomm.Get_rank()!=0) return; + if(intracomm.Get_rank()!=0) { + return; + } allDeltaBias.assign(intercomm.Get_size(),0.0); allDeltaBias[intercomm.Get_rank()]=localDeltaBias; intercomm.Sum(allDeltaBias); diff --git a/src/core/GREX.h b/src/core/GREX.h index 772e99fbbb..6a23e54f2b 100644 --- a/src/core/GREX.h +++ b/src/core/GREX.h @@ -33,8 +33,7 @@ class PlumedMain; class Communicator; class GREX: - public WithCmd -{ + public WithCmd { bool initialized; ForwardDecl intracomm_fwd; Communicator& intracomm=*intracomm_fwd; diff --git a/src/core/GenericMolInfo.cpp b/src/core/GenericMolInfo.cpp index 2791d2d112..be83d98f31 100644 --- a/src/core/GenericMolInfo.cpp +++ b/src/core/GenericMolInfo.cpp @@ -59,8 +59,7 @@ GenericMolInfo::GenericMolInfo( const ActionOptions&ao ): ActionAnyorder(ao), ActionPilot(ao), ActionAtomistic(ao), - iswhole_(false) -{ + iswhole_(false) { plumed_assert(getStride()==1); // Read what is contained in the pdb file parse("MOLTYPE",mytype); @@ -69,14 +68,18 @@ GenericMolInfo::GenericMolInfo( const ActionOptions&ao ): parseFlag("WHOLE", iswhole_); auto* moldat=plumed.getActionSet().selectLatest(this); - if( moldat ) log<<" overriding last MOLINFO with label " << moldat->getLabel()<<"\n"; + if( moldat ) { + log<<" overriding last MOLINFO with label " << moldat->getLabel()<<"\n"; + } std::vector backbone; parseAtomList("CHAIN",backbone); if( read_backbone.size()==0 ) { for(unsigned i=1;; ++i) { parseAtomList("CHAIN",i,backbone); - if( backbone.size()==0 ) break; + if( backbone.size()==0 ) { + break; + } read_backbone.push_back(backbone); backbone.resize(0); } @@ -86,17 +89,25 @@ GenericMolInfo::GenericMolInfo( const ActionOptions&ao ): if( read_backbone.size()==0 ) { parse("STRUCTURE",reference); - if( ! pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()))plumed_merror("missing input file " + reference ); + if( ! pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength())) { + plumed_merror("missing input file " + reference ); + } - std::vector chains; pdb.getChainNames( chains ); + std::vector chains; + pdb.getChainNames( chains ); log.printf(" pdb file named %s contains %u chains \n",reference.c_str(), static_cast(chains.size())); for(unsigned i=0; i GenericMolInfo::getSpecialKeywords() { } void GenericMolInfo::getBackbone( std::vector& restrings, const std::string& fortype, std::vector< std::vector >& backbone ) { - if( fortype!=mytype ) error("cannot calculate a variable designed for " + fortype + " molecules for molecule type " + mytype ); - if( MolDataClass::numberOfAtomsPerResidueInBackbone( mytype )==0 ) error("backbone is not defined for molecule type " + mytype ); + if( fortype!=mytype ) { + error("cannot calculate a variable designed for " + fortype + " molecules for molecule type " + mytype ); + } + if( MolDataClass::numberOfAtomsPerResidueInBackbone( mytype )==0 ) { + error("backbone is not defined for molecule type " + mytype ); + } if( read_backbone.size()!=0 ) { - if( restrings.size()!=1 ) error("cannot interpret anything other than all for residues when using CHAIN keywords"); - if( restrings[0]!="all" ) error("cannot interpret anything other than all for residues when using CHAIN keywords"); + if( restrings.size()!=1 ) { + error("cannot interpret anything other than all for residues when using CHAIN keywords"); + } + if( restrings[0]!="all" ) { + error("cannot interpret anything other than all for residues when using CHAIN keywords"); + } backbone.resize( read_backbone.size() ); for(unsigned i=0; i chains; pdb.getChainNames( chains ); + std::vector chains; + pdb.getChainNames( chains ); for(unsigned i=0; i > segments; + int nk, nj; + std::vector< std::vector > segments; std::vector thissegment; - Tools::convert(restrings[0],nk); thissegment.push_back(nk); + Tools::convert(restrings[0],nk); + thissegment.push_back(nk); for(unsigned i=1; i& restrings, const std for(unsigned j=0; jgetline(res); words=Tools::getWords(res); - if(!words.empty() && words[0]=="Error") plumed_error()<0 && atoms.size()>0) error("either use explicit atom list or import from index file"); - if(ndxfile.length()==0 && ndxgroup.size()>0) error("NDX_GROUP can be only used is NDX_FILE is also used"); + if(ndxfile.length()>0 && atoms.size()>0) { + error("either use explicit atom list or import from index file"); + } + if(ndxfile.length()==0 && ndxgroup.size()>0) { + error("NDX_GROUP can be only used is NDX_FILE is also used"); + } if(ndxfile.length()>0) { @@ -169,16 +172,22 @@ Group::Group(const ActionOptions&ao): for(unsigned i=0; i0) { log<<" the following atoms were not found:"; - for(unsigned i=0; i Group::getGroupAtoms() const { std::vector atoms_str(atoms.size()); for(unsigned i=0; i a = getValueIndices( atoms[i] ); - if( xpos[a.first]->getNumberOfValues()==1 ) atoms_str[i] = (xpos[a.first]->getPntrToAction())->getLabel(); - else { Tools::convert( atoms[i].serial(), atoms_str[i] ); } + if( xpos[a.first]->getNumberOfValues()==1 ) { + atoms_str[i] = (xpos[a.first]->getPntrToAction())->getLabel(); + } else { + Tools::convert( atoms[i].serial(), atoms_str[i] ); + } } return atoms_str; } diff --git a/src/core/PbcAction.cpp b/src/core/PbcAction.cpp index ccbca7ebbe..6b036d73a7 100644 --- a/src/core/PbcAction.cpp +++ b/src/core/PbcAction.cpp @@ -48,31 +48,44 @@ void PbcAction::registerKeywords( Keywords& keys ) { PbcAction::PbcAction(const ActionOptions&ao): Action(ao), ActionToPutData(ao), - interface(NULL) -{ - std::vector shape(2); shape[0]=shape[1]=3; - addValue( shape ); setNotPeriodic(); setUnit( "length", "energy" ); - getPntrToValue()->buildDataStore(); getPntrToValue()->reshapeMatrixStore(3); + interface(NULL) { + std::vector shape(2); + shape[0]=shape[1]=3; + addValue( shape ); + setNotPeriodic(); + setUnit( "length", "energy" ); + getPntrToValue()->buildDataStore(); + getPntrToValue()->reshapeMatrixStore(3); } void PbcAction::setPbc() { if( !interface ) { std::vector allput=plumed.getActionSet().select(); - if( allput.size()>1 ) warning("found more than one interface so don't know how to broadcast cell"); + if( allput.size()>1 ) { + warning("found more than one interface so don't know how to broadcast cell"); + } interface = allput[0]; } - Tensor box; if( interface ) interface->broadcastToDomains( getPntrToValue() ); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) box(i,j) = getPntrToValue()->get(3*i+j); + Tensor box; + if( interface ) { + interface->broadcastToDomains( getPntrToValue() ); + } + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + box(i,j) = getPntrToValue()->get(3*i+j); + } pbc.setBox(box); } void PbcAction::wait() { - ActionToPutData::wait(); setPbc(); + ActionToPutData::wait(); + setPbc(); } void PbcAction::readBinary(std::istream&i) { - ActionToPutData::readBinary(i); setPbc(); + ActionToPutData::readBinary(i); + setPbc(); } } diff --git a/src/core/PbcAction.h b/src/core/PbcAction.h index 91042478cf..32ae30184b 100644 --- a/src/core/PbcAction.h +++ b/src/core/PbcAction.h @@ -47,7 +47,9 @@ class PbcAction : public ActionToPutData { Pbc& getPbc(); void wait() override; void readBinary(std::istream&i) override; - PbcAction* castToPbcAction() noexcept final { return this; } + PbcAction* castToPbcAction() noexcept final { + return this; + } }; inline diff --git a/src/core/PlumedMain.cpp b/src/core/PlumedMain.cpp index c2e50f51b2..962aa7e6c3 100644 --- a/src/core/PlumedMain.cpp +++ b/src/core/PlumedMain.cpp @@ -106,10 +106,18 @@ namespace PLMD { plumed_assert(words.size()>2); int error_code; Tools::convert(words[2],error_code); - if(words[1]=="std::generic_category") throw std::system_error(error_code,std::generic_category(),what); - if(words[1]=="std::system_category") throw std::system_error(error_code,std::system_category(),what); - if(words[1]=="std::iostream_category") throw std::system_error(error_code,std::iostream_category(),what); - if(words[1]=="std::future_category") throw std::system_error(error_code,std::future_category(),what); + if(words[1]=="std::generic_category") { + throw std::system_error(error_code,std::generic_category(),what); + } + if(words[1]=="std::system_category") { + throw std::system_error(error_code,std::system_category(),what); + } + if(words[1]=="std::iostream_category") { + throw std::system_error(error_code,std::iostream_category(),what); + } + if(words[1]=="std::future_category") { + throw std::system_error(error_code,std::future_category(),what); + } } if(words[0]=="std::filesystem::filesystem_error") { @@ -117,13 +125,25 @@ namespace PLMD { plumed_assert(words.size()>2); Tools::convert(words[2],error_code); std::error_code x_error_code; - if(words[1]=="std::generic_category") x_error_code=::std::error_code(error_code,::std::generic_category()); - if(words[1]=="std::system_category") x_error_code=::std::error_code(error_code,::std::system_category()); - if(words[1]=="std::iostream_category") x_error_code=::std::error_code(error_code,::std::iostream_category()); - if(words[1]=="std::future_category") x_error_code=::std::error_code(error_code,::std::future_category()); + if(words[1]=="std::generic_category") { + x_error_code=::std::error_code(error_code,::std::generic_category()); + } + if(words[1]=="std::system_category") { + x_error_code=::std::error_code(error_code,::std::system_category()); + } + if(words[1]=="std::iostream_category") { + x_error_code=::std::error_code(error_code,::std::iostream_category()); + } + if(words[1]=="std::future_category") { + x_error_code=::std::error_code(error_code,::std::future_category()); + } - if(words.size()<4) throw std::filesystem::filesystem_error(what,x_error_code); - if(words.size()<5) throw std::filesystem::filesystem_error(what,std::filesystem::path(words[3]),x_error_code); + if(words.size()<4) { + throw std::filesystem::filesystem_error(what,x_error_code); + } + if(words.size()<5) { + throw std::filesystem::filesystem_error(what,std::filesystem::path(words[3]),x_error_code); + } throw std::filesystem::filesystem_error(what,std::filesystem::path(words[3]),std::filesystem::path(words[4]),x_error_code); } @@ -156,17 +176,29 @@ namespace PLMD { if(words[0]=="std::ios_base::failure") { int error_code=0; - if(words.size()>2) Tools::convert(words[2],error_code); - if(words.size()>1 && words[1]=="std::generic_category") throw std::ios_base::failure(what,std::error_code(error_code,std::generic_category())); - if(words.size()>1 && words[1]=="std::system_category") throw std::ios_base::failure(what,std::error_code(error_code,std::system_category())); - if(words.size()>1 && words[1]=="std::iostream_category") throw std::ios_base::failure(what,std::error_code(error_code,std::iostream_category())); - if(words.size()>1 && words[1]=="std::future_category") throw std::ios_base::failure(what,std::error_code(error_code,std::future_category())); + if(words.size()>2) { + Tools::convert(words[2],error_code); + } + if(words.size()>1 && words[1]=="std::generic_category") { + throw std::ios_base::failure(what,std::error_code(error_code,std::generic_category())); + } + if(words.size()>1 && words[1]=="std::system_category") { + throw std::ios_base::failure(what,std::error_code(error_code,std::system_category())); + } + if(words.size()>1 && words[1]=="std::iostream_category") { + throw std::ios_base::failure(what,std::error_code(error_code,std::iostream_category())); + } + if(words.size()>1 && words[1]=="std::future_category") { + throw std::ios_base::failure(what,std::error_code(error_code,std::future_category())); + } throw std::ios_base::failure(what); } if(words[0]=="int") { int value=0; - if(words.size()>1) Tools::convert(words[1],value); + if(words.size()>1) { + Tools::convert(words[1],value); + } throw value; } @@ -256,8 +288,7 @@ PlumedMain::PlumedMain(): // automatically write on log in destructor stopwatch_fwd(log), actionSet_fwd(*this), - passtools(DataPassingTools::create(sizeof(double))) -{ + passtools(DataPassingTools::create(sizeof(double))) { passtools->usingNaturalUnits=false; increaseReferenceCounter(); log.link(comm); @@ -304,7 +335,9 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { } else { int iword=-1; const auto it=word_map.find(words[0]); - if(it!=word_map.end()) iword=it->second; + if(it!=word_map.end()) { + iword=it->second; + } switch(iword) { case cmd_setBox: @@ -346,7 +379,9 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { case cmd_setEnergy: CHECK_INIT(initialized,word); CHECK_NOTNULL(val,word); - if( name_of_energy!="" ) setInputValue( name_of_energy, 0, 1, val ); + if( name_of_energy!="" ) { + setInputValue( name_of_energy, 0, 1, val ); + } break; case cmd_setForces: CHECK_INIT(initialized,word); @@ -416,15 +451,17 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { step=val.get(); startStep(); break; - case cmd_setValue: - { - CHECK_INIT(initialized,words[0]); plumed_assert(nw==2); setInputValue( std::string(words[1]), 0, 1, val ); + case cmd_setValue: { + CHECK_INIT(initialized,words[0]); + plumed_assert(nw==2); + setInputValue( std::string(words[1]), 0, 1, val ); } break; /* ADDED WITH API=7 */ - case cmd_setValueForces: - { - CHECK_INIT(initialized,words[0]); plumed_assert(nw==2); setInputForce( std::string(words[1]), val ); + case cmd_setValueForces: { + CHECK_INIT(initialized,words[0]); + plumed_assert(nw==2); + setInputForce( std::string(words[1]), val ); } break; // words used less frequently: @@ -434,7 +471,9 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { for(const auto & pp : inputs ) { plumed_assert(pp); DomainDecomposition* dd=pp->castToDomainDecomposition(); - if( dd ) dd->setAtomsNlocal(val.get()); + if( dd ) { + dd->setAtomsNlocal(val.get()); + } } break; case cmd_setAtomsGatindex: @@ -442,7 +481,9 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { for(const auto & pp : inputs ) { plumed_assert(pp); DomainDecomposition* dd=pp->castToDomainDecomposition(); - if( dd ) dd->setAtomsGatindex(val,false); + if( dd ) { + dd->setAtomsGatindex(val,false); + } } break; case cmd_setAtomsFGatindex: @@ -450,7 +491,9 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { for(const auto & pp : inputs ) { plumed_assert(pp); DomainDecomposition* dd=pp->castToDomainDecomposition(); - if( dd ) dd->setAtomsGatindex(val,false); + if( dd ) { + dd->setAtomsGatindex(val,false); + } } break; case cmd_setAtomsContiguous: @@ -459,7 +502,9 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { for(const auto & pp : inputs ) { plumed_assert(pp); DomainDecomposition* dd=pp->castToDomainDecomposition(); - if( dd ) dd->setAtomsContiguous(val.get()); + if( dd ) { + dd->setAtomsContiguous(val.get()); + } } break; case cmd_createFullList: @@ -468,18 +513,22 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { for(const auto & pp : inputs ) { plumed_assert(pp); DomainDecomposition* dd=pp->castToDomainDecomposition(); - if( dd ) dd->createFullList(val); + if( dd ) { + dd->createFullList(val); + } } break; - case cmd_getFullList: - { + case cmd_getFullList: { CHECK_INIT(initialized,word); CHECK_NOTNULL(val,word); unsigned nlists=0; for(const auto & pp : inputs ) { plumed_assert(pp); DomainDecomposition* dd=pp->castToDomainDecomposition(); - if( dd ) { dd->getFullList(val); nlists++; } + if( dd ) { + dd->getFullList(val); + nlists++; + } } plumed_assert( nlists==1 ); } @@ -489,46 +538,58 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { for(const auto & pp : inputs ) { plumed_assert(pp); DomainDecomposition* dd=pp->castToDomainDecomposition(); - if( dd ) dd->clearFullList(); + if( dd ) { + dd->clearFullList(); + } } break; /* ADDED WITH API==6 */ - case cmd_getDataRank: - { - CHECK_INIT(initialized,words[0]); plumed_assert(nw==2 || nw==3); - std::string vtype=""; if( nw==3 ) vtype=" TYPE="+std::string(words[2]); + case cmd_getDataRank: { + CHECK_INIT(initialized,words[0]); + plumed_assert(nw==2 || nw==3); + std::string vtype=""; + if( nw==3 ) { + vtype=" TYPE="+std::string(words[2]); + } readInputLine( "grab_" + std::string(words[1]) + ": GET ARG=" + std::string(words[1]) + vtype ); ActionToGetData* as=actionSet.selectWithLabel("grab_"+std::string(words[1])); - plumed_assert( as ); as->get_rank( val ); + plumed_assert( as ); + as->get_rank( val ); } break; /* ADDED WITH API==6 */ - case cmd_getDataShape: - { + case cmd_getDataShape: { CHECK_INIT(initialized,std::string(words[0])); ActionToGetData* as1=actionSet.selectWithLabel("grab_"+std::string(words[1])); - plumed_assert( as1 ); as1->get_shape( val ); + plumed_assert( as1 ); + as1->get_shape( val ); } break; /* ADDED WITH API==6 */ - case cmd_setMemoryForData: - { - CHECK_INIT(initialized,words[0]); plumed_assert(nw==2 || nw==3); + case cmd_setMemoryForData: { + CHECK_INIT(initialized,words[0]); + plumed_assert(nw==2 || nw==3); ActionToGetData* as2=actionSet.selectWithLabel("grab_"+std::string(words[1])); - plumed_assert( as2 ); as2->set_memory( val ); + plumed_assert( as2 ); + as2->set_memory( val ); } break; /* ADDED WITH API==6 */ - case cmd_setErrorHandler: - { - if(val) error_handler=*static_cast(val.get()); - else error_handler.handler=NULL; + case cmd_setErrorHandler: { + if(val) { + error_handler=*static_cast(val.get()); + } else { + error_handler.handler=NULL; + } } break; case cmd_read: CHECK_INIT(initialized,word); - if(val)readInputFile(val.getCString()); - else readInputFile("plumed.dat"); + if(val) { + readInputFile(val.getCString()); + } else { + readInputFile("plumed.dat"); + } break; case cmd_readInputLine: CHECK_INIT(initialized,word); @@ -540,18 +601,21 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { CHECK_NOTNULL(val,word); readInputLines(val.getCString()); break; - case cmd_clear: - { + case cmd_clear: { CHECK_INIT(initialized,word); std::vector natoms; for(const auto & pp : inputs ) { plumed_assert(pp); DomainDecomposition* dd=pp->castToDomainDecomposition(); - if ( dd ) natoms.push_back( dd->getNumberOfAtoms() ); + if ( dd ) { + natoms.push_back( dd->getNumberOfAtoms() ); + } } - actionSet.clearDelete(); inputs.clear(); + actionSet.clearDelete(); + inputs.clear(); for(unsigned i=0; iusingNaturalUnits=true; break; - case cmd_setNoVirial: - { + case cmd_setNoVirial: { CHECK_NOTINIT(initialized,word); ActionToPutData* ap=actionSet.selectWithLabel("Box"); - if( ap ) ap->noforce=true; - else { + if( ap ) { + ap->noforce=true; + } else { ActionForInterface* af = actionSet.selectWithLabel(MDEngine); - if( af ) plumed_merror("setNoVirial should be called after number of atoms have been set"); + if( af ) { + plumed_merror("setNoVirial should be called after number of atoms have been set"); + } } } break; @@ -629,33 +695,38 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { case cmd_setMPIComm: CHECK_NOTINIT(initialized,word); comm.Set_comm(val); - for(const auto & pp : inputs ) pp->Set_comm(comm); + for(const auto & pp : inputs ) { + pp->Set_comm(comm); + } break; case cmd_setMPIFComm: CHECK_NOTINIT(initialized,word); comm.Set_fcomm(val); - for(const auto & pp : inputs ) pp->Set_comm(comm); + for(const auto & pp : inputs ) { + pp->Set_comm(comm); + } break; case cmd_setMPImultiSimComm: CHECK_NOTINIT(initialized,word); multi_sim_comm.Set_comm(val); break; - case cmd_setNatoms: - { + case cmd_setNatoms: { CHECK_NOTINIT(initialized,word); CHECK_NOTNULL(val,word); - int natoms = val.get(); std::string str_natoms; Tools::convert( natoms, str_natoms ); + int natoms = val.get(); + std::string str_natoms; + Tools::convert( natoms, str_natoms ); ActionForInterface* dd=actionSet.selectWithLabel(MDEngine); - if( !dd && natoms>0 ) readInputLine( MDEngine + ": DOMAIN_DECOMPOSITION NATOMS=" + str_natoms + + - " VALUE1=posx UNIT1=length PERIODIC1=NO CONSTANT1=False ROLE1=x" + - " VALUE2=posy UNIT2=length PERIODIC2=NO CONSTANT2=False ROLE2=y" + - " VALUE3=posz UNIT3=length PERIODIC3=NO CONSTANT3=False ROLE3=z" + - " VALUE4=Masses UNIT4=mass PERIODIC4=NO CONSTANT4=True ROLE4=m" + - " VALUE5=Charges UNIT5=charge PERIODIC5=NO CONSTANT5=True ROLE5=q", true ); + if( !dd && natoms>0 ) + readInputLine( MDEngine + ": DOMAIN_DECOMPOSITION NATOMS=" + str_natoms + + + " VALUE1=posx UNIT1=length PERIODIC1=NO CONSTANT1=False ROLE1=x" + + " VALUE2=posy UNIT2=length PERIODIC2=NO CONSTANT2=False ROLE2=y" + + " VALUE3=posz UNIT3=length PERIODIC3=NO CONSTANT3=False ROLE3=z" + + " VALUE4=Masses UNIT4=mass PERIODIC4=NO CONSTANT4=True ROLE4=m" + + " VALUE5=Charges UNIT5=charge PERIODIC5=NO CONSTANT5=True ROLE5=q", true ); } break; - case cmd_setTimestep: - { + case cmd_setTimestep: { CHECK_NOTINIT(initialized,word); CHECK_NOTNULL(val,word); ActionToPutData* ts = actionSet.selectWithLabel("timestep"); @@ -663,7 +734,9 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { readInputLine("timestep: PUT UNIT=time PERIODIC=NO CONSTANT", true); ts = actionSet.selectWithLabel("timestep"); } - if( !ts->setValuePointer("timestep", val ) ) plumed_error(); + if( !ts->setValuePointer("timestep", val ) ) { + plumed_error(); + } // The following is to avoid extra digits in case the MD code uses floats // e.g.: float f=0.002 when converted to double becomes 0.002000000094995 // To avoid this, we keep only up to 6 significant digits after first one @@ -676,13 +749,14 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { } break; /* ADDED WITH API==2 */ - case cmd_setKbT: - { + case cmd_setKbT: { CHECK_NOTINIT(initialized,word); CHECK_NOTNULL(val,word); readInputLine("kBT: PUT CONSTANT PERIODIC=NO UNIT=energy", true); ActionToPutData* kb = actionSet.selectWithLabel("kBT"); - if( !kb->setValuePointer("kBT", val ) ) plumed_error(); + if( !kb->setValuePointer("kBT", val ) ) { + plumed_error(); + } kb->updateUnits( passtools.get() ); } break; @@ -690,21 +764,27 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { case cmd_setRestart: CHECK_NOTINIT(initialized,word); CHECK_NOTNULL(val,word); - if(val.get()!=0) restart=true; + if(val.get()!=0) { + restart=true; + } break; /* ADDED WITH API==4 */ case cmd_doCheckPoint: CHECK_INIT(initialized,word); CHECK_NOTNULL(val,word); doCheckPoint = false; - if(val.get()!=0) doCheckPoint = true; + if(val.get()!=0) { + doCheckPoint = true; + } break; /* ADDED WITH API==6 */ case cmd_setNumOMPthreads: CHECK_NOTNULL(val,word); { auto nt=val.get(); - if(nt==0) nt=1; + if(nt==0) { + nt=1; + } OpenMP::setNumThreads(nt); } break; @@ -713,7 +793,9 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { CHECK_NOTNULL(val,word); { auto id=val.get(); - if(id>=0) gpuDeviceId=id; + if(id>=0) { + gpuDeviceId=id; + } } break; /* ADDED WITH API==6 */ @@ -724,8 +806,11 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { /* ADDED WITH API==10 */ case cmd_setNestedExceptions: CHECK_NOTNULL(val,word); - if(val.get()!=0) nestedExceptions=true; - else nestedExceptions=false; + if(val.get()!=0) { + nestedExceptions=true; + } else { + nestedExceptions=false; + } break; /* STOP API */ case cmd_setMDEngine: @@ -773,16 +858,18 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { CHECK_INIT(initialized,word); runJobsAtEndOfCalculation(); break; - case cmd_isEnergyNeeded: - { + case cmd_isEnergyNeeded: { CHECK_INIT(initialized,word); CHECK_NOTNULL(val,word); if( name_of_energy =="" ) { val.set(int(0)); } else { ActionToPutData* ap=actionSet.selectWithLabel(name_of_energy); - if(ap->isActive()) val.set(int(1)); - else val.set(int(0)); + if(ap->isActive()) { + val.set(int(1)); + } else { + val.set(int(0)); + } } } break; @@ -796,52 +883,68 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { plumed_assert(nw==2); val.set(int(actionRegister().check(dlloader.getHandles(), std::string(words[1])) ? 1:0)); break; - case cmd_setExtraCV: - { + case cmd_setExtraCV: { CHECK_NOTNULL(val,word); plumed_assert(nw==2); - if( valueExists(std::string(words[1])) ) setInputValue( std::string(words[1]), 0, 1, val ); + if( valueExists(std::string(words[1])) ) { + setInputValue( std::string(words[1]), 0, 1, val ); + } } break; - case cmd_setExtraCVForce: - { - CHECK_NOTNULL(val,word); plumed_assert(nw==2); - if( valueExists(std::string(words[1])) ) setInputForce( std::string(words[1]), val ); + case cmd_setExtraCVForce: { + CHECK_NOTNULL(val,word); + plumed_assert(nw==2); + if( valueExists(std::string(words[1])) ) { + setInputForce( std::string(words[1]), val ); + } } break; /* ADDED WITH API==10 */ case cmd_isExtraCVNeeded: CHECK_NOTNULL(val,word); - plumed_assert(nw==2); val.set(int(0)); + plumed_assert(nw==2); + val.set(int(0)); for(const auto & p : inputs) { - if( p->getLabel()==words[1] && p->isActive() ) { val.set(int(1)); break; } + if( p->getLabel()==words[1] && p->isActive() ) { + val.set(int(1)); + break; + } } break; case cmd_GREX: - if(!grex) grex=Tools::make_unique(*this); + if(!grex) { + grex=Tools::make_unique(*this); + } plumed_massert(grex,"error allocating grex"); { std::string kk=std::string(words[1]); - for(unsigned i=2; icmd(kk.c_str(),val); } break; case cmd_CLTool: CHECK_NOTINIT(initialized,word); - if(!cltool) cltool=Tools::make_unique(); + if(!cltool) { + cltool=Tools::make_unique(); + } { std::string kk(words[1]); - for(unsigned i=2; icmd(kk.c_str(),val); } break; break; /* ADDED WITH API==7 */ - case cmd_convert: - { + case cmd_convert: { double v; plumed_assert(words.size()==2); - if(Tools::convertNoexcept(std::string(words[1]),v)) passtools->double2MD(v,val); + if(Tools::convertNoexcept(std::string(words[1]),v)) { + passtools->double2MD(v,val); + } } break; default: @@ -871,7 +974,9 @@ void PlumedMain::cmd(std::string_view word,const TypesafePtr & val) { void PlumedMain::init() { // check that initialization just happens once initialized=true; - if(!log.isOpen()) log.link(stdout); + if(!log.isOpen()) { + log.link(stdout); + } log<<"PLUMED is starting\n"; log<<"Version: "<castToDomainDecomposition(); - if ( dd ) log.printf("Number of atoms: %d\n",dd->getNumberOfAtoms()); + if ( dd ) { + log.printf("Number of atoms: %d\n",dd->getNumberOfAtoms()); + } + } + if(grex) { + log.printf("GROMACS-like replica exchange is on\n"); } - if(grex) log.printf("GROMACS-like replica exchange is on\n"); log.printf("File suffix: %s\n",getSuffix().c_str()); if(plumedDat.length()>0) { readInputFile(plumedDat); @@ -901,11 +1010,13 @@ void PlumedMain::init() { } setUnits( passtools->usingNaturalUnits, passtools->units ); ActionToPutData* ts = actionSet.selectWithLabel("timestep"); - if(ts) log.printf("Timestep: %f\n",(ts->copyOutput(0))->get()); + if(ts) { + log.printf("Timestep: %f\n",(ts->copyOutput(0))->get()); + } ActionToPutData* kb = actionSet.selectWithLabel("kBT"); - if(kb) + if(kb) { log.printf("KbT: %f\n",(kb->copyOutput(0))->get()); - else { + } else { log.printf("KbT has not been set by the MD engine\n"); log.printf("It should be set by hand where needed\n"); } @@ -916,9 +1027,12 @@ void PlumedMain::init() { } void PlumedMain::setupInterfaceActions() { - inputs.clear(); std::vector ap=actionSet.select(); + inputs.clear(); + std::vector ap=actionSet.select(); for(unsigned i=0; igetName()=="ENERGY" || ap[i]->getDependencies().size()==0 ) inputs.push_back( ap[i] ); + if( ap[i]->getName()=="ENERGY" || ap[i]->getDependencies().size()==0 ) { + inputs.push_back( ap[i] ); + } } } @@ -937,15 +1051,21 @@ void PlumedMain::readInputFile(const std::string & str) { void PlumedMain::readInputFile(IFile & ifile) { std::vector words; - while(Tools::getParsedLine(ifile,words) && !endPlumed) readInputWords(words,false); + while(Tools::getParsedLine(ifile,words) && !endPlumed) { + readInputWords(words,false); + } endPlumed=false; pilots=actionSet.select(); setupInterfaceActions(); } void PlumedMain::readInputLine(const std::string & str, const bool& before_init) { - if( !before_init ) plumed_assert(initialized); - if(str.empty()) return; + if( !before_init ) { + plumed_assert(initialized); + } + if(str.empty()) { + return; + } std::vector words=Tools::getWords(str); citations.clear(); readInputWords(words,before_init); @@ -958,7 +1078,9 @@ void PlumedMain::readInputLine(const std::string & str, const bool& before_init) void PlumedMain::readInputLines(const std::string & str) { plumed_assert(initialized); - if(str.empty()) return; + if(str.empty()) { + return; + } log<<"FILE: (temporary)\n"; @@ -967,7 +1089,9 @@ void PlumedMain::readInputLines(const std::string & str) { plumed_assert(fp); // make sure file is closed (and thus deleted) also if an exception occurs - auto deleter=[](auto fp) { std::fclose(fp); }; + auto deleter=[](auto fp) { + std::fclose(fp); + }; std::unique_ptr fp_deleter(fp,deleter); auto ret=std::fputs(str.c_str(),fp); @@ -985,9 +1109,12 @@ void PlumedMain::readInputLines(const std::string & str) { } void PlumedMain::readInputWords(const std::vector & words, const bool& before_init) { - if( !before_init ) plumed_assert(initialized); - if(words.empty())return; - else if(words[0]=="_SET_SUFFIX") { + if( !before_init ) { + plumed_assert(initialized); + } + if(words.empty()) { + return; + } else if(words[0]=="_SET_SUFFIX") { plumed_assert(words.size()==2); setSuffix(words[1]); } else { @@ -997,7 +1124,9 @@ void PlumedMain::readInputWords(const std::vector & words, const bo if(!action) { std::string msg; msg ="ERROR\nI cannot understand line:"; - for(unsigned i=0; iisActive()) { - if(p->checkNeedsGradients()) p->setOption("GRADIENTS"); + if(p->checkNeedsGradients()) { + p->setOption("GRADIENTS"); + } } } @@ -1074,21 +1207,29 @@ void PlumedMain::prepareDependencies() { bool PlumedMain::inputsAreActive() const { for(const auto & ip : inputs) { - if( ip->onStep() ) return true; + if( ip->onStep() ) { + return true; + } } return false; } void PlumedMain::shareAll() { - for(const auto & ip : inputs) ip->shareAll(); + for(const auto & ip : inputs) { + ip->shareAll(); + } } void PlumedMain::shareData() { // atom positions are shared (but only if there is something to do) - if(!active)return; + if(!active) { + return; + } // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("2 Sharing data"); - for(const auto & ip : inputs) ip->share(); + for(const auto & ip : inputs) { + ip->share(); + } } void PlumedMain::performCalcNoUpdate() { @@ -1112,17 +1253,24 @@ void PlumedMain::performCalc() { } void PlumedMain::waitData() { - if(!active)return; + if(!active) { + return; + } // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("3 Waiting for data"); for(const auto & ip : inputs) { - if( ip->isActive() && ip->hasBeenSet() ) ip->wait(); - else if( ip->isActive() ) ip->warning("input requested but this quantity has not been set"); + if( ip->isActive() && ip->hasBeenSet() ) { + ip->wait(); + } else if( ip->isActive() ) { + ip->warning("input requested but this quantity has not been set"); + } } } void PlumedMain::justCalculate() { - if(!active)return; + if(!active) { + return; + } // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("4 Calculating (forward loop)"); bias=0.0; @@ -1132,9 +1280,15 @@ void PlumedMain::justCalculate() { // depend on masses and charges bool firststep=false; for(const auto & ip : inputs) { - if( ip->firststep ) firststep=true; + if( ip->firststep ) { + firststep=true; + } + } + if( firststep ) { + for(const auto & ip : inputs) { + ip->firststep=false; + } } - if( firststep ) { for(const auto & ip : inputs) ip->firststep=false; } int iaction=0; // calculate the active actions in order (assuming *backward* dependence) @@ -1149,22 +1303,39 @@ void PlumedMain::justCalculate() { if(detailedTimers) { auto actionNumberLabel=std::to_string(iaction); const unsigned m=actionSet.size(); - unsigned k=0; unsigned n=1; while(ngetLabel()); } ActionWithValue*av=p->castToActionWithValue(); ActionAtomistic*aa=p->castToActionAtomistic(); { - if(av) av->clearInputForces(); - if(av) av->clearDerivatives(); - if( av && av->calculateOnUpdate() ) continue ; + if(av) { + av->clearInputForces(); + } + if(av) { + av->clearDerivatives(); + } + if( av && av->calculateOnUpdate() ) { + continue ; + } } { - if(aa) if(aa->isActive()) aa->retrieveAtoms(); + if(aa) + if(aa->isActive()) { + aa->retrieveAtoms(); + } + } + if(p->checkNumericalDerivatives()) { + p->calculateNumericalDerivatives(); + } else { + p->calculate(); } - if(p->checkNumericalDerivatives()) p->calculateNumericalDerivatives(); - else p->calculate(); // This retrieves components called bias if(av) { bias+=av->getOutputQuantity("bias"); @@ -1172,9 +1343,13 @@ void PlumedMain::justCalculate() { av->setGradientsIfNeeded(); } // This makes all values that depend on the (fixed) masses and charges constant - if( firststep ) p->setupConstantValues( true ); + if( firststep ) { + p->setupConstantValues( true ); + } ActionWithVirtualAtom*avv=p->castToActionWithVirtualAtom(); - if(avv)avv->setGradientsIfNeeded(); + if(avv) { + avv->setGradientsIfNeeded(); + } } } catch(...) { plumed_error_nested() << "An error happened while calculating " << p->getLabel(); @@ -1190,7 +1365,9 @@ void PlumedMain::justApply() { } void PlumedMain::backwardPropagate() { - if(!active)return; + if(!active) { + return; + } int iaction=0; // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("5 Applying (backward loop)"); @@ -1205,7 +1382,12 @@ void PlumedMain::backwardPropagate() { if(detailedTimers) { auto actionNumberLabel=std::to_string(iaction); const unsigned m=actionSet.size(); - unsigned k=0; unsigned n=1; while(ngetLabel()); } @@ -1218,11 +1400,15 @@ void PlumedMain::backwardPropagate() { // Stopwatch is stopped when sw goes out of scope. // We explicitly declare a Stopwatch::Handler here to allow for conditional initialization. Stopwatch::Handler sw1; - if(detailedTimers) sw1=stopwatch.startStop("5B Update forces"); + if(detailedTimers) { + sw1=stopwatch.startStop("5B Update forces"); + } } void PlumedMain::update() { - if(!active)return; + if(!active) { + return; + } // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("6 Update"); @@ -1233,16 +1419,27 @@ void PlumedMain::update() { p->beforeUpdate(); if(p->isActive() && p->checkUpdate() && updateFlagsTop()) { ActionWithValue* av=dynamic_cast(p.get()); - if( av && av->calculateOnUpdate() ) { p->prepare(); p->calculate(); } - else p->update(); + if( av && av->calculateOnUpdate() ) { + p->prepare(); + p->calculate(); + } else { + p->update(); + } } } - while(!updateFlags.empty()) updateFlags.pop(); - if(!updateFlags.empty()) plumed_merror("non matching changes in the update flags"); + while(!updateFlags.empty()) { + updateFlags.pop(); + } + if(!updateFlags.empty()) { + plumed_merror("non matching changes in the update flags"); + } // Check that no action has told the calculation to stop if(stopNow) { - if(stopFlag) stopFlag.set(int(1)); - else plumed_merror("your md code cannot handle plumed stop events - add a call to plumed.comm(stopFlag,stopCondition)"); + if(stopFlag) { + stopFlag.set(int(1)); + } else { + plumed_merror("your md code cannot handle plumed stop events - add a call to plumed.comm(stopFlag,stopCondition)"); + } } // flush by default every 10000 steps @@ -1251,7 +1448,9 @@ void PlumedMain::update() { if(step%10000==0||doCheckPoint) { fflush(); log.flush(); - for(const auto & p : actionSet) p->fflush(); + for(const auto & p : actionSet) { + p->fflush(); + } } } @@ -1261,10 +1460,12 @@ void PlumedMain::load(const std::string& fileName) { size_t n=libName.find_last_of("."); std::string extension=""; std::string base=libName; - if(n!=std::string::npos && n0) log<<" (only on master node)"; + if(comm.Get_size()>0) { + log<<" (only on master node)"; + } log<<"\n"; // On MPI process (intracomm), we use Get_rank to make sure a single process does the compilation @@ -1289,7 +1495,9 @@ void PlumedMain::load(const std::string& fileName) { // It however decreases the system load if many threads are used. auto s=section.startStop(cmd); int ret=std::system(cmd.c_str()); - if(ret!=0) plumed_error() <<"An error happened while executing command "<isActive() && ip->hasBeenSet() ) ip->reset(); + if( ip->isActive() && ip->hasBeenSet() ) { + ip->reset(); + } } } @@ -1330,7 +1542,9 @@ FILE* PlumedMain::fopen(const char *path, const char *mode) { std::string suffix(getSuffix()); std::string ppathsuf=ppath+suffix; FILE*fp=std::fopen(const_cast(ppathsuf.c_str()),const_cast(mmode.c_str())); - if(!fp) fp=std::fopen(const_cast(ppath.c_str()),const_cast(mmode.c_str())); + if(!fp) { + fp=std::fopen(const_cast(ppath.c_str()),const_cast(mmode.c_str())); + } plumed_massert(fp,"file " + ppath + " cannot be found"); return fp; } @@ -1364,14 +1578,20 @@ void PlumedMain::stop() { void PlumedMain::runJobsAtEndOfCalculation() { for(const auto & p : actionSet) { ActionWithValue* av=dynamic_cast(p.get()); - if( av && av->calculateOnUpdate() ) p->activate(); + if( av && av->calculateOnUpdate() ) { + p->activate(); + } } for(const auto & p : actionSet) { ActionPilot* ap=dynamic_cast(p.get()); ActionWithValue* av=dynamic_cast(p.get()); - if( av && av->calculateOnUpdate() ) { p->calculate(); } - else if( ap && !av && ap->getStride()==0 ) { p->update(); } - else p->runFinalJobs(); + if( av && av->calculateOnUpdate() ) { + p->calculate(); + } else if( ap && !av && ap->getStride()==0 ) { + p->update(); + } else { + p->runFinalJobs(); + } } } @@ -1389,7 +1609,9 @@ unsigned PlumedMain::useCountReferenceCounter() const noexcept { bool PlumedMain::valueExists( const std::string& name ) const { for(const auto & p : inputs) { - if( p->getLabel()==name ) return true; + if( p->getLabel()==name ) { + return true; + } } return false; } @@ -1397,7 +1619,12 @@ bool PlumedMain::valueExists( const std::string& name ) const { void PlumedMain::setInputValue( const std::string& name, const unsigned& start, const unsigned& stride, const TypesafePtr & val ) { bool found=false; for(const auto & pp : inputs) { - if( pp->setValuePointer( name, val ) ) { pp->setStart(name, start); pp->setStride(name, stride); found=true; break; } + if( pp->setValuePointer( name, val ) ) { + pp->setStart(name, start); + pp->setStride(name, stride); + found=true; + break; + } } plumed_massert( found, "found no action to set named " + name ); } @@ -1405,28 +1632,42 @@ void PlumedMain::setInputValue( const std::string& name, const unsigned& start, void PlumedMain::setInputForce( const std::string& name, const TypesafePtr & val ) { bool found=false; for(const auto & pp : inputs) { - if( pp->setForcePointer( name, val ) ) { found=true; break; } + if( pp->setForcePointer( name, val ) ) { + found=true; + break; + } } plumed_massert( found, "found no action to set named " + name ); } void PlumedMain::setUnits( const bool& natural, const Units& u ) { - passtools->usingNaturalUnits = natural; passtools->units=u; + passtools->usingNaturalUnits = natural; + passtools->units=u; std::vector idata = actionSet.select(); - for(const auto & ip : idata) ip->updateUnits( passtools.get() ); - for(const auto & p : actionSet ) p->resetStoredTimestep(); + for(const auto & ip : idata) { + ip->updateUnits( passtools.get() ); + } + for(const auto & p : actionSet ) { + p->resetStoredTimestep(); + } } void PlumedMain::startStep() { - for(const auto & ip : inputs) ip->resetForStepStart(); + for(const auto & ip : inputs) { + ip->resetForStepStart(); + } } void PlumedMain::writeBinary(std::ostream&o)const { - for(const auto & ip : inputs) ip->writeBinary(o); + for(const auto & ip : inputs) { + ip->writeBinary(o); + } } void PlumedMain::readBinary(std::istream&i) { - for(const auto & ip : inputs) ip->readBinary(i); + for(const auto & ip : inputs) { + ip->readBinary(i); + } } void PlumedMain::setEnergyValue( const std::string& name ) { @@ -1459,20 +1700,26 @@ double PlumedMain::MDQuantityToPLUMED( const std::string& unit, const TypesafePt } double PlumedMain::DeprecatedAtoms::getKBoltzmann() const { - if( plumed.usingNaturalUnits() ) return 1.0; + if( plumed.usingNaturalUnits() ) { + return 1.0; + } return kBoltzmann/plumed.getUnits().getEnergy(); } double PlumedMain::DeprecatedAtoms::getKbT() const { ActionForInterface* kb=plumed.getActionSet().selectWithLabel("kBT"); - if( kb ) return (kb->copyOutput(0))->get(); + if( kb ) { + return (kb->copyOutput(0))->get(); + } return 0.0; } int PlumedMain::DeprecatedAtoms::getNatoms() const { std::vector inputs=plumed.getActionSet().select(); for(const auto & pp : inputs ) { - if( pp->getRole()=="x" ) return (pp->copyOutput(0))->getShape()[0]; + if( pp->getRole()=="x" ) { + return (pp->copyOutput(0))->getShape()[0]; + } } return 0; } diff --git a/src/core/PlumedMain.h b/src/core/PlumedMain.h index a50ba85fb7..902ecfe10e 100644 --- a/src/core/PlumedMain.h +++ b/src/core/PlumedMain.h @@ -79,8 +79,7 @@ which defines completely the external plumed interface. It does not contain any static data. */ class PlumedMain: - public WithCmd -{ + public WithCmd { /// Pointers to files opened in actions associated to this object. /// Notice that with the current implementation this should be at the top of this /// structure. Indeed, this should be destroyed *after* all the actions allocated @@ -430,7 +429,9 @@ class PlumedMain: /// Referenge to the log stream Log & getLog(); /// Return the number of the step - long long int getStep()const {return step;} + long long int getStep()const { + return step; + } /// Stop the run void exit(int c=0); /// Load a shared library @@ -458,7 +459,11 @@ class PlumedMain: /// Check if restarting bool getRestart()const; /// Set restart flag - void setRestart(bool f) {if(!doParseOnly) restart=f;} + void setRestart(bool f) { + if(!doParseOnly) { + restart=f; + } + } /// Check if checkpointing bool getCPT()const; /// Set exchangeStep flag @@ -475,7 +480,9 @@ class PlumedMain: void resetActive(bool active); /// Access to exchange patterns - ExchangePatterns& getExchangePatterns() {return exchangePatterns;} + ExchangePatterns& getExchangePatterns() { + return exchangePatterns; + } /// Push a state to update flags void updateFlagsPush(bool); @@ -606,7 +613,9 @@ bool PlumedMain::callErrorHandler(int code,const char* msg)const { if(error_handler.handler) { error_handler.handler(error_handler.ptr,code,msg); return true; - } else return false; + } else { + return false; + } } diff --git a/src/core/PlumedMainInitializer.cpp b/src/core/PlumedMainInitializer.cpp index 674fa0c7f8..cc854a8334 100644 --- a/src/core/PlumedMainInitializer.cpp +++ b/src/core/PlumedMainInitializer.cpp @@ -113,7 +113,9 @@ extern "C" { static void plumed_plumedmain_cmd_safe(void*plumed,const char*key,plumed_safeptr_x safe) { plumed_massert(plumed,"trying to use a plumed object which is not initialized"); auto p=static_cast(plumed); - if(getenvTypesafeDebug()) typesafeDebug(key,safe); + if(getenvTypesafeDebug()) { + typesafeDebug(key,safe); + } p->cmd(key,PLMD::TypesafePtr::fromSafePtr(&safe)); } } @@ -130,70 +132,120 @@ static void translate_current(plumed_nothrow_handler_x nothrow,void**nested=null // cppcheck-suppress rethrowNoCurrentException throw; } catch(const PLMD::ExceptionTypeError & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,20300,msg,opt); } catch(const PLMD::ExceptionError & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,20200,msg,opt); } catch(const PLMD::ExceptionDebug & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,20100,msg,opt); } catch(const PLMD::Exception & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,20000,msg,opt); } catch(const PLMD::lepton::Exception & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,19900,msg,opt); // 11000 to 12000 are "bad exceptions". message will be copied without new allocations } catch(const std::bad_variant_access & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11700,msg,opt); } catch(const std::bad_optional_access & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11600,msg,opt); } catch(const std::bad_exception & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11500,msg,opt); } catch(const std::bad_array_new_length & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11410,msg,opt); } catch(const std::bad_alloc & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11400,msg,opt); } catch(const std::bad_function_call & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11300,msg,opt); } catch(const std::bad_weak_ptr & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11200,msg,opt); } catch(const std::bad_any_cast & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11150,msg,opt); } catch(const std::bad_cast & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11100,msg,opt); } catch(const std::bad_typeid & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11000,msg,opt); } catch(const std::regex_error & e) { - if(!msg) msg=e.what(); - if(e.code()==std::regex_constants::error_collate) nothrow.handler(nothrow.ptr,10240,msg,opt); - else if(e.code()==std::regex_constants::error_ctype) nothrow.handler(nothrow.ptr,10241,msg,opt); - else if(e.code()==std::regex_constants::error_escape) nothrow.handler(nothrow.ptr,10242,msg,opt); - else if(e.code()==std::regex_constants::error_backref) nothrow.handler(nothrow.ptr,10243,msg,opt); - else if(e.code()==std::regex_constants::error_brack) nothrow.handler(nothrow.ptr,10244,msg,opt); - else if(e.code()==std::regex_constants::error_paren) nothrow.handler(nothrow.ptr,10245,msg,opt); - else if(e.code()==std::regex_constants::error_brace) nothrow.handler(nothrow.ptr,10246,msg,opt); - else if(e.code()==std::regex_constants::error_badbrace) nothrow.handler(nothrow.ptr,10247,msg,opt); - else if(e.code()==std::regex_constants::error_range) nothrow.handler(nothrow.ptr,10248,msg,opt); - else if(e.code()==std::regex_constants::error_space) nothrow.handler(nothrow.ptr,10249,msg,opt); - else if(e.code()==std::regex_constants::error_badrepeat) nothrow.handler(nothrow.ptr,10250,msg,opt); - else if(e.code()==std::regex_constants::error_complexity) nothrow.handler(nothrow.ptr,10251,msg,opt); - else if(e.code()==std::regex_constants::error_stack) nothrow.handler(nothrow.ptr,10252,msg,opt); + if(!msg) { + msg=e.what(); + } + if(e.code()==std::regex_constants::error_collate) { + nothrow.handler(nothrow.ptr,10240,msg,opt); + } else if(e.code()==std::regex_constants::error_ctype) { + nothrow.handler(nothrow.ptr,10241,msg,opt); + } else if(e.code()==std::regex_constants::error_escape) { + nothrow.handler(nothrow.ptr,10242,msg,opt); + } else if(e.code()==std::regex_constants::error_backref) { + nothrow.handler(nothrow.ptr,10243,msg,opt); + } else if(e.code()==std::regex_constants::error_brack) { + nothrow.handler(nothrow.ptr,10244,msg,opt); + } else if(e.code()==std::regex_constants::error_paren) { + nothrow.handler(nothrow.ptr,10245,msg,opt); + } else if(e.code()==std::regex_constants::error_brace) { + nothrow.handler(nothrow.ptr,10246,msg,opt); + } else if(e.code()==std::regex_constants::error_badbrace) { + nothrow.handler(nothrow.ptr,10247,msg,opt); + } else if(e.code()==std::regex_constants::error_range) { + nothrow.handler(nothrow.ptr,10248,msg,opt); + } else if(e.code()==std::regex_constants::error_space) { + nothrow.handler(nothrow.ptr,10249,msg,opt); + } else if(e.code()==std::regex_constants::error_badrepeat) { + nothrow.handler(nothrow.ptr,10250,msg,opt); + } else if(e.code()==std::regex_constants::error_complexity) { + nothrow.handler(nothrow.ptr,10251,msg,opt); + } else if(e.code()==std::regex_constants::error_stack) { + nothrow.handler(nothrow.ptr,10252,msg,opt); + } // fallback to generic runtime_error - else nothrow.handler(nothrow.ptr,10200,msg,opt); + else { + nothrow.handler(nothrow.ptr,10200,msg,opt); + } } catch(const std::filesystem::filesystem_error & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } int value=e.code().value(); opt[2]="c"; // "c" passes the error code. @@ -204,11 +256,17 @@ static void translate_current(plumed_nothrow_handler_x nothrow,void**nested=null int system_category=2; int iostream_category=3; int future_category=4; - if(e.code().category()==std::generic_category()) opt[5]=&generic_category; - else if(e.code().category()==std::system_category()) opt[5]=&system_category; - else if(e.code().category()==std::iostream_category()) opt[5]=&iostream_category; - else if(e.code().category()==std::future_category()) opt[5]=&future_category; - else opt[5]=nullptr; + if(e.code().category()==std::generic_category()) { + opt[5]=&generic_category; + } else if(e.code().category()==std::system_category()) { + opt[5]=&system_category; + } else if(e.code().category()==std::iostream_category()) { + opt[5]=&iostream_category; + } else if(e.code().category()==std::future_category()) { + opt[5]=&future_category; + } else { + opt[5]=nullptr; + } // local class, just needed to propely pass path information // path is stored as a span of bytes. @@ -240,74 +298,124 @@ static void translate_current(plumed_nothrow_handler_x nothrow,void**nested=null nothrow.handler(nothrow.ptr,10229,msg,opt); } catch(const std::ios_base::failure & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } int value=e.code().value(); opt[2]="c"; // "c" passes the error code. opt[3]=&value; - if(e.code().category()==std::generic_category()) nothrow.handler(nothrow.ptr,10230,msg,opt); - else if(e.code().category()==std::system_category()) nothrow.handler(nothrow.ptr,10231,msg,opt); - else if(e.code().category()==std::iostream_category()) nothrow.handler(nothrow.ptr,10232,msg,opt); - else if(e.code().category()==std::future_category()) nothrow.handler(nothrow.ptr,10233,msg,opt); - else + if(e.code().category()==std::generic_category()) { + nothrow.handler(nothrow.ptr,10230,msg,opt); + } else if(e.code().category()==std::system_category()) { + nothrow.handler(nothrow.ptr,10231,msg,opt); + } else if(e.code().category()==std::iostream_category()) { + nothrow.handler(nothrow.ptr,10232,msg,opt); + } else if(e.code().category()==std::future_category()) { + nothrow.handler(nothrow.ptr,10233,msg,opt); + } else // 10239 represents std::ios_base::failure with default constructur + { nothrow.handler(nothrow.ptr,10239,msg,opt); + } } catch(const std::system_error & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } int value=e.code().value(); opt[2]="c"; // "c" passes the error code. opt[3]=&value; - if(e.code().category()==std::generic_category()) nothrow.handler(nothrow.ptr,10220,msg,opt); - else if(e.code().category()==std::system_category()) nothrow.handler(nothrow.ptr,10221,msg,opt); - else if(e.code().category()==std::iostream_category()) nothrow.handler(nothrow.ptr,10222,msg,opt); - else if(e.code().category()==std::future_category()) nothrow.handler(nothrow.ptr,10223,msg,opt); + if(e.code().category()==std::generic_category()) { + nothrow.handler(nothrow.ptr,10220,msg,opt); + } else if(e.code().category()==std::system_category()) { + nothrow.handler(nothrow.ptr,10221,msg,opt); + } else if(e.code().category()==std::iostream_category()) { + nothrow.handler(nothrow.ptr,10222,msg,opt); + } else if(e.code().category()==std::future_category()) { + nothrow.handler(nothrow.ptr,10223,msg,opt); + } // fallback to generic runtime_error - else nothrow.handler(nothrow.ptr,10200,msg,opt); + else { + nothrow.handler(nothrow.ptr,10200,msg,opt); + } } catch(const std::underflow_error &e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10215,msg,opt); } catch(const std::overflow_error &e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10210,msg,opt); } catch(const std::range_error &e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10205,msg,opt); } catch(const std::runtime_error & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10200,msg,opt); } catch(const std::future_error & e) { - if(!msg) msg=e.what(); - if(e.code()==std::make_error_code(std::future_errc::broken_promise)) nothrow.handler(nothrow.ptr,10125,msg,opt); - else if(e.code()==std::make_error_code(std::future_errc::future_already_retrieved)) nothrow.handler(nothrow.ptr,10126,msg,opt); - else if(e.code()==std::make_error_code(std::future_errc::promise_already_satisfied)) nothrow.handler(nothrow.ptr,10127,msg,opt); - else if(e.code()==std::make_error_code(std::future_errc::no_state)) nothrow.handler(nothrow.ptr,10128,msg,opt); + if(!msg) { + msg=e.what(); + } + if(e.code()==std::make_error_code(std::future_errc::broken_promise)) { + nothrow.handler(nothrow.ptr,10125,msg,opt); + } else if(e.code()==std::make_error_code(std::future_errc::future_already_retrieved)) { + nothrow.handler(nothrow.ptr,10126,msg,opt); + } else if(e.code()==std::make_error_code(std::future_errc::promise_already_satisfied)) { + nothrow.handler(nothrow.ptr,10127,msg,opt); + } else if(e.code()==std::make_error_code(std::future_errc::no_state)) { + nothrow.handler(nothrow.ptr,10128,msg,opt); + } // fallback to generic logic_error - else nothrow.handler(nothrow.ptr,10100,msg,opt); + else { + nothrow.handler(nothrow.ptr,10100,msg,opt); + } } catch(const std::out_of_range & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10120,msg,opt); } catch(const std::length_error & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10115,msg,opt); } catch(const std::domain_error & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10110,msg,opt); } catch(const std::invalid_argument & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10105,msg,opt); } catch(const std::logic_error & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10100,msg,opt); // generic exception. message will be copied without new allocations // reports all non caught exceptions that are derived from std::exception // for instance, boost exceptions would end up here } catch(const std::exception & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,10000,msg,opt); } catch(const char* m) { - if(!msg) msg=m; + if(!msg) { + msg=m; + } nothrow.handler(nothrow.ptr,10000,msg,opt); } catch(const std::string & s) { - if(!msg) msg=s.c_str(); + if(!msg) { + msg=s.c_str(); + } nothrow.handler(nothrow.ptr,10000,msg,opt); } catch (...) { // if exception cannot be translated, we add a bad_exception to the stack @@ -357,7 +465,9 @@ extern "C" { // was linked against a different C++ library try { plumed_massert(plumed,"trying to use a plumed object which is not initialized"); - if(getenvTypesafeDebug()) typesafeDebug(key,safe); + if(getenvTypesafeDebug()) { + typesafeDebug(key,safe); + } p->cmd(key,PLMD::TypesafePtr::fromSafePtr(&safe)); } catch(...) { if(p->getNestedExceptions()) { @@ -436,33 +546,41 @@ class PlumedMainInitializer { const bool debug; public: PlumedMainInitializer(): - debug(std::getenv("PLUMED_LOAD_DEBUG")) - { + debug(std::getenv("PLUMED_LOAD_DEBUG")) { // make sure static plumed_function_pointers is initialized here plumed_symbol_table_init(); - if(debug) std::fprintf(stderr,"+++ Initializing PLUMED with plumed_symbol_table version %i at %p\n",plumed_symbol_table.version,(void*)&plumed_symbol_table); + if(debug) { + std::fprintf(stderr,"+++ Initializing PLUMED with plumed_symbol_table version %i at %p\n",plumed_symbol_table.version,(void*)&plumed_symbol_table); + } #if defined(__PLUMED_HAS_DLOPEN) if(std::getenv("PLUMED_LOAD_SKIP_REGISTRATION")) { - if(debug) std::fprintf(stderr,"+++ Skipping registration +++\n"); + if(debug) { + std::fprintf(stderr,"+++ Skipping registration +++\n"); + } return; } typedef plumed_plumedmain_function_holder_x* (*plumed_kernel_register_type_x)(const plumed_plumedmain_function_holder_x*); plumed_kernel_register_type_x plumed_kernel_register=nullptr; void* handle=nullptr; #if defined(__PLUMED_HAS_RTLD_DEFAULT) - if(debug) std::fprintf(stderr,"+++ Registering functions. Looking in RTLD_DEFAULT +++\n"); + if(debug) { + std::fprintf(stderr,"+++ Registering functions. Looking in RTLD_DEFAULT +++\n"); + } void* dls=dlsym(RTLD_DEFAULT,"plumed_kernel_register"); #else handle=dlopen(NULL,RTLD_LOCAL); - if(debug) std::fprintf(stderr,"+++ Registering functions. dlopen handle at %p +++\n",handle); + if(debug) { + std::fprintf(stderr,"+++ Registering functions. dlopen handle at %p +++\n",handle); + } void* dls=dlsym(handle,"plumed_kernel_register"); #endif *(void **)(&plumed_kernel_register)=dls; if(debug) { if(plumed_kernel_register) { std::fprintf(stderr,"+++ plumed_kernel_register found at %p +++\n",dls); + } else { + std::fprintf(stderr,"+++ plumed_kernel_register not found +++\n"); } - else std::fprintf(stderr,"+++ plumed_kernel_register not found +++\n"); } void*createp; void*cmdp; @@ -470,17 +588,24 @@ class PlumedMainInitializer { plumed_convert_fptr(createp,plumed_symbol_table.functions.create); plumed_convert_fptr(cmdp,plumed_symbol_table.functions.cmd); plumed_convert_fptr(finalizep,plumed_symbol_table.functions.finalize); - if(plumed_kernel_register && debug) std::fprintf(stderr,"+++ Registering functions at %p (%p,%p,%p) +++\n", - (void*)&plumed_symbol_table.functions,createp,cmdp,finalizep); - if(plumed_kernel_register) (*plumed_kernel_register)(&plumed_symbol_table.functions); + if(plumed_kernel_register && debug) + std::fprintf(stderr,"+++ Registering functions at %p (%p,%p,%p) +++\n", + (void*)&plumed_symbol_table.functions,createp,cmdp,finalizep); + if(plumed_kernel_register) { + (*plumed_kernel_register)(&plumed_symbol_table.functions); + } // Notice that handle could be null in the following cases: // - if we use RTLD_DEFAULT // - on Linux if we don't use RTLD_DEFAULT, since dlopen(NULL,RTLD_LOCAL) returns a null pointer. - if(handle) dlclose(handle); + if(handle) { + dlclose(handle); + } #endif } ~PlumedMainInitializer() { - if(debug) std::fprintf(stderr,"+++ Finalizing PLUMED with plumed_symbol_table at %p\n",(void*)&plumed_symbol_table); + if(debug) { + std::fprintf(stderr,"+++ Finalizing PLUMED with plumed_symbol_table at %p\n",(void*)&plumed_symbol_table); + } } } PlumedMainInitializerRegisterMe; } diff --git a/src/core/RegisterBase.cpp b/src/core/RegisterBase.cpp index 00be774de6..a181ba8bbc 100644 --- a/src/core/RegisterBase.cpp +++ b/src/core/RegisterBase.cpp @@ -51,18 +51,18 @@ Singleton & getSingleton() { } Register::RegistrationLock::RegistrationLock(const std::string & fullPath): - active(true) -{ + active(true) { pushDLRegistration(fullPath); } Register::RegistrationLock::~RegistrationLock() noexcept { - if(active) popDLRegistration(); + if(active) { + popDLRegistration(); + } } Register::RegistrationLock::RegistrationLock(RegistrationLock&& other) noexcept: - active(other.active) -{ + active(other.active) { other.active=false; } @@ -83,14 +83,18 @@ void Register::pushDLRegistration(const std::string & fullPath) { void Register::popDLRegistration() noexcept { auto & singleton=getSingleton(); - for(auto & reg : singleton.registers) reg->clearStaged(); + for(auto & reg : singleton.registers) { + reg->clearStaged(); + } singleton.registeringCounter--; singleton.registeringMutex.unlock(); } void Register::completeAllRegistrations(void* image) { auto & singleton=getSingleton(); - for(auto & reg : singleton.registers) reg->completeRegistration(image); + for(auto & reg : singleton.registers) { + reg->completeRegistration(image); + } } std::string Register::imageToString(void* image) { @@ -121,7 +125,9 @@ Register::~Register() noexcept { // this is to protect removal std::unique_lock lock(singleton.registeringMutex); auto it=std::find(singleton.registers.begin(),singleton.registers.end(),this); - if(it!=singleton.registers.end()) singleton.registers.erase(it); + if(it!=singleton.registers.end()) { + singleton.registers.erase(it); + } } std::vector Register::getKeysWithDLHandle(void* image) const { @@ -129,7 +135,9 @@ std::vector Register::getKeysWithDLHandle(void* image) const { const auto prefix=imageToString(image)+":"; for(auto & k : getKeys()) { if(Tools::startWith(k,prefix)) { - if(!std::getenv("PLUMED_LOAD_ACTION_DEBUG")) k=k.substr(prefix.length()); + if(!std::getenv("PLUMED_LOAD_ACTION_DEBUG")) { + k=k.substr(prefix.length()); + } res.push_back(k); } } @@ -138,7 +146,9 @@ std::vector Register::getKeysWithDLHandle(void* image) const { std::ostream & operator<<(std::ostream &log,const Register ®) { std::vector s(reg.getKeys()); - for(unsigned i=0; i bool RegisterBase::check(const std::vector & images,const std::string & key) const { // lock map for reading std::shared_lock lock(mutex); - if(m.count(key)>0) return true; + if(m.count(key)>0) { + return true; + } for(auto image : images) { std::string k=imageToString(image)+":"+key; - if(m.count(k)>0) return true; + if(m.count(k)>0) { + return true; + } } return false; } @@ -206,7 +210,9 @@ const Content & RegisterBase::get(const std::vector & images,con std::shared_lock lock(mutex); for(auto image = images.rbegin(); image != images.rend(); ++image) { auto qualified_key=imageToString(*image) + ":" + key; - if(m.count(qualified_key)>0) return m.find(qualified_key)->second->content; + if(m.count(qualified_key)>0) { + return m.find(qualified_key)->second->content; + } } plumed_assert(m.count(key)>0); return m.find(key)->second->content; @@ -218,7 +224,9 @@ const std::string & RegisterBase::getFullPath(const std::vector std::shared_lock lock(mutex); for(auto image = images.rbegin(); image != images.rend(); ++image) { auto qualified_key=imageToString(*image) + ":" + key; - if(m.count(qualified_key)>0) return m.find(qualified_key)->second->fullPath; + if(m.count(qualified_key)>0) { + return m.find(qualified_key)->second->fullPath; + } } plumed_assert(m.count(key)>0); return m.find(key)->second->fullPath; @@ -239,7 +247,8 @@ void RegisterBase::remove(ID id) { if(id.ptr) { for(auto p=m.begin(); p!=m.end(); ++p) { if(p->second.get()==id.ptr) { - m.erase(p); break; + m.erase(p); + break; } } } @@ -250,7 +259,9 @@ std::vector RegisterBase::getKeys() const { // lock map for reading std::shared_lock lock(mutex); std::vector s; - for(const auto & it : m) s.push_back(it.first); + for(const auto & it : m) { + s.push_back(it.first); + } std::sort(s.begin(),s.end()); return s; } @@ -259,7 +270,9 @@ template RegisterBase::~RegisterBase() noexcept { if(m.size()>0) { std::string names=""; - for(const auto & p : m) names+=p.first+" "; + for(const auto & p : m) { + names+=p.first+" "; + } std::cerr<<"WARNING: Directive "+ names +" has not been properly unregistered. This might lead to memory leak!!\n"; } } diff --git a/src/core/TargetDist.cpp b/src/core/TargetDist.cpp index 40cd2c3828..3f76b16fcc 100644 --- a/src/core/TargetDist.cpp +++ b/src/core/TargetDist.cpp @@ -50,9 +50,14 @@ void TargetDist::read( const PDB& pdb, const std::vector & ar ) { void TargetDist::read( const std::vector& targ, const std::vector & ar ) { plumed_assert( targ.size()==ar.size() ); - target.resize( ar.size() ); args.resize( ar.size() ); + target.resize( ar.size() ); + args.resize( ar.size() ); log.printf(" distance from this point in cv space : "); - for(unsigned i=0; i& derivs ) { double dist=0; for(unsigned i=0; idifference( target[i], args[i]->get() ); - derivs[i]=tmp; dist+=tmp*tmp; + derivs[i]=tmp; + dist+=tmp*tmp; } dist=std::sqrt(dist); - for(unsigned i=0; igetName()=="ACCUMULATE" || action->getName()=="COLLECT" ) valtype=average; + if( action->getName()=="ACCUMULATE" || action->getName()=="COLLECT" ) { + valtype=average; + } + } + if( action ) { + storedata=action->getName()=="PUT" || valtype==average; + } + if( ss.size() && withderiv ) { + storedata=true; } - if( action ) storedata=action->getName()=="PUT" || valtype==average; - if( ss.size() && withderiv ) storedata=true; setShape( ss ); } void Value::setValType( const std::string& vtype ) { - if( vtype=="normal" ) valtype=normal; - else if( vtype=="constant" ) valtype=constant; - else if( vtype=="average" ) valtype=average; - else if( vtype=="calcFromAverage" ) valtype=calcFromAverage; - else plumed_merror("invalid valtype " + vtype ); + if( vtype=="normal" ) { + valtype=normal; + } else if( vtype=="constant" ) { + valtype=constant; + } else if( vtype=="average" ) { + valtype=average; + } else if( vtype=="calcFromAverage" ) { + valtype=calcFromAverage; + } else { + plumed_merror("invalid valtype " + vtype ); + } } void Value::setShape( const std::vector&ss ) { - std::size_t tot=1; shape.resize( ss.size() ); - for(unsigned i=0; i0 && hasDeriv ) { // This is for grids ngrid_der = shape.size(); - if( action ) ngrid_der = action->getNumberOfDerivatives(); + if( action ) { + ngrid_der = action->getNumberOfDerivatives(); + } std::size_t ndata = tot*(1+ngrid_der); - data.resize( ndata ); inputForce.resize( tot ); + data.resize( ndata ); + inputForce.resize( tot ); } else if( shape.size()==0 ) { // This is for scalars - data.resize(1); inputForce.resize(1); + data.resize(1); + inputForce.resize(1); } else if( storedata && shape.size()<2 ) { // This is for vectors (matrices have special version because we have sparse storage) - data.resize( tot ); inputForce.resize( tot ); + data.resize( tot ); + inputForce.resize( tot ); } } @@ -155,22 +175,32 @@ bool Value::isPeriodic()const { } bool Value::applyForce(std::vector& forces ) const { - if( !hasForce || valtype!=normal ) return false; + if( !hasForce || valtype!=normal ) { + return false; + } plumed_dbg_massert( data.size()-1==forces.size()," forces array has wrong size" ); const unsigned N=data.size()-1; - for(unsigned i=0; ierror("could not convert period string " + str_min + " to real"); + if( !Tools::convertNoexcept(str_min,min) ) { + action->error("could not convert period string " + str_min + " to real"); + } str_max=pmax; - if( !Tools::convertNoexcept(str_max,max) ) action->error("could not convert period string " + str_max + " to read"); + if( !Tools::convertNoexcept(str_max,max) ) { + action->error("could not convert period string " + str_max + " to read"); + } setupPeriodicity(); } @@ -188,7 +218,9 @@ void Value::getDomain(double&minout,double&maxout) const { void Value::setGradients( ActionAtomistic* aa, unsigned& start ) { // Can't do gradients if we don't have derivatives - if( !hasDeriv ) return; + if( !hasDeriv ) { + return; + } plumed_assert( shape.size()==0 ); for(unsigned j=0; jgetNumberOfAtoms(); ++j) { Vector der(data[1+start+3*j],data[1+start+3*j+1],data[1+start+3*j+2]); @@ -198,7 +230,10 @@ void Value::setGradients( ActionAtomistic* aa, unsigned& start ) { } void Value::passGradients( const double& der, std::map& g ) const { - for(const auto & p : gradients) { AtomNumber iatom=p.first; g[iatom] += p.second*der; } + for(const auto & p : gradients) { + AtomNumber iatom=p.first; + g[iatom] += p.second*der; + } } double Value::projection(const Value& v1,const Value&v2) { @@ -222,15 +257,24 @@ ActionWithValue* Value::getPntrToAction() { void Value::set(const std::size_t& n, const double& v ) { value_set=true; - if( getRank()==0 ) { plumed_assert( n==0 ); data[n]=v; applyPeriodicity(n); } - else if( !hasDeriv ) { plumed_dbg_massert( n( action ); - if( av ) (av->getFirstActionInChain())->never_reduce_tasks=true; + if( av ) { + (av->getFirstActionInChain())->never_reduce_tasks=true; + } } void Value::reshapeMatrixStore( const unsigned& n ) { plumed_dbg_assert( shape.size()==2 && !hasDeriv ); - if( !storedata ) return ; - ncols=n; if( ncols>shape[1] ) ncols=shape[1]; + if( !storedata ) { + return ; + } + ncols=n; + if( ncols>shape[1] ) { + ncols=shape[1]; + } unsigned size=shape[0]*ncols; if( matrix_bookeeping.size()!=(size+shape[0]) ) { - data.resize( size ); inputForce.resize( size ); + data.resize( size ); + inputForce.resize( size ); matrix_bookeeping.resize( size + shape[0], 0 ); if( ncols>=shape[1] ) { for(unsigned i=0; i0 ) return true; + if( !storedata && shape.size()>0 ) { + return true; + } ActionWithVector* av=dynamic_cast(action); - if( av ) return (av->getFirstActionInChain())->getLabel()==c; + if( av ) { + return (av->getFirstActionInChain())->getLabel()==c; + } return false; } void Value::setConstant() { - valtype=constant; storedata=true; setShape( shape ); - if( getRank()==2 && !hasDeriv ) reshapeMatrixStore( shape[1] ); + valtype=constant; + storedata=true; + setShape( shape ); + if( getRank()==2 && !hasDeriv ) { + reshapeMatrixStore( shape[1] ); + } } void Value::writeBinary(std::ostream&o) const { @@ -333,22 +416,34 @@ void Value::writeBinary(std::ostream&o) const { void Value::setSymmetric( const bool& sym ) { plumed_assert( shape.size()==2 && !hasDeriv ); - if( sym && shape[0]!=shape[1] ) plumed_merror("non-square matrix cannot be symmetric"); + if( sym && shape[0]!=shape[1] ) { + plumed_merror("non-square matrix cannot be symmetric"); + } symmetric=sym; } void Value::retrieveEdgeList( unsigned& nedge, std::vector >& active, std::vector& elems ) { - nedge=0; plumed_dbg_assert( shape.size()==2 && !hasDeriv ); + nedge=0; + plumed_dbg_assert( shape.size()==2 && !hasDeriv ); // Check we have enough space to store the edge list - if( elems.size()i ) continue; - active[nedge].first = i; active[nedge].second = getRowIndex(i,j); - elems[nedge] = get(i*ncols+j,false); nedge++; + if( fabs(get(i*ncols+j,false))i ) { + continue; + } + active[nedge].first = i; + active[nedge].second = getRowIndex(i,j); + elems[nedge] = get(i*ncols+j,false); + nedge++; } } } @@ -359,26 +454,37 @@ void Value::readBinary(std::istream&i) { void Value::convertIndexToindices(const std::size_t& index, std::vector& indices ) const { if( hasDeriv || getRank()==1 ) { - std::size_t kk=index; indices[0]=index%shape[0]; + std::size_t kk=index; + indices[0]=index%shape[0]; for(unsigned i=1; i=2) indices[shape.size()-1]=(kk-indices[shape.size()-2])/shape[shape.size()-2]; + if(shape.size()>=2) { + indices[shape.size()-1]=(kk-indices[shape.size()-2])/shape[shape.size()-2]; + } } else if( getRank()==2 ) { - indices[0]=std::floor( index/shape[1] ); indices[1] = index%shape[1]; + indices[0]=std::floor( index/shape[1] ); + indices[1] = index%shape[1]; } } void Value::print( OFile& ofile ) const { - if( isPeriodic() ) { ofile.printField( "min_" + name, str_min ); ofile.printField("max_" + name, str_max ); } + if( isPeriodic() ) { + ofile.printField( "min_" + name, str_min ); + ofile.printField("max_" + name, str_max ); + } if( shape.size()==0 || getNumberOfValues()==1 ) { ofile.printField( name, get(0) ); } else { std::vector indices( shape.size() ); for(unsigned i=0; i0 && hasDerivatives() ) return "grid"; - if( getRank()==1 ) return "vector"; - if( getRank()==2 ) return "matrix"; + if( getRank()==0 ) { + return "scalar"; + } + if( getRank()>0 && hasDerivatives() ) { + return "grid"; + } + if( getRank()==1 ) { + return "vector"; + } + if( getRank()==2 ) { + return "matrix"; + } plumed_merror("unknown type for value " + getName() ); return ""; } diff --git a/src/core/Value.h b/src/core/Value.h index 20cbfeeee6..07448e973b 100644 --- a/src/core/Value.h +++ b/src/core/Value.h @@ -254,7 +254,9 @@ inline void Value::applyPeriodicity(const unsigned& ival) { if(periodicity==periodic) { data[ival]=min+difference(min,data[ival]); - if(data[ival]0 ) return shape.size(); + if( shape.size()>0 ) { + return shape.size(); + } return data.size() - 1; } @@ -307,8 +313,12 @@ bool Value::hasDerivatives() const { inline void Value::resizeDerivatives(int n) { - if( shape.size()>0 ) return; - if(hasDeriv) data.resize(1+n); + if( shape.size()>0 ) { + return; + } + if(hasDeriv) { + data.resize(1+n); + } } inline @@ -325,22 +335,34 @@ void Value::setDerivative(unsigned i, double d) { inline void Value::clearInputForce() { - if( !hasForce ) return; - hasForce=false; std::fill(inputForce.begin(),inputForce.end(),0); + if( !hasForce ) { + return; + } + hasForce=false; + std::fill(inputForce.begin(),inputForce.end(),0); } inline void Value::clearInputForce( const std::vector& index ) { - if( !hasForce ) return; - hasForce=false; for(const auto & p : index) inputForce[p.index()]=0; + if( !hasForce ) { + return; + } + hasForce=false; + for(const auto & p : index) { + inputForce[p.index()]=0; + } } inline void Value::clearDerivatives( const bool force ) { - if( !force && (valtype==constant || valtype==average) ) return; + if( !force && (valtype==constant || valtype==average) ) { + return; + } value_set=false; - if( data.size()>1 ) std::fill(data.begin()+1, data.end(), 0); + if( data.size()>1 ) { + std::fill(data.begin()+1, data.end(), 0); + } } inline @@ -370,7 +392,9 @@ double Value::difference(double d1,double d2)const { // remember: pbc brings the difference in a range of -0.5:0.5 s=Tools::pbc(s); return s*max_minus_min; - } else plumed_merror("periodicity should be set to compute differences"); + } else { + plumed_merror("periodicity should be set to compute differences"); + } } inline @@ -401,13 +425,18 @@ const std::vector& Value::getShape() const { inline unsigned Value::getNumberOfValues() const { - unsigned size=1; for(unsigned i=0; i shape) { - if(shape.size()>4) plumed_error() << "Maximum shape size is 4"; + if(shape.size()>4) { + plumed_error() << "Maximum shape size is 4"; + } std::array shape_; unsigned j=0; for(auto i : shape) { diff --git a/src/crystdistrib/BopsShortcut.cpp b/src/crystdistrib/BopsShortcut.cpp index f06ecc1e4c..7b7dfe1c5b 100644 --- a/src/crystdistrib/BopsShortcut.cpp +++ b/src/crystdistrib/BopsShortcut.cpp @@ -64,39 +64,61 @@ void BopsShortcut::registerKeywords( Keywords& keys ) { keys.add("compulsory", "CUTOFF", "cutoff for the distance matrix"); // keys.add("compulsory","SWITCH","the switching function that acts on the distances between points)"); keys.setValueDescription("the values of the bops order parameters"); - keys.needsAction("DISTANCE_MATRIX"); keys.needsAction("QUATERNION_BOND_PRODUCT_MATRIX"); keys.needsAction("CUSTOM"); - keys.needsAction("ONES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("DISTANCE_MATRIX"); + keys.needsAction("QUATERNION_BOND_PRODUCT_MATRIX"); + keys.needsAction("CUSTOM"); + keys.needsAction("ONES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); } BopsShortcut::BopsShortcut(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Open a file and read in the kernels - double h_dops,h_bops; std::string kfunc, kfunc_dops,kfunc_bops,fname_dops,fname_bops; - parse("KERNELFILE_DOPS",fname_dops); parse("KERNELFILE_BOPS",fname_bops); IFile ifile_dops, ifile_bops; ifile_dops.open(fname_dops); ifile_bops.open(fname_bops); + double h_dops,h_bops; + std::string kfunc, kfunc_dops,kfunc_bops,fname_dops,fname_bops; + parse("KERNELFILE_DOPS",fname_dops); + parse("KERNELFILE_BOPS",fname_bops); + IFile ifile_dops, ifile_bops; + ifile_dops.open(fname_dops); + ifile_bops.open(fname_bops); for(unsigned k=0;; ++k) { - if( !ifile_dops.scanField("height",h_dops) || !ifile_bops.scanField("height",h_bops) ) break;//checks eof - std::string ktype_dops, ktype_bops; ifile_dops.scanField("kerneltype",ktype_dops); ifile_bops.scanField("kerneltype",ktype_bops); - if( ktype_dops!="gaussian" ) error("cannot process kernels of type " + ktype_dops );//straightup error - if( ktype_bops!="gaussian" ) error("cannot process kernels of type " + ktype_bops ); - - double mu_dops, mu_i, mu_j, mu_k; std::string hstr_dops, hstr_bops, smu_dops,smu_i, smu_j, smu_k, sigmastr,kappastr; + if( !ifile_dops.scanField("height",h_dops) || !ifile_bops.scanField("height",h_bops) ) { + break; //checks eof + } + std::string ktype_dops, ktype_bops; + ifile_dops.scanField("kerneltype",ktype_dops); + ifile_bops.scanField("kerneltype",ktype_bops); + if( ktype_dops!="gaussian" ) { + error("cannot process kernels of type " + ktype_dops ); //straightup error + } + if( ktype_bops!="gaussian" ) { + error("cannot process kernels of type " + ktype_bops ); + } + + double mu_dops, mu_i, mu_j, mu_k; + std::string hstr_dops, hstr_bops, smu_dops,smu_i, smu_j, smu_k, sigmastr,kappastr; Tools::convert( h_dops, hstr_dops ); Tools::convert( h_bops, hstr_bops ); - ifile_dops.scanField("mu",mu_dops); Tools::convert( mu_dops, smu_dops ); + ifile_dops.scanField("mu",mu_dops); + Tools::convert( mu_dops, smu_dops ); //ifile_bops.scanField("mu_w",mu_w); Tools::convert( mu_w, smu_w ); - ifile_bops.scanField("mu_i",mu_i); Tools::convert( mu_i, smu_i ); - ifile_bops.scanField("mu_j",mu_j); Tools::convert( mu_j, smu_j ); - ifile_bops.scanField("mu_k",mu_k); Tools::convert( mu_k, smu_k ); + ifile_bops.scanField("mu_i",mu_i); + Tools::convert( mu_i, smu_i ); + ifile_bops.scanField("mu_j",mu_j); + Tools::convert( mu_j, smu_j ); + ifile_bops.scanField("mu_k",mu_k); + Tools::convert( mu_k, smu_k ); double sigma,kappa; - ifile_dops.scanField("sigma",sigma); Tools::convert( sigma, sigmastr ); - ifile_bops.scanField("kappa",kappa); Tools::convert( kappa, kappastr ); + ifile_dops.scanField("sigma",sigma); + Tools::convert( sigma, sigmastr ); + ifile_bops.scanField("kappa",kappa); + Tools::convert( kappa, kappastr ); @@ -105,24 +127,35 @@ BopsShortcut::BopsShortcut(const ActionOptions&ao): kfunc_bops += "*exp(" + kappastr + "*(i*" + smu_i + "+j*" + smu_j + "+k*" + smu_k + "))"; kfunc_dops += "*exp(-(x-" + smu_dops +")^2/" + "(2*" + sigmastr +"*" +sigmastr + "))"; - if (k==0) kfunc = kfunc_dops + "*" + kfunc_bops; else kfunc+= "+" + kfunc_dops + "*" + kfunc_bops; + if (k==0) { + kfunc = kfunc_dops + "*" + kfunc_bops; + } else { + kfunc+= "+" + kfunc_dops + "*" + kfunc_bops; + } } std::string sp_str, specA, specB, grpinfo; double cutoff; - parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); parse("CUTOFF",cutoff); + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); + parse("CUTOFF",cutoff); if( sp_str.length()>0 ) { grpinfo="GROUP=" + sp_str; } else {//not sure how to use this - if( specA.length()==0 || specB.length()==0 ) error("no atoms were specified in input use either SPECIES or SPECIESA + SPECIESB"); + if( specA.length()==0 || specB.length()==0 ) { + error("no atoms were specified in input use either SPECIES or SPECIESA + SPECIESB"); + } grpinfo="GROUPA=" + specA + " GROUPB=" + specB; } - std::string cutstr; Tools::convert( cutoff, cutstr ); + std::string cutstr; + Tools::convert( cutoff, cutstr ); // Setup the contact matrix // std::string switchstr; parse("SWITCH",switchstr); readInputLine( getShortcutLabel() + "_cmat: DISTANCE_MATRIX " + grpinfo + " CUTOFF=" + cutstr + " COMPONENTS"); if( specA.length()==0 ) { - std::string quatstr; parse("QUATERNIONS",quatstr); + std::string quatstr; + parse("QUATERNIONS",quatstr); readInputLine( getShortcutLabel() + "_quatprod: QUATERNION_BOND_PRODUCT_MATRIX ARG=" + quatstr + ".*," + getShortcutLabel() + "_cmat.*" ); } else { plumed_error(); @@ -144,7 +177,8 @@ BopsShortcut::BopsShortcut(const ActionOptions&ao): // Find the number of ones we need to multiply by ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_cmat"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); // readInputLine( getShortcutLabel() + ": MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_kfunc," + getShortcutLabel() + "_ones"); diff --git a/src/crystdistrib/DopsShortcut.cpp b/src/crystdistrib/DopsShortcut.cpp index 7465b3b732..70c017de69 100644 --- a/src/crystdistrib/DopsShortcut.cpp +++ b/src/crystdistrib/DopsShortcut.cpp @@ -61,38 +61,67 @@ void DopsShortcut::registerKeywords( Keywords& keys ) { keys.add("compulsory","KERNELFILE","the file containing the list of kernel parameters. We expect h, mu and sigma parameters for a 1D Gaussian kernel of the form h*exp(-(x-mu)^2/2sigma^2)"); keys.add("compulsory","CUTOFF","6.25","to make the calculation faster we calculate a cutoff value on the distances. The input to this keyword determines x in this expreession max(mu + sqrt(2*x)/sigma)"); keys.setValueDescription("the values of the DOPS order parameters"); - keys.needsAction("DISTANCE_MATRIX"); keys.needsAction("CUSTOM"); keys.needsAction("ONES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("DISTANCE_MATRIX"); + keys.needsAction("CUSTOM"); + keys.needsAction("ONES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); } DopsShortcut::DopsShortcut(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Open a file and read in the kernels - double cutoff=0, h; std::string kfunc,fname; double dp2cutoff; parse("CUTOFF",dp2cutoff); - parse("KERNELFILE",fname); IFile ifile; ifile.open(fname); + double cutoff=0, h; + std::string kfunc,fname; + double dp2cutoff; + parse("CUTOFF",dp2cutoff); + parse("KERNELFILE",fname); + IFile ifile; + ifile.open(fname); for(unsigned k=0;; ++k) { - if( !ifile.scanField("height",h) ) break; - std::string ktype; ifile.scanField("kerneltype",ktype); if( ktype!="gaussian" ) error("cannot process kernels of type " + ktype ); - double mu, sigma; ifile.scanField("mu",mu); ifile.scanField("sigma",sigma); ifile.scanField(); - std::string hstr, mustr, sigmastr; Tools::convert( h, hstr ); - Tools::convert( 2*sigma*sigma, sigmastr ); Tools::convert( mu, mustr ); + if( !ifile.scanField("height",h) ) { + break; + } + std::string ktype; + ifile.scanField("kerneltype",ktype); + if( ktype!="gaussian" ) { + error("cannot process kernels of type " + ktype ); + } + double mu, sigma; + ifile.scanField("mu",mu); + ifile.scanField("sigma",sigma); + ifile.scanField(); + std::string hstr, mustr, sigmastr; + Tools::convert( h, hstr ); + Tools::convert( 2*sigma*sigma, sigmastr ); + Tools::convert( mu, mustr ); // Get a sensible value for the cutoff double support = sqrt(2.0*dp2cutoff)*(1.0/sigma); - if( mu+support>cutoff ) cutoff= mu + support; + if( mu+support>cutoff ) { + cutoff= mu + support; + } // And make the kernel - if( k==0 ) kfunc = hstr; else kfunc += "+" + hstr; + if( k==0 ) { + kfunc = hstr; + } else { + kfunc += "+" + hstr; + } kfunc += "*exp(-(x-" + mustr +")^2/" + sigmastr + ")"; } std::string sp_str, specA, specB, grpinfo; - parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); if( sp_str.length()>0 ) { grpinfo="GROUP=" + sp_str; } else { - if( specA.length()==0 || specB.length()==0 ) error("no atoms were specified in input use either SPECIES or SPECIESA + SPECIESB"); + if( specA.length()==0 || specB.length()==0 ) { + error("no atoms were specified in input use either SPECIES or SPECIESA + SPECIESB"); + } grpinfo="GROUPA=" + specA + " GROUPB=" + specB; } - std::string cutstr; Tools::convert( cutoff, cutstr ); + std::string cutstr; + Tools::convert( cutoff, cutstr ); // Setup the contact matrix readInputLine( getShortcutLabel() + "_cmat: DISTANCE_MATRIX " + grpinfo + " CUTOFF=" + cutstr); // And the kernels @@ -100,7 +129,8 @@ DopsShortcut::DopsShortcut(const ActionOptions&ao): // Find the number of ones we need to multiply by ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_cmat"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); // And the final order parameters readInputLine( getShortcutLabel() + ": MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_kval," + getShortcutLabel() + "_ones"); diff --git a/src/crystdistrib/Quaternion.cpp b/src/crystdistrib/Quaternion.cpp index 700b04d016..557a595117 100644 --- a/src/crystdistrib/Quaternion.cpp +++ b/src/crystdistrib/Quaternion.cpp @@ -119,7 +119,8 @@ typedef colvar::MultiColvarTemplate QuaternionMulti; PLUMED_REGISTER_ACTION(QuaternionMulti,"QUATERNION_VECTOR") void Quaternion::registerKeywords( Keywords& keys ) { - Colvar::registerKeywords( keys ); keys.setDisplayName("QUATERNION"); + Colvar::registerKeywords( keys ); + keys.setDisplayName("QUATERNION"); keys.add("atoms","ATOMS","the three atom that we are using to calculate the quaternion"); keys.addOutputComponent("w","default","the real component of quaternion"); keys.addOutputComponent("i","default","the i component of the quaternion"); @@ -133,12 +134,15 @@ Quaternion::Quaternion(const ActionOptions&ao): pbc(true), value(4), derivs(4), - virial(4) -{ - for(unsigned i=0; i<4; ++i) derivs[i].resize(3); + virial(4) { + for(unsigned i=0; i<4; ++i) { + derivs[i].resize(3); + } std::vector atoms; parseAtomList(-1,atoms,this); - if(atoms.size()!=3) error("Number of specified atoms should be 3"); + if(atoms.size()!=3) { + error("Number of specified atoms should be 3"); + } // please note, I do NO checking if these atoms are in the same molecule at all, so be careful in your input bool nopbc=!pbc; @@ -151,25 +155,35 @@ Quaternion::Quaternion(const ActionOptions&ao): void Quaternion::parseAtomList( const int& num, std::vector& t, ActionAtomistic* aa ) { aa->parseAtomList("ATOMS",num,t); - if( t.size()==3 ) aa->log.printf(" involving atoms %d %d %d\n",t[0].serial(),t[1].serial(),t[0].serial()); + if( t.size()==3 ) { + aa->log.printf(" involving atoms %d %d %d\n",t[0].serial(),t[1].serial(),t[0].serial()); + } } unsigned Quaternion::getModeAndSetupValues( ActionWithValue* av ) { // This sets up values that we can pass around in PLUMED - av->addComponentWithDerivatives("w"); av->componentIsNotPeriodic("w"); - av->addComponentWithDerivatives("i"); av->componentIsNotPeriodic("i"); - av->addComponentWithDerivatives("j"); av->componentIsNotPeriodic("j"); - av->addComponentWithDerivatives("k"); av->componentIsNotPeriodic("k"); + av->addComponentWithDerivatives("w"); + av->componentIsNotPeriodic("w"); + av->addComponentWithDerivatives("i"); + av->componentIsNotPeriodic("i"); + av->addComponentWithDerivatives("j"); + av->componentIsNotPeriodic("j"); + av->addComponentWithDerivatives("k"); + av->componentIsNotPeriodic("k"); return 0; } void Quaternion::calculate() { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } calculateCV( 0, masses, charges, getPositions(), value, derivs, virial, this ); for(unsigned j=0; j<4; ++j) { Value* valuej=getPntrToComponent(j); - for(unsigned i=0; i<3; ++i) setAtomsDerivatives(valuej,i,derivs[j][i] ); + for(unsigned i=0; i<3; ++i) { + setAtomsDerivatives(valuej,i,derivs[j][i] ); + } setBoxDerivatives(valuej,virial[j]); valuej->set(value[j]); } @@ -184,8 +198,10 @@ void Quaternion::calculateCV( const unsigned& mode, const std::vector& m Vector vec2_comp = delta( pos[0], pos[2] ); //components between atom 1 and 3 ////////x-vector calculations/////// - double magx = vec1_comp.modulo(); Vector xt = vec1_comp / magx; - std::vector dx(3); double magx3= magx*magx*magx; + double magx = vec1_comp.modulo(); + Vector xt = vec1_comp / magx; + std::vector dx(3); + double magx3= magx*magx*magx; //dx[i] - derivatives of atom i's coordinates dx[0](0,0) = ( -(vec1_comp[1]*vec1_comp[1]+vec1_comp[2]*vec1_comp[2])/magx3 ); //dx[0]/dx0 dx[0](0,1) = ( vec1_comp[0]*vec1_comp[1]/magx3 ); // dx[0]/dy0 @@ -211,13 +227,16 @@ void Quaternion::calculateCV( const unsigned& mode, const std::vector& m ////////y-vector calculations//////// //project vec2_comp on to vec1_comp //first do dot product of unormalized x and unormed y, divided by magnitude of x^2 - double dp = dotProduct( vec1_comp, vec2_comp ); double magx2=magx*magx; - std::vector fac_derivs(3); double magx4=magx2*magx2, fac = dp/magx2; //fac meaning factor on front + double dp = dotProduct( vec1_comp, vec2_comp ); + double magx2=magx*magx; + std::vector fac_derivs(3); + double magx4=magx2*magx2, fac = dp/magx2; //fac meaning factor on front fac_derivs[0] = (-vec2_comp - vec1_comp)/magx2 + 2*dp*vec1_comp / magx4; fac_derivs[1] = (vec2_comp)/(magx2) - 2*dp*vec1_comp / magx4; fac_derivs[2] = (vec1_comp)/(magx2); //atom 1, components x2,y2,z2 //now multiply fac by unormed x, and subtract it from unormed y, then normalize - Vector yt = vec2_comp - fac*vec1_comp; std::vector dy(3); + Vector yt = vec2_comp - fac*vec1_comp; + std::vector dy(3); dy[0](0,0) = -1 - fac_derivs[0][0]*vec1_comp[0] + fac; // dy[0]/dx0 dy[0](0,1) = -fac_derivs[0][1]*vec1_comp[0]; // dy[0]/dy0 dy[0](0,2) = -fac_derivs[0][2]*vec1_comp[0]; @@ -248,17 +267,27 @@ void Quaternion::calculateCV( const unsigned& mode, const std::vector& m dy[2](2,1) = -fac_derivs[2][1]*vec1_comp[2]; dy[2](2,2) = 1 - fac_derivs[2][2]*vec1_comp[2]; //now normalize, and we have our y vector - double magy = yt.modulo(); double imagy = 1/magy, magy3 = magy*magy*magy; - Tensor abc; for(unsigned i=0; i<3; ++i) abc.setRow(i, yt); - Tensor abc_diag; abc_diag.setRow(0, Vector(yt[0], 0, 0)); abc_diag.setRow(1, Vector(0, yt[1], 0)); abc_diag.setRow(2, Vector(0, 0, yt[2])); + double magy = yt.modulo(); + double imagy = 1/magy, magy3 = magy*magy*magy; + Tensor abc; + for(unsigned i=0; i<3; ++i) { + abc.setRow(i, yt); + } + Tensor abc_diag; + abc_diag.setRow(0, Vector(yt[0], 0, 0)); + abc_diag.setRow(1, Vector(0, yt[1], 0)); + abc_diag.setRow(2, Vector(0, 0, yt[2])); Tensor abc_prod = matmul(abc_diag, abc); - for(unsigned i=0; i<3; ++i) dy[i] = dy[i]/magy - matmul(abc_prod, dy[i])/magy3; + for(unsigned i=0; i<3; ++i) { + dy[i] = dy[i]/magy - matmul(abc_prod, dy[i])/magy3; + } //normalize now, derivatives are with respect to un-normalized y vector yt = yt / magy; ///////z-vector calculations///////// //comparatively simple - Vector zt = crossProduct(xt,yt); std::vector dz(3); + Vector zt = crossProduct(xt,yt); + std::vector dz(3); dz[0].setCol( 0, crossProduct( dx[0].getCol(0), yt ) + crossProduct( xt, dy[0].getCol(0) ) ); dz[0].setCol( 1, crossProduct( dx[0].getCol(1), yt ) + crossProduct( xt, dy[0].getCol(1) ) ); dz[0].setCol( 2, crossProduct( dx[0].getCol(2), yt ) + crossProduct( xt, dy[0].getCol(2) ) ); @@ -319,69 +348,106 @@ void Quaternion::calculateCV( const unsigned& mode, const std::vector& m std::vector dS(3); if (tr > 1.0E-8) { //to avoid numerical instability double S = 1/(sqrt(tr) * 2); // S=4*qw - for(unsigned i=0; i<3; ++i) dS[i] = (-2*S*S*S)*(tdx[i].getRow(0) + tdy[i].getRow(1) + tdz[i].getRow(2)); + for(unsigned i=0; i<3; ++i) { + dS[i] = (-2*S*S*S)*(tdx[i].getRow(0) + tdy[i].getRow(1) + tdz[i].getRow(2)); + } vals[0] = 0.25 / S; - for(unsigned i=0; i<3; ++i) derivs[0][i] =-0.25*dS[i]/(S*S); + for(unsigned i=0; i<3; ++i) { + derivs[0][i] =-0.25*dS[i]/(S*S); + } vals[1] = (z[1] - y[2]) * S; - for(unsigned i=0; i<3; ++i) derivs[1][i] = (S)*(tdz[i].getRow(1) - tdy[i].getRow(2)) + (z[1]-y[2])*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[1][i] = (S)*(tdz[i].getRow(1) - tdy[i].getRow(2)) + (z[1]-y[2])*dS[i]; + } vals[2] = (x[2] - z[0]) * S; - for(unsigned i=0; i<3; ++i) derivs[2][i] = (S)*(tdx[i].getRow(2) - tdz[i].getRow(0)) + (x[2]-z[0])*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[2][i] = (S)*(tdx[i].getRow(2) - tdz[i].getRow(0)) + (x[2]-z[0])*dS[i]; + } vals[3] = (y[0] - x[1]) * S; - for(unsigned i=0; i<3; ++i) derivs[3][i] = (S)*(tdy[i].getRow(0) - tdx[i].getRow(1)) + (y[0]-x[1])*dS[i]; - } - else if ((x[0] > y[1])&(x[0] > z[2])) { + for(unsigned i=0; i<3; ++i) { + derivs[3][i] = (S)*(tdy[i].getRow(0) - tdx[i].getRow(1)) + (y[0]-x[1])*dS[i]; + } + } else if ((x[0] > y[1])&(x[0] > z[2])) { float S = sqrt(1.0 + x[0] - y[1] - z[2]) * 2; // S=4*qx - for(unsigned i=0; i<3; ++i) dS[i] = (2/S)*(tdx[i].getRow(0) - tdy[i].getRow(1) - tdz[i].getRow(2)); + for(unsigned i=0; i<3; ++i) { + dS[i] = (2/S)*(tdx[i].getRow(0) - tdy[i].getRow(1) - tdz[i].getRow(2)); + } vals[0] = (z[1] - y[2]) / S; - for(unsigned i=0; i<3; ++i) derivs[0][i] = (1/S)*(tdz[i].getRow(1) - tdy[i].getRow(2)) - (vals[0]/S)*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[0][i] = (1/S)*(tdz[i].getRow(1) - tdy[i].getRow(2)) - (vals[0]/S)*dS[i]; + } vals[1] = 0.25 * S; - for(unsigned i=0; i<3; ++i) derivs[1][i] =0.25*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[1][i] =0.25*dS[i]; + } vals[2] = (x[1] + y[0]) / S; - for(unsigned i=0; i<3; ++i) derivs[2][i] = (1/S)*(tdx[i].getRow(1) + tdy[i].getRow(0)) - (vals[2]/S)*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[2][i] = (1/S)*(tdx[i].getRow(1) + tdy[i].getRow(0)) - (vals[2]/S)*dS[i]; + } vals[3] = (x[2] + z[0]) / S; - for(unsigned i=0; i<3; ++i) derivs[3][i] = (1/S)*(tdx[i].getRow(2) + tdz[i].getRow(0)) - (vals[3]/S)*dS[i]; - } - else if (y[1] > z[2]) { + for(unsigned i=0; i<3; ++i) { + derivs[3][i] = (1/S)*(tdx[i].getRow(2) + tdz[i].getRow(0)) - (vals[3]/S)*dS[i]; + } + } else if (y[1] > z[2]) { float S = sqrt(1.0 + y[1] - x[0] - z[2]) * 2; // S=4*qy - for(unsigned i=0; i<3; ++i) dS[i] = (2/S)*( -tdx[i].getRow(0) + tdy[i].getRow(1) - tdz[i].getRow(2)); + for(unsigned i=0; i<3; ++i) { + dS[i] = (2/S)*( -tdx[i].getRow(0) + tdy[i].getRow(1) - tdz[i].getRow(2)); + } vals[0] = (x[2] - z[0]) / S; - for(unsigned i=0; i<3; ++i) derivs[0][i] = (1/S)*(tdx[i].getRow(2) - tdz[i].getRow(0)) - (vals[0]/S)*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[0][i] = (1/S)*(tdx[i].getRow(2) - tdz[i].getRow(0)) - (vals[0]/S)*dS[i]; + } vals[1] = (x[1] + y[0]) / S; - for(unsigned i=0; i<3; ++i) derivs[1][i] = (1/S)*(tdx[i].getRow(1) + tdy[i].getRow(0)) - (vals[1]/S)*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[1][i] = (1/S)*(tdx[i].getRow(1) + tdy[i].getRow(0)) - (vals[1]/S)*dS[i]; + } vals[2] = 0.25 * S; - for(unsigned i=0; i<3; ++i) derivs[2][i] =0.25*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[2][i] =0.25*dS[i]; + } vals[3] = (y[2] + z[1]) / S; - for(unsigned i=0; i<3; ++i) derivs[3][i] = (1/S)*(tdy[i].getRow(2) + tdz[i].getRow(1)) - (vals[3]/S)*dS[i]; - } - else { + for(unsigned i=0; i<3; ++i) { + derivs[3][i] = (1/S)*(tdy[i].getRow(2) + tdz[i].getRow(1)) - (vals[3]/S)*dS[i]; + } + } else { float S = sqrt(1.0 + z[2] - x[0] - y[1]) * 2; // S=4*qz - for(unsigned i=0; i<3; ++i) dS[i] = (2/S)*(-tdx[i].getRow(0) - tdy[i].getRow(1) + tdz[i].getRow(2)); + for(unsigned i=0; i<3; ++i) { + dS[i] = (2/S)*(-tdx[i].getRow(0) - tdy[i].getRow(1) + tdz[i].getRow(2)); + } vals[0] = (y[0] - x[1]) / S; - for(unsigned i=0; i<3; ++i) derivs[0][i] = (1/S)*(tdy[i].getRow(0) - tdx[i].getRow(1)) - (vals[0]/S)*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[0][i] = (1/S)*(tdy[i].getRow(0) - tdx[i].getRow(1)) - (vals[0]/S)*dS[i]; + } vals[1] = (x[2] + z[0]) / S; - for(unsigned i=0; i<3; ++i) derivs[1][i] = (1/S)*(tdx[i].getRow(2) + tdz[i].getRow(0)) - (vals[1]/S)*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[1][i] = (1/S)*(tdx[i].getRow(2) + tdz[i].getRow(0)) - (vals[1]/S)*dS[i]; + } vals[2] = (y[2] + z[1]) / S; - for(unsigned i=0; i<3; ++i) derivs[2][i] = (1/S)*(tdy[i].getRow(2) + tdz[i].getRow(1)) - (vals[2]/S)*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[2][i] = (1/S)*(tdy[i].getRow(2) + tdz[i].getRow(1)) - (vals[2]/S)*dS[i]; + } vals[3] = 0.25 * S; - for(unsigned i=0; i<3; ++i) derivs[3][i] =0.25*dS[i]; + for(unsigned i=0; i<3; ++i) { + derivs[3][i] =0.25*dS[i]; + } } setBoxDerivativesNoPbc( pos, derivs, virial ); diff --git a/src/crystdistrib/QuaternionBondProductMatrix.cpp b/src/crystdistrib/QuaternionBondProductMatrix.cpp index fb92cb1969..c4b5739e5a 100644 --- a/src/crystdistrib/QuaternionBondProductMatrix.cpp +++ b/src/crystdistrib/QuaternionBondProductMatrix.cpp @@ -73,7 +73,8 @@ PLUMED_REGISTER_ACTION(QuaternionBondProductMatrix,"QUATERNION_BOND_PRODUCT_MATR void QuaternionBondProductMatrix::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords(keys); keys.use("ARG"); + ActionWithMatrix::registerKeywords(keys); + keys.use("ARG"); keys.addOutputComponent("w","default","the real component of quaternion"); keys.addOutputComponent("i","default","the i component of the quaternion"); keys.addOutputComponent("j","default","the j component of the quaternion"); @@ -82,39 +83,75 @@ void QuaternionBondProductMatrix::registerKeywords( Keywords& keys ) { QuaternionBondProductMatrix::QuaternionBondProductMatrix(const ActionOptions&ao): Action(ao), - ActionWithMatrix(ao) -{ - if( getNumberOfArguments()!=8 ) error("should be eight arguments to this action, 4 quaternion components and 4 matrices"); + ActionWithMatrix(ao) { + if( getNumberOfArguments()!=8 ) { + error("should be eight arguments to this action, 4 quaternion components and 4 matrices"); + } unsigned nquat = getPntrToArgument(0)->getNumberOfValues(); for(unsigned i=0; i<4; ++i) { - Value* myarg=getPntrToArgument(i); myarg->buildDataStore(); - if( myarg->getRank()!=1 ) error("first four arguments to this action should be vectors"); - if( (myarg->getPntrToAction())->getName()!="QUATERNION_VECTOR" ) error("first four arguments to this action should be quaternions"); - std::string mylab=getPntrToArgument(i)->getName(); std::size_t dot=mylab.find_first_of("."); - if( i==0 && mylab.substr(dot+1)!="w" ) error("quaternion arguments are in wrong order"); - if( i==1 && mylab.substr(dot+1)!="i" ) error("quaternion arguments are in wrong order"); - if( i==2 && mylab.substr(dot+1)!="j" ) error("quaternion arguments are in wrong order"); - if( i==3 && mylab.substr(dot+1)!="k" ) error("quaternion arguments are in wrong order"); + Value* myarg=getPntrToArgument(i); + myarg->buildDataStore(); + if( myarg->getRank()!=1 ) { + error("first four arguments to this action should be vectors"); + } + if( (myarg->getPntrToAction())->getName()!="QUATERNION_VECTOR" ) { + error("first four arguments to this action should be quaternions"); + } + std::string mylab=getPntrToArgument(i)->getName(); + std::size_t dot=mylab.find_first_of("."); + if( i==0 && mylab.substr(dot+1)!="w" ) { + error("quaternion arguments are in wrong order"); + } + if( i==1 && mylab.substr(dot+1)!="i" ) { + error("quaternion arguments are in wrong order"); + } + if( i==2 && mylab.substr(dot+1)!="j" ) { + error("quaternion arguments are in wrong order"); + } + if( i==3 && mylab.substr(dot+1)!="k" ) { + error("quaternion arguments are in wrong order"); + } } std::vector shape( getPntrToArgument(4)->getShape() ); for(unsigned i=4; i<8; ++i) { Value* myarg=getPntrToArgument(i); - if( myarg->getRank()!=2 ) error("second four arguments to this action should be matrices"); - if( myarg->getShape()[0]!=shape[0] || myarg->getShape()[1]!=shape[1] ) error("matrices should all have the same shape"); - if( myarg->getShape()[0]!=nquat ) error("number of rows in matrix should equal number of input quaternions"); - std::string mylab=getPntrToArgument(i)->getName(); std::size_t dot=mylab.find_first_of("."); - if( i==5 && mylab.substr(dot+1)!="x" ) error("quaternion arguments are in wrong order"); - if( i==6 && mylab.substr(dot+1)!="y" ) error("quaternion arguments are in wrong order"); - if( i==7 && mylab.substr(dot+1)!="z" ) error("quaternion arguments are in wrong order"); + if( myarg->getRank()!=2 ) { + error("second four arguments to this action should be matrices"); + } + if( myarg->getShape()[0]!=shape[0] || myarg->getShape()[1]!=shape[1] ) { + error("matrices should all have the same shape"); + } + if( myarg->getShape()[0]!=nquat ) { + error("number of rows in matrix should equal number of input quaternions"); + } + std::string mylab=getPntrToArgument(i)->getName(); + std::size_t dot=mylab.find_first_of("."); + if( i==5 && mylab.substr(dot+1)!="x" ) { + error("quaternion arguments are in wrong order"); + } + if( i==6 && mylab.substr(dot+1)!="y" ) { + error("quaternion arguments are in wrong order"); + } + if( i==7 && mylab.substr(dot+1)!="z" ) { + error("quaternion arguments are in wrong order"); + } + } + addComponent( "w", shape ); + componentIsNotPeriodic("w"); + addComponent( "i", shape ); + componentIsNotPeriodic("i"); + addComponent( "j", shape ); + componentIsNotPeriodic("j"); + addComponent( "k", shape ); + componentIsNotPeriodic("k"); + done_in_chain=true; + nderivatives = buildArgumentStore(0); + + std::string headstr=getFirstActionInChain()->getLabel(); + stored.resize( getNumberOfArguments() ); + for(unsigned i=0; iignoreStoredValue( headstr ); } - addComponent( "w", shape ); componentIsNotPeriodic("w"); - addComponent( "i", shape ); componentIsNotPeriodic("i"); - addComponent( "j", shape ); componentIsNotPeriodic("j"); - addComponent( "k", shape ); componentIsNotPeriodic("k"); - done_in_chain=true; nderivatives = buildArgumentStore(0); - - std::string headstr=getFirstActionInChain()->getLabel(); stored.resize( getNumberOfArguments() ); - for(unsigned i=0; iignoreStoredValue( headstr ); } unsigned QuaternionBondProductMatrix::getNumberOfDerivatives() { @@ -123,42 +160,58 @@ unsigned QuaternionBondProductMatrix::getNumberOfDerivatives() { unsigned QuaternionBondProductMatrix::getNumberOfColumns() const { const ActionWithMatrix* am=dynamic_cast( getPntrToArgument(4)->getPntrToAction() ); - plumed_assert( am ); return am->getNumberOfColumns(); + plumed_assert( am ); + return am->getNumberOfColumns(); } void QuaternionBondProductMatrix::setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const { unsigned start_n = getPntrToArgument(4)->getShape()[0], size_v = getPntrToArgument(4)->getShape()[1]; - if( indices.size()!=size_v+1 ) indices.resize( size_v+1 ); - for(unsigned i=0; i=getPntrToArgument(0)->getShape()[0] ) ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + if( index2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + } std::vector quat(4), bond(4), quatTemp(4); std::vector dqt(2); //dqt[0] -> derivs w.r.t quat [dwt/dw1 dwt/di1 dwt/dj1 dwt/dk1] //[dit/dw1 dit/di1 dit/dj1 dit/dk1] etc, and dqt[1] is w.r.t the vector-turned-quaternion called bond // Retrieve the quaternion - for(unsigned i=0; i<4; ++i) quat[i] = getArgumentElement( i, index1, myvals ); + for(unsigned i=0; i<4; ++i) { + quat[i] = getArgumentElement( i, index1, myvals ); + } // Retrieve the components of the matrix double weight = getElementOfMatrixArgument( 4, index1, ind2, myvals ); - for(unsigned i=1; i<4; ++i) bond[i] = getElementOfMatrixArgument( 4+i, index1, ind2, myvals ); + for(unsigned i=1; i<4; ++i) { + bond[i] = getElementOfMatrixArgument( 4+i, index1, ind2, myvals ); + } // calculate normalization factor bond[0]=0.0; double normFac = 1/sqrt(bond[1]*bond[1] + bond[2]*bond[2] + bond[3]*bond[3]); - if (bond[1] == 0.0 && bond[2]==0.0 && bond[3]==0) normFac=1; //just for the case where im comparing a quat to itself, itll be 0 at the end anyway + if (bond[1] == 0.0 && bond[2]==0.0 && bond[3]==0) { + normFac=1; //just for the case where im comparing a quat to itself, itll be 0 at the end anyway + } double normFac3 = normFac*normFac*normFac; //I hold off on normalizing because this can be done at the very end, and it makes the derivatives with respect to 'bond' more simple std::vector quat_conj(4); - quat_conj[0] = quat[0]; quat_conj[1] = -1*quat[1]; quat_conj[2] = -1*quat[2]; quat_conj[3] = -1*quat[3]; + quat_conj[0] = quat[0]; + quat_conj[1] = -1*quat[1]; + quat_conj[2] = -1*quat[2]; + quat_conj[3] = -1*quat[3]; //make a conjugate of q1 my own sanity @@ -171,7 +224,11 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co //real part of q1*q2 for(unsigned i=0; i<4; ++i) { - if( i>0 ) {pref=-1; conj=-1; pref2=-1;} + if( i>0 ) { + pref=-1; + conj=-1; + pref2=-1; + } quatTemp[0]+=pref*quat_conj[i]*bond[i]; dqt[0](0,i) = conj*pref*bond[i]; dqt[1](0,i) = pref2*quat_conj[i]; @@ -184,11 +241,19 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co pref2=1; for (unsigned i=0; i<4; i++) { - if(i==3) pref=-1; - else pref=1; - if(i==2) pref2=-1; - else pref2=1; - if (i>0) conj=-1; + if(i==3) { + pref=-1; + } else { + pref=1; + } + if(i==2) { + pref2=-1; + } else { + pref2=1; + } + if (i>0) { + conj=-1; + } quatTemp[1]+=pref*quat_conj[i]*bond[(5-i)%4]; dqt[0](1,i) =conj*pref*bond[(5-i)%4]; @@ -203,11 +268,19 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co conj=1; for (unsigned i=0; i<4; i++) { - if(i==1) pref=-1; - else pref=1; - if (i==3) pref2=-1; - else pref2=1; - if (i>0) conj=-1; + if(i==1) { + pref=-1; + } else { + pref=1; + } + if (i==3) { + pref2=-1; + } else { + pref2=1; + } + if (i>0) { + conj=-1; + } quatTemp[2]+=pref*quat_conj[i]*bond[(i+2)%4]; dqt[0](2,i)=conj*pref*bond[(i+2)%4]; @@ -222,11 +295,19 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co conj=1; for (unsigned i=0; i<4; i++) { - if(i==2) pref=-1; - else pref=1; - if(i==1) pref2=-1; - else pref2=1; - if(i>0) conj=-1; + if(i==2) { + pref=-1; + } else { + pref=1; + } + if(i==1) { + pref2=-1; + } else { + pref2=1; + } + if(i>0) { + conj=-1; + } quatTemp[3]+=pref*quat_conj[i]*bond[(3-i)]; dqt[0](3,i)=conj*pref*bond[3-i]; dqt[1](3,i)= pref2*quat_conj[3-i]; @@ -242,10 +323,15 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co pref=1; pref2=1; for(unsigned i=0; i<4; ++i) { - if( i>0 ) {pref=-1; pref2=-1;} + if( i>0 ) { + pref=-1; + pref2=-1; + } myvals.addValue( getConstPntrToComponent(0)->getPositionInStream(), normFac*pref*quatTemp[i]*quat[i] ); wf+=normFac*pref*quatTemp[i]*quat[i]; - if( doNotCalculateDerivatives() ) continue ; + if( doNotCalculateDerivatives() ) { + continue ; + } tempDot=(dotProduct(Vector4d(quat[0],-quat[1],-quat[2],-quat[3]), dqt[0].getCol(i)) + pref2*quatTemp[i])*normFac; addDerivativeOnVectorArgument( stored[i], 0, i, index1, tempDot, myvals); } @@ -253,8 +339,11 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co //addDerivativeOnMatrixArgument( false, 0, 4, index1, ind2, 0.0, myvals ); for(unsigned i=0; i<4; ++i) { tempDot=dotProduct(Vector4d(quat[0],-quat[1],-quat[2],-quat[3]), dqt[1].getCol(i))*normFac; - if (i!=0 )addDerivativeOnMatrixArgument( stored[4+i], 0, 4+i, index1, ind2, tempDot, myvals ); - else addDerivativeOnMatrixArgument( stored[4+i], 0, 4+i, index1, ind2, 0.0, myvals ); + if (i!=0 ) { + addDerivativeOnMatrixArgument( stored[4+i], 0, 4+i, index1, ind2, tempDot, myvals ); + } else { + addDerivativeOnMatrixArgument( stored[4+i], 0, 4+i, index1, ind2, 0.0, myvals ); + } } // for (unsigned i=0; i<4; ++i) { //myvals.addValue( getConstPntrToComponent(0)->getPositionInStream(), 0.0 ); @@ -268,13 +357,21 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co pref=1; pref2=1; for (unsigned i=0; i<4; i++) { - if(i==3) pref=-1; - else pref=1; + if(i==3) { + pref=-1; + } else { + pref=1; + } myvals.addValue( getConstPntrToComponent(1)->getPositionInStream(), normFac*pref*quatTemp[i]*quat[(5-i)%4]); xf+=normFac*pref*quatTemp[i]*quat[(5-i)%4]; - if(i==2) pref2=-1; - else pref2=1; - if( doNotCalculateDerivatives() ) continue ; + if(i==2) { + pref2=-1; + } else { + pref2=1; + } + if( doNotCalculateDerivatives() ) { + continue ; + } tempDot=(dotProduct(Vector4d(quat[1],quat[0],quat[3],-quat[2]), dqt[0].getCol(i)) + pref2*quatTemp[(5-i)%4])*normFac; addDerivativeOnVectorArgument( stored[i], 1, i, index1, tempDot, myvals); } @@ -282,8 +379,11 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co for(unsigned i=0; i<4; ++i) { tempDot=dotProduct(Vector4d(quat[1],quat[0],quat[3],-quat[2]), dqt[1].getCol(i))*normFac; - if (i!=0) addDerivativeOnMatrixArgument( stored[4+i], 1, 4+i, index1, ind2, tempDot+(-bond[i]*normFac*normFac*xf), myvals ); - else addDerivativeOnMatrixArgument( stored[4+i], 1, 4+i, index1, ind2, 0.0, myvals ); + if (i!=0) { + addDerivativeOnMatrixArgument( stored[4+i], 1, 4+i, index1, ind2, tempDot+(-bond[i]*normFac*normFac*xf), myvals ); + } else { + addDerivativeOnMatrixArgument( stored[4+i], 1, 4+i, index1, ind2, 0.0, myvals ); + } } @@ -292,14 +392,22 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co pref=1; pref2=1; for (unsigned i=0; i<4; i++) { - if(i==1) pref=-1; - else pref=1; - if (i==3) pref2=-1; - else pref2=1; + if(i==1) { + pref=-1; + } else { + pref=1; + } + if (i==3) { + pref2=-1; + } else { + pref2=1; + } myvals.addValue( getConstPntrToComponent(2)->getPositionInStream(), normFac*pref*quatTemp[i]*quat[(i+2)%4]); yf+=normFac*pref*quatTemp[i]*quat[(i+2)%4]; - if( doNotCalculateDerivatives() ) continue ; + if( doNotCalculateDerivatives() ) { + continue ; + } tempDot=(dotProduct(Vector4d(quat[2],-quat[3],quat[0],quat[1]), dqt[0].getCol(i)) + pref2*quatTemp[(i+2)%4])*normFac; addDerivativeOnVectorArgument( stored[i], 2, i, index1, tempDot, myvals); } @@ -307,8 +415,11 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co for(unsigned i=0; i<4; ++i) { tempDot=dotProduct(Vector4d(quat[2],-quat[3],quat[0],quat[1]), dqt[1].getCol(i))*normFac; - if (i!=0) addDerivativeOnMatrixArgument( stored[4+i], 2, 4+i, index1, ind2, tempDot+(-bond[i]*normFac*normFac*yf), myvals ); - else addDerivativeOnMatrixArgument( stored[4+i], 2, 4+i, index1, ind2, 0.0, myvals ); + if (i!=0) { + addDerivativeOnMatrixArgument( stored[4+i], 2, 4+i, index1, ind2, tempDot+(-bond[i]*normFac*normFac*yf), myvals ); + } else { + addDerivativeOnMatrixArgument( stored[4+i], 2, 4+i, index1, ind2, 0.0, myvals ); + } } @@ -317,14 +428,22 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co pref=1; pref2=1; for (unsigned i=0; i<4; i++) { - if(i==2) pref=-1; - else pref=1; - if(i==1) pref2=-1; - else pref2=1; + if(i==2) { + pref=-1; + } else { + pref=1; + } + if(i==1) { + pref2=-1; + } else { + pref2=1; + } myvals.addValue( getConstPntrToComponent(3)->getPositionInStream(), normFac*pref*quatTemp[i]*quat[(3-i)]); zf+=normFac*pref*quatTemp[i]*quat[(3-i)]; - if( doNotCalculateDerivatives() ) continue ; + if( doNotCalculateDerivatives() ) { + continue ; + } tempDot=(dotProduct(Vector4d(quat[3],quat[2],-quat[1],quat[0]), dqt[0].getCol(i)) + pref2*quatTemp[(3-i)])*normFac; addDerivativeOnVectorArgument( stored[i], 3, i, index1, tempDot, myvals); } @@ -332,48 +451,72 @@ void QuaternionBondProductMatrix::performTask( const std::string& controller, co for(unsigned i=0; i<4; ++i) { tempDot=dotProduct(Vector4d(quat[3],quat[2],-quat[1],quat[0]), dqt[1].getCol(i))*normFac; - if (i!=0) addDerivativeOnMatrixArgument( stored[4+i], 3, 4+i, index1, ind2, tempDot+(-bond[i]*normFac*normFac*zf), myvals ); - else addDerivativeOnMatrixArgument( stored[4+i], 3, 4+i, index1, ind2, 0.0, myvals ); + if (i!=0) { + addDerivativeOnMatrixArgument( stored[4+i], 3, 4+i, index1, ind2, tempDot+(-bond[i]*normFac*normFac*zf), myvals ); + } else { + addDerivativeOnMatrixArgument( stored[4+i], 3, 4+i, index1, ind2, 0.0, myvals ); + } } - if( doNotCalculateDerivatives() ) return ; + if( doNotCalculateDerivatives() ) { + return ; + } for(unsigned outcomp=0; outcomp<4; ++outcomp) { unsigned ostrn = getConstPntrToComponent(outcomp)->getPositionInStream(); for(unsigned i=4; i<8; ++i) { bool found=false; for(unsigned j=4; jgetPositionInStream(); for(unsigned k=0; k & indices, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() || !matrixChainContinues() ) return ; + if( doNotCalculateDerivatives() || !matrixChainContinues() ) { + return ; + } for(unsigned j=0; jgetPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); - std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); unsigned ntwo_atoms = myvals.getSplitIndex(); + std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); + unsigned ntwo_atoms = myvals.getSplitIndex(); // Quaternion - for(unsigned k=0; k<4; ++k) { matrix_indices[nmat_ind] = arg_deriv_starts[k] + ival; nmat_ind++; } + for(unsigned k=0; k<4; ++k) { + matrix_indices[nmat_ind] = arg_deriv_starts[k] + ival; + nmat_ind++; + } // Loop over row of matrix for(unsigned n=4; n<8; ++n) { bool found=false; for(unsigned k=4; kgetPositionInMatrixStash(); std::vector& imat_indices( myvals.getMatrixRowDerivativeIndices( istrn ) ); - for(unsigned k=0; kgetPositionInMatrixStash() ); } myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind ); diff --git a/src/crystdistrib/QuaternionProductMatrix.cpp b/src/crystdistrib/QuaternionProductMatrix.cpp index 53213f7ab0..024b2afb91 100644 --- a/src/crystdistrib/QuaternionProductMatrix.cpp +++ b/src/crystdistrib/QuaternionProductMatrix.cpp @@ -41,7 +41,9 @@ class QuaternionProductMatrix : public ActionWithMatrix { static void registerKeywords( Keywords& keys ); explicit QuaternionProductMatrix(const ActionOptions&); unsigned getNumberOfDerivatives(); - unsigned getNumberOfColumns() const override { return getConstPntrToComponent(0)->getShape()[1]; } + unsigned getNumberOfColumns() const override { + return getConstPntrToComponent(0)->getShape()[1]; + } void setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const ; void performTask( const std::string& controller, const unsigned& index1, const unsigned& index2, MultiValue& myvals ) const override; void runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const override ; @@ -50,7 +52,8 @@ class QuaternionProductMatrix : public ActionWithMatrix { PLUMED_REGISTER_ACTION(QuaternionProductMatrix,"QUATERNION_PRODUCT_MATRIX") void QuaternionProductMatrix::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords(keys); keys.use("ARG"); + ActionWithMatrix::registerKeywords(keys); + keys.use("ARG"); keys.addOutputComponent("w","default","the real component of quaternion"); keys.addOutputComponent("i","default","the i component of the quaternion"); keys.addOutputComponent("j","default","the j component of the quaternion"); @@ -59,25 +62,48 @@ void QuaternionProductMatrix::registerKeywords( Keywords& keys ) { QuaternionProductMatrix::QuaternionProductMatrix(const ActionOptions&ao): Action(ao), - ActionWithMatrix(ao) -{ - if( getNumberOfArguments()!=8 ) error("should be eight arguments to this action. Four quaternions for each set of atoms. You can repeat actions"); + ActionWithMatrix(ao) { + if( getNumberOfArguments()!=8 ) { + error("should be eight arguments to this action. Four quaternions for each set of atoms. You can repeat actions"); + } unsigned nquat = getPntrToArgument(0)->getNumberOfValues(); for(unsigned i=0; i<8; ++i) { - Value* myarg=getPntrToArgument(i); if( i==4 ) nquat = getPntrToArgument(i)->getNumberOfValues(); - if( myarg->getRank()!=1 ) error("all arguments to this action should be vectors"); - if( (myarg->getPntrToAction())->getName()!="QUATERNION_VECTOR" ) error("all arguments to this action should be quaternions"); - std::string mylab=getPntrToArgument(i)->getName(); std::size_t dot=mylab.find_first_of("."); - if( (i==0 || i==4) && mylab.substr(dot+1)!="w" ) error("quaternion arguments are in wrong order"); - if( (i==1 || i==5) && mylab.substr(dot+1)!="i" ) error("quaternion arguments are in wrong order"); - if( (i==2 || i==6) && mylab.substr(dot+1)!="j" ) error("quaternion arguments are in wrong order"); - if( (i==3 || i==7) && mylab.substr(dot+1)!="k" ) error("quaternion arguments are in wrong order"); + Value* myarg=getPntrToArgument(i); + if( i==4 ) { + nquat = getPntrToArgument(i)->getNumberOfValues(); + } + if( myarg->getRank()!=1 ) { + error("all arguments to this action should be vectors"); + } + if( (myarg->getPntrToAction())->getName()!="QUATERNION_VECTOR" ) { + error("all arguments to this action should be quaternions"); + } + std::string mylab=getPntrToArgument(i)->getName(); + std::size_t dot=mylab.find_first_of("."); + if( (i==0 || i==4) && mylab.substr(dot+1)!="w" ) { + error("quaternion arguments are in wrong order"); + } + if( (i==1 || i==5) && mylab.substr(dot+1)!="i" ) { + error("quaternion arguments are in wrong order"); + } + if( (i==2 || i==6) && mylab.substr(dot+1)!="j" ) { + error("quaternion arguments are in wrong order"); + } + if( (i==3 || i==7) && mylab.substr(dot+1)!="k" ) { + error("quaternion arguments are in wrong order"); + } } - std::vector shape(2); shape[0]=getPntrToArgument(0)->getShape()[0]; shape[1]=getPntrToArgument(4)->getShape()[0]; - addComponent( "w", shape ); componentIsNotPeriodic("w"); - addComponent( "i", shape ); componentIsNotPeriodic("i"); - addComponent( "j", shape ); componentIsNotPeriodic("j"); - addComponent( "k", shape ); componentIsNotPeriodic("k"); + std::vector shape(2); + shape[0]=getPntrToArgument(0)->getShape()[0]; + shape[1]=getPntrToArgument(4)->getShape()[0]; + addComponent( "w", shape ); + componentIsNotPeriodic("w"); + addComponent( "i", shape ); + componentIsNotPeriodic("i"); + addComponent( "j", shape ); + componentIsNotPeriodic("j"); + addComponent( "k", shape ); + componentIsNotPeriodic("k"); nderivatives = buildArgumentStore(0); } @@ -87,21 +113,31 @@ unsigned QuaternionProductMatrix::getNumberOfDerivatives() { void QuaternionProductMatrix::setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const { unsigned start_n = getPntrToArgument(0)->getShape()[0], size_v = getPntrToArgument(4)->getShape()[0]; - if( indices.size()!=size_v+1 ) indices.resize( size_v+1 ); - for(unsigned i=0; i=getPntrToArgument(0)->getShape()[0] ) ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + if( index2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + } std::vector quat1(4), quat2(4); // Retrieve the first quaternion - for(unsigned i=0; i<4; ++i) quat1[i] = getArgumentElement( i, index1, myvals ); + for(unsigned i=0; i<4; ++i) { + quat1[i] = getArgumentElement( i, index1, myvals ); + } // Retrieve the second quaternion - for(unsigned i=0; i<4; ++i) quat2[i] = getArgumentElement( 4+i, ind2, myvals ); + for(unsigned i=0; i<4; ++i) { + quat2[i] = getArgumentElement( 4+i, ind2, myvals ); + } //make q1 the conjugate quat1[1] *= -1; @@ -114,10 +150,17 @@ void QuaternionProductMatrix::performTask( const std::string& controller, const double conj=1; //real part of q1*q2 for(unsigned i=0; i<4; ++i) { - if( i>0 ) {pref=-1; pref2=-1;} + if( i>0 ) { + pref=-1; + pref2=-1; + } myvals.addValue( getConstPntrToComponent(0)->getPositionInStream(), pref*quat1[i]*quat2[i] ); - if( doNotCalculateDerivatives() ) continue ; - if (i>0) conj=-1; + if( doNotCalculateDerivatives() ) { + continue ; + } + if (i>0) { + conj=-1; + } addDerivativeOnVectorArgument( false, 0, i, index1, conj*pref*quat2[i], myvals ); addDerivativeOnVectorArgument( false, 0, 4+i, ind2, pref2*quat1[i], myvals ); } @@ -126,13 +169,23 @@ void QuaternionProductMatrix::performTask( const std::string& controller, const conj=1; pref2=1; for (unsigned i=0; i<4; i++) { - if(i==3) pref=-1; - else pref=1; - if(i==2) pref2=-1; - else pref2=1; + if(i==3) { + pref=-1; + } else { + pref=1; + } + if(i==2) { + pref2=-1; + } else { + pref2=1; + } myvals.addValue( getConstPntrToComponent(1)->getPositionInStream(), pref*quat1[i]*quat2[(5-i)%4]); - if( doNotCalculateDerivatives() ) continue ; - if (i>0) conj=-1; + if( doNotCalculateDerivatives() ) { + continue ; + } + if (i>0) { + conj=-1; + } addDerivativeOnVectorArgument( false, 1, i, index1, conj*pref*quat2[(5-i)%4], myvals ); addDerivativeOnVectorArgument( false, 1, 4+i, ind2, pref2*quat1[(5-i)%4], myvals ); } @@ -142,13 +195,23 @@ void QuaternionProductMatrix::performTask( const std::string& controller, const conj=1; pref2=1; for (unsigned i=0; i<4; i++) { - if(i==1) pref=-1; - else pref=1; - if (i==3) pref2=-1; - else pref2=1; + if(i==1) { + pref=-1; + } else { + pref=1; + } + if (i==3) { + pref2=-1; + } else { + pref2=1; + } myvals.addValue( getConstPntrToComponent(2)->getPositionInStream(), pref*quat1[i]*quat2[(i+2)%4]); - if( doNotCalculateDerivatives() ) continue ; - if (i>0) conj=-1; + if( doNotCalculateDerivatives() ) { + continue ; + } + if (i>0) { + conj=-1; + } addDerivativeOnVectorArgument( false, 2, i, index1, conj*pref*quat2[(i+2)%4], myvals ); addDerivativeOnVectorArgument( false, 2, 4+i, ind2, pref2*quat1[(i+2)%4], myvals ); } @@ -158,13 +221,23 @@ void QuaternionProductMatrix::performTask( const std::string& controller, const conj=1; pref2=1; for (unsigned i=0; i<4; i++) { - if(i==2) pref=-1; - else pref=1; - if(i==1) pref2=-1; - else pref2=1; + if(i==2) { + pref=-1; + } else { + pref=1; + } + if(i==1) { + pref2=-1; + } else { + pref2=1; + } myvals.addValue( getConstPntrToComponent(3)->getPositionInStream(), pref*quat1[i]*quat2[(3-i)]); - if( doNotCalculateDerivatives() ) continue ; - if (i>0) conj=-1; + if( doNotCalculateDerivatives() ) { + continue ; + } + if (i>0) { + conj=-1; + } addDerivativeOnVectorArgument( false, 3, i, index1, conj*pref*quat2[3-i], myvals ); addDerivativeOnVectorArgument( false, 3, 4+i, ind2, pref2*quat1[3-i], myvals ); @@ -174,19 +247,34 @@ void QuaternionProductMatrix::performTask( const std::string& controller, const } void QuaternionProductMatrix::runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() || !matrixChainContinues() ) return ; + if( doNotCalculateDerivatives() || !matrixChainContinues() ) { + return ; + } for(unsigned j=0; jgetPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); - std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); unsigned ntwo_atoms = myvals.getSplitIndex(); + std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); + unsigned ntwo_atoms = myvals.getSplitIndex(); // Quaternion for first molecule - unsigned base = 0; for(unsigned k=0; k<4; ++k) { matrix_indices[nmat_ind] = base + ival; base += getPntrToArgument(k)->getShape()[0]; nmat_ind++; } + unsigned base = 0; + for(unsigned k=0; k<4; ++k) { + matrix_indices[nmat_ind] = base + ival; + base += getPntrToArgument(k)->getShape()[0]; + nmat_ind++; + } // Loop over row of matrix for(unsigned i=1; i=getPntrToArgument(0)->getShape()[0] ) ind2 = indices[i] - getPntrToArgument(0)->getShape()[0]; + unsigned ind2 = indices[i]; + if( ind2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = indices[i] - getPntrToArgument(0)->getShape()[0]; + } base = 4*getPntrToArgument(0)->getShape()[0]; // Quaternion of second molecule - for(unsigned k=0; k<4; ++k) { matrix_indices[nmat_ind] = base + ind2; base += getPntrToArgument(4+k)->getShape()[0]; nmat_ind++; } + for(unsigned k=0; k<4; ++k) { + matrix_indices[nmat_ind] = base + ind2; + base += getPntrToArgument(4+k)->getShape()[0]; + nmat_ind++; + } } myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind ); } diff --git a/src/crystdistrib/RopsShortcut.cpp b/src/crystdistrib/RopsShortcut.cpp index d647de6664..22aa869ad3 100644 --- a/src/crystdistrib/RopsShortcut.cpp +++ b/src/crystdistrib/RopsShortcut.cpp @@ -64,39 +64,62 @@ void RopsShortcut::registerKeywords( Keywords& keys ) { keys.add("compulsory", "CUTOFF", "cutoff for the distance matrix"); // keys.add("compulsory","SWITCH","the switching function that acts on the distances between points)"); keys.setValueDescription("the values of the ROPS order parameters"); - keys.needsAction("DISTANCE_MATRIX"); keys.needsAction("QUATERNION_PRODUCT_MATRIX"); - keys.needsAction("ONES"); keys.needsAction("CUSTOM"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("DISTANCE_MATRIX"); + keys.needsAction("QUATERNION_PRODUCT_MATRIX"); + keys.needsAction("ONES"); + keys.needsAction("CUSTOM"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); } RopsShortcut::RopsShortcut(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Open a file and read in the kernels - double h_dops,h_rops; std::string kfunc, kfunc_dops,kfunc_rops,fname_dops,fname_rops; - parse("KERNELFILE_DOPS",fname_dops); parse("KERNELFILE_ROPS",fname_rops); IFile ifile_dops, ifile_rops; ifile_dops.open(fname_dops); ifile_rops.open(fname_rops); + double h_dops,h_rops; + std::string kfunc, kfunc_dops,kfunc_rops,fname_dops,fname_rops; + parse("KERNELFILE_DOPS",fname_dops); + parse("KERNELFILE_ROPS",fname_rops); + IFile ifile_dops, ifile_rops; + ifile_dops.open(fname_dops); + ifile_rops.open(fname_rops); for(unsigned k=0;; ++k) { - if( !ifile_dops.scanField("height",h_dops) || !ifile_rops.scanField("height",h_rops) ) break;//checks eof - std::string ktype_dops, ktype_rops; ifile_dops.scanField("kerneltype",ktype_dops); ifile_rops.scanField("kerneltype",ktype_rops); - if( ktype_dops!="gaussian" ) error("cannot process kernels of type " + ktype_dops );//straightup error - if( ktype_rops!="gaussian" ) error("cannot process kernels of type " + ktype_rops ); - - double mu_dops,mu_w, mu_i, mu_j, mu_k; std::string hstr_dops, hstr_rops, smu_dops,smu_w, smu_i, smu_j, smu_k, sigmastr,kappastr; + if( !ifile_dops.scanField("height",h_dops) || !ifile_rops.scanField("height",h_rops) ) { + break; //checks eof + } + std::string ktype_dops, ktype_rops; + ifile_dops.scanField("kerneltype",ktype_dops); + ifile_rops.scanField("kerneltype",ktype_rops); + if( ktype_dops!="gaussian" ) { + error("cannot process kernels of type " + ktype_dops ); //straightup error + } + if( ktype_rops!="gaussian" ) { + error("cannot process kernels of type " + ktype_rops ); + } + + double mu_dops,mu_w, mu_i, mu_j, mu_k; + std::string hstr_dops, hstr_rops, smu_dops,smu_w, smu_i, smu_j, smu_k, sigmastr,kappastr; Tools::convert( h_dops, hstr_dops ); Tools::convert( h_rops, hstr_rops ); - ifile_dops.scanField("mu",mu_dops); Tools::convert( mu_dops, smu_dops ); - ifile_rops.scanField("mu_w",mu_w); Tools::convert( mu_w, smu_w ); - ifile_rops.scanField("mu_i",mu_i); Tools::convert( mu_i, smu_i ); - ifile_rops.scanField("mu_j",mu_j); Tools::convert( mu_j, smu_j ); - ifile_rops.scanField("mu_k",mu_k); Tools::convert( mu_k, smu_k ); + ifile_dops.scanField("mu",mu_dops); + Tools::convert( mu_dops, smu_dops ); + ifile_rops.scanField("mu_w",mu_w); + Tools::convert( mu_w, smu_w ); + ifile_rops.scanField("mu_i",mu_i); + Tools::convert( mu_i, smu_i ); + ifile_rops.scanField("mu_j",mu_j); + Tools::convert( mu_j, smu_j ); + ifile_rops.scanField("mu_k",mu_k); + Tools::convert( mu_k, smu_k ); double sigma,kappa; - ifile_dops.scanField("sigma",sigma); Tools::convert( sigma, sigmastr ); - ifile_rops.scanField("kappa",kappa); Tools::convert( kappa, kappastr ); + ifile_dops.scanField("sigma",sigma); + Tools::convert( sigma, sigmastr ); + ifile_rops.scanField("kappa",kappa); + Tools::convert( kappa, kappastr ); @@ -105,24 +128,35 @@ RopsShortcut::RopsShortcut(const ActionOptions&ao): kfunc_rops += "*exp(" + kappastr + "*(w*" + smu_w + "+i*" + smu_i + "+j*" + smu_j + "+k*" + smu_k + ")^2)"; kfunc_dops += "*exp(-(x-" + smu_dops +")^2/" + "(2*" + sigmastr +"*" +sigmastr + "))"; - if (k==0) kfunc = kfunc_dops + "*" + kfunc_rops; else kfunc+= "+" + kfunc_dops + "*" + kfunc_rops; + if (k==0) { + kfunc = kfunc_dops + "*" + kfunc_rops; + } else { + kfunc+= "+" + kfunc_dops + "*" + kfunc_rops; + } } std::string sp_str, specA, specB, grpinfo; double cutoff; - parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); parse("CUTOFF",cutoff); + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); + parse("CUTOFF",cutoff); if( sp_str.length()>0 ) { grpinfo="GROUP=" + sp_str; } else {//not sure how to use this - if( specA.length()==0 || specB.length()==0 ) error("no atoms were specified in input use either SPECIES or SPECIESA + SPECIESB"); + if( specA.length()==0 || specB.length()==0 ) { + error("no atoms were specified in input use either SPECIES or SPECIESA + SPECIESB"); + } grpinfo="GROUPA=" + specA + " GROUPB=" + specB; } - std::string cutstr; Tools::convert( cutoff, cutstr ); + std::string cutstr; + Tools::convert( cutoff, cutstr ); // Setup the contact matrix // std::string switchstr; parse("SWITCH",switchstr); readInputLine( getShortcutLabel() + "_cmat: DISTANCE_MATRIX " + grpinfo + " CUTOFF=" + cutstr); if( specA.length()==0 ) { - std::string quatstr; parse("QUATERNIONS",quatstr); + std::string quatstr; + parse("QUATERNIONS",quatstr); readInputLine( getShortcutLabel() + "_quatprod: QUATERNION_PRODUCT_MATRIX ARG=" + quatstr + ".*," + quatstr + ".*" ); } else { plumed_error(); @@ -134,7 +168,8 @@ RopsShortcut::RopsShortcut(const ActionOptions&ao): // Find the number of ones we need to multiply by ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_cmat"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); // readInputLine( getShortcutLabel() + ": MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_kfunc," + getShortcutLabel() + "_ones"); diff --git a/src/dimred/ArrangePoints.cpp b/src/dimred/ArrangePoints.cpp index 357eefe4d0..30910e3c14 100644 --- a/src/dimred/ArrangePoints.cpp +++ b/src/dimred/ArrangePoints.cpp @@ -59,7 +59,9 @@ class ArrangePoints : public: static void registerKeywords( Keywords& keys ); ArrangePoints( const ActionOptions& ); - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } void prepare() override ; void calculate() override ; virtual void optimize( std::vector& pos ); @@ -69,8 +71,10 @@ class ArrangePoints : PLUMED_REGISTER_ACTION(ArrangePoints,"ARRANGE_POINTS") void ArrangePoints::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.use("ARG"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.use("ARG"); keys.add("numbered","TARGET","the matrix of target quantities that you would like to match"); keys.add("numbered","FUNC","a function that is applied on the distances between the points in the low dimensional space"); keys.add("numbered","WEIGHTS","the matrix with the weights of the target quantities"); @@ -92,96 +96,153 @@ ArrangePoints::ArrangePoints( const ActionOptions& ao ) : ActionWithValue(ao), ActionWithArguments(ao), current_index(0), - dist_target(-1) -{ + dist_target(-1) { dimout = getNumberOfArguments(); - std::vector shape(1); shape[0]=getPntrToArgument(0)->getNumberOfValues(); + std::vector shape(1); + shape[0]=getPntrToArgument(0)->getNumberOfValues(); for(unsigned i=0; igetNumberOfValues() ) error("mismatch between sizes of input coordinates"); - std::string num; Tools::convert( i+1, num ); addComponent( "coord-" + num, shape ); - componentIsNotPeriodic( "coord-" + num ); getPntrToArgument(i)->buildDataStore(); + if( shape[0]!=getPntrToArgument(i)->getNumberOfValues() ) { + error("mismatch between sizes of input coordinates"); + } + std::string num; + Tools::convert( i+1, num ); + addComponent( "coord-" + num, shape ); + componentIsNotPeriodic( "coord-" + num ); + getPntrToArgument(i)->buildDataStore(); } - std::vector args( getArguments() ), target, weights; std::string sfd, errors; + std::vector args( getArguments() ), target, weights; + std::string sfd, errors; // Read in target "distances" and target weights for(unsigned i=1;; ++i) { - target.resize(0); if( !parseArgumentList("TARGET",i,target) ) break; - std::string inum; Tools::convert( i, inum ); checkInputMatrix( "TARGET" + inum, shape[0], target ); - if( !parseArgumentList("WEIGHTS",i,weights) ) error("missing WEIGHTS" + inum + " keyword in input"); + target.resize(0); + if( !parseArgumentList("TARGET",i,target) ) { + break; + } + std::string inum; + Tools::convert( i, inum ); + checkInputMatrix( "TARGET" + inum, shape[0], target ); + if( !parseArgumentList("WEIGHTS",i,weights) ) { + error("missing WEIGHTS" + inum + " keyword in input"); + } checkInputMatrix( "WEIGHTS" + inum, shape[0], weights ); - args.push_back( target[0] ); args.push_back( weights[0] ); - bool has_sf = parseNumbered("FUNC",i,sfd); switchingFunction.push_back( SwitchingFunction() ); + args.push_back( target[0] ); + args.push_back( weights[0] ); + bool has_sf = parseNumbered("FUNC",i,sfd); + switchingFunction.push_back( SwitchingFunction() ); if( !has_sf ) { - switchingFunction[i-1].set( "CUSTOM FUNC=1-sqrt(x2) R_0=1.0", errors ); dist_target=i-1; + switchingFunction[i-1].set( "CUSTOM FUNC=1-sqrt(x2) R_0=1.0", errors ); + dist_target=i-1; } else { switchingFunction[i-1].set( sfd, errors ); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } } log.printf(" %sth term seeks to match tranformed distances with those in matrix %s \n", inum.c_str(), target[0]->getName().c_str() ); log.printf(" in %sth term distances are transformed by 1-switching function with r_0=%s \n", inum.c_str(), switchingFunction[i-1].description().c_str() ); log.printf(" in %sth term weights of matrix elements in stress function are given by %s \n", inum.c_str(), weights[0]->getName().c_str() ); } - std::string mtype; parse("MINTYPE",mtype); + std::string mtype; + parse("MINTYPE",mtype); if( mtype=="conjgrad" ) { mintype=conjgrad; log.printf(" minimimising stress function using conjugate gradients\n"); } else if( mtype=="pointwise") { mintype=pointwise; log.printf(" minimimising stress function using pointwise global optimisation\n"); - npoints.resize(dimout); nfgrid.resize(dimout); - parseVector("CGRID_SIZE",npoints); parse("BUFFER",gbuf); parse("NCYCLES",ncycles); - parseVector("FGRID_SIZE",nfgrid); if( nfgrid[0]!=0 && dimout!=2 ) error("interpolation only works in two dimensions"); + npoints.resize(dimout); + nfgrid.resize(dimout); + parseVector("CGRID_SIZE",npoints); + parse("BUFFER",gbuf); + parse("NCYCLES",ncycles); + parseVector("FGRID_SIZE",nfgrid); + if( nfgrid[0]!=0 && dimout!=2 ) { + error("interpolation only works in two dimensions"); + } log.printf(" doing %u cycles of global optimization sweeps\n",ncycles); log.printf(" using coarse grid of points that is %u",npoints[0]); - for(unsigned j=1; j0 ) { log.printf(" interpolating stress onto grid of points that is %u",nfgrid[0]); - for(unsigned j=1; j& mat ) const { mat[0]->buildDataStore(); - if( mat.size()!=1 ) error("should only be one value in input to " + key ); - if( mat[0]->getRank()!=2 || mat[0]->hasDerivatives() ) error("input to " + key + " keyword should be a matrix"); - if( mat[0]->getShape()[0]!=nvals || mat[0]->getShape()[1]!=nvals ) error("input to " + key + " keyword has the wrong size"); + if( mat.size()!=1 ) { + error("should only be one value in input to " + key ); + } + if( mat[0]->getRank()!=2 || mat[0]->hasDerivatives() ) { + error("input to " + key + " keyword should be a matrix"); + } + if( mat[0]->getShape()[0]!=nvals || mat[0]->getShape()[1]!=nvals ) { + error("input to " + key + " keyword has the wrong size"); + } } double ArrangePoints::calculateStress( const std::vector& p, std::vector& d ) { - double stress=0; for(unsigned i=0; i dtmp(dimout); std::vector shape( getPntrToArgument( dimout )->getShape() ); unsigned targi=shape[0]*current_index; unsigned nmatrices = ( getNumberOfArguments() - dimout ) / 2; for(unsigned i=0; iget( shape[0]*i+j ); + for(unsigned j=0; jget( shape[0]*i+j ); + } // Get the difference for the connection double fdiff = fd - getPntrToArgument( dimout + 2*k )->get( targi+i ); // Calculate derivatives double pref = -2.*weight*fdiff*df; - for(unsigned n=0; n& p, std::vector double ArrangePoints::calculateFullStress( const std::vector& p, std::vector& d ) { // Zero derivative and stress accumulators - for(unsigned i=0; i dtmp( dimout ); + for(unsigned i=0; i dtmp( dimout ); unsigned nmatrices = ( getNumberOfArguments() - dimout ) / 2; std::vector shape( getPntrToArgument( dimout )->getShape() ); for(unsigned i=1; i& p, std::ve double fdiff = fd - getPntrToArgument( dimout + 2*k )->get( shape[0]*i+j ); // Calculate derivatives double pref = -2.*weight*fdiff*df; - for(unsigned n=0; n& p, SM for(unsigned i=1; i& p, SM // Get the difference for the connection double fdiff = getPntrToArgument( dimout + 2*k )->get( shape[0]*i+j ) - fd; // Now set the weight if difference in distance is larger than regularisation parameter - if( fabs(diff)>smacof_reg ) wval -= weight*fdiff*df*dd1 / diff; + if( fabs(diff)>smacof_reg ) { + wval -= weight*fdiff*df*dd1 / diff; + } // And the total stress and weights - stress += weight*fdiff*fdiff; totalWeight += weight; + stress += weight*fdiff*fdiff; + totalWeight += weight; } - mysmacof.setWeight( j, i, wval ); mysmacof.setWeight( i, j, wval ); + mysmacof.setWeight( j, i, wval ); + mysmacof.setWeight( i, j, wval ); } } return stress / totalWeight; @@ -258,18 +341,28 @@ void ArrangePoints::optimize( std::vector& pos ) { unsigned nvals=getPntrToArgument( dimout )->getShape()[0]; std::vector gmin( dimout ), gmax( dimout ), mypoint( dimout ); // Find the extent of the grid - for(unsigned j=0; j gmax[j] ) gmax[j] = pos[dimout*i+j]; + if( pos[dimout*i+j] < gmin[j] ) { + gmin[j] = pos[dimout*i+j]; + } + if( pos[dimout*i+j] > gmax[j] ) { + gmax[j] = pos[dimout*i+j]; + } } } for(unsigned j=0; j mygridsearch( gmin, gmax, npoints, nfgrid, this ); // Run multiple loops over all projections for(unsigned i=0; i& pos ) { current_index=j; // Find current projection of jth point - for(unsigned k=0; k& pos ) { // Recalculate weights matrix and sigma double newsig = recalculateSmacofWeights( pos, mysmacof ); // Test whether or not the algorithm has converged - if( fabs( newsig - stress ) shape(1,getPntrToArgument( dimout )->getShape()[0]); for(unsigned j=0; jgetShape()[0]!=shape[0] ) getPntrToComponent(j)->setShape( shape ); + if( getPntrToComponent(j)->getShape()[0]!=shape[0] ) { + getPntrToComponent(j)->setShape( shape ); + } } } @@ -319,13 +423,17 @@ void ArrangePoints::calculate() { unsigned nvals = getPntrToArgument( dimout )->getShape()[0]; std::vector pos( dimout*nvals ); for(unsigned i=0; iget(i); + for(unsigned j=0; jget(i); + } } // Do the optimization optimize( pos ); // And set the final values for(unsigned i=0; iset( i, pos[dimout*i+j] ); + for(unsigned j=0; jset( i, pos[dimout*i+j] ); + } } } diff --git a/src/dimred/ClassicalMultiDimensionalScaling.cpp b/src/dimred/ClassicalMultiDimensionalScaling.cpp index ff948203e2..4e5d723fd6 100644 --- a/src/dimred/ClassicalMultiDimensionalScaling.cpp +++ b/src/dimred/ClassicalMultiDimensionalScaling.cpp @@ -176,24 +176,35 @@ void ClassicalMultiDimensionalScaling::registerKeywords( Keywords& keys ) { keys.add("compulsory","ARG","the arguments that you would like to make the histogram for"); keys.add("compulsory","NLOW_DIM","number of low-dimensional coordinates required"); keys.setValueDescription("the low dimensional projections for the input data points"); - keys.needsAction("TRANSPOSE"); keys.needsAction("DISSIMILARITIES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); keys.needsAction("VSTACK"); - keys.needsAction("SUM"); keys.needsAction("CUSTOM"); keys.needsAction("OUTER_PRODUCT"); keys.needsAction("DIAGONALIZE"); + keys.needsAction("TRANSPOSE"); + keys.needsAction("DISSIMILARITIES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("VSTACK"); + keys.needsAction("SUM"); + keys.needsAction("CUSTOM"); + keys.needsAction("OUTER_PRODUCT"); + keys.needsAction("DIAGONALIZE"); } ClassicalMultiDimensionalScaling::ClassicalMultiDimensionalScaling( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Find the argument name - std::string argn; parse("ARG",argn); std::string dissimilarities=""; + std::string argn; + parse("ARG",argn); + std::string dissimilarities=""; ActionShortcut* as = plumed.getActionSet().getShortcutActionWithLabel( argn ); - if( !as ) error("found no action with name " + argn ); + if( !as ) { + error("found no action with name " + argn ); + } if( as->getName()!="COLLECT_FRAMES" ) { if( as->getName().find("LANDMARK_SELECT")==std::string::npos ) { error("found no COLLECT_FRAMES or LANDMARK_SELECT action with label " + argn ); } else { ActionWithValue* dissims = plumed.getActionSet().selectWithLabel( argn + "_sqrdissims"); - if( dissims ) dissimilarities = argn + "_sqrdissims"; + if( dissims ) { + dissimilarities = argn + "_sqrdissims"; + } } } if( dissimilarities.length()==0 ) { @@ -219,16 +230,27 @@ ClassicalMultiDimensionalScaling::ClassicalMultiDimensionalScaling( const Action // Step 4: subtract the column sums readInputLine( getShortcutLabel() + "_cmat: CUSTOM ARG=" + getShortcutLabel() + "_csummat," + getShortcutLabel() + "_intT FUNC=y-x PERIODIC=NO"); // And generate the multidimensional scaling projection - unsigned ndim; parse("NLOW_DIM",ndim); - std::string vecstr="1"; for(unsigned i=1; igetName()!="COLLECT_FRAMES" ) error("found no COLLECT_FRAMES action with label " + argn ); + if( !as || as->getName()!="COLLECT_FRAMES" ) { + error("found no COLLECT_FRAMES action with label " + argn ); + } // Get the final weights using the logsumexp trick readInputLine( getShortcutLabel() + "_weights: LOGSUMEXP ARG=" + argn + "_logweights"); // Now transpose the collected frames @@ -138,9 +148,14 @@ PCA::PCA(const ActionOptions&ao): readInputLine( getShortcutLabel() + "_averages: OUTER_PRODUCT ARG=" + argn + "_ones," + getShortcutLabel() + "_mean"); // Make a matrix of weights ActionWithValue* av2 = plumed.getActionSet().selectWithLabel( argn + "_data" ); - if( !av2 ) error("count not find data"); + if( !av2 ) { + error("count not find data"); + } unsigned nones = (av2->copyOutput(0))->getShape()[1]; - std::string ones="1"; for(unsigned i=1; inones ) error("cannot generate projection in space of dimension higher than input coordinates"); - for(unsigned i=1; inones ) { + error("cannot generate projection in space of dimension higher than input coordinates"); + } + for(unsigned i=1; i0 && av2->getName()=="VSTACK" ) { - std::vector argnames; av2->getMatrixColumnTitles( argnames ); - std::string argname_str=argnames[0]; for(unsigned i=1; i0 ) fmt=" FMT=" + fmt; + std::vector argnames; + av2->getMatrixColumnTitles( argnames ); + std::string argname_str=argnames[0]; + for(unsigned i=1; i0 ) { + fmt=" FMT=" + fmt; + } readInputLine("DUMPPDB DESCRIPTION=PCA ARG_NAMES=" + argname_str + " ARG=" + getShortcutLabel() + "_pca FILE=" + filename + " STRIDE=" + pstride + fmt ); } else { - if( av2->getName()!="COLLECT" ) error("input data should be VSTACK if list of arguments of COLLECT if atom positions"); + if( av2->getName()!="COLLECT" ) { + error("input data should be VSTACK if list of arguments of COLLECT if atom positions"); + } ActionAtomistic* rmsdact = plumed.getActionSet().selectWithLabel( argn + "_getposx" ); - if( !rmsdact ) error("could not find action that gets positions from trajectory for RMSD"); - std::vector atoms( rmsdact->getAbsoluteIndexes() ); std::string indices; Tools::convert( atoms[0].serial(), indices ); - for(unsigned i=1; i atoms( rmsdact->getAbsoluteIndexes() ); + std::string indices; + Tools::convert( atoms[0].serial(), indices ); + for(unsigned i=1; i& pp, std::vector& der ); @@ -60,7 +62,8 @@ class ProjectPoints : public ActionWithVector { PLUMED_REGISTER_ACTION(ProjectPoints,"PROJECT_POINTS") void ProjectPoints::registerKeywords( Keywords& keys ) { - ActionWithVector::registerKeywords( keys ); keys.use("ARG"); + ActionWithVector::registerKeywords( keys ); + keys.use("ARG"); keys.add("numbered","TARGET","the matrix of target quantities that you would like to match"); keys.add("numbered","FUNC","a function that is applied on the distances between the points in the low dimensional space"); keys.add("numbered","WEIGHTS","the matrix with the weights of the target quantities"); @@ -73,67 +76,119 @@ ProjectPoints::ProjectPoints( const ActionOptions& ao ) : Action(ao), ActionWithVector(ao), rowstart(OpenMP::getNumThreads()), - myminimiser( this ) -{ - dimout = getNumberOfArguments(); unsigned nvals=getPntrToArgument(0)->getNumberOfValues(); + myminimiser( this ) { + dimout = getNumberOfArguments(); + unsigned nvals=getPntrToArgument(0)->getNumberOfValues(); for(unsigned i=0; igetNumberOfValues() ) error("mismatch between numbers of projections"); + if( nvals!=getPntrToArgument(i)->getNumberOfValues() ) { + error("mismatch between numbers of projections"); + } } - std::vector args( getArguments() ), target, weights; std::string sfd, errors; unsigned ntoproj=0; + std::vector args( getArguments() ), target, weights; + std::string sfd, errors; + unsigned ntoproj=0; // Read in target "distances" and target weights for(unsigned i=1;; ++i) { - target.resize(0); if( !parseArgumentList("TARGET",i,target) ) break; - std::string inum; Tools::convert( i, inum ); - if( target.size()!=1 ) error("should only be one value in input to TARGET" + inum ); - if( (target[0]->getRank()!=1 && target[0]->getRank()!=2) || target[0]->hasDerivatives() ) error("input to TARGET" + inum + " keyword should be a vector/matrix"); - if( target[0]->getShape()[0]!=nvals ) error("number of rows in target matrix should match number of input coordinates"); - if( i==1 && target[0]->getRank()==1 ) { ntoproj = 1; } - else if( ntoproj==1 && target[0]->getRank()!=1 ) error("mismatch between numbers of target distances"); - else if( i==1 ) ntoproj = target[0]->getShape()[1]; - else if( ntoproj!=target[0]->getShape()[1] ) error("mismatch between numbers of target distances"); - if( !parseArgumentList("WEIGHTS",i,weights) ) error("missing WEIGHTS" + inum + " keyword in input"); - if( weights.size()!=1 ) error("should only be one value in input to WEIGHTS" + inum ); - if( weights[0]->getRank()!=1 || weights[0]->hasDerivatives() ) error("input to WEIGHTS" + inum + " keyword should be a vector"); - if( weights[0]->getShape()[0]!=nvals ) error("number of weights should match number of input coordinates"); - target[0]->buildDataStore(); weights[0]->buildDataStore(); args.push_back( target[0] ); args.push_back( weights[0] ); - bool has_sf = parseNumbered("FUNC",i,sfd); switchingFunction.push_back( SwitchingFunction() ); + target.resize(0); + if( !parseArgumentList("TARGET",i,target) ) { + break; + } + std::string inum; + Tools::convert( i, inum ); + if( target.size()!=1 ) { + error("should only be one value in input to TARGET" + inum ); + } + if( (target[0]->getRank()!=1 && target[0]->getRank()!=2) || target[0]->hasDerivatives() ) { + error("input to TARGET" + inum + " keyword should be a vector/matrix"); + } + if( target[0]->getShape()[0]!=nvals ) { + error("number of rows in target matrix should match number of input coordinates"); + } + if( i==1 && target[0]->getRank()==1 ) { + ntoproj = 1; + } else if( ntoproj==1 && target[0]->getRank()!=1 ) { + error("mismatch between numbers of target distances"); + } else if( i==1 ) { + ntoproj = target[0]->getShape()[1]; + } else if( ntoproj!=target[0]->getShape()[1] ) { + error("mismatch between numbers of target distances"); + } + if( !parseArgumentList("WEIGHTS",i,weights) ) { + error("missing WEIGHTS" + inum + " keyword in input"); + } + if( weights.size()!=1 ) { + error("should only be one value in input to WEIGHTS" + inum ); + } + if( weights[0]->getRank()!=1 || weights[0]->hasDerivatives() ) { + error("input to WEIGHTS" + inum + " keyword should be a vector"); + } + if( weights[0]->getShape()[0]!=nvals ) { + error("number of weights should match number of input coordinates"); + } + target[0]->buildDataStore(); + weights[0]->buildDataStore(); + args.push_back( target[0] ); + args.push_back( weights[0] ); + bool has_sf = parseNumbered("FUNC",i,sfd); + switchingFunction.push_back( SwitchingFunction() ); if( !has_sf ) { switchingFunction[i-1].set( "CUSTOM FUNC=1-sqrt(x2) R_0=1.0", errors ); } else { switchingFunction[i-1].set( sfd, errors ); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } } log.printf(" %sth term seeks to match tranformed distances with those in matrix %s \n", inum.c_str(), target[0]->getName().c_str() ); log.printf(" in %sth term distances are transformed by 1-switching function with r_0=%s \n", inum.c_str(), switchingFunction[i-1].description().c_str() ); log.printf(" in %sth term weights of matrix elements in stress function are given by %s \n", inum.c_str(), weights[0]->getName().c_str() ); } - std::vector shape(1); shape[0]=ntoproj; if( ntoproj==1 ) shape.resize(0); + std::vector shape(1); + shape[0]=ntoproj; + if( ntoproj==1 ) { + shape.resize(0); + } for(unsigned i=0; igetRank()==0 ) return; + if( getPntrToComponent(0)->getRank()==0 ) { + return; + } - std::vector shape(1); shape[0] = getPntrToArgument(dimout)->getShape()[0]; + std::vector shape(1); + shape[0] = getPntrToArgument(dimout)->getShape()[0]; for(unsigned i=0; igetShape()[0]!=shape[0] ) getPntrToComponent(i)->setShape(shape); + if( getPntrToComponent(i)->getShape()[0]!=shape[0] ) { + getPntrToComponent(i)->setShape(shape); + } } } double ProjectPoints::calculateStress( const std::vector& pp, std::vector& der ) { - unsigned nmatrices = ( getNumberOfArguments() - dimout ) / 2; double stress=0; + unsigned nmatrices = ( getNumberOfArguments() - dimout ) / 2; + double stress=0; unsigned t=OpenMP::getThreadNum(); - std::vector dtmp( pp.size() ); unsigned nland = getPntrToArgument(0)->getShape()[0]; + std::vector dtmp( pp.size() ); + unsigned nland = getPntrToArgument(0)->getShape()[0]; for(unsigned i=0; iget(i); dd2 += dtmp[k]*dtmp[k]; } + double dd2 = 0; + for(unsigned k=0; kget(i); + dd2 += dtmp[k]*dtmp[k]; + } for(unsigned k=0; k& pp, std::vecto // Get the difference for the connection double fdiff = fd - getPntrToArgument( dimout + 2*k )->get( rowstart[t]+i ); // Calculate derivatives - double pref = -2.*weight*fdiff*df; for(unsigned n=0; n& pp, std::vecto } void ProjectPoints::getProjection( const unsigned& current, std::vector& point ) const { - Value* targ = getPntrToArgument( dimout ); unsigned nland = getPntrToArgument(0)->getShape()[0]; - unsigned base = current; if( targ->getRank()==2 ) base = current*targ->getShape()[1]; - unsigned closest=0; double mindist = targ->get( base ); + Value* targ = getPntrToArgument( dimout ); + unsigned nland = getPntrToArgument(0)->getShape()[0]; + unsigned base = current; + if( targ->getRank()==2 ) { + base = current*targ->getShape()[1]; + } + unsigned closest=0; + double mindist = targ->get( base ); for(unsigned i=1; iget( base + i ); - if( distget(closest) + (random.RandU01() - 0.5)*0.01; + Random random; + random.setSeed(-1234); + for(unsigned j=0; jget(closest) + (random.RandU01() - 0.5)*0.01; + } // And do the optimisation - rowstart[OpenMP::getThreadNum()]=current; if( targ->getRank()==2 ) rowstart[OpenMP::getThreadNum()] = current*targ->getShape()[1]; + rowstart[OpenMP::getThreadNum()]=current; + if( targ->getRank()==2 ) { + rowstart[OpenMP::getThreadNum()] = current*targ->getShape()[1]; + } myminimiser.minimise( cgtol, point, &ProjectPoints::calculateStress ); } void ProjectPoints::performTask( const unsigned& current, MultiValue& myvals ) const { - std::vector point( dimout ); getProjection( current, point ); - for(unsigned j=0; jgetPositionInStream(), point[j] ); + std::vector point( dimout ); + getProjection( current, point ); + for(unsigned j=0; jgetPositionInStream(), point[j] ); + } } void ProjectPoints::calculate() { if( getPntrToComponent(0)->getRank()==0 ) { - std::vector point( dimout ); getProjection( 0, point ); - for(unsigned i=0; iset(point[i]); - } else runAllTasks(); + std::vector point( dimout ); + getProjection( 0, point ); + for(unsigned i=0; iset(point[i]); + } + } else { + runAllTasks(); + } } } diff --git a/src/dimred/SMACOF.cpp b/src/dimred/SMACOF.cpp index ded2f633e9..b07076a81b 100644 --- a/src/dimred/SMACOF.cpp +++ b/src/dimred/SMACOF.cpp @@ -24,83 +24,120 @@ namespace PLMD { namespace dimred { -SMACOF::SMACOF( const Value* target) -{ +SMACOF::SMACOF( const Value* target) { std::vector shape( target->getShape() ); - Distances.resize( shape[0], shape[1] ); Weights.resize( shape[0], shape[1] ); + Distances.resize( shape[0], shape[1] ); + Weights.resize( shape[0], shape[1] ); for(unsigned i=0; iget(shape[0]*i+j) ); + for(unsigned j=0; jget(shape[0]*i+j) ); + } } } void SMACOF::optimize( const double& tol, const unsigned& maxloops, std::vector& proj ) { - unsigned M = Distances.nrows(); unsigned nlow=proj.size() / M; Matrix Z( M, nlow ); + unsigned M = Distances.nrows(); + unsigned nlow=proj.size() / M; + Matrix Z( M, nlow ); // Transfer initial projection to matrix unsigned k = 0; for(unsigned i=0; i V(M,M); for(unsigned i=0; i mypseudo(M, M); pseudoInvert(V, mypseudo); - Matrix dists( M, M ); double myfirstsig = calculateSigma( Z, dists ); + Matrix mypseudo(M, M); + pseudoInvert(V, mypseudo); + Matrix dists( M, M ); + double myfirstsig = calculateSigma( Z, dists ); // initial sigma is made up of the original distances minus the distances between the projections all squared. Matrix temp( M, M ), BZ( M, M ), newZ( M, nlow ); for(unsigned n=0; n0 ) BZ(i,j) = -Weights(i,j)*Distances(i,j) / dists(i,j); - else BZ(i,j)=0.; + if(i==j) { + continue; //skips over the diagonal elements + } + + if( dists(i,j)>0 ) { + BZ(i,j) = -Weights(i,j)*Distances(i,j) / dists(i,j); + } else { + BZ(i,j)=0.; + } } //the diagonal elements are -off diagonal elements BZ(i,i)-=BZ(i,j) (Equation 8.25) BZ(i,i)=0; //create the space memory for the diagonal elements which are scalars for(unsigned j=0; j& Z, Matrix& dists ) { - unsigned M = Distances.nrows(); double sigma=0; double totalWeight=0; + unsigned M = Distances.nrows(); + double sigma=0; + double totalWeight=0; for(unsigned i=1; igetName()!="COLLECT_FRAMES" ) { if( as->getName().find("LANDMARK_SELECT")==std::string::npos ) { error("found no COLLECT_FRAMES or LANDMARK_SELECT action with label " + argn ); } else { ActionWithValue* dissims = plumed.getActionSet().selectWithLabel( argn + "_sqrdissims"); - if( dissims ) dissimilarities = argn + "_sqrdissims"; + if( dissims ) { + dissimilarities = argn + "_sqrdissims"; + } } } - unsigned ndim; parse("NLOW_DIM",ndim); - std::string str_ndim; Tools::convert( ndim, str_ndim ); + unsigned ndim; + parse("NLOW_DIM",ndim); + std::string str_ndim; + Tools::convert( ndim, str_ndim ); // Construct a projection using classical MDS readInputLine( getShortcutLabel() + "_mds: CLASSICAL_MDS ARG=" + argn + " NLOW_DIM=" + str_ndim ); // Transform the dissimilarities using the switching function - std::string hdfunc; parse("HIGH_DIM_FUNCTION",hdfunc); + std::string hdfunc; + parse("HIGH_DIM_FUNCTION",hdfunc); readInputLine( getShortcutLabel() + "_hdmat: MORE_THAN ARG=" + dissimilarities + " SQUARED SWITCH={" + hdfunc + "}"); // Now for the weights - read the vector of weights first - std::string wvec; parse("WEIGHTS",wvec); if( wvec.length()==0 ) wvec = argn + "_weights"; + std::string wvec; + parse("WEIGHTS",wvec); + if( wvec.length()==0 ) { + wvec = argn + "_weights"; + } // Now calculate the sum of thse weights readInputLine( wvec + "_sum: SUM ARG=" + wvec + " PERIODIC=NO"); // And normalise the vector of weights using this sum @@ -101,43 +119,94 @@ SketchMap::SketchMap( const ActionOptions& ao): // And now create the matrix of weights readInputLine( wvec + "_mat: OUTER_PRODUCT ARG=" + wvec + "_normed," + wvec + "_normed"); // Run the arrange points object - std::string ldfunc, cgtol, maxiter; parse("LOW_DIM_FUNCTION",ldfunc); parse("CGTOL",cgtol); parse("MAXITER",maxiter); unsigned ncycles; parse("NCYCLES",ncycles); - std::string num, argstr, lname=getShortcutLabel() + "_ap"; if( ncycles>0 ) lname = getShortcutLabel() + "_cg"; - argstr = "ARG=" + getShortcutLabel() + "_mds-1"; for(unsigned i=1; i0 ) { + lname = getShortcutLabel() + "_cg"; + } + argstr = "ARG=" + getShortcutLabel() + "_mds-1"; + for(unsigned i=1; i fgrid; parseVector("FGRID_SIZE",fgrid); - std::string ncyc; Tools::convert(ncycles,ncyc); std::string pwise_args=" NCYCLES=" + ncyc + " BUFFER=" + buf; + std::string buf; + parse("BUFFER",buf); + std::vector fgrid; + parseVector("FGRID_SIZE",fgrid); + std::string ncyc; + Tools::convert(ncycles,ncyc); + std::string pwise_args=" NCYCLES=" + ncyc + " BUFFER=" + buf; if( fgrid.size()>0 ) { - if( fgrid.size()!=ndim ) error("number of elements of fgrid is not correct"); - pwise_args += " FGRID_SIZE=" + fgrid[0]; for(unsigned i=1; i cgrid(ndim); + parseVector("CGRID_SIZE",cgrid); + pwise_args += " CGRID_SIZE=" + cgrid[0]; + for(unsigned i=1; i cgrid(ndim); parseVector("CGRID_SIZE",cgrid); - pwise_args += " CGRID_SIZE=" + cgrid[0]; for(unsigned i=1; igetName().find("LANDMARK_SELECT")==std::string::npos ) { readInputLine( getShortcutLabel() + "_osample_pp: PROJECT_POINTS " + argstr + " TARGET1=" + getShortcutLabel() + "_hdmat FUNC1={" + ldfunc + "} WEIGHTS1=" + wvec + "_normed CGTOL=" + cgtol ); } else { ActionWithValue* dissims = plumed.getActionSet().selectWithLabel( argn + "_rectdissims"); - if( !dissims ) error("cannot PROJECT_ALL as " + as->getName() + " with label " + argn + " was involved without the DISSIMILARITIES keyword"); + if( !dissims ) { + error("cannot PROJECT_ALL as " + as->getName() + " with label " + argn + " was involved without the DISSIMILARITIES keyword"); + } readInputLine( getShortcutLabel() + "_lhdmat: MORE_THAN ARG=" + argn + "_rectdissims SQUARED SWITCH={" + hdfunc + "}"); readInputLine( getShortcutLabel() + "_osample_pp: PROJECT_POINTS ARG=" + argstr + " TARGET1=" + getShortcutLabel() + "_lhdmat FUNC1={" + ldfunc + "} WEIGHTS1=" + wvec + "_normed CGTOL=" + cgtol ); } - argstr="ARG=" + getShortcutLabel() + "_osample_pp.coord-1"; for(unsigned i=1; i argnames; parseVector("ARG",argnames); - std::string type, reference_data, reference; parse("REFERENCE",reference); parse("TYPE",type); + std::vector argnames; + parseVector("ARG",argnames); + std::string type, reference_data, reference; + parse("REFERENCE",reference); + parse("TYPE",type); mapping::Path::readInputFrames( reference, type, argnames, false, this, reference_data ); // And read in the data that we want on the projections - std::vector pnames; parseVector("PROPERTY",pnames); - std::string weights; parse("WEIGHT",weights); pnames.push_back( weights ); + std::vector pnames; + parseVector("PROPERTY",pnames); + std::string weights; + parse("WEIGHT",weights); + pnames.push_back( weights ); // Now create fixed vectors using some sort of reference action mapping::Path::readPropertyInformation( pnames, getShortcutLabel(), reference, this ); // Normalise the vector of weights readInputLine( getShortcutLabel() + "_wsum: SUM PERIODIC=NO ARG=" + weights + "_ref"); readInputLine( getShortcutLabel() + "_weights: CUSTOM ARG=" + getShortcutLabel() + "_wsum," + weights + "_ref FUNC=y/x PERIODIC=NO"); // Transform the high dimensional distances - std::string hdfunc; parse("HIGH_DIM_FUNCTION",hdfunc); + std::string hdfunc; + parse("HIGH_DIM_FUNCTION",hdfunc); readInputLine( getShortcutLabel() + "_targ: MORE_THAN ARG=" + getShortcutLabel() + "_data SQUARED SWITCH={" + hdfunc + "}"); // Create the projection object - std::string ldfunc, cgtol; parse("LOW_DIM_FUNCTION",ldfunc); parse("CGTOL",cgtol); - std::string argstr="ARG=" + pnames[0] + "_ref"; for(unsigned i=1; i &p_dimensions, bool DRRForceGrid::isInBoundary(const vector &pos) const { bool result = true; for (size_t i = 0; i < ndims; ++i) { - if (pos[i] < dimensions[i].min || pos[i] > dimensions[i].max) + if (pos[i] < dimensions[i].min || pos[i] > dimensions[i].max) { return false; + } } return result; } @@ -158,8 +165,9 @@ size_t DRRForceGrid::sampleAddress(const vector &pos) const { bool DRRForceGrid::store(const vector &pos, const vector &f, unsigned long int nsamples) { if (isInBoundary(pos)) { - if (nsamples == 0) + if (nsamples == 0) { return true; + } const size_t baseaddr = sampleAddress(pos); samples[baseaddr] += nsamples; auto it_fa = begin(forces) + baseaddr * ndims; @@ -180,8 +188,9 @@ vector DRRForceGrid::merge(const vector &dA, vector DRRForceGrid::getAccumulatedForces(const vector &pos) const { vector result(ndims, 0); - if (!isInBoundary(pos)) + if (!isInBoundary(pos)) { return result; + } const size_t force_addr = sampleAddress(pos) * ndims; std::copy(begin(forces) + force_addr, begin(forces) + force_addr + ndims, begin(result)); @@ -208,11 +217,14 @@ vector DRRForceGrid::getGradient(const vector &pos, } const size_t baseaddr = sampleAddress(pos); const unsigned long int &count = samples[baseaddr]; - if (count == 0) + if (count == 0) { return result; + } auto it_fa = begin(forces) + baseaddr * ndims; std::transform(it_fa, it_fa + ndims, begin(result), - [&count](double fa) { return (-1.0) * fa / count; }); + [&count](double fa) { + return (-1.0) * fa / count; + }); return result; } @@ -480,8 +492,9 @@ vector CZAR::getGradient(const vector &pos, const size_t baseaddr = sampleAddress(pos); const vector log_deriv(getCountsLogDerivative(pos)); const unsigned long int &count = samples[baseaddr]; - if (count == 0) + if (count == 0) { return result; + } auto it_fa = begin(forces) + baseaddr * ndims; std::transform(it_fa, it_fa + ndims, begin(log_deriv), begin(result), [&count, this](double fa, double ld) { diff --git a/src/drr/DRR.h b/src/drr/DRR.h index 3f6fd88802..dbe293a936 100644 --- a/src/drr/DRR.h +++ b/src/drr/DRR.h @@ -84,15 +84,29 @@ class DRRAxis { periodic = true; } /// Getters - double getMin() const { return this->min; } - double getMax() const { return this->max; } - double getWidth() const { return binWidth; } - double getDomainMax() const { return this->domainMax; } - double getDomainMin() const { return this->domainMin; } - size_t getBins() const { return this->nbins; } + double getMin() const { + return this->min; + } + double getMax() const { + return this->max; + } + double getWidth() const { + return binWidth; + } + double getDomainMax() const { + return this->domainMax; + } + double getDomainMin() const { + return this->domainMin; + } + size_t getBins() const { + return this->nbins; + } /// Check periodicity - bool isPeriodic() const { return this->periodic; } + bool isPeriodic() const { + return this->periodic; + } /// Check real periodicity, i.e. the maximum == the domain maximum bool isRealPeriodic() const; @@ -198,9 +212,13 @@ class DRRForceGrid { static vector merge(const vector &dA, const vector &dB); /// Get suffix - string getSuffix() const { return suffix; } + string getSuffix() const { + return suffix; + } /// Set unit for .grad output - void setOutputUnit(double unit) { outputunit = unit; } + void setOutputUnit(double unit) { + outputunit = unit; + } /// Destructor virtual ~DRRForceGrid() {} @@ -266,10 +284,11 @@ class DRRForceGrid { ss.precision(std::numeric_limits::max_digits10); ss << std::fixed << "# " << dimensions[i].min << ' ' << dimensions[i].binWidth << ' ' << dimensions[i].nbins; - if (dimensions[i].isPeriodic()) + if (dimensions[i].isPeriodic()) { ss << " 1" << '\n'; - else + } else { ss << " 0" << '\n'; + } } fillTable(mp); headers = ss.str(); @@ -336,8 +355,12 @@ class CZAR : public DRRForceGrid { : DRRForceGrid(p_dimensions, p_suffix, initializeTable), kbt(p_kbt) {} vector getGradient(const vector &pos, bool SkipCheck = false) const; - double getkbt() const { return kbt; } - void setkbt(double p_kbt) { kbt = p_kbt; } + double getkbt() const { + return kbt; + } + void setkbt(double p_kbt) { + kbt = p_kbt; + } static CZAR mergewindow(const CZAR &cWA, const CZAR &cWB); void writeZCountZGrad(const string &filename, bool addition = false) const; ~CZAR() {} diff --git a/src/drr/DynamicReferenceRestraining.cpp b/src/drr/DynamicReferenceRestraining.cpp index 77c40ff532..7cc246387b 100644 --- a/src/drr/DynamicReferenceRestraining.cpp +++ b/src/drr/DynamicReferenceRestraining.cpp @@ -357,8 +357,7 @@ DynamicReferenceRestraining::DynamicReferenceRestraining( useCZARestimator(true), useUIestimator(false), mergeHistoryFiles(false), textoutput(false), withExternalForce(false), withExternalFict(false), reflectingWall(getNumberOfArguments(), 0), - maxFactors(getNumberOfArguments(), 1.0) -{ + maxFactors(getNumberOfArguments(), 1.0) { log << "eABF/DRR: You now are using the extended adaptive biasing " "force(eABF) method." << '\n'; @@ -454,8 +453,9 @@ DynamicReferenceRestraining::DynamicReferenceRestraining( vector zgmin(ndims); parseVector("GRID_MIN", gmin); parseVector("ZGRID_MIN", zgmin); - if (gmin.size() != ndims) + if (gmin.size() != ndims) { error("eABF/DRR: not enough values for GRID_MIN"); + } if (zgmin.size() != ndims) { log << "eABF/DRR: You didn't specify ZGRID_MIN. " << '\n' << "eABF/DRR: The GRID_MIN will be used instead."; @@ -465,8 +465,9 @@ DynamicReferenceRestraining::DynamicReferenceRestraining( vector zgmax(ndims); parseVector("GRID_MAX", gmax); parseVector("ZGRID_MAX", zgmax); - if (gmax.size() != ndims) + if (gmax.size() != ndims) { error("eABF/DRR: not enough values for GRID_MAX"); + } if (zgmax.size() != ndims) { log << "eABF/DRR: You didn't specify ZGRID_MAX. " << '\n' << "eABF/DRR: The GRID_MAX will be used instead."; @@ -614,8 +615,9 @@ DynamicReferenceRestraining::DynamicReferenceRestraining( componentIsPeriodic(comp, a, b); delim[i].setPeriodicity(c, d); zdelim[i].setPeriodicity(c, d); - } else + } else { componentIsNotPeriodic(comp); + } fictValue[i] = getPntrToComponent(comp); // Velocity output comp = getPntrToArgument(i)->getName() + "_vfict"; diff --git a/src/drr/colvar_UIestimator.h b/src/drr/colvar_UIestimator.h index 250a69687c..10805c49d5 100644 --- a/src/drr/colvar_UIestimator.h +++ b/src/drr/colvar_UIestimator.h @@ -40,47 +40,41 @@ namespace PLMD { namespace drr { -namespace UIestimator -{ +namespace UIestimator { const int Y_SIZE = 21; const int HALF_Y_SIZE = 10; const double BOLTZMANN = 0.0083144621; const int EXTENDED_X_SIZE = HALF_Y_SIZE; -class n_matrix // spare matrix, stores the distribution matrix of n(x,y) -{ +class n_matrix { // spare matrix, stores the distribution matrix of n(x,y) public: n_matrix() {} n_matrix(const std::vector & lowerboundary_p, // lowerboundary of x const std::vector & upperboundary_p, // upperboundary of const std::vector & width_p, // width of x const int y_size) // size of y, for example, ysize=7, then when x=1, the distribution of y in [-2,4] is considered - : lowerboundary(lowerboundary_p), upperboundary(upperboundary_p), width(width_p) - { + : lowerboundary(lowerboundary_p), upperboundary(upperboundary_p), width(width_p) { this->dimension = lowerboundary.size(); this->y_size = y_size; // keep in mind the internal (spare) matrix is stored in diagonal form this->y_total_size = int(pow(y_size, dimension) + 0.000001); // the range of the matrix is [lowerboundary, upperboundary] x_total_size = 1; - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { x_size.push_back(int((upperboundary[i] - lowerboundary[i]) / width[i] + 0.000001)); x_total_size *= x_size[i]; } // initialize the internal matrix matrix.reserve(x_total_size); - for (int i = 0; i < x_total_size; i++) - { + for (int i = 0; i < x_total_size; i++) { matrix.push_back(std::vector(y_total_size, 0)); } temp.resize(dimension); } - int inline get_value(const std::vector & x, const std::vector & y) - { + int inline get_value(const std::vector & x, const std::vector & y) { //if (matrix[convert_x(x)][convert_y(x, y)]!=0) //{ //std::cout< & x, const std::vector & y, const int value) - { + void inline set_value(const std::vector & x, const std::vector & y, const int value) { matrix[convert_x(x)][convert_y(x,y)] = value; } - void inline increase_value(const std::vector & x, const std::vector & y, const int value) - { + void inline increase_value(const std::vector & x, const std::vector & y, const int value) { matrix[convert_x(x)][convert_y(x,y)] += value; } @@ -113,57 +105,50 @@ class n_matrix // spare matrix, stores the distribution matrix of n(x,y) std::vector temp; // this vector is used in convert_x and convert_y to save computational resource - int convert_x(const std::vector & x) // convert real x value to its interal index - { - for (int i = 0; i < dimension; i++) - { + int convert_x(const std::vector & x) { // convert real x value to its interal index + for (int i = 0; i < dimension; i++) { temp[i] = int((x[i] - lowerboundary[i]) / width[i] + 0.000001); } int index = 0; - for (int i = 0; i < dimension; i++) - { - if (i + 1 < dimension) - { + for (int i = 0; i < dimension; i++) { + if (i + 1 < dimension) { int x_temp = 1; - for (int j = i + 1; j < dimension; j++) + for (int j = i + 1; j < dimension; j++) { x_temp *= x_size[j]; + } index += temp[i] * x_temp; - } - else + } else { index += temp[i]; + } } return index; } - int convert_y(const std::vector & x, const std::vector & y) // convert real y value to its interal index - { - for (int i = 0; i < dimension; i++) - { + int convert_y(const std::vector & x, const std::vector & y) { // convert real y value to its interal index + for (int i = 0; i < dimension; i++) { temp[i] = round((round(y[i] / width[i] + 0.000001) - round(x[i] / width[i] + 0.000001)) + (y_size - 1) / 2 + 0.000001); } int index = 0; - for (int i = 0; i < dimension; i++) - { - if (i + 1 < dimension) + for (int i = 0; i < dimension; i++) { + if (i + 1 < dimension) { index += temp[i] * int(pow(y_size, dimension - i - 1) + 0.000001); - else + } else { index += temp[i]; + } } return index; } - double round(double r) - { + double round(double r) { return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5); } }; // vector, store the sum_x, sum_x_square, count_y template -class n_vector -{ +class n_vector { public: n_vector() {} n_vector(const std::vector & lowerboundary, // lowerboundary of x @@ -171,13 +156,11 @@ class n_vector const std::vector & width_p, // width of x const int y_size, // size of y, for example, ysize=7, then when x=1, the distribution of y in [-2,4] is considered const T & default_value) // the default value of T - :width(width_p) - { + :width(width_p) { this->dimension = lowerboundary.size(); x_total_size = 1; - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { this->lowerboundary.push_back(lowerboundary[i] - (y_size - 1) / 2 * width[i] - 0.000001); this->upperboundary.push_back(upperboundary[i] + (y_size - 1) / 2 * width[i] + 0.000001); @@ -191,18 +174,15 @@ class n_vector temp.resize(dimension); } - T inline get_value(const std::vector & x) - { + T inline get_value(const std::vector & x) { return vector[convert_x(x)]; } - void inline set_value(const std::vector & x, const T & value) - { + void inline set_value(const std::vector & x, const T & value) { vector[convert_x(x)] = value; } - void inline increase_value(const std::vector & x, const T & value) - { + void inline increase_value(const std::vector & x, const T & value) { vector[convert_x(x)] += value; } private: @@ -217,32 +197,28 @@ class n_vector std::vector temp; // this vector is used in convert_x and convert_y to save computational resource - int convert_x(const std::vector & x) // convert real x value to its interal index - { - for (int i = 0; i < dimension; i++) - { + int convert_x(const std::vector & x) { // convert real x value to its interal index + for (int i = 0; i < dimension; i++) { temp[i] = int((x[i] - lowerboundary[i]) / width[i] + 0.000001); } int index = 0; - for (int i = 0; i < dimension; i++) - { - if (i + 1 < dimension) - { + for (int i = 0; i < dimension; i++) { + if (i + 1 < dimension) { int x_temp = 1; - for (int j = i + 1; j < dimension; j++) + for (int j = i + 1; j < dimension; j++) { x_temp *= x_size[j]; + } index += temp[i] * x_temp; - } - else + } else { index += temp[i]; + } } return index; } }; -class UIestimator // the implemension of UI estimator -{ +class UIestimator { // the implemension of UI estimator public: UIestimator() {} @@ -260,13 +236,11 @@ class UIestimator // the implemension of UI estimator width(width_p), krestr(krestr_p), output_filename(output_filename_p), output_freq(output_freq_p), restart(restart_p), input_filename(input_filename_p), - temperature(temperature_p) - { + temperature(temperature_p) { dimension = lowerboundary.size(); - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { sum_x.push_back(n_vector(lowerboundary, upperboundary, width, Y_SIZE, 0.0)); sum_x_square.push_back(n_vector(lowerboundary, upperboundary, width, Y_SIZE, 0.0)); @@ -283,46 +257,40 @@ class UIestimator // the implemension of UI estimator written = false; written_1D = false; - if (dimension == 1) - { + if (dimension == 1) { std::vector upperboundary_temp = upperboundary; upperboundary_temp[0] = upperboundary[0] + width[0]; oneD_pmf = n_vector(lowerboundary, upperboundary_temp, width, 1, 0.0); } - if (restart == true) - { + if (restart == true) { input_grad = n_vector >(lowerboundary, upperboundary, width, 1, std::vector(dimension, 0.0)); input_count = n_vector(lowerboundary, upperboundary, width, 1, 0); // initialize input_Grad and input_count std::vector loop_flag(dimension, 0); - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { loop_flag[i] = lowerboundary[i]; } - while (true) - { - for (int i = 0; i < dimension; i++) - { + while (true) { + for (int i = 0; i < dimension; i++) { input_grad.set_value(loop_flag, std::vector(dimension,0)); } input_count.set_value(loop_flag, 0); // iterate over any dimensions int i = dimension - 1; - while (true) - { + while (true) { loop_flag[i] += width[i]; - if (loop_flag[i] > upperboundary[i] - width[i] + 0.00001) - { + if (loop_flag[i] > upperboundary[i] - width[i] + 0.00001) { loop_flag[i] = lowerboundary[i]; i--; - if (i < 0) + if (i < 0) { goto INITIAL_LOOPEND; - } - else + } + } else { break; + } } } INITIAL_LOOPEND: @@ -333,8 +301,7 @@ class UIestimator // the implemension of UI estimator ~UIestimator() {} // called from MD engine every step - bool update(const int step, const std::vector & x, std::vector y) - { + bool update(const int step, const std::vector & x, std::vector y) { //std::cout<<"weeeee: :"< 150 && y[i] < -150) - { + if (x[i] > 150 && y[i] < -150) { //std::vector x_temp(x); //x_temp[i] -= 360; //update(7, x_temp, y); y[i] += 360; } - if (x[i] < -150 && y[i] > 150) - { + if (x[i] < -150 && y[i] > 150) { //std::vector x_temp(x); //x_temp[i] += 360; //update(7, x_temp, y); @@ -371,8 +334,9 @@ class UIestimator // the implemension of UI estimator if (x[i] < lowerboundary[i] - EXTENDED_X_SIZE * width[i] + 0.00001 || x[i] > upperboundary[i] + EXTENDED_X_SIZE * width[i] - 0.00001 \ || y[i] - x[i] < -HALF_Y_SIZE * width[i] + 0.00001 || y[i] - x[i] > HALF_Y_SIZE * width[i] - 0.00001 \ - || y[i] - lowerboundary[i] < -HALF_Y_SIZE * width[i] + 0.00001 || y[i] - upperboundary[i] > HALF_Y_SIZE * width[i] - 0.00001) + || y[i] - lowerboundary[i] < -HALF_Y_SIZE * width[i] + 0.00001 || y[i] - upperboundary[i] > HALF_Y_SIZE * width[i] - 0.00001) { return false; + } } //for (int i = 0; i < dimension; i++) @@ -381,19 +345,18 @@ class UIestimator // the implemension of UI estimator //} //std::cout< upperboundary[i] - 0.000001) // adapt colvars precision - if (x[i] < lowerboundary[i] + 0.00001 || x[i] > upperboundary[i] - 0.00001) + if (x[i] < lowerboundary[i] + 0.00001 || x[i] > upperboundary[i] - 0.00001) { return false; + } } distribution_x_y.increase_value(x, y, 1); @@ -401,8 +364,7 @@ class UIestimator // the implemension of UI estimator } // update the output_filename - void update_output_filename(const std::string& filename) - { + void update_output_filename(const std::string& filename) { output_filename = filename; } @@ -440,39 +402,34 @@ class UIestimator // the implemension of UI estimator bool written_1D; // calculate gradients from the internal variables - void calc_pmf() - { + void calc_pmf() { int norm; std::vector loop_flag(dimension, 0); - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { loop_flag[i] = lowerboundary[i] - HALF_Y_SIZE * width[i]; } - while (true) - { + while (true) { norm = count_y.get_value(loop_flag) > 0 ? count_y.get_value(loop_flag) : 1; - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { x_av[i].set_value(loop_flag, sum_x[i].get_value(loop_flag) / norm); sigma_square[i].set_value(loop_flag, sum_x_square[i].get_value(loop_flag) / norm - x_av[i].get_value(loop_flag) * x_av[i].get_value(loop_flag)); } // iterate over any dimensions int i = dimension - 1; - while (true) - { + while (true) { loop_flag[i] += width[i]; - if (loop_flag[i] > upperboundary[i] + HALF_Y_SIZE * width[i] - width[i] + 0.00001) - { + if (loop_flag[i] > upperboundary[i] + HALF_Y_SIZE * width[i] - width[i] + 0.00001) { loop_flag[i] = lowerboundary[i] - HALF_Y_SIZE * width[i]; i--; - if (i < 0) + if (i < 0) { goto LOOPEND; - } - else + } + } else { break; + } } } LOOPEND: @@ -483,55 +440,49 @@ class UIestimator // the implemension of UI estimator std::vector loop_flag_x(dimension, 0); std::vector loop_flag_y(dimension, 0); - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { loop_flag_x[i] = lowerboundary[i]; loop_flag_y[i] = loop_flag_x[i] - HALF_Y_SIZE * width[i]; } - while (true) - { + while (true) { norm = 0; - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { av[i] = 0; diff_av[i] = 0; loop_flag_y[i] = loop_flag_x[i] - HALF_Y_SIZE * width[i]; } - while (true) - { + while (true) { //std::cout<<"pppppppppppppppppppppp "< 0.00001 || sigma_square[i].get_value(loop_flag_y) < -0.00001) + for (int i = 0; i < dimension; i++) { + if (sigma_square[i].get_value(loop_flag_y) > 0.00001 || sigma_square[i].get_value(loop_flag_y) < -0.00001) { av[i] += distribution_x_y.get_value(loop_flag_x, loop_flag_y) * ( (loop_flag_x[i] + 0.5 * width[i]) - x_av[i].get_value(loop_flag_y)) / sigma_square[i].get_value(loop_flag_y); + } diff_av[i] += distribution_x_y.get_value(loop_flag_x, loop_flag_y) * (loop_flag_x[i] - loop_flag_y[i]); } // iterate over any dimensions int i = dimension - 1; - while (true) - { + while (true) { loop_flag_y[i] += width[i]; - if (loop_flag_y[i] > loop_flag_x[i] + HALF_Y_SIZE * width[i] - width[i] + 0.00001) - { + if (loop_flag_y[i] > loop_flag_x[i] + HALF_Y_SIZE * width[i] - width[i] + 0.00001) { loop_flag_y[i] = loop_flag_x[i] - HALF_Y_SIZE * width[i]; i--; - if (i < 0) + if (i < 0) { goto LOOPEND2; - } - else + } + } else { break; + } } } LOOPEND2: std::vector grad_temp(dimension, 0); - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { diff_av[i] /= (norm > 0 ? norm : 1); av[i] = BOLTZMANN * temperature * av[i] / (norm > 0 ? norm : 1); grad_temp[i] = av[i] - krestr[i] * diff_av[i]; @@ -541,27 +492,26 @@ class UIestimator // the implemension of UI estimator // iterate over any dimensions int i = dimension - 1; - while (true) - { + while (true) { loop_flag_x[i] += width[i]; - if (loop_flag_x[i] > upperboundary[i] - width[i] + 0.00001) - { + if (loop_flag_x[i] > upperboundary[i] - width[i] + 0.00001) { loop_flag_x[i] = lowerboundary[i]; i--; - if (i < 0) + if (i < 0) { goto LOOPEND3; - } - else + } + } else { break; + } } } -LOOPEND3:; +LOOPEND3: + ; } // calculate 1D pmf - void calc_1D_pmf() - { + void calc_1D_pmf() { std::vector last_position(1, 0); std::vector position(1, 0); @@ -570,33 +520,28 @@ LOOPEND3:; oneD_pmf.set_value(lowerboundary, 0); last_position = lowerboundary; - for (double i = lowerboundary[0] + width[0]; i < upperboundary[0] + 0.000001; i += width[0]) - { + for (double i = lowerboundary[0] + width[0]; i < upperboundary[0] + 0.000001; i += width[0]) { position[0] = i + 0.000001; - if (restart == false || input_count.get_value(last_position) == 0) - { + if (restart == false || input_count.get_value(last_position) == 0) { dG = oneD_pmf.get_value(last_position) + grad.get_value(last_position)[0] * width[0]; - } - else - { + } else { dG = oneD_pmf.get_value(last_position) + ((grad.get_value(last_position)[0] * count.get_value(last_position) + input_grad.get_value(last_position)[0] * input_count.get_value(last_position)) / (count.get_value(last_position) + input_count.get_value(last_position))) * width[0]; } - if (dG < min) + if (dG < min) { min = dG; + } oneD_pmf.set_value(position, dG); last_position[0] = i + 0.000001; } - for (double i = lowerboundary[0]; i < upperboundary[0] + 0.000001; i += width[0]) - { + for (double i = lowerboundary[0]; i < upperboundary[0] + 0.000001; i += width[0]) { position[0] = i + 0.000001; oneD_pmf.set_value(position, oneD_pmf.get_value(position) - min); } } // write 1D pmf - void write_1D_pmf() - { + void write_1D_pmf() { std::string pmf_filename = output_filename + ".UI.pmf"; // only for colvars module! @@ -605,8 +550,7 @@ LOOPEND3:; std::ofstream ofile_pmf(pmf_filename.c_str()); std::vector position(1, 0); - for (double i = lowerboundary[0]; i < upperboundary[0] + 0.000001; i += width[0]) - { + for (double i = lowerboundary[0]; i < upperboundary[0] + 0.000001; i += width[0]) { ofile_pmf << i << " "; position[0] = i + 0.000001; ofile_pmf << oneD_pmf.get_value(position) << std::endl; @@ -617,11 +561,9 @@ LOOPEND3:; } // write heads of the output files - void writehead(std::ofstream& os) const - { + void writehead(std::ofstream& os) const { os << "# " << dimension << std::endl; - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { os.precision(std::numeric_limits::max_digits10); os << "# " << std::fixed << lowerboundary[i] << " " << width[i] << " " << int((upperboundary[i] - lowerboundary[i]) / width[i] + 0.000001) << " " << 0 << std::endl; } @@ -685,8 +627,7 @@ LOOPEND3:; // } // write output files - void write_files() - { + void write_files() { std::string grad_filename = output_filename + ".UI.grad"; std::string hist_filename = output_filename + ".UI.hist.grad"; std::string count_filename = output_filename + ".UI.count"; @@ -704,47 +645,39 @@ LOOPEND3:; writehead(ofile_hist); writehead(ofile_count); - if (dimension == 1) - { + if (dimension == 1) { calc_1D_pmf(); write_1D_pmf(); } std::vector loop_flag(dimension, 0); - for (int i = 0; i < dimension; i++) - { + for (int i = 0; i < dimension; i++) { loop_flag[i] = lowerboundary[i]; } - while (true) - { - for (int i = 0; i < dimension; i++) - { + while (true) { + for (int i = 0; i < dimension; i++) { ofile << std::fixed << std::setprecision(6) << loop_flag[i] + 0.5 * width[i] << " "; ofile_hist << std::fixed << std::setprecision(6) << loop_flag[i] + 0.5 * width[i] << " "; ofile_count << std::fixed << std::setprecision(6) << loop_flag[i] + 0.5 * width[i] << " "; } - if (restart == false) - { - for (int i = 0; i < dimension; i++) - { + if (restart == false) { + for (int i = 0; i < dimension; i++) { ofile << std::fixed << std::setprecision(6) << grad.get_value(loop_flag)[i] << " "; ofile_hist << std::fixed << std::setprecision(6) << grad.get_value(loop_flag)[i] << " "; } ofile << std::endl; ofile_hist << std::endl; ofile_count << count.get_value(loop_flag) << " " < upperboundary[i] - width[i] + 0.00001) - { + if (loop_flag[i] > upperboundary[i] - width[i] + 0.00001) { loop_flag[i] = lowerboundary[i]; i--; ofile << std::endl; ofile_hist << std::endl; ofile_count << std::endl; - if (i < 0) + if (i < 0) { goto LOOPEND4; - } - else + } + } else { break; + } } } LOOPEND4: @@ -781,8 +713,7 @@ LOOPEND3:; } // read input files - void read_inputfiles(const std::vector& input_filename) - { + void read_inputfiles(const std::vector& input_filename) { char sharp; double nothing; int dimension_temp; @@ -791,8 +722,7 @@ LOOPEND3:; std::vector position_temp(dimension, 0); std::vector grad_temp(dimension, 0); int count_temp = 0; - for (unsigned int i = 0; i < input_filename.size(); i++) - { + for (unsigned int i = 0; i < input_filename.size(); i++) { int size = 1, size_temp = 0; std::string count_filename = input_filename[i] + ".UI.count"; @@ -804,38 +734,30 @@ LOOPEND3:; count_file >> sharp >> dimension_temp; grad_file >> sharp >> dimension_temp; - for (int j = 0; j < dimension; j++) - { + for (int j = 0; j < dimension; j++) { count_file >> sharp >> nothing >> nothing >> size_temp >> nothing; grad_file >> sharp >> nothing >> nothing >> nothing >> nothing; size *= size_temp; } - for (int j = 0; j < size; j++) - { - do - { - for (int k = 0; k < dimension; k++) - { + for (int j = 0; j < size; j++) { + do { + for (int k = 0; k < dimension; k++) { count_file >> position_temp[k]; grad_file >> nothing; } - for (int l = 0; l < dimension; l++) - { + for (int l = 0; l < dimension; l++) { grad_file >> grad_temp[l]; } count_file >> count_temp; - } - while (position_temp[i] < lowerboundary[i] - 0.000001 || position_temp[i] > upperboundary[i] + 0.000001); + } while (position_temp[i] < lowerboundary[i] - 0.000001 || position_temp[i] > upperboundary[i] + 0.000001); - if (count_temp == 0) - { + if (count_temp == 0) { continue; } - for (int m = 0; m < dimension; m++) - { + for (int m = 0; m < dimension; m++) { grad_temp[m] = (grad_temp[m] * count_temp + input_grad.get_value(position_temp)[m] * input_count.get_value(position_temp)) / (count_temp + input_count.get_value(position_temp)); } input_grad.set_value(position_temp, grad_temp); diff --git a/src/drr/drrtool.cpp b/src/drr/drrtool.cpp index 0de438af11..964d78375e 100644 --- a/src/drr/drrtool.cpp +++ b/src/drr/drrtool.cpp @@ -78,7 +78,9 @@ class drrtool : public CLTool { void extractdrr(const vector &filename); void mergewindows(const vector &filename, string outputname); void calcDivergence(const vector &filename, const string &fmt); - string description() const { return "Extract or merge the drrstate files."; } + string description() const { + return "Extract or merge the drrstate files."; + } private: bool verbosity; @@ -164,11 +166,13 @@ void drrtool::extractdrr(const vector &filename) { } string outputname(filename[j]); outputname.resize(outputname.length() - suffix.length()); - if (verbosity) + if (verbosity) { std::cout << "Writing ABF(naive) estimator files..." << '\n'; + } abfgrid.writeAll(outputname); - if (verbosity) + if (verbosity) { std::cout << "Writing CZAR estimator files..." << '\n'; + } czarestimator.writeAll(outputname); czarestimator.writeZCountZGrad(outputname); } @@ -211,9 +215,13 @@ void drrtool::mergewindows(const vector &filename, string outputname) { // Generate new file name for merged grad and count vector tmp_name = filename; std::transform(std::begin(tmp_name), std::end(tmp_name), std::begin(tmp_name), - [&](const string & s) {return s.substr(0, s.find(suffix));}); + [&](const string & s) { + return s.substr(0, s.find(suffix)); + }); outputname = std::accumulate(std::begin(tmp_name), std::end(tmp_name), string(""), - [](const string & a, const string & b) {return a + b + "+";}); + [](const string & a, const string & b) { + return a + b + "+"; + }); outputname.resize(outputname.size() - 1); std::cerr << "You have not specified an output filename for the merged" << " result, so the default name \"" + outputname diff --git a/src/eds/EDS.cpp b/src/eds/EDS.cpp index 6b86d470d9..c93ef9bbe6 100644 --- a/src/eds/EDS.cpp +++ b/src/eds/EDS.cpp @@ -31,10 +31,8 @@ using namespace bias; // namespace is lowercase to match // module names being all lowercase -namespace PLMD -{ -namespace eds -{ +namespace PLMD { +namespace eds { //+PLUMEDOC EDSMOD_BIAS EDS /* @@ -192,8 +190,7 @@ eds: EDS ARG=d1 CENTER=2.0 TEMP=1.0 IN_RESTART=restart.eds FREEZE MEAN */ //+ENDPLUMEDOC -class EDS : public Bias -{ +class EDS : public Bias { private: /*We will get this and store it once, since on-the-fly changing number of CVs will be fatal*/ @@ -278,8 +275,7 @@ class EDS : public Bias PLUMED_REGISTER_ACTION(EDS, "EDS") -void EDS::registerKeywords(Keywords &keys) -{ +void EDS::registerKeywords(Keywords &keys) { Bias::registerKeywords(keys); keys.use("ARG"); keys.add("optional", "CENTER", "The desired centers (equilibrium values) which will be sought during the adaptive linear biasing. This is for fixed centers"); @@ -359,8 +355,7 @@ EDS::EDS(const ActionOptions &ao) : PLUMED_BIAS_INIT(ao), pseudo_virial_sum_(0.0), max_logweight_(0.0), wsum_(0.0), - value_force2_(NULL) -{ + value_force2_(NULL) { double temp = -1.0; bool b_mean = false; std::vector wvalues; @@ -369,8 +364,7 @@ EDS::EDS(const ActionOptions &ao) : PLUMED_BIAS_INIT(ao), componentIsNotPeriodic("force2"); value_force2_ = getPntrToComponent("force2"); - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { std::string comp = getPntrToArgument(i)->getName() + "_coupling"; addComponent(comp); componentIsNotPeriodic(comp); @@ -408,70 +402,60 @@ EDS::EDS(const ActionOptions &ao) : PLUMED_BIAS_INIT(ao), * 3. Reading Restarts */ - if (center_.size() == 0) - { - if (center_values_.size() == 0) + if (center_.size() == 0) { + if (center_values_.size() == 0) { error("Must set either CENTER or CENTER_ARG"); - else if (center_values_.size() != ncvs_) + } else if (center_values_.size() != ncvs_) { error("CENTER_ARG must contain the same number of variables as ARG"); + } b_c_values_ = true; center_.resize(ncvs_); log.printf(" EDS will use possibly varying centers\n"); - } - else - { - if (center_.size() != ncvs_) + } else { + if (center_.size() != ncvs_) { error("Must have same number of CENTER arguments as ARG arguments"); - else if (center_values_.size() != 0) + } else if (center_values_.size() != 0) { error("You can only set CENTER or CENTER_ARG. Not both"); + } b_c_values_ = false; log.printf(" EDS will use fixed centers\n"); } // check for weights - if (wvalues.size() > 1) - { + if (wvalues.size() > 1) { error("LOGWEIGHTS can only support one weight set. Please only pass one action"); - } - else if (wvalues.size() == 1) - { + } else if (wvalues.size() == 1) { logweights_ = dynamic_cast(wvalues[0]->getPntrToAction()); b_weights_ = true; } log.printf(" setting scaling:"); - if (scale_.size() > 0 && scale_.size() < ncvs_) - { + if (scale_.size() > 0 && scale_.size() < ncvs_) { error("the number of BIAS_SCALE values be the same as number of CVs"); - } - else if (scale_.size() == 0 && b_c_values_) - { + } else if (scale_.size() == 0 && b_c_values_) { log.printf(" Setting SCALE to be 1 for all CVs\n"); scale_.resize(ncvs_); - for (unsigned int i = 0; i < ncvs_; ++i) + for (unsigned int i = 0; i < ncvs_; ++i) { scale_[i] = 1; - } - else if (scale_.size() == 0 && !b_c_values_) - { + } + } else if (scale_.size() == 0 && !b_c_values_) { log.printf(" (default) "); scale_.resize(ncvs_); - for (unsigned int i = 0; i < scale_.size(); ++i) - { - if (center_[i] == 0) + for (unsigned int i = 0; i < scale_.size(); ++i) { + if (center_[i] == 0) { error("BIAS_SCALE parameter has been set to CENTER value of 0 (as is default). This will divide by 0, so giving up. See doc for EDS bias"); + } scale_[i] = center_[i]; } - } - else - { - for (unsigned int i = 0; i < scale_.size(); ++i) + } else { + for (unsigned int i = 0; i < scale_.size(); ++i) { log.printf(" %f", scale_[i]); + } } log.printf("\n"); - if (b_lm_) - { + if (b_lm_) { log.printf(" EDS will perform Levenberg-Marquardt minimization with mixing parameter = %f\n", lm_mixing_par_); differences_.resize(ncvs_); alpha_vector_.resize(ncvs_); @@ -481,36 +465,34 @@ EDS::EDS(const ActionOptions &ao) : PLUMED_BIAS_INIT(ao), lm_inv_.resize(ncvs_, ncvs_); covar2_ *= 0; lm_inv_ *= 0; - if (multi_prop_ != 1) + if (multi_prop_ != 1) { log.printf(" WARNING - doing LM minimization but MULTI_PROP!=1\n"); - } - else if (b_covar_) - { + } + } else if (b_covar_) { log.printf(" EDS will utilize covariance matrix for update steps\n"); covar_.resize(ncvs_, ncvs_); - } - else - { + } else { log.printf(" EDS will utilize variance for update steps\n"); ssds_.resize(ncvs_); } b_virial_ = virial_scaling_; - if (b_virial_) - { - if (ncvs_ == 1) + if (b_virial_) { + if (ncvs_ == 1) { error("Minimizing the virial is only valid with multiply correlated collective variables."); + } // check that the CVs can be used to compute pseudo-virial log.printf(" EDS will compute virials of CVs and penalize with scale of %f. Checking CVs are valid...", virial_scaling_); - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { auto a = dynamic_cast(getPntrToArgument(i)->getPntrToAction()); - if (!a) + if (!a) { error("If using VIRIAL keyword, you must have normal CVs as arguments to EDS. Offending action: " + getPntrToArgument(i)->getPntrToAction()->getName()); + } // cppcheck-suppress nullPointerRedundantCheck - if (!(a->getPbc().isOrthorombic())) + if (!(a->getPbc().isOrthorombic())) { log.printf(" WARNING: EDS Virial should have a orthorombic cell\n"); + } } log.printf("done.\n"); addComponent("pressure"); @@ -518,23 +500,18 @@ EDS::EDS(const ActionOptions &ao) : PLUMED_BIAS_INIT(ao), value_pressure_ = getPntrToComponent("pressure"); } - if (b_mean && !b_freeze_) - { + if (b_mean && !b_freeze_) { error("EDS keyword MEAN can only be used along with keyword FREEZE"); } - if (in_restart_name_ != "") - { + if (in_restart_name_ != "") { b_restart_ = true; log.printf(" reading simulation information from file: %s\n", in_restart_name_.c_str()); readInRestart(b_mean); - } - else - { + } else { // in driver, this results in kbt of 0 - if (kbt_ == 0) - { + if (kbt_ == 0) { error(" Unable to determine valid kBT. " "Could be because you are runnning from driver or MD didn't give temperature.\n" "Consider setting temperature manually with the TEMP keyword."); @@ -544,19 +521,14 @@ EDS::EDS(const ActionOptions &ao) : PLUMED_BIAS_INIT(ao), log.printf(" kBT = %f\n", kbt_); log.printf(" Updating every %i steps\n", update_period_); - if (!b_c_values_) - { + if (!b_c_values_) { log.printf(" with centers:"); - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { log.printf(" %f ", center_[i]); } - } - else - { + } else { log.printf(" with actions centers:"); - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { log.printf(" %s ", center_values_[i]->getName().c_str()); // add dependency on these actions addDependency(center_values_[i]->getPntrToAction()); @@ -564,8 +536,7 @@ EDS::EDS(const ActionOptions &ao) : PLUMED_BIAS_INIT(ao), } log.printf("\n with initial ranges / rates:\n"); - for (unsigned int i = 0; i < max_coupling_range_.size(); ++i) - { + for (unsigned int i = 0; i < max_coupling_range_.size(); ++i) { // this is just an empirical guess. Bigger range, bigger grads. Less frequent updates, bigger changes // // using the current maxing out scheme, max_coupling_range is the biggest step that can be taken in any given interval @@ -574,79 +545,68 @@ EDS::EDS(const ActionOptions &ao) : PLUMED_BIAS_INIT(ao), log.printf(" %f / %f\n", max_coupling_range_[i], max_coupling_grad_[i]); } - if (seed_ > 0) - { + if (seed_ > 0) { log.printf(" setting random seed = %i", seed_); rand_.setSeed(seed_); } for (unsigned int i = 0; i < ncvs_; ++i) - if (target_coupling_[i] != 0.0) + if (target_coupling_[i] != 0.0) { b_adaptive_ = false; + } - if (!b_adaptive_) - { - if (b_ramp_) - { + if (!b_adaptive_) { + if (b_ramp_) { log.printf(" ramping up coupling constants over %i steps\n", update_period_); } log.printf(" with starting coupling constants"); - for (unsigned int i = 0; i < set_coupling_.size(); ++i) + for (unsigned int i = 0; i < set_coupling_.size(); ++i) { log.printf(" %f", set_coupling_[i]); + } log.printf("\n"); log.printf(" and final coupling constants"); - for (unsigned int i = 0; i < target_coupling_.size(); ++i) + for (unsigned int i = 0; i < target_coupling_.size(); ++i) { log.printf(" %f", target_coupling_[i]); + } log.printf("\n"); } // now do setup - if (b_ramp_) - { + if (b_ramp_) { update_period_ *= -1; } - for (unsigned int i = 0; i < set_coupling_.size(); ++i) + for (unsigned int i = 0; i < set_coupling_.size(); ++i) { current_coupling_[i] = set_coupling_[i]; + } // if b_adaptive_, then first half will be used for equilibrating and second half for statistics - if (update_period_ > 0) - { + if (update_period_ > 0) { update_period_ /= 2; } } - if (b_freeze_) - { + if (b_freeze_) { b_adaptive_ = false; update_period_ = 0; - if (b_mean) - { + if (b_mean) { log.printf(" freezing bias at the average level from the restart file\n"); - } - else - { + } else { log.printf(" freezing bias at current level\n"); } } - if (multi_prop_ == -1.0) - { + if (multi_prop_ == -1.0) { log.printf(" Will update each dimension stochastically with probability 1 / number of CVs\n"); multi_prop_ = 1.0 / ncvs_; - } - else if (multi_prop_ > 0 && multi_prop_ <= 1.0) - { + } else if (multi_prop_ > 0 && multi_prop_ <= 1.0) { log.printf(" Will update each dimension stochastically with probability %f\n", multi_prop_); - } - else - { + } else { error(" MULTI_PROP must be between 0 and 1\n"); } - if (out_restart_name_.length() > 0) - { + if (out_restart_name_.length() > 0) { log.printf(" writing restart information every %i steps to file %s with format %s\n", abs(update_period_), out_restart_name_.c_str(), fmt_.c_str()); b_write_restart_ = true; setupOutRestart(); @@ -656,53 +616,39 @@ EDS::EDS(const ActionOptions &ao) : PLUMED_BIAS_INIT(ao), log << " Bibliography " << plumed.cite("G. M. Hocky, T. Dannenhoffer-Lafage, G. A. Voth, J. Chem. Theory Comput. 13 (9), 4593-4603 (2017)") << "\n"; } -void EDS::readInRestart(const bool b_mean) -{ +void EDS::readInRestart(const bool b_mean) { int adaptive_i = 0; in_restart_.open(in_restart_name_); - if (in_restart_.FieldExist("kbt")) - { + if (in_restart_.FieldExist("kbt")) { in_restart_.scanField("kbt", kbt_); - } - else - { + } else { error("No field 'kbt' in restart file"); } log.printf(" with kBT = %f\n", kbt_); - if (in_restart_.FieldExist("update_period")) - { + if (in_restart_.FieldExist("update_period")) { in_restart_.scanField("update_period", update_period_); - } - else - { + } else { error("No field 'update_period' in restart file"); } log.printf(" Updating every %i steps\n", update_period_); - if (in_restart_.FieldExist("adaptive")) - { + if (in_restart_.FieldExist("adaptive")) { // note, no version of scanField for boolean in_restart_.scanField("adaptive", adaptive_i); - } - else - { + } else { error("No field 'adaptive' in restart file"); } b_adaptive_ = bool(adaptive_i); - if (in_restart_.FieldExist("seed")) - { + if (in_restart_.FieldExist("seed")) { in_restart_.scanField("seed", seed_); - } - else - { + } else { error("No field 'seed' in restart file"); } - if (seed_ > 0) - { + if (seed_ > 0) { log.printf(" setting random seed = %i", seed_); rand_.setSeed(seed_); } @@ -712,11 +658,9 @@ void EDS::readInRestart(const bool b_mean) unsigned int N = 0; std::string cv_name; - while (in_restart_.scanField("time", time)) - { + while (in_restart_.scanField("time", time)) { - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { cv_name = getPntrToArgument(i)->getName(); in_restart_.scanField(cv_name + "_center", set_coupling_[i]); in_restart_.scanField(cv_name + "_set", set_coupling_[i]); @@ -726,12 +670,12 @@ void EDS::readInRestart(const bool b_mean) in_restart_.scanField(cv_name + "_maxgrad", max_coupling_grad_[i]); in_restart_.scanField(cv_name + "_accum", coupling_accum_[i]); in_restart_.scanField(cv_name + "_mean", means_[i]); - if (in_restart_.FieldExist(cv_name + "_pseudovirial")) - { - if (b_virial_) + if (in_restart_.FieldExist(cv_name + "_pseudovirial")) { + if (b_virial_) { in_restart_.scanField(cv_name + "_pseudovirial", pseudo_virial_[i]); - else // discard the field + } else { // discard the field in_restart_.scanField(cv_name + "_pseudovirial", tmp); + } } // unused due to difference between covar/nocovar in_restart_.scanField(cv_name + "_std", tmp); @@ -744,54 +688,53 @@ void EDS::readInRestart(const bool b_mean) } log.printf(" with centers:"); - for (unsigned int i = 0; i < center_.size(); ++i) - { + for (unsigned int i = 0; i < center_.size(); ++i) { log.printf(" %f", center_[i]); } log.printf("\n and scaling:"); - for (unsigned int i = 0; i < scale_.size(); ++i) - { + for (unsigned int i = 0; i < scale_.size(); ++i) { log.printf(" %f", scale_[i]); } log.printf("\n with initial ranges / rates:\n"); - for (unsigned int i = 0; i < max_coupling_range_.size(); ++i) - { + for (unsigned int i = 0; i < max_coupling_range_.size(); ++i) { log.printf(" %f / %f\n", max_coupling_range_[i], max_coupling_grad_[i]); } - if (!b_adaptive_ && update_period_ < 0) - { + if (!b_adaptive_ && update_period_ < 0) { log.printf(" ramping up coupling constants over %i steps\n", -update_period_); } - if (b_mean) - { + if (b_mean) { log.printf("Loaded in averages for coupling constants...\n"); - for (unsigned int i = 0; i < current_coupling_.size(); ++i) + for (unsigned int i = 0; i < current_coupling_.size(); ++i) { current_coupling_[i] = avg_bias[i] / N; - for (unsigned int i = 0; i < current_coupling_.size(); ++i) + } + for (unsigned int i = 0; i < current_coupling_.size(); ++i) { set_coupling_[i] = avg_bias[i] / N; + } } log.printf(" with current coupling constants:\n "); - for (unsigned int i = 0; i < current_coupling_.size(); ++i) + for (unsigned int i = 0; i < current_coupling_.size(); ++i) { log.printf(" %f", current_coupling_[i]); + } log.printf("\n"); log.printf(" with initial coupling constants:\n "); - for (unsigned int i = 0; i < set_coupling_.size(); ++i) + for (unsigned int i = 0; i < set_coupling_.size(); ++i) { log.printf(" %f", set_coupling_[i]); + } log.printf("\n"); log.printf(" and final coupling constants:\n "); - for (unsigned int i = 0; i < target_coupling_.size(); ++i) + for (unsigned int i = 0; i < target_coupling_.size(); ++i) { log.printf(" %f", target_coupling_[i]); + } log.printf("\n"); in_restart_.close(); } -void EDS::setupOutRestart() -{ +void EDS::setupOutRestart() { out_restart_.link(*this); out_restart_.fmtField(fmt_); out_restart_.open(out_restart_name_); @@ -803,13 +746,11 @@ void EDS::setupOutRestart() out_restart_.addConstantField("kbt").printField("kbt", kbt_); } -void EDS::writeOutRestart() -{ +void EDS::writeOutRestart() { std::string cv_name; out_restart_.printField("time", getTimeStep() * getStep()); - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { cv_name = getPntrToArgument(i)->getName(); out_restart_.printField(cv_name + "_center", center_[i]); out_restart_.printField(cv_name + "_set", set_coupling_[i]); @@ -819,34 +760,34 @@ void EDS::writeOutRestart() out_restart_.printField(cv_name + "_maxgrad", max_coupling_grad_[i]); out_restart_.printField(cv_name + "_accum", coupling_accum_[i]); out_restart_.printField(cv_name + "_mean", means_[i]); - if (b_virial_) + if (b_virial_) { out_restart_.printField(cv_name + "_pseudovirial", pseudo_virial_[i]); - if (!b_covar_ && !b_lm_) + } + if (!b_covar_ && !b_lm_) { out_restart_.printField(cv_name + "_std", ssds_[i] / (fmax(1, update_calls_ - 1))); - else + } else { out_restart_.printField(cv_name + "_std", covar_(i, i) / (fmax(1, update_calls_ - 1))); + } } out_restart_.printField(); } -void EDS::calculate() -{ +void EDS::calculate() { // get center values from action if necessary if (b_c_values_) - for (unsigned int i = 0; i < ncvs_; ++i) + for (unsigned int i = 0; i < ncvs_; ++i) { center_[i] = center_values_[i]->get(); + } apply_bias(); } -void EDS::apply_bias() -{ +void EDS::apply_bias() { // Compute linear force as in "restraint" double ene = 0, totf2 = 0, cv, m, f; - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { cv = difference(i, center_[i], getArgument(i)); m = current_coupling_[i]; f = -m; @@ -859,17 +800,14 @@ void EDS::apply_bias() value_force2_->set(totf2); } -void EDS::update_statistics() -{ +void EDS::update_statistics() { double s, N, w = 1.0; std::vector deltas(ncvs_); // update weight max, if necessary - if (b_weights_) - { + if (b_weights_) { w = logweights_->getLogWeight(); - if (max_logweight_ < w) - { + if (max_logweight_ < w) { // we have new max. Need to shift existing values wsum_ *= exp(max_logweight_ - w); max_logweight_ = w; @@ -878,27 +816,22 @@ void EDS::update_statistics() w = exp(w - max_logweight_); wsum_ += w; N = wsum_; - } - else - { + } else { N = fmax(1, update_calls_); } // Welford, West, and Hanso online variance method // with weights (default = 1.0) - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { deltas[i] = difference(i, means_[i], getArgument(i)) * w; means_[i] += deltas[i] / N; - if (!b_covar_ && !b_lm_) + if (!b_covar_ && !b_lm_) { ssds_[i] += deltas[i] * difference(i, means_[i], getArgument(i)); + } } - if (b_covar_ || b_lm_) - { - for (unsigned int i = 0; i < ncvs_; ++i) - { - for (unsigned int j = i; j < ncvs_; ++j) - { + if (b_covar_ || b_lm_) { + for (unsigned int i = 0; i < ncvs_; ++i) { + for (unsigned int j = i; j < ncvs_; ++j) { s = (N - 1) * deltas[i] * deltas[j] / N / N - covar_(i, j) / N; covar_(i, j) += s; // do this so we don't double count @@ -906,43 +839,41 @@ void EDS::update_statistics() } } } - if (b_virial_) + if (b_virial_) { update_pseudo_virial(); + } } -void EDS::reset_statistics() -{ - for (unsigned int i = 0; i < ncvs_; ++i) - { +void EDS::reset_statistics() { + for (unsigned int i = 0; i < ncvs_; ++i) { means_[i] = 0; - if (!b_covar_ && !b_lm_) + if (!b_covar_ && !b_lm_) { ssds_[i] = 0; + } } if (b_covar_ || b_lm_) for (unsigned int i = 0; i < ncvs_; ++i) - for (unsigned int j = 0; j < ncvs_; ++j) + for (unsigned int j = 0; j < ncvs_; ++j) { covar_(i, j) = 0; - if (b_virial_) - { - for (unsigned int i = 0; i < ncvs_; ++i) + } + if (b_virial_) { + for (unsigned int i = 0; i < ncvs_; ++i) { pseudo_virial_[i] = 0; + } pseudo_virial_sum_ = 0; } - if (b_weights_) - { + if (b_weights_) { wsum_ = 0; max_logweight_ = 0; } } -void EDS::calc_lm_step_size() -{ +void EDS::calc_lm_step_size() { // calulcate step size // uses scale here, which by default is center mult(covar_, covar_, covar2_); - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { differences_[i] = difference(i, center_[i], means_[i]); covar2_[i][i] += lm_mixing_par_ * covar2_[i][i]; } @@ -952,51 +883,46 @@ void EDS::calc_lm_step_size() Invert(covar2_, lm_inv_); mult(lm_inv_, alpha_vector_, alpha_vector_2_); - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { step_size_[i] = 2 * alpha_vector_2_[i] / kbt_ / scale_[i]; } } -void EDS::calc_covar_step_size() -{ +void EDS::calc_covar_step_size() { // calulcate step size // uses scale here, which by default is center double tmp; - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { tmp = 0; - for (unsigned int j = 0; j < ncvs_; ++j) + for (unsigned int j = 0; j < ncvs_; ++j) { tmp += difference(i, center_[i], means_[i]) * covar_(i, j); + } step_size_[i] = 2 * tmp / kbt_ / scale_[i] * update_calls_ / fmax(1, update_calls_ - 1); } } -void EDS::calc_ssd_step_size() -{ +void EDS::calc_ssd_step_size() { double tmp; - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { tmp = 2. * difference(i, center_[i], means_[i]) * ssds_[i] / fmax(1, update_calls_ - 1); step_size_[i] = tmp / kbt_ / scale_[i]; } } -void EDS::update_pseudo_virial() -{ +void EDS::update_pseudo_virial() { // We want to compute the bias force on each atom times the position // of the atoms. double p, netp = 0, netpv = 0; double volume = 0; - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { // checked in setup to ensure this cast is valid. ActionAtomistic *cv = dynamic_cast(getPntrToArgument(i)->getPntrToAction()); Tensor v(cv->getVirial()); Tensor box(cv->getBox()); const unsigned int natoms = cv->getNumberOfAtoms(); - if (!volume) + if (!volume) { volume = box.determinant(); + } // pressure contribution is -dBias / dV // dBias / dV = alpha / w * dCV / dV @@ -1014,10 +940,11 @@ void EDS::update_pseudo_virial() p *= (volume) / (kbt_ * natoms); // compute running mean of scaled - if (set_coupling_[i] != 0) + if (set_coupling_[i] != 0) { pseudo_virial_[i] = (p - pseudo_virial_[i]) / (fmax(1, update_calls_)); - else + } else { pseudo_virial_[i] = 0; + } // update net pressure netpv += pseudo_virial_[i]; } @@ -1026,35 +953,35 @@ void EDS::update_pseudo_virial() pseudo_virial_sum_ = netpv; } -void EDS::update_bias() -{ +void EDS::update_bias() { log.flush(); - if (b_lm_) + if (b_lm_) { calc_lm_step_size(); - else if (b_covar_) + } else if (b_covar_) { calc_covar_step_size(); - else + } else { calc_ssd_step_size(); + } - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { // multidimesional stochastic step - if (ncvs_ == 1 || (rand_.RandU01() < (multi_prop_))) - { + if (ncvs_ == 1 || (rand_.RandU01() < (multi_prop_))) { - if (b_virial_) - { + if (b_virial_) { // apply virial regularization // P * dP/dcoupling // coupling is already included in virial term due to plumed propogating from bias to forces // thus we need to divide by it to get the derivative (since force is linear in coupling) if (fabs(set_coupling_[i]) > 0.000000001) // my heuristic for if EDS has started to prevent / 0 // scale^2 here is to align units + { step_size_[i] -= 2 * scale_[i] * scale_[i] * virial_scaling_ * pseudo_virial_sum_ * pseudo_virial_sum_ / set_coupling_[i]; + } } - if (step_size_[i] == 0) + if (step_size_[i] == 0) { continue; + } // clip gradient step_size_[i] = copysign(fmin(fabs(step_size_[i]), max_coupling_grad_[i]), step_size_[i]); @@ -1064,9 +991,7 @@ void EDS::update_bias() // no negative sign because it's in step_size set_coupling_[i] += step_size_[i] * max_coupling_range_[i] / sqrt(coupling_accum_[i]); coupling_rate_[i] = (set_coupling_[i] - current_coupling_[i]) / update_period_; - } - else - { + } else { // do not change the bias coupling_rate_[i] = 0; } @@ -1076,59 +1001,51 @@ void EDS::update_bias() reset_statistics(); } -void EDS::update() -{ +void EDS::update() { // adjust parameters according to EDS recipe update_calls_++; // if we aren't wating for the bias to equilibrate, set flag to collect data // want statistics before writing restart - if (!b_equil_ && update_period_ > 0) + if (!b_equil_ && update_period_ > 0) { update_statistics(); + } // write restart with correct statistics before bias update // check if we're ramping or doing normal updates and then restart if needed. The ramping check // is complicated because we could be frozen, finished ramping or not ramping. // The + 2 is so we have an extra line showing that the bias isn't changing (for my sanity and yours) - if (b_write_restart_) - { + if (b_write_restart_) { if (getStep() == 0 || ((update_period_ < 0 && !b_freeze_ && update_calls_ <= fabs(update_period_) + 2) || - (update_period_ > 0 && update_calls_ % update_period_ == 0))) + (update_period_ > 0 && update_calls_ % update_period_ == 0))) { writeOutRestart(); + } } int b_finished_equil_flag = 1; // assume forces already applied and saved // are we ramping to a constant value and not done equilibrating? - if (update_period_ < 0) - { - if (update_calls_ <= fabs(update_period_) && !b_freeze_) - { - for (unsigned int i = 0; i < ncvs_; ++i) + if (update_period_ < 0) { + if (update_calls_ <= fabs(update_period_) && !b_freeze_) { + for (unsigned int i = 0; i < ncvs_; ++i) { current_coupling_[i] += (target_coupling_[i] - set_coupling_[i]) / fabs(update_period_); + } } // make sure we don't reset update calls b_finished_equil_flag = 0; - } - else if (update_period_ == 0) - { // do we have a no-update case? + } else if (update_period_ == 0) { + // do we have a no-update case? // not updating // pass - } - else if (b_equil_) - { + } else if (b_equil_) { // equilibrating // check if we've reached the setpoint - for (unsigned int i = 0; i < ncvs_; ++i) - { - if (coupling_rate_[i] == 0 || pow(current_coupling_[i] - set_coupling_[i], 2) < pow(coupling_rate_[i], 2)) - { + for (unsigned int i = 0; i < ncvs_; ++i) { + if (coupling_rate_[i] == 0 || pow(current_coupling_[i] - set_coupling_[i], 2) < pow(coupling_rate_[i], 2)) { b_finished_equil_flag &= 1; - } - else - { + } else { current_coupling_[i] += coupling_rate_[i]; b_finished_equil_flag = 0; } @@ -1136,15 +1053,13 @@ void EDS::update() } // reduce all the flags - if (b_equil_ && b_finished_equil_flag) - { + if (b_equil_ && b_finished_equil_flag) { b_equil_ = false; update_calls_ = 0; } // Now we update coupling constant, if necessary - if (!b_equil_ && update_period_ > 0 && update_calls_ == update_period_ && !b_freeze_) - { + if (!b_equil_ && update_period_ > 0 && update_calls_ == update_period_ && !b_freeze_) { update_bias(); update_calls_ = 0; avg_coupling_count_++; @@ -1152,19 +1067,16 @@ void EDS::update() } // close update if // pass couplings out so they are accessible - for (unsigned int i = 0; i < ncvs_; ++i) - { + for (unsigned int i = 0; i < ncvs_; ++i) { out_coupling_[i]->set(current_coupling_[i]); } } -EDS::~EDS() -{ +EDS::~EDS() { out_restart_.close(); } -void EDS::turnOnDerivatives() -{ +void EDS::turnOnDerivatives() { // do nothing // this is to avoid errors triggered when a bias is used as a CV // (This is done in ExtendedLagrangian.cpp) diff --git a/src/envsim/EnvironmentSimilarity.cpp b/src/envsim/EnvironmentSimilarity.cpp index 4f67821e4d..e1cef042c6 100644 --- a/src/envsim/EnvironmentSimilarity.cpp +++ b/src/envsim/EnvironmentSimilarity.cpp @@ -219,50 +219,77 @@ void EnvironmentSimilarity::registerKeywords( Keywords& keys ) { keys.add("compulsory","LAMBDA","100","Lambda parameter. This is only used if you have more than one reference environment"); keys.add("compulsory","CUTOFF","3","how many multiples of sigma would you like to consider beyond the maximum distance in the environment"); keys.add("optional","ATOM_NAMES_FILE","PDB file with atom names for all atoms in SPECIES. Atoms in reference environments will be compared only if atom names match."); - multicolvar::MultiColvarShortcuts::shortcutKeywords( keys ); keys.needsAction("GROUP"); - keys.needsAction("DISTANCE_MATRIX"); keys.needsAction("ONES"); keys.needsAction("CONSTANT"); - keys.needsAction("CUSTOM"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); keys.needsAction("COMBINE"); + multicolvar::MultiColvarShortcuts::shortcutKeywords( keys ); + keys.needsAction("GROUP"); + keys.needsAction("DISTANCE_MATRIX"); + keys.needsAction("ONES"); + keys.needsAction("CONSTANT"); + keys.needsAction("CUSTOM"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("COMBINE"); } EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - std::string atomNamesFile; parse("ATOM_NAMES_FILE",atomNamesFile); PDB atomnamepdb; - if( !atomNamesFile.empty() && !atomnamepdb.read(atomNamesFile,usingNaturalUnits(),0.1/getUnits().getLength()) ) error("missing input file " + atomNamesFile); + ActionShortcut(ao) { + std::string atomNamesFile; + parse("ATOM_NAMES_FILE",atomNamesFile); + PDB atomnamepdb; + if( !atomNamesFile.empty() && !atomnamepdb.read(atomNamesFile,usingNaturalUnits(),0.1/getUnits().getLength()) ) { + error("missing input file " + atomNamesFile); + } - double maxdist=0; std::vector allspec(1); - std::string crystal_structure; parse("CRYSTAL_STRUCTURE", crystal_structure); + double maxdist=0; + std::vector allspec(1); + std::string crystal_structure; + parse("CRYSTAL_STRUCTURE", crystal_structure); std::vector > > environments; if( crystal_structure=="CUSTOM" ) { if( !atomNamesFile.empty() ) { - allspec[0]=atomnamepdb.getAtomName(atomnamepdb.getAtomNumbers()[0]); unsigned natoms=atomnamepdb.getPositions().size(); + allspec[0]=atomnamepdb.getAtomName(atomnamepdb.getAtomNumbers()[0]); + unsigned natoms=atomnamepdb.getPositions().size(); for(unsigned i=0; i0 ) { - PDB pdb; pdb.read(reffile,plumed.usingNaturalUnits(),0.1/plumed.getUnits().getLength()); + PDB pdb; + pdb.read(reffile,plumed.usingNaturalUnits(),0.1/plumed.getUnits().getLength()); environments.push_back( getReferenceEnvironment( pdb, allspec, maxdist ) ); log.printf(" reading %d reference vectors from %s \n", environments[0].size(), reffile.c_str() ); } else { for(unsigned int i=1;; i++) { - PDB pdb; if( !parseNumbered("REFERENCE_",i,reffile) ) break; - if( !pdb.read(reffile,usingNaturalUnits(),0.1/getUnits().getLength()) ) error("missing input file " + reffile ); + PDB pdb; + if( !parseNumbered("REFERENCE_",i,reffile) ) { + break; + } + if( !pdb.read(reffile,usingNaturalUnits(),0.1/getUnits().getLength()) ) { + error("missing input file " + reffile ); + } environments.push_back( getReferenceEnvironment( pdb, allspec, maxdist ) ); log.printf(" Reference environment %d : reading %d reference vectors from %s \n", i, environments[i-1].size(), reffile.c_str() ); } } } else { - std::vector lattice_constants; parseVector("LATTICE_CONSTANTS", lattice_constants); + std::vector lattice_constants; + parseVector("LATTICE_CONSTANTS", lattice_constants); if (crystal_structure == "FCC") { - if (lattice_constants.size() != 1) error("Number of LATTICE_CONSTANTS arguments must be one for FCC"); - environments.resize(1); environments[0].resize(12); + if (lattice_constants.size() != 1) { + error("Number of LATTICE_CONSTANTS arguments must be one for FCC"); + } + environments.resize(1); + environments[0].resize(12); environments[0][0] = std::pair( 0, Vector(+0.5,+0.5,+0.0)*lattice_constants[0] ); environments[0][1] = std::pair( 0, Vector(-0.5,-0.5,+0.0)*lattice_constants[0] ); environments[0][2] = std::pair( 0, Vector(+0.5,-0.5,+0.0)*lattice_constants[0] ); @@ -277,8 +304,11 @@ EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): environments[0][11] = std::pair( 0, Vector(+0.0,+0.5,-0.5)*lattice_constants[0] ); maxdist = std::sqrt(2)*lattice_constants[0]/2.; } else if (crystal_structure == "SC") { - if (lattice_constants.size() != 1) error("Number of LATTICE_CONSTANTS arguments must be one for SC"); - environments.resize(1); environments[0].resize(6); + if (lattice_constants.size() != 1) { + error("Number of LATTICE_CONSTANTS arguments must be one for SC"); + } + environments.resize(1); + environments[0].resize(6); environments[0][0] = std::pair( 0, Vector(+1.0,+0.0,+0.0)*lattice_constants[0] ); environments[0][1] = std::pair( 0, Vector(-1.0,+0.0,+0.0)*lattice_constants[0] ); environments[0][2] = std::pair( 0, Vector(+0.0,+1.0,+0.0)*lattice_constants[0] ); @@ -287,8 +317,11 @@ EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): environments[0][5] = std::pair( 0, Vector(+0.0,+0.0,-1.0)*lattice_constants[0] ); maxdist = lattice_constants[0]; } else if( crystal_structure == "BCC") { - if (lattice_constants.size() != 1) error("Number of LATTICE_CONSTANTS arguments must be one for BCC"); - environments.resize(1); environments[0].resize(14); + if (lattice_constants.size() != 1) { + error("Number of LATTICE_CONSTANTS arguments must be one for BCC"); + } + environments.resize(1); + environments[0].resize(14); environments[0][0] = std::pair( 0, Vector(+0.5,+0.5,+0.5)*lattice_constants[0] ); environments[0][1] = std::pair( 0, Vector(-0.5,-0.5,-0.5)*lattice_constants[0] ); environments[0][2] = std::pair( 0, Vector(-0.5,+0.5,+0.5)*lattice_constants[0] ); @@ -305,8 +338,13 @@ EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): environments[0][13] = std::pair( 0, Vector(+0.0,+0.0,-1.0)*lattice_constants[0] ); maxdist = lattice_constants[0]; } else if (crystal_structure == "HCP") { - if (lattice_constants.size() != 2) error("Number of LATTICE_CONSTANTS arguments must be two for HCP"); - environments.resize(2); environments[0].resize(12); environments[1].resize(12); double sqrt3=std::sqrt(3); + if (lattice_constants.size() != 2) { + error("Number of LATTICE_CONSTANTS arguments must be two for HCP"); + } + environments.resize(2); + environments[0].resize(12); + environments[1].resize(12); + double sqrt3=std::sqrt(3); environments[0][0] = std::pair( 0, Vector(+0.5,+sqrt3/2.0,+0.0)*lattice_constants[0] ); environments[0][1] = std::pair( 0, Vector(-0.5,+sqrt3/2.0,+0.0)*lattice_constants[0] ); environments[0][2] = std::pair( 0, Vector(+0.5,-sqrt3/2.0,+0.0)*lattice_constants[0] ); @@ -333,8 +371,12 @@ EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): environments[1][11] = std::pair( 0, Vector(+0.0,+sqrt3/3.0,+0.0)*lattice_constants[0] + Vector(+0.0,+0.0,-0.5)*lattice_constants[1] ); maxdist = lattice_constants[0]; } else if (crystal_structure == "DIAMOND") { - if (lattice_constants.size() != 1) error("Number of LATTICE_CONSTANTS arguments must be one for DIAMOND"); - environments.resize(2); environments[0].resize(4); environments[1].resize(4); + if (lattice_constants.size() != 1) { + error("Number of LATTICE_CONSTANTS arguments must be one for DIAMOND"); + } + environments.resize(2); + environments[0].resize(4); + environments[1].resize(4); environments[0][0] = std::pair( 0, Vector(+1.0,+1.0,+1.0)*lattice_constants[0]/4.0 ); environments[0][1] = std::pair( 0, Vector(-1.0,-1.0,+1.0)*lattice_constants[0]/4.0 ); environments[0][2] = std::pair( 0, Vector(+1.0,-1.0,-1.0)*lattice_constants[0]/4.0 ); @@ -344,34 +386,62 @@ EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): environments[1][2] = std::pair( 0, Vector(+1.0,+1.0,-1.0)*lattice_constants[0]/4.0 ); environments[1][3] = std::pair( 0, Vector(-1.0,-1.0,-1.0)*lattice_constants[0]/4.0 ); maxdist = std::sqrt(3)*lattice_constants[0]/4.0; - } else error( crystal_structure + " is not a valid input for keyword CRYSTAL_STRUCTURE"); + } else { + error( crystal_structure + " is not a valid input for keyword CRYSTAL_STRUCTURE"); + } } std::string matlab = getShortcutLabel() + "_cmat"; - double cutoff, sig; parse("SIGMA",sig); parse("CUTOFF",cutoff); std::string lcutoff; parse("LCUTOFF",lcutoff); - std::string sig2; Tools::convert( sig*sig, sig2 ); std::vector > funcstr(environments.size()); - std::string str_cutoff; Tools::convert( maxdist + cutoff*sig, str_cutoff ); - std::string str_natoms, xpos, ypos, zpos; Tools::convert( environments[0].size(), str_natoms ); + double cutoff, sig; + parse("SIGMA",sig); + parse("CUTOFF",cutoff); + std::string lcutoff; + parse("LCUTOFF",lcutoff); + std::string sig2; + Tools::convert( sig*sig, sig2 ); + std::vector > funcstr(environments.size()); + std::string str_cutoff; + Tools::convert( maxdist + cutoff*sig, str_cutoff ); + std::string str_natoms, xpos, ypos, zpos; + Tools::convert( environments[0].size(), str_natoms ); for(unsigned j=0; j0 ) { + funcstr[j][k] += ")"; + } else { + funcstr[j][k] ="FUNC=0"; } - if( funcstr[j][k].length()>0 ) funcstr[j][k] += ")"; else funcstr[j][k] ="FUNC=0"; } } // Create the constact matrix - std::string sp_str, specA, specB; parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); + std::string sp_str, specA, specB; + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); if( sp_str.length()>0 ) { readInputLine( matlab + ": DISTANCE_MATRIX COMPONENTS GROUP=" + sp_str + " CUTOFF=" + str_cutoff ); readInputLine( getShortcutLabel() + "_grp: GROUP ATOMS=" + sp_str ); } else { - if( specA.length()==0 ) error("no atoms were specified use SPECIES or SPECIESA+SPECIESB"); - if( specB.length()==0 ) error("no atoms were specified for SPECIESB"); + if( specA.length()==0 ) { + error("no atoms were specified use SPECIES or SPECIESA+SPECIESB"); + } + if( specB.length()==0 ) { + error("no atoms were specified for SPECIESB"); + } readInputLine( matlab + ": DISTANCE_MATRIX COMPONENTS GROUPA=" + specA + " GROUPB=" + specB + " CUTOFF=" + str_cutoff ); readInputLine( getShortcutLabel() + "_grp: GROUP ATOMS=" + specA ); } @@ -379,31 +449,47 @@ EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): // Make a vector containing all ones ActionWithValue* av = plumed.getActionSet().selectWithLabel( matlab ); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); if( allspec.size()==1 ) { readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); } else { unsigned natoms=atomnamepdb.getPositions().size(); - unsigned firstneigh=0; if( sp_str.length()==0 ) firstneigh = (av->copyOutput(0))->getShape()[0]; + unsigned firstneigh=0; + if( sp_str.length()==0 ) { + firstneigh = (av->copyOutput(0))->getShape()[0]; + } for(unsigned i=0; i1 ) { + parse("LAMBDA",lambda); + } // And now do the funcstr bit for(unsigned j=0; j1 ) readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + envargstr + " PERIODIC=NO VAR=" + varstr + " FUNC=" + maxfuncstr + ")" ); + if( funcstr.size()>1 ) { + readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + envargstr + " PERIODIC=NO VAR=" + varstr + " FUNC=" + maxfuncstr + ")" ); + } // Read in all the shortcut stuff - std::map keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); multicolvar::MultiColvarShortcuts::expandFunctions( getShortcutLabel(), getShortcutLabel(), "", keymap, this ); } std::vector > EnvironmentSimilarity::getReferenceEnvironment( const PDB& pdb, const std::vector& anames, double& maxdist ) { - unsigned natoms = pdb.getPositions().size(); std::vector > env( natoms ); + unsigned natoms = pdb.getPositions().size(); + std::vector > env( natoms ); for(unsigned i=0; i( identity, pdb.getPositions()[i] ); double dist = env[i].second.modulo(); - if( dist>maxdist ) maxdist = dist; + if( dist>maxdist ) { + maxdist = dist; + } } return env; } diff --git a/src/fisst/FISST.cpp b/src/fisst/FISST.cpp index 9d1f6038e2..c136226a86 100644 --- a/src/fisst/FISST.cpp +++ b/src/fisst/FISST.cpp @@ -220,14 +220,15 @@ FISST::FISST(const ActionOptions&ao): reset_period_(0), observable_freq_(0), kbt_(0.0), - value_force2_(NULL) -{ - if(ncvs_==0) + value_force2_(NULL) { + if(ncvs_==0) { error("Must specify at least one CV with ARG"); + } //temporary - if(ncvs_>1) + if(ncvs_>1) { error("FISST only supports using one CV right now"); + } addComponent("force2"); componentIsNotPeriodic("force2"); @@ -258,8 +259,9 @@ FISST::FISST(const ActionOptions&ao): parse("IN_RESTART",in_restart_name_); checkRead(); - if(center_.size() != ncvs_) + if(center_.size() != ncvs_) { error("Must have same number of CENTER arguments as ARG arguments"); + } if(in_restart_name_ != "") { b_restart_ = true; @@ -267,7 +269,9 @@ FISST::FISST(const ActionOptions&ao): readInRestart(); } else { - if(! kbt_ > 0.0) kbt_=getkBT(); + if(! kbt_ > 0.0) { + kbt_=getkBT(); + } //in driver, this results in kbt of 0 if(kbt_ == 0) { @@ -285,7 +289,9 @@ FISST::FISST(const ActionOptions&ao): } log.printf("\n"); observable_weight_.resize(n_interpolation_); - for(unsigned int i = 0; i0) { - if(observable_freq_==0) observable_freq_ = period_; + if(observable_freq_==0) { + observable_freq_ = period_; + } log.printf(" writing observable information every %i steps to file %s with format %s\n",observable_freq_,out_observable_name_.c_str(), fmt_.c_str()); b_write_observable_ = true; setupOutObservable(); @@ -348,11 +359,13 @@ FISST::FISST(const ActionOptions&ao): void FISST::NormalizeForceWeights() { double denom = 0.0; - for(unsigned i=0; i0) out_restart_.addConstantField("reset_period").printField("reset_period",reset_period_); + if(reset_period_>0) { + out_restart_.addConstantField("reset_period").printField("reset_period",reset_period_); + } out_restart_.addConstantField("min_force").printField("min_force",min_force_); out_restart_.addConstantField("max_force").printField("max_force",max_force_); } @@ -497,16 +522,19 @@ void FISST::writeOutObservable() { void FISST::calculate() { if(getStep() == 0 ) { - if(b_write_restart_) writeOutRestart(); - if(b_write_observable_) writeOutObservable(); + if(b_write_restart_) { + writeOutRestart(); + } + if(b_write_observable_) { + writeOutObservable(); + } } if(! b_freeze_) { if(b_restart_ && b_first_restart_sample_) { //dont' update statistics if restarting and first sample b_first_restart_sample_ = false; - } - else { + } else { update_statistics(); } } @@ -515,7 +543,9 @@ void FISST::calculate() { //check about writing restart file if(getStep()>0 && getStep()%period_==0) { - if(b_write_restart_) writeOutRestart(); + if(b_write_restart_) { + writeOutRestart(); + } } if(getStep()>0 && getStep()%observable_freq_==0) { if(b_write_observable_) { @@ -556,16 +586,14 @@ void FISST::update_statistics() { int step = getStep(); if(reset_period_>0 && step>0 && step%reset_period_==0) { n_samples_=1; - } - else { + } else { n_samples_++; } double d_n_samples = (double)n_samples_; for(unsigned int i = 0; i < ncvs_; ++i) { double Q_i = difference(i, center_[i], getArgument(i)); - for(unsigned int j=0; j getGridCoordinateNames() const override ; - void performTask( const unsigned& current, MultiValue& myvals ) const override { plumed_error(); } + void performTask( const unsigned& current, MultiValue& myvals ) const override { + plumed_error(); + } void calculate() override ; }; PLUMED_REGISTER_ACTION(FourierTransform,"FOURIER_TRANSFORM") void FourierTransform::registerKeywords( Keywords& keys ) { - ActionWithGrid::registerKeywords( keys ); keys.use("ARG"); + ActionWithGrid::registerKeywords( keys ); + keys.use("ARG"); keys.add("optional","FT_TYPE","choose what kind of data you want as output on the grid. Possible values are: ABS = compute the complex modulus of Fourier coefficients (DEFAULT); NORM = compute the norm (i.e. ABS^2) of Fourier coefficients; COMPLEX = store the FFTW complex output on the grid (as a vector)."); keys.add("compulsory","FOURIER_PARAMETERS","default","what kind of normalization is applied to the output and if the Fourier transform in FORWARD or BACKWARD. This keyword takes the form FOURIER_PARAMETERS=A,B, where A and B can be 0, 1 or -1. The default values are A=1 (no normalization at all) and B=1 (forward FFT). Other possible choices for A are: " "A=-1: normalize by the number of data, " @@ -103,9 +108,10 @@ FourierTransform::FourierTransform(const ActionOptions&ao): firsttime(true), real_output(true), store_norm(false), - fourier_params(2) -{ - if( getPntrToArgument(0)->getRank()!=2 ) error("fourier transform currently only works with two dimensional grids"); + fourier_params(2) { + if( getPntrToArgument(0)->getRank()!=2 ) { + error("fourier transform currently only works with two dimensional grids"); + } // Get the type of FT parse("FT_TYPE",output_type); @@ -119,19 +125,26 @@ FourierTransform::FourierTransform(const ActionOptions&ao): } else if ( output_type=="COMPLEX" || output_type=="complex" ) { log<<" keyword FT_TYPE is '"<< output_type <<"' : output grid will contain the COMPLEX Fourier coefficients\n"; real_output=false; - } else error("keyword FT_TYPE unrecognized!"); + } else { + error("keyword FT_TYPE unrecognized!"); + } // Normalize output? - std::string params_str; parse("FOURIER_PARAMETERS",params_str); + std::string params_str; + parse("FOURIER_PARAMETERS",params_str); if (params_str=="default") { fourier_params.assign( fourier_params.size(), 1 ); log.printf(" default values of Fourier parameters A=%i, B=%i : the output will NOT be normalized and BACKWARD Fourier transform is computed \n", fourier_params[0],fourier_params[1]); } else { std::vector fourier_str = Tools::getWords(params_str, "\t\n ,"); - if (fourier_str.size()>2) error("FOURIER_PARAMETERS can take just two values"); + if (fourier_str.size()>2) { + error("FOURIER_PARAMETERS can take just two values"); + } for (unsigned i=0; i1 || fourier_params[i]<-1) error("values accepted for FOURIER_PARAMETERS are only -1, 1 or 0"); + if (fourier_params[i]>1 || fourier_params[i]<-1) { + error("values accepted for FOURIER_PARAMETERS are only -1, 1 or 0"); + } } log.printf(" Fourier parameters are A=%i, B=%i \n", fourier_params[0],fourier_params[1]); } @@ -146,11 +159,19 @@ FourierTransform::FourierTransform(const ActionOptions&ao): unsigned dimension = getPntrToArgument(0)->getRank(); gridtools::ActionWithGrid* ag=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); - if( !ag ) error("input action should be a grid"); + if( !ag ) { + error("input action should be a grid"); + } const gridtools::GridCoordinatesObject & gcoords( ag->getGridCoordinatesObject() ); - if( gcoords.getGridType()=="fibonacci" ) error("cannot fourier transform fibonacci grids"); - std::vector ipbc( dimension ); for(unsigned i=0; i ipbc( dimension ); + for(unsigned i=0; i( getPntrToArgument(0)->getPntrToAction() ); const gridtools::GridCoordinatesObject & gcoords( ag->getGridCoordinatesObject() ); - std::vector fspacing; std::vector snbins( getGridCoordinatesObject().getDimension() ); + std::vector fspacing; + std::vector snbins( getGridCoordinatesObject().getDimension() ); std::vector smin( gcoords.getDimension() ), smax( gcoords.getDimension() ); for(unsigned i=0; isetShape( gcoords.getNbin(true) ); } - gridcoords.setBounds( smin, smax, snbins, fspacing ); firsttime=false; - for(unsigned i=0; isetShape( gcoords.getNbin(true) ); } #ifdef __PLUMED_HAS_FFTW @@ -198,7 +228,10 @@ void FourierTransform::calculate() { // Get the size of the input data arrays (to allocate FFT data) std::vector N_input_data( gridcoords.getNbin(true) ); - size_t fft_dimension=1; for(unsigned i=0; i( N_input_data[i] ); + size_t fft_dimension=1; + for(unsigned i=0; i( N_input_data[i] ); + } // FFT arrays std::vector > input_data(fft_dimension), fft_data(fft_dimension); @@ -234,8 +267,11 @@ void FourierTransform::calculate() { if (real_output) { double ft_value; // Compute abs/norm and fix normalization - if (!store_norm) ft_value=std::abs( fft_data[out_ind[0]*N_out_data[0]+out_ind[1]] / norm ); - else ft_value=std::norm( fft_data[out_ind[0]*N_out_data[0]+out_ind[1]] / norm ); + if (!store_norm) { + ft_value=std::abs( fft_data[out_ind[0]*N_out_data[0]+out_ind[1]] / norm ); + } else { + ft_value=std::norm( fft_data[out_ind[0]*N_out_data[0]+out_ind[1]] / norm ); + } // Set the value getPntrToComponent(0)->set( i, ft_value); } else { diff --git a/src/function/Bessel.cpp b/src/function/Bessel.cpp index d853e209b0..afd8e24b8c 100644 --- a/src/function/Bessel.cpp +++ b/src/function/Bessel.cpp @@ -69,7 +69,9 @@ class Bessel : public FunctionTemplateBase { double chbevl(double x,std::vector& array) const; // sub copied from scipy in C void fill_coefficients(); public: - bool derivativesImplemented() override { return false; } + bool derivativesImplemented() override { + return false; + } void registerKeywords( Keywords& keys ) override; void read( ActionWithArguments* action ) override; void calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const override; @@ -88,10 +90,17 @@ void Bessel::registerKeywords(Keywords& keys) { } void Bessel::read( ActionWithArguments* action ) { - if( action->getNumberOfArguments()!=1 ) action->error("should only be one argument to bessel actions"); - if( action->getPntrToArgument(0)->isPeriodic() ) action->error("cannot use this function on periodic functions"); - action->parse("ORDER",order); action->log.printf(" computing %dth order bessel function \n", order ); - if( order!=0 ) action->error("only zero order bessel function is implemented"); + if( action->getNumberOfArguments()!=1 ) { + action->error("should only be one argument to bessel actions"); + } + if( action->getPntrToArgument(0)->isPeriodic() ) { + action->error("cannot use this function on periodic functions"); + } + action->parse("ORDER",order); + action->log.printf(" computing %dth order bessel function \n", order ); + if( order!=0 ) { + action->error("only zero order bessel function is implemented"); + } fill_coefficients(); } @@ -122,7 +131,9 @@ void Bessel::calc( const ActionWithArguments* action, const std::vector& return; } vals[0] = chbevl(32.0 / x - 2.0, B) / sqrt(x) ; - } else plumed_error(); + } else { + plumed_error(); + } } std::vector Bessel::A; diff --git a/src/function/Between.cpp b/src/function/Between.cpp index 15667e9460..b902244e9a 100644 --- a/src/function/Between.cpp +++ b/src/function/Between.cpp @@ -75,32 +75,46 @@ void Between::registerKeywords(Keywords& keys) { } void Between::read( ActionWithArguments* action ) { - if( action->getNumberOfArguments()!=1 ) action->error("should only be one argument to between actions"); + if( action->getNumberOfArguments()!=1 ) { + action->error("should only be one argument to between actions"); + } std::string str_min, str_max, tstr_min, tstr_max; bool isPeriodic = action->getPntrToArgument(0)->isPeriodic(); - if( isPeriodic ) action->getPntrToArgument(0)->getDomain( str_min, str_max ); + if( isPeriodic ) { + action->getPntrToArgument(0)->getDomain( str_min, str_max ); + } - std::string hinput; action->parse("SWITCH",hinput); + std::string hinput; + action->parse("SWITCH",hinput); if(hinput.length()==0) { std::string low, up, sme; - action->parse("LOWER",low); action->parse("UPPER",up); action->parse("SMEAR",sme); + action->parse("LOWER",low); + action->parse("UPPER",up); + action->parse("SMEAR",sme); hinput = "GAUSSIAN LOWER=" + low + " UPPER=" + up + " SMEAR=" + sme; } - std::string errors; hist.set( hinput, errors ); - if( errors.size()!=0 ) action->error( errors ); + std::string errors; + hist.set( hinput, errors ); + if( errors.size()!=0 ) { + action->error( errors ); + } action->log.printf(" %s \n", hist.description().c_str() ); - if( !isPeriodic ) hist.isNotPeriodic(); - else { - double min; Tools::convert( str_min, min ); - double max; Tools::convert( str_max, max ); + if( !isPeriodic ) { + hist.isNotPeriodic(); + } else { + double min; + Tools::convert( str_min, min ); + double max; + Tools::convert( str_max, max ); hist.isPeriodic( min, max ); } } void Between::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { - plumed_dbg_assert( args.size()==1 ); vals[0] = hist.calculate( args[0], derivatives(0,0) ); + plumed_dbg_assert( args.size()==1 ); + vals[0] = hist.calculate( args[0], derivatives(0,0) ); } } diff --git a/src/function/Between.h b/src/function/Between.h index 4375398751..7e95496e9f 100644 --- a/src/function/Between.h +++ b/src/function/Between.h @@ -33,7 +33,9 @@ class Between : public FunctionTemplateBase { public: void registerKeywords( Keywords& keys ) override; void read( ActionWithArguments* action ) override; - bool getDerivativeZeroIfValueIsZero() const override { return true; } + bool getDerivativeZeroIfValueIsZero() const override { + return true; + } void calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const override; }; diff --git a/src/function/Combine.cpp b/src/function/Combine.cpp index 72f9a3961f..3e59f2b198 100644 --- a/src/function/Combine.cpp +++ b/src/function/Combine.cpp @@ -123,26 +123,45 @@ void Combine::registerKeywords(Keywords& keys) { } void Combine::read( ActionWithArguments* action ) { - coefficients.resize( action->getNumberOfArguments() ); parameters.resize( action->getNumberOfArguments() ); powers.resize( action->getNumberOfArguments() ); + coefficients.resize( action->getNumberOfArguments() ); + parameters.resize( action->getNumberOfArguments() ); + powers.resize( action->getNumberOfArguments() ); parseVector(action,"COEFFICIENTS",coefficients); - if(coefficients.size()!=static_cast(action->getNumberOfArguments())) action->error("Size of COEFFICIENTS array should be the same as number for arguments"); + if(coefficients.size()!=static_cast(action->getNumberOfArguments())) { + action->error("Size of COEFFICIENTS array should be the same as number for arguments"); + } parseVector(action,"PARAMETERS",parameters); - if(parameters.size()!=static_cast(action->getNumberOfArguments())) action->error("Size of PARAMETERS array should be the same as number for arguments"); - parseVector(action,"POWERS",powers); if(powers.size()!=static_cast(action->getNumberOfArguments())) action->error("Size of POWERS array should be the same as number for arguments"); + if(parameters.size()!=static_cast(action->getNumberOfArguments())) { + action->error("Size of PARAMETERS array should be the same as number for arguments"); + } + parseVector(action,"POWERS",powers); + if(powers.size()!=static_cast(action->getNumberOfArguments())) { + action->error("Size of POWERS array should be the same as number for arguments"); + } parseFlag(action,"NORMALIZE",normalize); if(normalize) { double n=0.0; - for(unsigned i=0; ilog.printf(" with coefficients:"); - for(unsigned i=0; ilog.printf(" %f",coefficients[i]); + for(unsigned i=0; ilog.printf(" %f",coefficients[i]); + } action->log.printf("\n with parameters:"); - for(unsigned i=0; ilog.printf(" %f",parameters[i]); + for(unsigned i=0; ilog.printf(" %f",parameters[i]); + } action->log.printf("\n and powers:"); - for(unsigned i=0; ilog.printf(" %f",powers[i]); + for(unsigned i=0; ilog.printf(" %f",powers[i]); + } action->log.printf("\n"); } diff --git a/src/function/Combine.h b/src/function/Combine.h index e93f384abb..35ce2a5407 100644 --- a/src/function/Combine.h +++ b/src/function/Combine.h @@ -27,8 +27,7 @@ namespace PLMD { namespace function { -class Combine : public FunctionTemplateBase -{ +class Combine : public FunctionTemplateBase { bool normalize; std::vector coefficients; std::vector parameters; diff --git a/src/function/Custom.cpp b/src/function/Custom.cpp index 85e20a3579..cd15d9676c 100644 --- a/src/function/Custom.cpp +++ b/src/function/Custom.cpp @@ -273,43 +273,73 @@ void Custom::registerKeywords(Keywords& keys) { void Custom::read( ActionWithArguments* action ) { // Read in the variables - std::vector var; parseVector(action,"VAR",var); parse(action,"FUNC",func); + std::vector var; + parseVector(action,"VAR",var); + parse(action,"FUNC",func); if(var.size()==0) { var.resize(action->getNumberOfArguments()); - if(var.size()>3) action->error("Using more than 3 arguments you should explicitly write their names with VAR"); - if(var.size()>0) var[0]="x"; - if(var.size()>1) var[1]="y"; - if(var.size()>2) var[2]="z"; + if(var.size()>3) { + action->error("Using more than 3 arguments you should explicitly write their names with VAR"); + } + if(var.size()>0) { + var[0]="x"; + } + if(var.size()>1) { + var[1]="y"; + } + if(var.size()>2) { + var[2]="z"; + } + } + if(var.size()!=action->getNumberOfArguments()) { + action->error("Size of VAR array should be the same as number of arguments"); } - if(var.size()!=action->getNumberOfArguments()) action->error("Size of VAR array should be the same as number of arguments"); // Check for operations that are not multiplication (this can probably be done much more cleverly) bool onlymultiplication = func.find("*")!=std::string::npos; // Find first bracket in expression if( func.find("(")!=std::string::npos ) { - std::size_t br = func.find_first_of("("); std::string subexpr=func.substr(0,br); onlymultiplication = func.find("*")!=std::string::npos; - if( subexpr.find("/")!=std::string::npos ) { std::size_t sl = func.find_first_of("/"); std::string aa = subexpr.substr(0,sl); subexpr=aa; } - if( subexpr.find("+")!=std::string::npos || subexpr.find("-")!=std::string::npos ) onlymultiplication=false; + std::size_t br = func.find_first_of("("); + std::string subexpr=func.substr(0,br); + onlymultiplication = func.find("*")!=std::string::npos; + if( subexpr.find("/")!=std::string::npos ) { + std::size_t sl = func.find_first_of("/"); + std::string aa = subexpr.substr(0,sl); + subexpr=aa; + } + if( subexpr.find("+")!=std::string::npos || subexpr.find("-")!=std::string::npos ) { + onlymultiplication=false; + } // Now work out which vars are in multiplication if( onlymultiplication ) { for(unsigned i=0; igetPntrToArgument(i)->isDerivativeZeroWhenValueIsZero() ) check_multiplication_vars.push_back(i); + action->getPntrToArgument(i)->isDerivativeZeroWhenValueIsZero() ) { + check_multiplication_vars.push_back(i); + } } } } else if( func.find("/")!=std::string::npos ) { - onlymultiplication=true; if( func.find("+")!=std::string::npos || func.find("-")!=std::string::npos ) onlymultiplication=false; + onlymultiplication=true; + if( func.find("+")!=std::string::npos || func.find("-")!=std::string::npos ) { + onlymultiplication=false; + } if( onlymultiplication ) { - std::size_t br = func.find_first_of("/"); std::string subexpr=func.substr(0,br); + std::size_t br = func.find_first_of("/"); + std::string subexpr=func.substr(0,br); for(unsigned i=0; igetPntrToArgument(i)->isDerivativeZeroWhenValueIsZero() ) check_multiplication_vars.push_back(i); + action->getPntrToArgument(i)->isDerivativeZeroWhenValueIsZero() ) { + check_multiplication_vars.push_back(i); + } } } } else if( func.find("+")!=std::string::npos || func.find("-")!=std::string::npos ) { onlymultiplication=false; } else { for(unsigned i=0; igetPntrToArgument(i)->isDerivativeZeroWhenValueIsZero() ) check_multiplication_vars.push_back(i); + if( action->getPntrToArgument(i)->isDerivativeZeroWhenValueIsZero() ) { + check_multiplication_vars.push_back(i); + } } } if( check_multiplication_vars.size()>0 ) { @@ -318,11 +348,17 @@ void Custom::read( ActionWithArguments* action ) { action->log.printf(" with function : %s\n",func.c_str()); action->log.printf(" with variables :"); - for(unsigned i=0; ilog.printf(" %s",var[i].c_str()); - action->log.printf("\n"); function.set( func, var, action ); - std::vector zeros( action->getNumberOfArguments(), 0 ); double fval = abs(function.evaluate(zeros)); + for(unsigned i=0; ilog.printf(" %s",var[i].c_str()); + } + action->log.printf("\n"); + function.set( func, var, action ); + std::vector zeros( action->getNumberOfArguments(), 0 ); + double fval = abs(function.evaluate(zeros)); zerowhenallzero=(fvallog.printf(" not calculating when all arguments are zero \n"); + if( zerowhenallzero ) { + action->log.printf(" not calculating when all arguments are zero \n"); + } } std::string Custom::getGraphInfo( const std::string& name ) const { @@ -335,7 +371,9 @@ bool Custom::getDerivativeZeroIfValueIsZero() const { std::vector Custom::getArgumentsToCheck( const std::vector& args ) { std::vector fargs( check_multiplication_vars.size() ); - for(unsigned i=0; i& bool allzero=false; if( check_multiplication_vars.size()>0 ) { for(unsigned i=0; iepsilon ) { allzero=false; break; } + if( fabs(args[i])>epsilon ) { + allzero=false; + break; + } } } if( allzero ) { - vals[0]=0; for(unsigned i=0; igetName() ) return "the average for argument " + cname; - if( cname==getPntrToArgument(i)->getName() + "_m" ) return "the moment for argument " + cname; + if( cname==getPntrToArgument(i)->getName() ) { + return "the average for argument " + cname; + } + if( cname==getPntrToArgument(i)->getName() + "_m" ) { + return "the moment for argument " + cname; + } } - plumed_error(); return ""; + plumed_error(); + return ""; } @@ -167,7 +197,9 @@ void Ensemble::calculate() { bias.resize(ens_dim); if(master) { bias[my_repl] = getArgument(narg); - if(ens_dim>1) multi_sim_comm.Sum(&bias[0], ens_dim); + if(ens_dim>1) { + multi_sim_comm.Sum(&bias[0], ens_dim); + } } comm.Sum(&bias[0], ens_dim); const double maxbias = *(std::max_element(bias.begin(), bias.end())); @@ -188,8 +220,12 @@ void Ensemble::calculate() { std::vector dmean(narg,fact); // calculate the mean if(master) { - for(unsigned i=0; i1) multi_sim_comm.Sum(&mean[0], narg); + for(unsigned i=0; i1) { + multi_sim_comm.Sum(&mean[0], narg); + } } comm.Sum(&mean[0], narg); @@ -206,7 +242,9 @@ void Ensemble::calculate() { v_moment[i] = tmp*getArgument(i); dv_moment[i] = moment*tmp; } - if(ens_dim>1) multi_sim_comm.Sum(&v_moment[0], narg); + if(ens_dim>1) { + multi_sim_comm.Sum(&v_moment[0], narg); + } } else { for(unsigned i=0; i1) multi_sim_comm.Sum(&v_moment[0], narg); + if(ens_dim>1) { + multi_sim_comm.Sum(&v_moment[0], narg); + } } else { for(unsigned i=0; i strings; Tools::getParsedLine(input, strings); - if (strings.empty()) + if (strings.empty()) { continue; + } std::vector colvarLine; double value; int max = columns.empty() ? strings.size() : columns.size(); - for (int i = 0; i < max; ++i) - { + for (int i = 0; i < max; ++i) { int col = columns.empty() ? i : columns[i]; // If no columns have been entered, ignore the first (time) and take the rest - if (columns.empty() && i == 0) + if (columns.empty() && i == 0) { continue; + } Tools::convert(strings[col], value); colvarLine.push_back(value); @@ -170,8 +171,7 @@ FuncPathGeneral::FuncPathGeneral(const ActionOptions&ao): Action(ao), Function(ao), neigh_size(-1), - neigh_stride(-1.) -{ + neigh_stride(-1.) { parse("LAMBDA", lambda); parse("NEIGH_SIZE", neigh_size); parse("NEIGH_STRIDE", neigh_stride); @@ -180,11 +180,13 @@ FuncPathGeneral::FuncPathGeneral(const ActionOptions&ao): parseVector("COLUMNS", columns); checkRead(); log.printf(" lambda is %f\n", lambda); - if (getNumberOfArguments() != coefficients.size()) + if (getNumberOfArguments() != coefficients.size()) { plumed_merror("The numbers of coefficients and CVs are different!"); + } if (!columns.empty()) { - if (columns.size() != coefficients.size()) + if (columns.size() != coefficients.size()) { plumed_merror("The numbers of coefficients and columns are different!"); + } } log.printf(" Consistency check completed! Your path cvs look good!\n"); @@ -204,8 +206,10 @@ FuncPathGeneral::FuncPathGeneral(const ActionOptions&ao): log.printf(" Neighbour list NOT enabled \n"); } - addComponentWithDerivatives("s"); componentIsNotPeriodic("s"); - addComponentWithDerivatives("z"); componentIsNotPeriodic("z"); + addComponentWithDerivatives("s"); + componentIsNotPeriodic("s"); + addComponentWithDerivatives("z"); + componentIsNotPeriodic("z"); // Initialise vectors std::vector temp (coefficients.size()); @@ -217,8 +221,9 @@ FuncPathGeneral::FuncPathGeneral(const ActionOptions&ao): } // Store the arguments - for (unsigned i=0; igetDomain(min_lim, max_lim); domains.push_back((max_lim - min_lim) / 2); - } - else + } else { domains.push_back(-1.); + } } } @@ -248,8 +253,9 @@ void FuncPathGeneral::calculate() { if (neighpair.empty()) { // Resize at the first step neighpair.resize(path_cv_values.size()); - for (unsigned i = 0; i < path_cv_values.size(); ++i) + for (unsigned i = 0; i < path_cv_values.size(); ++i) { neighpair[i].first = i; + } } Value* val_s_path=getPntrToComponent("s"); @@ -260,10 +266,12 @@ void FuncPathGeneral::calculate() { for (pairiter it = neighpair.begin(); it != neighpair.end(); ++it) { diff = (value - path_cv_values[(*it).first][j]); if (domains[j] > 0) { - if (diff > domains[j]) + if (diff > domains[j]) { diff -= 2 * domains[j]; - if (diff < -domains[j]) + } + if (diff < -domains[j]) { diff += 2 * domains[j]; + } } (*it).second += Tools::fastpow(coefficients[j] * diff, 2); numerators[(*it).first][j] = 2 * Tools::fastpow(coefficients[j], 2) * diff; @@ -277,7 +285,9 @@ void FuncPathGeneral::calculate() { partition += expdist; } - if(partition==0.0) partition=std::numeric_limits::min(); + if(partition==0.0) { + partition=std::numeric_limits::min(); + } s_path /= partition; val_s_path->set(s_path); @@ -320,15 +330,17 @@ void FuncPathGeneral::prepare() { // Resize the effective list neighpair.resize(neigh_size); log.printf(" NEIGHBOUR LIST NOW INCLUDES INDICES: "); - for (int i = 0; i < neigh_size; ++i) + for (int i = 0; i < neigh_size; ++i) { log.printf(" %i ",neighpair[i].first); + } log.printf(" \n"); } else { if (int(getStep()) % int(neigh_stride / getTimeStep()) == 0) { log.printf(" Time %f : recalculating full neighbour list \n", getStep() * getTimeStep()); neighpair.resize(path_cv_values.size()); - for (unsigned i = 0; i < path_cv_values.size(); ++i) + for (unsigned i = 0; i < path_cv_values.size(); ++i) { neighpair[i].first = i; + } } } } diff --git a/src/function/FuncPathMSD.cpp b/src/function/FuncPathMSD.cpp index 88f823afe3..0e1ea76cfa 100644 --- a/src/function/FuncPathMSD.cpp +++ b/src/function/FuncPathMSD.cpp @@ -192,9 +192,11 @@ class FuncPathMSD : public Function { } // now sort according the second value std::sort(order.begin(), order.end(), ordering()); - std::vector vv(v.size()); n=0; + std::vector vv(v.size()); + n=0; for (const auto & it : order) { - vv[n]=it.first; n++; + vv[n]=it.first; + n++; } return vv; } @@ -230,8 +232,7 @@ FuncPathMSD::FuncPathMSD(const ActionOptions&ao): Action(ao), Function(ao), neigh_size(-1), - neigh_stride(-1.) -{ + neigh_stride(-1.) { parse("LAMBDA",lambda); parse("NEIGH_SIZE",neigh_size); @@ -240,10 +241,14 @@ FuncPathMSD::FuncPathMSD(const ActionOptions&ao): log.printf(" lambda is %f\n",lambda); // list the action involved and check the type std::string myname=getPntrToArgument(0)->getPntrToAction()->getName(); - if(myname!="RMSD_SCALAR"&&myname!="CONTACTMAP"&&myname!="DISTANCE"&&myname!="PIV") error("One or more of your arguments is not of RMSD/CONTACTMAP/DISTANCE/PIV type!!!"); + if(myname!="RMSD_SCALAR"&&myname!="CONTACTMAP"&&myname!="DISTANCE"&&myname!="PIV") { + error("One or more of your arguments is not of RMSD/CONTACTMAP/DISTANCE/PIV type!!!"); + } for(unsigned i=1; igetPntrToAction()->getName()!=myname ) error("mismatch between the types of arguments"); + if( getPntrToArgument(i)->getPntrToAction()->getName()!=myname ) { + error("mismatch between the types of arguments"); + } } log.printf(" Consistency check completed! Your path cvs look good!\n"); // do some neighbor printout @@ -259,14 +264,19 @@ FuncPathMSD::FuncPathMSD(const ActionOptions&ao): log.printf(" Neighbor list NOT enabled \n"); } - addComponentWithDerivatives("s"); componentIsNotPeriodic("s"); - addComponentWithDerivatives("z"); componentIsNotPeriodic("z"); + addComponentWithDerivatives("s"); + componentIsNotPeriodic("s"); + addComponentWithDerivatives("z"); + componentIsNotPeriodic("z"); // now backup the arguments - for(unsigned i=0; i argstocall; diff --git a/src/function/FuncSumHills.cpp b/src/function/FuncSumHills.cpp index 65eef4238c..f69d5fc616 100644 --- a/src/function/FuncSumHills.cpp +++ b/src/function/FuncSumHills.cpp @@ -77,7 +77,8 @@ FilesHandler::FilesHandler(const std::vector &filenames, const bool // note that the FileHandler is completely transparent respect to the biasrepresentation // no check are made at this level bool FilesHandler::readBunch(BiasRepresentation *br, int stride = -1) { - bool morefiles; morefiles=true; + bool morefiles; + morefiles=true; if(parallelread) { (*log)<<" doing parallelread \n"; plumed_merror("parallelread is not yet implemented !!!"); @@ -89,7 +90,8 @@ bool FilesHandler::readBunch(BiasRepresentation *br, int stride = -1) { ff=ifiles[beingread].get(); if(!isopen) { (*log)<<" opening file "<open(filenames[beingread]); isopen=true; + ff->open(filenames[beingread]); + isopen=true; } int n=0; while(true) { @@ -110,7 +112,8 @@ bool FilesHandler::readBunch(BiasRepresentation *br, int stride = -1) { (*log)<<" now total "<getNumberOfKernels()<<" kernels \n"; beingread++; if(beingreadopen(filenames[beingread]); + ff=ifiles[beingread].get(); + ff->open(filenames[beingread]); (*log)<<" opening file "<scanField("time",dummy)) { //(*log)<<" scanning one hill: "<FieldExist("biasf")) ifile->scanField("biasf",dummy); - if(ifile->FieldExist("clock")) ifile->scanField("clock",dummy); + if(ifile->FieldExist("biasf")) { + ifile->scanField("biasf",dummy); + } + if(ifile->FieldExist("clock")) { + ifile->scanField("clock",dummy); + } // keep this intermediate function in case you need to parse more data in the future br->pushKernel(ifile); //(*log)<<" read hill\n"; - if(br->hasSigmaInInput())ifile->allowIgnoredFields(); + if(br->hasSigmaInInput()) { + ifile->allowIgnoredFields(); + } ifile->scanField(); return true; } else { @@ -173,8 +186,7 @@ double mylogder( double v1 ) { class FuncSumHills : - public Function -{ + public Function { std::vector hillsFiles,histoFiles; std::vector proj; int initstride; @@ -239,8 +251,7 @@ FuncSumHills::FuncSumHills(const ActionOptions&ao): lowI_(-1.), uppI_(-1.), beta(-1.), - fmt("%14.9f") -{ + fmt("%14.9f") { // format parse("FMT",fmt); @@ -249,44 +260,62 @@ FuncSumHills::FuncSumHills(const ActionOptions&ao): // Grid Stuff std::vector gmin; parseVector("GRID_MIN",gmin); - if(gmin.size()!=getNumberOfArguments() && gmin.size()!=0) error("not enough values for GRID_MIN"); + if(gmin.size()!=getNumberOfArguments() && gmin.size()!=0) { + error("not enough values for GRID_MIN"); + } plumed_massert(gmin.size()==getNumberOfArguments() || gmin.size()==0,"need GRID_MIN argument for this") ; std::vector gmax; parseVector("GRID_MAX",gmax); - if(gmax.size()!=getNumberOfArguments() && gmax.size()!=0) error("not enough values for GRID_MAX"); + if(gmax.size()!=getNumberOfArguments() && gmax.size()!=0) { + error("not enough values for GRID_MAX"); + } plumed_massert(gmax.size()==getNumberOfArguments() || gmax.size()==0,"need GRID_MAX argument for this") ; std::vector gbin; std::vector gspacing; parseVector("GRID_BIN",gbin); plumed_massert(gbin.size()==getNumberOfArguments() || gbin.size()==0,"need GRID_BIN argument for this") ; - if(gbin.size()!=getNumberOfArguments() && gbin.size()!=0) error("not enough values for GRID_BIN"); + if(gbin.size()!=getNumberOfArguments() && gbin.size()!=0) { + error("not enough values for GRID_BIN"); + } parseVector("GRID_SPACING",gspacing); plumed_massert(gspacing.size()==getNumberOfArguments() || gspacing.size()==0,"need GRID_SPACING argument for this") ; - if(gspacing.size()!=getNumberOfArguments() && gspacing.size()!=0) error("not enough values for GRID_SPACING"); + if(gspacing.size()!=getNumberOfArguments() && gspacing.size()!=0) { + error("not enough values for GRID_SPACING"); + } if(gspacing.size()!=0 && gbin.size()==0) { log<<" The number of bins will be estimated from GRID_SPACING\n"; } else if(gspacing.size()!=0 && gbin.size()!=0) { log<<" You specified both GRID_BIN and GRID_SPACING\n"; log<<" The more conservative (highest) number of bins will be used for each variable\n"; } - if(gspacing.size()!=0) for(unsigned i=0; i tmpI(2); parseVector("INTERVAL",tmpI); - if(tmpI.size()!=2&&tmpI.size()!=0) error("both a lower and an upper limits must be provided with INTERVAL"); - else if(tmpI.size()==2) { + if(tmpI.size()!=2&&tmpI.size()!=0) { + error("both a lower and an upper limits must be provided with INTERVAL"); + } else if(tmpI.size()==2) { lowI_=tmpI.at(0); uppI_=tmpI.at(1); - if(getNumberOfArguments()!=1) error("INTERVAL limits correction works only for monodimensional metadynamics!"); - if(uppI_ histoSigma; if(integratehisto) { parseVector("HISTOSIGMA",histoSigma); - for(unsigned i=0; igetName()); + for(unsigned i=0; igetName()); + } } // add some automatic hills width: not in case stride is defined @@ -343,13 +386,17 @@ FuncSumHills::FuncSumHills(const ActionOptions&ao): log<<" No boundaries defined: need to do a prescreening of hills \n"; std::vector tmphillsvalues, tmphistovalues; if(integratehills) { - for(unsigned i=0; igetName(); for(unsigned j=0; j0.,"if you make a projection or a histogram correction then you need KT flag!"); beta=1./beta; @@ -417,16 +466,21 @@ FuncSumHills::FuncSumHills(const ActionOptions&ao): // output suffix or names if(initstride<0) { log<<" Doing only one integration: no stride \n"; - outhills="fes.dat"; outhisto="histo.dat"; - } - else { - outhills="fes_"; outhisto="histo_"; + outhills="fes.dat"; + outhisto="histo.dat"; + } else { + outhills="fes_"; + outhisto="histo_"; log<<" Doing integration slices every "<getName(); for(unsigned j=0; jsetRescaledToBias(true); log<<" required the -bias instead of the free energy \n"; - if(initstride<0) {outhills="negativebias.dat";} - else {outhills="negativebias_";} + if(initstride<0) { + outhills="negativebias.dat"; + } else { + outhills="negativebias_"; + } } } parse("OUTHILLS",outhills); parse("OUTHISTO",outhisto); - if(integratehills)log<<" output file for fes/bias is : "< hillsHandler; std::unique_ptr histoHandler; - if(integratehills) hillsHandler=Tools::make_unique(hillsFiles,parallelread,*this, log); - if(integratehisto) histoHandler=Tools::make_unique(histoFiles,parallelread,*this, log); + if(integratehills) { + hillsHandler=Tools::make_unique(hillsFiles,parallelread,*this, log); + } + if(integratehisto) { + histoHandler=Tools::make_unique(histoFiles,parallelread,*this, log); + } // Stopwatch is logged when it goes out of scope Stopwatch sw(log); @@ -502,18 +569,27 @@ FuncSumHills::FuncSumHills(const ActionOptions&ao): // read a number of hills and put in the bias representation int nfiles=0; - bool ibias=integratehills; bool ihisto=integratehisto; + bool ibias=integratehills; + bool ihisto=integratehisto; while(true) { if( integratehills && ibias ) { - if(nohistory) {biasrep->clear(); log<<" clearing history before reading a new block\n";}; + if(nohistory) { + biasrep->clear(); + log<<" clearing history before reading a new block\n"; + }; log<<" reading hills: \n"; - ibias=hillsHandler->readBunch(biasrep.get(),initstride) ; log<<"\n"; + ibias=hillsHandler->readBunch(biasrep.get(),initstride) ; + log<<"\n"; } if( integratehisto && ihisto ) { - if(nohistory) {historep->clear(); log<<" clearing history before reading a new block\n";}; + if(nohistory) { + historep->clear(); + log<<" clearing history before reading a new block\n"; + }; log<<" reading histogram: \n"; - ihisto=histoHandler->readBunch(historep.get(),initstride) ; log<<"\n"; + ihisto=histoHandler->readBunch(historep.get(),initstride) ; + log<<"\n"; } // dump: need to project? @@ -525,17 +601,27 @@ FuncSumHills::FuncSumHills(const ActionOptions&ao): BiasWeight Bw(beta); Grid biasGrid=*(biasrep->getGridPtr()); Grid smallGrid=biasGrid.project(proj,&Bw); - OFile gridfile; gridfile.link(*this); - std::ostringstream ostr; ostr<0) { myout=outhills+ostr.str()+".dat" ;} else {myout=outhills;} + if(initstride>0) { + myout=outhills+ostr.str()+".dat" ; + } else { + myout=outhills; + } log<<" Bias: Writing subgrid on file "<getGridPtr()); - OFile gridfile; gridfile.link(*this); - std::ostringstream ostr; ostr<0) { myout=outhisto+ostr.str()+".dat" ;} else {myout=outhisto;} + if(initstride>0) { + myout=outhisto+ostr.str()+".dat" ; + } else { + myout=outhisto; + } log<<" Histo: Writing subgrid on file "<getGridPtr()); biasGrid.scaleAllValuesAndDerivatives(-1.); - OFile gridfile; gridfile.link(*this); - std::ostringstream ostr; ostr<0) { myout=outhills+ostr.str()+".dat" ;} else {myout=outhills;} + if(initstride>0) { + myout=outhills+ostr.str()+".dat" ; + } else { + myout=outhills; + } log<<" Writing full grid on file "<0) { myout=outhisto+ostr.str()+".dat" ;} else {myout=outhisto;} + if(initstride>0) { + myout=outhisto+ostr.str()+".dat" ; + } else { + myout=outhisto; + } log<<" Writing full grid on file "<resizeDerivatives(getNumberOfArguments()); } -void Function::apply() -{ - if( !checkForForces() ) return; - unsigned ind=0; addForcesOnArguments( 0, getForcesToApply(), ind, getLabel() ); +void Function::apply() { + if( !checkForForces() ) { + return; + } + unsigned ind=0; + addForcesOnArguments( 0, getForcesToApply(), ind, getLabel() ); } } diff --git a/src/function/Function.h b/src/function/Function.h index 2074a66410..6fa6a8be59 100644 --- a/src/function/Function.h +++ b/src/function/Function.h @@ -36,8 +36,7 @@ This is the abstract base class to use for implementing new CV function, within class Function: public ActionWithValue, - public ActionWithArguments -{ + public ActionWithArguments { protected: void setDerivative(int,double); void setDerivative(Value*,int,double); @@ -66,7 +65,9 @@ inline unsigned Function::getNumberOfDerivatives() { unsigned narg=0; for(unsigned i=0; igetRank()==0 ) narg++; + if( getPntrToArgument(i)->getRank()==0 ) { + narg++; + } } return narg; } diff --git a/src/function/FunctionOfMatrix.h b/src/function/FunctionOfMatrix.h index 067e83c4b8..ee252e10b4 100644 --- a/src/function/FunctionOfMatrix.h +++ b/src/function/FunctionOfMatrix.h @@ -51,7 +51,9 @@ class FunctionOfMatrix : public ActionWithMatrix { static void registerKeywords(Keywords&); explicit FunctionOfMatrix(const ActionOptions&); /// Get the label to write in the graph - std::string writeInGraph() const override { return myfunc.getGraphInfo( getName() ); } + std::string writeInGraph() const override { + return myfunc.getGraphInfo( getName() ); + } /// Make sure the derivatives are turned on void turnOnDerivatives() override; /// Get the number of derivatives for this action @@ -75,11 +77,15 @@ class FunctionOfMatrix : public ActionWithMatrix { template void FunctionOfMatrix::registerKeywords(Keywords& keys ) { - ActionWithMatrix::registerKeywords(keys); keys.use("ARG"); std::string name = keys.getDisplayName(); - std::size_t und=name.find("_MATRIX"); keys.setDisplayName( name.substr(0,und) ); + ActionWithMatrix::registerKeywords(keys); + keys.use("ARG"); + std::string name = keys.getDisplayName(); + std::size_t und=name.find("_MATRIX"); + keys.setDisplayName( name.substr(0,und) ); keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); keys.reserve("compulsory","PERIODIC","if the output of your function is periodic then you should specify the periodicity of the function. If the output is not periodic you must state this using PERIODIC=NO"); - T tfunc; tfunc.registerKeywords( keys ); + T tfunc; + tfunc.registerKeywords( keys ); if( keys.getDisplayName()=="SUM" ) { keys.setValueDescription("the sum of all the elements in the input matrix"); } else if( keys.getDisplayName()=="HIGHEST" ) { @@ -95,31 +101,42 @@ template FunctionOfMatrix::FunctionOfMatrix(const ActionOptions&ao): Action(ao), ActionWithMatrix(ao), - firststep(true) -{ - if( myfunc.getArgStart()>0 ) error("this has not beeen implemented -- if you are interested email gareth.tribello@gmail.com"); + firststep(true) { + if( myfunc.getArgStart()>0 ) { + error("this has not beeen implemented -- if you are interested email gareth.tribello@gmail.com"); + } // Get the shape of the output std::vector shape( getValueShapeFromArguments() ); // Check if the output matrix is symmetric - bool symmetric=true; unsigned argstart=myfunc.getArgStart(); + bool symmetric=true; + unsigned argstart=myfunc.getArgStart(); for(unsigned i=argstart; igetRank()==2 ) { - if( !getPntrToArgument(i)->isSymmetric() ) { symmetric=false; } + if( !getPntrToArgument(i)->isSymmetric() ) { + symmetric=false; + } } } // Read the input and do some checks myfunc.read( this ); // Setup to do this in chain if possible - if( myfunc.doWithTasks() ) done_in_chain=true; + if( myfunc.doWithTasks() ) { + done_in_chain=true; + } // Check we are not calculating a sum - if( myfunc.zeroRank() ) shape.resize(0); + if( myfunc.zeroRank() ) { + shape.resize(0); + } // Get the names of the components std::vector components( keywords.getOutputComponents() ); // Create the values to hold the output std::vector str_ind( myfunc.getComponentsPerLabel() ); for(unsigned i=0; i0 ) { - std::string compstr = components[i]; if( components[i]==".#!value" ) compstr = ""; + std::string compstr = components[i]; + if( components[i]==".#!value" ) { + compstr = ""; + } for(unsigned j=0; j::FunctionOfMatrix(const ActionOptions&ao): } else if( components[i]==".#!value" && myfunc.zeroRank() ) { addValueWithDerivatives( shape ); } else if( components[i]==".#!value" ) { - addValue( shape ); getPntrToComponent(0)->setSymmetric( symmetric ); + addValue( shape ); + getPntrToComponent(0)->setSymmetric( symmetric ); } else if( components[i].find_first_of("_")!=std::string::npos ) { - if( getNumberOfArguments()-argstart==1 ) { addValue( shape ); getPntrToComponent(0)->setSymmetric( symmetric ); } - else { + if( getNumberOfArguments()-argstart==1 ) { + addValue( shape ); + getPntrToComponent(0)->setSymmetric( symmetric ); + } else { for(unsigned j=argstart; jgetName() + components[i], shape ); getPntrToComponent(i*(getNumberOfArguments()-argstart)+j-argstart)->setSymmetric( symmetric ); } } - } else { addComponent( components[i], shape ); getPntrToComponent(i)->setSymmetric( symmetric ); } + } else { + addComponent( components[i], shape ); + getPntrToComponent(i)->setSymmetric( symmetric ); + } } // Check if this can be sped up if( myfunc.getDerivativeZeroIfValueIsZero() ) { - for(int i=0; isetDerivativeIsZeroWhenValueIsZero(); + for(int i=0; isetDerivativeIsZeroWhenValueIsZero(); + } } // Set the periodicities of the output components myfunc.setPeriodicityForOutputs( this ); // We can't do this with if we are dividing a stack by some a product v.v^T product as we need to store the vector // In order to do this type of calculation. There should be a neater fix than this but I can't see it. - bool foundneigh=false; const ActionWithMatrix* chainstart = NULL; + bool foundneigh=false; + const ActionWithMatrix* chainstart = NULL; for(unsigned i=argstart; iisConstant() && getNumberOfArguments()>1 ) continue ; + if( getPntrToArgument(i)->isConstant() && getNumberOfArguments()>1 ) { + continue ; + } std::string argname=(getPntrToArgument(i)->getPntrToAction())->getName(); - if( argname=="NEIGHBORS" ) { foundneigh=true; break; } + if( argname=="NEIGHBORS" ) { + foundneigh=true; + break; + } ActionWithVector* av=dynamic_cast( getPntrToArgument(i)->getPntrToAction() ); - if( !av ) done_in_chain=false; + if( !av ) { + done_in_chain=false; + } if( getPntrToArgument(i)->getRank()==0 ) { function::FunctionOfVector* as = dynamic_cast*>( getPntrToArgument(i)->getPntrToAction() ); - if(as) done_in_chain=false; + if(as) { + done_in_chain=false; + } } else if( getPntrToArgument(i)->ignoreStoredValue( getLabel() ) ) { // This option deals with the case when you have two adjacency matrices, A_ij and B_ij, multiplied together. This cannot be done in the chain as the rows // of the two adjacency matrix are run over separately. The value A_ij is thus not available when B_ij is calculated. ActionWithMatrix* am = dynamic_cast( getPntrToArgument(i)->getPntrToAction() ); - plumed_assert( am ); const ActionWithMatrix* thischain = am->getFirstMatrixInChain(); - if( !thischain->isAdjacencyMatrix() && thischain->getName()!="VSTACK" ) continue; - if( !chainstart ) chainstart = thischain; - else if( thischain!=chainstart ) done_in_chain=false; + plumed_assert( am ); + const ActionWithMatrix* thischain = am->getFirstMatrixInChain(); + if( !thischain->isAdjacencyMatrix() && thischain->getName()!="VSTACK" ) { + continue; + } + if( !chainstart ) { + chainstart = thischain; + } else if( thischain!=chainstart ) { + done_in_chain=false; + } } } // If we are working with neighbors we trick PLUMED into storing ALL the components of the other arguments @@ -177,7 +218,9 @@ FunctionOfMatrix::FunctionOfMatrix(const ActionOptions&ao): for(unsigned i=argstart; igetPntrToAction(); if( av->getName()!="NEIGHBORS" ) { - for(int i=0; igetNumberOfComponents(); ++i) (av->copyOutput(i))->buildDataStore(); + for(int i=0; igetNumberOfComponents(); ++i) { + (av->copyOutput(i))->buildDataStore(); + } } } } @@ -187,8 +230,11 @@ FunctionOfMatrix::FunctionOfMatrix(const ActionOptions&ao): template void FunctionOfMatrix::turnOnDerivatives() { - if( !myfunc.derivativesImplemented() ) error("derivatives have not been implemended for " + getName() ); - ActionWithValue::turnOnDerivatives(); myfunc.setup(this); + if( !myfunc.derivativesImplemented() ) { + error("derivatives have not been implemended for " + getName() ); + } + ActionWithValue::turnOnDerivatives(); + myfunc.setup(this); } template @@ -198,7 +244,8 @@ unsigned FunctionOfMatrix::getNumberOfDerivatives() { template void FunctionOfMatrix::prepare() { - unsigned argstart = myfunc.getArgStart(); std::vector shape(2); + unsigned argstart = myfunc.getArgStart(); + std::vector shape(2); for(unsigned i=argstart; igetRank()==2 ) { shape[0] = getPntrToArgument(i)->getShape()[0]; @@ -209,7 +256,10 @@ void FunctionOfMatrix::prepare() { for(unsigned i=0; igetRank()==2 && (myval->getShape()[0]!=shape[0] || myval->getShape()[1]!=shape[1]) ) { - myval->setShape(shape); if( myval->valueIsStored() ) myval->reshapeMatrixStore( shape[1] ); + myval->setShape(shape); + if( myval->valueIsStored() ) { + myval->reshapeMatrixStore( shape[1] ); + } } } ActionWithVector::prepare(); @@ -222,20 +272,29 @@ unsigned FunctionOfMatrix::getNumberOfColumns() const { for(unsigned i=argstart; igetRank()==2 ) { ActionWithMatrix* am=dynamic_cast( getPntrToArgument(i)->getPntrToAction() ); - if( am ) return am->getNumberOfColumns(); + if( am ) { + return am->getNumberOfColumns(); + } return getPntrToArgument(i)->getShape()[1]; } } } - plumed_error(); return 0; + plumed_error(); + return 0; } template void FunctionOfMatrix::setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const { - for(unsigned i=0; igetRank()==2 ); + for(unsigned i=0; igetRank()==2 ); + } unsigned start_n = getPntrToArgument(0)->getShape()[0], size_v = getPntrToArgument(0)->getShape()[1]; - if( indices.size()!=size_v+1 ) indices.resize( size_v+1 ); - for(unsigned i=0; i::setupStreamedComponents( const std::string& headstr, u std::string control = getFirstActionInChain()->getLabel(); for(unsigned i=0; iignoreStoredValue( control ); - if( !stored_arguments[i] ) update_arguments[i] = true; - else update_arguments[i] = !argumentDependsOn( headstr, this, getPntrToArgument(i) ); + if( !stored_arguments[i] ) { + update_arguments[i] = true; + } else { + update_arguments[i] = !argumentDependsOn( headstr, this, getPntrToArgument(i) ); + } } firststep=false; } @@ -265,29 +327,45 @@ void FunctionOfMatrix::setupStreamedComponents( const std::string& headstr, u template void FunctionOfMatrix::performTask( const std::string& controller, const unsigned& index1, const unsigned& index2, MultiValue& myvals ) const { - unsigned argstart=myfunc.getArgStart(); std::vector args( getNumberOfArguments() - argstart ); + unsigned argstart=myfunc.getArgStart(); + std::vector args( getNumberOfArguments() - argstart ); unsigned ind2 = index2; - if( getConstPntrToComponent(0)->getRank()==2 && index2>=getConstPntrToComponent(0)->getShape()[0] ) ind2 = index2 - getConstPntrToComponent(0)->getShape()[0]; - else if( index2>=getPntrToArgument(0)->getShape()[0] ) ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + if( getConstPntrToComponent(0)->getRank()==2 && index2>=getConstPntrToComponent(0)->getShape()[0] ) { + ind2 = index2 - getConstPntrToComponent(0)->getShape()[0]; + } else if( index2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + } if( actionInChain() ) { for(unsigned i=argstart; igetRank()==0 ) args[i-argstart] = getPntrToArgument(i)->get(); - else if( !getPntrToArgument(i)->valueHasBeenSet() ) args[i-argstart] = myvals.get( getPntrToArgument(i)->getPositionInStream() ); - else args[i-argstart] = getPntrToArgument(i)->get( getPntrToArgument(i)->getShape()[1]*index1 + ind2 ); + if( getPntrToArgument(i)->getRank()==0 ) { + args[i-argstart] = getPntrToArgument(i)->get(); + } else if( !getPntrToArgument(i)->valueHasBeenSet() ) { + args[i-argstart] = myvals.get( getPntrToArgument(i)->getPositionInStream() ); + } else { + args[i-argstart] = getPntrToArgument(i)->get( getPntrToArgument(i)->getShape()[1]*index1 + ind2 ); + } } } else { for(unsigned i=argstart; igetRank()==2 ) args[i-argstart]=getPntrToArgument(i)->get( getPntrToArgument(i)->getShape()[1]*index1 + ind2 ); - else args[i-argstart] = getPntrToArgument(i)->get(); + if( getPntrToArgument(i)->getRank()==2 ) { + args[i-argstart]=getPntrToArgument(i)->get( getPntrToArgument(i)->getShape()[1]*index1 + ind2 ); + } else { + args[i-argstart] = getPntrToArgument(i)->get(); + } } } // Calculate the function and its derivatives - std::vector vals( getNumberOfComponents() ); Matrix derivatives( getNumberOfComponents(), getNumberOfArguments()-argstart ); + std::vector vals( getNumberOfComponents() ); + Matrix derivatives( getNumberOfComponents(), getNumberOfArguments()-argstart ); myfunc.calc( this, args, vals, derivatives ); // And set the values - for(unsigned i=0; igetPositionInStream(), vals[i] ); + for(unsigned i=0; igetPositionInStream(), vals[i] ); + } // Return if we are not computing derivatives - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } if( actionInChain() ) { for(int i=0; i::performTask( const std::string& controller, const unsi unsigned istrn = getPntrToArgument(j)->getPositionInStream(); if( stored_arguments[j] ) { unsigned task_index = getPntrToArgument(i)->getShape()[1]*index1 + ind2; - myvals.clearDerivatives(istrn); myvals.addDerivative( istrn, task_index, 1.0 ); myvals.updateIndex( istrn, task_index ); + myvals.clearDerivatives(istrn); + myvals.addDerivative( istrn, task_index, 1.0 ); + myvals.updateIndex( istrn, task_index ); } for(unsigned k=0; k::performTask( const std::string& controller, const unsi for(int i=0; igetPositionInStream(); for(unsigned j=argstart; jgetRank()==0 ) continue ; + if( !update_arguments[j] || getPntrToArgument(j)->getRank()==0 ) { + continue ; + } // Ensure we only store one lot of derivative indices bool found=false; for(unsigned k=0; kgetPositionInStream(); for(unsigned k=0; k::performTask( const std::string& controller, const unsi } } } else { - unsigned base=0; ind2 = index2; + unsigned base=0; + ind2 = index2; for(unsigned j=argstart; jgetRank()!=2 ) continue ; - if( index2>=getPntrToArgument(j)->getShape()[0] ) ind2 = index2 - getPntrToArgument(j)->getShape()[0]; + if( getPntrToArgument(j)->getRank()!=2 ) { + continue ; + } + if( index2>=getPntrToArgument(j)->getShape()[0] ) { + ind2 = index2 - getPntrToArgument(j)->getShape()[0]; + } break; } for(unsigned j=argstart; j::performTask( const std::string& controller, const unsi template void FunctionOfMatrix::runEndOfRowJobs( const unsigned& ind, const std::vector & indices, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } unsigned argstart=myfunc.getArgStart(); if( actionInChain() && getConstPntrToComponent(0)->getRank()==2 ) { // This is triggered if we are outputting a matrix for(int vv=0; vvgetPositionInMatrixStash(); - std::vector& mat_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); unsigned ntot_mat=0; - if( mat_indices.size()& mat_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); + unsigned ntot_mat=0; + if( mat_indices.size()getRank()==0 ) continue ; + if( !update_arguments[i] || getPntrToArgument(i)->getRank()==0 ) { + continue ; + } // Ensure we only store one lot of derivative indices bool found=false; for(unsigned j=0; jgetShape()[1]*ind; @@ -383,7 +487,9 @@ void FunctionOfMatrix::runEndOfRowJobs( const unsigned& ind, const std::vecto } else { unsigned istrn = getPntrToArgument(i)->getPositionInMatrixStash(); std::vector& imat_indices( myvals.getMatrixRowDerivativeIndices( istrn ) ); - for(unsigned k=0; k::runEndOfRowJobs( const unsigned& ind, const std::vecto for(unsigned i=argstart; igetPositionInMatrixStash(); std::vector& mat_indices( myvals.getMatrixRowDerivativeIndices( istrn ) ); for(unsigned k=0; k::runEndOfRowJobs( const unsigned& ind, const std::vecto } else if( getConstPntrToComponent(0)->getRank()==2 ) { for(int vv=0; vvgetPositionInMatrixStash(); - std::vector& mat_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); unsigned ntot_mat=0; - if( mat_indices.size()& mat_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); + unsigned ntot_mat=0; + if( mat_indices.size()getRank()==0 ) continue ; - unsigned ss = getPntrToArgument(i)->getShape()[1]; unsigned tbase = matderbase + ss*myvals.getTaskIndex(); - for(unsigned k=0; kgetNumberOfValues(); + if( getPntrToArgument(i)->getRank()==0 ) { + continue ; + } + unsigned ss = getPntrToArgument(i)->getShape()[1]; + unsigned tbase = matderbase + ss*myvals.getTaskIndex(); + for(unsigned k=0; kgetNumberOfValues(); } myvals.setNumberOfMatrixRowDerivatives( nmat, ntot_mat ); } @@ -424,16 +545,23 @@ void FunctionOfMatrix::runEndOfRowJobs( const unsigned& ind, const std::vecto template std::vector FunctionOfMatrix::getValueShapeFromArguments() { - unsigned argstart=myfunc.getArgStart(); std::vector shape(2); shape[0]=shape[1]=0; + unsigned argstart=myfunc.getArgStart(); + std::vector shape(2); + shape[0]=shape[1]=0; for(unsigned i=argstart; igetRank()==2 || getPntrToArgument(i)->getRank()==0 ); if( getPntrToArgument(i)->getRank()==2 ) { - if( shape[0]>0 && (getPntrToArgument(i)->getShape()[0]!=shape[0] || getPntrToArgument(i)->getShape()[1]!=shape[1]) ) error("all matrices input should have the same shape"); - else if( shape[0]==0 ) { shape[0]=getPntrToArgument(i)->getShape()[0]; shape[1]=getPntrToArgument(i)->getShape()[1]; } + if( shape[0]>0 && (getPntrToArgument(i)->getShape()[0]!=shape[0] || getPntrToArgument(i)->getShape()[1]!=shape[1]) ) { + error("all matrices input should have the same shape"); + } else if( shape[0]==0 ) { + shape[0]=getPntrToArgument(i)->getShape()[0]; + shape[1]=getPntrToArgument(i)->getShape()[1]; + } plumed_assert( !getPntrToArgument(i)->hasDerivatives() ); } } - myfunc.setPrefactor( this, 1.0 ); return shape; + myfunc.setPrefactor( this, 1.0 ); + return shape; } } diff --git a/src/function/FunctionOfScalar.h b/src/function/FunctionOfScalar.h index 00ab91197e..c7b909993f 100644 --- a/src/function/FunctionOfScalar.h +++ b/src/function/FunctionOfScalar.h @@ -45,7 +45,9 @@ class FunctionOfScalar : public Function { explicit FunctionOfScalar(const ActionOptions&); virtual ~FunctionOfScalar() {} /// Get the label to write in the graph - std::string writeInGraph() const override { return myfunc.getGraphInfo( getName() ); } + std::string writeInGraph() const override { + return myfunc.getGraphInfo( getName() ); + } std::string getOutputComponentDescription( const std::string& cname, const Keywords& keys ) const override ; void calculate() override; static void registerKeywords(Keywords&); @@ -54,20 +56,26 @@ class FunctionOfScalar : public Function { template void FunctionOfScalar::registerKeywords(Keywords& keys) { - Function::registerKeywords(keys); keys.use("ARG"); std::string name = keys.getDisplayName(); - std::size_t und=name.find("_SCALAR"); keys.setDisplayName( name.substr(0,und) ); + Function::registerKeywords(keys); + keys.use("ARG"); + std::string name = keys.getDisplayName(); + std::size_t und=name.find("_SCALAR"); + keys.setDisplayName( name.substr(0,und) ); keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); - T tfunc; tfunc.registerKeywords( keys ); - if( keys.getDisplayName()=="SUM" ) keys.setValueDescription("the sum of all the input arguments"); - else if( keys.getDisplayName()=="MEAN" ) keys.setValueDescription("the mean of all the input arguments"); + T tfunc; + tfunc.registerKeywords( keys ); + if( keys.getDisplayName()=="SUM" ) { + keys.setValueDescription("the sum of all the input arguments"); + } else if( keys.getDisplayName()=="MEAN" ) { + keys.setValueDescription("the mean of all the input arguments"); + } } template FunctionOfScalar::FunctionOfScalar(const ActionOptions&ao): Action(ao), Function(ao), - firststep(true) -{ + firststep(true) { myfunc.read( this ); // Get the names of the components std::vector components( keywords.getOutputComponents() ); @@ -75,42 +83,74 @@ FunctionOfScalar::FunctionOfScalar(const ActionOptions&ao): std::vector str_ind( myfunc.getComponentsPerLabel() ); for(unsigned i=0; i0 ) { - std::string compstr = components[i]; if( compstr==".#!value" ) compstr = ""; - for(unsigned j=0; jgetName() + components[i] ); } - } else addComponentWithDerivatives( components[i] ); + std::string compstr = components[i]; + if( compstr==".#!value" ) { + compstr = ""; + } + for(unsigned j=0; jgetName() + components[i] ); + } + } + } else { + addComponentWithDerivatives( components[i] ); + } } // Set the periodicities of the output components - myfunc.setPeriodicityForOutputs( this ); myfunc.setPrefactor( this, 1.0 ); + myfunc.setPeriodicityForOutputs( this ); + myfunc.setPrefactor( this, 1.0 ); } template std::string FunctionOfScalar::getOutputComponentDescription( const std::string& cname, const Keywords& keys ) const { - if( getName().find("SORT")==std::string::npos ) return ActionWithValue::getOutputComponentDescription( cname, keys ); + if( getName().find("SORT")==std::string::npos ) { + return ActionWithValue::getOutputComponentDescription( cname, keys ); + } return "the " + cname + "th largest of the input scalars"; } template void FunctionOfScalar::turnOnDerivatives() { - if( !myfunc.derivativesImplemented() ) error("derivatives have not been implemended for " + getName() ); + if( !myfunc.derivativesImplemented() ) { + error("derivatives have not been implemended for " + getName() ); + } ActionWithValue::turnOnDerivatives(); } template void FunctionOfScalar::calculate() { - if( firststep ) { myfunc.setup( this ); firststep=false; } unsigned argstart = myfunc.getArgStart(); - std::vector args( getNumberOfArguments() - argstart ); for(unsigned i=argstart; iget(); - std::vector vals( getNumberOfComponents() ); Matrix derivatives( getNumberOfComponents(), args.size() ); + if( firststep ) { + myfunc.setup( this ); + firststep=false; + } + unsigned argstart = myfunc.getArgStart(); + std::vector args( getNumberOfArguments() - argstart ); + for(unsigned i=argstart; iget(); + } + std::vector vals( getNumberOfComponents() ); + Matrix derivatives( getNumberOfComponents(), args.size() ); myfunc.calc( this, args, vals, derivatives ); - for(unsigned i=0; iset(vals[i]); - if( doNotCalculateDerivatives() ) return; + for(unsigned i=0; iset(vals[i]); + } + if( doNotCalculateDerivatives() ) { + return; + } for(unsigned i=0; i& task_reducing_actions ); /// Get the label to write in the graph - std::string writeInGraph() const override { return myfunc.getGraphInfo( getName() ); } + std::string writeInGraph() const override { + return myfunc.getGraphInfo( getName() ); + } /// This builds the task list for the action void calculate() override; /// This ensures that we create some bookeeping stuff during the first step @@ -74,11 +76,17 @@ class FunctionOfVector : public ActionWithVector { template void FunctionOfVector::registerKeywords(Keywords& keys ) { - Action::registerKeywords(keys); ActionWithValue::registerKeywords(keys); ActionWithArguments::registerKeywords(keys); keys.use("ARG"); - std::string name = keys.getDisplayName(); std::size_t und=name.find("_VECTOR"); keys.setDisplayName( name.substr(0,und) ); + Action::registerKeywords(keys); + ActionWithValue::registerKeywords(keys); + ActionWithArguments::registerKeywords(keys); + keys.use("ARG"); + std::string name = keys.getDisplayName(); + std::size_t und=name.find("_VECTOR"); + keys.setDisplayName( name.substr(0,und) ); keys.reserve("compulsory","PERIODIC","if the output of your function is periodic then you should specify the periodicity of the function. If the output is not periodic you must state this using PERIODIC=NO"); keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); - T tfunc; tfunc.registerKeywords( keys ); + T tfunc; + tfunc.registerKeywords( keys ); if( keys.getDisplayName()=="SUM" ) { keys.setValueDescription("the sum of all the elements in the input vector"); } else if( keys.getDisplayName()=="MEAN" ) { @@ -100,45 +108,70 @@ FunctionOfVector::FunctionOfVector(const ActionOptions&ao): ActionWithVector(ao), doAtEnd(true), firststep(true), - nderivatives(0) -{ + nderivatives(0) { // Get the shape of the output - std::vector shape(1); shape[0]=getNumberOfFinalTasks(); + std::vector shape(1); + shape[0]=getNumberOfFinalTasks(); // Read the input and do some checks myfunc.read( this ); // Create the task list if( myfunc.doWithTasks() ) { - doAtEnd=false; if( shape[0]>0 ) done_in_chain=true; - } else { plumed_assert( getNumberOfArguments()==1 ); done_in_chain=false; getPntrToArgument(0)->buildDataStore(); } + doAtEnd=false; + if( shape[0]>0 ) { + done_in_chain=true; + } + } else { + plumed_assert( getNumberOfArguments()==1 ); + done_in_chain=false; + getPntrToArgument(0)->buildDataStore(); + } // Get the names of the components std::vector components( keywords.getOutputComponents() ); // Create the values to hold the output std::vector str_ind( myfunc.getComponentsPerLabel() ); for(unsigned i=0; i0 ) { - std::string strcompn = components[i]; if( components[i]==".#!value" ) strcompn = ""; + std::string strcompn = components[i]; + if( components[i]==".#!value" ) { + strcompn = ""; + } for(unsigned j=0; jgetName() + components[i] ); - else addComponent( getPntrToArgument(i)->getName() + components[i], shape ); + if( myfunc.zeroRank() ) { + addComponentWithDerivatives( getPntrToArgument(i)->getName() + components[i] ); + } else { + addComponent( getPntrToArgument(i)->getName() + components[i], shape ); + } } } - } else if( components[i]==".#!value" && myfunc.zeroRank() ) addValueWithDerivatives(); - else if( components[i]==".#!value" ) addValue(shape); - else if( myfunc.zeroRank() ) addComponentWithDerivatives( components[i] ); - else addComponent( components[i], shape ); + } else if( components[i]==".#!value" && myfunc.zeroRank() ) { + addValueWithDerivatives(); + } else if( components[i]==".#!value" ) { + addValue(shape); + } else if( myfunc.zeroRank() ) { + addComponentWithDerivatives( components[i] ); + } else { + addComponent( components[i], shape ); + } } // Check if we can turn off the derivatives when they are zero if( myfunc.getDerivativeZeroIfValueIsZero() ) { - for(int i=0; isetDerivativeIsZeroWhenValueIsZero(); + for(int i=0; isetDerivativeIsZeroWhenValueIsZero(); + } } // Check if this is a timeseries unsigned argstart=myfunc.getArgStart(); @@ -157,32 +190,48 @@ FunctionOfVector::FunctionOfVector(const ActionOptions&ao): // No chains if we are using a sum or a mean if( getPntrToArgument(i)->getRank()==0 ) { FunctionOfVector* as = dynamic_cast*>( getPntrToArgument(i)->getPntrToAction() ); - if(as) done_in_chain=false; + if(as) { + done_in_chain=false; + } } else { ActionWithVector* av=dynamic_cast( getPntrToArgument(i)->getPntrToAction() ); - if( !av ) done_in_chain=false; + if( !av ) { + done_in_chain=false; + } } } // Don't need to do the calculation in a chain if the input is constant bool allconstant=true; for(unsigned i=argstart; iisConstant() ) { allconstant=false; break; } + if( !getPntrToArgument(i)->isConstant() ) { + allconstant=false; + break; + } + } + if( allconstant ) { + done_in_chain=false; } - if( allconstant ) done_in_chain=false; nderivatives = buildArgumentStore(myfunc.getArgStart()); } template std::string FunctionOfVector::getOutputComponentDescription( const std::string& cname, const Keywords& keys ) const { - if( getName().find("SORT")==std::string::npos ) return ActionWithValue::getOutputComponentDescription( cname, keys ); - if( getNumberOfArguments()==1 ) return "the " + cname + "th largest element of the vector " + getPntrToArgument(0)->getName(); + if( getName().find("SORT")==std::string::npos ) { + return ActionWithValue::getOutputComponentDescription( cname, keys ); + } + if( getNumberOfArguments()==1 ) { + return "the " + cname + "th largest element of the vector " + getPntrToArgument(0)->getName(); + } return "the " + cname + "th largest element in the input vectors"; } template void FunctionOfVector::turnOnDerivatives() { - if( !getPntrToComponent(0)->isConstant() && !myfunc.derivativesImplemented() ) error("derivatives have not been implemended for " + getName() ); - ActionWithValue::turnOnDerivatives(); myfunc.setup(this ); + if( !getPntrToComponent(0)->isConstant() && !myfunc.derivativesImplemented() ) { + error("derivatives have not been implemended for " + getName() ); + } + ActionWithValue::turnOnDerivatives(); + myfunc.setup(this ); } template @@ -192,15 +241,19 @@ unsigned FunctionOfVector::getNumberOfDerivatives() { template void FunctionOfVector::prepare() { - unsigned argstart = myfunc.getArgStart(); std::vector shape(1); + unsigned argstart = myfunc.getArgStart(); + std::vector shape(1); for(unsigned i=argstart; igetRank()==1 ) { - shape[0] = getPntrToArgument(i)->getShape()[0]; break; + shape[0] = getPntrToArgument(i)->getShape()[0]; + break; } } for(unsigned i=0; igetRank()==1 && myval->getShape()[0]!=shape[0] ) { myval->setShape(shape); } + if( myval->getRank()==1 && myval->getShape()[0]!=shape[0] ) { + myval->setShape(shape); + } } ActionWithVector::prepare(); } @@ -211,8 +264,11 @@ void FunctionOfVector::setupStreamedComponents( const std::string& headstr, u stored_arguments.resize( getNumberOfArguments() ); std::string control = getFirstActionInChain()->getLabel(); for(unsigned i=0; iisConstant() ) stored_arguments[i]=false; - else stored_arguments[i] = !getPntrToArgument(i)->ignoreStoredValue( control ); + if( getPntrToArgument(i)->isConstant() ) { + stored_arguments[i]=false; + } else { + stored_arguments[i] = !getPntrToArgument(i)->ignoreStoredValue( control ); + } } firststep=false; } @@ -221,26 +277,39 @@ void FunctionOfVector::setupStreamedComponents( const std::string& headstr, u template void FunctionOfVector::performTask( const unsigned& current, MultiValue& myvals ) const { - unsigned argstart=myfunc.getArgStart(); std::vector args( getNumberOfArguments()-argstart); + unsigned argstart=myfunc.getArgStart(); + std::vector args( getNumberOfArguments()-argstart); if( actionInChain() ) { for(unsigned i=argstart; igetRank()==0 ) args[i-argstart] = getPntrToArgument(i)->get(); - else if( !getPntrToArgument(i)->valueHasBeenSet() ) args[i-argstart] = myvals.get( getPntrToArgument(i)->getPositionInStream() ); - else args[i-argstart] = getPntrToArgument(i)->get( myvals.getTaskIndex() ); + if( getPntrToArgument(i)->getRank()==0 ) { + args[i-argstart] = getPntrToArgument(i)->get(); + } else if( !getPntrToArgument(i)->valueHasBeenSet() ) { + args[i-argstart] = myvals.get( getPntrToArgument(i)->getPositionInStream() ); + } else { + args[i-argstart] = getPntrToArgument(i)->get( myvals.getTaskIndex() ); + } } } else { for(unsigned i=argstart; igetRank()==1 ) args[i-argstart]=getPntrToArgument(i)->get(current); - else args[i-argstart] = getPntrToArgument(i)->get(); + if( getPntrToArgument(i)->getRank()==1 ) { + args[i-argstart]=getPntrToArgument(i)->get(current); + } else { + args[i-argstart] = getPntrToArgument(i)->get(); + } } } // Calculate the function and its derivatives - std::vector vals( getNumberOfComponents() ); Matrix derivatives( getNumberOfComponents(), args.size() ); + std::vector vals( getNumberOfComponents() ); + Matrix derivatives( getNumberOfComponents(), args.size() ); myfunc.calc( this, args, vals, derivatives ); // And set the values - for(unsigned i=0; igetPositionInStream(), vals[i] ); + for(unsigned i=0; igetPositionInStream(), vals[i] ); + } // Return if we are not computing derivatives - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } // And now compute the derivatives // Second condition here is only not true if actionInChain()==True if // input arguments the only non-constant objects in input are scalars. @@ -250,8 +319,12 @@ void FunctionOfVector::performTask( const unsigned& current, MultiValue& myva for(unsigned j=0; jgetPositionInStream(); if( stored_arguments[argstart+j] ) { - unsigned task_index = myvals.getTaskIndex(); if( getPntrToArgument(argstart+j)->getRank()==0 ) task_index=0; - myvals.addDerivative( istrn, task_index, 1.0 ); myvals.updateIndex( istrn, task_index ); + unsigned task_index = myvals.getTaskIndex(); + if( getPntrToArgument(argstart+j)->getRank()==0 ) { + task_index=0; + } + myvals.addDerivative( istrn, task_index, 1.0 ); + myvals.updateIndex( istrn, task_index ); } unsigned arg_deriv_s = arg_deriv_starts[argstart+j]; for(unsigned k=0; k::performTask( const unsigned& current, MultiValue& myva } } // Ensure we only store one lot of derivative indices - bool found=false; ActionWithValue* aav=getPntrToArgument(argstart+j)->getPntrToAction(); + bool found=false; + ActionWithValue* aav=getPntrToArgument(argstart+j)->getPntrToAction(); for(unsigned k=0; kgetPntrToAction()!=aav ) { ActionWithVector* av = dynamic_cast( getPntrToArgument(argstart+j)->getPntrToAction() ); if( av ) { - for(int i=0; iupdateAdditionalIndices( getConstPntrToComponent(i)->getPositionInStream(), myvals ); + for(int i=0; iupdateAdditionalIndices( getConstPntrToComponent(i)->getPositionInStream(), myvals ); + } } } - found=true; break; + found=true; + break; } } - if( found ) continue; + if( found ) { + continue; + } for(unsigned k=0; k::getNumberOfFinalTasks() { if( nelements>0 ) { // if( getPntrToArgument(i)->isTimeSeries() && getPntrToArgument(i)->getShape()[0]isTimeSeries(); // else - if(getPntrToArgument(i)->getShape()[0]!=nelements ) error("all vectors input should have the same length"); - } else if( nelements==0 ) nelements=getPntrToArgument(i)->getShape()[0]; + if(getPntrToArgument(i)->getShape()[0]!=nelements ) { + error("all vectors input should have the same length"); + } + } else if( nelements==0 ) { + nelements=getPntrToArgument(i)->getShape()[0]; + } plumed_assert( !getPntrToArgument(i)->hasDerivatives() ); } } @@ -325,34 +408,56 @@ unsigned FunctionOfVector::getNumberOfFinalTasks() { template void FunctionOfVector::areAllTasksRequired( std::vector& task_reducing_actions ) { - if( task_reducing_actions.size()==0 ) return; - if( !myfunc.allComponentsRequired( getArguments(), task_reducing_actions ) ) task_reducing_actions.push_back(this); + if( task_reducing_actions.size()==0 ) { + return; + } + if( !myfunc.allComponentsRequired( getArguments(), task_reducing_actions ) ) { + task_reducing_actions.push_back(this); + } } template void FunctionOfVector::runSingleTaskCalculation( const Value* arg, ActionWithValue* action, T& f ) { // This is used if we are doing sorting actions on a single vector - unsigned nv = arg->getNumberOfValues(); std::vector args( nv ); - for(unsigned i=0; iget(i); - std::vector vals( action->getNumberOfComponents() ); Matrix derivatives( action->getNumberOfComponents(), nv ); - ActionWithArguments* aa=dynamic_cast(action); plumed_assert( aa ); f.calc( aa, args, vals, derivatives ); - for(unsigned i=0; icopyOutput(i)->set( vals[i] ); + unsigned nv = arg->getNumberOfValues(); + std::vector args( nv ); + for(unsigned i=0; iget(i); + } + std::vector vals( action->getNumberOfComponents() ); + Matrix derivatives( action->getNumberOfComponents(), nv ); + ActionWithArguments* aa=dynamic_cast(action); + plumed_assert( aa ); + f.calc( aa, args, vals, derivatives ); + for(unsigned i=0; icopyOutput(i)->set( vals[i] ); + } // Return if we are not computing derivatives - if( action->doNotCalculateDerivatives() ) return; + if( action->doNotCalculateDerivatives() ) { + return; + } // Now set the derivatives for(unsigned j=0; jcopyOutput(i)->setDerivative( j, derivatives(i,j) ); + for(unsigned i=0; icopyOutput(i)->setDerivative( j, derivatives(i,j) ); + } } } template void FunctionOfVector::calculate() { // Everything is done elsewhere - if( actionInChain() ) return; + if( actionInChain() ) { + return; + } // This is done if we are calculating a function of multiple cvs - if( !doAtEnd ) runAllTasks(); + if( !doAtEnd ) { + runAllTasks(); + } // This is used if we are doing sorting actions on a single vector - else if( !myfunc.doWithTasks() ) runSingleTaskCalculation( getPntrToArgument(0), this, myfunc ); + else if( !myfunc.doWithTasks() ) { + runSingleTaskCalculation( getPntrToArgument(0), this, myfunc ); + } } } diff --git a/src/function/FunctionShortcut.h b/src/function/FunctionShortcut.h index 7a730dbddb..9a2ac9b89c 100644 --- a/src/function/FunctionShortcut.h +++ b/src/function/FunctionShortcut.h @@ -48,42 +48,71 @@ void FunctionShortcut::registerKeywords(Keywords& keys ) { ActionShortcut::registerKeywords( keys ); keys.add("numbered","ARG","the input to this function"); keys.reserve("compulsory","PERIODIC","if the output of your function is periodic then you should specify the periodicity of the function. If the output is not periodic you must state this using PERIODIC=NO"); - keys.addActionNameSuffix("_SCALAR"); keys.addActionNameSuffix("_VECTOR"); keys.addActionNameSuffix("_MATRIX"); keys.addActionNameSuffix("_GRID"); - T tfunc; tfunc.registerKeywords( keys ); + keys.addActionNameSuffix("_SCALAR"); + keys.addActionNameSuffix("_VECTOR"); + keys.addActionNameSuffix("_MATRIX"); + keys.addActionNameSuffix("_GRID"); + T tfunc; + tfunc.registerKeywords( keys ); } template FunctionShortcut::FunctionShortcut(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - std::vector args; parseVector("ARG",args); - std::string allargs=args[0]; for(unsigned i=1; i vals; ActionWithArguments::interpretArgumentList( args, plumed.getActionSet(), this, vals ); - if( vals.size()==0 ) error("found no input arguments to function"); + ActionShortcut(ao) { + std::vector args; + parseVector("ARG",args); + std::string allargs=args[0]; + for(unsigned i=1; i vals; + ActionWithArguments::interpretArgumentList( args, plumed.getActionSet(), this, vals ); + if( vals.size()==0 ) { + error("found no input arguments to function"); + } createAction( this, vals, allargs ); } template void FunctionShortcut::createAction( ActionShortcut* action, const std::vector& vals, const std::string& allargs ) { - unsigned maxrank=vals[0]->getRank(); bool isgrid=false; + unsigned maxrank=vals[0]->getRank(); + bool isgrid=false; for(unsigned i=0; igetRank()>0 && vals[i]->hasDerivatives() ) isgrid=true; - if( vals[i]->getRank()>maxrank ) maxrank=vals[i]->getRank(); + if( vals[i]->getRank()>0 && vals[i]->hasDerivatives() ) { + isgrid=true; + } + if( vals[i]->getRank()>maxrank ) { + maxrank=vals[i]->getRank(); + } } if( isgrid ) { - if( actionRegister().check( action->getName() + "_GRID") ) action->readInputLine( action->getShortcutLabel() + ": " + action->getName() + "_GRID ARG=" + allargs + " " + action->convertInputLineToString() ); - else plumed_merror("there is no action registered that allows you to do " + action->getName() + " with functions on a grid"); + if( actionRegister().check( action->getName() + "_GRID") ) { + action->readInputLine( action->getShortcutLabel() + ": " + action->getName() + "_GRID ARG=" + allargs + " " + action->convertInputLineToString() ); + } else { + plumed_merror("there is no action registered that allows you to do " + action->getName() + " with functions on a grid"); + } } else if( maxrank==0 ) { - if( actionRegister().check( action->getName() + "_SCALAR") ) action->readInputLine( action->getShortcutLabel() + ": " + action->getName() + "_SCALAR ARG=" + allargs + " " + action->convertInputLineToString() ); - else plumed_merror("there is no action registered that allows you to do " + action->getName() + " with scalars"); + if( actionRegister().check( action->getName() + "_SCALAR") ) { + action->readInputLine( action->getShortcutLabel() + ": " + action->getName() + "_SCALAR ARG=" + allargs + " " + action->convertInputLineToString() ); + } else { + plumed_merror("there is no action registered that allows you to do " + action->getName() + " with scalars"); + } } else if( maxrank==1 ) { - if( actionRegister().check( action->getName() + "_VECTOR") ) action->readInputLine( action->getShortcutLabel() + ": " + action->getName() + "_VECTOR ARG=" + allargs + " " + action->convertInputLineToString() ); - else plumed_merror("there is no action registered that allows you to do " + action->getName() + " with vectors"); + if( actionRegister().check( action->getName() + "_VECTOR") ) { + action->readInputLine( action->getShortcutLabel() + ": " + action->getName() + "_VECTOR ARG=" + allargs + " " + action->convertInputLineToString() ); + } else { + plumed_merror("there is no action registered that allows you to do " + action->getName() + " with vectors"); + } } else if( maxrank==2 ) { - if( actionRegister().check( action->getName() + "_MATRIX") ) action->readInputLine( action->getShortcutLabel() + ": " + action->getName() + "_MATRIX ARG=" + allargs + " " + action->convertInputLineToString() ); - else plumed_merror("there is no action registered that allows you to do " + action->getName() + " with matrices"); - } else plumed_error(); + if( actionRegister().check( action->getName() + "_MATRIX") ) { + action->readInputLine( action->getShortcutLabel() + ": " + action->getName() + "_MATRIX ARG=" + allargs + " " + action->convertInputLineToString() ); + } else { + plumed_merror("there is no action registered that allows you to do " + action->getName() + " with matrices"); + } + } else { + plumed_error(); + } } } diff --git a/src/function/FunctionTemplateBase.h b/src/function/FunctionTemplateBase.h index 27bd657feb..ab723d97e3 100644 --- a/src/function/FunctionTemplateBase.h +++ b/src/function/FunctionTemplateBase.h @@ -44,20 +44,30 @@ class FunctionTemplateBase { void parseFlag( Action* action, const std::string&key, bool&t ); public: /// Override this function if you have not implemented the derivatives - virtual bool derivativesImplemented() { return true; } + virtual bool derivativesImplemented() { + return true; + } //// virtual std::vector getComponentsPerLabel() const ; - virtual bool getDerivativeZeroIfValueIsZero() const { return false; } + virtual bool getDerivativeZeroIfValueIsZero() const { + return false; + } virtual std::string getGraphInfo( const std::string& lab ) const ; virtual void registerKeywords( Keywords& keys ) = 0; virtual void read( ActionWithArguments* action ) = 0; - virtual bool doWithTasks() const { return true; } + virtual bool doWithTasks() const { + return true; + } virtual std::vector getArgumentsToCheck( const std::vector& args ); bool allComponentsRequired( const std::vector& args, const std::vector& actions ); - virtual bool zeroRank() const { return false; } + virtual bool zeroRank() const { + return false; + } virtual void setPeriodicityForOutputs( ActionWithValue* action ); virtual void setPrefactor( ActionWithArguments* action, const double pref ) {} - virtual unsigned getArgStart() const { return 0; } + virtual unsigned getArgStart() const { + return 0; + } virtual void setup( ActionWithValue* action ); virtual void calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const = 0; }; @@ -79,16 +89,21 @@ void FunctionTemplateBase::parseFlag( Action* action, const std::string&key, boo inline std::vector FunctionTemplateBase::getComponentsPerLabel() const { - std::vector comps; return comps; + std::vector comps; + return comps; } inline void FunctionTemplateBase::setup( ActionWithValue* action ) { noderiv=action->doNotCalculateDerivatives(); // Check for grids in input - ActionWithArguments* aarg=dynamic_cast( action ); plumed_assert( aarg ); + ActionWithArguments* aarg=dynamic_cast( action ); + plumed_assert( aarg ); for(unsigned i=0; igetNumberOfArguments(); ++i) { - if( aarg->getPntrToArgument(i)->getRank()>0 && aarg->getPntrToArgument(i)->hasDerivatives() ) { noderiv=false; break; } + if( aarg->getPntrToArgument(i)->getRank()>0 && aarg->getPntrToArgument(i)->hasDerivatives() ) { + noderiv=false; + break; + } } } @@ -96,13 +111,21 @@ inline void FunctionTemplateBase::setPeriodicityForOutputs( ActionWithValue* action ) { plumed_massert( action->getNumberOfComponents()==1,"you must defined a setPeriodicityForOutputs function in your function class"); if( action->keywords.exists("PERIODIC") ) { - std::vector period; parseVector(action,"PERIODIC",period); + std::vector period; + parseVector(action,"PERIODIC",period); if( period.size()==1 ) { - if( period[0]!="NO") action->error("input to PERIODIC keyword does not make sense"); - action->setNotPeriodic(); return; - } else if( period.size()!=2 ) action->error("input to PERIODIC keyword does not make sense"); + if( period[0]!="NO") { + action->error("input to PERIODIC keyword does not make sense"); + } + action->setNotPeriodic(); + return; + } else if( period.size()!=2 ) { + action->error("input to PERIODIC keyword does not make sense"); + } action->setPeriodic( period[0], period[1] ); - } else action->setNotPeriodic(); + } else { + action->setNotPeriodic(); + } } inline @@ -115,19 +138,27 @@ bool FunctionTemplateBase::allComponentsRequired( const std::vector& arg std::vector checkArgs = getArgumentsToCheck( args ); for(unsigned i=0; i( checkArgs[i]->getPntrToAction() ); - if( !av ) return false; + if( !av ) { + return false; + } bool found=false; for(unsigned j=0; j& args, std::vector& vals, Matrix& derivatives ) const override; }; @@ -104,17 +108,27 @@ PLUMED_REGISTER_ACTION(VectorHighest,"HIGHEST_VECTOR") PLUMED_REGISTER_ACTION(VectorHighest,"LOWEST_VECTOR") void Highest::registerKeywords( Keywords& keys ) { - if( keys.getDisplayName().find("LOWEST") ) keys.setValueDescription("the lowest of the input values"); - else keys.setValueDescription("the highest of the input values"); + if( keys.getDisplayName().find("LOWEST") ) { + keys.setValueDescription("the lowest of the input values"); + } else { + keys.setValueDescription("the highest of the input values"); + } } void Highest::read( ActionWithArguments* action ) { - min=action->getName().find("LOWEST")!=std::string::npos; if( !min ) plumed_assert( action->getName().find("HIGHEST")!=std::string::npos ); + min=action->getName().find("LOWEST")!=std::string::npos; + if( !min ) { + plumed_assert( action->getName().find("HIGHEST")!=std::string::npos ); + } for(unsigned i=0; igetNumberOfArguments(); ++i) { - if( action->getPntrToArgument(i)->isPeriodic() ) action->error("Cannot sort periodic values (check argument "+ action->getPntrToArgument(i)->getName() +")"); + if( action->getPntrToArgument(i)->isPeriodic() ) { + action->error("Cannot sort periodic values (check argument "+ action->getPntrToArgument(i)->getName() +")"); + } } scalar_out = action->getNumberOfArguments()==1; - if( scalar_out && action->getPntrToArgument(0)->getRank()==0 ) action->error("sorting a single scalar is trivial"); + if( scalar_out && action->getPntrToArgument(0)->getRank()==0 ) { + action->error("sorting a single scalar is trivial"); + } } void Highest::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { diff --git a/src/function/LessThan.cpp b/src/function/LessThan.cpp index 780ae9a6e1..a544a2cad0 100644 --- a/src/function/LessThan.cpp +++ b/src/function/LessThan.cpp @@ -77,30 +77,49 @@ void LessThan::registerKeywords(Keywords& keys) { } void LessThan::read( ActionWithArguments* action ) { - if( action->getNumberOfArguments()!=1 ) action->error("should only be one argument to less_than actions"); - if( action->getPntrToArgument(0)->isPeriodic() ) action->error("cannot use this function on periodic functions"); + if( action->getNumberOfArguments()!=1 ) { + action->error("should only be one argument to less_than actions"); + } + if( action->getPntrToArgument(0)->isPeriodic() ) { + action->error("cannot use this function on periodic functions"); + } std::string sw,errors; action->parse("SWITCH",sw); if(sw.length()>0) { switchingFunction.set(sw,errors); - if( errors.length()!=0 ) action->error("problem reading SWITCH keyword : " + errors ); + if( errors.length()!=0 ) { + action->error("problem reading SWITCH keyword : " + errors ); + } } else { - int nn=6; int mm=0; double d0=0.0; double r0=0.0; action->parse("R_0",r0); - if(r0<=0.0) action->error("R_0 should be explicitly specified and positive"); - action->parse("D_0",d0); action->parse("NN",nn); action->parse("MM",mm); + int nn=6; + int mm=0; + double d0=0.0; + double r0=0.0; + action->parse("R_0",r0); + if(r0<=0.0) { + action->error("R_0 should be explicitly specified and positive"); + } + action->parse("D_0",d0); + action->parse("NN",nn); + action->parse("MM",mm); switchingFunction.set(nn,mm,r0,d0); } action->log<<" using switching function with cutoff "<parseFlag("SQUARED",squared); - if( squared ) action->log<<" input quantity is square of quantity that switching function acts upon\n"; + if( squared ) { + action->log<<" input quantity is square of quantity that switching function acts upon\n"; + } } void LessThan::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { plumed_dbg_assert( args.size()==1 ); - if( squared ) vals[0] = switchingFunction.calculateSqr( args[0], derivatives(0,0) ); - else vals[0] = switchingFunction.calculate( args[0], derivatives(0,0) ); + if( squared ) { + vals[0] = switchingFunction.calculateSqr( args[0], derivatives(0,0) ); + } else { + vals[0] = switchingFunction.calculate( args[0], derivatives(0,0) ); + } derivatives(0,0) = args[0]*derivatives(0,0); } diff --git a/src/function/LessThan.h b/src/function/LessThan.h index 5c342f2220..6a425cf835 100644 --- a/src/function/LessThan.h +++ b/src/function/LessThan.h @@ -34,7 +34,9 @@ class LessThan : public FunctionTemplateBase { public: void registerKeywords( Keywords& keys ) override; void read( ActionWithArguments* action ) override; - bool getDerivativeZeroIfValueIsZero() const override { return true; } + bool getDerivativeZeroIfValueIsZero() const override { + return true; + } void calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const override; }; diff --git a/src/function/LocalEnsemble.cpp b/src/function/LocalEnsemble.cpp index f417f3fb8c..1f8d548834 100644 --- a/src/function/LocalEnsemble.cpp +++ b/src/function/LocalEnsemble.cpp @@ -74,8 +74,7 @@ res: RESTRAINT ARG=stca.*,stcb.*,stco.*,sthn.*,stnh.* AT=0.,0.,0.,0.,0. KAPPA=0. class LocalEnsemble : - public Function -{ + public Function { unsigned ens_dim; unsigned narg; public: @@ -98,22 +97,31 @@ void LocalEnsemble::registerKeywords(Keywords& keys) { LocalEnsemble::LocalEnsemble(const ActionOptions&ao): Action(ao), Function(ao), - ens_dim(0) -{ + ens_dim(0) { parse("NUM",ens_dim); - if(ens_dim==0) error("NUM should be greater or equal to 1"); + if(ens_dim==0) { + error("NUM should be greater or equal to 1"); + } std::vector arg; int oldsize=-1; for(unsigned i=1; i<=ens_dim; ++i ) { std::vector larg; - if(!parseArgumentList("ARG",i,larg)) break; - for(unsigned j=0; j(larg.size())) error("In LOCALENSEMBLE you should have the same number of arguments for each ARG keyword"); + if(!parseArgumentList("ARG",i,larg)) { + break; + } + for(unsigned j=0; j(larg.size())) { + error("In LOCALENSEMBLE you should have the same number of arguments for each ARG keyword"); + } oldsize = larg.size(); if(!larg.empty()) { log.printf(" with arguments %u: ", i); - for(unsigned j=0; jgetName().c_str()); + for(unsigned j=0; jgetName().c_str()); + } log.printf("\n"); } } @@ -134,8 +142,7 @@ std::string LocalEnsemble::getOutputComponentDescription( const std::string& cna return "the average for argument named " + cname; } -void LocalEnsemble::calculate() -{ +void LocalEnsemble::calculate() { const double fact = 1.0/static_cast(ens_dim); #pragma omp parallel for num_threads(OpenMP::getNumThreads()) for(unsigned i=0; i getComponentsPerLabel() const override ; void setPeriodicityForOutputs( ActionWithValue* action ) override; void calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const override; @@ -90,61 +94,93 @@ void Moments::registerKeywords(Keywords& keys) { void Moments::read( ActionWithArguments* action ) { scalar_out = action->getNumberOfArguments()==1; - if( scalar_out && action->getPntrToArgument(0)->getRank()==0 ) action->error("cannot calculate moments if only given one variable"); + if( scalar_out && action->getPntrToArgument(0)->getRank()==0 ) { + action->error("cannot calculate moments if only given one variable"); + } isperiodic = (action->getPntrToArgument(0))->isPeriodic(); if( isperiodic ) { - std::string str_min, str_max; (action->getPntrToArgument(0))->getDomain( str_min, str_max ); + std::string str_min, str_max; + (action->getPntrToArgument(0))->getDomain( str_min, str_max ); for(unsigned i=1; igetNumberOfArguments(); ++i) { - if( !(action->getPntrToArgument(i))->isPeriodic() ) action->error("cannot mix periodic and non periodic variables when calculating moments"); - std::string str_min2, str_max2; (action->getPntrToArgument(i))->getDomain( str_min2, str_max2); - if( str_min!=str_min2 || str_max!=str_max2 ) action->error("all input arguments should have same domain when calculating moments"); + if( !(action->getPntrToArgument(i))->isPeriodic() ) { + action->error("cannot mix periodic and non periodic variables when calculating moments"); + } + std::string str_min2, str_max2; + (action->getPntrToArgument(i))->getDomain( str_min2, str_max2); + if( str_min!=str_min2 || str_max!=str_max2 ) { + action->error("all input arguments should have same domain when calculating moments"); + } } - Tools::convert(str_min,min); Tools::convert(str_max,max); pfactor = 2*pi / ( max-min ); + Tools::convert(str_min,min); + Tools::convert(str_max,max); + pfactor = 2*pi / ( max-min ); } else { for(unsigned i=1; igetNumberOfArguments(); ++i) { - if( (action->getPntrToArgument(i))->isPeriodic() ) action->error("cannot mix periodic and non periodic variables when calculating moments"); + if( (action->getPntrToArgument(i))->isPeriodic() ) { + action->error("cannot mix periodic and non periodic variables when calculating moments"); + } } } parseVector(action,"POWERS",powers); for(unsigned i=0; ierror("first central moment is zero do you really need to calculate that"); + if( powers[i]<2 ) { + action->error("first central moment is zero do you really need to calculate that"); + } action->log.printf(" computing %dth central moment of distribution of input cvs \n", powers[i]); } } std::vector Moments::getComponentsPerLabel() const { - std::vector comp; std::string num; + std::vector comp; + std::string num; for(unsigned i=0; icomponentIsNotPeriodic("moment-" + num); } + for(unsigned i=0; icomponentIsNotPeriodic("moment-" + num); + } } void Moments::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { - double mean=0; double inorm = 1.0 / static_cast( args.size() ); + double mean=0; + double inorm = 1.0 / static_cast( args.size() ); if( isperiodic ) { double sinsum=0, cossum=0, val; - for(unsigned i=0; igetPntrToArgument(0); for(unsigned npow=0; npowdifference( mean, args[i] ), powers[npow] - 1 ); - dev1*=inorm; vals[npow] = 0; double prefactor = powers[npow]*inorm; for(unsigned i=0; idifference( mean, args[i] ); vals[npow] += inorm*pow( tmp, powers[npow] ); + dev1+=pow( arg0->difference( mean, args[i] ), powers[npow] - 1 ); + } + dev1*=inorm; + vals[npow] = 0; + double prefactor = powers[npow]*inorm; + for(unsigned i=0; idifference( mean, args[i] ); + vals[npow] += inorm*pow( tmp, powers[npow] ); derivatives(npow,i) = prefactor*(pow( tmp, powers[npow] - 1 ) - dev1); } } diff --git a/src/function/MoreThan.cpp b/src/function/MoreThan.cpp index f8ddb55324..1ff0d56a7e 100644 --- a/src/function/MoreThan.cpp +++ b/src/function/MoreThan.cpp @@ -77,30 +77,49 @@ void MoreThan::registerKeywords(Keywords& keys) { } void MoreThan::read( ActionWithArguments* action ) { - if( action->getNumberOfArguments()!=1 ) action->error("should only be one argument to more_than actions"); - if( action->getPntrToArgument(0)->isPeriodic() ) action->error("cannot use this function on periodic functions"); + if( action->getNumberOfArguments()!=1 ) { + action->error("should only be one argument to more_than actions"); + } + if( action->getPntrToArgument(0)->isPeriodic() ) { + action->error("cannot use this function on periodic functions"); + } std::string sw,errors; action->parse("SWITCH",sw); if(sw.length()>0) { switchingFunction.set(sw,errors); - if( errors.length()!=0 ) action->error("problem reading SWITCH keyword : " + errors ); + if( errors.length()!=0 ) { + action->error("problem reading SWITCH keyword : " + errors ); + } } else { - int nn=6; int mm=0; double d0=0.0; double r0=0.0; action->parse("R_0",r0); - if(r0<=0.0) action->error("R_0 should be explicitly specified and positive"); - action->parse("D_0",d0); action->parse("NN",nn); action->parse("MM",mm); + int nn=6; + int mm=0; + double d0=0.0; + double r0=0.0; + action->parse("R_0",r0); + if(r0<=0.0) { + action->error("R_0 should be explicitly specified and positive"); + } + action->parse("D_0",d0); + action->parse("NN",nn); + action->parse("MM",mm); switchingFunction.set(nn,mm,r0,d0); } action->log<<" using switching function with cutoff "<parseFlag("SQUARED",squared); - if( squared ) action->log<<" input quantity is square of quantity that switching function acts upon\n"; + if( squared ) { + action->log<<" input quantity is square of quantity that switching function acts upon\n"; + } } void MoreThan::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { plumed_dbg_assert( args.size()==1 ); - if( squared ) vals[0] = 1.0 - switchingFunction.calculateSqr( args[0], derivatives(0,0) ); - else vals[0] = 1.0 - switchingFunction.calculate( args[0], derivatives(0,0) ); + if( squared ) { + vals[0] = 1.0 - switchingFunction.calculateSqr( args[0], derivatives(0,0) ); + } else { + vals[0] = 1.0 - switchingFunction.calculate( args[0], derivatives(0,0) ); + } derivatives(0,0) = -args[0]*derivatives(0,0); } diff --git a/src/function/MoreThan.h b/src/function/MoreThan.h index f5e84f273d..0bf2137b03 100644 --- a/src/function/MoreThan.h +++ b/src/function/MoreThan.h @@ -34,7 +34,9 @@ class MoreThan : public FunctionTemplateBase { public: void registerKeywords( Keywords& keys ) override; void read( ActionWithArguments* action ) override; - bool getDerivativeZeroIfValueIsZero() const override { return true; } + bool getDerivativeZeroIfValueIsZero() const override { + return true; + } void calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const override; }; diff --git a/src/function/Piecewise.cpp b/src/function/Piecewise.cpp index 221bfb9243..e71412b884 100644 --- a/src/function/Piecewise.cpp +++ b/src/function/Piecewise.cpp @@ -102,29 +102,43 @@ void Piecewise::registerKeywords(Keywords& keys) { void Piecewise::read( ActionWithArguments* action ) { for(int i=0;; i++) { std::vector pp; - if(!action->parseNumberedVector("POINT",i,pp) ) break; - if(pp.size()!=2) action->error("points should be in x,y format"); + if(!action->parseNumberedVector("POINT",i,pp) ) { + break; + } + if(pp.size()!=2) { + action->error("points should be in x,y format"); + } points.push_back(std::pair(pp[0],pp[1])); - if(i>0 && points[i].first<=points[i-1].first) action->error("points abscissas should be monotonously increasing"); + if(i>0 && points[i].first<=points[i-1].first) { + action->error("points abscissas should be monotonously increasing"); + } } for(unsigned i=0; igetNumberOfArguments(); i++) { - if(action->getPntrToArgument(i)->isPeriodic()) action->error("Cannot use PIECEWISE on periodic arguments"); + if(action->getPntrToArgument(i)->isPeriodic()) { + action->error("Cannot use PIECEWISE on periodic arguments"); + } } action->log.printf(" on points:"); - for(unsigned i=0; ilog.printf(" (%f,%f)",points[i].first,points[i].second); + for(unsigned i=0; ilog.printf(" (%f,%f)",points[i].first,points[i].second); + } action->log.printf("\n"); } void Piecewise::setPeriodicityForOutputs( ActionWithValue* action ) { - for(unsigned i=0; igetNumberOfComponents(); ++i) action->copyOutput(i)->setNotPeriodic(); + for(unsigned i=0; igetNumberOfComponents(); ++i) { + action->copyOutput(i)->setNotPeriodic(); + } } void Piecewise::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { for(unsigned i=0; i getComponentsPerLabel() const override ; void setPeriodicityForOutputs( ActionWithValue* action ) override; void calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const override; @@ -100,23 +104,35 @@ void Sort::registerKeywords(Keywords& keys) { void Sort::read( ActionWithArguments* action ) { - scalar_out = action->getNumberOfArguments()==1; nargs = action->getNumberOfArguments(); if( scalar_out ) nargs = action->getPntrToArgument(0)->getNumberOfValues(); + scalar_out = action->getNumberOfArguments()==1; + nargs = action->getNumberOfArguments(); + if( scalar_out ) { + nargs = action->getPntrToArgument(0)->getNumberOfValues(); + } for(unsigned i=0; igetNumberOfArguments(); ++i) { - if((action->getPntrToArgument(i))->isPeriodic()) action->error("Cannot sort periodic values (check argument "+ (action->getPntrToArgument(i))->getName() +")"); + if((action->getPntrToArgument(i))->isPeriodic()) { + action->error("Cannot sort periodic values (check argument "+ (action->getPntrToArgument(i))->getName() +")"); + } } } std::vector Sort::getComponentsPerLabel() const { - std::vector comp; std::string num; + std::vector comp; + std::string num; for(unsigned i=0; icomponentIsNotPeriodic( num ); } + for(unsigned i=0; icomponentIsNotPeriodic( num ); + } } void Sort::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { @@ -127,8 +143,12 @@ void Sort::calc( const ActionWithArguments* action, const std::vector& a data[i].second=i; } // STL sort sorts based on first element (value) then second (index) - std::sort(data.begin(),data.end()); derivatives = 0; - for(int i=0; i parameters; bool sqdonly; bool components; @@ -89,46 +88,65 @@ Stats::Stats(const ActionOptions&ao): Function(ao), sqdonly(false), components(false), - upperd(false) -{ + upperd(false) { parseVector("PARAMETERS",parameters); - if(parameters.size()!=static_cast(getNumberOfArguments())&&!parameters.empty()) + if(parameters.size()!=static_cast(getNumberOfArguments())&&!parameters.empty()) { error("Size of PARAMETERS array should be either 0 or the same as of the number of arguments in ARG1"); + } std::vector arg2; parseArgumentList("PARARG",arg2); if(!arg2.empty()) { - if(parameters.size()>0) error("It is not possible to use PARARG and PARAMETERS together"); - if(arg2.size()!=getNumberOfArguments()) error("Size of PARARG array should be the same as number for arguments in ARG"); + if(parameters.size()>0) { + error("It is not possible to use PARARG and PARAMETERS together"); + } + if(arg2.size()!=getNumberOfArguments()) { + error("Size of PARARG array should be the same as number for arguments in ARG"); + } for(unsigned i=0; iget()); - if(arg2[i]->hasDerivatives()==true) error("PARARG can only accept arguments without derivatives"); + if(arg2[i]->hasDerivatives()==true) { + error("PARARG can only accept arguments without derivatives"); + } } } - if(parameters.size()!=getNumberOfArguments()) + if(parameters.size()!=getNumberOfArguments()) { error("PARARG or PARAMETERS arrays should include the same number of elements as the arguments in ARG"); + } - if(getNumberOfArguments()<2) error("STATS need at least two arguments to be used"); + if(getNumberOfArguments()<2) { + error("STATS need at least two arguments to be used"); + } parseFlag("SQDEVSUM",sqdonly); parseFlag("SQDEV",components); parseFlag("UPPERDISTS",upperd); - if(sqdonly&&components) error("You cannot used SQDEVSUM and SQDEV at the sametime"); + if(sqdonly&&components) { + error("You cannot used SQDEVSUM and SQDEV at the sametime"); + } - if(components) sqdonly = true; + if(components) { + sqdonly = true; + } - if(!arg2.empty()) log.printf(" using %zu parameters from inactive actions:", arg2.size()); - else log.printf(" using %zu parameters:", arg2.size()); - for(unsigned i=0; iset(dev*dev); @@ -168,7 +189,9 @@ void Stats::calculate() } setDerivative(val,i,2.*dev); } - if(!components) val->set(nsqd); + if(!components) { + val->set(nsqd); + } } else { diff --git a/src/function/Sum.cpp b/src/function/Sum.cpp index fc2cc01e56..ccc4878f1c 100644 --- a/src/function/Sum.cpp +++ b/src/function/Sum.cpp @@ -106,16 +106,22 @@ typedef FunctionOfMatrix MatrixSum; PLUMED_REGISTER_ACTION(MatrixSum,"SUM_MATRIX") void Sum::registerKeywords( Keywords& keys ) { - keys.use("PERIODIC"); keys.setValueDescription("the sum"); + keys.use("PERIODIC"); + keys.setValueDescription("the sum"); } void Sum::read( ActionWithArguments* action ) { - if( action->getNumberOfArguments()!=1 ) action->error("should only be one argument to sum actions"); + if( action->getNumberOfArguments()!=1 ) { + action->error("should only be one argument to sum actions"); + } } void Sum::setPrefactor( ActionWithArguments* action, const double pref ) { - if(action->getName().find("MEAN")!=std::string::npos) prefactor = pref / (action->getPntrToArgument(0))->getNumberOfValues(); - else prefactor = pref; + if(action->getName().find("MEAN")!=std::string::npos) { + prefactor = pref / (action->getPntrToArgument(0))->getNumberOfValues(); + } else { + prefactor = pref; + } } bool Sum::zeroRank() const { @@ -123,7 +129,8 @@ bool Sum::zeroRank() const { } void Sum::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { - vals[0]=prefactor*args[0]; derivatives(0,0)=prefactor; + vals[0]=prefactor*args[0]; + derivatives(0,0)=prefactor; } } diff --git a/src/funnel/FPS.cpp b/src/funnel/FPS.cpp index 3ca828b7de..5bb67f4518 100644 --- a/src/funnel/FPS.cpp +++ b/src/funnel/FPS.cpp @@ -128,15 +128,15 @@ void FUNNEL_PS::registerKeywords(Keywords& keys) { FUNNEL_PS::FUNNEL_PS(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), - pbc(true),squared(true) -{ + pbc(true),squared(true) { string reference; parse("REFERENCE",reference); string type; type.assign("OPTIMAL"); parseAtomList("LIGAND",ligand_com); - if(ligand_com.size()!=1) + if(ligand_com.size()!=1) { error("Number of specified atoms should be one, normally the COM of the ligand"); + } parseVector("POINTS",points); bool nopbc=!pbc; parseFlag("NOPBC",nopbc); @@ -150,8 +150,9 @@ FUNNEL_PS::FUNNEL_PS(const ActionOptions&ao): checkRead(); // read everything in ang and transform to nm if we are not in natural units - if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) + if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) { error("missing input file " + reference ); + } bool remove_com=true; bool normalize_weights=true; @@ -177,8 +178,11 @@ FUNNEL_PS::FUNNEL_PS(const ActionOptions&ao): log.printf(" average from file %s\n",reference.c_str()); log.printf(" method for alignment : %s \n",type.c_str() ); - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } addComponentWithDerivatives("lp"); componentIsNotPeriodic("lp"); @@ -192,7 +196,9 @@ FUNNEL_PS::FUNNEL_PS(const ActionOptions&ao): // calculator void FUNNEL_PS::calculate() { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } Tensor Rotation; Matrix > drotdpos(3,3); diff --git a/src/funnel/Funnel.cpp b/src/funnel/Funnel.cpp index 7a9c83b851..b5ebd30bbf 100644 --- a/src/funnel/Funnel.cpp +++ b/src/funnel/Funnel.cpp @@ -202,7 +202,9 @@ Funnel::Funnel(const ActionOptions& ao): parse("SAFETY",safety); string file; parse("FILE",file); - if( file.length()==0 ) error("No funnel file name was specified"); + if( file.length()==0 ) { + error("No funnel file name was specified"); + } parse("SCALE",scale_); //Reading optional arguments @@ -275,12 +277,18 @@ Funnel::Funnel(const ActionOptions& ao): gridfile.open(file); BiasGrid_=Grid::create(funcl,getArguments(),gridfile,sparsegrid,spline,true); //not necessary anymore? gridfile.close(); - if(BiasGrid_->getDimension()!=getNumberOfArguments()) error("mismatch between dimensionality of input grid and number of arguments"); + if(BiasGrid_->getDimension()!=getNumberOfArguments()) { + error("mismatch between dimensionality of input grid and number of arguments"); + } for(unsigned i=0; iisPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) error("periodicity mismatch between arguments and input bias"); + if( getPntrToArgument(i)->isPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) { + error("periodicity mismatch between arguments and input bias"); + } } comm.Barrier(); - if(comm.Get_rank()==0 && walkers_mpi) multi_sim_comm.Barrier(); + if(comm.Get_rank()==0 && walkers_mpi) { + multi_sim_comm.Barrier(); + } log<<" Bibliography "<getName().c_str(), getPntrToArgument(1)->getName().c_str(), funcl.c_str(), getPntrToArgument(0)->getName().c_str(), getPntrToArgument(1)->getName().c_str()); - if (sphere==false) pof.printf("#! SET min_%s %f\n", getPntrToArgument(0)->getName().c_str(), MIN_S); - else pof.printf("#! SET min_%s %f\n", getPntrToArgument(0)->getName().c_str(), -z_cc-safety); + if (sphere==false) { + pof.printf("#! SET min_%s %f\n", getPntrToArgument(0)->getName().c_str(), MIN_S); + } else { + pof.printf("#! SET min_%s %f\n", getPntrToArgument(0)->getName().c_str(), -z_cc-safety); + } pof.printf("#! SET max_%s %f\n", getPntrToArgument(0)->getName().c_str(), MAX_S); pof.printf("#! SET nbins_%s %f\n", getPntrToArgument(0)->getName().c_str(), NBIN_S); pof.printf("#! SET periodic_%s false\n", getPntrToArgument(0)->getName().c_str()); @@ -340,76 +349,75 @@ void Funnel::createBIAS(const double& R_cyl, const double& z_cc, const double& a for(int is=0; is <= NBIN_S; is++) { if (sphere==false) { SS = MIN_S + is * DX_S; - } - else { + } else { SS = - z_cc - safety + is * DX_S; } bool cone = false; if (sphere==false) { - if(SS <= z_cc) cone = true; - } - else { - if (SS <= sqrt(pow(z_cc,2)-pow(R_cyl,2))) cone = true; + if(SS <= z_cc) { + cone = true; + } + } else { + if (SS <= sqrt(pow(z_cc,2)-pow(R_cyl,2))) { + cone = true; + } } //Set wall boundaries properly if(cone == true) { if(sphere==false) { Zmax = R_cyl + (z_cc - SS) * tg_alpha; - } - else { + } else { if (SS > -z_cc) { Zmax = sqrt(pow(z_cc,2) - pow(SS,2)); - } - else { + } else { Zmax = 0; } } + } else { + Zmax = R_cyl; } - else Zmax = R_cyl; for(int iz=0; iz <= NBIN_Z; iz++) { ZZ = MIN_Z + iz * DX_Z; //Inside or outside? bool inside; - if(ZZ < Zmax) inside = true; - else inside = false; + if(ZZ < Zmax) { + inside = true; + } else { + inside = false; + } if(inside == true) { POT = 0; FS = 0; FZ = 0; - } - else { + } else { if(cone == true) { if(sphere==false) { POT = 0.5 * KAPPA * (ZZ - Zmax) * (ZZ - Zmax); FZ = - KAPPA * (ZZ - Zmax); FS = - KAPPA * (ZZ - Zmax) * tg_alpha; - } - else { + } else { D = sqrt(pow(ZZ,2)+pow(SS,2)); d = D - z_cc; POT = 0.5 * KAPPA * pow(d,2); FZ = - KAPPA * d * ZZ / D; FS = - KAPPA * d * SS / D; } - } - else { + } else { if(sphere==false) { POT = 0.5 * KAPPA * (ZZ - Zmax) * (ZZ - Zmax); FZ = - KAPPA * (ZZ - Zmax); FS = 0; - } - else { + } else { D = sqrt(pow(ZZ,2)+pow(SS,2)); d = D - z_cc; if(ZZ>=R_cyl+slope*(SS-z_cc)) { POT = 0.5 * KAPPA * pow(d,2); FZ = - KAPPA * d * ZZ / D; FS = - KAPPA * d * SS / D; - } - else { + } else { POT = 0.5 * KAPPA * pow(sqrt(pow((ZZ+slope*z_cc-R_cyl)/slope,2)+pow(ZZ,2))- z_cc,2); FZ = - KAPPA*(sqrt(pow((ZZ+slope*z_cc-R_cyl)/slope,2)+pow(ZZ,2))-z_cc)* @@ -426,8 +434,7 @@ void Funnel::createBIAS(const double& R_cyl, const double& z_cc, const double& a pof.close(); } -void Funnel::calculate() -{ +void Funnel::calculate() { unsigned ncv=getNumberOfArguments(); vector cv(ncv), der(ncv); diff --git a/src/generic/Accumulate.cpp b/src/generic/Accumulate.cpp index a6fd3bedb4..2032e13e79 100644 --- a/src/generic/Accumulate.cpp +++ b/src/generic/Accumulate.cpp @@ -41,8 +41,7 @@ namespace generic { class Accumulate : public ActionWithValue, public ActionWithArguments, - public ActionPilot -{ + public ActionPilot { private: bool clearnextstep; unsigned clearstride; @@ -50,8 +49,12 @@ class Accumulate : static void registerKeywords( Keywords& keys ); Accumulate( const ActionOptions& ); unsigned getNumberOfDerivatives(); - bool calculateOnUpdate() override { return false; } - bool calculateConstantValues( const bool& have_atoms ) override { return false; } + bool calculateOnUpdate() override { + return false; + } + bool calculateConstantValues( const bool& have_atoms ) override { + return false; + } void calculate() override {} void apply() override {} void update() override ; @@ -60,9 +63,13 @@ class Accumulate : PLUMED_REGISTER_ACTION(Accumulate,"ACCUMULATE") void Accumulate::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); - keys.use("ARG"); keys.use("UPDATE_FROM"); keys.use("UPDATE_UNTIL"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + ActionPilot::registerKeywords( keys ); + keys.use("ARG"); + keys.use("UPDATE_FROM"); + keys.use("UPDATE_UNTIL"); keys.add("compulsory","STRIDE","1","the frequency with which the data should be collected and added to the quantity being averaged"); keys.add("compulsory","CLEAR","0","the frequency with which to clear all the accumulated data. The default value " "of 0 implies that all the data will be used and that the grid will never be cleared"); @@ -74,23 +81,33 @@ Accumulate::Accumulate( const ActionOptions& ao ): ActionWithValue(ao), ActionWithArguments(ao), ActionPilot(ao), - clearnextstep(true) -{ - if( getNumberOfArguments()!=1 ) error("there should only be one argument to this action"); - if( !getPntrToArgument(0)->hasDerivatives() && getPntrToArgument(0)->getRank()!=0 ) error("input to the accumulate action should be a scalar or a grid"); + clearnextstep(true) { + if( getNumberOfArguments()!=1 ) { + error("there should only be one argument to this action"); + } + if( !getPntrToArgument(0)->hasDerivatives() && getPntrToArgument(0)->getRank()!=0 ) { + error("input to the accumulate action should be a scalar or a grid"); + } parse("CLEAR",clearstride); if( clearstride>0 ) { - if( clearstride%getStride()!=0 ) error("CLEAR parameter must be a multiple of STRIDE"); + if( clearstride%getStride()!=0 ) { + error("CLEAR parameter must be a multiple of STRIDE"); + } log.printf(" clearing average every %u steps \n",clearstride); } std::vector shape( getPntrToArgument(0)->getShape() ); - addValueWithDerivatives( shape ); setNotPeriodic(); - if( getPntrToArgument(0)->isPeriodic() ) error("you cannot accumulate a periodic quantity"); + addValueWithDerivatives( shape ); + setNotPeriodic(); + if( getPntrToArgument(0)->isPeriodic() ) { + error("you cannot accumulate a periodic quantity"); + } } unsigned Accumulate::getNumberOfDerivatives() { - if( getPntrToArgument(0)->getRank()>0 ) return getPntrToArgument(0)->getNumberOfGridDerivatives(); + if( getPntrToArgument(0)->getRank()>0 ) { + return getPntrToArgument(0)->getNumberOfGridDerivatives(); + } return getPntrToArgument(0)->getNumberOfDerivatives(); } @@ -99,21 +116,32 @@ void Accumulate::update() { if( getPntrToComponent(0)->getNumberOfValues()!=getPntrToArgument(0)->getNumberOfValues() ) { getPntrToComponent(0)->setShape( getPntrToArgument(0)->getShape() ); } - clearnextstep=false; getPntrToComponent(0)->set(0,0.0); getPntrToComponent(0)->clearDerivatives(true); + clearnextstep=false; + getPntrToComponent(0)->set(0,0.0); + getPntrToComponent(0)->clearDerivatives(true); + } + if( getStep()==0 ) { + return; } - if( getStep()==0 ) return; - Value* myarg=getPntrToArgument(0); Value* myout = getPntrToComponent(0); + Value* myarg=getPntrToArgument(0); + Value* myout = getPntrToComponent(0); if( getPntrToArgument(0)->getRank()>0 ) { unsigned nvals = myarg->getNumberOfValues(), nder = myarg->getNumberOfGridDerivatives(); for(unsigned i=0; iset( i, myout->get(i) + myarg->get(i) ); - for(unsigned j=0; jaddGridDerivatives( i, j, myarg->getGridDerivative( i, j ) ); + for(unsigned j=0; jaddGridDerivatives( i, j, myarg->getGridDerivative( i, j ) ); + } } - } else getPntrToComponent(0)->add( getPntrToArgument(0)->get() ); + } else { + getPntrToComponent(0)->add( getPntrToArgument(0)->get() ); + } // Clear if required - if( clearstride>0 && getStep()%clearstride==0 ) clearnextstep=true; + if( clearstride>0 && getStep()%clearstride==0 ) { + clearnextstep=true; + } } } diff --git a/src/generic/Average.cpp b/src/generic/Average.cpp index 8163b3dcee..57373b11f6 100644 --- a/src/generic/Average.cpp +++ b/src/generic/Average.cpp @@ -106,42 +106,63 @@ void Average::registerKeywords( Keywords& keys ) { keys.add("compulsory","CLEAR","0","the frequency with whihc to clear the data that is being averaged"); keys.add("optional","NORMALIZATION","keyword for old version of the code that is there to maintain back compatibility only. Adding this keyword does nothing"); keys.setValueDescription("the value of the average"); - keys.needsAction("COMBINE"); keys.needsAction("CUSTOM"); keys.needsAction("ONES"); keys.needsAction("ACCUMULATE"); + keys.needsAction("COMBINE"); + keys.needsAction("CUSTOM"); + keys.needsAction("ONES"); + keys.needsAction("ACCUMULATE"); } Average::Average( const ActionOptions& ao ): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { - std::string lw; parse("LOGWEIGHTS",lw); std::string stride, clearstride; parse("STRIDE",stride); parse("CLEAR",clearstride); + std::string lw; + parse("LOGWEIGHTS",lw); + std::string stride, clearstride; + parse("STRIDE",stride); + parse("CLEAR",clearstride); if( lw.length()>0 ) { readInputLine( getShortcutLabel() + "_wsum: COMBINE ARG=" + lw + " PERIODIC=NO"); readInputLine( getShortcutLabel() + "_weight: CUSTOM ARG=" + getShortcutLabel() + "_wsum FUNC=exp(x) PERIODIC=NO"); - } else readInputLine( getShortcutLabel() + "_weight: ONES SIZE=1" ); + } else { + readInputLine( getShortcutLabel() + "_weight: ONES SIZE=1" ); + } - std::vector arg; parseVector("ARG",arg); - if( arg.size()!=1 ) error("should only be one argument to this action"); - std::vector vals; ActionWithArguments::interpretArgumentList( arg, plumed.getActionSet(), this, vals ); + std::vector arg; + parseVector("ARG",arg); + if( arg.size()!=1 ) { + error("should only be one argument to this action"); + } + std::vector vals; + ActionWithArguments::interpretArgumentList( arg, plumed.getActionSet(), this, vals ); readInputLine( getShortcutLabel() + "_denom: ACCUMULATE ARG=" + getShortcutLabel() + "_weight STRIDE=" + stride + " CLEAR=" + clearstride ); if( vals[0]->isPeriodic() ) { - std::string lbound, ubound, pfactor; vals[0]->getDomain( lbound, ubound ); pfactor = "((" + ubound + "-" + lbound + ")/(pi+pi))"; + std::string lbound, ubound, pfactor; + vals[0]->getDomain( lbound, ubound ); + pfactor = "((" + ubound + "-" + lbound + ")/(pi+pi))"; readInputLine( getShortcutLabel() + "_sin: CUSTOM ARG=" + arg[0] + "," + getShortcutLabel() + "_weight FUNC=y*sin((x-" + lbound + ")/" + pfactor + ") PERIODIC=NO"); readInputLine( getShortcutLabel() + "_cos: CUSTOM ARG=" + arg[0] + "," + getShortcutLabel() + "_weight FUNC=y*cos((x-" + lbound + ")/" + pfactor + ") PERIODIC=NO"); readInputLine( getShortcutLabel() + "_sinsum: ACCUMULATE ARG=" + getShortcutLabel() + "_sin STRIDE=" + stride + " CLEAR=" + clearstride ); readInputLine( getShortcutLabel() + "_cossum: ACCUMULATE ARG=" + getShortcutLabel() + "_cos STRIDE=" + stride + " CLEAR=" + clearstride ); readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_sinsum," + getShortcutLabel() + "_cossum," + getShortcutLabel() + "_denom FUNC=" + lbound + "+" + pfactor + "*atan2(x/z,y/z) PERIODIC=" + lbound +"," + ubound); } else { - std::string normstr; parse("NORMALIZATION",normstr); - if( normstr=="true" || normstr=="false" ) warning("NORMALIZATION is deprecated. You are advised to take this out of input files in future and use the new syntax with ACCUMULATE for unormalized data rather than the shortcut AVERAGE"); - else if( normstr.length()>0 ) error("NORMALIZATION=" + normstr + " is not valid PLUMED input. If you want an unormalised 'average' use ACCUMULATE"); + std::string normstr; + parse("NORMALIZATION",normstr); + if( normstr=="true" || normstr=="false" ) { + warning("NORMALIZATION is deprecated. You are advised to take this out of input files in future and use the new syntax with ACCUMULATE for unormalized data rather than the shortcut AVERAGE"); + } else if( normstr.length()>0 ) { + error("NORMALIZATION=" + normstr + " is not valid PLUMED input. If you want an unormalised 'average' use ACCUMULATE"); + } readInputLine( getShortcutLabel() + "_prod: CUSTOM ARG=" + arg[0] + "," + getShortcutLabel() + "_weight FUNC=x*y PERIODIC=NO"); if( normstr.length()==0 || normstr=="true" ) { readInputLine( getShortcutLabel() + "_numer: ACCUMULATE ARG=" + getShortcutLabel() + "_prod STRIDE=" + stride + " CLEAR=" + clearstride ); readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_numer," + getShortcutLabel() + "_denom FUNC=x/y PERIODIC=NO"); - } else if( normstr=="false" ) readInputLine( getShortcutLabel() + ": ACCUMULATE ARG=" + getShortcutLabel() + "_prod STRIDE=" + stride + " CLEAR=" + clearstride ); - else plumed_error(); + } else if( normstr=="false" ) { + readInputLine( getShortcutLabel() + ": ACCUMULATE ARG=" + getShortcutLabel() + "_prod STRIDE=" + stride + " CLEAR=" + clearstride ); + } else { + plumed_error(); + } } } diff --git a/src/generic/Collect.cpp b/src/generic/Collect.cpp index fe44c0344f..f829b9bbb7 100644 --- a/src/generic/Collect.cpp +++ b/src/generic/Collect.cpp @@ -41,8 +41,7 @@ namespace generic { class Collect : public ActionWithValue, public ActionWithArguments, - public ActionPilot -{ + public ActionPilot { private: bool usefirstconf; unsigned clearstride; @@ -50,8 +49,12 @@ class Collect : static void registerKeywords( Keywords& keys ); Collect( const ActionOptions& ); unsigned getNumberOfDerivatives(); - bool calculateOnUpdate() override { return false; } - bool calculateConstantValues( const bool& have_atoms ) override { return false; } + bool calculateOnUpdate() override { + return false; + } + bool calculateConstantValues( const bool& have_atoms ) override { + return false; + } void calculate() override {} void apply() override {} void update() override ; @@ -60,9 +63,13 @@ class Collect : PLUMED_REGISTER_ACTION(Collect,"COLLECT") void Collect::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); - keys.use("ARG"); keys.use("UPDATE_FROM"); keys.use("UPDATE_UNTIL"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + ActionPilot::registerKeywords( keys ); + keys.use("ARG"); + keys.use("UPDATE_FROM"); + keys.use("UPDATE_UNTIL"); keys.add("compulsory","STRIDE","1","the frequency with which the data should be collected and added to the quantity being averaged"); keys.add("compulsory","CLEAR","0","the frequency with which to clear all the accumulated data. The default value " "of 0 implies that all the data will be used and that the grid will never be cleared"); @@ -75,37 +82,66 @@ Collect::Collect( const ActionOptions& ao ): ActionWithValue(ao), ActionWithArguments(ao), ActionPilot(ao), - usefirstconf(false) -{ - if( getNumberOfArguments()!=1 ) error("there should only be one argument to this action"); - if( getPntrToArgument(0)->getRank()>0 && getPntrToArgument(0)->hasDerivatives() ) error("input to the collect argument cannot be a grid"); + usefirstconf(false) { + if( getNumberOfArguments()!=1 ) { + error("there should only be one argument to this action"); + } + if( getPntrToArgument(0)->getRank()>0 && getPntrToArgument(0)->hasDerivatives() ) { + error("input to the collect argument cannot be a grid"); + } - std::string type; parse("TYPE",type); - if( getPntrToArgument(0)->getNumberOfValues()==1 && (type=="auto" || type=="vector") ) type="vector"; - else if( getPntrToArgument(0)->getNumberOfValues()==1 && type=="matrix" ) error("invalid type specified. Cannot construct a matrix by collecting scalars"); - else if( getPntrToArgument(0)->getNumberOfValues()!=1 && type=="auto" ) error("missing TYPE keyword. TYPE should specify whether data is to be stored as a vector or a matrix"); - else if( type!="vector" && type!="matrix" ) error("invalid TYPE specified. Should be matrix/scalar found " + type); + std::string type; + parse("TYPE",type); + if( getPntrToArgument(0)->getNumberOfValues()==1 && (type=="auto" || type=="vector") ) { + type="vector"; + } else if( getPntrToArgument(0)->getNumberOfValues()==1 && type=="matrix" ) { + error("invalid type specified. Cannot construct a matrix by collecting scalars"); + } else if( getPntrToArgument(0)->getNumberOfValues()!=1 && type=="auto" ) { + error("missing TYPE keyword. TYPE should specify whether data is to be stored as a vector or a matrix"); + } else if( type!="vector" && type!="matrix" ) { + error("invalid TYPE specified. Should be matrix/scalar found " + type); + } - if( type=="vector" ) log.printf(" adding %d elements to stored vector each time we collect\n", getPntrToArgument(0)->getNumberOfValues() ); - else log.printf(" constructing matrix with rows of length %d from input data\n", getPntrToArgument(0)->getNumberOfValues() ); + if( type=="vector" ) { + log.printf(" adding %d elements to stored vector each time we collect\n", getPntrToArgument(0)->getNumberOfValues() ); + } else { + log.printf(" constructing matrix with rows of length %d from input data\n", getPntrToArgument(0)->getNumberOfValues() ); + } - parse("CLEAR",clearstride); unsigned nvals=0; + parse("CLEAR",clearstride); + unsigned nvals=0; if( clearstride==getStride() ) { - nvals=1; usefirstconf=(getStride()==0); + nvals=1; + usefirstconf=(getStride()==0); } else if( clearstride>0 ) { - if( clearstride%getStride()!=0 ) error("CLEAR parameter must be a multiple of STRIDE"); + if( clearstride%getStride()!=0 ) { + error("CLEAR parameter must be a multiple of STRIDE"); + } log.printf(" clearing collected data every %u steps \n",clearstride); nvals=(clearstride/getStride()); } - std::vector shape(1); shape[0]=nvals; getPntrToArgument(0)->buildDataStore(); - if( type=="matrix" ) { shape.resize(2); shape[1] = getPntrToArgument(0)->getNumberOfValues(); } - if( type=="vector" ) { shape[0] = nvals*getPntrToArgument(0)->getNumberOfValues(); } - addValue( shape ); if( shape.size()==2 ) getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + std::vector shape(1); + shape[0]=nvals; + getPntrToArgument(0)->buildDataStore(); + if( type=="matrix" ) { + shape.resize(2); + shape[1] = getPntrToArgument(0)->getNumberOfValues(); + } + if( type=="vector" ) { + shape[0] = nvals*getPntrToArgument(0)->getNumberOfValues(); + } + addValue( shape ); + if( shape.size()==2 ) { + getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + } if( getPntrToArgument(0)->isPeriodic() ) { - std::string min, max; getPntrToArgument(0)->getDomain( min, max ); + std::string min, max; + getPntrToArgument(0)->getDomain( min, max ); setPeriodic( min, max ); - } else setNotPeriodic(); + } else { + setNotPeriodic(); + } } unsigned Collect::getNumberOfDerivatives() { @@ -113,22 +149,34 @@ unsigned Collect::getNumberOfDerivatives() { } void Collect::update() { - if( getStep()==0 || (!onStep() && !usefirstconf) ) return ; + if( getStep()==0 || (!onStep() && !usefirstconf) ) { + return ; + } usefirstconf=false; Value* myin=getPntrToArgument(0); Value* myout=getPntrToComponent(0); unsigned nargs=myin->getNumberOfValues(); if( clearstride==getStride() ) { - for(unsigned i=0; iset( i, myin->get(i) ); + for(unsigned i=0; iset( i, myin->get(i) ); + } } else if( clearstride>0 ) { unsigned step = getStep() - clearstride*std::floor( getStep() / clearstride ); - if( getStep()%clearstride==0 ) step = step + clearstride; + if( getStep()%clearstride==0 ) { + step = step + clearstride; + } unsigned base = (step/getStride()-1)*nargs; - for(unsigned i=0; iset( base+i, myin->get(i) ); + for(unsigned i=0; iset( base+i, myin->get(i) ); + } } else { - for(unsigned i=0; ipush_back( myin->get(i) ); - if( myout->getRank()==2 ) myout->reshapeMatrixStore( nargs ); + for(unsigned i=0; ipush_back( myin->get(i) ); + } + if( myout->getRank()==2 ) { + myout->reshapeMatrixStore( nargs ); + } } } diff --git a/src/generic/Committor.cpp b/src/generic/Committor.cpp index 20ed416c21..ff9f8e3c0f 100644 --- a/src/generic/Committor.cpp +++ b/src/generic/Committor.cpp @@ -56,8 +56,7 @@ COMMITTOR ... class Committor : public ActionPilot, - public ActionWithArguments -{ + public ActionWithArguments { private: std::string file; OFile ofile; @@ -83,7 +82,8 @@ void Committor::registerKeywords( Keywords& keys ) { keys.use("ARG"); keys.add("numbered", "BASIN_LL","List of lower limits for basin #"); keys.add("numbered", "BASIN_UL","List of upper limits for basin #"); - keys.reset_style("BASIN_LL","compulsory"); keys.reset_style("BASIN_UL","compulsory"); + keys.reset_style("BASIN_LL","compulsory"); + keys.reset_style("BASIN_UL","compulsory"); keys.add("compulsory","STRIDE","1","the frequency with which the CVs are analyzed"); keys.add("optional","FILE","the name of the file on which to output the reached basin"); keys.add("optional","FMT","the format that should be used to output real numbers"); @@ -96,8 +96,7 @@ Committor::Committor(const ActionOptions&ao): ActionWithArguments(ao), fmt("%f"), basin(0), - doNotStop(false) -{ + doNotStop(false) { ofile.link(*this); parse("FILE",file); if(file.length()>0) { @@ -115,9 +114,15 @@ Committor::Committor(const ActionOptions&ao): std::vector tmpl, tmpu; parseNumberedVector("BASIN_LL", b, tmpl ); parseNumberedVector("BASIN_UL", b, tmpu ); - if( tmpl.empty() && tmpu.empty() ) break; - if( tmpl.size()!=getNumberOfArguments()) error("Wrong number of values for BASIN_LL: they should be equal to the number of arguments"); - if( tmpu.size()!=getNumberOfArguments()) error("Wrong number of values for BASIN_UL: they should be equal to the number of arguments"); + if( tmpl.empty() && tmpu.empty() ) { + break; + } + if( tmpl.size()!=getNumberOfArguments()) { + error("Wrong number of values for BASIN_LL: they should be equal to the number of arguments"); + } + if( tmpu.size()!=getNumberOfArguments()) { + error("Wrong number of values for BASIN_UL: they should be equal to the number of arguments"); + } lowerlimits.push_back(tmpl); upperlimits.push_back(tmpu); nbasins=b; @@ -131,13 +136,19 @@ Committor::Committor(const ActionOptions&ao): for(unsigned b=0; bupperlimits[b][i]) error("COMMITTOR: UPPER bounds must always be greater than LOWER bounds"); + if(lowerlimits[b][i]>upperlimits[b][i]) { + error("COMMITTOR: UPPER bounds must always be greater than LOWER bounds"); + } log.printf(" %f - %f\n", lowerlimits[b][i], upperlimits[b][i]); } - if(doNotStop) log.printf(" COMMITOR will keep track of the visited basins without stopping the simulations\n"); + if(doNotStop) { + log.printf(" COMMITOR will keep track of the visited basins without stopping the simulations\n"); + } } - for(unsigned i=0; i shape; std::vector vals; + ActionWithValue(ao) { + bool nolog=false; + parseFlag("NOLOG",nolog); + bool scalars=false; + std::string fname, vname; + parse("FILE",fname); + std::vector shape; + std::vector vals; if( fname.length()>0 ) { - IFile mfile; mfile.open(fname); + IFile mfile; + mfile.open(fname); // Read in first line - std::vector words; unsigned nline=0; + std::vector words; + unsigned nline=0; while( nline==0 ) { Tools::getParsedLine( mfile, words ); nline=words.size(); @@ -102,48 +111,87 @@ Constant::Constant(const ActionOptions&ao): shape.resize(1); error("invalid matrix in input file"); } - shape.resize(2); shape[1]=nline; + shape.resize(2); + shape[1]=nline; std::vector tmpdis( shape[1] ); - for(unsigned j=0; j0 && nc>0 ) { - shape.resize(2); shape[0]=nr; shape[1]=nc; vals.resize( nr*nc ); + shape.resize(2); + shape[0]=nr; + shape[1]=nc; + vals.resize( nr*nc ); log.printf(" reading in %d by %d matrix \n", nr, nc ); - } else if( nr>0 || nc>0 ) error("makes no sense to set only one of NROWS and NCOLS to a non-zero value"); - parseVector("VALUES",vals); parseFlag("SCALARS",scalars); + } else if( nr>0 || nc>0 ) { + error("makes no sense to set only one of NROWS and NCOLS to a non-zero value"); + } + parseVector("VALUES",vals); + parseFlag("SCALARS",scalars); if( vals.size()==0 ) { parseVector("VALUE",vals); - if( vals.size()!=1 ) error("VALUE keyword should take a single scalar"); - } else if( vals.size()==1 ) scalars=false; + if( vals.size()!=1 ) { + error("VALUE keyword should take a single scalar"); + } + } else if( vals.size()==1 ) { + scalars=false; + } log.printf(" read in %d values :", vals.size() ); - if( !nolog ) { for(unsigned i=0; i1 ) { shape.resize(1); shape[0] = vals.size(); } + if( !scalars && shape.size()==0 && vals.size()>1 ) { + shape.resize(1); + shape[0] = vals.size(); + } } if( !scalars ) { // Now set the value - addValue( shape ); setNotPeriodic(); getPntrToComponent(0)->setConstant(); - for(unsigned i=0; iset( i, vals[i] ); + addValue( shape ); + setNotPeriodic(); + getPntrToComponent(0)->setConstant(); + for(unsigned i=0; iset( i, vals[i] ); + } } else { for(unsigned i=0; isetConstant(); comp->set(vals[i]); + comp->setConstant(); + comp->set(vals[i]); } } } diff --git a/src/generic/CreateMask.cpp b/src/generic/CreateMask.cpp index 4177567ff3..b86fccfac3 100644 --- a/src/generic/CreateMask.cpp +++ b/src/generic/CreateMask.cpp @@ -46,7 +46,9 @@ class CreateMask : public: static void registerKeywords( Keywords& keys ); CreateMask( const ActionOptions& ); - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } void prepare() override ; void calculate() override ; void apply() override {} @@ -55,8 +57,10 @@ class CreateMask : PLUMED_REGISTER_ACTION(CreateMask,"CREATE_MASK") void CreateMask::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.use("ARG"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.use("ARG"); keys.add("compulsory","TYPE","the way the zeros are supposed to be set"); keys.add("compulsory","NZEROS","the number of zeros that you want to put in the mask"); keys.add("optional","SEED","the seed to use for the random number generator"); @@ -68,59 +72,101 @@ CreateMask::CreateMask( const ActionOptions& ao ) : Action(ao), ActionWithValue(ao), ActionWithArguments(ao), - nzeros(0) -{ - if( getNumberOfArguments()!=1 ) error("should only be one argument to this action"); - if( getPntrToArgument(0)->getRank()!=1 ) error("argument should be a vector"); - std::string stype; parse("TYPE",stype); if( stype!="nomask" ) parse("NZEROS",nzeros); + nzeros(0) { + if( getNumberOfArguments()!=1 ) { + error("should only be one argument to this action"); + } + if( getPntrToArgument(0)->getRank()!=1 ) { + error("argument should be a vector"); + } + std::string stype; + parse("TYPE",stype); + if( stype!="nomask" ) { + parse("NZEROS",nzeros); + } if( stype=="nomask" ) { - type=nomask; log.printf(" setting all points in output mask to zero \n"); + type=nomask; + log.printf(" setting all points in output mask to zero \n"); } else if( stype=="stride" ) { - type=stride; log.printf(" setting every %d equally spaced points in output mask to zero \n", nzeros ); + type=stride; + log.printf(" setting every %d equally spaced points in output mask to zero \n", nzeros ); } else if( stype=="random" ) { - unsigned seed=230623; parse("SEED",seed); r.setSeed(-seed); getPntrToArgument(0)->buildDataStore(); - type=random; log.printf(" choosing %d points to set to non-zero in mask in accordance with input weights \n", nzeros ); - } else error( stype + " is not a valid way input for TYPE"); - std::vector shape(1); shape[0] = getPntrToArgument(0)->getShape()[0]; - addValue( shape ); setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); - for(unsigned i=0; iset( i, 1.0 ); + unsigned seed=230623; + parse("SEED",seed); + r.setSeed(-seed); + getPntrToArgument(0)->buildDataStore(); + type=random; + log.printf(" choosing %d points to set to non-zero in mask in accordance with input weights \n", nzeros ); + } else { + error( stype + " is not a valid way input for TYPE"); + } + std::vector shape(1); + shape[0] = getPntrToArgument(0)->getShape()[0]; + addValue( shape ); + setNotPeriodic(); + getPntrToComponent(0)->buildDataStore(); + for(unsigned i=0; iset( i, 1.0 ); + } } void CreateMask::prepare() { - Value* out=getPntrToComponent(0); Value* arg=getPntrToArgument(0); + Value* out=getPntrToComponent(0); + Value* arg=getPntrToArgument(0); if( out->getShape()[0]!=arg->getShape()[0] ) { - std::vector shape(1); shape[0] = arg->getShape()[0]; out->setShape( shape ); + std::vector shape(1); + shape[0] = arg->getShape()[0]; + out->setShape( shape ); } if( type!=nomask ) { - for(unsigned i=nzeros; igetShape()[0]; ++i) out->set( i, 1 ); + for(unsigned i=nzeros; igetShape()[0]; ++i) { + out->set( i, 1 ); + } } } void CreateMask::calculate() { - Value* out=getPntrToComponent(0); Value* arg=getPntrToArgument(0); + Value* out=getPntrToComponent(0); + Value* arg=getPntrToArgument(0); unsigned ns = arg->getShape()[0]; - for(unsigned i=0; iset( i, 1.0 ); + for(unsigned i=0; iset( i, 1.0 ); + } if( type==stride ) { std::size_t ss = int( std::floor( ns / nzeros ) ); - for(unsigned i=0; iset( i*ss, 0.0 ); + for(unsigned i=0; iset( i*ss, 0.0 ); + } } else if( type==random ) { for(unsigned i=0; iget(j)>0 ) totweights += arg->get(j); + if( out->get(j)>0 ) { + totweights += arg->get(j); + } } - double rr = r.U01()*totweights; double accum=0; + double rr = r.U01()*totweights; + double accum=0; for(unsigned j=0; jget(j)>0 ) accum += arg->get(j); - if( accumset( j, 0 ); break; + if( out->get(j)>0 ) { + accum += arg->get(j); + } + if( accumset( j, 0 ); + break; } } } else if( type==nomask ) { - for(unsigned i=0; iset( i, 0.0 ); - } else error("invalid mask creation type"); + for(unsigned i=0; iset( i, 0.0 ); + } + } else { + error("invalid mask creation type"); + } } } diff --git a/src/generic/Debug.cpp b/src/generic/Debug.cpp index e7fe458ef8..722d665e3e 100644 --- a/src/generic/Debug.cpp +++ b/src/generic/Debug.cpp @@ -45,8 +45,7 @@ DEBUG logRequestedAtoms STRIDE=2 */ //+ENDPLUMEDOC class Debug: - public ActionPilot -{ + public ActionPilot { OFile ofile; bool logActivity; bool logRequestedAtoms; @@ -80,12 +79,20 @@ Debug::Debug(const ActionOptions&ao): logRequestedAtoms(false), novirial(false) { parseFlag("logActivity",logActivity); - if(logActivity) log.printf(" logging activity\n"); + if(logActivity) { + log.printf(" logging activity\n"); + } parseFlag("logRequestedAtoms",logRequestedAtoms); - if(logRequestedAtoms) log.printf(" logging requested atoms\n"); + if(logRequestedAtoms) { + log.printf(" logging requested atoms\n"); + } parseFlag("NOVIRIAL",novirial); - if(novirial) log.printf(" Switching off virial contribution\n"); - if(novirial) plumed.novirial=true; + if(novirial) { + log.printf(" Switching off virial contribution\n"); + } + if(novirial) { + plumed.novirial=true; + } parseFlag("DETAILED_TIMERS",detailedTimers); if(detailedTimers) { log.printf(" Detailed timing on\n"); @@ -109,15 +116,24 @@ void Debug::apply() { const ActionSet&actionSet(plumed.getActionSet()); int a=0; for(const auto & p : actionSet) { - if(dynamic_cast(p.get()))continue; - if(p->isActive()) a++; + if(dynamic_cast(p.get())) { + continue; + } + if(p->isActive()) { + a++; + } }; if(a>0) { ofile<<"activity at step "<(p.get()))continue; - if(p->isActive()) ofile.printf("+"); - else ofile.printf("-"); + if(dynamic_cast(p.get())) { + continue; + } + if(p->isActive()) { + ofile.printf("+"); + } else { + ofile.printf("-"); + } }; ofile.printf("\n"); }; @@ -128,7 +144,9 @@ void Debug::apply() { int n; plumed.cmd("createFullList",&n); plumed.cmd("getFullList",&l); - for(int i=0; i atoms; std::string file; parse("FILE",file); - if(file.length()==0) error("name out output file was not specified"); + if(file.length()==0) { + error("name out output file was not specified"); + } type=Tools::extension(file); log<<" file name "<0) { if(ntype!="xyz" && ntype!="gro" && ntype!="xtc" && ntype!="trr" - ) error("TYPE cannot be understood"); + ) { + error("TYPE cannot be understood"); + } log<<" file type enforced to be "<0 ) { - if( type!="xyz" ) error("can only print atomic properties when outputting xyz files"); + if( type!="xyz" ) { + error("can only print atomic properties when outputting xyz files"); + } std::vector argnames; for(unsigned i=0; igetRank()!=1 || getPntrToArgument(i)->hasDerivatives() ) error("arguments for xyz output should be vectors"); - if( getPntrToArgument(i)->getNumberOfValues()!=atoms.size() ) error("number of elements in vector " + getPntrToArgument(i)->getName() + " is not equal to number of atoms output"); - getPntrToArgument(i)->buildDataStore(true); argnames.push_back( getPntrToArgument(i)->getName() ); + if( getPntrToArgument(i)->getRank()!=1 || getPntrToArgument(i)->hasDerivatives() ) { + error("arguments for xyz output should be vectors"); + } + if( getPntrToArgument(i)->getNumberOfValues()!=atoms.size() ) { + error("number of elements in vector " + getPntrToArgument(i)->getName() + " is not equal to number of atoms output"); + } + getPntrToArgument(i)->buildDataStore(true); + argnames.push_back( getPntrToArgument(i)->getName() ); + } + std::vector str_upper, str_lower; + std::string errors; + parseVector("LESS_THAN_OR_EQUAL",str_upper); + parseVector("GREATER_THAN_OR_EQUAL",str_lower); + if( !bounds.setBounds( getNumberOfArguments(), str_lower, str_upper, errors ) ) { + error( errors ); + } + if( bounds.wereSet() ) { + log.printf(" %s \n", bounds.report( argnames ).c_str() ); } - std::vector str_upper, str_lower; std::string errors; - parseVector("LESS_THAN_OR_EQUAL",str_upper); parseVector("GREATER_THAN_OR_EQUAL",str_lower); - if( !bounds.setBounds( getNumberOfArguments(), str_lower, str_upper, errors ) ) error( errors ); - if( bounds.wereSet() ) log.printf(" %s \n", bounds.report( argnames ).c_str() ); } requestAtoms(atoms, false); @@ -259,11 +290,20 @@ DumpAtoms::DumpAtoms(const ActionOptions&ao): if( moldat ) { log<<" MOLINFO DATA found with label " <getLabel()<<", using proper atom names\n"; names.resize(atoms.size()); - for(unsigned i=0; igetPDBsize()) names[i]=moldat->getAtomName(atoms[i]); + for(unsigned i=0; igetPDBsize()) { + names[i]=moldat->getAtomName(atoms[i]); + } residueNumbers.resize(atoms.size()); - for(unsigned i=0; igetPDBsize()) residueNumbers[i]=moldat->getResidueNumber(atoms[i]); + for(unsigned i=0; igetPDBsize()) { + residueNumbers[i]=moldat->getResidueNumber(atoms[i]); + } residueNames.resize(atoms.size()); - for(unsigned i=0; igetPDBsize()) residueNames[i]=moldat->getResidueName(atoms[i]); + for(unsigned i=0; igetPDBsize()) { + residueNames[i]=moldat->getResidueName(atoms[i]); + } } } @@ -283,10 +323,15 @@ void DumpAtoms::unlockRequests() { void DumpAtoms::update() { if(type=="xyz") { - unsigned nat=0; std::vector args( getNumberOfArguments() ); + unsigned nat=0; + std::vector args( getNumberOfArguments() ); for(unsigned i=0; iget(i); - if( bounds.check( args ) ) nat++; + for(unsigned j=0; jget(i); + } + if( bounds.check( args ) ) { + nat++; + } } of.printf("%d\n",nat); const Tensor & t(getPbc().getBox()); @@ -300,13 +345,22 @@ void DumpAtoms::update() { ); } for(unsigned i=0; iget(i); - if( !bounds.check(args) ) continue; + for(unsigned j=0; jget(i); + } + if( !bounds.check(args) ) { + continue; + } const char* defname="X"; const char* name=defname; - if(names.size()>0) if(names[i].length()>0) name=names[i].c_str(); + if(names.size()>0) + if(names[i].length()>0) { + name=names[i].c_str(); + } of.printf(("%s "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz).c_str(),name,lenunit*getPosition(i)(0),lenunit*getPosition(i)(1),lenunit*getPosition(i)(2)); - for(unsigned j=0; jget(i) ); + for(unsigned j=0; jget(i) ); + } of.printf("\n"); } } else if(type=="gro") { @@ -317,10 +371,17 @@ void DumpAtoms::update() { const char* defname="X"; const char* name=defname; unsigned residueNumber=0; - if(names.size()>0) if(names[i].length()>0) name=names[i].c_str(); - if(residueNumbers.size()>0) residueNumber=residueNumbers[i]; + if(names.size()>0) + if(names[i].length()>0) { + name=names[i].c_str(); + } + if(residueNumbers.size()>0) { + residueNumber=residueNumbers[i]; + } std::string resname=""; - if(residueNames.size()>0) resname=residueNames[i]; + if(residueNames.size()>0) { + resname=residueNames[i]; + } of.printf(("%5u%-5s%5s%5d"+fmt_gro_pos+fmt_gro_pos+fmt_gro_pos+"\n").c_str(), residueNumber%100000,resname.c_str(),name,getAbsoluteIndex(i).serial()%100000, lenunit*getPosition(i)(0),lenunit*getPosition(i)(1),lenunit*getPosition(i)(2)); @@ -336,17 +397,25 @@ void DumpAtoms::update() { int step=getStep(); float time=getTime()/getUnits().getTime(); float precision=Tools::fastpow(10.0,iprecision); - for(int i=0; i<3; i++) for(int j=0; j<3; j++) box[i][j]=lenunit*t(i,j); + for(int i=0; i<3; i++) + for(int j=0; j<3; j++) { + box[i][j]=lenunit*t(i,j); + } // here we cannot use a std::vector since it does not compile. // we thus use a std::unique_ptr auto pos = Tools::make_unique(natoms); - for(int i=0; igetPntrToAction())->turnOnDerivatives(); - if( getPntrToArgument(0)->getRank()>0 ) error("cannot dump derivatives of non-scalar objects"); + if( getPntrToArgument(0)->getRank()>0 ) { + error("cannot dump derivatives of non-scalar objects"); + } unsigned npar=getPntrToArgument(0)->getNumberOfDerivatives(); - if( npar==0 ) error("one or more arguments has no derivatives"); + if( npar==0 ) { + error("one or more arguments has no derivatives"); + } for(unsigned i=1; igetPntrToAction())->turnOnDerivatives(); - if( getPntrToArgument(i)->getRank()>0 ) error("cannot dump derivatives of non-scalar objects"); - if( npar!=getPntrToArgument(i)->getNumberOfDerivatives() ) error("the number of derivatives must be the same in all values being dumped"); + if( getPntrToArgument(i)->getRank()>0 ) { + error("cannot dump derivatives of non-scalar objects"); + } + if( npar!=getPntrToArgument(i)->getNumberOfDerivatives() ) { + error("the number of derivatives must be the same in all values being dumped"); + } } checkRead(); } diff --git a/src/generic/DumpForces.cpp b/src/generic/DumpForces.cpp index 8fc1411f63..b3ba3ab13c 100644 --- a/src/generic/DumpForces.cpp +++ b/src/generic/DumpForces.cpp @@ -52,8 +52,7 @@ DUMPFORCES ARG=distance STRIDE=1 FILE=forces class DumpForces : public ActionPilot, - public ActionWithArguments -{ + public ActionWithArguments { std::string file; std::string fmt; OFile of; @@ -85,17 +84,20 @@ DumpForces::DumpForces(const ActionOptions&ao): Action(ao), ActionPilot(ao), ActionWithArguments(ao), - fmt("%15.10f") -{ + fmt("%15.10f") { parse("FILE",file); - if( file.length()==0 ) error("name of file was not specified"); + if( file.length()==0 ) { + error("name of file was not specified"); + } parse("FMT",fmt); fmt=" "+fmt; of.link(*this); of.open(file); log.printf(" on file %s\n",file.c_str()); log.printf(" with format %s\n",fmt.c_str()); - if( getNumberOfArguments()==0 ) error("no arguments have been specified"); + if( getNumberOfArguments()==0 ) { + error("no arguments have been specified"); + } checkRead(); } diff --git a/src/generic/DumpMassCharge.cpp b/src/generic/DumpMassCharge.cpp index 66107ce17f..5ff4a80632 100644 --- a/src/generic/DumpMassCharge.cpp +++ b/src/generic/DumpMassCharge.cpp @@ -25,8 +25,7 @@ #include "tools/File.h" #include "core/PlumedMain.h" -namespace PLMD -{ +namespace PLMD { namespace generic { //+PLUMEDOC PRINTANALYSIS DUMPMASSCHARGE @@ -75,8 +74,7 @@ DUMPMASSCHARGE FILE=mcfile ATOMS=solute_ions class DumpMassCharge: public ActionAtomistic, - public ActionPilot -{ + public ActionPilot { std::string file; bool first; bool second; @@ -86,7 +84,9 @@ class DumpMassCharge: explicit DumpMassCharge(const ActionOptions&); ~DumpMassCharge(); static void registerKeywords( Keywords& keys ); - bool actionHasForces() override { return false; } + bool actionHasForces() override { + return false; + } void prepare() override; void calculate() override {} void apply() override {} @@ -113,17 +113,20 @@ DumpMassCharge::DumpMassCharge(const ActionOptions&ao): first(true), second(true), print_masses(true), - print_charges(true) -{ + print_charges(true) { std::vector atoms; parse("FILE",file); - if(file.length()==0) error("name of output file was not specified"); + if(file.length()==0) { + error("name of output file was not specified"); + } log.printf(" output written to file %s\n",file.c_str()); parseAtomList("ATOMS",atoms); if(atoms.size()==0) { - std::vector strvec(1); strvec[0]="@mdatoms"; interpretAtomList( strvec,atoms ); + std::vector strvec(1); + strvec[0]="@mdatoms"; + interpretAtomList( strvec,atoms ); } bool only_masses = false; @@ -144,7 +147,9 @@ DumpMassCharge::DumpMassCharge(const ActionOptions&ao): checkRead(); log.printf(" printing the following atoms:" ); - for(unsigned i=0; i atoms; parseVector("ATOMS",atoms); + if(file.length()==0) { + error("name out output file was not specified"); + } + std::vector atoms; + parseVector("ATOMS",atoms); if( atoms.size()>0 ) { - std::vector atom_args; interpretArgumentList( atoms, plumed.getActionSet(), this, atom_args ); - if( atom_args.size()!=1 ) error("only one action should appear in input to atom args"); - std::vector args( getArguments() ); args.push_back( atom_args[0] ); requestArguments( args ); - std::vector indices; parseVector("ATOM_INDICES",indices); std::vector xvals,yvals,zvals,masv,chargev; + std::vector atom_args; + interpretArgumentList( atoms, plumed.getActionSet(), this, atom_args ); + if( atom_args.size()!=1 ) { + error("only one action should appear in input to atom args"); + } + std::vector args( getArguments() ); + args.push_back( atom_args[0] ); + requestArguments( args ); + std::vector indices; + parseVector("ATOM_INDICES",indices); + std::vector xvals,yvals,zvals,masv,chargev; ActionAtomistic::getAtomValuesFromPlumedObject(plumed,xvals,yvals,zvals,masv,chargev); ActionAtomistic::interpretAtomList( indices, xvals, this, pdb_atom_indices ); log.printf(" printing atoms : "); - for(unsigned i=0; igetShape()[1]/3 ) error("mismatch between size of matrix containing positions and vector of atom indices"); - beta.resize( atom_args[0]->getShape()[1]/3 ); occupancy.resize( atom_args[0]->getShape()[1]/3 ); - parseVector("OCCUPANCY", occupancy ); parseVector("BETA", beta ); + if( pdb_atom_indices.size()!=atom_args[0]->getShape()[1]/3 ) { + error("mismatch between size of matrix containing positions and vector of atom indices"); + } + beta.resize( atom_args[0]->getShape()[1]/3 ); + occupancy.resize( atom_args[0]->getShape()[1]/3 ); + parseVector("OCCUPANCY", occupancy ); + parseVector("BETA", beta ); parseVector("RESIDUE_INDICES",pdb_resid_indices); if( pdb_resid_indices.size()==0 ) { pdb_resid_indices.resize( pdb_atom_indices.size() ); - for(unsigned i=0; igetRank()==0 || getPntrToArgument(0)->hasDerivatives() ) error("argument for printing of PDB should be vector or matrix"); + if( getPntrToArgument(0)->getRank()==0 || getPntrToArgument(0)->hasDerivatives() ) { + error("argument for printing of PDB should be vector or matrix"); + } unsigned nv=getPntrToArgument(0)->getShape()[0]; for(unsigned i=0; igetRank()==0 || getPntrToArgument(i)->hasDerivatives() ) error("argument for printing of PDB should be vector or matrix"); - if( getPntrToArgument(i)->getShape()[0]!=nv ) error("for printing to pdb files all arguments must have same number of values"); + if( getPntrToArgument(i)->getRank()==0 || getPntrToArgument(i)->hasDerivatives() ) { + error("argument for printing of PDB should be vector or matrix"); + } + if( getPntrToArgument(i)->getShape()[0]!=nv ) { + error("for printing to pdb files all arguments must have same number of values"); + } } } void DumpPDB::printAtom( OFile& opdbf, const unsigned& anum, const unsigned& rnum, const Vector& pos, const double& m, const double& q ) const { - if( rnum>999 ) plumed_merror("atom number too large to be used as residue number"); - std::array at; const char* msg = h36::hy36encode(5,anum,&at[0]); - plumed_assert(msg==nullptr) << msg; at[5]=0; double lunits = plumed.getUnits().getLength()/0.1; + if( rnum>999 ) { + plumed_merror("atom number too large to be used as residue number"); + } + std::array at; + const char* msg = h36::hy36encode(5,anum,&at[0]); + plumed_assert(msg==nullptr) << msg; + at[5]=0; + double lunits = plumed.getUnits().getLength()/0.1; opdbf.printf("ATOM %s X RES %4u %8.3f%8.3f%8.3f%6.2f%6.2f\n", &at[0], rnum, lunits*pos[0], lunits*pos[1], lunits*pos[2], m, q ); } void DumpPDB::buildArgnames() { - unsigned nargs = getNumberOfArguments(); if( pdb_atom_indices.size()>0 ) nargs = nargs - 1; - if( nargs<0 ) return; + unsigned nargs = getNumberOfArguments(); + if( pdb_atom_indices.size()>0 ) { + nargs = nargs - 1; + } + if( nargs<0 ) { + return; + } - argnames.resize(0); unsigned nvals = getPntrToArgument(0)->getShape()[0]; - if( getPntrToArgument(0)->getRank()==2 ) nvals = getPntrToArgument(0)->getShape()[0]; + argnames.resize(0); + unsigned nvals = getPntrToArgument(0)->getShape()[0]; + if( getPntrToArgument(0)->getRank()==2 ) { + nvals = getPntrToArgument(0)->getShape()[0]; + } for(unsigned i=0; igetShape()[0]!=nvals ) error("all arguments should have same number of values"); + if( getPntrToArgument(i)->getShape()[0]!=nvals ) { + error("all arguments should have same number of values"); + } if( getPntrToArgument(i)->getRank()==1 ) { argnames.push_back( getPntrToArgument(i)->getName() ); } else if( getPntrToArgument(i)->getRank()==2 ) { @@ -147,40 +194,62 @@ void DumpPDB::buildArgnames() { } void DumpPDB::update() { - OFile opdbf; opdbf.link(*this); + OFile opdbf; + opdbf.link(*this); opdbf.setBackupString("analysis"); opdbf.open( file ); - std::size_t psign=fmt.find("%"); plumed_assert( psign!=std::string::npos ); + std::size_t psign=fmt.find("%"); + plumed_assert( psign!=std::string::npos ); std::string descr2="%s=%-" + fmt.substr(psign+1) + " "; - unsigned totargs = 0; unsigned nvals = getPntrToArgument(0)->getShape()[0]; + unsigned totargs = 0; + unsigned nvals = getPntrToArgument(0)->getShape()[0]; for(unsigned i=0; igetShape()[0]!=nvals ) error("all arguments should have same number of values"); - if( getPntrToArgument(i)->getRank()==1 ) totargs += 1; - else if( getPntrToArgument(i)->getRank()==2 ) totargs += getPntrToArgument(i)->getShape()[1]; + if( getPntrToArgument(i)->getShape()[0]!=nvals ) { + error("all arguments should have same number of values"); + } + if( getPntrToArgument(i)->getRank()==1 ) { + totargs += 1; + } else if( getPntrToArgument(i)->getRank()==2 ) { + totargs += getPntrToArgument(i)->getShape()[1]; + } + } + if( totargs!=argnames.size() ) { + buildArgnames(); } - if( totargs!=argnames.size() ) buildArgnames(); - if( description.length()>0 ) opdbf.printf("# %s AT STEP %lld TIME %f \n", description.c_str(), getStep(), getTime() ); + if( description.length()>0 ) { + opdbf.printf("# %s AT STEP %lld TIME %f \n", description.c_str(), getStep(), getTime() ); + } unsigned nargs = getNumberOfArguments(), atomarg=0; if( pdb_atom_indices.size()>0 ) { - if( nargs>1 ) { atomarg = nargs - 1; nargs = nargs-1; } - else nargs = 0; + if( nargs>1 ) { + atomarg = nargs - 1; + nargs = nargs-1; + } else { + nargs = 0; + } } for(unsigned i=0; igetRank()==1 ) { - opdbf.printf( descr2.c_str(), argnames[n].c_str(), thisarg->get(i) ); n++; + opdbf.printf( descr2.c_str(), argnames[n].c_str(), thisarg->get(i) ); + n++; } else if( thisarg->getRank()==2 ) { unsigned ncols = thisarg->getShape()[1]; - for(unsigned k=0; kget(i*ncols+k) ); n++; } + for(unsigned k=0; kget(i*ncols+k) ); + n++; + } } opdbf.printf("\n"); } if( pdb_atom_indices.size()>0 ) { - unsigned npos = pdb_atom_indices.size(); Vector pos; + unsigned npos = pdb_atom_indices.size(); + Vector pos; for(unsigned k=0; kget(npos*(3*i+0) + k); pos[1]=getPntrToArgument(atomarg)->get(npos*(3*i+1) + k); diff --git a/src/generic/DumpProjections.cpp b/src/generic/DumpProjections.cpp index 87d02d7a18..2e1cf335a7 100644 --- a/src/generic/DumpProjections.cpp +++ b/src/generic/DumpProjections.cpp @@ -49,8 +49,7 @@ DUMPPROJECTIONS ARG=d FILE=proj STRIDE=20 class DumpProjections : public ActionPilot, - public ActionWithArguments -{ + public ActionWithArguments { std::string file; std::string fmt; OFile of; @@ -60,7 +59,9 @@ class DumpProjections : static void registerKeywords(Keywords& keys); void apply() override {} void update() override; - bool checkNeedsGradients()const override {return true;} + bool checkNeedsGradients()const override { + return true; + } ~DumpProjections(); }; @@ -83,10 +84,11 @@ DumpProjections::DumpProjections(const ActionOptions&ao): Action(ao), ActionPilot(ao), ActionWithArguments(ao), - fmt("%15.10f") -{ + fmt("%15.10f") { parse("FILE",file); - if( file.length()==0 ) error("filename not specified"); + if( file.length()==0 ) { + error("filename not specified"); + } parse("FMT",fmt); fmt=" "+fmt; of.open(file); diff --git a/src/generic/DumpVector.cpp b/src/generic/DumpVector.cpp index 51f3b7a963..50a71c718d 100644 --- a/src/generic/DumpVector.cpp +++ b/src/generic/DumpVector.cpp @@ -61,7 +61,8 @@ PLUMED_REGISTER_ACTION(DumpVector,"DUMPVECTOR") void DumpVector::registerKeywords( Keywords& keys ) { Action::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.use("ARG"); + ActionWithArguments::registerKeywords( keys ); + keys.use("ARG"); keys.add("compulsory","STRIDE","0","the frequency with which the grid should be output to the file."); keys.add("compulsory","FILE","density","the file on which to write the vetors"); keys.add("optional","FMT","the format that should be used to output real numbers"); @@ -72,23 +73,38 @@ DumpVector::DumpVector(const ActionOptions&ao): Action(ao), ActionWithArguments(ao), ActionPilot(ao), - fmt("%f") -{ - if( getNumberOfArguments()==0 ) error("found no arguments"); - buildArgnames(); parse("FILE",filename); parseFlag("PRINT_ONE_FILE", onefile); - if(filename.length()==0) error("name out output file was not specified"); + fmt("%f") { + if( getNumberOfArguments()==0 ) { + error("found no arguments"); + } + buildArgnames(); + parse("FILE",filename); + parseFlag("PRINT_ONE_FILE", onefile); + if(filename.length()==0) { + error("name out output file was not specified"); + } log.printf(" outputting data with label %s to file named %s",getPntrToArgument(0)->getName().c_str(), filename.c_str() ); - parse("FMT",fmt); log.printf(" with format %s \n", fmt.c_str() ); fmt = " " + fmt; - if( onefile ) log.printf(" printing all grids on a single file \n"); - else log.printf(" printing all grids on separate files \n"); + parse("FMT",fmt); + log.printf(" with format %s \n", fmt.c_str() ); + fmt = " " + fmt; + if( onefile ) { + log.printf(" printing all grids on a single file \n"); + } else { + log.printf(" printing all grids on separate files \n"); + } } void DumpVector::buildArgnames() { - argnames.resize(0); unsigned nvals = getPntrToArgument(0)->getShape()[0]; - if( getPntrToArgument(0)->getRank()==2 ) nvals = getPntrToArgument(0)->getShape()[0]; + argnames.resize(0); + unsigned nvals = getPntrToArgument(0)->getShape()[0]; + if( getPntrToArgument(0)->getRank()==2 ) { + nvals = getPntrToArgument(0)->getShape()[0]; + } for(unsigned i=0; igetShape()[0]!=nvals ) error("all arguments should have same number of values"); + if( getPntrToArgument(i)->getShape()[0]!=nvals ) { + error("all arguments should have same number of values"); + } if( getPntrToArgument(i)->getRank()==1 ) { argnames.push_back( getPntrToArgument(i)->getName() ); } else if( getPntrToArgument(i)->getRank()==2 ) { @@ -99,17 +115,26 @@ void DumpVector::buildArgnames() { } void DumpVector::update() { - OFile ofile; ofile.link(*this); - if( onefile ) ofile.enforceRestart(); - else ofile.setBackupString("analysis"); + OFile ofile; + ofile.link(*this); + if( onefile ) { + ofile.enforceRestart(); + } else { + ofile.setBackupString("analysis"); + } ofile.open( filename ); unsigned totargs = 0; for(unsigned i=0; igetRank()==1 ) totargs += 1; - else if( getPntrToArgument(i)->getRank()==2 ) totargs += getPntrToArgument(i)->getShape()[1]; + if( getPntrToArgument(i)->getRank()==1 ) { + totargs += 1; + } else if( getPntrToArgument(i)->getRank()==2 ) { + totargs += getPntrToArgument(i)->getShape()[1]; + } + } + if( totargs!=argnames.size() ) { + buildArgnames(); } - if( totargs!=argnames.size() ) buildArgnames(); unsigned nvals = getPntrToArgument(0)->getShape()[0]; for(unsigned i=0; igetRank()==1 ) { - ofile.fmtField(fmt); ofile.printField(argnames[n],getPntrToArgument(j)->get(i) ); n++; + ofile.fmtField(fmt); + ofile.printField(argnames[n],getPntrToArgument(j)->get(i) ); + n++; } else if( getPntrToArgument(j)->getRank()==2 ) { unsigned ncols = getPntrToArgument(j)->getShape()[1]; - for(unsigned k=0; kget(i*ncols+k)); n++; } + for(unsigned k=0; kget(i*ncols+k)); + n++; + } } } ofile.printField(); diff --git a/src/generic/EffectiveEnergyDrift.cpp b/src/generic/EffectiveEnergyDrift.cpp index c8e1368645..fe93815ee6 100644 --- a/src/generic/EffectiveEnergyDrift.cpp +++ b/src/generic/EffectiveEnergyDrift.cpp @@ -157,15 +157,18 @@ EffectiveEnergyDrift::EffectiveEnergyDrift(const ActionOptions&ao): domains(NULL), posx(NULL), posy(NULL), - posz(NULL) -{ + posz(NULL) { //stride must be == 1 - if(getStride()!=1) error("EFFECTIVE_ENERGY_DRIFT must have STRIDE=1 to work properly"); + if(getStride()!=1) { + error("EFFECTIVE_ENERGY_DRIFT must have STRIDE=1 to work properly"); + } //parse and open FILE std::string fileName; parse("FILE",fileName); - if(fileName.length()==0) error("name out output file was not specified\n"); + if(fileName.length()==0) { + error("name out output file was not specified\n"); + } output.link(*this); output.open(fileName); @@ -182,14 +185,19 @@ EffectiveEnergyDrift::EffectiveEnergyDrift(const ActionOptions&ao): ensemble=false; parseFlag("ENSEMBLE",ensemble); if(ensemble&&comm.Get_rank()==0) { - if(multi_sim_comm.Get_size()<2) error("You CANNOT run Replica-Averaged simulations without running multiple replicas!\n"); + if(multi_sim_comm.Get_size()<2) { + error("You CANNOT run Replica-Averaged simulations without running multiple replicas!\n"); + } } log<<"Bibliography "< tmpActions=plumed.getActionSet().select(); - for(unsigned i=0; iexists(tmpActions[i]->getLabel()+".bias")) biases.push_back(tmpActions[i]); + for(unsigned i=0; iexists(tmpActions[i]->getLabel()+".bias")) { + biases.push_back(tmpActions[i]); + } //resize counters and displacements useful to communicate with MPI_Allgatherv indexCnt.resize(nProc); @@ -200,13 +208,21 @@ EffectiveEnergyDrift::EffectiveEnergyDrift(const ActionOptions&ao): pbc_action=plumed.getActionSet().selectWithLabel("Box"); // Get the domain decomposition object std::vector ddact=plumed.getActionSet().select(); - if( ddact.size()>1 ) warning("found more than one interface so don't know get gatindex"); + if( ddact.size()>1 ) { + warning("found more than one interface so don't know get gatindex"); + } domains = ddact[0]; std::vector inputs=plumed.getActionSet().select(); for(const auto & pp : inputs ) { - if( pp->getRole()=="x" ) posx = pp; - if( pp->getRole()=="y" ) posy = pp; - if( pp->getRole()=="z" ) posz = pp; + if( pp->getRole()=="x" ) { + posx = pp; + } + if( pp->getRole()=="y" ) { + posy = pp; + } + if( pp->getRole()=="z" ) { + posz = pp; + } } plumed_assert( posx && posy && posz ); //resize the received buffers @@ -220,15 +236,20 @@ EffectiveEnergyDrift::~EffectiveEnergyDrift() { } void EffectiveEnergyDrift::update() { - Pbc & tpbc(pbc_action->getPbc()); bool pbc=tpbc.isSet(); + Pbc & tpbc(pbc_action->getPbc()); + bool pbc=tpbc.isSet(); //retrieve data of local atoms const std::vector& gatindex = domains->getGatindex(); nLocalAtoms = gatindex.size(); - xpositions.resize( gatindex.size() ); posx->getLocalValues( xpositions ); - ypositions.resize( gatindex.size() ); posy->getLocalValues( ypositions ); - zpositions.resize( gatindex.size() ); posz->getLocalValues( zpositions ); - positions.resize( gatindex.size() ); forces.resize( gatindex.size() ); + xpositions.resize( gatindex.size() ); + posx->getLocalValues( xpositions ); + ypositions.resize( gatindex.size() ); + posy->getLocalValues( ypositions ); + zpositions.resize( gatindex.size() ); + posz->getLocalValues( zpositions ); + positions.resize( gatindex.size() ); + forces.resize( gatindex.size() ); for(unsigned i=0; icopyOutput(0); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) virial[i][j]=boxValue->getForce(3*i+j); + box=B; + Tensor virial; + Value* boxValue = pbc_action->copyOutput(0); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + virial[i][j]=boxValue->getForce(3*i+j); + } fbox=matmul(transpose(inverse(box)),virial); } @@ -286,7 +312,9 @@ void EffectiveEnergyDrift::update() { for(int i=0; igetOutputQuantity("bias"); + for(unsigned i=0; igetOutputQuantity("bias"); + } plumed.comm.Sum(&eedSum,1); double effective = eedSum+bias-initialBias-plumed.getWork(); // this is to take into account ensemble averaging if(ensemble) { - if(plumed.comm.Get_rank()==0) plumed.multi_sim_comm.Sum(&effective,1); - else effective=0.; + if(plumed.comm.Get_rank()==0) { + plumed.multi_sim_comm.Sum(&effective,1); + } else { + effective=0.; + } plumed.comm.Sum(&effective,1); } output.fmtField(" %f"); diff --git a/src/generic/EndPlumed.cpp b/src/generic/EndPlumed.cpp index 8323d34599..a3d5331bc0 100644 --- a/src/generic/EndPlumed.cpp +++ b/src/generic/EndPlumed.cpp @@ -52,8 +52,7 @@ PRINT ARG=d FILE=COLVAR STRIDE=1 */ //+ENDPLUMEDOC class EndPlumed: - public Action -{ + public Action { public: explicit EndPlumed(const ActionOptions&ao); /// Register all the relevant keywords for the action @@ -69,8 +68,7 @@ void EndPlumed::registerKeywords( Keywords& keys ) { } EndPlumed::EndPlumed(const ActionOptions&ao): - Action(ao) -{ + Action(ao) { checkRead(); plumed.setEndPlumed(); } diff --git a/src/generic/FitToTemplate.cpp b/src/generic/FitToTemplate.cpp index 6fae4e6998..ff8f2f9bc8 100644 --- a/src/generic/FitToTemplate.cpp +++ b/src/generic/FitToTemplate.cpp @@ -170,8 +170,7 @@ the ligand. class FitToTemplate: public ActionPilot, public ActionAtomistic, - public ActionWithValue -{ + public ActionWithValue { std::string type; bool nopbc; std::vector weights; @@ -194,10 +193,14 @@ class FitToTemplate: public: explicit FitToTemplate(const ActionOptions&ao); static void registerKeywords( Keywords& keys ); - bool actionHasForces() override { return true; } + bool actionHasForces() override { + return true; + } void calculate() override; void apply() override; - unsigned getNumberOfDerivatives() override {plumed_merror("You should not call this function");}; + unsigned getNumberOfDerivatives() override { + plumed_merror("You should not call this function"); + }; }; PLUMED_REGISTER_ACTION(FitToTemplate,"FIT_TO_TEMPLATE") @@ -216,8 +219,7 @@ FitToTemplate::FitToTemplate(const ActionOptions&ao): ActionPilot(ao), ActionAtomistic(ao), ActionWithValue(ao), - nopbc(false) -{ + nopbc(false) { std::string reference; parse("REFERENCE",reference); type.assign("SIMPLE"); @@ -231,40 +233,61 @@ FitToTemplate::FitToTemplate(const ActionOptions&ao): PDB pdb; // read everything in ang and transform to nm if we are not in natural units - if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) + if( !pdb.read(reference,usingNaturalUnits(),0.1/getUnits().getLength()) ) { error("missing input file " + reference ); + } requestAtoms(pdb.getAtomNumbers()); log.printf(" found %zu atoms in input \n",pdb.getAtomNumbers().size()); log.printf(" with indices : "); for(unsigned i=0; i positions=pdb.getPositions(); weights=pdb.getOccupancy(); - std::vector aligned=pdb.getAtomNumbers(); p_aligned.resize( aligned.size() ); - for(unsigned i=0; i aligned=pdb.getAtomNumbers(); + p_aligned.resize( aligned.size() ); + for(unsigned i=0; i weights_measure=pdb.getBeta(); - n=0.0; for(unsigned i=0; i(); @@ -275,7 +298,8 @@ FitToTemplate::FitToTemplate(const ActionOptions&ao): log<<" Ignoring PBCs when doing alignment, make sure your molecule is whole!("Box"); - if( !pbc_action ) error("cannot align box has not been set"); + if( !pbc_action ) { + error("cannot align box has not been set"); + } boxValue=pbc_action->copyOutput(0); } void FitToTemplate::calculate() { - if(!nopbc) makeWhole(); + if(!nopbc) { + makeWhole(); + } if (type=="SIMPLE") { Vector cc; @@ -313,11 +341,11 @@ void FitToTemplate::calculate() { Vector ato=getGlobalPosition(a); setGlobalPosition(a,ato+shift); } - } - else if( type=="OPTIMAL" or type=="OPTIMAL-FAST") { + } else if( type=="OPTIMAL" or type=="OPTIMAL-FAST") { // specific stuff that provides all that is needed double r=rmsd->calc_FitElements( getPositions(), rotation, drotdpos, centeredpositions, center_positions); - setValue(r); unsigned nat = getTotAtoms(); + setValue(r); + unsigned nat = getTotAtoms(); for(unsigned i=0; i a = getValueIndices( AtomNumber::index(i)); Vector ato=getGlobalPosition(a); @@ -338,8 +366,13 @@ void FitToTemplate::apply() { totForce+=getForce(a); } Tensor vv=Tensor(center,totForce); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) boxValue->addForce( 3*i+j, vv(i,j) ); - for(unsigned i=0; iaddForce( 3*i+j, vv(i,j) ); + } + for(unsigned i=0; igetForce( 3*i+j ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + virial[i][j] = boxValue->getForce( 3*i+j ); + } // notice that an extra Tensor(center,matmul(rotation,totForce)) is required to // compute the derivatives of the rotation with respect to center Tensor ww=matmul(transpose(rotation),virial+Tensor(center,matmul(rotation,totForce))); @@ -375,8 +411,12 @@ void FitToTemplate::apply() { virial+=extProduct(getPosition(i),g); } // finally, correction to the virial - boxValue->clearInputForce(); virial+=extProduct(matmul(transpose(rotation),center),totForce); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) boxValue->addForce( 3*i+j, virial(i,j) ); + boxValue->clearInputForce(); + virial+=extProduct(matmul(transpose(rotation),center),totForce); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + boxValue->addForce( 3*i+j, virial(i,j) ); + } } } diff --git a/src/generic/Flush.cpp b/src/generic/Flush.cpp index 374ba30c8f..eddbd64897 100644 --- a/src/generic/Flush.cpp +++ b/src/generic/Flush.cpp @@ -55,13 +55,11 @@ PRINT ARG=d2 STRIDE=10 FILE=colvar2 //+ENDPLUMEDOC class Flush: - public ActionPilot -{ + public ActionPilot { public: explicit Flush(const ActionOptions&ao): Action(ao), - ActionPilot(ao) - { + ActionPilot(ao) { checkRead(); } static void registerKeywords( Keywords& keys ); @@ -71,8 +69,9 @@ class Flush: plumed.fflush(); log.flush(); const ActionSet & actionSet(plumed.getActionSet()); - for(const auto & p : actionSet) + for(const auto & p : actionSet) { p->fflush(); + } } }; diff --git a/src/generic/GatherReplicas.cpp b/src/generic/GatherReplicas.cpp index eaa0fe7de9..16ac4b0528 100644 --- a/src/generic/GatherReplicas.cpp +++ b/src/generic/GatherReplicas.cpp @@ -53,28 +53,44 @@ class GatherReplicas : PLUMED_REGISTER_ACTION(GatherReplicas,"GATHER_REPLICAS") void GatherReplicas::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); ActionWithArguments::registerKeywords( keys ); - keys.remove("ARG"); keys.add("compulsory","ARG","the argument from the various replicas that you would like to gather"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.remove("ARG"); + keys.add("compulsory","ARG","the argument from the various replicas that you would like to gather"); keys.addOutputComponent("rep","default","the input arguments for each of the replicas"); } GatherReplicas::GatherReplicas( const ActionOptions& ao ): Action(ao), ActionWithValue(ao), - ActionWithArguments(ao) -{ - if( getNumberOfArguments()!=1 ) error("you can only gather one argument at a time with GatherReplicas"); + ActionWithArguments(ao) { + if( getNumberOfArguments()!=1 ) { + error("you can only gather one argument at a time with GatherReplicas"); + } std::vector shape( getPntrToArgument(0)->getShape() ); - std::string min, max; nreplicas=multi_sim_comm.Get_size(); bool periodic=false; - if( getPntrToArgument(0)->isPeriodic() ) { periodic=true; getPntrToArgument(0)->getDomain( min, max ); } + std::string min, max; + nreplicas=multi_sim_comm.Get_size(); + bool periodic=false; + if( getPntrToArgument(0)->isPeriodic() ) { + periodic=true; + getPntrToArgument(0)->getDomain( min, max ); + } for(unsigned i=0; ihasDerivatives() ) addComponentWithDerivatives( "rep-" + num, shape ); - else addComponent( "rep-" + num, shape ); - if( periodic ) componentIsPeriodic( "rep-" + num, min, max ); - else componentIsNotPeriodic( "rep-" + num ); + std::string num; + Tools::convert( i+1, num); + if( getPntrToArgument(0)->hasDerivatives() ) { + addComponentWithDerivatives( "rep-" + num, shape ); + } else { + addComponent( "rep-" + num, shape ); + } + if( periodic ) { + componentIsPeriodic( "rep-" + num, min, max ); + } else { + componentIsNotPeriodic( "rep-" + num ); + } } } @@ -88,25 +104,45 @@ void GatherReplicas::calculate() { std::vector dval( nvals*(1+nder) ), datap(nreplicas*nvals*(1+nder) ); for(unsigned i=0; iget(i); - if( myarg->getRank()==0 ) { for(unsigned j=0; jgetDerivative(j); } - else if( myarg->hasDerivatives() ) { for(unsigned j=0; jgetGridDerivative( i, j ); } + if( myarg->getRank()==0 ) { + for(unsigned j=0; jgetDerivative(j); + } + } else if( myarg->hasDerivatives() ) { + for(unsigned j=0; jgetGridDerivative( i, j ); + } + } + } + if(comm.Get_rank()==0) { + multi_sim_comm.Allgather(dval,datap); } - if(comm.Get_rank()==0) multi_sim_comm.Allgather(dval,datap); for(unsigned k=0; kgetNumberOfDerivatives()!=myarg->getNumberOfDerivatives() ) myout->resizeDerivatives( myarg->getNumberOfDerivatives() ); + if( myout->getNumberOfDerivatives()!=myarg->getNumberOfDerivatives() ) { + myout->resizeDerivatives( myarg->getNumberOfDerivatives() ); + } unsigned sstart=k*nvals*(1+nder); for(unsigned i=0; iset( i, datap[sstart+i*(1+nder)] ); - if( myarg->getRank()==0 ) { for(unsigned j=0; jsetDerivative( j, dval[i*(1+nder)+1+j] ); } - else if( myarg->hasDerivatives() ) { for(unsigned j=0; jaddGridDerivatives( i, j, dval[i*(1+nder)+1+j] ); } + if( myarg->getRank()==0 ) { + for(unsigned j=0; jsetDerivative( j, dval[i*(1+nder)+1+j] ); + } + } else if( myarg->hasDerivatives() ) { + for(unsigned j=0; jaddGridDerivatives( i, j, dval[i*(1+nder)+1+j] ); + } + } } } } void GatherReplicas::apply() { - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } error("apply has not been implemented for GatherReplicas"); } diff --git a/src/generic/Include.cpp b/src/generic/Include.cpp index f8b44ffddd..26f7d7da91 100644 --- a/src/generic/Include.cpp +++ b/src/generic/Include.cpp @@ -148,8 +148,7 @@ RESTRAINT ARG=t AT=1.2 KAPPA=10 //+ENDPLUMEDOC class Include : - public ActionAnyorder -{ + public ActionAnyorder { public: static void registerKeywords( Keywords& keys ); explicit Include(const ActionOptions&ao); @@ -166,8 +165,7 @@ void Include::registerKeywords( Keywords& keys ) { Include::Include(const ActionOptions&ao): Action(ao), - ActionAnyorder(ao) -{ + ActionAnyorder(ao) { std::string f; parse("FILE",f); checkRead(); diff --git a/src/generic/MassChargeInput.cpp b/src/generic/MassChargeInput.cpp index 986f7533ed..49755e3cd9 100644 --- a/src/generic/MassChargeInput.cpp +++ b/src/generic/MassChargeInput.cpp @@ -60,35 +60,55 @@ void MassChargeInput::registerKeywords(Keywords& keys) { MassChargeInput::MassChargeInput(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { const ActionSet& actionset(plumed.getActionSet()); for(const auto & p : actionset) { // check that all the preceding actions are ActionSetup if( !dynamic_cast(p.get()) && !dynamic_cast(p.get()) && !dynamic_cast(p.get()) ) { error("Action " + getLabel() + " is a setup action, and should be only preceded by other setup actions or by actions that can be used in any order."); - } else if( (p.get())->getName()=="READMASSCHARGE" ) error("should only be one READMASSCHARGE action in the input file"); + } else if( (p.get())->getName()=="READMASSCHARGE" ) { + error("should only be one READMASSCHARGE action in the input file"); + } } // Check for correct number of atoms - unsigned natoms=0; std::vector inputs=plumed.getActionSet().select(); + unsigned natoms=0; + std::vector inputs=plumed.getActionSet().select(); for(const auto & pp : inputs ) { - if( pp->getRole()=="x" ) natoms = (pp->copyOutput(0))->getShape()[0]; + if( pp->getRole()=="x" ) { + natoms = (pp->copyOutput(0))->getShape()[0]; + } } - std::string input; parse("FILE",input); std::vector masses( natoms ), charges( natoms ); + std::string input; + parse("FILE",input); + std::vector masses( natoms ), charges( natoms ); if( input.length()>0 ) { log.printf(" reading masses and charges from file named %s \n", input.c_str() ); - IFile ifile; ifile.open( input ); int index; double mass; double charge; + IFile ifile; + ifile.open( input ); + int index; + double mass; + double charge; while(ifile.scanField("index",index).scanField("mass",mass).scanField("charge",charge).scanField()) { - if( index>=natoms ) error("indices of atoms in input file are too large"); - masses[index]=mass; charges[index]=charge; + if( index>=natoms ) { + error("indices of atoms in input file are too large"); + } + masses[index]=mass; + charges[index]=charge; } ifile.close(); } else { - std::string pdbinpt; parse("PDBFILE",pdbinpt); PDB pdb; + std::string pdbinpt; + parse("PDBFILE",pdbinpt); + PDB pdb; log.printf(" reading masses and charges from pdb file named %s \n", pdbinpt.c_str() ); - if( !pdb.read(pdbinpt, false, 1.0 ) ) error("error reading pdb file containing masses and charges"); - if( natoms!=pdb.size() ) error("mismatch between number of atoms passed from MD code and number of atoms in PDB file"); - masses = pdb.getOccupancy(); charges = pdb.getBeta(); + if( !pdb.read(pdbinpt, false, 1.0 ) ) { + error("error reading pdb file containing masses and charges"); + } + if( natoms!=pdb.size() ) { + error("mismatch between number of atoms passed from MD code and number of atoms in PDB file"); + } + masses = pdb.getOccupancy(); + charges = pdb.getBeta(); } // Now get masses and charges @@ -96,8 +116,10 @@ MassChargeInput::MassChargeInput(const ActionOptions& ao): Tools::convert( masses[0], mstr ); Tools::convert( charges[0], qstr ); for(unsigned i=1; i argn; parseVector("ARG",argn); std::vector theargs; + ActionShortcut(ao) { + std::string input; + parse("REFERENCE",input); + unsigned frame; + parse("NUMBER",frame); + bool noargs=false; + std::vector argn; + parseVector("ARG",argn); + std::vector theargs; if( argn.size()>0 ) { parseFlag("NOARGS",noargs); - if( !noargs ) ActionWithArguments::interpretArgumentList( argn, plumed.getActionSet(), this, theargs ); - else if( argn.size()>1 ) error("can only read one argument at a time from input pdb file"); - else log.printf(" reading argument %s from file \n", argn[0].c_str() ); + if( !noargs ) { + ActionWithArguments::interpretArgumentList( argn, plumed.getActionSet(), this, theargs ); + } else if( argn.size()>1 ) { + error("can only read one argument at a time from input pdb file"); + } else { + log.printf(" reading argument %s from file \n", argn[0].c_str() ); + } + } + if( theargs.size()>1 ) { + error("can only read one argument at a time from input pdb file"); } - if( theargs.size()>1 ) error("can only read one argument at a time from input pdb file"); - FILE* fp=std::fopen(input.c_str(),"r"); bool do_read=true; std::vector vals; - if(!fp) plumed_merror("could not open reference file " + input); unsigned natoms=0, nframes=0; + FILE* fp=std::fopen(input.c_str(),"r"); + bool do_read=true; + std::vector vals; + if(!fp) { + plumed_merror("could not open reference file " + input); + } + unsigned natoms=0, nframes=0; while ( do_read ) { - PDB mypdb; do_read=mypdb.readFromFilepointer(fp,plumed.usingNaturalUnits(),0.1/plumed.getUnits().getLength()); - if( !do_read && nframes>0 ) break ; + PDB mypdb; + do_read=mypdb.readFromFilepointer(fp,plumed.usingNaturalUnits(),0.1/plumed.getUnits().getLength()); + if( !do_read && nframes>0 ) { + break ; + } - if( natoms==0 ) natoms = mypdb.getPositions().size(); - else if( mypdb.getPositions().size()!=natoms ) plumed_merror("mismatch between sizes of reference configurations"); + if( natoms==0 ) { + natoms = mypdb.getPositions().size(); + } else if( mypdb.getPositions().size()!=natoms ) { + plumed_merror("mismatch between sizes of reference configurations"); + } if( nframes+1==frame || frame==0 ) { std::vector align( mypdb.getOccupancy() ); - double asum=0; for(unsigned i=0; iepsilon ) { - double iasum = 1 / asum; for(unsigned i=0; i0 ) { - double iasum = 1 / mypdb.size(); for(unsigned i=0; i argvals( 1 ); - if( !mypdb.getArgumentValue(argn[0], argvals ) ) error("argument " + argn[0] + " was not set in pdb input"); + if( !mypdb.getArgumentValue(argn[0], argvals ) ) { + error("argument " + argn[0] + " was not set in pdb input"); + } vals.push_back( argvals[0] ); } else { std::vector argvals( theargs[0]->getNumberOfValues() ); - if( !mypdb.getArgumentValue(theargs[0]->getName(), argvals ) ) error("argument " + theargs[0]->getName() + " was not set in pdb input"); - for(unsigned i=0; igetName(), argvals ) ) { + error("argument " + theargs[0]->getName() + " was not set in pdb input"); + } + for(unsigned i=0; i0 ) nframes=1; - std::fclose(fp); std::string rnum; plumed_assert( vals.size()>0 ); - Tools::convert( vals[0], rnum ); std::string valstr = " VALUES=" + rnum; - for(unsigned i=1; i0 ) { + nframes=1; + } + std::fclose(fp); + std::string rnum; + plumed_assert( vals.size()>0 ); + Tools::convert( vals[0], rnum ); + std::string valstr = " VALUES=" + rnum; + for(unsigned i=1; inframes ) { - std::string nc, nr; Tools::convert( nframes, nr ); Tools::convert( vals.size()/nframes, nc ); + std::string nc, nr; + Tools::convert( nframes, nr ); + Tools::convert( vals.size()/nframes, nc ); readInputLine( getShortcutLabel() + ": CONSTANT NROWS=" + nr + " NCOLS=" + nc + valstr ); - } else readInputLine( getShortcutLabel() + ": CONSTANT" + valstr ); + } else { + readInputLine( getShortcutLabel() + ": CONSTANT" + valstr ); + } } } diff --git a/src/generic/Plumed.cpp b/src/generic/Plumed.cpp index 3972d5b1e6..e449799a1e 100644 --- a/src/generic/Plumed.cpp +++ b/src/generic/Plumed.cpp @@ -126,8 +126,7 @@ PLUMED FILE=plumed.dat CHDIR=directory2 class Plumed: public ActionAtomistic, public ActionWithValue, - public ActionPilot -{ + public ActionPilot { /// True on root processor const bool root; /// Separate directory. @@ -168,7 +167,9 @@ class Plumed: unsigned getNumberOfDerivatives() override { return 0; } - bool actionHasForces() override { return true; } + bool actionHasForces() override { + return true; + } }; PLUMED_REGISTER_ACTION(Plumed,"PLUMED") @@ -219,14 +220,15 @@ API([&]() { // as a matter of fact, any version <2.5 will not even load due to namespace pollution plumed_assert(api>3) << "API>3 is required for the PLUMED action to work correctly\n"; return api; -}()) -{ +}()) { Tools::DirectoryChanger directoryChanger(directory.c_str()); bool noreplicas; parseFlag("NOREPLICAS",noreplicas); int nreps; - if(root) nreps=multi_sim_comm.Get_size(); + if(root) { + nreps=multi_sim_comm.Get_size(); + } comm.Bcast(nreps,0); if(nreps>1) { if(noreplicas) { @@ -256,76 +258,133 @@ API([&]() { parse("FILE",file); if(file.length()>0) { log<<" with input file "<0) { log<<" with log file "< numbers; numbers.reserve(index.size()); - for(auto i : index) numbers.emplace_back(AtomNumber::index(i)); + for(auto i : index) { + numbers.emplace_back(AtomNumber::index(i)); + } requestAtoms(numbers); } } void Plumed::calculate() { Tools::DirectoryChanger directoryChanger(directory.c_str()); - if(root) p.cmd("setStopFlag",&stop); + if(root) { + p.cmd("setStopFlag",&stop); + } Tensor box=getPbc().getBox(); - if(root) p.cmd("setBox",&box[0][0], {3,3}); + if(root) + p.cmd("setBox",&box[0][0], {3,3}); virial.zero(); - for(int i=0; iset(bias); } @@ -398,14 +487,22 @@ void Plumed::calculate() { void Plumed::apply() { Tools::DirectoryChanger directoryChanger(directory.c_str()); std::vector fforces( forces.size() + 9, 0 ); - for(unsigned i=0; i0) { @@ -139,7 +137,9 @@ Print::Print(const ActionOptions&ao): parse("_ROTATE",rotate); if(rotate>0) { rotateCountdown=rotate; - for(unsigned i=0; i a(1,rotateArguments[0]); requestArguments(std::vector(1,rotateArguments[0])); rotateLast=0; @@ -173,7 +173,8 @@ void Print::update() { ofile.fmtField(" %f"); ofile.printField("time",getTime()); for(unsigned i=0; iprint( ofile ); + ofile.fmtField(fmt); + getPntrToArgument(i)->print( ofile ); } ofile.printField(); } diff --git a/src/generic/PrintNDX.cpp b/src/generic/PrintNDX.cpp index afe4a25116..78a9d77088 100644 --- a/src/generic/PrintNDX.cpp +++ b/src/generic/PrintNDX.cpp @@ -40,8 +40,7 @@ namespace generic { class PrintNDX : public ActionPilot, public ActionAtomistic, - public ActionWithArguments -{ + public ActionWithArguments { std::string file; OFile ofile; CheckInRange bounds; @@ -50,8 +49,12 @@ class PrintNDX : std::string writeInGraph() const override; explicit PrintNDX(const ActionOptions&); static void registerKeywords(Keywords& keys); - bool actionHasForces() override { return false; } - void calculateNumericalDerivatives( ActionWithValue* a=NULL ) override { plumed_error(); } + bool actionHasForces() override { + return false; + } + void calculateNumericalDerivatives( ActionWithValue* a=NULL ) override { + plumed_error(); + } void lockRequests() override; void unlockRequests() override; void apply() override {} @@ -81,8 +84,7 @@ PrintNDX::PrintNDX(const ActionOptions&ao): Action(ao), ActionPilot(ao), ActionAtomistic(ao), - ActionWithArguments(ao) -{ + ActionWithArguments(ao) { ofile.link(*this); parse("FILE",file); if(file.length()>0) { @@ -92,23 +94,39 @@ PrintNDX::PrintNDX(const ActionOptions&ao): log.printf(" on plumed log file\n"); ofile.link(log); } - std::vector all_atoms; parseAtomList("ATOMS",all_atoms); std::vector argnames( getNumberOfArguments() ); + std::vector all_atoms; + parseAtomList("ATOMS",all_atoms); + std::vector argnames( getNumberOfArguments() ); requestAtoms( all_atoms, false ); for(unsigned i=0; igetRank()!=1 || getPntrToArgument(i)->hasDerivatives() ) error("arguments for print ndx should be vector"); - if( getPntrToArgument(i)->getShape()[0]!=all_atoms.size() ) error("mismatch between number of arguments and number of input atoms"); - getPntrToArgument(i)->buildDataStore(true); argnames[i] = getPntrToArgument(i)->getName(); + if( getPntrToArgument(i)->getRank()!=1 || getPntrToArgument(i)->hasDerivatives() ) { + error("arguments for print ndx should be vector"); + } + if( getPntrToArgument(i)->getShape()[0]!=all_atoms.size() ) { + error("mismatch between number of arguments and number of input atoms"); + } + getPntrToArgument(i)->buildDataStore(true); + argnames[i] = getPntrToArgument(i)->getName(); } log.printf(" printing ndx file containing indices of atoms that have arguments in ranges prescribed below \n"); log.printf(" full set of atom indices investigated are : "); for(unsigned int i=0; i str_upper, str_lower; std::string errors; - parseVector("LESS_THAN_OR_EQUAL",str_upper); parseVector("GREATER_THAN_OR_EQUAL",str_lower); - if( !bounds.setBounds( getNumberOfArguments(), str_lower, str_upper, errors ) ) error( errors ); - if( bounds.wereSet() ) log.printf(" %s \n", bounds.report( argnames ).c_str() ); + log.printf("\n"); + std::vector str_upper, str_lower; + std::string errors; + parseVector("LESS_THAN_OR_EQUAL",str_upper); + parseVector("GREATER_THAN_OR_EQUAL",str_lower); + if( !bounds.setBounds( getNumberOfArguments(), str_lower, str_upper, errors ) ) { + error( errors ); + } + if( bounds.wereSet() ) { + log.printf(" %s \n", bounds.report( argnames ).c_str() ); + } checkRead(); } @@ -127,13 +145,19 @@ void PrintNDX::unlockRequests() { } void PrintNDX::update() { - unsigned n=0; std::vector argvals( getNumberOfArguments() ); + unsigned n=0; + std::vector argvals( getNumberOfArguments() ); ofile.printf("[ %s step %d ] \n", getLabel().c_str(), getStep() ); for(unsigned i=0; iget(i); + for(unsigned j=0; jget(i); + } if( bounds.check( argvals ) ) { - ofile.printf("%6d", getAbsoluteIndexes()[i].serial() ); n++; - if( n%15==0 ) ofile.printf("\n"); + ofile.printf("%6d", getAbsoluteIndexes()[i].serial() ); + n++; + if( n%15==0 ) { + ofile.printf("\n"); + } } } ofile.printf("\n"); diff --git a/src/generic/RandomExchanges.cpp b/src/generic/RandomExchanges.cpp index 027e8e0a88..3d0a571ab5 100644 --- a/src/generic/RandomExchanges.cpp +++ b/src/generic/RandomExchanges.cpp @@ -71,8 +71,7 @@ should be the same in all input files. //+ENDPLUMEDOC class RandomExchanges: - public Action -{ + public Action { public: static void registerKeywords( Keywords& keys ); explicit RandomExchanges(const ActionOptions&ao); @@ -88,13 +87,14 @@ void RandomExchanges::registerKeywords( Keywords& keys ) { } RandomExchanges::RandomExchanges(const ActionOptions&ao): - Action(ao) -{ + Action(ao) { plumed.getExchangePatterns().setFlag(ExchangePatterns::RANDOM); // I convert the seed to -seed because I think it is more general to use a positive seed in input int seed=-1; parse("SEED",seed); - if(seed>=0) plumed.getExchangePatterns().setSeed(-seed); + if(seed>=0) { + plumed.getExchangePatterns().setSeed(-seed); + } } } diff --git a/src/generic/Read.cpp b/src/generic/Read.cpp index bb28bd9148..2b5e7e80ae 100644 --- a/src/generic/Read.cpp +++ b/src/generic/Read.cpp @@ -76,8 +76,7 @@ The file input_colvar.data is just a normal colvar file as shown below class Read : public ActionPilot, - public ActionWithValue -{ + public ActionWithValue { private: bool ignore_time; bool ignore_forces; @@ -131,8 +130,7 @@ Read::Read(const ActionOptions&ao): ActionWithValue(ao), ignore_time(false), ignore_forces(false), - nlinesPerStep(1) -{ + nlinesPerStep(1) { // Read the file name from the input line parse("FILE",filename); // Check if time is to be ignored @@ -151,50 +149,80 @@ Read::Read(const ActionOptions&ao): if( !cloned_file ) { ifile_ptr=Tools::make_unique(); ifile=ifile_ptr.get(); - if( !ifile->FileExist(filename) ) error("could not find file named " + filename); + if( !ifile->FileExist(filename) ) { + error("could not find file named " + filename); + } ifile->link(*this); ifile->open(filename); ifile->allowIgnoredFields(); } parse("EVERY",nlinesPerStep); - if(nlinesPerStep>1) log.printf(" only reading every %uth line of file %s\n",nlinesPerStep,filename.c_str() ); - else log.printf(" reading data from file %s\n",filename.c_str() ); + if(nlinesPerStep>1) { + log.printf(" only reading every %uth line of file %s\n",nlinesPerStep,filename.c_str() ); + } else { + log.printf(" reading data from file %s\n",filename.c_str() ); + } // Find out what we are reading - std::vector valread; parseVector("VALUES",valread); + std::vector valread; + parseVector("VALUES",valread); - if(nlinesPerStep>1 && cloned_file) error("Opening a file multiple times and using EVERY is not allowed"); + if(nlinesPerStep>1 && cloned_file) { + error("Opening a file multiple times and using EVERY is not allowed"); + } std::size_t dot=valread[0].find_first_of('.'); if( valread[0].find(".")!=std::string::npos ) { std::string label=valread[0].substr(0,dot); std::string name=valread[0].substr(dot+1); if( name=="*" ) { - if( valread.size()>1 ) error("all values must be from the same Action when using READ"); + if( valread.size()>1 ) { + error("all values must be from the same Action when using READ"); + } std::vector fieldnames; ifile->scanFieldList( fieldnames ); for(unsigned i=0; i(this, fieldnames[i], false) ); addComponentWithDerivatives( fieldnames[i].substr(dot+1) ); - if( ifile->FieldExist("min_" + fieldnames[i]) ) componentIsPeriodic( fieldnames[i].substr(dot+1), "-pi","pi" ); - else componentIsNotPeriodic( fieldnames[i].substr(dot+1) ); + readvals.emplace_back(Tools::make_unique(this, fieldnames[i], false) ); + addComponentWithDerivatives( fieldnames[i].substr(dot+1) ); + if( ifile->FieldExist("min_" + fieldnames[i]) ) { + componentIsPeriodic( fieldnames[i].substr(dot+1), "-pi","pi" ); + } else { + componentIsNotPeriodic( fieldnames[i].substr(dot+1) ); + } } } } else { - readvals.emplace_back(Tools::make_unique(this, valread[0], false) ); addComponentWithDerivatives( name ); - if( ifile->FieldExist("min_" + valread[0]) ) componentIsPeriodic( valread[0].substr(dot+1), "-pi", "pi" ); - else componentIsNotPeriodic( valread[0].substr(dot+1) ); + readvals.emplace_back(Tools::make_unique(this, valread[0], false) ); + addComponentWithDerivatives( name ); + if( ifile->FieldExist("min_" + valread[0]) ) { + componentIsPeriodic( valread[0].substr(dot+1), "-pi", "pi" ); + } else { + componentIsNotPeriodic( valread[0].substr(dot+1) ); + } for(unsigned i=1; i(this, valread[i], false) ); addComponentWithDerivatives( valread[i].substr(dot+1) ); - if( ifile->FieldExist("min_" + valread[i]) ) componentIsPeriodic( valread[i].substr(dot+1), "-pi", "pi" ); - else componentIsNotPeriodic( valread[i].substr(dot+1) ); + if( valread[i].substr(0,dot)!=label ) { + error("all values must be from the same Action when using READ"); + }; + readvals.emplace_back(Tools::make_unique(this, valread[i], false) ); + addComponentWithDerivatives( valread[i].substr(dot+1) ); + if( ifile->FieldExist("min_" + valread[i]) ) { + componentIsPeriodic( valread[i].substr(dot+1), "-pi", "pi" ); + } else { + componentIsNotPeriodic( valread[i].substr(dot+1) ); + } } } } else { - if( valread.size()!=1 ) error("all values must be from the same Action when using READ"); - readvals.emplace_back(Tools::make_unique(this, valread[0], false) ); addValueWithDerivatives(); - if( ifile->FieldExist("min_" + valread[0]) ) setPeriodic( "-pi", "pi" ); - else setNotPeriodic(); + if( valread.size()!=1 ) { + error("all values must be from the same Action when using READ"); + } + readvals.emplace_back(Tools::make_unique(this, valread[0], false) ); + addValueWithDerivatives(); + if( ifile->FieldExist("min_" + valread[0]) ) { + setPeriodic( "-pi", "pi" ); + } else { + setNotPeriodic(); + } log.printf(" reading value %s and storing as %s\n",valread[0].c_str(),getLabel().c_str() ); } checkRead(); @@ -203,9 +231,12 @@ Read::Read(const ActionOptions&ao): std::string Read::getOutputComponentDescription( const std::string& cname, const Keywords& keys ) const { plumed_assert( !exists( getLabel() ) ); for(unsigned i=0; igetName().find( cname )!=std::string::npos ) return "values from the column labelled " + readvals[i]->getName() + " in the file named " + filename; + if( readvals[i]->getName().find( cname )!=std::string::npos ) { + return "values from the column labelled " + readvals[i]->getName() + " in the file named " + filename; + } } - plumed_error(); return ""; + plumed_error(); + return ""; } std::string Read::getFilename() const { @@ -221,8 +252,9 @@ unsigned Read::getNumberOfDerivatives() { } void Read::turnOnDerivatives() { - if( !ignore_forces ) error("cannot calculate derivatives for colvars that are read in from a file. If you are postprocessing and " - "these forces do not matter add the flag IGNORE_FORCES to all READ actions"); + if( !ignore_forces ) + error("cannot calculate derivatives for colvars that are read in from a file. If you are postprocessing and " + "these forces do not matter add the flag IGNORE_FORCES to all READ actions"); } void Read::prepare() { @@ -231,7 +263,9 @@ void Read::prepare() { if( !ifile->scanField("time",du_time) ) { error("Reached end of file " + filename + " before end of trajectory"); } else if( std::abs( du_time-getTime() )>getTimeStep() && !ignore_time ) { - std::string str_dutime,str_ptime; Tools::convert(du_time,str_dutime); Tools::convert(getTime(),str_ptime); + std::string str_dutime,str_ptime; + Tools::convert(du_time,str_dutime); + Tools::convert(getTime(),str_ptime); error("mismatched times in colvar files : colvar time=" + str_dutime + " plumed time=" + str_ptime + ". Add IGNORE_TIME to ignore error."); } } @@ -254,8 +288,11 @@ void Read::calculate() { void Read::update() { if( !cloned_file ) { for(unsigned i=0; iscanField(); double du_time; - if( !ifile->scanField("time",du_time) && !plumed.inputsAreActive() ) plumed.stop(); + ifile->scanField(); + double du_time; + if( !ifile->scanField("time",du_time) && !plumed.inputsAreActive() ) { + plumed.stop(); + } } } } diff --git a/src/generic/ResetCell.cpp b/src/generic/ResetCell.cpp index 0882258e56..7aa82d9788 100644 --- a/src/generic/ResetCell.cpp +++ b/src/generic/ResetCell.cpp @@ -93,8 +93,7 @@ END class ResetCell: public ActionPilot, - public ActionAtomistic -{ + public ActionAtomistic { std::string type; Tensor rotation,newbox; Value* boxValue; @@ -118,16 +117,19 @@ void ResetCell::registerKeywords( Keywords& keys ) { ResetCell::ResetCell(const ActionOptions&ao): Action(ao), ActionPilot(ao), - ActionAtomistic(ao) -{ + ActionAtomistic(ao) { type.assign("TRIANGULAR"); parse("TYPE",type); log<<" type: "<("Box"); - if( !pbc_action ) error("cannot reset cell if box has not been set"); + if( !pbc_action ) { + error("cannot reset cell if box has not been set"); + } boxValue=pbc_action->copyOutput(0); } @@ -153,7 +155,9 @@ void ResetCell::calculate() { newbox[2][1]=c*(bc-ac*ab)/std::sqrt(1-ab*ab); newbox[2][2]=std::sqrt(c*c-newbox[2][0]*newbox[2][0]-newbox[2][1]*newbox[2][1]); - if(determinant(newbox)*determinant(box)<0) newbox[2][2]=-newbox[2][2]; + if(determinant(newbox)*determinant(box)<0) { + newbox[2][2]=-newbox[2][2]; + } // rotation matrix from old to new coordinates rotation=transpose(matmul(inverse(box),newbox)); @@ -192,13 +196,20 @@ void ResetCell::apply() { // of the virial matrix equal to their symmetric ones. // GB Tensor virial; - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) virial[i][j]=boxValue->getForce( 3*i+j ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + virial[i][j]=boxValue->getForce( 3*i+j ); + } virial[0][1]=virial[1][0]; virial[0][2]=virial[2][0]; virial[1][2]=virial[2][1]; // rotate back virial - virial=matmul(transpose(rotation),matmul(virial,rotation)); boxValue->clearInputForce(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) boxValue->addForce( 3*i+j, virial(i,j) ); + virial=matmul(transpose(rotation),matmul(virial,rotation)); + boxValue->clearInputForce(); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + boxValue->addForce( 3*i+j, virial(i,j) ); + } } diff --git a/src/generic/Time.cpp b/src/generic/Time.cpp index 804074e93c..bee55aa878 100644 --- a/src/generic/Time.cpp +++ b/src/generic/Time.cpp @@ -48,7 +48,9 @@ class Time : public ActionWithValue { // active methods: void calculate() override; void apply() override {} - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } }; PLUMED_REGISTER_ACTION(Time,"TIME") @@ -60,9 +62,9 @@ void Time::registerKeywords( Keywords& keys ) { } Time::Time(const ActionOptions&ao): - Action(ao),ActionWithValue(ao) -{ - addValueWithDerivatives(); setNotPeriodic(); + Action(ao),ActionWithValue(ao) { + addValueWithDerivatives(); + setNotPeriodic(); // resize derivative by hand to a nonzero value getPntrToValue()->resizeDerivatives(1); } diff --git a/src/generic/UpdateIf.cpp b/src/generic/UpdateIf.cpp index a7abb36d04..b3854282b1 100644 --- a/src/generic/UpdateIf.cpp +++ b/src/generic/UpdateIf.cpp @@ -78,8 +78,7 @@ UPDATE_IF ARG=coord END class UpdateIf: public ActionPilot, - public ActionWithArguments -{ + public ActionWithArguments { std::vector lower; std::vector upper; bool on; @@ -112,17 +111,28 @@ UpdateIf::UpdateIf(const ActionOptions&ao): ActionPilot(ao), ActionWithArguments(ao), on(false), - end(false) -{ + end(false) { parseFlag("END",end); parseVector("LESS_THAN",upper); parseVector("MORE_THAN",lower); - if(end && upper.size()!=0) error("END and LESS_THAN are not compatible"); - if(end && lower.size()!=0) error("END and MORE_THAN are not compatible"); - if(upper.size()==0) upper.assign(getNumberOfArguments(),+std::numeric_limits::max()); - if(lower.size()==0) lower.assign(getNumberOfArguments(),-std::numeric_limits::max()); - if(upper.size()!=getNumberOfArguments()) error("LESS_THAN should have the same size as ARG"); - if(lower.size()!=getNumberOfArguments()) error("MORE_THAN should have the same size as ARG"); + if(end && upper.size()!=0) { + error("END and LESS_THAN are not compatible"); + } + if(end && lower.size()!=0) { + error("END and MORE_THAN are not compatible"); + } + if(upper.size()==0) { + upper.assign(getNumberOfArguments(),+std::numeric_limits::max()); + } + if(lower.size()==0) { + lower.assign(getNumberOfArguments(),-std::numeric_limits::max()); + } + if(upper.size()!=getNumberOfArguments()) { + error("LESS_THAN should have the same size as ARG"); + } + if(lower.size()!=getNumberOfArguments()) { + error("MORE_THAN should have the same size as ARG"); + } for(unsigned i=0; i=upper[i] || getArgument(i)<=lower[i]) on=false; + if(getArgument(i)>=upper[i] || getArgument(i)<=lower[i]) { + on=false; + } } } void UpdateIf::beforeUpdate() { - if(end) plumed.updateFlagsPop(); - else { - if(on) plumed.updateFlagsPush(plumed.updateFlagsTop()); - else plumed.updateFlagsPush(false); + if(end) { + plumed.updateFlagsPop(); + } else { + if(on) { + plumed.updateFlagsPush(plumed.updateFlagsTop()); + } else { + plumed.updateFlagsPush(false); + } } } diff --git a/src/generic/WholeMolecules.cpp b/src/generic/WholeMolecules.cpp index e04ebfca4a..38a7c743f1 100644 --- a/src/generic/WholeMolecules.cpp +++ b/src/generic/WholeMolecules.cpp @@ -101,8 +101,7 @@ WHOLEMOLECULES RESIDUES=all MOLTYPE=protein class WholeMolecules: public ActionPilot, - public ActionAtomistic -{ + public ActionAtomistic { std::vector > > p_groups; std::vector > > p_roots; std::vector refs; @@ -110,7 +109,9 @@ class WholeMolecules: public: explicit WholeMolecules(const ActionOptions&ao); static void registerKeywords( Keywords& keys ); - bool actionHasForces() override { return false; } + bool actionHasForces() override { + return false; + } void calculate() override; void apply() override {} }; @@ -137,8 +138,7 @@ WholeMolecules::WholeMolecules(const ActionOptions&ao): Action(ao), ActionPilot(ao), ActionAtomistic(ao), - doemst(false), addref(false) -{ + doemst(false), addref(false) { std::vector > groups; std::vector > roots; // parse optional flags @@ -149,20 +149,30 @@ WholeMolecules::WholeMolecules(const ActionOptions&ao): for(int i=0;; i++) { std::vector group; parseAtomList("ENTITY",i,group); - if( group.empty() ) break; + if( group.empty() ) { + break; + } groups.push_back(group); } // Read residues to align from MOLINFO - std::vector resstrings; parseVector("RESIDUES",resstrings); + std::vector resstrings; + parseVector("RESIDUES",resstrings); if( resstrings.size()>0 ) { if( resstrings.size()==1 ) { - if( resstrings[0]=="all" ) resstrings[0]="all-ter"; // Include terminal groups in alignment + if( resstrings[0]=="all" ) { + resstrings[0]="all-ter"; // Include terminal groups in alignment + } + } + std::string moltype; + parse("MOLTYPE",moltype); + if(moltype.length()==0) { + error("Found RESIDUES keyword without specification of the molecule - use MOLTYPE"); } - std::string moltype; parse("MOLTYPE",moltype); - if(moltype.length()==0) error("Found RESIDUES keyword without specification of the molecule - use MOLTYPE"); auto* moldat=plumed.getActionSet().selectLatest(this); - if( !moldat ) error("MOLINFO is required to use RESIDUES"); + if( !moldat ) { + error("MOLINFO is required to use RESIDUES"); + } std::vector< std::vector > backatoms; moldat->getBackbone( resstrings, moltype, backatoms ); for(unsigned i=0; i(this); - if( !moldat ) error("MOLINFO is required to use EMST"); + if( !moldat ) { + error("MOLINFO is required to use EMST"); + } // initialize tree Tree tree = Tree(moldat); // cycle on groups and reorder atoms @@ -189,7 +203,9 @@ WholeMolecules::WholeMolecules(const ActionOptions&ao): // fill root vector with previous atom in groups for(unsigned i=0; i root; - for(unsigned j=0; j(this); - if( !moldat ) error("MOLINFO is required to use ADDREFERENCE"); + if( !moldat ) { + error("MOLINFO is required to use ADDREFERENCE"); + } for(unsigned i=0; igetPosition(groups[i][0])); @@ -208,9 +226,13 @@ WholeMolecules::WholeMolecules(const ActionOptions&ao): // print out info for(unsigned i=0; i refatoms; std::vector > p_atoms; @@ -156,7 +155,9 @@ class WrapAround: public: explicit WrapAround(const ActionOptions&ao); static void registerKeywords( Keywords& keys ); - bool actionHasForces() override { return false; } + bool actionHasForces() override { + return false; + } void calculate() override; void apply() override {} }; @@ -179,39 +180,60 @@ WrapAround::WrapAround(const ActionOptions&ao): ActionPilot(ao), ActionAtomistic(ao), groupby(1), - pair_(false) -{ - std::vector atoms; parseAtomList("ATOMS",atoms); - std::vector reference; parseAtomList("AROUND",reference); + pair_(false) { + std::vector atoms; + parseAtomList("ATOMS",atoms); + std::vector reference; + parseAtomList("AROUND",reference); parse("GROUPBY",groupby); parseFlag("PAIR", pair_); log.printf(" atoms in reference :"); - for(unsigned j=0; j1) log<<" atoms will be grouped by "<1) { + log<<" atoms will be grouped by "< merged(atoms.size()+reference.size()); merge(atoms.begin(),atoms.end(),reference.begin(),reference.end(),merged.begin()); - p_atoms.resize( atoms.size() ); for(unsigned i=0; i( action ); if( !ag && action->getName()=="ACCUMULATE" ) { ActionWithArguments* aa=dynamic_cast( action ); - plumed_assert( aa ); ag = dynamic_cast( (aa->getPntrToArgument(0))->getPntrToAction() ); + plumed_assert( aa ); + ag = dynamic_cast( (aa->getPntrToArgument(0))->getPntrToAction() ); } - plumed_assert( ag ); return ag; + plumed_assert( ag ); + return ag; } void ActionWithGrid::registerKeywords( Keywords& keys ) { @@ -40,13 +42,15 @@ void ActionWithGrid::registerKeywords( Keywords& keys ) { ActionWithGrid::ActionWithGrid(const ActionOptions&ao): Action(ao), ActionWithVector(ao), - firststep(true) -{ + firststep(true) { } void ActionWithGrid::calculate() { plumed_assert( !actionInChain() ); - if( firststep ) { setupOnFirstStep( true ); firststep=false; } + if( firststep ) { + setupOnFirstStep( true ); + firststep=false; + } runAllTasks(); } diff --git a/src/gridtools/ConvertToFES.cpp b/src/gridtools/ConvertToFES.cpp index f2b18bdabd..fadfabf944 100644 --- a/src/gridtools/ConvertToFES.cpp +++ b/src/gridtools/ConvertToFES.cpp @@ -73,21 +73,35 @@ void ConvertToFES::registerKeywords( Keywords& keys ) { keys.add("optional","TEMP","the temperature at which you are operating"); keys.addFlag("MINTOZERO",false,"set the minimum in the free energy to be equal to zero"); keys.setValueDescription("the free energy surface"); - keys.needsAction("FIND_GRID_MINIMUM"); keys.needsAction("CUSTOM"); + keys.needsAction("FIND_GRID_MINIMUM"); + keys.needsAction("CUSTOM"); } ConvertToFES::ConvertToFES(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - bool minzero=false; parseFlag("MINTOZERO",minzero); - double simtemp=getkBT(); if( simtemp==0 ) error("TEMP not set - use keyword TEMP"); + ActionShortcut(ao) { + bool minzero=false; + parseFlag("MINTOZERO",minzero); + double simtemp=getkBT(); + if( simtemp==0 ) { + error("TEMP not set - use keyword TEMP"); + } - std::vector argv; parseVector("GRID",argv); - if( argv.size()==0 ) parseVector("ARG",argv); - if( argv.size()!=1 ) error("should only have one argument"); + std::vector argv; + parseVector("GRID",argv); + if( argv.size()==0 ) { + parseVector("ARG",argv); + } + if( argv.size()!=1 ) { + error("should only have one argument"); + } - std::string str_temp; Tools::convert( simtemp, str_temp ); std::string flab=""; if( minzero ) flab="_unz"; + std::string str_temp; + Tools::convert( simtemp, str_temp ); + std::string flab=""; + if( minzero ) { + flab="_unz"; + } readInputLine( getShortcutLabel() + flab + ": CUSTOM ARG=" + argv[0] + " FUNC=-" + str_temp + "*log(x) PERIODIC=NO"); if( minzero ) { readInputLine( getShortcutLabel() + "_min: FIND_GRID_MINIMUM ARG=" + getShortcutLabel() + "_unz" ); diff --git a/src/gridtools/DumpGrid.cpp b/src/gridtools/DumpGrid.cpp index d6eedd3277..6eabb02f72 100644 --- a/src/gridtools/DumpGrid.cpp +++ b/src/gridtools/DumpGrid.cpp @@ -198,7 +198,8 @@ PLUMED_REGISTER_ACTION(DumpGrid,"DUMPGRID") void DumpGrid::registerKeywords( Keywords& keys ) { Action::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.use("ARG"); + ActionWithArguments::registerKeywords( keys ); + keys.use("ARG"); keys.add("optional","GRID","the grid you would like to print (can also use ARG for specifying what is being printed)"); keys.add("compulsory","STRIDE","0","the frequency with which the grid should be output to the file. Default of zero means dump at end of calculation"); keys.add("compulsory","FILE","density","the file on which to write the grid."); @@ -211,34 +212,59 @@ DumpGrid::DumpGrid(const ActionOptions&ao): Action(ao), ActionWithArguments(ao), ActionPilot(ao), - fmt("%f") -{ + fmt("%f") { if( getNumberOfArguments()==0 ) { - std::vector grids; parseArgumentList("GRID",grids); requestArguments(grids); + std::vector grids; + parseArgumentList("GRID",grids); + requestArguments(grids); + } + if( getNumberOfArguments()!=1 ) { + error("should only be one argument"); + } + if( getPntrToArgument(0)->getRank()==0 || !getPntrToArgument(0)->hasDerivatives() ) { + error("input should be a grid"); + } + if( getName()=="DUMPCUBE" && getPntrToArgument(0)->getRank()!=3 ) { + error("input should be a three dimensional grid"); } - if( getNumberOfArguments()!=1 ) error("should only be one argument"); - if( getPntrToArgument(0)->getRank()==0 || !getPntrToArgument(0)->hasDerivatives() ) error("input should be a grid"); - if( getName()=="DUMPCUBE" && getPntrToArgument(0)->getRank()!=3 ) error("input should be a three dimensional grid"); parse("FILE",filename); - if(filename.length()==0) error("name out output file was not specified"); + if(filename.length()==0) { + error("name out output file was not specified"); + } ActionWithGrid* ag = ActionWithGrid::getInputActionWithGrid( getPntrToArgument(0)->getPntrToAction() ); - if( !ag ) error( getPntrToArgument(0)->getName() + " is not grid"); + if( !ag ) { + error( getPntrToArgument(0)->getName() + " is not grid"); + } log.printf(" outputting grid with label %s to file named %s",getPntrToArgument(0)->getName().c_str(), filename.c_str() ); - parse("FMT",fmt); log.printf(" with format %s \n", fmt.c_str() ); - if( getName()=="DUMPGRID" ) fmt = " " + fmt; else if( getName()=="DUMPCUBE" ) fmt = fmt + " "; - parseFlag("PRINT_ONE_FILE", onefile); parseFlag("PRINT_XYZ",xyzfile); + parse("FMT",fmt); + log.printf(" with format %s \n", fmt.c_str() ); + if( getName()=="DUMPGRID" ) { + fmt = " " + fmt; + } else if( getName()=="DUMPCUBE" ) { + fmt = fmt + " "; + } + parseFlag("PRINT_ONE_FILE", onefile); + parseFlag("PRINT_XYZ",xyzfile); if( xyzfile ) { - if( getName()=="DUMPCUBE" ) error("PRINT_XYZ flag not compatible with DUMPCUBE"); - if( ag->getGridCoordinatesObject().getGridType()=="flat" ) error("can only use PRINT_XYZ option for fibonacci grids"); + if( getName()=="DUMPCUBE" ) { + error("PRINT_XYZ flag not compatible with DUMPCUBE"); + } + if( ag->getGridCoordinatesObject().getGridType()=="flat" ) { + error("can only use PRINT_XYZ option for fibonacci grids"); + } log.printf(" outputting grid to xyzfile\n"); } - if( onefile ) log.printf(" printing all grids on a single file \n"); - else log.printf(" printing all grids on separate files \n"); + if( onefile ) { + log.printf(" printing all grids on a single file \n"); + } else { + log.printf(" printing all grids on separate files \n"); + } } void DumpGrid::update() { - OFile ofile; ofile.link(*this); + OFile ofile; + ofile.link(*this); if( onefile ) { ofile.enforceRestart(); ofile.open( filename ); @@ -248,44 +274,66 @@ void DumpGrid::update() { } ActionWithGrid* ag = ActionWithGrid::getInputActionWithGrid( getPntrToArgument(0)->getPntrToAction() ); - plumed_assert( ag ); const GridCoordinatesObject & mygrid = ag->getGridCoordinatesObject(); + plumed_assert( ag ); + const GridCoordinatesObject & mygrid = ag->getGridCoordinatesObject(); if( getName()=="DUMPCUBE" ) { - double lunit=1.0; std::vector argnames( ag->getGridCoordinateNames() ); + double lunit=1.0; + std::vector argnames( ag->getGridCoordinateNames() ); ofile.printf("PLUMED CUBE FILE\n"); ofile.printf("OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z\n"); // Number of atoms followed by position of origin (origin set so that center of grid is in center of cell) - bool isdists=true; std::vector extent(3); std::vector min( mygrid.getMin() ), max( mygrid.getMax() ); + bool isdists=true; + std::vector extent(3); + std::vector min( mygrid.getMin() ), max( mygrid.getMax() ); for(unsigned j=0; j<3; ++j) { if( argnames[j].find(".")!=std::string::npos ) { std::size_t dot = argnames[j].find("."); std::string name = argnames[j].substr(dot+1); - if( name!="x" && name!="y" && name!="z" ) isdists=false; - } else isdists=false; + if( name!="x" && name!="y" && name!="z" ) { + isdists=false; + } + } else { + isdists=false; + } - double mind, maxd; Tools::convert( min[j], mind ); Tools::convert( max[j], maxd ); - if( mygrid.isPeriodic(j) ) extent[j]=maxd-mind; - else { extent[j]=maxd-mind+mygrid.getGridSpacing()[j]; } + double mind, maxd; + Tools::convert( min[j], mind ); + Tools::convert( max[j], maxd ); + if( mygrid.isPeriodic(j) ) { + extent[j]=maxd-mind; + } else { + extent[j]=maxd-mind+mygrid.getGridSpacing()[j]; + } } if( isdists ) { - if( plumed.usingNaturalUnits() ) lunit = 1.0/0.5292; - else lunit = plumed.getUnits().getLength()/.05929; + if( plumed.usingNaturalUnits() ) { + lunit = 1.0/0.5292; + } else { + lunit = plumed.getUnits().getLength()/.05929; + } } - std::string ostr = "%d " + fmt + fmt + fmt + "\n"; Value* gval=getPntrToArgument(0); + std::string ostr = "%d " + fmt + fmt + fmt + "\n"; + Value* gval=getPntrToArgument(0); ofile.printf(ostr.c_str(),1,-0.5*lunit*extent[0],-0.5*lunit*extent[1],-0.5*lunit*extent[2]); ofile.printf(ostr.c_str(),mygrid.getNbin(true)[0],lunit*mygrid.getGridSpacing()[0],0.0,0.0); // Number of bins in each direction followed by ofile.printf(ostr.c_str(),mygrid.getNbin(true)[1],0.0,lunit*mygrid.getGridSpacing()[1],0.0); // shape of voxel ofile.printf(ostr.c_str(),mygrid.getNbin(true)[2],0.0,0.0,lunit*mygrid.getGridSpacing()[2]); ofile.printf(ostr.c_str(),1,0.0,0.0,0.0); // Fake atom otherwise VMD doesn't work - std::vector pp(3); std::vector nbin( mygrid.getNbin(true) ); + std::vector pp(3); + std::vector nbin( mygrid.getNbin(true) ); for(pp[0]=0; pp[0]0; --i) ival=ival*nbin[i-1]+pp[i-1]; + for(unsigned i=pp.size()-1; i>0; --i) { + ival=ival*nbin[i-1]+pp[i-1]; + } ofile.printf(fmt.c_str(), gval->get(ival) ); - if(pp[2]%6==5) ofile.printf("\n"); + if(pp[2]%6==5) { + ofile.printf("\n"); + } } ofile.printf("\n"); } @@ -293,11 +341,15 @@ void DumpGrid::update() { } else if( xyzfile ) { std::vector coords(3); Value* myarg = getPntrToArgument(0); - unsigned nvals = myarg->getNumberOfValues(); ofile.printf("%d\n\n", nvals); + unsigned nvals = myarg->getNumberOfValues(); + ofile.printf("%d\n\n", nvals); for(unsigned i=0; iget(i); mygrid.getGridPointCoordinates( i, coords ); + double val = myarg->get(i); + mygrid.getGridPointCoordinates( i, coords ); ofile.printf("X"); - for(unsigned j=0; j<3; ++j) ofile.printf((" " + fmt).c_str(), val*coords[j] ); + for(unsigned j=0; j<3; ++j) { + ofile.printf((" " + fmt).c_str(), val*coords[j] ); + } ofile.printf("\n"); } } else { @@ -320,7 +372,9 @@ void DumpGrid::update() { for(unsigned i=0; igetNumberOfValues(); ++i) { // Retrieve and print the grid coordinates mygrid.getGridPointCoordinates( i, ind, xx ); - if(i>0 && gval->getRank()==2 && ind[gval->getRank()-2]==0) ofile.printf("\n"); + if(i>0 && gval->getRank()==2 && ind[gval->getRank()-2]==0) { + ofile.printf("\n"); + } ofile.fmtField(fmt); if( mygrid.getGridType()=="fibonacci" ) { ofile.printField("nbins", static_cast(gval->getNumberOfValues()) ); @@ -329,16 +383,26 @@ void DumpGrid::update() { ofile.printField("min_" + argn[j], mygrid.getMin()[j] ); ofile.printField("max_" + argn[j], mygrid.getMax()[j] ); ofile.printField("nbins_" + argn[j], static_cast(mygrid.getNbin(false)[j]) ); - if( mygrid.isPeriodic(j) ) ofile.printField("periodic_" + argn[j], "true" ); - else ofile.printField("periodic_" + argn[j], "false" ); + if( mygrid.isPeriodic(j) ) { + ofile.printField("periodic_" + argn[j], "true" ); + } else { + ofile.printField("periodic_" + argn[j], "false" ); + } } } // Print the grid coordinates - for(unsigned j=0; jgetRank(); ++j) { ofile.fmtField(fmt); ofile.printField(argn[j],xx[j]); } + for(unsigned j=0; jgetRank(); ++j) { + ofile.fmtField(fmt); + ofile.printField(argn[j],xx[j]); + } // Print value - ofile.fmtField(fmt); ofile.printField( gval->getName(), gval->get(i) ); + ofile.fmtField(fmt); + ofile.printField( gval->getName(), gval->get(i) ); // Print the derivatives - for(unsigned j=0; jgetRank(); ++j) { ofile.fmtField(fmt); ofile.printField( "d" + gval->getName() + "_" + argn[j], gval->getGridDerivative(i,j) ); } + for(unsigned j=0; jgetRank(); ++j) { + ofile.fmtField(fmt); + ofile.printField( "d" + gval->getName() + "_" + argn[j], gval->getGridDerivative(i,j) ); + } ofile.printField(); } } diff --git a/src/gridtools/EvaluateFunctionOnGrid.cpp b/src/gridtools/EvaluateFunctionOnGrid.cpp index 9add313e8f..8576f92e82 100644 --- a/src/gridtools/EvaluateFunctionOnGrid.cpp +++ b/src/gridtools/EvaluateFunctionOnGrid.cpp @@ -74,33 +74,52 @@ void EvaluateFunctionOnGrid::registerKeywords(Keywords& keys ) { keys.add("compulsory","GRID","the name of the grid that we are using to evaluate the function"); keys.add("optional","ARG","the arguments that you would like to use when evaluating the function. If not specified these are determined from the names of the grid dimensions"); keys.reserve("compulsory","PERIODIC","if the output of your function is periodic then you should specify the periodicity of the function. If the output is not periodic you must state this using PERIODIC=NO"); - EvaluateGridFunction ii; ii.registerKeywords( keys ); - keys.addActionNameSuffix("_SCALAR"); keys.addActionNameSuffix("_VECTOR"); + EvaluateGridFunction ii; + ii.registerKeywords( keys ); + keys.addActionNameSuffix("_SCALAR"); + keys.addActionNameSuffix("_VECTOR"); } EvaluateFunctionOnGrid::EvaluateFunctionOnGrid(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Get the grid that we are evaluating here - std::vector gridn(1); parse("GRID",gridn[0]); - std::vector gridv; ActionWithArguments::interpretArgumentList( gridn, plumed.getActionSet(), this, gridv ); + std::vector gridn(1); + parse("GRID",gridn[0]); + std::vector gridv; + ActionWithArguments::interpretArgumentList( gridn, plumed.getActionSet(), this, gridv ); // Read the input arguments from the input file - std::vector argn; parseVector("ARG",argn); + std::vector argn; + parseVector("ARG",argn); // Now get the arguments ActionWithGrid* ag = dynamic_cast( gridv[0]->getPntrToAction() ); - if( !ag ) error("argument to GRID argument is not a grid"); + if( !ag ) { + error("argument to GRID argument is not a grid"); + } if( argn.size()==0 ) { std::vector argn2( ag->getGridCoordinateNames() ); - argn.resize( argn2.size() ); for(unsigned i=0; igetRank() ) { + error("found wrong number of arguments in Evaluate function on grid"); } - if( argn.size()!=gridv[0]->getRank() ) error("found wrong number of arguments in Evaluate function on grid"); // Now use this information to create a gridobject - if( ag->getGridCoordinatesObject().getGridType()=="fibonacci" ) error("cannot interpolate on fibonacci sphere"); + if( ag->getGridCoordinatesObject().getGridType()=="fibonacci" ) { + error("cannot interpolate on fibonacci sphere"); + } // Now get the actual values we are using - std::vector vals; ActionWithArguments::interpretArgumentList( argn, plumed.getActionSet(), this, vals ); - if( vals.size()==0 ) error("found no input arguments to function"); - std::string allargs = gridn[0]; for(unsigned i=0; i vals; + ActionWithArguments::interpretArgumentList( argn, plumed.getActionSet(), this, vals ); + if( vals.size()==0 ) { + error("found no input arguments to function"); + } + std::string allargs = gridn[0]; + for(unsigned i=0; i::createAction( this, vals, allargs ); } diff --git a/src/gridtools/EvaluateGridFunction.cpp b/src/gridtools/EvaluateGridFunction.cpp index 47d0490bb4..b00ffa66a6 100644 --- a/src/gridtools/EvaluateGridFunction.cpp +++ b/src/gridtools/EvaluateGridFunction.cpp @@ -35,24 +35,35 @@ void EvaluateGridFunction::registerKeywords( Keywords& keys ) { std::vector EvaluateGridFunction::getPbc() const { std::vector ipbc( gridobject.getDimension() ); - for(unsigned i=0; igetPntrToArgument(0)->getRank()==0 || !action->getPntrToArgument(0)->hasDerivatives() ) action->error("should have one grid as input to this action"); + if( action->getPntrToArgument(0)->getRank()==0 || !action->getPntrToArgument(0)->hasDerivatives() ) { + action->error("should have one grid as input to this action"); + } // Get the input grid ActionWithGrid* ag = ActionWithGrid::getInputActionWithGrid( (action->getPntrToArgument(0))->getPntrToAction() ); - if( ag->getGridCoordinatesObject().getGridType()!="flat" ) action->error("cannot interpolate on fibonacci sphere"); + if( ag->getGridCoordinatesObject().getGridType()!="flat" ) { + action->error("cannot interpolate on fibonacci sphere"); + } std::vector ipbc( ag->getGridCoordinatesObject().getDimension() ); - for(unsigned i=0; igetGridCoordinatesObject().isPeriodic(i); + for(unsigned i=0; igetGridCoordinatesObject().isPeriodic(i); + } gridobject.setup( "flat", ipbc, 0, 0.0 ); // Now use this information to create a gridobject std::vector argn; parseFlag(action,"ZERO_OUTSIDE_GRID_RANGE",set_zero_outside_range); - if( set_zero_outside_range ) action->log.printf(" function is zero outside grid range \n"); + if( set_zero_outside_range ) { + action->log.printf(" function is zero outside grid range \n"); + } // Get the type of interpolation that we are doing - std::string itype; parse(action,"INTERPOLATION_TYPE",itype); + std::string itype; + parse(action,"INTERPOLATION_TYPE",itype); if( itype=="spline" ) { interpolation_type=spline; spline_interpolator=Tools::make_unique( action->getPntrToArgument(0), gridobject ); @@ -62,7 +73,9 @@ void EvaluateGridFunction::read( ActionWithArguments* action ) { interpolation_type=floor; } else if( itype=="ceiling" ) { interpolation_type=ceiling; - } else action->error("type " + itype + " of interpolation is not defined"); + } else { + action->error("type " + itype + " of interpolation is not defined"); + } action->log.printf(" generating off grid points using %s interpolation \n", itype.c_str() ); } @@ -70,49 +83,80 @@ void EvaluateGridFunction::setup( ActionWithValue* action ) { FunctionTemplateBase::setup( action ); ActionWithArguments* aarg = dynamic_cast( action ); ActionWithGrid* ag = ActionWithGrid::getInputActionWithGrid( (aarg->getPntrToArgument(0))->getPntrToAction() ); - const GridCoordinatesObject & ingrid = ag->getGridCoordinatesObject(); std::vector sp( ingrid.getGridSpacing() ); + const GridCoordinatesObject & ingrid = ag->getGridCoordinatesObject(); + std::vector sp( ingrid.getGridSpacing() ); gridobject.setBounds( ingrid.getMin(), ingrid.getMax(), ingrid.getNbin(false), sp ); } void EvaluateGridFunction::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { - if( set_zero_outside_range && !gridobject.inbounds( args ) ) { vals[0]=0.0; return; } - unsigned dimension = gridobject.getDimension(); plumed_dbg_assert( args.size()==dimension && vals.size()==1 ); + if( set_zero_outside_range && !gridobject.inbounds( args ) ) { + vals[0]=0.0; + return; + } + unsigned dimension = gridobject.getDimension(); + plumed_dbg_assert( args.size()==dimension && vals.size()==1 ); if( interpolation_type==spline ) { std::vector der( dimension ); vals[0] = spline_interpolator->splineInterpolation( args, der ); - for(unsigned j=0; jgetPntrToArgument(0); std::vector xfloor(dimension); + Value* values=action->getPntrToArgument(0); + std::vector xfloor(dimension); std::vector indices(dimension), nindices(dimension), ind(dimension); - gridobject.getIndices( args, indices ); unsigned nn=gridobject.getIndex(args); + gridobject.getIndices( args, indices ); + unsigned nn=gridobject.getIndex(args); gridobject.getGridPointCoordinates( nn, nindices, xfloor ); - double y1 = values->get(nn); vals[0] = y1; + double y1 = values->get(nn); + vals[0] = y1; for(unsigned i=0; iget( gridobject.getIndex(ind) ) - y1 )*X; derivatives(0,i) = ( values->get( gridobject.getIndex(ind) ) - y1 ) / ddx; } } else if( interpolation_type==floor ) { - Value* values=action->getPntrToArgument(0); std::vector indices(dimension); - gridobject.getIndices( args, indices ); unsigned nn = gridobject.getIndex(indices); + Value* values=action->getPntrToArgument(0); + std::vector indices(dimension); + gridobject.getIndices( args, indices ); + unsigned nn = gridobject.getIndex(indices); plumed_dbg_assert( nngetNumberOfValues() ); vals[0] = values->get( nn ); - for(unsigned j=0; jgetGridDerivative( nn, j ); + for(unsigned j=0; jgetGridDerivative( nn, j ); + } } else if( interpolation_type==ceiling ) { - Value* values=action->getPntrToArgument(0); std::vector indices(dimension); + Value* values=action->getPntrToArgument(0); + std::vector indices(dimension); gridobject.getIndices( args, indices ); for(unsigned i=0; iget( nn ); - for(unsigned j=0; jgetGridDerivative( nn, j ); - } else plumed_error(); + unsigned nn = gridobject.getIndex(indices); + vals[0] = values->get( nn ); + for(unsigned j=0; jgetGridDerivative( nn, j ); + } + } else { + plumed_error(); + } } void EvaluateGridFunction::applyForce( const ActionWithArguments* action, const std::vector& args, const double& force, std::vector& forcesToApply ) const { @@ -120,32 +164,52 @@ void EvaluateGridFunction::applyForce( const ActionWithArguments* action, const if( interpolation_type==spline ) { action->error("can't apply forces on values interpolated using splines"); } else if( interpolation_type==linear ) { - Value* values=action->getPntrToArgument(0); std::vector xfloor(dimension); + Value* values=action->getPntrToArgument(0); + std::vector xfloor(dimension); std::vector indices(dimension), nindices(dimension), ind(dimension); - gridobject.getIndices( args, indices ); unsigned nn=gridobject.getIndex(args); + gridobject.getIndices( args, indices ); + unsigned nn=gridobject.getIndex(args); gridobject.getGridPointCoordinates( nn, nindices, xfloor ); for(unsigned i=0; igetPntrToArgument(0); std::vector indices(dimension); - gridobject.getIndices( args, indices ); unsigned nn = gridobject.getIndex(indices); + Value* values=action->getPntrToArgument(0); + std::vector indices(dimension); + gridobject.getIndices( args, indices ); + unsigned nn = gridobject.getIndex(indices); forcesToApply[nn] += force; } else if( interpolation_type==ceiling ) { - Value* values=action->getPntrToArgument(0); std::vector indices(dimension); + Value* values=action->getPntrToArgument(0); + std::vector indices(dimension); gridobject.getIndices( args, indices ); for(unsigned i=0; i& args, std::vector& vals, Matrix& derivatives ) const override ; /// Get the vector containing the minimum value of the grid in each dimension diff --git a/src/gridtools/FindGridOptimum.cpp b/src/gridtools/FindGridOptimum.cpp index 516822e4d3..db00f6fbbd 100644 --- a/src/gridtools/FindGridOptimum.cpp +++ b/src/gridtools/FindGridOptimum.cpp @@ -54,20 +54,25 @@ class FindGridOptimum : public ActionWithGrid { public: static void registerKeywords( Keywords& keys ); explicit FindGridOptimum(const ActionOptions&ao); - void setupOnFirstStep( const bool incalc ) override { plumed_error(); } + void setupOnFirstStep( const bool incalc ) override { + plumed_error(); + } unsigned getNumberOfDerivatives() override ; void calculate() override ; std::vector getGridCoordinateNames() const override ; const GridCoordinatesObject& getGridCoordinatesObject() const override ; double calculateValueAndDerivatives( const std::vector& pp, std::vector& der ); - void performTask( const unsigned& current, MultiValue& myvals ) const override { plumed_error(); } + void performTask( const unsigned& current, MultiValue& myvals ) const override { + plumed_error(); + } }; PLUMED_REGISTER_ACTION(FindGridOptimum,"FIND_GRID_MAXIMUM") PLUMED_REGISTER_ACTION(FindGridOptimum,"FIND_GRID_MINIMUM") void FindGridOptimum::registerKeywords( Keywords& keys ) { - ActionWithGrid::registerKeywords( keys ); keys.use("ARG"); + ActionWithGrid::registerKeywords( keys ); + keys.use("ARG"); keys.addFlag("NOINTERPOL",false,"do not interpolate the function when finding the optimum"); keys.add("compulsory","CGTOL","1E-4","the tolerance for the conjugate gradient optimization"); keys.addOutputComponent("optval","default","the value of the function at the optimum"); @@ -78,17 +83,28 @@ void FindGridOptimum::registerKeywords( Keywords& keys ) { FindGridOptimum::FindGridOptimum(const ActionOptions&ao): Action(ao), ActionWithGrid(ao), - cgtol(0) -{ - if( getName()=="FIND_GRID_MAXIMUM" ) domin=false; - else if( getName()=="FIND_GRID_MINIMUM" ) domin=true; - else plumed_error(); + cgtol(0) { + if( getName()=="FIND_GRID_MAXIMUM" ) { + domin=false; + } else if( getName()=="FIND_GRID_MINIMUM" ) { + domin=true; + } else { + plumed_error(); + } // Create value for this function std::vector argn( getGridCoordinateNames() ); - std::vector shape(0); for(unsigned i=0; i( getPntrToArgument(0), getGridCoordinatesObject() ); } + std::vector shape(0); + for(unsigned i=0; i( getPntrToArgument(0), getGridCoordinatesObject() ); + } } unsigned FindGridOptimum::getNumberOfDerivatives() { @@ -97,12 +113,14 @@ unsigned FindGridOptimum::getNumberOfDerivatives() { const GridCoordinatesObject& FindGridOptimum::getGridCoordinatesObject() const { ActionWithGrid* ag=ActionWithGrid::getInputActionWithGrid( getPntrToArgument(0)->getPntrToAction() ); - plumed_assert( ag ); return ag->getGridCoordinatesObject(); + plumed_assert( ag ); + return ag->getGridCoordinatesObject(); } std::vector FindGridOptimum::getGridCoordinateNames() const { ActionWithGrid* ag=ActionWithGrid::getInputActionWithGrid( getPntrToArgument(0)->getPntrToAction() ); - plumed_assert( ag ); return ag->getGridCoordinateNames(); + plumed_assert( ag ); + return ag->getGridCoordinateNames(); } double FindGridOptimum::calculateValueAndDerivatives( const std::vector& pp, std::vector& der ) { @@ -110,39 +128,70 @@ double FindGridOptimum::calculateValueAndDerivatives( const std::vector& // We normalise the derivatives here and set them so that the linesearch is done over the cell that we know // in the grid that we know the minimum is inside std::vector spacing( getGridCoordinatesObject().getGridSpacing() ); - double norm = 0; for(unsigned i=0; i optargs( gval->getRank() ); std::vector gridind( gval->getRank() ); - double optval=gval->get( 0 ); ingrid.getGridPointCoordinates( 0, gridind, optargs ); - unsigned nval = gval->getNumberOfValues(); bool constant=true; + const GridCoordinatesObject& ingrid = getGridCoordinatesObject(); + Value* gval = getPntrToArgument(0); + std::vector optargs( gval->getRank() ); + std::vector gridind( gval->getRank() ); + double optval=gval->get( 0 ); + ingrid.getGridPointCoordinates( 0, gridind, optargs ); + unsigned nval = gval->getNumberOfValues(); + bool constant=true; for(unsigned i=0; iget( i ); - if( domin && (tvaloptval || std::isnan(optval)) ) { constant=false; optval=tval; ingrid.getGridPointCoordinates( i, gridind, optargs ); } + if( domin && (tvaloptval || std::isnan(optval)) ) { + constant=false; + optval=tval; + ingrid.getGridPointCoordinates( i, gridind, optargs ); + } } // This basically ensures we deal with cases where all points on the grid are infinity as isinf doesn't work on intel compiler if( constant ) { - if( domin && gval->get(0)>=gval->get(1) ) return; - else if( gval->get(0)<=gval->get(1) ) return; + if( domin && gval->get(0)>=gval->get(1) ) { + return; + } else if( gval->get(0)<=gval->get(1) ) { + return; + } + } + if( std::isinf(optval) ) { + return; } - if( std::isinf(optval) ) { return; } - if( std::isnan(optval) ) error("all values on grid are nans"); + if( std::isnan(optval) ) { + error("all values on grid are nans"); + } // And do conjugate gradient optimisation (because we can!!) if( cgtol>0 ) { ConjugateGradient myminimiser( this ); myminimiser.minimise( cgtol, optargs, &FindGridOptimum::calculateValueAndDerivatives ); } // And set the final value - for(unsigned j=0; jset( optargs[j] ); + for(unsigned j=0; jset( optargs[j] ); + } std::vector optder( gval->getRank() ); getPntrToComponent(optargs.size())->set( function->splineInterpolation( optargs, optder ) ); } diff --git a/src/gridtools/FunctionOfGrid.h b/src/gridtools/FunctionOfGrid.h index aec8cae75d..89cfe8bb7c 100644 --- a/src/gridtools/FunctionOfGrid.h +++ b/src/gridtools/FunctionOfGrid.h @@ -42,7 +42,9 @@ class FunctionOfGrid : public ActionWithGrid { /// Get the number of derivatives for this action unsigned getNumberOfDerivatives() override ; /// Get the label to write in the graph - std::string writeInGraph() const override { return myfunc.getGraphInfo( getName() ); } + std::string writeInGraph() const override { + return myfunc.getGraphInfo( getName() ); + } /// Get the underlying names std::vector getGridCoordinateNames() const override ; /// Get the underlying grid coordinates object @@ -58,10 +60,17 @@ class FunctionOfGrid : public ActionWithGrid { template void FunctionOfGrid::registerKeywords(Keywords& keys ) { - ActionWithGrid::registerKeywords(keys); keys.use("ARG"); std::string name = keys.getDisplayName(); - std::size_t und=name.find("_GRID"); keys.setDisplayName( name.substr(0,und) ); + ActionWithGrid::registerKeywords(keys); + keys.use("ARG"); + std::string name = keys.getDisplayName(); + std::size_t und=name.find("_GRID"); + keys.setDisplayName( name.substr(0,und) ); keys.reserve("compulsory","PERIODIC","if the output of your function is periodic then you should specify the periodicity of the function. If the output is not periodic you must state this using PERIODIC=NO"); - T tfunc; tfunc.registerKeywords( keys ); if( typeid(tfunc)==typeid(function::Custom()) ) keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); + T tfunc; + tfunc.registerKeywords( keys ); + if( typeid(tfunc)==typeid(function::Custom()) ) { + keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); + } if( keys.getDisplayName()=="INTEGRATE") { keys.setValueDescription("the numerical integral of the input function over its whole domain"); } else if( keys.outputComponentExists(".#!value") ) { @@ -72,34 +81,49 @@ void FunctionOfGrid::registerKeywords(Keywords& keys ) { template FunctionOfGrid::FunctionOfGrid(const ActionOptions&ao): Action(ao), - ActionWithGrid(ao) -{ - if( getNumberOfArguments()==0 ) error("found no arguments"); + ActionWithGrid(ao) { + if( getNumberOfArguments()==0 ) { + error("found no arguments"); + } // This will require a fix - if( getPntrToArgument(0)->getRank()==0 || !getPntrToArgument(0)->hasDerivatives() ) error("first input to this action must be a grid"); + if( getPntrToArgument(0)->getRank()==0 || !getPntrToArgument(0)->hasDerivatives() ) { + error("first input to this action must be a grid"); + } // Get the shape of the input grid std::vector shape( getPntrToArgument(0)->getShape() ); for(unsigned i=1; igetRank()==0 ) continue; + if( getPntrToArgument(i)->getRank()==0 ) { + continue; + } std::vector s( getPntrToArgument(i)->getShape() ); - if( s.size()!=shape.size() ) error("mismatch between dimensionalities of input grids"); + if( s.size()!=shape.size() ) { + error("mismatch between dimensionalities of input grids"); + } } // Read the input and do some checks myfunc.read( this ); // Check we are not calculating an integral - if( myfunc.zeroRank() ) { shape.resize(0); } + if( myfunc.zeroRank() ) { + shape.resize(0); + } // Check that derivatives are available - if( !myfunc.derivativesImplemented() ) error("derivatives have not been implemended for " + getName() ); + if( !myfunc.derivativesImplemented() ) { + error("derivatives have not been implemended for " + getName() ); + } // Get the names of the components std::vector components( keywords.getOutputComponents() ); // Create the values to hold the output - if( components.size()!=1 || components[0]!=".#!value" ) error("functions of grid should only output one grid"); + if( components.size()!=1 || components[0]!=".#!value" ) { + error("functions of grid should only output one grid"); + } addValueWithDerivatives( shape ); // Set the periodicities of the output components myfunc.setPeriodicityForOutputs( this ); // Check if we can turn off the derivatives when they are zero if( myfunc.getDerivativeZeroIfValueIsZero() ) { - for(int i=0; isetDerivativeIsZeroWhenValueIsZero(); + for(int i=0; isetDerivativeIsZeroWhenValueIsZero(); + } } setupOnFirstStep( false ); } @@ -112,56 +136,82 @@ void FunctionOfGrid::setupOnFirstStep( const bool incalc ) { if( mygrid.getGridType()=="flat" ) { std::vector shape( getGridCoordinatesObject().getNbin(true) ); for(unsigned i=1; igetRank()==0 ) continue; + if( getPntrToArgument(i)->getRank()==0 ) { + continue; + } std::vector s( getPntrToArgument(i)->getShape() ); for(unsigned j=0; jgetRank()>0 ) getPntrToComponent(i)->setShape(shape); + if( getPntrToComponent(i)->getRank()>0 ) { + getPntrToComponent(i)->setShape(shape); + } } std::vector vv( getGridCoordinatesObject().getGridSpacing() ); - volume=vv[0]; for(unsigned i=1; i( npoints ); + volume=vv[0]; + for(unsigned i=1; i( npoints ); + } // This resizes the scalars for(int i=0; igetRank()==0 ) getPntrToComponent(i)->resizeDerivatives( npoints ); + if( getPntrToComponent(i)->getRank()==0 ) { + getPntrToComponent(i)->resizeDerivatives( npoints ); + } + } + if( getName()=="SUM_GRID" ) { + volume = 1.0; } - if( getName()=="SUM_GRID" ) volume = 1.0; // This sets the prefactor to the volume which converts integrals to sums - myfunc.setup( this ); myfunc.setPrefactor( this, volume ); + myfunc.setup( this ); + myfunc.setPrefactor( this, volume ); } template const GridCoordinatesObject& FunctionOfGrid::getGridCoordinatesObject() const { ActionWithGrid* ag=ActionWithGrid::getInputActionWithGrid( getPntrToArgument(0)->getPntrToAction() ); - plumed_assert( ag ); return ag->getGridCoordinatesObject(); + plumed_assert( ag ); + return ag->getGridCoordinatesObject(); } template std::vector FunctionOfGrid::getGridCoordinateNames() const { ActionWithGrid* ag=ActionWithGrid::getInputActionWithGrid( getPntrToArgument(0)->getPntrToAction() ); - plumed_assert( ag ); return ag->getGridCoordinateNames(); + plumed_assert( ag ); + return ag->getGridCoordinateNames(); } template unsigned FunctionOfGrid::getNumberOfDerivatives() { - if( myfunc.zeroRank() ) return getPntrToArgument(0)->getNumberOfValues(); + if( myfunc.zeroRank() ) { + return getPntrToArgument(0)->getNumberOfValues(); + } unsigned nder = getGridCoordinatesObject().getDimension(); return getGridCoordinatesObject().getDimension() + getNumberOfArguments() - myfunc.getArgStart(); } template void FunctionOfGrid::performTask( const unsigned& current, MultiValue& myvals ) const { - unsigned argstart=myfunc.getArgStart(); std::vector args( getNumberOfArguments() - argstart ); + unsigned argstart=myfunc.getArgStart(); + std::vector args( getNumberOfArguments() - argstart ); for(unsigned i=argstart; igetRank()==0 ) args[i-argstart]=getPntrToArgument(i)->get(); - else args[i-argstart] = getPntrToArgument(i)->get(current); + if( getPntrToArgument(i)->getRank()==0 ) { + args[i-argstart]=getPntrToArgument(i)->get(); + } else { + args[i-argstart] = getPntrToArgument(i)->get(current); + } } // Calculate the function and its derivatives - std::vector vals(1); Matrix derivatives( 1, getNumberOfArguments()-argstart ); - myfunc.calc( this, args, vals, derivatives ); unsigned np = myvals.getTaskIndex(); + std::vector vals(1); + Matrix derivatives( 1, getNumberOfArguments()-argstart ); + myfunc.calc( this, args, vals, derivatives ); + unsigned np = myvals.getTaskIndex(); // And set the values and derivatives unsigned ostrn = getConstPntrToComponent(0)->getPositionInStream(); myvals.addValue( ostrn, vals[0] ); @@ -172,14 +222,19 @@ void FunctionOfGrid::performTask( const unsigned& current, MultiValue& myvals myvals.addDerivative( ostrn, getConstPntrToComponent(0)->getRank()+j-argstart, derivatives(0,j-argstart) ); // And now we calculate the derivatives of the value that is stored on the grid correctly so that we can interpolate functions if( getPntrToArgument(j)->getRank()!=0 ) { - for(unsigned k=0; kgetRank(); ++k) myvals.addDerivative( ostrn, k, derivatives(0,j-argstart)*getPntrToArgument(j)->getGridDerivative( np, k ) ); + for(unsigned k=0; kgetRank(); ++k) { + myvals.addDerivative( ostrn, k, derivatives(0,j-argstart)*getPntrToArgument(j)->getGridDerivative( np, k ) ); + } } } unsigned nderivatives = getConstPntrToComponent(0)->getNumberOfGridDerivatives(); - for(unsigned j=0; j::gatherStoredValue( const unsigned& valindex, const unsig plumed_dbg_assert( getNumberOfComponents()==1 && valindex==0 ); unsigned nder = getConstPntrToComponent(0)->getNumberOfGridDerivatives(); unsigned ostr = getConstPntrToComponent(0)->getPositionInStream(); - unsigned kp = bufstart + code*(1+nder); buffer[kp] += myvals.get( ostr ); - for(unsigned i=0; i void FunctionOfGrid::apply() { - if( doNotCalculateDerivatives() || !getPntrToComponent(0)->forcesWereAdded() ) return; + if( doNotCalculateDerivatives() || !getPntrToComponent(0)->forcesWereAdded() ) { + return; + } // This applies forces for the integral - if( myfunc.zeroRank() ) { ActionWithVector::apply(); return; } + if( myfunc.zeroRank() ) { + ActionWithVector::apply(); + return; + } // Work out how to deal with arguments unsigned nscalars=0, argstart=myfunc.getArgStart(); for(unsigned i=argstart; igetRank()==0 ) { nscalars++; } + if( getPntrToArgument(i)->getRank()==0 ) { + nscalars++; + } } - std::vector totv(nscalars,0); Value* outval=getPntrToComponent(0); + std::vector totv(nscalars,0); + Value* outval=getPntrToComponent(0); for(unsigned i=0; igetNumberOfValues(); ++i) { nscalars=0; for(unsigned j=argstart; jgetForce(i); if( getPntrToArgument(j)->getRank()==0 ) { - totv[nscalars] += fforce*outval->getGridDerivative( i, outval->getRank()+j ); nscalars++; + totv[nscalars] += fforce*outval->getGridDerivative( i, outval->getRank()+j ); + nscalars++; } else { double vval = outval->getGridDerivative( i, outval->getRank()+j ); getPntrToArgument(j)->addForce( i, fforce*vval ); @@ -223,7 +292,10 @@ void FunctionOfGrid::apply() { } nscalars=0; for(unsigned i=argstart; igetRank()==0 ) { getPntrToArgument(i)->addForce( 0, totv[nscalars] ); nscalars++; } + if( getPntrToArgument(i)->getRank()==0 ) { + getPntrToArgument(i)->addForce( 0, totv[nscalars] ); + nscalars++; + } } } diff --git a/src/gridtools/Gradient.cpp b/src/gridtools/Gradient.cpp index 051a3bb1b8..edeaaebb18 100644 --- a/src/gridtools/Gradient.cpp +++ b/src/gridtools/Gradient.cpp @@ -51,40 +51,58 @@ void Gradient::registerKeywords( Keywords& keys ) { keys.add("compulsory","KERNEL","gaussian-bin","the type of kernel function to be used in the grids"); keys.add("compulsory","ATOMS","calculate the gradient of these atoms"); keys.setValueDescription("the desired gradient"); - keys.needsAction("DISTANCES"); keys.needsAction("KDE"); keys.needsAction("INTERPOLATE_GRID"); - keys.needsAction("CUSTOM"); keys.needsAction("SUM_GRID"); keys.needsAction("COMBINE"); + keys.needsAction("DISTANCES"); + keys.needsAction("KDE"); + keys.needsAction("INTERPOLATE_GRID"); + keys.needsAction("CUSTOM"); + keys.needsAction("SUM_GRID"); + keys.needsAction("COMBINE"); } Gradient::Gradient(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - std::string atom_str; parse("ATOMS",atom_str); - std::string dir; parse("DIR",dir); - std::string origin_str; parse("ORIGIN",origin_str); - std::string nbin_str; parse("NBINS",nbin_str); - std::string band_str; parse("SIGMA",band_str); - std::string kernel_str; parse("KERNEL",kernel_str); + ActionShortcut(ao) { + std::string atom_str; + parse("ATOMS",atom_str); + std::string dir; + parse("DIR",dir); + std::string origin_str; + parse("ORIGIN",origin_str); + std::string nbin_str; + parse("NBINS",nbin_str); + std::string band_str; + parse("SIGMA",band_str); + std::string kernel_str; + parse("KERNEL",kernel_str); // First get positions of all atoms relative to origin readInputLine( getShortcutLabel() + "_dist: DISTANCES ORIGIN=" + origin_str + " ATOMS=" + atom_str + " COMPONENTS"); // Now constrcut the histograms if( dir=="x" || dir=="xy" || dir=="xz" || dir=="xyz" ) { readInputLine( getShortcutLabel() + "_xhisto: KDE ARG=" + getShortcutLabel() + "_dist.x GRID_BIN=" + nbin_str + " KERNEL=" + kernel_str + " BANDWIDTH=" + band_str ); - std::string thislab = getShortcutLabel() + "_xgrad"; if( dir=="x" ) thislab = getShortcutLabel(); + std::string thislab = getShortcutLabel() + "_xgrad"; + if( dir=="x" ) { + thislab = getShortcutLabel(); + } readInputLine( thislab + "_shift: INTERPOLATE_GRID ARG=" + getShortcutLabel() + "_xhisto INTERPOLATION_TYPE=ceiling MIDPOINTS"); readInputLine( thislab + "_x2: CUSTOM ARG=" + getShortcutLabel() + "_xhisto," + thislab + "_shift FUNC=(x-y)*(x-y) PERIODIC=NO"); readInputLine( thislab + ": SUM_GRID ARG=" + thislab + "_x2 PERIODIC=NO"); } if( dir=="y" || dir=="xy" || dir=="yz" || dir=="xyz" ) { readInputLine( getShortcutLabel() + "_yhisto: KDE ARG=" + getShortcutLabel() + "_dist.y GRID_BIN=" + nbin_str + " KERNEL=" + kernel_str + " BANDWIDTH=" + band_str ); - std::string thislab = getShortcutLabel() + "_ygrad"; if( dir=="y" ) thislab = getShortcutLabel(); + std::string thislab = getShortcutLabel() + "_ygrad"; + if( dir=="y" ) { + thislab = getShortcutLabel(); + } readInputLine( thislab + "_shift: INTERPOLATE_GRID ARG=" + getShortcutLabel() + "_yhisto INTERPOLATION_TYPE=ceiling MIDPOINTS"); readInputLine( thislab + "_x2: CUSTOM ARG=" + getShortcutLabel() + "_yhisto," + thislab + "_shift FUNC=(x-y)*(x-y) PERIODIC=NO"); readInputLine( thislab + ": SUM_GRID ARG=" + thislab + "_x2 PERIODIC=NO"); } if( dir=="z" || dir=="yz" || dir=="xz" || dir=="xyz" ) { readInputLine( getShortcutLabel() + "_zhisto: KDE ARG=" + getShortcutLabel() + "_dist.z GRID_BIN=" + nbin_str + " KERNEL=" + kernel_str + " BANDWIDTH=" + band_str ); - std::string thislab = getShortcutLabel() + "_zgrad"; if( dir=="z" ) thislab = getShortcutLabel(); + std::string thislab = getShortcutLabel() + "_zgrad"; + if( dir=="z" ) { + thislab = getShortcutLabel(); + } readInputLine( thislab + "_shift: INTERPOLATE_GRID ARG=" + getShortcutLabel() + "_zhisto INTERPOLATION_TYPE=ceiling MIDPOINTS"); readInputLine( thislab + "_x2: CUSTOM ARG=" + getShortcutLabel() + "_zhisto," + thislab + "_shift FUNC=(x-y)*(x-y) PERIODIC=NO"); readInputLine( thislab + ": SUM_GRID ARG=" + thislab + "_x2 PERIODIC=NO"); diff --git a/src/gridtools/GridCoordinatesObject.cpp b/src/gridtools/GridCoordinatesObject.cpp index ef4705e511..5656cb0431 100644 --- a/src/gridtools/GridCoordinatesObject.cpp +++ b/src/gridtools/GridCoordinatesObject.cpp @@ -28,93 +28,156 @@ namespace gridtools { void GridCoordinatesObject::setup( const std::string& geom, const std::vector& ipbc, const unsigned& np, const double& fib_cutoff ) { - if( geom=="flat" ) { gtype=flat; dimension = ipbc.size(); } - else if( geom=="fibonacci" ) { gtype=fibonacci; dimension = 3; } - else plumed_merror( geom + " is invalid geometry type"); + if( geom=="flat" ) { + gtype=flat; + dimension = ipbc.size(); + } else if( geom=="fibonacci" ) { + gtype=fibonacci; + dimension = 3; + } else { + plumed_merror( geom + " is invalid geometry type"); + } if( gtype==flat ) { - bounds_set=false; npoints=0; pbc.resize( ipbc.size() ); for(unsigned i=0; i( npoints ); fib_shift = fib_offset/2 - 1; std::vector icoord( dimension ), jcoord( dimension ); // Find minimum distance between each pair of points - std::vector tindices( dimension ); std::vector mindists( npoints ); + std::vector tindices( dimension ); + std::vector mindists( npoints ); for(unsigned i=0; imindists[i] ) mindists[i]=dot; + double dot=0; + for(unsigned k=0; kmindists[i] ) { + mindists[i]=dot; + } } } // And now take minimum of dot products double min=mindists[0]; for(unsigned i=1; ifinal_cutoff ) { fib_nlist[i].push_back(j); } + double dot=0; + for(unsigned k=0; kfinal_cutoff ) { + fib_nlist[i].push_back(j); + } } } - } else plumed_error(); + } else { + plumed_error(); + } } void GridCoordinatesObject::setBounds( const std::vector& smin, const std::vector& smax, const std::vector& binsin, std::vector& spacing ) { plumed_dbg_assert( smin.size()==dimension && smax.size()==dimension ); plumed_assert( gtype==flat && (spacing.size()==dimension || binsin.size()==dimension) ); - str_min.resize( dimension ); str_max.resize( dimension ); nbin.resize( dimension ); - min.resize( dimension ); max.resize( dimension ); dx.resize( dimension ); stride.resize( dimension ); - - npoints=1; bounds_set=(smin[0]!="auto" && smax[0]!="auto"); + str_min.resize( dimension ); + str_max.resize( dimension ); + nbin.resize( dimension ); + min.resize( dimension ); + max.resize( dimension ); + dx.resize( dimension ); + stride.resize( dimension ); + + npoints=1; + bounds_set=(smin[0]!="auto" && smax[0]!="auto"); if( bounds_set ) { for(unsigned i=1; i( nbin[i] ); + nbin[i]=binsin[i]; + dx[i] = ( max[i] - min[i] ) / static_cast( nbin[i] ); } else if( spacing.size()==dimension && bounds_set ) { - nbin[i] = std::floor(( max[i] - min[i] ) / spacing[i]) + 1; dx[i]=spacing[i]; - } else if( bounds_set ) plumed_error(); - if( !pbc[i] ) { max[i] +=dx[i]; nbin[i]+=1; } + nbin[i] = std::floor(( max[i] - min[i] ) / spacing[i]) + 1; + dx[i]=spacing[i]; + } else if( bounds_set ) { + plumed_error(); + } + if( !pbc[i] ) { + max[i] +=dx[i]; + nbin[i]+=1; + } stride[i]=npoints; npoints*=nbin[i]; } if( spacing.size()!=dimension && bounds_set ) { - spacing.resize(dimension); for(unsigned i=0; i& indices ) } bool GridCoordinatesObject::inbounds( const std::vector& point ) const { - if( gtype==fibonacci ) return true; + if( gtype==fibonacci ) { + return true; + } plumed_dbg_assert( bounds_set && point.size()==dimension ); for(unsigned i=0; i(max[i]-dx[i]) ) return false; + if( pbc[i] ) { + continue; + } + if( point[i](max[i]-dx[i]) ) { + return false; + } } return true; } @@ -142,15 +211,19 @@ void GridCoordinatesObject::getIndices( const std::vector& point, std::v plumed_dbg_assert( gtype==flat && bounds_set && point.size()==dimension && indices.size()==dimension ); for(unsigned i=0; inbin[i] ) plumed_merror("point is outside grid range"); + if( pbc[i] ) { + indices[i]=indices[i]%nbin[i]; + } else if( indices[i]>nbin[i] ) { + plumed_merror("point is outside grid range"); + } } } unsigned GridCoordinatesObject::getIndex( const std::vector& point ) const { plumed_dbg_assert( bounds_set && point.size()==dimension ); if( gtype==flat ) { - std::vector indices(dimension); getIndices( point, indices ); + std::vector indices(dimension); + getIndices( point, indices ); return getIndex( indices ); } else if( gtype==fibonacci ) { return getFibonacciIndex( point ); @@ -162,34 +235,63 @@ unsigned GridCoordinatesObject::getIndex( const std::vector& point ) con unsigned GridCoordinatesObject::getFibonacciIndex( const std::vector& p ) const { plumed_dbg_assert( gtype==fibonacci ); // Convert input point to coordinates on cylinder - int k=2; double phi = atan2( p[2], p[0] ), sinthet2 = 1 - p[1]*p[1]; + int k=2; + double phi = atan2( p[2], p[0] ), sinthet2 = 1 - p[1]*p[1]; // Calculate power to raise golden ratio - if( sinthet2 B(2,2), invB(2,2); std::vector thisp(3); + Matrix B(2,2), invB(2,2); + std::vector thisp(3); B(0,0) = 2*pi*((F0+1)*igolden - std::floor((F0+1)*igolden)) - fib_increment; B(0,1) = 2*pi*((F1+1)*igolden - std::floor((F1+1)*igolden)) - fib_increment; - B(1,0) = -2*F0/npoints; B(1,1) = -2*F1/npoints; Invert( B, invB ); - std::vector vv(2), rc(2); vv[0]=-phi; vv[1] = p[1] - fib_shift; - mult( invB, vv, rc ); std::vector c(2); c[0]=std::floor(rc[0]); c[1]=std::floor(rc[1]); - unsigned outind=0; double mindist = 10000000.; + B(1,0) = -2*F0/npoints; + B(1,1) = -2*F1/npoints; + Invert( B, invB ); + std::vector vv(2), rc(2); + vv[0]=-phi; + vv[1] = p[1] - fib_shift; + mult( invB, vv, rc ); + std::vector c(2); + c[0]=std::floor(rc[0]); + c[1]=std::floor(rc[1]); + unsigned outind=0; + double mindist = 10000000.; for(int s=0; s<4; ++s) { double ttt, costheta = B(1,0)*( c[0] + s%2 ) + B(1,1)*( c[1] + s/2 ) + fib_shift; - if( costheta>1 ) ttt=1; else if( costheta<-1 ) ttt=-1; else ttt=costheta; + if( costheta>1 ) { + ttt=1; + } else if( costheta<-1 ) { + ttt=-1; + } else { + ttt=costheta; + } costheta = 2*ttt - costheta; - unsigned i = std::floor( 0.5*npoints*(1+costheta) ); getFibonacciCoordinates( i, thisp ); - double dist=0; for(unsigned j=0; j<3; ++j) { double tmp=thisp[j]-p[j]; dist += tmp*tmp; } - if( dist& nnbin, std::vector& indices ) const { - plumed_dbg_assert( gtype==flat ); unsigned kk=index; indices[0]=index%nnbin[0]; + plumed_dbg_assert( gtype==flat ); + unsigned kk=index; + indices[0]=index%nnbin[0]; for(unsigned i=1; i& indices ) const { - plumed_dbg_assert( gtype==flat ); convertIndexToIndices( index, nbin, indices ); + plumed_dbg_assert( gtype==flat ); + convertIndexToIndices( index, nbin, indices ); } void GridCoordinatesObject::getGridPointCoordinates( const unsigned& ipoint, std::vector& x ) const { - std::vector tindices( dimension ); getGridPointCoordinates( ipoint, tindices, x ); + std::vector tindices( dimension ); + getGridPointCoordinates( ipoint, tindices, x ); } void GridCoordinatesObject::getGridPointCoordinates( const unsigned& ipoint, std::vector& tindices, std::vector& x ) const { @@ -219,64 +323,101 @@ void GridCoordinatesObject::getGridPointCoordinates( const unsigned& ipoint, std } void GridCoordinatesObject::putCoordinateAtValue( const unsigned& ind, const double& val, std::vector& coords ) const { - std::vector point( dimension ); getGridPointCoordinates( ind, point ); + std::vector point( dimension ); + getGridPointCoordinates( ind, point ); if( gtype==flat ) { - if( coords.size()!=(dimension+1) ) coords.resize( (dimension+1) ); - for(unsigned i=0; i& tindices, std::vector& x ) const { - plumed_dbg_assert( gtype==flat ); getIndices( ipoint, tindices ); - for(unsigned i=0; i& x ) const { plumed_dbg_assert( gtype==fibonacci ); - x[1] = (ipoint*fib_offset) + fib_shift; double r = sqrt( 1 - x[1]*x[1] ); - double phi = ipoint*fib_increment; x[0] = r*cos(phi); x[2] = r*sin(phi); - double norm=0; for(unsigned j=0; j<3; ++j) norm+=x[j]*x[j]; - norm = sqrt(norm); for(unsigned j=0; j<3; ++j) x[j] = x[j] / norm; + x[1] = (ipoint*fib_offset) + fib_shift; + double r = sqrt( 1 - x[1]*x[1] ); + double phi = ipoint*fib_increment; + x[0] = r*cos(phi); + x[2] = r*sin(phi); + double norm=0; + for(unsigned j=0; j<3; ++j) { + norm+=x[j]*x[j]; + } + norm = sqrt(norm); + for(unsigned j=0; j<3; ++j) { + x[j] = x[j] / norm; + } } void GridCoordinatesObject::getSplineNeighbors( const unsigned& mybox, unsigned& nneighbors, std::vector& mysneigh ) const { - plumed_dbg_assert( gtype==flat ); mysneigh.resize( static_cast(pow(2.,dimension)) ); + plumed_dbg_assert( gtype==flat ); + mysneigh.resize( static_cast(pow(2.,dimension)) ); - unsigned inind; nneighbors = 0; + unsigned inind; + nneighbors = 0; std::vector tmp_indices( dimension ); std::vector my_indices( dimension ); getIndices( mybox, my_indices ); for(unsigned i=0; i GridCoordinatesObject::getMin() const { - plumed_dbg_assert( gtype==flat ); return str_min; + plumed_dbg_assert( gtype==flat ); + return str_min; } std::vector GridCoordinatesObject::getMax() const { - plumed_dbg_assert( gtype==flat ); return str_max; + plumed_dbg_assert( gtype==flat ); + return str_max; } std::vector GridCoordinatesObject::getNbin( const bool& shape ) const { plumed_dbg_assert( gtype==flat && nbin.size()==dimension ); std::vector ngrid( dimension ); for(unsigned i=0; i& pp, const s if( gtype == flat ) { plumed_dbg_assert( nneigh.size()==dimension ); std::vector indices( dimension ); - for(unsigned i=0; i& indices, unsigned& num_neighbors, std::vector& neighbors ) const { plumed_dbg_assert( gtype==flat && bounds_set && nneigh.size()==dimension ); - unsigned num_neigh=1; std::vector small_bin( dimension ); + unsigned num_neigh=1; + std::vector small_bin( dimension ); for(unsigned i=0; inbin[i] ) small_bin[i]=nbin[i]; + if( pbc[i] && small_bin[i]>nbin[i] ) { + small_bin[i]=nbin[i]; + } num_neigh *=small_bin[i]; } - if( neighbors.size()!=num_neigh ) neighbors.resize( num_neigh ); + if( neighbors.size()!=num_neigh ) { + neighbors.resize( num_neigh ); + } num_neighbors=0; std::vector s_indices(dimension), t_indices(dimension); @@ -319,10 +472,18 @@ void GridCoordinatesObject::getNeighbors( const std::vector& indices, convertIndexToIndices( index, small_bin, s_indices ); for(unsigned i=0; i=nbin[i]) found=false; - if( pbc[i] && i0<0) i0=nbin[i]-(-i0)%nbin[i]; - if( pbc[i] && i0>=nbin[i]) i0%=nbin[i]; + if(!pbc[i] && i0<0) { + found=false; + } + if(!pbc[i] && i0>=nbin[i]) { + found=false; + } + if( pbc[i] && i0<0) { + i0=nbin[i]-(-i0)%nbin[i]; + } + if( pbc[i] && i0>=nbin[i]) { + i0%=nbin[i]; + } t_indices[i]=static_cast(i0); } if( found ) { diff --git a/src/gridtools/GridCoordinatesObject.h b/src/gridtools/GridCoordinatesObject.h index b8d3662df8..e7da5f03f2 100644 --- a/src/gridtools/GridCoordinatesObject.h +++ b/src/gridtools/GridCoordinatesObject.h @@ -123,7 +123,9 @@ unsigned GridCoordinatesObject::getNumberOfPoints() const { inline const std::vector& GridCoordinatesObject::getGridSpacing() const { - if( gtype==flat ) return dx; + if( gtype==flat ) { + return dx; + } plumed_merror("dont understand what spacing means for spherical grids"); return dx; } @@ -131,7 +133,10 @@ const std::vector& GridCoordinatesObject::getGridSpacing() const { inline double GridCoordinatesObject::getCellVolume() const { if( gtype==flat ) { - double myvol=1.0; for(unsigned i=0; i( getNumberOfPoints() ); @@ -157,8 +162,11 @@ const std::vector& GridCoordinatesObject::getStride() const { inline std::string GridCoordinatesObject::getGridType() const { - if( gtype==flat ) return "flat"; - else if( gtype==fibonacci ) return "fibonacci"; + if( gtype==flat ) { + return "flat"; + } else if( gtype==fibonacci ) { + return "fibonacci"; + } return ""; } diff --git a/src/gridtools/GridSearch.h b/src/gridtools/GridSearch.h index 1225c2519a..b1beec455e 100644 --- a/src/gridtools/GridSearch.h +++ b/src/gridtools/GridSearch.h @@ -47,18 +47,23 @@ class GridSearch { public: GridSearch( const std::vector& mmin, const std::vector& mmax, const std::vector& ng, const std::vector& nfg, FCLASS* funcc ) : myclass_func( funcc ), - using_fgrid(false) - { + using_fgrid(false) { // Setup the min and max values for the grid std::vector gmin( nfg.size() ), gmax( nfg.size() ); - std::vector pbc( nfg.size(), false ); std::vector dummy_spacing; - for(unsigned i=0; i pbc( nfg.size(), false ); + std::vector dummy_spacing; + for(unsigned i=0; i0 ) { - using_fgrid=true; myfgrid.setup("flat", pbc, 0, 0.0 ); dummy_spacing.resize(0); + using_fgrid=true; + myfgrid.setup("flat", pbc, 0, 0.0 ); + dummy_spacing.resize(0); myfgrid.setBounds( gmin, gmax, nfg, dummy_spacing ); } value.reset( new Value( NULL, "gval", true, mygrid.getNbin(true)) ); @@ -70,29 +75,42 @@ class GridSearch { template void GridSearch::setGridElement( const unsigned& ind, const double& emin, const std::vector& der ) { - value->set( ind, emin ); for(unsigned j=0; jsetGridDerivatives( ind, j, der[j] ); + value->set( ind, emin ); + for(unsigned j=0; jsetGridDerivatives( ind, j, der[j] ); + } } template bool GridSearch::minimise( std::vector& p, engf_pointer myfunc ) { - std::vector der( p.size() ); std::vector coords( p.size() ); + std::vector der( p.size() ); + std::vector coords( p.size() ); double initial_eng = (myclass_func->*myfunc)( p, der ); - mygrid.getGridPointCoordinates( 0, coords ); unsigned pmin=0; - double emin=(myclass_func->*myfunc)( coords, der ); setGridElement( 0, emin, der ); + mygrid.getGridPointCoordinates( 0, coords ); + unsigned pmin=0; + double emin=(myclass_func->*myfunc)( coords, der ); + setGridElement( 0, emin, der ); for(unsigned i=1; i*myfunc)( coords, der ); setGridElement( i, eng, der ); - if( engsplineInterpolation( coords, der ); for(unsigned i=1; isplineInterpolation( coords, der ); - if( eng*myfunc)( coords, der ); diff --git a/src/gridtools/Histogram.cpp b/src/gridtools/Histogram.cpp index e7db8defab..f3e2e24bbd 100644 --- a/src/gridtools/Histogram.cpp +++ b/src/gridtools/Histogram.cpp @@ -202,7 +202,9 @@ class Histogram : public ActionShortcut { PLUMED_REGISTER_ACTION(Histogram,"HISTOGRAM") void Histogram::registerKeywords( Keywords& keys ) { - ActionShortcut::registerKeywords( keys ); keys.use("UPDATE_FROM"); keys.use("UPDATE_UNTIL"); + ActionShortcut::registerKeywords( keys ); + keys.use("UPDATE_FROM"); + keys.use("UPDATE_UNTIL"); keys.add("compulsory","NORMALIZATION","ndata","This controls how the data is normalized it can be set equal to true, false or ndata. See above for an explanation"); keys.add("optional","ARG","the quantity that is being averaged"); keys.add("optional","DATA","an alternative to the ARG keyword"); @@ -217,27 +219,47 @@ void Histogram::registerKeywords( Keywords& keys ) { keys.add("compulsory","STRIDE","1","the frequency with which to store data for averaging"); keys.add("compulsory","CLEAR","0","the frequency with whihc to clear the data that is being averaged"); keys.setValueDescription("the estimate of the histogram as a function of the argument that was obtained"); - keys.needsAction("COMBINE"); keys.needsAction("CUSTOM"); keys.needsAction("ONES"); - keys.needsAction("KDE"); keys.needsAction("ACCUMULATE"); + keys.needsAction("COMBINE"); + keys.needsAction("CUSTOM"); + keys.needsAction("ONES"); + keys.needsAction("KDE"); + keys.needsAction("ACCUMULATE"); } Histogram::Histogram( const ActionOptions& ao ): Action(ao), - ActionShortcut(ao) -{ - std::string normflag; parse("NORMALIZATION",normflag); - std::string lw; parse("LOGWEIGHTS",lw); std::string stride, clearstride; parse("STRIDE",stride); parse("CLEAR",clearstride); + ActionShortcut(ao) { + std::string normflag; + parse("NORMALIZATION",normflag); + std::string lw; + parse("LOGWEIGHTS",lw); + std::string stride, clearstride; + parse("STRIDE",stride); + parse("CLEAR",clearstride); if( lw.length()>0 && normflag!="ndata" ) { readInputLine( getShortcutLabel() + "_wsum: COMBINE ARG=" + lw + " PERIODIC=NO"); readInputLine( getShortcutLabel() + "_weight: CUSTOM ARG=" + getShortcutLabel() + "_wsum FUNC=exp(x) PERIODIC=NO"); - } else readInputLine( getShortcutLabel() + "_weight: ONES SIZE=1" ); - - std::vector arglist; parseVector("ARG",arglist); if( arglist.size()==0 ) parseVector("DATA",arglist); - if( arglist.size()==0 ) error("arguments have not been specified use ARG"); - std::vector theargs; ActionWithArguments::interpretArgumentList( arglist, plumed.getActionSet(), this, theargs ); - plumed_assert( theargs.size()>0 ); std::string argstr=theargs[0]->getName(); - for(unsigned i=1; igetName(); - std::string strnum; Tools::convert( theargs[0]->getNumberOfValues(), strnum ); + } else { + readInputLine( getShortcutLabel() + "_weight: ONES SIZE=1" ); + } + + std::vector arglist; + parseVector("ARG",arglist); + if( arglist.size()==0 ) { + parseVector("DATA",arglist); + } + if( arglist.size()==0 ) { + error("arguments have not been specified use ARG"); + } + std::vector theargs; + ActionWithArguments::interpretArgumentList( arglist, plumed.getActionSet(), this, theargs ); + plumed_assert( theargs.size()>0 ); + std::string argstr=theargs[0]->getName(); + for(unsigned i=1; igetName(); + } + std::string strnum; + Tools::convert( theargs[0]->getNumberOfValues(), strnum ); if( theargs[0]->getNumberOfValues()==1 ) { // Create the KDE object readInputLine( getShortcutLabel() + "_kde: KDE ARG=" + argstr + " " + convertInputLineToString() ); diff --git a/src/gridtools/InterpolateGrid.cpp b/src/gridtools/InterpolateGrid.cpp index e667494c62..64479aefd8 100644 --- a/src/gridtools/InterpolateGrid.cpp +++ b/src/gridtools/InterpolateGrid.cpp @@ -75,30 +75,44 @@ PLUMED_REGISTER_ACTION(InterpolateGrid,"INTERPOLATE_GRID") void InterpolateGrid::registerKeywords( Keywords& keys ) { ActionWithGrid::registerKeywords( keys ); - keys.add("optional","GRID_BIN","the number of bins for the grid"); keys.use("ARG"); + keys.add("optional","GRID_BIN","the number of bins for the grid"); + keys.use("ARG"); keys.add("optional","GRID_SPACING","the approximate grid spacing (to be used as an alternative or together with GRID_BIN)"); keys.addFlag("MIDPOINTS",false,"interpolate the values of the function at the midpoints of the grid coordinates of the input grid"); - EvaluateGridFunction ii; ii.registerKeywords( keys ); + EvaluateGridFunction ii; + ii.registerKeywords( keys ); } InterpolateGrid::InterpolateGrid(const ActionOptions&ao): Action(ao), - ActionWithGrid(ao) -{ - if( getNumberOfArguments()!=1 ) error("should only be one argument to this action"); - if( getPntrToArgument(0)->getRank()==0 || !getPntrToArgument(0)->hasDerivatives() ) error("input to this action should be a grid"); + ActionWithGrid(ao) { + if( getNumberOfArguments()!=1 ) { + error("should only be one argument to this action"); + } + if( getPntrToArgument(0)->getRank()==0 || !getPntrToArgument(0)->hasDerivatives() ) { + error("input to this action should be a grid"); + } - parseFlag("MIDPOINTS",midpoints); parseVector("GRID_BIN",nbin); parseVector("GRID_SPACING",gspacing); unsigned dimension = getPntrToArgument(0)->getRank(); - if( !midpoints && nbin.size()!=dimension && gspacing.size()!=dimension ) error("MIDPOINTS, GRID_BIN or GRID_SPACING must be set"); + parseFlag("MIDPOINTS",midpoints); + parseVector("GRID_BIN",nbin); + parseVector("GRID_SPACING",gspacing); + unsigned dimension = getPntrToArgument(0)->getRank(); + if( !midpoints && nbin.size()!=dimension && gspacing.size()!=dimension ) { + error("MIDPOINTS, GRID_BIN or GRID_SPACING must be set"); + } if( midpoints ) { log.printf(" evaluating function at midpoints of cells in input grid\n"); } else if( nbin.size()==dimension ) { log.printf(" number of bins in grid %d", nbin[0]); - for(unsigned i=1; iisPeriodic() ) { - std::string min, max; getPntrToArgument(0)->getDomain( min, max ); setPeriodic( min, max ); - } else setNotPeriodic(); + std::string min, max; + getPntrToArgument(0)->getDomain( min, max ); + setPeriodic( min, max ); + } else { + setNotPeriodic(); + } setupOnFirstStep( false ); } void InterpolateGrid::setupOnFirstStep( const bool incalc ) { input_grid.setup( this ); ActionWithGrid* ag=ActionWithGrid::getInputActionWithGrid( getPntrToArgument(0)->getPntrToAction() ); - plumed_assert( ag ); const GridCoordinatesObject& mygrid = ag->getGridCoordinatesObject(); + plumed_assert( ag ); + const GridCoordinatesObject& mygrid = ag->getGridCoordinatesObject(); if( midpoints ) { - double min, max; nbin.resize( getPntrToComponent(0)->getRank() ); + double min, max; + nbin.resize( getPntrToComponent(0)->getRank() ); std::vector str_min( input_grid.getMin() ), str_max(input_grid.getMax() ); for(unsigned i=0; isetShape( output_grid.getNbin(true) ); - if( !incalc ) gspacing.resize(0); + if( !incalc ) { + gspacing.resize(0); + } } unsigned InterpolateGrid::getNumberOfDerivatives() { @@ -155,26 +185,40 @@ const GridCoordinatesObject& InterpolateGrid::getGridCoordinatesObject() const { std::vector InterpolateGrid::getGridCoordinateNames() const { ActionWithGrid* ag = ActionWithGrid::getInputActionWithGrid( getPntrToArgument(0)->getPntrToAction() ); - plumed_assert( ag ); return ag->getGridCoordinateNames(); + plumed_assert( ag ); + return ag->getGridCoordinateNames(); } void InterpolateGrid::performTask( const unsigned& current, MultiValue& myvals ) const { - std::vector pos( output_grid.getDimension() ); output_grid.getGridPointCoordinates( current, pos ); - std::vector val(1); Matrix der( 1, output_grid.getDimension() ); input_grid.calc( this, pos, val, der ); - unsigned ostrn = getConstPntrToComponent(0)->getPositionInStream(); myvals.setValue( ostrn, val[0] ); - for(unsigned i=0; i pos( output_grid.getDimension() ); + output_grid.getGridPointCoordinates( current, pos ); + std::vector val(1); + Matrix der( 1, output_grid.getDimension() ); + input_grid.calc( this, pos, val, der ); + unsigned ostrn = getConstPntrToComponent(0)->getPositionInStream(); + myvals.setValue( ostrn, val[0] ); + for(unsigned i=0; i& buffer ) const { - plumed_dbg_assert( valindex==0 ); unsigned ostrn = getConstPntrToComponent(0)->getPositionInStream(); - unsigned istart = bufstart + (1+output_grid.getDimension())*code; buffer[istart] += myvals.get( ostrn ); - for(unsigned i=0; igetPositionInStream(); + unsigned istart = bufstart + (1+output_grid.getDimension())*code; + buffer[istart] += myvals.get( ostrn ); + for(unsigned i=0; i& forces ) const { - std::vector pos(output_grid.getDimension()); double ff = myval->getForce(itask); - output_grid.getGridPointCoordinates( itask, pos ); input_grid.applyForce( this, pos, ff, forces ); + std::vector pos(output_grid.getDimension()); + double ff = myval->getForce(itask); + output_grid.getGridPointCoordinates( itask, pos ); + input_grid.applyForce( this, pos, ff, forces ); } diff --git a/src/gridtools/Interpolator.cpp b/src/gridtools/Interpolator.cpp index 43cdb865a3..b5f2f65f30 100644 --- a/src/gridtools/Interpolator.cpp +++ b/src/gridtools/Interpolator.cpp @@ -25,37 +25,49 @@ namespace PLMD { namespace gridtools { double Interpolator::splineInterpolation( const std::vector& x, std::vector& der ) const { - plumed_dbg_assert( gridobject.getGridType()=="flat" ); unsigned dimension = gridobject.getDimension(); + plumed_dbg_assert( gridobject.getGridType()=="flat" ); + unsigned dimension = gridobject.getDimension(); - double X,X2,X3,value=0; der.assign(der.size(),0.0); + double X,X2,X3,value=0; + der.assign(der.size(),0.0); std::vector fd(dimension); std::vector C(dimension); std::vector D(dimension); std::vector dder(dimension); std::vector nindices(dimension); - std::vector indices(dimension); gridobject.getIndices( x, indices ); - std::vector xfloor(dimension); gridobject.getGridPointCoordinates( gridobject.getIndex(x), nindices, xfloor ); + std::vector indices(dimension); + gridobject.getIndices( x, indices ); + std::vector xfloor(dimension); + gridobject.getGridPointCoordinates( gridobject.getIndex(x), nindices, xfloor ); // loop over neighbors - std::vector neigh; unsigned n_neigh; + std::vector neigh; + unsigned n_neigh; gridobject.getSplineNeighbors( gridobject.getIndex(indices), n_neigh, neigh ); for(unsigned int ipoint=0; ipointget( neigh[ipoint] ); - for(unsigned j=0; jgetGridDerivative( neigh[ipoint], j ); + for(unsigned j=0; jgetGridDerivative( neigh[ipoint], j ); + } gridobject.getIndices( neigh[ipoint], nindices ); double ff=1.0; for(unsigned j=0; j& x, std::vec } for(unsigned j=0; j shape( getNumberOfArguments() ); center.resize( getNumberOfArguments() ); + fixed_width(false) { + std::vector shape( getNumberOfArguments() ); + center.resize( getNumberOfArguments() ); numberOfKernels=getPntrToArgument(0)->getNumberOfValues(); for(unsigned i=1; igetNumberOfValues() ) error("mismatch between numbers of values in input arguments"); + if( numberOfKernels!=getPntrToArgument(i)->getNumberOfValues() ) { + error("mismatch between numbers of values in input arguments"); + } } - bool weights_are_volumes=true; std::vector weight_str; parseVector("VOLUMES",weight_str); + bool weights_are_volumes=true; + std::vector weight_str; + parseVector("VOLUMES",weight_str); if( weight_str.size()==0 ) { parseVector("HEIGHTS",weight_str); - if( weight_str.size()>0 ) weights_are_volumes=false; + if( weight_str.size()>0 ) { + weights_are_volumes=false; + } } hasheight=(weight_str.size()==1); - if( weight_str.size()>1 ) error("only one scalar/vector/matrix should be input to HEIGHTS"); + if( weight_str.size()>1 ) { + error("only one scalar/vector/matrix should be input to HEIGHTS"); + } if( getName()=="KDE" ) { parse("KERNEL",kerneltype); if( kerneltype!="DISCRETE" ) { - std::string bandwidth; std::vector bwidths; parseVector("BANDWIDTH",bwidths); + std::string bandwidth; + std::vector bwidths; + parseVector("BANDWIDTH",bwidths); if( bwidths.size()>0 ) { std::string band="VALUES=" + bwidths[0]; for(unsigned i=0; i0 ) band += "," + bwidths[i]; + if( i>0 ) { + band += "," + bwidths[i]; + } } plumed.readInputLine( getLabel() + "_sigma: CONSTANT " + band ); plumed.readInputLine( getLabel() + "_cov: CUSTOM ARG=" + getLabel() + "_sigma FUNC=x*x PERIODIC=NO" ); @@ -150,51 +163,84 @@ KDE::KDE(const ActionOptions&ao): bandwidth = getLabel() + "_icov"; if( (kerneltype=="gaussian" || kerneltype=="GAUSSIAN") && weights_are_volumes ) { - std::string pstr; Tools::convert( sqrt(pow(2*pi,bwidths.size())), pstr ); + std::string pstr; + Tools::convert( sqrt(pow(2*pi,bwidths.size())), pstr ); plumed.readInputLine( getLabel() + "_bwprod: PRODUCT ARG=" + getLabel() + "_cov"); plumed.readInputLine( getLabel() + "_vol: CUSTOM ARG=" + getLabel() + "_bwprod FUNC=(sqrt(x)*" + pstr + ") PERIODIC=NO"); - if( hasheight ) plumed.readInputLine( getLabel() + "_height: CUSTOM ARG=" + weight_str[0] + "," + getLabel() + "_vol FUNC=x/y PERIODIC=NO"); - else plumed.readInputLine( getLabel() + "_height: CUSTOM ARG=" + getLabel() + "_vol FUNC=1/x PERIODIC=NO"); - hasheight=true; weight_str.resize(1); weight_str[0] = getLabel() + "_height"; + if( hasheight ) { + plumed.readInputLine( getLabel() + "_height: CUSTOM ARG=" + weight_str[0] + "," + getLabel() + "_vol FUNC=x/y PERIODIC=NO"); + } else { + plumed.readInputLine( getLabel() + "_height: CUSTOM ARG=" + getLabel() + "_vol FUNC=1/x PERIODIC=NO"); + } + hasheight=true; + weight_str.resize(1); + weight_str[0] = getLabel() + "_height"; } - } else parse("METRIC",bandwidth); + } else { + parse("METRIC",bandwidth); + } weight_str.push_back( bandwidth ); } } if( weight_str.size()>0 ) { - std::vector weight_args; ActionWithArguments::interpretArgumentList( weight_str, plumed.getActionSet(), this, weight_args ); - std::vector args( getArguments() ); args.push_back( weight_args[0] ); - if( hasheight && weight_args[0]->getNumberOfValues()>1 && numberOfKernels!=weight_args[0]->getNumberOfValues() ) error("mismatch between numbers of values in input arguments and HEIGHTS"); + std::vector weight_args; + ActionWithArguments::interpretArgumentList( weight_str, plumed.getActionSet(), this, weight_args ); + std::vector args( getArguments() ); + args.push_back( weight_args[0] ); + if( hasheight && weight_args[0]->getNumberOfValues()>1 && numberOfKernels!=weight_args[0]->getNumberOfValues() ) { + error("mismatch between numbers of values in input arguments and HEIGHTS"); + } if( weight_str.size()==2 ) { log.printf(" quantities used for weights are : %s \n", weight_str[0].c_str() ); args.push_back( weight_args[1] ); - if( weight_args[1]->getRank()==1 && weight_args[1]->getNumberOfValues()!=shape.size() ) error("size of bandwidth vector is incorrect"); - if( weight_args[1]->getRank()>2 ) error("bandwidths cannot have rank greater than 2"); - bwargno=args.size()-1; log.printf(" bandwidths are taken from : %s \n", weight_str[1].c_str() ); + if( weight_args[1]->getRank()==1 && weight_args[1]->getNumberOfValues()!=shape.size() ) { + error("size of bandwidth vector is incorrect"); + } + if( weight_args[1]->getRank()>2 ) { + error("bandwidths cannot have rank greater than 2"); + } + bwargno=args.size()-1; + log.printf(" bandwidths are taken from : %s \n", weight_str[1].c_str() ); } else if( !hasheight ) { - if( weight_args[0]->getRank()==1 && weight_args[0]->getNumberOfValues()!=shape.size() ) error("size of bandwidth vector is incorrect"); - if( weight_args[0]->getRank()>2 ) error("bandwidths cannot have rank greater than 2"); - bwargno=args.size()-1; log.printf(" bandwidths are taken from : %s \n", weight_str[0].c_str() ); + if( weight_args[0]->getRank()==1 && weight_args[0]->getNumberOfValues()!=shape.size() ) { + error("size of bandwidth vector is incorrect"); + } + if( weight_args[0]->getRank()>2 ) { + error("bandwidths cannot have rank greater than 2"); + } + bwargno=args.size()-1; + log.printf(" bandwidths are taken from : %s \n", weight_str[0].c_str() ); } else if ( weight_str.size()==1 ) { log.printf(" quantities used for weights are : %s \n", weight_str[0].c_str() ); - } else error("only one scalar/vector/matrix should be input to HEIGHTS"); + } else { + error("only one scalar/vector/matrix should be input to HEIGHTS"); + } requestArguments( args ); } if( getName()=="KDE" ) { - bool hasauto=false; gmin.resize( shape.size() ); gmax.resize( shape.size() ); - parseVector("GRID_MIN",gmin); parseVector("GRID_MAX",gmax); + bool hasauto=false; + gmin.resize( shape.size() ); + gmax.resize( shape.size() ); + parseVector("GRID_MIN",gmin); + parseVector("GRID_MAX",gmax); for(unsigned i=0; iisPeriodic() ) { - if( gmin[i]=="auto" ) getPntrToArgument(i)->getDomain( gmin[i], gmax[i] ); - else { - std::string str_min, str_max; getPntrToArgument(i)->getDomain( str_min, str_max ); - if( str_min!=gmin[i] || str_max!=gmax[i] ) error("all periodic arguments should have the same domain"); + if( gmin[i]=="auto" ) { + getPntrToArgument(i)->getDomain( gmin[i], gmax[i] ); + } else { + std::string str_min, str_max; + getPntrToArgument(i)->getDomain( str_min, str_max ); + if( str_min!=gmin[i] || str_max!=gmax[i] ) { + error("all periodic arguments should have the same domain"); + } } } else if( getPntrToArgument(i)->getName().find(".")!=std::string::npos ) { std::size_t dot = getPntrToArgument(i)->getName().find_first_of("."); @@ -209,94 +255,145 @@ KDE::KDE(const ActionOptions&ao): log.printf(" for %dth coordinate min is set to %s and max is set to %s \n", (i+1), gmin[i].c_str(), gmax[i].c_str() ); } } - if( hasauto && gmin.size()>3 ) error("can only set GRID_MIN and GRID_MAX automatically if components of distance are used in input"); + if( hasauto && gmin.size()>3 ) { + error("can only set GRID_MIN and GRID_MAX automatically if components of distance are used in input"); + } - parseVector("GRID_BIN",nbin); parseVector("GRID_SPACING",gspacing); parse("CUTOFF",dp2cutoff); + parseVector("GRID_BIN",nbin); + parseVector("GRID_SPACING",gspacing); + parse("CUTOFF",dp2cutoff); if( kerneltype.find("bin")==std::string::npos && kerneltype!="DISCRETE" ) { - std::string errors; switchingFunction.set( kerneltype + " R_0=1.0 NOSTRETCH", errors ); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); + std::string errors; + switchingFunction.set( kerneltype + " R_0=1.0 NOSTRETCH", errors ); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } } - if( nbin.size()!=shape.size() && gspacing.size()!=shape.size() ) error("GRID_BIN or GRID_SPACING must be set"); + if( nbin.size()!=shape.size() && gspacing.size()!=shape.size() ) { + error("GRID_BIN or GRID_SPACING must be set"); + } // Create a value std::vector ipbc( shape.size() ); for(unsigned i=0; iisPeriodic() || gmin[i]=="auto" ) ipbc[i]=true; - else ipbc[i]=false; + if( getPntrToArgument( i )->isPeriodic() || gmin[i]=="auto" ) { + ipbc[i]=true; + } else { + ipbc[i]=false; + } } gridobject.setup( "flat", ipbc, 0, 0.0 ); } else { - if( shape.size()!=3 ) error("should have three coordinates in input to this action"); + if( shape.size()!=3 ) { + error("should have three coordinates in input to this action"); + } - parse("GRID_BIN",nbins); log.printf(" setting number of bins to %d \n", nbins ); - parse("CONCENTRATION",von_misses_concentration); fixed_width=true; + parse("GRID_BIN",nbins); + log.printf(" setting number of bins to %d \n", nbins ); + parse("CONCENTRATION",von_misses_concentration); + fixed_width=true; von_misses_norm = von_misses_concentration / ( 4*pi*sinh( von_misses_concentration ) ); log.printf(" setting concentration parameter to %f \n", von_misses_concentration ); // Create a value std::vector ipbc( shape.size(), false ); double fib_cutoff = std::log( epsilon / von_misses_norm ) / von_misses_concentration; - gridobject.setup( "fibonacci", ipbc, nbins, fib_cutoff ); checkRead(); + gridobject.setup( "fibonacci", ipbc, nbins, fib_cutoff ); + checkRead(); // Setup the grid - shape[0]=nbins; shape[1]=shape[2]=1; + shape[0]=nbins; + shape[1]=shape[2]=1; } parseFlag("IGNORE_IF_OUT_OF_RANGE",ignore_out_of_bounds); - if( ignore_out_of_bounds ) log.printf(" ignoring kernels that are outside of grid \n"); - addValueWithDerivatives( shape ); setNotPeriodic(); + if( ignore_out_of_bounds ) { + log.printf(" ignoring kernels that are outside of grid \n"); + } + addValueWithDerivatives( shape ); + setNotPeriodic(); getPntrToComponent(0)->setDerivativeIsZeroWhenValueIsZero(); // Make sure we store all the arguments - for(unsigned i=0; ibuildDataStore(); + for(unsigned i=0; ibuildDataStore(); + } // Check for task reduction - updateTaskListReductionStatus(); setupOnFirstStep( false ); + updateTaskListReductionStatus(); + setupOnFirstStep( false ); } void KDE::setupOnFirstStep( const bool incalc ) { - if( getName()=="SPHERICAL_KDE" ) return ; + if( getName()=="SPHERICAL_KDE" ) { + return ; + } for(unsigned i=0; i("Box"); Tensor box( bv->getPbc().getBox() ); + PbcAction* bv = plumed.getActionSet().selectWithLabel("Box"); + Tensor box( bv->getPbc().getBox() ); std::size_t dot = getPntrToArgument(i)->getName().find_first_of("."); std::string name = getPntrToArgument(i)->getName().substr(dot+1); - if( name=="x" ) { lcoord=-0.5*box(0,0); ucoord=0.5*box(0,0); } - else if( name=="y" ) { lcoord=-0.5*box(1,1); ucoord=0.5*box(1,1); } - else if( name=="z" ) { lcoord=-0.5*box(2,2); ucoord=0.5*box(2,2); } - else plumed_error(); + if( name=="x" ) { + lcoord=-0.5*box(0,0); + ucoord=0.5*box(0,0); + } else if( name=="y" ) { + lcoord=-0.5*box(1,1); + ucoord=0.5*box(1,1); + } else if( name=="z" ) { + lcoord=-0.5*box(2,2); + ucoord=0.5*box(2,2); + } else { + plumed_error(); + } // And convert to strings for bin and bmax - Tools::convert( lcoord, gmin[i] ); Tools::convert( ucoord, gmax[i] ); + Tools::convert( lcoord, gmin[i] ); + Tools::convert( ucoord, gmax[i] ); } if( incalc ) { grid_diff_value.push_back( Value() ); - if( gridobject.isPeriodic(i) ) grid_diff_value[i].setDomain( gmin[i], gmax[i] ); - else grid_diff_value[i].setNotPeriodic(); + if( gridobject.isPeriodic(i) ) { + grid_diff_value[i].setDomain( gmin[i], gmax[i] ); + } else { + grid_diff_value[i].setNotPeriodic(); + } } } // And setup the grid object gridobject.setBounds( gmin, gmax, nbin, gspacing ); std::vector shape( gridobject.getNbin(true) ); getPntrToComponent(0)->setShape( shape ); - bool hasauto=false; for(unsigned i=0; iisConstant() ) { - fixed_width=true; setupNeighborsVector(); + fixed_width=true; + setupNeighborsVector(); } } void KDE::setupNeighborsVector() { if( kerneltype!="DISCRETE" ) { - std::vector support(gmin.size(),0); nneigh.resize( gmin.size() ); + std::vector support(gmin.size(),0); + nneigh.resize( gmin.size() ); if( kerneltype.find("bin")!=std::string::npos ) { std::size_t dd = kerneltype.find("-bin"); - HistogramBead bead; bead.setKernelType( kerneltype.substr(0,dd) ); + HistogramBead bead; + bead.setKernelType( kerneltype.substr(0,dd) ); Value* bw_arg=getPntrToArgument(bwargno); if( bw_arg->getRank()<2 ) { for(unsigned i=0; iget(i)) ); - support[i] = bead.getCutoff(); nneigh[i] = static_cast( ceil( support[i]/gridobject.getGridSpacing()[i] )); + support[i] = bead.getCutoff(); + nneigh[i] = static_cast( ceil( support[i]/gridobject.getGridSpacing()[i] )); } - } else plumed_error(); + } else { + plumed_error(); + } } else { Value* bw_arg=getPntrToArgument(bwargno); if( bw_arg->getRank()<2 ) { @@ -305,24 +402,41 @@ void KDE::setupNeighborsVector() { nneigh[i] = static_cast( ceil( support[i] / gridobject.getGridSpacing()[i] ) ); } } else if( bw_arg->getRank()==2 ) { - Matrix metric(support.size(),support.size()); unsigned k=0; + Matrix metric(support.size(),support.size()); + unsigned k=0; for(unsigned i=0; iget(k); k++; } + for(unsigned j=0; jget(k); + k++; + } } - Matrix myautovec(support.size(),support.size()); std::vector myautoval(support.size()); - diagMat(metric,myautoval,myautovec); double maxautoval=1/myautoval[0]; unsigned ind_maxautoval=0; + Matrix myautovec(support.size(),support.size()); + std::vector myautoval(support.size()); + diagMat(metric,myautoval,myautovec); + double maxautoval=1/myautoval[0]; + unsigned ind_maxautoval=0; for(unsigned i=1; imaxautoval) { maxautoval=neweig; ind_maxautoval=i; } + double neweig=1/myautoval[i]; + if(neweig>maxautoval) { + maxautoval=neweig; + ind_maxautoval=i; + } } for(unsigned i=0; i( ceil( support[i] / gridobject.getGridSpacing()[i] ) ); } - } else plumed_error(); + } else { + plumed_error(); + } } for(unsigned i=0; i(fmax-fmin) ) error("bandwidth is too large for periodic grid"); + double fmax, fmin; + Tools::convert( gridobject.getMin()[i], fmin ); + Tools::convert( gridobject.getMax()[i], fmax ); + if( gridobject.isPeriodic(i) && 2*support[i]>(fmax-fmin) ) { + error("bandwidth is too large for periodic grid"); + } } } } @@ -333,7 +447,9 @@ unsigned KDE::getNumberOfDerivatives() { std::vector KDE::getGridCoordinateNames() const { std::vector names( gridobject.getDimension() ); - for(unsigned i=0; igetName(); + for(unsigned i=0; igetName(); + } return names; } @@ -342,25 +458,41 @@ const GridCoordinatesObject& KDE::getGridCoordinatesObject() const { } void KDE::areAllTasksRequired( std::vector& task_reducing_actions ) { - if( numberOfKernels==1 || (hasheight && getPntrToArgument(gridobject.getDimension())->getRank()>0) ) task_reducing_actions.push_back(this); + if( numberOfKernels==1 || (hasheight && getPntrToArgument(gridobject.getDimension())->getRank()>0) ) { + task_reducing_actions.push_back(this); + } } void KDE::getNumberOfTasks( unsigned& ntasks ) { - if( !fixed_width ) setupNeighborsVector(); + if( !fixed_width ) { + setupNeighborsVector(); + } ntasks = numberOfKernels = getPntrToArgument(0)->getNumberOfValues(); - if( numberOfKernels>1 ) return; + if( numberOfKernels>1 ) { + return; + } - hh = 1.0; if( hasheight ) hh = getPntrToArgument(gridobject.getDimension())->get(); - for(unsigned i=0; iget(); + hh = 1.0; + if( hasheight ) { + hh = getPntrToArgument(gridobject.getDimension())->get(); + } + for(unsigned i=0; iget(); + } if( !ignore_out_of_bounds && !gridobject.inbounds( center ) ) { //if( fabs(height)>epsilon ) warning("bounds are possibly set too small as hills with substantial heights are being ignored"); return; } if( kerneltype=="DISCRETE" ) { - num_neigh=1; neighbors.resize(1); - for(unsigned i=0; igetNumberOfValues(); return; } @@ -368,75 +500,121 @@ void KDE::getNumberOfTasks( unsigned& ntasks ) { int KDE::checkTaskStatus( const unsigned& taskno, int& flag ) const { if( numberOfKernels>1 ) { if( hasheight && getPntrToArgument(gridobject.getDimension())->getRank()>0 - && fabs(getPntrToArgument(gridobject.getDimension())->get(taskno))get(taskno)) args( gridobject.getDimension() ), der( gridobject.getDimension() ); + double newval; + std::vector args( gridobject.getDimension() ), der( gridobject.getDimension() ); unsigned valout = getConstPntrToComponent(0)->getPositionInStream(); gridobject.getGridPointCoordinates( current, args ); if( getName()=="KDE" ) { if( kerneltype=="DISCRETE" ) { newval = 1.0; } else if( kerneltype.find("bin")!=std::string::npos ) { - double val=hh; std::size_t dd = kerneltype.find("-bin"); - HistogramBead bead; bead.setKernelType( kerneltype.substr(0,dd) ); Value* bw_arg=getPntrToArgument(bwargno); + double val=hh; + std::size_t dd = kerneltype.find("-bin"); + HistogramBead bead; + bead.setKernelType( kerneltype.substr(0,dd) ); + Value* bw_arg=getPntrToArgument(bwargno); for(unsigned j=0; jgetRank()<2 ) bead.set( args[j], args[j]+gridobject.getGridSpacing()[j], 1/sqrt(bw_arg->get(j)) ); - else if( bw_arg->getRank()==2 ) plumed_error(); + double lcoord, ucoord; + Tools::convert( gmin[j], lcoord ); + Tools::convert( gmax[j], ucoord ); + bead.isPeriodic( lcoord, ucoord ); + } else { + bead.isNotPeriodic(); + } + if( bw_arg->getRank()<2 ) { + bead.set( args[j], args[j]+gridobject.getGridSpacing()[j], 1/sqrt(bw_arg->get(j)) ); + } else if( bw_arg->getRank()==2 ) { + plumed_error(); + } double contr = bead.calculateWithCutoff( args[j], der[j] ); - val = val*contr; der[j] = der[j] / contr; + val = val*contr; + der[j] = der[j] / contr; } - for(unsigned j=0; j& args, double& height ) const { - height=1.0; for(unsigned i=0; iget( myvals.getTaskIndex() ); - if( hasheight && getPntrToArgument(args.size())->getRank()==0 ) height = getPntrToArgument( args.size() )->get(); - else if( hasheight ) height = getPntrToArgument( args.size() )->get( myvals.getTaskIndex() ); + height=1.0; + for(unsigned i=0; iget( myvals.getTaskIndex() ); + } + if( hasheight && getPntrToArgument(args.size())->getRank()==0 ) { + height = getPntrToArgument( args.size() )->get(); + } else if( hasheight ) { + height = getPntrToArgument( args.size() )->get( myvals.getTaskIndex() ); + } } double KDE::evaluateKernel( const std::vector& gpoint, const std::vector& args, const double& height, std::vector& der ) const { - double r2=0, hval = height; Value* bw_arg=getPntrToArgument(bwargno); + double r2=0, hval = height; + Value* bw_arg=getPntrToArgument(bwargno); if( bw_arg->getRank()<2 ) { for(unsigned j=0; jget(j); r2 += tmp*der[j]; + der[j] = tmp*bw_arg->get(j); + r2 += tmp*der[j]; } } else if( bw_arg->getRank()==2 ) { for(unsigned j=0; jget(j*der.size()+k)*dp_k; r2 += dp_j*dp_k*bw_arg->get(j*der.size()+k); + if(j==k) { + dp_k = dp_j; + } else { + dp_k = -grid_diff_value[k].difference( gpoint[k], args[k] ); + } + der[j] += bw_arg->get(j*der.size()+k)*dp_k; + r2 += dp_j*dp_k*bw_arg->get(j*der.size()+k); } } - } else plumed_error(); + } else { + plumed_error(); + } double dval, val=hval*switchingFunction.calculateSqr( r2, dval ); - dval *= hval; for(unsigned j=0; j& bead ) const { for(unsigned j=0; j& bead, const std::vector& gpoint, const std::vector& args, const double& height, std::vector& der ) const { - double val=height; std::vector contr( args.size() ); Value* bw_arg=getPntrToArgument(bwargno); + double val=height; + std::vector contr( args.size() ); + Value* bw_arg=getPntrToArgument(bwargno); if( bw_arg->getRank()<2 ) { for(unsigned j=0; jget(j)) ); contr[j] = bead[j].calculateWithCutoff( args[j], der[j] ); val = val*contr[j]; } - } else plumed_error(); + } else { + plumed_error(); + } for(unsigned j=0; jepsilon ) der[j] *= val / contr[j]; + if( fabs(contr[j])>epsilon ) { + der[j] *= val / contr[j]; + } } return val; } @@ -473,60 +661,86 @@ void KDE::gatherStoredValue( const unsigned& valindex, const unsigned& code, con plumed_dbg_assert( valindex==0 ); if( numberOfKernels==1 ) { unsigned istart = bufstart + (1+gridobject.getDimension())*code; - unsigned valout = getConstPntrToComponent(0)->getPositionInStream(); buffer[istart] += myvals.get( valout ); - for(unsigned i=0; igetPositionInStream(); + buffer[istart] += myvals.get( valout ); + for(unsigned i=0; i args( gridobject.getDimension() ); double height; retrieveArgumentsAndHeight( myvals, args, height ); + std::vector args( gridobject.getDimension() ); + double height; + retrieveArgumentsAndHeight( myvals, args, height ); if( !ignore_out_of_bounds && !gridobject.inbounds( args ) ) { // if( fabs(height)>epsilon ) warning("bounds are possibly set too small as hills with substantial heights are being ignored"); return ; } // Add the kernel to the grid - unsigned num_neigh; std::vector neighbors; - if( kerneltype!="DISCRETE" ) gridobject.getNeighbors( args, nneigh, num_neigh, neighbors ); + unsigned num_neigh; + std::vector neighbors; + if( kerneltype!="DISCRETE" ) { + gridobject.getNeighbors( args, nneigh, num_neigh, neighbors ); + } std::vector der( args.size() ), gpoint( args.size() ); if( fabs(height)>epsilon ) { if( getName()=="KDE" ) { if( kerneltype=="DISCRETE" ) { std::vector newargs( args.size() ); - for(unsigned i=0; i bead( args.size() ); setupHistogramBeads( bead ); + std::vector bead( args.size() ); + setupHistogramBeads( bead ); for(unsigned i=0; i& force_tasks ) const { - if( !myval->forcesWereAdded() ) return ; - if( numberOfKernels==1 ) plumed_error(); + if( !myval->forcesWereAdded() ) { + return ; + } + if( numberOfKernels==1 ) { + plumed_error(); + } int flag=1; for(unsigned i=0; i args( gridobject.getDimension() ); + double height; + std::vector args( gridobject.getDimension() ); retrieveArgumentsAndHeight( myvals, args, height ); - unsigned num_neigh; std::vector neighbors; + unsigned num_neigh; + std::vector neighbors; gridobject.getNeighbors( args, nneigh, num_neigh, neighbors ); std::vector der( args.size() ), gpoint( args.size() ); - unsigned hforce_start = 0; for(unsigned j=0; jgetNumberOfStoredValues(); + unsigned hforce_start = 0; + for(unsigned j=0; jgetNumberOfStoredValues(); + } if( fabs(height)>epsilon ) { if( getName()=="KDE" ) { if( kerneltype.find("bin")!=std::string::npos ) { - std::vector bead( args.size() ); setupHistogramBeads( bead ); + std::vector bead( args.size() ); + setupHistogramBeads( bead ); for(unsigned i=0; igetForce( neighbors[i] ); - if( hasheight && getPntrToArgument(args.size())->getRank()==0 ) forces[ hforce_start ] += val*fforce / height; - else if( hasheight ) forces[ hforce_start + getPntrToArgument(args.size())->getIndexInStore(itask) ] += val*fforce / height; - unsigned n=0; for(unsigned j=0; jgetIndexInStore(itask)] += der[j]*fforce; n += getPntrToArgument(j)->getNumberOfStoredValues(); } + double val = evaluateBeadValue( bead, gpoint, args, height, der ); + double fforce = getConstPntrToComponent(0)->getForce( neighbors[i] ); + if( hasheight && getPntrToArgument(args.size())->getRank()==0 ) { + forces[ hforce_start ] += val*fforce / height; + } else if( hasheight ) { + forces[ hforce_start + getPntrToArgument(args.size())->getIndexInStore(itask) ] += val*fforce / height; + } + unsigned n=0; + for(unsigned j=0; jgetIndexInStore(itask)] += der[j]*fforce; + n += getPntrToArgument(j)->getNumberOfStoredValues(); + } } } else { for(unsigned i=0; igetForce( neighbors[i] ); - if( hasheight && getPntrToArgument(args.size())->getRank()==0 ) forces[ hforce_start ] += val*fforce / height; - else if( hasheight ) forces[ hforce_start + getPntrToArgument(args.size())->getIndexInStore(itask) ] += val*fforce / height; - unsigned n=0; for(unsigned j=0; jgetIndexInStore(itask)] += -der[j]*fforce; n += getPntrToArgument(j)->getNumberOfStoredValues(); } + if( hasheight && getPntrToArgument(args.size())->getRank()==0 ) { + forces[ hforce_start ] += val*fforce / height; + } else if( hasheight ) { + forces[ hforce_start + getPntrToArgument(args.size())->getIndexInStore(itask) ] += val*fforce / height; + } + unsigned n=0; + for(unsigned j=0; jgetIndexInStore(itask)] += -der[j]*fforce; + n += getPntrToArgument(j)->getNumberOfStoredValues(); + } } } } else { for(unsigned i=0; igetForce( neighbors[i] ); double newval = height*von_misses_norm*exp( von_misses_concentration*dot ); - if( hasheight && getPntrToArgument(args.size())->getRank()==0 ) forces[ hforce_start ] += newval*fforce / height; - else if( hasheight ) forces[ hforce_start + getPntrToArgument(args.size())->getIndexInStore(itask) ] += newval*fforce / height; - unsigned n=0; for(unsigned j=0; jgetIndexInStore(itask)] += von_misses_concentration*newval*gpoint[j]*fforce; n += getPntrToArgument(j)->getNumberOfStoredValues(); } + double dot=0; + for(unsigned j=0; jgetForce( neighbors[i] ); + double newval = height*von_misses_norm*exp( von_misses_concentration*dot ); + if( hasheight && getPntrToArgument(args.size())->getRank()==0 ) { + forces[ hforce_start ] += newval*fforce / height; + } else if( hasheight ) { + forces[ hforce_start + getPntrToArgument(args.size())->getIndexInStore(itask) ] += newval*fforce / height; + } + unsigned n=0; + for(unsigned j=0; jgetIndexInStore(itask)] += von_misses_concentration*newval*gpoint[j]*fforce; + n += getPntrToArgument(j)->getNumberOfStoredValues(); + } } } } diff --git a/src/gridtools/KLEntropy.cpp b/src/gridtools/KLEntropy.cpp index e41845373d..9c0896b9dc 100644 --- a/src/gridtools/KLEntropy.cpp +++ b/src/gridtools/KLEntropy.cpp @@ -49,18 +49,24 @@ void KLEntropy::registerKeywords( Keywords& keys ) { keys.add("compulsory","REFERENCE","a file containing the reference density in grid format"); keys.add("compulsory","VALUE","the name of the value that should be read from the grid"); keys.setValueDescription("the value of the KL-Entropy"); - keys.needsAction("REFERENCE_GRID"); keys.needsAction("CUSTOM"); keys.needsAction("INTEGRATE_GRID"); + keys.needsAction("REFERENCE_GRID"); + keys.needsAction("CUSTOM"); + keys.needsAction("INTEGRATE_GRID"); } KLEntropy::KLEntropy( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Reference grid object - std::string ref_str, val_str, input_g; parse("VALUE",val_str); parse("REFERENCE",ref_str); parse("ARG",input_g); + std::string ref_str, val_str, input_g; + parse("VALUE",val_str); + parse("REFERENCE",ref_str); + parse("ARG",input_g); readInputLine( getShortcutLabel() + "_ref: REFERENCE_GRID VALUE=" + val_str + " FILE=" + ref_str ); // Compute KL divergence - if( input_g=="") plumed_merror("could not find ARG keyword in input to KL_ENTROPY"); + if( input_g=="") { + plumed_merror("could not find ARG keyword in input to KL_ENTROPY"); + } readInputLine( getShortcutLabel() + "_kl: CUSTOM ARG=" + input_g + "," + getShortcutLabel() + "_ref FUNC=y*log(y/(0.5*(x+y))) PERIODIC=NO"); // Compute integral readInputLine( getShortcutLabel() + ": INTEGRATE_GRID ARG=" + getShortcutLabel() + "_kl PERIODIC=NO"); diff --git a/src/gridtools/MultiColvarDensity.cpp b/src/gridtools/MultiColvarDensity.cpp index a51b83f557..f76404bbe0 100644 --- a/src/gridtools/MultiColvarDensity.cpp +++ b/src/gridtools/MultiColvarDensity.cpp @@ -99,37 +99,76 @@ void MultiColvarDensity::registerKeywords( Keywords& keys ) { keys.addFlag("UNORMALIZED",false,"do not divide by the density"); keys.add("optional","NORMALIZATION","set true/false to determine how to the data is normalised"); keys.setValueDescription("the average value of the order parameters at each point on the grid"); - keys.needsAction("DISTANCES"); keys.needsAction("KDE"); keys.needsAction("ACCUMULATE"); - keys.needsAction("CUSTOM"); keys.needsAction("ONES"); keys.needsAction("CUSTOM"); + keys.needsAction("DISTANCES"); + keys.needsAction("KDE"); + keys.needsAction("ACCUMULATE"); + keys.needsAction("CUSTOM"); + keys.needsAction("ONES"); + keys.needsAction("CUSTOM"); } MultiColvarDensity::MultiColvarDensity(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read in the position of the origin - std::string origin_str; parse("ORIGIN",origin_str); + std::string origin_str; + parse("ORIGIN",origin_str); // Read in the quantity we are calculating the density for - std::string atoms_str, data_str; parse("ATOMS",atoms_str); parse("DATA",data_str); - if( atoms_str.length()==0 && data_str.length()==0 ) error("quantity to calculate the density for was not specified used DATA/ATOMS"); + std::string atoms_str, data_str; + parse("ATOMS",atoms_str); + parse("DATA",data_str); + if( atoms_str.length()==0 && data_str.length()==0 ) { + error("quantity to calculate the density for was not specified used DATA/ATOMS"); + } // Get the information on the direction for the density - std::string dir, direction_string; parse("DIR",dir); std::string nbins=""; parse("NBINS",nbins); if(nbins.length()>0) nbins=" GRID_BIN=" + nbins; - if( dir=="x" ) direction_string = "ARG=" + getShortcutLabel() + "_dist.x " + nbins; - else if( dir=="y" ) direction_string = "ARG=" + getShortcutLabel() + "_dist.y " + nbins; - else if( dir=="z" ) direction_string = "ARG=" + getShortcutLabel() + "_dist.z " + nbins; - else if( dir=="xy" ) direction_string = "ARG=" + getShortcutLabel() + "_dist.x," + getShortcutLabel() + "_dist.y " + nbins; - else if( dir=="xz" ) direction_string = "ARG=" + getShortcutLabel() + "_dist.x," + getShortcutLabel() + "_dist.z " + nbins; - else if( dir=="yz" ) direction_string = "ARG=" + getShortcutLabel() + "_dist.y," + getShortcutLabel() + "_dist.z " + nbins; - else if( dir=="xyz" ) direction_string = "ARG=" + getShortcutLabel() + "_dist.x," + getShortcutLabel() + "_dist.y," + getShortcutLabel() + "_dist.z " + nbins; - else error( dir + " is invalid dir specification use x/y/z/xy/xz/yz/xyz"); + std::string dir, direction_string; + parse("DIR",dir); + std::string nbins=""; + parse("NBINS",nbins); + if(nbins.length()>0) { + nbins=" GRID_BIN=" + nbins; + } + if( dir=="x" ) { + direction_string = "ARG=" + getShortcutLabel() + "_dist.x " + nbins; + } else if( dir=="y" ) { + direction_string = "ARG=" + getShortcutLabel() + "_dist.y " + nbins; + } else if( dir=="z" ) { + direction_string = "ARG=" + getShortcutLabel() + "_dist.z " + nbins; + } else if( dir=="xy" ) { + direction_string = "ARG=" + getShortcutLabel() + "_dist.x," + getShortcutLabel() + "_dist.y " + nbins; + } else if( dir=="xz" ) { + direction_string = "ARG=" + getShortcutLabel() + "_dist.x," + getShortcutLabel() + "_dist.z " + nbins; + } else if( dir=="yz" ) { + direction_string = "ARG=" + getShortcutLabel() + "_dist.y," + getShortcutLabel() + "_dist.z " + nbins; + } else if( dir=="xyz" ) { + direction_string = "ARG=" + getShortcutLabel() + "_dist.x," + getShortcutLabel() + "_dist.y," + getShortcutLabel() + "_dist.z " + nbins; + } else { + error( dir + " is invalid dir specification use x/y/z/xy/xz/yz/xyz"); + } // Parse the keymap for this averaging stuff - std::string stride, clear; parse("STRIDE",stride); parse("CLEAR",clear); bool unorm; parseFlag("UNORMALIZED",unorm); - if( !unorm ) { std::string normstr; parse("NORMALIZATION",normstr); if( normstr=="false" ) unorm=true; } + std::string stride, clear; + parse("STRIDE",stride); + parse("CLEAR",clear); + bool unorm; + parseFlag("UNORMALIZED",unorm); + if( !unorm ) { + std::string normstr; + parse("NORMALIZATION",normstr); + if( normstr=="false" ) { + unorm=true; + } + } // Create distance action - bool hasheights; std::string dist_words = getShortcutLabel() + "_dist: DISTANCES COMPONENTS ORIGIN=" + origin_str; - if( atoms_str.length()>0 ) { hasheights=false; dist_words += " ATOMS=" + atoms_str; } - else { hasheights=true; dist_words += " ATOMS=" + data_str; } + bool hasheights; + std::string dist_words = getShortcutLabel() + "_dist: DISTANCES COMPONENTS ORIGIN=" + origin_str; + if( atoms_str.length()>0 ) { + hasheights=false; + dist_words += " ATOMS=" + atoms_str; + } else { + hasheights=true; + dist_words += " ATOMS=" + data_str; + } // plumed_massert( keys.count("ORIGIN"), "you must specify the position of the origin" ); readInputLine( dist_words ); @@ -137,8 +176,12 @@ MultiColvarDensity::MultiColvarDensity(const ActionOptions&ao): // Make the kde object for the numerator if needed if( hasheights ) { readInputLine( getShortcutLabel() + "_inumer: KDE VOLUMES=" + data_str + " " + direction_string + " " + inputLine ); - if( unorm ) { readInputLine( getShortcutLabel() + ": ACCUMULATE ARG=" + getShortcutLabel() + "_inumer STRIDE=" + stride + " CLEAR=" + clear ); return; } - else readInputLine( getShortcutLabel() + "_numer: ACCUMULATE ARG=" + getShortcutLabel() + "_inumer STRIDE=" + stride + " CLEAR=" + clear ); + if( unorm ) { + readInputLine( getShortcutLabel() + ": ACCUMULATE ARG=" + getShortcutLabel() + "_inumer STRIDE=" + stride + " CLEAR=" + clear ); + return; + } else { + readInputLine( getShortcutLabel() + "_numer: ACCUMULATE ARG=" + getShortcutLabel() + "_inumer STRIDE=" + stride + " CLEAR=" + clear ); + } } // Make the kde object readInputLine( getShortcutLabel() + "_kde: KDE " + inputLine + " " + direction_string ); diff --git a/src/gridtools/PairEntropies.cpp b/src/gridtools/PairEntropies.cpp index 59db395548..5ef52e9cd6 100644 --- a/src/gridtools/PairEntropies.cpp +++ b/src/gridtools/PairEntropies.cpp @@ -44,39 +44,59 @@ class PairEntropies : public ActionShortcut { PLUMED_REGISTER_ACTION(PairEntropies,"PAIRENTROPIES") void PairEntropies::registerKeywords( Keywords& keys ) { - RDF::registerKeywords( keys ); keys.remove("GROUP"); keys.remove("GROUPA"); keys.remove("GROUPB"); + RDF::registerKeywords( keys ); + keys.remove("GROUP"); + keys.remove("GROUPA"); + keys.remove("GROUPB"); keys.add("atoms","ATOMS","the atoms that you would like to compute the entropies for"); keys.setValueDescription("the a vector containing the KL-entropy that is computed from the radial distribution function around each of the atoms in the input"); - keys.needsAction("PAIRENTROPY"); keys.needsAction("INTERPOLATE_GRID"); - keys.needsAction("INTEGRATE_GRID"); keys.needsAction("CUSTOM"); + keys.needsAction("PAIRENTROPY"); + keys.needsAction("INTERPOLATE_GRID"); + keys.needsAction("INTEGRATE_GRID"); + keys.needsAction("CUSTOM"); keys.needsAction("CONCATENATE"); } PairEntropies::PairEntropies(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read in the atoms involved - std::string atoms_str; parse("ATOMS",atoms_str); + std::string atoms_str; + parse("ATOMS",atoms_str); // Create the x2 value - std::string maxr, nbins, dens; parse("MAXR",maxr); parse("GRID_BIN",nbins); parse("DENSITY",dens); + std::string maxr, nbins, dens; + parse("MAXR",maxr); + parse("GRID_BIN",nbins); + parse("DENSITY",dens); std::string grid_setup = "GRID_MIN=0 GRID_MAX=" + maxr + " GRID_BIN=" + nbins; RDF::createX2ReferenceObject( getShortcutLabel(), grid_setup, dens.length()==0, this ); // Create the number of input atoms std::string pair_str = "GRID_BIN=" + nbins + " MAXR=" + maxr + " " + convertInputLineToString(); - std::vector awords=Tools::getWords(atoms_str,"\t\n ,"); Tools::interpretRanges( awords ); + std::vector awords=Tools::getWords(atoms_str,"\t\n ,"); + Tools::interpretRanges( awords ); // Now create all the pairentropy objects for(unsigned i=0; i0 ) ref_str = "REFERENCE=" + ref_name; else ref_name = getShortcutLabel() + "_rdf"; + ActionShortcut(ao) { + std::string ref_str, ref_name; + parse("REFERENCE",ref_name); + if( ref_name.length()>0 ) { + ref_str = "REFERENCE=" + ref_name; + } else { + ref_name = getShortcutLabel() + "_rdf"; + } // Read in the atoms and get the number of atoms that we are using - std::string atom_str, group_str, natoms; parse("GROUP",group_str); + std::string atom_str, group_str, natoms; + parse("GROUP",group_str); if( group_str.length()>0 ) { atom_str="GROUP=" + group_str; std::vector awords=Tools::getWords(group_str,"\t\n ,"); - Tools::interpretRanges( awords ); Tools::convert( awords.size(), natoms ); + Tools::interpretRanges( awords ); + Tools::convert( awords.size(), natoms ); } else { std::string groupa_str, groupb_str; - parse("GROUPA",groupa_str); parse("GROUPB",groupb_str); + parse("GROUPA",groupa_str); + parse("GROUPB",groupb_str); atom_str="GROUPA=" + groupa_str + " GROUPB=" + groupb_str; std::vector awords=Tools::getWords(groupb_str,"\t\n ,"); - Tools::interpretRanges( awords ); Tools::convert( awords.size()+1, natoms ); + Tools::interpretRanges( awords ); + Tools::convert( awords.size()+1, natoms ); } // Read in all other keywords and create the RDF object - std::string maxr, nbins, dens, bw, cutoff; parse("MAXR",maxr); parse("GRID_BIN",nbins); parse("DENSITY",dens); parse("BANDWIDTH",bw); parse("CUTOFF",cutoff); - std::string dens_str; if( dens.length()>0 ) dens_str = " DENSITY=" + dens; + std::string maxr, nbins, dens, bw, cutoff; + parse("MAXR",maxr); + parse("GRID_BIN",nbins); + parse("DENSITY",dens); + parse("BANDWIDTH",bw); + parse("CUTOFF",cutoff); + std::string dens_str; + if( dens.length()>0 ) { + dens_str = " DENSITY=" + dens; + } readInputLine( getShortcutLabel() + "_rdf: RDF " + atom_str + " CUTOFF=" + cutoff + " GRID_BIN=" + nbins + " MAXR=" + maxr + dens_str + " BANDWIDTH=" + bw + " " + ref_str); // And compute the two functions we are integrating (we use two matheval objects here and sum them in order to avoid nans from taking logarithms of zero) readInputLine( getShortcutLabel() + "_conv_t1: CUSTOM ARG=" + getShortcutLabel() + "_rdf," + ref_name + "_x2 FUNC=x*y*log(x) PERIODIC=NO"); @@ -81,8 +99,11 @@ PairEntropy::PairEntropy(const ActionOptions&ao): readInputLine( getShortcutLabel() + "_int: INTEGRATE_GRID ARG=" + getShortcutLabel() + "_midp PERIODIC=NO"); // And then integrate // And multiply by final normalizing constant std::string norm_str; - if( dens.length()>0 ) norm_str = " FUNC=-2*pi*x*" + dens; - else norm_str = "," + ref_name + "_vol FUNC=-(2*pi*x/y)*" + natoms; + if( dens.length()>0 ) { + norm_str = " FUNC=-2*pi*x*" + dens; + } else { + norm_str = "," + ref_name + "_vol FUNC=-(2*pi*x/y)*" + natoms; + } readInputLine( getShortcutLabel() + ": CUSTOM PERIODIC=NO ARG=" + getShortcutLabel() + "_int" + norm_str ); } diff --git a/src/gridtools/RDF.cpp b/src/gridtools/RDF.cpp index 1716d5cd14..c4b99128ec 100644 --- a/src/gridtools/RDF.cpp +++ b/src/gridtools/RDF.cpp @@ -40,7 +40,9 @@ void RDF::createX2ReferenceObject( const std::string& lab, const std::string& gr // Create grid with normalizing function action->readInputLine( lab + "_x2: REFERENCE_GRID PERIODIC=NO FUNC=x*x " + grid_setup ); // Compute density if required - if( calc_dens ) action->readInputLine( lab + "_vol: VOLUME" ); + if( calc_dens ) { + action->readInputLine( lab + "_vol: VOLUME" ); + } } void RDF::registerKeywords( Keywords& keys ) { @@ -58,44 +60,68 @@ void RDF::registerKeywords( Keywords& keys ) { keys.add("optional","DENSITY","the reference density to use when normalizing the RDF"); keys.add("hidden","REFERENCE","this is the label of the reference objects"); keys.setValueDescription("the radial distribution function"); - keys.needsAction("REFERENCE_GRID"); keys.needsAction("VOLUME"); keys.needsAction("DISTANCE_MATRIX"); - keys.needsAction("CUSTOM"); keys.needsAction("KDE"); keys.needsAction("ACCUMULATE"); + keys.needsAction("REFERENCE_GRID"); + keys.needsAction("VOLUME"); + keys.needsAction("DISTANCE_MATRIX"); + keys.needsAction("CUSTOM"); + keys.needsAction("KDE"); + keys.needsAction("ACCUMULATE"); keys.needsAction("CONSTANT"); } RDF::RDF(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read in grid extent and number of bins - std::string maxr, nbins, dens; parse("MAXR",maxr); parse("GRID_BIN",nbins); parse("DENSITY",dens); + std::string maxr, nbins, dens; + parse("MAXR",maxr); + parse("GRID_BIN",nbins); + parse("DENSITY",dens); std::string grid_setup = "GRID_MIN=0 GRID_MAX=" + maxr + " GRID_BIN=" + nbins; // Create grid with normalizing function on it - std::string refstr; parse("REFERENCE",refstr); + std::string refstr; + parse("REFERENCE",refstr); if( refstr.length()==0 ) { - createX2ReferenceObject( getShortcutLabel(), grid_setup, dens.length()==0, this ); refstr = getShortcutLabel(); + createX2ReferenceObject( getShortcutLabel(), grid_setup, dens.length()==0, this ); + refstr = getShortcutLabel(); } // Read input to histogram - std::string cutoff, kernel, bandwidth, kernel_data; parse("KERNEL",kernel); + std::string cutoff, kernel, bandwidth, kernel_data; + parse("KERNEL",kernel); if( kernel=="DISCRETE" ) { - cutoff = maxr; kernel_data="KERNEL=DISCRETE"; + cutoff = maxr; + kernel_data="KERNEL=DISCRETE"; warning("rdf is normalised by dividing by the surface area at the grid value and not by the volume of the bin as it should be with discrete kernels"); } else { - parse("BANDWIDTH",bandwidth); double rcut; parse("CUTOFF",rcut); kernel_data="KERNEL=" + kernel + " IGNORE_IF_OUT_OF_RANGE BANDWIDTH=" + bandwidth; - double bw; Tools::convert( bandwidth, bw ); double fcut; Tools::convert( maxr, fcut ); Tools::convert( fcut + sqrt(2.0*rcut)*bw, cutoff ); + parse("BANDWIDTH",bandwidth); + double rcut; + parse("CUTOFF",rcut); + kernel_data="KERNEL=" + kernel + " IGNORE_IF_OUT_OF_RANGE BANDWIDTH=" + bandwidth; + double bw; + Tools::convert( bandwidth, bw ); + double fcut; + Tools::convert( maxr, fcut ); + Tools::convert( fcut + sqrt(2.0*rcut)*bw, cutoff ); } // Create contact matrix - std::string natoms, str_norm_atoms, atom_str, group_str, groupa_str, groupb_str; parse("GROUP",group_str); + std::string natoms, str_norm_atoms, atom_str, group_str, groupa_str, groupb_str; + parse("GROUP",group_str); if( group_str.length()>0 ) { - atom_str="GROUP=" + group_str; std::vector awords=Tools::getWords(group_str,"\t\n ,"); - Tools::interpretRanges( awords ); Tools::convert( awords.size(), natoms ); str_norm_atoms = natoms; + atom_str="GROUP=" + group_str; + std::vector awords=Tools::getWords(group_str,"\t\n ,"); + Tools::interpretRanges( awords ); + Tools::convert( awords.size(), natoms ); + str_norm_atoms = natoms; } else { - parse("GROUPA",groupa_str); parse("GROUPB",groupb_str); + parse("GROUPA",groupa_str); + parse("GROUPB",groupb_str); std::vector awords=Tools::getWords(groupb_str,"\t\n ,"); - Tools::interpretRanges( awords ); Tools::convert( awords.size(), natoms ); + Tools::interpretRanges( awords ); + Tools::convert( awords.size(), natoms ); atom_str="GROUPA=" + groupa_str + " GROUPB=" + groupb_str; - std::vector bwords=Tools::getWords(groupa_str,"\t\n ,"); Tools::interpretRanges( bwords ); + std::vector bwords=Tools::getWords(groupa_str,"\t\n ,"); + Tools::interpretRanges( bwords ); Tools::convert( bwords.size()+1, str_norm_atoms ); } // Retrieve the number of atoms @@ -104,11 +130,15 @@ RDF::RDF(const ActionOptions&ao): // Calculate weights of distances readInputLine( getShortcutLabel() + "_wmat: CUSTOM ARG=" + getShortcutLabel() + "_mat FUNC=step(" + cutoff + "-x) PERIODIC=NO"); // Now create a histogram from the contact matrix - unsigned clear, stride; parse("CLEAR",clear); parse("STRIDE",stride); + unsigned clear, stride; + parse("CLEAR",clear); + parse("STRIDE",stride); if( clear==1 ) { readInputLine( getShortcutLabel() + "_kde: KDE ARG=" + getShortcutLabel() + "_mat VOLUMES=" + getShortcutLabel() + "_wmat " + grid_setup + " " + kernel_data); } else { - std::string stridestr, clearstr; Tools::convert( stride, stridestr ); Tools::convert( clear, clearstr ); + std::string stridestr, clearstr; + Tools::convert( stride, stridestr ); + Tools::convert( clear, clearstr ); readInputLine( getShortcutLabel() + "_okde: KDE ARG=" + getShortcutLabel() + "_mat HEIGHTS=" + getShortcutLabel() + "_wmat " + grid_setup + " " + kernel_data); readInputLine( getShortcutLabel() + "_kde: ACCUMULATE ARG=" + getShortcutLabel() + "_okde STRIDE=" + stridestr + " CLEAR=" + clearstr ); readInputLine( getShortcutLabel() + "_one: CONSTANT VALUE=1"); @@ -119,11 +149,17 @@ RDF::RDF(const ActionOptions&ao): // And normalize by density and number of atoms (separated from above to avoid nans) std::string func_str = "PERIODIC=NO ARG=" + getShortcutLabel() + "_vrdf"; if( dens.length()>0 ) { - if( clear==1 ) func_str += " FUNC=x/(" + dens + "*" + str_norm_atoms + ")"; - else func_str += "," + getShortcutLabel() + "_norm FUNC=x/(y*" + dens + "*" + str_norm_atoms + ")"; + if( clear==1 ) { + func_str += " FUNC=x/(" + dens + "*" + str_norm_atoms + ")"; + } else { + func_str += "," + getShortcutLabel() + "_norm FUNC=x/(y*" + dens + "*" + str_norm_atoms + ")"; + } } else { - if( clear==1 ) func_str += "," + refstr + "_vol FUNC=x*y/(" + natoms + "*" + str_norm_atoms + ")"; - else func_str += "," + refstr + "_vol," + getShortcutLabel() + "_norm FUNC=x*y/(z*" + natoms + "*" + str_norm_atoms + ")"; + if( clear==1 ) { + func_str += "," + refstr + "_vol FUNC=x*y/(" + natoms + "*" + str_norm_atoms + ")"; + } else { + func_str += "," + refstr + "_vol," + getShortcutLabel() + "_norm FUNC=x*y/(z*" + natoms + "*" + str_norm_atoms + ")"; + } } readInputLine( getShortcutLabel() + ": CUSTOM " + func_str); } diff --git a/src/gridtools/ReadGridInSetup.cpp b/src/gridtools/ReadGridInSetup.cpp index 2ac2b91952..132872819b 100644 --- a/src/gridtools/ReadGridInSetup.cpp +++ b/src/gridtools/ReadGridInSetup.cpp @@ -63,8 +63,12 @@ class ReadGridInSetup : public ActionWithGrid { static void registerKeywords( Keywords& keys ); explicit ReadGridInSetup(const ActionOptions&ao); unsigned getNumberOfDerivatives() override ; - void setupOnFirstStep( const bool incalc ) override { plumed_merror("should not be in ReadGridInSetup setupOnFirstStep" ); } - void performTask( const unsigned& current, MultiValue& myvals ) const override { plumed_merror("should not be in readGridInSetup performTask"); } + void setupOnFirstStep( const bool incalc ) override { + plumed_merror("should not be in ReadGridInSetup setupOnFirstStep" ); + } + void performTask( const unsigned& current, MultiValue& myvals ) const override { + plumed_merror("should not be in readGridInSetup performTask"); + } std::vector getGridCoordinateNames() const override ; const GridCoordinatesObject& getGridCoordinatesObject() const override ; }; @@ -72,7 +76,8 @@ class ReadGridInSetup : public ActionWithGrid { PLUMED_REGISTER_ACTION(ReadGridInSetup,"REFERENCE_GRID") void ReadGridInSetup::registerKeywords( Keywords& keys ) { - ActionWithGrid::registerKeywords(keys); keys.remove("SERIAL"); + ActionWithGrid::registerKeywords(keys); + keys.remove("SERIAL"); keys.add("optional","FUNC","the function to compute on the grid"); keys.add("compulsory","GRID_MIN","auto","the lower bounds for the grid"); keys.add("compulsory","GRID_MAX","auto","the upper bounds for the grid"); @@ -87,33 +92,50 @@ void ReadGridInSetup::registerKeywords( Keywords& keys ) { ReadGridInSetup::ReadGridInSetup(const ActionOptions&ao): Action(ao), - ActionWithGrid(ao) -{ - std::string func; parse("FUNC",func); + ActionWithGrid(ao) { + std::string func; + parse("FUNC",func); if( func.length()>0 ) { // Read in stuff for grid - std::vector gmin; parseVector("GRID_MIN",gmin); - std::vector gmax(gmin.size()); parseVector("GRID_MAX",gmax); - std::vector gbin(gmin.size()); parseVector("GRID_BIN",gbin); - std::vector pbc(gmin.size()); parseVector("PERIODIC",pbc); + std::vector gmin; + parseVector("GRID_MIN",gmin); + std::vector gmax(gmin.size()); + parseVector("GRID_MAX",gmax); + std::vector gbin(gmin.size()); + parseVector("GRID_BIN",gbin); + std::vector pbc(gmin.size()); + parseVector("PERIODIC",pbc); std::vector ipbc( pbc.size() ); for(unsigned i=0; i3) + if(gmin.size()>3) { error("Using more than 3 arguments you should explicitly write their names with VAR"); - if(dernames.size()>0) dernames[0]="x"; - if(dernames.size()>1) dernames[1]="y"; - if(dernames.size()>2) dernames[2]="z"; + } + if(dernames.size()>0) { + dernames[0]="x"; + } + if(dernames.size()>1) { + dernames[1]="y"; + } + if(dernames.size()>2) { + dernames[2]="z"; + } + } + if(dernames.size()!=gmin.size()) { + error("Size of VAR array should be the same as number of grid dimensions"); } - if(dernames.size()!=gmin.size()) error("Size of VAR array should be the same as number of grid dimensions"); // Create the grid and the value of the grid createGridAndValue( "flat", ipbc, 0, gmin, gmax, gbin ); @@ -121,14 +143,22 @@ ReadGridInSetup::ReadGridInSetup(const ActionOptions&ao): // Read in stuff for function log.printf(" evaluating function : %s\n",func.c_str()); log.printf(" with variables :"); - for(unsigned i=0; i dder( dernames.size() ), xx( dernames.size() ); Value* valout=getPntrToComponent(0); + std::vector dder( dernames.size() ), xx( dernames.size() ); + Value* valout=getPntrToComponent(0); for(unsigned index=0; indexgetNumberOfValues(); ++index) { gridobject.getGridPointCoordinates( index, xx ); for(unsigned j=0; j0 ) { std::size_t dot=filen.find_first_of("."); - if( dot!=std::string::npos ) tstyle=filen.substr(dot+1); - if( tstyle!="grid" ) error("can only read in grids using read value in setup"); + if( dot!=std::string::npos ) { + tstyle=filen.substr(dot+1); + } + if( tstyle!="grid" ) { + error("can only read in grids using read value in setup"); + } log.printf(" reading function %s on grid from file %s \n", valuestr.c_str(), filen.c_str() ); } - IFile ifile; ifile.open(filen); - if( !ifile.FieldExist( valuestr ) ) error("could not find grid value in input file"); - std::vector fieldnames; ifile.scanFieldList( fieldnames ); + IFile ifile; + ifile.open(filen); + if( !ifile.FieldExist( valuestr ) ) { + error("could not find grid value in input file"); + } + std::vector fieldnames; + ifile.scanFieldList( fieldnames ); // Retrieve the names of the variables the grid is computed over bool flatgrid=false; for(unsigned i=0; i gmin( dernames.size() ), gmax( dernames.size() ); std::string pstring; - int gbin1; std::vector gbin( dernames.size() ); std::vector ipbc( dernames.size() ); + std::vector gmin( dernames.size() ), gmax( dernames.size() ); + std::string pstring; + int gbin1; + std::vector gbin( dernames.size() ); + std::vector ipbc( dernames.size() ); if( !flatgrid ) { - ifile.scanField( "nbins", gbin1); gbin[0]=gbin1; + ifile.scanField( "nbins", gbin1); + gbin[0]=gbin1; createGridAndValue( "fibonacci", ipbc, gbin[0], gmin, gmax, gbin ); } else { for(unsigned i=0; i dder( dernames.size() ), xx( dernames.size() ); for(unsigned i=0; igetNumberOfValues(); ++i) { - double x, val; ifile.scanField( valuestr, val ); + double x, val; + ifile.scanField( valuestr, val ); for(unsigned j=0; jset( index, val ); - for(unsigned j=0; jaddGridDerivatives( index, j, dder[j] ); + for(unsigned j=0; jaddGridDerivatives( index, j, dder[j] ); + } ifile.scanField(); } ifile.close(); @@ -248,15 +312,20 @@ ReadGridInSetup::ReadGridInSetup(const ActionOptions&ao): void ReadGridInSetup::createGridAndValue( const std::string& gtype, const std::vector& ipbc, const unsigned& nfermi, const std::vector& gmin, const std::vector& gmax, const std::vector& gbin ) { - gridobject.setup( gtype, ipbc, nfermi, 0.0 ); std::vector gspacing; + gridobject.setup( gtype, ipbc, nfermi, 0.0 ); + std::vector gspacing; if( gtype=="flat" ) { gridobject.setBounds( gmin, gmax, gbin, gspacing ); // Now create the value std::vector shape( gridobject.getNbin(true) ); - ActionWithValue::addValueWithDerivatives( shape ); setNotPeriodic(); + ActionWithValue::addValueWithDerivatives( shape ); + setNotPeriodic(); } else { - std::vector shape( 3 ); shape[0]=gbin[0]; shape[1]=shape[2]=1; - ActionWithValue::addValueWithDerivatives( shape ); setNotPeriodic(); + std::vector shape( 3 ); + shape[0]=gbin[0]; + shape[1]=shape[2]=1; + ActionWithValue::addValueWithDerivatives( shape ); + setNotPeriodic(); } for(unsigned i=0; isetConstant(); diff --git a/src/isdb/CS2Backbone.cpp b/src/isdb/CS2Backbone.cpp index e91cfa1321..a4234f5035 100644 --- a/src/isdb/CS2Backbone.cpp +++ b/src/isdb/CS2Backbone.cpp @@ -176,160 +176,193 @@ class CS2BackboneDB { public: inline unsigned kind(const std::string &s) { - if(s=="GLY") return GLY; - else if(s=="PRO") return PRO; + if(s=="GLY") { + return GLY; + } else if(s=="PRO") { + return PRO; + } return STD; } inline unsigned atom_kind(const std::string &s) { - if(s=="HA")return HA_ATOM; - else if(s=="H") return H_ATOM; - else if(s=="N") return N_ATOM; - else if(s=="CA")return CA_ATOM; - else if(s=="CB")return CB_ATOM; - else if(s=="C") return C_ATOM; + if(s=="HA") { + return HA_ATOM; + } else if(s=="H") { + return H_ATOM; + } else if(s=="N") { + return N_ATOM; + } else if(s=="CA") { + return CA_ATOM; + } else if(s=="CB") { + return CB_ATOM; + } else if(s=="C") { + return C_ATOM; + } return -1; } - unsigned get_numXtraDists() {return numXtraDists;} + unsigned get_numXtraDists() { + return numXtraDists; + } //PARAMETERS - inline double * CONSTAACURR(const unsigned a_kind, const unsigned at_kind) {return c_aa[a_kind][at_kind];} - inline double * CONSTAANEXT(const unsigned a_kind, const unsigned at_kind) {return c_aa_succ[a_kind][at_kind];} - inline double * CONSTAAPREV(const unsigned a_kind, const unsigned at_kind) {return c_aa_prev[a_kind][at_kind];} - inline double * CONST_BB2(const unsigned a_kind, const unsigned at_kind) {return co_bb[a_kind][at_kind];} - inline double * CONST_SC2(const unsigned a_kind, const unsigned at_kind, unsigned res_type) { return co_sc_[a_kind][at_kind][res_type];} - inline double * CONST_XD(const unsigned a_kind, const unsigned at_kind) { return co_xd[a_kind][at_kind];} - inline double * CO_SPHERE(const unsigned a_kind, const unsigned at_kind, unsigned exp_type) { return co_sphere[a_kind][at_kind][exp_type];} - inline double * CO_RING(const unsigned a_kind, const unsigned at_kind) { return co_ring[a_kind][at_kind];} - inline double * CO_DA(const unsigned a_kind, const unsigned at_kind) { return co_da[a_kind][at_kind];} - inline double * PARS_DA(const unsigned a_kind, const unsigned at_kind, const unsigned ang_kind) { return pars_da[a_kind][at_kind][ang_kind];} + inline double * CONSTAACURR(const unsigned a_kind, const unsigned at_kind) { + return c_aa[a_kind][at_kind]; + } + inline double * CONSTAANEXT(const unsigned a_kind, const unsigned at_kind) { + return c_aa_succ[a_kind][at_kind]; + } + inline double * CONSTAAPREV(const unsigned a_kind, const unsigned at_kind) { + return c_aa_prev[a_kind][at_kind]; + } + inline double * CONST_BB2(const unsigned a_kind, const unsigned at_kind) { + return co_bb[a_kind][at_kind]; + } + inline double * CONST_SC2(const unsigned a_kind, const unsigned at_kind, unsigned res_type) { + return co_sc_[a_kind][at_kind][res_type]; + } + inline double * CONST_XD(const unsigned a_kind, const unsigned at_kind) { + return co_xd[a_kind][at_kind]; + } + inline double * CO_SPHERE(const unsigned a_kind, const unsigned at_kind, unsigned exp_type) { + return co_sphere[a_kind][at_kind][exp_type]; + } + inline double * CO_RING(const unsigned a_kind, const unsigned at_kind) { + return co_ring[a_kind][at_kind]; + } + inline double * CO_DA(const unsigned a_kind, const unsigned at_kind) { + return co_da[a_kind][at_kind]; + } + inline double * PARS_DA(const unsigned a_kind, const unsigned at_kind, const unsigned ang_kind) { + return pars_da[a_kind][at_kind][ang_kind]; + } void parse(const std::string &file, const double dscale) { std::ifstream in; in.open(file.c_str()); - if(!in) plumed_merror("Unable to open DB file: " + file); + if(!in) { + plumed_merror("Unable to open DB file: " + file); + } unsigned c_kind = 0; unsigned c_atom = 0; unsigned nline = 0; - for(unsigned i=0; i<3; i++) for(unsigned j=0; j<6; j++) { + for(unsigned i=0; i<3; i++) + for(unsigned j=0; j<6; j++) { for(unsigned k=0; k<20; k++) { c_aa[i][j][k]=0.; c_aa_prev[i][j][k]=0.; c_aa_succ[i][j][k]=0.; - for(unsigned m=0; m<20; m++) co_sc_[i][j][k][m]=0.; + for(unsigned m=0; m<20; m++) { + co_sc_[i][j][k][m]=0.; + } + } + for(unsigned k=0; k<16; k++) { + co_bb[i][j][k]=0.; + } + for(unsigned k=0; k<8; k++) { + co_sphere[i][j][0][k]=0.; + co_sphere[i][j][1][k]=0.; } - for(unsigned k=0; k<16; k++) {co_bb[i][j][k]=0.; } - for(unsigned k=0; k<8; k++) { co_sphere[i][j][0][k]=0.; co_sphere[i][j][1][k]=0.; } for(unsigned k=0; k<3; k++) { co_da[i][j][k]=0.; - for(unsigned l=0; l<5; l++) pars_da[i][j][k][l]=0.; + for(unsigned l=0; l<5; l++) { + pars_da[i][j][k][l]=0.; + } + } + for(unsigned k=0; k<5; k++) { + co_ring[i][j][k]=0.; + } + for(unsigned k=0; k tok; std::vector tmp; tok = split(line,' '); for(unsigned q=0; q & v, const double scale) { for(unsigned i=1; i used_atoms; parseAtomList("ATOMS",used_atoms); parseFlag("CAMSHIFT",camshift); - if(camshift&&getDoScore()) plumed_merror("It is not possible to use CAMSHIFT and DOSCORE at the same time"); + if(camshift&&getDoScore()) { + plumed_merror("It is not possible to use CAMSHIFT and DOSCORE at the same time"); + } bool nopbc=!pbc; parseFlag("NOPBC",nopbc); @@ -568,10 +609,13 @@ CS2Backbone::CS2Backbone(const ActionOptions&ao): db.parse(stringadb,scale); PDB pdb; - if( !pdb.read(stringapdb,usingNaturalUnits(),1./scale) ) plumed_merror("missing input file " + stringapdb); + if( !pdb.read(stringapdb,usingNaturalUnits(),1./scale) ) { + plumed_merror("missing input file " + stringapdb); + } // first of all we build the list of chemical shifts we want to predict - log.printf(" Reading experimental data ...\n"); log.flush(); + log.printf(" Reading experimental data ...\n"); + log.flush(); stringadb = stringa_data + std::string("/CAshifts.dat"); log.printf(" Initializing CA shifts %s\n", stringadb.c_str()); init_cs(stringadb, "CA", pdb); @@ -591,15 +635,20 @@ CS2Backbone::CS2Backbone(const ActionOptions&ao): log.printf(" Initializing N shifts %s\n", stringadb.c_str()); init_cs(stringadb, "N", pdb); - if(chemicalshifts.size()==0) plumed_merror("There are no chemical shifts to calculate, there must be at least a not empty file (CA|CB|C|HA|H|N|shifts.dat)"); + if(chemicalshifts.size()==0) { + plumed_merror("There are no chemical shifts to calculate, there must be at least a not empty file (CA|CB|C|HA|H|N|shifts.dat)"); + } init_types(pdb); init_rings(pdb); log<<" Bibliography " < iter(in), end; unsigned begin=0; @@ -661,42 +718,73 @@ void CS2Backbone::init_cs(const std::string &file, const std::string &nucl, cons if(begin==1) { begin=0; ichain++; - } else begin=1; + } else { + begin=1; + } continue; } int ro = atoi(tok.c_str()); - if(ro<0) plumed_merror("Residue numbers should be positive\n"); + if(ro<0) { + plumed_merror("Residue numbers should be positive\n"); + } unsigned resnum = static_cast (ro); tok = *iter; ++iter; double cs = atof(tok.c_str()); - if(cs==0) continue; + if(cs==0) { + continue; + } unsigned fres, lres; std::string errmsg; pdb.getResidueRange(chains[ichain], fres, lres, errmsg); - if(resnum==fres||resnum==lres) plumed_merror("First and Last residue of each chain should be annotated as # in " + file + " Remember that residue numbers should match"); + if(resnum==fres||resnum==lres) { + plumed_merror("First and Last residue of each chain should be annotated as # in " + file + " Remember that residue numbers should match"); + } // check in the PDB for the chain/residue/atom and enable the chemical shift std::string RES = pdb.getResidueName(resnum, chains[ichain]); - if(RES=="HIE"||RES=="HIP"||RES=="HIS"||RES=="HSP"||RES=="HSE"||RES=="CYS"||RES=="GLH"||RES=="ASH"||RES=="UNK") continue; - if(RES=="GLN"&&nucl=="CB") continue; - if(RES=="ILE"&&nucl=="CB") continue; - if(RES=="PRO"&&nucl=="N") continue; - if(RES=="PRO"&&nucl=="H") continue; - if(RES=="PRO"&&nucl=="CB") continue; - if(RES=="GLY"&&nucl=="HA") continue; - if(RES=="GLY"&&nucl=="CB") continue; + if(RES=="HIE"||RES=="HIP"||RES=="HIS"||RES=="HSP"||RES=="HSE"||RES=="CYS"||RES=="GLH"||RES=="ASH"||RES=="UNK") { + continue; + } + if(RES=="GLN"&&nucl=="CB") { + continue; + } + if(RES=="ILE"&&nucl=="CB") { + continue; + } + if(RES=="PRO"&&nucl=="N") { + continue; + } + if(RES=="PRO"&&nucl=="H") { + continue; + } + if(RES=="PRO"&&nucl=="CB") { + continue; + } + if(RES=="GLY"&&nucl=="HA") { + continue; + } + if(RES=="GLY"&&nucl=="CB") { + continue; + } ChemicalShift tmp_cs; tmp_cs.exp_cs = cs; - if(nucl=="CA") tmp_cs.nucleus = "ca-"; - else if(nucl=="CB") tmp_cs.nucleus = "cb-"; - else if(nucl=="C") tmp_cs.nucleus = "co-"; - else if(nucl=="HA") tmp_cs.nucleus = "ha-"; - else if(nucl=="H") tmp_cs.nucleus = "hn-"; - else if(nucl=="N") tmp_cs.nucleus = "nh-"; + if(nucl=="CA") { + tmp_cs.nucleus = "ca-"; + } else if(nucl=="CB") { + tmp_cs.nucleus = "cb-"; + } else if(nucl=="C") { + tmp_cs.nucleus = "co-"; + } else if(nucl=="HA") { + tmp_cs.nucleus = "ha-"; + } else if(nucl=="H") { + tmp_cs.nucleus = "hn-"; + } else if(nucl=="N") { + tmp_cs.nucleus = "nh-"; + } tmp_cs.chain = ichain; tmp_cs.res_num = resnum; tmp_cs.res_type_curr = frag2enum(RES); @@ -705,44 +793,73 @@ void CS2Backbone::init_cs(const std::string &file, const std::string &nucl, cons tmp_cs.res_name = RES; tmp_cs.res_kind = db.kind(RES); tmp_cs.atm_kind = db.atom_kind(nucl); - if(RES!="ALA"&&RES!="GLY") {tmp_cs.bb.resize(18); tmp_cs.has_chi1=true;} - else {tmp_cs.bb.resize(16); tmp_cs.has_chi1=false;} + if(RES!="ALA"&&RES!="GLY") { + tmp_cs.bb.resize(18); + tmp_cs.has_chi1=true; + } else { + tmp_cs.bb.resize(16); + tmp_cs.has_chi1=false; + } std::vector res_atoms = pdb.getAtomsInResidue(resnum, chains[ichain]); // find the position of the nucleus and of the other backbone atoms as well as for phi/psi/chi for(unsigned a=0; a prev_res_atoms = pdb.getAtomsInResidue(resnum-1, chains[ichain]); // find the position of the previous residues backbone atoms for(unsigned a=0; a at1; - if(resOffsetP1[q]== 0) at1 = res_atoms; - if(resOffsetP1[q]==-1) at1 = prev_res_atoms; - if(resOffsetP1[q]==+1) at1 = next_res_atoms; + if(resOffsetP1[q]== 0) { + at1 = res_atoms; + } + if(resOffsetP1[q]==-1) { + at1 = prev_res_atoms; + } + if(resOffsetP1[q]==+1) { + at1 = next_res_atoms; + } std::vector at2; - if(resOffsetP2[q]== 0) at2 = res_atoms; - if(resOffsetP2[q]==-1) at2 = prev_res_atoms; - if(resOffsetP2[q]==+1) at2 = next_res_atoms; + if(resOffsetP2[q]== 0) { + at2 = res_atoms; + } + if(resOffsetP2[q]==-1) { + at2 = prev_res_atoms; + } + if(resOffsetP2[q]==+1) { + at2 = next_res_atoms; + } int tmp1 = -1; for(unsigned a=0; a frg_atoms = pdb.getAtomsInResidue(res,chains[i]); @@ -891,8 +1043,12 @@ void CS2Backbone::init_rings(const PDB &pdb) } ri.numAtoms = 6; total_rings_atoms += 6; - if(frg=="PHE") ri.rtype = RingInfo::R_PHE; - if(frg=="TYR") ri.rtype = RingInfo::R_TYR; + if(frg=="PHE") { + ri.rtype = RingInfo::R_PHE; + } + if(frg=="TYR") { + ri.rtype = RingInfo::R_TYR; + } ringInfo.push_back(ri); } else if(frg=="TRP") { @@ -950,14 +1106,21 @@ void CS2Backbone::init_rings(const PDB &pdb) } } - for(unsigned cs=0; cs camshift_sigma2(6); @@ -976,7 +1139,9 @@ void CS2Backbone::calculate() cs_derivs.resize(chemicalshifts.size()*max_cs_atoms,Vector(0,0,0)); cs_atoms.resize(chemicalshifts.size()*max_cs_atoms,0); all_shifts.resize(chemicalshifts.size(),0); - if(camshift||getDoScore()) aa_derivs.resize(getNumberOfAtoms(),Vector(0,0,0)); + if(camshift||getDoScore()) { + aa_derivs.resize(getNumberOfAtoms(),Vector(0,0,0)); + } unsigned stride = comm.Get_size(); unsigned rank = comm.Get_rank(); @@ -986,7 +1151,9 @@ void CS2Backbone::calculate() } unsigned nt=OpenMP::getNumThreads(); - if(nt*stride*2>chemicalshifts.size()) nt=1; + if(nt*stride*2>chemicalshifts.size()) { + nt=1; + } // a single loop over all chemical shifts #pragma omp parallel num_threads(nt) @@ -1011,9 +1178,13 @@ void CS2Backbone::calculate() const unsigned bbsize = 16; for(unsigned q=0; qbb[q]; - if(ipos==jpos) continue; + if(ipos==jpos) { + continue; + } const Vector distance = delta(getPosition(jpos),getPosition(ipos)); const double d = distance.modulo(); const double fact = cb2q/d; @@ -1110,9 +1281,13 @@ void CS2Backbone::calculate() const unsigned sidsize = myfrag->side_chain.size(); for(unsigned q=0; qside_chain[q]; - if(ipos==jpos) continue; + if(ipos==jpos) { + continue; + } const Vector distance = delta(getPosition(jpos),getPosition(ipos)); const double d = distance.modulo(); const double fact = cs2q/d; @@ -1131,8 +1306,12 @@ void CS2Backbone::calculate() const unsigned xdsize=myfrag->xd1.size(); for(unsigned q=0; qxd1[q]==-1||myfrag->xd2[q]==-1) continue; + if(cxdq==0.) { + continue; + } + if(myfrag->xd1[q]==-1||myfrag->xd2[q]==-1) { + continue; + } const Vector distance = delta(getPosition(myfrag->xd1[q]),getPosition(myfrag->xd2[q])); const double d = distance.modulo(); const double fact = cxdq/d; @@ -1184,7 +1363,9 @@ void CS2Backbone::calculate() const double fU = fUU/nL; double OneOverN = 1./6.; - if(ringInfo[q].numAtoms==5) OneOverN=1./3.; + if(ringInfo[q].numAtoms==5) { + OneOverN=1./3.; + } const Vector factor2 = OneOverN*n; const Vector factor4 = (OneOverN/dL_nL)*d; @@ -1274,7 +1455,9 @@ void CS2Backbone::calculate() } ++box_count; - if(box_count == box_nupdate) box_count = 0; + if(box_count == box_nupdate) { + box_count = 0; + } if(!camshift) { if(!serial) { @@ -1287,8 +1470,9 @@ void CS2Backbone::calculate() for(unsigned cs=0; csset(all_shifts[cs]); - if(getDoScore()) setCalcData(cs, all_shifts[cs]); - else { + if(getDoScore()) { + setCalcData(cs, all_shifts[cs]); + } else { const unsigned kdx=cs*max_cs_atoms; Tensor csvirial; for(unsigned i=0; i(res_curr-res_num[bat])); - if(res_dist<2) continue; + if(res_dist<2) { + continue; + } const Vector distance = delta(getPosition(bat),getPosition(chemicalshifts[cs].ipos)); const double d2=distance.modulo2(); - if(d2max_cs_atoms) max_cs_atoms = chemicalshifts[cs].totcsatoms; + if(chemicalshifts[cs].totcsatoms>max_cs_atoms) { + max_cs_atoms = chemicalshifts[cs].totcsatoms; + } } } @@ -1392,7 +1588,9 @@ void CS2Backbone::compute_ring_parameters() { ringInfo[i].g[5] = delta(getPosition(ringInfo[i].atom[3]),getPosition(ringInfo[i].atom[1])); // ring center Vector midP = getPosition(ringInfo[i].atom[0]); - for(unsigned j=1; j CS2Backbone::side_chain_atoms(const std::string &s) { sc.push_back( "2HG2" ); sc.push_back( "3HG2" ); return sc; - } else plumed_merror("Sidechain atoms unknown: " + s); + } else { + plumed_merror("Sidechain atoms unknown: " + s); + } } bool CS2Backbone::isSP2(const std::string & resType, const std::string & atomName) { bool sp2 = false; - if (atomName == "C") return true; - if (atomName == "O") return true; + if (atomName == "C") { + return true; + } + if (atomName == "O") { + return true; + } if(resType == "TRP") { - if (atomName == "CG") sp2 = true; - else if (atomName == "CD1") sp2 = true; - else if (atomName == "CD2") sp2 = true; - else if (atomName == "CE2") sp2 = true; - else if (atomName == "CE3") sp2 = true; - else if (atomName == "CZ2") sp2 = true; - else if (atomName == "CZ3") sp2 = true; - else if (atomName == "CH2") sp2 = true; + if (atomName == "CG") { + sp2 = true; + } else if (atomName == "CD1") { + sp2 = true; + } else if (atomName == "CD2") { + sp2 = true; + } else if (atomName == "CE2") { + sp2 = true; + } else if (atomName == "CE3") { + sp2 = true; + } else if (atomName == "CZ2") { + sp2 = true; + } else if (atomName == "CZ3") { + sp2 = true; + } else if (atomName == "CH2") { + sp2 = true; + } } else if (resType == "ASP") { - if (atomName == "CG") sp2 = true; - else if (atomName == "OD1") sp2 = true; - else if (atomName == "OD2") sp2 = true; + if (atomName == "CG") { + sp2 = true; + } else if (atomName == "OD1") { + sp2 = true; + } else if (atomName == "OD2") { + sp2 = true; + } } else if (resType == "GLU") { - if (atomName == "CD") sp2 = true; - else if (atomName == "OE1") sp2 = true; - else if (atomName == "OE2") sp2 = true; + if (atomName == "CD") { + sp2 = true; + } else if (atomName == "OE1") { + sp2 = true; + } else if (atomName == "OE2") { + sp2 = true; + } } else if (resType == "ARG") { - if (atomName == "CZ") sp2 = true; + if (atomName == "CZ") { + sp2 = true; + } } else if (resType == "HIS") { - if (atomName == "CG") sp2 = true; - else if (atomName == "ND1") sp2 = true; - else if (atomName == "CD2") sp2 = true; - else if (atomName == "CE1") sp2 = true; - else if (atomName == "NE2") sp2 = true; + if (atomName == "CG") { + sp2 = true; + } else if (atomName == "ND1") { + sp2 = true; + } else if (atomName == "CD2") { + sp2 = true; + } else if (atomName == "CE1") { + sp2 = true; + } else if (atomName == "NE2") { + sp2 = true; + } } else if (resType == "PHE") { - if (atomName == "CG") sp2 = true; - else if (atomName == "CD1") sp2 = true; - else if (atomName == "CD2") sp2 = true; - else if (atomName == "CE1") sp2 = true; - else if (atomName == "CE2") sp2 = true; - else if (atomName == "CZ") sp2 = true; + if (atomName == "CG") { + sp2 = true; + } else if (atomName == "CD1") { + sp2 = true; + } else if (atomName == "CD2") { + sp2 = true; + } else if (atomName == "CE1") { + sp2 = true; + } else if (atomName == "CE2") { + sp2 = true; + } else if (atomName == "CZ") { + sp2 = true; + } } else if (resType == "TYR") { - if (atomName == "CG") sp2 = true; - else if (atomName == "CD1") sp2 = true; - else if (atomName == "CD2") sp2 = true; - else if (atomName == "CE1") sp2 = true; - else if (atomName == "CE2") sp2 = true; - else if (atomName == "CZ") sp2 = true; + if (atomName == "CG") { + sp2 = true; + } else if (atomName == "CD1") { + sp2 = true; + } else if (atomName == "CD2") { + sp2 = true; + } else if (atomName == "CE1") { + sp2 = true; + } else if (atomName == "CE2") { + sp2 = true; + } else if (atomName == "CZ") { + sp2 = true; + } } else if (resType == "ASN") { - if (atomName == "CG") sp2 = true; - else if (atomName == "OD1") sp2 = true; + if (atomName == "CG") { + sp2 = true; + } else if (atomName == "OD1") { + sp2 = true; + } } else if (resType == "GLN") { - if (atomName == "CD") sp2 = true; - else if (atomName == "OE1") sp2 = true; + if (atomName == "CD") { + sp2 = true; + } else if (atomName == "OE1") { + sp2 = true; + } } return sp2; } bool CS2Backbone::is_chi1_cx(const std::string & frg, const std::string & atm) { - if(atm=="CG") return true; - if((frg == "CYS")&&(atm =="SG")) return true; - if(((frg == "ILE")||(frg == "VAL"))&&(atm == "CG1")) return true; - if((frg == "SER")&&(atm == "OG")) return true; - if((frg == "THR")&&(atm == "OG1")) return true; + if(atm=="CG") { + return true; + } + if((frg == "CYS")&&(atm =="SG")) { + return true; + } + if(((frg == "ILE")||(frg == "VAL"))&&(atm == "CG1")) { + return true; + } + if((frg == "SER")&&(atm == "OG")) { + return true; + } + if((frg == "THR")&&(atm == "OG1")) { + return true; + } return false; } void CS2Backbone::xdist_name_map(std::string & name) { - if((name == "OT1")||(name == "OC1")) name = "O"; - else if ((name == "HN") || (name == "HT1") || (name == "H1")) name = "H"; - else if ((name == "CG1")|| (name == "OG")|| - (name == "SG") || (name == "OG1")) name = "CG"; - else if ((name == "HA1")|| (name == "HA3")) name = "HA"; + if((name == "OT1")||(name == "OC1")) { + name = "O"; + } else if ((name == "HN") || (name == "HT1") || (name == "H1")) { + name = "H"; + } else if ((name == "CG1")|| (name == "OG")|| + (name == "SG") || (name == "OG1")) { + name = "CG"; + } else if ((name == "HA1")|| (name == "HA3")) { + name = "HA"; + } } void CS2Backbone::update() { // write status file - if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) writeStatus(); + if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) { + writeStatus(); + } } } diff --git a/src/isdb/Caliber.cpp b/src/isdb/Caliber.cpp index 338df29e47..9059ebec34 100644 --- a/src/isdb/Caliber.cpp +++ b/src/isdb/Caliber.cpp @@ -144,20 +144,27 @@ Caliber::Caliber(const ActionOptions&ao): scale_(1), doregres_zero_(false), nregres_zero_(0), - optsigmamean_stride_(0) -{ + optsigmamean_stride_(0) { parse("KAPPA",mult); std::string filename; parse("FILE",filename); - if( filename.length()==0 ) error("No external variable file was specified"); + if( filename.length()==0 ) { + error("No external variable file was specified"); + } unsigned averaging=0; parse("AVERAGING", averaging); - if(averaging>0) optsigmamean_stride_ = averaging; + if(averaging>0) { + optsigmamean_stride_ = averaging; + } double tscale=1.0; parse("TSCALE", tscale); - if(tscale<=0.) error("The time scale factor must be greater than 0."); + if(tscale<=0.) { + error("The time scale factor must be greater than 0."); + } parse("SCALE", scale_); - if(scale_==0.) error("The time scale factor cannot be 0."); + if(scale_==0.) { + error("The time scale factor cannot be 0."); + } // regression with zero intercept parse("REGRES_ZERO", nregres_zero_); if(nregres_zero_>0) { @@ -177,7 +184,9 @@ Caliber::Caliber(const ActionOptions&ao): if(master) { nrep_ = multi_sim_comm.Get_size(); replica_ = multi_sim_comm.Get_rank(); - if(noensemble) nrep_ = 1; + if(noensemble) { + nrep_ = 1; + } } else { nrep_ = 0; replica_ = 0; @@ -188,11 +197,15 @@ Caliber::Caliber(const ActionOptions&ao): const unsigned narg = getNumberOfArguments(); sigma_mean2_.resize(narg,1); sigma_mean2_last_.resize(narg); - for(unsigned j=0; j &mean) -{ +void Caliber::get_sigma_mean(const double fact, const std::vector &mean) { const unsigned narg = getNumberOfArguments(); const double dnrep = static_cast(nrep_); - if(sigma_mean2_last_[0].size()==optsigmamean_stride_) for(unsigned i=0; i sigma_mean2_now(narg,0); if(master) { for(unsigned i=0; i1) multi_sim_comm.Sum(&sigma_mean2_now[0], narg); + if(nrep_>1) { + multi_sim_comm.Sum(&sigma_mean2_now[0], narg); + } } comm.Sum(&sigma_mean2_now[0], narg); @@ -253,35 +281,44 @@ void Caliber::get_sigma_mean(const double fact, const std::vector &mean) } } -void Caliber::replica_averaging(const double fact, std::vector &mean) -{ +void Caliber::replica_averaging(const double fact, std::vector &mean) { const unsigned narg = getNumberOfArguments(); if(master) { - for(unsigned i=0; i1) multi_sim_comm.Sum(&mean[0], narg); + for(unsigned i=0; i1) { + multi_sim_comm.Sum(&mean[0], narg); + } } comm.Sum(&mean[0], narg); } -double Caliber::getSpline(const unsigned iarg) -{ +double Caliber::getSpline(const unsigned iarg) { const double deltat = time[1] - time[0]; const int tindex = static_cast(getTime()/deltat); unsigned start, end; start=tindex; - if(tindex+10.0000001) yy=-dder/grid; + if(std::abs(grid)>0.0000001) { + yy=-dder/grid; + } int x0=1; - if(ipoint==tindex) x0=0; + if(ipoint==tindex) { + x0=0; + } double X=std::abs((getTime()-time[tindex])/deltat-(double)x0); double X2=X*X; @@ -293,8 +330,7 @@ double Caliber::getSpline(const unsigned iarg) return value; } -void Caliber::do_regression_zero(const std::vector &mean) -{ +void Caliber::do_regression_zero(const std::vector &mean) { // parameters[i] = scale_ * mean[i]: find scale_ with linear regression double num = 0.0; double den = 0.0; @@ -309,8 +345,7 @@ void Caliber::do_regression_zero(const std::vector &mean) } } -void Caliber::calculate() -{ +void Caliber::calculate() { const unsigned narg = getNumberOfArguments(); const double dnrep = static_cast(nrep_); const double fact = 1.0/dnrep; @@ -318,10 +353,14 @@ void Caliber::calculate() std::vector mean(narg,0); std::vector dmean_x(narg,fact); replica_averaging(fact, mean); - if(optsigmamean_stride_>0) get_sigma_mean(fact, mean); + if(optsigmamean_stride_>0) { + get_sigma_mean(fact, mean); + } // in case of regression with zero intercept, calculate scale - if(doregres_zero_ && getStep()%nregres_zero_==0) do_regression_zero(mean); + if(doregres_zero_ && getStep()%nregres_zero_==0) { + do_regression_zero(mean); + } double ene=0; for(unsigned i=0; iset(mean[i]); } - if(doregres_zero_) valueScale->set(scale_); + if(doregres_zero_) { + valueScale->set(scale_); + } setBias(ene); } diff --git a/src/isdb/EMMI.cpp b/src/isdb/EMMI.cpp index e79b63c4c7..f9eaf05ed5 100644 --- a/src/isdb/EMMI.cpp +++ b/src/isdb/EMMI.cpp @@ -110,8 +110,7 @@ PRINT ARG=emr.* FILE=COLVAR STRIDE=500 FMT=%20.10f class EMMI : public ActionAtomistic, public ActionWithArguments, - public ActionWithValue -{ + public ActionWithValue { private: // temperature in kbt @@ -293,8 +292,11 @@ void EMMI::setDerivatives() { } // Resize all derivative arrays - forces.resize( nder ); forcesToApply.resize( nder ); - for(int i=0; iresizeDerivatives(nder); + forces.resize( nder ); + forcesToApply.resize( nder ); + for(int i=0; iresizeDerivatives(nder); + } } inline @@ -330,27 +332,39 @@ void EMMI::calculateNumericalDerivatives( ActionWithValue* a=NULL ) { if( getNumberOfAtoms()>0 ) { Matrix save_derivatives( getNumberOfComponents(), getNumberOfArguments() ); for(int j=0; jhasDerivatives()) save_derivatives(j,i)=getPntrToComponent(j)->getDerivative(i); + for(unsigned i=0; ihasDerivatives()) { + save_derivatives(j,i)=getPntrToComponent(j)->getDerivative(i); + } } calculateAtomicNumericalDerivatives( a, getNumberOfArguments() ); for(int j=0; jhasDerivatives()) getPntrToComponent(j)->addDerivative( i, save_derivatives(j,i) ); + for(unsigned i=0; ihasDerivatives()) { + getPntrToComponent(j)->addDerivative( i, save_derivatives(j,i) ); + } } } } inline void EMMI::apply() { - bool wasforced=false; forcesToApply.assign(forcesToApply.size(),0.0); + bool wasforced=false; + forcesToApply.assign(forcesToApply.size(),0.0); for(int i=0; iapplyForce( forces ) ) { wasforced=true; - for(unsigned i=0; i0 ) setForcesOnAtoms( forcesToApply, ind ); + unsigned ind=0; + addForcesOnArguments( 0, forcesToApply, ind, getLabel() ); + if( getNumberOfAtoms()>0 ) { + setForcesOnAtoms( forcesToApply, ind ); + } } } @@ -445,8 +459,7 @@ EMMI::EMMI(const ActionOptions&ao): nregres_(0), scale_(1.), dpcutoff_(15.0), nexp_(1000000), nanneal_(0), kanneal_(0.), anneal_(1.), prior_(1.), ovstride_(0), - do_reweight_(false), first_time_w_(true), decay_w_(1.) -{ + do_reweight_(false), first_time_w_(true), decay_w_(1.) { // periodic boundary conditions bool nopbc=!pbc_; parseFlag("NOPBC",nopbc); @@ -463,33 +476,51 @@ EMMI::EMMI(const ActionOptions&ao): // type of data noise std::string noise; parse("NOISETYPE",noise); - if (noise=="GAUSS") noise_ = 0; - else if(noise=="OUTLIERS") noise_ = 1; - else if(noise=="MARGINAL") noise_ = 2; - else error("Unknown noise type!"); + if (noise=="GAUSS") { + noise_ = 0; + } else if(noise=="OUTLIERS") { + noise_ = 1; + } else if(noise=="MARGINAL") { + noise_ = 2; + } else { + error("Unknown noise type!"); + } // minimum value for error double sigma_min; parse("SIGMA_MIN", sigma_min); - if(sigma_min<0) error("SIGMA_MIN should be greater or equal to zero"); + if(sigma_min<0) { + error("SIGMA_MIN should be greater or equal to zero"); + } // the following parameters must be specified with noise type 0 and 1 double sigma_ini, dsigma; if(noise_!=2) { // initial value of the uncertainty parse("SIGMA0", sigma_ini); - if(sigma_ini<=0) error("you must specify a positive SIGMA0"); + if(sigma_ini<=0) { + error("you must specify a positive SIGMA0"); + } // MC parameters parse("DSIGMA", dsigma); - if(dsigma<0) error("you must specify a positive DSIGMA"); + if(dsigma<0) { + error("you must specify a positive DSIGMA"); + } parse("MC_STRIDE", MCstride_); - if(dsigma>0 && MCstride_<=0) error("you must specify a positive MC_STRIDE"); + if(dsigma>0 && MCstride_<=0) { + error("you must specify a positive MC_STRIDE"); + } // status file parameters parse("WRITE_STRIDE", statusstride_); - if(statusstride_==0) error("you must specify a positive WRITE_STRIDE"); + if(statusstride_==0) { + error("you must specify a positive WRITE_STRIDE"); + } parse("STATUS_FILE", statusfilename_); - if(statusfilename_=="") statusfilename_ = "MISTATUS"+getLabel(); - else statusfilename_ = statusfilename_+getLabel(); + if(statusfilename_=="") { + statusfilename_ = "MISTATUS"+getLabel(); + } else { + statusfilename_ = statusfilename_+getLabel(); + } } // error file @@ -513,7 +544,9 @@ EMMI::EMMI(const ActionOptions&ao): // simulated annealing stuff parse("ANNEAL", nanneal_); parse("ANNEAL_FACT", kanneal_); - if(nanneal_>0 && kanneal_<=1.0) error("with ANNEAL, ANNEAL_FACT must be greater than 1"); + if(nanneal_>0 && kanneal_<=1.0) { + error("with ANNEAL, ANNEAL_FACT must be greater than 1"); + } // regression stride parse("REGRESSION",nregres_); @@ -523,8 +556,12 @@ EMMI::EMMI(const ActionOptions&ao): parse("REG_SCALE_MAX",scale_max_); parse("REG_DSCALE",dscale_); // checks - if(scale_max_<=scale_min_) error("with REGRESSION, REG_SCALE_MAX must be greater than REG_SCALE_MIN"); - if(dscale_<=0.) error("with REGRESSION, REG_DSCALE must be positive"); + if(scale_max_<=scale_min_) { + error("with REGRESSION, REG_SCALE_MAX must be greater than REG_SCALE_MIN"); + } + if(dscale_<=0.) { + error("with REGRESSION, REG_DSCALE must be positive"); + } } // scale factor @@ -533,13 +570,19 @@ EMMI::EMMI(const ActionOptions&ao): // read map resolution double reso; parse("RESOLUTION", reso); - if(reso<=0.) error("RESOLUTION should be strictly positive"); + if(reso<=0.) { + error("RESOLUTION should be strictly positive"); + } // neighbor list stuff parse("NL_CUTOFF",nl_cutoff_); - if(nl_cutoff_<=0.0) error("NL_CUTOFF should be explicitly specified and positive"); + if(nl_cutoff_<=0.0) { + error("NL_CUTOFF should be explicitly specified and positive"); + } parse("NL_STRIDE",nl_stride_); - if(nl_stride_==0) error("NL_STRIDE should be explicitly specified and positive"); + if(nl_stride_==0) { + error("NL_STRIDE should be explicitly specified and positive"); + } // averaging or not parseFlag("NO_AVER",no_aver_); @@ -547,7 +590,9 @@ EMMI::EMMI(const ActionOptions&ao): // write overlap file parse("WRITE_OV_STRIDE", ovstride_); parse("WRITE_OV", ovfilename_); - if(ovstride_>0 && ovfilename_=="") error("With WRITE_OV_STRIDE you must specify WRITE_OV"); + if(ovstride_>0 && ovfilename_=="") { + error("With WRITE_OV_STRIDE you must specify WRITE_OV"); + } // set parallel stuff size_=comm.Get_size(); @@ -570,11 +615,20 @@ EMMI::EMMI(const ActionOptions&ao): // Reweighting flag parseFlag("REWEIGHT", do_reweight_); - if(do_reweight_&&getNumberOfArguments()!=1) error("To REWEIGHT one must provide one single bias as an argument"); - if(do_reweight_&&no_aver_) error("REWEIGHT cannot be used with NO_AVER"); - if(do_reweight_&&nrep_<2) error("REWEIGHT can only be used in parallel with 2 or more replicas"); - if(!getRestart()) average_weights_.resize(nrep_, 1./static_cast(nrep_)); - else average_weights_.resize(nrep_, 0.); + if(do_reweight_&&getNumberOfArguments()!=1) { + error("To REWEIGHT one must provide one single bias as an argument"); + } + if(do_reweight_&&no_aver_) { + error("REWEIGHT cannot be used with NO_AVER"); + } + if(do_reweight_&&nrep_<2) { + error("REWEIGHT can only be used in parallel with 2 or more replicas"); + } + if(!getRestart()) { + average_weights_.resize(nrep_, 1./static_cast(nrep_)); + } else { + average_weights_.resize(nrep_, 0.); + } unsigned averaging=0; parse("AVERAGING", averaging); @@ -585,10 +639,14 @@ EMMI::EMMI(const ActionOptions&ao): checkRead(); log.printf(" atoms involved : "); - for(unsigned i=0; i0) log.printf(" reading experimental errors from file : %s\n", errfile.c_str()); - if(ovfile.size()>0) log.printf(" reading experimental overlaps from file : %s\n", ovfile.c_str()); + if(errfile.size()>0) { + log.printf(" reading experimental errors from file : %s\n", errfile.c_str()); + } + if(ovfile.size()>0) { + log.printf(" reading experimental overlaps from file : %s\n", ovfile.c_str()); + } log.printf(" temperature of the system in energy unit : %f\n",kbt_); log.printf(" prior exponent : %f\n",prior_); log.printf(" number of replicas for averaging: %u\n",nrep_); @@ -633,14 +695,20 @@ EMMI::EMMI(const ActionOptions&ao): log.printf(" number of GMM components : %u\n", static_cast(GMM_d_m_.size())); // normalize atom weight map - if(norm_d <= 0.0) norm_d = accumulate(GMM_d_w_.begin(), GMM_d_w_.end(), 0.0); + if(norm_d <= 0.0) { + norm_d = accumulate(GMM_d_w_.begin(), GMM_d_w_.end(), 0.0); + } double norm_m = accumulate(GMM_m_w.begin(), GMM_m_w.end(), 0.0); // renormalization - for(unsigned i=0; i exp_err; - if(errfile.size()>0) exp_err = read_exp_errors(errfile); + if(errfile.size()>0) { + exp_err = read_exp_errors(errfile); + } // get self overlaps between data GMM components if(ovfile.size()>0) { @@ -664,8 +732,11 @@ EMMI::EMMI(const ActionOptions&ao): // GMM id int GMMid = GMM_d_grps_[Gid][i]; // add to experimental error - if(errfile.size()>0) err.push_back(exp_err[GMMid]); - else err.push_back(0.); + if(errfile.size()>0) { + err.push_back(exp_err[GMMid]); + } else { + err.push_back(0.); + } // add to GMM overlap ovdd.push_back(ovdd_[GMMid]); } @@ -690,7 +761,9 @@ EMMI::EMMI(const ActionOptions&ao): } // read status file if restarting - if(getRestart() && noise_!=2) read_status(); + if(getRestart() && noise_!=2) { + read_status(); + } // calculate auxiliary stuff calculate_useful_stuff(reso); @@ -705,17 +778,27 @@ EMMI::EMMI(const ActionOptions&ao): GMM_d_cov_.clear(); // add components - addComponentWithDerivatives("scoreb"); componentIsNotPeriodic("scoreb"); + addComponentWithDerivatives("scoreb"); + componentIsNotPeriodic("scoreb"); - if(noise_!=2) {addComponent("acc"); componentIsNotPeriodic("acc");} + if(noise_!=2) { + addComponent("acc"); + componentIsNotPeriodic("acc"); + } if(nregres_>0) { - addComponent("scale"); componentIsNotPeriodic("scale"); - addComponent("accscale"); componentIsNotPeriodic("accscale"); - addComponent("enescale"); componentIsNotPeriodic("enescale"); + addComponent("scale"); + componentIsNotPeriodic("scale"); + addComponent("accscale"); + componentIsNotPeriodic("accscale"); + addComponent("enescale"); + componentIsNotPeriodic("enescale"); } - if(nanneal_>0) {addComponent("anneal"); componentIsNotPeriodic("anneal");} + if(nanneal_>0) { + addComponent("anneal"); + componentIsNotPeriodic("anneal"); + } if(do_reweight_) { addComponent("biasDer"); @@ -728,15 +811,20 @@ EMMI::EMMI(const ActionOptions&ao): componentIsNotPeriodic("neff"); for(unsigned i=0; iset(sigma_[i]); } // initialize random seed unsigned iseed; - if(rank_==0) iseed = time(NULL)+replica_; - else iseed = 0; + if(rank_==0) { + iseed = time(NULL)+replica_; + } else { + iseed = 0; + } comm.Sum(&iseed, 1); random_.setSeed(-iseed); @@ -748,16 +836,20 @@ EMMI::EMMI(const ActionOptions&ao): log<<" Bibliography "<1)log<1) { + log< &v) -{ +double EMMI::get_median(std::vector &v) { // dimension of std::vector unsigned size = v.size(); // in case of only one entry @@ -791,8 +882,7 @@ double EMMI::get_median(std::vector &v) } } -void EMMI::read_status() -{ +void EMMI::read_status() { double MDtime; // open file auto ifile = Tools::make_unique(); @@ -802,7 +892,8 @@ void EMMI::read_status() while(ifile->scanField("MD_time", MDtime)) { for(unsigned i=0; iscanField("s"+num, sigma_[i]); } @@ -815,8 +906,7 @@ void EMMI::read_status() } } -void EMMI::print_status(long long int step) -{ +void EMMI::print_status(long long int step) { // if first time open the file if(first_status_) { first_status_ = false; @@ -830,7 +920,8 @@ void EMMI::print_status(long long int step) statusfile_.printField("MD_time", MDtime); for(unsigned i=0; i(std::floor(random_.RandU01()*static_cast(GMM_d_grps_.size()))); - if(nGMM==GMM_d_grps_.size()) nGMM -= 1; + if(nGMM==GMM_d_grps_.size()) { + nGMM -= 1; + } // generate random move double shift = dsigma_[nGMM] * ( 2.0 * random_.RandU01() - 1.0 ); // new sigma double new_s = sigma_[nGMM] + shift; // check boundaries - if(new_s > sigma_max_[nGMM]) {new_s = 2.0 * sigma_max_[nGMM] - new_s;} - if(new_s < sigma_min_[nGMM]) {new_s = 2.0 * sigma_min_[nGMM] - new_s;} + if(new_s > sigma_max_[nGMM]) { + new_s = 2.0 * sigma_max_[nGMM] - new_s; + } + if(new_s < sigma_min_[nGMM]) { + new_s = 2.0 * sigma_min_[nGMM] - new_s; + } // old s2 double old_inv_s2 = 1.0 / sigma_[nGMM] / sigma_[nGMM]; // new s2 @@ -918,7 +1016,9 @@ void EMMI::doMonteCarlo() } // local communication if(rank_!=0) { - for(unsigned i=0; i1) { @@ -927,12 +1027,12 @@ void EMMI::doMonteCarlo() } // update sigma output - std::string num; Tools::convert(nGMM, num); + std::string num; + Tools::convert(nGMM, num); getPntrToComponent("sigma-"+num)->set(sigma_[nGMM]); } -std::vector EMMI::read_exp_errors(const std::string & errfile) -{ +std::vector EMMI::read_exp_errors(const std::string & errfile) { int nexp, idcomp; double err; std::vector exp_err; @@ -948,7 +1048,8 @@ std::vector EMMI::read_exp_errors(const std::string & errfile) double err_tot = 0.0; // cycle on number of experimental overlaps for(unsigned i=0; iscanField("Err"+ss, err); // add to total error err_tot += err*err; @@ -967,8 +1068,7 @@ std::vector EMMI::read_exp_errors(const std::string & errfile) return exp_err; } -std::vector EMMI::read_exp_overlaps(const std::string & ovfile) -{ +std::vector EMMI::read_exp_overlaps(const std::string & ovfile) { int idcomp; double ov; std::vector ovdd; @@ -992,8 +1092,7 @@ std::vector EMMI::read_exp_overlaps(const std::string & ovfile) return ovdd; } -std::vector EMMI::get_GMM_m(std::vector &atoms) -{ +std::vector EMMI::get_GMM_m(std::vector &atoms) { // list of weights - one per atom std::vector GMM_m_w; @@ -1051,24 +1150,25 @@ std::vector EMMI::get_GMM_m(std::vector &atoms) return GMM_m_w; } -void EMMI::check_GMM_d(const VectorGeneric<6> &cov, double w) -{ +void EMMI::check_GMM_d(const VectorGeneric<6> &cov, double w) { // check if positive defined, by calculating the 3 leading principal minors double pm1 = cov[0]; double pm2 = cov[0]*cov[3]-cov[1]*cov[1]; double pm3 = cov[0]*(cov[3]*cov[5]-cov[4]*cov[4])-cov[1]*(cov[1]*cov[5]-cov[4]*cov[2])+cov[2]*(cov[1]*cov[4]-cov[3]*cov[2]); // apply Sylvester’s criterion - if(pm1<=0.0 || pm2<=0.0 || pm3<=0.0) + if(pm1<=0.0 || pm2<=0.0 || pm3<=0.0) { error("check data GMM: covariance matrix is not positive defined"); + } // check if weight is positive - if(w<=0) error("check data GMM: weight must be positive"); + if(w<=0) { + error("check data GMM: weight must be positive"); + } } // read GMM data file in PLUMED format: -void EMMI::get_GMM_d(const std::string & GMM_file) -{ +void EMMI::get_GMM_d(const std::string & GMM_file) { VectorGeneric<6> cov; // open file @@ -1093,7 +1193,9 @@ void EMMI::get_GMM_d(const std::string & GMM_file) // check input check_GMM_d(cov, w); // check beta - if(beta<0) error("Beta must be positive!"); + if(beta<0) { + error("Beta must be positive!"); + } // center of the Gaussian GMM_d_m_.push_back(Vector(m0,m1,m2)); // covariance matrix @@ -1114,13 +1216,14 @@ void EMMI::get_GMM_d(const std::string & GMM_file) GMM_d_grps_.resize(bu.size()); // and fill it in for(unsigned i=0; i=GMM_d_grps_.size()) error("Check Beta values"); + if(GMM_d_beta_[i]>=GMM_d_grps_.size()) { + error("Check Beta values"); + } GMM_d_grps_[GMM_d_beta_[i]].push_back(i); } } -void EMMI::calculate_useful_stuff(double reso) -{ +void EMMI::calculate_useful_stuff(double reso) { // We use the following definition for resolution: // the Fourier transform of the density distribution in real space // f(s) falls to 1/e of its maximum value at wavenumber 1/resolution @@ -1133,10 +1236,15 @@ void EMMI::calculate_useful_stuff(double reso) Bave /= static_cast(GMM_m_type_.size()); // calculate blur factor double blur = 0.0; - if(reso*reso>Bave) blur = reso*reso-Bave; - else warning("PLUMED should not be used with maps at resolution better than 0.3 nm"); + if(reso*reso>Bave) { + blur = reso*reso-Bave; + } else { + warning("PLUMED should not be used with maps at resolution better than 0.3 nm"); + } // add blur to B - for(unsigned i=0; i &GMM_cov_0, const VectorGeneric<6> &GMM_cov_1, double GMM_w_0, double GMM_w_1, - VectorGeneric<6> &sum, VectorGeneric<6> &inv_sum) -{ + VectorGeneric<6> &sum, VectorGeneric<6> &inv_sum) { // we need the sum of the covariance matrices - for(unsigned k=0; k<6; ++k) sum[k] = GMM_cov_0[k] + GMM_cov_1[k]; + for(unsigned k=0; k<6; ++k) { + sum[k] = GMM_cov_0[k] + GMM_cov_1[k]; + } // and to calculate its determinant double det = sum[0]*(sum[3]*sum[5]-sum[4]*sum[4]); @@ -1216,8 +1330,7 @@ double EMMI::get_prefactor_inverse return pre_fact; } -double EMMI::get_self_overlap(unsigned id) -{ +double EMMI::get_self_overlap(unsigned id) { double ov_tot = 0.0; VectorGeneric<6> sum, inv_sum; Vector ov_der; @@ -1235,12 +1348,14 @@ double EMMI::get_self_overlap(unsigned id) // get overlap and derivatives double EMMI::get_overlap(const Vector &m_m, const Vector &d_m, double pre_fact, - const VectorGeneric<6> &inv_cov_md, Vector &ov_der) -{ + const VectorGeneric<6> &inv_cov_md, Vector &ov_der) { Vector md; // calculate std::vector difference m_m-d_m with/without pbc - if(pbc_) md = pbcDistance(d_m, m_m); - else md = delta(d_m, m_m); + if(pbc_) { + md = pbcDistance(d_m, m_m); + } else { + md = delta(d_m, m_m); + } // calculate product of transpose of md and inv_cov_md double p_x = md[0]*inv_cov_md[0]+md[1]*inv_cov_md[1]+md[2]*inv_cov_md[2]; double p_y = md[0]*inv_cov_md[1]+md[1]*inv_cov_md[3]+md[2]*inv_cov_md[4]; @@ -1256,12 +1371,14 @@ double EMMI::get_overlap(const Vector &m_m, const Vector &d_m, double pre_fact, // get the exponent of the overlap double EMMI::get_exp_overlap(const Vector &m_m, const Vector &d_m, - const VectorGeneric<6> &inv_cov_md) -{ + const VectorGeneric<6> &inv_cov_md) { Vector md; // calculate std::vector difference m_m-d_m with/without pbc - if(pbc_) md = pbcDistance(d_m, m_m); - else md = delta(d_m, m_m); + if(pbc_) { + md = pbcDistance(d_m, m_m); + } else { + md = delta(d_m, m_m); + } // calculate product of transpose of md and inv_cov_md double p_x = md[0]*inv_cov_md[0]+md[1]*inv_cov_md[1]+md[2]*inv_cov_md[2]; double p_y = md[0]*inv_cov_md[1]+md[1]*inv_cov_md[3]+md[2]*inv_cov_md[4]; @@ -1271,8 +1388,7 @@ double EMMI::get_exp_overlap(const Vector &m_m, const Vector &d_m, return ov; } -void EMMI::update_neighbor_list() -{ +void EMMI::update_neighbor_list() { // dimension of GMM and atom std::vectors unsigned GMM_d_size = GMM_d_m_.size(); unsigned GMM_m_size = GMM_m_type_.size(); @@ -1297,7 +1413,9 @@ void EMMI::update_neighbor_list() // get index of 0.5*expov in tabulated exponential unsigned itab = static_cast (round( 0.5*expov/dexp_ )); // check boundaries and skip atom in case - if(itab >= tab_exp_.size()) continue; + if(itab >= tab_exp_.size()) { + continue; + } // in case calculate overlap double ov = pre_fact_[kaux] * tab_exp_[itab]; // add to list @@ -1308,7 +1426,9 @@ void EMMI::update_neighbor_list() ov_tot += ov; } // check if zero size -> ov_tot = 0 - if(ov_l.size()==0) continue; + if(ov_l.size()==0) { + continue; + } // define cutoff double ov_cut = ov_tot * nl_cutoff_; // sort ov_l in ascending order @@ -1318,12 +1438,16 @@ void EMMI::update_neighbor_list() for(unsigned i=0; i= ov_cut) break; - else ov_m.erase(ov_l[i]); + if(res >= ov_cut) { + break; + } else { + ov_m.erase(ov_l[i]); + } } // now add atoms to neighborlist - for(std::map::iterator it=ov_m.begin(); it!=ov_m.end(); ++it) + for(std::map::iterator it=ov_m.begin(); it!=ov_m.end(); ++it) { nl_l.push_back(id*GMM_m_size+it->second); + } // end cycle on GMM components in parallel } // find total dimension of neighborlist @@ -1347,9 +1471,10 @@ void EMMI::update_neighbor_list() ovmd_der_.resize(tot_size); } -void EMMI::prepare() -{ - if(getExchangeStep()) first_time_=true; +void EMMI::prepare() { + if(getExchangeStep()) { + first_time_=true; + } } // overlap calculator @@ -1361,8 +1486,12 @@ void EMMI::calculate_overlap() { } // clean temporary std::vectors - for(unsigned i=0; i scale_max_) {new_scale = 2.0 * scale_max_ - new_scale;} - if(new_scale < scale_min_) {new_scale = 2.0 * scale_min_ - new_scale;} + if(new_scale > scale_max_) { + new_scale = 2.0 * scale_max_ - new_scale; + } + if(new_scale < scale_min_) { + new_scale = 2.0 * scale_min_ - new_scale; + } // new energy double new_ene = scaleEnergy(new_scale); // accept or reject @@ -1470,8 +1604,7 @@ double EMMI::doRegression() return scale_best; } -double EMMI::get_annealing(long long int step) -{ +double EMMI::get_annealing(long long int step) { // default no annealing double fact = 1.0; // position in annealing cycle @@ -1480,21 +1613,28 @@ double EMMI::get_annealing(long long int step) double ncd = static_cast(nc); double nn = static_cast(nanneal_); // set fact - if(nc>=nanneal_ && nc<2*nanneal_) fact = (kanneal_-1.0) / nn * ( ncd - nn ) + 1.0; - if(nc>=2*nanneal_ && nc<3*nanneal_) fact = kanneal_; - if(nc>=3*nanneal_) fact = (1.0-kanneal_) / nn * ( ncd - 3.0*nn) + kanneal_; + if(nc>=nanneal_ && nc<2*nanneal_) { + fact = (kanneal_-1.0) / nn * ( ncd - nn ) + 1.0; + } + if(nc>=2*nanneal_ && nc<3*nanneal_) { + fact = kanneal_; + } + if(nc>=3*nanneal_) { + fact = (1.0-kanneal_) / nn * ( ncd - 3.0*nn) + kanneal_; + } return fact; } -void EMMI::get_weights(double &weight, double &norm, double &neff) -{ +void EMMI::get_weights(double &weight, double &norm, double &neff) { const double dnrep = static_cast(nrep_); // calculate the weights either from BIAS if(do_reweight_) { std::vector bias(nrep_,0); if(rank_==0) { bias[replica_] = getArgument(0); - if(nrep_>1) multi_sim_comm.Sum(&bias[0], nrep_); + if(nrep_>1) { + multi_sim_comm.Sum(&bias[0], nrep_); + } } comm.Sum(&bias[0], nrep_); @@ -1509,12 +1649,16 @@ void EMMI::get_weights(double &weight, double &norm, double &neff) } } else { first_time_w_ = false; - for(unsigned i=0; iset(neff); } -void EMMI::calculate() -{ +void EMMI::calculate() { // calculate CV calculate_overlap(); @@ -1549,15 +1692,23 @@ void EMMI::calculate() if(!no_aver_ && nrep_>1) { // if master node, calculate average across replicas if(rank_==0) { - for(unsigned i=0; i1) comm.Sum(&ovmd_ave_[0], ovmd_ave_.size()); + if(size_>1) { + comm.Sum(&ovmd_ave_[0], ovmd_ave_.size()); + } } else { - for(unsigned i=0; i0) { - if(step%nregres_==0 && !getExchangeStep()) scale_ = doRegression(); + if(step%nregres_==0 && !getExchangeStep()) { + scale_ = doRegression(); + } // set scale component getPntrToComponent("scale")->set(scale_); } // write model overlap to file - if(ovstride_>0 && step%ovstride_==0) write_model_overlap(step); + if(ovstride_>0 && step%ovstride_==0) { + write_model_overlap(step); + } // clear energy and virial ene_ = 0.0; virial_.zero(); // Gaussian noise - if(noise_==0) calculate_Gauss(); + if(noise_==0) { + calculate_Gauss(); + } // Outliers noise - if(noise_==1) calculate_Outliers(); + if(noise_==1) { + calculate_Outliers(); + } // Marginal noise - if(noise_==2) calculate_Marginal(); + if(noise_==2) { + calculate_Marginal(); + } // get annealing rescale factor if(nanneal_>0) { @@ -1607,7 +1768,9 @@ void EMMI::calculate() multi_sim_comm.Sum(&ene_, 1); } else { // set der_GMMid derivatives and energy to zero - for(unsigned i=0; iset(ene_); @@ -1665,10 +1835,14 @@ void EMMI::calculate() if(noise_!=2) { // do Montecarlo - if(dsigma_[0]>0 && step%MCstride_==0 && !getExchangeStep()) doMonteCarlo(); + if(dsigma_[0]>0 && step%MCstride_==0 && !getExchangeStep()) { + doMonteCarlo(); + } // print status - if(step%statusstride_==0) print_status(step); + if(step%statusstride_==0) { + print_status(step); + } // calculate acceptance ratio double acc = MCaccept_ / MCtrials_; @@ -1680,8 +1854,7 @@ void EMMI::calculate() } -void EMMI::calculate_Gauss() -{ +void EMMI::calculate_Gauss() { // cycle on all the GMM groups for(unsigned i=0; i0 && mapfilename_=="") error("With WRITE_MAP_STRIDE you must specify WRITE_MAP"); + if(mapstride_>0 && mapfilename_=="") { + error("With WRITE_MAP_STRIDE you must specify WRITE_MAP"); + } // use GPU? parseFlag("GPU",gpu_); @@ -369,7 +394,9 @@ EMMIVOX::EMMIVOX(const ActionOptions&ao): // set parallel stuff unsigned mpisize=comm.Get_size(); - if(mpisize>1) error("EMMIVOX supports only OpenMP parallelization"); + if(mpisize>1) { + error("EMMIVOX supports only OpenMP parallelization"); + } // get number of replicas if(no_aver_) { @@ -379,15 +406,26 @@ EMMIVOX::EMMIVOX(const ActionOptions&ao): } replica_ = multi_sim_comm.Get_rank(); - if(nrep_>1 && dbfact_>0) error("Bfactor sampling not supported with ensemble averaging"); + if(nrep_>1 && dbfact_>0) { + error("Bfactor sampling not supported with ensemble averaging"); + } log.printf(" number of atoms involved : %u\n", atoms.size()); log.printf(" experimental density map : %s\n", datafile.c_str()); - if(no_aver_) log.printf(" without ensemble averaging\n"); - if(gpu_) {log.printf(" running on GPU \n");} - else {log.printf(" running on CPU \n");} - if(nl_dist_cutoff_ <1.0e+10) log.printf(" neighbor list distance cutoff : %lf\n", nl_dist_cutoff_); - if(nl_gauss_cutoff_<1.0e+10) log.printf(" neighbor list Gaussian sigma cutoff : %lf\n", nl_gauss_cutoff_); + if(no_aver_) { + log.printf(" without ensemble averaging\n"); + } + if(gpu_) { + log.printf(" running on GPU \n"); + } else { + log.printf(" running on CPU \n"); + } + if(nl_dist_cutoff_ <1.0e+10) { + log.printf(" neighbor list distance cutoff : %lf\n", nl_dist_cutoff_); + } + if(nl_gauss_cutoff_<1.0e+10) { + log.printf(" neighbor list Gaussian sigma cutoff : %lf\n", nl_gauss_cutoff_); + } log.printf(" neighbor list update stride : %u\n", nl_stride_); log.printf(" minimum density error : %f\n", sigma_min); log.printf(" scale factor : %lf\n", scale_); @@ -399,7 +437,9 @@ EMMIVOX::EMMIVOX(const ActionOptions&ao): log.printf(" stride MC move : %u\n", MCBstride_); log.printf(" using prior with sigma : %f\n", bfactsig_); } - if(bfactread_) log.printf(" reading Bfactors from file : %s\n", statusfilename_.c_str()); + if(bfactread_) { + log.printf(" reading Bfactors from file : %s\n", statusfilename_.c_str()); + } log.printf(" temperature of the system in energy unit : %f\n", kbt_); if(nrep_>1) { log.printf(" number of replicas for averaging: %u\n", nrep_); @@ -409,7 +449,9 @@ EMMIVOX::EMMIVOX(const ActionOptions&ao): log.printf(" writing model density to file : %s\n", mapfilename_.c_str()); log.printf(" with stride : %u\n", mapstride_); } - if(martini_) log.printf(" using Martini scattering factors\n"); + if(martini_) { + log.printf(" using Martini scattering factors\n"); + } // calculate model constant parameters std::vector Model_w = get_Model_param(atoms); @@ -455,7 +497,9 @@ EMMIVOX::EMMIVOX(const ActionOptions&ao): initialize_Bfactor(reso); // read status file if restarting - if(getRestart() || bfactread_) read_status(); + if(getRestart() || bfactread_) { + read_status(); + } // prepare auxiliary vectors get_auxiliary_vectors(); @@ -466,12 +510,22 @@ EMMIVOX::EMMIVOX(const ActionOptions&ao): score_der_.resize(ovdd_.size()); // add components - addComponentWithDerivatives("scoreb"); componentIsNotPeriodic("scoreb"); - addComponent("scale"); componentIsNotPeriodic("scale"); - addComponent("offset"); componentIsNotPeriodic("offset"); - addComponent("kbt"); componentIsNotPeriodic("kbt"); - if(dbfact_>0) {addComponent("accB"); componentIsNotPeriodic("accB");} - if(do_corr_) {addComponent("corr"); componentIsNotPeriodic("corr");} + addComponentWithDerivatives("scoreb"); + componentIsNotPeriodic("scoreb"); + addComponent("scale"); + componentIsNotPeriodic("scale"); + addComponent("offset"); + componentIsNotPeriodic("offset"); + addComponent("kbt"); + componentIsNotPeriodic("kbt"); + if(dbfact_>0) { + addComponent("accB"); + componentIsNotPeriodic("accB"); + } + if(do_corr_) { + addComponent("corr"); + componentIsNotPeriodic("corr"); + } // initialize random seed unsigned iseed = time(NULL)+replica_; @@ -483,12 +537,13 @@ EMMIVOX::EMMIVOX(const ActionOptions&ao): // print bibliography log<<" Bibliography "<1)log<1) { + log< v) -{ +double EMMIVOX::get_median(std::vector v) { // dimension of vector unsigned size = v.size(); // in case of only one entry @@ -545,8 +599,7 @@ double EMMIVOX::get_median(std::vector v) } } -void EMMIVOX::read_status() -{ +void EMMIVOX::read_status() { double MDtime; // open file IFile *ifile = new IFile(); @@ -564,10 +617,13 @@ void EMMIVOX::read_status() // key: pair of residue/chain IDs std::pair key = Model_rlist_[ir]; // convert ires to std::string - std::string num; Tools::convert(key.first,num); + std::string num; + Tools::convert(key.first,num); // read entry std::string ch = key.second; - if(ch==" ") ch=""; + if(ch==" ") { + ch=""; + } ifile->scanField("bf-"+num+":"+ch, Model_b_[key]); } } @@ -581,8 +637,7 @@ void EMMIVOX::read_status() delete ifile; } -void EMMIVOX::print_status(long int step) -{ +void EMMIVOX::print_status(long int step) { // if first time open the file if(first_status_) { first_status_ = false; @@ -606,7 +661,8 @@ void EMMIVOX::print_status(long int step) // bfactor from map double bf = Model_b_[key]; // convert ires to std::string - std::string num; Tools::convert(key.first,num); + std::string num; + Tools::convert(key.first,num); // print entry statusfile_.printField("bf-"+num+":"+key.second, bf); } @@ -614,8 +670,7 @@ void EMMIVOX::print_status(long int step) statusfile_.printField(); } -bool EMMIVOX::doAccept(double oldE, double newE, double kbt) -{ +bool EMMIVOX::doAccept(double oldE, double newE, double kbt) { bool accept = false; // calculate delta energy double delta = ( newE - oldE ) / kbt; @@ -625,16 +680,19 @@ bool EMMIVOX::doAccept(double oldE, double newE, double kbt) } else { // otherwise extract random number double s = random_.RandU01(); - if( s < exp(-delta) ) { accept = true; } + if( s < exp(-delta) ) { + accept = true; + } } return accept; } -std::vector EMMIVOX::get_Model_param(std::vector &atoms) -{ +std::vector EMMIVOX::get_Model_param(std::vector &atoms) { // check if MOLINFO line is present auto* moldat=plumed.getActionSet().selectLatest(this); - if(!moldat) error("MOLINFO DATA not found\n"); + if(!moldat) { + error("MOLINFO DATA not found\n"); + } log<<" MOLINFO DATA found with label " <getLabel()<<", using proper atom names\n"; // list of weights - one per atom @@ -648,28 +706,70 @@ std::vector EMMIVOX::get_Model_param(std::vector &atoms) // map between an atom type and an index std::map type_map; // atomistic types - type_map["C"]=0; type_map["O"]=1; type_map["N"]=2; - type_map["S"]=3; type_map["P"]=4; type_map["F"]=5; - type_map["NA"]=6; type_map["MG"]=7; type_map["CL"]=8; - type_map["CA"]=9; type_map["K"]=10; type_map["ZN"]=11; + type_map["C"]=0; + type_map["O"]=1; + type_map["N"]=2; + type_map["S"]=3; + type_map["P"]=4; + type_map["F"]=5; + type_map["NA"]=6; + type_map["MG"]=7; + type_map["CL"]=8; + type_map["CA"]=9; + type_map["K"]=10; + type_map["ZN"]=11; // Martini types - type_map["ALA_BB"]=12; type_map["ALA_SC1"]=13; type_map["CYS_BB"]=14; - type_map["CYS_SC1"]=15; type_map["ASP_BB"]=16; type_map["ASP_SC1"]=17; - type_map["GLU_BB"]=18; type_map["GLU_SC1"]=19; type_map["PHE_BB"]=20; - type_map["PHE_SC1"]=21; type_map["PHE_SC2"]=22; type_map["PHE_SC3"]=23; - type_map["GLY_BB"]=24; type_map["HIS_BB"]=25; type_map["HIS_SC1"]=26; - type_map["HIS_SC2"]=27; type_map["HIS_SC3"]=28; type_map["ILE_BB"]=29; - type_map["ILE_SC1"]=30; type_map["LYS_BB"]=31; type_map["LYS_SC1"]=32; - type_map["LYS_SC2"]=33; type_map["LEU_BB"]=34; type_map["LEU_SC1"]=35; - type_map["MET_BB"]=36; type_map["MET_SC1"]=37; type_map["ASN_BB"]=38; - type_map["ASN_SC1"]=39; type_map["PRO_BB"]=40; type_map["PRO_SC1"]=41; - type_map["GLN_BB"]=42; type_map["GLN_SC1"]=43; type_map["ARG_BB"]=44; - type_map["ARG_SC1"]=45; type_map["ARG_SC2"]=46; type_map["SER_BB"]=47; - type_map["SER_SC1"]=48; type_map["THR_BB"]=49; type_map["THR_SC1"]=50; - type_map["VAL_BB"]=51; type_map["VAL_SC1"]=52; type_map["TRP_BB"]=53; - type_map["TRP_SC1"]=54; type_map["TRP_SC2"]=55; type_map["TRP_SC3"]=56; - type_map["TRP_SC4"]=57; type_map["TRP_SC5"]=58; type_map["TYR_BB"]=59; - type_map["TYR_SC1"]=60; type_map["TYR_SC2"]=61; type_map["TYR_SC3"]=62; + type_map["ALA_BB"]=12; + type_map["ALA_SC1"]=13; + type_map["CYS_BB"]=14; + type_map["CYS_SC1"]=15; + type_map["ASP_BB"]=16; + type_map["ASP_SC1"]=17; + type_map["GLU_BB"]=18; + type_map["GLU_SC1"]=19; + type_map["PHE_BB"]=20; + type_map["PHE_SC1"]=21; + type_map["PHE_SC2"]=22; + type_map["PHE_SC3"]=23; + type_map["GLY_BB"]=24; + type_map["HIS_BB"]=25; + type_map["HIS_SC1"]=26; + type_map["HIS_SC2"]=27; + type_map["HIS_SC3"]=28; + type_map["ILE_BB"]=29; + type_map["ILE_SC1"]=30; + type_map["LYS_BB"]=31; + type_map["LYS_SC1"]=32; + type_map["LYS_SC2"]=33; + type_map["LEU_BB"]=34; + type_map["LEU_SC1"]=35; + type_map["MET_BB"]=36; + type_map["MET_SC1"]=37; + type_map["ASN_BB"]=38; + type_map["ASN_SC1"]=39; + type_map["PRO_BB"]=40; + type_map["PRO_SC1"]=41; + type_map["GLN_BB"]=42; + type_map["GLN_SC1"]=43; + type_map["ARG_BB"]=44; + type_map["ARG_SC1"]=45; + type_map["ARG_SC2"]=46; + type_map["SER_BB"]=47; + type_map["SER_SC1"]=48; + type_map["THR_BB"]=49; + type_map["THR_SC1"]=50; + type_map["VAL_BB"]=51; + type_map["VAL_SC1"]=52; + type_map["TRP_BB"]=53; + type_map["TRP_SC1"]=54; + type_map["TRP_SC2"]=55; + type_map["TRP_SC3"]=56; + type_map["TRP_SC4"]=57; + type_map["TRP_SC5"]=58; + type_map["TYR_BB"]=59; + type_map["TYR_SC1"]=60; + type_map["TYR_SC2"]=61; + type_map["TYR_SC3"]=62; type_map["TYR_SC4"]=63; // fill in sigma vector for atoms Model_s_.push_back(0.01*Vector5d(0.114,1.0825,5.4281,17.8811,51.1341)); // C @@ -829,12 +929,24 @@ std::vector EMMIVOX::get_Model_param(std::vector &atoms) // convert to std::string type_s = std::string(1,type); // special cases - if(name=="SOD" || name=="NA" || name =="Na") type_s = "NA"; - if(name=="MG" || name=="Mg") type_s = "MG"; - if(name=="CLA" || name=="CL" || name =="Cl") type_s = "CL"; - if((resname=="CAL" || resname=="CA") && (name=="CAL" || name=="CA" || name =="C0")) type_s = "CA"; - if(name=="POT" || name=="K") type_s = "K"; - if(name=="ZN" || name=="Zn") type_s = "ZN"; + if(name=="SOD" || name=="NA" || name =="Na") { + type_s = "NA"; + } + if(name=="MG" || name=="Mg") { + type_s = "MG"; + } + if(name=="CLA" || name=="CL" || name =="Cl") { + type_s = "CL"; + } + if((resname=="CAL" || resname=="CA") && (name=="CAL" || name=="CA" || name =="C0")) { + type_s = "CA"; + } + if(name=="POT" || name=="K") { + type_s = "K"; + } + if(name=="ZN" || name=="Zn") { + type_s = "ZN"; + } } // check if key in map if(type_map.find(type_s) != type_map.end()) { @@ -847,7 +959,9 @@ std::vector EMMIVOX::get_Model_param(std::vector &atoms) unsigned ires = moldat->getResidueNumber(atoms[i]); // and chain std::string c ("*"); - if(!bfactnoc_) c = moldat->getChainID(atoms[i]); + if(!bfactnoc_) { + c = moldat->getChainID(atoms[i]); + } // define pair residue/chain IDs std::pair key = std::make_pair(ires,c); // add to map between residue/chain and list of atoms @@ -864,16 +978,16 @@ std::vector EMMIVOX::get_Model_param(std::vector &atoms) for(unsigned i=0; i key = Model_res_[i]; // search in Model_rlist_ - if(find(Model_rlist_.begin(), Model_rlist_.end(), key) == Model_rlist_.end()) + if(find(Model_rlist_.begin(), Model_rlist_.end(), key) == Model_rlist_.end()) { Model_rlist_.push_back(key); + } } // return weights return Model_w; } // read experimental data file in PLUMED format: -void EMMIVOX::get_exp_data(const std::string &datafile) -{ +void EMMIVOX::get_exp_data(const std::string &datafile) { Vector pos; double dens, err; int idcomp; @@ -904,8 +1018,7 @@ void EMMIVOX::get_exp_data(const std::string &datafile) delete ifile; } -void EMMIVOX::initialize_Bfactor(double reso) -{ +void EMMIVOX::initialize_Bfactor(double reso) { double bfactini = 0.0; // if doing Bfactor Monte Carlo if(dbfact_>0) { @@ -930,14 +1043,17 @@ void EMMIVOX::initialize_Bfactor(double reso) } // prepare auxiliary vectors -void EMMIVOX::get_auxiliary_vectors() -{ +void EMMIVOX::get_auxiliary_vectors() { // number of atoms unsigned natoms = Model_res_.size(); // clear lists - pref_.clear(); invs2_.clear(); cut_.clear(); + pref_.clear(); + invs2_.clear(); + cut_.clear(); // resize - pref_.resize(natoms); invs2_.resize(natoms); cut_.resize(natoms); + pref_.resize(natoms); + invs2_.resize(natoms); + cut_.resize(natoms); // cycle on all atoms #pragma omp parallel for num_threads(OpenMP::getNumThreads()) for(unsigned im=0; im pref(5*natoms), invs2(5*natoms); @@ -991,10 +1106,10 @@ void EMMIVOX::push_auxiliary_gpu() invs2_gpu_ = torch::from_blob(invs2.data(), {5,natoms}, torch::kFloat64).clone().to(torch::kFloat32).to(device_t_); } -void EMMIVOX::get_close_residues() -{ +void EMMIVOX::get_close_residues() { // clear neighbor list - nl_res_.clear(); nl_res_.resize(Model_rlist_.size()); + nl_res_.clear(); + nl_res_.resize(Model_rlist_.size()); // loop in parallel #pragma omp parallel num_threads(OpenMP::getNumThreads()) @@ -1034,7 +1149,9 @@ void EMMIVOX::get_close_residues() } } // check if neighbor already found - if(neigh) break; + if(neigh) { + break; + } } // if neighbors, add to local list @@ -1047,14 +1164,14 @@ void EMMIVOX::get_close_residues() // add to global list #pragma omp critical { - for(unsigned i=0; i bfactmax_) {bfactnew = 2.0*bfactmax_ - bfactnew;} - if(bfactnew < bfactmin_) {bfactnew = 2.0*bfactmin_ - bfactnew;} + if(bfactnew > bfactmax_) { + bfactnew = 2.0*bfactmax_ - bfactnew; + } + if(bfactnew < bfactmin_) { + bfactnew = 2.0*bfactmin_ - bfactnew; + } // useful quantities std::map deltaov; @@ -1109,8 +1230,9 @@ void EMMIVOX::doMonteCarloBfact() // add to global list #pragma omp critical { - for(std::map::iterator itov=deltaov_l.begin(); itov!=deltaov_l.end(); ++itov) + for(std::map::iterator itov=deltaov_l.begin(); itov!=deltaov_l.end(); ++itov) { deltaov[itov->first] += itov->second; + } } } @@ -1172,7 +1294,9 @@ void EMMIVOX::doMonteCarloBfact() // accept or reject bool accept = false; if(bfactemin_) { - if(new_ene < old_ene) accept = true; + if(new_ene < old_ene) { + accept = true; + } } else { accept = doAccept(old_ene, new_ene, kbt_); } @@ -1184,8 +1308,9 @@ void EMMIVOX::doMonteCarloBfact() // update bfactor Model_b_[key] = bfactnew; // change all the ovmd_ affected - for(std::map::iterator itov=deltaov.begin(); itov!=deltaov.end(); ++itov) + for(std::map::iterator itov=deltaov.begin(); itov!=deltaov.end(); ++itov) { ovmd_[itov->first] += itov->second; + } } } // end cycle on bfactors @@ -1200,8 +1325,7 @@ void EMMIVOX::doMonteCarloBfact() // get overlap double EMMIVOX::get_overlap(const Vector &d_m, const Vector &m_m, - const Vector5d &cfact, const Vector5d &m_s, double bfact) -{ + const Vector5d &cfact, const Vector5d &m_s, double bfact) { // calculate vector difference Vector md = delta(m_m, d_m); // norm squared @@ -1219,8 +1343,7 @@ double EMMIVOX::get_overlap(const Vector &d_m, const Vector &m_m, return ov_tot; } -void EMMIVOX::update_neighbor_sphere() -{ +void EMMIVOX::update_neighbor_sphere() { // number of atoms unsigned natoms = Model_type_.size(); // clear neighbor sphere @@ -1242,7 +1365,9 @@ void EMMIVOX::update_neighbor_sphere() // calculate distance double dist = delta(getPosition(im), d_m).modulo(); // add to local list - if(dist<=2.0*cut_[im]) ns_l.push_back(std::make_pair(id,im)); + if(dist<=2.0*cut_[im]) { + ns_l.push_back(std::make_pair(id,im)); + } } } // add to global list @@ -1251,8 +1376,7 @@ void EMMIVOX::update_neighbor_sphere() } } -bool EMMIVOX::do_neighbor_sphere() -{ +bool EMMIVOX::do_neighbor_sphere() { std::vector dist(getPositions().size()); bool update = false; @@ -1264,14 +1388,15 @@ bool EMMIVOX::do_neighbor_sphere() // check if update or not double maxdist = *max_element(dist.begin(), dist.end()); - if(maxdist>=1.0) update=true; + if(maxdist>=1.0) { + update=true; + } // return if update or not return update; } -void EMMIVOX::update_neighbor_list() -{ +void EMMIVOX::update_neighbor_list() { // number of atoms unsigned natoms = Model_type_.size(); // clear neighbor list @@ -1287,7 +1412,9 @@ void EMMIVOX::update_neighbor_list() // calculate distance double dist = delta(Map_m_[ns_[i].first], getPosition(ns_[i].second)).modulo(); // add to local neighbour list - if(dist<=cut_[ns_[i].second]) nl_l.push_back(ns_[i]); + if(dist<=cut_[ns_[i].second]) { + nl_l.push_back(ns_[i]); + } } // add to global list #pragma omp critical @@ -1302,7 +1429,8 @@ void EMMIVOX::update_neighbor_list() // in case of B-factors sampling - at the right step if(dbfact_>0 && getStep()%MCBstride_==0) { // clear vectors - Model_nb_.clear(); Model_nb_.resize(natoms); + Model_nb_.clear(); + Model_nb_.resize(natoms); // cycle over the neighbor list to creat a list of voxels per atom #pragma omp parallel num_threads(OpenMP::getNumThreads()) { @@ -1315,8 +1443,9 @@ void EMMIVOX::update_neighbor_list() // add to global list #pragma omp critical { - for(unsigned i=0; i(nrep_); - for(int i=0; i0 && step%mapstride_==0) do_comm = true; - if(dbfact_>0 && step%MCBstride_==0) do_comm = true; - if(do_corr_) do_comm = true; + if(mapstride_>0 && step%mapstride_==0) { + do_comm = true; + } + if(dbfact_>0 && step%MCBstride_==0) { + do_comm = true; + } + if(do_corr_) { + do_comm = true; + } // in case of metainference: already communicated - if(!no_aver_ && nrep_>1) do_comm = false; + if(!no_aver_ && nrep_>1) { + do_comm = false; + } if(do_comm) { // communicate ovmd_gpu_ to CPU [1, nd] torch::Tensor ovmd_cpu = ovmd_gpu_.detach().to(torch::kCPU).to(torch::kFloat64); @@ -1423,8 +1561,7 @@ void EMMIVOX::calculate_fmod() } // calculate score -void EMMIVOX::calculate_score() -{ +void EMMIVOX::calculate_score() { // number of atoms int natoms = Model_type_.size(); @@ -1463,7 +1600,9 @@ void EMMIVOX::calculate_score() torch::Tensor ene_cpu = ene.detach().to(torch::kCPU).to(torch::kFloat64); ene_ = *ene_cpu.data_ptr(); // with marginal, simply multiply by number of replicas! - if(!no_aver_ && nrep_>1) ene_ *= static_cast(nrep_); + if(!no_aver_ && nrep_>1) { + ene_ *= static_cast(nrep_); + } // // 2) communicate derivatives to CPU torch::Tensor atom_der_cpu = atoms_der_gpu.detach().to(torch::kCPU).to(torch::kFloat64); @@ -1488,8 +1627,7 @@ void EMMIVOX::calculate_score() virial_ = virial; } -void EMMIVOX::calculate() -{ +void EMMIVOX::calculate() { // get time step long int step = getStep(); @@ -1500,10 +1638,15 @@ void EMMIVOX::calculate() if(first_time_ || getExchangeStep() || step%nl_stride_==0) { // check if time to update neighbor sphere bool update = false; - if(first_time_ || getExchangeStep()) update = true; - else update = do_neighbor_sphere(); + if(first_time_ || getExchangeStep()) { + update = true; + } else { + update = do_neighbor_sphere(); + } // update neighbor sphere - if(update) update_neighbor_sphere(); + if(update) { + update_neighbor_sphere(); + } // update neighbor list update_neighbor_list(); // set flag @@ -1517,9 +1660,13 @@ void EMMIVOX::calculate() if(dbfact_>0) { double acc = 0.0; // do Monte Carlo - if(step%MCBstride_==0 && !getExchangeStep() && step>0) doMonteCarloBfact(); + if(step%MCBstride_==0 && !getExchangeStep() && step>0) { + doMonteCarloBfact(); + } // calculate acceptance ratio - if(MCBtrials_>0) acc = MCBaccept_ / MCBtrials_; + if(MCBtrials_>0) { + acc = MCBaccept_ / MCBtrials_; + } // set value getPntrToComponent("accB")->set(acc); } @@ -1532,21 +1679,28 @@ void EMMIVOX::calculate() score->set(ene_); setBoxDerivatives(score, virial_); #pragma omp parallel for - for(unsigned i=0; iset(scale_); getPntrToComponent("offset")->set(offset_); // calculate correlation coefficient - if(do_corr_) calculate_corr(); + if(do_corr_) { + calculate_corr(); + } // PRINT other quantities to files // - status file - if(step%statusstride_==0) print_status(step); + if(step%statusstride_==0) { + print_status(step); + } // - density file - if(mapstride_>0 && step%mapstride_==0) write_model_density(step); + if(mapstride_>0 && step%mapstride_==0) { + write_model_density(step); + } } -void EMMIVOX::calculate_corr() -{ +void EMMIVOX::calculate_corr() { // number of data points double nd = static_cast(ovdd_.size()); // average ovmd_ and ovdd_ diff --git a/src/isdb/FretEfficiency.cpp b/src/isdb/FretEfficiency.cpp index d1990695f3..a8e0ee2bdb 100644 --- a/src/isdb/FretEfficiency.cpp +++ b/src/isdb/FretEfficiency.cpp @@ -101,12 +101,12 @@ void FretEfficiency::registerKeywords( Keywords& keys ) { FretEfficiency::FretEfficiency(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), - pbc(true) -{ + pbc(true) { std::vector atoms; parseAtomList("ATOMS",atoms); - if(atoms.size()!=2) + if(atoms.size()!=2) { error("Number of specified atoms should be 2"); + } parse("R0",R0_); bool nopbc=!pbc; parseFlag("NOPBC",nopbc); @@ -116,8 +116,11 @@ FretEfficiency::FretEfficiency(const ActionOptions&ao): log.printf(" between atoms %d %d\n",atoms[0].serial(),atoms[1].serial()); log.printf(" with Forster radius set to %lf\n",R0_); - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } log << " Bibliography" << plumed.cite("Bonomi, Camilloni, Bioinformatics, 33, 3999 (2017)") << "\n"; @@ -131,7 +134,9 @@ FretEfficiency::FretEfficiency(const ActionOptions&ao): // calculator void FretEfficiency::calculate() { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } Vector distance=delta(getPosition(0),getPosition(1)); const double dist_mod=distance.modulo(); diff --git a/src/isdb/Jcoupling.cpp b/src/isdb/Jcoupling.cpp index 8f2ec44974..117e836be4 100644 --- a/src/isdb/Jcoupling.cpp +++ b/src/isdb/Jcoupling.cpp @@ -85,8 +85,7 @@ PRINT ARG=jhanst.*,jhan.* FILE=COLVAR STRIDE=100 //+ENDPLUMEDOC class JCoupling : - public MetainferenceBase -{ + public MetainferenceBase { private: bool pbc; enum { HAN, HAHN, CCG, NCG, CUSTOM }; @@ -124,8 +123,7 @@ void JCoupling::registerKeywords(Keywords& keys) { JCoupling::JCoupling(const ActionOptions&ao): PLUMED_METAINF_INIT(ao), - pbc(true) -{ + pbc(true) { bool nopbc = !pbc; parseFlag("NOPBC", nopbc); pbc =! nopbc; @@ -180,13 +178,21 @@ JCoupling::JCoupling(const ActionOptions&ao): coupl.resize( ncoupl_ ); unsigned ntarget=0; for(unsigned i=0; i deriv(ncoupl_*6); std::vector j(ncoupl_,0.); @@ -326,7 +336,9 @@ void JCoupling::calculate() dd1 *= derj; dd2 *= derj; - if(getDoScore()) setCalcData(r, j[r]); + if(getDoScore()) { + setCalcData(r, j[r]); + } deriv[a0] = dd0; deriv[a0+1] = -dd0; deriv[a0+2] = dd1; @@ -363,7 +375,8 @@ void JCoupling::calculate() } else { for (unsigned r=0; rset(j[r]); setAtomsDerivatives(val, a0, deriv[a0]); @@ -386,7 +399,9 @@ void JCoupling::calculate() void JCoupling::update() { // write status file - if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) writeStatus(); + if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) { + writeStatus(); + } } } diff --git a/src/isdb/Metainference.cpp b/src/isdb/Metainference.cpp index 604a8de72e..f264da0c14 100644 --- a/src/isdb/Metainference.cpp +++ b/src/isdb/Metainference.cpp @@ -154,8 +154,7 @@ LABEL=spe */ //+ENDPLUMEDOC -class Metainference : public bias::Bias -{ +class Metainference : public bias::Bias { // experimental values std::vector parameters; // noise type @@ -368,8 +367,7 @@ Metainference::Metainference(const ActionOptions&ao): N_optimized_step_(0), optimized_step_(0), sigmamax_opt_done_(false), - average_weights_stride_(1) -{ + average_weights_stride_(1) { bool noensemble = false; parseFlag("NOENSEMBLE", noensemble); @@ -378,7 +376,9 @@ Metainference::Metainference(const ActionOptions&ao): if(master) { nrep_ = multi_sim_comm.Get_size(); replica_ = multi_sim_comm.Get_rank(); - if(noensemble) nrep_ = 1; + if(noensemble) { + nrep_ = 1; + } } else { nrep_ = 0; replica_ = 0; @@ -390,19 +390,30 @@ Metainference::Metainference(const ActionOptions&ao): parse("SELECTOR", selector_); parse("NSELECT", nsel); // do checks - if(selector_.length()>0 && nsel<=1) error("With SELECTOR active, NSELECT must be greater than 1"); - if(selector_.length()==0 && nsel>1) error("With NSELECT greater than 1, you must specify SELECTOR"); + if(selector_.length()>0 && nsel<=1) { + error("With SELECTOR active, NSELECT must be greater than 1"); + } + if(selector_.length()==0 && nsel>1) { + error("With NSELECT greater than 1, you must specify SELECTOR"); + } // initialise firstTimeW firstTimeW.resize(nsel, true); // reweight implies a different number of arguments (the latest one must always be the bias) parseFlag("REWEIGHT", do_reweight_); - if(do_reweight_&&nrep_<2) error("REWEIGHT can only be used in parallel with 2 or more replicas"); - if(!getRestart()) average_weights_.resize(nsel, std::vector (nrep_, 1./static_cast(nrep_))); - else average_weights_.resize(nsel, std::vector (nrep_, 0.)); + if(do_reweight_&&nrep_<2) { + error("REWEIGHT can only be used in parallel with 2 or more replicas"); + } + if(!getRestart()) { + average_weights_.resize(nsel, std::vector (nrep_, 1./static_cast(nrep_))); + } else { + average_weights_.resize(nsel, std::vector (nrep_, 0.)); + } narg = getNumberOfArguments(); - if(do_reweight_) narg--; + if(do_reweight_) { + narg--; + } unsigned averaging=0; parse("AVERAGING", averaging); @@ -412,38 +423,57 @@ Metainference::Metainference(const ActionOptions&ao): } parseVector("PARAMETERS",parameters); - if(parameters.size()!=static_cast(narg)&&!parameters.empty()) + if(parameters.size()!=static_cast(narg)&&!parameters.empty()) { error("Size of PARAMETERS array should be either 0 or the same as of the number of arguments in ARG1"); + } std::vector arg2; parseArgumentList("PARARG",arg2); if(!arg2.empty()) { - if(parameters.size()>0) error("It is not possible to use PARARG and PARAMETERS together"); - if(arg2.size()!=narg) error("Size of PARARG array should be the same as number for arguments in ARG"); + if(parameters.size()>0) { + error("It is not possible to use PARARG and PARAMETERS together"); + } + if(arg2.size()!=narg) { + error("Size of PARARG array should be the same as number for arguments in ARG"); + } for(unsigned i=0; iget()); - if(arg2[i]->hasDerivatives()==true) error("PARARG can only accept arguments without derivatives"); + if(arg2[i]->hasDerivatives()==true) { + error("PARARG can only accept arguments without derivatives"); + } } } - if(parameters.size()!=narg) + if(parameters.size()!=narg) { error("PARARG or PARAMETERS arrays should include the same number of elements as the arguments in ARG"); + } std::string stringa_noise; parse("NOISETYPE",stringa_noise); - if(stringa_noise=="GAUSS") noise_type_ = GAUSS; - else if(stringa_noise=="MGAUSS") noise_type_ = MGAUSS; - else if(stringa_noise=="OUTLIERS") noise_type_ = OUTLIERS; - else if(stringa_noise=="MOUTLIERS") noise_type_ = MOUTLIERS; - else if(stringa_noise=="GENERIC") noise_type_ = GENERIC; - else error("Unknown noise type!"); + if(stringa_noise=="GAUSS") { + noise_type_ = GAUSS; + } else if(stringa_noise=="MGAUSS") { + noise_type_ = MGAUSS; + } else if(stringa_noise=="OUTLIERS") { + noise_type_ = OUTLIERS; + } else if(stringa_noise=="MOUTLIERS") { + noise_type_ = MOUTLIERS; + } else if(stringa_noise=="GENERIC") { + noise_type_ = GENERIC; + } else { + error("Unknown noise type!"); + } if(noise_type_== GENERIC) { std::string stringa_like; parse("LIKELIHOOD",stringa_like); - if(stringa_like=="GAUSS") gen_likelihood_ = LIKE_GAUSS; - else if(stringa_like=="LOGN") gen_likelihood_ = LIKE_LOGN; - else error("Unknown likelihood type!"); + if(stringa_like=="GAUSS") { + gen_likelihood_ = LIKE_GAUSS; + } else if(stringa_like=="LOGN") { + gen_likelihood_ = LIKE_LOGN; + } else { + error("Unknown likelihood type!"); + } parse("DFTILDE",Dftilde_); } @@ -451,35 +481,55 @@ Metainference::Metainference(const ActionOptions&ao): parse("WRITE_STRIDE",write_stride_); std::string status_file_name_; parse("STATUS_FILE",status_file_name_); - if(status_file_name_=="") status_file_name_ = "MISTATUS"+getLabel(); - else status_file_name_ = status_file_name_+getLabel(); + if(status_file_name_=="") { + status_file_name_ = "MISTATUS"+getLabel(); + } else { + status_file_name_ = status_file_name_+getLabel(); + } std::string stringa_optsigma; parse("OPTSIGMAMEAN", stringa_optsigma); - if(stringa_optsigma=="NONE") do_optsigmamean_=0; - else if(stringa_optsigma=="SEM") do_optsigmamean_=1; - else if(stringa_optsigma=="SEM_MAX") do_optsigmamean_=2; + if(stringa_optsigma=="NONE") { + do_optsigmamean_=0; + } else if(stringa_optsigma=="SEM") { + do_optsigmamean_=1; + } else if(stringa_optsigma=="SEM_MAX") { + do_optsigmamean_=2; + } unsigned aver_max_steps=0; parse("SIGMA_MAX_STEPS", aver_max_steps); - if(aver_max_steps==0&&do_optsigmamean_==2) aver_max_steps=averaging*2000; - if(aver_max_steps>0&&do_optsigmamean_<2) error("SIGMA_MAX_STEPS can only be used together with OPTSIGMAMEAN=SEM_MAX"); - if(aver_max_steps>0&&do_optsigmamean_==2) N_optimized_step_=aver_max_steps; - if(aver_max_steps>0&&aver_max_steps0&&do_optsigmamean_<2) { + error("SIGMA_MAX_STEPS can only be used together with OPTSIGMAMEAN=SEM_MAX"); + } + if(aver_max_steps>0&&do_optsigmamean_==2) { + N_optimized_step_=aver_max_steps; + } + if(aver_max_steps>0&&aver_max_steps read_sigma_mean_; parseVector("SIGMA_MEAN0",read_sigma_mean_); - if(do_optsigmamean_==0 && read_sigma_mean_.size()==0 && !getRestart()) + if(do_optsigmamean_==0 && read_sigma_mean_.size()==0 && !getRestart()) { error("If you don't use OPTSIGMAMEAN and you are not RESTARTING then you MUST SET SIGMA_MEAN0"); + } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { if(read_sigma_mean_.size()==narg) { sigma_mean2_.resize(narg); - for(unsigned i=0; i readsigma; parseVector("SIGMA0",readsigma); - if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma.size()>1) + if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma.size()>1) { error("If you want to use more than one SIGMA you should use NOISETYPE=MGAUSS|MOUTLIERS|GENERIC"); + } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { sigma_.resize(readsigma.size()); sigma_=readsigma; - } else sigma_.resize(1, readsigma[0]); + } else { + sigma_.resize(1, readsigma[0]); + } std::vector readsigma_min; parseVector("SIGMA_MIN",readsigma_min); - if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_min.size()>1) + if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_min.size()>1) { error("If you want to use more than one SIGMA you should use NOISETYPE=MGAUSS|MOUTLIERS|GENERIC"); + } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { sigma_min_.resize(readsigma_min.size()); sigma_min_=readsigma_min; - } else sigma_min_.resize(1, readsigma_min[0]); + } else { + sigma_min_.resize(1, readsigma_min[0]); + } std::vector readsigma_max; parseVector("SIGMA_MAX",readsigma_max); - if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_max.size()>1) + if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_max.size()>1) { error("If you want to use more than one SIGMA you should use NOISETYPE=MGAUSS|MOUTLIERS|GENERIC"); + } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { sigma_max_.resize(readsigma_max.size()); sigma_max_=readsigma_max; - } else sigma_max_.resize(1, readsigma_max[0]); + } else { + sigma_max_.resize(1, readsigma_max[0]); + } - if(sigma_max_.size()!=sigma_min_.size()) error("The number of values for SIGMA_MIN and SIGMA_MAX must be the same"); + if(sigma_max_.size()!=sigma_min_.size()) { + error("The number of values for SIGMA_MIN and SIGMA_MAX must be the same"); + } std::vector read_dsigma; parseVector("DSIGMA",read_dsigma); - if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_max.size()>1) + if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_max.size()>1) { error("If you want to use more than one SIGMA you should use NOISETYPE=MGAUSS|MOUTLIERS|GENERIC"); + } if(read_dsigma.size()>0) { Dsigma_.resize(read_dsigma.size()); Dsigma_=read_dsigma; @@ -596,7 +686,9 @@ Metainference::Metainference(const ActionOptions&ao): parse("MC_CHUNKSIZE", MCchunksize_); // get temperature kbt_ = getkBT(); - if(kbt_==0.0) error("Unless the MD engine passes the temperature to plumed, you must specify it using TEMP"); + if(kbt_==0.0) { + error("Unless the MD engine passes the temperature to plumed, you must specify it using TEMP"); + } checkRead(); @@ -634,7 +726,9 @@ Metainference::Metainference(const ActionOptions&ao): restart_sfile.link(*this); if(getRestart()&&restart_sfile.FileExist(status_file_name_)) { firstTime = false; - for(unsigned i=0; i1) multi_sim_comm.Sum(&average_weights_[i][0], nrep_); + if(nrep_>1) { + multi_sim_comm.Sum(&average_weights_[i][0], nrep_); + } } comm.Sum(&average_weights_[i][0], nrep_); } @@ -714,13 +814,19 @@ Metainference::Metainference(const ActionOptions&ao): } /* If DSIGMA is not yet initialised do it now */ - for(unsigned i=0; iset(std::sqrt(sigma_mean2_[i])); - addComponent("sigma-"+num); componentIsNotPeriodic("sigma-"+num); + addComponent("sigma-"+num); + componentIsNotPeriodic("sigma-"+num); valueSigma.push_back(getPntrToComponent("sigma-"+num)); getPntrToComponent("sigma-"+num)->set(sigma_[i]); if(noise_type_==GENERIC) { - addComponent("ftilde-"+num); componentIsNotPeriodic("ftilde-"+num); + addComponent("ftilde-"+num); + componentIsNotPeriodic("ftilde-"+num); valueFtilde.push_back(getPntrToComponent("ftilde-"+num)); } } } else { - addComponent("sigmaMean"); componentIsNotPeriodic("sigmaMean"); + addComponent("sigmaMean"); + componentIsNotPeriodic("sigmaMean"); valueSigmaMean.push_back(getPntrToComponent("sigmaMean")); getPntrToComponent("sigmaMean")->set(std::sqrt(sigma_mean2_[0])); - addComponent("sigma"); componentIsNotPeriodic("sigma"); + addComponent("sigma"); + componentIsNotPeriodic("sigma"); valueSigma.push_back(getPntrToComponent("sigma")); getPntrToComponent("sigma")->set(sigma_[0]); } @@ -883,7 +1010,9 @@ Metainference::Metainference(const ActionOptions&ao): // in this case we want the same seed everywhere auto ts = std::chrono::time_point_cast(std::chrono::steady_clock::now()).time_since_epoch().count(); iseed = static_cast(ts); - if(master&&nrep_>1) multi_sim_comm.Bcast(iseed,0); + if(master&&nrep_>1) { + multi_sim_comm.Bcast(iseed,0); + } comm.Bcast(iseed,0); // this is used for scale and offset sampling and acceptance random[1].setSeed(-iseed); @@ -905,20 +1034,24 @@ Metainference::Metainference(const ActionOptions&ao): } log<<" Bibliography "<0) log<0) { + log< &mean, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { const double scale2 = scale*scale; const double sm2 = sigma_mean2_[0]; const double ss2 = sigma[0]*sigma[0] + scale2*sm2; @@ -933,22 +1066,24 @@ double Metainference::getEnergySP(const std::vector &mean, const std::ve const double a2 = 0.5*dev*dev + ss2; if(sm2 > 0.0) { ene += std::log(2.0*a2/(1.0-std::exp(-a2/sm2))); - } - else { + } else { ene += std::log(2.0*a2); } } } // add one single Jeffrey's prior and one normalisation per data point ene += 0.5*std::log(sss) + static_cast(narg)*0.5*std::log(0.5*M_PI*M_PI/ss2); - if(doscale_ || doregres_zero_) ene += 0.5*std::log(sss); - if(dooffset_) ene += 0.5*std::log(sss); + if(doscale_ || doregres_zero_) { + ene += 0.5*std::log(sss); + } + if(dooffset_) { + ene += 0.5*std::log(sss); + } return kbt_ * ene; } double Metainference::getEnergySPE(const std::vector &mean, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { const double scale2 = scale*scale; double ene = 0.0; #pragma omp parallel num_threads(OpenMP::getNumThreads()) shared(ene) @@ -962,20 +1097,22 @@ double Metainference::getEnergySPE(const std::vector &mean, const std::v const double a2 = 0.5*dev*dev + ss2; if(sm2 > 0.0) { ene += 0.5*std::log(sss) + 0.5*std::log(0.5*M_PI*M_PI/ss2) + std::log(2.0*a2/(1.0-std::exp(-a2/sm2))); - } - else { + } else { ene += 0.5*std::log(sss) + 0.5*std::log(0.5*M_PI*M_PI/ss2) + std::log(2.0*a2); } - if(doscale_ || doregres_zero_) ene += 0.5*std::log(sss); - if(dooffset_) ene += 0.5*std::log(sss); + if(doscale_ || doregres_zero_) { + ene += 0.5*std::log(sss); + } + if(dooffset_) { + ene += 0.5*std::log(sss); + } } } return kbt_ * ene; } double Metainference::getEnergyMIGEN(const std::vector &mean, const std::vector &ftilde, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { double ene = 0.0; #pragma omp parallel num_threads(OpenMP::getNumThreads()) shared(ene) { @@ -984,26 +1121,35 @@ double Metainference::getEnergyMIGEN(const std::vector &mean, const std: const double inv_sb2 = 1./(sigma[i]*sigma[i]); const double inv_sm2 = 1./sigma_mean2_[i]; double devb = 0; - if(gen_likelihood_==LIKE_GAUSS) devb = scale*ftilde[i]-parameters[i]+offset; - else if(gen_likelihood_==LIKE_LOGN) devb = std::log(scale*ftilde[i]/parameters[i]); + if(gen_likelihood_==LIKE_GAUSS) { + devb = scale*ftilde[i]-parameters[i]+offset; + } else if(gen_likelihood_==LIKE_LOGN) { + devb = std::log(scale*ftilde[i]/parameters[i]); + } double devm = mean[i] - ftilde[i]; // deviation + normalisation + jeffrey double normb = 0.; - if(gen_likelihood_==LIKE_GAUSS) normb = -0.5*std::log(0.5/M_PI*inv_sb2); - else if(gen_likelihood_==LIKE_LOGN) normb = -0.5*std::log(0.5/M_PI*inv_sb2/(parameters[i]*parameters[i])); + if(gen_likelihood_==LIKE_GAUSS) { + normb = -0.5*std::log(0.5/M_PI*inv_sb2); + } else if(gen_likelihood_==LIKE_LOGN) { + normb = -0.5*std::log(0.5/M_PI*inv_sb2/(parameters[i]*parameters[i])); + } const double normm = -0.5*std::log(0.5/M_PI*inv_sm2); const double jeffreys = -0.5*std::log(2.*inv_sb2); ene += 0.5*devb*devb*inv_sb2 + 0.5*devm*devm*inv_sm2 + normb + normm + jeffreys; - if(doscale_ || doregres_zero_) ene += jeffreys; - if(dooffset_) ene += jeffreys; + if(doscale_ || doregres_zero_) { + ene += jeffreys; + } + if(dooffset_) { + ene += jeffreys; + } } } return kbt_ * ene; } double Metainference::getEnergyGJ(const std::vector &mean, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { const double scale2 = scale*scale; const double inv_s2 = 1./(sigma[0]*sigma[0] + scale2*sigma_mean2_[0]); const double inv_sss = 1./(sigma[0]*sigma[0] + sigma_mean2_[0]); @@ -1021,15 +1167,18 @@ double Metainference::getEnergyGJ(const std::vector &mean, const std::ve const double jeffreys = -0.5*std::log(2.*inv_sss); // add Jeffrey's prior in case one sigma for all data points + one normalisation per datapoint ene += jeffreys + static_cast(narg)*normalisation; - if(doscale_ || doregres_zero_) ene += jeffreys; - if(dooffset_) ene += jeffreys; + if(doscale_ || doregres_zero_) { + ene += jeffreys; + } + if(dooffset_) { + ene += jeffreys; + } return kbt_ * ene; } double Metainference::getEnergyGJE(const std::vector &mean, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { const double scale2 = scale*scale; double ene = 0.0; @@ -1044,15 +1193,18 @@ double Metainference::getEnergyGJE(const std::vector &mean, const std::v const double normalisation = -0.5*std::log(0.5/M_PI*inv_s2); const double jeffreys = -0.5*std::log(2.*inv_sss); ene += 0.5*dev*dev*inv_s2 + normalisation + jeffreys; - if(doscale_ || doregres_zero_) ene += jeffreys; - if(dooffset_) ene += jeffreys; + if(doscale_ || doregres_zero_) { + ene += jeffreys; + } + if(dooffset_) { + ene += jeffreys; + } } } return kbt_ * ene; } -void Metainference::moveTilde(const std::vector &mean_, double &old_energy) -{ +void Metainference::moveTilde(const std::vector &mean_, double &old_energy) { std::vector new_ftilde(sigma_.size()); new_ftilde = ftilde_; @@ -1083,8 +1235,7 @@ void Metainference::moveTilde(const std::vector &mean_, double &old_ener } } -void Metainference::moveScaleOffset(const std::vector &mean_, double &old_energy) -{ +void Metainference::moveScaleOffset(const std::vector &mean_, double &old_energy) { double new_scale = scale_; if(doscale_) { @@ -1093,8 +1244,12 @@ void Metainference::moveScaleOffset(const std::vector &mean_, double &ol const double ds1 = Dscale_*r1; new_scale += ds1; // check boundaries - if(new_scale > scale_max_) {new_scale = 2.0 * scale_max_ - new_scale;} - if(new_scale < scale_min_) {new_scale = 2.0 * scale_min_ - new_scale;} + if(new_scale > scale_max_) { + new_scale = 2.0 * scale_max_ - new_scale; + } + if(new_scale < scale_min_) { + new_scale = 2.0 * scale_min_ - new_scale; + } } else { const double r1 = random[1].Gaussian(); const double ds1 = 0.5*(scale_mu_-new_scale)+Dscale_*std::exp(1)/M_PI*r1; @@ -1110,8 +1265,12 @@ void Metainference::moveScaleOffset(const std::vector &mean_, double &ol const double ds1 = Doffset_*r1; new_offset += ds1; // check boundaries - if(new_offset > offset_max_) {new_offset = 2.0 * offset_max_ - new_offset;} - if(new_offset < offset_min_) {new_offset = 2.0 * offset_min_ - new_offset;} + if(new_offset > offset_max_) { + new_offset = 2.0 * offset_max_ - new_offset; + } + if(new_offset < offset_min_) { + new_offset = 2.0 * offset_min_ - new_offset; + } } else { const double r1 = random[1].Gaussian(); const double ds1 = 0.5*(offset_mu_-new_offset)+Doffset_*std::exp(1)/M_PI*r1; @@ -1145,7 +1304,9 @@ void Metainference::moveScaleOffset(const std::vector &mean_, double &ol if(master) { totenergies[0] = old_energy; totenergies[1] = new_energy; - if(nrep_>1) multi_sim_comm.Sum(totenergies); + if(nrep_>1) { + multi_sim_comm.Sum(totenergies); + } } else { totenergies[0] = 0; totenergies[1] = 0; @@ -1172,8 +1333,7 @@ void Metainference::moveScaleOffset(const std::vector &mean_, double &ol } } -void Metainference::moveSigmas(const std::vector &mean_, double &old_energy, const unsigned i, const std::vector &indices, bool &breaknow) -{ +void Metainference::moveSigmas(const std::vector &mean_, double &old_energy, const unsigned i, const std::vector &indices, bool &breaknow) { std::vector new_sigma(sigma_.size()); new_sigma = sigma_; @@ -1196,8 +1356,12 @@ void Metainference::moveSigmas(const std::vector &mean_, double &old_ene const double ds2 = Dsigma_[index]*r2; new_sigma[index] = sigma_[index] + ds2; // check boundaries - if(new_sigma[index] > sigma_max_[index]) {new_sigma[index] = 2.0 * sigma_max_[index] - new_sigma[index];} - if(new_sigma[index] < sigma_min_[index]) {new_sigma[index] = 2.0 * sigma_min_[index] - new_sigma[index];} + if(new_sigma[index] > sigma_max_[index]) { + new_sigma[index] = 2.0 * sigma_max_[index] - new_sigma[index]; + } + if(new_sigma[index] < sigma_min_[index]) { + new_sigma[index] = 2.0 * sigma_min_[index] - new_sigma[index]; + } } } else { // change all sigmas @@ -1206,8 +1370,12 @@ void Metainference::moveSigmas(const std::vector &mean_, double &old_ene const double ds2 = Dsigma_[j]*r2; new_sigma[j] = sigma_[j] + ds2; // check boundaries - if(new_sigma[j] > sigma_max_[j]) {new_sigma[j] = 2.0 * sigma_max_[j] - new_sigma[j];} - if(new_sigma[j] < sigma_min_[j]) {new_sigma[j] = 2.0 * sigma_min_[j] - new_sigma[j];} + if(new_sigma[j] > sigma_max_[j]) { + new_sigma[j] = 2.0 * sigma_max_[j] - new_sigma[j]; + } + if(new_sigma[j] < sigma_min_[j]) { + new_sigma[j] = 2.0 * sigma_min_[j] - new_sigma[j]; + } } } @@ -1254,8 +1422,7 @@ void Metainference::moveSigmas(const std::vector &mean_, double &old_ene } } -double Metainference::doMonteCarlo(const std::vector &mean_) -{ +double Metainference::doMonteCarlo(const std::vector &mean_) { // calculate old energy with the updated coordinates double old_energy=0.; @@ -1294,13 +1461,19 @@ double Metainference::doMonteCarlo(const std::vector &mean_) for(unsigned i=0; i &mean_) if(noise_type_==GENERIC) { double accept = static_cast(MCacceptFT_) / static_cast(MCtrial_); valueAcceptFT->set(accept); - for(unsigned i=0; iset(ftilde_[i]); + for(unsigned i=0; iset(ftilde_[i]); + } } /* scale and offset */ - if(doscale_ || doregres_zero_) valueScale->set(scale_); - if(dooffset_) valueOffset->set(offset_); + if(doscale_ || doregres_zero_) { + valueScale->set(scale_); + } + if(dooffset_) { + valueOffset->set(offset_); + } if(doscale_||dooffset_) { double accept = static_cast(MCacceptScale_) / static_cast(MCtrial_); valueAcceptScale->set(accept); } /* sigmas */ - for(unsigned i=0; iset(sigma_[i]); + for(unsigned i=0; iset(sigma_[i]); + } double accept = static_cast(MCaccept_) / static_cast(MCtrial_); valueAccept->set(accept); } // here we sum the score over the replicas to get the full metainference score that we save as a bias if(master) { - if(nrep_>1) multi_sim_comm.Sum(old_energy); + if(nrep_>1) { + multi_sim_comm.Sum(old_energy); + } } else { old_energy=0; } @@ -1342,8 +1525,7 @@ double Metainference::doMonteCarlo(const std::vector &mean_) */ void Metainference::getEnergyForceSP(const std::vector &mean, const std::vector &dmean_x, - const std::vector &dmean_b) -{ + const std::vector &dmean_b) { const double scale2 = scale_*scale_; const double sm2 = sigma_mean2_[0]; const double ss2 = sigma_[0]*sigma_[0] + scale2*sm2; @@ -1361,14 +1543,15 @@ void Metainference::getEnergyForceSP(const std::vector &mean, const std: const double dt = 1./t; const double dit = 1./(1.-dt); f[i] = -scale_*dev*(dit/sm2 + 1./a2); - } - else { + } else { f[i] = -scale_*dev*(1./a2); } } } // collect contribution to forces and energy from other replicas - if(nrep_>1) multi_sim_comm.Sum(&f[0],narg); + if(nrep_>1) { + multi_sim_comm.Sum(&f[0],narg); + } } // intra-replica summation comm.Sum(&f[0],narg); @@ -1386,8 +1569,7 @@ void Metainference::getEnergyForceSP(const std::vector &mean, const std: } void Metainference::getEnergyForceSPE(const std::vector &mean, const std::vector &dmean_x, - const std::vector &dmean_b) -{ + const std::vector &dmean_b) { const double scale2 = scale_*scale_; std::vector f(narg,0); @@ -1405,14 +1587,15 @@ void Metainference::getEnergyForceSPE(const std::vector &mean, const std const double dt = 1./t; const double dit = 1./(1.-dt); f[i] = -scale_*dev*(dit/sm2 + 1./a2); - } - else { + } else { f[i] = -scale_*dev*(1./a2); } } } // collect contribution to forces and energy from other replicas - if(nrep_>1) multi_sim_comm.Sum(&f[0],narg); + if(nrep_>1) { + multi_sim_comm.Sum(&f[0],narg); + } } comm.Sum(&f[0],narg); @@ -1429,14 +1612,15 @@ void Metainference::getEnergyForceSPE(const std::vector &mean, const std } void Metainference::getEnergyForceGJ(const std::vector &mean, const std::vector &dmean_x, - const std::vector &dmean_b) -{ + const std::vector &dmean_b) { const double scale2 = scale_*scale_; double inv_s2=0.; if(master) { inv_s2 = 1./(sigma_[0]*sigma_[0] + scale2*sigma_mean2_[0]); - if(nrep_>1) multi_sim_comm.Sum(inv_s2); + if(nrep_>1) { + multi_sim_comm.Sum(inv_s2); + } } comm.Sum(inv_s2); @@ -1459,14 +1643,17 @@ void Metainference::getEnergyForceGJ(const std::vector &mean, const std: } void Metainference::getEnergyForceGJE(const std::vector &mean, const std::vector &dmean_x, - const std::vector &dmean_b) -{ + const std::vector &dmean_b) { const double scale2 = scale_*scale_; std::vector inv_s2(sigma_.size(),0.); if(master) { - for(unsigned i=0; i1) multi_sim_comm.Sum(&inv_s2[0],sigma_.size()); + for(unsigned i=0; i1) { + multi_sim_comm.Sum(&inv_s2[0],sigma_.size()); + } } comm.Sum(&inv_s2[0],sigma_.size()); @@ -1488,8 +1675,7 @@ void Metainference::getEnergyForceGJE(const std::vector &mean, const std } } -void Metainference::getEnergyForceMIGEN(const std::vector &mean, const std::vector &dmean_x, const std::vector &dmean_b) -{ +void Metainference::getEnergyForceMIGEN(const std::vector &mean, const std::vector &dmean_x, const std::vector &dmean_b) { std::vector inv_s2(sigma_.size(),0.); std::vector dev(sigma_.size(),0.); std::vector dev2(sigma_.size(),0.); @@ -1525,15 +1711,16 @@ void Metainference::getEnergyForceMIGEN(const std::vector &mean, const s } } -void Metainference::get_weights(const unsigned iselect, double &weight, double &norm, double &neff) -{ +void Metainference::get_weights(const unsigned iselect, double &weight, double &norm, double &neff) { const double dnrep = static_cast(nrep_); // calculate the weights either from BIAS if(do_reweight_) { std::vector bias(nrep_,0); if(master) { bias[replica_] = getArgument(narg); - if(nrep_>1) multi_sim_comm.Sum(&bias[0], nrep_); + if(nrep_>1) { + multi_sim_comm.Sum(&bias[0], nrep_); + } } comm.Sum(&bias[0], nrep_); @@ -1546,12 +1733,16 @@ void Metainference::get_weights(const unsigned iselect, double &weight, double & } } else { firstTimeW[iselect] = false; - for(unsigned i=0; iset(neff); } -void Metainference::get_sigma_mean(const unsigned iselect, const double weight, const double norm, const double neff, const std::vector &mean) -{ +void Metainference::get_sigma_mean(const unsigned iselect, const double weight, const double norm, const double neff, const std::vector &mean) { const double dnrep = static_cast(nrep_); std::vector sigma_mean2_tmp(sigma_mean2_.size(), 0.); if(do_optsigmamean_>0) { // remove first entry of the history std::vector if(sigma_mean2_last_[iselect][0].size()==optsigmamean_stride_&&optsigmamean_stride_>0) - for(unsigned i=0; i sigma_mean2_now(narg,0); if(master) { - for(unsigned i=0; i1) multi_sim_comm.Sum(&sigma_mean2_now[0], narg); + for(unsigned i=0; i1) { + multi_sim_comm.Sum(&sigma_mean2_now[0], narg); + } } comm.Sum(&sigma_mean2_now[0], narg); - for(unsigned i=0; i0) { - for(unsigned i=0; i sigma_mean2_last_[iselect][i][0]) sigma_mean2_last_[iselect][i][0] = sigma_mean2_now[i]; + for(unsigned i=0; i sigma_mean2_last_[iselect][i][0]) { + sigma_mean2_last_[iselect][i][0] = sigma_mean2_now[i]; + } } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { @@ -1605,13 +1808,17 @@ void Metainference::get_sigma_mean(const unsigned iselect, const double weight, valueSigmaMean[i]->set(std::sqrt(sigma_mean2_tmp[i])); if(noise_type_==GENERIC) { sigma_min_[i] = std::sqrt(sigma_mean2_tmp[i]); - if(sigma_[i] < sigma_min_[i]) sigma_[i] = sigma_min_[i]; + if(sigma_[i] < sigma_min_[i]) { + sigma_[i] = sigma_min_[i]; + } } } } else if(noise_type_==GAUSS||noise_type_==OUTLIERS) { // find maximum for each data point std::vector max_values; - for(unsigned i=0; i1&&!sigmamax_opt_done_) { for(unsigned i=0; ioptsigmamean_stride_) sigma_max_est_[i]=sigma_mean2_tmp[i]; + if(sigma_max_est_[i]optsigmamean_stride_) { + sigma_max_est_[i]=sigma_mean2_tmp[i]; + } // ready to set once and for all the value of sigma_max if(optimized_step_==N_optimized_step_) { sigmamax_opt_done_=true; for(unsigned i=0; isigma_max_[i]) sigma_[i]=sigma_max_[i]; + if(sigma_[i]>sigma_max_[i]) { + sigma_[i]=sigma_max_[i]; + } } } } @@ -1651,22 +1862,29 @@ void Metainference::get_sigma_mean(const unsigned iselect, const double weight, sigma_mean2_ = sigma_mean2_tmp; } -void Metainference::replica_averaging(const double weight, const double norm, std::vector &mean, std::vector &dmean_b) -{ +void Metainference::replica_averaging(const double weight, const double norm, std::vector &mean, std::vector &dmean_b) { if(master) { - for(unsigned i=0; i1) multi_sim_comm.Sum(&mean[0], narg); + for(unsigned i=0; i1) { + multi_sim_comm.Sum(&mean[0], narg); + } } comm.Sum(&mean[0], narg); // set the derivative of the mean with respect to the bias - for(unsigned i=0; i(average_weights_stride_); + for(unsigned i=0; i(average_weights_stride_); + } // this is only for generic metainference - if(firstTime) {ftilde_ = mean; firstTime = false;} + if(firstTime) { + ftilde_ = mean; + firstTime = false; + } } -void Metainference::do_regression_zero(const std::vector &mean) -{ +void Metainference::do_regression_zero(const std::vector &mean) { // parameters[i] = scale_ * mean[i]: find scale_ with linear regression double num = 0.0; double den = 0.0; @@ -1681,14 +1899,15 @@ void Metainference::do_regression_zero(const std::vector &mean) } } -void Metainference::calculate() -{ +void Metainference::calculate() { // get step const long long int step = getStep(); unsigned iselect = 0; // set the value of selector for REM-like stuff - if(selector_.length()>0) iselect = static_cast(plumed.passMap[selector_]); + if(selector_.length()>0) { + iselect = static_cast(plumed.passMap[selector_]); + } /* 1) collect weights */ double weight = 0.; @@ -1709,7 +1928,9 @@ void Metainference::calculate() get_sigma_mean(iselect, weight, norm, neff, mean); // in case of regression with zero intercept, calculate scale - if(doregres_zero_ && step%nregres_zero_==0) do_regression_zero(mean); + if(doregres_zero_ && step%nregres_zero_==0) { + do_regression_zero(mean); + } /* 4) run monte carlo */ double ene = doMonteCarlo(mean); @@ -1736,8 +1957,7 @@ void Metainference::calculate() setBias(ene); } -void Metainference::writeStatus() -{ +void Metainference::writeStatus() { sfile_.rewind(); sfile_.printField("time",getTimeStep()*getStep()); //nsel @@ -1794,7 +2014,9 @@ void Metainference::writeStatus() void Metainference::update() { // write status file - if(write_stride_>0&& (getStep()%write_stride_==0 || getCPT()) ) writeStatus(); + if(write_stride_>0&& (getStep()%write_stride_==0 || getCPT()) ) { + writeStatus(); + } } } diff --git a/src/isdb/MetainferenceBase.cpp b/src/isdb/MetainferenceBase.cpp index 6e9d230827..4da6add335 100644 --- a/src/isdb/MetainferenceBase.cpp +++ b/src/isdb/MetainferenceBase.cpp @@ -125,8 +125,7 @@ MetainferenceBase::MetainferenceBase(const ActionOptions&ao): N_optimized_step_(0), optimized_step_(0), sigmamax_opt_done_(false), - decay_w_(1.) -{ + decay_w_(1.) { parseFlag("DOSCORE", doscore_); bool noensemble = false; @@ -137,7 +136,9 @@ MetainferenceBase::MetainferenceBase(const ActionOptions&ao): if(master) { nrep_ = multi_sim_comm.Get_size(); replica_ = multi_sim_comm.Get_rank(); - if(noensemble) nrep_ = 1; + if(noensemble) { + nrep_ = 1; + } } else { nrep_ = 0; replica_ = 0; @@ -148,18 +149,29 @@ MetainferenceBase::MetainferenceBase(const ActionOptions&ao): parse("SELECTOR", selector_); parse("NSELECT", nsel_); // do checks - if(selector_.length()>0 && nsel_<=1) error("With SELECTOR active, NSELECT must be greater than 1"); - if(selector_.length()==0 && nsel_>1) error("With NSELECT greater than 1, you must specify SELECTOR"); + if(selector_.length()>0 && nsel_<=1) { + error("With SELECTOR active, NSELECT must be greater than 1"); + } + if(selector_.length()==0 && nsel_>1) { + error("With NSELECT greater than 1, you must specify SELECTOR"); + } // initialise firstTimeW firstTimeW.resize(nsel_, true); // reweight implies a different number of arguments (the latest one must always be the bias) parseFlag("REWEIGHT", do_reweight_); - if(do_reweight_&&getNumberOfArguments()!=1) error("To REWEIGHT one must provide one single bias as an argument"); - if(do_reweight_&&nrep_<2) error("REWEIGHT can only be used in parallel with 2 or more replicas"); - if(!getRestart()) average_weights_.resize(nsel_, std::vector (nrep_, 1./static_cast(nrep_))); - else average_weights_.resize(nsel_, std::vector (nrep_, 0.)); + if(do_reweight_&&getNumberOfArguments()!=1) { + error("To REWEIGHT one must provide one single bias as an argument"); + } + if(do_reweight_&&nrep_<2) { + error("REWEIGHT can only be used in parallel with 2 or more replicas"); + } + if(!getRestart()) { + average_weights_.resize(nsel_, std::vector (nrep_, 1./static_cast(nrep_))); + } else { + average_weights_.resize(nsel_, std::vector (nrep_, 0.)); + } unsigned averaging=0; parse("AVERAGING", averaging); @@ -170,50 +182,79 @@ MetainferenceBase::MetainferenceBase(const ActionOptions&ao): std::string stringa_noise; parse("NOISETYPE",stringa_noise); - if(stringa_noise=="GAUSS") noise_type_ = GAUSS; - else if(stringa_noise=="MGAUSS") noise_type_ = MGAUSS; - else if(stringa_noise=="OUTLIERS") noise_type_ = OUTLIERS; - else if(stringa_noise=="MOUTLIERS") noise_type_ = MOUTLIERS; - else if(stringa_noise=="GENERIC") noise_type_ = GENERIC; - else error("Unknown noise type!"); + if(stringa_noise=="GAUSS") { + noise_type_ = GAUSS; + } else if(stringa_noise=="MGAUSS") { + noise_type_ = MGAUSS; + } else if(stringa_noise=="OUTLIERS") { + noise_type_ = OUTLIERS; + } else if(stringa_noise=="MOUTLIERS") { + noise_type_ = MOUTLIERS; + } else if(stringa_noise=="GENERIC") { + noise_type_ = GENERIC; + } else { + error("Unknown noise type!"); + } if(noise_type_== GENERIC) { std::string stringa_like; parse("LIKELIHOOD",stringa_like); - if(stringa_like=="GAUSS") gen_likelihood_ = LIKE_GAUSS; - else if(stringa_like=="LOGN") gen_likelihood_ = LIKE_LOGN; - else error("Unknown likelihood type!"); + if(stringa_like=="GAUSS") { + gen_likelihood_ = LIKE_GAUSS; + } else if(stringa_like=="LOGN") { + gen_likelihood_ = LIKE_LOGN; + } else { + error("Unknown likelihood type!"); + } parse("DFTILDE",Dftilde_); } parse("WRITE_STRIDE",write_stride_); parse("STATUS_FILE",status_file_name_); - if(status_file_name_=="") status_file_name_ = "MISTATUS"+getLabel(); - else status_file_name_ = status_file_name_+getLabel(); + if(status_file_name_=="") { + status_file_name_ = "MISTATUS"+getLabel(); + } else { + status_file_name_ = status_file_name_+getLabel(); + } std::string stringa_optsigma; parse("OPTSIGMAMEAN", stringa_optsigma); - if(stringa_optsigma=="NONE") do_optsigmamean_=0; - else if(stringa_optsigma=="SEM") do_optsigmamean_=1; - else if(stringa_optsigma=="SEM_MAX") do_optsigmamean_=2; + if(stringa_optsigma=="NONE") { + do_optsigmamean_=0; + } else if(stringa_optsigma=="SEM") { + do_optsigmamean_=1; + } else if(stringa_optsigma=="SEM_MAX") { + do_optsigmamean_=2; + } unsigned aver_max_steps=0; parse("SIGMA_MAX_STEPS", aver_max_steps); - if(aver_max_steps==0&&do_optsigmamean_==2) aver_max_steps=averaging*2000; - if(aver_max_steps>0&&do_optsigmamean_<2) error("SIGMA_MAX_STEPS can only be used together with OPTSIGMAMEAN=SEM_MAX"); - if(aver_max_steps>0&&do_optsigmamean_==2) N_optimized_step_=aver_max_steps; - if(aver_max_steps>0&&aver_max_steps0&&do_optsigmamean_<2) { + error("SIGMA_MAX_STEPS can only be used together with OPTSIGMAMEAN=SEM_MAX"); + } + if(aver_max_steps>0&&do_optsigmamean_==2) { + N_optimized_step_=aver_max_steps; + } + if(aver_max_steps>0&&aver_max_steps read_sigma_mean_; parseVector("SIGMA_MEAN0",read_sigma_mean_); - if(do_optsigmamean_==0 && read_sigma_mean_.size()==0 && !getRestart() && doscore_) + if(do_optsigmamean_==0 && read_sigma_mean_.size()==0 && !getRestart() && doscore_) { error("If you don't use OPTSIGMAMEAN and you are not RESTARTING then you MUST SET SIGMA_MEAN0"); + } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { if(read_sigma_mean_.size()>0) { sigma_mean2_.resize(read_sigma_mean_.size()); - for(unsigned i=0; i readsigma; parseVector("SIGMA0",readsigma); - if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma.size()>1) + if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma.size()>1) { error("If you want to use more than one SIGMA you should use NOISETYPE=MGAUSS|MOUTLIERS|GENERIC"); + } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { sigma_.resize(readsigma.size()); sigma_=readsigma; - } else sigma_.resize(1, readsigma[0]); + } else { + sigma_.resize(1, readsigma[0]); + } std::vector readsigma_min; parseVector("SIGMA_MIN",readsigma_min); - if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_min.size()>1) + if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_min.size()>1) { error("If you want to use more than one SIGMA you should use NOISETYPE=MGAUSS|MOUTLIERS|GENERIC"); + } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { sigma_min_.resize(readsigma_min.size()); sigma_min_=readsigma_min; - } else sigma_min_.resize(1, readsigma_min[0]); + } else { + sigma_min_.resize(1, readsigma_min[0]); + } std::vector readsigma_max; parseVector("SIGMA_MAX",readsigma_max); - if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_max.size()>1) + if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_max.size()>1) { error("If you want to use more than one SIGMA you should use NOISETYPE=MGAUSS|MOUTLIERS|GENERIC"); + } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { sigma_max_.resize(readsigma_max.size()); sigma_max_=readsigma_max; - } else sigma_max_.resize(1, readsigma_max[0]); + } else { + sigma_max_.resize(1, readsigma_max[0]); + } - if(sigma_max_.size()!=sigma_min_.size()) error("The number of values for SIGMA_MIN and SIGMA_MAX must be the same"); + if(sigma_max_.size()!=sigma_min_.size()) { + error("The number of values for SIGMA_MIN and SIGMA_MAX must be the same"); + } std::vector read_dsigma; parseVector("DSIGMA",read_dsigma); - if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_max.size()>1) + if((noise_type_!=MGAUSS&&noise_type_!=MOUTLIERS&&noise_type_!=GENERIC)&&readsigma_max.size()>1) { error("If you want to use more than one SIGMA you should use NOISETYPE=MGAUSS|MOUTLIERS|GENERIC"); + } if(read_dsigma.size()>0) { Dsigma_.resize(read_dsigma.size()); Dsigma_=read_dsigma; @@ -322,7 +397,9 @@ MetainferenceBase::MetainferenceBase(const ActionOptions&ao): parse("MC_CHUNKSIZE", MCchunksize_); // get temperature kbt_=getkBT(); - if(kbt_==0.0&&doscore_) error("Unless the MD engine passes the temperature to plumed, you must specify it using TEMP"); + if(kbt_==0.0&&doscore_) { + error("Unless the MD engine passes the temperature to plumed, you must specify it using TEMP"); + } // initialize random seed unsigned iseed; @@ -340,7 +417,9 @@ MetainferenceBase::MetainferenceBase(const ActionOptions&ao): // in this case we want the same seed everywhere auto ts = std::chrono::time_point_cast(std::chrono::steady_clock::now()).time_since_epoch().count(); iseed = static_cast(ts); - if(master&&nrep_>1) multi_sim_comm.Bcast(iseed,0); + if(master&&nrep_>1) { + multi_sim_comm.Bcast(iseed,0); + } comm.Bcast(iseed,0); // this is used for scale and offset sampling and acceptance random[1].setSeed(-iseed); @@ -363,24 +442,28 @@ MetainferenceBase::MetainferenceBase(const ActionOptions&ao): } -MetainferenceBase::~MetainferenceBase() -{ - if(sfile_.isOpen()) sfile_.close(); +MetainferenceBase::~MetainferenceBase() { + if(sfile_.isOpen()) { + sfile_.close(); + } } -void MetainferenceBase::Initialise(const unsigned input) -{ +void MetainferenceBase::Initialise(const unsigned input) { setNarg(input); if(narg!=parameters.size()) { - std::string num1; Tools::convert(parameters.size(),num1); - std::string num2; Tools::convert(narg,num2); + std::string num1; + Tools::convert(parameters.size(),num1); + std::string num2; + Tools::convert(narg,num2); std::string msg = "The number of experimental values " + num1 +" must be the same of the calculated values " + num2; error(msg); } // resize std::vector for sigma_mean history sigma_mean2_last_.resize(nsel_); - for(unsigned i=0; i1) multi_sim_comm.Sum(&average_weights_[i][0], nrep_); + if(nrep_>1) { + multi_sim_comm.Sum(&average_weights_[i][0], nrep_); + } } comm.Sum(&average_weights_[i][0], nrep_); } @@ -509,7 +606,10 @@ void MetainferenceBase::Initialise(const unsigned input) } /* If DSIGMA is not yet initialised do it now */ - for(unsigned i=0; iset(std::sqrt(sigma_mean2_[i])); - addComponent("sigma-"+num); componentIsNotPeriodic("sigma-"+num); + addComponent("sigma-"+num); + componentIsNotPeriodic("sigma-"+num); valueSigma.push_back(getPntrToComponent("sigma-"+num)); getPntrToComponent("sigma-"+num)->set(sigma_[i]); if(noise_type_==GENERIC) { - addComponent("ftilde-"+num); componentIsNotPeriodic("ftilde-"+num); + addComponent("ftilde-"+num); + componentIsNotPeriodic("ftilde-"+num); valueFtilde.push_back(getPntrToComponent("ftilde-"+num)); } } } else { - addComponent("sigmaMean"); componentIsNotPeriodic("sigmaMean"); + addComponent("sigmaMean"); + componentIsNotPeriodic("sigmaMean"); valueSigmaMean.push_back(getPntrToComponent("sigmaMean")); getPntrToComponent("sigmaMean")->set(std::sqrt(sigma_mean2_[0])); - addComponent("sigma"); componentIsNotPeriodic("sigma"); + addComponent("sigma"); + componentIsNotPeriodic("sigma"); valueSigma.push_back(getPntrToComponent("sigma")); getPntrToComponent("sigma")->set(sigma_[0]); } @@ -579,8 +685,11 @@ void MetainferenceBase::Initialise(const unsigned input) switch(noise_type_) { case GENERIC: log.printf(" with general metainference "); - if(gen_likelihood_==LIKE_GAUSS) log.printf(" and a gaussian likelihood\n"); - else if(gen_likelihood_==LIKE_LOGN) log.printf(" and a log-normal likelihood\n"); + if(gen_likelihood_==LIKE_GAUSS) { + log.printf(" and a gaussian likelihood\n"); + } else if(gen_likelihood_==LIKE_LOGN) { + log.printf(" and a log-normal likelihood\n"); + } log.printf(" ensemble average parameter sampled with a step %lf of sigma_mean\n", Dftilde_); break; case GAUSS: @@ -607,7 +716,9 @@ void MetainferenceBase::Initialise(const unsigned input) comm.Sum(dummy_scale); for(unsigned i=1; i0) log<0) { + log<0) iselect = static_cast(plumed.passMap[selector_]); + if(selector_.length()>0) { + iselect = static_cast(plumed.passMap[selector_]); + } } double MetainferenceBase::getEnergySP(const std::vector &mean, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { const double scale2 = scale*scale; const double sm2 = sigma_mean2_[0]; const double ss2 = sigma[0]*sigma[0] + scale2*sm2; @@ -701,22 +829,24 @@ double MetainferenceBase::getEnergySP(const std::vector &mean, const std const double a2 = 0.5*dev*dev + ss2; if(sm2 > 0.0) { ene += std::log(2.0*a2/(1.0-std::exp(-a2/sm2))); - } - else { + } else { ene += std::log(2.0*a2); } } } // add one single Jeffrey's prior and one normalisation per data point ene += 0.5*std::log(sss) + static_cast(narg)*0.5*std::log(0.5*M_PI*M_PI/ss2); - if(doscale_ || doregres_zero_) ene += 0.5*std::log(sss); - if(dooffset_) ene += 0.5*std::log(sss); + if(doscale_ || doregres_zero_) { + ene += 0.5*std::log(sss); + } + if(dooffset_) { + ene += 0.5*std::log(sss); + } return kbt_ * ene; } double MetainferenceBase::getEnergySPE(const std::vector &mean, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { const double scale2 = scale*scale; double ene = 0.0; #pragma omp parallel num_threads(OpenMP::getNumThreads()) shared(ene) @@ -730,20 +860,22 @@ double MetainferenceBase::getEnergySPE(const std::vector &mean, const st const double a2 = 0.5*dev*dev + ss2; if(sm2 > 0.0) { ene += 0.5*std::log(sss) + 0.5*std::log(0.5*M_PI*M_PI/ss2) + std::log(2.0*a2/(1.0-std::exp(-a2/sm2))); - } - else { + } else { ene += 0.5*std::log(sss) + 0.5*std::log(0.5*M_PI*M_PI/ss2) + std::log(2.0*a2); } - if(doscale_ || doregres_zero_) ene += 0.5*std::log(sss); - if(dooffset_) ene += 0.5*std::log(sss); + if(doscale_ || doregres_zero_) { + ene += 0.5*std::log(sss); + } + if(dooffset_) { + ene += 0.5*std::log(sss); + } } } return kbt_ * ene; } double MetainferenceBase::getEnergyMIGEN(const std::vector &mean, const std::vector &ftilde, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { double ene = 0.0; #pragma omp parallel num_threads(OpenMP::getNumThreads()) shared(ene) { @@ -752,26 +884,35 @@ double MetainferenceBase::getEnergyMIGEN(const std::vector &mean, const const double inv_sb2 = 1./(sigma[i]*sigma[i]); const double inv_sm2 = 1./sigma_mean2_[i]; double devb = 0; - if(gen_likelihood_==LIKE_GAUSS) devb = scale*ftilde[i]-parameters[i]+offset; - else if(gen_likelihood_==LIKE_LOGN) devb = std::log(scale*ftilde[i]/parameters[i]); + if(gen_likelihood_==LIKE_GAUSS) { + devb = scale*ftilde[i]-parameters[i]+offset; + } else if(gen_likelihood_==LIKE_LOGN) { + devb = std::log(scale*ftilde[i]/parameters[i]); + } double devm = mean[i] - ftilde[i]; // deviation + normalisation + jeffrey double normb = 0.; - if(gen_likelihood_==LIKE_GAUSS) normb = -0.5*std::log(0.5/M_PI*inv_sb2); - else if(gen_likelihood_==LIKE_LOGN) normb = -0.5*std::log(0.5/M_PI*inv_sb2/(parameters[i]*parameters[i])); + if(gen_likelihood_==LIKE_GAUSS) { + normb = -0.5*std::log(0.5/M_PI*inv_sb2); + } else if(gen_likelihood_==LIKE_LOGN) { + normb = -0.5*std::log(0.5/M_PI*inv_sb2/(parameters[i]*parameters[i])); + } const double normm = -0.5*std::log(0.5/M_PI*inv_sm2); const double jeffreys = -0.5*std::log(2.*inv_sb2); ene += 0.5*devb*devb*inv_sb2 + 0.5*devm*devm*inv_sm2 + normb + normm + jeffreys; - if(doscale_ || doregres_zero_) ene += jeffreys; - if(dooffset_) ene += jeffreys; + if(doscale_ || doregres_zero_) { + ene += jeffreys; + } + if(dooffset_) { + ene += jeffreys; + } } } return kbt_ * ene; } double MetainferenceBase::getEnergyGJ(const std::vector &mean, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { const double scale2 = scale*scale; const double inv_s2 = 1./(sigma[0]*sigma[0] + scale2*sigma_mean2_[0]); const double inv_sss = 1./(sigma[0]*sigma[0] + sigma_mean2_[0]); @@ -789,15 +930,18 @@ double MetainferenceBase::getEnergyGJ(const std::vector &mean, const std const double jeffreys = -0.5*std::log(2.*inv_sss); // add Jeffrey's prior in case one sigma for all data points + one normalisation per datapoint ene += jeffreys + static_cast(narg)*normalisation; - if(doscale_ || doregres_zero_) ene += jeffreys; - if(dooffset_) ene += jeffreys; + if(doscale_ || doregres_zero_) { + ene += jeffreys; + } + if(dooffset_) { + ene += jeffreys; + } return kbt_ * ene; } double MetainferenceBase::getEnergyGJE(const std::vector &mean, const std::vector &sigma, - const double scale, const double offset) -{ + const double scale, const double offset) { const double scale2 = scale*scale; double ene = 0.0; @@ -812,15 +956,18 @@ double MetainferenceBase::getEnergyGJE(const std::vector &mean, const st const double normalisation = -0.5*std::log(0.5/M_PI*inv_s2); const double jeffreys = -0.5*std::log(2.*inv_sss); ene += 0.5*dev*dev*inv_s2 + normalisation + jeffreys; - if(doscale_ || doregres_zero_) ene += jeffreys; - if(dooffset_) ene += jeffreys; + if(doscale_ || doregres_zero_) { + ene += jeffreys; + } + if(dooffset_) { + ene += jeffreys; + } } } return kbt_ * ene; } -void MetainferenceBase::moveTilde(const std::vector &mean_, double &old_energy) -{ +void MetainferenceBase::moveTilde(const std::vector &mean_, double &old_energy) { std::vector new_ftilde(sigma_.size()); new_ftilde = ftilde_; @@ -851,8 +998,7 @@ void MetainferenceBase::moveTilde(const std::vector &mean_, double &old_ } } -void MetainferenceBase::moveScaleOffset(const std::vector &mean_, double &old_energy) -{ +void MetainferenceBase::moveScaleOffset(const std::vector &mean_, double &old_energy) { double new_scale = scale_; if(doscale_) { @@ -861,8 +1007,12 @@ void MetainferenceBase::moveScaleOffset(const std::vector &mean_, double const double ds1 = Dscale_*r1; new_scale += ds1; // check boundaries - if(new_scale > scale_max_) {new_scale = 2.0 * scale_max_ - new_scale;} - if(new_scale < scale_min_) {new_scale = 2.0 * scale_min_ - new_scale;} + if(new_scale > scale_max_) { + new_scale = 2.0 * scale_max_ - new_scale; + } + if(new_scale < scale_min_) { + new_scale = 2.0 * scale_min_ - new_scale; + } } else { const double r1 = random[1].Gaussian(); const double ds1 = 0.5*(scale_mu_-new_scale)+Dscale_*std::exp(1)/M_PI*r1; @@ -878,8 +1028,12 @@ void MetainferenceBase::moveScaleOffset(const std::vector &mean_, double const double ds1 = Doffset_*r1; new_offset += ds1; // check boundaries - if(new_offset > offset_max_) {new_offset = 2.0 * offset_max_ - new_offset;} - if(new_offset < offset_min_) {new_offset = 2.0 * offset_min_ - new_offset;} + if(new_offset > offset_max_) { + new_offset = 2.0 * offset_max_ - new_offset; + } + if(new_offset < offset_min_) { + new_offset = 2.0 * offset_min_ - new_offset; + } } else { const double r1 = random[1].Gaussian(); const double ds1 = 0.5*(offset_mu_-new_offset)+Doffset_*std::exp(1)/M_PI*r1; @@ -913,7 +1067,9 @@ void MetainferenceBase::moveScaleOffset(const std::vector &mean_, double if(master) { totenergies[0] = old_energy; totenergies[1] = new_energy; - if(nrep_>1) multi_sim_comm.Sum(totenergies); + if(nrep_>1) { + multi_sim_comm.Sum(totenergies); + } } else { totenergies[0] = 0; totenergies[1] = 0; @@ -940,8 +1096,7 @@ void MetainferenceBase::moveScaleOffset(const std::vector &mean_, double } } -void MetainferenceBase::moveSigmas(const std::vector &mean_, double &old_energy, const unsigned i, const std::vector &indices, bool &breaknow) -{ +void MetainferenceBase::moveSigmas(const std::vector &mean_, double &old_energy, const unsigned i, const std::vector &indices, bool &breaknow) { std::vector new_sigma(sigma_.size()); new_sigma = sigma_; @@ -964,8 +1119,12 @@ void MetainferenceBase::moveSigmas(const std::vector &mean_, double &old const double ds2 = Dsigma_[index]*r2; new_sigma[index] = sigma_[index] + ds2; // check boundaries - if(new_sigma[index] > sigma_max_[index]) {new_sigma[index] = 2.0 * sigma_max_[index] - new_sigma[index];} - if(new_sigma[index] < sigma_min_[index]) {new_sigma[index] = 2.0 * sigma_min_[index] - new_sigma[index];} + if(new_sigma[index] > sigma_max_[index]) { + new_sigma[index] = 2.0 * sigma_max_[index] - new_sigma[index]; + } + if(new_sigma[index] < sigma_min_[index]) { + new_sigma[index] = 2.0 * sigma_min_[index] - new_sigma[index]; + } } } else { // change all sigmas @@ -974,8 +1133,12 @@ void MetainferenceBase::moveSigmas(const std::vector &mean_, double &old const double ds2 = Dsigma_[j]*r2; new_sigma[j] = sigma_[j] + ds2; // check boundaries - if(new_sigma[j] > sigma_max_[j]) {new_sigma[j] = 2.0 * sigma_max_[j] - new_sigma[j];} - if(new_sigma[j] < sigma_min_[j]) {new_sigma[j] = 2.0 * sigma_min_[j] - new_sigma[j];} + if(new_sigma[j] > sigma_max_[j]) { + new_sigma[j] = 2.0 * sigma_max_[j] - new_sigma[j]; + } + if(new_sigma[j] < sigma_min_[j]) { + new_sigma[j] = 2.0 * sigma_min_[j] - new_sigma[j]; + } } } @@ -1022,8 +1185,7 @@ void MetainferenceBase::moveSigmas(const std::vector &mean_, double &old } } -double MetainferenceBase::doMonteCarlo(const std::vector &mean_) -{ +double MetainferenceBase::doMonteCarlo(const std::vector &mean_) { // calculate old energy with the updated coordinates double old_energy=0.; @@ -1062,13 +1224,19 @@ double MetainferenceBase::doMonteCarlo(const std::vector &mean_) for(unsigned i=0; i &mean_) if(noise_type_==GENERIC) { double accept = static_cast(MCacceptFT_) / static_cast(MCtrial_); valueAcceptFT->set(accept); - for(unsigned i=0; iset(ftilde_[i]); + for(unsigned i=0; iset(ftilde_[i]); + } } /* scale and offset */ - if(doscale_ || doregres_zero_) valueScale->set(scale_); - if(dooffset_) valueOffset->set(offset_); + if(doscale_ || doregres_zero_) { + valueScale->set(scale_); + } + if(dooffset_) { + valueOffset->set(offset_); + } if(doscale_||dooffset_) { double accept = static_cast(MCacceptScale_) / static_cast(MCtrial_); valueAcceptScale->set(accept); } /* sigmas */ - for(unsigned i=0; iset(sigma_[i]); + for(unsigned i=0; iset(sigma_[i]); + } double accept = static_cast(MCaccept_) / static_cast(MCtrial_); valueAccept->set(accept); } // here we sum the score over the replicas to get the full metainference score that we save as a bias if(master) { - if(nrep_>1) multi_sim_comm.Sum(old_energy); + if(nrep_>1) { + multi_sim_comm.Sum(old_energy); + } } else { old_energy=0; } @@ -1110,8 +1288,7 @@ double MetainferenceBase::doMonteCarlo(const std::vector &mean_) */ void MetainferenceBase::getEnergyForceSP(const std::vector &mean, const std::vector &dmean_x, - const std::vector &dmean_b) -{ + const std::vector &dmean_b) { const double scale2 = scale_*scale_; const double sm2 = sigma_mean2_[0]; const double ss2 = sigma_[0]*sigma_[0] + scale2*sm2; @@ -1129,14 +1306,15 @@ void MetainferenceBase::getEnergyForceSP(const std::vector &mean, const const double dt = 1./t; const double dit = 1./(1.-dt); f[i] = -scale_*dev*(dit/sm2 + 1./a2); - } - else { + } else { f[i] = -scale_*dev*(1./a2); } } } // collect contribution to forces and energy from other replicas - if(nrep_>1) multi_sim_comm.Sum(&f[0],narg); + if(nrep_>1) { + multi_sim_comm.Sum(&f[0],narg); + } } // intra-replica summation comm.Sum(&f[0],narg); @@ -1154,8 +1332,7 @@ void MetainferenceBase::getEnergyForceSP(const std::vector &mean, const } void MetainferenceBase::getEnergyForceSPE(const std::vector &mean, const std::vector &dmean_x, - const std::vector &dmean_b) -{ + const std::vector &dmean_b) { const double scale2 = scale_*scale_; std::vector f(narg,0); @@ -1173,14 +1350,15 @@ void MetainferenceBase::getEnergyForceSPE(const std::vector &mean, const const double dt = 1./t; const double dit = 1./(1.-dt); f[i] = -scale_*dev*(dit/sm2 + 1./a2); - } - else { + } else { f[i] = -scale_*dev*(1./a2); } } } // collect contribution to forces and energy from other replicas - if(nrep_>1) multi_sim_comm.Sum(&f[0],narg); + if(nrep_>1) { + multi_sim_comm.Sum(&f[0],narg); + } } comm.Sum(&f[0],narg); @@ -1197,14 +1375,15 @@ void MetainferenceBase::getEnergyForceSPE(const std::vector &mean, const } void MetainferenceBase::getEnergyForceGJ(const std::vector &mean, const std::vector &dmean_x, - const std::vector &dmean_b) -{ + const std::vector &dmean_b) { const double scale2 = scale_*scale_; double inv_s2=0.; if(master) { inv_s2 = 1./(sigma_[0]*sigma_[0] + scale2*sigma_mean2_[0]); - if(nrep_>1) multi_sim_comm.Sum(inv_s2); + if(nrep_>1) { + multi_sim_comm.Sum(inv_s2); + } } comm.Sum(inv_s2); @@ -1227,14 +1406,17 @@ void MetainferenceBase::getEnergyForceGJ(const std::vector &mean, const } void MetainferenceBase::getEnergyForceGJE(const std::vector &mean, const std::vector &dmean_x, - const std::vector &dmean_b) -{ + const std::vector &dmean_b) { const double scale2 = scale_*scale_; std::vector inv_s2(sigma_.size(),0.); if(master) { - for(unsigned i=0; i1) multi_sim_comm.Sum(&inv_s2[0],sigma_.size()); + for(unsigned i=0; i1) { + multi_sim_comm.Sum(&inv_s2[0],sigma_.size()); + } } comm.Sum(&inv_s2[0],sigma_.size()); @@ -1256,8 +1438,7 @@ void MetainferenceBase::getEnergyForceGJE(const std::vector &mean, const } } -void MetainferenceBase::getEnergyForceMIGEN(const std::vector &mean, const std::vector &dmean_x, const std::vector &dmean_b) -{ +void MetainferenceBase::getEnergyForceMIGEN(const std::vector &mean, const std::vector &dmean_x, const std::vector &dmean_b) { std::vector inv_s2(sigma_.size(),0.); std::vector dev(sigma_.size(),0.); std::vector dev2(sigma_.size(),0.); @@ -1293,15 +1474,16 @@ void MetainferenceBase::getEnergyForceMIGEN(const std::vector &mean, con } } -void MetainferenceBase::get_weights(double &weight, double &norm, double &neff) -{ +void MetainferenceBase::get_weights(double &weight, double &norm, double &neff) { const double dnrep = static_cast(nrep_); // calculate the weights either from BIAS if(do_reweight_) { std::vector bias(nrep_,0); if(master) { bias[replica_] = getArgument(0); - if(nrep_>1) multi_sim_comm.Sum(&bias[0], nrep_); + if(nrep_>1) { + multi_sim_comm.Sum(&bias[0], nrep_); + } } comm.Sum(&bias[0], nrep_); @@ -1313,12 +1495,16 @@ void MetainferenceBase::get_weights(double &weight, double &norm, double &neff) } } else { firstTimeW[iselect] = false; - for(unsigned i=0; iset(neff); } -void MetainferenceBase::get_sigma_mean(const double weight, const double norm, const double neff, const std::vector &mean) -{ +void MetainferenceBase::get_sigma_mean(const double weight, const double norm, const double neff, const std::vector &mean) { const double dnrep = static_cast(nrep_); std::vector sigma_mean2_tmp(sigma_mean2_.size()); if(do_optsigmamean_>0) { // remove first entry of the history std::vector if(sigma_mean2_last_[iselect][0].size()==optsigmamean_stride_&&optsigmamean_stride_>0) - for(unsigned i=0; i sigma_mean2_now(narg,0); if(master) { - for(unsigned i=0; i1) multi_sim_comm.Sum(&sigma_mean2_now[0], narg); + for(unsigned i=0; i1) { + multi_sim_comm.Sum(&sigma_mean2_now[0], narg); + } } comm.Sum(&sigma_mean2_now[0], narg); - for(unsigned i=0; i0) { - for(unsigned i=0; i sigma_mean2_last_[iselect][i][0]) sigma_mean2_last_[iselect][i][0] = sigma_mean2_now[i]; + for(unsigned i=0; i sigma_mean2_last_[iselect][i][0]) { + sigma_mean2_last_[iselect][i][0] = sigma_mean2_now[i]; + } } if(noise_type_==MGAUSS||noise_type_==MOUTLIERS||noise_type_==GENERIC) { @@ -1372,13 +1570,17 @@ void MetainferenceBase::get_sigma_mean(const double weight, const double norm, c valueSigmaMean[i]->set(std::sqrt(sigma_mean2_tmp[i])); if(noise_type_==GENERIC) { sigma_min_[i] = std::sqrt(sigma_mean2_tmp[i]); - if(sigma_[i] < sigma_min_[i]) sigma_[i] = sigma_min_[i]; + if(sigma_[i] < sigma_min_[i]) { + sigma_[i] = sigma_min_[i]; + } } } } else if(noise_type_==GAUSS||noise_type_==OUTLIERS) { // find maximum for each data point std::vector max_values; - for(unsigned i=0; i1&&!sigmamax_opt_done_) { for(unsigned i=0; ioptsigmamean_stride_) sigma_max_est_[i]=sigma_mean2_tmp[i]; + if(sigma_max_est_[i]optsigmamean_stride_) { + sigma_max_est_[i]=sigma_mean2_tmp[i]; + } // ready to set once and for all the value of sigma_max if(optimized_step_==N_optimized_step_) { sigmamax_opt_done_=true; for(unsigned i=0; isigma_max_[i]) sigma_[i]=sigma_max_[i]; + if(sigma_[i]>sigma_max_[i]) { + sigma_[i]=sigma_max_[i]; + } } } } @@ -1418,22 +1624,29 @@ void MetainferenceBase::get_sigma_mean(const double weight, const double norm, c sigma_mean2_ = sigma_mean2_tmp; } -void MetainferenceBase::replica_averaging(const double weight, const double norm, std::vector &mean, std::vector &dmean_b) -{ +void MetainferenceBase::replica_averaging(const double weight, const double norm, std::vector &mean, std::vector &dmean_b) { if(master) { - for(unsigned i=0; i1) multi_sim_comm.Sum(&mean[0], narg); + for(unsigned i=0; i1) { + multi_sim_comm.Sum(&mean[0], narg); + } } comm.Sum(&mean[0], narg); // set the derivative of the mean with respect to the bias - for(unsigned i=0; i &mean) -{ +void MetainferenceBase::do_regression_zero(const std::vector &mean) { // parameters[i] = scale_ * mean[i]: find scale_ with linear regression double num = 0.0; double den = 0.0; @@ -1448,8 +1661,7 @@ void MetainferenceBase::do_regression_zero(const std::vector &mean) } } -double MetainferenceBase::getScore() -{ +double MetainferenceBase::getScore() { /* Metainference */ /* 1) collect weights */ double weight = 0.; @@ -1470,7 +1682,9 @@ double MetainferenceBase::getScore() get_sigma_mean(weight, norm, neff, mean); // in case of regression with zero intercept, calculate scale - if(doregres_zero_ && getStep()%nregres_zero_==0) do_regression_zero(mean); + if(doregres_zero_ && getStep()%nregres_zero_==0) { + do_regression_zero(mean); + } /* 4) run monte carlo */ double ene = doMonteCarlo(mean); @@ -1497,9 +1711,10 @@ double MetainferenceBase::getScore() return ene; } -void MetainferenceBase::writeStatus() -{ - if(!doscore_) return; +void MetainferenceBase::writeStatus() { + if(!doscore_) { + return; + } sfile_.rewind(); sfile_.printField("time",getTimeStep()*getStep()); //nsel diff --git a/src/isdb/MetainferenceBase.h b/src/isdb/MetainferenceBase.h index 6767d0b425..5615eefa59 100644 --- a/src/isdb/MetainferenceBase.h +++ b/src/isdb/MetainferenceBase.h @@ -44,8 +44,7 @@ information as to how to go about implementing a new Metainference action. class MetainferenceBase : public ActionAtomistic, public ActionWithArguments, - public ActionWithValue -{ + public ActionWithValue { private: std::vector forces; std::vector forcesToApply; @@ -209,62 +208,57 @@ class MetainferenceBase : }; inline -void MetainferenceBase::setNarg(const unsigned input) -{ +void MetainferenceBase::setNarg(const unsigned input) { narg = input; } inline -bool MetainferenceBase::getDoScore() -{ +bool MetainferenceBase::getDoScore() { return doscore_; } inline -unsigned MetainferenceBase::getWstride() -{ +unsigned MetainferenceBase::getWstride() { return write_stride_; } inline -unsigned MetainferenceBase::getNarg() -{ +unsigned MetainferenceBase::getNarg() { return narg; } inline -void MetainferenceBase::setMetaDer(const unsigned index, const double der) -{ +void MetainferenceBase::setMetaDer(const unsigned index, const double der) { metader_[index] = der; } inline -double MetainferenceBase::getMetaDer(const unsigned index) -{ +double MetainferenceBase::getMetaDer(const unsigned index) { return metader_[index]; } inline -double MetainferenceBase::getCalcData(const unsigned index) -{ +double MetainferenceBase::getCalcData(const unsigned index) { return calc_data_[index]; } inline -void MetainferenceBase::setCalcData(const unsigned index, const double datum) -{ +void MetainferenceBase::setCalcData(const unsigned index, const double datum) { calc_data_[index] = datum; } inline -void MetainferenceBase::setCalcData(const std::vector& data) -{ - for(unsigned i=0; i& data) { + for(unsigned i=0; i& input) { - for(unsigned i=0; iresizeDerivatives(nder); + forces.resize( nder ); + forcesToApply.resize( nder ); + for(int i=0; iresizeDerivatives(nder); + } } inline @@ -326,27 +323,39 @@ void MetainferenceBase::calculateNumericalDerivatives( ActionWithValue* a=NULL ) if( getNumberOfAtoms()>0 ) { Matrix save_derivatives( getNumberOfComponents(), getNumberOfArguments() ); for(int j=0; jhasDerivatives()) save_derivatives(j,i)=getPntrToComponent(j)->getDerivative(i); + for(unsigned i=0; ihasDerivatives()) { + save_derivatives(j,i)=getPntrToComponent(j)->getDerivative(i); + } } calculateAtomicNumericalDerivatives( a, getNumberOfArguments() ); for(int j=0; jhasDerivatives()) getPntrToComponent(j)->addDerivative( i, save_derivatives(j,i) ); + for(unsigned i=0; ihasDerivatives()) { + getPntrToComponent(j)->addDerivative( i, save_derivatives(j,i) ); + } } } } inline void MetainferenceBase::apply() { - bool wasforced=false; forcesToApply.assign(forcesToApply.size(),0.0); + bool wasforced=false; + forcesToApply.assign(forcesToApply.size(),0.0); for(int i=0; iapplyForce( forces ) ) { wasforced=true; - for(unsigned i=0; i0 ) setForcesOnAtoms( forcesToApply, ind ); + unsigned ind=0; + addForcesOnArguments( 0, forcesToApply, ind, getLabel() ); + if( getNumberOfAtoms()>0 ) { + setForcesOnAtoms( forcesToApply, ind ); + } } } diff --git a/src/isdb/NOE.cpp b/src/isdb/NOE.cpp index 6db09fb287..98b80979f3 100644 --- a/src/isdb/NOE.cpp +++ b/src/isdb/NOE.cpp @@ -65,8 +65,7 @@ PRINT ARG=noes.* FILE=colvar //+ENDPLUMEDOC class NOE : - public MetainferenceBase -{ + public MetainferenceBase { private: bool pbc; std::vector nga; @@ -99,8 +98,7 @@ void NOE::registerKeywords( Keywords& keys ) { NOE::NOE(const ActionOptions&ao): PLUMED_METAINF_INIT(ao), - pbc(true) -{ + pbc(true) { bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; @@ -109,21 +107,33 @@ NOE::NOE(const ActionOptions&ao): std::vector t, ga_lista, gb_lista; for(int i=1;; ++i ) { parseAtomList("GROUPA", i, t ); - if( t.empty() ) break; - for(unsigned j=0; j ngb; for(int i=1;; ++i ) { parseAtomList("GROUPB", i, t ); - if( t.empty() ) break; - for(unsigned j=0; j(ga_lista,gb_lista,false,true,pbc,getPbc(),comm); @@ -132,13 +142,21 @@ NOE::NOE(const ActionOptions&ao): noedist.resize( nga.size() ); unsigned ntarget=0; for(unsigned i=0; i deriv(tot_size, Vector{0,0,0}); @@ -205,8 +229,11 @@ void NOE::calculate() Tensor dervir; double noe=0; unsigned index=0; - for(unsigned k=0; kgetClosePair(index+j).second; Vector distance; - if(pbc) distance=pbcDistance(getPosition(i0),getPosition(i1)); - else distance=delta(getPosition(i0),getPosition(i1)); + if(pbc) { + distance=pbcDistance(getPosition(i0),getPosition(i1)); + } else { + distance=delta(getPosition(i0),getPosition(i1)); + } const double ir2=1./distance.modulo2(); const double ir6=ir2*ir2*ir2; @@ -232,7 +262,9 @@ void NOE::calculate() val->set(noe); if(!getDoScore()) { setBoxDerivatives(val, dervir); - } else setCalcData(i, noe); + } else { + setCalcData(i, noe); + } } if(getDoScore()) { @@ -245,15 +277,20 @@ void NOE::calculate() Value* val=getPntrToComponent("score"); for(unsigned i=0; igetClosePair(index+j).first; const unsigned i1=nl->getClosePair(index+j).second; Vector distance; - if(pbc) distance=pbcDistance(getPosition(i0),getPosition(i1)); - else distance=delta(getPosition(i0),getPosition(i1)); + if(pbc) { + distance=pbcDistance(getPosition(i0),getPosition(i1)); + } else { + distance=delta(getPosition(i0),getPosition(i1)); + } dervir += Tensor(distance,deriv[index+j]*getMetaDer(i)); setAtomsDerivatives(val, i0, deriv[index+j]*getMetaDer(i)); @@ -266,7 +303,9 @@ void NOE::calculate() void NOE::update() { // write status file - if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) writeStatus(); + if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) { + writeStatus(); + } } } diff --git a/src/isdb/PRE.cpp b/src/isdb/PRE.cpp index 98a9a0e292..8b7903fc7a 100644 --- a/src/isdb/PRE.cpp +++ b/src/isdb/PRE.cpp @@ -68,8 +68,7 @@ PRINT ARG=HN_pre.* FILE=PRE.dat STRIDE=1 //+ENDPLUMEDOC class PRE : - public MetainferenceBase -{ + public MetainferenceBase { private: bool pbc; bool doratio; @@ -110,8 +109,7 @@ void PRE::registerKeywords( Keywords& keys ) { PRE::PRE(const ActionOptions&ao): PLUMED_METAINF_INIT(ao), pbc(true), - doratio(true) -{ + doratio(true) { bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; @@ -122,14 +120,21 @@ PRE::PRE(const ActionOptions&ao): std::vector atom; parseAtomList("SPINLABEL",atom); - if(atom.size()!=1) error("Number of specified atom should be 1"); + if(atom.size()!=1) { + error("Number of specified atom should be 1"); + } // Read in the atoms std::vector t, ga_lista, gb_lista; for(int i=1;; ++i ) { parseAtomList("GROUPA", i, t ); - if( t.empty() ) break; - for(unsigned j=0; j(gb_lista,ga_lista,false,true,pbc,getPbc(),comm); @@ -201,20 +226,25 @@ PRE::PRE(const ActionOptions&ao): } tot_size = index; - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } log << " Bibliography" << plumed.cite("Bonomi, Camilloni, Bioinformatics, 33, 3999 (2017)") << "\n"; if(!getDoScore()) { for(unsigned i=0; i deriv(tot_size, Vector{0,0,0}); std::vector fact(nga.size(), 0.); @@ -256,9 +287,12 @@ void PRE::calculate() Tensor dervir; double pre=0; unsigned index=0; - for(unsigned k=0; k(nga[i]); - std::string num; Tools::convert(i,num); + std::string num; + Tools::convert(i,num); Value* val=getPntrToComponent("pre-"+num); // cycle over equivalent atoms for(unsigned j=0; jgetClosePair(index+j).second; Vector distance; - if(pbc) distance=pbcDistance(getPosition(i0),getPosition(i1)); - else distance=delta(getPosition(i0),getPosition(i1)); + if(pbc) { + distance=pbcDistance(getPosition(i0),getPosition(i1)); + } else { + distance=delta(getPosition(i0),getPosition(i1)); + } const double r2=distance.modulo2(); const double r6=r2*r2*r2; @@ -278,7 +315,9 @@ void PRE::calculate() pre += tmpir6; deriv[index+j] = -tmpir8*distance; - if(!getDoScore()) dervir += Tensor(distance,deriv[index+j]); + if(!getDoScore()) { + dervir += Tensor(distance,deriv[index+j]); + } } double tmpratio; if(!doratio) { @@ -298,7 +337,9 @@ void PRE::calculate() setAtomsDerivatives(val, i0, fact[i]*deriv[index+j]); setAtomsDerivatives(val, i1, -fact[i]*deriv[index+j]); } - } else setCalcData(i, ratio); + } else { + setCalcData(i, ratio); + } } if(getDoScore()) { @@ -311,15 +352,20 @@ void PRE::calculate() Value* val=getPntrToComponent("score"); for(unsigned i=0; igetClosePair(index+j).first; const unsigned i1=nl->getClosePair(index+j).second; Vector distance; - if(pbc) distance=pbcDistance(getPosition(i0),getPosition(i1)); - else distance=delta(getPosition(i0),getPosition(i1)); + if(pbc) { + distance=pbcDistance(getPosition(i0),getPosition(i1)); + } else { + distance=delta(getPosition(i0),getPosition(i1)); + } dervir += Tensor(distance,fact[i]*deriv[index+j]*getMetaDer(i)); setAtomsDerivatives(val, i0, fact[i]*deriv[index+j]*getMetaDer(i)); @@ -332,7 +378,9 @@ void PRE::calculate() void PRE::update() { // write status file - if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) writeStatus(); + if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) { + writeStatus(); + } } } diff --git a/src/isdb/RDC.cpp b/src/isdb/RDC.cpp index 6c51df81e6..95eb8a3d46 100644 --- a/src/isdb/RDC.cpp +++ b/src/isdb/RDC.cpp @@ -172,8 +172,7 @@ PRINT ARG=st.corr,pcse.bias FILE=colvar //+ENDPLUMEDOC class RDC : - public MetainferenceBase -{ + public MetainferenceBase { private: double Const; double mu_s; @@ -246,8 +245,7 @@ RDC::RDC(const ActionOptions&ao): Const(1.), mu_s(1.), scale(1.), - pbc(true) -{ + pbc(true) { bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; @@ -255,16 +253,22 @@ RDC::RDC(const ActionOptions&ao): const double RDCConst = 0.3356806; const double PCSConst = 1.0; - if( getName().find("RDC")!=std::string::npos) { Const *= RDCConst; } - else if( getName().find("PCS")!=std::string::npos) { Const *= PCSConst; } + if( getName().find("RDC")!=std::string::npos) { + Const *= RDCConst; + } else if( getName().find("PCS")!=std::string::npos) { + Const *= PCSConst; + } // Read in the atoms std::vector t, atoms; for(int i=1;; ++i ) { parseAtomList("ATOMS", i, t ); - if( t.empty() ) break; + if( t.empty() ) { + break; + } if( t.size()!=2 ) { - std::string ss; Tools::convert(i,ss); + std::string ss; + Tools::convert(i,ss); error("ATOMS" + ss + " keyword has the wrong number of atoms"); } atoms.push_back(t[0]); @@ -276,38 +280,58 @@ RDC::RDC(const ActionOptions&ao): // Read in GYROMAGNETIC constants parse("GYROM", mu_s); - if(mu_s==0.) error("GYROM cannot be 0"); + if(mu_s==0.) { + error("GYROM cannot be 0"); + } // Read in SCALING factors parse("SCALE", scale); - if(scale==0.) error("SCALE cannot be 0"); + if(scale==0.) { + error("SCALE cannot be 0"); + } svd=false; parseFlag("SVD",svd); #ifndef __PLUMED_HAS_GSL - if(svd) error("You CANNOT use SVD without GSL. Recompile PLUMED with GSL!\n"); + if(svd) { + error("You CANNOT use SVD without GSL. Recompile PLUMED with GSL!\n"); + } #endif - if(svd&&getDoScore()) error("It is not possible to use SVD and METAINFERENCE together"); + if(svd&&getDoScore()) { + error("It is not possible to use SVD and METAINFERENCE together"); + } // Optionally add an experimental value coupl.resize( ndata ); unsigned ntarget=0; for(unsigned i=0; i dmax(coupl.size()); for(unsigned r=0; rset(rdc); if(!getDoScore()) { setBoxDerivatives(val, Tensor(distance,dRDC[index])); setAtomsDerivatives(val, r, dRDC[index]); setAtomsDerivatives(val, r+1, -dRDC[index]); - } else setCalcData(index, rdc); + } else { + setCalcData(index, rdc); + } } } @@ -496,12 +536,14 @@ void RDC::calculate() /* calculate final derivatives */ Value* val=getPntrToComponent("score"); - for(unsigned r=0; r0&& (getStep()%getWstride()==0 || getCPT()) ) writeStatus(); + if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) { + writeStatus(); + } } } diff --git a/src/isdb/Rescale.cpp b/src/isdb/Rescale.cpp index 705b8a762e..f29ffd9232 100644 --- a/src/isdb/Rescale.cpp +++ b/src/isdb/Rescale.cpp @@ -114,8 +114,7 @@ PRINT FILE=COLVAR ARG=* STRIDE=100 */ //+ENDPLUMEDOC -class Rescale : public bias::Bias -{ +class Rescale : public bias::Bias { // gamma parameter std::vector gamma_; double w0_; @@ -185,8 +184,7 @@ void Rescale::registerKeywords(Keywords& keys) { Rescale::Rescale(const ActionOptions&ao): PLUMED_BIAS_INIT(ao), nores_(0), Biaspace_(1), first_bias_(true), - MCsteps_(1), MCstride_(1), MCfirst_(-1), MCaccgamma_(0) -{ + MCsteps_(1), MCstride_(1), MCfirst_(-1), MCaccgamma_(0) { // set up replica stuff if(comm.Get_rank()==0) { nrep_ = multi_sim_comm.Get_size(); @@ -211,19 +209,23 @@ Rescale::Rescale(const ActionOptions&ao): // number of bias parse("NOT_RESCALED", nores_); - if(nores_>0 && nores_!=nbin) error("The number of non scaled arguments must be equal to either 0 or the number of bins"); + if(nores_>0 && nores_!=nbin) { + error("The number of non scaled arguments must be equal to either 0 or the number of bins"); + } // maximum value of rescale std::vector max_rescale; parseVector("MAX_RESCALE", max_rescale); // check dimension of max_rescale - if(max_rescale.size()!=(getNumberOfArguments()-nores_)) + if(max_rescale.size()!=(getNumberOfArguments()-nores_)) { error("Size of MAX_RESCALE array must be equal to the number of arguments that will to be scaled"); + } // calculate exponents double igamma_max = static_cast(nbin); - for(unsigned i=0; i not_shared; parseVector("NOT_SHARED", not_shared); // and change the non-shared for(unsigned i=0; i=(getNumberOfArguments()-nores_) && nrep_>1) + if((not_shared[i]-1)>=(getNumberOfArguments()-nores_) && nrep_>1) { error("NOT_RESCALED args must always be shared when using multiple replicas"); - if((not_shared[i]-1)>=getNumberOfArguments()) + } + if((not_shared[i]-1)>=getNumberOfArguments()) { error("NOT_SHARED args should be lower than total number of arguments"); + } shared_[not_shared[i]-1] = 0; } @@ -271,7 +277,9 @@ Rescale::Rescale(const ActionOptions&ao): log.printf(" name of the SELECTOR use for this action %s\n",selector_.c_str()); log.printf(" number of bins in grid %u\n",nbin); log.printf(" number of arguments that will not be scaled %u\n",nores_); - if(nrep_>1) log<<" number of arguments that will not be summed across replicas "<1) { + log<<" number of arguments that will not be summed across replicas "<(); ifile->link(*this); @@ -329,24 +340,29 @@ void Rescale::read_bias() } } -unsigned Rescale::proposeMove(unsigned x, unsigned xmin, unsigned xmax) -{ +unsigned Rescale::proposeMove(unsigned x, unsigned xmin, unsigned xmax) { int xmin_i = static_cast(xmin); int xmax_i = static_cast(xmax); int dx; int r = rand() % 2; - if( r % 2 == 0 ) dx = +1; - else dx = -1; + if( r % 2 == 0 ) { + dx = +1; + } else { + dx = -1; + } // new index, integer int x_new = static_cast(x) + dx; // check boundaries - if(x_new >= xmax_i) x_new = xmax_i-1; - if(x_new < xmin_i) x_new = xmin_i; + if(x_new >= xmax_i) { + x_new = xmax_i-1; + } + if(x_new < xmin_i) { + x_new = xmin_i; + } return static_cast(x_new); } -bool Rescale::doAccept(double oldE, double newE) -{ +bool Rescale::doAccept(double oldE, double newE) { bool accept = false; // calculate delta energy double delta = ( newE - oldE ) / kbt_; @@ -356,14 +372,15 @@ bool Rescale::doAccept(double oldE, double newE) } else { // otherwise extract random number double s = static_cast(rand()) / RAND_MAX; - if( s < std::exp(-delta) ) { accept = true; } + if( s < std::exp(-delta) ) { + accept = true; + } } return accept; } void Rescale::doMonteCarlo(unsigned igamma, double oldE, - const std::vector & args, const std::vector & bargs) -{ + const std::vector & args, const std::vector & bargs) { double oldB, newB; // cycle on MC steps @@ -395,7 +412,9 @@ void Rescale::doMonteCarlo(unsigned igamma, double oldE, } // send values of gamma to all replicas if(comm.Get_rank()==0) { - if(multi_sim_comm.Get_rank()!=0) igamma = 0; + if(multi_sim_comm.Get_rank()!=0) { + igamma = 0; + } multi_sim_comm.Sum(&igamma, 1); } else { igamma = 0; @@ -407,8 +426,7 @@ void Rescale::doMonteCarlo(unsigned igamma, double oldE, plumed.passMap[selector_]=static_cast(igamma); } -void Rescale::print_bias(long long int step) -{ +void Rescale::print_bias(long long int step) { // if first time open the file if(first_bias_) { first_bias_ = false; @@ -433,8 +451,7 @@ void Rescale::print_bias(long long int step) Biasfile_.printField(); } -void Rescale::calculate() -{ +void Rescale::calculate() { // get the current value of the selector unsigned igamma = static_cast(plumed.passMap[selector_]); @@ -445,9 +462,14 @@ void Rescale::calculate() double arg = getArgument(i); // sum shared arguments across replicas if(shared_[i]==1) { - if(comm.Get_rank()==0) multi_sim_comm.Sum(arg); - else arg = 0.0; - if(comm.Get_size()>1) comm.Sum(arg); + if(comm.Get_rank()==0) { + multi_sim_comm.Sum(arg); + } else { + arg = 0.0; + } + if(comm.Get_size()>1) { + comm.Sum(arg); + } } // put into all_args all_args[i] = arg; @@ -455,12 +477,20 @@ void Rescale::calculate() // now separate terms that should be rescaled std::vector args; - if(getNumberOfArguments()-nores_>0) args.resize(getNumberOfArguments()-nores_); - for(unsigned i=0; i0) { + args.resize(getNumberOfArguments()-nores_); + } + for(unsigned i=0; i bargs; - if(nores_>0) bargs.resize(nores_); - for(unsigned i=0; i0) { + bargs.resize(nores_); + } + for(unsigned i=0; iset(igamma); // get time step long long int step = getStep(); - if(MCfirst_==-1) MCfirst_=step; + if(MCfirst_==-1) { + MCfirst_=step; + } // calculate gamma acceptance double MCtrials = std::floor(static_cast(step-MCfirst_) / static_cast(MCstride_))+1.0; double accgamma = static_cast(MCaccgamma_) / static_cast(MCsteps_) / MCtrials; getPntrToComponent("accgamma")->set(accgamma); // do MC at the right time step - if(step%MCstride_==0&&!getExchangeStep()) doMonteCarlo(igamma, ene, args, bargs); + if(step%MCstride_==0&&!getExchangeStep()) { + doMonteCarlo(igamma, ene, args, bargs); + } // add well-tempered like bias if(step%Biaspace_==0) { @@ -502,7 +538,9 @@ void Rescale::calculate() } // print bias - if(step%Biasstride_==0) print_bias(step); + if(step%Biasstride_==0) { + print_bias(step); + } } diff --git a/src/isdb/SAXS.cpp b/src/isdb/SAXS.cpp index ef207bb92e..b9c972180f 100644 --- a/src/isdb/SAXS.cpp +++ b/src/isdb/SAXS.cpp @@ -241,8 +241,7 @@ PRINT ARG=(SANS\.q-.*),(SANS\.exp-.*) FILE=sansdata STRIDE=1 //+ENDPLUMEDOC class SAXS : - public MetainferenceBase -{ + public MetainferenceBase { private: enum { H, C, N, O, P, S, NTT }; enum { ALA_BB, ARG_BB, ARG_SC1, ARG_SC2, ASN_BB, ASN_SC1, ASP_BB, ASP_SC1, CYS_BB, CYS_SC1, @@ -481,10 +480,12 @@ SAXS::SAXS(const ActionOptions&ao): gpu(false), onebead(false), isFirstStep(true), - deviceid(-1) -{ - if( getName().find("SAXS")!=std::string::npos) { saxs=true; } - else if( getName().find("SANS")!=std::string::npos) { saxs=false; } + deviceid(-1) { + if( getName().find("SAXS")!=std::string::npos) { + saxs=true; + } else if( getName().find("SANS")!=std::string::npos) { + saxs=false; + } std::vector atoms; parseAtomList("ATOMS",atoms); @@ -495,21 +496,30 @@ SAXS::SAXS(const ActionOptions&ao): bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } parseFlag("GPU",gpu); #ifndef __PLUMED_HAS_ARRAYFIRE - if(gpu) error("To use the GPU mode PLUMED must be compiled with ARRAYFIRE"); + if(gpu) { + error("To use the GPU mode PLUMED must be compiled with ARRAYFIRE"); + } #endif parse("DEVICEID",deviceid); #ifdef __PLUMED_HAS_ARRAYFIRE if(gpu&&comm.Get_rank()==0) { // if not set try to check the one set by the API - if(deviceid==-1) deviceid=plumed.getGpuDeviceId(); + if(deviceid==-1) { + deviceid=plumed.getGpuDeviceId(); + } // if still not set use 0 - if(deviceid==-1) deviceid=0; + if(deviceid==-1) { + deviceid=0; + } #ifdef __PLUMED_HAS_ARRAYFIRE_CUDA af::setDevice(afcu::getNativeId(deviceid)); #elif __PLUMED_HAS_ARRAYFIRE_OCL @@ -523,24 +533,42 @@ SAXS::SAXS(const ActionOptions&ao): bool atomistic=false; parseFlag("ATOMISTIC",atomistic); - if(atomistic) log.printf(" using ATOMISTIC form factors\n"); + if(atomistic) { + log.printf(" using ATOMISTIC form factors\n"); + } bool martini=false; parseFlag("MARTINI",martini); - if(martini) log.printf(" using MARTINI form factors\n"); + if(martini) { + log.printf(" using MARTINI form factors\n"); + } onebead=false; parseFlag("ONEBEAD",onebead); - if(onebead) log.printf(" using ONEBEAD form factors\n"); + if(onebead) { + log.printf(" using ONEBEAD form factors\n"); + } bool fromfile=false; std::string parametersfile; parse("PARAMETERSFILE",parametersfile); - if (parametersfile.length() != 0) fromfile=true; - if(fromfile) log.printf(" will read form factors from file\n"); + if (parametersfile.length() != 0) { + fromfile=true; + } + if(fromfile) { + log.printf(" will read form factors from file\n"); + } parseFlag("ABSOLUTE",absolute); - if(martini&&atomistic) error("You cannot use MARTINI and ATOMISTIC at the same time"); - if(martini&&onebead) error("You cannot use MARTINI and ONEBEAD at the same time"); - if(onebead&&atomistic) error("You cannot use ONEBEAD and ATOMISTIC at the same time"); - if((martini)&&(!saxs)) error("MARTINI cannot be used with SANS"); + if(martini&&atomistic) { + error("You cannot use MARTINI and ATOMISTIC at the same time"); + } + if(martini&&onebead) { + error("You cannot use MARTINI and ONEBEAD at the same time"); + } + if(onebead&&atomistic) { + error("You cannot use ONEBEAD and ATOMISTIC at the same time"); + } + if((martini)&&(!saxs)) { + error("MARTINI cannot be used with SANS"); + } if((fromfile)&&((atomistic)||(martini)||(onebead))) { error("You cannot read parameters from file and use ATOMISTIC/MARTINI/ONEBEAD"); } @@ -548,17 +576,27 @@ SAXS::SAXS(const ActionOptions&ao): unsigned ntarget=0; for(unsigned i=0;; ++i) { double t_list; - if( !parseNumbered( "QVALUE", i+1, t_list) ) break; - if(t_list<=0.) error("QVALUE cannot be less or equal to zero!\n"); - if(onebead&&t_list>0.3) error("ONEBEAD mapping QVALUE must be smaller or equal to 0.3"); + if( !parseNumbered( "QVALUE", i+1, t_list) ) { + break; + } + if(t_list<=0.) { + error("QVALUE cannot be less or equal to zero!\n"); + } + if(onebead&&t_list>0.3) { + error("ONEBEAD mapping QVALUE must be smaller or equal to 0.3"); + } q_list.push_back(t_list); ntarget++; } const unsigned numq = ntarget; for(unsigned i=0; i0&&q_list[i]0&&q_list[i] 1.) error("DEUTER_CONC must be in 0-1 range"); - if ((atomistic||onebead)&&(!saxs)) log.printf(" Solvent deuterium fraction: %lf/1.000000\n", deuter_conc); + if ((deuter_conc)&&(fromfile)) { + error("DEUTER_CONC cannot be used with PARAMETERSFILE"); + } + if(deuter_conc < 0. || deuter_conc > 1.) { + error("DEUTER_CONC must be in 0-1 range"); + } + if ((atomistic||onebead)&&(!saxs)) { + log.printf(" Solvent deuterium fraction: %lf/1.000000\n", deuter_conc); + } PDB pdb; if(onebead) { std::string template_name; parse("TEMPLATE",template_name); log.printf(" Template for ONEBEAD mapping conversion: %s\n", template_name.c_str()); - if( !pdb.read(template_name,usingNaturalUnits(),1.) ) plumed_merror("missing input file " + template_name); + if( !pdb.read(template_name,usingNaturalUnits(),1.) ) { + plumed_merror("missing input file " + template_name); + } } // preliminary mapping for onebead representation @@ -642,10 +702,14 @@ SAXS::SAXS(const ActionOptions&ao): parameter.resize(size); ntarget=0; for(unsigned i=0; i(size)); for(unsigned i=0; i parameter; parameter.resize(size); ntarget=0; for(unsigned i=0; i(size)); for(unsigned i=0; i size) error("PARAMETERSFILE has more PARAMETERS than there are scattering centers"); - std::string num; Tools::convert(ntarget+1,num); + if (line.empty()) { + continue; + } + if (ntarget > size) { + error("PARAMETERSFILE has more PARAMETERS than there are scattering centers"); + } + std::string num; + Tools::convert(ntarget+1,num); std::vector lineread{line}; - if (!Tools::parseVector(lineread, "PARAMETERS"+num, parameter[ntarget], -1)) error("Missing PARAMETERS or PARAMETERS not sorted"); + if (!Tools::parseVector(lineread, "PARAMETERS"+num, parameter[ntarget], -1)) { + error("Missing PARAMETERS or PARAMETERS not sorted"); + } ntarget++; } - if( ntarget!=size ) error("found wrong number of PARAMETERS in file"); + if( ntarget!=size ) { + error("found wrong number of PARAMETERS in file"); + } for(unsigned i=0; i(size)); @@ -722,20 +804,31 @@ SAXS::SAXS(const ActionOptions&ao): while(ifile.getline(line)) { Tools::ltrim(line); Tools::trimComments(line); - if (line.empty()) continue; - if (ntarget > size) error("PARAMETERSFILE has more PARAMETERS than there are scattering centers"); - std::string num; Tools::convert(ntarget+1,num); + if (line.empty()) { + continue; + } + if (ntarget > size) { + error("PARAMETERSFILE has more PARAMETERS than there are scattering centers"); + } + std::string num; + Tools::convert(ntarget+1,num); std::vector lineread{line}; long double scatlen; atoi[ntarget]=ntarget; - if (!Tools::parse(lineread, "PARAMETERS"+num, scatlen, -1)) error("Missing PARAMETERS or PARAMETERS not sorted"); + if (!Tools::parse(lineread, "PARAMETERS"+num, scatlen, -1)) { + error("Missing PARAMETERS or PARAMETERS not sorted"); + } for(unsigned k=0; k(NTT)); - if(saxs) Iq0=calculateAFF(atoms, FF_tmp, rho); - else Iq0=calculateAFFsans(atoms, FF_tmp, deuter_conc); + if(saxs) { + Iq0=calculateAFF(atoms, FF_tmp, rho); + } else { + Iq0=calculateAFFsans(atoms, FF_tmp, deuter_conc); + } Iq0 *= Iq0; } @@ -830,31 +928,53 @@ SAXS::SAXS(const ActionOptions&ao): expint.resize( numq ); ntarget=0; for(unsigned i=0; i(FF_tmp[k][atoi[i]])/(std::sqrt(Iq0)); - for(unsigned i=0; i(FF_tmp[k][atoi[i]])/(std::sqrt(Iq0)); + } + for(unsigned i=0; i > &Nlist) -{ +void SAXS::calcNlist(std::vector > &Nlist) { unsigned natoms = getNumberOfAtoms(); for(unsigned i = 0; i < natoms; ++i) { if (LCPOparam[i].size()>0) { @@ -1078,24 +1207,30 @@ void SAXS::sasa_calculate(std::vector &solv_res) { } } #pragma omp critical - { // combining private_sasares into sasares + { + // combining private_sasares into sasares for (unsigned i = 0; i < nres; ++i) { sasares[i] += private_sasares[i]; } } } for(unsigned i=0; isasa_cutoff) solv_res[i] = 1; - else solv_res[i] = 0; + if(sasares[i]>sasa_cutoff) { + solv_res[i] = 1; + } else { + solv_res[i] = 0; + } } } -void SAXS::calculate_gpu(std::vector &pos, std::vector &deriv) -{ +void SAXS::calculate_gpu(std::vector &pos, std::vector &deriv) { #ifdef __PLUMED_HAS_ARRAYFIRE unsigned size; - if(onebead) size = nres; - else size = getNumberOfAtoms(); + if(onebead) { + size = nres; + } else { + size = getNumberOfAtoms(); + } const unsigned numq = q_list.size(); std::vector sum; @@ -1195,10 +1330,13 @@ void SAXS::calculate_gpu(std::vector &pos, std::vector &deriv) comm.Bcast(sum, 0); for(unsigned k=0; kset(sum[k]); - if(getDoScore()) setCalcData(k, sum[k]); + if(getDoScore()) { + setCalcData(k, sum[k]); + } for(unsigned i=0; i &pos, std::vector &deriv) #endif } -void SAXS::calculate_cpu(std::vector &pos, std::vector &deriv) -{ +void SAXS::calculate_cpu(std::vector &pos, std::vector &deriv) { unsigned size; - if(onebead) size = nres; - else size = getNumberOfAtoms(); + if(onebead) { + size = nres; + } else { + size = getNumberOfAtoms(); + } const unsigned numq = q_list.size(); unsigned stride = comm.Get_size(); @@ -1255,8 +1395,12 @@ void SAXS::calculate_cpu(std::vector &pos, std::vector &deriv) } #pragma omp critical if(nt>1) { - for(unsigned i=0; i &pos, std::vector &deriv) for (unsigned k=0; kset(sum[k]); - if(getDoScore()) setCalcData(k, sum[k]); + if(getDoScore()) { + setCalcData(k, sum[k]); + } } } -void SAXS::calculate() -{ - if(pbc) makeWhole(); +void SAXS::calculate() { + if(pbc) { + makeWhole(); + } const size_t size = getNumberOfAtoms(); const size_t numq = q_list.size(); @@ -1341,7 +1489,9 @@ void SAXS::calculate() std::vector aa_deriv(size); size_t beads_size = size; - if(onebead) beads_size = nres; + if(onebead) { + beads_size = nres; + } // these are the derivatives particle,q std::vector bd_deriv(numq*beads_size); @@ -1369,7 +1519,9 @@ void SAXS::calculate() if(saxs) { if(getStep()%solv_stride == 0 || isFirstStep) { isFirstStep = 0; - if(rho_corr!=rho) sasa_calculate(solv_res); + if(rho_corr!=rho) { + sasa_calculate(solv_res); + } Iq0=0.; for(unsigned i=0; i(size,(Vector(1,1,1))); } - if(gpu) calculate_gpu(beads_pos, bd_deriv); - else calculate_cpu(beads_pos, bd_deriv); + if(gpu) { + calculate_gpu(beads_pos, bd_deriv); + } else { + calculate_cpu(beads_pos, bd_deriv); + } if(getDoScore()) { /* Metainference */ @@ -1484,7 +1641,8 @@ void SAXS::calculate() Tensor deriv_box; Value* val; if(!getDoScore()) { - std::string num; Tools::convert(k,num); + std::string num; + Tools::convert(k,num); val=getPntrToComponent("q-"+num); if(onebead) { @@ -1542,11 +1700,14 @@ void SAXS::calculate() void SAXS::update() { // write status file - if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) writeStatus(); + if(getWstride()>0&& (getStep()%getWstride()==0 || getCPT()) ) { + writeStatus(); + } } unsigned SAXS::getOnebeadMapping(const PDB &pdb, const std::vector &atoms) { - std::vector chains; pdb.getChainNames( chains ); + std::vector chains; + pdb.getChainNames( chains ); std::vector > AtomResidueName; // cycle over chains @@ -1560,7 +1721,8 @@ unsigned SAXS::getOnebeadMapping(const PDB &pdb, const std::vector & std::string Rname = pdb.getResidueName(res, chains[i]); Rname.erase(std::remove_if(Rname.begin(), Rname.end(), ::isspace),Rname.end()); std::vector res_atoms = pdb.getAtomsInResidue(res, chains[i]); - std::vector tmp_residue_atom; tmp_residue_atom.resize(3,0); + std::vector tmp_residue_atom; + tmp_residue_atom.resize(3,0); // cycle over atoms for(unsigned a=0; a & } else { type = Aname.at(1); } - if (type == 'H') atoms_masses.push_back(1.008); - else if(type == 'C') atoms_masses.push_back(12.011); - else if(type == 'N') atoms_masses.push_back(14.007); - else if(type == 'O') atoms_masses.push_back(15.999); - else if(type == 'S') atoms_masses.push_back(32.065); - else if(type == 'P') atoms_masses.push_back(30.974); - else { + if (type == 'H') { + atoms_masses.push_back(1.008); + } else if(type == 'C') { + atoms_masses.push_back(12.011); + } else if(type == 'N') { + atoms_masses.push_back(14.007); + } else if(type == 'O') { + atoms_masses.push_back(15.999); + } else if(type == 'S') { + atoms_masses.push_back(32.065); + } else if(type == 'P') { + atoms_masses.push_back(30.974); + } else { error("Unknown element in mass extraction\n"); } if(pdb.allowedResidue("protein",Rname)) { @@ -1617,7 +1785,9 @@ unsigned SAXS::getOnebeadMapping(const PDB &pdb, const std::vector & tmp_residue_atom[2]++; } // error - else error("Atom name "+Aname+" cannot be indexed to any bead. Check the PDB."); + else { + error("Atom name "+Aname+" cannot be indexed to any bead. Check the PDB."); + } } } if(pdb.allowedResidue("protein",Rname)) { @@ -1625,7 +1795,9 @@ unsigned SAXS::getOnebeadMapping(const PDB &pdb, const std::vector & } else { atoms_per_bead.push_back(tmp_residue_atom[0]); atoms_per_bead.push_back(tmp_residue_atom[1]); - if(tmp_residue_atom[2]>0) atoms_per_bead.push_back(tmp_residue_atom[2]); + if(tmp_residue_atom[2]>0) { + atoms_per_bead.push_back(tmp_residue_atom[2]); + } } } } @@ -1633,8 +1805,7 @@ unsigned SAXS::getOnebeadMapping(const PDB &pdb, const std::vector & return atoms_per_bead.size(); } -void SAXS::getMartiniFFparam(const std::vector &atoms, std::vector > ¶meter) -{ +void SAXS::getMartiniFFparam(const std::vector &atoms, std::vector > ¶meter) { parameter[ALA_BB].push_back(9.045); parameter[ALA_BB].push_back(-0.098114); parameter[ALA_BB].push_back(7.54281); @@ -2707,7 +2878,9 @@ void SAXS::getMartiniFFparam(const std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector > ¶meter_vac, std::vector > ¶meter_mix, std::vector > ¶meter_solv, const std::vector & residue_atom) -{ +void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, std::vector > ¶meter_vac, std::vector > ¶meter_mix, std::vector > ¶meter_solv, const std::vector & residue_atom) { parameter_solv[TRP].push_back(60737.60249988003); parameter_solv[TRP].push_back(-77.75716755173752); @@ -3956,7 +4184,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - G3 } else if(Rname=="G3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -3974,7 +4204,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - G5 } else if(Rname=="G5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -3989,7 +4221,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - GT } else if(Rname=="GT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4007,7 +4241,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - U } else if(Rname=="U") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -4024,7 +4260,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - U3 } else if(Rname=="U3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4041,7 +4279,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - U5 } else if(Rname=="U5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -4055,7 +4295,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - UT } else if(Rname=="UT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4072,7 +4314,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - A } else if(Rname=="A") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -4090,7 +4334,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - A3 } else if(Rname=="A3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4108,7 +4354,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - A5 } else if(Rname=="A5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -4123,7 +4371,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - AT } else if(Rname=="AT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4141,7 +4391,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - C } else if(Rname=="C") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -4158,7 +4410,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - C3 } else if(Rname=="C3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4175,7 +4429,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - C5 } else if(Rname=="C5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -4189,7 +4445,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - CT } else if(Rname=="CT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4206,7 +4464,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - G } else if(Rname=="DG") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -4224,7 +4484,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - G3 } else if(Rname=="DG3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4242,7 +4504,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - G5 } else if(Rname=="DG5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -4257,7 +4521,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - GT } else if(Rname=="DGT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4275,7 +4541,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - T } else if(Rname=="DT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -4293,7 +4561,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - T3 } else if(Rname=="DT3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4311,7 +4581,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - T5 } else if(Rname=="DT5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -4326,7 +4598,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - TT } else if(Rname=="DTT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4344,7 +4618,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - A } else if(Rname=="DA") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -4362,7 +4638,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - A3 } else if(Rname=="DA3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4380,7 +4658,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - A5 } else if(Rname=="DA5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -4395,7 +4675,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - AT } else if(Rname=="DAT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4413,7 +4695,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - C } else if(Rname=="DC") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -4430,7 +4714,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - C3 } else if(Rname=="DC3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4447,7 +4733,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - C5 } else if(Rname=="DC5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -4461,7 +4749,9 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - CT } else if(Rname=="DCT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -4478,13 +4768,16 @@ void SAXS::getOnebeadparam(const PDB &pdb, const std::vector &atoms, Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); - } else error("Residue not known: "+Rname); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } + } else { + error("Residue not known: "+Rname); + } } } -void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector &atoms, std::vector > ¶meter_vac_H, std::vector > ¶meter_mix_H, std::vector > ¶meter_solv_H) -{ +void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector &atoms, std::vector > ¶meter_vac_H, std::vector > ¶meter_mix_H, std::vector > ¶meter_solv_H) { parameter_solv_H[TRP].push_back(60737.60249988011); parameter_solv_H[TRP].push_back(-77.77344118516487); parameter_solv_H[TRP].push_back(-205962.80436572764); @@ -5407,7 +5700,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - G3 } else if(Rname=="G3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5425,7 +5720,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - G5 } else if(Rname=="G5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -5440,7 +5737,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - GT } else if(Rname=="GT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5458,7 +5757,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - U } else if(Rname=="U") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -5475,7 +5776,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - U3 } else if(Rname=="U3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5492,7 +5795,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - U5 } else if(Rname=="U5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -5506,7 +5811,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - UT } else if(Rname=="UT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5523,7 +5830,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - A } else if(Rname=="A") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -5541,7 +5850,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - A3 } else if(Rname=="A3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5559,7 +5870,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - A5 } else if(Rname=="A5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -5574,7 +5887,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - AT } else if(Rname=="AT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5592,7 +5907,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - C } else if(Rname=="C") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -5609,7 +5926,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - C3 } else if(Rname=="C3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5626,7 +5945,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - C5 } else if(Rname=="C5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -5640,7 +5961,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - CT } else if(Rname=="CT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5657,7 +5980,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - G } else if(Rname=="DG") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -5675,7 +6000,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - G3 } else if(Rname=="DG3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5693,7 +6020,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - G5 } else if(Rname=="DG5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -5708,7 +6037,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - GT } else if(Rname=="DGT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5726,7 +6057,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - T } else if(Rname=="DT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -5744,7 +6077,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - T3 } else if(Rname=="DT3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5762,7 +6097,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - T5 } else if(Rname=="DT5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -5777,7 +6114,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - TT } else if(Rname=="DTT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5795,7 +6134,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - A } else if(Rname=="DA") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -5813,7 +6154,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - A3 } else if(Rname=="DA3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5831,7 +6174,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - A5 } else if(Rname=="DA5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -5846,7 +6191,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - AT } else if(Rname=="DAT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5864,7 +6211,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - C } else if(Rname=="DC") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -5881,7 +6230,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - C3 } else if(Rname=="DC3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5898,7 +6249,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - C5 } else if(Rname=="DC5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -5912,7 +6265,9 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - CT } else if(Rname=="DCT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -5929,13 +6284,17 @@ void SAXS::getOnebeadparam_sansH(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); - } else error("Residue not known: "+Rname); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } + } else { + error("Residue not known: "+Rname); + } } } -void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector &atoms, std::vector > ¶meter_vac_D, std::vector > ¶meter_mix_D) -{ // parameter_solv is identical in SAXS/SANS_H/SANS_D since it depends exclusively on param_v. For that reason we kept param_solv only in SAXS and SANS_H. +void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector &atoms, std::vector > ¶meter_vac_D, std::vector > ¶meter_mix_D) { + // parameter_solv is identical in SAXS/SANS_H/SANS_D since it depends exclusively on param_v. For that reason we kept param_solv only in SAXS and SANS_H. parameter_mix_D[TRP].push_back(8105.740500119327); parameter_mix_D[TRP].push_back(-41.785616935469804); parameter_mix_D[TRP].push_back(-25456.92790554363); @@ -6576,7 +6935,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - G3 } else if(Rname=="G3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6594,7 +6955,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - G5 } else if(Rname=="G5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -6609,7 +6972,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - GT } else if(Rname=="GT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6627,7 +6992,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - U } else if(Rname=="U") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -6644,7 +7011,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - U3 } else if(Rname=="U3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6661,7 +7030,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - U5 } else if(Rname=="U5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -6675,7 +7046,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - UT } else if(Rname=="UT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6692,7 +7065,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="O4" || Aname=="C5" || Aname=="C6" || Aname=="H3" || Aname=="H5" || Aname=="H6") { atoi[residue_atom[i]]=BASE_U; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - A } else if(Rname=="A") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -6710,7 +7085,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - A3 } else if(Rname=="A3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6728,7 +7105,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - A5 } else if(Rname=="A5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -6743,7 +7122,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - AT } else if(Rname=="AT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6761,7 +7142,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - C } else if(Rname=="C") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -6778,7 +7161,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - C3 } else if(Rname=="C3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6795,7 +7180,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - C5 } else if(Rname=="C5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -6809,7 +7196,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // RNA - CT } else if(Rname=="CT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6826,7 +7215,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - G } else if(Rname=="DG") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -6844,7 +7235,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - G3 } else if(Rname=="DG3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6862,7 +7255,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - G5 } else if(Rname=="DG5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -6877,7 +7272,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - GT } else if(Rname=="DGT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6895,7 +7292,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="N7" || Aname=="C8" || Aname=="N9" || Aname=="H1" || Aname=="H8" || Aname=="H21" || Aname=="H22" ) { atoi[residue_atom[i]]=BASE_G; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - T } else if(Rname=="DT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -6913,7 +7312,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - T3 } else if(Rname=="DT3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6931,7 +7332,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - T5 } else if(Rname=="DT5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -6946,7 +7349,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - TT } else if(Rname=="DTT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -6964,7 +7369,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C7" || Aname=="H3" || Aname=="H6" || Aname=="H71" || Aname=="H72" || Aname=="H73" ) { atoi[residue_atom[i]]=BASE_T; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - A } else if(Rname=="DA") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -6982,7 +7389,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - A3 } else if(Rname=="DA3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -7000,7 +7409,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - A5 } else if(Rname=="DA5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -7015,7 +7426,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - AT } else if(Rname=="DAT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -7033,7 +7446,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C8" || Aname=="N9" || Aname=="H2" || Aname=="H8" || Aname=="H61" || Aname=="H62" ) { atoi[residue_atom[i]]=BASE_A; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - C } else if(Rname=="DC") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="HP" || @@ -7050,7 +7465,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - C3 } else if(Rname=="DC3") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -7067,7 +7484,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - C5 } else if(Rname=="DC5") { if( Aname=="O5'" || Aname=="C5'" || Aname=="O4'" || Aname=="C4'" || @@ -7081,7 +7500,9 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } // DNA - CT } else if(Rname=="DCT") { if( Aname=="P" || Aname=="OP1" || Aname=="OP2" || Aname=="OP3" || @@ -7098,13 +7519,16 @@ void SAXS::getOnebeadparam_sansD(const PDB &pdb, const std::vector & Aname=="C4" || Aname=="N4" || Aname=="C5" || Aname=="C6" || Aname=="H5" || Aname=="H6" || Aname=="H41" || Aname=="H42" ) { atoi[residue_atom[i]]=BASE_C; - } else error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); - } else error("Residue not known: "+Rname); + } else { + error("Atom name "+Aname+" is not defined for residue "+Rname+". Check the PDB."); + } + } else { + error("Residue not known: "+Rname); + } } } -double SAXS::calculateAFF(const std::vector &atoms, std::vector > &FF_tmp, const double rho) -{ +double SAXS::calculateAFF(const std::vector &atoms, std::vector > &FF_tmp, const double rho) { std::map AA_map; AA_map["H"] = H; AA_map["C"] = C; @@ -7123,41 +7547,83 @@ double SAXS::calculateAFF(const std::vector &atoms, std::vector(this); @@ -7197,7 +7663,9 @@ double SAXS::calculateAFF(const std::vector &atoms, std::vector &atoms, std::vector &atoms, std::vector > &FF_tmp, const double deuter_conc) -{ +double SAXS::calculateAFFsans(const std::vector &atoms, std::vector > &FF_tmp, const double deuter_conc) { std::map AA_map; AA_map["H"] = H; AA_map["C"] = C; @@ -7227,13 +7696,19 @@ double SAXS::calculateAFFsans(const std::vector &atoms, std::vector< param_b.resize(NTT); param_v.resize(NTT); - param_b[H] = -0.374; param_v[H] = 5.15; + param_b[H] = -0.374; + param_v[H] = 5.15; // param_b[D] = 0.667; - param_b[C] = 0.665; param_v[C] = 16.44; - param_b[N] = 0.94; param_v[N] = 2.49; - param_b[O] = 0.580; param_v[O] = 9.13; - param_b[P] = 0.51; param_v[P] = 5.73; - param_b[S] = 0.28; param_v[S] = 19.86; + param_b[C] = 0.665; + param_v[C] = 16.44; + param_b[N] = 0.94; + param_v[N] = 2.49; + param_b[O] = 0.580; + param_v[O] = 9.13; + param_b[P] = 0.51; + param_v[P] = 5.73; + param_b[S] = 0.28; + param_v[S] = 19.86; double solv_sc_length = 0.1*(param_b[O] + 2.*((1. - deuter_conc) * param_b[H] + deuter_conc * 0.667)); // per water electron (10 electrons) @@ -7278,7 +7753,9 @@ double SAXS::calculateAFFsans(const std::vector &atoms, std::vector< } else { error("MOLINFO DATA not found\n"); } - if(absolute) Iq0 = 1; + if(absolute) { + Iq0 = 1; + } return Iq0; } @@ -8488,12 +8965,10 @@ std::map > SAXS::setupLCPOparam() { } // assigns LCPO parameters to each atom reading from database -void SAXS::readLCPOparam(const std::vector > &AtomResidueName, unsigned natoms) -{ +void SAXS::readLCPOparam(const std::vector > &AtomResidueName, unsigned natoms) { std::map > lcpomap = setupLCPOparam(); - for(unsigned i=0; i LCPOparamVector = lcpomap.at(identifier); @@ -8530,8 +9005,7 @@ void SAXS::readLCPOparam(const std::vector > &AtomResid } } -void SAXS::resolution_function() -{ +void SAXS::resolution_function() { const unsigned numq = q_list.size(); // only OpenMP because numq might be smaller than the number of ranks @@ -8554,12 +9028,12 @@ void SAXS::resolution_function() // i0e function from cephes // compute I0(x) * exp (-x), with I0 being the modified Bessel function // of first kind and zeroth order. -inline double SAXS::i0e(double x) -{ +inline double SAXS::i0e(double x) { double y = 0.0; - if (x < 0) + if (x < 0) { x = -x; + } if (x <= 8.0) { y = (x/2.0) - 2.0; return chbevl(y, A); @@ -8568,8 +9042,7 @@ inline double SAXS::i0e(double x) return chbevl(32.0/x - 2.0, B) / sqrt(x); } -double SAXS::chbevl(double x, const std::vector &coeffs) -{ +double SAXS::chbevl(double x, const std::vector &coeffs) { double b0, b1, b2; unsigned n = coeffs.size(); @@ -8585,10 +9058,11 @@ double SAXS::chbevl(double x, const std::vector &coeffs) return 0.5 * (b0 - b2); } -inline double SAXS::interpolation(std::vector &coeffs, double x) -{ +inline double SAXS::interpolation(std::vector &coeffs, double x) { unsigned s = 0; - while ((x >= q_list[s+1]) && (s+1 < q_list.size()-1)) s++; + while ((x >= q_list[s+1]) && (s+1 < q_list.size()-1)) { + s++; + } double dx = x - coeffs[s].x; return coeffs[s].a + coeffs[s].b*dx + coeffs[s].c*dx*dx + coeffs[s].d*dx*dx*dx; @@ -8596,8 +9070,7 @@ inline double SAXS::interpolation(std::vector &coeffs, double x) // natural bc cubic spline implementation from the Wikipedia algorithm // modified from https://stackoverflow.com/a/19216702/3254658 -std::vector SAXS::spline_coeffs(std::vector &x, std::vector &y) -{ +std::vector SAXS::spline_coeffs(std::vector &x, std::vector &y) { unsigned n = x.size()-1; std::vector a; a.insert(a.begin(), y.begin(), y.end()); @@ -8605,13 +9078,15 @@ std::vector SAXS::spline_coeffs(std::vector &x, std: std::vector d(n); std::vector h; - for(unsigned i=0; i alpha; alpha.push_back(0); - for(unsigned i=1; i c(n+1); std::vector l(n+1); diff --git a/src/isdb/Select.cpp b/src/isdb/Select.cpp index 1b933c2b43..4304bc56d8 100644 --- a/src/isdb/Select.cpp +++ b/src/isdb/Select.cpp @@ -66,8 +66,7 @@ PRINT ARG=pbactive STRIDE=100 FILE=COLVAR */ //+ENDPLUMEDOC -class Select : public function::Function -{ +class Select : public function::Function { std::string selector_; public: @@ -86,12 +85,12 @@ void Select::registerKeywords(Keywords& keys) { } Select::Select(const ActionOptions&ao): - Action(ao), Function(ao) -{ + Action(ao), Function(ao) { // name of selector parse("SELECTOR", selector_); - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); checkRead(); log.printf(" select based on %s\n",selector_.c_str()); @@ -99,15 +98,18 @@ Select::Select(const ActionOptions&ao): } -void Select::calculate() -{ +void Select::calculate() { unsigned iselect = static_cast(plumed.passMap[selector_]); // check if iselect is smaller than the number of arguments - if(iselect>=getNumberOfArguments()) error("the value of the SELECTOR is greater than the number of arguments!"); + if(iselect>=getNumberOfArguments()) { + error("the value of the SELECTOR is greater than the number of arguments!"); + } // put all the derivatives to zero - for(unsigned i=0; i atoms; parseAtomList("ATOMS",atoms); @@ -156,22 +155,26 @@ Shadow::Shadow(const ActionOptions&ao): checkRead(); log.printf(" atoms involved : "); - for(unsigned i=0; i1) comm.Sum(&reference[0][0], 3*natoms); + if(size_>1) { + comm.Sum(&reference[0][0], 3*natoms); + } // clear the rmsd object rmsd_.clear(); @@ -196,10 +203,11 @@ void Shadow::update_reference() rmsd_.set(align,displace,reference,"OPTIMAL"); } -void Shadow::calculate() -{ +void Shadow::calculate() { // make whole - if(pbc_) makeWhole(); + if(pbc_) { + makeWhole(); + } // if it is time, update reference coordinates if(first_time_ || getStep()%nupdate_==0) { @@ -215,7 +223,9 @@ void Shadow::calculate() setValue(rmsd); // if this is not the reference replica, add derivatives if(!isreference_) { - for(unsigned i=0; i argn; parseVector("ARG",argn); std::vector theargs; + ActionShortcut(ao) { + std::string stride, clearstride; + parse("STRIDE",stride); + parse("CLEAR",clearstride); + std::vector argn; + parseVector("ARG",argn); + std::vector theargs; ActionWithArguments::interpretArgumentList( argn, plumed.getActionSet(), this, theargs ); - std::string indices; parse("ATOMS",indices); - if( theargs.size()==0 && indices.length()==0 ) error("no arguments or atoms were specified for collection"); + std::string indices; + parse("ATOMS",indices); + if( theargs.size()==0 && indices.length()==0 ) { + error("no arguments or atoms were specified for collection"); + } // Create the values to collect the atomic positions if( indices.length()>0 ) { // Collect reference position - readInputLine( getShortcutLabel() + "_getposx: POSITION ATOMS=" + indices ); std::string align; parse("ALIGN",align); + readInputLine( getShortcutLabel() + "_getposx: POSITION ATOMS=" + indices ); + std::string align; + parse("ALIGN",align); readInputLine( getShortcutLabel() + "_getpos: CONCATENATE ARG=" + getShortcutLabel() + "_getposx.x," + getShortcutLabel() + "_getposx.y," + getShortcutLabel() + "_getposx.z"); // Find atomic center readInputLine( getShortcutLabel() + "_cposx: MEAN ARG=" + getShortcutLabel() + "_getposx.x PERIODIC=NO"); @@ -100,37 +119,62 @@ CollectFrames::CollectFrames( const ActionOptions& ao ): // Add the reference position to the RMSD displacement readInputLine( getShortcutLabel() + "_fpos: COMBINE ARG=" + getShortcutLabel() + "_refposT," + getShortcutLabel() + "_rmsd.disp PERIODIC=NO"); // Store the reference data - std::string suffix = "_atomdata"; if( theargs.size()==0 ) suffix = "_data"; + std::string suffix = "_atomdata"; + if( theargs.size()==0 ) { + suffix = "_data"; + } readInputLine( getShortcutLabel() + suffix + ": COLLECT TYPE=matrix ARG=" + getShortcutLabel() + "_fpos STRIDE=" + stride + " CLEAR=" + clearstride ); } // Create all the collect actions for arguments for(unsigned i=0; igetNumberOfValues()!=theargs[0]->getNumberOfValues() ) error("mismatch between number of arguments calculated by each collected argument"); + if( theargs[i]->getNumberOfValues()!=theargs[0]->getNumberOfValues() ) { + error("mismatch between number of arguments calculated by each collected argument"); + } readInputLine( getShortcutLabel() + "_" + fixArgumentName( theargs[i]->getName() ) + ": COLLECT ARG=" + theargs[i]->getName() + " STRIDE=" + stride + " CLEAR=" + clearstride ); } // Make a list of collect actions if( theargs.size()>0 ) { std::string allcol = getShortcutLabel() + "_" + fixArgumentName( theargs[0]->getName() ); - for(unsigned i=1; igetName() ); + for(unsigned i=1; igetName() ); + } // And transfer everything to a matrix - std::string suffix = "_argdata"; if( indices.length()==0 ) suffix = "_data"; + std::string suffix = "_argdata"; + if( indices.length()==0 ) { + suffix = "_data"; + } readInputLine( getShortcutLabel() + suffix + ": VSTACK ARG=" + allcol ); } // Merge all the collected data together into a single matrix - if( theargs.size()>0 && indices.length()>0 ) readInputLine( getShortcutLabel() + "_data: CONCATENATE MATRIX11=" + getShortcutLabel() + "_atomdata MATRIX12=" + getShortcutLabel() + "_argdata"); + if( theargs.size()>0 && indices.length()>0 ) { + readInputLine( getShortcutLabel() + "_data: CONCATENATE MATRIX11=" + getShortcutLabel() + "_atomdata MATRIX12=" + getShortcutLabel() + "_argdata"); + } // Now get the logweights - std::vector logw; parseVector("LOGWEIGHTS",logw); std::vector thew; - if( logw.size()>0 ) ActionWithArguments::interpretArgumentList( logw, plumed.getActionSet(), this, thew ); - if( logw.size()>1 ) error("maximum of one argument should be specified for logweights"); + std::vector logw; + parseVector("LOGWEIGHTS",logw); + std::vector thew; + if( logw.size()>0 ) { + ActionWithArguments::interpretArgumentList( logw, plumed.getActionSet(), this, thew ); + } + if( logw.size()>1 ) { + error("maximum of one argument should be specified for logweights"); + } if( logw.size()==0 ) { - std::string zeros="0"; if( theargs.size()>0 ) { for(unsigned i=1; igetNumberOfValues(); ++i) zeros += ",0"; } + std::string zeros="0"; + if( theargs.size()>0 ) { + for(unsigned i=1; igetNumberOfValues(); ++i) { + zeros += ",0"; + } + } readInputLine( getShortcutLabel() + "_cweight: CONSTANT VALUE=" + zeros ); readInputLine( getShortcutLabel() + "_logweights: COLLECT ARG=" + getShortcutLabel() + "_cweight STRIDE=" + stride + " CLEAR=" + clearstride ); } else { - if( theargs[0]->getNumberOfValues()!=thew[0]->getNumberOfValues() ) error("mismatch between number of weights and number of collected arguments"); + if( theargs[0]->getNumberOfValues()!=thew[0]->getNumberOfValues() ) { + error("mismatch between number of weights and number of collected arguments"); + } readInputLine( getShortcutLabel() + "_logweights: COLLECT ARG=" + thew[0]->getName() + " STRIDE=" + stride + " CLEAR=" + clearstride ); } // And finally create a value that contains as many ones as there are data points (this is used if we want to do Classical MDS diff --git a/src/landmarks/FarthestPointSampling.cpp b/src/landmarks/FarthestPointSampling.cpp index 119a982cce..700fad7ae7 100644 --- a/src/landmarks/FarthestPointSampling.cpp +++ b/src/landmarks/FarthestPointSampling.cpp @@ -42,11 +42,15 @@ class FarthestPointSampling : public matrixtools::MatrixOperationBase { public: static void registerKeywords( Keywords& keys ); explicit FarthestPointSampling( const ActionOptions& ao ); - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } void prepare() override ; void calculate() override ; void apply() override {} - double getForceOnMatrixElement( const unsigned& jrow, const unsigned& krow ) const { plumed_merror("this should not be called"); } + double getForceOnMatrixElement( const unsigned& jrow, const unsigned& krow ) const { + plumed_merror("this should not be called"); + } }; PLUMED_REGISTER_ACTION(FarthestPointSampling,"FARTHEST_POINT_SAMPLING") @@ -60,37 +64,57 @@ void FarthestPointSampling::registerKeywords( Keywords& keys ) { FarthestPointSampling::FarthestPointSampling( const ActionOptions& ao ): Action(ao), - MatrixOperationBase(ao) -{ - if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(0)->getShape()[1] ) error("input to this argument should be a square matrix of dissimilarities"); - parse("NZEROS",nlandmarks); parse("SEED",seed); + MatrixOperationBase(ao) { + if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(0)->getShape()[1] ) { + error("input to this argument should be a square matrix of dissimilarities"); + } + parse("NZEROS",nlandmarks); + parse("SEED",seed); log.printf(" selecting %d landmark points \n", nlandmarks ); - std::vector shape(1); shape[0] = getPntrToArgument(0)->getShape()[0]; - addValue( shape ); setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); + std::vector shape(1); + shape[0] = getPntrToArgument(0)->getShape()[0]; + addValue( shape ); + setNotPeriodic(); + getPntrToComponent(0)->buildDataStore(); } void FarthestPointSampling::prepare() { Value* myval = getPntrToComponent(0); if( myval->getShape()[0]!=getPntrToArgument(0)->getShape()[0] ) { - std::vector shape(1); shape[0] = getPntrToArgument(0)->getShape()[0]; myval->setShape(shape); + std::vector shape(1); + shape[0] = getPntrToArgument(0)->getShape()[0]; + myval->setShape(shape); + } + for(unsigned i=0; iset( i, 0.0 ); + } + for(unsigned i=nlandmarks; igetShape()[0]; ++i) { + myval->set( i, 1.0 ); } - for(unsigned i=0; iset( i, 0.0 ); - for(unsigned i=nlandmarks; igetShape()[0]; ++i) myval->set( i, 1.0 ); } void FarthestPointSampling::calculate() { - Value* myval=getPntrToComponent(0); unsigned npoints = getPntrToArgument(0)->getShape()[0]; - for(unsigned i=0; iset( i, 1.0 ); + Value* myval=getPntrToComponent(0); + unsigned npoints = getPntrToArgument(0)->getShape()[0]; + for(unsigned i=0; iset( i, 1.0 ); + } std::vector landmarks( nlandmarks ); // Select first point at random - Random random; random.setSeed(-seed); double rand=random.RandU01(); - landmarks[0] = std::floor( npoints*rand ); myval->set( landmarks[0], 0 ); + Random random; + random.setSeed(-seed); + double rand=random.RandU01(); + landmarks[0] = std::floor( npoints*rand ); + myval->set( landmarks[0], 0 ); // Now find distance to all other points (N.B. We can use squared distances here for speed) - Matrix distances( nlandmarks, npoints ); Value* myarg = getPntrToArgument(0); - for(unsigned i=0; iget( landmarks[0]*npoints + i ); + Matrix distances( nlandmarks, npoints ); + Value* myarg = getPntrToArgument(0); + for(unsigned i=0; iget( landmarks[0]*npoints + i ); + } // Now find all other landmarks for(unsigned i=1; imaxd ) { + maxd=mind; + landmarks[i]=j; } - if( mind>maxd ) { maxd=mind; landmarks[i]=j; } } myval->set( landmarks[i], 0 ); - for(unsigned k=0; kget( landmarks[i]*npoints + k ); + for(unsigned k=0; kget( landmarks[i]*npoints + k ); + } } } diff --git a/src/landmarks/LandmarkSelection.cpp b/src/landmarks/LandmarkSelection.cpp index 87214d8596..4358fac406 100644 --- a/src/landmarks/LandmarkSelection.cpp +++ b/src/landmarks/LandmarkSelection.cpp @@ -78,61 +78,99 @@ void LandmarkSelection::registerKeywords( Keywords& keys ) { keys.addOutputComponent("logweights","ARG","the logarithms of the weights of the data points"); keys.addOutputComponent("rectdissims","DISSIMILARITIES","a rectangular matrix containing the distances between the landmark points and the rest of the points"); keys.addOutputComponent("sqrdissims","DISSIMILARITIES","a square matrix containing the distances between each pair of landmark points"); - keys.needsAction("LOGSUMEXP"); keys.needsAction("TRANSPOSE"); keys.needsAction("DISSIMILARITIES"); - keys.needsAction("ONES"); keys.needsAction("CREATE_MASK"); keys.needsAction("FARTHEST_POINT_SAMPLING"); - keys.needsAction("SELECT_WITH_MASK"); keys.needsAction("COMBINE"); keys.needsAction("VORONOI"); - keys.needsAction("MATRIX_PRODUCT"); keys.needsAction("CUSTOM"); + keys.needsAction("LOGSUMEXP"); + keys.needsAction("TRANSPOSE"); + keys.needsAction("DISSIMILARITIES"); + keys.needsAction("ONES"); + keys.needsAction("CREATE_MASK"); + keys.needsAction("FARTHEST_POINT_SAMPLING"); + keys.needsAction("SELECT_WITH_MASK"); + keys.needsAction("COMBINE"); + keys.needsAction("VORONOI"); + keys.needsAction("MATRIX_PRODUCT"); + keys.needsAction("CUSTOM"); } LandmarkSelection::LandmarkSelection( const ActionOptions& ao ): Action(ao), - ActionShortcut(ao) -{ - std::string nlandmarks; parse("NLANDMARKS",nlandmarks); bool novoronoi; parseFlag("NOVORONOI",novoronoi); - - bool nodissims; parseFlag("NODISSIMILARITIES",nodissims); - std::string argn, dissims; parse("ARG",argn); parse("DISSIMILARITIES",dissims); + ActionShortcut(ao) { + std::string nlandmarks; + parse("NLANDMARKS",nlandmarks); + bool novoronoi; + parseFlag("NOVORONOI",novoronoi); + + bool nodissims; + parseFlag("NODISSIMILARITIES",nodissims); + std::string argn, dissims; + parse("ARG",argn); + parse("DISSIMILARITIES",dissims); if( argn.length()>0 ) { ActionShortcut* as = plumed.getActionSet().getShortcutActionWithLabel( argn ); - if( !as || as->getName()!="COLLECT_FRAMES" ) error("found no COLLECT_FRAMES action with label " + argn ); + if( !as || as->getName()!="COLLECT_FRAMES" ) { + error("found no COLLECT_FRAMES action with label " + argn ); + } // Get the weights readInputLine( getShortcutLabel() + "_allweights: LOGSUMEXP ARG=" + argn + "_logweights"); } if( dissims.length()>0 ) { ActionWithValue* ds = plumed.getActionSet().selectWithLabel( dissims ); - if( (ds->copyOutput(0))->getRank()!=2 ) error("input for dissimilarities shoudl be a matrix"); + if( (ds->copyOutput(0))->getRank()!=2 ) { + error("input for dissimilarities shoudl be a matrix"); + } // Calculate the dissimilarities if the user didn't specify them } else if( !nodissims ) { - readInputLine( getShortcutLabel() + "_" + argn + "_dataT: TRANSPOSE ARG=" + argn + "_data"); dissims = getShortcutLabel() + "_dissims"; + readInputLine( getShortcutLabel() + "_" + argn + "_dataT: TRANSPOSE ARG=" + argn + "_data"); + dissims = getShortcutLabel() + "_dissims"; readInputLine( getShortcutLabel() + "_dissims: DISSIMILARITIES SQUARED ARG=" + argn + "_data," + getShortcutLabel() + "_" + argn + "_dataT"); } // This deals with a corner case whereby users have a matrix of dissimilarities but no corresponding coordinates for these frames if( argn.length()==0 && dissims.size()>0 ) { ActionWithValue* ds = plumed.getActionSet().selectWithLabel( dissims ); - if( ds->getName()!="CONSTANT" || (ds->copyOutput(0))->getRank()!=2 ) error("set ARG as well as DISSIMILARITIES"); - std::string size; Tools::convert( (ds->copyOutput(0))->getShape()[0], size ); + if( ds->getName()!="CONSTANT" || (ds->copyOutput(0))->getRank()!=2 ) { + error("set ARG as well as DISSIMILARITIES"); + } + std::string size; + Tools::convert( (ds->copyOutput(0))->getShape()[0], size ); readInputLine( getShortcutLabel() + "_allweights: ONES SIZE=" + size ); } if( getName()=="LANDMARK_SELECT_STRIDE" ) { readInputLine( getShortcutLabel() + "_mask: CREATE_MASK ARG=" + getShortcutLabel() + "_allweights TYPE=stride NZEROS=" + nlandmarks ); } else if( getName()=="LANDMARK_SELECT_RANDOM" ) { - if( argn.length()==0 ) error("must set COLLECT_FRAMES object for landmark selection using ARG keyword"); - std::string seed; parse("SEED",seed); if( seed.length()>0 ) seed = " SEED=" + seed; + if( argn.length()==0 ) { + error("must set COLLECT_FRAMES object for landmark selection using ARG keyword"); + } + std::string seed; + parse("SEED",seed); + if( seed.length()>0 ) { + seed = " SEED=" + seed; + } readInputLine( getShortcutLabel() + "_mask: CREATE_MASK ARG=" + getShortcutLabel() + "_allweights TYPE=random NZEROS=" + nlandmarks + seed ); } else if( getName()=="LANDMARK_SELECT_FPS" ) { - if( dissims.length()==0 ) error("dissimiarities must be defined to use FPS sampling"); - std::string seed; parse("SEED",seed); if( seed.length()>0 ) seed = " SEED=" + seed; + if( dissims.length()==0 ) { + error("dissimiarities must be defined to use FPS sampling"); + } + std::string seed; + parse("SEED",seed); + if( seed.length()>0 ) { + seed = " SEED=" + seed; + } readInputLine( getShortcutLabel() + "_mask: FARTHEST_POINT_SAMPLING ARG=" + dissims + " NZEROS=" + nlandmarks + seed ); } - if( argn.length()>0 ) readInputLine( getShortcutLabel() + "_data: SELECT_WITH_MASK ARG=" + argn + "_data ROW_MASK=" + getShortcutLabel() + "_mask"); + if( argn.length()>0 ) { + readInputLine( getShortcutLabel() + "_data: SELECT_WITH_MASK ARG=" + argn + "_data ROW_MASK=" + getShortcutLabel() + "_mask"); + } - unsigned nland; Tools::convert( nlandmarks, nland ); + unsigned nland; + Tools::convert( nlandmarks, nland ); if( dissims.length()>0 ) { ActionWithValue* ds = plumed.getActionSet().selectWithLabel( dissims ); if( (ds->copyOutput(0))->getShape()[0]==nland ) { - if( !novoronoi ) { warning("cannot use voronoi procedure to give weights as not all distances between points are known"); novoronoi=true; } + if( !novoronoi ) { + warning("cannot use voronoi procedure to give weights as not all distances between points are known"); + novoronoi=true; + } readInputLine( getShortcutLabel() + "_sqrdissims: COMBINE ARG=" + dissims + " PERIODIC=NO"); } else { readInputLine( getShortcutLabel() + "_rmask: CREATE_MASK ARG=" + getShortcutLabel() + "_allweights TYPE=nomask"); @@ -148,11 +186,15 @@ LandmarkSelection::LandmarkSelection( const ActionOptions& ao ): readInputLine( getShortcutLabel() + "_weights: TRANSPOSE ARG=" + getShortcutLabel() + "_weightsT"); readInputLine( getShortcutLabel() + "_logweights: CUSTOM ARG=" + getShortcutLabel() + "_weights FUNC=log(x) PERIODIC=NO"); } else if( argn.length()>0 ) { - if( !novoronoi ) warning("cannot use voronoi procedure to give weights to landmark points as DISSIMILARITIES was not set"); + if( !novoronoi ) { + warning("cannot use voronoi procedure to give weights to landmark points as DISSIMILARITIES was not set"); + } readInputLine( getShortcutLabel() + "_logweights: SELECT_WITH_MASK ARG=" + argn + "_logweights MASK=" + getShortcutLabel() + "_mask"); } // Create the vector of ones that is needed by Classical MDS - if( argn.length()>0 ) readInputLine( getShortcutLabel() + "_ones: SELECT_WITH_MASK ARG=" + argn + "_ones MASK=" + getShortcutLabel() + "_mask"); + if( argn.length()>0 ) { + readInputLine( getShortcutLabel() + "_ones: SELECT_WITH_MASK ARG=" + argn + "_ones MASK=" + getShortcutLabel() + "_mask"); + } } } diff --git a/src/landmarks/LogSumExp.cpp b/src/landmarks/LogSumExp.cpp index 9423a1e7ac..62bf7a1dbe 100644 --- a/src/landmarks/LogSumExp.cpp +++ b/src/landmarks/LogSumExp.cpp @@ -50,16 +50,18 @@ void LogSumExp::registerKeywords( Keywords& keys ) { ActionShortcut::registerKeywords( keys ); keys.add("compulsory","ARG","the vector of logweights that you would like to normalise using the logsumexp trick"); keys.setValueDescription("the logarithms of the input weights logweights that are computed with the log-sum weights formula"); - keys.needsAction("HIGHEST"); keys.needsAction("CUSTOM"); keys.needsAction("SUM"); + keys.needsAction("HIGHEST"); + keys.needsAction("CUSTOM"); + keys.needsAction("SUM"); } LogSumExp::LogSumExp( const ActionOptions& ao ): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Find the argument name - std::string argn; parse("ARG",argn); + std::string argn; + parse("ARG",argn); // Find the maximum weight readInputLine( getShortcutLabel() + "_maxlogweight: HIGHEST ARG=" + argn ); readInputLine( getShortcutLabel() + "_maxweight: CUSTOM ARG=" + getShortcutLabel() + "_maxlogweight FUNC=exp(x) PERIODIC=NO"); diff --git a/src/logmfd/LogMFD.cpp b/src/logmfd/LogMFD.cpp index 1ddc9b561d..9ed5029121 100644 --- a/src/logmfd/LogMFD.cpp +++ b/src/logmfd/LogMFD.cpp @@ -585,8 +585,7 @@ LogMFD::LogMFD( const ActionOptions& ao ): ffict(getNumberOfArguments(),0.0), fict_ave(getNumberOfArguments(),0.0), fictValue(getNumberOfArguments(),NULL), - vfictValue(getNumberOfArguments(),NULL) -{ + vfictValue(getNumberOfArguments(),NULL) { backup.fict.resize(getNumberOfArguments(),0.0); backup.vfict.resize(getNumberOfArguments(),0.0); backup.ffict.resize(getNumberOfArguments(),0.0); @@ -626,15 +625,13 @@ LogMFD::LogMFD( const ActionOptions& ao ): parseVector("WORK",vwork); // initial work of this replica work = vwork[multi_sim_comm.Get_rank()]; - } - else { + } else { work = 0.0; } if( kbtpd>=0.0 ) { kbtpd *= getKBoltzmann(); - } - else { + } else { kbtpd = kbt; } @@ -646,11 +643,9 @@ LogMFD::LogMFD( const ActionOptions& ao ): if(alpha == 0.0 && gamma == 0.0) { alpha = 4.0; gamma = 1 / alpha; - } - else if(alpha != 0.0 && gamma == 0.0) { + } else if(alpha != 0.0 && gamma == 0.0) { gamma = 1 / alpha; - } - else if(alpha == 0.0 && gamma != 0.0) { + } else if(alpha == 0.0 && gamma != 0.0) { alpha = 1 / gamma; } @@ -660,23 +655,22 @@ LogMFD::LogMFD( const ActionOptions& ao ): if( multi_sim_comm.Get_size()>1 ) { if( TAMD ) { log.printf("TAMD-PD, replica parallel of TAMD, no logarithmic flattening.\n"); - } - else { + } else { log.printf("LogPD, replica parallel of LogMFD.\n"); } log.printf("number of replica : %d.\n", multi_sim_comm.Get_size() ); - } - else { + } else { if( TAMD ) { log.printf("TAMD, no logarithmic flattening.\n"); - } - else { + } else { log.printf("LogMFD, logarithmic flattening.\n"); } } log.printf(" with harmonic force constant "); - for(unsigned i=0; igetDomain(a,b); componentIsPeriodic(comp,a,b); - } - else { + } else { componentIsNotPeriodic(comp); } fictValue[i] = getPntrToComponent(comp); @@ -763,7 +766,9 @@ void LogMFD::calculate() { // set initial values of fictitious variables if they were not specified. for(unsigned i=0; i1 ) { fprintf(outlog, "# LogPD, replica parallel of LogMFD\n"); fprintf(outlog, "# number of replica : %d\n", multi_sim_comm.Get_size() ); - } - else { + } else { fprintf(outlog, "# LogMFD\n"); } @@ -923,7 +924,9 @@ void LogMFD::calculate() { bounces back variables, updates free energy, and record logs. */ void LogMFD::update() { - if( (getStep()-step_initial)%interval != interval-1 ) return; + if( (getStep()-step_initial)%interval != interval-1 ) { + return; + } for(unsigned i=0; i argnames; parseVector("ARG",argnames); - std::string reference_data, metric, mtype; parse("TYPE", mtype); - std::string reference; parse("REFERENCE",reference); - FILE* fp=std::fopen(reference.c_str(),"r"); PDB mypdb; if(!fp) error("could not open reference file " + reference ); - bool do_read=mypdb.readFromFilepointer(fp,false,0.1); if( !do_read ) error("missing file " + reference ); + std::vector argnames; + parseVector("ARG",argnames); + std::string reference_data, metric, mtype; + parse("TYPE", mtype); + std::string reference; + parse("REFERENCE",reference); + FILE* fp=std::fopen(reference.c_str(),"r"); + PDB mypdb; + if(!fp) { + error("could not open reference file " + reference ); + } + bool do_read=mypdb.readFromFilepointer(fp,false,0.1); + if( !do_read ) { + error("missing file " + reference ); + } // Create list of reference configurations that PLUMED will use Path::readInputFrames( reference, mtype, argnames, true, this, reference_data ); // Now get coordinates on spath - std::vector pnames; parseVector("PROPERTY",pnames); Path::readPropertyInformation( pnames, getShortcutLabel(), reference, this ); + std::vector pnames; + parseVector("PROPERTY",pnames); + Path::readPropertyInformation( pnames, getShortcutLabel(), reference, this ); // Create action that computes the geometric path variablesa - std::string propstr = getShortcutLabel() + "_ind"; if( pnames.size()>0 ) propstr = pnames[0] + "_ref"; - if( argnames.size()>0 ) readInputLine( getShortcutLabel() + ": GEOMETRIC_PATH ARG=" + getShortcutLabel() + "_data " + " PROPERTY=" + propstr + " REFERENCE=" + reference_data + " METRIC={DIFFERENCE}"); - else { - std::string num, align_str, displace_str; Tools::convert( mypdb.getOccupancy()[0], align_str ); Tools::convert( mypdb.getBeta()[0], displace_str ); - for(unsigned j=1; j0 ) { + propstr = pnames[0] + "_ref"; + } + if( argnames.size()>0 ) { + readInputLine( getShortcutLabel() + ": GEOMETRIC_PATH ARG=" + getShortcutLabel() + "_data " + " PROPERTY=" + propstr + " REFERENCE=" + reference_data + " METRIC={DIFFERENCE}"); + } else { + std::string num, align_str, displace_str; + Tools::convert( mypdb.getOccupancy()[0], align_str ); + Tools::convert( mypdb.getBeta()[0], displace_str ); + for(unsigned j=1; j0 ) readInputLine( getShortcutLabel() + "_disp: AVERAGE_PATH_DISPLACEMENT ARG=" + getShortcutLabel() + "_data HALFLIFE=" + halflife + " CLEAR=" + update + " METRIC={DIFFERENCE} REFERENCE=" + reference_data ); - else readInputLine( getShortcutLabel() + "_disp: AVERAGE_PATH_DISPLACEMENT ARG=" + getShortcutLabel() + "_data.disp HALFLIFE=" + halflife + " CLEAR=" + update + " METRIC={" + metric + "} METRIC_COMPONENT=disp REFERENCE=" + reference_data ); + std::string update, halflife; + parse("HALFLIFE",halflife); + parse("UPDATE",update); + std::string refframes = " REFERENCE=" + getShortcutLabel() + "_pos"; + if( argnames.size()>0 ) { + readInputLine( getShortcutLabel() + "_disp: AVERAGE_PATH_DISPLACEMENT ARG=" + getShortcutLabel() + "_data HALFLIFE=" + halflife + " CLEAR=" + update + " METRIC={DIFFERENCE} REFERENCE=" + reference_data ); + } else { + readInputLine( getShortcutLabel() + "_disp: AVERAGE_PATH_DISPLACEMENT ARG=" + getShortcutLabel() + "_data.disp HALFLIFE=" + halflife + " CLEAR=" + update + " METRIC={" + metric + "} METRIC_COMPONENT=disp REFERENCE=" + reference_data ); + } // Create the object to update the path - std::string fixedn; parse("FIXED",fixedn); std::string component="METRIC_COMPONENT=disp"; if( argnames.size()>0 ) { metric="DIFFERENCE"; component=""; } - if( fixedn.length()>0 ) readInputLine("REPARAMETERIZE_PATH DISPLACE_FRAMES=" + getShortcutLabel() + "_disp FIXED=" + fixedn + " STRIDE=" + update + " METRIC={" + metric + "} " + component + " REFERENCE=" + reference_data ); - else readInputLine("REPARAMETERIZE_PATH DISPLACE_FRAMES=" + getShortcutLabel() + "_disp STRIDE=" + update + " METRIC={" + metric + "} " + component + " REFERENCE=" + reference_data ); + std::string fixedn; + parse("FIXED",fixedn); + std::string component="METRIC_COMPONENT=disp"; + if( argnames.size()>0 ) { + metric="DIFFERENCE"; + component=""; + } + if( fixedn.length()>0 ) { + readInputLine("REPARAMETERIZE_PATH DISPLACE_FRAMES=" + getShortcutLabel() + "_disp FIXED=" + fixedn + " STRIDE=" + update + " METRIC={" + metric + "} " + component + " REFERENCE=" + reference_data ); + } else { + readInputLine("REPARAMETERIZE_PATH DISPLACE_FRAMES=" + getShortcutLabel() + "_disp STRIDE=" + update + " METRIC={" + metric + "} " + component + " REFERENCE=" + reference_data ); + } // Information for write out - std::string wfilename; parse("WFILE",wfilename); + std::string wfilename; + parse("WFILE",wfilename); if( wfilename.length()>0 ) { // This just gets the atom numbers for output std::string atomstr; if( argnames.size()==0 ) { - FILE* fp=std::fopen(reference.c_str(),"r"); double fake_unit=0.1; PDB mypdb; bool do_read=mypdb.readFromFilepointer(fp,false,fake_unit); - std::string num; Tools::convert( mypdb.getAtomNumbers()[0].serial(), atomstr ); - for(unsigned j=1; j0 ) { - std::string argstr = argnames[0]; for(unsigned i=1; i pcoord; parseVector("PROPERTY", pcoord ); std::vector theprop; + std::vector pcoord; + parseVector("PROPERTY", pcoord ); + std::vector theprop; ActionWithArguments::interpretArgumentList( pcoord, plumed.getActionSet(), this, theprop ); - if( theprop.size()!=1 ) error("did not find property to project on"); - if( theprop[0]->getNumberOfValues()!=getPntrToArgument(0)->getShape()[0] ) error("mismatch between number of frames and property of interest"); + if( theprop.size()!=1 ) { + error("did not find property to project on"); + } + if( theprop[0]->getNumberOfValues()!=getPntrToArgument(0)->getShape()[0] ) { + error("mismatch between number of frames and property of interest"); + } log.printf(" projecting onto : %s \n", theprop[0]->getName().c_str() ); - std::vector args( getArguments() ); args.push_back( theprop[0] ); requestArguments( args ); + std::vector args( getArguments() ); + args.push_back( theprop[0] ); + requestArguments( args ); // Create the values to store the output - addComponentWithDerivatives("s"); componentIsNotPeriodic("s"); - addComponentWithDerivatives("z"); componentIsNotPeriodic("z"); + addComponentWithDerivatives("s"); + componentIsNotPeriodic("s"); + addComponentWithDerivatives("z"); + componentIsNotPeriodic("z"); } unsigned GeometricPath::getNumberOfDerivatives() { @@ -81,37 +94,64 @@ unsigned GeometricPath::getNumberOfDerivatives() { } void GeometricPath::calculate() { - unsigned k=0, iclose1=0, iclose2=0; double v1v1=0, v3v3=0; + unsigned k=0, iclose1=0, iclose2=0; + double v1v1=0, v3v3=0; unsigned nrows = getPntrToArgument(0)->getShape()[0]; unsigned ncols = getPntrToArgument(0)->getShape()[1]; for(unsigned i=0; iget(k); - dist += tmp*tmp; k++; + dist += tmp*tmp; + k++; + } + if( i==0 ) { + v1v1 = dist; + iclose1 = 0; + } else if( dist1 ) isign=1; else if( isign<-1 ) isign=-1; + if( isign>1 ) { + isign=1; + } else if( isign<-1 ) { + isign=-1; + } int iclose3 = iclose1 + isign; - unsigned ifrom=iclose1, ito=iclose3; if( iclose3<0 || iclose3>=nrows ) { ifrom=iclose2; ito=iclose1; } + unsigned ifrom=iclose1, ito=iclose3; + if( iclose3<0 || iclose3>=nrows ) { + ifrom=iclose2; + ito=iclose1; + } // And calculate projection of vector connecting current point to closest frame on vector connecting nearest two frames - std::vector displace; path_projector.getDisplaceVector( ifrom, ito, displace ); - double v2v2=0, v1v2=0; k=ncols*iclose1; - for(unsigned i=0; iget(k+i); } + std::vector displace; + path_projector.getDisplaceVector( ifrom, ito, displace ); + double v2v2=0, v1v2=0; + k=ncols*iclose1; + for(unsigned i=0; iget(k+i); + } // This computes s value double spacing = getPntrToArgument(1)->get(iclose1) - getPntrToArgument(1)->get(iclose2); double root = sqrt( v1v2*v1v2 - v2v2 * ( v1v1 - v3v3) ); double dx = 0.5 * ( (root + v1v2) / v2v2 - 1.); double path_s = getPntrToArgument(1)->get(iclose1) + spacing * dx; - Value* sp = getPntrToComponent(0); sp->set( path_s ); + Value* sp = getPntrToComponent(0); + sp->set( path_s ); if( !doNotCalculateDerivatives() ) { for(unsigned i=0; iaddDerivative( ncols*iclose1 + i, 0.5*spacing*(v1v2*displace[i]/v2v2 - getPntrToArgument(0)->get(ncols*iclose1 + i))/root + 0.5*spacing*displace[i]/v2v2 ); @@ -120,10 +160,17 @@ void GeometricPath::calculate() { } // This computes z value - path_projector.getDisplaceVector( iclose2, iclose1, displace ); double v4v4=0, proj=0; k=ncols*iclose1; - for(unsigned i=0; iget(k+i); } - double path_z = v1v1 + dx*dx*v4v4 - 2*dx*proj; path_z = sqrt(path_z); - Value* zp = getPntrToComponent(1); zp->set( path_z ); + path_projector.getDisplaceVector( iclose2, iclose1, displace ); + double v4v4=0, proj=0; + k=ncols*iclose1; + for(unsigned i=0; iget(k+i); + } + double path_z = v1v1 + dx*dx*v4v4 - 2*dx*proj; + path_z = sqrt(path_z); + Value* zp = getPntrToComponent(1); + zp->set( path_z ); if( !doNotCalculateDerivatives() ) { for(unsigned i=0; iaddDerivative( ncols*iclose1 + i, (1/path_z)*(getPntrToArgument(0)->get(ncols*iclose1 + i) + diff --git a/src/mapping/GeometricPathShortcut.cpp b/src/mapping/GeometricPathShortcut.cpp index beecdea35c..ac7d58438d 100644 --- a/src/mapping/GeometricPathShortcut.cpp +++ b/src/mapping/GeometricPathShortcut.cpp @@ -45,31 +45,58 @@ class GeometricPathShortcut : public ActionShortcut { PLUMED_REGISTER_ACTION(GeometricPathShortcut,"GPATH") void GeometricPathShortcut::registerKeywords( Keywords& keys ) { - ActionShortcut::registerKeywords( keys ); Path::registerInputFileKeywords( keys ); + ActionShortcut::registerKeywords( keys ); + Path::registerInputFileKeywords( keys ); keys.add("optional","PROPERTY","read in path coordinates by finding option with this label in remark of pdb frames"); keys.addOutputComponent("s","default","the position on the path"); keys.addOutputComponent("z","default","the distance from the path"); - keys.needsAction("DISPLACEMENT"); keys.needsAction("GEOMETRIC_PATH"); keys.needsAction("PDB2CONSTANT"); keys.needsAction("CONSTANT"); + keys.needsAction("DISPLACEMENT"); + keys.needsAction("GEOMETRIC_PATH"); + keys.needsAction("PDB2CONSTANT"); + keys.needsAction("CONSTANT"); } GeometricPathShortcut::GeometricPathShortcut( const ActionOptions& ao ): Action(ao), - ActionShortcut(ao) -{ - std::string mtype, reference_data; std::vector argnames; parseVector("ARG",argnames); parse("TYPE", mtype); + ActionShortcut(ao) { + std::string mtype, reference_data; + std::vector argnames; + parseVector("ARG",argnames); + parse("TYPE", mtype); // Create list of reference configurations that PLUMED will use - std::string reference; parse("REFERENCE",reference); - FILE* fp=std::fopen(reference.c_str(),"r"); PDB mypdb; if(!fp) error("could not open reference file " + reference ); - bool do_read=mypdb.readFromFilepointer(fp,false,0.1); if( !do_read ) error("missing file " + reference ); + std::string reference; + parse("REFERENCE",reference); + FILE* fp=std::fopen(reference.c_str(),"r"); + PDB mypdb; + if(!fp) { + error("could not open reference file " + reference ); + } + bool do_read=mypdb.readFromFilepointer(fp,false,0.1); + if( !do_read ) { + error("missing file " + reference ); + } Path::readInputFrames( reference, mtype, argnames, true, this, reference_data ); // Now get coordinates on spath - std::vector pnames; parseVector("PROPERTY",pnames); Path::readPropertyInformation( pnames, getShortcutLabel(), reference, this ); + std::vector pnames; + parseVector("PROPERTY",pnames); + Path::readPropertyInformation( pnames, getShortcutLabel(), reference, this ); // Create action that computes the geometric path variablesa - std::string propstr = getShortcutLabel() + "_ind"; if( pnames.size()>0 ) propstr = pnames[0] + "_ref"; - if( argnames.size()>0 ) readInputLine( getShortcutLabel() + ": GEOMETRIC_PATH ARG=" + getShortcutLabel() + "_data " + " PROPERTY=" + propstr + " REFERENCE=" + reference_data + " METRIC={DIFFERENCE}"); - else { - std::string num, align_str, displace_str; Tools::convert( mypdb.getOccupancy()[0], align_str ); Tools::convert( mypdb.getBeta()[0], displace_str ); - for(unsigned j=1; j0 ) { + propstr = pnames[0] + "_ref"; + } + if( argnames.size()>0 ) { + readInputLine( getShortcutLabel() + ": GEOMETRIC_PATH ARG=" + getShortcutLabel() + "_data " + " PROPERTY=" + propstr + " REFERENCE=" + reference_data + " METRIC={DIFFERENCE}"); + } else { + std::string num, align_str, displace_str; + Tools::convert( mypdb.getOccupancy()[0], align_str ); + Tools::convert( mypdb.getBeta()[0], displace_str ); + for(unsigned j=1; j0 ) { // And now create the rmsd object std::string rmsd_line = getShortcutLabel() + "_at: RMSD DISPLACEMENT SQUARED NUMBER=1 REFERENCE=" + reference; - bool nopbc; parseFlag("NOPBC",nopbc); if(nopbc) rmsd_line += " NOPBC"; + bool nopbc; + parseFlag("NOPBC",nopbc); + if(nopbc) { + rmsd_line += " NOPBC"; + } // Now create the RMSD object readInputLine( rmsd_line + " TYPE=" + mtype ); } - std::vector argnames; parseVector("ARG",argnames); unsigned nargs=0; std::string instargs, refargs; std::vector theargs; - if( argnames.size()>0 ) ActionWithArguments::interpretArgumentList( argnames, plumed.getActionSet(), this, theargs ); + std::vector argnames; + parseVector("ARG",argnames); + unsigned nargs=0; + std::string instargs, refargs; + std::vector theargs; + if( argnames.size()>0 ) { + ActionWithArguments::interpretArgumentList( argnames, plumed.getActionSet(), this, theargs ); + } for(unsigned i=0; igetName() ); nargs += theargs[i]->getNumberOfValues(); + std::string iargn = Path::fixArgumentName( theargs[i]->getName() ); + nargs += theargs[i]->getNumberOfValues(); if( theargs[i]->getNumberOfValues()>1 ) { readInputLine( getShortcutLabel() + "_ref_" + iargn + "T: PDB2CONSTANT NUMBER=1 REFERENCE=" + reference + " ARG=" + theargs[i]->getName() ); readInputLine( getShortcutLabel() + "_ref_" + iargn + ": TRANSPOSE ARG=" + getShortcutLabel() + "_ref_" + iargn + "T"); - } else readInputLine( getShortcutLabel() + "_ref_" + iargn + ": PDB2CONSTANT NUMBER=1 REFERENCE=" + reference + " ARG=" + theargs[i]->getName() ); - if( i==0 ) { instargs=" ARG1=" + theargs[i]->getName(); refargs=" ARG2=" + getShortcutLabel() + "_ref_" + iargn; } - else { instargs +="," + theargs[i]->getName(); refargs +="," + getShortcutLabel() + "_ref_" + iargn; } + } else { + readInputLine( getShortcutLabel() + "_ref_" + iargn + ": PDB2CONSTANT NUMBER=1 REFERENCE=" + reference + " ARG=" + theargs[i]->getName() ); + } + if( i==0 ) { + instargs=" ARG1=" + theargs[i]->getName(); + refargs=" ARG2=" + getShortcutLabel() + "_ref_" + iargn; + } else { + instargs +="," + theargs[i]->getName(); + refargs +="," + getShortcutLabel() + "_ref_" + iargn; + } + } + if( theargs.size()>0 ) { + readInputLine( getShortcutLabel() + "_argdist: EUCLIDEAN_DISTANCE SQUARED" + instargs + refargs ); } - if( theargs.size()>0 ) readInputLine( getShortcutLabel() + "_argdist: EUCLIDEAN_DISTANCE SQUARED" + instargs + refargs ); if( pdb.getPositions().size()>0 && theargs.size()>0 ) { readInputLine( getShortcutLabel() + ": CONCATENATE ARG=" + getShortcutLabel() + "_at.disp," + getShortcutLabel() + "_argdist_diffT"); readInputLine( getShortcutLabel() + "_dist: COMBINE ARG=" + getShortcutLabel() + "_at.dist," + getShortcutLabel() + "_argdist PERIODIC=NO"); } // Get the displace stuff - std::vector displace( pdb.getBeta() ); double dtot = 0; - for(unsigned i=0; i displace( pdb.getBeta() ); + double dtot = 0; + for(unsigned i=0; i argdir(nargs); PDB mypdb; do_read=mypdb.readFromFilepointer(fp,plumed.usingNaturalUnits(),0.1/plumed.getUnits().getLength()); + std::vector argdir(nargs); + PDB mypdb; + do_read=mypdb.readFromFilepointer(fp,plumed.usingNaturalUnits(),0.1/plumed.getUnits().getLength()); if( do_read ) { nfram++; // Normalize the eigenvector in the input @@ -246,10 +290,17 @@ PCAVars::PCAVars( const ActionOptions& ao ): unsigned k=0; for(unsigned i=0; i argval( theargs[i]->getNumberOfValues() ); - if( !mypdb.getArgumentValue(theargs[i]->getName(), argval) ) error("argument " + theargs[i]->getName() + " was not set in pdb input"); - for(unsigned j=0; jgetName(), argval) ) { + error("argument " + theargs[i]->getName() + " was not set in pdb input"); + } + for(unsigned j=0; j normed_coeffs( 3*mypdb.getPositions().size() ); + norm = sqrt( norm ); + std::vector normed_coeffs( 3*mypdb.getPositions().size() ); for(unsigned i=0; i0 ) { - if( nfram==1 ) Tools::convert( normed_coeffs[0], pvec ); - else { Tools::convert( normed_coeffs[0], coeff1 ); pvec += "," + coeff1; } + if( nfram==1 ) { + Tools::convert( normed_coeffs[0], pvec ); + } else { + Tools::convert( normed_coeffs[0], coeff1 ); + pvec += "," + coeff1; + } for(unsigned i=1; i0 ) { - if( nfram==1 ) Tools::convert( argdir[0] / norm, pvec ); - else { Tools::convert( argdir[0] / norm, coeff1 ); pvec += "," + coeff1; } - for(unsigned i=1; i0 ) readInputLine( getShortcutLabel() + "_eig: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_peig," + getShortcutLabel() + "_at.disp"); - else if( theargs.size()>0 ) readInputLine( getShortcutLabel() + "_eig: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_peig," + getShortcutLabel() + "_argdist_diffT"); + if( pdb.getPositions().size()>0 && theargs.size()>0 ) { + readInputLine( getShortcutLabel() + "_eig: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_peig," + getShortcutLabel() ); + } else if( pdb.getPositions().size()>0 ) { + readInputLine( getShortcutLabel() + "_eig: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_peig," + getShortcutLabel() + "_at.disp"); + } else if( theargs.size()>0 ) { + readInputLine( getShortcutLabel() + "_eig: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_peig," + getShortcutLabel() + "_argdist_diffT"); + } for(unsigned i=0; i0 && theargs.size()>0 ) readInputLine( getShortcutLabel() + "_residual: CUSTOM ARG=" + getShortcutLabel() + "_dist," + getShortcutLabel() + "_eigsum2 FUNC=sqrt(x-y) PERIODIC=NO"); - else if( pdb.getPositions().size()>0 ) readInputLine( getShortcutLabel() + "_residual: CUSTOM ARG=" + getShortcutLabel() + "_at.dist," + getShortcutLabel() + "_eigsum2 FUNC=sqrt(x-y) PERIODIC=NO"); - else if( theargs.size()>0 ) readInputLine( getShortcutLabel() + "_residual: CUSTOM ARG=" + getShortcutLabel() + "_argdist," + getShortcutLabel() + "_eigsum2 FUNC=sqrt(x-y) PERIODIC=NO"); + if( pdb.getPositions().size()>0 && theargs.size()>0 ) { + readInputLine( getShortcutLabel() + "_residual: CUSTOM ARG=" + getShortcutLabel() + "_dist," + getShortcutLabel() + "_eigsum2 FUNC=sqrt(x-y) PERIODIC=NO"); + } else if( pdb.getPositions().size()>0 ) { + readInputLine( getShortcutLabel() + "_residual: CUSTOM ARG=" + getShortcutLabel() + "_at.dist," + getShortcutLabel() + "_eigsum2 FUNC=sqrt(x-y) PERIODIC=NO"); + } else if( theargs.size()>0 ) { + readInputLine( getShortcutLabel() + "_residual: CUSTOM ARG=" + getShortcutLabel() + "_argdist," + getShortcutLabel() + "_eigsum2 FUNC=sqrt(x-y) PERIODIC=NO"); + } } } diff --git a/src/mapping/Path.cpp b/src/mapping/Path.cpp index aab10ade2f..9f5e345c70 100644 --- a/src/mapping/Path.cpp +++ b/src/mapping/Path.cpp @@ -209,7 +209,8 @@ PLUMED_REGISTER_ACTION(Path,"PATH") PLUMED_REGISTER_ACTION(Path,"GPROPERTYMAP") void Path::registerKeywords( Keywords& keys ) { - ActionShortcut::registerKeywords( keys ); Path::registerInputFileKeywords( keys ); + ActionShortcut::registerKeywords( keys ); + Path::registerInputFileKeywords( keys ); keys.add("optional","PROPERTY","the property to be used in the index. This should be in the REMARK of the reference"); keys.add("compulsory","LAMBDA","the lambda parameter is needed for smoothing, is in the units of plumed"); keys.addOutputComponent("gspath","GPATH","the position along the path calculated using the geometric formula"); @@ -229,34 +230,57 @@ void Path::registerInputFileKeywords( Keywords& keys ) { keys.addFlag("NOSPATH",false,"do not calculate the spath CV"); keys.addFlag("NOZPATH",false,"do not calculate the zpath CV"); keys.addFlag("GPATH",false,"calculate the trigonometric path"); - keys.needsAction("DRMSD"); keys.needsAction("RMSD"); keys.needsAction("LOWEST"); keys.needsAction("GPATH"); - keys.needsAction("EUCLIDEAN_DISTANCE"); keys.needsAction("CUSTOM"); keys.needsAction("SUM"); keys.needsAction("COMBINE"); - keys.needsAction("NORMALIZED_EUCLIDEAN_DISTANCE"); keys.needsAction("PDB2CONSTANT"); keys.needsAction("CONSTANT"); + keys.needsAction("DRMSD"); + keys.needsAction("RMSD"); + keys.needsAction("LOWEST"); + keys.needsAction("GPATH"); + keys.needsAction("EUCLIDEAN_DISTANCE"); + keys.needsAction("CUSTOM"); + keys.needsAction("SUM"); + keys.needsAction("COMBINE"); + keys.needsAction("NORMALIZED_EUCLIDEAN_DISTANCE"); + keys.needsAction("PDB2CONSTANT"); + keys.needsAction("CONSTANT"); } Path::Path( const ActionOptions& ao ): Action(ao), - ActionShortcut(ao) -{ - bool nospath, nozpath, gpath; parseFlag("NOSPATH",nospath); parseFlag("NOZPATH",nozpath); parseFlag("GPATH",gpath); + ActionShortcut(ao) { + bool nospath, nozpath, gpath; + parseFlag("NOSPATH",nospath); + parseFlag("NOZPATH",nozpath); + parseFlag("GPATH",gpath); if( gpath ) { readInputLine( getShortcutLabel() + "_gpath: GPATH " + convertInputLineToString() ); readInputLine( getShortcutLabel() + "_gspath: COMBINE ARG=" + getShortcutLabel() + "_gpath.s PERIODIC=NO"); readInputLine( getShortcutLabel() + "_gzpath: COMBINE ARG=" + getShortcutLabel() + "_gpath.z PERIODIC=NO"); } - if( nospath && nozpath ) return; + if( nospath && nozpath ) { + return; + } // Setup the properties std::vector properties, pnames; - if( getName()=="PATH") { properties.resize(1); } - else { parseVector("PROPERTY",pnames); properties.resize( pnames.size() ); } - std::string type, reference_data, reference; parse("REFERENCE",reference); - std::vector argnames; parseVector("ARG",argnames); parse("TYPE",type); - if( type.find("DRMSD")!=std::string::npos ) readInputLine( getShortcutLabel() + "_data: DRMSD SQUARED TYPE=" + type + " REFERENCE=" + reference ); - else readInputFrames( reference, type, argnames, false, this, reference_data ); + if( getName()=="PATH") { + properties.resize(1); + } else { + parseVector("PROPERTY",pnames); + properties.resize( pnames.size() ); + } + std::string type, reference_data, reference; + parse("REFERENCE",reference); + std::vector argnames; + parseVector("ARG",argnames); + parse("TYPE",type); + if( type.find("DRMSD")!=std::string::npos ) { + readInputLine( getShortcutLabel() + "_data: DRMSD SQUARED TYPE=" + type + " REFERENCE=" + reference ); + } else { + readInputFrames( reference, type, argnames, false, this, reference_data ); + } // Find the shortest distance to the frames readInputLine( getShortcutLabel() + "_mindist: LOWEST ARG=" + getShortcutLabel() + "_data"); // Now create all other parts of the calculation - std::string lambda; parse("LAMBDA",lambda); + std::string lambda; + parse("LAMBDA",lambda); // Now create MATHEVAL object to compute exponential functions readInputLine( getShortcutLabel() + "_weights: CUSTOM ARG=" + getShortcutLabel() + "_data," + getShortcutLabel() + "_mindist FUNC=exp(-(x-y)*" + lambda + ") PERIODIC=NO" ); // Create denominator @@ -284,48 +308,86 @@ Path::Path( const ActionOptions& ao ): } std::string Path::fixArgumentName( const std::string& argin ) { - std::string argout = argin; std::size_t dot=argin.find("."); - if( dot!=std::string::npos ) argout = argin.substr(0,dot) + "_" + argin.substr(dot+1); + std::string argout = argin; + std::size_t dot=argin.find("."); + if( dot!=std::string::npos ) { + argout = argin.substr(0,dot) + "_" + argin.substr(dot+1); + } return argout; } void Path::readInputFrames( const std::string& reference, const std::string& type, std::vector& argnames, const bool& displacements, ActionShortcut* action, std::string& reference_data ) { - FILE* fp=std::fopen(reference.c_str(),"r"); PDB pdb; if(!fp) action->error("could not open reference file " + reference ); - bool do_read=pdb.readFromFilepointer(fp,false,0.1); if( !do_read ) action->error("missing file " + reference ); + FILE* fp=std::fopen(reference.c_str(),"r"); + PDB pdb; + if(!fp) { + action->error("could not open reference file " + reference ); + } + bool do_read=pdb.readFromFilepointer(fp,false,0.1); + if( !do_read ) { + action->error("missing file " + reference ); + } if( pdb.getPositions().size()!=0 && argnames.size()==0 ) { reference_data = action->getShortcutLabel() + "_data_ref"; - if( displacements ) action->readInputLine( action->getShortcutLabel() + "_data: RMSD DISPLACEMENT SQUARED REFERENCE=" + reference + " TYPE=" + type ); - else action->readInputLine( action->getShortcutLabel() + "_data: RMSD SQUARED REFERENCE=" + reference + " TYPE=" + type ); + if( displacements ) { + action->readInputLine( action->getShortcutLabel() + "_data: RMSD DISPLACEMENT SQUARED REFERENCE=" + reference + " TYPE=" + type ); + } else { + action->readInputLine( action->getShortcutLabel() + "_data: RMSD SQUARED REFERENCE=" + reference + " TYPE=" + type ); + } } else if( pdb.getPositions().size()!=0 ) { reference_data = action->getShortcutLabel() + "_atomdata_ref"; - if( displacements ) action->readInputLine( action->getShortcutLabel() + "_atomdata: RMSD DISPLACEMENT SQUARED REFERENCE=" + reference + " TYPE=" + type ); - else action->readInputLine( action->getShortcutLabel() + "_atomdata: RMSD SQUARED REFERENCE=" + reference + " TYPE=" + type ); + if( displacements ) { + action->readInputLine( action->getShortcutLabel() + "_atomdata: RMSD DISPLACEMENT SQUARED REFERENCE=" + reference + " TYPE=" + type ); + } else { + action->readInputLine( action->getShortcutLabel() + "_atomdata: RMSD SQUARED REFERENCE=" + reference + " TYPE=" + type ); + } } else if( argnames.size()==0 ) { argnames.resize( pdb.getArgumentNames().size() ); - for(unsigned i=0; i theargs; + if( argnames.size()>0 ) { + ActionWithArguments::interpretArgumentList( argnames, action->plumed.getActionSet(), action, theargs ); } - std::vector theargs; if( argnames.size()>0 ) ActionWithArguments::interpretArgumentList( argnames, action->plumed.getActionSet(), action, theargs ); if( theargs.size()>0 ) { std::string instargs, refargs; for(unsigned i=0; igetName() ); action->readInputLine( action->getShortcutLabel() + "_ref_" + iargn + ": PDB2CONSTANT REFERENCE=" + reference + " ARG=" + theargs[i]->getName() ); - if( i==0 ) { instargs=" ARG1=" + theargs[i]->getName(); refargs=" ARG2=" + action->getShortcutLabel() + "_ref_" + iargn; } - else { instargs +="," + theargs[i]->getName(); refargs +="," + action->getShortcutLabel() + "_ref_" + iargn; } - if( pdb.getPositions().size()==0 && i==0 ) reference_data = action->getShortcutLabel() + "_ref_" + iargn; - else reference_data += "," + action->getShortcutLabel() + "_ref_" + iargn; + if( i==0 ) { + instargs=" ARG1=" + theargs[i]->getName(); + refargs=" ARG2=" + action->getShortcutLabel() + "_ref_" + iargn; + } else { + instargs +="," + theargs[i]->getName(); + refargs +="," + action->getShortcutLabel() + "_ref_" + iargn; + } + if( pdb.getPositions().size()==0 && i==0 ) { + reference_data = action->getShortcutLabel() + "_ref_" + iargn; + } else { + reference_data += "," + action->getShortcutLabel() + "_ref_" + iargn; + } } - std::string comname="EUCLIDEAN_DISTANCE SQUARED"; std::string coeffstr; action->parse("COEFFICIENTS",coeffstr); + std::string comname="EUCLIDEAN_DISTANCE SQUARED"; + std::string coeffstr; + action->parse("COEFFICIENTS",coeffstr); if( coeffstr.length()>0 ) { - if( displacements ) action->error("cannot use COEFFICIENTS arguments with GEOMETRIC PATH"); + if( displacements ) { + action->error("cannot use COEFFICIENTS arguments with GEOMETRIC PATH"); + } action->readInputLine( action->getShortcutLabel() + "_coeff: CONSTANT VALUES=" + coeffstr ); action->readInputLine( action->getShortcutLabel() + "_coeff2: CUSTOM ARG=" + action->getShortcutLabel() + "_coeff FUNC=x*x PERIODIC=NO"); comname = "NORMALIZED_EUCLIDEAN_DISTANCE SQUARED METRIC=" + action->getShortcutLabel() + "_coeff2"; - } else if( displacements ) comname = "DISPLACEMENT"; + } else if( displacements ) { + comname = "DISPLACEMENT"; + } - if( pdb.getPositions().size()==0 ) action->readInputLine( action->getShortcutLabel() + "_data: " + comname + instargs + refargs ); - else action->readInputLine( action->getShortcutLabel() + "_argdata: " + comname + instargs + refargs ); + if( pdb.getPositions().size()==0 ) { + action->readInputLine( action->getShortcutLabel() + "_data: " + comname + instargs + refargs ); + } else { + action->readInputLine( action->getShortcutLabel() + "_argdata: " + comname + instargs + refargs ); + } } } @@ -337,8 +399,13 @@ void Path::readPropertyInformation( const std::vector& pnames, cons } } else { ActionWithValue* av=action->plumed.getActionSet().selectWithLabel( lab + "_data" ); - unsigned nfram = av->copyOutput(0)->getShape()[0]; std::string indices = "VALUES=1"; - for(unsigned i=1; icopyOutput(0)->getShape()[0]; + std::string indices = "VALUES=1"; + for(unsigned i=1; ireadInputLine( lab + "_ind: CONSTANT " + indices ); } } diff --git a/src/mapping/PathDisplacements.cpp b/src/mapping/PathDisplacements.cpp index a202dd8f77..1ddaef3fcd 100644 --- a/src/mapping/PathDisplacements.cpp +++ b/src/mapping/PathDisplacements.cpp @@ -59,8 +59,12 @@ class PathDisplacements : public ActionWithValue, public ActionPilot, public Act PLUMED_REGISTER_ACTION(PathDisplacements,"AVERAGE_PATH_DISPLACEMENT") void PathDisplacements::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.use("ARG"); PathProjectionCalculator::registerKeywords( keys ); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionPilot::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.use("ARG"); + PathProjectionCalculator::registerKeywords( keys ); keys.add("compulsory","STRIDE","1","the frequency with which the average displacements should be collected and added to the average displacements"); keys.add("compulsory","HALFLIFE","-1","the number of MD steps after which a previously measured path distance weighs only 50 percent in the average. This option may increase convergence by allowing to forget the memory of a bad initial guess path. The default is to set this to infinity"); keys.add("compulsory","CLEAR","0","the frequency with which to clear all the accumulated data. The default value " @@ -74,30 +78,42 @@ PathDisplacements::PathDisplacements(const ActionOptions& ao): ActionPilot(ao), ActionWithArguments(ao), clearnextstep(false), - path_projector(this) -{ + path_projector(this) { // Read in clear instructions parse("CLEAR",clearstride); if( clearstride>0 ) { - if( clearstride%getStride()!=0 ) error("CLEAR parameter must be a multiple of STRIDE"); + if( clearstride%getStride()!=0 ) { + error("CLEAR parameter must be a multiple of STRIDE"); + } log.printf(" clearing average every %u steps \n",clearstride); } - double halflife; parse("HALFLIFE",halflife); + double halflife; + parse("HALFLIFE",halflife); log.printf(" weight of contribution to frame halves every %f steps \n",halflife); - if( halflife<0 ) fadefact=1.0; - else fadefact = exp( -0.693147180559945 / static_cast(halflife) ); + if( halflife<0 ) { + fadefact=1.0; + } else { + fadefact = exp( -0.693147180559945 / static_cast(halflife) ); + } // Now create the weights vector and displacements matrix unsigned nrows = getPntrToArgument(0)->getShape()[0]; unsigned ncols = getPntrToArgument(0)->getShape()[1]; - wsum.resize( nrows ); displacements.resize( nrows, ncols ); + wsum.resize( nrows ); + displacements.resize( nrows, ncols ); for(unsigned i=0; i shape(2); shape[0]=nrows; shape[1]=ncols; - addValue( shape ); setNotPeriodic(); + std::vector shape(2); + shape[0]=nrows; + shape[1]=ncols; + addValue( shape ); + setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); } @@ -113,64 +129,105 @@ void PathDisplacements::update() { if( clearnextstep ) { unsigned k=0; for(unsigned i=0; iset(k,0); k++; } + for(unsigned j=0; jset(k,0); + k++; + } } clearnextstep=false; } - unsigned k=0, iclose1=0, iclose2=0; double v1v1=0, v3v3=0; + unsigned k=0, iclose1=0, iclose2=0; + double v1v1=0, v3v3=0; for(unsigned i=0; iget(k); - dist += tmp*tmp; k++; + dist += tmp*tmp; + k++; + } + if( i==0 ) { + v1v1 = dist; + iclose1 = 0; + } else if( dist1 ) isign=1; else if( isign<-1 ) isign=-1; + if( isign>1 ) { + isign=1; + } else if( isign<-1 ) { + isign=-1; + } int iclose3 = iclose1 + isign; - unsigned ifrom=iclose1, ito=iclose3; if( iclose3<0 || iclose3>=nrows ) { ifrom=iclose2; ito=iclose1; } + unsigned ifrom=iclose1, ito=iclose3; + if( iclose3<0 || iclose3>=nrows ) { + ifrom=iclose2; + ito=iclose1; + } // Calculate the dot product of v1 with v2 path_projector.getDisplaceVector( ifrom, ito, displace_v ); - double v2v2=0, v1v2=0; unsigned kclose1 = iclose1*ncols; - for(unsigned i=0; iget(kclose1+i); } + double v2v2=0, v1v2=0; + unsigned kclose1 = iclose1*ncols; + for(unsigned i=0; iget(kclose1+i); + } double root = sqrt( v1v2*v1v2 - v2v2 * ( v1v1 - v3v3) ); double dx = 0.5 * ( (root + v1v2) / v2v2 - 1.); - double weight2 = -1.* dx; double weight1 = 1.0 + dx; + double weight2 = -1.* dx; + double weight1 = 1.0 + dx; if( weight1>1.0 ) { - weight1=1.0; weight2=0.0; + weight1=1.0; + weight2=0.0; } else if( weight2>1.0 ) { - weight1=0.0; weight2=1.0; + weight1=0.0; + weight2=1.0; } // Accumulate displacements for path for(unsigned i=0; iget(kclose1+i) - dx*displace_v[i]; - displacements(iclose1,i) += weight1 * displace; displacements(iclose2,i) += weight2 * displace; + displacements(iclose1,i) += weight1 * displace; + displacements(iclose2,i) += weight2 * displace; } // Update weight accumulators - wsum[iclose1] *= fadefact; wsum[iclose2] *= fadefact; - wsum[iclose1] += weight1; wsum[iclose2] += weight2; + wsum[iclose1] *= fadefact; + wsum[iclose2] *= fadefact; + wsum[iclose1] += weight1; + wsum[iclose2] += weight2; // Update numbers in values if( wsum[iclose1] > epsilon ) { - for(unsigned i=0; iset( kclose1+i, displacements(iclose1,i) / wsum[iclose1] ); + for(unsigned i=0; iset( kclose1+i, displacements(iclose1,i) / wsum[iclose1] ); + } } if( wsum[iclose2] > epsilon ) { unsigned kclose2 = iclose2*ncols; - for(unsigned i=0; iset( kclose2+i, displacements(iclose2,i) / wsum[iclose2] ); + for(unsigned i=0; iset( kclose2+i, displacements(iclose2,i) / wsum[iclose2] ); + } } // Clear if required - if( (getStep()>0 && clearstride>0 && getStep()%clearstride==0) ) clearnextstep=true; + if( (getStep()>0 && clearstride>0 && getStep()%clearstride==0) ) { + clearnextstep=true; + } } } diff --git a/src/mapping/PathProjectionCalculator.cpp b/src/mapping/PathProjectionCalculator.cpp index fe22867246..80eab7ed8a 100644 --- a/src/mapping/PathProjectionCalculator.cpp +++ b/src/mapping/PathProjectionCalculator.cpp @@ -36,66 +36,115 @@ void PathProjectionCalculator::registerKeywords(Keywords& keys) { } PathProjectionCalculator::PathProjectionCalculator( Action* act ): - mypath_obj(NULL) -{ + mypath_obj(NULL) { ActionWithArguments* aarg=dynamic_cast( act ); if( aarg ) { mypath_obj = aarg->getPntrToArgument(0); // Check that we have only one argument as input - if( aarg->getNumberOfArguments()!=1 ) act->error("should only have one argument to this function"); + if( aarg->getNumberOfArguments()!=1 ) { + act->error("should only have one argument to this function"); + } } // Ensure that values are stored in base calculation and that PLUMED doesn't try to calculate this in the stream - if( mypath_obj ) mypath_obj->buildDataStore(); + if( mypath_obj ) { + mypath_obj->buildDataStore(); + } // Check that the input is a matrix - if( mypath_obj ) if( mypath_obj->getRank()!=2 ) act->error("the input to this action should be a matrix"); + if( mypath_obj ) + if( mypath_obj->getRank()!=2 ) { + act->error("the input to this action should be a matrix"); + } // Get the labels for the reference points - std::vector reference_data; act->parseVector("REFERENCE", reference_data); + std::vector reference_data; + act->parseVector("REFERENCE", reference_data); std::vector allrmsd = act->plumed.getActionSet().select(); ActionWithArguments::interpretArgumentList( reference_data, act->plumed.getActionSet(), act, refargs ); for(unsigned i=0; igetPntrToAction(); for(unsigned j=0; jcheckForDependency(thisact) ) { rmsd_objects.push_back( allrmsd[j] ); break; } + if( allrmsd[j]->checkForDependency(thisact) ) { + rmsd_objects.push_back( allrmsd[j] ); + break; + } + } + if( !refargs[i]->isConstant() ) { + act->error("input" + refargs[i]->getName() + " is not constant"); + } + if( refargs[i]->getRank()==2 && reference_data.size()!=1 ) { + act->error("should only be one matrix in input to path projection object"); + } + if( refargs[i]->getRank()>0 && refargs[i]->getShape()[0]!=refargs[0]->getShape()[0] ) { + act->error("mismatch in number of reference frames in input to reference_data"); } - if( !refargs[i]->isConstant() ) act->error("input" + refargs[i]->getName() + " is not constant"); - if( refargs[i]->getRank()==2 && reference_data.size()!=1 ) act->error("should only be one matrix in input to path projection object"); - if( refargs[i]->getRank()>0 && refargs[i]->getShape()[0]!=refargs[0]->getShape()[0] ) act->error("mismatch in number of reference frames in input to reference_data"); } // Create a plumed main object to compute distances between reference configurations int s=sizeof(double); metric.cmd("setRealPrecision",&s); metric.cmd("setMDEngine","plumed"); - int nat=0; metric.cmd("setNatoms",&nat); metric.cmd("setNoVirial"); - unsigned nargs=refargs.size(); if( refargs[0]->getRank()==2 ) nargs = refargs[0]->getShape()[1]; - std::string str_nargs; Tools::convert( nargs, str_nargs ); std::string period_str=" PERIODIC=NO"; - if( mypath_obj && mypath_obj->isPeriodic() ) { std::string min, max; mypath_obj->getDomain( min, max ); period_str=" PERIODIC=" + min + "," + max; } + int nat=0; + metric.cmd("setNatoms",&nat); + metric.cmd("setNoVirial"); + unsigned nargs=refargs.size(); + if( refargs[0]->getRank()==2 ) { + nargs = refargs[0]->getShape()[1]; + } + std::string str_nargs; + Tools::convert( nargs, str_nargs ); + std::string period_str=" PERIODIC=NO"; + if( mypath_obj && mypath_obj->isPeriodic() ) { + std::string min, max; + mypath_obj->getDomain( min, max ); + period_str=" PERIODIC=" + min + "," + max; + } metric.readInputLine("arg1: PUT UNIT=number SHAPE=" + str_nargs + period_str, true); metric.readInputLine("arg2: PUT UNIT=number SHAPE=" + str_nargs + period_str, true); - double tstep=1.0; metric.cmd("setTimestep",&tstep); - std::string inp; act->parse("METRIC",inp); inp += " ARG=arg2,arg1"; const char* cinp=inp.c_str(); + double tstep=1.0; + metric.cmd("setTimestep",&tstep); + std::string inp; + act->parse("METRIC",inp); + inp += " ARG=arg2,arg1"; + const char* cinp=inp.c_str(); std::vector input=Tools::getWords(inp); if( input.size()==1 && !actionRegister().check(input[0]) ) { - metric.cmd("setPlumedDat",cinp); metric.cmd("init"); + metric.cmd("setPlumedDat",cinp); + metric.cmd("init"); } else { - metric.cmd("init"); metric.cmd("readInputLine",cinp); + metric.cmd("init"); + metric.cmd("readInputLine",cinp); } // Now setup stuff to retrieve the final displacement unsigned aind = metric.getActionSet().size()-1; while( true ) { const ActionShortcut* as=dynamic_cast( metric.getActionSet()[aind].get() ); - if( !as ) break ; aind = aind - 1; plumed_assert( aind>=0 ); + if( !as ) { + break ; + } + aind = aind - 1; + plumed_assert( aind>=0 ); } ActionWithValue* fav = dynamic_cast( metric.getActionSet()[aind].get() ); - if( !fav ) act->error("final value should calculate relevant value that you want as reference"); + if( !fav ) { + act->error("final value should calculate relevant value that you want as reference"); + } std::string name = (fav->copyOutput(0))->getName(); if( fav->getNumberOfComponents()>1 ) { - std::string comp; act->parse("METRIC_COMPONENT",comp); name = fav->getLabel() + "." + comp; + std::string comp; + act->parse("METRIC_COMPONENT",comp); + name = fav->getLabel() + "." + comp; } - long rank; metric.cmd("getDataRank " + name, &rank ); - if( rank==0 ) rank=1; - std::vector ishape( rank ); metric.cmd("getDataShape " + name, &ishape[0] ); - unsigned nvals=1; for(unsigned i=0; i ishape( rank ); + metric.cmd("getDataShape " + name, &ishape[0] ); + unsigned nvals=1; + for(unsigned i=0; i valdata1( data.size() ), valdata2( data.size() ); - getReferenceConfiguration( ito, valdata2 ); getReferenceConfiguration( ifrom, valdata1 ); + getReferenceConfiguration( ito, valdata2 ); + getReferenceConfiguration( ifrom, valdata1 ); metric.cmd("setValue arg1", &valdata1[0] ); metric.cmd("setValue arg2", &valdata2[0] ); metric.cmd("calc"); } void PathProjectionCalculator::getDisplaceVector( const unsigned& ifrom, const unsigned& ito, std::vector& displace ) { - if( displace.size()!=data.size() ) displace.resize( data.size() ); - computeVectorBetweenFrames( ifrom, ito ); for(unsigned i=0; i& refpos ) const { - if( refpos.size()!=data.size() ) refpos.resize( data.size() ); + if( refpos.size()!=data.size() ) { + refpos.resize( data.size() ); + } if( refargs[0]->getRank()==2 ) { - for(unsigned i=0; iget( iframe*refpos.size() + i ); + for(unsigned i=0; iget( iframe*refpos.size() + i ); + } } else { - for(unsigned i=0; iget(iframe); + for(unsigned i=0; iget(iframe); + } } } void PathProjectionCalculator::setReferenceConfiguration( const unsigned& iframe, std::vector& refpos ) { plumed_dbg_assert( refpos.size()==data.size() ); if( refargs[0]->getRank()==2 ) { - for(unsigned i=0; iset( iframe*refpos.size() + i, refpos[i] ); + for(unsigned i=0; iset( iframe*refpos.size() + i, refpos[i] ); + } } else { - for(unsigned i=0; iset( iframe, refpos[i] ); + for(unsigned i=0; iset( iframe, refpos[i] ); + } } } void PathProjectionCalculator::updateDepedentRMSDObjects() { - for(unsigned i=0; isetReferenceConfigurations(); + for(unsigned i=0; isetReferenceConfigurations(); + } } } diff --git a/src/mapping/PathReparameterization.cpp b/src/mapping/PathReparameterization.cpp index d4f46f4d91..cde590dbd9 100644 --- a/src/mapping/PathReparameterization.cpp +++ b/src/mapping/PathReparameterization.cpp @@ -73,7 +73,8 @@ class PathReparameterization : public ActionPilot { PLUMED_REGISTER_ACTION(PathReparameterization,"REPARAMETERIZE_PATH") void PathReparameterization::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); + Action::registerKeywords( keys ); + ActionPilot::registerKeywords( keys ); PathProjectionCalculator::registerKeywords(keys); keys.add("compulsory","STRIDE","1","the frequency with which to reparameterize the path"); keys.add("compulsory","FIXED","0","the frames in the path to fix"); @@ -87,40 +88,60 @@ PathReparameterization::PathReparameterization(const ActionOptions&ao): Action(ao), ActionPilot(ao), displace_value(NULL), - path_projector(this) -{ - parse("MAXCYLES",maxcycles); parse("TOL",TOL); + path_projector(this) { + parse("MAXCYLES",maxcycles); + parse("TOL",TOL); log.printf(" running till change is less than %f or until there have been %d optimization cycles \n", TOL, maxcycles); - len.resize( path_projector.getNumberOfFrames() ); sumlen.resize( path_projector.getNumberOfFrames() ); sfrac.resize( path_projector.getNumberOfFrames() ); - std::vector fixed; parseVector("FIXED",fixed); + len.resize( path_projector.getNumberOfFrames() ); + sumlen.resize( path_projector.getNumberOfFrames() ); + sfrac.resize( path_projector.getNumberOfFrames() ); + std::vector fixed; + parseVector("FIXED",fixed); if( fixed.size()==1 ) { - if( fixed[0]!=0 ) error("input to FIXED should be two integers"); - ifix1=0; ifix2=path_projector.getNumberOfFrames()-1; + if( fixed[0]!=0 ) { + error("input to FIXED should be two integers"); + } + ifix1=0; + ifix2=path_projector.getNumberOfFrames()-1; } else if( fixed.size()==2 ) { if( fixed[0]<1 || fixed[1]<1 || fixed[0]>path_projector.getNumberOfFrames() || fixed[1]>path_projector.getNumberOfFrames() ) { error("input to FIXED should be two numbers between 1 and the number of frames"); } - ifix1=fixed[0]-1; ifix2=fixed[1]-1; - } else error("input to FIXED should be two integers"); + ifix1=fixed[0]-1; + ifix2=fixed[1]-1; + } else { + error("input to FIXED should be two integers"); + } log.printf(" fixing frames %d and %d when reparameterizing \n", ifix1, ifix2 ); - std::string dframe; parse("DISPLACE_FRAMES",dframe); + std::string dframe; + parse("DISPLACE_FRAMES",dframe); if( dframe.length()>0 ) { ActionWithValue* av = plumed.getActionSet().selectWithLabel( dframe ); - if( !av ) error("could not find action with label " + dframe + " specified to DISPLACE_FRAMES keyword in input file"); - if( av->getName()!="AVERAGE_PATH_DISPLACEMENT" ) error("displace object is not of correct type"); + if( !av ) { + error("could not find action with label " + dframe + " specified to DISPLACE_FRAMES keyword in input file"); + } + if( av->getName()!="AVERAGE_PATH_DISPLACEMENT" ) { + error("displace object is not of correct type"); + } displace_value = av->copyOutput(0); } } bool PathReparameterization::loopEnd( const int& index, const int& end, const int& inc ) const { - if( inc>0 && indexend ) return false; + if( inc>0 && indexend ) { + return false; + } return true; } double PathReparameterization::computeSpacing( const unsigned& ifrom, const unsigned& ito ) { path_projector.getDisplaceVector( ifrom, ito, data ); - double length=0; for(unsigned i=0; iiend ) { incr=-1; } + int incr=1; + if( istart>iend ) { + incr=-1; + } for(int i=istart+incr; loopEnd(i,iend+incr,incr)==false; i+=incr) { - len[i] = computeSpacing( i-incr, i ); sumlen[i] = sumlen[i-incr] + len[i]; + len[i] = computeSpacing( i-incr, i ); + sumlen[i] = sumlen[i-incr] + len[i]; //printf("FRAME %d TO FRAME %d EQUALS %f : %f \n",i-incr,i,len[i],sumlen[i] ); } } void PathReparameterization::reparameterizePart( const int& istart, const int& iend, const double& target ) { - calcCurrentPathSpacings( istart, iend ); unsigned cfin; + calcCurrentPathSpacings( istart, iend ); + unsigned cfin; // If a target separation is set we fix where we want the nodes - int incr=1; if( istart>iend ) { incr=-1; } + int incr=1; + if( istart>iend ) { + incr=-1; + } if( target>0 ) { if( iend>istart ) { - for(unsigned i=istart; iiend-1; --i) sfrac[i]=target*(istart-i); + for(int i=istart-1; i>iend-1; --i) { + sfrac[i]=target*(istart-i); + } } cfin = iend+incr; } else { cfin = iend; } - double prevsum=0.; Matrix newmatrix( path_projector.getNumberOfFrames(), data.size() ); + double prevsum=0.; + Matrix newmatrix( path_projector.getNumberOfFrames(), data.size() ); for(unsigned iter=0; iter( iend - istart ); - for(unsigned i=istart; i=sfrac[i])) ) { k+=incr; - if( cfin==iend && k>= iend+1 ) plumed_merror("path reparameterization error"); - else if( cfin==(iend+1) && k>=iend ) { k=iend-1; break; } - else if( cfin==(iend-1) && k<=iend ) { k=iend+1; break; } + if( cfin==iend && k>= iend+1 ) { + plumed_merror("path reparameterization error"); + } else if( cfin==(iend+1) && k>=iend ) { + k=iend-1; + break; + } else if( cfin==(iend-1) && k<=iend ) { + k=iend+1; + break; + } } double dr = (sfrac[i]-sumlen[k])/len[k+incr]; // Copy the reference configuration to the row of a matrix path_projector.getReferenceConfiguration( k, data ); - for(unsigned j=0; jget( kstart + j ); + for(unsigned j=0; jget( kstart + j ); + } // And now set the new position of the refernce frame path_projector.setReferenceConfiguration( i, data ); } @@ -219,8 +275,12 @@ void PathReparameterization::update() { double target = sumlen[ifix2] / ( ifix2 - ifix1 ); // And reparameterize the begining and end of the path - if( ifix1>0 ) reparameterizePart( ifix1, 0, target ); - if( ifix2<(path_projector.getNumberOfFrames()-1) ) reparameterizePart( ifix2, path_projector.getNumberOfFrames()-1, target ); + if( ifix1>0 ) { + reparameterizePart( ifix1, 0, target ); + } + if( ifix2<(path_projector.getNumberOfFrames()-1) ) { + reparameterizePart( ifix2, path_projector.getNumberOfFrames()-1, target ); + } // And update any RMSD objects that depend on input values path_projector.updateDepedentRMSDObjects(); } diff --git a/src/mapping/PathTools.cpp b/src/mapping/PathTools.cpp index 9c85b98d2c..a5e07d60ef 100644 --- a/src/mapping/PathTools.cpp +++ b/src/mapping/PathTools.cpp @@ -105,8 +105,7 @@ plumed pathtools --path inpath.pdb --metric EUCLIDEAN --out outpath.pdb --fixed //+ENDPLUMEDOC class PathTools : - public CLTool -{ + public CLTool { public: static void registerKeywords( Keywords& keys ); explicit PathTools(const CLToolOptions& co ); @@ -136,66 +135,115 @@ void PathTools::registerKeywords( Keywords& keys ) { } PathTools::PathTools(const CLToolOptions& co ): - CLTool(co) -{ + CLTool(co) { inputdata=commandline; } int PathTools::main(FILE* in, FILE*out,Communicator& pc) { // Create a PLUMED object - PlumedMain plmd; int s=sizeof(double); + PlumedMain plmd; + int s=sizeof(double); plmd.cmd("setRealPrecision",&s); plmd.cmd("setMDEngine","pathtools"); // plmd.cmd("setNoVirial"); - double tstep=1.0; plmd.cmd("setTimestep",&tstep); + double tstep=1.0; + plmd.cmd("setTimestep",&tstep); plmd.cmd("init"); - int step=1; plmd.cmd("setStep",&step); - - std::string mtype; parse("--metric",mtype); - std::string ifilename; parse("--path",ifilename); - std::string ofmt; parse("--arg-fmt",ofmt); - std::string ofilename; parse("--out",ofilename); - std::vector argstr; parseVector("--arg",argstr); + int step=1; + plmd.cmd("setStep",&step); + + std::string mtype; + parse("--metric",mtype); + std::string ifilename; + parse("--path",ifilename); + std::string ofmt; + parse("--arg-fmt",ofmt); + std::string ofilename; + parse("--out",ofilename); + std::vector argstr; + parseVector("--arg",argstr); if( ifilename.length()>0 ) { fprintf(out,"Reparameterising path in file named %s so that all frames are equally spaced \n",ifilename.c_str() ); - FILE* fp=fopen(ifilename.c_str(),"r"); PDB mypdb; bool do_read=mypdb.readFromFilepointer(fp,false,0.1); - std::vector alig( mypdb.getOccupancy() ), disp( mypdb.getBeta() ); std::vector indices( mypdb.getAtomNumbers() ); - std::vector residue_indices( indices.size() ); for(unsigned i=0; i alig( mypdb.getOccupancy() ), disp( mypdb.getBeta() ); + std::vector indices( mypdb.getAtomNumbers() ); + std::vector residue_indices( indices.size() ); + for(unsigned i=0; i0 ) { for(unsigned i=0; i0 ) { reparam_str += argstr[0]; for(unsigned i=0; i fixed; parseVector("--fixed",fixed); + if( argstr.size()>0 ) { + reparam_str += argstr[0]; + for(unsigned i=0; i fixed; + parseVector("--fixed",fixed); if( fixed.size()==1 ) { - if( fixed[0]!=0 ) error("input to --fixed should be two integers"); - fixed.resize(2); fixed[0]=1; fixed[1]=nfram; + if( fixed[0]!=0 ) { + error("input to --fixed should be two integers"); + } + fixed.resize(2); + fixed[0]=1; + fixed[1]=nfram; } else if( fixed.size()==2 ) { if( fixed[0]<1 || fixed[1]<1 || fixed[0]>nfram || fixed[1]>nfram ) { error("input to --fixed should be two numbers between 0 and the number of frames-1"); } - } else error("input to --fixed should be two integers"); - std::string fix1, fix2; Tools::convert( fixed[0], fix1 ); Tools::convert( fixed[1], fix2 ); + } else { + error("input to --fixed should be two integers"); + } + std::string fix1, fix2; + Tools::convert( fixed[0], fix1 ); + Tools::convert( fixed[1], fix2 ); reparam_str += " FIXED=" + fix1 + "," + fix2; - std::string tol; parse("--tolerance",tol); reparam_str += " TOL=" + tol; + std::string tol; + parse("--tolerance",tol); + reparam_str += " TOL=" + tol; // Now create the metric object reparam_str += " METRIC="; if( mtype=="OPTIMAL-FAST" || mtype=="OPTIMAL" || mtype=="SIMPLE" ) { reparam_str += "{RMSD_VECTOR DISPLACEMENT SQUARED UNORMALIZED TYPE=" + mtype; // Get the align values - std::string anum; Tools::convert( alig[0], anum ); reparam_str += " ALIGN=" + anum; - for(unsigned i=1; iupdate(); // And print the final reference configurations std::string pinput="DUMPPDB STRIDE=1 DESCRIPTION=PATH FILE=" + ofilename + " FMT=" + ofmt; if( argstr.size()>0 ) { - pinput += " ARG=" + argstr[0]; for(unsigned i=1; iupdate(); @@ -230,78 +304,151 @@ int PathTools::main(FILE* in, FILE*out,Communicator& pc) { } for(unsigned i=0; i start_pos( argstr.size() ), end_pos( argstr.size() ); std::vector indices; + std::vector start_pos( argstr.size() ), end_pos( argstr.size() ); + std::vector indices; if( argstr.size()>0 ) { for(unsigned i=0; i sshape( 1 ); plmd.cmd("getDataShape " + argstr[i] + "_start", &sshape[0] ); - if( sshape[0]!=1 ) error("should only be one frame in input pdb"); + const char* inpt = input.c_str(); + plmd.cmd("readInputLine", inpt ); + long srank; + plmd.cmd("getDataRank " + argstr[i] + "_start", &srank ); + if( srank!=1 ) { + error("should only be one frame in input pdb"); + } + std::vector sshape( 1 ); + plmd.cmd("getDataShape " + argstr[i] + "_start", &sshape[0] ); + if( sshape[0]!=1 ) { + error("should only be one frame in input pdb"); + } plmd.cmd("setMemoryForData " + argstr[i] + "_start", &start_pos[i] ); std::string input2 = argstr[i] + "_end: PDB2CONSTANT REFERENCE=" + iend + " ARG=" + argstr[i]; - const char* inpt2 = input2.c_str(); plmd.cmd("readInputLine", inpt2 ); - long erank; plmd.cmd("getDataRank " + argstr[i] + "_end", &erank ); - if( erank!=1 ) error("should only be one frame in input pdb"); - std::vector eshape( 1 ); plmd.cmd("getDataShape " + argstr[i] + "_end", &eshape[0] ); - if( eshape[0]!=1 ) error("should only be one frame in input pdb"); + const char* inpt2 = input2.c_str(); + plmd.cmd("readInputLine", inpt2 ); + long erank; + plmd.cmd("getDataRank " + argstr[i] + "_end", &erank ); + if( erank!=1 ) { + error("should only be one frame in input pdb"); + } + std::vector eshape( 1 ); + plmd.cmd("getDataShape " + argstr[i] + "_end", &eshape[0] ); + if( eshape[0]!=1 ) { + error("should only be one frame in input pdb"); + } plmd.cmd("setMemoryForData " + argstr[i] + "_end", &end_pos[i] ); } } else { std::string input = "start: PDB2CONSTANT REFERENCE=" + istart; - const char* inpt = input.c_str(); plmd.cmd("readInputLine", inpt ); - FILE* fp=fopen(istart.c_str(),"r"); PDB mypdb; bool do_read=mypdb.readFromFilepointer(fp,false,0.1); - indices.resize( mypdb.getAtomNumbers().size() ); for(unsigned i=0; i sshape( srank ); plmd.cmd("getDataShape start", &sshape[0] ); start_pos.resize( sshape[0]*sshape[1] ); - if( sshape[0]!=1 ) error("should only be one frame in input pdb: " + istart); + const char* inpt = input.c_str(); + plmd.cmd("readInputLine", inpt ); + FILE* fp=fopen(istart.c_str(),"r"); + PDB mypdb; + bool do_read=mypdb.readFromFilepointer(fp,false,0.1); + indices.resize( mypdb.getAtomNumbers().size() ); + for(unsigned i=0; i sshape( srank ); + plmd.cmd("getDataShape start", &sshape[0] ); + start_pos.resize( sshape[0]*sshape[1] ); + if( sshape[0]!=1 ) { + error("should only be one frame in input pdb: " + istart); + } plmd.cmd("setMemoryForData start", &start_pos[0] ); std::string input2 = "end: PDB2CONSTANT REFERENCE=" + iend; - const char* inpt2 = input2.c_str(); plmd.cmd("readInputLine", inpt2 ); - long erank; plmd.cmd("getDataRank end", &erank ); if( erank!=2 ) error("should only be one frame in input pdb: " + iend); - std::vector eshape( erank ); plmd.cmd("getDataShape end", &eshape[0] ); end_pos.resize( eshape[0]*eshape[1] ); - if( eshape[0]!=1 ) error("should only be one frame in input pdb: " + iend ); + const char* inpt2 = input2.c_str(); + plmd.cmd("readInputLine", inpt2 ); + long erank; + plmd.cmd("getDataRank end", &erank ); + if( erank!=2 ) { + error("should only be one frame in input pdb: " + iend); + } + std::vector eshape( erank ); + plmd.cmd("getDataShape end", &eshape[0] ); + end_pos.resize( eshape[0]*eshape[1] ); + if( eshape[0]!=1 ) { + error("should only be one frame in input pdb: " + iend ); + } plmd.cmd("setMemoryForData end", &end_pos[0] ); } // Now create the metric object - std::vector alig, disp; std::vector residue_indices; + std::vector alig, disp; + std::vector residue_indices; if( mtype=="OPTIMAL-FAST" || mtype=="OPTIMAL" || mtype=="SIMPLE" ) { std::string trinput = "endT: TRANSPOSE ARG=end"; - const char* tinp=trinput.c_str(); plmd.cmd("readInputLine",tinp); - PDB pdb; pdb.read(istart,false,0.1); - alig.resize( pdb.getOccupancy().size() ); disp.resize( pdb.getBeta().size() ); - for(unsigned i=0; i( plmd.getActionSet()[aind].get() ); - if( !as ) break ; aind = aind - 1; plumed_assert( aind>=0 ); + if( !as ) { + break ; + } + aind = aind - 1; + plumed_assert( aind>=0 ); } ActionWithValue* av = dynamic_cast( plmd.getActionSet()[aind].get() ); - if( !av ) error("invalid input for metric" ); - if( av->getNumberOfComponents()!=1 && av->getName()!="RMSD_VECTOR" ) error("cannot use multi component actions as metric"); + if( !av ) { + error("invalid input for metric" ); + } + if( av->getNumberOfComponents()!=1 && av->getName()!="RMSD_VECTOR" ) { + error("cannot use multi component actions as metric"); + } std::string mydisp = av->copyOutput(0)->getName(); // Now add calls so we can grab the data from plumed - long rank; plmd.cmd("getDataRank " + mydisp, &rank ); - if( rank!=1 ) error("displacement must be a vector quantity"); - std::vector ishape( rank ); plmd.cmd("getDataShape " + mydisp, &ishape[0] ); - std::vector displacement( ishape[0] ); plmd.cmd("setMemoryForData " + mydisp, &displacement[0] ); + long rank; + plmd.cmd("getDataRank " + mydisp, &rank ); + if( rank!=1 ) { + error("displacement must be a vector quantity"); + } + std::vector ishape( rank ); + plmd.cmd("getDataShape " + mydisp, &ishape[0] ); + std::vector displacement( ishape[0] ); + plmd.cmd("setMemoryForData " + mydisp, &displacement[0] ); // And calculate the displacement plmd.cmd("calc"); // Now read in the initial frame // Now create frames - double delr = 1.0 / static_cast( nbetween ); std::vector > allframes; std::vector frame( displacement.size() ); + double delr = 1.0 / static_cast( nbetween ); + std::vector > allframes; + std::vector frame( displacement.size() ); for(int i=0; i("timestep"); ts->setValuePointer("timestep", &tstep ); std::string pinput="DUMPPDB STRIDE=1 DESCRIPTION=PATH FILE=" + ofilename + " FMT=" + ofmt; if( argstr.size()>0 ) { for(unsigned i=0; iupdate(); // And output suggestions on the value of Lambda @@ -381,77 +589,120 @@ int PathTools::main(FILE* in, FILE*out,Communicator& pc) { void PathTools::printLambda( const std::string& mtype, const std::vector& argstr, const std::string& ofile ) { // Create a PLUMED object - PlumedMain plmd; int s=sizeof(double); + PlumedMain plmd; + int s=sizeof(double); plmd.cmd("setRealPrecision",&s); plmd.cmd("setMDEngine","pathtools"); - double tstep=1.0; plmd.cmd("setTimestep",&tstep); + double tstep=1.0; + plmd.cmd("setTimestep",&tstep); plmd.cmd("init"); - int step=1; plmd.cmd("setStep",&step); + int step=1; + plmd.cmd("setStep",&step); FILE* fp=fopen(ofile.c_str(),"r"); - bool do_read=true; unsigned nfram=0; + bool do_read=true; + unsigned nfram=0; std::vector alig, disp; // Read in the argument names for(unsigned i=0; i0 ) { for(unsigned i=0; i data( nfram ); for(unsigned j=1; j ishape(1); plmd.cmd("getDataShape d" + istr, &ishape[0] ); - if( ishape[0]!=1 ) error("distance should be of rank 1"); + long rank; + plmd.cmd("getDataRank d" + istr, &rank ); + if( rank!=1 ) { + error("distance should be of rank 1"); + } + std::vector ishape(1); + plmd.cmd("getDataShape d" + istr, &ishape[0] ); + if( ishape[0]!=1 ) { + error("distance should be of rank 1"); + } plmd.cmd("setMemoryForData d" + istr, &data[j-1] ); } - plmd.cmd("calc"); double mean=0; + plmd.cmd("calc"); + double mean=0; printf("N.B. THIS CODE ALWAYS AIMS TO CREATE EQUALLY SPACED FRAMES \n"); printf("THERE MAY BE SMALL DESCREPENCIES IN THE NUMBERS BELOW, HOWEVER, BECAUSE OF ROUNDING ERRORS \n"); for(unsigned i=1; i( nfram-1 ) ); } diff --git a/src/matrixtools/CovarianceMatrix.cpp b/src/matrixtools/CovarianceMatrix.cpp index 77bfc24a0a..2ba5482d19 100644 --- a/src/matrixtools/CovarianceMatrix.cpp +++ b/src/matrixtools/CovarianceMatrix.cpp @@ -49,19 +49,30 @@ void CovarianceMatrix::registerKeywords(Keywords& keys ) { "are used as weights for the input data points."); keys.addFlag("UNORMALIZED",false,"do not divide by the sum of the weights"); keys.setValueDescription("the covariance matrix"); - keys.needsAction("SUM"); keys.needsAction("CUSTOM"); keys.needsAction("VSTACK"); keys.needsAction("TRANSPOSE"); - keys.needsAction("ONES"); keys.needsAction("OUTER_PRODUCT"); keys.needsAction("MATRIX_PRODUCT"); + keys.needsAction("SUM"); + keys.needsAction("CUSTOM"); + keys.needsAction("VSTACK"); + keys.needsAction("TRANSPOSE"); + keys.needsAction("ONES"); + keys.needsAction("OUTER_PRODUCT"); + keys.needsAction("MATRIX_PRODUCT"); } CovarianceMatrix::CovarianceMatrix(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - std::vector args; parseVector("ARG",args); - unsigned nargs=args.size(); std::string argstr="ARG=" + args[0]; - for(unsigned i=1; i args; + parseVector("ARG",args); + unsigned nargs=args.size(); + std::string argstr="ARG=" + args[0]; + for(unsigned i=1; igetNumberOfValues(); } + unsigned getNumberOfDerivatives() override { + return getPntrToArgument(0)->getNumberOfValues(); + } /// void prepare() override ; /// @@ -65,53 +67,79 @@ void DiagonalizeMatrix::registerKeywords( Keywords& keys ) { DiagonalizeMatrix::DiagonalizeMatrix(const ActionOptions& ao): Action(ao), - MatrixOperationBase(ao) -{ - if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(0)->getShape()[1] ) error("input matrix should be square"); + MatrixOperationBase(ao) { + if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(0)->getShape()[1] ) { + error("input matrix should be square"); + } - std::vector eigv; parseVector("VECTORS",eigv); + std::vector eigv; + parseVector("VECTORS",eigv); if( eigv.size()>1 ) { - Tools::interpretRanges(eigv); desired_vectors.resize( eigv.size() ); - for(unsigned i=0; igetShape()[0] ); - for(unsigned i=0; i eval_shape(0); - std::vector evec_shape(1); evec_shape[0] = getPntrToArgument(0)->getShape()[0]; + std::string num; + std::vector eval_shape(0); + std::vector evec_shape(1); + evec_shape[0] = getPntrToArgument(0)->getShape()[0]; for(unsigned i=0; ibuildDataStore(); } - std::vector eigvecs_shape(2); eigvecs_shape[0]=eigvecs_shape[1]=getPntrToArgument(0)->getShape()[0]; - mymatrix.resize( eigvecs_shape[0], eigvecs_shape[1] ); eigvals.resize( eigvecs_shape[0] ); eigvecs.resize( eigvecs_shape[0], eigvecs_shape[1] ); + std::vector eigvecs_shape(2); + eigvecs_shape[0]=eigvecs_shape[1]=getPntrToArgument(0)->getShape()[0]; + mymatrix.resize( eigvecs_shape[0], eigvecs_shape[1] ); + eigvals.resize( eigvecs_shape[0] ); + eigvecs.resize( eigvecs_shape[0], eigvecs_shape[1] ); } void DiagonalizeMatrix::prepare() { - std::vector shape(1); shape[0]=getPntrToArgument(0)->getShape()[0]; + std::vector shape(1); + shape[0]=getPntrToArgument(0)->getShape()[0]; for(unsigned i=0; igetShape()[0]!=shape[0] ) getPntrToComponent( 2*i+1 )->setShape( shape ); + if( getPntrToComponent( 2*i+1 )->getShape()[0]!=shape[0] ) { + getPntrToComponent( 2*i+1 )->setShape( shape ); + } } } void DiagonalizeMatrix::calculate() { - if( getPntrToArgument(0)->getShape()[0]==0 ) return ; + if( getPntrToArgument(0)->getShape()[0]==0 ) { + return ; + } // Resize stuff that might need resizing unsigned nvals=getPntrToArgument(0)->getShape()[0]; - if( eigvals.size()!=nvals ) { mymatrix.resize( nvals, nvals ); eigvals.resize( nvals ); eigvecs.resize( nvals, nvals ); } + if( eigvals.size()!=nvals ) { + mymatrix.resize( nvals, nvals ); + eigvals.resize( nvals ); + eigvecs.resize( nvals, nvals ); + } // Retrieve the matrix from input retrieveFullMatrix( mymatrix ); @@ -120,8 +148,11 @@ void DiagonalizeMatrix::calculate() { // And set the eigenvalues and eigenvectors for(unsigned i=0; iset( eigvals[ mymatrix.ncols()-desired_vectors[i]] ); - Value* evec_out = getPntrToComponent(2*i+1); unsigned vreq = mymatrix.ncols()-desired_vectors[i]; - for(unsigned j=0; jset( j, eigvecs( vreq, j ) ); + Value* evec_out = getPntrToComponent(2*i+1); + unsigned vreq = mymatrix.ncols()-desired_vectors[i]; + for(unsigned j=0; jset( j, eigvecs( vreq, j ) ); + } } } @@ -134,13 +165,17 @@ double DiagonalizeMatrix::getForceOnMatrixElement( const unsigned& jrow, const u ff += getConstPntrToComponent(2*i)->getForce(0)*eigvecs(ncol,jrow)*eigvecs(ncol,kcol); } // And forces on eigenvectors - if( !getConstPntrToComponent(2*i+1)->forcesWereAdded() ) continue; + if( !getConstPntrToComponent(2*i+1)->forcesWereAdded() ) { + continue; + } unsigned ncol = mymatrix.ncols()-desired_vectors[i]; for(unsigned n=0; ngetForce(n) * tmp2; diff --git a/src/matrixtools/InvertMatrix.cpp b/src/matrixtools/InvertMatrix.cpp index 72633d261a..acec86f776 100644 --- a/src/matrixtools/InvertMatrix.cpp +++ b/src/matrixtools/InvertMatrix.cpp @@ -45,12 +45,16 @@ class InvertMatrix : public MatrixOperationBase { /// Constructor explicit InvertMatrix(const ActionOptions&); /// - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } /// Do the calculation void calculate() override; /// void apply() override; - double getForceOnMatrixElement( const unsigned& jrow, const unsigned& krow ) const override { plumed_error(); } + double getForceOnMatrixElement( const unsigned& jrow, const unsigned& krow ) const override { + plumed_error(); + } }; PLUMED_REGISTER_ACTION(InvertMatrix,"INVERT_MATRIX") @@ -63,16 +67,24 @@ void InvertMatrix::registerKeywords( Keywords& keys ) { InvertMatrix::InvertMatrix(const ActionOptions& ao): Action(ao), MatrixOperationBase(ao), - input_is_constant(false) -{ - if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(0)->getShape()[1] ) error("input matrix should be square"); + input_is_constant(false) { + if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(0)->getShape()[1] ) { + error("input matrix should be square"); + } ActionSetup* as = dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); - if(as) input_is_constant=true; + if(as) { + input_is_constant=true; + } - std::vector shape(2); shape[0]=shape[1]=getPntrToArgument(0)->getShape()[0]; addValue( shape ); - setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); - mymatrix.resize( shape[0], shape[1] ); inverse.resize( shape[0], shape[1] ); + std::vector shape(2); + shape[0]=shape[1]=getPntrToArgument(0)->getShape()[0]; + addValue( shape ); + setNotPeriodic(); + getPntrToComponent(0)->buildDataStore(); + getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + mymatrix.resize( shape[0], shape[1] ); + inverse.resize( shape[0], shape[1] ); } void InvertMatrix::calculate() { @@ -81,18 +93,24 @@ void InvertMatrix::calculate() { // Now invert the matrix Invert( mymatrix, inverse ); // And set the inverse - unsigned k = 0; Value* myval=getPntrToComponent(0); + unsigned k = 0; + Value* myval=getPntrToComponent(0); for(unsigned i=0; iset( k, inverse(i,j) ); k++; + myval->set( k, inverse(i,j) ); + k++; } } - if( !doNotCalculateDerivatives() && !input_is_constant ) error("derivatives of inverse matrix have not been implemented"); + if( !doNotCalculateDerivatives() && !input_is_constant ) { + error("derivatives of inverse matrix have not been implemented"); + } } void InvertMatrix::apply() { - if( doNotCalculateDerivatives() || input_is_constant ) return; + if( doNotCalculateDerivatives() || input_is_constant ) { + return; + } error("derivatives of inverse matrix have not been implemented"); } diff --git a/src/matrixtools/MatrixOperationBase.cpp b/src/matrixtools/MatrixOperationBase.cpp index e2b2a4d7b0..0636d2807a 100644 --- a/src/matrixtools/MatrixOperationBase.cpp +++ b/src/matrixtools/MatrixOperationBase.cpp @@ -25,24 +25,34 @@ namespace PLMD { namespace matrixtools { void MatrixOperationBase::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithArguments::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); - keys.use("ARG"); keys.remove("NUMERICAL_DERIVATIVES"); + Action::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + keys.use("ARG"); + keys.remove("NUMERICAL_DERIVATIVES"); keys.add("optional","MATRIX","the input matrix (can use ARG instead)"); } MatrixOperationBase::MatrixOperationBase(const ActionOptions&ao): Action(ao), ActionWithArguments(ao), - ActionWithValue(ao) -{ + ActionWithValue(ao) { if( getNumberOfArguments()==0 ) { - std::vector args; parseArgumentList("MATRIX",args); requestArguments(args); + std::vector args; + parseArgumentList("MATRIX",args); + requestArguments(args); + } + if( getNumberOfArguments()!=1 ) { + error("should only be one argument to this action"); } - if( getNumberOfArguments()!=1 ) error("should only be one argument to this action"); if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) { if( getName()=="TRANSPOSE" ) { - if (getPntrToArgument(0)->getRank()!=1 || getPntrToArgument(0)->hasDerivatives() ) error("input to this argument should be a matrix or vector"); - } else error("input to this argument should be a matrix"); + if (getPntrToArgument(0)->getRank()!=1 || getPntrToArgument(0)->hasDerivatives() ) { + error("input to this argument should be a matrix or vector"); + } + } else { + error("input to this argument should be a matrix"); + } } getPntrToArgument(0)->buildDataStore(); } @@ -51,29 +61,42 @@ void MatrixOperationBase::retrieveFullMatrix( Matrix& mymatrix ) { if( mymatrix.nrows()!=getPntrToArgument(0)->getShape()[0] || mymatrix.nrows()!=getPntrToArgument(0)->getShape()[1] ) { mymatrix.resize( getPntrToArgument(0)->getShape()[0], getPntrToArgument(0)->getShape()[1] ); } - unsigned nedge; getPntrToArgument(0)->retrieveEdgeList( nedge, pairs, vals ); mymatrix=0; + unsigned nedge; + getPntrToArgument(0)->retrieveEdgeList( nedge, pairs, vals ); + mymatrix=0; bool symmetric = getPntrToArgument(0)->isSymmetric(); for(unsigned i=0; iforcesWereAdded() ) { forces=true; break; } + if( getPntrToComponent(i)->forcesWereAdded() ) { + forces=true; + break; + } + } + if( !forces ) { + return; } - if( !forces ) return; Value* mat = getPntrToArgument(0); unsigned ncols=mat->getNumberOfColumns(); for(unsigned i=0; igetShape()[0]; ++i) { unsigned ncol = mat->getRowLength(i); - for(unsigned j=0; jaddForce( i*ncols+j, getForceOnMatrixElement( i, mat->getRowIndex(i,j) ), false ); + for(unsigned j=0; jaddForce( i*ncols+j, getForceOnMatrixElement( i, mat->getRowIndex(i,j) ), false ); + } } } diff --git a/src/matrixtools/MatrixOperationBase.h b/src/matrixtools/MatrixOperationBase.h index e3d279c0f7..1aa5525308 100644 --- a/src/matrixtools/MatrixOperationBase.h +++ b/src/matrixtools/MatrixOperationBase.h @@ -31,8 +31,7 @@ namespace matrixtools { class MatrixOperationBase : public ActionWithArguments, - public ActionWithValue -{ + public ActionWithValue { private: /// These are used to hold the matrix std::vector vals; diff --git a/src/matrixtools/MatrixTimesMatrix.cpp b/src/matrixtools/MatrixTimesMatrix.cpp index 34dc2f0b5a..498e282cb4 100644 --- a/src/matrixtools/MatrixTimesMatrix.cpp +++ b/src/matrixtools/MatrixTimesMatrix.cpp @@ -53,7 +53,9 @@ class MatrixTimesMatrix : public ActionWithMatrix { explicit MatrixTimesMatrix(const ActionOptions&); void prepare() override ; unsigned getNumberOfDerivatives(); - unsigned getNumberOfColumns() const override { return getConstPntrToComponent(0)->getShape()[1]; } + unsigned getNumberOfColumns() const override { + return getConstPntrToComponent(0)->getShape()[1]; + } void getAdditionalTasksRequired( ActionWithVector* action, std::vector& atasks ) override ; void setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const ; void performTask( const std::string& controller, const unsigned& index1, const unsigned& index2, MultiValue& myvals ) const override; @@ -64,28 +66,44 @@ PLUMED_REGISTER_ACTION(MatrixTimesMatrix,"MATRIX_PRODUCT") PLUMED_REGISTER_ACTION(MatrixTimesMatrix,"DISSIMILARITIES") void MatrixTimesMatrix::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords(keys); keys.use("ARG"); + ActionWithMatrix::registerKeywords(keys); + keys.use("ARG"); keys.addFlag("SQUARED",false,"calculate the squares of the dissimilarities (this option cannot be used with MATRIX_PRODUCT)"); keys.setValueDescription("the product of the two input matrices"); } MatrixTimesMatrix::MatrixTimesMatrix(const ActionOptions&ao): Action(ao), - ActionWithMatrix(ao) -{ - if( getNumberOfArguments()!=2 ) error("should be two arguments to this action, a matrix and a vector"); - if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) error("first argument to this action should be a matrix"); - if( getPntrToArgument(1)->getRank()!=2 || getPntrToArgument(1)->hasDerivatives() ) error("second argument to this action should be a matrix"); - if( getPntrToArgument(0)->getShape()[1]!=getPntrToArgument(1)->getShape()[0] ) error("number of columns in first matrix does not equal number of rows in second matrix"); - std::vector shape(2); shape[0]=getPntrToArgument(0)->getShape()[0]; shape[1]=getPntrToArgument(1)->getShape()[1]; - addValue( shape ); setNotPeriodic(); nderivatives = buildArgumentStore(0); + ActionWithMatrix(ao) { + if( getNumberOfArguments()!=2 ) { + error("should be two arguments to this action, a matrix and a vector"); + } + if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) { + error("first argument to this action should be a matrix"); + } + if( getPntrToArgument(1)->getRank()!=2 || getPntrToArgument(1)->hasDerivatives() ) { + error("second argument to this action should be a matrix"); + } + if( getPntrToArgument(0)->getShape()[1]!=getPntrToArgument(1)->getShape()[0] ) { + error("number of columns in first matrix does not equal number of rows in second matrix"); + } + std::vector shape(2); + shape[0]=getPntrToArgument(0)->getShape()[0]; + shape[1]=getPntrToArgument(1)->getShape()[1]; + addValue( shape ); + setNotPeriodic(); + nderivatives = buildArgumentStore(0); std::string headstr=getFirstActionInChain()->getLabel(); stored_matrix1 = getPntrToArgument(0)->ignoreStoredValue( headstr ); stored_matrix2 = getPntrToArgument(1)->ignoreStoredValue( headstr ); if( getName()=="DISSIMILARITIES" ) { parseFlag("SQUARED",squared); - if( squared ) log.printf(" calculating the squares of the dissimilarities \n"); - } else squared=true; + if( squared ) { + log.printf(" calculating the squares of the dissimilarities \n"); + } + } else { + squared=true; + } } unsigned MatrixTimesMatrix::getNumberOfDerivatives() { @@ -94,52 +112,83 @@ unsigned MatrixTimesMatrix::getNumberOfDerivatives() { void MatrixTimesMatrix::prepare() { Value* myval = getPntrToComponent(0); - if( myval->getShape()[0]==getPntrToArgument(0)->getShape()[0] && myval->getShape()[1]==getPntrToArgument(1)->getShape()[1] ) return; - std::vector shape(2); shape[0]=getPntrToArgument(0)->getShape()[0]; shape[1]=getPntrToArgument(1)->getShape()[1]; - myval->setShape(shape); if( myval->valueIsStored() ) myval->reshapeMatrixStore( shape[1] ); + if( myval->getShape()[0]==getPntrToArgument(0)->getShape()[0] && myval->getShape()[1]==getPntrToArgument(1)->getShape()[1] ) { + return; + } + std::vector shape(2); + shape[0]=getPntrToArgument(0)->getShape()[0]; + shape[1]=getPntrToArgument(1)->getShape()[1]; + myval->setShape(shape); + if( myval->valueIsStored() ) { + myval->reshapeMatrixStore( shape[1] ); + } } void MatrixTimesMatrix::getAdditionalTasksRequired( ActionWithVector* action, std::vector& atasks ) { ActionWithMatrix* adj=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); - if( !adj->isAdjacencyMatrix() ) return; - adj->retrieveAtoms(); adj->getAdditionalTasksRequired( action, atasks ); + if( !adj->isAdjacencyMatrix() ) { + return; + } + adj->retrieveAtoms(); + adj->getAdditionalTasksRequired( action, atasks ); } void MatrixTimesMatrix::setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const { unsigned start_n = getPntrToArgument(0)->getShape()[0], size_v = getPntrToArgument(1)->getShape()[1]; - if( indices.size()!=size_v+1 ) indices.resize( size_v+1 ); - for(unsigned i=0; igetPositionInStream(), ind2=index2; - if( index2>=getPntrToArgument(0)->getShape()[0] ) ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + if( index2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + } Value* myarg = getPntrToArgument(0); - unsigned nmult=myarg->getRowLength(index1); double matval=0; + unsigned nmult=myarg->getRowLength(index1); + double matval=0; std::vector dvec1(nmult), dvec2(nmult); for(unsigned i=0; igetRowIndex( index1, i ); double val1 = getElementOfMatrixArgument( 0, index1, kind, myvals ); double val2 = getElementOfMatrixArgument( 1, kind, ind2, myvals ); if( getName()=="DISSIMILARITIES" ) { - double tmp = getPntrToArgument(0)->difference(val2, val1); matval += tmp*tmp; + double tmp = getPntrToArgument(0)->difference(val2, val1); + matval += tmp*tmp; if( !squared ) { - dvec1[i] = 2*tmp; dvec2[i] = -2*tmp; continue; - } else { val2 = -2*tmp; val1 = 2*tmp; } - } else matval+= val1*val2; + dvec1[i] = 2*tmp; + dvec2[i] = -2*tmp; + continue; + } else { + val2 = -2*tmp; + val1 = 2*tmp; + } + } else { + matval+= val1*val2; + } - if( doNotCalculateDerivatives() ) continue; + if( doNotCalculateDerivatives() ) { + continue; + } addDerivativeOnMatrixArgument( stored_matrix1, 0, 0, index1, kind, val2, myvals ); addDerivativeOnMatrixArgument( stored_matrix2, 0, 1, kind, ind2, val1, myvals ); } // And add this part of the product - if( !squared ) matval = sqrt(matval); + if( !squared ) { + matval = sqrt(matval); + } myvals.addValue( ostrn, matval ); - if( squared || doNotCalculateDerivatives() ) return; + if( squared || doNotCalculateDerivatives() ) { + return; + } for(unsigned i=0; igetRowIndex( index1, i ); @@ -149,17 +198,25 @@ void MatrixTimesMatrix::performTask( const std::string& controller, const unsign } void MatrixTimesMatrix::runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() || !matrixChainContinues() ) return ; + if( doNotCalculateDerivatives() || !matrixChainContinues() ) { + return ; + } unsigned mat1s = ival*getPntrToArgument(0)->getShape()[1]; unsigned nmult = getPntrToArgument(0)->getShape()[1], ss = getPntrToArgument(1)->getShape()[1]; unsigned nmat = getConstPntrToComponent(0)->getPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); - std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); unsigned ntwo_atoms = myvals.getSplitIndex(); + std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); + unsigned ntwo_atoms = myvals.getSplitIndex(); for(unsigned j=0; j=getPntrToArgument(0)->getShape()[0] ) ind2 = indices[i] - getPntrToArgument(0)->getShape()[0]; - matrix_indices[nmat_ind] = arg_deriv_starts[1] + j*ss + ind2; nmat_ind++; + unsigned ind2 = indices[i]; + if( ind2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = indices[i] - getPntrToArgument(0)->getShape()[0]; + } + matrix_indices[nmat_ind] = arg_deriv_starts[1] + j*ss + ind2; + nmat_ind++; } } myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind ); diff --git a/src/matrixtools/MatrixTimesVector.cpp b/src/matrixtools/MatrixTimesVector.cpp index 4725b5131c..fad3f53838 100644 --- a/src/matrixtools/MatrixTimesVector.cpp +++ b/src/matrixtools/MatrixTimesVector.cpp @@ -43,10 +43,15 @@ class MatrixTimesVector : public ActionWithMatrix { static void registerKeywords( Keywords& keys ); explicit MatrixTimesVector(const ActionOptions&); std::string getOutputComponentDescription( const std::string& cname, const Keywords& keys ) const override ; - unsigned getNumberOfColumns() const override { plumed_error(); } + unsigned getNumberOfColumns() const override { + plumed_error(); + } unsigned getNumberOfDerivatives(); void prepare() override ; - bool isInSubChain( unsigned& nder ) override { nder = arg_deriv_starts[0]; return true; } + bool isInSubChain( unsigned& nder ) override { + nder = arg_deriv_starts[0]; + return true; + } void setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const ; void performTask( const std::string& controller, const unsigned& index1, const unsigned& index2, MultiValue& myvals ) const override; void runEndOfRowJobs( const unsigned& ind, const std::vector & indices, MultiValue& myvals ) const override ; @@ -56,7 +61,8 @@ class MatrixTimesVector : public ActionWithMatrix { PLUMED_REGISTER_ACTION(MatrixTimesVector,"MATRIX_VECTOR_PRODUCT") void MatrixTimesVector::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords(keys); keys.use("ARG"); + ActionWithMatrix::registerKeywords(keys); + keys.use("ARG"); keys.setValueDescription("the vector that is obtained by taking the product between the matrix and the vector that were input"); ActionWithValue::useCustomisableComponents(keys); } @@ -74,81 +80,129 @@ std::string MatrixTimesVector::getOutputComponentDescription( const std::string& return "the product of the matrix " + getPntrToArgument(i)->getName() + " and the vector " + getPntrToArgument(getNumberOfArguments()-1)->getName(); } } - plumed_merror( "could not understand request for component " + cname ); return ""; + plumed_merror( "could not understand request for component " + cname ); + return ""; } MatrixTimesVector::MatrixTimesVector(const ActionOptions&ao): Action(ao), ActionWithMatrix(ao), - sumrows(false) -{ - if( getNumberOfArguments()<2 ) error("Not enough arguments specified"); + sumrows(false) { + if( getNumberOfArguments()<2 ) { + error("Not enough arguments specified"); + } unsigned nvectors=0, nmatrices=0; for(unsigned i=0; ihasDerivatives() ) error("arguments should be vectors or matrices"); - if( getPntrToArgument(i)->getRank()<=1 ) nvectors++; - if( getPntrToArgument(i)->getRank()==2 ) nmatrices++; + if( getPntrToArgument(i)->hasDerivatives() ) { + error("arguments should be vectors or matrices"); + } + if( getPntrToArgument(i)->getRank()<=1 ) { + nvectors++; + } + if( getPntrToArgument(i)->getRank()==2 ) { + nmatrices++; + } } - std::vector shape(1); shape[0]=getPntrToArgument(0)->getShape()[0]; + std::vector shape(1); + shape[0]=getPntrToArgument(0)->getShape()[0]; if( nvectors==1 ) { unsigned n = getNumberOfArguments()-1; for(unsigned i=0; igetRank()!=2 || getPntrToArgument(i)->hasDerivatives() ) error("all arguments other than last argument should be matrices"); + if( getPntrToArgument(i)->getRank()!=2 || getPntrToArgument(i)->hasDerivatives() ) { + error("all arguments other than last argument should be matrices"); + } if( getPntrToArgument(n)->getRank()==0 ) { - if( getPntrToArgument(i)->getShape()[1]!=1 ) error("number of columns in input matrix does not equal number of elements in vector"); - } else if( getPntrToArgument(i)->getShape()[1]!=getPntrToArgument(n)->getShape()[0] ) error("number of columns in input matrix does not equal number of elements in vector"); + if( getPntrToArgument(i)->getShape()[1]!=1 ) { + error("number of columns in input matrix does not equal number of elements in vector"); + } + } else if( getPntrToArgument(i)->getShape()[1]!=getPntrToArgument(n)->getShape()[0] ) { + error("number of columns in input matrix does not equal number of elements in vector"); + } } if( getPntrToArgument(n)->getRank()>0 ) { - if( getPntrToArgument(n)->getRank()!=1 || getPntrToArgument(n)->hasDerivatives() ) error("last argument to this action should be a vector"); + if( getPntrToArgument(n)->getRank()!=1 || getPntrToArgument(n)->hasDerivatives() ) { + error("last argument to this action should be a vector"); + } } getPntrToArgument(n)->buildDataStore(); ActionWithVector* av=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); - if( av ) done_in_chain=canBeAfterInChain( av ); + if( av ) { + done_in_chain=canBeAfterInChain( av ); + } if( getNumberOfArguments()==2 ) { - addValue( shape ); setNotPeriodic(); + addValue( shape ); + setNotPeriodic(); } else { for(unsigned i=0; igetName(); - if( name.find_first_of(".")!=std::string::npos ) { std::size_t dot=name.find_first_of("."); name = name.substr(dot+1); } - addComponent( name, shape ); componentIsNotPeriodic( name ); + if( name.find_first_of(".")!=std::string::npos ) { + std::size_t dot=name.find_first_of("."); + name = name.substr(dot+1); + } + addComponent( name, shape ); + componentIsNotPeriodic( name ); } } if( (getPntrToArgument(n)->getPntrToAction())->getName()=="CONSTANT" ) { sumrows=true; if( getPntrToArgument(n)->getRank()==0 ) { - if( fabs( getPntrToArgument(n)->get() - 1.0 )>epsilon ) sumrows = false; + if( fabs( getPntrToArgument(n)->get() - 1.0 )>epsilon ) { + sumrows = false; + } } else { for(unsigned i=0; igetShape()[0]; ++i) { - if( fabs( getPntrToArgument(n)->get(i) - 1.0 )>epsilon ) { sumrows=false; break; } + if( fabs( getPntrToArgument(n)->get(i) - 1.0 )>epsilon ) { + sumrows=false; + break; + } } } } } else if( nmatrices==1 ) { - if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) error("first argument to this action should be a matrix"); + if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) { + error("first argument to this action should be a matrix"); + } for(unsigned i=1; igetRank()>1 || getPntrToArgument(i)->hasDerivatives() ) error("all arguments other than first argument should be vectors"); + if( getPntrToArgument(i)->getRank()>1 || getPntrToArgument(i)->hasDerivatives() ) { + error("all arguments other than first argument should be vectors"); + } if( getPntrToArgument(i)->getRank()==0 ) { - if( getPntrToArgument(0)->getShape()[1]!=1 ) error("number of columns in input matrix does not equal number of elements in vector"); - } else if( getPntrToArgument(0)->getShape()[1]!=getPntrToArgument(i)->getShape()[0] ) error("number of columns in input matrix does not equal number of elements in vector"); + if( getPntrToArgument(0)->getShape()[1]!=1 ) { + error("number of columns in input matrix does not equal number of elements in vector"); + } + } else if( getPntrToArgument(0)->getShape()[1]!=getPntrToArgument(i)->getShape()[0] ) { + error("number of columns in input matrix does not equal number of elements in vector"); + } getPntrToArgument(i)->buildDataStore(); } ActionWithVector* av=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); - if( av ) done_in_chain=canBeAfterInChain( av ); + if( av ) { + done_in_chain=canBeAfterInChain( av ); + } for(unsigned i=1; igetName(); - if( name.find_first_of(".")!=std::string::npos ) { std::size_t dot=name.find_first_of("."); name = name.substr(dot+1); } - addComponent( name, shape ); componentIsNotPeriodic( name ); + if( name.find_first_of(".")!=std::string::npos ) { + std::size_t dot=name.find_first_of("."); + name = name.substr(dot+1); + } + addComponent( name, shape ); + componentIsNotPeriodic( name ); } - } else error("You should either have one vector or one matrix in input"); + } else { + error("You should either have one vector or one matrix in input"); + } nderivatives = buildArgumentStore(0); - std::string headstr=getFirstActionInChain()->getLabel(); stored_arg.resize( getNumberOfArguments() ); - for(unsigned i=0; iignoreStoredValue( headstr ); + std::string headstr=getFirstActionInChain()->getLabel(); + stored_arg.resize( getNumberOfArguments() ); + for(unsigned i=0; iignoreStoredValue( headstr ); + } } unsigned MatrixTimesVector::getNumberOfDerivatives() { @@ -156,35 +210,56 @@ unsigned MatrixTimesVector::getNumberOfDerivatives() { } void MatrixTimesVector::prepare() { - ActionWithVector::prepare(); Value* myval = getPntrToComponent(0); - if( myval->getShape()[0]==getPntrToArgument(0)->getShape()[0] ) return; - std::vector shape(1); shape[0] = getPntrToArgument(0)->getShape()[0]; myval->setShape(shape); + ActionWithVector::prepare(); + Value* myval = getPntrToComponent(0); + if( myval->getShape()[0]==getPntrToArgument(0)->getShape()[0] ) { + return; + } + std::vector shape(1); + shape[0] = getPntrToArgument(0)->getShape()[0]; + myval->setShape(shape); } void MatrixTimesVector::setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const { unsigned start_n = getPntrToArgument(0)->getShape()[0], size_v = getPntrToArgument(0)->getRowLength(task_index); - if( indices.size()!=size_v+1 ) indices.resize( size_v + 1 ); - for(unsigned i=0; i=getPntrToArgument(0)->getShape()[0] ) ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + unsigned ind2 = index2; + if( index2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + } if( sumrows ) { - unsigned n=getNumberOfArguments()-1; double matval = 0; + unsigned n=getNumberOfArguments()-1; + double matval = 0; for(unsigned i=0; igetPositionInStream(); Value* myarg = getPntrToArgument(i); - if( !myarg->valueHasBeenSet() ) myvals.addValue( ostrn, myvals.get( myarg->getPositionInStream() ) ); - else myvals.addValue( ostrn, myarg->get( index1*myarg->getNumberOfColumns() + ind2, false ) ); + if( !myarg->valueHasBeenSet() ) { + myvals.addValue( ostrn, myvals.get( myarg->getPositionInStream() ) ); + } else { + myvals.addValue( ostrn, myarg->get( index1*myarg->getNumberOfColumns() + ind2, false ) ); + } // Now lets work out the derivatives - if( doNotCalculateDerivatives() ) continue; + if( doNotCalculateDerivatives() ) { + continue; + } addDerivativeOnMatrixArgument( stored_arg[i], i, i, index1, ind2, 1.0, myvals ); } } else if( getPntrToArgument(1)->getRank()==1 ) { - double matval = 0; Value* myarg = getPntrToArgument(0); unsigned vcol = ind2; - if( !myarg->valueHasBeenSet() ) matval = myvals.get( myarg->getPositionInStream() ); - else { + double matval = 0; + Value* myarg = getPntrToArgument(0); + unsigned vcol = ind2; + if( !myarg->valueHasBeenSet() ) { + matval = myvals.get( myarg->getPositionInStream() ); + } else { matval = myarg->get( index1*myarg->getNumberOfColumns() + ind2, false ); vcol = getPntrToArgument(0)->getRowIndex( index1, ind2 ); } @@ -194,16 +269,22 @@ void MatrixTimesVector::performTask( const std::string& controller, const unsign // And add this part of the product myvals.addValue( ostrn, matval*vecval ); // Now lets work out the derivatives - if( doNotCalculateDerivatives() ) continue; - addDerivativeOnMatrixArgument( stored_arg[0], i, 0, index1, ind2, vecval, myvals ); addDerivativeOnVectorArgument( stored_arg[i+1], i, i+1, vcol, matval, myvals ); + if( doNotCalculateDerivatives() ) { + continue; + } + addDerivativeOnMatrixArgument( stored_arg[0], i, 0, index1, ind2, vecval, myvals ); + addDerivativeOnVectorArgument( stored_arg[i+1], i, i+1, vcol, matval, myvals ); } } else { - unsigned n=getNumberOfArguments()-1; double matval = 0; unsigned vcol = ind2; + unsigned n=getNumberOfArguments()-1; + double matval = 0; + unsigned vcol = ind2; for(unsigned i=0; igetPositionInStream(); Value* myarg = getPntrToArgument(i); - if( !myarg->valueHasBeenSet() ) matval = myvals.get( myarg->getPositionInStream() ); - else { + if( !myarg->valueHasBeenSet() ) { + matval = myvals.get( myarg->getPositionInStream() ); + } else { matval = myarg->get( index1*myarg->getNumberOfColumns() + ind2, false ); vcol = getPntrToArgument(i)->getRowIndex( index1, ind2 ); } @@ -211,36 +292,50 @@ void MatrixTimesVector::performTask( const std::string& controller, const unsign // And add this part of the product myvals.addValue( ostrn, matval*vecval ); // Now lets work out the derivatives - if( doNotCalculateDerivatives() ) continue; - addDerivativeOnMatrixArgument( stored_arg[i], i, i, index1, ind2, vecval, myvals ); addDerivativeOnVectorArgument( stored_arg[n], i, n, vcol, matval, myvals ); + if( doNotCalculateDerivatives() ) { + continue; + } + addDerivativeOnMatrixArgument( stored_arg[i], i, i, index1, ind2, vecval, myvals ); + addDerivativeOnVectorArgument( stored_arg[n], i, n, vcol, matval, myvals ); } } } void MatrixTimesVector::runEndOfRowJobs( const unsigned& ind, const std::vector & indices, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() || !actionInChain() ) return ; + if( doNotCalculateDerivatives() || !actionInChain() ) { + return ; + } if( getPntrToArgument(1)->getRank()==1 ) { unsigned istrn = getPntrToArgument(0)->getPositionInMatrixStash(); std::vector& mat_indices( myvals.getMatrixRowDerivativeIndices( istrn ) ); for(unsigned j=0; jgetPositionInStream(); - for(unsigned i=0; igetPositionInMatrixStash(); unsigned ostrn = getConstPntrToComponent(j)->getPositionInStream(); std::vector& mat_indices( myvals.getMatrixRowDerivativeIndices( istrn ) ); - for(unsigned i=0; igetRank()==1 ) n = 1; + unsigned n = getNumberOfArguments()-1; + if( getPntrToArgument(1)->getRank()==1 ) { + n = 1; + } unsigned nvals = getPntrToArgument(n)->getNumberOfValues(); - for(unsigned i=0; igetShape()[1]; } + unsigned getNumberOfColumns() const override { + return getConstPntrToComponent(0)->getShape()[1]; + } void setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const ; void performTask( const std::string& controller, const unsigned& index1, const unsigned& index2, MultiValue& myvals ) const override; void runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const override ; @@ -55,7 +57,8 @@ class OuterProduct : public ActionWithMatrix { PLUMED_REGISTER_ACTION(OuterProduct,"OUTER_PRODUCT") void OuterProduct::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords(keys); keys.use("ARG"); + ActionWithMatrix::registerKeywords(keys); + keys.use("ARG"); keys.add("compulsory","FUNC","x*y","the function of the input vectors that should be put in the elements of the outer product"); keys.addFlag("ELEMENTS_ON_DIAGONAL_ARE_ZERO",false,"set all diagonal elements to zero"); keys.setValueDescription("a matrix containing the outer product of the two input vectors that was obtained using the function that was input"); @@ -65,13 +68,19 @@ OuterProduct::OuterProduct(const ActionOptions&ao): Action(ao), ActionWithMatrix(ao), domin(false), - domax(false) -{ - if( getNumberOfArguments()!=2 ) error("should be two arguments to this action, a matrix and a vector"); - if( getPntrToArgument(0)->getRank()!=1 || getPntrToArgument(0)->hasDerivatives() ) error("first argument to this action should be a vector"); - if( getPntrToArgument(1)->getRank()!=1 || getPntrToArgument(1)->hasDerivatives() ) error("first argument to this action should be a vector"); + domax(false) { + if( getNumberOfArguments()!=2 ) { + error("should be two arguments to this action, a matrix and a vector"); + } + if( getPntrToArgument(0)->getRank()!=1 || getPntrToArgument(0)->hasDerivatives() ) { + error("first argument to this action should be a vector"); + } + if( getPntrToArgument(1)->getRank()!=1 || getPntrToArgument(1)->hasDerivatives() ) { + error("first argument to this action should be a vector"); + } - std::string func; parse("FUNC",func); + std::string func; + parse("FUNC",func); if( func=="min") { domin=true; log.printf(" taking minimum of two input vectors \n"); @@ -80,18 +89,28 @@ OuterProduct::OuterProduct(const ActionOptions&ao): log.printf(" taking maximum of two input vectors \n"); } else { log.printf(" with function : %s \n", func.c_str() ); - std::vector var(2); var[0]="x"; var[1]="y"; + std::vector var(2); + var[0]="x"; + var[1]="y"; function.set( func, var, this ); } parseFlag("ELEMENTS_ON_DIAGONAL_ARE_ZERO",diagzero); - if( diagzero ) log.printf(" setting diagonal elements equal to zero\n"); + if( diagzero ) { + log.printf(" setting diagonal elements equal to zero\n"); + } - std::vector shape(2); shape[0]=getPntrToArgument(0)->getShape()[0]; shape[1]=getPntrToArgument(1)->getShape()[0]; - addValue( shape ); setNotPeriodic(); nderivatives = buildArgumentStore(0); + std::vector shape(2); + shape[0]=getPntrToArgument(0)->getShape()[0]; + shape[1]=getPntrToArgument(1)->getShape()[0]; + addValue( shape ); + setNotPeriodic(); + nderivatives = buildArgumentStore(0); std::string headstr=getFirstActionInChain()->getLabel(); stored_vector1 = getPntrToArgument(0)->ignoreStoredValue( headstr ); stored_vector2 = getPntrToArgument(1)->ignoreStoredValue( headstr ); - if( getPntrToArgument(0)->isDerivativeZeroWhenValueIsZero() || getPntrToArgument(1)->isDerivativeZeroWhenValueIsZero() ) getPntrToComponent(0)->setDerivativeIsZeroWhenValueIsZero(); + if( getPntrToArgument(0)->isDerivativeZeroWhenValueIsZero() || getPntrToArgument(1)->isDerivativeZeroWhenValueIsZero() ) { + getPntrToComponent(0)->setDerivativeIsZeroWhenValueIsZero(); + } } unsigned OuterProduct::getNumberOfDerivatives() { @@ -99,46 +118,82 @@ unsigned OuterProduct::getNumberOfDerivatives() { } void OuterProduct::prepare() { - ActionWithVector::prepare(); Value* myval=getPntrToComponent(0); - if( myval->getShape()[0]==getPntrToArgument(0)->getShape()[0] && myval->getShape()[1]==getPntrToArgument(1)->getShape()[0] ) return; - std::vector shape(2); shape[0] = getPntrToArgument(0)->getShape()[0]; shape[1] = getPntrToArgument(1)->getShape()[0]; + ActionWithVector::prepare(); + Value* myval=getPntrToComponent(0); + if( myval->getShape()[0]==getPntrToArgument(0)->getShape()[0] && myval->getShape()[1]==getPntrToArgument(1)->getShape()[0] ) { + return; + } + std::vector shape(2); + shape[0] = getPntrToArgument(0)->getShape()[0]; + shape[1] = getPntrToArgument(1)->getShape()[0]; myval->setShape( shape ); } void OuterProduct::setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const { unsigned start_n = getPntrToArgument(0)->getShape()[0], size_v = getPntrToArgument(1)->getShape()[0]; if( diagzero ) { - if( indices.size()!=size_v ) indices.resize( size_v ); + if( indices.size()!=size_v ) { + indices.resize( size_v ); + } unsigned k=1; for(unsigned i=0; igetPositionInStream(), ind2=index2; - if( index2>=getPntrToArgument(0)->getShape()[0] ) ind2 = index2 - getPntrToArgument(0)->getShape()[0]; - if( diagzero && index1==ind2 ) return; + if( index2>=getPntrToArgument(0)->getShape()[0] ) { + ind2 = index2 - getPntrToArgument(0)->getShape()[0]; + } + if( diagzero && index1==ind2 ) { + return; + } - double fval; unsigned jarg = 0, kelem = index1; bool jstore=stored_vector1; + double fval; + unsigned jarg = 0, kelem = index1; + bool jstore=stored_vector1; std::vector args(2); args[0] = getArgumentElement( 0, index1, myvals ); args[1] = getArgumentElement( 1, ind2, myvals ); if( domin ) { - fval=args[0]; if( args[1]args[0] ) { fval=args[1]; jarg=1; kelem=ind2; jstore=stored_vector2; } - } else { fval=function.evaluate( args ); } + fval=args[0]; + if( args[1]>args[0] ) { + fval=args[1]; + jarg=1; + kelem=ind2; + jstore=stored_vector2; + } + } else { + fval=function.evaluate( args ); + } myvals.addValue( ostrn, fval ); - if( doNotCalculateDerivatives() ) return ; + if( doNotCalculateDerivatives() ) { + return ; + } if( domin || domax ) { addDerivativeOnVectorArgument( jstore, 0, jarg, kelem, 1.0, myvals ); @@ -146,15 +201,21 @@ void OuterProduct::performTask( const std::string& controller, const unsigned& i addDerivativeOnVectorArgument( stored_vector1, 0, 0, index1, function.evaluateDeriv( 0, args ), myvals ); addDerivativeOnVectorArgument( stored_vector2, 0, 1, ind2, function.evaluateDeriv( 1, args ), myvals ); } - if( doNotCalculateDerivatives() || !matrixChainContinues() ) return ; + if( doNotCalculateDerivatives() || !matrixChainContinues() ) { + return ; + } unsigned nmat = getConstPntrToComponent(0)->getPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); - myvals.getMatrixRowDerivativeIndices( nmat )[nmat_ind] = arg_deriv_starts[1] + ind2; myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind+1 ); + myvals.getMatrixRowDerivativeIndices( nmat )[nmat_ind] = arg_deriv_starts[1] + ind2; + myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind+1 ); } void OuterProduct::runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() || !matrixChainContinues() ) return ; + if( doNotCalculateDerivatives() || !matrixChainContinues() ) { + return ; + } unsigned nmat = getConstPntrToComponent(0)->getPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); - myvals.getMatrixRowDerivativeIndices( nmat )[nmat_ind] = ival; myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind+1 ); + myvals.getMatrixRowDerivativeIndices( nmat )[nmat_ind] = ival; + myvals.setNumberOfMatrixRowDerivatives( nmat, nmat_ind+1 ); } } diff --git a/src/matrixtools/TransposeMatrix.cpp b/src/matrixtools/TransposeMatrix.cpp index 125bd43b31..932a9d251e 100644 --- a/src/matrixtools/TransposeMatrix.cpp +++ b/src/matrixtools/TransposeMatrix.cpp @@ -40,7 +40,9 @@ class TransposeMatrix : public MatrixOperationBase { /// Constructor explicit TransposeMatrix(const ActionOptions&); /// - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } /// void prepare() override ; /// @@ -60,67 +62,115 @@ void TransposeMatrix::registerKeywords( Keywords& keys ) { TransposeMatrix::TransposeMatrix(const ActionOptions& ao): Action(ao), - MatrixOperationBase(ao) -{ - if( getPntrToArgument(0)->isSymmetric() ) error("input matrix is symmetric. Transposing will achieve nothing!"); + MatrixOperationBase(ao) { + if( getPntrToArgument(0)->isSymmetric() ) { + error("input matrix is symmetric. Transposing will achieve nothing!"); + } std::vector shape; - if( getPntrToArgument(0)->getRank()==0 ) error("transposing a scalar?"); - else if( getPntrToArgument(0)->getRank()==1 ) { shape.resize(2); shape[0]=1; shape[1]=getPntrToArgument(0)->getShape()[0]; } - else if( getPntrToArgument(0)->getShape()[0]==1 ) { shape.resize(1); shape[0] = getPntrToArgument(0)->getShape()[1]; } - else { shape.resize(2); shape[0]=getPntrToArgument(0)->getShape()[1]; shape[1]=getPntrToArgument(0)->getShape()[0]; } - addValue( shape ); setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); - if( shape.size()==2 ) getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + if( getPntrToArgument(0)->getRank()==0 ) { + error("transposing a scalar?"); + } else if( getPntrToArgument(0)->getRank()==1 ) { + shape.resize(2); + shape[0]=1; + shape[1]=getPntrToArgument(0)->getShape()[0]; + } else if( getPntrToArgument(0)->getShape()[0]==1 ) { + shape.resize(1); + shape[0] = getPntrToArgument(0)->getShape()[1]; + } else { + shape.resize(2); + shape[0]=getPntrToArgument(0)->getShape()[1]; + shape[1]=getPntrToArgument(0)->getShape()[0]; + } + addValue( shape ); + setNotPeriodic(); + getPntrToComponent(0)->buildDataStore(); + if( shape.size()==2 ) { + getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + } } void TransposeMatrix::prepare() { - Value* myval = getPntrToComponent(0); Value* myarg = getPntrToArgument(0); + Value* myval = getPntrToComponent(0); + Value* myarg = getPntrToArgument(0); if( myarg->getRank()==1 ) { if( myval->getShape()[0]!=1 || myval->getShape()[1]!=myarg->getShape()[0] ) { - std::vector shape(2); shape[0] = 1; shape[1] = myarg->getShape()[0]; - myval->setShape( shape ); myval->reshapeMatrixStore( shape[1] ); + std::vector shape(2); + shape[0] = 1; + shape[1] = myarg->getShape()[0]; + myval->setShape( shape ); + myval->reshapeMatrixStore( shape[1] ); } } else if( myarg->getShape()[0]==1 ) { - if( myval->getShape()[0]!=myarg->getShape()[1] ) { std::vector shape(1); shape[0] = myarg->getShape()[1]; myval->setShape( shape ); } + if( myval->getShape()[0]!=myarg->getShape()[1] ) { + std::vector shape(1); + shape[0] = myarg->getShape()[1]; + myval->setShape( shape ); + } } else if( myarg->getShape()[0]!=myval->getShape()[1] || myarg->getShape()[1]!=myval->getShape()[0] ) { - std::vector shape(2); shape[0] = myarg->getShape()[1]; shape[1] = myarg->getShape()[0]; - myval->setShape( shape ); myval->reshapeMatrixStore( shape[1] ); + std::vector shape(2); + shape[0] = myarg->getShape()[1]; + shape[1] = myarg->getShape()[0]; + myval->setShape( shape ); + myval->reshapeMatrixStore( shape[1] ); } } void TransposeMatrix::calculate() { // Retrieve the non-zero pairs - Value* myarg=getPntrToArgument(0); Value* myval=getPntrToComponent(0); + Value* myarg=getPntrToArgument(0); + Value* myval=getPntrToComponent(0); if( myarg->getRank()<=1 || myval->getRank()==1 ) { if( myarg->getRank()<=1 && myval->getShape()[1]!=myarg->getShape()[0] ) { - std::vector shape( 2 ); shape[0] = 1; shape[1] = myarg->getShape()[0]; - myval->setShape( shape ); myval->reshapeMatrixStore( shape[1] ); + std::vector shape( 2 ); + shape[0] = 1; + shape[1] = myarg->getShape()[0]; + myval->setShape( shape ); + myval->reshapeMatrixStore( shape[1] ); } else if( myval->getRank()==1 && myval->getShape()[0]!=myarg->getShape()[1] ) { - std::vector shape( 1 ); shape[0] = myarg->getShape()[1]; + std::vector shape( 1 ); + shape[0] = myarg->getShape()[1]; myval->setShape( shape ); } unsigned nv=myarg->getNumberOfValues(); - for(unsigned i=0; iset( i, myarg->get(i) ); + for(unsigned i=0; iset( i, myarg->get(i) ); + } } else { if( myarg->getShape()[0]!=myval->getShape()[1] || myarg->getShape()[1]!=myval->getShape()[0] ) { - std::vector shape( 2 ); shape[0] = myarg->getShape()[1]; shape[1] = myarg->getShape()[0]; - myval->setShape( shape ); myval->reshapeMatrixStore( shape[1] ); + std::vector shape( 2 ); + shape[0] = myarg->getShape()[1]; + shape[1] = myarg->getShape()[0]; + myval->setShape( shape ); + myval->reshapeMatrixStore( shape[1] ); + } + std::vector vals; + std::vector > pairs; + std::vector shape( myval->getShape() ); + unsigned nedge=0; + myarg->retrieveEdgeList( nedge, pairs, vals ); + for(unsigned i=0; iset( pairs[i].second*shape[1] + pairs[i].first, vals[i] ); } - std::vector vals; std::vector > pairs; - std::vector shape( myval->getShape() ); unsigned nedge=0; myarg->retrieveEdgeList( nedge, pairs, vals ); - for(unsigned i=0; iset( pairs[i].second*shape[1] + pairs[i].first, vals[i] ); } } void TransposeMatrix::apply() { - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } // Apply force on the matrix if( getPntrToComponent(0)->forcesWereAdded() ) { - Value* myarg=getPntrToArgument(0); Value* myval=getPntrToComponent(0); + Value* myarg=getPntrToArgument(0); + Value* myval=getPntrToComponent(0); if( myarg->getRank()<=1 || myval->getRank()==1 ) { unsigned nv=myarg->getNumberOfValues(); - for(unsigned i=0; iaddForce( i, myval->getForce(i) ); - } else MatrixOperationBase::apply(); + for(unsigned i=0; iaddForce( i, myval->getForce(i) ); + } + } else { + MatrixOperationBase::apply(); + } } } diff --git a/src/matrixtools/Voronoi.cpp b/src/matrixtools/Voronoi.cpp index a5ab13090b..df91ba6f2e 100644 --- a/src/matrixtools/Voronoi.cpp +++ b/src/matrixtools/Voronoi.cpp @@ -39,8 +39,12 @@ class Voronoi : public ActionWithMatrix { static void registerKeywords( Keywords& keys ); explicit Voronoi(const ActionOptions&); void prepare() override ; - unsigned getNumberOfDerivatives() override { return 0; } - unsigned getNumberOfColumns() const override { return getConstPntrToComponent(0)->getShape()[1]; } + unsigned getNumberOfDerivatives() override { + return 0; + } + unsigned getNumberOfColumns() const override { + return getConstPntrToComponent(0)->getShape()[1]; + } void setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const override {} void performTask( const std::string& controller, const unsigned& index1, const unsigned& index2, MultiValue& myvals ) const override {} void runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const override {} @@ -51,33 +55,51 @@ class Voronoi : public ActionWithMatrix { PLUMED_REGISTER_ACTION(Voronoi,"VORONOI") void Voronoi::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords(keys); keys.use("ARG"); + ActionWithMatrix::registerKeywords(keys); + keys.use("ARG"); keys.setValueDescription("a matrix in which element ij is equal to one if the ij component of the input matrix is lower than all the ik elements of the matrix where k is not j and zero otherwise"); } Voronoi::Voronoi(const ActionOptions&ao): Action(ao), - ActionWithMatrix(ao) -{ - if( getNumberOfArguments()!=1 ) error("should be one arguments to this action, a matrix"); - if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) error("argument to this action should be a matrix"); - if( getPntrToArgument(0)->getShape()[1]>getPntrToArgument(0)->getShape()[0] ) warning("would expect number of columns in matrix to exceed number of rows"); - getPntrToArgument(0)->buildDataStore(); std::vector shape( getPntrToArgument(0)->getShape() ); - addValue( shape ); setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); + ActionWithMatrix(ao) { + if( getNumberOfArguments()!=1 ) { + error("should be one arguments to this action, a matrix"); + } + if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) { + error("argument to this action should be a matrix"); + } + if( getPntrToArgument(0)->getShape()[1]>getPntrToArgument(0)->getShape()[0] ) { + warning("would expect number of columns in matrix to exceed number of rows"); + } + getPntrToArgument(0)->buildDataStore(); + std::vector shape( getPntrToArgument(0)->getShape() ); + addValue( shape ); + setNotPeriodic(); + getPntrToComponent(0)->buildDataStore(); } void Voronoi::prepare() { Value* myval = getPntrToComponent(0); - if( myval->getShape()[0]==getPntrToArgument(0)->getShape()[0] && myval->getShape()[1]==getPntrToArgument(0)->getShape()[1] ) return; - std::vector shape( getPntrToArgument(0)->getShape() ); myval->setShape(shape); + if( myval->getShape()[0]==getPntrToArgument(0)->getShape()[0] && myval->getShape()[1]==getPntrToArgument(0)->getShape()[1] ) { + return; + } + std::vector shape( getPntrToArgument(0)->getShape() ); + myval->setShape(shape); } void Voronoi::gatherStoredValue( const unsigned& valindex, const unsigned& code, const MultiValue& myvals, const unsigned& bufstart, std::vector& buffer ) const { - Value* arg0 = getPntrToArgument(0); unsigned nv = 0; std::size_t cc=code; double minmax = arg0->get( cc*arg0->getShape()[1] ); + Value* arg0 = getPntrToArgument(0); + unsigned nv = 0; + std::size_t cc=code; + double minmax = arg0->get( cc*arg0->getShape()[1] ); for(unsigned i=0; igetShape()[1]; ++i) { double value = arg0->get( code*arg0->getShape()[1] + i ); - if( valuegetShape()[1] + nv] = 1; } diff --git a/src/maze/Loss.cpp b/src/maze/Loss.cpp index 76a4a16e9b..2e2d0280dd 100644 --- a/src/maze/Loss.cpp +++ b/src/maze/Loss.cpp @@ -74,8 +74,7 @@ void Loss::registerKeywords(Keywords& keys) { } Loss::Loss(const ActionOptions& ao) - : PLUMED_COLVAR_INIT(ao) -{ + : PLUMED_COLVAR_INIT(ao) { if (keywords.exists("PARAMS")) { parseVector("PARAMS", params_); diff --git a/src/maze/Memetic.cpp b/src/maze/Memetic.cpp index 36774e55e7..7cc61c6534 100644 --- a/src/maze/Memetic.cpp +++ b/src/maze/Memetic.cpp @@ -147,8 +147,7 @@ Memetic::Memetic(const ActionOptions& ao) score_best_(0), adaptation_(true), coding_len_(3), - local_search_on_(false) -{ + local_search_on_(false) { log.printf("maze> Memetic sampling.\n"); if (keywords.exists("CAPACITY")) { diff --git a/src/maze/Memetic.h b/src/maze/Memetic.h index 439f72cb3b..695584d07b 100644 --- a/src/maze/Memetic.h +++ b/src/maze/Memetic.h @@ -357,7 +357,9 @@ void Memetic::sort_members() { } double Memetic::score_mean() { - auto acc = [](double s, const Member& m) { return s + m.score; }; + auto acc = [](double s, const Member& m) { + return s + m.score; + }; return std::accumulate( members_.begin(), @@ -440,8 +442,7 @@ void Memetic::mutation(std::vector& m) { void Memetic::stochastic_hill_climbing( Member& m, - const std::vector& params) -{ + const std::vector& params) { for (std::size_t i = 0; i < n_local_iterations_; ++i) { Member n; n.translation = m.translation; @@ -456,8 +457,7 @@ void Memetic::stochastic_hill_climbing( void Memetic::random_restart_hill_climbing( Member& m, - const std::vector& params) -{ + const std::vector& params) { unsigned int n_restarts = static_cast(params[0]); std::vector s(n_restarts); unsigned int ndx = 0; @@ -479,8 +479,7 @@ void Memetic::random_restart_hill_climbing( void Memetic::annealing( Member& m, - const std::vector& params) -{ + const std::vector& params) { double T = params[0]; double alpha = params[1]; @@ -506,15 +505,13 @@ void Memetic::annealing( void Memetic::luus_jaakola( Member& m, - const std::vector& params) -{ + const std::vector& params) { /* TODO */ } void Memetic::adaptive_random_search( Member& m, - const std::vector& params) -{ + const std::vector& params) { double rho_start = params[0]; double rho_lower_bound = params[1]; double ex = params[2]; @@ -533,8 +530,7 @@ void Memetic::adaptive_random_search( while (rho_k > rho_lower_bound && k < n_local_iterations_) { if (ns >= s_ex) { rho_k *= ex; - } - else if (nf >= f_ct) { + } else if (nf >= f_ct) { rho_k *= ct; } @@ -558,8 +554,7 @@ void Memetic::adaptive_random_search( bk[i] = 0.2 * bk[i] + 0.4 * (chi[i] - xk[i]); xk[i] = chi[i]; } - } - else if (score_tmp < score_xk && score_xk <= score_chi) { + } else if (score_tmp < score_xk && score_xk <= score_chi) { ns++; nf = 0; @@ -567,8 +562,7 @@ void Memetic::adaptive_random_search( bk[i] = bk[i] - 0.4 * (chi[i] - xk[i]); xk[i] = 2.0 * xk[i] - chi[i]; } - } - else { + } else { ns = 0; nf++; @@ -591,12 +585,13 @@ void Memetic::local_search(std::vector& m) { double probability = rnd::next_double(); if (probability < local_search_rate_) { - if (local_search_type_ == "stochastic_hill_climbing") + if (local_search_type_ == "stochastic_hill_climbing") { stochastic_hill_climbing(m[i]); - else if (local_search_type_ == "adaptive_random_search") + } else if (local_search_type_ == "adaptive_random_search") { adaptive_random_search(m[i]); - else if (local_search_type_ == "random_restart_hill_climbing") + } else if (local_search_type_ == "random_restart_hill_climbing") { random_restart_hill_climbing(m[i]); + } } } } @@ -621,8 +616,7 @@ void Memetic::mating(std::vector& m) { if (i > j) { m.erase(m.begin() + i); m.erase(m.begin() + j); - } - else if (j > i) { + } else if (j > i) { m.erase(m.begin() + j); m.erase(m.begin() + i); } @@ -672,8 +666,7 @@ double Memetic::score_member(const Vector& coding) { if (pbc_) { distance = pbcDistance(getPosition(i0) + dev, getPosition(i1)); - } - else { + } else { distance = delta(getPosition(i0) + dev, getPosition(i1)); } diff --git a/src/maze/Optimizer.cpp b/src/maze/Optimizer.cpp index 73dc38ca2d..fbf2a0a56c 100644 --- a/src/maze/Optimizer.cpp +++ b/src/maze/Optimizer.cpp @@ -143,8 +143,7 @@ Optimizer::Optimizer(const ActionOptions& ao) sampling_r_(0.0), serial_(false), validate_list_(true), - first_time_(true) -{ + first_time_(true) { parseFlag("SERIAL", serial_); if (keywords.exists("LOSS")) { @@ -234,8 +233,7 @@ Optimizer::Optimizer(const ActionOptions& ao) nl_cutoff_, nl_stride_ ); - } - else { + } else { neighbor_list_=Tools::make_unique( ga_list, gb_list, @@ -246,8 +244,7 @@ Optimizer::Optimizer(const ActionOptions& ao) comm ); } - } - else { + } else { if (do_neigh) { neighbor_list_ = Tools::make_unique( ga_list, @@ -258,8 +255,7 @@ Optimizer::Optimizer(const ActionOptions& ao) nl_cutoff_, nl_stride_ ); - } - else { + } else { neighbor_list_=Tools::make_unique( ga_list, serial_, @@ -294,8 +290,7 @@ Optimizer::Optimizer(const ActionOptions& ao) if (pbc_) { log.printf("maze> Using periodic boundary conditions.\n"); - } - else { + } else { log.printf("maze> Without periodic boundary conditions.\n"); } @@ -393,8 +388,7 @@ void Optimizer::prepare() { validate_list_ = true; first_time_ = false; - } - else { + } else { requestAtoms(neighbor_list_->getReducedAtomList()); validate_list_ = false; @@ -430,8 +424,7 @@ double Optimizer::score() { if (pbc_) { distance = pbcDistance(getPosition(i0), getPosition(i1)); - } - else { + } else { distance = delta(getPosition(i0), getPosition(i1)); } @@ -448,8 +441,7 @@ void Optimizer::update_nl() { } } -double Optimizer::sampling_radius() -{ +double Optimizer::sampling_radius() { const unsigned nl_size=neighbor_list_->size(); Vector d; double min=std::numeric_limits::max(); @@ -464,8 +456,7 @@ double Optimizer::sampling_radius() if (pbc_) { d = pbcDistance(getPosition(i0), getPosition(i1)); - } - else { + } else { d = delta(getPosition(i0), getPosition(i1)); } @@ -491,8 +482,7 @@ void Optimizer::calculate() { value_action_->set(score()); value_sampling_radius_->set(sampling_radius()); - } - else { + } else { first_step_=false; value_x_->set(opt_[0]); diff --git a/src/maze/Optimizer_Bias.cpp b/src/maze/Optimizer_Bias.cpp index 7b420fd493..af17fed790 100644 --- a/src/maze/Optimizer_Bias.cpp +++ b/src/maze/Optimizer_Bias.cpp @@ -260,8 +260,7 @@ OptimizerBias::OptimizerBias(const ActionOptions& ao) : PLUMED_BIAS_INIT(ao), bias_(0.0), force_(0.0), - total_distance_(0.0) -{ + total_distance_(0.0) { log.printf( "maze> You are using the maze module of PLUMED2,\ please read and cite " diff --git a/src/maze/Random_Acceleration_MD.cpp b/src/maze/Random_Acceleration_MD.cpp index 741fda6e95..7eae952b48 100644 --- a/src/maze/Random_Acceleration_MD.cpp +++ b/src/maze/Random_Acceleration_MD.cpp @@ -180,8 +180,7 @@ void Random_Acceleration_MD::optimize() { if (pbc_) { d = pbcDistance(c, com_); - } - else { + } else { d = delta(c, com_); } diff --git a/src/maze/Random_Walk.cpp b/src/maze/Random_Walk.cpp index 5d82c456e4..6d4e2ab6f2 100644 --- a/src/maze/Random_Walk.cpp +++ b/src/maze/Random_Walk.cpp @@ -103,8 +103,7 @@ void Random_Walk::registerKeywords(Keywords& keys) { } Random_Walk::Random_Walk(const ActionOptions& ao) - : PLUMED_OPT_INIT(ao) -{ + : PLUMED_OPT_INIT(ao) { log.printf("maze> Fake optimizer that returns a next step as random,\ can be used to monitor loss, and for debugging and regtests purposes.\n"); diff --git a/src/maze/Simulated_Annealing.cpp b/src/maze/Simulated_Annealing.cpp index 4edf3003cc..48090e536b 100644 --- a/src/maze/Simulated_Annealing.cpp +++ b/src/maze/Simulated_Annealing.cpp @@ -143,8 +143,7 @@ void Simulated_Annealing::registerKeywords(Keywords& keys) { } Simulated_Annealing::Simulated_Annealing(const ActionOptions& ao) - : PLUMED_OPT_INIT(ao) -{ + : PLUMED_OPT_INIT(ao) { log.printf("maze> Simulated annealing optimizer.\n"); if(keywords.exists("COOLING")) { @@ -184,17 +183,13 @@ Simulated_Annealing::Simulated_Annealing(const ActionOptions& ao) void Simulated_Annealing::decrease_probability(unsigned int time) { if (cooling_scheme_ == "linear") { probability_decreaser_ -= time * cooling_factor_; - } - else if (cooling_scheme_ == "exponential") { + } else if (cooling_scheme_ == "exponential") { probability_decreaser_ *= pow(cooling_factor_, time); - } - else if (cooling_scheme_ == "geometric") { + } else if (cooling_scheme_ == "geometric") { probability_decreaser_ *= cooling_factor_; - } - else if (cooling_scheme_ == "logarithmic") { + } else if (cooling_scheme_ == "logarithmic") { probability_decreaser_ = cooling_factor_ / std::log(time + 1); - } - else if (cooling_scheme_ == "hoffman") { + } else if (cooling_scheme_ == "hoffman") { probability_decreaser_ = (cooling_factor_ - 1) / std::log(time); } } @@ -234,8 +229,7 @@ void Simulated_Annealing::optimize() { getPosition(i0) + dev, getPosition(i1) ); - } - else { + } else { distance = delta( getPosition(i0) + get_opt(), getPosition(i1) diff --git a/src/maze/Steered_MD.cpp b/src/maze/Steered_MD.cpp index 867c354f2c..74854ab181 100644 --- a/src/maze/Steered_MD.cpp +++ b/src/maze/Steered_MD.cpp @@ -124,8 +124,7 @@ void Steered_MD::registerKeywords(Keywords& keys) { Steered_MD::Steered_MD(const ActionOptions& ao) : PLUMED_OPT_INIT(ao), - total_dist_(0.0) -{ + total_dist_(0.0) { log.printf("maze> Steered MD.\n"); if (keywords.exists("PULLING")) { @@ -157,8 +156,7 @@ void Steered_MD::optimize() { if (pbc_) { d = pbcDistance(c, com_); - } - else { + } else { d = delta(c, com_); } diff --git a/src/maze/Tools.h b/src/maze/Tools.h index d20694cd4e..b09bf141d6 100644 --- a/src/maze/Tools.h +++ b/src/maze/Tools.h @@ -106,8 +106,9 @@ template std::vector tls::vector_n(const std::vector& v) { double l=vector_l(v); std::vector n; - for(std::size_t i=0; i tls::get_labels_actions(const ActionSet& actionset) { std::vector action_str(0); std::vector action_pntrs=actionset.select(); - for(unsigned int i=0; igetLabel()); + } return action_str; } @@ -167,8 +169,9 @@ std::vector tls::get_pointers_labels( for(unsigned int i=0; i(action_labels[i]); - if(action_pntrs[i]==NULL) + if(action_pntrs[i]==NULL) { missing.push_back(action_labels[i]); + } } return action_pntrs; diff --git a/src/membranefusion/FusionPoreExpansionP.cpp b/src/membranefusion/FusionPoreExpansionP.cpp index 303a40e356..45ec5bbfd9 100644 --- a/src/membranefusion/FusionPoreExpansionP.cpp +++ b/src/membranefusion/FusionPoreExpansionP.cpp @@ -27,10 +27,8 @@ along with plumed. If not, see . #endif #endif -namespace PLMD -{ -namespace membranefusion -{ +namespace PLMD { +namespace membranefusion { //+PLUMEDOC MEMBRANEFUSIONMOD_COLVAR FUSIONPOREEXPANSIONP /* A CV for inducing the expansion of a fusion pore from a nucleated fusion pore. @@ -71,8 +69,7 @@ PRINT ARG=fusionPoreExpansion FILE=COLVAR STRIDE=1 */ //+ENDPLUMEDOC -class fusionPoreExpansionP : public Colvar -{ +class fusionPoreExpansionP : public Colvar { std::vector UMEM, LMEM, TAILS, WATERS, POXYGENS; std::vector NSMEM, DSMEM, HMEM, VO, D, H, RMAX, R0, XCYL, YCYL; @@ -84,8 +81,7 @@ class fusionPoreExpansionP : public Colvar PLUMED_REGISTER_ACTION(fusionPoreExpansionP, "FUSIONPOREEXPANSIONP") -void fusionPoreExpansionP::registerKeywords(Keywords &keys) -{ +void fusionPoreExpansionP::registerKeywords(Keywords &keys) { Colvar::registerKeywords(keys); keys.add("atoms", "UMEMBRANE", "all the beads of the upper membrane."); keys.add("atoms", "LMEMBRANE", "all the beads of the lower membrane."); @@ -105,103 +101,119 @@ void fusionPoreExpansionP::registerKeywords(Keywords &keys) keys.setValueDescription("the value of the CV"); } -fusionPoreExpansionP::fusionPoreExpansionP(const ActionOptions &ao) : PLUMED_COLVAR_INIT(ao) -{ +fusionPoreExpansionP::fusionPoreExpansionP(const ActionOptions &ao) : PLUMED_COLVAR_INIT(ao) { parseAtomList("UMEMBRANE", UMEM); - if (UMEM.size() == 0) + if (UMEM.size() == 0) { error("UMEMBRANE has not any atom specified."); + } parseAtomList("LMEMBRANE", LMEM); - if (LMEM.size() == 0) + if (LMEM.size() == 0) { error("LMEMBRANE has not any atom specified."); + } parseAtomList("TAILS", TAILS); - if (TAILS.size() == 0) + if (TAILS.size() == 0) { error("TAILS has not any atom specified."); + } parseAtomList("WATERS", WATERS); - if (WATERS.size() == 0) + if (WATERS.size() == 0) { error("WATERS has not any atom specified."); + } parseAtomList("PHOSPHATEOXYGENS", POXYGENS); - if (POXYGENS.size() == 0) + if (POXYGENS.size() == 0) { error("PHOSPHATEOXYGENS has not any atom specified."); + } parseVector("NSMEM", NSMEM); - if (NSMEM.size() > 1) + if (NSMEM.size() > 1) { error("NSMEM cannot take more than one value."); + } parseVector("DSMEM", DSMEM); - if (DSMEM.size() > 1) + if (DSMEM.size() > 1) { error("DSMEM cannot take more than one value."); - if (DSMEM.size() == 0) + } + if (DSMEM.size() == 0) { DSMEM.push_back(0.1); + } parseVector("HMEM", HMEM); - if (HMEM.size() > 1) + if (HMEM.size() > 1) { error("HMEM cannot take more than one value."); - if (HMEM.size() == 0) + } + if (HMEM.size() == 0) { HMEM.push_back(0.25); + } parseVector("VO", VO); - if (VO.size() > 1) + if (VO.size() > 1) { error("VO cannot take more than one value."); - if (VO.size() == 0) + } + if (VO.size() == 0) { VO.push_back(0.076879); + } parseVector("D", D); - if (D.size() > 1) + if (D.size() > 1) { error("D cannot take more than one value."); + } parseVector("H", H); - if (H.size() > 1) + if (H.size() > 1) { error("H cannot take more than one value."); - if (H.size() == 0) + } + if (H.size() == 0) { H.push_back(0.1); + } parseVector("RMAX", RMAX); - if (RMAX.size() > 1) + if (RMAX.size() > 1) { error("RMAX cannot take more than one value."); - if (RMAX.size() == 0) + } + if (RMAX.size() == 0) { RMAX.push_back(2.5); + } parseVector("R0", R0); - if (R0.size() > 1) + if (R0.size() > 1) { error("R0 cannot take more than one value."); + } parseVector("XCYL", XCYL); - if (XCYL.size() > 1) + if (XCYL.size() > 1) { error("XCYL cannot take more than one value."); - if (XCYL.size() == 0) + } + if (XCYL.size() == 0) { XCYL.push_back(-1.0); + } parseVector("YCYL", YCYL); - if (YCYL.size() > 1) + if (YCYL.size() > 1) { error("YCYL cannot take more than one value."); - if (YCYL.size() == 0) + } + if (YCYL.size() == 0) { YCYL.push_back(-1.0); + } checkRead(); std::vector atoms; - for (unsigned i = 0; i < UMEM.size(); i++) - { + for (unsigned i = 0; i < UMEM.size(); i++) { atoms.push_back(UMEM[i]); } - for (unsigned i = 0; i < LMEM.size(); i++) - { + for (unsigned i = 0; i < LMEM.size(); i++) { atoms.push_back(LMEM[i]); } - for (unsigned i = 0; i < TAILS.size(); i++) - { + for (unsigned i = 0; i < TAILS.size(); i++) { atoms.push_back(TAILS[i]); } - for (unsigned i = 0; i < WATERS.size(); i++) - { + for (unsigned i = 0; i < WATERS.size(); i++) { atoms.push_back(WATERS[i]); } - for (unsigned i = 0; i < POXYGENS.size(); i++) - { + for (unsigned i = 0; i < POXYGENS.size(); i++) { atoms.push_back(POXYGENS[i]); } @@ -209,8 +221,7 @@ fusionPoreExpansionP::fusionPoreExpansionP(const ActionOptions &ao) : PLUMED_COL setNotPeriodic(); requestAtoms(atoms); } -void fusionPoreExpansionP::calculate() -{ +void fusionPoreExpansionP::calculate() { /************************* * * * System * @@ -228,8 +239,7 @@ void fusionPoreExpansionP::calculate() #pragma omp parallel for private(uMemAngle, lMemAngle) reduction(+:ZuMemcos, ZuMemsin, ZlMemcos, ZlMemsin) #endif #endif - for (unsigned i = 0; i < UMEM.size(); i++) - { + for (unsigned i = 0; i < UMEM.size(); i++) { uMemAngle = 2.0 * M_PI * getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i)))[2]; lMemAngle = 2.0 * M_PI * getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + UMEM.size())))[2]; ZuMemcos += cos(uMemAngle); @@ -308,48 +318,36 @@ void fusionPoreExpansionP::calculate() #pragma omp parallel for private(ZTailDistance, PositionS_Mem, TailPosition, x, aux, s1_Mem, s2_Mem) reduction(vec_double_plus:Fs_Mem, sx_Mem, sy_Mem, cx_Mem, cy_Mem) #endif #endif - for (unsigned i = 0; i < TAILS.size(); i++) - { + for (unsigned i = 0; i < TAILS.size(); i++) { ZTailDistance = pbcDistance(Vector(0.0, 0.0, ZMems), getPosition(i + membraneBeads))[2]; PositionS_Mem = (ZTailDistance + firstSliceZDist_Mem) / DSMEM[0]; // If the following condition is met the particle is in the Z space of the cylinder. - if ((PositionS_Mem >= (-0.5 - HMEM[0])) && (PositionS_Mem <= (NSMEM[0] + 0.5 - 1.0 + HMEM[0]))) - { + if ((PositionS_Mem >= (-0.5 - HMEM[0])) && (PositionS_Mem <= (NSMEM[0] + 0.5 - 1.0 + HMEM[0]))) { //Defining the slices to analyze each particle. - if (PositionS_Mem < 1) - { + if (PositionS_Mem < 1) { s1_Mem = 0; s2_Mem = 2; - } - else if (PositionS_Mem <= (NSMEM[0] - 2.0)) - { + } else if (PositionS_Mem <= (NSMEM[0] - 2.0)) { s1_Mem = floor(PositionS_Mem) - 1; s2_Mem = floor(PositionS_Mem) + 1; - } - else - { + } else { s1_Mem = NSMEM[0] - 3; s2_Mem = NSMEM[0] - 1; } TailPosition = getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + membraneBeads))); - for (unsigned s = s1_Mem; s <= s2_Mem; s++) - { + for (unsigned s = s1_Mem; s <= s2_Mem; s++) { x = (ZTailDistance - (s + 0.5 - NSMEM[0] / 2.0) * DSMEM[0]) * 2.0 / DSMEM[0]; - if (!((x <= -1.0 - HMEM[0]) || (x >= 1.0 + HMEM[0]))) - { - if (((-1.0 + HMEM[0]) <= x) && (x <= (1.0 - HMEM[0]))) - { + if (!((x <= -1.0 - HMEM[0]) || (x >= 1.0 + HMEM[0]))) { + if (((-1.0 + HMEM[0]) <= x) && (x <= (1.0 - HMEM[0]))) { faxial_Mem[i + TAILS.size() * s] = 1.0; Fs_Mem[s] += 1.0; sx_Mem[s] += sin(2.0 * M_PI * TailPosition[0]); sy_Mem[s] += sin(2.0 * M_PI * TailPosition[1]); cx_Mem[s] += cos(2.0 * M_PI * TailPosition[0]); cy_Mem[s] += cos(2.0 * M_PI * TailPosition[1]); - } - else if (((1.0 - HMEM[0]) < x) && (x < (1.0 + HMEM[0]))) - { + } else if (((1.0 - HMEM[0]) < x) && (x < (1.0 + HMEM[0]))) { aux = 0.5 - ((3.0 * x - 3.0) / (4.0 * HMEM[0])) + (pow((x - 1.0), 3) / (4.0 * pow(HMEM[0], 3))); faxial_Mem[i + TAILS.size() * s] = aux; Fs_Mem[s] += aux; @@ -357,9 +355,7 @@ void fusionPoreExpansionP::calculate() sy_Mem[s] += aux * sin(2.0 * M_PI * TailPosition[1]); cx_Mem[s] += aux * cos(2.0 * M_PI * TailPosition[0]); cy_Mem[s] += aux * cos(2.0 * M_PI * TailPosition[1]); - } - else if (((-1.0 - HMEM[0]) < x) && (x < (-1.0 + HMEM[0]))) - { + } else if (((-1.0 - HMEM[0]) < x) && (x < (-1.0 + HMEM[0]))) { aux = 0.5 + ((3.0 * x + 3.0) / (4.0 * HMEM[0])) - (pow((x + 1.0), 3) / (4.0 * pow(HMEM[0], 3))); faxial_Mem[i + TAILS.size() * s] = aux; Fs_Mem[s] += aux; @@ -373,10 +369,8 @@ void fusionPoreExpansionP::calculate() } } - for (unsigned s = 0; s < NSMEM[0]; s++) - { - if (Fs_Mem[s] != 0.0) - { + for (unsigned s = 0; s < NSMEM[0]; s++) { + if (Fs_Mem[s] != 0.0) { ws_Mem[s] = tanh(Fs_Mem[s]); W_Mem += ws_Mem[s]; sx_Mem[s] = sx_Mem[s] / Fs_Mem[s]; @@ -398,13 +392,10 @@ void fusionPoreExpansionP::calculate() // Eq. 12 Hub & Awasthi JCTC 2017. double Xcyl_Mem, Ycyl_Mem; - if ((XCYL[0] > 0.0) && (YCYL[0] > 0.0)) - { + if ((XCYL[0] > 0.0) && (YCYL[0] > 0.0)) { Xcyl_Mem = XCYL[0]; Ycyl_Mem = YCYL[0]; - } - else - { + } else { Xcyl_Mem = (atan2(-Xsc_Mem, -Xcc_Mem) + M_PI) * Lx / (2 * M_PI); Ycyl_Mem = (atan2(-Ysc_Mem, -Ycc_Mem) + M_PI) * Ly / (2 * M_PI); } @@ -467,29 +458,22 @@ void fusionPoreExpansionP::calculate() #pragma omp parallel for private(MemCylDistances, x, angle, auxcos, auxsin) reduction(+:ZMemRMAXcos, ZMemRMAXsin, countAux) #endif #endif - for (unsigned i = 0; i < membraneBeads; i++) -{ + for (unsigned i = 0; i < membraneBeads; i++) { MemCylDistances = pbcDistance(xyzCyl, pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i))); x = sqrt(pow(MemCylDistances[0], 2) + pow(MemCylDistances[1], 2)) / RMAX[0]; - if (!((x <= -1.0 - H[0]) || (x >= 1.0 + H[0]))) - { + if (!((x <= -1.0 - H[0]) || (x >= 1.0 + H[0]))) { angle = 2.0 * M_PI * getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i)))[2]; auxcos = cos(angle); auxsin = sin(angle); - if (((-1.0 + H[0]) <= x) && (x <= (1.0 - H[0]))) - { + if (((-1.0 + H[0]) <= x) && (x <= (1.0 - H[0]))) { ZMemRMAXcos += 1.0 * auxcos; ZMemRMAXsin += 1.0 * auxsin; countAux += 1.0; - } - else if (((1.0 - H[0]) < x) && (x < (1.0 + H[0]))) - { + } else if (((1.0 - H[0]) < x) && (x < (1.0 + H[0]))) { ZMemRMAXcos += (0.5 - 0.75 * (x - 1.0) / H[0] + 0.25 * pow((x - 1.0), 3) / pow(H[0], 3)) * auxcos; ZMemRMAXsin += (0.5 - 0.75 * (x - 1.0) / H[0] + 0.25 * pow((x - 1.0), 3) / pow(H[0], 3)) * auxsin; countAux += (0.5 - 0.75 * (x - 1.0) / H[0] + 0.25 * pow((x - 1.0), 3) / pow(H[0], 3)); - } - else if (((-1.0 - H[0]) < x) && (x < (-1.0 + H[0]))) - { + } else if (((-1.0 - H[0]) < x) && (x < (-1.0 + H[0]))) { ZMemRMAXcos += (0.5 + 0.75 * (x + 1.0) / H[0] - 0.25 * pow((x + 1.0), 3) / pow(H[0], 3)) * auxcos; ZMemRMAXsin += (0.5 + 0.75 * (x + 1.0) / H[0] - 0.25 * pow((x + 1.0), 3) / pow(H[0], 3)) * auxsin; countAux += (0.5 + 0.75 * (x + 1.0) / H[0] - 0.25 * pow((x + 1.0), 3) / pow(H[0], 3)); @@ -508,8 +492,7 @@ void fusionPoreExpansionP::calculate() #pragma omp parallel for private(distCylinder, fz, fz_prime, fr, fr_prime, ri, x) reduction(+:np) #endif #endif - for (unsigned i = 0; i < chainBeads; i++) -{ + for (unsigned i = 0; i < chainBeads; i++) { distCylinder = pbcDistance(xyzCyl, pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + noChainBeads))); fz = 0.0; fz_prime = 0.0; @@ -518,37 +501,25 @@ void fusionPoreExpansionP::calculate() ri = sqrt(pow(distCylinder[0], 2) + pow(distCylinder[1], 2)); x = ri / RMAX[0]; - if (!((x <= -1.0 - H[0]) || (x >= 1.0 + H[0]))) - { - if (((-1.0 + H[0]) <= x) && (x <= (1.0 - H[0]))) - { + if (!((x <= -1.0 - H[0]) || (x >= 1.0 + H[0]))) { + if (((-1.0 + H[0]) <= x) && (x <= (1.0 - H[0]))) { fr = 1.0; - } - else if (((1.0 - H[0]) < x) && (x < (1.0 + H[0]))) - { + } else if (((1.0 - H[0]) < x) && (x < (1.0 + H[0]))) { fr = 0.5 - 0.75 * (x - 1.0) / H[0] + 0.25 * pow((x - 1.0), 3) / pow(H[0], 3); fr_prime = (-0.75 / H[0] + 0.75 * pow((x - 1.0), 2) / pow(H[0], 3)) / (RMAX[0] * ri); - } - else if (((-1.0 - H[0]) < x) && (x < (-1.0 + H[0]))) - { + } else if (((-1.0 - H[0]) < x) && (x < (-1.0 + H[0]))) { fr = 0.5 + 0.75 * (x + 1.0) / H[0] - 0.25 * pow((x + 1.0), 3) / pow(H[0], 3); fr_prime = (0.75 / H[0] - 0.75 * pow((x + 1), 2) / pow(H[0], 3)) / (RMAX[0] * ri); } x = distCylinder[2] * 2.0 / D[0]; - if (!((x <= -1.0 - H[0]) || (x >= 1.0 + H[0]))) - { - if (((-1.0 + H[0]) <= x) && (x <= (1.0 - H[0]))) - { + if (!((x <= -1.0 - H[0]) || (x >= 1.0 + H[0]))) { + if (((-1.0 + H[0]) <= x) && (x <= (1.0 - H[0]))) { fz = 1.0; - } - else if (((1.0 - H[0]) < x) && (x < (1.0 + H[0]))) - { + } else if (((1.0 - H[0]) < x) && (x < (1.0 + H[0]))) { fz = 0.5 - 0.75 * (x - 1.0) / H[0] + 0.25 * pow((x - 1.0), 3) / pow(H[0], 3); fz_prime = (-0.75 / H[0] + 0.75 * pow((x - 1.0), 2) / pow(H[0], 3)) * 2.0 / D[0]; - } - else if (((-1.0 - H[0]) < x) && (x < (-1.0 + H[0]))) - { + } else if (((-1.0 - H[0]) < x) && (x < (-1.0 + H[0]))) { fz = 0.5 + 0.75 * (x + 1.0) / H[0] - 0.25 * pow((x + 1.0), 3) / pow(H[0], 3); fz_prime = (0.75 / H[0] - 0.75 * pow((x + 1), 2) / pow(H[0], 3)) * 2.0 / D[0]; } @@ -571,8 +542,7 @@ void fusionPoreExpansionP::calculate() // Aux for the derivatives calculations. Eq. 7 Hub 2021 JCTC. double fact2 = 0.0; - if (poreR != 0.0) -{ + if (poreR != 0.0) { fact2 = VO[0] / (2.0 * M_PI * RO * D[0] * poreR); } @@ -584,8 +554,7 @@ void fusionPoreExpansionP::calculate() #pragma omp parallel for #endif #endif - for (unsigned i = 0; i < chainBeads; i++) -{ + for (unsigned i = 0; i < chainBeads; i++) { derivatives[i][0] = fact2 * d_np_dx[i]; derivatives[i][1] = fact2 * d_np_dy[i]; derivatives[i][2] = fact2 * d_np_dz[i]; @@ -593,8 +562,7 @@ void fusionPoreExpansionP::calculate() } Tensor virial; - for (unsigned i = 0; i < chainBeads; i++) -{ + for (unsigned i = 0; i < chainBeads; i++) { setAtomsDerivatives((i + noChainBeads), derivatives[i]); virial -= Tensor(CylDistances[i], derivatives[i]); } diff --git a/src/membranefusion/FusionPoreNucleationP.cpp b/src/membranefusion/FusionPoreNucleationP.cpp index a68ea0f47c..53d8c6f666 100644 --- a/src/membranefusion/FusionPoreNucleationP.cpp +++ b/src/membranefusion/FusionPoreNucleationP.cpp @@ -27,10 +27,8 @@ along with plumed. If not, see . #endif #endif -namespace PLMD -{ -namespace membranefusion -{ +namespace PLMD { +namespace membranefusion { //+PLUMEDOC MEMBRANEFUSIONMOD_COLVAR FUSIONPORENUCLEATIONP /* A CV for inducing the nucleation of the fusion pore from a hemifusion stalk. @@ -74,8 +72,7 @@ PRINT ARG=fusionPoreNucleation FILE=COLVAR STRIDE=1 */ //+ENDPLUMEDOC -class fusionPoreNucleationP : public Colvar -{ +class fusionPoreNucleationP : public Colvar { std::vector UMEM, LMEM, TAILS, WATERS, POXYGENS; std::vector NSMEM, DSMEM, HMEM, NS, DS, HCH, RCYL, ZETA, ONEOVERS2C2CUTOFF, XCYL, YCYL; @@ -87,8 +84,7 @@ class fusionPoreNucleationP : public Colvar PLUMED_REGISTER_ACTION(fusionPoreNucleationP, "FUSIONPORENUCLEATIONP") -void fusionPoreNucleationP::registerKeywords(Keywords &keys) -{ +void fusionPoreNucleationP::registerKeywords(Keywords &keys) { Colvar::registerKeywords(keys); keys.add("atoms", "UMEMBRANE", "all the beads of the upper membrane."); keys.add("atoms", "LMEMBRANE", "all the beads of the lower membrane."); @@ -109,111 +105,130 @@ void fusionPoreNucleationP::registerKeywords(Keywords &keys) keys.setValueDescription("the value of the CV"); } -fusionPoreNucleationP::fusionPoreNucleationP(const ActionOptions &ao) : PLUMED_COLVAR_INIT(ao) -{ +fusionPoreNucleationP::fusionPoreNucleationP(const ActionOptions &ao) : PLUMED_COLVAR_INIT(ao) { parseAtomList("UMEMBRANE", UMEM); - if (UMEM.size() == 0) + if (UMEM.size() == 0) { error("UMEMBRANE has not any atom specified."); + } parseAtomList("LMEMBRANE", LMEM); - if (LMEM.size() == 0) + if (LMEM.size() == 0) { error("LMEMBRANE has not any atom specified."); + } parseAtomList("TAILS", TAILS); - if (TAILS.size() == 0) + if (TAILS.size() == 0) { error("TAILS has not any atom specified."); + } parseAtomList("WATERS", WATERS); - if (WATERS.size() == 0) + if (WATERS.size() == 0) { error("WATERS has not any atom specified."); + } parseAtomList("PHOSPHATEOXYGENS", POXYGENS); - if (POXYGENS.size() == 0) + if (POXYGENS.size() == 0) { error("PHOSPHATEOXYGENS has not any atom specified."); + } parseVector("NSMEM", NSMEM); - if (NSMEM.size() > 1) + if (NSMEM.size() > 1) { error("NSMEM cannot take more than one value."); + } parseVector("DSMEM", DSMEM); - if (DSMEM.size() > 1) + if (DSMEM.size() > 1) { error("DSMEM cannot take more than one value."); - if (DSMEM.size() == 0) + } + if (DSMEM.size() == 0) { DSMEM.push_back(0.1); + } parseVector("HMEM", HMEM); - if (HMEM.size() > 1) + if (HMEM.size() > 1) { error("HMEM cannot take more than one value."); - if (HMEM.size() == 0) + } + if (HMEM.size() == 0) { HMEM.push_back(0.25); + } parseVector("NS", NS); - if (NS.size() > 1) + if (NS.size() > 1) { error("NS cannot take more than one value."); + } parseVector("DS", DS); - if (DS.size() > 1) + if (DS.size() > 1) { error("DS cannot take more than one value."); - if (DS.size() == 0) + } + if (DS.size() == 0) { DS.push_back(0.25); + } parseVector("HCH", HCH); - if (HCH.size() > 1) + if (HCH.size() > 1) { error("H cannot take more than one value."); - if (HCH.size() == 0) + } + if (HCH.size() == 0) { HCH.push_back(0.25); + } parseVector("RCYL", RCYL); - if (RCYL.size() > 1) + if (RCYL.size() > 1) { error("RCYL cannot take more than one value."); - if (RCYL.size() == 0) + } + if (RCYL.size() == 0) { RCYL.push_back(0.8); + } parseVector("ZETA", ZETA); - if (ZETA.size() > 1) + if (ZETA.size() > 1) { error("ZETA cannot take more than one value."); - if (ZETA.size() == 0) + } + if (ZETA.size() == 0) { ZETA.push_back(0.75); + } parseVector("ONEOVERS2C2CUTOFF", ONEOVERS2C2CUTOFF); - if (ONEOVERS2C2CUTOFF.size() > 1) + if (ONEOVERS2C2CUTOFF.size() > 1) { error("ONEOVERS2C2CUTOFF cannot take more than one value."); - if (ONEOVERS2C2CUTOFF.size() == 0) + } + if (ONEOVERS2C2CUTOFF.size() == 0) { ONEOVERS2C2CUTOFF.push_back(500); + } parseVector("XCYL", XCYL); - if (XCYL.size() > 1) + if (XCYL.size() > 1) { error("XCYL cannot take more than one value."); - if (XCYL.size() == 0) + } + if (XCYL.size() == 0) { XCYL.push_back(-1.0); + } parseVector("YCYL", YCYL); - if (YCYL.size() > 1) + if (YCYL.size() > 1) { error("YCYL cannot take more than one value."); - if (YCYL.size() == 0) + } + if (YCYL.size() == 0) { YCYL.push_back(-1.0); + } checkRead(); std::vector atoms; - for (unsigned i = 0; i < UMEM.size(); i++) - { + for (unsigned i = 0; i < UMEM.size(); i++) { atoms.push_back(UMEM[i]); } - for (unsigned i = 0; i < LMEM.size(); i++) - { + for (unsigned i = 0; i < LMEM.size(); i++) { atoms.push_back(LMEM[i]); } - for (unsigned i = 0; i < TAILS.size(); i++) - { + for (unsigned i = 0; i < TAILS.size(); i++) { atoms.push_back(TAILS[i]); } - for (unsigned i = 0; i < WATERS.size(); i++) - { + for (unsigned i = 0; i < WATERS.size(); i++) { atoms.push_back(WATERS[i]); } - for (unsigned i = 0; i < POXYGENS.size(); i++) - { + for (unsigned i = 0; i < POXYGENS.size(); i++) { atoms.push_back(POXYGENS[i]); } @@ -222,8 +237,7 @@ fusionPoreNucleationP::fusionPoreNucleationP(const ActionOptions &ao) : PLUMED_C requestAtoms(atoms); } -void fusionPoreNucleationP::calculate() -{ +void fusionPoreNucleationP::calculate() { /************************* * * * System * @@ -241,8 +255,7 @@ void fusionPoreNucleationP::calculate() #pragma omp parallel for private(uMemAngle, lMemAngle) reduction(+:ZuMemcos, ZuMemsin, ZlMemcos, ZlMemsin) #endif #endif - for (unsigned i = 0; i < UMEM.size(); i++) - { + for (unsigned i = 0; i < UMEM.size(); i++) { uMemAngle = 2.0 * M_PI * getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i)))[2]; lMemAngle = 2.0 * M_PI * getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + UMEM.size())))[2]; ZuMemcos += cos(uMemAngle); @@ -321,48 +334,36 @@ void fusionPoreNucleationP::calculate() #pragma omp parallel for private(ZTailDistance, PositionS_Mem, s1_Mem, s2_Mem, TailPosition, x, aux) reduction(vec_double_plus:Fs_Mem, sx_Mem, sy_Mem, cx_Mem, cy_Mem) #endif #endif - for (unsigned i = 0; i < TAILS.size(); i++) - { + for (unsigned i = 0; i < TAILS.size(); i++) { ZTailDistance = pbcDistance(Vector(0.0, 0.0, ZMems), getPosition(i + membraneBeads))[2]; PositionS_Mem = (ZTailDistance + firstSliceZDist_Mem) / DSMEM[0]; // If the following condition is met the particle is in the Z space of the cylinder. - if ((PositionS_Mem >= (-0.5 - HMEM[0])) && (PositionS_Mem <= (NSMEM[0] + 0.5 - 1.0 + HMEM[0]))) - { + if ((PositionS_Mem >= (-0.5 - HMEM[0])) && (PositionS_Mem <= (NSMEM[0] + 0.5 - 1.0 + HMEM[0]))) { //Defining the slices to analyze each particle. - if (PositionS_Mem < 1) - { + if (PositionS_Mem < 1) { s1_Mem = 0; s2_Mem = 2; - } - else if (PositionS_Mem <= (NSMEM[0] - 2.0)) - { + } else if (PositionS_Mem <= (NSMEM[0] - 2.0)) { s1_Mem = floor(PositionS_Mem) - 1; s2_Mem = floor(PositionS_Mem) + 1; - } - else - { + } else { s1_Mem = NSMEM[0] - 3; s2_Mem = NSMEM[0] - 1; } TailPosition = getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + membraneBeads))); - for (unsigned s = s1_Mem; s <= s2_Mem; s++) - { + for (unsigned s = s1_Mem; s <= s2_Mem; s++) { x = (ZTailDistance - (s + 0.5 - NSMEM[0] / 2.0) * DSMEM[0]) * 2.0 / DSMEM[0]; - if (!((x <= -1.0 - HMEM[0]) || (x >= 1.0 + HMEM[0]))) - { - if (((-1.0 + HMEM[0]) <= x) && (x <= (1.0 - HMEM[0]))) - { + if (!((x <= -1.0 - HMEM[0]) || (x >= 1.0 + HMEM[0]))) { + if (((-1.0 + HMEM[0]) <= x) && (x <= (1.0 - HMEM[0]))) { faxial_Mem[i + TAILS.size() * s] = 1.0; Fs_Mem[s] += 1.0; sx_Mem[s] += sin(2.0 * M_PI * TailPosition[0]); sy_Mem[s] += sin(2.0 * M_PI * TailPosition[1]); cx_Mem[s] += cos(2.0 * M_PI * TailPosition[0]); cy_Mem[s] += cos(2.0 * M_PI * TailPosition[1]); - } - else if (((1.0 - HMEM[0]) < x) && (x < (1.0 + HMEM[0]))) - { + } else if (((1.0 - HMEM[0]) < x) && (x < (1.0 + HMEM[0]))) { aux = 0.5 - ((3.0 * x - 3.0) / (4.0 * HMEM[0])) + (pow((x - 1.0), 3) / (4.0 * pow(HMEM[0], 3))); faxial_Mem[i + TAILS.size() * s] = aux; Fs_Mem[s] += aux; @@ -370,9 +371,7 @@ void fusionPoreNucleationP::calculate() sy_Mem[s] += aux * sin(2.0 * M_PI * TailPosition[1]); cx_Mem[s] += aux * cos(2.0 * M_PI * TailPosition[0]); cy_Mem[s] += aux * cos(2.0 * M_PI * TailPosition[1]); - } - else if (((-1.0 - HMEM[0]) < x) && (x < (-1.0 + HMEM[0]))) - { + } else if (((-1.0 - HMEM[0]) < x) && (x < (-1.0 + HMEM[0]))) { aux = 0.5 + ((3.0 * x + 3.0) / (4.0 * HMEM[0])) - (pow((x + 1.0), 3) / (4.0 * pow(HMEM[0], 3))); faxial_Mem[i + TAILS.size() * s] = aux; Fs_Mem[s] += aux; @@ -386,10 +385,8 @@ void fusionPoreNucleationP::calculate() } } - for (unsigned s = 0; s < NSMEM[0]; s++) - { - if (Fs_Mem[s] != 0.0) - { + for (unsigned s = 0; s < NSMEM[0]; s++) { + if (Fs_Mem[s] != 0.0) { ws_Mem[s] = tanh(Fs_Mem[s]); W_Mem += ws_Mem[s]; sx_Mem[s] = sx_Mem[s] / Fs_Mem[s]; @@ -411,13 +408,10 @@ void fusionPoreNucleationP::calculate() // Eq. 12 Hub & Awasthi JCTC 2017. double Xcyl_Mem, Ycyl_Mem; - if ((XCYL[0] > 0.0) && (YCYL[0] > 0.0)) - { + if ((XCYL[0] > 0.0) && (YCYL[0] > 0.0)) { Xcyl_Mem = XCYL[0]; Ycyl_Mem = YCYL[0]; - } - else - { + } else { Xcyl_Mem = (atan2(-Xsc_Mem, -Xcc_Mem) + M_PI) * Lx / (2 * M_PI); Ycyl_Mem = (atan2(-Ysc_Mem, -Ycc_Mem) + M_PI) * Ly / (2 * M_PI); } @@ -496,57 +490,44 @@ void fusionPoreNucleationP::calculate() #pragma omp parallel for private(distCylinder, aux, condition1, condition2, condition3, ZMemDistance, PositionS, Position, x) reduction(vec_double_plus:Fs, sx, sy, cx, cy) #endif #endif - for (unsigned i = 0; i < chainBeads; i++) -{ + for (unsigned i = 0; i < chainBeads; i++) { distCylinder = pbcDistance(xyzCyl_Mem, pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + noChainBeads))); aux = sqrt(pow(distCylinder[0], 2) + pow(distCylinder[1], 2)); condition1 = ((aux / RCYLAVERAGE) < 1.0); condition2 = ((pbcDistance(Vector(0.0, 0.0, ZuMem), getPosition(i + noChainBeads))[2] > 0) && (aux / RCYLAVERAGE) < 2.0); condition3 = ((pbcDistance(getPosition(i + noChainBeads), Vector(0.0, 0.0, ZlMem))[2] > 0) && (aux / RCYLAVERAGE) < 2.0); - if (condition1 || condition2 || condition3) - { + if (condition1 || condition2 || condition3) { ZMemDistance = pbcDistance(Vector(0.0, 0.0, ZMems), getPosition(i + noChainBeads))[2]; PositionS = (ZMemDistance + firstSliceZDist) / DS[0]; // If the following condition is met the particle is in the Z space of the cylinder. - if ((PositionS >= (-0.5 - HCH[0])) && (PositionS <= (NS[0] + 0.5 - 1.0 + HCH[0]))) - { + if ((PositionS >= (-0.5 - HCH[0])) && (PositionS <= (NS[0] + 0.5 - 1.0 + HCH[0]))) { analyzeThisParticle[i] = 1.0; //Defining the slices to analyze each particle. - if (PositionS < 1) - { + if (PositionS < 1) { s1[i] = 0; s2[i] = 2; - } - else if (PositionS <= (NS[0] - 2.0)) - { + } else if (PositionS <= (NS[0] - 2.0)) { s1[i] = floor(PositionS) - 1; s2[i] = floor(PositionS) + 1; - } - else - { + } else { s1[i] = NS[0] - 3; s2[i] = NS[0] - 1; } Position = getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + noChainBeads))); - for (unsigned s = s1[i]; s <= s2[i]; s++) - { + for (unsigned s = s1[i]; s <= s2[i]; s++) { x = (ZMemDistance - (s + 0.5 - NS[0] / 2.0) * DS[0]) * 2.0 / DS[0]; - if (!((x <= -1.0 - HCH[0]) || (x >= 1.0 + HCH[0]))) - { - if (((-1.0 + HCH[0]) <= x) && (x <= (1.0 - HCH[0]))) - { + if (!((x <= -1.0 - HCH[0]) || (x >= 1.0 + HCH[0]))) { + if (((-1.0 + HCH[0]) <= x) && (x <= (1.0 - HCH[0]))) { faxial[i + chainBeads * s] = 1.0; Fs[s] += 1.0; sx[s] += sin(2.0 * M_PI * Position[0]); sy[s] += sin(2.0 * M_PI * Position[1]); cx[s] += cos(2.0 * M_PI * Position[0]); cy[s] += cos(2.0 * M_PI * Position[1]); - } - else if (((1.0 - HCH[0]) < x) && (x < (1.0 + HCH[0]))) - { + } else if (((1.0 - HCH[0]) < x) && (x < (1.0 + HCH[0]))) { aux = 0.5 - ((3.0 * x - 3.0) / (4.0 * HCH[0])) + (pow((x - 1.0), 3) / (4.0 * pow(HCH[0], 3))); faxial[i + chainBeads * s] = aux; d_faxial_dz[i + chainBeads * s] = ((-3.0 / (4.0 * HCH[0])) + ((3.0 * pow((x - 1), 2)) / (4.0 * pow(HCH[0], 3)))) * 2.0 / DS[0]; @@ -555,9 +536,7 @@ void fusionPoreNucleationP::calculate() sy[s] += aux * sin(2.0 * M_PI * Position[1]); cx[s] += aux * cos(2.0 * M_PI * Position[0]); cy[s] += aux * cos(2.0 * M_PI * Position[1]); - } - else if (((-1.0 - HCH[0]) < x) && (x < (-1.0 + HCH[0]))) - { + } else if (((-1.0 - HCH[0]) < x) && (x < (-1.0 + HCH[0]))) { aux = 0.5 + ((3.0 * x + 3.0) / (4.0 * HCH[0])) - (pow((x + 1.0), 3) / (4.0 * pow(HCH[0], 3))); faxial[i + chainBeads * s] = aux; d_faxial_dz[i + chainBeads * s] = ((3.0 / (4.0 * HCH[0])) - ((3.0 * pow((x + 1), 2)) / (4.0 * pow(HCH[0], 3)))) * 2.0 / DS[0]; @@ -573,10 +552,8 @@ void fusionPoreNucleationP::calculate() } } - for (unsigned s = 0; s < NS[0]; s++) - { - if (Fs[s] != 0.0) - { + for (unsigned s = 0; s < NS[0]; s++) { + if (Fs[s] != 0.0) { ws[s] = tanh(Fs[s]); W += ws[s]; sx[s] = sx[s] / Fs[s]; @@ -631,21 +608,15 @@ void fusionPoreNucleationP::calculate() // To avoid rare instabilities auxX and auxY are truncated at a configurable value (default 500). double auxX = (1 / (pow(Xsc, 2) + pow(Xcc, 2))), auxY = (1 / (pow(Ysc, 2) + pow(Ycc, 2))); - if (auxX > ONEOVERS2C2CUTOFF[0]) - { + if (auxX > ONEOVERS2C2CUTOFF[0]) { auxX = Lx * ONEOVERS2C2CUTOFF[0] / (2 * M_PI); - } - else - { + } else { auxX = Lx * auxX / (2 * M_PI); } - if (auxY > ONEOVERS2C2CUTOFF[0]) - { + if (auxY > ONEOVERS2C2CUTOFF[0]) { auxY = Ly * ONEOVERS2C2CUTOFF[0] / (2 * M_PI); - } - else - { + } else { auxY = Ly * auxY / (2 * M_PI); } @@ -666,11 +637,9 @@ void fusionPoreNucleationP::calculate() #pragma omp parallel for private(d_Xsc_dx,d_Xcc_dx,d_Ysc_dy,d_Ycc_dy,d_Xsc_dz,d_Xcc_dz,d_Ysc_dz,d_Ycc_dz,d_sx_dx,d_sy_dy,d_cx_dx,d_cy_dy,d_sx_dz,d_sy_dz,d_cx_dz,d_cy_dz,d_ws_dz,ri,x,fradial) reduction(vec_double_plus: Nsp, Axs, Ays) #endif #endif - for (unsigned i = 0; i < chainBeads; i++) -{ + for (unsigned i = 0; i < chainBeads; i++) { CylDistances[i] = pbcDistance(xyzCyl, pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + noChainBeads))); - if (analyzeThisParticle[i]) - { + if (analyzeThisParticle[i]) { Position = getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + noChainBeads))); d_Xsc_dx = 0.0; d_Xcc_dx = 0.0; @@ -680,10 +649,8 @@ void fusionPoreNucleationP::calculate() d_Xcc_dz = 0.0; d_Ysc_dz = 0.0; d_Ycc_dz = 0.0; - for (unsigned s = s1[i]; s <= s2[i]; s++) - { - if (Fs[s] != 0.0) - { + for (unsigned s = s1[i]; s <= s2[i]; s++) { + if (Fs[s] != 0.0) { d_sx_dx = faxial[i + chainBeads * s] * 2.0 * M_PI * cos(2.0 * M_PI * Position[0]) / (Lx * Fs[s]); d_sy_dy = faxial[i + chainBeads * s] * 2.0 * M_PI * cos(2.0 * M_PI * Position[1]) / (Ly * Fs[s]); d_cx_dx = -faxial[i + chainBeads * s] * 2.0 * M_PI * sin(2.0 * M_PI * Position[0]) / (Lx * Fs[s]); @@ -711,27 +678,20 @@ void fusionPoreNucleationP::calculate() ri = sqrt(pow(CylDistances[i][0], 2) + pow(CylDistances[i][1], 2)); x = ri / RCYL[0]; - if (!((x <= -1.0 - HCH[0]) || (x >= 1.0 + HCH[0]))) - { - if (((-1.0 + HCH[0]) <= x) && (x <= (1.0 - HCH[0]))) - { + if (!((x <= -1.0 - HCH[0]) || (x >= 1.0 + HCH[0]))) { + if (((-1.0 + HCH[0]) <= x) && (x <= (1.0 - HCH[0]))) { fradial = 1.0; - } - else if (((1.0 - HCH[0]) < x) && (x < (1.0 + HCH[0]))) - { + } else if (((1.0 - HCH[0]) < x) && (x < (1.0 + HCH[0]))) { fradial = 0.5 - ((3.0 * x - 3.0) / (4.0 * HCH[0])) + (pow((x - 1.0), 3) / (4.0 * pow(HCH[0], 3))); d_fradial_dx[i] = ((-3.0 / (4.0 * HCH[0])) + ((3.0 * pow((x - 1), 2)) / (4.0 * pow(HCH[0], 3)))) * CylDistances[i][0] / (RCYL[0] * ri); d_fradial_dy[i] = ((-3.0 / (4.0 * HCH[0])) + ((3.0 * pow((x - 1), 2)) / (4.0 * pow(HCH[0], 3)))) * CylDistances[i][1] / (RCYL[0] * ri); - } - else if (((-1.0 - HCH[0]) < x) && (x < (-1.0 + HCH[0]))) - { + } else if (((-1.0 - HCH[0]) < x) && (x < (-1.0 + HCH[0]))) { fradial = 0.5 + ((3.0 * x + 3.0) / (4.0 * HCH[0])) - (pow((x + 1.0), 3) / (4.0 * pow(HCH[0], 3))); d_fradial_dx[i] = ((3.0 / (4.0 * HCH[0])) - ((3.0 * pow((x + 1), 2)) / (4.0 * pow(HCH[0], 3)))) * CylDistances[i][0] / (RCYL[0] * ri); d_fradial_dy[i] = ((3.0 / (4.0 * HCH[0])) - ((3.0 * pow((x + 1), 2)) / (4.0 * pow(HCH[0], 3)))) * CylDistances[i][1] / (RCYL[0] * ri); } - for (unsigned s = s1[i]; s <= s2[i]; s++) - { + for (unsigned s = s1[i]; s <= s2[i]; s++) { Nsp[s] += fradial * faxial[i + chainBeads * s]; Axs[s] += faxial[i + chainBeads * s] * d_fradial_dx[i]; Ays[s] += faxial[i + chainBeads * s] * d_fradial_dy[i]; @@ -741,16 +701,12 @@ void fusionPoreNucleationP::calculate() } } - for (unsigned s = 0; s < NS[0]; s++) - { - if (Nsp[s] <= 1.0) - { + for (unsigned s = 0; s < NS[0]; s++) { + if (Nsp[s] <= 1.0) { psi[s] = ZETA[0] * Nsp[s]; d_psi[s] = ZETA[0]; Xi_n += psi[s]; - } - else - { + } else { psi[s] = 1.0 - c * exp(-b * Nsp[s]); d_psi[s] = b * c * exp(-b * Nsp[s]); Xi_n += psi[s]; @@ -770,22 +726,17 @@ void fusionPoreNucleationP::calculate() #pragma omp parallel for private(aux) #endif #endif - for (unsigned i = 0; i < chainBeads; i++) -{ - if (analyzeThisParticle[i]) - { - for (unsigned s = s1[i]; s <= s2[i]; s++) - { - if (faxial[i + chainBeads * s]) - { + for (unsigned i = 0; i < chainBeads; i++) { + if (analyzeThisParticle[i]) { + for (unsigned s = s1[i]; s <= s2[i]; s++) { + if (faxial[i + chainBeads * s]) { faxial_d_fradial_dx[i + chainBeads * s] = faxial[i + chainBeads * s] * d_fradial_dx[i] - d_Xcyl_dx[i] * Axs[s]; faxial_d_fradial_dy[i + chainBeads * s] = faxial[i + chainBeads * s] * d_fradial_dy[i] - d_Ycyl_dy[i] * Ays[s]; faxial_d_fradial_dz[i + chainBeads * s] = -d_Xcyl_dz[i] * Axs[s] - d_Ycyl_dz[i] * Ays[s]; } } - for (unsigned s = s1[i]; s <= s2[i]; s++) - { + for (unsigned s = s1[i]; s <= s2[i]; s++) { aux = d_psi[s] / NS[0]; derivatives_Chain[i][0] += aux * faxial_d_fradial_dx[i + chainBeads * s]; derivatives_Chain[i][1] += aux * faxial_d_fradial_dy[i + chainBeads * s]; @@ -795,8 +746,7 @@ void fusionPoreNucleationP::calculate() } Tensor virial; - for (unsigned i = 0; i < chainBeads; i++) -{ + for (unsigned i = 0; i < chainBeads; i++) { setAtomsDerivatives((i + noChainBeads), derivatives_Chain[i]); virial -= Tensor(CylDistances[i], derivatives_Chain[i]); } diff --git a/src/membranefusion/MemFusionP.cpp b/src/membranefusion/MemFusionP.cpp index b4351a0ae8..16e21980f5 100644 --- a/src/membranefusion/MemFusionP.cpp +++ b/src/membranefusion/MemFusionP.cpp @@ -27,10 +27,8 @@ along with plumed. If not, see . #endif #endif -namespace PLMD -{ -namespace membranefusion -{ +namespace PLMD { +namespace membranefusion { //+PLUMEDOC MEMBRANEFUSIONMOD_COLVAR MEMFUSIONP /* Calculate a CV that can induce the formation of the hemifusion stalk between two initially flat and planar bilayers. @@ -75,8 +73,7 @@ You can test this CV with another example in this
1) + if (NSMEM.size() > 1) { error("NSMEM cannot take more than one value."); + } parseVector("DSMEM", DSMEM); - if (DSMEM.size() > 1) + if (DSMEM.size() > 1) { error("DSMEM cannot take more than one value."); - if (DSMEM.size() == 0) + } + if (DSMEM.size() == 0) { DSMEM.push_back(0.1); + } parseVector("HMEM", HMEM); - if (HMEM.size() > 1) + if (HMEM.size() > 1) { error("HMEM cannot take more than one value."); - if (HMEM.size() == 0) + } + if (HMEM.size() == 0) { HMEM.push_back(0.25); + } parseVector("RCYLMEM", RCYLMEM); - if (RCYLMEM.size() > 1) + if (RCYLMEM.size() > 1) { error("RCYLMEM cannot take more than one value."); - if (RCYLMEM.size() == 0) + } + if (RCYLMEM.size() == 0) { RCYLMEM.push_back(1.75); + } parseVector("ZETAMEM", ZETAMEM); - if (ZETAMEM.size() > 1) + if (ZETAMEM.size() > 1) { error("ZETA cannot take more than one value."); - if (ZETAMEM.size() == 0) + } + if (ZETAMEM.size() == 0) { ZETAMEM.push_back(0.5); + } parseVector("ONEOVERS2C2CUTOFF", ONEOVERS2C2CUTOFF); - if (ONEOVERS2C2CUTOFF.size() > 1) + if (ONEOVERS2C2CUTOFF.size() > 1) { error("ONEOVERS2C2CUTOFF cannot take more than one value."); - if (ONEOVERS2C2CUTOFF.size() == 0) + } + if (ONEOVERS2C2CUTOFF.size() == 0) { ONEOVERS2C2CUTOFF.push_back(500); + } parseVector("XCYL", XCYL); - if (XCYL.size() > 1) + if (XCYL.size() > 1) { error("XCYL cannot take more than one value."); - if (XCYL.size() == 0) + } + if (XCYL.size() == 0) { XCYL.push_back(-1.0); + } parseVector("YCYL", YCYL); - if (YCYL.size() > 1) + if (YCYL.size() > 1) { error("YCYL cannot take more than one value."); - if (YCYL.size() == 0) + } + if (YCYL.size() == 0) { YCYL.push_back(-1.0); + } checkRead(); std::vector atoms; - for (unsigned i = 0; i < UMEM.size(); i++) - { + for (unsigned i = 0; i < UMEM.size(); i++) { atoms.push_back(UMEM[i]); } - for (unsigned i = 0; i < LMEM.size(); i++) - { + for (unsigned i = 0; i < LMEM.size(); i++) { atoms.push_back(LMEM[i]); } - for (unsigned i = 0; i < TAILS.size(); i++) - { + for (unsigned i = 0; i < TAILS.size(); i++) { atoms.push_back(TAILS[i]); } @@ -186,8 +196,7 @@ memFusionP::memFusionP(const ActionOptions &ao) : PLUMED_COLVAR_INIT(ao) requestAtoms(atoms); } -void memFusionP::calculate() -{ +void memFusionP::calculate() { /************************** * * * System * @@ -205,8 +214,7 @@ void memFusionP::calculate() #pragma omp parallel for private(uMemAngle, lMemAngle) reduction(+:ZuMemcos, ZuMemsin, ZlMemcos, ZlMemsin) #endif #endif - for (unsigned i = 0; i < UMEM.size(); i++) - { + for (unsigned i = 0; i < UMEM.size(); i++) { uMemAngle = 2.0 * M_PI * getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i)))[2]; lMemAngle = 2.0 * M_PI * getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + UMEM.size())))[2]; ZuMemcos += cos(uMemAngle); @@ -294,49 +302,37 @@ void memFusionP::calculate() #pragma omp parallel for private(ZTailDistance, PositionS_Mem, TailPosition, x, aux) reduction(vec_double_plus:Fs_Mem, sx_Mem, sy_Mem, cx_Mem, cy_Mem) #endif #endif - for (unsigned i = 0; i < TAILS.size(); i++) - { + for (unsigned i = 0; i < TAILS.size(); i++) { ZTailDistance = pbcDistance(Vector(0.0, 0.0, ZMems), getPosition(i + membraneBeads))[2]; PositionS_Mem = (ZTailDistance + firstSliceZDist_Mem) / DSMEM[0]; // If the following condition is met the particle is in the Z space of the cylinder. - if ((PositionS_Mem >= (-0.5 - HMEM[0])) && (PositionS_Mem <= (NSMEM[0] + 0.5 - 1.0 + HMEM[0]))) - { + if ((PositionS_Mem >= (-0.5 - HMEM[0])) && (PositionS_Mem <= (NSMEM[0] + 0.5 - 1.0 + HMEM[0]))) { analyzeThisParticle_Mem[i] = 1.0; // Defining the slices to analyze each particle. - if (PositionS_Mem < 1) - { + if (PositionS_Mem < 1) { s1_Mem[i] = 0; s2_Mem[i] = 2; - } - else if (PositionS_Mem <= (NSMEM[0] - 2.0)) - { + } else if (PositionS_Mem <= (NSMEM[0] - 2.0)) { s1_Mem[i] = floor(PositionS_Mem) - 1; s2_Mem[i] = floor(PositionS_Mem) + 1; - } - else - { + } else { s1_Mem[i] = NSMEM[0] - 3; s2_Mem[i] = NSMEM[0] - 1; } TailPosition = getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + membraneBeads))); - for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) - { + for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) { x = (ZTailDistance - (s + 0.5 - NSMEM[0] / 2.0) * DSMEM[0]) * 2.0 / DSMEM[0]; - if (!((x <= -1.0 - HMEM[0]) || (x >= 1.0 + HMEM[0]))) - { - if (((-1.0 + HMEM[0]) <= x) && (x <= (1.0 - HMEM[0]))) - { + if (!((x <= -1.0 - HMEM[0]) || (x >= 1.0 + HMEM[0]))) { + if (((-1.0 + HMEM[0]) <= x) && (x <= (1.0 - HMEM[0]))) { faxial_Mem[i + TAILS.size() * s] = 1.0; Fs_Mem[s] += 1.0; sx_Mem[s] += sin(2.0 * M_PI * TailPosition[0]); sy_Mem[s] += sin(2.0 * M_PI * TailPosition[1]); cx_Mem[s] += cos(2.0 * M_PI * TailPosition[0]); cy_Mem[s] += cos(2.0 * M_PI * TailPosition[1]); - } - else if (((1.0 - HMEM[0]) < x) && (x < (1.0 + HMEM[0]))) - { + } else if (((1.0 - HMEM[0]) < x) && (x < (1.0 + HMEM[0]))) { aux = 0.5 - ((3.0 * x - 3.0) / (4.0 * HMEM[0])) + (pow((x - 1.0), 3) / (4.0 * pow(HMEM[0], 3))); faxial_Mem[i + TAILS.size() * s] = aux; d_faxial_Mem_dz[i + TAILS.size() * s] = ((-3.0 / (4.0 * HMEM[0])) + ((3.0 * pow((x - 1), 2)) / (4.0 * pow(HMEM[0], 3)))) * 2.0 / DSMEM[0]; @@ -345,9 +341,7 @@ void memFusionP::calculate() sy_Mem[s] += aux * sin(2.0 * M_PI * TailPosition[1]); cx_Mem[s] += aux * cos(2.0 * M_PI * TailPosition[0]); cy_Mem[s] += aux * cos(2.0 * M_PI * TailPosition[1]); - } - else if (((-1.0 - HMEM[0]) < x) && (x < (-1.0 + HMEM[0]))) - { + } else if (((-1.0 - HMEM[0]) < x) && (x < (-1.0 + HMEM[0]))) { aux = 0.5 + ((3.0 * x + 3.0) / (4.0 * HMEM[0])) - (pow((x + 1.0), 3) / (4.0 * pow(HMEM[0], 3))); faxial_Mem[i + TAILS.size() * s] = aux; d_faxial_Mem_dz[i + TAILS.size() * s] = ((3.0 / (4.0 * HMEM[0])) - ((3.0 * pow((x + 1), 2)) / (4.0 * pow(HMEM[0], 3)))) * 2.0 / DSMEM[0]; @@ -362,10 +356,8 @@ void memFusionP::calculate() } } - for (unsigned s = 0; s < NSMEM[0]; s++) - { - if (Fs_Mem[s] != 0.0) - { + for (unsigned s = 0; s < NSMEM[0]; s++) { + if (Fs_Mem[s] != 0.0) { ws_Mem[s] = tanh(Fs_Mem[s]); W_Mem += ws_Mem[s]; sx_Mem[s] = sx_Mem[s] / Fs_Mem[s]; @@ -387,13 +379,10 @@ void memFusionP::calculate() // Eq. 12 Hub & Awasthi JCTC 2017. double Xcyl_Mem, Ycyl_Mem; - if ((XCYL[0] > 0.0) && (YCYL[0] > 0.0)) - { + if ((XCYL[0] > 0.0) && (YCYL[0] > 0.0)) { Xcyl_Mem = XCYL[0]; Ycyl_Mem = YCYL[0]; - } - else - { + } else { Xcyl_Mem = (atan2(-Xsc_Mem, -Xcc_Mem) + M_PI) * Lx / (2 * M_PI); Ycyl_Mem = (atan2(-Ysc_Mem, -Ycc_Mem) + M_PI) * Ly / (2 * M_PI); } @@ -428,21 +417,15 @@ void memFusionP::calculate() // To avoid rare instabilities auxX_Mem and auxY_Mem are truncated at a configurable value (default = 500). double auxX_Mem = (1 / (pow(Xsc_Mem, 2) + pow(Xcc_Mem, 2))), auxY_Mem = (1 / (pow(Ysc_Mem, 2) + pow(Ycc_Mem, 2))); - if (auxX_Mem > ONEOVERS2C2CUTOFF[0]) - { + if (auxX_Mem > ONEOVERS2C2CUTOFF[0]) { auxX_Mem = Lx * ONEOVERS2C2CUTOFF[0] / (2 * M_PI); - } - else - { + } else { auxX_Mem = Lx * auxX_Mem / (2 * M_PI); } - if (auxY_Mem > ONEOVERS2C2CUTOFF[0]) - { + if (auxY_Mem > ONEOVERS2C2CUTOFF[0]) { auxY_Mem = Ly * ONEOVERS2C2CUTOFF[0] / (2 * M_PI); - } - else - { + } else { auxY_Mem = Ly * auxY_Mem / (2 * M_PI); } @@ -466,10 +449,8 @@ void memFusionP::calculate() #pragma omp parallel for private(TailPosition,d_Xsc_Mem_dx,d_Xcc_Mem_dx,d_Ysc_Mem_dy,d_Ycc_Mem_dy,d_Xsc_Mem_dz,d_Xcc_Mem_dz,d_Ysc_Mem_dz,d_Ycc_Mem_dz,d_sx_Mem_dx,d_sy_Mem_dy,d_cx_Mem_dx,d_cy_Mem_dy,d_sx_Mem_dz,d_sy_Mem_dz,d_cx_Mem_dz,d_cy_Mem_dz,d_ws_Mem_dz,ri_Mem,x,fradial_Mem) reduction(vec_double_plus: Nsp_Mem, Axs_Mem, Ays_Mem) #endif #endif - for (unsigned i = 0; i < TAILS.size(); i++) - { - if (analyzeThisParticle_Mem[i]) - { + for (unsigned i = 0; i < TAILS.size(); i++) { + if (analyzeThisParticle_Mem[i]) { TailPosition = getPbc().realToScaled(pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + membraneBeads))); d_Xsc_Mem_dx = 0.0; d_Xcc_Mem_dx = 0.0; @@ -479,10 +460,8 @@ void memFusionP::calculate() d_Xcc_Mem_dz = 0.0; d_Ysc_Mem_dz = 0.0; d_Ycc_Mem_dz = 0.0; - for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) - { - if (Fs_Mem[s] != 0.0) - { + for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) { + if (Fs_Mem[s] != 0.0) { d_sx_Mem_dx = faxial_Mem[i + TAILS.size() * s] * 2.0 * M_PI * cos(2.0 * M_PI * TailPosition[0]) / (Lx * Fs_Mem[s]); d_sy_Mem_dy = faxial_Mem[i + TAILS.size() * s] * 2.0 * M_PI * cos(2.0 * M_PI * TailPosition[1]) / (Ly * Fs_Mem[s]); d_cx_Mem_dx = -faxial_Mem[i + TAILS.size() * s] * 2.0 * M_PI * sin(2.0 * M_PI * TailPosition[0]) / (Lx * Fs_Mem[s]); @@ -511,27 +490,20 @@ void memFusionP::calculate() CylDistances_Mem[i] = pbcDistance(xyzCyl_Mem, pbcDistance(Vector(0.0, 0.0, 0.0), getPosition(i + membraneBeads))); ri_Mem = sqrt(pow(CylDistances_Mem[i][0], 2) + pow(CylDistances_Mem[i][1], 2)); x = ri_Mem / RCYLMEM[0]; - if (!((x <= -1.0 - HMEM[0]) || (x >= 1.0 + HMEM[0]))) - { - if (((-1.0 + HMEM[0]) <= x) && (x <= (1.0 - HMEM[0]))) - { + if (!((x <= -1.0 - HMEM[0]) || (x >= 1.0 + HMEM[0]))) { + if (((-1.0 + HMEM[0]) <= x) && (x <= (1.0 - HMEM[0]))) { fradial_Mem = 1.0; - } - else if (((1.0 - HMEM[0]) < x) && (x < (1.0 + HMEM[0]))) - { + } else if (((1.0 - HMEM[0]) < x) && (x < (1.0 + HMEM[0]))) { fradial_Mem = 0.5 - ((3.0 * x - 3.0) / (4.0 * HMEM[0])) + (pow((x - 1.0), 3) / (4.0 * pow(HMEM[0], 3))); d_fradial_Mem_dx[i] = ((-3.0 / (4.0 * HMEM[0])) + ((3.0 * pow((x - 1), 2)) / (4.0 * pow(HMEM[0], 3)))) * CylDistances_Mem[i][0] / (RCYLMEM[0] * ri_Mem); d_fradial_Mem_dy[i] = ((-3.0 / (4.0 * HMEM[0])) + ((3.0 * pow((x - 1), 2)) / (4.0 * pow(HMEM[0], 3)))) * CylDistances_Mem[i][1] / (RCYLMEM[0] * ri_Mem); - } - else if (((-1.0 - HMEM[0]) < x) && (x < (-1.0 + HMEM[0]))) - { + } else if (((-1.0 - HMEM[0]) < x) && (x < (-1.0 + HMEM[0]))) { fradial_Mem = 0.5 + ((3.0 * x + 3.0) / (4.0 * HMEM[0])) - (pow((x + 1.0), 3) / (4.0 * pow(HMEM[0], 3))); d_fradial_Mem_dx[i] = ((3.0 / (4.0 * HMEM[0])) - ((3.0 * pow((x + 1), 2)) / (4.0 * pow(HMEM[0], 3)))) * CylDistances_Mem[i][0] / (RCYLMEM[0] * ri_Mem); d_fradial_Mem_dy[i] = ((3.0 / (4.0 * HMEM[0])) - ((3.0 * pow((x + 1), 2)) / (4.0 * pow(HMEM[0], 3)))) * CylDistances_Mem[i][1] / (RCYLMEM[0] * ri_Mem); } - for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) - { + for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) { Nsp_Mem[s] += fradial_Mem * faxial_Mem[i + TAILS.size() * s]; Axs_Mem[s] += faxial_Mem[i + TAILS.size() * s] * d_fradial_Mem_dx[i]; Ays_Mem[s] += faxial_Mem[i + TAILS.size() * s] * d_fradial_Mem_dy[i]; @@ -541,16 +513,12 @@ void memFusionP::calculate() } } - for (unsigned s = 0; s < NSMEM[0]; s++) - { - if (Nsp_Mem[s] <= 1.0) - { + for (unsigned s = 0; s < NSMEM[0]; s++) { + if (Nsp_Mem[s] <= 1.0) { psi_Mem[s] = ZETAMEM[0] * Nsp_Mem[s]; d_psi_Mem[s] = ZETAMEM[0]; Xi_Mem += psi_Mem[s]; - } - else - { + } else { psi_Mem[s] = 1.0 - c_Mem * exp(-b_Mem * Nsp_Mem[s]); d_psi_Mem[s] = b_Mem * c_Mem * exp(-b_Mem * Nsp_Mem[s]); Xi_Mem += psi_Mem[s]; @@ -570,22 +538,17 @@ void memFusionP::calculate() #pragma omp parallel for private(aux) #endif #endif - for (unsigned i = 0; i < TAILS.size(); i++) - { - if (analyzeThisParticle_Mem[i]) - { - for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) - { - if (faxial_Mem[i + TAILS.size() * s]) - { + for (unsigned i = 0; i < TAILS.size(); i++) { + if (analyzeThisParticle_Mem[i]) { + for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) { + if (faxial_Mem[i + TAILS.size() * s]) { faxial_Mem_d_fradial_Mem_dx[i + TAILS.size() * s] = faxial_Mem[i + TAILS.size() * s] * d_fradial_Mem_dx[i] - d_Xcyl_Mem_dx[i] * Axs_Mem[s]; faxial_Mem_d_fradial_Mem_dy[i + TAILS.size() * s] = faxial_Mem[i + TAILS.size() * s] * d_fradial_Mem_dy[i] - d_Ycyl_Mem_dy[i] * Ays_Mem[s]; faxial_Mem_d_fradial_Mem_dz[i + TAILS.size() * s] = -d_Xcyl_Mem_dz[i] * Axs_Mem[s] - d_Ycyl_Mem_dz[i] * Ays_Mem[s]; } } - for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) - { + for (unsigned s = s1_Mem[i]; s <= s2_Mem[i]; s++) { aux = d_psi_Mem[s] / NSMEM[0]; derivatives_Mem[i][0] += aux * faxial_Mem_d_fradial_Mem_dx[i + TAILS.size() * s]; derivatives_Mem[i][1] += aux * faxial_Mem_d_fradial_Mem_dy[i + TAILS.size() * s]; @@ -596,8 +559,7 @@ void memFusionP::calculate() // Derivatives and virial for the Xi_Mem. Tensor virial; - for (unsigned i = 0; i < TAILS.size(); i++) - { + for (unsigned i = 0; i < TAILS.size(); i++) { setAtomsDerivatives((i + membraneBeads), derivatives_Mem[i]); virial -= Tensor(CylDistances_Mem[i], derivatives_Mem[i]); } diff --git a/src/multicolvar/AlphaBeta.cpp b/src/multicolvar/AlphaBeta.cpp index dce98504fe..ad4d3bb3b9 100644 --- a/src/multicolvar/AlphaBeta.cpp +++ b/src/multicolvar/AlphaBeta.cpp @@ -60,43 +60,74 @@ void AlphaBeta::registerKeywords(Keywords& keys) { keys.add("numbered","COEFFICIENT","the coefficient for each of the torsional angles. If you use a single COEFFICIENT value the " "same reference value is used for all torsional angles"); keys.setValueDescription("the alpha beta CV"); - keys.needsAction("CONSTANT"); keys.needsAction("TORSION"); keys.needsAction("COMBINE"); keys.needsAction("CUSTOM"); keys.needsAction("SUM"); + keys.needsAction("CONSTANT"); + keys.needsAction("TORSION"); + keys.needsAction("COMBINE"); + keys.needsAction("CUSTOM"); + keys.needsAction("SUM"); } AlphaBeta::AlphaBeta(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read in the reference value - std::string refstr; parse("REFERENCE",refstr); unsigned nref=0; + std::string refstr; + parse("REFERENCE",refstr); + unsigned nref=0; if( refstr.length()==0 ) { for(unsigned i=0;; ++i) { std::string refval; - if( !parseNumbered( "REFERENCE", i+1, refval ) ) break; - if( i==0 ) refstr = refval; else refstr += "," + refval; + if( !parseNumbered( "REFERENCE", i+1, refval ) ) { + break; + } + if( i==0 ) { + refstr = refval; + } else { + refstr += "," + refval; + } nref++; } } - std::string coeffstr; parse("COEFFICIENT",coeffstr); unsigned ncoeff=0; + std::string coeffstr; + parse("COEFFICIENT",coeffstr); + unsigned ncoeff=0; if( coeffstr.length()==0 ) { for(unsigned i=0;; ++i) { std::string coeff; - if( !parseNumbered( "COEFFICIENT", i+1, coeff) ) break; - if( i==0 ) coeffstr = coeff; else coeffstr += "," + coeff; + if( !parseNumbered( "COEFFICIENT", i+1, coeff) ) { + break; + } + if( i==0 ) { + coeffstr = coeff; + } else { + coeffstr += "," + coeff; + } ncoeff++; } } - if( coeffstr.length()==0 ) coeffstr="1"; + if( coeffstr.length()==0 ) { + coeffstr="1"; + } // Calculate angles readInputLine( getShortcutLabel() + "_torsions: TORSION " + convertInputLineToString() ); ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_torsions" ); plumed_assert( av && (av->copyOutput(0))->getRank()==1 ); if( nref==0 ) { - std::string refval=refstr; for(unsigned i=1; i<(av->copyOutput(0))->getShape()[0]; ++i) refstr += "," + refval; - } else if( nref!=(av->copyOutput(0))->getShape()[0] ) error("mismatch between number of reference values and number of ATOMS specified"); + std::string refval=refstr; + for(unsigned i=1; i<(av->copyOutput(0))->getShape()[0]; ++i) { + refstr += "," + refval; + } + } else if( nref!=(av->copyOutput(0))->getShape()[0] ) { + error("mismatch between number of reference values and number of ATOMS specified"); + } if( ncoeff==0 ) { - std::string coeff=coeffstr; for(unsigned i=1; i<(av->copyOutput(0))->getShape()[0]; ++i) coeffstr += "," + coeff; - } else if( ncoeff!=(av->copyOutput(0))->getShape()[0] ) error("mismatch between number of coefficients and number of ATOMS specified"); + std::string coeff=coeffstr; + for(unsigned i=1; i<(av->copyOutput(0))->getShape()[0]; ++i) { + coeffstr += "," + coeff; + } + } else if( ncoeff!=(av->copyOutput(0))->getShape()[0] ) { + error("mismatch between number of coefficients and number of ATOMS specified"); + } readInputLine( getShortcutLabel() + "_ref: CONSTANT VALUES=" + refstr ); readInputLine( getShortcutLabel() + "_coeff: CONSTANT VALUES=" + coeffstr ); // Caculate difference from reference using combine diff --git a/src/multicolvar/Angles.cpp b/src/multicolvar/Angles.cpp index d035dc28df..e42bd04522 100644 --- a/src/multicolvar/Angles.cpp +++ b/src/multicolvar/Angles.cpp @@ -109,57 +109,83 @@ void Angles::registerKeywords( Keywords& keys ) { "GROUPC are calculated. The GROUPA atoms are assumed to be the central " "atoms"); keys.add("optional","SWITCH","the switching function specifies that only those bonds that have a length that is less than a certain threshold are considered"); - MultiColvarShortcuts::shortcutKeywords( keys ); keys.needsAction("ANGLE"); keys.needsAction("COORD_ANGLES"); + MultiColvarShortcuts::shortcutKeywords( keys ); + keys.needsAction("ANGLE"); + keys.needsAction("COORD_ANGLES"); } Angles::Angles(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - std::string swit; parse("SWITCH",swit); + ActionShortcut(ao) { + std::string swit; + parse("SWITCH",swit); if( swit.length()>0 ) { - std::string cat, grp; parse("GROUPA",cat); parse("GROUPB",grp); - if( cat.length()==0 || grp.length()==0 ) error("must use GROUPA/GROUPB when using SWITCH"); + std::string cat, grp; + parse("GROUPA",cat); + parse("GROUPB",grp); + if( cat.length()==0 || grp.length()==0 ) { + error("must use GROUPA/GROUPB when using SWITCH"); + } readInputLine( getShortcutLabel() + ": COORD_ANGLES SWITCH={" + swit + "} CATOMS=" + cat + " GROUP=" + grp + " " + convertInputLineToString() ); return; } - std::vector group; parseVector("GROUP",group); - std::vector groupa; parseVector("GROUPA",groupa); - std::vector groupb; parseVector("GROUPB",groupb); - std::vector groupc; parseVector("GROUPC",groupc); + std::vector group; + parseVector("GROUP",group); + std::vector groupa; + parseVector("GROUPA",groupa); + std::vector groupb; + parseVector("GROUPB",groupb); + std::vector groupc; + parseVector("GROUPC",groupc); if( group.size()>0 ) { - if( groupa.size()>0 || groupb.size()>0 || groupc.size()>0 ) error("should only be GROUP keyword in input not GROUPA/GROUPB/GROUPC"); - Tools::interpretRanges( group ); std::string ainput = getShortcutLabel() + ": ANGLE"; unsigned n=1; + if( groupa.size()>0 || groupb.size()>0 || groupc.size()>0 ) { + error("should only be GROUP keyword in input not GROUPA/GROUPB/GROUPC"); + } + Tools::interpretRanges( group ); + std::string ainput = getShortcutLabel() + ": ANGLE"; + unsigned n=1; // Not sure if this triple sum makes any sense for(unsigned i=2; i0 ) { - Tools::interpretRanges( groupa ); Tools::interpretRanges( groupb ); Tools::interpretRanges( groupc ); - unsigned n=1; std::string ainput = getShortcutLabel() + ": ANGLE"; + Tools::interpretRanges( groupa ); + Tools::interpretRanges( groupb ); + Tools::interpretRanges( groupc ); + unsigned n=1; + std::string ainput = getShortcutLabel() + ": ANGLE"; for(unsigned i=0; i0 ) { - Tools::interpretRanges( groupa ); Tools::interpretRanges( groupb ); - unsigned n=1; std::string ainput; ainput = getShortcutLabel() + ": ANGLE"; + Tools::interpretRanges( groupa ); + Tools::interpretRanges( groupb ); + unsigned n=1; + std::string ainput; + ainput = getShortcutLabel() + ": ANGLE"; for(unsigned i=0; i catoms; parseVector("CATOMS",catoms); Tools::interpretRanges(catoms); + std::vector catoms; + parseVector("CATOMS",catoms); + Tools::interpretRanges(catoms); // Parse the coordination sphere - std::vector group; parseVector("GROUP",group); Tools::interpretRanges(group); + std::vector group; + parseVector("GROUP",group); + Tools::interpretRanges(group); // Create the list of atoms - std::string atlist; unsigned k=1; + std::string atlist; + unsigned k=1; for(unsigned i=0; i keymap; readShortcutKeywords( keys, keymap ); if( do_mean ) keymap.insert(std::pair("SUM","")); + Keywords keys; + MultiColvarShortcuts::shortcutKeywords( keys ); + pruneShortcuts( keys ); + bool do_mean; + parseFlag("MEAN",do_mean); + std::map keymap; + readShortcutKeywords( keys, keymap ); + if( do_mean ) { + keymap.insert(std::pair("SUM","")); + } MultiColvarShortcuts::expandFunctions( getShortcutLabel(), getShortcutLabel() + "_angles", getShortcutLabel() + "_wmat", keymap, this ); if( do_mean ) { readInputLine( getShortcutLabel() + "_denom: SUM ARG=" + getShortcutLabel() + "_wmat PERIODIC=NO"); diff --git a/src/multicolvar/Dihcor.cpp b/src/multicolvar/Dihcor.cpp index bb0c4c3ee2..d4bacd1210 100644 --- a/src/multicolvar/Dihcor.cpp +++ b/src/multicolvar/Dihcor.cpp @@ -89,7 +89,8 @@ PLUMED_REGISTER_ACTION(Dihcor,"DIHCOR") void Dihcor::registerKeywords( Keywords& keys ) { ActionShortcut::registerKeywords( keys ); - keys.needsAction("DIHEDRAL_CORRELATION"); keys.needsAction("SUM"); + keys.needsAction("DIHEDRAL_CORRELATION"); + keys.needsAction("SUM"); keys.add("atoms","ATOMS","the set of 8 atoms that are being used each of the dihedral correlation values"); keys.addFlag("NOPBC",false,"ignore the periodic boundary conditions when calculating distances"); keys.setValueDescription("the sum of all the dihedral correlations"); @@ -97,8 +98,7 @@ void Dihcor::registerKeywords( Keywords& keys ) { Dihcor::Dihcor(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { readInputLine( getShortcutLabel() +"_data: DIHEDRAL_CORRELATION " + convertInputLineToString() ); readInputLine( getShortcutLabel() + ": SUM ARG=" + getShortcutLabel() + "_data PERIODIC=NO"); } diff --git a/src/multicolvar/Distances.cpp b/src/multicolvar/Distances.cpp index 4975f3c963..09c797304f 100644 --- a/src/multicolvar/Distances.cpp +++ b/src/multicolvar/Distances.cpp @@ -202,77 +202,137 @@ void Distances::registerKeywords(Keywords& keys) { keys.addFlag("COMPONENTS",false,"calculate the x, y and z components of the distance separately and store them as label.x, label.y and label.z"); keys.addFlag("SCALED_COMPONENTS",false,"calculate the a, b and c scaled components of the distance separately and store them as label.a, label.b and label.c"); keys.addFlag("LOWMEM",false,"this flag does nothing and is present only to ensure back-compatibility"); - keys.reset_style("ATOMS","atoms"); MultiColvarShortcuts::shortcutKeywords( keys ); + keys.reset_style("ATOMS","atoms"); + MultiColvarShortcuts::shortcutKeywords( keys ); keys.add("atoms","ORIGIN","calculate the distance of all the atoms specified using the ATOMS keyword from this point"); keys.add("numbered","LOCATION","the location at which the CV is assumed to be in space"); keys.reset_style("LOCATION","atoms"); keys.addOutputComponent("x","COMPONENTS","the x-components of the distance vectors"); keys.addOutputComponent("y","COMPONENTS","the y-components of the distance vectors"); keys.addOutputComponent("z","COMPONENTS","the z-components of the distance vectors"); - keys.needsAction("GROUP"); keys.needsAction("DISTANCE"); keys.needsAction("CENTER"); + keys.needsAction("GROUP"); + keys.needsAction("DISTANCE"); + keys.needsAction("CENTER"); } Distances::Distances(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Create distances - bool lowmem; parseFlag("LOWMEM",lowmem); - if( lowmem ) warning("LOWMEM flag is deprecated and is no longer required for this action"); + bool lowmem; + parseFlag("LOWMEM",lowmem); + if( lowmem ) { + warning("LOWMEM flag is deprecated and is no longer required for this action"); + } std::string dline = getShortcutLabel() + ": DISTANCE"; - bool nopbc; parseFlag("NOPBC",nopbc); if( nopbc ) dline += " NOPBC"; + bool nopbc; + parseFlag("NOPBC",nopbc); + if( nopbc ) { + dline += " NOPBC"; + } if( getName()=="DISTANCES" ) { - bool comp; parseFlag("COMPONENTS",comp); if( comp ) dline += " COMPONENTS"; - bool scomp; parseFlag("SCALED_COMPONENTS",scomp); if( scomp ) dline += " SCALED_COMPONENTS"; - } else dline += " COMPONENTS"; + bool comp; + parseFlag("COMPONENTS",comp); + if( comp ) { + dline += " COMPONENTS"; + } + bool scomp; + parseFlag("SCALED_COMPONENTS",scomp); + if( scomp ) { + dline += " SCALED_COMPONENTS"; + } + } else { + dline += " COMPONENTS"; + } // Parse origin - std::string num, ostr; parse("ORIGIN",ostr); + std::string num, ostr; + parse("ORIGIN",ostr); if( ostr.length()>0 ) { // Parse atoms - std::vector afstr; MultiColvarShortcuts::parseAtomList("ATOMS",afstr,this); - for(unsigned i=0; i afstr; + MultiColvarShortcuts::parseAtomList("ATOMS",afstr,this); + for(unsigned i=0; i grp; MultiColvarShortcuts::parseAtomList("GROUP",grp,this); - std::vector grpa; MultiColvarShortcuts::parseAtomList("GROUPA",grpa,this); + std::vector grp; + MultiColvarShortcuts::parseAtomList("GROUP",grp,this); + std::vector grpa; + MultiColvarShortcuts::parseAtomList("GROUPA",grpa,this); if( grp.size()>0 ) { - if( grpa.size()>0 ) error("should not be using GROUPA in tandem with GROUP"); + if( grpa.size()>0 ) { + error("should not be using GROUPA in tandem with GROUP"); + } unsigned n=0; for(unsigned i=1; i0 ) { - std::vector grpb; MultiColvarShortcuts::parseAtomList("GROUPB",grpb,this); - if( grpb.size()==0 ) error("found GROUPA but no corresponding GROUPB"); - std::string grpstr = getShortcutLabel() + "_grp: GROUP ATOMS="; bool printcomment=false; + std::vector grpb; + MultiColvarShortcuts::parseAtomList("GROUPB",grpb,this); + if( grpb.size()==0 ) { + error("found GROUPA but no corresponding GROUPB"); + } + std::string grpstr = getShortcutLabel() + "_grp: GROUP ATOMS="; + bool printcomment=false; for(unsigned i=0; i str_atomsA; parseVector("VECTORSTART",str_atomsA); Tools::interpretRanges( str_atomsA ); - std::vector str_atomsB; parseVector("VECTOREND",str_atomsB); Tools::interpretRanges( str_atomsB ); - std::vector str_atomsC; parseVector("GROUP",str_atomsC); Tools::interpretRanges( str_atomsC ); - unsigned n=1; std::string dinput= getShortcutLabel() + "_dis: DISTANCE", ainput = getShortcutLabel() + "_ang: ANGLE"; + ActionShortcut(ao) { + std::vector str_atomsA; + parseVector("VECTORSTART",str_atomsA); + Tools::interpretRanges( str_atomsA ); + std::vector str_atomsB; + parseVector("VECTOREND",str_atomsB); + Tools::interpretRanges( str_atomsB ); + std::vector str_atomsC; + parseVector("GROUP",str_atomsC); + Tools::interpretRanges( str_atomsC ); + unsigned n=1; + std::string dinput= getShortcutLabel() + "_dis: DISTANCE", ainput = getShortcutLabel() + "_ang: ANGLE"; for(unsigned i=0; i keymap; readShortcutKeywords( keymap, action ); expandFunctions( labout, argin, weights, keymap, action ); + std::map keymap; + readShortcutKeywords( keymap, action ); + expandFunctions( labout, argin, weights, keymap, action ); } void MultiColvarShortcuts::readShortcutKeywords( std::map& keymap, ActionShortcut* action ) { - Keywords keys; shortcutKeywords( keys ); action->readShortcutKeywords( keys, keymap ); + Keywords keys; + shortcutKeywords( keys ); + action->readShortcutKeywords( keys, keymap ); } void MultiColvarShortcuts::parseAtomList( const std::string& key, std::vector& atoms, ActionShortcut* action ) { - std::vector astr; action->parseVector(key,astr); if( astr.size()==0 ) return ; + std::vector astr; + action->parseVector(key,astr); + if( astr.size()==0 ) { + return ; + } Tools::interpretRanges( astr ); for(unsigned i=0; iplumed.getActionSet().selectWithLabel(astr[i]); if( mygr ) { std::vector grstr( mygr->getGroupAtoms() ); - for(unsigned j=0; jplumed.getActionSet().selectWithLabel(astr[i] + "_grp"); if( mygr2 ) { std::vector grstr( mygr2->getGroupAtoms() ); - for(unsigned j=0; j& keymap, ActionShortcut* action ) { - if( keymap.empty() ) return; + if( keymap.empty() ) { + return; + } // Parse LESS_THAN if( keymap.count("LESS_THAN") ) { std::string sum_arg = labout + "_lt", lt_string = keymap.find("LESS_THAN")->second; @@ -110,8 +132,11 @@ void MultiColvarShortcuts::expandFunctions( const std::string& labout, const std } if( keymap.count("LESS_THAN1") ) { for(unsigned i=1;; ++i) { - std::string istr; Tools::convert( i, istr ); - if( !keymap.count("LESS_THAN" + istr ) ) { break; } + std::string istr; + Tools::convert( i, istr ); + if( !keymap.count("LESS_THAN" + istr ) ) { + break; + } std::string sum_arg = labout + "_lt" + istr, lt_string1 = keymap.find("LESS_THAN" + istr)->second; action->readInputLine( labout + "_lt" + istr + ": LESS_THAN ARG=" + argin + " SWITCH={" + lt_string1 + "}"); if( weights.length()>0 ) { @@ -133,8 +158,11 @@ void MultiColvarShortcuts::expandFunctions( const std::string& labout, const std } if( keymap.count("MORE_THAN1") ) { for(unsigned i=1;; ++i) { - std::string istr; Tools::convert( i, istr ); - if( !keymap.count("MORE_THAN" + istr ) ) { break; } + std::string istr; + Tools::convert( i, istr ); + if( !keymap.count("MORE_THAN" + istr ) ) { + break; + } std::string sum_arg = labout + "_mt" + istr, mt_string1 = keymap.find("MORE_THAN" + istr)->second; action->readInputLine( labout + "_mt" + istr + ": MORE_THAN ARG=" + argin + " SWITCH={" + mt_string1 + "}"); if( weights.length()>0 ) { @@ -146,9 +174,12 @@ void MultiColvarShortcuts::expandFunctions( const std::string& labout, const std } // Parse ALT_MIN if( keymap.count("ALT_MIN") ) { - if( weights.length()>0 ) plumed_merror("cannot use ALT_MIN with this shortcut"); + if( weights.length()>0 ) { + plumed_merror("cannot use ALT_MIN with this shortcut"); + } std::string amin_string = keymap.find("ALT_MIN")->second; - std::size_t dd = amin_string.find("BETA"); std::string beta_str = amin_string.substr(dd+5); + std::size_t dd = amin_string.find("BETA"); + std::string beta_str = amin_string.substr(dd+5); beta_str.erase(std::remove_if(beta_str.begin(), beta_str.end(), ::isspace), beta_str.end()); action->readInputLine( labout + "_me_altmin: CUSTOM ARG=" + argin + " FUNC=exp(-x*" + beta_str + ") PERIODIC=NO"); action->readInputLine( labout + "_mec_altmin: SUM ARG=" + labout + "_me_altmin PERIODIC=NO"); @@ -156,9 +187,12 @@ void MultiColvarShortcuts::expandFunctions( const std::string& labout, const std } // Parse MIN if( keymap.count("MIN") ) { - if( weights.length()>0 ) plumed_merror("cannot use MIN with this shortcut"); + if( weights.length()>0 ) { + plumed_merror("cannot use MIN with this shortcut"); + } std::string min_string = keymap.find("MIN")->second; - std::size_t dd = min_string.find("BETA"); std::string beta_str = min_string.substr(dd+5); + std::size_t dd = min_string.find("BETA"); + std::string beta_str = min_string.substr(dd+5); beta_str.erase(std::remove_if(beta_str.begin(), beta_str.end(), ::isspace), beta_str.end()); action->readInputLine( labout + "_me_min: CUSTOM ARG=" + argin + " FUNC=exp(" + beta_str + "/x) PERIODIC=NO"); action->readInputLine( labout + "_mec_min: SUM ARG=" + labout + "_me_min PERIODIC=NO"); @@ -166,9 +200,12 @@ void MultiColvarShortcuts::expandFunctions( const std::string& labout, const std } // Parse MAX if( keymap.count("MAX") ) { - if( weights.length()>0 ) plumed_merror("cannot use MAX with this shortcut"); + if( weights.length()>0 ) { + plumed_merror("cannot use MAX with this shortcut"); + } std::string max_string = keymap.find("MAX")->second; - std::size_t dd = max_string.find("BETA"); std::string beta_str = max_string.substr(dd+5); + std::size_t dd = max_string.find("BETA"); + std::string beta_str = max_string.substr(dd+5); beta_str.erase(std::remove_if(beta_str.begin(), beta_str.end(), ::isspace), beta_str.end()); action->readInputLine( labout + "_me_max: CUSTOM ARG=" + argin + " FUNC=exp(x/" + beta_str + ") PERIODIC=NO"); action->readInputLine( labout + "_mec_max: SUM ARG=" + labout + "_me_max PERIODIC=NO"); @@ -176,12 +213,16 @@ void MultiColvarShortcuts::expandFunctions( const std::string& labout, const std } // Parse HIGHEST if( keymap.count("HIGHEST") ) { - if( weights.length()>0 ) plumed_merror("cannot use HIGHEST with this shortcut"); + if( weights.length()>0 ) { + plumed_merror("cannot use HIGHEST with this shortcut"); + } action->readInputLine( labout + "_highest: HIGHEST ARG=" + argin ); } // Parse LOWEST if( keymap.count("LOWEST") ) { - if( weights.length()>0 ) plumed_merror("cannot use LOWEST with this shortcut"); + if( weights.length()>0 ) { + plumed_merror("cannot use LOWEST with this shortcut"); + } action->readInputLine( labout + "_lowest: LOWEST ARG=" + argin ); } // Parse SUM @@ -195,7 +236,9 @@ void MultiColvarShortcuts::expandFunctions( const std::string& labout, const std } // Parse MEAN if( keymap.count("MEAN") ) { - if( weights.length()>0 ) plumed_merror("cannot use MEAN with this shortcut"); + if( weights.length()>0 ) { + plumed_merror("cannot use MEAN with this shortcut"); + } action->readInputLine( labout + "_mean: MEAN ARG=" + argin + " PERIODIC=NO"); } // Parse BETWEEN @@ -211,8 +254,11 @@ void MultiColvarShortcuts::expandFunctions( const std::string& labout, const std std::string bt_string1; if( keymap.count("BETWEEN1") ) { for(unsigned i=1;; ++i) { - std::string istr; Tools::convert( i, istr ); - if( !keymap.count("BETWEEN" + istr) ) break; + std::string istr; + Tools::convert( i, istr ); + if( !keymap.count("BETWEEN" + istr) ) { + break; + } std::string sum_arg=labout + "_bt" + istr, bt_string1 = keymap.find("BETWEEN" + istr)->second; action->readInputLine( labout + "_bt" + istr + ": BETWEEN ARG=" + argin + " SWITCH={" + bt_string1 + "}" ); if( weights.length()>0 ) { @@ -225,18 +271,35 @@ void MultiColvarShortcuts::expandFunctions( const std::string& labout, const std // Parse HISTOGRAM if( keymap.count("HISTOGRAM") ) { std::vector words=Tools::getWords( keymap.find("HISTOGRAM")->second ); - unsigned nbins; bool found=Tools::parse(words,"NBINS",nbins,0); // Need replica index - if( !found ) plumed_merror("did not find NBINS in specification for HISTOGRAM"); - double lower; found=Tools::parse(words,"LOWER",lower,0); - if( !found ) plumed_merror("did not find LOWER in specification for HISTOGRAM"); - double upper; found=Tools::parse(words,"UPPER",upper,0); - if( !found ) plumed_merror("did not find UPPER in specification for HISTOGRAM"); + unsigned nbins; + bool found=Tools::parse(words,"NBINS",nbins,0); // Need replica index + if( !found ) { + plumed_merror("did not find NBINS in specification for HISTOGRAM"); + } + double lower; + found=Tools::parse(words,"LOWER",lower,0); + if( !found ) { + plumed_merror("did not find LOWER in specification for HISTOGRAM"); + } + double upper; + found=Tools::parse(words,"UPPER",upper,0); + if( !found ) { + plumed_merror("did not find UPPER in specification for HISTOGRAM"); + } double delr = ( upper - lower ) / static_cast( nbins ); - double smear=0.5; found=Tools::parse(words,"SMEAR",smear,0); - if( !found ) smear = 0.5; + double smear=0.5; + found=Tools::parse(words,"SMEAR",smear,0); + if( !found ) { + smear = 0.5; + } for(unsigned i=0; ireadInputLine( labout + "_bt" + istr + ": BETWEEN ARG=" + argin + " SWITCH={" + words[0] + " LOWER=" + low_str + " UPPER=" + high_str + " SMEAR=" + smstr + "}"); if( weights.length()>0 ) { sum_arg = labout + "_wbt" + istr; diff --git a/src/multicolvar/Planes.cpp b/src/multicolvar/Planes.cpp index e6dd5948cb..d60268b54f 100644 --- a/src/multicolvar/Planes.cpp +++ b/src/multicolvar/Planes.cpp @@ -59,31 +59,53 @@ void PlaneShortcut::registerKeywords( Keywords& keys ) { keys.addOutputComponent("_vmean","VMEAN","the norm of the mean vector"); keys.addFlag("VSUM",false,"calculate the norm of the sum of all the vectors"); keys.addOutputComponent("_vsum","VSUM","the norm of the mean vector"); - keys.needsAction("CENTER"); keys.needsAction("GROUP"); keys.needsAction("PLANE"); - keys.needsAction("MEAN"); keys.needsAction("SUM"); keys.needsAction("COMBINE"); keys.needsAction("CUSTOM"); + keys.needsAction("CENTER"); + keys.needsAction("GROUP"); + keys.needsAction("PLANE"); + keys.needsAction("MEAN"); + keys.needsAction("SUM"); + keys.needsAction("COMBINE"); + keys.needsAction("CUSTOM"); } PlaneShortcut::PlaneShortcut(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - bool vmean, vsum; parseFlag("VMEAN",vmean); parseFlag("VSUM",vsum); std::string dline; + ActionShortcut(ao) { + bool vmean, vsum; + parseFlag("VMEAN",vmean); + parseFlag("VSUM",vsum); + std::string dline; std::string grpstr = getShortcutLabel() + "_grp: GROUP ATOMS="; for(unsigned i=1;; ++i) { - std::string atstring; parseNumbered("ATOMS",i,atstring); - if( atstring.length()==0 ) break; - std::string locstr; parseNumbered("LOCATION",i,locstr); + std::string atstring; + parseNumbered("ATOMS",i,atstring); + if( atstring.length()==0 ) { + break; + } + std::string locstr; + parseNumbered("LOCATION",i,locstr); if( locstr.length()==0 ) { - std::string num; Tools::convert( i, num ); + std::string num; + Tools::convert( i, num ); readInputLine( getShortcutLabel() + "_vatom" + num + ": CENTER ATOMS=" + atstring ); - if( i==1 ) grpstr += getShortcutLabel() + "_vatom" + num; else grpstr += "," + getShortcutLabel() + "_vatom" + num; + if( i==1 ) { + grpstr += getShortcutLabel() + "_vatom" + num; + } else { + grpstr += "," + getShortcutLabel() + "_vatom" + num; + } } else { - if( i==1 ) grpstr += locstr; else grpstr += "," + locstr; + if( i==1 ) { + grpstr += locstr; + } else { + grpstr += "," + locstr; + } } - std::string num; Tools::convert( i, num ); + std::string num; + Tools::convert( i, num ); dline += " ATOMS" + num + "=" + atstring; } - readInputLine( grpstr ); readInputLine( getShortcutLabel() + ": PLANE " + dline + " " + convertInputLineToString() ); + readInputLine( grpstr ); + readInputLine( getShortcutLabel() + ": PLANE " + dline + " " + convertInputLineToString() ); if( vmean ) { readInputLine( getShortcutLabel() + "_xs: MEAN ARG=" + getShortcutLabel() + ".x PERIODIC=NO"); readInputLine( getShortcutLabel() + "_ys: MEAN ARG=" + getShortcutLabel() + ".y PERIODIC=NO"); diff --git a/src/multicolvar/Torsions.cpp b/src/multicolvar/Torsions.cpp index 406c89b6ff..2b461ced4a 100644 --- a/src/multicolvar/Torsions.cpp +++ b/src/multicolvar/Torsions.cpp @@ -78,14 +78,14 @@ class Torsions : public ActionShortcut { PLUMED_REGISTER_ACTION(Torsions,"TORSIONS") void Torsions::registerKeywords(Keywords& keys) { - ActionShortcut::registerKeywords( keys ); MultiColvarShortcuts::shortcutKeywords( keys ); + ActionShortcut::registerKeywords( keys ); + MultiColvarShortcuts::shortcutKeywords( keys ); keys.needsAction("TORSION"); } Torsions::Torsions(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { log.printf("Action TORSION\n"); log.printf(" with label %s \n", getShortcutLabel().c_str() ); readInputLine( getShortcutLabel() + ": TORSION " + convertInputLineToString() ); diff --git a/src/multicolvar/UWalls.cpp b/src/multicolvar/UWalls.cpp index fd5487d10b..0a88a46378 100644 --- a/src/multicolvar/UWalls.cpp +++ b/src/multicolvar/UWalls.cpp @@ -64,9 +64,9 @@ void UWalls::registerKeywords(Keywords& keys) { UWalls::UWalls(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - std::string data; parse("DATA",data); + ActionShortcut(ao) { + std::string data; + parse("DATA",data); readInputLine( getShortcutLabel() + ": UPPER_WALLS ARG=" + data + " " + convertInputLineToString() ); } diff --git a/src/multicolvar/XAngle.cpp b/src/multicolvar/XAngle.cpp index 63775f2b13..90bfacce8c 100644 --- a/src/multicolvar/XAngle.cpp +++ b/src/multicolvar/XAngle.cpp @@ -67,20 +67,26 @@ PLUMED_REGISTER_ACTION(XAngle,"ZANGLES") void XAngle::registerKeywords(Keywords& keys) { ActionShortcut::registerKeywords( keys ); keys.add("numbered","ATOMS","the pairs of atoms that you would like to calculate the angles for"); - keys.reset_style("ATOMS","atoms"); MultiColvarShortcuts::shortcutKeywords( keys ); - keys.needsAction("DISTANCE"); keys.needsAction("COMBINE"); keys.needsAction("CUSTOM"); + keys.reset_style("ATOMS","atoms"); + MultiColvarShortcuts::shortcutKeywords( keys ); + keys.needsAction("DISTANCE"); + keys.needsAction("COMBINE"); + keys.needsAction("CUSTOM"); } XAngle::XAngle(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Create distances std::string dline = getShortcutLabel() + "_dists: DISTANCE COMPONENTS"; for(unsigned i=1;; ++i) { - std::string atstring; parseNumbered("ATOMS",i,atstring); - if( atstring.length()==0 ) break; - std::string num; Tools::convert( i, num ); + std::string atstring; + parseNumbered("ATOMS",i,atstring); + if( atstring.length()==0 ) { + break; + } + std::string num; + Tools::convert( i, num ); dline += " ATOMS" + num + "=" + atstring; } readInputLine( dline ); @@ -91,9 +97,15 @@ XAngle::XAngle(const ActionOptions& ao): readInputLine( getShortcutLabel() + "_norm_y: CUSTOM ARG=" + getShortcutLabel() + "_dists.y," + getShortcutLabel() + "_norm FUNC=x/y PERIODIC=NO"); readInputLine( getShortcutLabel() + "_norm_z: CUSTOM ARG=" + getShortcutLabel() + "_dists.z," + getShortcutLabel() + "_norm FUNC=x/y PERIODIC=NO"); // Now compute the angles with matheval - if( getName()=="XANGLES" ) readInputLine( getShortcutLabel() + "_ang: CUSTOM FUNC=acos(x) PERIODIC=NO ARG=" + getShortcutLabel() + "_norm_x"); - if( getName()=="YANGLES" ) readInputLine( getShortcutLabel() + "_ang: CUSTOM FUNC=acos(x) PERIODIC=NO ARG=" + getShortcutLabel() + "_norm_y"); - if( getName()=="ZANGLES" ) readInputLine( getShortcutLabel() + "_ang: CUSTOM FUNC=acos(x) PERIODIC=NO ARG=" + getShortcutLabel() + "_norm_z"); + if( getName()=="XANGLES" ) { + readInputLine( getShortcutLabel() + "_ang: CUSTOM FUNC=acos(x) PERIODIC=NO ARG=" + getShortcutLabel() + "_norm_x"); + } + if( getName()=="YANGLES" ) { + readInputLine( getShortcutLabel() + "_ang: CUSTOM FUNC=acos(x) PERIODIC=NO ARG=" + getShortcutLabel() + "_norm_y"); + } + if( getName()=="ZANGLES" ) { + readInputLine( getShortcutLabel() + "_ang: CUSTOM FUNC=acos(x) PERIODIC=NO ARG=" + getShortcutLabel() + "_norm_z"); + } // Add shortcuts to label MultiColvarShortcuts::expandFunctions( getShortcutLabel(), getShortcutLabel() + "_ang", "", this ); } diff --git a/src/multicolvar/XYTorsions.cpp b/src/multicolvar/XYTorsions.cpp index 61de8b50d5..0390835f31 100644 --- a/src/multicolvar/XYTorsions.cpp +++ b/src/multicolvar/XYTorsions.cpp @@ -96,14 +96,15 @@ PLUMED_REGISTER_ACTION(XYTorsions,"ZYTORSIONS") void XYTorsions::registerKeywords(Keywords& keys) { ActionShortcut::registerKeywords( keys ); keys.add("numbered","ATOMS","the pairs of atoms that you would like to calculate the angles for"); - keys.reset_style("ATOMS","atoms"); MultiColvarShortcuts::shortcutKeywords( keys ); - keys.needsAction("FIXEDATOM"); keys.needsAction("TORSION"); + keys.reset_style("ATOMS","atoms"); + MultiColvarShortcuts::shortcutKeywords( keys ); + keys.needsAction("FIXEDATOM"); + keys.needsAction("TORSION"); } XYTorsions::XYTorsions(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { std::string vdir = getShortcutLabel() + "_vec2," + getShortcutLabel() + "_origin"; std::string adir = getShortcutLabel() + "_axis," + getShortcutLabel() + "_origin"; // Create action for position of origin @@ -136,9 +137,13 @@ XYTorsions::XYTorsions(const ActionOptions& ao): // Now create action to compute all torsions std::string torsions_str = getShortcutLabel() + ": TORSION"; for(unsigned i=1;; ++i) { - std::string atstring; parseNumbered("ATOMS",i,atstring); - if( atstring.length()==0 ) break; - std::string num; Tools::convert( i, num ); + std::string atstring; + parseNumbered("ATOMS",i,atstring); + if( atstring.length()==0 ) { + break; + } + std::string num; + Tools::convert( i, num ); torsions_str += " VECTORA" + num + "=" + atstring + " VECTORB" + num + "=" + vdir + " AXIS" + num + "=" + adir; } readInputLine( torsions_str ); diff --git a/src/opes/ECVcustom.cpp b/src/opes/ECVcustom.cpp index 8e87f18b5c..21d14094d0 100644 --- a/src/opes/ECVcustom.cpp +++ b/src/opes/ECVcustom.cpp @@ -59,8 +59,7 @@ opes: OPES_EXPANDED ARG=ecv.* PACE=500 //+ENDPLUMEDOC class ECVcustom : - public ExpansionCVs -{ + public ExpansionCVs { private: unsigned P0_contribution_; double barrier_; @@ -84,8 +83,7 @@ class ECVcustom : PLUMED_REGISTER_ACTION(ECVcustom,"ECV_CUSTOM") -void ECVcustom::registerKeywords(Keywords& keys) -{ +void ECVcustom::registerKeywords(Keywords& keys) { ExpansionCVs::registerKeywords(keys); keys.remove("ARG"); keys.add("compulsory","ARG","the labels of the single ECVs. Delta U_i, in energy units"); @@ -97,21 +95,22 @@ void ECVcustom::registerKeywords(Keywords& keys) ECVcustom::ECVcustom(const ActionOptions&ao) : Action(ao) , ExpansionCVs(ao) - , beta0_(1./kbt_) -{ + , beta0_(1./kbt_) { //set beta0_ bool dimensionless; parseFlag("DIMENSIONLESS",dimensionless); - if(dimensionless) + if(dimensionless) { beta0_=1; + } //set P0_contribution_ bool add_P0=false; parseFlag("ADD_P0",add_P0); - if(add_P0) + if(add_P0) { P0_contribution_=1; - else + } else { P0_contribution_=0; + } //set barrier_ barrier_=std::numeric_limits::infinity(); @@ -123,106 +122,105 @@ ECVcustom::ECVcustom(const ActionOptions&ao) totNumECVs_=getNumberOfArguments()+P0_contribution_; ECVs_.resize(getNumberOfArguments(),std::vector(totNumECVs_)); derECVs_.resize(getNumberOfArguments(),std::vector(totNumECVs_)); - for(unsigned j=0; j::infinity()) - { + } + if(barrier_!=std::numeric_limits::infinity()) { log.printf(" guess for free energy BARRIER = %g\n",barrier_); - if(dimensionless) + if(dimensionless) { log.printf(" also the BARRIER is considered to be DIMENSIONLESS\n"); + } } - if(P0_contribution_==1) + if(P0_contribution_==1) { log.printf(" -- ADD_P0: the target includes also the unbiased probability itself\n"); + } } -void ECVcustom::calculateECVs(const double * cv) -{ - for(unsigned j=0; j > ECVcustom::getIndex_k() const -{ +std::vector< std::vector > ECVcustom::getIndex_k() const { plumed_massert(isReady_ && totNumECVs_>0,"cannot access getIndex_k() of ECV before initialization"); std::vector< std::vector > index_k(totNumECVs_,std::vector(getNumberOfArguments())); for(unsigned k=0; k ECVcustom::getLambdas() const -{ +std::vector ECVcustom::getLambdas() const { std::vector lambdas(totNumECVs_); - if(P0_contribution_==1) - { + if(P0_contribution_==1) { std::ostringstream subs; subs<<"P0"; - for(unsigned j=1; j(this)->getPntrToArgument(kk)->getName(); - else + } else { subs<<"NaN"; - for(unsigned j=1; j(this)->getPntrToArgument(kk)->getName(); - else + } else { subs<<"_NaN"; + } } lambdas[k]=subs.str(); } return lambdas; } -void ECVcustom::initECVs() -{ +void ECVcustom::initECVs() { plumed_massert(!isReady_,"initialization should not be called twice"); isReady_=true; log.printf(" *%4u ECVs for %s\n",totNumECVs_,getName().c_str()); } -void ECVcustom::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) -{ +void ECVcustom::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) { initECVs(); calculateECVs(&all_obs_cvs[index_j]); - for(unsigned j=0; j& lambdas) -{ +void ECVcustom::initECVs_restart(const std::vector& lambdas) { std::size_t pos=0; - for(unsigned j=0; jlambdas[0].length(),"this should not happen, more '_' than expected in "+getName()); diff --git a/src/opes/ECVlinear.cpp b/src/opes/ECVlinear.cpp index 48650d607d..852877363d 100644 --- a/src/opes/ECVlinear.cpp +++ b/src/opes/ECVlinear.cpp @@ -70,8 +70,7 @@ Notice that by defauly LAMBDA=0, LAMBDA_MIN=0 and LAMBDA_MAX=1, which is the typ //+ENDPLUMEDOC class ECVlinear : - public ExpansionCVs -{ + public ExpansionCVs { private: bool todoAutomatic_; bool geom_spacing_; @@ -94,8 +93,7 @@ class ECVlinear : PLUMED_REGISTER_ACTION(ECVlinear,"ECV_LINEAR") -void ECVlinear::registerKeywords(Keywords& keys) -{ +void ECVlinear::registerKeywords(Keywords& keys) { ExpansionCVs::registerKeywords(keys); keys.remove("ARG"); keys.add("compulsory","ARG","the label of the Hamiltonian difference. Delta U"); @@ -112,15 +110,15 @@ ECVlinear::ECVlinear(const ActionOptions&ao) : Action(ao) , ExpansionCVs(ao) , todoAutomatic_(false) - , beta0_(1./kbt_) -{ + , beta0_(1./kbt_) { plumed_massert(getNumberOfArguments()==1,"only DeltaU should be given as ARG"); //set beta0_ bool dimensionless; parseFlag("DIMENSIONLESS",dimensionless); - if(dimensionless) + if(dimensionless) { beta0_=1; + } //parse lambda info parse("LAMBDA",lambda0_); @@ -138,28 +136,26 @@ ECVlinear::ECVlinear(const ActionOptions&ao) checkRead(); //set the diff vector using lambdas - if(lambdas.size()>0) - { + if(lambdas.size()>0) { plumed_massert(lambda_steps==0,"cannot set both LAMBDA_STEPS and LAMBDA_SET_ALL"); plumed_massert(lambda_min==myNone && lambda_max==myNone,"cannot set both LAMBDA_SET_ALL and LAMBDA_MIN/MAX"); plumed_massert(lambdas.size()>=2,"set at least 2 lambdas with LAMBDA_SET_ALL"); - for(unsigned k=0; k0) + } + if(lambda_steps>0) { derECVs_=getSteps(derECVs_[0],derECVs_[1],lambda_steps,"LAMBDA",geom_spacing_,beta0_*lambda0_); - else + } else { todoAutomatic_=true; + } } - if(lambda0_lambda_max) + if(lambda0_lambda_max) { log.printf(" +++ WARNING +++ running at LAMBDA=%g which is outside the chosen lambda range\n",lambda0_); + } //print some info log.printf(" running at LAMBDA=%g\n",lambda0_); log.printf(" targeting a lambda range from LAMBDA_MIN=%g to LAMBDA_MAX=%g\n",lambda_min,lambda_max); - if(dimensionless) + if(dimensionless) { log.printf(" -- DIMENSIONLESS: the ARG is not multiplied by beta\n"); - if(geom_spacing_) + } + if(geom_spacing_) { log.printf(" -- GEOM_SPACING: lambdas will be geometrically spaced\n"); + } } -void ECVlinear::calculateECVs(const double * DeltaU) -{ - for(unsigned k=0; k ECVlinear::getLambdas() const -{ +std::vector ECVlinear::getLambdas() const { plumed_massert(!todoAutomatic_,"cannot access lambdas before initializing them"); std::vector lambdas(derECVs_.size()); - for(unsigned k=0; k ECVlinear::getLambdas() const return lambdas; } -void ECVlinear::initECVs() -{ +void ECVlinear::initECVs() { plumed_massert(!isReady_,"initialization should not be called twice"); plumed_massert(!todoAutomatic_,"this should not happen"); totNumECVs_=derECVs_.size(); @@ -230,17 +226,17 @@ void ECVlinear::initECVs() log.printf(" *%4lu lambdas for %s\n",derECVs_.size(),getName().c_str()); } -void ECVlinear::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) -{ - if(todoAutomatic_) //estimate the steps in lambda from observations - { +void ECVlinear::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) { + if(todoAutomatic_) { //estimate the steps in lambda from observations plumed_massert(all_obs_cvs.size()%ncv==0 && index_j obs_cv(all_obs_cvs.size()/ncv); //copy only useful observation (would be better not to copy...) - for(unsigned t=0; t& all_obs_cvs,const uns calculateECVs(&all_obs_cvs[index_j]); } -void ECVlinear::initECVs_restart(const std::vector& lambdas) -{ +void ECVlinear::initECVs_restart(const std::vector& lambdas) { std::size_t pos=lambdas[0].find("_"); plumed_massert(pos==std::string::npos,"this should not happen, only one CV is used in "+getName()); - if(todoAutomatic_) - { + if(todoAutomatic_) { derECVs_=getSteps(derECVs_[0],derECVs_[1],lambdas.size(),"LAMBDA",geom_spacing_,beta0_*lambda0_); todoAutomatic_=false; } diff --git a/src/opes/ECVmultiThermal.cpp b/src/opes/ECVmultiThermal.cpp index 9ab1ce1a49..7066330ca3 100644 --- a/src/opes/ECVmultiThermal.cpp +++ b/src/opes/ECVmultiThermal.cpp @@ -78,8 +78,7 @@ Notice that \f$p=0.06022140857\f$ corresponds to 1 bar when using the default PL //+ENDPLUMEDOC class ECVmultiThermal : - public ExpansionCVs -{ + public ExpansionCVs { private: bool todoAutomatic_; bool geom_spacing_; @@ -100,8 +99,7 @@ class ECVmultiThermal : PLUMED_REGISTER_ACTION(ECVmultiThermal,"ECV_MULTITHERMAL") -void ECVmultiThermal::registerKeywords(Keywords& keys) -{ +void ECVmultiThermal::registerKeywords(Keywords& keys) { ExpansionCVs::registerKeywords(keys); keys.remove("ARG"); keys.add("compulsory","ARG","the label of the internal energy of the system. If volume is fixed it is calculated by the ENERGY colvar"); @@ -115,8 +113,7 @@ void ECVmultiThermal::registerKeywords(Keywords& keys) ECVmultiThermal::ECVmultiThermal(const ActionOptions&ao) : Action(ao) , ExpansionCVs(ao) - , todoAutomatic_(false) -{ + , todoAutomatic_(false) { plumed_massert(getNumberOfArguments()==1,"only the internal energy should be given as ARG"); //set temp0 @@ -137,31 +134,27 @@ ECVmultiThermal::ECVmultiThermal(const ActionOptions&ao) checkRead(); //set the intermediate temperatures - if(temps.size()>0) - { + if(temps.size()>0) { plumed_massert(temp_steps==0,"cannot set both TEMP_STEPS and TEMP_SET_ALL"); plumed_massert(temp_min==-1 && temp_max==-1,"cannot set both TEMP_SET_ALL and TEMP_MIN/MAX"); plumed_massert(temps.size()>=2,"set at least 2 temperatures"); temp_min=temps[0]; temp_max=temps[temps.size()-1]; derECVs_.resize(temps.size()); - for(unsigned k=0; k0) + } + if(temp_steps>0) { derECVs_=getSteps(derECVs_[0],derECVs_[1],temp_steps,"TEMP",geom_spacing_,1./kbt_); - else + } else { todoAutomatic_=true; + } } const double tol=1e-3; //if temp is taken from MD engine it might be numerically slightly different - if(temp0<(1-tol)*temp_min || temp0>(1+tol)*temp_max) + if(temp0<(1-tol)*temp_min || temp0>(1+tol)*temp_max) { log.printf(" +++ WARNING +++ running at TEMP=%g which is outside the chosen temperature range\n",temp0); + } //print some info log.printf(" targeting a temperature range from TEMP_MIN=%g to TEMP_MAX=%g\n",temp_min,temp_max); - if(!geom_spacing_) + if(!geom_spacing_) { log.printf(" -- NO_GEOM_SPACING: inverse temperatures will be linearly spaced\n"); + } } -void ECVmultiThermal::calculateECVs(const double * ene) -{ - for(unsigned k=0; k ECVmultiThermal::getLambdas() const -{ +std::vector ECVmultiThermal::getLambdas() const { plumed_massert(!todoAutomatic_,"cannot access lambdas before initializing them"); const double temp0=kbt_/getKBoltzmann(); std::vector lambdas(derECVs_.size()); - for(unsigned k=0; k ECVmultiThermal::getLambdas() const return lambdas; } -void ECVmultiThermal::initECVs() -{ +void ECVmultiThermal::initECVs() { plumed_massert(!isReady_,"initialization should not be called twice"); plumed_massert(!todoAutomatic_,"this should not happen"); totNumECVs_=derECVs_.size(); @@ -231,14 +223,13 @@ void ECVmultiThermal::initECVs() log.printf(" *%4lu temperatures for %s\n",derECVs_.size(),getName().c_str()); } -void ECVmultiThermal::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) -{ - if(todoAutomatic_) //estimate the steps in beta from observations - { +void ECVmultiThermal::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) { + if(todoAutomatic_) { //estimate the steps in beta from observations plumed_massert(all_obs_cvs.size()%ncv==0 && index_j obs_ene(all_obs_cvs.size()/ncv); //copy only useful observation (would be better not to copy...) - for(unsigned t=0; t& all_obs_cvs,con calculateECVs(&all_obs_cvs[index_j]); } -void ECVmultiThermal::initECVs_restart(const std::vector& lambdas) -{ +void ECVmultiThermal::initECVs_restart(const std::vector& lambdas) { std::size_t pos=lambdas[0].find("_"); plumed_massert(pos==std::string::npos,"this should not happen, only one CV is used in "+getName()); - if(todoAutomatic_) - { + if(todoAutomatic_) { derECVs_=getSteps(derECVs_[0],derECVs_[1],lambdas.size(),"TEMP",geom_spacing_,1./kbt_); todoAutomatic_=false; } diff --git a/src/opes/ECVmultiThermalBaric.cpp b/src/opes/ECVmultiThermalBaric.cpp index 059fec82cc..390e81d0d8 100644 --- a/src/opes/ECVmultiThermalBaric.cpp +++ b/src/opes/ECVmultiThermalBaric.cpp @@ -72,8 +72,7 @@ If you modify them via the \ref UNITS command, then the pressure has to be resca //+ENDPLUMEDOC class ECVmultiThermalBaric : - public ExpansionCVs -{ + public ExpansionCVs { private: bool todoAutomatic_beta_; bool todoAutomatic_pres_; @@ -107,8 +106,7 @@ class ECVmultiThermalBaric : PLUMED_REGISTER_ACTION(ECVmultiThermalBaric,"ECV_MULTITHERMAL_MULTIBARIC") -void ECVmultiThermalBaric::registerKeywords(Keywords& keys) -{ +void ECVmultiThermalBaric::registerKeywords(Keywords& keys) { ExpansionCVs::registerKeywords(keys); keys.remove("ARG"); keys.add("compulsory","ARG","the labels of the potential energy and of the volume of the system. You can calculate them with ENERGY and VOLUME respectively"); @@ -136,8 +134,7 @@ ECVmultiThermalBaric::ECVmultiThermalBaric(const ActionOptions&ao) , todoAutomatic_pres_(false) , coeff_(0) , pres_low_(0) - , kB_temp_low_(0) -{ + , kB_temp_low_(0) { plumed_massert(getNumberOfArguments()==2,"ENERGY and VOLUME should be given as ARG"); //set temp0 @@ -172,8 +169,7 @@ ECVmultiThermalBaric::ECVmultiThermalBaric(const ActionOptions&ao) checkRead(); - if(custom_lambdas_.size()>0) - { + if(custom_lambdas_.size()>0) { //make sure no incompatible options are used plumed_massert(temps.size()==0,"cannot set both SET_ALL_TEMP_PRESSURE and TEMP_SET_ALL"); plumed_massert(pres_.size()==0,"cannot set both SET_ALL_TEMP_PRESSURE and PRESSURE_SET_ALL"); @@ -186,10 +182,8 @@ ECVmultiThermalBaric::ECVmultiThermalBaric(const ActionOptions&ao) derECVs_beta_.resize(custom_lambdas_.size()); derECVs_pres_.resize(custom_lambdas_.size()); const std::string error_msg="SET_ALL_TEMP_PRESSURE: two underscore-separated values are expected for each comma-separated point, cannot understand: "; - for(unsigned i=0; i0) - { + if(temps.size()>0) { plumed_massert(temp_steps==0,"cannot set both TEMP_STEPS and TEMP_SET_ALL"); plumed_massert(temp_min==-1 && temp_max==-1,"cannot set both TEMP_SET_ALL and TEMP_MIN/MAX"); plumed_massert(temps.size()>=2,"set at least 2 temperatures"); temp_min=temps[0]; temp_max=temps[temps.size()-1]; derECVs_beta_.resize(temps.size()); - for(unsigned k=0; k0) + } + if(temp_steps>0) { derECVs_beta_=getSteps(derECVs_beta_[0],derECVs_beta_[1],temp_steps,"TEMP",geom_spacing_,1./kbt_); - else + } else { todoAutomatic_beta_=true; + } } const double tol=1e-3; //if temp is taken from MD engine it might be numerically slightly different - if(temp0<(1-tol)*temp_min || temp0>(1+tol)*temp_max) + if(temp0<(1-tol)*temp_min || temp0>(1+tol)*temp_max) { log.printf(" +++ WARNING +++ running at TEMP=%g which is outside the chosen temperature range\n",temp0); + } //set the intermediate pressures - if(pres_.size()>0) - { + if(pres_.size()>0) { plumed_massert(pres_steps==0,"cannot set both PRESSURE_STEPS and PRESSURE_SET_ALL"); plumed_massert(pres_min==myNone && pres_max==myNone,"cannot set both PRESSURE_SET_ALL and PRESSURE_MIN/MAX"); plumed_massert(pres_.size()>=2,"set at least 2 pressures"); - for(unsigned kk=0; kk=pres_min,"PRESSURE_MAX should be bigger than PRESSURE_MIN"); - if(pres_min==pres_max && pres_steps==0) + if(pres_min==pres_max && pres_steps==0) { pres_steps=1; - if(pres_steps>0) + } + if(pres_steps>0) { pres_=getSteps(pres_min,pres_max,pres_steps,"PRESSURE",false,0); - else - { + } else { pres_.resize(2); pres_[0]=pres_min; pres_[1]=pres_max; todoAutomatic_pres_=true; } } - if(pres0_pres_max) + if(pres0_pres_max) { log.printf(" +++ WARNING +++ running at PRESSURE=%g which is outside the chosen pressure range\n",pres0_); + } //set CUT_CORNER std::string cc_usage("CUT_CORNER=temp_low,pres_low,temp_high,pres_high"); - if(cut_corner.size()==4) - { + if(cut_corner.size()==4) { const double temp_low=cut_corner[0]; const double pres_low=cut_corner[1]; const double temp_high=cut_corner[2]; @@ -311,9 +297,7 @@ ECVmultiThermalBaric::ECVmultiThermalBaric(const ActionOptions&ao) const double small_value=(temp_high-pres_low)/1e4; pres_low_=pres_low-small_value; //make sure pres_max is included plumed_massert(pres_max>=coeff_*(kB*temp_max-kB_temp_low_)+pres_low_,"please chose a pres_high slightly smaller than PRESSURE_MAX in "+cc_usage); - } - else - { + } else { plumed_massert(cut_corner.size()==0,"expected 4 values: "+cc_usage); } } @@ -321,67 +305,66 @@ ECVmultiThermalBaric::ECVmultiThermalBaric(const ActionOptions&ao) //print some info log.printf(" running at TEMP=%g and PRESSURE=%g\n",temp0,pres0_); log.printf(" targeting a temperature range from TEMP_MIN=%g to TEMP_MAX=%g\n",temp_min,temp_max); - if(temp_min==temp_max) + if(temp_min==temp_max) { log.printf(" +++ WARNING +++ if you only need a multibaric simulation it is more efficient to set it up with ECV_LINEAR\n"); + } log.printf(" and a pressure range from PRESSURE_MIN=%g to PRESSURE_MAX=%g\n",pres_min,pres_max); - if(pres_min==pres_max) + if(pres_min==pres_max) { log.printf(" +++ WARNING +++ if you only need a multithermal simulation it is more efficient to set it up with ECV_MULTITHERMAL\n"); - if(!geom_spacing_) + } + if(!geom_spacing_) { log.printf(" -- NO_GEOM_SPACING: inverse temperatures will be linearly spaced\n"); - if(coeff_!=0) + } + if(coeff_!=0) { log.printf(" -- CUT_CORNER: ignoring some high temperature and low pressure values\n"); + } } -void ECVmultiThermalBaric::calculateECVs(const double * ene_vol) -{ - for(unsigned k=0; k > ECVmultiThermalBaric::getIndex_k() const -{ +std::vector< std::vector > ECVmultiThermalBaric::getIndex_k() const { plumed_massert(isReady_ && totNumECVs_>0,"cannot access getIndex_k() of ECV before initialization"); std::vector< std::vector > index_k; - if(custom_lambdas_.size()>0) - { //same as default getIndex_k() function + if(custom_lambdas_.size()>0) { + //same as default getIndex_k() function plumed_massert(totNumECVs_==custom_lambdas_.size(),"this should not happen"); for(unsigned i=0; i {i,i}); - } - else - { + } else { unsigned i=0; - for(unsigned k=0; k=line_k) //important to be inclusive, thus >=, not just > - { + for(unsigned kk=0; kk=line_k) { //important to be inclusive, thus >=, not just > index_k.emplace_back(std::vector {k,i}); i++; } @@ -392,22 +375,19 @@ std::vector< std::vector > ECVmultiThermalBaric::getIndex_k() const return index_k; } -std::vector ECVmultiThermalBaric::getLambdas() const -{ - if(custom_lambdas_.size()>0) +std::vector ECVmultiThermalBaric::getLambdas() const { + if(custom_lambdas_.size()>0) { return custom_lambdas_; + } plumed_massert(!todoAutomatic_beta_ && !todoAutomatic_pres_,"cannot access lambdas before initializing them"); std::vector lambdas; const double kB=getKBoltzmann(); - for(unsigned k=0; k=line_k) - { + for(unsigned kk=0; kk=line_k) { std::ostringstream subs; subs< ECVmultiThermalBaric::getLambdas() const return lambdas; } -void ECVmultiThermalBaric::initECVs() -{ +void ECVmultiThermalBaric::initECVs() { plumed_massert(!isReady_,"initialization should not be called twice"); plumed_massert(!todoAutomatic_beta_ && !todoAutomatic_pres_,"this should not happen"); totNumECVs_=getLambdas().size(); //slow, but runs only once - if(custom_lambdas_.size()>0) - { + if(custom_lambdas_.size()>0) { log.printf(" *%4lu temperatures for %s\n",derECVs_beta_.size(),getName().c_str()); log.printf(" *%4lu beta-pressures for %s\n",derECVs_pres_.size(),getName().c_str()); log.printf(" -- SET_ALL_TEMP_PRESSURE: total number of temp-pres points is %u\n",totNumECVs_); - } - else - { + } else { plumed_massert(derECVs_beta_.size()*pres_.size()>=totNumECVs_,"this should not happen, is something wrong with CUT_CORNER ?"); derECVs_pres_.resize(totNumECVs_); //pres is mixed with temp (beta*p*V), thus we need to store all possible //initialize the derECVs. //this could be done before and one could avoid storing also beta0, beta_k, etc. but this way the code should be more readable unsigned i=0; - for(unsigned k=0; k=line_k) - { + for(unsigned kk=0; kk=line_k) { derECVs_pres_[i]=(pres_[kk]/kB_temp_k-pres0_/kbt_); i++; } @@ -450,33 +423,33 @@ void ECVmultiThermalBaric::initECVs() } log.printf(" *%4lu temperatures for %s\n",derECVs_beta_.size(),getName().c_str()); log.printf(" *%4lu pressures for %s\n",pres_.size(),getName().c_str()); - if(coeff_!=0) + if(coeff_!=0) { log.printf(" -- CUT_CORNER: %lu temp-pres points were excluded, thus total is %u\n",derECVs_beta_.size()*pres_.size()-totNumECVs_,totNumECVs_); + } } ECVs_beta_.resize(derECVs_beta_.size()); ECVs_pres_.resize(derECVs_pres_.size()); isReady_=true; } -void ECVmultiThermalBaric::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) -{ - if(todoAutomatic_beta_) //estimate the steps in beta from observations - { +void ECVmultiThermalBaric::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) { + if(todoAutomatic_beta_) { //estimate the steps in beta from observations plumed_massert(all_obs_cvs.size()%ncv==0 && index_j obs_ene(all_obs_cvs.size()/ncv); //copy only useful observations - for(unsigned t=0; t obs_vol(all_obs_cvs.size()/ncv); //copy only useful observations - for(unsigned t=0; t& all_obs_cv calculateECVs(&all_obs_cvs[index_j]); } -void ECVmultiThermalBaric::initECVs_restart(const std::vector& lambdas) -{ +void ECVmultiThermalBaric::initECVs_restart(const std::vector& lambdas) { std::size_t pos=lambdas[0].find("_"); plumed_massert(pos!=std::string::npos,"this should not happen, two CVs are used in "+getName()+", not less"); pos=lambdas[0].find("_",pos+1); plumed_massert(pos==std::string::npos,"this should not happen, two CVs are used in "+getName()+", not more"); - auto getPres=[&lambdas](const unsigned i) {return lambdas[i].substr(lambdas[i].find("_")+1);}; - if(todoAutomatic_pres_) - { + auto getPres=[&lambdas](const unsigned i) { + return lambdas[i].substr(lambdas[i].find("_")+1); + }; + if(todoAutomatic_pres_) { unsigned pres_steps=1; std::string pres_min=getPres(0); - for(unsigned i=1; i::infinity(); @@ -132,38 +130,33 @@ ECVumbrellasFile::ECVumbrellasFile(const ActionOptions&ao): parse("FILE",umbrellasFileName); IFile ifile; ifile.link(*this); - if(ifile.FileExist(umbrellasFileName)) - { + if(ifile.FileExist(umbrellasFileName)) { log.printf(" reading from FILE '%s'\n",umbrellasFileName.c_str()); ifile.open(umbrellasFileName); ifile.allowIgnoredFields(); double time; //first field is ignored - while(ifile.scanField("time",time)) - { - for(unsigned j=0; jgetName(),centers_j); centers_[j].push_back(centers_j); //this might be slow } - for(unsigned j=0; jgetName(),sigmas_j); sigmas_[j].push_back(sigmas_j); } ifile.scanField(); } - } - else + } else { plumed_merror("Umbrellas FILE '"+umbrellasFileName+"' not found"); + } checkRead(); //extra consistency checks const unsigned sizeUmbrellas=centers_[0].size(); - for(unsigned j=0; j::infinity()) + if(barrier_!=std::numeric_limits::infinity()) { log.printf(" guess for free energy BARRIER = %g\n",barrier_); - if(P0_contribution_==1) + } + if(P0_contribution_==1) { log.printf(" -- ADD_P0: the target includes also the unbiased probability itself\n"); - if(lower_only_) + } + if(lower_only_) { log.printf(" -- LOWER_HALF_ONLY: the ECVs are set to zero for values of the CV above the respective center\n"); + } } -void ECVumbrellasFile::calculateECVs(const double * cv) -{ - if(lower_only_) - { - for(unsigned j=0; j=0) - { + if(dist_jk>=0) { ECVs_[j][k]=0; derECVs_[j][k]=0; - } - else - { + } else { ECVs_[j][k]=0.5*std::pow(dist_jk,2); derECVs_[j][k]=dist_jk/sigmas_[j][kk]; } } } - } - else - { - for(unsigned j=0; j ECVumbrellasFile::getLambdas() const -{ //notice that sigmas are not considered! +std::vector ECVumbrellasFile::getLambdas() const { + //notice that sigmas are not considered! std::vector lambdas(totNumECVs_); - if(P0_contribution_==1) - { + if(P0_contribution_==1) { std::ostringstream subs; subs<<"P0"; - for(unsigned j=1; j& all_obs_cvs,const unsigned ncv,const unsigned index_j) -{ +void ECVumbrellasFile::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) { //this non-linear exansion never uses automatic initialization initECVs(); calculateECVs(&all_obs_cvs[index_j]); //use only first obs point for(unsigned j=0; j& lambdas) -{ +void ECVumbrellasFile::initECVs_restart(const std::vector& lambdas) { std::size_t pos=0; - for(unsigned j=0; jlambdas[0].length(),"this should not happen, more '_' than expected in "+getName()); diff --git a/src/opes/ECVumbrellasLine.cpp b/src/opes/ECVumbrellasLine.cpp index 0ab817422f..3c420889bc 100644 --- a/src/opes/ECVumbrellasLine.cpp +++ b/src/opes/ECVumbrellasLine.cpp @@ -69,8 +69,7 @@ opes: OPES_EXPANDED ARG=ecv1.*,ecv2.* PACE=500 //+ENDPLUMEDOC class ECVumbrellasLine : - public ExpansionCVs -{ + public ExpansionCVs { private: double barrier_; unsigned P0_contribution_; @@ -96,8 +95,7 @@ class ECVumbrellasLine : PLUMED_REGISTER_ACTION(ECVumbrellasLine,"ECV_UMBRELLAS_LINE") -void ECVumbrellasLine::registerKeywords(Keywords& keys) -{ +void ECVumbrellasLine::registerKeywords(Keywords& keys) { ExpansionCVs::registerKeywords(keys); keys.use("ARG"); keys.add("compulsory","CV_MIN","the minimum of the CV range to be explored"); @@ -111,15 +109,15 @@ void ECVumbrellasLine::registerKeywords(Keywords& keys) ECVumbrellasLine::ECVumbrellasLine(const ActionOptions&ao): Action(ao), - ExpansionCVs(ao) -{ + ExpansionCVs(ao) { //set P0_contribution_ bool add_P0=false; parseFlag("ADD_P0",add_P0); - if(add_P0) + if(add_P0) { P0_contribution_=1; - else + } else { P0_contribution_=0; + } //set barrier_ barrier_=std::numeric_limits::infinity(); @@ -137,37 +135,38 @@ ECVumbrellasLine::ECVumbrellasLine(const ActionOptions&ao): double spacing; parse("SPACING",spacing); double length=0; - for(unsigned j=0; j1) - for(unsigned k=0; kisPeriodic()) - { + } + if(getPntrToArgument(j)->isPeriodic()) { double min,max; std::string min_str,max_str; getPntrToArgument(j)->getDomain(min,max); getPntrToArgument(j)->getDomain(min_str,max_str); plumed_massert(cv_min[j]>=min,"ARG "+std::to_string(j)+": CV_MIN cannot be smaller than the periodic bound "+min_str); plumed_massert(cv_max[j]<=max,"ARG "+std::to_string(j)+": CV_MAX cannot be greater than the periodic bound "+max_str); - if(cv_min[j]==min && cv_max[j]==max) + if(cv_min[j]==min && cv_max[j]==max) { full_period++; + } } } - if(full_period==getNumberOfArguments() && sizeUmbrellas>1) //first and last are the same point - { + if(full_period==getNumberOfArguments() && sizeUmbrellas>1) { //first and last are the same point sizeUmbrellas--; - for(unsigned j=0; j::infinity()) + if(barrier_!=std::numeric_limits::infinity()) { log.printf(" guess for free energy BARRIER = %g\n",barrier_); - if(P0_contribution_==1) + } + if(P0_contribution_==1) { log.printf(" -- ADD_P0: the target includes also the unbiased probability itself\n"); - if(lower_only_) + } + if(lower_only_) { log.printf(" -- LOWER_HALF_ONLY: the ECVs are set to zero for values of the CV above the respective center\n"); + } } -void ECVumbrellasLine::calculateECVs(const double * cv) -{ - if(lower_only_) - { - for(unsigned j=0; j=0) - { + if(dist_jk>=0) { ECVs_[j][k]=0; derECVs_[j][k]=0; - } - else - { + } else { ECVs_[j][k]=0.5*std::pow(dist_jk,2); derECVs_[j][k]=dist_jk/sigma_; } } } - } - else - { - for(unsigned j=0; j ECVumbrellasLine::getLambdas() const -{ +std::vector ECVumbrellasLine::getLambdas() const { std::vector lambdas(totNumECVs_); - if(P0_contribution_==1) - { + if(P0_contribution_==1) { std::ostringstream subs; subs<<"P0"; - for(unsigned j=1; j& all_obs_cvs,const unsigned ncv,const unsigned index_j) -{ +void ECVumbrellasLine::initECVs_observ(const std::vector& all_obs_cvs,const unsigned ncv,const unsigned index_j) { //this non-linear exansion never uses automatic initialization initECVs(); calculateECVs(&all_obs_cvs[index_j]); //use only first obs point for(unsigned j=0; j& lambdas) -{ +void ECVumbrellasLine::initECVs_restart(const std::vector& lambdas) { std::size_t pos=0; - for(unsigned j=0; jlambdas[0].length(),"this should not happen, more '_' than expected in "+getName()); diff --git a/src/opes/ExpansionCVs.cpp b/src/opes/ExpansionCVs.cpp index 4d2b3632c9..4b2636377c 100644 --- a/src/opes/ExpansionCVs.cpp +++ b/src/opes/ExpansionCVs.cpp @@ -23,8 +23,7 @@ namespace PLMD { namespace opes { -void ExpansionCVs::registerKeywords(Keywords& keys) -{ +void ExpansionCVs::registerKeywords(Keywords& keys) { Action::registerKeywords(keys); ActionWithValue::registerKeywords(keys); ActionWithArguments::registerKeywords(keys); @@ -37,8 +36,7 @@ ExpansionCVs::ExpansionCVs(const ActionOptions&ao) , ActionWithValue(ao) , ActionWithArguments(ao) , isReady_(false) - , totNumECVs_(0) -{ + , totNumECVs_(0) { //set kbt_ const double kB=getKBoltzmann(); kbt_=getkBT(); @@ -46,19 +44,17 @@ ExpansionCVs::ExpansionCVs(const ActionOptions&ao) //set components plumed_massert( getNumberOfArguments()!=0, "you must specify the underlying CV"); - for(unsigned j=0; jgetName(); ActionWithValue::addComponentWithDerivatives(name_j); getPntrToComponent(j)->resizeDerivatives(1); - if(getPntrToArgument(j)->isPeriodic()) //it should not be necessary, but why not - { + if(getPntrToArgument(j)->isPeriodic()) { //it should not be necessary, but why not std::string min,max; getPntrToArgument(j)->getDomain(min,max); getPntrToComponent(j)->setDomain(min,max); - } - else + } else { getPntrToComponent(j)->setNotPeriodic(); + } } plumed_massert((int)getNumberOfArguments()==getNumberOfComponents(),"Expansion CVs have same number of arguments and components"); } @@ -67,87 +63,78 @@ std::string ExpansionCVs::getOutputComponentDescription( const std::string& cnam return "the value of the argument named " + cname; } -void ExpansionCVs::calculate() -{ +void ExpansionCVs::calculate() { std::vector args(getNumberOfArguments()); - for(unsigned j=0; jset(args[j]); //components are equal to arguments getPntrToComponent(j)->addDerivative(0,1.); //the derivative of the identity is 1 } - if(isReady_) + if(isReady_) { calculateECVs(&args[0]); + } } -void ExpansionCVs::apply() -{ - for(unsigned j=0; j force_j(1); - if(getPntrToComponent(j)->applyForce(force_j)) //a bias is applied? - getPntrToArgument(j)->addForce(force_j[0]); //just tell it to the CV! + if(getPntrToComponent(j)->applyForce(force_j)) { //a bias is applied? + getPntrToArgument(j)->addForce(force_j[0]); //just tell it to the CV! + } } } -std::vector< std::vector > ExpansionCVs::getIndex_k() const -{ +std::vector< std::vector > ExpansionCVs::getIndex_k() const { plumed_massert(isReady_ && totNumECVs_>0,"cannot access getIndex_k() of ECV before initialization"); std::vector< std::vector > index_k(totNumECVs_,std::vector(getNumberOfArguments())); for(unsigned k=0; k ExpansionCVs::getSteps(double lambda_min,double lambda_max,const unsigned lambda_steps,const std::string& msg,const bool geom_spacing, const double shift) const -{ +std::vector ExpansionCVs::getSteps(double lambda_min,double lambda_max,const unsigned lambda_steps,const std::string& msg,const bool geom_spacing, const double shift) const { plumed_massert(!(lambda_min==lambda_max && lambda_steps>1),"cannot have multiple "+msg+"_STEPS if "+msg+"_MIN=="+msg+"_MAX"); std::vector lambda(lambda_steps); - if(lambda_steps==1) - { + if(lambda_steps==1) { lambda[0]=(lambda_min+lambda_max)/2.; log.printf(" +++ WARNING +++ using one single %s as target = %g\n",msg.c_str(),lambda[0]); - } - else - { - if(geom_spacing) //geometric spacing - { //this way lambda[k]/lambda[k+1] is constant + } else { + if(geom_spacing) { //geometric spacing + //this way lambda[k]/lambda[k+1] is constant lambda_min+=shift; lambda_max+=shift; plumed_massert(lambda_min>0,"cannot use GEOM_SPACING when %s_MIN is not greater than zero"); plumed_massert(lambda_max>0,"cannot use GEOM_SPACING when %s_MAX is not greater than zero"); const double log_lambda_min=std::log(lambda_min); const double log_lambda_max=std::log(lambda_max); - for(unsigned k=0; k& obs,const std::string& msg) const -{ //for linear expansions only, it uses effective sample size (Neff) to estimate the grid spacing - if(left_side==0 && right_side==0) - { +unsigned ExpansionCVs::estimateNumSteps(const double left_side,const double right_side,const std::vector& obs,const std::string& msg) const { + //for linear expansions only, it uses effective sample size (Neff) to estimate the grid spacing + if(left_side==0 && right_side==0) { log.printf(" +++ WARNING +++ %s_MIN and %s_MAX are equal to %s, using single step\n",msg.c_str(),msg.c_str(),msg.c_str()); return 1; } - auto get_neff_HWHM=[](const double side,const std::vector& obs) //HWHM = half width at half maximum. neff is in general not symmetric - { + auto get_neff_HWHM=[](const double side,const std::vector& obs) { //HWHM = half width at half maximum. neff is in general not symmetric //func: Neff/N-0.5 is a function between -0.5 and 0.5 - auto func=[](const double delta,const std::vector& obs) - { + auto func=[](const double delta,const std::vector& obs) { double sum_w=0; double sum_w2=0; //we could avoid recomputing safe_shift every time, but here speed is not a concern const double safe_shift=delta<0?*std::max_element(obs.begin(),obs.end()):*std::min_element(obs.begin(),obs.end()); - for(unsigned t=0; t=0) - return 0.0; //no zero is present! - if(b<0) //left side case - { + if(func_b>=0) { + return 0.0; //no zero is present! + } + if(b<0) { //left side case std::swap(a,b); std::swap(func_a,func_b); } double c=a; double func_c=func_a; - while(std::abs(func_c)>tolerance) - { - if(func_a*func_c>0) - { + while(std::abs(func_c)>tolerance) { + if(func_a*func_c>0) { a=c; func_a=func_c; - } - else - { + } else { b=c; func_b=func_c; } @@ -190,32 +173,33 @@ unsigned ExpansionCVs::estimateNumSteps(const double left_side,const double righ //estimation double left_HWHM=0; - if(left_side!=0) + if(left_side!=0) { left_HWHM=get_neff_HWHM(left_side,obs); + } double right_HWHM=0; - if(right_side!=0) + if(right_side!=0) { right_HWHM=get_neff_HWHM(right_side,obs); - if(left_HWHM==0) - { + } + if(left_HWHM==0) { right_HWHM*=2; - if(left_side==0) + if(left_side==0) { log.printf(" --- %s_MIN is equal to %s\n",msg.c_str(),msg.c_str()); - else + } else { log.printf(" +++ WARNING +++ %s_MIN is very close to %s\n",msg.c_str(),msg.c_str()); + } } - if(right_HWHM==0) - { + if(right_HWHM==0) { left_HWHM*=2; - if(right_side==0) + if(right_side==0) { log.printf(" --- %s_MAX is equal to %s\n",msg.c_str(),msg.c_str()); - else + } else { log.printf(" +++ WARNING +++ %s_MAX is very close to %s\n",msg.c_str(),msg.c_str()); + } } const double grid_spacing=left_HWHM+right_HWHM; log.printf(" estimated %s spacing = %g\n",msg.c_str(),grid_spacing); unsigned steps=std::ceil(std::abs(right_side-left_side)/grid_spacing); - if(steps<2 || grid_spacing==0) - { + if(steps<2 || grid_spacing==0) { log.printf(" +++ WARNING +++ %s range is very narrow, using %s_MIN and %s_MAX as only steps\n",msg.c_str(),msg.c_str(),msg.c_str()); steps=2; } diff --git a/src/opes/ExpansionCVs.h b/src/opes/ExpansionCVs.h index bad74897bb..842bfc8f0c 100644 --- a/src/opes/ExpansionCVs.h +++ b/src/opes/ExpansionCVs.h @@ -34,8 +34,7 @@ They take as argument regular CVs, and output them as components without modific class ExpansionCVs: public ActionWithValue, - public ActionWithArguments -{ + public ActionWithArguments { protected: bool isReady_; //true only after initECVs double kbt_; @@ -52,10 +51,17 @@ class ExpansionCVs: void apply() override; void calculate() override; static void registerKeywords(Keywords&); - inline unsigned getNumberOfDerivatives() override {return 1;}; + inline unsigned getNumberOfDerivatives() override { + return 1; + }; - inline double getKbT() const {return kbt_;}; - inline unsigned getTotNumECVs() const {plumed_massert(isReady_,"cannot ask for totNumECVs before ECV isReady"); return totNumECVs_;}; + inline double getKbT() const { + return kbt_; + }; + inline unsigned getTotNumECVs() const { + plumed_massert(isReady_,"cannot ask for totNumECVs before ECV isReady"); + return totNumECVs_; + }; virtual std::vector< std::vector > getIndex_k() const; //might need to override this virtual void calculateECVs(const double *) = 0; diff --git a/src/opes/OPESexpanded.cpp b/src/opes/OPESexpanded.cpp index afb309b20f..f824fb55b7 100644 --- a/src/opes/OPESexpanded.cpp +++ b/src/opes/OPESexpanded.cpp @@ -178,8 +178,7 @@ class OPESexpanded : public bias::Bias { PLUMED_REGISTER_ACTION(OPESexpanded,"OPES_EXPANDED") -void OPESexpanded::registerKeywords(Keywords& keys) -{ +void OPESexpanded::registerKeywords(Keywords& keys) { Bias::registerKeywords(keys); keys.remove("ARG"); keys.add("compulsory","ARG","the label of the ECVs that define the expansion. You can use an * to make sure all the output components of the ECVs are used, as in the examples above"); @@ -212,8 +211,7 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) , ncv_(getNumberOfArguments()) , deltaF_size_(0) , rct_(0) - , work_(0) -{ + , work_(0) { //set pace parse("PACE",stride_); parse("OBSERVATION_STEPS",obs_steps_); @@ -235,12 +233,15 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) parse("STATE_WSTRIDE",wStateStride_); storeOldStates_=false; parseFlag("STORE_STATES",storeOldStates_); - if(wStateStride_!=0 || storeOldStates_) + if(wStateStride_!=0 || storeOldStates_) { plumed_massert(stateFileName.length()>0,"filename for storing simulation status not specified, use STATE_WFILE"); - if(wStateStride_>0) + } + if(wStateStride_>0) { plumed_massert(wStateStride_>=(int)stride_,"STATE_WSTRIDE is in units of MD steps, thus should be a multiple of PACE"); - if(stateFileName.length()>0 && wStateStride_==0) - wStateStride_=-1;//will print only on CPT events (checkpoints set by some MD engines, like gromacs) + } + if(stateFileName.length()>0 && wStateStride_==0) { + wStateStride_=-1; //will print only on CPT events (checkpoints set by some MD engines, like gromacs) + } //work flag parseFlag("CALC_WORK",calc_work_); @@ -248,22 +249,18 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) //multiple walkers //external MW for cp2k not supported, but anyway cp2k cannot put bias on energy! bool walkers_mpi=false; parseFlag("WALKERS_MPI",walkers_mpi); - if(walkers_mpi) - { + if(walkers_mpi) { //If this Action is not compiled with MPI the user is informed and we exit gracefully plumed_massert(Communicator::plumedHasMPI(),"Invalid walkers configuration: WALKERS_MPI flag requires MPI compilation"); plumed_massert(Communicator::initialized(),"Invalid walkers configuration: WALKERS_MPI needs the communicator correctly initialized."); - if(comm.Get_rank()==0) //multi_sim_comm works on first rank only - { + if(comm.Get_rank()==0) { //multi_sim_comm works on first rank only NumWalkers_=multi_sim_comm.Get_size(); walker_rank_=multi_sim_comm.Get_rank(); } comm.Bcast(NumWalkers_,0); //if each walker has more than one processor update them all comm.Bcast(walker_rank_,0); - } - else - { + } else { NumWalkers_=1; walker_rank_=0; } @@ -274,8 +271,7 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) rank_=comm.Get_rank(); bool serial=false; parseFlag("SERIAL",serial); - if(serial) - { + if(serial) { NumOMP_=1; NumParallel_=1; rank_=0; @@ -287,38 +283,33 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) init_pntrToECVsClass(); //set kbt_ kbt_=pntrToECVsClass_[0]->getKbT(); - for(unsigned l=0; lgetKbT())<1e-4,"must set same TEMP for each ECV"); + } //restart if needed - if(getRestart()) - { + if(getRestart()) { bool stateRestart=true; - if(restartFileName.length()==0) - { + if(restartFileName.length()==0) { stateRestart=false; restartFileName=deltaFsFileName; } IFile ifile; ifile.link(*this); - if(ifile.FileExist(restartFileName)) - { + if(ifile.FileExist(restartFileName)) { log.printf(" RESTART - make sure all ECVs used are the same as before\n"); log.printf(" restarting from: %s\n",restartFileName.c_str()); ifile.open(restartFileName); - if(stateRestart) //get all info - { + if(stateRestart) { //get all info log.printf(" it should be a STATE file (not a DELTAFS file)\n"); double time; //not used ifile.scanField("time",time); ifile.scanField("counter",counter_); ifile.scanField("rct",rct_); std::string tmp_lambda; - while(ifile.scanField(getPntrToArgument(0)->getName(),tmp_lambda)) - { + while(ifile.scanField(getPntrToArgument(0)->getName(),tmp_lambda)) { std::string subs="DeltaF_"+tmp_lambda; - for(unsigned jj=1; jjgetName(),tmp_lambda); subs+="_"+tmp_lambda; @@ -331,11 +322,10 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) tmp_lambda.clear(); } log.printf(" successfully read %lu DeltaF values\n",deltaF_name_.size()); - if(NumParallel_>1) + if(NumParallel_>1) { all_deltaF_=deltaF_; - } - else //get just deltaFs names - { + } + } else { //get just deltaFs names ifile.scanFieldList(deltaF_name_); plumed_massert(deltaF_name_.size()>=4,"RESTART - fewer than expected FIELDS found in '"+deltaFsFileName+"' file"); plumed_massert(deltaF_name_[deltaF_name_.size()-1]=="print_stride","RESTART - coult not find expected FIELDS in '"+deltaFsFileName+"' file"); @@ -344,38 +334,39 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) deltaF_name_.pop_back(); deltaF_name_.erase(deltaF_name_.begin(),deltaF_name_.begin()+2); std::size_t pos=5; //each name starts with "DeltaF" - for(unsigned j=0; jdeltaF_name_[0].length(),"RESTART - more '_' than expected in DeltaF fields: did you add new CV?"); } //get lambdas, init ECVs and Link them deltaF_size_=deltaF_name_.size(); - auto getLambdaName=[](const std::string& name,const unsigned start,const unsigned dim) - { + auto getLambdaName=[](const std::string& name,const unsigned start,const unsigned dim) { std::size_t pos_start=5; //each name starts with "DeltaF" - for(unsigned j=0; j<=start; j++) + for(unsigned j=0; j<=start; j++) { pos_start=name.find("_",pos_start+1); + } std::size_t pos_end=pos_start; - for(unsigned j=0; j=0; l--) - { + for(int l=pntrToECVsClass_.size()-1; l>=0; l--) { const unsigned dim_l=pntrToECVsClass_[l]->getNumberOfArguments(); index_j-=dim_l; std::vector lambdas_l(1); lambdas_l[0]=getLambdaName(deltaF_name_[0],index_j,dim_l); - for(unsigned i=sizeSkip; iinitECVs_restart(lambdas_l); @@ -385,42 +376,38 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) init_linkECVs(); //link ECVs and initializes index_k_ log.printf(" ->%4u DeltaFs in total\n",deltaF_size_); obs_steps_=0; //avoid initializing again - if(stateRestart) - { - if(NumParallel_>1) - { + if(stateRestart) { + if(NumParallel_>1) { const unsigned start=(deltaF_size_/NumParallel_)*rank_+std::min(rank_,deltaF_size_%NumParallel_); unsigned iter=0; - for(unsigned i=start; i0) + if(count_lines>0) { counter_+=restart_stride; + } count_lines++; } counter_*=NumWalkers_; @@ -428,63 +415,65 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) } ifile.reset(false); ifile.close(); - } - else //same behaviour as METAD + } else { //same behaviour as METAD plumed_merror("RESTART requested, but file '"+restartFileName+"' was not found!\n Set RESTART=NO or provide a restart file"); - if(NumWalkers_>1) //make sure that all walkers are doing the same thing - { + } + if(NumWalkers_>1) { //make sure that all walkers are doing the same thing std::vector all_counter(NumWalkers_); - if(comm.Get_rank()==0) + if(comm.Get_rank()==0) { multi_sim_comm.Allgather(counter_,all_counter); + } comm.Bcast(all_counter,0); bool same_number_of_steps=true; for(unsigned w=1; w0) + } else if(restartFileName.length()>0) { log.printf(" +++ WARNING +++ the provided STATE_RFILE will be ignored, since RESTART was not requested\n"); + } //sync all walkers to avoid opening files before reding is over (see also METAD) comm.Barrier(); - if(comm.Get_rank()==0 && walkers_mpi) + if(comm.Get_rank()==0 && walkers_mpi) { multi_sim_comm.Barrier(); + } //setup DeltaFs file deltaFsOfile_.link(*this); - if(NumWalkers_>1) - { - if(walker_rank_>0) - deltaFsFileName="/dev/null"; //only first walker writes on file + if(NumWalkers_>1) { + if(walker_rank_>0) { + deltaFsFileName="/dev/null"; //only first walker writes on file + } deltaFsOfile_.enforceSuffix(""); } deltaFsOfile_.open(deltaFsFileName); - if(fmt.length()>0) + if(fmt.length()>0) { deltaFsOfile_.fmtField(" "+fmt); + } deltaFsOfile_.setHeavyFlush(); //do I need it? deltaFsOfile_.addConstantField("print_stride"); deltaFsOfile_.printField("print_stride",print_stride_); //open file for storing state - if(wStateStride_!=0) - { + if(wStateStride_!=0) { stateOfile_.link(*this); - if(NumWalkers_>1) - { - if(walker_rank_>0) - stateFileName="/dev/null"; //only first walker writes on file + if(NumWalkers_>1) { + if(walker_rank_>0) { + stateFileName="/dev/null"; //only first walker writes on file + } stateOfile_.enforceSuffix(""); } stateOfile_.open(stateFileName); - if(fmt.length()>0) + if(fmt.length()>0) { stateOfile_.fmtField(" "+fmt); + } } //add output components - if(calc_work_) - { + if(calc_work_) { addComponent("work"); componentIsNotPeriodic("work"); } @@ -492,90 +481,96 @@ OPESexpanded::OPESexpanded(const ActionOptions&ao) //printing some info log.printf(" updating the bias with PACE = %u\n",stride_); log.printf(" initial unbiased OBSERVATION_STEPS = %u (in units of PACE)\n",obs_steps_); - if(wStateStride_>0) + if(wStateStride_>0) { log.printf(" state checkpoints are written on file %s every %d MD steps\n",stateFileName.c_str(),wStateStride_); - if(wStateStride_==-1) + } + if(wStateStride_==-1) { log.printf(" state checkpoints are written on file '%s' only on CPT events (or never if MD code does define them!)\n",stateFileName.c_str()); - if(walkers_mpi) + } + if(walkers_mpi) { log.printf(" -- WALKERS_MPI: if multiple replicas are present, they will share the same bias via MPI\n"); - if(NumWalkers_>1) - { + } + if(NumWalkers_>1) { log.printf(" using multiple walkers\n"); log.printf(" number of walkers: %u\n",NumWalkers_); log.printf(" walker rank: %u\n",walker_rank_); } int mw_warning=0; - if(!walkers_mpi && comm.Get_rank()==0 && multi_sim_comm.Get_size()>(int)NumWalkers_) + if(!walkers_mpi && comm.Get_rank()==0 && multi_sim_comm.Get_size()>(int)NumWalkers_) { mw_warning=1; + } comm.Bcast(mw_warning,0); - if(mw_warning) //log.printf messes up with comm, so never use it without Bcast! + if(mw_warning) { //log.printf messes up with comm, so never use it without Bcast! log.printf(" +++ WARNING +++ multiple replicas will NOT communicate unless the flag WALKERS_MPI is used\n"); - if(NumParallel_>1) + } + if(NumParallel_>1) { log.printf(" using multiple MPI processes per simulation: %u\n",NumParallel_); - if(NumOMP_>1) + } + if(NumOMP_>1) { log.printf(" using multiple OpenMP threads per simulation: %u\n",NumOMP_); - if(serial) + } + if(serial) { log.printf(" -- SERIAL: no loop parallelization, despite %d MPI processes and %u OpenMP threads available\n",comm.Get_size(),OpenMP::getNumThreads()); + } log.printf(" Bibliography: "); log<::max(); #pragma omp parallel num_threads(NumOMP_) { #pragma omp for reduction(max:diffMax) - for(unsigned i=0; idiffMax) + if(diff_[i]>diffMax) { diffMax=diff_[i]; + } } } - if(NumParallel_>1) + if(NumParallel_>1) { comm.Max(diffMax); + } //calculate the bias and the forces double sum=0; std::vector der_sum_cv(ncv_,0); - if(NumOMP_==1) - { - for(unsigned i=0; i omp_der_sum_cv(ncv_,0); #pragma omp for reduction(+:sum) nowait - for(unsigned i=0; i1) - { //each MPI process has part of the full deltaF_ vector, so must Sum + if(NumParallel_>1) { + //each MPI process has part of the full deltaF_ vector, so must Sum comm.Sum(sum); comm.Sum(der_sum_cv); } @@ -583,27 +578,25 @@ void OPESexpanded::calculate() //set bias and forces const double bias=-kbt_*(diffMax+std::log(sum/deltaF_size_)); setBias(bias); - for(unsigned j=0; j0) - { - for(unsigned j=0; j0) { + for(unsigned j=0; j cvs(ncv_); - for(unsigned j=0; j all_bias(NumWalkers_); std::vector all_cvs(NumWalkers_*ncv_); - if(comm.Get_rank()==0) - { + if(comm.Get_rank()==0) { multi_sim_comm.Allgather(current_bias,all_bias); multi_sim_comm.Allgather(cvs,all_cvs); } comm.Bcast(all_bias,0); comm.Bcast(all_cvs,0); - for(unsigned w=0; wcalculateECVs(&all_cvs[index_wj]); index_wj+=pntrToECVsClass_[k]->getNumberOfArguments(); } @@ -645,36 +635,40 @@ void OPESexpanded::update() } //write DeltaFs to file - if((counter_/NumWalkers_-1)%print_stride_==0) + if((counter_/NumWalkers_-1)%print_stride_==0) { printDeltaF(); + } //calculate work if requested - if(calc_work_) - { //some copy and paste from calculate() + if(calc_work_) { + //some copy and paste from calculate() //get diffMax, to avoid over/underflow double diffMax=-std::numeric_limits::max(); #pragma omp parallel num_threads(NumOMP_) { #pragma omp for reduction(max:diffMax) - for(unsigned i=0; idiffMax) + if(diff_[i]>diffMax) { diffMax=diff_[i]; + } } } - if(NumParallel_>1) + if(NumParallel_>1) { comm.Max(diffMax); + } //calculate the bias double sum=0; #pragma omp parallel num_threads(NumOMP_) { #pragma omp for reduction(+:sum) nowait - for(unsigned i=0; i1) + if(NumParallel_>1) { comm.Sum(sum); + } const double new_bias=-kbt_*(diffMax+std::log(sum/deltaF_size_)); //accumulate work work_+=new_bias-current_bias; @@ -683,30 +677,26 @@ void OPESexpanded::update() } //dump state if requested - if( (wStateStride_>0 && getStep()%wStateStride_==0) || (wStateStride_==-1 && getCPT()) ) + if( (wStateStride_>0 && getStep()%wStateStride_==0) || (wStateStride_==-1 && getCPT()) ) { dumpStateToFile(); + } } -void OPESexpanded::init_pntrToECVsClass() -{ +void OPESexpanded::init_pntrToECVsClass() { std::vector all_pntrToECVsClass=plumed.getActionSet().select(); plumed_massert(all_pntrToECVsClass.size()>0,"no Expansion CVs found"); - for(unsigned j=0; jgetName().find("."); plumed_massert(dot_posgetName().size(),error_notECV+", thus contain a dot in the name"); unsigned foundECV_l=all_pntrToECVsClass.size(); - for(unsigned l=0; lgetName().substr(0,dot_pos)==all_pntrToECVsClass[l]->getLabel()) - { + for(unsigned l=0; lgetName().substr(0,dot_pos)==all_pntrToECVsClass[l]->getLabel()) { foundECV_l=l; pntrToECVsClass_.push_back(all_pntrToECVsClass[l]); std::string missing_arg="some ECV component is missing from ARG"; plumed_massert(j+all_pntrToECVsClass[l]->getNumberOfArguments()<=getNumberOfArguments(),missing_arg); - for(unsigned h=0; hgetNumberOfArguments(); h++) - { + for(unsigned h=0; hgetNumberOfArguments(); h++) { std::string argName=getPntrToArgument(j+h)->getName(); std::string expectedECVname=all_pntrToECVsClass[l]->getComponentsVector()[h]; plumed_massert(argName==expectedECVname,missing_arg+", or is in wrong order: given ARG="+argName+" expected ARG="+expectedECVname); @@ -718,12 +708,12 @@ void OPESexpanded::init_pntrToECVsClass() plumed_massert(foundECV_lgetLabel()!=pntrToECVsClass_[ll]->getLabel(),"cannot use same ECV twice"); + } } -void OPESexpanded::init_linkECVs() -{ +void OPESexpanded::init_linkECVs() { //TODO It should be possible to make all of this more straightforward (and probably also faster): // - get rid of index_k_, making it trivial for each ECV // - store the ECVs_ and derECVs_ vectors here as a contiguous vector, and use pointers in the ECV classes @@ -731,20 +721,19 @@ void OPESexpanded::init_linkECVs() // - ECVmultiThermalBaric has a nontrivial index_k_ to avoid duplicates. use duplicates instead // - can the ECVs be MPI parallel or it's too complicated? plumed_massert(deltaF_size_>0,"must set deltaF_size_ before calling init_linkECVs()"); - if(NumParallel_==1) + if(NumParallel_==1) { deltaF_.resize(deltaF_size_); - else - { + } else { const unsigned extra=(rank_<(deltaF_size_%NumParallel_)?1:0); deltaF_.resize(deltaF_size_/NumParallel_+extra); //these are used when printing deltaF_ to file all_deltaF_.resize(deltaF_size_); all_size_.resize(NumParallel_,deltaF_size_/NumParallel_); disp_.resize(NumParallel_); - for(unsigned r=0; r(ncv_)); unsigned index_j=0; unsigned sizeSkip=deltaF_size_; - for(unsigned l=0; l > l_index_k(pntrToECVsClass_[l]->getIndex_k()); plumed_massert(deltaF_size_%l_index_k.size()==0,"buggy ECV: mismatch between getTotNumECVs() and getIndex_k().size()"); plumed_massert(l_index_k[0].size()==pntrToECVsClass_[l]->getNumberOfArguments(),"buggy ECV: mismatch between number of ARG and underlying CVs"); sizeSkip/=l_index_k.size(); - for(unsigned h=0; hgetNumberOfArguments(); h++) - { + for(unsigned h=0; hgetNumberOfArguments(); h++) { ECVs_[index_j+h]=pntrToECVsClass_[l]->getPntrToECVs(h); derECVs_[index_j+h]=pntrToECVsClass_[l]->getPntrToDerECVs(h); - if(NumParallel_==1) - { - for(unsigned i=0; igetNumberOfArguments(); @@ -782,14 +768,13 @@ void OPESexpanded::init_linkECVs() plumed_massert(sizeSkip==1,"this should not happen!"); } -void OPESexpanded::init_fromObs() //This could probably be faster and/or require less memory... -{ +void OPESexpanded::init_fromObs() { //This could probably be faster and/or require less memory... //in case of multiple walkers gather all the statistics - if(NumWalkers_>1) - { + if(NumWalkers_>1) { std::vector all_obs_cv(ncv_*obs_steps_*NumWalkers_); - if(comm.Get_rank()==0) + if(comm.Get_rank()==0) { multi_sim_comm.Allgather(obs_cvs_,all_obs_cv); + } comm.Bcast(all_obs_cv,0); obs_cvs_=all_obs_cv; //could this lead to memory issues? obs_steps_*=NumWalkers_; @@ -798,8 +783,7 @@ void OPESexpanded::init_fromObs() //This could probably be faster and/or require //initialize ECVs from observations unsigned index_j=0; deltaF_size_=1; - for(unsigned l=0; linitECVs_observ(obs_cvs_,ncv_,index_j); deltaF_size_*=pntrToECVsClass_[l]->getTotNumECVs(); //ECVs from different exansions will be combined index_j+=pntrToECVsClass_[l]->getNumberOfArguments(); @@ -812,23 +796,22 @@ void OPESexpanded::init_fromObs() //This could probably be faster and/or require //for the first point, t=0, the ECVs are calculated by initECVs_observ, setting also any initial guess index_j=0; for(unsigned i=0; icalculateECVs(&obs_cvs_[t*ncv_+index_j]); index_j+=pntrToECVsClass_[l]->getNumberOfArguments(); } - for(unsigned i=0; i0) //save exp from overflow + if(diff_i>0) { //save exp from overflow deltaF_[i]-=kbt_*(diff_i+std::log1p(std::exp(-diff_i))+std::log1p(-1./(1.+t))); - else + } else { deltaF_[i]-=kbt_*(std::log1p(std::exp(diff_i))+std::log1p(-1./(1.+t))); + } } } obs_cvs_.clear(); @@ -836,13 +819,13 @@ void OPESexpanded::init_fromObs() //This could probably be faster and/or require //set deltaF_name_ deltaF_name_.resize(deltaF_size_,"DeltaF"); unsigned sizeSkip=deltaF_size_; - for(unsigned l=0; l lambdas_l=pntrToECVsClass_[l]->getLambdas(); plumed_massert(lambdas_l.size()==pntrToECVsClass_[l]->getTotNumECVs(),"buggy ECV: mismatch between getTotNumECVs() and getLambdas().size()"); sizeSkip/=lambdas_l.size(); - for(unsigned i=0; i1) - comm.Allgatherv(deltaF_,all_deltaF_,&all_size_[0],&disp_[0]); //can we avoid using this big vector? - for(unsigned i=0; i1) { + comm.Allgatherv(deltaF_,all_deltaF_,&all_size_[0],&disp_[0]); //can we avoid using this big vector? + } + for(unsigned i=0; i6,"not enought _ in deltaF_name_"+std::to_string(i-1)+" string?"); const std::size_t pos_end=deltaF_name_[i].find("_",pos_start); stateOfile_.printField(getPntrToArgument(j)->getName()," "+deltaF_name_[i].substr(pos_start,pos_end-pos_start)); pos_start=pos_end+1; } - if(NumParallel_==1) + if(NumParallel_==1) { stateOfile_.printField("DeltaF",deltaF_[i]); - else + } else { stateOfile_.printField("DeltaF",all_deltaF_[i]); + } stateOfile_.printField(); } //make sure file is written even if small - if(!storeOldStates_) + if(!storeOldStates_) { stateOfile_.flush(); + } } -void OPESexpanded::updateDeltaF(double bias) -{ +void OPESexpanded::updateDeltaF(double bias) { plumed_dbg_massert(counter_>0,"deltaF_ must be initialized"); counter_++; const double arg=(bias-rct_)/kbt_-std::log(counter_-1.); double increment; - if(arg>0) //save exp from overflow + if(arg>0) { //save exp from overflow increment=kbt_*(arg+std::log1p(std::exp(-arg))); - else + } else { increment=kbt_*(std::log1p(std::exp(arg))); + } #pragma omp parallel num_threads(NumOMP_) { #pragma omp for - for(unsigned i=0; i0) //save exp from overflow + if(diff_i>0) { //save exp from overflow deltaF_[i]+=increment-kbt_*(diff_i+std::log1p(std::exp(-diff_i))); - else + } else { deltaF_[i]+=increment-kbt_*std::log1p(std::exp(diff_i)); + } } } rct_+=increment+kbt_*std::log1p(-1./counter_); } -double OPESexpanded::getExpansion(unsigned i) const -{ +double OPESexpanded::getExpansion(unsigned i) const { double expansion=0; - for(unsigned j=0; j center; std::vector sigma; @@ -250,7 +249,9 @@ class OPESmetad : public bias::Bias { static void registerKeywords(Keywords& keys); }; -struct convergence { static const bool explore=false; }; +struct convergence { + static const bool explore=false; +}; typedef OPESmetad OPESmetad_c; PLUMED_REGISTER_ACTION(OPESmetad_c,"OPES_METAD") @@ -294,20 +295,22 @@ PRINT STRIDE=100 FILE=COLVAR ARG=cv,opes.* */ //+ENDPLUMEDOC -struct exploration { static const bool explore=true; }; +struct exploration { + static const bool explore=true; +}; typedef OPESmetad OPESmetad_e; PLUMED_REGISTER_ACTION(OPESmetad_e,"OPES_METAD_EXPLORE") template -void OPESmetad::registerKeywords(Keywords& keys) -{ +void OPESmetad::registerKeywords(Keywords& keys) { Bias::registerKeywords(keys); keys.use("ARG"); keys.add("compulsory","TEMP","-1","temperature. If not set, it is taken from MD engine, but not all MD codes provide it"); keys.add("compulsory","PACE","the frequency for kernel deposition"); std::string info_sigma("the initial widths of the kernels"); - if(mode::explore) + if(mode::explore) { info_sigma+=", divided by the square root of gamma"; + } info_sigma+=". If not set, an adaptive sigma will be used with the given ADAPTIVE_SIGMA_STRIDE"; keys.add("compulsory","SIGMA","ADAPTIVE",info_sigma); keys.add("compulsory","BARRIER","the free energy barrier to be overcome. It is used to set BIASFACTOR, EPSILON, and KERNEL_CUTOFF to reasonable values"); @@ -316,10 +319,11 @@ void OPESmetad::registerKeywords(Keywords& keys) keys.add("optional","ADAPTIVE_SIGMA_STRIDE","number of steps for measuring adaptive sigma. Default is 10xPACE"); keys.add("optional","SIGMA_MIN","never reduce SIGMA below this value"); std::string info_biasfactor("the gamma bias factor used for the well-tempered target distribution. "); - if(mode::explore) + if(mode::explore) { info_biasfactor+="Cannot be 'inf'"; - else + } else { info_biasfactor+="Set to 'inf' for uniform flat target"; + } keys.add("optional","BIASFACTOR",info_biasfactor); keys.add("optional","EPSILON","the value of the regularization constant for the probability"); keys.add("optional","KERNEL_CUTOFF","truncate kernels at this distance, in units of sigma"); @@ -338,8 +342,9 @@ void OPESmetad::registerKeywords(Keywords& keys) keys.addFlag("STORE_STATES",false,"append to STATE_WFILE instead of ovewriting it each time"); //miscellaneous keys.add("optional","EXCLUDED_REGION","kernels are not deposited when the action provided here has a nonzero value, see example above"); - if(!mode::explore) + if(!mode::explore) { keys.add("optional","EXTRA_BIAS","consider also these other bias potentials for the internal reweighting. This can be used e.g. for sampling a custom target distribution (see example above)"); + } keys.addFlag("CALC_WORK",false,"calculate the total accumulated work done by the bias since last restart"); keys.addFlag("WALKERS_MPI",false,"switch on MPI version of multiple walkers"); keys.addFlag("SERIAL",false,"perform calculations in serial"); @@ -365,8 +370,7 @@ OPESmetad::OPESmetad(const ActionOptions& ao) , ncv_(getNumberOfArguments()) , Zed_(1) , work_(0) - , excluded_region_(NULL) -{ + , excluded_region_(NULL) { std::string error_in_input1("Error in input in action "+getName()+" with label "+getLabel()+": the keyword "); std::string error_in_input2(" could not be read correctly"); @@ -384,20 +388,17 @@ OPESmetad::OPESmetad(const ActionOptions& ao) biasfactor_=barrier/kbt_; std::string biasfactor_str; parse("BIASFACTOR",biasfactor_str); - if(biasfactor_str=="inf" || biasfactor_str=="INF") - { + if(biasfactor_str=="inf" || biasfactor_str=="INF") { biasfactor_=std::numeric_limits::infinity(); bias_prefactor_=1; - } - else - { - if(biasfactor_str.length()>0) + } else { + if(biasfactor_str.length()>0) { plumed_massert(Tools::convertNoexcept(biasfactor_str,biasfactor_),error_in_input1+"BIASFACTOR"+error_in_input2); + } plumed_massert(biasfactor_>1,"BIASFACTOR must be greater than one (use 'inf' for uniform target)"); bias_prefactor_=1-1./biasfactor_; } - if(mode::explore) - { + if(mode::explore) { plumed_massert(!std::isinf(biasfactor_),"BIASFACTOR=inf is not compatible with EXPLORE mode"); bias_prefactor_=biasfactor_-1; } @@ -409,35 +410,33 @@ OPESmetad::OPESmetad(const ActionOptions& ao) parseVector("SIGMA",sigma_str); sigma0_.resize(ncv_); double dummy; - if(sigma_str.size()==1 && !Tools::convertNoexcept(sigma_str[0],dummy)) - { + if(sigma_str.size()==1 && !Tools::convertNoexcept(sigma_str[0],dummy)) { plumed_massert(sigma_str[0]=="ADAPTIVE" || sigma_str[0]=="adaptive",error_in_input1+"SIGMA"+error_in_input2); plumed_massert(!std::isinf(biasfactor_),"cannot use BIASFACTOR=inf with adaptive SIGMA"); adaptive_counter_=0; - if(adaptive_sigma_stride_==0) - adaptive_sigma_stride_=10*stride_; //NB: this is arbitrary, chosen from few tests + if(adaptive_sigma_stride_==0) { + adaptive_sigma_stride_=10*stride_; //NB: this is arbitrary, chosen from few tests + } av_cv_.resize(ncv_,0); av_M2_.resize(ncv_,0); plumed_massert(adaptive_sigma_stride_>=stride_,"better to chose ADAPTIVE_SIGMA_STRIDE > PACE"); adaptive_sigma_=true; - } - else - { + } else { plumed_massert(sigma_str.size()==ncv_,"number of SIGMA parameters does not match number of arguments"); plumed_massert(adaptive_sigma_stride_==0,"if SIGMA is not ADAPTIVE you cannot set an ADAPTIVE_SIGMA_STRIDE"); - for(unsigned i=0; i0 && !adaptive_sigma_) - { - for(unsigned i=0; i0 && !adaptive_sigma_) { + for(unsigned i=0; i::OPESmetad(const ActionOptions& ao) sum_weights2_=sum_weights_*sum_weights_; double cutoff=sqrt(2.*barrier/bias_prefactor_/kbt_); - if(mode::explore) - cutoff=sqrt(2.*barrier/kbt_); //otherwise it is too small + if(mode::explore) { + cutoff=sqrt(2.*barrier/kbt_); //otherwise it is too small + } parse("KERNEL_CUTOFF",cutoff); plumed_massert(cutoff>0,"you must choose a value for KERNEL_CUTOFF greater than zero"); cutoff2_=cutoff*cutoff; @@ -457,25 +457,24 @@ OPESmetad::OPESmetad(const ActionOptions& ao) threshold2_=1; parse("COMPRESSION_THRESHOLD",threshold2_); threshold2_*=threshold2_; - if(threshold2_!=0) + if(threshold2_!=0) { plumed_massert(threshold2_>0 && threshold2_ nlist_param; parseVector("NLIST_PARAMETERS",nlist_param); - if(nlist_param.size()==0) - { + if(nlist_param.size()==0) { nlist_param_[0]=3.0;//*cutoff2_ -> max distance of neighbors nlist_param_[1]=0.5;//*nlist_dev2_[i] -> condition for rebuilding - } - else - { + } else { nlist_=true; plumed_massert(nlist_param.size()==2,"two cutoff parameters are needed for the neighbor list"); plumed_massert(nlist_param[0]>1.0,"the first of NLIST_PARAMETERS must be greater than 1. The smaller the first, the smaller should be the second as well"); @@ -493,8 +492,8 @@ OPESmetad::OPESmetad(const ActionOptions& ao) //optional stuff no_Zed_=false; parseFlag("NO_ZED",no_Zed_); - if(no_Zed_) - { //this makes it more gentle in the initial phase + if(no_Zed_) { + //this makes it more gentle in the initial phase sum_weights_=1; sum_weights2_=1; } @@ -508,17 +507,16 @@ OPESmetad::OPESmetad(const ActionOptions& ao) //options involving extra arguments std::vector args; parseArgumentList("EXCLUDED_REGION",args); - if(args.size()>0) - { + if(args.size()>0) { plumed_massert(args.size()==1,"only one characteristic function should define the region to be excluded"); requestExtraDependencies(args); excluded_region_=args[0]; } - if(!mode::explore) - { + if(!mode::explore) { parseArgumentList("EXTRA_BIAS",extra_biases_); - if(extra_biases_.size()>0) + if(extra_biases_.size()>0) { requestExtraDependencies(extra_biases_); + } } //kernels file @@ -536,32 +534,31 @@ OPESmetad::OPESmetad(const ActionOptions& ao) parse("STATE_WSTRIDE",wStateStride_); storeOldStates_=false; parseFlag("STORE_STATES",storeOldStates_); - if(wStateStride_!=0 || storeOldStates_) + if(wStateStride_!=0 || storeOldStates_) { plumed_massert(stateFileName.length()>0,"filename for storing simulation status not specified, use STATE_WFILE"); - if(wStateStride_>0) + } + if(wStateStride_>0) { plumed_massert(wStateStride_>=(int)stride_,"STATE_WSTRIDE is in units of MD steps, thus it is suggested to use a multiple of PACE"); - if(stateFileName.length()>0 && wStateStride_==0) - wStateStride_=-1;//will print only on CPT events (checkpoints set by some MD engines, like gromacs) + } + if(stateFileName.length()>0 && wStateStride_==0) { + wStateStride_=-1; //will print only on CPT events (checkpoints set by some MD engines, like gromacs) + } //multiple walkers //TODO implement also external mw for cp2k bool walkers_mpi=false; parseFlag("WALKERS_MPI",walkers_mpi); - if(walkers_mpi) - { + if(walkers_mpi) { //If this Action is not compiled with MPI the user is informed and we exit gracefully plumed_massert(Communicator::plumedHasMPI(),"Invalid walkers configuration: WALKERS_MPI flag requires MPI compilation"); plumed_massert(Communicator::initialized(),"Invalid walkers configuration: WALKERS_MPI needs the communicator correctly initialized."); - if(comm.Get_rank()==0)//multi_sim_comm works on first rank only - { + if(comm.Get_rank()==0) { //multi_sim_comm works on first rank only NumWalkers_=multi_sim_comm.Get_size(); walker_rank_=multi_sim_comm.Get_rank(); } comm.Bcast(NumWalkers_,0); //if each walker has more than one processor update them all comm.Bcast(walker_rank_,0); - } - else - { + } else { NumWalkers_=1; walker_rank_=0; } @@ -572,8 +569,7 @@ OPESmetad::OPESmetad(const ActionOptions& ao) rank_=comm.Get_rank(); bool serial=false; parseFlag("SERIAL",serial); - if(serial) - { + if(serial) { NumOMP_=1; NumParallel_=1; rank_=0; @@ -583,31 +579,25 @@ OPESmetad::OPESmetad(const ActionOptions& ao) //restart if needed bool convertKernelsToState=false; - if(getRestart()) - { + if(getRestart()) { bool stateRestart=true; - if(restartFileName.length()==0) - { + if(restartFileName.length()==0) { stateRestart=false; restartFileName=kernelsFileName; } IFile ifile; ifile.link(*this); - if(ifile.FileExist(restartFileName)) - { + if(ifile.FileExist(restartFileName)) { bool tmp_nlist=nlist_; nlist_=false; // NLIST is not needed while restarting ifile.open(restartFileName); log.printf(" RESTART - make sure all used options are compatible\n"); log.printf(" restarting from: %s\n",restartFileName.c_str()); std::string action_name=getName(); - if(stateRestart) - { + if(stateRestart) { log.printf(" it should be a STATE file (not a KERNELS file)\n"); action_name+="_state"; - } - else - { + } else { log.printf(" +++ WARNING +++ RESTART from KERNELS might be approximate, use STATE_WFILE and STATE_RFILE to restart from the exact state\n"); action_name+="_kernels"; } @@ -616,61 +606,55 @@ OPESmetad::OPESmetad(const ActionOptions& ao) plumed_massert(action_name==old_action_name,"RESTART - mismatch between old and new action name. Expected '"+action_name+"', but found '"+old_action_name+"'"); std::string old_biasfactor_str; ifile.scanField("biasfactor",old_biasfactor_str); - if(old_biasfactor_str=="inf" || old_biasfactor_str=="INF") - { - if(!std::isinf(biasfactor_)) + if(old_biasfactor_str=="inf" || old_biasfactor_str=="INF") { + if(!std::isinf(biasfactor_)) { log.printf(" +++ WARNING +++ previous bias factor was inf while now it is %g\n",biasfactor_); - } - else - { + } + } else { double old_biasfactor; ifile.scanField("biasfactor",old_biasfactor); - if(std::abs(biasfactor_-old_biasfactor)>1e-6*biasfactor_) + if(std::abs(biasfactor_-old_biasfactor)>1e-6*biasfactor_) { log.printf(" +++ WARNING +++ previous bias factor was %g while now it is %g. diff = %g\n",old_biasfactor,biasfactor_,biasfactor_-old_biasfactor); + } } double old_epsilon; ifile.scanField("epsilon",old_epsilon); - if(std::abs(epsilon_-old_epsilon)>1e-6*epsilon_) + if(std::abs(epsilon_-old_epsilon)>1e-6*epsilon_) { log.printf(" +++ WARNING +++ previous epsilon was %g while now it is %g. diff = %g\n",old_epsilon,epsilon_,epsilon_-old_epsilon); + } double old_cutoff; ifile.scanField("kernel_cutoff",old_cutoff); - if(std::abs(cutoff-old_cutoff)>1e-6*cutoff) + if(std::abs(cutoff-old_cutoff)>1e-6*cutoff) { log.printf(" +++ WARNING +++ previous kernel_cutoff was %g while now it is %g. diff = %g\n",old_cutoff,cutoff,cutoff-old_cutoff); + } double old_threshold; const double threshold=sqrt(threshold2_); ifile.scanField("compression_threshold",old_threshold); - if(std::abs(threshold-old_threshold)>1e-6*threshold) + if(std::abs(threshold-old_threshold)>1e-6*threshold) { log.printf(" +++ WARNING +++ previous compression_threshold was %g while now it is %g. diff = %g\n",old_threshold,threshold,threshold-old_threshold); - if(stateRestart) - { + } + if(stateRestart) { ifile.scanField("zed",Zed_); ifile.scanField("sum_weights",sum_weights_); ifile.scanField("sum_weights2",sum_weights2_); ifile.scanField("counter",counter_); - if(adaptive_sigma_) - { + if(adaptive_sigma_) { ifile.scanField("adaptive_counter",adaptive_counter_); - if(NumWalkers_==1) - { - for(unsigned i=0; igetName(),sigma0_[i]); ifile.scanField("av_cv_"+getPntrToArgument(i)->getName(),av_cv_[i]); ifile.scanField("av_M2_"+getPntrToArgument(i)->getName(),av_M2_[i]); } - } - else - { + } else { for(unsigned w=0; wgetName()+"_"+std::to_string(w); ifile.scanField("sigma0_"+arg_iw,tmp0); ifile.scanField("av_cv_"+arg_iw,tmp1); ifile.scanField("av_M2_"+arg_iw,tmp2); - if(w==walker_rank_) - { + if(w==walker_rank_) { sigma0_[i]=tmp0; av_cv_[i]=tmp1; av_M2_[i]=tmp2; @@ -679,10 +663,8 @@ OPESmetad::OPESmetad(const ActionOptions& ao) } } } - for(unsigned i=0; iisPeriodic()) - { + for(unsigned i=0; iisPeriodic()) { std::string arg_min,arg_max; getPntrToArgument(i)->getDomain(arg_min,arg_max); std::string file_min,file_max; @@ -692,40 +674,40 @@ OPESmetad::OPESmetad(const ActionOptions& ao) plumed_massert(file_max==arg_max,"RESTART - mismatch between old and new ARG periodicity"); } } - if(stateRestart) - { + if(stateRestart) { double time; - while(ifile.scanField("time",time)) - { + while(ifile.scanField("time",time)) { std::vector center(ncv_); std::vector sigma(ncv_); double height; - for(unsigned i=0; igetName(),center[i]); - for(unsigned i=0; igetName(),sigma[i]); + } ifile.scanField("height",height); ifile.scanField(); kernels_.emplace_back(height,center,sigma); } log.printf(" a total of %lu kernels where read\n",kernels_.size()); - } - else - { + } else { ifile.allowIgnoredFields(); //this allows for multiple restart, but without checking for consistency between them! double time; - while(ifile.scanField("time",time)) - { + while(ifile.scanField("time",time)) { std::vector center(ncv_); std::vector sigma(ncv_); double height; double logweight; - for(unsigned i=0; igetName(),center[i]); - for(unsigned i=0; igetName(),sigma[i]); - if(counter_==(1+walker_rank_) && adaptive_sigma_) + } + if(counter_==(1+walker_rank_) && adaptive_sigma_) { sigma0_=sigma; + } ifile.scanField("height",height); ifile.scanField("logweight",logweight); ifile.scanField(); @@ -736,14 +718,15 @@ OPESmetad::OPESmetad(const ActionOptions& ao) counter_++; } KDEnorm_=mode::explore?counter_:sum_weights_; - if(!no_Zed_) - { + if(!no_Zed_) { double sum_uprob=0; for(unsigned k=rank_; k1) + } + if(NumParallel_>1) { comm.Sum(sum_uprob); + } Zed_=sum_uprob/KDEnorm_/kernels_.size(); } log.printf(" a total of %llu kernels where read, and compressed to %lu\n",counter_-1,kernels_.size()); @@ -752,42 +735,45 @@ OPESmetad::OPESmetad(const ActionOptions& ao) ifile.reset(false); ifile.close(); nlist_=tmp_nlist; - } - else //same behaviour as METAD + } else { //same behaviour as METAD plumed_merror("RESTART requested, but file '"+restartFileName+"' was not found!\n Set RESTART=NO or provide a restart file"); - if(NumWalkers_>1) //make sure that all walkers are doing the same thing - { + } + if(NumWalkers_>1) { //make sure that all walkers are doing the same thing const unsigned kernels_size=kernels_.size(); std::vector all_kernels_size(NumWalkers_); - if(comm.Get_rank()==0) + if(comm.Get_rank()==0) { multi_sim_comm.Allgather(kernels_size,all_kernels_size); + } comm.Bcast(all_kernels_size,0); bool same_number_of_kernels=true; for(unsigned w=1; w0) + } else if(restartFileName.length()>0) { log.printf(" +++ WARNING +++ the provided STATE_RFILE will be ignored, since RESTART was not requested\n"); + } //sync all walkers to avoid opening files before reading is over (see also METAD) comm.Barrier(); - if(comm.Get_rank()==0 && walkers_mpi) + if(comm.Get_rank()==0 && walkers_mpi) { multi_sim_comm.Barrier(); + } //setup output kernels file kernelsOfile_.link(*this); - if(NumWalkers_>1) - { - if(walker_rank_>0) - kernelsFileName="/dev/null"; //only first walker writes on file + if(NumWalkers_>1) { + if(walker_rank_>0) { + kernelsFileName="/dev/null"; //only first walker writes on file + } kernelsOfile_.enforceSuffix(""); } kernelsOfile_.open(kernelsFileName); - if(fmt.length()>0) + if(fmt.length()>0) { kernelsOfile_.fmtField(" "+fmt); + } kernelsOfile_.setHeavyFlush(); //do I need it? //define and set const fields kernelsOfile_.addConstantField("action"); @@ -795,8 +781,9 @@ OPESmetad::OPESmetad(const ActionOptions& ao) kernelsOfile_.addConstantField("epsilon"); kernelsOfile_.addConstantField("kernel_cutoff"); kernelsOfile_.addConstantField("compression_threshold"); - for(unsigned i=0; i::OPESmetad(const ActionOptions& ao) kernelsOfile_.printField("compression_threshold",sqrt(threshold2_)); //open file for storing state - if(wStateStride_!=0) - { + if(wStateStride_!=0) { stateOfile_.link(*this); - if(NumWalkers_>1) - { - if(walker_rank_>0) - stateFileName="/dev/null"; //only first walker writes on file + if(NumWalkers_>1) { + if(walker_rank_>0) { + stateFileName="/dev/null"; //only first walker writes on file + } stateOfile_.enforceSuffix(""); } stateOfile_.open(stateFileName); - if(fmt.length()>0) + if(fmt.length()>0) { stateOfile_.fmtField(" "+fmt); - if(convertKernelsToState) + } + if(convertKernelsToState) { dumpStateToFile(); + } } //set initial old values @@ -837,13 +825,11 @@ OPESmetad::OPESmetad(const ActionOptions& ao) addComponent("nker"); componentIsNotPeriodic("nker"); getPntrToComponent("nker")->set(kernels_.size()); - if(calc_work_) - { + if(calc_work_) { addComponent("work"); componentIsNotPeriodic("work"); } - if(nlist_) - { + if(nlist_) { addComponent("nlker"); componentIsNotPeriodic("nlker"); addComponent("nlsteps"); @@ -856,116 +842,129 @@ OPESmetad::OPESmetad(const ActionOptions& ao) log.printf(" depositing new kernels with PACE = %u\n",stride_); log.printf(" expected BARRIER is %g\n",barrier); log.printf(" using target distribution with BIASFACTOR gamma = %g\n",biasfactor_); - if(std::isinf(biasfactor_)) + if(std::isinf(biasfactor_)) { log.printf(" (thus a uniform flat target distribution, no well-tempering)\n"); - if(excluded_region_!=NULL) + } + if(excluded_region_!=NULL) { log.printf(" -- EXCLUDED_REGION: kernels will be deposited only when '%s' is equal to zero\n",excluded_region_->getName().c_str()); - if(extra_biases_.size()>0) - { + } + if(extra_biases_.size()>0) { log.printf(" -- EXTRA_BIAS: "); - for(unsigned e=0; egetName().c_str()); + } log.printf("will be reweighted\n"); } - if(adaptive_sigma_) - { + if(adaptive_sigma_) { log.printf(" adaptive SIGMA will be used, with ADAPTIVE_SIGMA_STRIDE = %u\n",adaptive_sigma_stride_); unsigned x=std::ceil(adaptive_sigma_stride_/stride_); log.printf(" thus the first x kernel depositions will be skipped, x = ADAPTIVE_SIGMA_STRIDE/PACE = %u\n",x); - } - else - { + } else { log.printf(" kernels have initial SIGMA = "); - for(unsigned i=0; i0) - { + if(sigma_min_.size()>0) { log.printf(" kernels have a SIGMA_MIN = "); - for(unsigned i=0; iepsilon_*(1+1e-6)) + if(val_at_cutoff_>epsilon_*(1+1e-6)) { log.printf(" +++ WARNING +++ the KERNEL_CUTOFF might be too small for the given EPSILON\n"); + } log.printf(" kernels will be compressed when closer than COMPRESSION_THRESHOLD = %g\n",sqrt(threshold2_)); - if(threshold2_==0) + if(threshold2_==0) { log.printf(" +++ WARNING +++ kernels will never merge, expect slowdowns\n"); - if(!recursive_merge_) + } + if(!recursive_merge_) { log.printf(" -- RECURSIVE_MERGE_OFF: only one merge for each new kernel will be attempted. This is faster only if total number of kernels does not grow too much\n"); - if(nlist_) + } + if(nlist_) { log.printf(" -- NLIST: using neighbor list for kernels, with parameters: %g,%g\n",nlist_param_[0],nlist_param_[1]); - if(nlist_pace_reset_) + } + if(nlist_pace_reset_) { log.printf(" -- NLIST_PACE_RESET: forcing the neighbor list to update every PACE\n"); - if(no_Zed_) + } + if(no_Zed_) { log.printf(" -- NO_ZED: using fixed normalization factor = %g\n",Zed_); - if(wStateStride_>0) + } + if(wStateStride_>0) { log.printf(" state checkpoints are written on file %s every %d MD steps\n",stateFileName.c_str(),wStateStride_); - if(wStateStride_==-1) + } + if(wStateStride_==-1) { log.printf(" state checkpoints are written on file %s only on CPT events (or never if MD code does define them!)\n",stateFileName.c_str()); - if(walkers_mpi) + } + if(walkers_mpi) { log.printf(" -- WALKERS_MPI: if multiple replicas are present, they will share the same bias via MPI\n"); - if(NumWalkers_>1) - { + } + if(NumWalkers_>1) { log.printf(" using multiple walkers\n"); log.printf(" number of walkers: %u\n",NumWalkers_); log.printf(" walker rank: %u\n",walker_rank_); } int mw_warning=0; - if(!walkers_mpi && comm.Get_rank()==0 && multi_sim_comm.Get_size()>(int)NumWalkers_) + if(!walkers_mpi && comm.Get_rank()==0 && multi_sim_comm.Get_size()>(int)NumWalkers_) { mw_warning=1; + } comm.Bcast(mw_warning,0); - if(mw_warning) //log.printf messes up with comm, so never use it without Bcast! + if(mw_warning) { //log.printf messes up with comm, so never use it without Bcast! log.printf(" +++ WARNING +++ multiple replicas will NOT communicate unless the flag WALKERS_MPI is used\n"); - if(NumParallel_>1) + } + if(NumParallel_>1) { log.printf(" using multiple MPI processes per simulation: %u\n",NumParallel_); - if(NumOMP_>1) + } + if(NumOMP_>1) { log.printf(" using multiple OpenMP threads per simulation: %u\n",NumOMP_); - if(serial) + } + if(serial) { log.printf(" -- SERIAL: no loop parallelization, despite %d MPI processes and %u OpenMP threads available\n",comm.Get_size(),OpenMP::getNumThreads()); + } log.printf(" Bibliography: "); log< -void OPESmetad::calculate() -{ +void OPESmetad::calculate() { //get cv std::vector cv(ncv_); - for(unsigned i=0; inlist_param_[1]*nlist_dev2_[i]) - { + if(diff_i*diff_i>nlist_param_[1]*nlist_dev2_[i]) { nlist_update_=true; break; } } } - if(nlist_update_) + if(nlist_update_) { updateNlist(cv); + } } //set bias and forces @@ -973,57 +972,55 @@ void OPESmetad::calculate() const double prob=getProbAndDerivatives(cv,der_prob); const double bias=kbt_*bias_prefactor_*std::log(prob/Zed_+epsilon_); setBias(bias); - for(unsigned i=0; i -void OPESmetad::update() -{ - if(isFirstStep_)//same in MetaD, useful for restarts? - { +void OPESmetad::update() { + if(isFirstStep_) { //same in MetaD, useful for restarts? isFirstStep_=false; return; } //update variance if adaptive sigma - if(adaptive_sigma_) - { + if(adaptive_sigma_) { adaptive_counter_++; unsigned tau=adaptive_sigma_stride_; - if(adaptive_counter_1 if restarting - return; //do not apply bias before having measured sigma + if(adaptive_counter_1 if restarting + return; //do not apply bias before having measured sigma + } } //do update - if(getStep()%stride_==0 && (excluded_region_==NULL || excluded_region_->get()==0)) - { + if(getStep()%stride_==0 && (excluded_region_==NULL || excluded_region_->get()==0)) { old_KDEnorm_=KDEnorm_; delta_kernels_.clear(); unsigned old_nker=kernels_.size(); //get new kernel height double log_weight=getOutputQuantity(0)/kbt_; //first value is always the current bias - for(unsigned e=0; eget()/kbt_; //extra biases contribute to the weight + for(unsigned e=0; eget()/kbt_; //extra biases contribute to the weight + } double height=std::exp(log_weight); //update sum_weights_ and neff double sum_heights=height; double sum_heights2=height*height; - if(NumWalkers_>1) - { - if(comm.Get_rank()==0) - { + if(NumWalkers_>1) { + if(comm.Get_rank()==0) { multi_sim_comm.Sum(sum_heights); multi_sim_comm.Sum(sum_heights2); } @@ -1036,90 +1033,85 @@ void OPESmetad::update() const double neff=std::pow(1+sum_weights_,2)/(1+sum_weights2_); //adding 1 makes it more robust at the start getPntrToComponent("rct")->set(kbt_*std::log(sum_weights_/counter_)); getPntrToComponent("neff")->set(neff); - if(mode::explore) - { + if(mode::explore) { KDEnorm_=counter_; height=1; //plain KDE, bias reweight does not enter here - } - else + } else { KDEnorm_=sum_weights_; + } //if needed, rescale sigma and height std::vector sigma=sigma0_; - if(adaptive_sigma_) - { + if(adaptive_sigma_) { const double factor=mode::explore?1:biasfactor_; - if(counter_==1+NumWalkers_) //first time only - { - for(unsigned i=0; i1e-6,"ADAPTIVE SIGMA is suspiciously small for CV i="+std::to_string(i)+"\nManually provide SIGMA or set a safe SIGMA_MIN to avoid possible issues"); } - else - { - for(unsigned i=0; i1e-6,"ADAPTIVE SIGMA is suspiciously small for CV i="+std::to_string(i)+"\nManually provide SIGMA or set a safe SIGMA_MIN to avoid possible issues"); + } + } else { + for(unsigned i=0; i0) - { - for(unsigned i=0; i0) { + for(unsigned i=0; i center(ncv_); - for(unsigned i=0; i all_height(NumWalkers_,0.0); std::vector all_center(NumWalkers_*ncv_,0.0); std::vector all_sigma(NumWalkers_*ncv_,0.0); std::vector all_logweight(NumWalkers_,0.0); - if(comm.Get_rank()==0) - { + if(comm.Get_rank()==0) { multi_sim_comm.Allgather(height,all_height); multi_sim_comm.Allgather(center,all_center); multi_sim_comm.Allgather(sigma,all_sigma); @@ -1129,111 +1121,102 @@ void OPESmetad::update() comm.Bcast(all_center,0); comm.Bcast(all_sigma,0); comm.Bcast(all_logweight,0); - if(nlist_) - { //gather all the nlist_index_, so merging can be done using it + if(nlist_) { + //gather all the nlist_index_, so merging can be done using it std::vector all_nlist_size(NumWalkers_); - if(comm.Get_rank()==0) - { + if(comm.Get_rank()==0) { all_nlist_size[walker_rank_]=nlist_index_.size(); multi_sim_comm.Sum(all_nlist_size); } comm.Bcast(all_nlist_size,0); unsigned tot_size=0; - for(unsigned w=0; w0) - { + } + if(tot_size>0) { std::vector disp(NumWalkers_); - for(unsigned w=0; w all_nlist_index(tot_size); - if(comm.Get_rank()==0) + if(comm.Get_rank()==0) { multi_sim_comm.Allgatherv(nlist_index_,all_nlist_index,&all_nlist_size[0],&disp[0]); + } comm.Bcast(all_nlist_index,0); std::set nlist_index_set(all_nlist_index.begin(),all_nlist_index.end()); //remove duplicates and sort nlist_index_.assign(nlist_index_set.begin(),nlist_index_set.end()); } } - for(unsigned w=0; w center_w(all_center.begin()+ncv_*w,all_center.begin()+ncv_*(w+1)); std::vector sigma_w(all_sigma.begin()+ncv_*w,all_sigma.begin()+ncv_*(w+1)); addKernel(all_height[w],center_w,sigma_w,all_logweight[w]); } } getPntrToComponent("nker")->set(kernels_.size()); - if(nlist_) - { + if(nlist_) { getPntrToComponent("nlker")->set(nlist_index_.size()); - if(nlist_pace_reset_) + if(nlist_pace_reset_) { nlist_update_=true; + } } //update Zed_ - if(!no_Zed_) - { + if(!no_Zed_) { double sum_uprob=0; const unsigned ks=kernels_.size(); const unsigned ds=delta_kernels_.size(); const bool few_kernels=(ks*ks<(3*ks*ds+2*ds*ds*NumParallel_+100)); //this seems reasonable, but is not rigorous... - if(few_kernels) //really needed? Probably is almost always false - { + if(few_kernels) { //really needed? Probably is almost always false #pragma omp parallel num_threads(NumOMP_) { #pragma omp for reduction(+:sum_uprob) nowait for(unsigned k=rank_; k1) + if(NumParallel_>1) { comm.Sum(sum_uprob); - } - else - { + } + } else { // Here instead of redoing the full summation, we add only the changes, knowing that // uprob = old_uprob + delta_uprob // and we also need to consider that in the new sum there are some novel centers and some disappeared ones double delta_sum_uprob=0; - if(!nlist_) - { + if(!nlist_) { #pragma omp parallel num_threads(NumOMP_) { #pragma omp for reduction(+:delta_sum_uprob) nowait - for(unsigned k=rank_; k1) + if(NumParallel_>1) { comm.Sum(delta_sum_uprob); + } #pragma omp parallel num_threads(NumOMP_) { #pragma omp for reduction(+:delta_sum_uprob) - for(unsigned d=0; d::update() } //calculate work if requested - if(calc_work_) - { + if(calc_work_) { std::vector dummy(ncv_); //derivatives are not actually needed const double prob=getProbAndDerivatives(center,dummy); const double new_bias=kbt_*bias_prefactor_*std::log(prob/Zed_+epsilon_); @@ -1257,113 +1239,104 @@ void OPESmetad::update() } //dump state if requested - if( (wStateStride_>0 && getStep()%wStateStride_==0) || (wStateStride_==-1 && getCPT()) ) + if( (wStateStride_>0 && getStep()%wStateStride_==0) || (wStateStride_==-1 && getCPT()) ) { dumpStateToFile(); + } } template -double OPESmetad::getProbAndDerivatives(const std::vector& cv,std::vector& der_prob) -{ +double OPESmetad::getProbAndDerivatives(const std::vector& cv,std::vector& der_prob) { double prob=0.0; - if(!nlist_) - { - if(NumOMP_==1 || (unsigned)kernels_.size()<2*NumOMP_*NumParallel_) - { + if(!nlist_) { + if(NumOMP_==1 || (unsigned)kernels_.size()<2*NumOMP_*NumParallel_) { // for performances and thread safety std::vector dist(ncv_); - for(unsigned k=rank_; k omp_deriv(der_prob.size(),0.); // for performances and thread safety std::vector dist(ncv_); #pragma omp for reduction(+:prob) nowait - for(unsigned k=rank_; k dist(ncv_); - for(unsigned nk=rank_; nk omp_deriv(der_prob.size(),0.); // for performances and thread safety std::vector dist(ncv_); #pragma omp for reduction(+:prob) nowait - for(unsigned nk=rank_; nk1) - { + if(NumParallel_>1) { comm.Sum(prob); comm.Sum(der_prob); } //normalize the estimate prob/=KDEnorm_; - for(unsigned i=0; i -void OPESmetad::addKernel(const double height,const std::vector& center,const std::vector& sigma) -{ +void OPESmetad::addKernel(const double height,const std::vector& center,const std::vector& sigma) { bool no_match=true; - if(threshold2_!=0) - { + if(threshold2_!=0) { unsigned taker_k=getMergeableKernel(center,kernels_.size()); - if(taker_kgiver_k) //saves time when erasing + if(taker_k>giver_k) { //saves time when erasing std::swap(taker_k,giver_k); + } mergeKernels(kernels_[taker_k],kernels_[giver_k]); delta_kernels_.push_back(kernels_[taker_k]); kernels_.erase(kernels_.begin()+giver_k); - if(nlist_) - { + if(nlist_) { unsigned giver_nk=0; bool found_giver=false; - for(unsigned nk=0; nk::addKernel(const double height,const std::vector& c } } } - if(no_match) - { + if(no_match) { kernels_.emplace_back(height,center,sigma); delta_kernels_.emplace_back(height,center,sigma); - if(nlist_) + if(nlist_) { nlist_index_.push_back(kernels_.size()-1); + } } } template -void OPESmetad::addKernel(const double height,const std::vector& center,const std::vector& sigma,const double logweight) -{ +void OPESmetad::addKernel(const double height,const std::vector& center,const std::vector& sigma,const double logweight) { addKernel(height,center,sigma); //write to file kernelsOfile_.printField("time",getTime()); - for(unsigned i=0; igetName(),sigma[i]); + } kernelsOfile_.printField("height",height); kernelsOfile_.printField("logweight",logweight); kernelsOfile_.printField(); } template -unsigned OPESmetad::getMergeableKernel(const std::vector& giver_center,const unsigned giver_k) -{ //returns kernels_.size() if no match is found +unsigned OPESmetad::getMergeableKernel(const std::vector& giver_center,const unsigned giver_k) { + //returns kernels_.size() if no match is found unsigned min_k=kernels_.size(); double min_norm2=threshold2_; - if(!nlist_) - { + if(!nlist_) { #pragma omp parallel num_threads(NumOMP_) { unsigned min_k_omp = min_k; double min_norm2_omp = threshold2_; #pragma omp for nowait - for(unsigned k=rank_; k=min_norm2_omp) + if(norm2>=min_norm2_omp) { break; + } } - if(norm2=min_norm2) + if(norm2>=min_norm2) { break; + } } - if(norm21) - { + if(NumParallel_>1) { std::vector all_min_norm2(NumParallel_); std::vector all_min_k(NumParallel_); comm.Allgather(min_norm2,all_min_norm2); @@ -1490,89 +1456,85 @@ unsigned OPESmetad::getMergeableKernel(const std::vector& giver_ce } template -void OPESmetad::updateNlist(const std::vector& new_center) -{ - if(kernels_.size()==0) //no need to check for neighbors +void OPESmetad::updateNlist(const std::vector& new_center) { + if(kernels_.size()==0) { //no need to check for neighbors return; + } nlist_center_=new_center; nlist_index_.clear(); //first we gather all the nlist_index - if(NumOMP_==1 || (unsigned)kernels_.size()<2*NumOMP_*NumParallel_) - { - for(unsigned k=rank_; k private_nlist_index; #pragma omp for nowait - for(unsigned k=rank_; k1) - { + if(NumParallel_>1) { std::vector all_nlist_size(NumParallel_); all_nlist_size[rank_]=nlist_index_.size(); comm.Sum(all_nlist_size); unsigned tot_size=0; - for(unsigned r=0; r0) - { + } + if(tot_size>0) { std::vector disp(NumParallel_); - for(unsigned r=0; r local_nlist_index=nlist_index_; nlist_index_.resize(tot_size); comm.Allgatherv(local_nlist_index,nlist_index_,&all_nlist_size[0],&disp[0]); - if(recursive_merge_) + if(recursive_merge_) { std::sort(nlist_index_.begin(),nlist_index_.end()); + } } } //calculate the square deviation std::vector dev2(ncv_,0.); - for(unsigned k=rank_; k1) + if(NumParallel_>1) { comm.Sum(dev2); - for(unsigned i=0; iset(nlist_index_.size()); getPntrToComponent("nlsteps")->set(nlist_steps_); @@ -1581,20 +1543,17 @@ void OPESmetad::updateNlist(const std::vector& new_center) } template -void OPESmetad::dumpStateToFile() -{ +void OPESmetad::dumpStateToFile() { //gather adaptive sigma info if needed //doing this while writing to file can lead to misterious slowdowns std::vector all_sigma0; std::vector all_av_cv; std::vector all_av_M2; - if(adaptive_sigma_ && NumWalkers_>1) - { + if(adaptive_sigma_ && NumWalkers_>1) { all_sigma0.resize(NumWalkers_*ncv_); all_av_cv.resize(NumWalkers_*ncv_); all_av_M2.resize(NumWalkers_*ncv_); - if(comm.Get_rank()==0) - { + if(comm.Get_rank()==0) { multi_sim_comm.Allgather(sigma0_,all_sigma0); multi_sim_comm.Allgather(av_cv_,all_av_cv); multi_sim_comm.Allgather(av_M2_,all_av_M2); @@ -1605,10 +1564,11 @@ void OPESmetad::dumpStateToFile() } //rewrite header or rewind file - if(storeOldStates_) + if(storeOldStates_) { stateOfile_.clearFields(); - else if(walker_rank_==0) + } else if(walker_rank_==0) { stateOfile_.rewind(); + } //define fields stateOfile_.addConstantField("action"); stateOfile_.addConstantField("biasfactor"); @@ -1619,23 +1579,17 @@ void OPESmetad::dumpStateToFile() stateOfile_.addConstantField("sum_weights"); stateOfile_.addConstantField("sum_weights2"); stateOfile_.addConstantField("counter"); - if(adaptive_sigma_) - { + if(adaptive_sigma_) { stateOfile_.addConstantField("adaptive_counter"); - if(NumWalkers_==1) - { - for(unsigned i=0; igetName()); stateOfile_.addConstantField("av_cv_"+getPntrToArgument(i)->getName()); stateOfile_.addConstantField("av_M2_"+getPntrToArgument(i)->getName()); } - } - else - { + } else { for(unsigned w=0; wgetName()+"_"+std::to_string(w); stateOfile_.addConstantField("sigma0_"+arg_iw); stateOfile_.addConstantField("av_cv_"+arg_iw); @@ -1644,8 +1598,9 @@ void OPESmetad::dumpStateToFile() } } //print fields - for(unsigned i=0; i::dumpStateToFile() stateOfile_.printField("sum_weights",sum_weights_); stateOfile_.printField("sum_weights2",sum_weights2_); stateOfile_.printField("counter",counter_); - if(adaptive_sigma_) - { + if(adaptive_sigma_) { stateOfile_.printField("adaptive_counter",adaptive_counter_); - if(NumWalkers_==1) - { - for(unsigned i=0; igetName(),sigma0_[i]); stateOfile_.printField("av_cv_"+getPntrToArgument(i)->getName(),av_cv_[i]); stateOfile_.printField("av_M2_"+getPntrToArgument(i)->getName(),av_M2_[i]); } - } - else - { + } else { for(unsigned w=0; wgetName()+"_"+std::to_string(w); stateOfile_.printField("sigma0_"+arg_iw,all_sigma0[w*ncv_+i]); stateOfile_.printField("av_cv_"+arg_iw,all_av_cv[w*ncv_+i]); @@ -1680,69 +1629,72 @@ void OPESmetad::dumpStateToFile() } } //print kernels - for(unsigned k=0; kgetName(),kernels_[k].sigma[i]); + } stateOfile_.printField("height",kernels_[k].height); stateOfile_.printField(); } //make sure file is written even if small - if(!storeOldStates_) + if(!storeOldStates_) { stateOfile_.flush(); + } } template -inline double OPESmetad::evaluateKernel(const kernel& G,const std::vector& x) const -{ //NB: cannot be a method of kernel class, because uses external variables (for cutoff) +inline double OPESmetad::evaluateKernel(const kernel& G,const std::vector& x) const { + //NB: cannot be a method of kernel class, because uses external variables (for cutoff) double norm2=0; - for(unsigned i=0; i=cutoff2_) + if(norm2>=cutoff2_) { return 0; + } } return G.height*(std::exp(-0.5*norm2)-val_at_cutoff_); } template -inline double OPESmetad::evaluateKernel(const kernel& G,const std::vector& x, std::vector& acc_der, std::vector& dist) -{ //NB: cannot be a method of kernel class, because uses external variables (for cutoff) +inline double OPESmetad::evaluateKernel(const kernel& G,const std::vector& x, std::vector& acc_der, std::vector& dist) { + //NB: cannot be a method of kernel class, because uses external variables (for cutoff) double norm2=0; - for(unsigned i=0; i=cutoff2_) + if(norm2>=cutoff2_) { return 0; + } } const double val=G.height*(std::exp(-0.5*norm2)-val_at_cutoff_); - for(unsigned i=0; i -inline void OPESmetad::mergeKernels(kernel& k1,const kernel& k2) -{ +inline void OPESmetad::mergeKernels(kernel& k1,const kernel& k2) { const double h=k1.height+k2.height; - for(unsigned i=0; iisPeriodic(); - if(isPeriodic_i) - k1.center[i]=k2.center[i]+difference(i,k2.center[i],k1.center[i]); //fix PBC + if(isPeriodic_i) { + k1.center[i]=k2.center[i]+difference(i,k2.center[i],k1.center[i]); //fix PBC + } const double c_i=(k1.height*k1.center[i]+k2.height*k2.center[i])/h; const double ss_k1_part=k1.height*(k1.sigma[i]*k1.sigma[i]+k1.center[i]*k1.center[i]); const double ss_k2_part=k2.height*(k2.sigma[i]*k2.sigma[i]+k2.center[i]*k2.center[i]); const double ss_i=(ss_k1_part+ss_k2_part)/h-c_i*c_i; - if(isPeriodic_i) + if(isPeriodic_i) { k1.center[i]=bringBackInPbc(i,c_i); - else + } else { k1.center[i]=c_i; + } k1.sigma[i]=sqrt(ss_i); } k1.height=h; diff --git a/src/pamm/HBPammMatrix.cpp b/src/pamm/HBPammMatrix.cpp index d2b85ed537..3978d4db82 100644 --- a/src/pamm/HBPammMatrix.cpp +++ b/src/pamm/HBPammMatrix.cpp @@ -85,87 +85,157 @@ class HBPammMatrix : public adjmat::AdjacencyMatrixBase { PLUMED_REGISTER_ACTION(HBPammMatrix,"HBPAMM_MATRIX") void HBPammMatrix::registerKeywords( Keywords& keys ) { - adjmat::AdjacencyMatrixBase::registerKeywords( keys ); keys.use("GROUPC"); + adjmat::AdjacencyMatrixBase::registerKeywords( keys ); + keys.use("GROUPC"); keys.add("compulsory","ORDER","dah","the order in which the groups are specified in the input. Can be dah (donor/acceptor/hydrogens), " "adh (acceptor/donor/hydrogens) or hda (hydrogens/donor/hydrogens"); keys.add("compulsory","CLUSTERS","the name of the file that contains the definitions of all the kernels for PAMM"); keys.add("compulsory","REGULARISE","0.001","don't allow the denominator to be smaller then this value"); keys.add("compulsory","GAUSS_CUTOFF","6.25","the cutoff at which to stop evaluating the kernel function is set equal to sqrt(2*x)*(max(adc)+cov(adc))"); - keys.needsAction("PAMM"); keys.needsAction("ONES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("PAMM"); + keys.needsAction("ONES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); } HBPammMatrix::HBPammMatrix(const ActionOptions& ao): Action(ao), - AdjacencyMatrixBase(ao) -{ - double DP2CUTOFF; parse("GAUSS_CUTOFF",DP2CUTOFF); std::string sorder; parse("ORDER",sorder); + AdjacencyMatrixBase(ao) { + double DP2CUTOFF; + parse("GAUSS_CUTOFF",DP2CUTOFF); + std::string sorder; + parse("ORDER",sorder); if( sorder=="dah" ) { - incoord_to_hbcoord(0,0)=1; incoord_to_hbcoord(0,1)=-1; incoord_to_hbcoord(0,2)=0; - incoord_to_hbcoord(1,0)=1; incoord_to_hbcoord(1,1)=1; incoord_to_hbcoord(1,2)=0; - incoord_to_hbcoord(2,0)=0; incoord_to_hbcoord(2,1)=0; incoord_to_hbcoord(2,2)=1; + incoord_to_hbcoord(0,0)=1; + incoord_to_hbcoord(0,1)=-1; + incoord_to_hbcoord(0,2)=0; + incoord_to_hbcoord(1,0)=1; + incoord_to_hbcoord(1,1)=1; + incoord_to_hbcoord(1,2)=0; + incoord_to_hbcoord(2,0)=0; + incoord_to_hbcoord(2,1)=0; + incoord_to_hbcoord(2,2)=1; log.printf(" GROUPA is list of donor atoms \n"); } else if( sorder=="adh" ) { - incoord_to_hbcoord(0,0)=-1; incoord_to_hbcoord(0,1)=1; incoord_to_hbcoord(0,2)=0; - incoord_to_hbcoord(1,0)=1; incoord_to_hbcoord(1,1)=1; incoord_to_hbcoord(1,2)=0; - incoord_to_hbcoord(2,0)=0; incoord_to_hbcoord(2,1)=0; incoord_to_hbcoord(2,2)=1; + incoord_to_hbcoord(0,0)=-1; + incoord_to_hbcoord(0,1)=1; + incoord_to_hbcoord(0,2)=0; + incoord_to_hbcoord(1,0)=1; + incoord_to_hbcoord(1,1)=1; + incoord_to_hbcoord(1,2)=0; + incoord_to_hbcoord(2,0)=0; + incoord_to_hbcoord(2,1)=0; + incoord_to_hbcoord(2,2)=1; log.printf(" GROUPA is list of acceptor atoms \n"); } else if( sorder=="hda" ) { - incoord_to_hbcoord(0,0)=-1; incoord_to_hbcoord(0,1)=0; incoord_to_hbcoord(0,2)=1; - incoord_to_hbcoord(1,0)=1; incoord_to_hbcoord(1,1)=0; incoord_to_hbcoord(1,2)=1; - incoord_to_hbcoord(2,0)=0; incoord_to_hbcoord(2,1)=1; incoord_to_hbcoord(2,2)=0; + incoord_to_hbcoord(0,0)=-1; + incoord_to_hbcoord(0,1)=0; + incoord_to_hbcoord(0,2)=1; + incoord_to_hbcoord(1,0)=1; + incoord_to_hbcoord(1,1)=0; + incoord_to_hbcoord(1,2)=1; + incoord_to_hbcoord(2,0)=0; + incoord_to_hbcoord(2,1)=1; + incoord_to_hbcoord(2,2)=0; log.printf(" GROUPA is list of hydrogen atoms \n"); - } else plumed_error(); + } else { + plumed_error(); + } // Read in the regularisation parameter parse("REGULARISE",regulariser); // Read in the kernels - double sqr2pi = sqrt(2*pi); double sqrt2pi3 = sqr2pi*sqr2pi*sqr2pi; - std::string fname; parse("CLUSTERS", fname); double sfmax=0, ww; Vector cent; Tensor covar; - IFile ifile; ifile.open(fname); ifile.allowIgnoredFields(); + double sqr2pi = sqrt(2*pi); + double sqrt2pi3 = sqr2pi*sqr2pi*sqr2pi; + std::string fname; + parse("CLUSTERS", fname); + double sfmax=0, ww; + Vector cent; + Tensor covar; + IFile ifile; + ifile.open(fname); + ifile.allowIgnoredFields(); for(unsigned k=0;; ++k) { - if( !ifile.scanField("height",ww) ) break; - ifile.scanField("ptc",cent[0]); ifile.scanField("ssc",cent[1]); ifile.scanField("adc",cent[2]); - ifile.scanField("sigma_ptc_ptc",covar[0][0]); ifile.scanField("sigma_ptc_ssc",covar[0][1]); ifile.scanField("sigma_ptc_adc",covar[0][2]); - covar[1][0] = covar[0][1]; ifile.scanField("sigma_ssc_ssc",covar[1][1]); ifile.scanField("sigma_ssc_adc",covar[1][2]); - covar[2][0] = covar[0][2]; covar[2][1] = covar[1][2]; ifile.scanField("sigma_adc_adc",covar[2][2]); + if( !ifile.scanField("height",ww) ) { + break; + } + ifile.scanField("ptc",cent[0]); + ifile.scanField("ssc",cent[1]); + ifile.scanField("adc",cent[2]); + ifile.scanField("sigma_ptc_ptc",covar[0][0]); + ifile.scanField("sigma_ptc_ssc",covar[0][1]); + ifile.scanField("sigma_ptc_adc",covar[0][2]); + covar[1][0] = covar[0][1]; + ifile.scanField("sigma_ssc_ssc",covar[1][1]); + ifile.scanField("sigma_ssc_adc",covar[1][2]); + covar[2][0] = covar[0][2]; + covar[2][1] = covar[1][2]; + ifile.scanField("sigma_adc_adc",covar[2][2]); weight.push_back( ww / ( sqrt2pi3 * sqrt(covar.determinant()) ) ); - centers.push_back( cent ); kmat.push_back( covar.inverse() ); - - Vector eigval; Tensor eigvec; diagMatSym( covar, eigval, eigvec ); - unsigned ind_maxeval=0; double max_eval=eigval[0]; + centers.push_back( cent ); + kmat.push_back( covar.inverse() ); + + Vector eigval; + Tensor eigvec; + diagMatSym( covar, eigval, eigvec ); + unsigned ind_maxeval=0; + double max_eval=eigval[0]; for(unsigned i=1; i<3; ++i) { - if( eigval[i]>max_eval ) { max_eval=eigval[i]; ind_maxeval=i; } + if( eigval[i]>max_eval ) { + max_eval=eigval[i]; + ind_maxeval=i; + } } double rcut = cent[2] + sqrt(2.0*DP2CUTOFF)*fabs(sqrt(max_eval)*eigvec(2,ind_maxeval)); - if( rcut > sfmax ) sfmax = rcut; + if( rcut > sfmax ) { + sfmax = rcut; + } ifile.scanField(); } - ifile.close(); setLinkCellCutoff( false, sfmax ); + ifile.close(); + setLinkCellCutoff( false, sfmax ); } double HBPammMatrix::calculateWeight( const Vector& pos1, const Vector& pos2, const unsigned& natoms, MultiValue& myvals ) const { Vector ddij, ddik, ddin, in_dists, hb_pamm_dists, hb_pamm_ders, real_ders; - ddin = pbcDistance( pos1, pos2 ); in_dists[2] = ddin.modulo(); - if( in_dists[2]0 ) mwords += " GROUP=" + site_str; - else { - std::string d_str; parse("DONORS",d_str); mwords += " GROUPA=" + d_str; - std::string a_str; parse("ACCEPTORS",a_str); mwords += " GROUPB=" + a_str; + std::string site_str; + parse("SITES",site_str); + if( site_str.length()>0 ) { + mwords += " GROUP=" + site_str; + } else { + std::string d_str; + parse("DONORS",d_str); + mwords += " GROUPA=" + d_str; + std::string a_str; + parse("ACCEPTORS",a_str); + mwords += " GROUPB=" + a_str; } - std::string h_str; parse("HYDROGENS",h_str); mwords += " GROUPC=" + h_str + " ORDER=dah"; + std::string h_str; + parse("HYDROGENS",h_str); + mwords += " GROUPC=" + h_str + " ORDER=dah"; } else if( getName()=="HBPAMM_SA" ) { - std::string site_str; parse("SITES",site_str); - if( site_str.length()>0 ) mwords += " GROUP=" + site_str; - else { - std::string a_str; parse("ACCEPTORS",a_str); mwords += " GROUPA=" + a_str; - std::string d_str; parse("DONORS",d_str); mwords += " GROUPB=" + d_str; + std::string site_str; + parse("SITES",site_str); + if( site_str.length()>0 ) { + mwords += " GROUP=" + site_str; + } else { + std::string a_str; + parse("ACCEPTORS",a_str); + mwords += " GROUPA=" + a_str; + std::string d_str; + parse("DONORS",d_str); + mwords += " GROUPB=" + d_str; } - std::string h_str; parse("HYDROGENS",h_str); mwords += " GROUPC=" + h_str + " ORDER=adh"; + std::string h_str; + parse("HYDROGENS",h_str); + mwords += " GROUPC=" + h_str + " ORDER=adh"; } else if( getName()=="HBPAMM_SH" ) { - std::string h_str; parse("HYDROGENS",h_str); mwords += " GROUPA=" + h_str + " ORDER=hda"; - std::string site_str; parse("SITES",site_str); + std::string h_str; + parse("HYDROGENS",h_str); + mwords += " GROUPA=" + h_str + " ORDER=hda"; + std::string site_str; + parse("SITES",site_str); if( site_str.length()>0 ) { mwords += " GROUPB=" + site_str; mwords += " GROUPC=" + site_str; } else { - std::string d_str; parse("DONORS",d_str); mwords += " GROUPB=" + d_str; - std::string a_str; parse("ACCEPTORS",a_str); mwords += " GROUPC=" + a_str; + std::string d_str; + parse("DONORS",d_str); + mwords += " GROUPB=" + d_str; + std::string a_str; + parse("ACCEPTORS",a_str); + mwords += " GROUPC=" + a_str; } } - std::map keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); readInputLine( mwords + " " + convertInputLineToString() ); ActionWithValue* mb=plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_mat"); - plumed_assert( mb ); std::string nsize; Tools::convert( (mb->copyOutput(getShortcutLabel() + "_mat"))->getShape()[1], nsize ); + plumed_assert( mb ); + std::string nsize; + Tools::convert( (mb->copyOutput(getShortcutLabel() + "_mat"))->getShape()[1], nsize ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + nsize ); readInputLine( getShortcutLabel() + ": MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_mat," + getShortcutLabel() + "_ones"); multicolvar::MultiColvarShortcuts::expandFunctions( getShortcutLabel(), getShortcutLabel(), "", keymap, this ); diff --git a/src/pamm/PAMM.cpp b/src/pamm/PAMM.cpp index 00842de148..eb28385fb3 100644 --- a/src/pamm/PAMM.cpp +++ b/src/pamm/PAMM.cpp @@ -124,58 +124,79 @@ void PAMM::registerKeywords( Keywords& keys ) { keys.add("compulsory","REGULARISE","0.001","don't allow the denominator to be smaller then this value"); keys.add("compulsory","KERNELS","all","which kernels are we computing the PAMM values for"); multicolvar::MultiColvarShortcuts::shortcutKeywords( keys ); - keys.needsAction("KERNEL"); keys.needsAction("COMBINE"); + keys.needsAction("KERNEL"); + keys.needsAction("COMBINE"); } PAMM::PAMM(const ActionOptions& ao) : Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Must get list of input value names - std::vector valnames; parseVector("ARG",valnames); + std::vector valnames; + parseVector("ARG",valnames); // Create input values std::string argstr=" ARG=" + valnames[0]; - for(unsigned j=1; j keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + std::string kchoice; + parse("KERNELS",kchoice); + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); if( kchoice=="all" ) { for(unsigned k=0; k awords=Tools::getWords(kchoice,"\t\n ,"); Tools::interpretRanges( awords ); + std::vector awords=Tools::getWords(kchoice,"\t\n ,"); + Tools::interpretRanges( awords ); for(unsigned k=0; k. using namespace std; -namespace PLMD -{ -namespace piv -{ +namespace PLMD { +namespace piv { //+PLUMEDOC PIVMOD_COLVAR PIV /* @@ -183,8 +181,7 @@ When using PIV please cite \cite pipolo2017navigating . */ //+ENDPLUMEDOC -class PIV : public Colvar -{ +class PIV : public Colvar { private: bool pbc, serial, timer; ForwardDecl stopwatch_fwd; @@ -234,8 +231,7 @@ class PIV : public Colvar PLUMED_REGISTER_ACTION(PIV,"PIV") -void PIV::registerKeywords( Keywords& keys ) -{ +void PIV::registerKeywords( Keywords& keys ) { Colvar::registerKeywords( keys ); keys.add("numbered","SWITCH","The switching functions parameter." "You should specify a Switching function for all PIV blocks." @@ -294,8 +290,7 @@ PIV::PIV(const ActionOptions&ao): doneigh(false), test(false), CompDer(false), - com(false) -{ + com(false) { log << "Starting PIV Constructor\n"; { @@ -322,7 +317,9 @@ PIV::PIV(const ActionOptions&ao): // Precision on the real-to-integer transformation for the sorting parse("PRECISION",Nprec); - if(Nprec<2) error("Precision must be => 2"); + if(Nprec<2) { + error("Precision must be => 2"); + } // PBC bool nopbc=!pbc; @@ -344,7 +341,9 @@ PIV::PIV(const ActionOptions&ao): // Derivatives parseFlag("DERIVATIVES",CompDer); - if(CompDer) log << "Computing Derivatives\n"; + if(CompDer) { + log << "Computing Derivatives\n"; + } // Timing parseFlag("TIMER",timer); @@ -364,7 +363,9 @@ PIV::PIV(const ActionOptions&ao): // Test parseFlag("COM",com); - if(com) log << "Building PIV using COMs\n"; + if(com) { + log << "Building PIV using COMs\n"; + } // Volume Scaling parse("VOLUME",Vol0); @@ -546,9 +547,15 @@ PIV::PIV(const ActionOptions&ao): parseVector("NL_SKIN",nl_skin); //if(nl_skin.size()!=getNumberOfArguments() && nl_skin.size()!=0) error("not enough values for NL_SKIN"); for (unsigned j=0; jprev_stp&&getStep()%updatePIV==0)||CompDer) { - if (CompDer) log << " Step " << getStep() << " Computing Derivatives NON-SORTED PIV \n"; + if (CompDer) { + log << " Step " << getStep() << " Computing Derivatives NON-SORTED PIV \n"; + } // // build COMs from positions if requested if(com) { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } for(unsigned j=0; jsize(); i+=stride) { unsigned i0=(nl[j]->getClosePairAtomNumber(i).first).index(); unsigned i1=(nl[j]->getClosePairAtomNumber(i).second).index(); @@ -953,8 +975,12 @@ void PIV::calculate() A0[Vint].push_back(i0); A1[Vint].push_back(i1); } - if(timer) stopwatch.stop("1 Build cPIV"); - if(timer) stopwatch.start("2 Sort cPIV"); + if(timer) { + stopwatch.stop("1 Build cPIV"); + } + if(timer) { + stopwatch.start("2 Sort cPIV"); + } if(!doserial && comm.initialized()) { // Vectors keeping track of the dimension and the starting-position of the rank-specific pair vector in the big pair vector. std:: vector Vdim(stride,0); @@ -1017,8 +1043,12 @@ void PIV::calculate() // Loop on blocks //for(unsigned m=0;m PytorchModel::tensor_to_vector(const torch::Tensor& x) { PytorchModel::PytorchModel(const ActionOptions&ao): Action(ao), - Function(ao) -{ + Function(ao) { // print libtorch version std::stringstream ss; ss << TORCH_VERSION_MAJOR << "." << TORCH_VERSION_MINOR << "." << TORCH_VERSION_PATCH; @@ -134,8 +132,7 @@ PytorchModel::PytorchModel(const ActionOptions&ao): infile.close(); if (exist) { plumed_merror("Cannot load FILE: '"+fname+"'. Please check that it is a Pytorch compiled model (exported with 'torch.jit.trace' or 'torch.jit.script')."); - } - else { + } else { plumed_merror("The FILE: '"+fname+"' does not exist."); } } @@ -200,8 +197,9 @@ void PytorchModel::calculate() { // retrieve arguments vector current_S(_n_in); - for(unsigned i=0; i<_n_in; i++) + for(unsigned i=0; i<_n_in; i++) { current_S[i]=getArgument(i); + } //convert to tensor torch::Tensor input_S = torch::tensor(current_S).view({1,_n_in}).to(device); input_S.set_requires_grad(true); @@ -223,8 +221,9 @@ void PytorchModel::calculate() { vector der = this->tensor_to_vector ( gradient ); string name_comp = "node-"+std::to_string(j); //set derivatives of component j - for(unsigned i=0; i<_n_in; i++) + for(unsigned i=0; i<_n_in; i++) { setDerivative( getPntrToComponent(name_comp),i, der[i] ); + } } //set CV values diff --git a/src/refdist/Difference.cpp b/src/refdist/Difference.cpp index e58c3de4c9..3e389b3dbc 100644 --- a/src/refdist/Difference.cpp +++ b/src/refdist/Difference.cpp @@ -82,39 +82,58 @@ void Difference::registerKeywords(Keywords& keys) { } void Difference::read( ActionWithArguments* action ) { - if( action->getNumberOfArguments()!=2 ) action->error("should be two arguments to this action"); + if( action->getNumberOfArguments()!=2 ) { + action->error("should be two arguments to this action"); + } if( action->getPntrToArgument(0)->getRank()==action->getPntrToArgument(1)->getRank() ) { std::vector shape( action->getPntrToArgument(0)->getShape() ); for(unsigned i=0; igetPntrToArgument(1)->getShape()[i] ) action->error("shapes of input actions do not match"); + if( shape[i]!=action->getPntrToArgument(1)->getShape()[i] ) { + action->error("shapes of input actions do not match"); + } } } periodic=false; if( action->getPntrToArgument(0)->isPeriodic() ) { - periodic=true; action->getPntrToArgument(0)->getDomain( min0, max0 ); + periodic=true; + action->getPntrToArgument(0)->getDomain( min0, max0 ); if( !action->getPntrToArgument(1)->isConstant() && !action->getPntrToArgument(1)->isPeriodic() ) { action->error("period for input variables " + action->getPntrToArgument(0)->getName() + " and " + action->getPntrToArgument(1)->getName() + " should be the same 0"); } if( !action->getPntrToArgument(1)->isConstant() ) { - std::string min1, max1; action->getPntrToArgument(1)->getDomain( min1, max1 ); - if( min0!=min0 || max0!=max1 ) action->error("domain for input variables should be the same"); - } else action->getPntrToArgument(1)->setDomain( min0, max0 ); + std::string min1, max1; + action->getPntrToArgument(1)->getDomain( min1, max1 ); + if( min0!=min0 || max0!=max1 ) { + action->error("domain for input variables should be the same"); + } + } else { + action->getPntrToArgument(1)->setDomain( min0, max0 ); + } } else if( action->getPntrToArgument(1)->isPeriodic() ) { - periodic=true; action->getPntrToArgument(1)->getDomain( min0, max0 ); + periodic=true; + action->getPntrToArgument(1)->getDomain( min0, max0 ); if( !action->getPntrToArgument(1)->isConstant() ) { action->error("period for input variables " + action->getPntrToArgument(0)->getName() + " and " + action->getPntrToArgument(1)->getName() + " should be the same 1"); - } else action->getPntrToArgument(0)->setDomain( min0, max0 ); + } else { + action->getPntrToArgument(0)->setDomain( min0, max0 ); + } } } void Difference::setPeriodicityForOutputs( ActionWithValue* action ) { - if( periodic ) action->setPeriodic( min0, max0 ); - else action->setNotPeriodic(); + if( periodic ) { + action->setPeriodic( min0, max0 ); + } else { + action->setNotPeriodic(); + } } void Difference::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { - plumed_dbg_assert( args.size()==2 ); vals[0] = action->getPntrToArgument(0)->difference( args[1], args[0] ); derivatives(0,0) = 1.0; derivatives(0,1)=-1; + plumed_dbg_assert( args.size()==2 ); + vals[0] = action->getPntrToArgument(0)->difference( args[1], args[0] ); + derivatives(0,0) = 1.0; + derivatives(0,1)=-1; } } diff --git a/src/refdist/Displacement.cpp b/src/refdist/Displacement.cpp index 5db52c395a..ca8da2afda 100644 --- a/src/refdist/Displacement.cpp +++ b/src/refdist/Displacement.cpp @@ -53,23 +53,31 @@ void Displacement::registerKeywords( Keywords& keys ) { keys.add("compulsory","ARG1","The point that we are calculating the distance from"); keys.add("compulsory","ARG2","The point that we are calculating the distance to"); keys.setValueDescription("the differences between the input arguments"); - keys.needsAction("DIFFERENCE"); keys.needsAction("TRANSPOSE"); keys.needsAction("VSTACK"); + keys.needsAction("DIFFERENCE"); + keys.needsAction("TRANSPOSE"); + keys.needsAction("VSTACK"); } std::string Displacement::fixArgumentDot( const std::string& argin ) { - std::string argout = argin; std::size_t dot=argin.find("."); - if( dot!=std::string::npos ) argout = argin.substr(0,dot) + "_" + argin.substr(dot+1); + std::string argout = argin; + std::size_t dot=argin.find("."); + if( dot!=std::string::npos ) { + argout = argin.substr(0,dot) + "_" + argin.substr(dot+1); + } return argout; } Displacement::Displacement( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read in argument names - std::vector arg1f, arg2f; parseVector("ARG1",arg1f); parseVector("ARG2",arg2f); + std::vector arg1f, arg2f; + parseVector("ARG1",arg1f); + parseVector("ARG2",arg2f); // Check if one of the input arguments is a reference cluster - if( arg1f.size()!=arg2f.size() ) error("number of arguments specified to ARG1 should be same as number for ARG2"); + if( arg1f.size()!=arg2f.size() ) { + error("number of arguments specified to ARG1 should be same as number for ARG2"); + } Value* val1=getValueWithLabel( arg1f[0] ); if( arg1f.size()==1 && val1->getRank()!=0 ) { @@ -77,20 +85,34 @@ Displacement::Displacement( const ActionOptions& ao): if( val1->getNumberOfValues()==val2->getNumberOfValues() ) { readInputLine( getShortcutLabel() + "_" + fixArgumentDot(arg1f[0]) + "_diff: DIFFERENCE ARG=" + arg1f[0] + "," + arg2f[0] ); readInputLine( getShortcutLabel() + ": TRANSPOSE ARG=" + getShortcutLabel() + "_" + fixArgumentDot(arg1f[0]) + "_diff"); - } else readInputLine( getShortcutLabel() + ": DIFFERENCE ARG=" + arg1f[0] + "," + arg2f[0] ); + } else { + readInputLine( getShortcutLabel() + ": DIFFERENCE ARG=" + arg1f[0] + "," + arg2f[0] ); + } } else { - for(unsigned i=0; i( sname ); - if( !vv ) error("cannot find value with name " + name ); - if( dot==std::string::npos ) return vv->copyOutput(0); - if( !vv->exists(name) ) error("cannot find value with name " + name ); + if( !vv ) { + error("cannot find value with name " + name ); + } + if( dot==std::string::npos ) { + return vv->copyOutput(0); + } + if( !vv->exists(name) ) { + error("cannot find value with name " + name ); + } return vv->copyOutput( name ); } diff --git a/src/refdist/EuclideanDistance.cpp b/src/refdist/EuclideanDistance.cpp index c1a1943eb2..7f3858b61c 100644 --- a/src/refdist/EuclideanDistance.cpp +++ b/src/refdist/EuclideanDistance.cpp @@ -51,21 +51,30 @@ void EuclideanDistance::registerKeywords( Keywords& keys ) { keys.add("compulsory","ARG2","The point that we are calculating the distance to"); keys.addFlag("SQUARED",false,"The squared distance should be calculated"); keys.setValueDescription("the euclidean distances between the input vectors"); - keys.needsAction("DISPLACEMENT"); keys.needsAction("CUSTOM"); - keys.needsAction("TRANSPOSE"); keys.needsAction("MATRIX_PRODUCT_DIAGONAL"); + keys.needsAction("DISPLACEMENT"); + keys.needsAction("CUSTOM"); + keys.needsAction("TRANSPOSE"); + keys.needsAction("MATRIX_PRODUCT_DIAGONAL"); } EuclideanDistance::EuclideanDistance( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - std::string arg1, arg2; parse("ARG1",arg1); parse("ARG2",arg2); + ActionShortcut(ao) { + std::string arg1, arg2; + parse("ARG1",arg1); + parse("ARG2",arg2); // Vectors are in rows here readInputLine( getShortcutLabel() + "_diff: DISPLACEMENT ARG1=" + arg1 + " ARG2=" + arg2 ); // Get the action that computes the differences - ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_diff"); plumed_assert( av ); + ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_diff"); + plumed_assert( av ); // Check if squared - bool squared; parseFlag("SQUARED",squared); std::string olab = getShortcutLabel(); if( !squared ) olab += "_2"; + bool squared; + parseFlag("SQUARED",squared); + std::string olab = getShortcutLabel(); + if( !squared ) { + olab += "_2"; + } // Deal with an annoying corner case when displacement has a single argument if( av->copyOutput(0)->getRank()==0 ) { readInputLine( olab + ": CUSTOM ARG=" + getShortcutLabel() + "_diff FUNC=x*x PERIODIC=NO"); @@ -74,7 +83,9 @@ EuclideanDistance::EuclideanDistance( const ActionOptions& ao): readInputLine( getShortcutLabel() + "_diffT: TRANSPOSE ARG=" + getShortcutLabel() + "_diff"); readInputLine( olab + ": MATRIX_PRODUCT_DIAGONAL ARG=" + getShortcutLabel() + "_diff," + getShortcutLabel() + "_diffT"); } - if( !squared ) readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_2 FUNC=sqrt(x) PERIODIC=NO"); + if( !squared ) { + readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_2 FUNC=sqrt(x) PERIODIC=NO"); + } } } diff --git a/src/refdist/Kernel.cpp b/src/refdist/Kernel.cpp index 5176ea3c77..a8ea4cb9d1 100644 --- a/src/refdist/Kernel.cpp +++ b/src/refdist/Kernel.cpp @@ -63,98 +63,169 @@ void Kernel::registerKeywords(Keywords& keys) { keys.add("compulsory","NUMBER","1","if there are multiple sets of kernel parameters in the input file which set of kernel parameters would you like to read in here"); keys.addFlag("NORMALIZED",false,"would you like the kernel function to be normalized"); keys.setValueDescription("the value of the kernel evaluated at the argument values"); - keys.needsAction("CONSTANT"); keys.needsAction("CUSTOM"); keys.needsAction("NORMALIZED_EUCLIDEAN_DISTANCE"); - keys.needsAction("PRODUCT"); keys.needsAction("INVERT_MATRIX"); keys.needsAction("MAHALANOBIS_DISTANCE"); - keys.needsAction("DIAGONALIZE"); keys.needsAction("CONCATENATE"); keys.needsAction("DETERMINANT"); + keys.needsAction("CONSTANT"); + keys.needsAction("CUSTOM"); + keys.needsAction("NORMALIZED_EUCLIDEAN_DISTANCE"); + keys.needsAction("PRODUCT"); + keys.needsAction("INVERT_MATRIX"); + keys.needsAction("MAHALANOBIS_DISTANCE"); + keys.needsAction("DIAGONALIZE"); + keys.needsAction("CONCATENATE"); + keys.needsAction("DETERMINANT"); keys.needsAction("BESSEL"); } std::string Kernel::fixArgumentDot( const std::string& argin ) { - std::string argout = argin; std::size_t dot=argin.find("."); - if( dot!=std::string::npos ) argout = argin.substr(0,dot) + "_" + argin.substr(dot+1); + std::string argout = argin; + std::size_t dot=argin.find("."); + if( dot!=std::string::npos ) { + argout = argin.substr(0,dot) + "_" + argin.substr(dot+1); + } return argout; } Kernel::Kernel(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read in the arguments - std::vector argnames; parseVector("ARG",argnames); - if( argnames.size()==0 ) error("no arguments were specified"); + std::vector argnames; + parseVector("ARG",argnames); + if( argnames.size()==0 ) { + error("no arguments were specified"); + } // Now sort out the parameters - double weight; std::string fname; parse("REFERENCE",fname); bool usemahalanobis=false; + double weight; + std::string fname; + parse("REFERENCE",fname); + bool usemahalanobis=false; if( fname.length()>0 ) { - IFile ifile; ifile.open(fname); ifile.allowIgnoredFields(); - unsigned number; parse("NUMBER",number); bool readline=false; + IFile ifile; + ifile.open(fname); + ifile.allowIgnoredFields(); + unsigned number; + parse("NUMBER",number); + bool readline=false; // Create actions to hold the position of the center for(unsigned line=0; line center(argnames.size()); parseVector("CENTER",center); - for(unsigned i=0; i center(argnames.size()); + parseVector("CENTER",center); + for(unsigned i=0; i1); + std::string cov; + parse("COVAR",cov); + usemahalanobis=(argnames.size()>1); if( !usemahalanobis ) { readInputLine( getShortcutLabel() + "_var: CONSTANT VALUES=" + cov ); } else { - std::string nvals; Tools::convert( argnames.size(), nvals ); + std::string nvals; + Tools::convert( argnames.size(), nvals ); readInputLine( getShortcutLabel() + "_cov: CONSTANT NCOLS=" + nvals + " NROWS=" + nvals + " VALUES=" + cov ); } } else if( sig.size()==argnames.size() ) { // And actions to hold the standard deviation - std::string valstr = sig[0]; for(unsigned i=1; i( getShortcutLabel() + "_dist_2_diff" ); plumed_assert( av ); - if( !av->copyOutput(0)->isPeriodic() ) error("VON_MISSES only works with periodic variables"); + ActionWithValue* av=plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_dist_2_diff" ); + plumed_assert( av ); + if( !av->copyOutput(0)->isPeriodic() ) { + error("VON_MISSES only works with periodic variables"); + } av->copyOutput(0)->getDomain(min,max); readInputLine( getShortcutLabel() + "_bes: BESSEL ORDER=0 ARG=" + getShortcutLabel() + "_vec"); readInputLine( getShortcutLabel() + "_cc: CUSTOM ARG=" + getShortcutLabel() + "_bes FUNC=("+max+"-"+min+")*x PERIODIC=NO"); readInputLine( getShortcutLabel() + "_vol: PRODUCT ARG=" + getShortcutLabel() + "_cc"); - } else error("only gaussian and von-misses kernels are normalizable"); + } else { + error("only gaussian and von-misses kernels are normalizable"); + } // And the (suitably normalized) kernel readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_dist_2," + getShortcutLabel() + "_vol FUNC=" + wstr + "*exp(-x/2)/y PERIODIC=NO"); } else { diff --git a/src/refdist/MahalanobisDistance.cpp b/src/refdist/MahalanobisDistance.cpp index 69dfe9659d..4bd003d342 100644 --- a/src/refdist/MahalanobisDistance.cpp +++ b/src/refdist/MahalanobisDistance.cpp @@ -53,44 +53,70 @@ void MahalanobisDistance::registerKeywords( Keywords& keys ) { keys.addFlag("SQUARED",false,"The squared distance should be calculated"); keys.addFlag("VON_MISSES",false,"Compute the mahalanobis distance in a way that is more sympathetic to the periodic boundary conditions"); keys.setValueDescription("the Mahalanobis distances between the input vectors"); - keys.needsAction("DISPLACEMENT"); keys.needsAction("CUSTOM"); keys.needsAction("OUTER_PRODUCT"); - keys.needsAction("TRANSPOSE"); keys.needsAction("MATRIX_PRODUCT_DIAGONAL"); keys.needsAction("CONSTANT"); - keys.needsAction("MATRIX_VECTOR_PRODUCT"); keys.needsAction("MATRIX_PRODUCT"); keys.needsAction("COMBINE"); + keys.needsAction("DISPLACEMENT"); + keys.needsAction("CUSTOM"); + keys.needsAction("OUTER_PRODUCT"); + keys.needsAction("TRANSPOSE"); + keys.needsAction("MATRIX_PRODUCT_DIAGONAL"); + keys.needsAction("CONSTANT"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("MATRIX_PRODUCT"); + keys.needsAction("COMBINE"); } MahalanobisDistance::MahalanobisDistance( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - std::string arg1, arg2, metstr; parse("ARG1",arg1); parse("ARG2",arg2); parse("METRIC",metstr); + ActionShortcut(ao) { + std::string arg1, arg2, metstr; + parse("ARG1",arg1); + parse("ARG2",arg2); + parse("METRIC",metstr); // Check on input metric ActionWithValue* mav=plumed.getActionSet().selectWithLabel( metstr ); - if( !mav ) error("could not find action named " + metstr + " to use for metric"); - if( mav->copyOutput(0)->getRank()!=2 ) error("metric has incorrect rank"); + if( !mav ) { + error("could not find action named " + metstr + " to use for metric"); + } + if( mav->copyOutput(0)->getRank()!=2 ) { + error("metric has incorrect rank"); + } readInputLine( getShortcutLabel() + "_diff: DISPLACEMENT ARG1=" + arg1 + " ARG2=" + arg2 ); readInputLine( getShortcutLabel() + "_diffT: TRANSPOSE ARG=" + getShortcutLabel() + "_diff"); - bool von_miss, squared; parseFlag("VON_MISSES",von_miss); parseFlag("SQUARED",squared); + bool von_miss, squared; + parseFlag("VON_MISSES",von_miss); + parseFlag("SQUARED",squared); if( von_miss ) { unsigned nrows = mav->copyOutput(0)->getShape()[0]; - if( mav->copyOutput(0)->getShape()[1]!=nrows ) error("metric is not symmetric"); + if( mav->copyOutput(0)->getShape()[1]!=nrows ) { + error("metric is not symmetric"); + } // Create a matrix that can be used to compute the off diagonal elements std::string valstr, nrstr; - Tools::convert( mav->copyOutput(0)->get(0), valstr ); Tools::convert( nrows, nrstr ); + Tools::convert( mav->copyOutput(0)->get(0), valstr ); + Tools::convert( nrows, nrstr ); std::string diagmet = getShortcutLabel() + "_diagmet: CONSTANT VALUES=" + valstr; std::string offdiagmet = getShortcutLabel() + "_offdiagmet: CONSTANT NROWS=" + nrstr + " NCOLS=" + nrstr + " VALUES=0"; for(unsigned i=0; icopyOutput(0)->get(i*nrows+j), valstr ); - if( i==j && i>0 ) { offdiagmet += ",0"; diagmet += "," + valstr; } - else if( i!=j ) { offdiagmet += "," + valstr; } + if( i==j && i>0 ) { + offdiagmet += ",0"; + diagmet += "," + valstr; + } else if( i!=j ) { + offdiagmet += "," + valstr; + } } } - readInputLine( diagmet ); readInputLine( offdiagmet ); + readInputLine( diagmet ); + readInputLine( offdiagmet ); // Compute distances scaled by periods - ActionWithValue* av=plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_diff" ); plumed_assert( av ); - if( !av->copyOutput(0)->isPeriodic() ) error("VON_MISSES only works with periodic variables"); - std::string min, max; av->copyOutput(0)->getDomain(min,max); + ActionWithValue* av=plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_diff" ); + plumed_assert( av ); + if( !av->copyOutput(0)->isPeriodic() ) { + error("VON_MISSES only works with periodic variables"); + } + std::string min, max; + av->copyOutput(0)->getDomain(min,max); readInputLine( getShortcutLabel() + "_scaled: CUSTOM ARG=" + getShortcutLabel() + "_diffT FUNC=2*pi*x/(" + max +"-" + min + ") PERIODIC=NO"); // We start calculating off-diagonal elements by computing the sines of the scaled differences (this is a column vector) readInputLine( getShortcutLabel() + "_sinediffT: CUSTOM ARG=" + getShortcutLabel() + "_scaled FUNC=sin(x) PERIODIC=NO"); @@ -104,7 +130,10 @@ MahalanobisDistance::MahalanobisDistance( const ActionOptions& ao): // If this is a matrix we need create a matrix to multiply by if( av->copyOutput(0)->getShape()[0]>1 ) { // Create some ones - std::string ones=" VALUES=1"; for(unsigned i=1; icopyOutput(0)->getShape()[0]; ++i ) ones += ",1"; + std::string ones=" VALUES=1"; + for(unsigned i=1; icopyOutput(0)->getShape()[0]; ++i ) { + ones += ",1"; + } readInputLine( getShortcutLabel() + "_ones: CONSTANT " + ones ); // Now do some multiplication to create a matrix that can be multiplied by our "inverse variance" vector readInputLine( getShortcutLabel() + "_" + metstr + ": OUTER_PRODUCT ARG=" + metstr2 + "," + getShortcutLabel() + "_ones"); @@ -112,21 +141,38 @@ MahalanobisDistance::MahalanobisDistance( const ActionOptions& ao): } // Compute the diagonal elements readInputLine( getShortcutLabel() + "_prod: CUSTOM ARG=" + getShortcutLabel() + "_scaled," + metstr2 + " FUNC=2*(1-cos(x))*y PERIODIC=NO"); - std::string ncstr; Tools::convert( nrows, ncstr ); Tools::convert( av->copyOutput(0)->getShape()[0], nrstr ); - std::string ones=" VALUES=1"; for(unsigned i=1; icopyOutput(0)->getNumberOfValues(); ++i) ones += ",1"; + std::string ncstr; + Tools::convert( nrows, ncstr ); + Tools::convert( av->copyOutput(0)->getShape()[0], nrstr ); + std::string ones=" VALUES=1"; + for(unsigned i=1; icopyOutput(0)->getNumberOfValues(); ++i) { + ones += ",1"; + } readInputLine( getShortcutLabel() + "_matones: CONSTANT NROWS=" + nrstr + " NCOLS=" + ncstr + ones ); readInputLine( getShortcutLabel() + "_diag: MATRIX_PRODUCT_DIAGONAL ARG=" + getShortcutLabel() + "_matones," + getShortcutLabel() + "_prod"); // Sum everything - if( !squared ) readInputLine( getShortcutLabel() + "_2: COMBINE ARG=" + getShortcutLabel() + "_offdiag," + getShortcutLabel() + "_diag PERIODIC=NO"); - else readInputLine( getShortcutLabel() + ": COMBINE ARG=" + getShortcutLabel() + "_offdiag," + getShortcutLabel() + "_diag PERIODIC=NO"); + if( !squared ) { + readInputLine( getShortcutLabel() + "_2: COMBINE ARG=" + getShortcutLabel() + "_offdiag," + getShortcutLabel() + "_diag PERIODIC=NO"); + } else { + readInputLine( getShortcutLabel() + ": COMBINE ARG=" + getShortcutLabel() + "_offdiag," + getShortcutLabel() + "_diag PERIODIC=NO"); + } } else { - ActionWithValue* av=plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_diffT" ); plumed_assert( av && av->getNumberOfComponents()==1 ); - if( (av->copyOutput(0))->getRank()==1 ) readInputLine( getShortcutLabel() + "_matvec: MATRIX_VECTOR_PRODUCT ARG=" + metstr + "," + getShortcutLabel() +"_diffT"); - else readInputLine( getShortcutLabel() + "_matvec: MATRIX_PRODUCT ARG=" + metstr + "," + getShortcutLabel() +"_diffT"); - std::string olab = getShortcutLabel(); if( !squared ) olab += "_2"; + ActionWithValue* av=plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_diffT" ); + plumed_assert( av && av->getNumberOfComponents()==1 ); + if( (av->copyOutput(0))->getRank()==1 ) { + readInputLine( getShortcutLabel() + "_matvec: MATRIX_VECTOR_PRODUCT ARG=" + metstr + "," + getShortcutLabel() +"_diffT"); + } else { + readInputLine( getShortcutLabel() + "_matvec: MATRIX_PRODUCT ARG=" + metstr + "," + getShortcutLabel() +"_diffT"); + } + std::string olab = getShortcutLabel(); + if( !squared ) { + olab += "_2"; + } readInputLine( olab + ": MATRIX_PRODUCT_DIAGONAL ARG=" + getShortcutLabel() + "_diff," + getShortcutLabel() +"_matvec"); } - if( !squared ) readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_2 FUNC=sqrt(x) PERIODIC=NO"); + if( !squared ) { + readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_2 FUNC=sqrt(x) PERIODIC=NO"); + } } } diff --git a/src/refdist/MatrixProductDiagonal.cpp b/src/refdist/MatrixProductDiagonal.cpp index 74e32fc7fd..fdeba02c20 100644 --- a/src/refdist/MatrixProductDiagonal.cpp +++ b/src/refdist/MatrixProductDiagonal.cpp @@ -47,54 +47,81 @@ class MatrixProductDiagonal : public ActionWithVector { PLUMED_REGISTER_ACTION(MatrixProductDiagonal,"MATRIX_PRODUCT_DIAGONAL") void MatrixProductDiagonal::registerKeywords( Keywords& keys ) { - ActionWithVector::registerKeywords(keys); keys.use("ARG"); + ActionWithVector::registerKeywords(keys); + keys.use("ARG"); keys.setValueDescription("a vector containing the diagonal elements of the matrix that obtaned by multiplying the two input matrices together"); } MatrixProductDiagonal::MatrixProductDiagonal(const ActionOptions&ao): Action(ao), - ActionWithVector(ao) -{ - if( getNumberOfArguments()!=2 ) error("should be two arguments to this action, a matrix and a vector"); + ActionWithVector(ao) { + if( getNumberOfArguments()!=2 ) { + error("should be two arguments to this action, a matrix and a vector"); + } unsigned ncols; if( getPntrToArgument(0)->getRank()==1 ) { - if( getPntrToArgument(0)->hasDerivatives() ) error("first argument to this action should be a vector or matrix"); + if( getPntrToArgument(0)->hasDerivatives() ) { + error("first argument to this action should be a vector or matrix"); + } ncols = 1; } else if( getPntrToArgument(0)->getRank()==2 ) { - if( getPntrToArgument(0)->hasDerivatives() ) error("first argument to this action should be a matrix"); + if( getPntrToArgument(0)->hasDerivatives() ) { + error("first argument to this action should be a matrix"); + } ncols = getPntrToArgument(0)->getShape()[1]; } if( getPntrToArgument(1)->getRank()==1 ) { - if( getPntrToArgument(1)->hasDerivatives() ) error("second argument to this action should be a vector or matrix"); - if( ncols!=getPntrToArgument(1)->getShape()[0] ) error("number of columns in first matrix does not equal number of elements in vector"); - if( getPntrToArgument(0)->getShape()[0]!=1 ) error("matrix output by this action must be square"); - addValueWithDerivatives(); setNotPeriodic(); + if( getPntrToArgument(1)->hasDerivatives() ) { + error("second argument to this action should be a vector or matrix"); + } + if( ncols!=getPntrToArgument(1)->getShape()[0] ) { + error("number of columns in first matrix does not equal number of elements in vector"); + } + if( getPntrToArgument(0)->getShape()[0]!=1 ) { + error("matrix output by this action must be square"); + } + addValueWithDerivatives(); + setNotPeriodic(); } else { - if( getPntrToArgument(1)->getRank()!=2 || getPntrToArgument(1)->hasDerivatives() ) error("second argument to this action should be a vector or a matrix"); - if( ncols!=getPntrToArgument(1)->getShape()[0] ) error("number of columns in first matrix does not equal number of rows in second matrix"); - if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(1)->getShape()[1] ) error("matrix output by this action must be square"); - std::vector shape(1); shape[0]=getPntrToArgument(0)->getShape()[0]; - addValue( shape ); setNotPeriodic(); + if( getPntrToArgument(1)->getRank()!=2 || getPntrToArgument(1)->hasDerivatives() ) { + error("second argument to this action should be a vector or a matrix"); + } + if( ncols!=getPntrToArgument(1)->getShape()[0] ) { + error("number of columns in first matrix does not equal number of rows in second matrix"); + } + if( getPntrToArgument(0)->getShape()[0]!=getPntrToArgument(1)->getShape()[1] ) { + error("matrix output by this action must be square"); + } + std::vector shape(1); + shape[0]=getPntrToArgument(0)->getShape()[0]; + addValue( shape ); + setNotPeriodic(); } - getPntrToArgument(0)->buildDataStore(); getPntrToArgument(1)->buildDataStore(); + getPntrToArgument(0)->buildDataStore(); + getPntrToArgument(1)->buildDataStore(); } unsigned MatrixProductDiagonal::getNumberOfDerivatives() { - if( doNotCalculateDerivatives() ) return 0; + if( doNotCalculateDerivatives() ) { + return 0; + } return getPntrToArgument(0)->getNumberOfValues() + getPntrToArgument(1)->getNumberOfValues();; } void MatrixProductDiagonal::performTask( const unsigned& task_index, MultiValue& myvals ) const { unsigned ostrn = getConstPntrToComponent(0)->getPositionInStream(); - Value* arg1 = getPntrToArgument(0); Value* arg2 = getPntrToArgument(1); + Value* arg1 = getPntrToArgument(0); + Value* arg2 = getPntrToArgument(1); if( arg1->getRank()==1 ) { double val1 = arg1->get( task_index ); double val2 = arg2->get( task_index ); myvals.addValue( ostrn, val1*val2 ); - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } myvals.addDerivative( ostrn, task_index, val2 ); myvals.updateIndex( ostrn, task_index ); @@ -104,7 +131,10 @@ void MatrixProductDiagonal::performTask( const unsigned& task_index, MultiValue& } else { unsigned nmult = arg1->getRowLength(task_index); unsigned nrowsA = getPntrToArgument(0)->getShape()[1]; - unsigned nrowsB = 1; if( getPntrToArgument(1)->getRank()>1 ) nrowsB = getPntrToArgument(1)->getShape()[1]; + unsigned nrowsB = 1; + if( getPntrToArgument(1)->getRank()>1 ) { + nrowsB = getPntrToArgument(1)->getShape()[1]; + } unsigned nvals1 = getPntrToArgument(0)->getNumberOfValues(); double matval = 0; @@ -114,7 +144,9 @@ void MatrixProductDiagonal::performTask( const unsigned& task_index, MultiValue& double val2 = arg2->get( kind*nrowsB + task_index ); matval += val1*val2; - if( doNotCalculateDerivatives() ) continue; + if( doNotCalculateDerivatives() ) { + continue; + } myvals.addDerivative( ostrn, task_index*nrowsA + kind, val2 ); myvals.updateIndex( ostrn, task_index*nrowsA + kind ); @@ -129,11 +161,17 @@ void MatrixProductDiagonal::performTask( const unsigned& task_index, MultiValue& void MatrixProductDiagonal::calculate() { if( getPntrToArgument(1)->getRank()==1 ) { unsigned nder = getNumberOfDerivatives(); - MultiValue myvals( 1, nder, 0, 0, 0 ); performTask( 0, myvals ); + MultiValue myvals( 1, nder, 0, 0, 0 ); + performTask( 0, myvals ); - Value* myval=getPntrToComponent(0); myval->set( myvals.get(0) ); - for(unsigned i=0; isetDerivative( i, myvals.getDerivative(0,i) ); - } else runAllTasks(); + Value* myval=getPntrToComponent(0); + myval->set( myvals.get(0) ); + for(unsigned i=0; isetDerivative( i, myvals.getDerivative(0,i) ); + } + } else { + runAllTasks(); + } } } diff --git a/src/refdist/NormalizedEuclideanDistance.cpp b/src/refdist/NormalizedEuclideanDistance.cpp index efa96fdfec..b0bfc692f7 100644 --- a/src/refdist/NormalizedEuclideanDistance.cpp +++ b/src/refdist/NormalizedEuclideanDistance.cpp @@ -52,38 +52,55 @@ void NormalizedEuclideanDistance::registerKeywords( Keywords& keys ) { keys.add("compulsory","METRIC","The inverse covariance matrix that should be used when calculating the distance"); keys.addFlag("SQUARED",false,"The squared distance should be calculated"); keys.setValueDescription("the normalized euclidean distances between the input vectors"); - keys.needsAction("DISPLACEMENT"); keys.needsAction("CUSTOM"); keys.needsAction("OUTER_PRODUCT"); - keys.needsAction("TRANSPOSE"); keys.needsAction("MATRIX_PRODUCT_DIAGONAL"); keys.needsAction("ONES"); + keys.needsAction("DISPLACEMENT"); + keys.needsAction("CUSTOM"); + keys.needsAction("OUTER_PRODUCT"); + keys.needsAction("TRANSPOSE"); + keys.needsAction("MATRIX_PRODUCT_DIAGONAL"); + keys.needsAction("ONES"); } NormalizedEuclideanDistance::NormalizedEuclideanDistance( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - std::string arg1, arg2, metstr; parse("ARG1",arg1); parse("ARG2",arg2); parse("METRIC",metstr); + ActionShortcut(ao) { + std::string arg1, arg2, metstr; + parse("ARG1",arg1); + parse("ARG2",arg2); + parse("METRIC",metstr); // Vectors are in rows here readInputLine( getShortcutLabel() + "_diff: DISPLACEMENT ARG1=" + arg1 + " ARG2=" + arg2 ); // Vectors are in columns here readInputLine( getShortcutLabel() + "_diffT: TRANSPOSE ARG=" + getShortcutLabel() + "_diff"); // Get the action that computes the differences - ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_diffT"); plumed_assert( av ); + ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_diffT"); + plumed_assert( av ); // If this is a matrix we need create a matrix to multiply by if( av->copyOutput(0)->getRank()==2 ) { // Create some ones - std::string nones; Tools::convert( av->copyOutput(0)->getShape()[1], nones ); + std::string nones; + Tools::convert( av->copyOutput(0)->getShape()[1], nones ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + nones); // Now do some multiplication to create a matrix that can be multiplied by our "inverse variance" vector if( av->copyOutput(0)->getShape()[0]==1 ) { readInputLine( getShortcutLabel() + "_" + metstr + "T: CUSTOM ARG=" + metstr + "," + getShortcutLabel() + "_ones FUNC=x*y PERIODIC=NO"); readInputLine( getShortcutLabel() + "_" + metstr + ": TRANSPOSE ARG=" + getShortcutLabel() + "_" + metstr + "T"); - } else readInputLine( getShortcutLabel() + "_" + metstr + ": OUTER_PRODUCT ARG=" + metstr + "," + getShortcutLabel() + "_ones"); + } else { + readInputLine( getShortcutLabel() + "_" + metstr + ": OUTER_PRODUCT ARG=" + metstr + "," + getShortcutLabel() + "_ones"); + } metstr = getShortcutLabel() + "_" + metstr; } // Now do the multiplication readInputLine( getShortcutLabel() + "_sdiff: CUSTOM ARG=" + metstr + "," + getShortcutLabel() +"_diffT FUNC=x*y PERIODIC=NO"); - bool squared; parseFlag("SQUARED",squared); std::string olab = getShortcutLabel(); if( !squared ) olab += "_2"; + bool squared; + parseFlag("SQUARED",squared); + std::string olab = getShortcutLabel(); + if( !squared ) { + olab += "_2"; + } readInputLine( olab + ": MATRIX_PRODUCT_DIAGONAL ARG=" + getShortcutLabel() +"_diff," + getShortcutLabel() + "_sdiff"); - if( !squared ) readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_2 FUNC=sqrt(x) PERIODIC=NO"); + if( !squared ) { + readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_2 FUNC=sqrt(x) PERIODIC=NO"); + } } } diff --git a/src/s2cm/S2ContactModel.cpp b/src/s2cm/S2ContactModel.cpp index 0fbb3f5f0e..0061dafca3 100644 --- a/src/s2cm/S2ContactModel.cpp +++ b/src/s2cm/S2ContactModel.cpp @@ -113,8 +113,7 @@ S2ContactModel::S2ContactModel(const ActionOptions&ao): n_i_(0.0), total_prefactor_(0.0), r_globalshift_(0.0), - modeltype_(methyl) -{ + modeltype_(methyl) { parseFlag("SERIAL",serial_); @@ -162,9 +161,13 @@ S2ContactModel::S2ContactModel(const ActionOptions&ao): parseFlag("NLIST",doneigh); if(doneigh) { parse("NL_CUTOFF",nl_cut); - if(nl_cut<=0.0) error("NL_CUTOFF should be explicitly specified and positive"); + if(nl_cut<=0.0) { + error("NL_CUTOFF should be explicitly specified and positive"); + } parse("NL_STRIDE",nl_st); - if(nl_st<=0) error("NL_STRIDE should be explicitly specified and positive"); + if(nl_st<=0) { + error("NL_STRIDE should be explicitly specified and positive"); + } } parse("R_EFF",r_eff_); @@ -187,8 +190,7 @@ S2ContactModel::S2ContactModel(const ActionOptions&ao): bool dopair=false; if(doneigh) { nl=Tools::make_unique(main_atoms,heavy_atoms,serial_,dopair,pbc_,getPbc(),comm,nl_cut,nl_st); - } - else { + } else { nl=Tools::make_unique(main_atoms,heavy_atoms,serial_,dopair,pbc_,getPbc(),comm); } @@ -202,15 +204,16 @@ S2ContactModel::S2ContactModel(const ActionOptions&ao): log << plumed.cite("Ming and Bruschweiler, J. Biomol. NMR, 29, 363 (2004) - DOI:10.1023/B:JNMR.0000032612.70767.35"); log.printf("\n"); log.printf(" calculation of methyl order parameter using atom %d \n",methyl_atom[0].serial()); - } - else if(modeltype_==nh) { + } else if(modeltype_==nh) { log << plumed.cite("Zhang and Bruschweiler, J. Am. Chem. Soc. 124, 12654 (2002) - DOI:10.1021/ja027847a"); log.printf("\n"); log.printf(" calculation of NH order parameter using atoms %d and %d\n",nh_atoms[0].serial(),nh_atoms[1].serial()); } log.printf(" heavy atoms used in the calculation (%u in total):\n",static_cast(heavy_atoms.size())); for(unsigned int i=0; igetReducedAtomList()); invalidateList=false; - if(getExchangeStep()) error("Neighbor lists should be updated on exchange steps - choose a NL_STRIDE which divides the exchange stride!"); + if(getExchangeStep()) { + error("Neighbor lists should be updated on exchange steps - choose a NL_STRIDE which divides the exchange stride!"); + } + } + if(getExchangeStep()) { + firsttime=true; } - if(getExchangeStep()) firsttime=true; } } @@ -283,7 +290,9 @@ void S2ContactModel::calculate() { Vector distance; unsigned int i0=nl->getClosePair(i).first; unsigned int i1=nl->getClosePair(i).second; - if(getAbsoluteIndex(i0)==getAbsoluteIndex(i1)) {continue;} + if(getAbsoluteIndex(i0)==getAbsoluteIndex(i1)) { + continue; + } if(pbc_) { distance=pbcDistance(getPosition(i0),getPosition(i1)); diff --git a/src/sasa/sasa_HASEL.cpp b/src/sasa/sasa_HASEL.cpp index 0373ec5ce1..580f4a2ffc 100644 --- a/src/sasa/sasa_HASEL.cpp +++ b/src/sasa/sasa_HASEL.cpp @@ -182,32 +182,42 @@ SASA_HASEL::SASA_HASEL(const ActionOptions&ao): nl_update(0), DeltaGValues("absent"), Ti(0), - firstStepFlag(0) -{ + firstStepFlag(0) { rs = 0.14; parse("DELTAGFILE",DeltaGValues); parse("APPROACH", approach); parseAtomList("ATOMS",atoms); - if(atoms.size()==0) error("no atoms specified"); + if(atoms.size()==0) { + error("no atoms specified"); + } std::string Type; parse("TYPE",Type); parse("NL_STRIDE", stride); parseFlag("NOPBC",nopbc); checkRead(); - if(Type=="TOTAL") sasa_type=TOTAL; - else if(Type=="TRANSFER") sasa_type=TRANSFER; - else error("Unknown SASA type"); + if(Type=="TOTAL") { + sasa_type=TOTAL; + } else if(Type=="TRANSFER") { + sasa_type=TRANSFER; + } else { + error("Unknown SASA type"); + } - switch(sasa_type) - { - case TOTAL: log.printf(" TOTAL SASA;"); break; - case TRANSFER: log.printf(" TRANSFER MODEL;"); break; + switch(sasa_type) { + case TOTAL: + log.printf(" TOTAL SASA;"); + break; + case TRANSFER: + log.printf(" TRANSFER MODEL;"); + break; } log.printf(" atoms involved : "); for(unsigned i=0; i -void split(const std::string& str, Container& cont) -{ +void split(const std::string& str, Container& cont) { std::istringstream iss(str); std::copy(std::istream_iterator(iss), std::istream_iterator(), @@ -249,7 +259,9 @@ void split(const std::string& str, Container& cont) void SASA_HASEL::readPDB() { auto* moldat = plumed.getActionSet().selectLatest(this); - if( ! moldat ) error("Unable to find MOLINFO in input"); + if( ! moldat ) { + error("Unable to find MOLINFO in input"); + } AtomResidueName[0].clear(); AtomResidueName[1].clear(); @@ -587,9 +599,12 @@ void SASA_HASEL::readDeltaG() { } } } - if ( backboneflag == 0) error("Cannot find backbone value in Delta G parameters file\n"); + if ( backboneflag == 0) { + error("Cannot find backbone value in Delta G parameters file\n"); + } + } else { + error("Cannot open DeltaG file"); } - else error("Cannot open DeltaG file"); for(unsigned i=0; i(this); - if( ! moldat ) error("Unable to find MOLINFO in input"); + if( ! moldat ) { + error("Unable to find MOLINFO in input"); + } double Si, sasai, bij; double sasa = 0; vector derivatives( natoms ); diff --git a/src/sasa/sasa_LCPO.cpp b/src/sasa/sasa_LCPO.cpp index 094592f12e..ecf634d014 100755 --- a/src/sasa/sasa_LCPO.cpp +++ b/src/sasa/sasa_LCPO.cpp @@ -180,32 +180,42 @@ SASA_LCPO::SASA_LCPO(const ActionOptions&ao): Ti(0), stride(10), nl_update(0), - firstStepFlag(0) -{ + firstStepFlag(0) { rs = 0.14; parse("DELTAGFILE",DeltaGValues); parse("APPROACH", approach); parseAtomList("ATOMS",atoms); - if(atoms.size()==0) error("no atoms specified"); + if(atoms.size()==0) { + error("no atoms specified"); + } std::string Type; parse("TYPE",Type); parse("NL_STRIDE", stride); parseFlag("NOPBC",nopbc); checkRead(); - if(Type=="TOTAL") sasa_type=TOTAL; - else if(Type=="TRANSFER") sasa_type=TRANSFER; - else error("Unknown SASA type"); + if(Type=="TOTAL") { + sasa_type=TOTAL; + } else if(Type=="TRANSFER") { + sasa_type=TRANSFER; + } else { + error("Unknown SASA type"); + } - switch(sasa_type) - { - case TOTAL: log.printf(" TOTAL SASA;"); break; - case TRANSFER: log.printf(" TRANSFER MODEL;"); break; + switch(sasa_type) { + case TOTAL: + log.printf(" TOTAL SASA;"); + break; + case TRANSFER: + log.printf(" TRANSFER MODEL;"); + break; } log.printf(" atoms involved : "); for(unsigned i=0; i -void split(const std::string& str, Container& cont) -{ +void split(const std::string& str, Container& cont) { std::istringstream iss(str); std::copy(std::istream_iterator(iss), std::istream_iterator(), @@ -246,7 +256,9 @@ void split(const std::string& str, Container& cont) void SASA_LCPO::readPDB() { auto* moldat = plumed.getActionSet().selectLatest(this); - if( ! moldat ) error("Unable to find MOLINFO in input"); + if( ! moldat ) { + error("Unable to find MOLINFO in input"); + } AtomResidueName[0].clear(); AtomResidueName[1].clear(); @@ -553,9 +565,12 @@ void SASA_LCPO::readDeltaG() { } } } - if ( backboneflag == 0) error("Cannot find backbone value in Delta G parameters file\n"); + if ( backboneflag == 0) { + error("Cannot find backbone value in Delta G parameters file\n"); + } + } else { + error("Cannot open DeltaG file"); } - else error("Cannot open DeltaG file"); for(unsigned i=0; i 0 ) sasa += sasai/100; + if (sasai > 0 ) { + sasa += sasai/100; + } derivatives[i][0] += (dAijdc_2[0]*LCPOparam[i][2]+dAijdc_4[0]*LCPOparam[i][4])/10; derivatives[i][1] += (dAijdc_2[1]*LCPOparam[i][2]+dAijdc_4[1]*LCPOparam[i][4])/10; derivatives[i][2] += (dAijdc_2[2]*LCPOparam[i][2]+dAijdc_4[2]*LCPOparam[i][4])/10; @@ -1047,14 +1070,18 @@ void SASA_LCPO::calculate() { double sasai = (LCPOparam[i][1]*S1+LCPOparam[i][2]*Aij+LCPOparam[i][3]*Ajk+LCPOparam[i][4]*Aijk); if (AtomResidueName[0][i] == "N" || AtomResidueName[0][i] == "CA" || AtomResidueName[0][i] == "C" || AtomResidueName[0][i] == "O") { - if (sasai > 0 ) sasa += (sasai/MaxSurf[i][0]*DeltaG[natoms][0]); + if (sasai > 0 ) { + sasa += (sasai/MaxSurf[i][0]*DeltaG[natoms][0]); + } derivatives[i][0] += ((dAijdc_2[0]*LCPOparam[i][2]+dAijdc_4[0]*LCPOparam[i][4])/MaxSurf[i][0]*DeltaG[natoms][0])*10; derivatives[i][1] += ((dAijdc_2[1]*LCPOparam[i][2]+dAijdc_4[1]*LCPOparam[i][4])/MaxSurf[i][0]*DeltaG[natoms][0])*10; derivatives[i][2] += ((dAijdc_2[2]*LCPOparam[i][2]+dAijdc_4[2]*LCPOparam[i][4])/MaxSurf[i][0]*DeltaG[natoms][0])*10; } if (AtomResidueName[0][i] != "N" && AtomResidueName[0][i] != "CA" && AtomResidueName[0][i] != "C" && AtomResidueName[0][i] != "O") { - if (sasai > 0. ) sasa += (sasai/MaxSurf[i][1]*DeltaG[i][0]); + if (sasai > 0. ) { + sasa += (sasai/MaxSurf[i][1]*DeltaG[i][0]); + } derivatives[i][0] += ((dAijdc_2[0]*LCPOparam[i][2]+dAijdc_4[0]*LCPOparam[i][4])/MaxSurf[i][1]*DeltaG[i][0])*10; derivatives[i][1] += ((dAijdc_2[1]*LCPOparam[i][2]+dAijdc_4[1]*LCPOparam[i][4])/MaxSurf[i][1]*DeltaG[i][0])*10; derivatives[i][2] += ((dAijdc_2[2]*LCPOparam[i][2]+dAijdc_4[2]*LCPOparam[i][4])/MaxSurf[i][1]*DeltaG[i][0])*10; @@ -1066,7 +1093,9 @@ void SASA_LCPO::calculate() { } - for(unsigned i=0; i chains; std::string atoms; SecondaryStructureRMSD::readBackboneAtoms( this, plumed, "protein", chains, atoms ); + std::vector chains; + std::string atoms; + SecondaryStructureRMSD::readBackboneAtoms( this, plumed, "protein", chains, atoms ); // This constructs all conceivable sections of alpha helix in the backbone of the chains - unsigned nprevious=0, segno=1; std::string seglist; + unsigned nprevious=0, segno=1; + std::string seglist; for(unsigned i=0; i chains; std::string atoms; SecondaryStructureRMSD::readBackboneAtoms( this, plumed, "protein", chains, atoms ); + std::vector chains; + std::string atoms; + SecondaryStructureRMSD::readBackboneAtoms( this, plumed, "protein", chains, atoms ); bool intra_chain(false), inter_chain(false); - std::string style; parse("STYLE",style); + std::string style; + parse("STYLE",style); if( Tools::caseInSensStringCompare(style, "all") ) { - intra_chain=true; inter_chain=true; + intra_chain=true; + inter_chain=true; } else if( Tools::caseInSensStringCompare(style, "inter") ) { - intra_chain=false; inter_chain=true; + intra_chain=false; + inter_chain=true; } else if( Tools::caseInSensStringCompare(style, "intra") ) { - intra_chain=true; inter_chain=false; + intra_chain=true; + inter_chain=false; } else { error( style + " is not a valid directive for the STYLE keyword"); } // This constructs all conceivable sections of antibeta sheet in the backbone of the chains - std::string seglist; unsigned k=1; + std::string seglist; + unsigned k=1; if( intra_chain ) { - unsigned nprevious=0; std::vector nlist(30); + unsigned nprevious=0; + std::vector nlist(30); for(unsigned i=0; i nlist(30); for(unsigned ichain=1; ichain0 ) strands_cutoff=" CUTOFF_ATOMS=6,21 STRANDS_CUTOFF="+strands_cutoff; - std::string type; parse("TYPE",type); std::string lab = getShortcutLabel() + "_rmsd"; if( uselessthan ) lab = getShortcutLabel(); - std::string nopbcstr=""; bool nopbc; parseFlag("NOPBC",nopbc); if( nopbc ) nopbcstr = " NOPBC"; + std::string strands_cutoff; + parse("STRANDS_CUTOFF",strands_cutoff); + if( strands_cutoff.length()>0 ) { + strands_cutoff=" CUTOFF_ATOMS=6,21 STRANDS_CUTOFF="+strands_cutoff; + } + std::string type; + parse("TYPE",type); + std::string lab = getShortcutLabel() + "_rmsd"; + if( uselessthan ) { + lab = getShortcutLabel(); + } + std::string nopbcstr=""; + bool nopbc; + parseFlag("NOPBC",nopbc); + if( nopbc ) { + nopbcstr = " NOPBC"; + } readInputLine( lab + ": SECONDARY_STRUCTURE_RMSD BONDLENGTH=0.17" + seglist + structure + " " + atoms + " TYPE=" + type + strands_cutoff + nopbcstr ); // Create the less than object - if( ltmap.length()>0 ) SecondaryStructureRMSD::expandShortcut( uselessthan, getShortcutLabel(), lab, ltmap, this ); + if( ltmap.length()>0 ) { + SecondaryStructureRMSD::expandShortcut( uselessthan, getShortcutLabel(), lab, ltmap, this ); + } } } diff --git a/src/secondarystructure/ParabetaRMSD.cpp b/src/secondarystructure/ParabetaRMSD.cpp index cb2a35a786..cf88f2fb6b 100644 --- a/src/secondarystructure/ParabetaRMSD.cpp +++ b/src/secondarystructure/ParabetaRMSD.cpp @@ -97,8 +97,12 @@ PLUMED_REGISTER_ACTION(ParabetaRMSD,"PARABETARMSD") void ParabetaRMSD::registerKeywords( Keywords& keys ) { SecondaryStructureRMSD::registerKeywords( keys ); - keys.remove("ATOMS"); keys.remove("SEGMENT"); keys.remove("BONDLENGTH"); - keys.remove("NO_ACTION_LOG"); keys.remove("CUTOFF_ATOMS"); keys.remove("STRUCTURE"); + keys.remove("ATOMS"); + keys.remove("SEGMENT"); + keys.remove("BONDLENGTH"); + keys.remove("NO_ACTION_LOG"); + keys.remove("CUTOFF_ATOMS"); + keys.remove("STRUCTURE"); keys.add("compulsory","STYLE","all","Parallel beta sheets can either form in a single chain or from a pair of chains. If STYLE=all all " "chain configuration with the appropriate geometry are counted. If STYLE=inter " "only sheet-like configurations involving two chains are counted, while if STYLE=intra " @@ -108,33 +112,46 @@ void ParabetaRMSD::registerKeywords( Keywords& keys ) { ParabetaRMSD::ParabetaRMSD(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read in the input and create a string that describes how to compute the less than - std::string ltmap; bool uselessthan=SecondaryStructureRMSD::readShortcutWords( ltmap, this ); + std::string ltmap; + bool uselessthan=SecondaryStructureRMSD::readShortcutWords( ltmap, this ); // read in the backbone atoms - std::vector chains; std::string atoms; SecondaryStructureRMSD::readBackboneAtoms( this, plumed, "protein", chains, atoms ); + std::vector chains; + std::string atoms; + SecondaryStructureRMSD::readBackboneAtoms( this, plumed, "protein", chains, atoms ); - bool intra_chain(false), inter_chain(false); std::string seglist; - std::string style; parse("STYLE",style); unsigned jjkk=1; + bool intra_chain(false), inter_chain(false); + std::string seglist; + std::string style; + parse("STYLE",style); + unsigned jjkk=1; if( Tools::caseInSensStringCompare(style, "all") ) { - intra_chain=true; inter_chain=true; + intra_chain=true; + inter_chain=true; } else if( Tools::caseInSensStringCompare(style, "inter") ) { - intra_chain=false; inter_chain=true; + intra_chain=false; + inter_chain=true; } else if( Tools::caseInSensStringCompare(style, "intra") ) { - intra_chain=true; inter_chain=false; + intra_chain=true; + inter_chain=false; } else { error( style + " is not a valid directive for the STYLE keyword"); } // This constructs all conceivable sections of antibeta sheet in the backbone of the chains if( intra_chain ) { - unsigned nprevious=0; std::vector nlist(30); + unsigned nprevious=0; + std::vector nlist(30); for(unsigned i=0; i nlist(30); for(unsigned ichain=1; ichain0 ) strands_cutoff=" CUTOFF_ATOMS=6,21 STRANDS_CUTOFF="+strands_cutoff; - std::string type; parse("TYPE",type); std::string lab = getShortcutLabel() + "_low"; if( uselessthan ) lab = getShortcutLabel(); + std::string strands_cutoff; + parse("STRANDS_CUTOFF",strands_cutoff); + std::string nopbcstr=""; + bool nopbc; + parseFlag("NOPBC",nopbc); + if( nopbc ) { + nopbcstr = " NOPBC"; + } + if( strands_cutoff.length()>0 ) { + strands_cutoff=" CUTOFF_ATOMS=6,21 STRANDS_CUTOFF="+strands_cutoff; + } + std::string type; + parse("TYPE",type); + std::string lab = getShortcutLabel() + "_low"; + if( uselessthan ) { + lab = getShortcutLabel(); + } readInputLine( getShortcutLabel() + "_both: SECONDARY_STRUCTURE_RMSD BONDLENGTH=0.17" + seglist + structure + " " + atoms + " TYPE=" + type + strands_cutoff + nopbcstr ); if( ltmap.length()>0 ) { // Create the lowest line diff --git a/src/secondarystructure/SecondaryStructureRMSD.cpp b/src/secondarystructure/SecondaryStructureRMSD.cpp index 5265cf2a27..b0071a98ef 100644 --- a/src/secondarystructure/SecondaryStructureRMSD.cpp +++ b/src/secondarystructure/SecondaryStructureRMSD.cpp @@ -43,9 +43,14 @@ PLUMED_REGISTER_ACTION(SecondaryStructureRMSD,"SECONDARY_STRUCTURE_RMSD"); bool SecondaryStructureRMSD::readShortcutWords( std::string& ltmap, ActionShortcut* action ) { action->parse("LESS_THAN",ltmap); if( ltmap.length()==0 ) { - std::string nn, mm, d_0, r_0; action->parse("R_0",r_0); - if( r_0.length()==0 ) r_0="0.08"; - action->parse("NN",nn); action->parse("D_0",d_0); action->parse("MM",mm); + std::string nn, mm, d_0, r_0; + action->parse("R_0",r_0); + if( r_0.length()==0 ) { + r_0="0.08"; + } + action->parse("NN",nn); + action->parse("D_0",d_0); + action->parse("MM",mm); ltmap = "RATIONAL R_0=" + r_0 + " D_0=" + d_0 + " NN=" + nn + " MM=" + mm; return false; } @@ -54,8 +59,11 @@ bool SecondaryStructureRMSD::readShortcutWords( std::string& ltmap, ActionShortc void SecondaryStructureRMSD::expandShortcut( const bool& uselessthan, const std::string& labout, const std::string& labin, const std::string& ltmap, ActionShortcut* action ) { action->readInputLine( labout + "_lt: LESS_THAN ARG=" + labin + " SWITCH={" + ltmap +"}"); - if( uselessthan ) action->readInputLine( labout + "_lessthan: SUM ARG=" + labout + "_lt PERIODIC=NO"); - else action->readInputLine( labout + ": SUM ARG=" + labout + "_lt PERIODIC=NO"); + if( uselessthan ) { + action->readInputLine( labout + "_lessthan: SUM ARG=" + labout + "_lt PERIODIC=NO"); + } else { + action->readInputLine( labout + ": SUM ARG=" + labout + "_lt PERIODIC=NO"); + } } void SecondaryStructureRMSD::registerKeywords( Keywords& keys ) { @@ -90,21 +98,29 @@ void SecondaryStructureRMSD::registerKeywords( Keywords& keys ) { keys.add("hidden","NO_ACTION_LOG","suppresses printing from action on the log"); keys.addOutputComponent("struct","default","the vectors containing the rmsd distances between the residues and each of the reference structures"); keys.addOutputComponent("lessthan","default","the number blocks of residues that have an RMSD from the secondary structure that is less than the threshold"); - keys.needsAction("SECONDARY_STRUCTURE_RMSD"); keys.needsAction("LESS_THAN"); keys.needsAction("SUM"); + keys.needsAction("SECONDARY_STRUCTURE_RMSD"); + keys.needsAction("LESS_THAN"); + keys.needsAction("SUM"); } void SecondaryStructureRMSD::readBackboneAtoms( ActionShortcut* action, PlumedMain& plumed, const std::string& moltype, std::vector& chain_lengths, std::string& all_atoms ) { auto* moldat=plumed.getActionSet().selectLatest(action); - if( ! moldat ) action->error("Unable to find MOLINFO in input"); + if( ! moldat ) { + action->error("Unable to find MOLINFO in input"); + } - std::vector resstrings; action->parseVector( "RESIDUES", resstrings ); - if(resstrings.size()==0) action->error("residues are not defined, check the keyword RESIDUES"); - else if( Tools::caseInSensStringCompare(resstrings[0], "all") ) { + std::vector resstrings; + action->parseVector( "RESIDUES", resstrings ); + if(resstrings.size()==0) { + action->error("residues are not defined, check the keyword RESIDUES"); + } else if( Tools::caseInSensStringCompare(resstrings[0], "all") ) { resstrings[0]="all"; action->log.printf(" examining all possible secondary structure combinations\n"); } else { action->log.printf(" examining secondary structure in residue positions : %s ",resstrings[0].c_str() ); - for(unsigned i=1; ilog.printf(", %s",resstrings[i].c_str() ); + for(unsigned i=1; ilog.printf(", %s",resstrings[i].c_str() ); + } action->log.printf("\n"); } std::vector< std::vector > backatoms; @@ -114,9 +130,13 @@ void SecondaryStructureRMSD::readBackboneAtoms( ActionShortcut* action, PlumedMa for(unsigned i=0; i0) { log.printf(" ignoring contributions from strands that are more than %f apart\n",s_cutoff); - std::vector cutatoms; parseVector("CUTOFF_ATOMS",cutatoms); + std::vector cutatoms; + parseVector("CUTOFF_ATOMS",cutatoms); if( cutatoms.size()==2 ) { - align_atom_1=cutatoms[0]; align_atom_2=cutatoms[1]; - } else error("did not find CUTOFF_ATOMS in input"); + align_atom_1=cutatoms[0]; + align_atom_2=cutatoms[1]; + } else { + error("did not find CUTOFF_ATOMS in input"); + } } s_cutoff2=s_cutoff*s_cutoff; } // Read in the atoms - std::vector all_atoms; parseAtomList("ATOMS",all_atoms); requestAtoms( all_atoms ); + std::vector all_atoms; + parseAtomList("ATOMS",all_atoms); + requestAtoms( all_atoms ); for(unsigned i=1;; ++i) { std::vector newatoms; - if( !parseNumberedVector("SEGMENT",i,newatoms) ) break; + if( !parseNumberedVector("SEGMENT",i,newatoms) ) { + break; + } if( verbose_output ) { log.printf(" Secondary structure segment %u contains atoms : ", static_cast(colvar_atoms.size()+1)); - for(unsigned i=0; i cstruct; - if( !parseNumberedVector("STRUCTURE",ii,cstruct) ) break ; + if( !parseNumberedVector("STRUCTURE",ii,cstruct) ) { + break ; + } plumed_assert( cstruct.size()%3==0 && cstruct.size()/3==colvar_atoms[0].size() ); std::vector structure( cstruct.size()/3 ); for(unsigned i=0; i, double> targets; for(unsigned i=0; i bondlength) targets[std::make_pair(i,j)] = distance; + if(distance > bondlength) { + targets[std::make_pair(i,j)] = distance; + } } } drmsd_targets.push_back( targets ); } else { - Vector center; std::vector align( structure.size(), 1.0 ), displace( structure.size(), 1.0 ); - for(unsigned i=0; i align( structure.size(), 1.0 ), displace( structure.size(), 1.0 ); + for(unsigned i=0; i0 ); - std::vector shape(1); shape[0]=colvar_atoms.size(); - if( nref==1 ) { addValue( shape ); setNotPeriodic(); } - else { + std::vector shape(1); + shape[0]=colvar_atoms.size(); + if( nref==1 ) { + addValue( shape ); + setNotPeriodic(); + } else { std::string num; for(unsigned i=0; i& task_reducing_actions ) { - if( s_cutoff2>0 ) task_reducing_actions.push_back(this); + if( s_cutoff2>0 ) { + task_reducing_actions.push_back(this); + } } int SecondaryStructureRMSD::checkTaskStatus( const unsigned& taskno, int& flag ) const { if( s_cutoff2>0 ) { Vector distance=pbcDistance( ActionAtomistic::getPosition( getAtomIndex(taskno,align_atom_1) ), ActionAtomistic::getPosition( getAtomIndex(taskno,align_atom_2) ) ); - if( distance.modulo2() pos( natoms ), deriv( natoms ); - for(unsigned i=0; i(drmsd_targets[i].size()); unsigned ostrn = getConstPntrToComponent(i)->getPositionInStream(); - drmsd = sqrt(inpairs*drmsd); myvals.setValue( ostrn, drmsd ); + drmsd = sqrt(inpairs*drmsd); + myvals.setValue( ostrn, drmsd ); if( !doNotCalculateDerivatives() ) { double scalef = inpairs / drmsd; for(unsigned j=0; j0) u.setLength(s); + if(s.length()>0) { + u.setLength(s); + } if(u.getLengthString().length()>0 && u.getLengthString()=="nm") { log.printf(" length: %s\n",u.getLengthString().c_str()); - } - else if(u.getLengthString().length()>0 && u.getLengthString()!="nm") { + } else if(u.getLengthString().length()>0 && u.getLengthString()!="nm") { log.printf(" length: %s = %g nm\n",u.getLengthString().c_str(),u.getLength()); - } - else { + } else { log.printf(" length: %g nm\n",u.getLength()); } s=""; parse("ENERGY",s); - if(s.length()>0) u.setEnergy(s); + if(s.length()>0) { + u.setEnergy(s); + } if(u.getEnergyString().length()>0 && u.getEnergyString()=="kj/mol") { log.printf(" energy: %s\n",u.getEnergyString().c_str()); - } - else if(u.getEnergyString().length()>0 && u.getEnergyString()!="kj/mol") { + } else if(u.getEnergyString().length()>0 && u.getEnergyString()!="kj/mol") { log.printf(" energy: %s = %g kj/mol\n",u.getEnergyString().c_str(),u.getEnergy()); - } - else { + } else { log.printf(" energy: %g kj/mol\n",u.getEnergy()); } s=""; parse("TIME",s); - if(s.length()>0) u.setTime(s); + if(s.length()>0) { + u.setTime(s); + } if(u.getTimeString().length()>0 && u.getTimeString()=="ps") { log.printf(" time: %s\n",u.getTimeString().c_str()); - } - else if(u.getTimeString().length()>0 && u.getTimeString()!="ps") { + } else if(u.getTimeString().length()>0 && u.getTimeString()!="ps") { log.printf(" time: %s = %g ps\n",u.getTimeString().c_str(),u.getTime()); - } - else { + } else { log.printf(" time: %g ps\n",u.getTime()); } s=""; parse("CHARGE",s); - if(s.length()>0) u.setCharge(s); + if(s.length()>0) { + u.setCharge(s); + } if(u.getChargeString().length()>0 && u.getChargeString()=="e") { log.printf(" charge: %s\n",u.getChargeString().c_str()); - } - else if(u.getChargeString().length()>0 && u.getChargeString()!="e") { + } else if(u.getChargeString().length()>0 && u.getChargeString()!="e") { log.printf(" charge: %s = %g e\n",u.getChargeString().c_str(),u.getCharge()); - } - else { + } else { log.printf(" charge: %g e\n",u.getCharge()); } s=""; parse("MASS",s); - if(s.length()>0) u.setMass(s); + if(s.length()>0) { + u.setMass(s); + } if(u.getMassString().length()>0 && u.getMassString()=="amu") { log.printf(" mass: %s\n",u.getMassString().c_str()); - } - else if(u.getMassString().length()>0 && u.getMassString()!="amu") { + } else if(u.getMassString().length()>0 && u.getMassString()!="amu") { log.printf(" mass: %s = %g amu\n",u.getMassString().c_str(),u.getMass()); - } - else { + } else { log.printf(" mass: %g amu\n",u.getMass()); } diff --git a/src/sizeshape/mahadist.cpp b/src/sizeshape/mahadist.cpp index 67ac27914f..68b6befd40 100644 --- a/src/sizeshape/mahadist.cpp +++ b/src/sizeshape/mahadist.cpp @@ -103,8 +103,7 @@ position_maha_dist::position_maha_dist(const ActionOptions&ao): squared(false), dist(0), prec_f_name(""), - ref_f_name("") // Note! no comma here in the last line. -{ + ref_f_name("") { // Note! no comma here in the last line. parseAtomList("GROUP",atom_list); parse("REFERENCE", ref_f_name); parse("PRECISION", prec_f_name); @@ -121,12 +120,18 @@ position_maha_dist::position_maha_dist(const ActionOptions&ao): log.printf(" %d", atom_list[i].serial()); } - if(squared)log.printf("\n chosen to use SQUARED option for SIZESHAPE_POSITION_MAHA_DIST\n"); + if(squared) { + log.printf("\n chosen to use SQUARED option for SIZESHAPE_POSITION_MAHA_DIST\n"); + } - if(pbc) log.printf("\n using periodic boundary conditions\n"); - else log.printf("\n without periodic boundary conditions\n"); + if(pbc) { + log.printf("\n using periodic boundary conditions\n"); + } else { + log.printf("\n without periodic boundary conditions\n"); + } - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); requestAtoms(atom_list); @@ -136,25 +141,28 @@ position_maha_dist::position_maha_dist(const ActionOptions&ao): } // read inputs function -void position_maha_dist::readinputs() -{ +void position_maha_dist::readinputs() { unsigned N=getNumberOfAtoms(); // read ref coords in_.open(ref_f_name); - ref_str.resize(N,3); prec.resize(N,N); + ref_str.resize(N,3); + prec.resize(N,N); std::string line_, val_; unsigned c_=0; - while (c_ < N) - { + while (c_ < N) { in_.getline(line_); std::vector items_; std::stringstream check_(line_); - while(std::getline(check_, val_, ' ')) { items_.push_back(val_); } - for(int i=0; i<3; ++i) { ref_str(c_,i) = std::stold(items_[i]); } + while(std::getline(check_, val_, ' ')) { + items_.push_back(val_); + } + for(int i=0; i<3; ++i) { + ref_str(c_,i) = std::stold(items_[i]); + } c_ += 1; } in_.close(); @@ -165,8 +173,7 @@ void position_maha_dist::readinputs() std::string line, val; unsigned int c = 0; - while(c < N) - { + while(c < N) { in_.getline(line); // vector for storing the objects @@ -175,13 +182,11 @@ void position_maha_dist::readinputs() // stringstream helps to treat a string like an ifstream! std::stringstream check(line); - while (std::getline(check, val, ' ')) - { + while (std::getline(check, val, ' ')) { items.push_back(val); } - for(unsigned int i=0; i>* B) -{ +double position_maha_dist::determinant(int n, const std::vector>* B) { std::vector> A(n, std::vector(n, 0)); // make a copy first! for(int i=0; i maxA ) - { + if ( val > maxA ) { r = k; maxA = val; } } - if ( r != i ) - { - for ( int j = i; j < n; j++ ) std::swap( A[i][j], A[r][j] ); + if ( r != i ) { + for ( int j = i; j < n; j++ ) { + std::swap( A[i][j], A[r][j] ); + } det = -det; } // Row operations to make upper-triangular double pivot = A[i][i]; - if (std::abs( pivot ) < SMALL ) return 0.0; // Singular matrix + if (std::abs( pivot ) < SMALL ) { + return 0.0; // Singular matrix + } - for ( int r = i + 1; r < n; r++ ) // On lower rows - { + for ( int r = i + 1; r < n; r++ ) { // On lower rows double multiple = A[r][i] / pivot; // Multiple of row i to clear element in ith column - for ( int j = i; j < n; j++ ) A[r][j] -= multiple * A[i][j]; + for ( int j = i; j < n; j++ ) { + A[r][j] -= multiple * A[i][j]; + } } det *= pivot; // Determinant is product of diagonal } @@ -269,10 +276,17 @@ void position_maha_dist::kabsch_rot_mat() { unsigned k=0; // Transfer the matrix to the local array - for (int i=0; i( correlation(j,i) ); // note! its [j][i] not [i][j] + for (int i=0; i( correlation(j,i) ); // note! its [j][i] not [i][j] + } int nsv, info, nrows=rw, ncols=cl; - if(rw>cl) {nsv=cl;} else {nsv=rw;} + if(rw>cl) { + nsv=cl; + } else { + nsv=rw; + } // Create some containers for stuff from single value decomposition std::vector S(nsv); @@ -285,15 +299,20 @@ void position_maha_dist::kabsch_rot_mat() { std::vector work(1); plumed_lapack_dgesdd( "A", &nrows, &ncols, da.data(), &nrows, S.data(), U.data(), &nrows, VT.data(), &ncols, work.data(), &lwork, iwork.data(), &info ); //if(info!=0) return info; - if(info!=0) log.printf("info:", info); + if(info!=0) { + log.printf("info:", info); + } // Retrieve correct sizes for work and rellocate - lwork=(int) work[0]; work.resize(lwork); + lwork=(int) work[0]; + work.resize(lwork); // This does the singular value decomposition plumed_lapack_dgesdd( "A", &nrows, &ncols, da.data(), &nrows, S.data(), U.data(), &nrows, VT.data(), &ncols, work.data(), &lwork, iwork.data(), &info ); //if(info!=0) return info; - if(info!=0) log.printf("info:", info); + if(info!=0) { + log.printf("info:", info); + } // get U and VT in form of 2D vector (U_, VT_) @@ -302,8 +321,20 @@ void position_maha_dist::kabsch_rot_mat() { int c=0; - for(int i=0; i rotation(3,3); rotation.resize(3,3); Matrix u(3,3), vt(3,3); - for(int i=0; i<3; ++i) { for(int j=0; j<3; ++j) { u(i,j)=U_[i][j]; vt(i,j)=VT_[i][j]; } } + for(int i=0; i<3; ++i) { + for(int j=0; j<3; ++j) { + u(i,j)=U_[i][j]; + vt(i,j)=VT_[i][j]; + } + } // get rotation matrix mult(u, vt, rotation); @@ -336,7 +376,11 @@ double position_maha_dist::cal_maha_dist() { // compute the displacement Matrix disp(N,3); - for(unsigned int i=0; i prec_dot_disp(N,3); Matrix disp_T(3,N); @@ -349,9 +393,13 @@ double position_maha_dist::cal_maha_dist() { double maha_d=0.0; - for(int i=0; i<3; ++i) { maha_d += out(i,i);} + for(int i=0; i<3; ++i) { + maha_d += out(i,i); + } - if (!squared) maha_d = std::sqrt(maha_d); + if (!squared) { + maha_d = std::sqrt(maha_d); + } return maha_d; } @@ -370,12 +418,24 @@ void position_maha_dist::grad_maha(double d) { transpose(rotation, rot_T); mult(ref_str, rot_T, ref_str_rot_T); - for(unsigned i=0; i items_; std::stringstream check_(line_); - while(std::getline(check_, val_, ' ')) { items_.push_back(val_); } - for(int i=0; i<3; ++i) { ref_str(c_,i) = std::stold(items_[i]); } + while(std::getline(check_, val_, ' ')) { + items_.push_back(val_); + } + for(int i=0; i<3; ++i) { + ref_str(c_,i) = std::stold(items_[i]); + } c_ += 1; } in_.close(); @@ -178,8 +184,7 @@ void position_linear_proj::readinputs() std::string line, val; unsigned int c = 0; - while(c < N) - { + while(c < N) { in_.getline(line); // vector for storing the objects @@ -188,13 +193,11 @@ void position_linear_proj::readinputs() // stringstream helps to treat a string like an ifstream! std::stringstream check(line); - while (std::getline(check, val, ' ')) - { + while (std::getline(check, val, ' ')) { items.push_back(val); } - for(unsigned int i=0; i>* B) -{ +double position_linear_proj::determinant(int n, const std::vector>* B) { std::vector> A(n, std::vector(n, 0)); // make a copy first! for(int i=0; i maxA ) - { + if ( val > maxA ) { r = k; maxA = val; } } - if ( r != i ) - { - for ( int j = i; j < n; j++ ) std::swap( A[i][j], A[r][j] ); + if ( r != i ) { + for ( int j = i; j < n; j++ ) { + std::swap( A[i][j], A[r][j] ); + } det = -det; } // Row operations to make upper-triangular double pivot = A[i][i]; - if (std::abs( pivot ) < SMALL ) return 0.0; // Singular matrix + if (std::abs( pivot ) < SMALL ) { + return 0.0; // Singular matrix + } - for ( int r = i + 1; r < n; r++ ) // On lower rows - { + for ( int r = i + 1; r < n; r++ ) { // On lower rows double multiple = A[r][i] / pivot; // Multiple of row i to clear element in ith column - for ( int j = i; j < n; j++ ) A[r][j] -= multiple * A[i][j]; + for ( int j = i; j < n; j++ ) { + A[r][j] -= multiple * A[i][j]; + } } det *= pivot; // Determinant is product of diagonal } @@ -293,10 +302,17 @@ void position_linear_proj::kabsch_rot_mat() { unsigned k=0; // Transfer the matrix to the local array - for (int i=0; i( correlation(j,i) ); // note! its [j][i] not [i][j] + for (int i=0; i( correlation(j,i) ); // note! its [j][i] not [i][j] + } int nsv, info, nrows=rw, ncols=cl; - if(rw>cl) {nsv=cl;} else {nsv=rw;} + if(rw>cl) { + nsv=cl; + } else { + nsv=rw; + } // Create some containers for stuff from single value decomposition std::vector S(nsv); @@ -309,15 +325,20 @@ void position_linear_proj::kabsch_rot_mat() { std::vector work(1); plumed_lapack_dgesdd( "A", &nrows, &ncols, da.data(), &nrows, S.data(), U.data(), &nrows, VT.data(), &ncols, work.data(), &lwork, iwork.data(), &info ); //if(info!=0) return info; - if(info!=0) log.printf("info:", info); + if(info!=0) { + log.printf("info:", info); + } // Retrieve correct sizes for work and rellocate - lwork=(int) work[0]; work.resize(lwork); + lwork=(int) work[0]; + work.resize(lwork); // This does the singular value decomposition plumed_lapack_dgesdd( "A", &nrows, &ncols, da.data(), &nrows, S.data(), U.data(), &nrows, VT.data(), &ncols, work.data(), &lwork, iwork.data(), &info ); //if(info!=0) return info; - if(info!=0) log.printf("info:", info); + if(info!=0) { + log.printf("info:", info); + } // get U and VT in form of 2D vector (U_, VT_) @@ -326,8 +347,20 @@ void position_linear_proj::kabsch_rot_mat() { int c=0; - for(int i=0; i rotation(3,3); rotation.resize(3,3); Matrix u(3,3), vt(3,3); - for(int i=0; i<3; ++i) { for(int j=0; j<3; ++j) { u(i,j)=U_[i][j]; vt(i,j)=VT_[i][j]; } } + for(int i=0; i<3; ++i) { + for(int j=0; j<3; ++j) { + u(i,j)=U_[i][j]; + vt(i,j)=VT_[i][j]; + } + } // get rotation matrix mult(u, vt, rotation); @@ -361,11 +403,18 @@ double position_linear_proj::cal_position_linear_proj() { // compute the displacement std::vector disp(N*3); unsigned c=0; - for(unsigned int i=0; i concept Complete = requires { sizeof (T); }; @@ -352,17 +350,18 @@ concept NoThrowConstructibleFrom = std::is_nothrow_constructible::va template concept ConvertibleTo = std::is_convertible::value - && requires (typename std::add_rvalue_reference::type (&f) (void)) -{ +&& requires (typename std::add_rvalue_reference::type (&f) (void)) { static_cast (f ()); }; template concept NoThrowConvertibleTo = std::is_nothrow_convertible::value - && requires (typename std::add_rvalue_reference::type (&f) (void) noexcept) -{ - { static_cast (f ()) } noexcept; +&& requires (typename std::add_rvalue_reference::type (&f) (void) noexcept) { + { + static_cast (f ()) + } + noexcept; }; // Note: std::default_initializable requires std::destructible. @@ -426,12 +425,10 @@ concept EmplaceConstructible = && ( ( requires { typename X::allocator_type; } // only perform this check if X is && std::same_as::template rebind_alloc> - && ( requires (A m, T *p, Args&&... args) -{ +&& ( requires (A m, T *p, Args&&... args) { m.construct (p, std::forward (args)...); } -|| requires (T *p, Args&&... args) -{ +|| requires (T *p, Args&&... args) { #if __cplusplus >= 202002L // c++20 fully featured { std::construct_at (p, std::forward (args)...) } -> std::same_as; #else @@ -439,8 +436,7 @@ concept EmplaceConstructible = #endif })) || (! requires { typename X::allocator_type; } - && requires (T *p, Args&&... args) -{ +&& requires (T *p, Args&&... args) { #if __cplusplus >= 202002L // c++20 fully featured { std::construct_at (p, std::forward (args)...) } -> std::same_as; #else @@ -478,8 +474,7 @@ typename A = typename std::conditional::template rebind_alloc> - && ( requires (A m, T *p) -{ +&& ( requires (A m, T *p) { m.destroy (p); } || std::is_destructible::value)) @@ -502,15 +497,32 @@ EqualityComparable && Destructible && ConstructibleFrom && ConvertibleTo -&& requires (T p, T q, std::nullptr_t np) -{ +&& requires (T p, T q, std::nullptr_t np) { T (np); - { p = np } -> std::same_as; - { p != q } -> ContextuallyConvertibleToBool; - { p == np } -> ContextuallyConvertibleToBool; - { np == p } -> ContextuallyConvertibleToBool; - { p != np } -> ContextuallyConvertibleToBool; - { np != p } -> ContextuallyConvertibleToBool; + { + p = np + } + -> std::same_as; + { + p != q + } + -> ContextuallyConvertibleToBool; + { + p == np + } + -> ContextuallyConvertibleToBool; + { + np == p + } + -> ContextuallyConvertibleToBool; + { + p != np + } + -> ContextuallyConvertibleToBool; + { + np != p + } + -> ContextuallyConvertibleToBool; }; static_assert ( NullablePointer); @@ -527,8 +539,7 @@ NoThrowCopyConstructible typename std::allocator_traits::void_pointer vp, typename std::allocator_traits::const_void_pointer cvp, typename std::allocator_traits::value_type& r, - typename std::allocator_traits::size_type n) -{ + typename std::allocator_traits::size_type n) { /** Inner types **/ // A::pointer requires NullablePointer< typename std::allocator_traits::pointer>; @@ -581,46 +592,64 @@ NoThrowCopyConstructible // A::template rebind::other [optional] requires ! requires { typename A::template rebind::other; } - || requires - { + || requires { requires std::same_as::other>; requires std::same_as::other>; }; /** Operations on pointers **/ - { *p } -> std::same_as; - { *cp } -> std::same_as; + { + *p + } + -> std::same_as; + { + *cp + } + -> std::same_as; // Language in the standard implies that `decltype (p)` must either // be a raw pointer or implement `operator->`. There is no mention // of `std::to_address` or `std::pointer_traits::to_address`. requires std::same_as - || requires - { + || requires { { p.operator-> () } -> std::same_as; }; requires std::same_as - || requires - { + || requires { { cp.operator-> () } -> std::same_as; }; - { static_cast (vp) } -> std::same_as; - { static_cast (cvp) } -> std::same_as; + { + static_cast (vp) + } + -> std::same_as; + { + static_cast (cvp) + } + -> std::same_as; - { std::pointer_traits::pointer_to (r) } -> std::same_as; + { + std::pointer_traits::pointer_to (r) + } + -> std::same_as; /** Storage and lifetime operations **/ // a.allocate (n) - { a.allocate (n) } -> std::same_as; + { + a.allocate (n) + } + -> std::same_as; // a.allocate (n, cvp) [optional] requires ! requires { a.allocate (n, cvp); } || requires { { a.allocate (n, cvp) } -> std::same_as; }; // a.deallocate (p, n) - { a.deallocate (p, n) } -> std::convertible_to; + { + a.deallocate (p, n) + } + -> std::convertible_to; // a.max_size () [optional] requires ! requires { a.max_size (); } @@ -643,8 +672,7 @@ NoThrowCopyConstructible /** Influence on container operations **/ // a.select_on_container_copy_construction () [optional] requires ! requires { a.select_on_container_copy_construction (); } - || requires - { + || requires { { a.select_on_container_copy_construction () } -> std::same_as; }; @@ -657,13 +685,24 @@ NoThrowCopyConstructible requires BoolConstant< typename std::allocator_traits::propagate_on_container_swap>; - { a == b } -> std::same_as; - { a != b } -> std::same_as; + { + a == b + } + -> std::same_as; + { + a != b + } + -> std::same_as; } -&& requires (A a1, A a2) -{ - { a1 == a2 } -> std::same_as; - { a1 != a2 } -> std::same_as; +&& requires (A a1, A a2) { + { + a1 == a2 + } + -> std::same_as; + { + a1 != a2 + } + -> std::same_as; }; static_assert (AllocatorFor, int>, @@ -672,8 +711,7 @@ static_assert (AllocatorFor, int>, template concept Allocator = AllocatorFor; -namespace small_vector -{ +namespace small_vector { // Basically, these shut off the concepts if we have an incomplete type. // This namespace is only needed because of issues on Clang @@ -754,18 +792,17 @@ template #ifdef PLUMED_GCH_LIB_CONCEPTS requires concepts::small_vector::Allocator #endif -struct default_buffer_size -{ +struct default_buffer_size { private: template struct is_complete -: std::false_type - { }; +: std::false_type { + }; template struct is_complete (sizeof (U)))> -: std::true_type - { }; +: std::true_type { + }; public: using allocator_type = Allocator; @@ -817,8 +854,7 @@ default_buffer_size_v = default_buffer_size::value; #endif template -class small_vector_iterator -{ +class small_vector_iterator { public: using difference_type = DifferenceType; using value_type = typename std::iterator_traits::value_type; @@ -859,68 +895,59 @@ class small_vector_iterator PLUMED_GCH_CPP14_CONSTEXPR small_vector_iterator& - operator++ (void) noexcept - { + operator++ (void) noexcept { ++m_ptr; return *this; } PLUMED_GCH_CPP14_CONSTEXPR small_vector_iterator - operator++ (int) noexcept - { + operator++ (int) noexcept { return small_vector_iterator (m_ptr++); } PLUMED_GCH_CPP14_CONSTEXPR small_vector_iterator& - operator-- (void) noexcept - { + operator-- (void) noexcept { --m_ptr; return *this; } PLUMED_GCH_CPP14_CONSTEXPR small_vector_iterator - operator-- (int) noexcept - { + operator-- (int) noexcept { return small_vector_iterator (m_ptr--); } PLUMED_GCH_CPP14_CONSTEXPR small_vector_iterator& - operator+= (difference_type n) noexcept - { + operator+= (difference_type n) noexcept { m_ptr += n; return *this; } constexpr small_vector_iterator - operator+ (difference_type n) const noexcept - { + operator+ (difference_type n) const noexcept { return small_vector_iterator (m_ptr + n); } PLUMED_GCH_CPP14_CONSTEXPR small_vector_iterator& - operator-= (difference_type n) noexcept - { + operator-= (difference_type n) noexcept { m_ptr -= n; return *this; } constexpr small_vector_iterator - operator- (difference_type n) const noexcept - { + operator- (difference_type n) const noexcept { return small_vector_iterator (m_ptr - n); } constexpr reference - operator* (void) const noexcept - { + operator* (void) const noexcept { #ifdef PLUMED_GCH_LIB_LAUNDER return launder_and_dereference (m_ptr); #else @@ -930,15 +957,13 @@ class small_vector_iterator constexpr pointer - operator-> (void) const noexcept - { + operator-> (void) const noexcept { return get_pointer (m_ptr); } constexpr reference - operator[] (difference_type n) const noexcept - { + operator[] (difference_type n) const noexcept { #ifdef PLUMED_GCH_LIB_LAUNDER return launder_and_dereference (m_ptr + n); #else @@ -948,8 +973,7 @@ class small_vector_iterator constexpr const Pointer& - base (void) const noexcept - { + base (void) const noexcept { return m_ptr; } @@ -958,8 +982,7 @@ class small_vector_iterator typename std::enable_if::value, bool>::type = true> static constexpr pointer - get_pointer (Pointer ptr) noexcept - { + get_pointer (Pointer ptr) noexcept { return ptr; } @@ -967,8 +990,7 @@ class small_vector_iterator typename std::enable_if::value, bool>::type = false> static constexpr pointer - get_pointer (Pointer ptr) noexcept - { + get_pointer (Pointer ptr) noexcept { // Given the requirements for Allocator, Pointer must either be a raw pointer, or // have a defined operator-> which returns a raw pointer. return ptr.operator-> (); @@ -980,8 +1002,7 @@ class small_vector_iterator typename std::enable_if::value, bool>::type = true> static constexpr reference - launder_and_dereference (Pointer ptr) noexcept - { + launder_and_dereference (Pointer ptr) noexcept { return *std::launder (ptr); } @@ -989,8 +1010,7 @@ class small_vector_iterator typename std::enable_if::value, bool>::type = false> static constexpr reference - launder_and_dereference (Pointer ptr) noexcept - { + launder_and_dereference (Pointer ptr) noexcept { return *ptr; } @@ -1008,8 +1028,7 @@ bool operator== (const small_vector_iterator& lhs, const small_vector_iterator& rhs) noexcept (noexcept (lhs.base () == rhs.base ())) -requires requires { { lhs.base () == rhs.base () } -> std::convertible_to; } -{ +requires requires { { lhs.base () == rhs.base () } -> std::convertible_to; } { return lhs.base () == rhs.base (); } @@ -1019,8 +1038,7 @@ bool operator== (const small_vector_iterator& lhs, const small_vector_iterator& rhs) noexcept (noexcept (lhs.base () == rhs.base ())) -requires requires { { lhs.base () == rhs.base () } -> std::convertible_to; } -{ +requires requires { { lhs.base () == rhs.base () } -> std::convertible_to; } { return lhs.base () == rhs.base (); } @@ -1031,8 +1049,7 @@ constexpr auto operator<=> (const small_vector_iterator& lhs, const small_vector_iterator& rhs) -noexcept (noexcept (lhs.base () <=> rhs.base ())) -{ +noexcept (noexcept (lhs.base () <=> rhs.base ())) { return lhs.base () <=> rhs.base (); } @@ -1042,8 +1059,7 @@ constexpr auto operator<=> (const small_vector_iterator& lhs, const small_vector_iterator& rhs) -noexcept (noexcept (lhs.base () <=> rhs.base ())) -{ +noexcept (noexcept (lhs.base () <=> rhs.base ())) { return lhs.base () <=> rhs.base (); } @@ -1053,8 +1069,7 @@ constexpr auto operator<=> (const small_vector_iterator& lhs, const small_vector_iterator& rhs) -noexcept (noexcept (lhs.base () < rhs.base ()) && noexcept (rhs.base () < lhs.base ())) -{ +noexcept (noexcept (lhs.base () < rhs.base ()) && noexcept (rhs.base () < lhs.base ())) { using ordering = std::weak_ordering; return (lhs.base () < rhs.base ()) ? ordering::less : (rhs.base () < lhs.base ()) ? ordering::greater @@ -1066,8 +1081,7 @@ constexpr auto operator<=> (const small_vector_iterator& lhs, const small_vector_iterator& rhs) -noexcept (noexcept (lhs.base () < rhs.base ()) && noexcept (rhs.base () < lhs.base ())) -{ +noexcept (noexcept (lhs.base () < rhs.base ()) && noexcept (rhs.base () < lhs.base ())) { using ordering = std::weak_ordering; return (lhs.base () < rhs.base ()) ? ordering::less : (rhs.base () < lhs.base ()) ? ordering::greater @@ -1087,8 +1101,7 @@ template & lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return lhs.base () == rhs.base (); } @@ -1096,8 +1109,7 @@ template constexpr bool operator== (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return lhs.base () == rhs.base (); } @@ -1106,8 +1118,7 @@ template & lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return lhs.base () != rhs.base (); } @@ -1115,8 +1126,7 @@ template constexpr bool operator!= (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return lhs.base () != rhs.base (); } @@ -1125,8 +1135,7 @@ template & lhs, - const small_vector_iterator& rhs) noexcept -{ +const small_vector_iterator& rhs) noexcept { return lhs.base () < rhs.base (); } @@ -1134,8 +1143,7 @@ template constexpr bool operator< (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ +const small_vector_iterator& rhs) noexcept { return lhs.base () < rhs.base (); } @@ -1144,8 +1152,7 @@ template = (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return lhs.base () >= rhs.base (); } @@ -1153,8 +1160,7 @@ template constexpr bool operator>= (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return lhs.base () >= rhs.base (); } @@ -1163,8 +1169,7 @@ template (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return lhs.base () > rhs.base (); } @@ -1172,8 +1177,7 @@ template constexpr bool operator> (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return lhs.base () > rhs.base (); } @@ -1182,8 +1186,7 @@ template & lhs, - const small_vector_iterator& rhs) noexcept -{ +const small_vector_iterator& rhs) noexcept { return lhs.base () <= rhs.base (); } @@ -1191,8 +1194,7 @@ template constexpr bool operator<= (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ +const small_vector_iterator& rhs) noexcept { return lhs.base () <= rhs.base (); } @@ -1202,8 +1204,7 @@ template constexpr DifferenceType operator- (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return static_cast (lhs.base () - rhs.base ()); } @@ -1211,46 +1212,41 @@ template constexpr DifferenceType operator- (const small_vector_iterator& lhs, - const small_vector_iterator& rhs) noexcept -{ + const small_vector_iterator& rhs) noexcept { return static_cast (lhs.base () - rhs.base ()); } template constexpr small_vector_iterator -operator+ (DifferenceType n, const small_vector_iterator& it) noexcept -{ +operator+ (DifferenceType n, const small_vector_iterator& it) noexcept { return it + n; } -namespace detail -{ +namespace detail { #ifndef PLUMED_GCH_LIB_IS_SWAPPABLE -namespace small_vector_adl -{ +namespace small_vector_adl { using std::swap; template struct is_nothrow_swappable -: std::false_type -{ }; +: std::false_type { +}; template struct is_nothrow_swappable (), std::declval ()))> -: std::integral_constant (), std::declval ()))> -{ }; +: std::integral_constant (), std::declval ()))> { +}; } #endif template -class inline_storage -{ +class inline_storage { public: using value_ty = T; @@ -1263,43 +1259,37 @@ class inline_storage PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR value_ty * - get_inline_ptr (void) noexcept - { + get_inline_ptr (void) noexcept { return static_cast (static_cast (std::addressof (*m_data))); } PLUMED_GCH_NODISCARD constexpr const value_ty * - get_inline_ptr (void) const noexcept - { + get_inline_ptr (void) const noexcept { return static_cast (static_cast (std::addressof (*m_data))); } static constexpr std::size_t - element_size (void) noexcept - { + element_size (void) noexcept { return sizeof (value_ty); } static constexpr std::size_t - alignment (void) noexcept - { + alignment (void) noexcept { return alignof (value_ty); } static constexpr unsigned - num_elements (void) noexcept - { + num_elements (void) noexcept { return InlineCapacity; } static constexpr std::size_t - num_bytes (void) noexcept - { + num_bytes (void) noexcept { return num_elements () * element_size (); } @@ -1308,8 +1298,7 @@ class inline_storage }; template -class PLUMED_GCH_EMPTY_BASE inline_storage -{ +class PLUMED_GCH_EMPTY_BASE inline_storage { public: using value_ty = T; @@ -1322,43 +1311,37 @@ class PLUMED_GCH_EMPTY_BASE inline_storage PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR value_ty * - get_inline_ptr (void) noexcept - { + get_inline_ptr (void) noexcept { return nullptr; } PLUMED_GCH_NODISCARD constexpr const value_ty * - get_inline_ptr (void) const noexcept - { + get_inline_ptr (void) const noexcept { return nullptr; } static constexpr std::size_t - element_size (void) noexcept - { + element_size (void) noexcept { return sizeof (value_ty); } static constexpr std::size_t - alignment (void) noexcept - { + alignment (void) noexcept { return alignof (value_ty); } static constexpr unsigned - num_elements (void) noexcept - { + num_elements (void) noexcept { return 0; } static constexpr std::size_t - num_bytes (void) noexcept - { + num_bytes (void) noexcept { return 0; } }; @@ -1372,8 +1355,7 @@ class allocator_inliner; template class PLUMED_GCH_EMPTY_BASE allocator_inliner -: private Allocator -{ +: private Allocator { using alloc_traits = std::allocator_traits; static constexpr @@ -1399,8 +1381,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_inliner PLUMED_GCH_CPP20_CONSTEXPR void maybe_assign (const allocator_inliner& other) - noexcept (noexcept (std::declval ().operator= (other))) - { + noexcept (noexcept (std::declval ().operator= (other))) { Allocator::operator= (other); } @@ -1415,8 +1396,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_inliner PLUMED_GCH_CPP20_CONSTEXPR void maybe_assign (allocator_inliner&& other) - noexcept (noexcept (std::declval ().operator= (std::move (other)))) - { + noexcept (noexcept (std::declval ().operator= (std::move (other)))) { Allocator::operator= (std::move (other)); } @@ -1436,8 +1416,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_inliner PLUMED_GCH_CPP20_CONSTEXPR allocator_inliner& operator= (const allocator_inliner& other) - noexcept (noexcept (std::declval ().maybe_assign (other))) - { + noexcept (noexcept (std::declval ().maybe_assign (other))) { assert (&other != this && "`allocator_inliner` should not participate in self-copy-assignment."); maybe_assign (other); @@ -1447,8 +1426,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_inliner PLUMED_GCH_CPP20_CONSTEXPR allocator_inliner& operator= (allocator_inliner&& other) - noexcept (noexcept (std::declval ().maybe_assign (std::move (other)))) - { + noexcept (noexcept (std::declval ().maybe_assign (std::move (other)))) { assert (&other != this && "`allocator_inliner` should not participate in self-move-assignment."); maybe_assign (std::move (other)); @@ -1457,15 +1435,13 @@ class PLUMED_GCH_EMPTY_BASE allocator_inliner PLUMED_GCH_CPP14_CONSTEXPR Allocator& - allocator_ref (void) noexcept - { + allocator_ref (void) noexcept { return *this; } constexpr const Allocator& - allocator_ref (void) const noexcept - { + allocator_ref (void) const noexcept { return *this; } @@ -1480,16 +1456,14 @@ class PLUMED_GCH_EMPTY_BASE allocator_inliner typename std::enable_if::type = false> PLUMED_GCH_CPP20_CONSTEXPR void - swap (allocator_inliner& other) - { + swap (allocator_inliner& other) { using std::swap; swap (static_cast (*this), static_cast (other)); } }; template -class allocator_inliner -{ +class allocator_inliner { using alloc_traits = std::allocator_traits; static constexpr @@ -1515,8 +1489,7 @@ class allocator_inliner PLUMED_GCH_CPP20_CONSTEXPR void maybe_assign (const allocator_inliner& other) - noexcept (noexcept (std::declval () = other.m_alloc)) - { + noexcept (noexcept (std::declval () = other.m_alloc)) { m_alloc = other.m_alloc; } @@ -1531,8 +1504,7 @@ class allocator_inliner PLUMED_GCH_CPP20_CONSTEXPR void maybe_assign (allocator_inliner&& other) - noexcept (noexcept (std::declval () = std::move (other.m_alloc))) - { + noexcept (noexcept (std::declval () = std::move (other.m_alloc))) { m_alloc = std::move (other.m_alloc); } @@ -1552,8 +1524,7 @@ class allocator_inliner PLUMED_GCH_CPP20_CONSTEXPR allocator_inliner& operator= (const allocator_inliner& other) - noexcept (noexcept (std::declval ().maybe_assign (other))) - { + noexcept (noexcept (std::declval ().maybe_assign (other))) { assert (&other != this && "`allocator_inliner` should not participate in self-copy-assignment."); maybe_assign (other); @@ -1563,8 +1534,7 @@ class allocator_inliner PLUMED_GCH_CPP20_CONSTEXPR allocator_inliner& operator= (allocator_inliner&& other) - noexcept (noexcept (std::declval ().maybe_assign (std::move (other)))) - { + noexcept (noexcept (std::declval ().maybe_assign (std::move (other)))) { assert (&other != this && "`allocator_inliner` should not participate in self-move-assignment."); maybe_assign (std::move (other)); @@ -1573,15 +1543,13 @@ class allocator_inliner PLUMED_GCH_CPP14_CONSTEXPR Allocator& - allocator_ref (void) noexcept - { + allocator_ref (void) noexcept { return m_alloc; } constexpr const Allocator& - allocator_ref (void) const noexcept - { + allocator_ref (void) const noexcept { return m_alloc; } @@ -1596,8 +1564,7 @@ class allocator_inliner typename std::enable_if::type = false> PLUMED_GCH_CPP20_CONSTEXPR void - swap (allocator_inliner& other) - { + swap (allocator_inliner& other) { using std::swap; swap (m_alloc, other.m_alloc); } @@ -1608,18 +1575,17 @@ class allocator_inliner template class PLUMED_GCH_EMPTY_BASE allocator_interface -: public allocator_inliner -{ +: public allocator_inliner { public: template struct is_complete -: std::false_type - { }; +: std::false_type { + }; template struct is_complete (sizeof (U)))> -: std::true_type - { }; +: std::true_type { + }; using size_type = typename std::allocator_traits::size_type; @@ -1698,118 +1664,117 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface template struct is_trivially_destructible -: std::false_type - { }; +: std::false_type { + }; template struct is_trivially_destructible::value>::type> -: std::is_trivially_destructible - { }; +: std::is_trivially_destructible { + }; template struct is_trivially_constructible_impl -: std::false_type - { }; +: std::false_type { + }; template struct is_trivially_constructible_impl< typename std::enable_if::value>::type, V, Args...> -: std::is_trivially_constructible - { }; +: std::is_trivially_constructible { + }; template struct is_trivially_constructible -: is_trivially_constructible_impl - { }; +: is_trivially_constructible_impl { + }; template - struct underlying_if_enum - { + struct underlying_if_enum { using type = T; }; template struct underlying_if_enum::value>::type> -: std::underlying_type - { }; +: std::underlying_type { + }; template using underlying_if_enum_t = typename underlying_if_enum::type; template struct has_ptr_traits_to_address -: std::false_type - { }; +: std::false_type { + }; template struct has_ptr_traits_to_address::to_address (std::declval

()))>> -: std::true_type - { }; +: std::true_type { + }; template struct has_alloc_construct_check -: std::false_type - { }; +: std::false_type { + }; template struct has_alloc_construct_check< void_t ().construct (std::declval (), std::declval ()...))>, A, V, Args...> -: std::true_type - { }; +: std::true_type { + }; template struct has_alloc_construct_impl -: std::false_type - { }; +: std::false_type { + }; template struct has_alloc_construct_impl::value>::type, A, V, Args...> -: has_alloc_construct_check - { }; +: has_alloc_construct_check { + }; template struct has_alloc_construct -: has_alloc_construct_impl - { }; +: has_alloc_construct_impl { + }; template struct must_use_alloc_construct : bool_constant>::value - && has_alloc_construct::value> - { }; + && has_alloc_construct::value> { + }; template struct has_alloc_destroy_impl -: std::false_type - { }; +: std::false_type { + }; template struct has_alloc_destroy_impl< void_t ().destroy (std::declval ()))>, A, V> -: std::true_type - { }; +: std::true_type { + }; template struct has_alloc_destroy -: std::false_type - { }; +: std::false_type { + }; template struct has_alloc_destroy::value>::type> -: has_alloc_destroy_impl - { }; +: has_alloc_destroy_impl { + }; template struct must_use_alloc_destroy : bool_constant>::value - && has_alloc_destroy::value> - { }; + && has_alloc_destroy::value> { + }; public: allocator_interface (void) = default; @@ -1844,62 +1809,59 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface template struct is_memcpyable_integral -: std::false_type - { }; +: std::false_type { + }; template struct is_memcpyable_integral::value>::type> - { - using from = underlying_if_enum_t; - using to = underlying_if_enum_t; - - static constexpr - bool - value = (sizeof (from) == sizeof (to)) - && (std::is_same::value == std::is_same::value) - && std::is_integral::value - && std::is_integral::value; - }; + typename std::enable_if::value>::type> { + using from = underlying_if_enum_t; + using to = underlying_if_enum_t; + + static constexpr + bool + value = (sizeof (from) == sizeof (to)) + && (std::is_same::value == std::is_same::value) + && std::is_integral::value + && std::is_integral::value; + }; template struct is_convertible_pointer : bool_constant::value && std::is_pointer::value - && std::is_convertible::value> - { }; + && std::is_convertible::value> { + }; // Memcpyable assignment. template struct is_memcpyable -: std::false_type - { }; +: std::false_type { + }; template struct is_memcpyable::value>::type> - { - static_assert (! std::is_reference::value, - "QualifiedTo must not be a reference."); + typename std::enable_if::value>::type> { + static_assert (! std::is_reference::value, + "QualifiedTo must not be a reference."); - using from = typename std::remove_reference< - typename std::remove_cv::type>::type; + using from = typename std::remove_reference< + typename std::remove_cv::type>::type; - using to = typename std::remove_cv::type; + using to = typename std::remove_cv::type; - static constexpr - bool - value = std::is_trivially_assignable::value - && std::is_trivially_copyable::value - && ( std::is_same::type, to>::value - || is_memcpyable_integral::value - || is_convertible_pointer::value); - }; + static constexpr + bool + value = std::is_trivially_assignable::value + && std::is_trivially_copyable::value + && ( std::is_same::type, to>::value + || is_memcpyable_integral::value + || is_convertible_pointer::value); + }; // Memcpyable construction. template - struct is_uninitialized_memcpyable_impl - { + struct is_uninitialized_memcpyable_impl { static_assert (! std::is_reference::value, "QualifiedTo must not be a reference."); @@ -1921,23 +1883,23 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface template struct is_uninitialized_memcpyable -: std::false_type - { }; +: std::false_type { + }; template struct is_uninitialized_memcpyable -: is_uninitialized_memcpyable_impl - { }; +: is_uninitialized_memcpyable_impl { + }; template struct is_small_vector_iterator -: std::false_type - { }; +: std::false_type { + }; template struct is_small_vector_iterator> -: std::true_type - { }; +: std::true_type { + }; template struct is_contiguous_iterator @@ -1960,38 +1922,37 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface || std::is_same&> ()))>::value #endif - > - { }; + > { + }; template struct is_memcpyable_iterator : bool_constant ())>::value - && is_contiguous_iterator::value> - { }; + && is_contiguous_iterator::value> { + }; // Unwrap `move_iterator`s. template struct is_memcpyable_iterator> -: is_memcpyable_iterator - { }; +: is_memcpyable_iterator { + }; template struct is_uninitialized_memcpyable_iterator : bool_constant ())>::value - && is_contiguous_iterator::value> - { }; + && is_contiguous_iterator::value> { + }; // unwrap move_iterators template struct is_uninitialized_memcpyable_iterator, V> -: is_uninitialized_memcpyable_iterator - { }; +: is_uninitialized_memcpyable_iterator { + }; PLUMED_GCH_NORETURN static PLUMED_GCH_CPP20_CONSTEXPR void - throw_range_length_error (void) - { + throw_range_length_error (void) { #ifdef PLUMED_GCH_EXCEPTIONS throw std::length_error ("The specified range is too long."); #else @@ -2002,16 +1963,14 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface static constexpr value_ty * - to_address (value_ty *p) noexcept - { + to_address (value_ty *p) noexcept { static_assert (! std::is_function::value, "value_ty is a function pointer."); return p; } static constexpr const value_ty * - to_address (const value_ty *p) noexcept - { + to_address (const value_ty *p) noexcept { static_assert (! std::is_function::value, "value_ty is a function pointer."); return p; } @@ -2021,8 +1980,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface static constexpr auto to_address (const Pointer& p) noexcept - -> decltype (std::pointer_traits::to_address (p)) - { + -> decltype (std::pointer_traits::to_address (p)) { return std::pointer_traits::to_address (p); } @@ -2031,8 +1989,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface static constexpr auto to_address (const Pointer& p) noexcept - -> decltype (to_address (p.operator-> ())) - { + -> decltype (to_address (p.operator-> ())) { return to_address (p.operator-> ()); } @@ -2040,8 +1997,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_NODISCARD static PLUMED_GCH_CONSTEVAL std::size_t - numeric_max (void) noexcept - { + numeric_max (void) noexcept { static_assert (0 <= (std::numeric_limits::max) (), "Integer is nonpositive."); return static_cast ((std::numeric_limits::max) ()); } @@ -2049,8 +2005,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_NODISCARD static PLUMED_GCH_CPP17_CONSTEXPR size_ty - internal_range_length (cptr first, cptr last) noexcept - { + internal_range_length (cptr first, cptr last) noexcept { // This is guaranteed to be less than or equal to max size_ty. return static_cast (last - first); } @@ -2059,13 +2014,13 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_NODISCARD static PLUMED_GCH_CPP17_CONSTEXPR size_ty - external_range_length_impl (RandomIt first, RandomIt last, std::random_access_iterator_tag) - { + external_range_length_impl (RandomIt first, RandomIt last, std::random_access_iterator_tag) { assert (0 <= (last - first) && "Invalid range."); const auto len = static_cast (last - first); #ifndef NDEBUG - if (numeric_max () < len) + if (numeric_max () < len) { throw_range_length_error (); + } #endif return static_cast (len); } @@ -2074,15 +2029,14 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_NODISCARD static PLUMED_GCH_CPP17_CONSTEXPR size_ty - external_range_length_impl (ForwardIt first, ForwardIt last, std::forward_iterator_tag) - { + external_range_length_impl (ForwardIt first, ForwardIt last, std::forward_iterator_tag) { #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) - { + if (std::is_constant_evaluated ()) { // Make sure constexpr doesn't get broken by `using namespace std::rel_ops`. typename std::iterator_traits::difference_type len = 0; - for (; ! (first == last); ++first) + for (; ! (first == last); ++first) { ++len; + } assert (static_cast (len) <= numeric_max ()); return static_cast (len); } @@ -2090,8 +2044,9 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface const auto len = static_cast (std::distance (first, last)); #ifndef NDEBUG - if (numeric_max () < len) + if (numeric_max () < len) { throw_range_length_error (); + } #endif return static_cast (len); } @@ -2103,8 +2058,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_NODISCARD static PLUMED_GCH_CPP17_CONSTEXPR size_ty - external_range_length (ForwardIt first, ForwardIt last) - { + external_range_length (ForwardIt first, ForwardIt last) { using iterator_cat = typename std::iterator_traits::iterator_category; return external_range_length_impl (first, last, iterator_cat { }); } @@ -2116,15 +2070,14 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_NODISCARD static PLUMED_GCH_CPP17_CONSTEXPR size_ty - external_range_length (ForwardIt first, ForwardIt last) noexcept - { + external_range_length (ForwardIt first, ForwardIt last) noexcept { #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) - { + if (std::is_constant_evaluated ()) { // Make sure constexpr doesn't get broken by `using namespace std::rel_ops`. size_ty len = 0; - for (; ! (first == last); ++first) + for (; ! (first == last); ++first) { ++len; + } return len; } #endif @@ -2138,8 +2091,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_NODISCARD static PLUMED_GCH_CPP17_CONSTEXPR Iterator - unchecked_next (Iterator pos, Integer n = 1) noexcept - { + unchecked_next (Iterator pos, Integer n = 1) noexcept { unchecked_advance (pos, static_cast (n)); return pos; } @@ -2150,8 +2102,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_NODISCARD static PLUMED_GCH_CPP17_CONSTEXPR Iterator - unchecked_prev (Iterator pos, Integer n = 1) noexcept - { + unchecked_prev (Iterator pos, Integer n = 1) noexcept { unchecked_advance (pos, -static_cast (n)); return pos; } @@ -2161,15 +2112,13 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface typename Integer = IteratorDiffT> static PLUMED_GCH_CPP17_CONSTEXPR void - unchecked_advance (Iterator& pos, Integer n) noexcept - { + unchecked_advance (Iterator& pos, Integer n) noexcept { std::advance (pos, static_cast (n)); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP20_CONSTEXPR size_ty - get_max_size (void) const noexcept - { + get_max_size (void) const noexcept { // This is protected from max/min macros. return (std::min) (static_cast (alloc_traits::max_size (allocator_ref ())), static_cast (numeric_max ())); @@ -2177,22 +2126,19 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_NODISCARD PLUMED_GCH_CPP20_CONSTEXPR ptr - allocate (size_ty n) - { + allocate (size_ty n) { return alloc_traits::allocate (allocator_ref (), static_cast (n)); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP20_CONSTEXPR ptr - allocate_with_hint (size_ty n, cptr hint) - { + allocate_with_hint (size_ty n, cptr hint) { return alloc_traits::allocate (allocator_ref (), static_cast (n), hint); } PLUMED_GCH_CPP20_CONSTEXPR void - deallocate (ptr p, size_ty n) - { + deallocate (ptr p, size_ty n) { alloc_traits::deallocate (allocator_ref (), to_address (p), static_cast (n)); } @@ -2202,11 +2148,9 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface is_uninitialized_memcpyable::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - construct (ptr p, U&& val) noexcept - { + construct (ptr p, U&& val) noexcept { #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) - { + if (std::is_constant_evaluated ()) { alloc_traits::construct (allocator_ref (), to_address (p), std::forward (val)); return; } @@ -2225,8 +2169,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface construct (ptr p, Args&&... args) noexcept (noexcept (alloc_traits::construct (std::declval (), std::declval (), - std::forward (args)...))) - { + std::forward (args)...))) { alloc_traits::construct (allocator_ref (), to_address (p), std::forward (args)...); } @@ -2239,8 +2182,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_CPP20_CONSTEXPR void construct (ptr p, Args&&... args) - noexcept (noexcept (::new (std::declval ()) value_ty (std::declval ()...))) - { + noexcept (noexcept (::new (std::declval ()) value_ty (std::declval ()...))) { construct_at (to_address (p), std::forward (args)...); } @@ -2258,8 +2200,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface && has_alloc_destroy::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - destroy (ptr p) noexcept - { + destroy (ptr p) noexcept { alloc_traits::destroy (allocator_ref (), to_address (p)); } @@ -2270,8 +2211,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface &&! has_alloc_destroy::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - destroy (ptr p) noexcept - { + destroy (ptr p) noexcept { destroy_at (to_address (p)); } @@ -2288,10 +2228,10 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface || must_use_alloc_destroy::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - destroy_range (ptr first, ptr last) noexcept - { - for (; ! (first == last); ++first) + destroy_range (ptr first, ptr last) noexcept { + for (; ! (first == last); ++first) { destroy (first); + } } // allowed if trivially copyable and we use the standard allocator @@ -2301,19 +2241,20 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface is_uninitialized_memcpyable_iterator::value, bool>::type = true> PLUMED_GCH_CPP20_CONSTEXPR ptr - uninitialized_copy (ForwardIt first, ForwardIt last, ptr dest) noexcept - { + uninitialized_copy (ForwardIt first, ForwardIt last, ptr dest) noexcept { static_assert (std::is_constructible::value, "`value_type` must be copy constructible."); #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) + if (std::is_constant_evaluated ()) { return default_uninitialized_copy (first, last, dest); + } #endif const size_ty num_copy = external_range_length (first, last); - if (num_copy != 0) + if (num_copy != 0) { std::memcpy (to_address (dest), to_address (first), num_copy * sizeof (value_ty)); + } return unchecked_next (dest, num_copy); } @@ -2324,8 +2265,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface ptr uninitialized_copy (std::move_iterator first, std::move_iterator last, - ptr dest) noexcept - { + ptr dest) noexcept { return uninitialized_copy (first.base (), last.base (), dest); } @@ -2334,26 +2274,23 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface ! is_uninitialized_memcpyable_iterator::value, bool>::type = false> PLUMED_GCH_CPP20_CONSTEXPR ptr - uninitialized_copy (InputIt first, InputIt last, ptr d_first) - { + uninitialized_copy (InputIt first, InputIt last, ptr d_first) { return default_uninitialized_copy (first, last, d_first); } template PLUMED_GCH_CPP20_CONSTEXPR ptr - default_uninitialized_copy (InputIt first, InputIt last, ptr d_first) - { + default_uninitialized_copy (InputIt first, InputIt last, ptr d_first) { ptr d_last = d_first; - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { // Note: Not != because `using namespace std::rel_ops` can break constexpr. - for (; ! (first == last); ++first, static_cast (++d_last)) + for (; ! (first == last); ++first, static_cast (++d_last)) { construct (d_last, *first); + } return d_last; } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (d_first, d_last); PLUMED_GCH_THROW; } @@ -2364,11 +2301,11 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface &&! must_use_alloc_construct::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR ptr - uninitialized_value_construct (ptr first, ptr last) - { + uninitialized_value_construct (ptr first, ptr last) { #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) + if (std::is_constant_evaluated ()) { return default_uninitialized_value_construct (first, last); + } #endif std::fill (first, last, value_ty ()); return last; @@ -2379,24 +2316,21 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface || must_use_alloc_construct::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR ptr - uninitialized_value_construct (ptr first, ptr last) - { + uninitialized_value_construct (ptr first, ptr last) { return default_uninitialized_value_construct (first, last); } PLUMED_GCH_CPP20_CONSTEXPR ptr - default_uninitialized_value_construct (ptr first, ptr last) - { + default_uninitialized_value_construct (ptr first, ptr last) { ptr curr = first; - PLUMED_GCH_TRY - { - for (; ! (curr == last); ++curr) + PLUMED_GCH_TRY { + for (; ! (curr == last); ++curr) { construct (curr); + } return curr; } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (first, curr); PLUMED_GCH_THROW; } @@ -2404,24 +2338,21 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface PLUMED_GCH_CPP20_CONSTEXPR ptr - uninitialized_fill (ptr first, ptr last) - { + uninitialized_fill (ptr first, ptr last) { return uninitialized_value_construct (first, last); } PLUMED_GCH_CPP20_CONSTEXPR ptr - uninitialized_fill (ptr first, ptr last, const value_ty& val) - { + uninitialized_fill (ptr first, ptr last, const value_ty& val) { ptr curr = first; - PLUMED_GCH_TRY - { - for (; ! (curr == last); ++curr) + PLUMED_GCH_TRY { + for (; ! (curr == last); ++curr) { construct (curr, val); + } return curr; } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (first, curr); PLUMED_GCH_THROW; } @@ -2435,18 +2366,17 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface typename std::enable_if::value, bool>::type = true> static PLUMED_GCH_CPP20_CONSTEXPR void - destroy_at (value_ty *p) noexcept - { - for (auto& e : *p) + destroy_at (value_ty *p) noexcept { + for (auto& e : *p) { destroy_at (std::addressof (e)); + } } template ::value, bool>::type = false> static PLUMED_GCH_CPP20_CONSTEXPR void - destroy_at (value_ty *p) noexcept - { + destroy_at (value_ty *p) noexcept { p->~value_ty (); } @@ -2455,11 +2385,11 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface auto construct_at (value_ty *p, Args&&... args) noexcept (noexcept (::new (std::declval ()) V (std::declval ()...))) - -> decltype (::new (std::declval ()) V (std::declval ()...)) - { + -> decltype (::new (std::declval ()) V (std::declval ()...)) { #if defined (PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED) && defined (PLUMED_GCH_LIB_CONSTEXPR_MEMORY) - if (std::is_constant_evaluated ()) + if (std::is_constant_evaluated ()) { return std::construct_at (p, std::forward (args)...); + } #endif void *vp = const_cast (static_cast (p)); return ::new (vp) value_ty (std::forward(args)...); @@ -2467,8 +2397,7 @@ class PLUMED_GCH_EMPTY_BASE allocator_interface }; template -class small_vector_data_base -{ +class small_vector_data_base { public: using ptr = Pointer; using size_ty = SizeT; @@ -2480,18 +2409,29 @@ class small_vector_data_base small_vector_data_base& operator= (small_vector_data_base&&) noexcept = default; ~small_vector_data_base (void) = default; - constexpr ptr data_ptr (void) const noexcept { return m_data_ptr; } - constexpr size_ty capacity (void) const noexcept { return m_capacity; } - constexpr size_ty size (void) const noexcept { return m_size; } + constexpr ptr data_ptr (void) const noexcept { + return m_data_ptr; + } + constexpr size_ty capacity (void) const noexcept { + return m_capacity; + } + constexpr size_ty size (void) const noexcept { + return m_size; + } - PLUMED_GCH_CPP20_CONSTEXPR void set_data_ptr (ptr data_ptr) noexcept { m_data_ptr = data_ptr; } - PLUMED_GCH_CPP20_CONSTEXPR void set_capacity (size_ty capacity) noexcept { m_capacity = capacity; } - PLUMED_GCH_CPP20_CONSTEXPR void set_size (size_ty size) noexcept { m_size = size; } + PLUMED_GCH_CPP20_CONSTEXPR void set_data_ptr (ptr data_ptr) noexcept { + m_data_ptr = data_ptr; + } + PLUMED_GCH_CPP20_CONSTEXPR void set_capacity (size_ty capacity) noexcept { + m_capacity = capacity; + } + PLUMED_GCH_CPP20_CONSTEXPR void set_size (size_ty size) noexcept { + m_size = size; + } PLUMED_GCH_CPP20_CONSTEXPR void - set (ptr data_ptr, size_ty capacity, size_ty size) - { + set (ptr data_ptr, size_ty capacity, size_ty size) { m_data_ptr = data_ptr; m_capacity = capacity; m_size = size; @@ -2499,32 +2439,28 @@ class small_vector_data_base PLUMED_GCH_CPP20_CONSTEXPR void - swap_data_ptr (small_vector_data_base& other) noexcept - { + swap_data_ptr (small_vector_data_base& other) noexcept { using std::swap; swap (m_data_ptr, other.m_data_ptr); } PLUMED_GCH_CPP20_CONSTEXPR void - swap_capacity (small_vector_data_base& other) noexcept - { + swap_capacity (small_vector_data_base& other) noexcept { using std::swap; swap (m_capacity, other.m_capacity); } PLUMED_GCH_CPP20_CONSTEXPR void - swap_size (small_vector_data_base& other) noexcept - { + swap_size (small_vector_data_base& other) noexcept { using std::swap; swap (m_size, other.m_size); } PLUMED_GCH_CPP20_CONSTEXPR void - swap (small_vector_data_base& other) noexcept - { + swap (small_vector_data_base& other) noexcept { using std::swap; swap (m_data_ptr, other.m_data_ptr); swap (m_capacity, other.m_capacity); @@ -2539,8 +2475,7 @@ class small_vector_data_base template class small_vector_data -: public small_vector_data_base -{ +: public small_vector_data_base { public: using value_ty = T; @@ -2553,15 +2488,13 @@ class small_vector_data PLUMED_GCH_CPP14_CONSTEXPR value_ty * - storage (void) noexcept - { + storage (void) noexcept { return m_storage.get_inline_ptr (); } constexpr const value_ty * - storage (void) const noexcept - { + storage (void) const noexcept { return m_storage.get_inline_ptr (); } @@ -2572,8 +2505,7 @@ class small_vector_data template class PLUMED_GCH_EMPTY_BASE small_vector_data : public small_vector_data_base, -private inline_storage -{ +private inline_storage { using base = inline_storage; public: @@ -2588,23 +2520,20 @@ private inline_storage PLUMED_GCH_CPP14_CONSTEXPR value_ty * - storage (void) noexcept - { + storage (void) noexcept { return base::get_inline_ptr (); } constexpr const value_ty * - storage (void) const noexcept - { + storage (void) const noexcept { return base::get_inline_ptr (); } }; template class small_vector_base -: public allocator_interface -{ +: public allocator_interface { public: using size_type = typename allocator_interface::size_type; using difference_type = typename allocator_interface::difference_type; @@ -2650,16 +2579,14 @@ class small_vector_base PLUMED_GCH_NODISCARD static PLUMED_GCH_CONSTEVAL std::size_t - numeric_max (void) noexcept - { + numeric_max (void) noexcept { return alloc_interface::template numeric_max (); } PLUMED_GCH_NODISCARD static PLUMED_GCH_CONSTEVAL size_ty - get_inline_capacity (void) noexcept - { + get_inline_capacity (void) noexcept { return static_cast (InlineCapacity); } @@ -2671,8 +2598,7 @@ class small_vector_base template struct is_emplace_constructible_impl -: std::false_type - { +: std::false_type { using nothrow = std::false_type; }; @@ -2682,8 +2608,7 @@ class small_vector_base decltype (std::declval ().construct (std::declval (), std::declval ()...))>, AI, V, Args...> -: std::true_type - { +: std::true_type { using nothrow = bool_constant ().construct (std::declval (), std::declval ()...))>; @@ -2691,46 +2616,46 @@ class small_vector_base template struct is_emplace_constructible -: is_emplace_constructible_impl - { }; +: is_emplace_constructible_impl { + }; template struct is_nothrow_emplace_constructible -: is_emplace_constructible_impl::nothrow - { }; +: is_emplace_constructible_impl::nothrow { + }; template struct is_explicitly_move_insertable -: is_emplace_constructible - { }; +: is_emplace_constructible { + }; template struct is_explicitly_nothrow_move_insertable -: is_nothrow_emplace_constructible - { }; +: is_nothrow_emplace_constructible { + }; template struct is_explicitly_copy_insertable : std::integral_constant::value - && is_emplace_constructible::value> - { }; + && is_emplace_constructible::value> { + }; template struct is_explicitly_nothrow_copy_insertable : std::integral_constant::value - && is_nothrow_emplace_constructible::value> - { }; + && is_nothrow_emplace_constructible::value> { + }; template struct is_eraseable -: std::false_type - { }; +: std::false_type { + }; template struct is_eraseable ().destroy (std::declval ()))>> -: std::true_type - { }; +: std::true_type { + }; template struct relocate_with_move @@ -2749,8 +2674,8 @@ class small_vector_base #ifdef PLUMED_GCH_LIB_IS_ALWAYS_EQUAL || std::allocator_traits::is_always_equal::value #endif - > - { }; + > { + }; template struct allocations_are_swappable @@ -2759,8 +2684,8 @@ class small_vector_base #ifdef PLUMED_GCH_LIB_IS_ALWAYS_EQUAL || std::allocator_traits::is_always_equal::value #endif - > - { }; + > { + }; template using is_memcpyable = typename alloc_interface::template is_memcpyable; @@ -2772,8 +2697,7 @@ class small_vector_base PLUMED_GCH_NORETURN static PLUMED_GCH_CPP20_CONSTEXPR void - throw_overflow_error (void) - { + throw_overflow_error (void) { #ifdef PLUMED_GCH_EXCEPTIONS throw std::overflow_error ("The requested conversion would overflow."); #else @@ -2785,8 +2709,7 @@ class small_vector_base PLUMED_GCH_NORETURN static PLUMED_GCH_CPP20_CONSTEXPR void - throw_index_error (void) - { + throw_index_error (void) { #ifdef PLUMED_GCH_EXCEPTIONS throw std::out_of_range ("The requested index was out of range."); #else @@ -2798,8 +2721,7 @@ class small_vector_base PLUMED_GCH_NORETURN static PLUMED_GCH_CPP20_CONSTEXPR void - throw_increment_error (void) - { + throw_increment_error (void) { #ifdef PLUMED_GCH_EXCEPTIONS throw std::domain_error ("The requested increment was outside of the allowed range."); #else @@ -2813,8 +2735,7 @@ class small_vector_base PLUMED_GCH_NORETURN static PLUMED_GCH_CPP20_CONSTEXPR void - throw_allocation_size_error (void) - { + throw_allocation_size_error (void) { #ifdef PLUMED_GCH_EXCEPTIONS throw std::length_error ("The required allocation exceeds the maximum size."); #else @@ -2827,14 +2748,12 @@ class small_vector_base PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR ptr - ptr_cast (const small_vector_iterator& it) noexcept - { + ptr_cast (const small_vector_iterator& it) noexcept { return unchecked_next (begin_ptr (), it.base () - begin_ptr ()); } private: - class stack_temporary - { + class stack_temporary { public: stack_temporary (void) = delete; stack_temporary (const stack_temporary&) = delete; @@ -2846,43 +2765,37 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR explicit stack_temporary (alloc_interface& alloc_iface, Args&&... args) - : m_interface (alloc_iface) - { + : m_interface (alloc_iface) { m_interface.construct (get_pointer (), std::forward (args)...); } PLUMED_GCH_CPP20_CONSTEXPR - ~stack_temporary (void) - { + ~stack_temporary (void) { m_interface.destroy (get_pointer ()); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP20_CONSTEXPR const value_ty& - get (void) const noexcept - { + get (void) const noexcept { return *get_pointer (); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP20_CONSTEXPR value_ty&& - release (void) noexcept - { + release (void) noexcept { return std::move (*get_pointer ()); } private: PLUMED_GCH_NODISCARD PLUMED_GCH_CPP20_CONSTEXPR cptr - get_pointer (void) const noexcept - { + get_pointer (void) const noexcept { return static_cast (static_cast (std::addressof (m_data))); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP20_CONSTEXPR ptr - get_pointer (void) noexcept - { + get_pointer (void) noexcept { return static_cast (static_cast (std::addressof (m_data))); } @@ -2892,8 +2805,7 @@ class small_vector_base #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - class heap_temporary - { + class heap_temporary { public: heap_temporary (void) = delete; heap_temporary (const heap_temporary&) = delete; @@ -2906,37 +2818,31 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR explicit heap_temporary (alloc_interface& alloc_iface, Args&&... args) : m_interface (alloc_iface), - m_data_ptr (alloc_iface.allocate (sizeof (value_ty))) - { - PLUMED_GCH_TRY - { + m_data_ptr (alloc_iface.allocate (sizeof (value_ty))) { + PLUMED_GCH_TRY { m_interface.construct (m_data_ptr, std::forward (args)...); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { m_interface.deallocate (m_data_ptr, sizeof (value_ty)); PLUMED_GCH_THROW; } } PLUMED_GCH_CPP20_CONSTEXPR - ~heap_temporary (void) - { + ~heap_temporary (void) { m_interface.destroy (m_data_ptr); m_interface.deallocate (m_data_ptr, sizeof (value_ty)); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP20_CONSTEXPR const value_ty& - get (void) const noexcept - { + get (void) const noexcept { return *m_data_ptr; } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP20_CONSTEXPR value_ty&& - release (void) noexcept - { + release (void) noexcept { return std::move (*m_data_ptr); } @@ -2949,182 +2855,161 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR void - wipe (void) - { + wipe (void) { destroy_range (begin_ptr (), end_ptr ()); - if (has_allocation ()) + if (has_allocation ()) { deallocate (data_ptr (), get_capacity ()); + } } PLUMED_GCH_CPP20_CONSTEXPR void - set_data_ptr (ptr data_ptr) noexcept - { + set_data_ptr (ptr data_ptr) noexcept { m_data.set_data_ptr (data_ptr); } PLUMED_GCH_CPP20_CONSTEXPR void - set_capacity (size_ty capacity) noexcept - { + set_capacity (size_ty capacity) noexcept { m_data.set_capacity (static_cast (capacity)); } PLUMED_GCH_CPP20_CONSTEXPR void - set_size (size_ty size) noexcept - { + set_size (size_ty size) noexcept { m_data.set_size (static_cast (size)); } PLUMED_GCH_CPP20_CONSTEXPR void - set_data (ptr data_ptr, size_ty capacity, size_ty size) noexcept - { + set_data (ptr data_ptr, size_ty capacity, size_ty size) noexcept { m_data.set (data_ptr, static_cast (capacity), static_cast (size)); } PLUMED_GCH_CPP20_CONSTEXPR void - swap_data_ptr (small_vector_base& other) noexcept - { + swap_data_ptr (small_vector_base& other) noexcept { m_data.swap_data_ptr (other.m_data); } PLUMED_GCH_CPP20_CONSTEXPR void - swap_capacity (small_vector_base& other) noexcept - { + swap_capacity (small_vector_base& other) noexcept { m_data.swap_capacity (other.m_data); } PLUMED_GCH_CPP20_CONSTEXPR void - swap_size (small_vector_base& other) noexcept - { + swap_size (small_vector_base& other) noexcept { m_data.swap_size (other.m_data); } PLUMED_GCH_CPP20_CONSTEXPR void - swap_allocation (small_vector_base& other) noexcept - { + swap_allocation (small_vector_base& other) noexcept { m_data.swap (other.m_data); } PLUMED_GCH_CPP20_CONSTEXPR void - reset_data (ptr data_ptr, size_ty capacity, size_ty size) - { + reset_data (ptr data_ptr, size_ty capacity, size_ty size) { wipe (); m_data.set (data_ptr, static_cast (capacity), static_cast (size)); } PLUMED_GCH_CPP20_CONSTEXPR void - increase_size (size_ty n) noexcept - { + increase_size (size_ty n) noexcept { m_data.set_size (get_size () + n); } PLUMED_GCH_CPP20_CONSTEXPR void - decrease_size (size_ty n) noexcept - { + decrease_size (size_ty n) noexcept { m_data.set_size (get_size () - n); } PLUMED_GCH_CPP20_CONSTEXPR ptr - unchecked_allocate (size_ty n) - { + unchecked_allocate (size_ty n) { assert (InlineCapacity < n && "Allocated capacity should be greater than InlineCapacity."); return alloc_interface::allocate (n); } PLUMED_GCH_CPP20_CONSTEXPR ptr - unchecked_allocate (size_ty n, cptr hint) - { + unchecked_allocate (size_ty n, cptr hint) { assert (InlineCapacity < n && "Allocated capacity should be greater than InlineCapacity."); return alloc_interface::allocate_with_hint (n, hint); } PLUMED_GCH_CPP20_CONSTEXPR ptr - checked_allocate (size_ty n) - { - if (get_max_size () < n) + checked_allocate (size_ty n) { + if (get_max_size () < n) { throw_allocation_size_error (); + } return unchecked_allocate (n); } protected: PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR size_ty - unchecked_calculate_new_capacity (const size_ty minimum_required_capacity) const noexcept - { + unchecked_calculate_new_capacity (const size_ty minimum_required_capacity) const noexcept { const size_ty current_capacity = get_capacity (); assert (current_capacity < minimum_required_capacity); - if (get_max_size () - current_capacity <= current_capacity) + if (get_max_size () - current_capacity <= current_capacity) { return get_max_size (); + } // Note: This growth factor might be theoretically superior, but in testing it falls flat: // size_ty new_capacity = current_capacity + (current_capacity / 2); const size_ty new_capacity = 2 * current_capacity; - if (new_capacity < minimum_required_capacity) + if (new_capacity < minimum_required_capacity) { return minimum_required_capacity; + } return new_capacity; } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR size_ty - checked_calculate_new_capacity (const size_ty minimum_required_capacity) const - { - if (get_max_size () < minimum_required_capacity) + checked_calculate_new_capacity (const size_ty minimum_required_capacity) const { + if (get_max_size () < minimum_required_capacity) { throw_allocation_size_error (); + } return unchecked_calculate_new_capacity (minimum_required_capacity); } template PLUMED_GCH_CPP20_CONSTEXPR small_vector_base& - copy_assign_default (const small_vector_base& other) - { - if (get_capacity () < other.get_size ()) - { + copy_assign_default (const small_vector_base& other) { + if (get_capacity () < other.get_size ()) { // Reallocate. size_ty new_capacity = unchecked_calculate_new_capacity (other.get_size ()); ptr new_data_ptr = unchecked_allocate (new_capacity, other.allocation_end_ptr ()); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_copy (other.begin_ptr (), other.end_ptr (), new_data_ptr); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; } reset_data (new_data_ptr, new_capacity, other.get_size ()); - } - else - { - if (get_size () < other.get_size ()) - { + } else { + if (get_size () < other.get_size ()) { // No reallocation, partially in uninitialized space. std::copy_n (other.begin_ptr (), get_size (), begin_ptr ()); uninitialized_copy ( unchecked_next (other.begin_ptr (), get_size ()), other.end_ptr (), end_ptr ()); - } - else - { + } else { destroy_range (copy_range (other.begin_ptr (), other.end_ptr (), begin_ptr ()), end_ptr ()); } @@ -3145,13 +3030,12 @@ class small_vector_base >::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR small_vector_base& - copy_assign (const small_vector_base& other) - { - if (other.allocator_ref () == allocator_ref ()) + copy_assign (const small_vector_base& other) { + if (other.allocator_ref () == allocator_ref ()) { return copy_assign_default (other); + } - if (InlineCapacity < other.get_size ()) - { + if (InlineCapacity < other.get_size ()) { alloc_interface new_alloc (other); const size_ty new_capacity = other.get_size (); @@ -3159,32 +3043,26 @@ class small_vector_base new_capacity, other.allocation_end_ptr ()); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_copy (other.begin_ptr (), other.end_ptr (), new_data_ptr); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { new_alloc.deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; } reset_data (new_data_ptr, new_capacity, other.get_size ()); alloc_interface::operator= (new_alloc); - } - else - { - if (has_allocation ()) - { + } else { + if (has_allocation ()) { #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED ptr new_data_ptr; - if (std::is_constant_evaluated ()) - { + if (std::is_constant_evaluated ()) { alloc_interface new_alloc (other); new_data_ptr = new_alloc.allocate (InlineCapacity); - } - else + } else { new_data_ptr = storage_ptr (); + } #else const ptr new_data_ptr = storage_ptr (); #endif @@ -3194,17 +3072,13 @@ class small_vector_base deallocate (data_ptr (), get_capacity ()); set_data_ptr (new_data_ptr); set_capacity (InlineCapacity); - } - else if (get_size () < other.get_size ()) - { + } else if (get_size () < other.get_size ()) { std::copy_n (other.begin_ptr (), get_size (), begin_ptr ()); uninitialized_copy ( unchecked_next (other.begin_ptr (), get_size ()), other.end_ptr (), end_ptr ()); - } - else - { + } else { destroy_range (copy_range (other.begin_ptr (), other.end_ptr (), begin_ptr ()), end_ptr ()); } @@ -3223,16 +3097,14 @@ class small_vector_base >::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR small_vector_base& - copy_assign (const small_vector_base& other) - { + copy_assign (const small_vector_base& other) { return copy_assign_default (other); } template PLUMED_GCH_CPP20_CONSTEXPR void - move_allocation_pointer (small_vector_base&& other) noexcept - { + move_allocation_pointer (small_vector_base&& other) noexcept { reset_data (other.data_ptr (), other.get_capacity (), other.get_size ()); other.set_default (); } @@ -3240,8 +3112,7 @@ class small_vector_base template ::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR small_vector_base& - move_assign_default (small_vector_base&& other) noexcept - { + move_assign_default (small_vector_base&& other) noexcept { move_allocation_pointer (std::move (other)); alloc_interface::operator= (std::move (other)); return *this; @@ -3253,24 +3124,22 @@ class small_vector_base small_vector_base& move_assign_default (small_vector_base&& other) noexcept (std::is_nothrow_move_assignable::value - && std::is_nothrow_move_constructible::value) - { + && std::is_nothrow_move_constructible::value) { // We only move the allocation pointer over if it has strictly greater capacity than // the inline capacity of `*this` because allocations can never have a smaller capacity // than the inline capacity. - if (InlineCapacity < other.get_capacity ()) - move_allocation_pointer (std::move (other)); - else - { + if (InlineCapacity < other.get_capacity ()) { + move_allocation_pointer (std::move (other)); + } else { // We are guaranteed to have sufficient capacity to store the elements. - if (InlineCapacity < get_capacity ()) - { + if (InlineCapacity < get_capacity ()) { #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED ptr new_data_ptr; - if (std::is_constant_evaluated ()) + if (std::is_constant_evaluated ()) { new_data_ptr = other.allocate (InlineCapacity); - else + } else { new_data_ptr = storage_ptr (); + } #else const ptr new_data_ptr = storage_ptr (); #endif @@ -3280,17 +3149,13 @@ class small_vector_base deallocate (data_ptr (), get_capacity ()); set_data_ptr (new_data_ptr); set_capacity (InlineCapacity); - } - else if (get_size () < other.get_size ()) - { + } else if (get_size () < other.get_size ()) { // There are more elements in `other`. // Overwrite the existing range and uninitialized move the rest. ptr other_pivot = unchecked_next (other.begin_ptr (), get_size ()); std::move (other.begin_ptr (), other_pivot, begin_ptr ()); uninitialized_move (other_pivot, other.end_ptr (), end_ptr ()); - } - else - { + } else { // There are the same number or fewer elements in `other`. // Overwrite part of the existing range and destroy the rest. ptr new_end = std::move (other.begin_ptr (), other.end_ptr (), begin_ptr ()); @@ -3312,13 +3177,11 @@ class small_vector_base typename std::enable_if<(InlineCapacity < GreaterI)>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR small_vector_base& - move_assign_default (small_vector_base&& other) - { - if (other.has_allocation ()) + move_assign_default (small_vector_base&& other) { + if (other.has_allocation ()) { move_allocation_pointer (std::move (other)); - else if (get_capacity () < other.get_size () - || (has_allocation () && ! (other.allocator_ref () == allocator_ref ()))) - { + } else if (get_capacity () < other.get_size () + || (has_allocation () && ! (other.allocator_ref () == allocator_ref ()))) { // Reallocate. // The compiler should be able to optimize this. @@ -3329,30 +3192,23 @@ class small_vector_base ptr new_data_ptr = other.allocate_with_hint (new_capacity, other.allocation_end_ptr ()); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_move (other.begin_ptr (), other.end_ptr (), new_data_ptr); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { other.deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; } reset_data (new_data_ptr, new_capacity, other.get_size ()); - } - else - { - if (get_size () < other.get_size ()) - { + } else { + if (get_size () < other.get_size ()) { // There are more elements in `other`. // Overwrite the existing range and uninitialized move the rest. ptr other_pivot = unchecked_next (other.begin_ptr (), get_size ()); std::move (other.begin_ptr (), other_pivot, begin_ptr ()); uninitialized_move (other_pivot, other.end_ptr (), end_ptr ()); - } - else - { + } else { // fewer elements in other // overwrite part of the existing range and destroy the rest ptr new_end = std::move (other.begin_ptr (), other.end_ptr (), begin_ptr ()); @@ -3370,38 +3226,29 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR small_vector_base& - move_assign_unequal_no_propagate (small_vector_base&& other) - { - if (get_capacity () < other.get_size ()) - { + move_assign_unequal_no_propagate (small_vector_base&& other) { + if (get_capacity () < other.get_size ()) { // Reallocate. size_ty new_capacity = unchecked_calculate_new_capacity (other.get_size ()); ptr new_data_ptr = unchecked_allocate (new_capacity, other.allocation_end_ptr ()); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_move (other.begin_ptr (), other.end_ptr (), new_data_ptr); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; } reset_data (new_data_ptr, new_capacity, other.get_size ()); - } - else - { - if (get_size () < other.get_size ()) - { + } else { + if (get_size () < other.get_size ()) { // There are more elements in `other`. // Overwrite the existing range and uninitialized move the rest. ptr other_pivot = unchecked_next (other.begin_ptr (), get_size ()); std::move (other.begin_ptr (), other_pivot, begin_ptr ()); uninitialized_move (other_pivot, other.end_ptr (), end_ptr ()); - } - else - { + } else { // There are fewer elements in `other`. // Overwrite part of the existing range and destroy the rest. destroy_range ( @@ -3423,8 +3270,7 @@ class small_vector_base small_vector_base& move_assign (small_vector_base&& other) noexcept (noexcept ( - std::declval ().move_assign_default (std::move (other)))) - { + std::declval ().move_assign_default (std::move (other)))) { return move_assign_default (std::move (other)); } @@ -3432,10 +3278,10 @@ class small_vector_base typename std::enable_if::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR small_vector_base& - move_assign (small_vector_base&& other) - { - if (other.allocator_ref () == allocator_ref ()) + move_assign (small_vector_base&& other) { + if (other.allocator_ref () == allocator_ref ()) { return move_assign_default (std::move (other)); + } return move_assign_unequal_no_propagate (std::move (other)); } @@ -3443,8 +3289,7 @@ class small_vector_base typename std::enable_if::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - move_initialize (small_vector_base&& other) noexcept - { + move_initialize (small_vector_base&& other) noexcept { set_data (other.data_ptr (), other.get_capacity (), other.get_size ()); other.set_default (); } @@ -3454,15 +3299,11 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR void move_initialize (small_vector_base&& other) - noexcept (std::is_nothrow_move_constructible::value) - { - if (InlineCapacity < other.get_capacity ()) - { + noexcept (std::is_nothrow_move_constructible::value) { + if (InlineCapacity < other.get_capacity ()) { set_data (other.data_ptr (), other.get_capacity (), other.get_size ()); other.set_default (); - } - else - { + } else { set_to_inline_storage (); uninitialized_move (other.begin_ptr (), other.end_ptr (), data_ptr ()); set_size (other.get_size ()); @@ -3473,33 +3314,24 @@ class small_vector_base typename std::enable_if<(InlineCapacity < GreaterI)>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - move_initialize (small_vector_base&& other) - { - if (other.has_allocation ()) - { + move_initialize (small_vector_base&& other) { + if (other.has_allocation ()) { set_data (other.data_ptr (), other.get_capacity (), other.get_size ()); other.set_default (); - } - else - { - if (InlineCapacity < other.get_size ()) - { + } else { + if (InlineCapacity < other.get_size ()) { // We may throw in this case. set_data_ptr (unchecked_allocate (other.get_size (), other.allocation_end_ptr ())); set_capacity (other.get_size ()); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_move (other.begin_ptr (), other.end_ptr (), data_ptr ()); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (data_ptr (), get_capacity ()); PLUMED_GCH_THROW; } - } - else - { + } else { set_to_inline_storage (); uninitialized_move (other.begin_ptr (), other.end_ptr (), data_ptr ()); } @@ -3517,8 +3349,7 @@ class small_vector_base // ~small_vector_base (void) = impl; PLUMED_GCH_CPP20_CONSTEXPR - small_vector_base (void) noexcept - { + small_vector_base (void) noexcept { set_default (); } @@ -3529,25 +3360,19 @@ class small_vector_base small_vector_base (bypass_tag, const small_vector_base& other, const MaybeAlloc&... alloc) - : alloc_interface (other, alloc...) - { - if (InlineCapacity < other.get_size ()) - { + : alloc_interface (other, alloc...) { + if (InlineCapacity < other.get_size ()) { set_data_ptr (unchecked_allocate (other.get_size (), other.allocation_end_ptr ())); set_capacity (other.get_size ()); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_copy (other.begin_ptr (), other.end_ptr (), data_ptr ()); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (data_ptr (), get_capacity ()); PLUMED_GCH_THROW; } - } - else - { + } else { set_to_inline_storage (); uninitialized_copy (other.begin_ptr (), other.end_ptr (), data_ptr ()); } @@ -3560,8 +3385,7 @@ class small_vector_base small_vector_base (bypass_tag, small_vector_base&& other) noexcept (std::is_nothrow_move_constructible::value || (I == 0 && I == InlineCapacity)) - : alloc_interface (std::move (other)) - { + : alloc_interface (std::move (other)) { move_initialize (std::move (other)); } @@ -3585,32 +3409,25 @@ class small_vector_base )>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR small_vector_base (bypass_tag, small_vector_base&& other, const alloc_ty& alloc) - : alloc_interface (alloc) - { - if (other.allocator_ref () == alloc) - { + : alloc_interface (alloc) { + if (other.allocator_ref () == alloc) { move_initialize (std::move (other)); return; } - if (InlineCapacity < other.get_size ()) - { + if (InlineCapacity < other.get_size ()) { // We may throw in this case. set_data_ptr (unchecked_allocate (other.get_size (), other.allocation_end_ptr ())); set_capacity (other.get_size ()); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_move (other.begin_ptr (), other.end_ptr (), data_ptr ()); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (data_ptr (), get_capacity ()); PLUMED_GCH_THROW; } - } - else - { + } else { set_to_inline_storage (); uninitialized_move (other.begin_ptr (), other.end_ptr (), data_ptr ()); } @@ -3620,31 +3437,27 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR explicit small_vector_base (const alloc_ty& alloc) noexcept - : alloc_interface (alloc) - { + : alloc_interface (alloc) { set_default (); } PLUMED_GCH_CPP20_CONSTEXPR small_vector_base (size_ty count, const alloc_ty& alloc) - : alloc_interface (alloc) - { - if (InlineCapacity < count) - { + : alloc_interface (alloc) { + if (InlineCapacity < count) { set_data_ptr (checked_allocate (count)); set_capacity (count); - } - else + } else { set_to_inline_storage (); + } - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_value_construct (begin_ptr (), unchecked_next (begin_ptr (), count)); } - PLUMED_GCH_CATCH (...) - { - if (has_allocation ()) + PLUMED_GCH_CATCH (...) { + if (has_allocation ()) { deallocate (data_ptr (), get_capacity ()); + } PLUMED_GCH_THROW; } set_size (count); @@ -3652,24 +3465,21 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR small_vector_base (size_ty count, const value_ty& val, const alloc_ty& alloc) - : alloc_interface (alloc) - { - if (InlineCapacity < count) - { + : alloc_interface (alloc) { + if (InlineCapacity < count) { set_data_ptr (checked_allocate (count)); set_capacity (count); - } - else + } else { set_to_inline_storage (); + } - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_fill (begin_ptr (), unchecked_next (begin_ptr (), count), val); } - PLUMED_GCH_CATCH (...) - { - if (has_allocation ()) + PLUMED_GCH_CATCH (...) { + if (has_allocation ()) { deallocate (data_ptr (), get_capacity ()); + } PLUMED_GCH_THROW; } set_size (count); @@ -3678,28 +3488,26 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR small_vector_base (size_ty count, Generator& g, const alloc_ty& alloc) - : alloc_interface (alloc) - { - if (InlineCapacity < count) - { + : alloc_interface (alloc) { + if (InlineCapacity < count) { set_data_ptr (checked_allocate (count)); set_capacity (count); - } - else + } else { set_to_inline_storage (); + } ptr curr = begin_ptr (); const ptr new_end = unchecked_next (begin_ptr (), count); - PLUMED_GCH_TRY - { - for (; ! (curr == new_end); ++curr) + PLUMED_GCH_TRY { + for (; ! (curr == new_end); ++curr) { construct (curr, g ()); + } } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (begin_ptr (), curr); - if (has_allocation ()) + if (has_allocation ()) { deallocate (data_ptr (), get_capacity ()); + } PLUMED_GCH_THROW; } set_size (count); @@ -3713,8 +3521,7 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR small_vector_base (InputIt first, InputIt last, std::input_iterator_tag, const alloc_ty& alloc) - : small_vector_base (alloc) - { + : small_vector_base (alloc) { using iterator_cat = typename std::iterator_traits::iterator_category; append_range (first, last, iterator_cat { }); } @@ -3727,25 +3534,19 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR small_vector_base (ForwardIt first, ForwardIt last, std::forward_iterator_tag, const alloc_ty& alloc) - : alloc_interface (alloc) - { + : alloc_interface (alloc) { size_ty count = external_range_length (first, last); - if (InlineCapacity < count) - { + if (InlineCapacity < count) { set_data_ptr (unchecked_allocate (count)); set_capacity (count); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_copy (first, last, begin_ptr ()); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (data_ptr (), get_capacity ()); PLUMED_GCH_THROW; } - } - else - { + } else { set_to_inline_storage (); uninitialized_copy (first, last, begin_ptr ()); } @@ -3754,8 +3555,7 @@ class small_vector_base } PLUMED_GCH_CPP20_CONSTEXPR - ~small_vector_base (void) noexcept - { + ~small_vector_base (void) noexcept { assert (InlineCapacity <= get_capacity () && "Invalid capacity."); wipe (); } @@ -3764,45 +3564,39 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR void - set_to_inline_storage (void) - { + set_to_inline_storage (void) { set_capacity (InlineCapacity); #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) + if (std::is_constant_evaluated ()) { return set_data_ptr (alloc_interface::allocate (InlineCapacity)); + } #endif set_data_ptr (storage_ptr ()); } PLUMED_GCH_CPP20_CONSTEXPR void - assign_with_copies (size_ty count, const value_ty& val) - { - if (get_capacity () < count) - { + assign_with_copies (size_ty count, const value_ty& val) { + if (get_capacity () < count) { size_ty new_capacity = checked_calculate_new_capacity (count); ptr new_begin = unchecked_allocate (new_capacity); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_fill (new_begin, unchecked_next (new_begin, count), val); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (new_begin, new_capacity); PLUMED_GCH_THROW; } reset_data (new_begin, new_capacity, count); - } - else if (get_size () < count) - { + } else if (get_size () < count) { std::fill (begin_ptr (), end_ptr (), val); uninitialized_fill (end_ptr (), unchecked_next (begin_ptr (), count), val); set_size (count); - } - else + } else { erase_range (std::fill_n (begin_ptr (), count, val), end_ptr ()); + } } template ())>::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - assign_with_range (InputIt first, InputIt last, std::input_iterator_tag) - { + assign_with_range (InputIt first, InputIt last, std::input_iterator_tag) { using iterator_cat = typename std::iterator_traits::iterator_category; ptr curr = begin_ptr (); - for (; ! (end_ptr () == curr || first == last); ++curr, static_cast (++first)) + for (; ! (end_ptr () == curr || first == last); ++curr, static_cast (++first)) { *curr = *first; + } - if (first == last) + if (first == last) { erase_to_end (curr); - else + } else append_range (first, last, iterator_cat { }); } @@ -3831,34 +3625,28 @@ class small_vector_base decltype (*std::declval ())>::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - assign_with_range (ForwardIt first, ForwardIt last, std::forward_iterator_tag) - { + assign_with_range (ForwardIt first, ForwardIt last, std::forward_iterator_tag) { const size_ty count = external_range_length (first, last); - if (get_capacity () < count) - { + if (get_capacity () < count) { size_ty new_capacity = checked_calculate_new_capacity (count); ptr new_begin = unchecked_allocate (new_capacity); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_copy (first, last, new_begin); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (new_begin, new_capacity); PLUMED_GCH_THROW; } reset_data (new_begin, new_capacity, count); - } - else if (get_size () < count) - { + } else if (get_size () < count) { ForwardIt pivot = copy_n_return_in (first, get_size (), begin_ptr ()); uninitialized_copy (pivot, last, end_ptr ()); set_size (count); - } - else + } else { erase_range (copy_range (first, last, begin_ptr ()), end_ptr ()); + } } template ())>::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - assign_with_range (InputIt first, InputIt last, std::input_iterator_tag) - { + assign_with_range (InputIt first, InputIt last, std::input_iterator_tag) { using iterator_cat = typename std::iterator_traits::iterator_category; // If not assignable then destroy all elements and append. @@ -3877,8 +3664,8 @@ class small_vector_base } // Ie. move-if-noexcept. - struct strong_exception_policy - { }; + struct strong_exception_policy { + }; template ::value @@ -3888,8 +3675,7 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR ptr uninitialized_move (ptr first, ptr last, ptr d_first) - noexcept (std::is_nothrow_move_constructible::value) - { + noexcept (std::is_nothrow_move_constructible::value) { return uninitialized_copy (std::make_move_iterator (first), std::make_move_iterator (last), d_first); @@ -3903,15 +3689,13 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR ptr uninitialized_move (ptr first, ptr last, ptr d_first) - noexcept (alloc_interface::template is_uninitialized_memcpyable_iterator::value) - { + noexcept (alloc_interface::template is_uninitialized_memcpyable_iterator::value) { return uninitialized_copy (first, last, d_first); } PLUMED_GCH_CPP20_CONSTEXPR ptr - shift_into_uninitialized (ptr pos, size_ty n_shift) - { + shift_into_uninitialized (ptr pos, size_ty n_shift) { // Shift elements over to the right into uninitialized space. // Returns the start of the shifted range. // Precondition: shift < end_ptr () - pos @@ -3928,22 +3712,21 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - append_element (Args&&... args) - { - if (get_size () < get_capacity ()) - return emplace_into_current_end (std::forward (args)...); + append_element (Args&&... args) { + if (get_size () < get_capacity ()) { + return emplace_into_current_end (std::forward (args)...); + } return emplace_into_reallocation_end (std::forward (args)...); } PLUMED_GCH_CPP20_CONSTEXPR ptr - append_copies (size_ty count, const value_ty& val) - { - if (num_uninitialized () < count) - { + append_copies (size_ty count, const value_ty& val) { + if (num_uninitialized () < count) { // Reallocate. - if (get_max_size () - get_size () < count) + if (get_max_size () - get_size () < count) { throw_allocation_size_error (); + } size_ty original_size = get_size (); size_ty new_size = get_size () + count; @@ -3953,13 +3736,11 @@ class small_vector_base ptr new_data_ptr = unchecked_allocate (new_capacity, allocation_end_ptr ()); ptr new_last = unchecked_next (new_data_ptr, original_size); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { new_last = uninitialized_fill (new_last, unchecked_next (new_last, count), val); uninitialized_move (begin_ptr (), end_ptr (), new_data_ptr); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (unchecked_next (new_data_ptr, original_size), new_last); deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; @@ -3967,9 +3748,7 @@ class small_vector_base reset_data (new_data_ptr, new_capacity, new_size); return unchecked_next (new_data_ptr, original_size); - } - else - { + } else { const ptr ret = end_ptr (); uninitialized_fill (ret, unchecked_next (ret, count), val); increase_size (count); @@ -3982,18 +3761,14 @@ class small_vector_base std::is_same::value, bool>::type = true> PLUMED_GCH_CPP20_CONSTEXPR ptr - append_range (InputIt first, InputIt last, std::input_iterator_tag) - { + append_range (InputIt first, InputIt last, std::input_iterator_tag) { // Append with a strong exception guarantee. size_ty original_size = get_size (); - for (; ! (first == last); ++first) - { - PLUMED_GCH_TRY - { + for (; ! (first == last); ++first) { + PLUMED_GCH_TRY { append_element (*first); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { erase_range (unchecked_next (begin_ptr (), original_size), end_ptr ()); PLUMED_GCH_THROW; } @@ -4006,26 +3781,25 @@ class small_vector_base ! std::is_same::value, bool>::type = false> PLUMED_GCH_CPP20_CONSTEXPR ptr - append_range (InputIt first, InputIt last, std::input_iterator_tag) - { + append_range (InputIt first, InputIt last, std::input_iterator_tag) { size_ty original_size = get_size (); - for (; ! (first == last); ++first) + for (; ! (first == last); ++first) { append_element (*first); + } return unchecked_next (begin_ptr (), original_size); } template PLUMED_GCH_CPP20_CONSTEXPR ptr - append_range (ForwardIt first, ForwardIt last, std::forward_iterator_tag) - { + append_range (ForwardIt first, ForwardIt last, std::forward_iterator_tag) { const size_ty num_insert = external_range_length (first, last); - if (num_uninitialized () < num_insert) - { + if (num_uninitialized () < num_insert) { // Reallocate. - if (get_max_size () - get_size () < num_insert) + if (get_max_size () - get_size () < num_insert) { throw_allocation_size_error (); + } size_ty original_size = get_size (); size_ty new_size = get_size () + num_insert; @@ -4035,13 +3809,11 @@ class small_vector_base ptr new_data_ptr = unchecked_allocate (new_capacity, allocation_end_ptr ()); ptr new_last = unchecked_next (new_data_ptr, original_size); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { new_last = uninitialized_copy (first, last, new_last); uninitialized_move (begin_ptr (), end_ptr (), new_data_ptr); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (unchecked_next (new_data_ptr, original_size), new_last); deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; @@ -4049,9 +3821,7 @@ class small_vector_base reset_data (new_data_ptr, new_capacity, new_size); return unchecked_next (new_data_ptr, original_size); - } - else - { + } else { ptr ret = end_ptr (); uninitialized_copy (first, last, ret); increase_size (num_insert); @@ -4062,34 +3832,34 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - emplace_at (ptr pos, Args&&... args) - { + emplace_at (ptr pos, Args&&... args) { assert (get_size () <= get_capacity () && "size was greater than capacity"); - if (get_size () < get_capacity ()) + if (get_size () < get_capacity ()) { return emplace_into_current (pos, std::forward (args)...); + } return emplace_into_reallocation (pos, std::forward (args)...); } PLUMED_GCH_CPP20_CONSTEXPR ptr - insert_copies (ptr pos, size_ty count, const value_ty& val) - { - if (0 == count) + insert_copies (ptr pos, size_ty count, const value_ty& val) { + if (0 == count) { return pos; + } - if (end_ptr () == pos) - { - if (1 == count) + if (end_ptr () == pos) { + if (1 == count) { return append_element (val); + } return append_copies (count, val); } - if (num_uninitialized () < count) - { + if (num_uninitialized () < count) { // Reallocate. - if (get_max_size () - get_size () < count) + if (get_max_size () - get_size () < count) { throw_allocation_size_error (); + } const size_ty offset = internal_range_length (begin_ptr (), pos); @@ -4101,8 +3871,7 @@ class small_vector_base ptr new_first = unchecked_next (new_data_ptr, offset); ptr new_last = new_first; - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_fill (new_first, unchecked_next (new_first, count), val); unchecked_advance (new_last, count); @@ -4110,8 +3879,7 @@ class small_vector_base new_first = new_data_ptr; uninitialized_move (pos, end_ptr (), new_last); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (new_first, new_last); deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; @@ -4119,15 +3887,12 @@ class small_vector_base reset_data (new_data_ptr, new_capacity, new_size); return unchecked_next (begin_ptr (), offset); - } - else - { + } else { // If we have fewer to insert than tailing elements after `pos`, we shift into // uninitialized and then copy over. const size_ty tail_size = internal_range_length (pos, end_ptr ()); - if (tail_size < count) - { + if (tail_size < count) { // The number inserted is larger than the number after `pos`, // so part of the input will be used to construct new elements, // and another part of it will assign existing ones. @@ -4142,8 +3907,7 @@ class small_vector_base size_ty num_val_tail = count - tail_size; #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) - { + if (std::is_constant_evaluated ()) { uninitialized_fill (end_ptr (), unchecked_next (end_ptr (), num_val_tail), val); increase_size (num_val_tail); @@ -4161,8 +3925,7 @@ class small_vector_base uninitialized_fill (end_ptr (), unchecked_next (end_ptr (), num_val_tail), val); increase_size (num_val_tail); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { // We need to handle possible aliasing here. const stack_temporary tmp (*this, val); @@ -4175,8 +3938,7 @@ class small_vector_base // Finally, try to copy the rest of the elements over. std::fill_n (pos, tail_size, tmp.get ()); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { // Attempt to roll back and destroy the tail if we fail. ptr inserted_end = unchecked_prev (end_ptr (), tail_size); move_left (inserted_end, end_ptr (), pos); @@ -4185,19 +3947,15 @@ class small_vector_base PLUMED_GCH_THROW; } } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { // Destroy the elements constructed from the input. destroy_range (original_end, end_ptr ()); decrease_size (internal_range_length (original_end, end_ptr ())); PLUMED_GCH_THROW; } - } - else - { + } else { #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) - { + if (std::is_constant_evaluated ()) { const heap_temporary tmp (*this, val); ptr inserted_end = shift_into_uninitialized (pos, count); @@ -4212,12 +3970,10 @@ class small_vector_base // Attempt to copy over the elements. // If we fail we'll attempt a full roll-back. - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { std::fill (pos, inserted_end, tmp.get ()); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { ptr original_end = move_left (inserted_end, end_ptr (), pos); destroy_range (original_end, end_ptr ()); decrease_size (count); @@ -4231,17 +3987,16 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - insert_range_helper (ptr pos, ForwardIt first, ForwardIt last) - { + insert_range_helper (ptr pos, ForwardIt first, ForwardIt last) { assert (! (first == last) && "The range should not be empty."); assert (! (end_ptr () == pos) && "`pos` should not be at the end."); const size_ty num_insert = external_range_length (first, last); - if (num_uninitialized () < num_insert) - { + if (num_uninitialized () < num_insert) { // Reallocate. - if (get_max_size () - get_size () < num_insert) + if (get_max_size () - get_size () < num_insert) { throw_allocation_size_error (); + } const size_ty offset = internal_range_length (begin_ptr (), pos); const size_ty new_size = get_size () + num_insert; @@ -4252,8 +4007,7 @@ class small_vector_base ptr new_first = unchecked_next (new_data_ptr, offset); ptr new_last = new_first; - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_copy (first, last, new_first); unchecked_advance (new_last, num_insert); @@ -4261,8 +4015,7 @@ class small_vector_base new_first = new_data_ptr; uninitialized_move (pos, end_ptr (), new_last); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (new_first, new_last); deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; @@ -4270,14 +4023,11 @@ class small_vector_base reset_data (new_data_ptr, new_capacity, new_size); return unchecked_next (begin_ptr (), offset); - } - else - { + } else { // if we have fewer to insert than tailing elements after // `pos` we shift into uninitialized and then copy over const size_ty tail_size = internal_range_length (pos, end_ptr ()); - if (tail_size < num_insert) - { + if (tail_size < num_insert) { // Use the same method as insert_copies. ptr original_end = end_ptr (); ForwardIt pivot = unchecked_next (first, tail_size); @@ -4286,8 +4036,7 @@ class small_vector_base uninitialized_copy (pivot, last, end_ptr ()); increase_size (num_insert - tail_size); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { // Now move the tail to the end. uninitialized_move (pos, original_end, end_ptr ()); increase_size (tail_size); @@ -4297,8 +4046,7 @@ class small_vector_base // Finally, try to copy the rest of the elements over. copy_range (first, pivot, pos); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { // Attempt to roll back and destroy the tail if we fail. ptr inserted_end = unchecked_prev (end_ptr (), tail_size); move_left (inserted_end, end_ptr (), pos); @@ -4307,26 +4055,21 @@ class small_vector_base PLUMED_GCH_THROW; } } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { // If we throw, destroy the first copy we made. destroy_range (original_end, end_ptr ()); decrease_size (internal_range_length (original_end, end_ptr ())); PLUMED_GCH_THROW; } - } - else - { + } else { shift_into_uninitialized (pos, num_insert); // Attempt to copy over the elements. // If we fail we'll attempt a full roll-back. - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { copy_range (first, last, pos); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { ptr inserted_end = unchecked_next (pos, num_insert); ptr original_end = move_left (inserted_end, end_ptr (), pos); destroy_range (original_end, end_ptr ()); @@ -4341,8 +4084,7 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - insert_range (ptr pos, InputIt first, InputIt last, std::input_iterator_tag) - { + insert_range (ptr pos, InputIt first, InputIt last, std::input_iterator_tag) { assert (! (first == last) && "The range should not be empty."); // Ensure we use this specific overload to give a strong exception guarantee for 1 element. @@ -4361,13 +4103,14 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - insert_range (ptr pos, ForwardIt first, ForwardIt last, std::forward_iterator_tag) - { - if (! (end_ptr () == pos)) + insert_range (ptr pos, ForwardIt first, ForwardIt last, std::forward_iterator_tag) { + if (! (end_ptr () == pos)) { return insert_range_helper (pos, first, last); + } - if (unchecked_next (first) == last) + if (unchecked_next (first) == last) { return append_element (*first); + } using iterator_cat = typename std::iterator_traits::iterator_category; return append_range (first, last, iterator_cat { }); @@ -4376,8 +4119,7 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - emplace_into_current_end (Args&&... args) - { + emplace_into_current_end (Args&&... args) { construct (end_ptr (), std::forward (args)...); increase_size (1); return unchecked_prev (end_ptr ()); @@ -4388,10 +4130,10 @@ class small_vector_base std::is_nothrow_move_constructible::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR ptr - emplace_into_current (ptr pos, value_ty&& val) - { - if (pos == end_ptr ()) + emplace_into_current (ptr pos, value_ty&& val) { + if (pos == end_ptr ()) { return emplace_into_current_end (std::move (val)); + } // In the special case of value_ty&& we don't make a copy because behavior is unspecified // when it is an internal element. Hence, we'll take the opportunity to optimize and assume @@ -4405,14 +4147,13 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - emplace_into_current (ptr pos, Args&&... args) - { - if (pos == end_ptr ()) + emplace_into_current (ptr pos, Args&&... args) { + if (pos == end_ptr ()) { return emplace_into_current_end (std::forward (args)...); + } #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) - { + if (std::is_constant_evaluated ()) { heap_temporary tmp (*this, std::forward (args)...); shift_into_uninitialized (pos, 1); *pos = tmp.release (); @@ -4430,11 +4171,11 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - emplace_into_reallocation_end (Args&&... args) - { + emplace_into_reallocation_end (Args&&... args) { // Appending; strong exception guarantee. - if (get_max_size () == get_size ()) + if (get_max_size () == get_size ()) { throw_allocation_size_error (); + } const size_ty new_size = get_size () + 1; @@ -4443,21 +4184,18 @@ class small_vector_base const ptr new_data_ptr = unchecked_allocate (new_capacity, allocation_end_ptr ()); const ptr emplace_pos = unchecked_next (new_data_ptr, get_size ()); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { construct (emplace_pos, std::forward (args)...); PLUMED_GCH_TRY { uninitialized_move (begin_ptr (), end_ptr (), new_data_ptr); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy (emplace_pos); PLUMED_GCH_THROW; } } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; } @@ -4469,14 +4207,15 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - emplace_into_reallocation (ptr pos, Args&&... args) - { + emplace_into_reallocation (ptr pos, Args&&... args) { const size_ty offset = internal_range_length (begin_ptr (), pos); - if (offset == get_size ()) + if (offset == get_size ()) { return emplace_into_reallocation_end (std::forward (args)...); + } - if (get_max_size () == get_size ()) + if (get_max_size () == get_size ()) { throw_allocation_size_error (); + } const size_ty new_size = get_size () + 1; @@ -4486,8 +4225,7 @@ class small_vector_base ptr new_first = unchecked_next (new_data_ptr, offset); ptr new_last = new_first; - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { construct (new_first, std::forward (args)...); unchecked_advance (new_last, 1); @@ -4495,8 +4233,7 @@ class small_vector_base new_first = new_data_ptr; uninitialized_move (pos, end_ptr (), new_last); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (new_first, new_last); deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; @@ -4508,30 +4245,28 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR ptr - shrink_to_size (void) - { - if (! has_allocation () || get_size () == get_capacity ()) + shrink_to_size (void) { + if (! has_allocation () || get_size () == get_capacity ()) { return begin_ptr (); + } // The rest runs only if allocated. size_ty new_capacity; ptr new_data_ptr; - if (InlineCapacity < get_size ()) - { + if (InlineCapacity < get_size ()) { new_capacity = get_size (); new_data_ptr = unchecked_allocate (new_capacity, allocation_end_ptr ()); - } - else - { + } else { // We move to inline storage. new_capacity = InlineCapacity; #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) + if (std::is_constant_evaluated ()) { new_data_ptr = alloc_interface::allocate (InlineCapacity); - else + } else { new_data_ptr = storage_ptr (); + } #else new_data_ptr = storage_ptr (); #endif @@ -4551,19 +4286,19 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR void - resize_with (size_ty new_size, const ValueT&... val) - { + resize_with (size_ty new_size, const ValueT&... val) { // ValueT... should either be value_ty or empty. - if (new_size == 0) + if (new_size == 0) { erase_all (); + } - if (get_capacity () < new_size) - { + if (get_capacity () < new_size) { // Reallocate. - if (get_max_size () < new_size) + if (get_max_size () < new_size) { throw_allocation_size_error (); + } const size_ty original_size = get_size (); @@ -4572,8 +4307,7 @@ class small_vector_base ptr new_data_ptr = unchecked_allocate (new_capacity, allocation_end_ptr ()); ptr new_last = unchecked_next (new_data_ptr, original_size); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { new_last = uninitialized_fill ( new_last, unchecked_next (new_data_ptr, new_size), @@ -4582,43 +4316,38 @@ class small_vector_base // Strong exception guarantee. uninitialized_move (begin_ptr (), end_ptr (), new_data_ptr); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (unchecked_next (new_data_ptr, original_size), new_last); deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; } reset_data (new_data_ptr, new_capacity, new_size); - } - else if (get_size () < new_size) - { + } else if (get_size () < new_size) { // Construct in the uninitialized section. uninitialized_fill (end_ptr (), unchecked_next (begin_ptr (), new_size), val...); set_size (new_size); - } - else + } else { erase_range (unchecked_next (begin_ptr (), new_size), end_ptr ()); + } // Do nothing if the count is the same as the current size. } PLUMED_GCH_CPP20_CONSTEXPR void - request_capacity (size_ty request) - { - if (request <= get_capacity ()) + request_capacity (size_ty request) { + if (request <= get_capacity ()) { return; + } size_ty new_capacity = checked_calculate_new_capacity (request); ptr new_begin = unchecked_allocate (new_capacity); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_move (begin_ptr (), end_ptr (), new_begin); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (new_begin, new_capacity); PLUMED_GCH_THROW; } @@ -4631,8 +4360,7 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR ptr - erase_at (ptr pos) - { + erase_at (ptr pos) { move_left (unchecked_next (pos), end_ptr (), pos); erase_last (); return pos; @@ -4640,8 +4368,7 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR void - erase_last (void) - { + erase_last (void) { decrease_size (1); // The element located at end_ptr is still alive since the size decreased. @@ -4650,20 +4377,18 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR ptr - erase_range (ptr first, ptr last) - { - if (! (first == last)) + erase_range (ptr first, ptr last) { + if (! (first == last)) { erase_to_end (move_left (last, end_ptr (), first)); + } return first; } PLUMED_GCH_CPP20_CONSTEXPR void - erase_to_end (ptr pos) - { + erase_to_end (ptr pos) { assert (0 <= (end_ptr () - pos) && "`pos` was in the uninitialized range"); - if (size_ty change = internal_range_length (pos, end_ptr ())) - { + if (size_ty change = internal_range_length (pos, end_ptr ())) { decrease_size (change); destroy_range (pos, unchecked_next (pos, change)); } @@ -4671,8 +4396,7 @@ class small_vector_base PLUMED_GCH_CPP20_CONSTEXPR void - erase_all (void) - { + erase_all (void) { ptr curr_end = end_ptr (); set_size (0); destroy_range (begin_ptr (), curr_end); @@ -4687,8 +4411,7 @@ class small_vector_base #else && detail::small_vector_adl::is_nothrow_swappable::value #endif - ) - { + ) { assert (get_size () <= other.get_size ()); const ptr other_tail = std::swap_ranges (begin_ptr (), end_ptr (), other.begin_ptr ()); @@ -4707,8 +4430,7 @@ class small_vector_base #else && detail::small_vector_adl::is_nothrow_swappable::value #endif - ) - { + ) { // This function is used when: // We are using the standard allocator. // The allocators propagate and are equal. @@ -4721,10 +4443,9 @@ class small_vector_base assert (get_capacity () <= other.get_capacity ()); - if (has_allocation ()) // Implies that `other` also has an allocation. + if (has_allocation ()) { // Implies that `other` also has an allocation. swap_allocation (other); - else if (other.has_allocation ()) - { + } else if (other.has_allocation ()) { // Note: This will never be constant evaluated because both are always allocated. uninitialized_move (begin_ptr (), end_ptr (), other.storage_ptr ()); destroy_range (begin_ptr (), end_ptr ()); @@ -4736,30 +4457,27 @@ class small_vector_base other.set_capacity (InlineCapacity); swap_size (other); - } - else if (get_size () < other.get_size ()) + } else if (get_size () < other.get_size ()) { swap_elements (other); - else + } else { other.swap_elements (*this); + } alloc_interface::swap (other); } PLUMED_GCH_CPP20_CONSTEXPR void - swap_unequal_no_propagate (small_vector_base& other) - { + swap_unequal_no_propagate (small_vector_base& other) { assert (get_capacity () <= other.get_capacity ()); - if (get_capacity () < other.get_size ()) - { + if (get_capacity () < other.get_size ()) { // Reallocation required. // We should always be able to reuse the allocation of `other`. const size_ty new_capacity = unchecked_calculate_new_capacity (other.get_size ()); const ptr new_data_ptr = unchecked_allocate (new_capacity, end_ptr ()); - PLUMED_GCH_TRY - { + PLUMED_GCH_TRY { uninitialized_move (other.begin_ptr (), other.end_ptr (), new_data_ptr); PLUMED_GCH_TRY { @@ -4767,30 +4485,29 @@ class small_vector_base std::move (begin_ptr (), end_ptr (), other.begin_ptr ()), other.end_ptr ()); } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { destroy_range (new_data_ptr, unchecked_next (new_data_ptr, other.get_size ())); PLUMED_GCH_THROW; } } - PLUMED_GCH_CATCH (...) - { + PLUMED_GCH_CATCH (...) { deallocate (new_data_ptr, new_capacity); PLUMED_GCH_THROW; } destroy_range (begin_ptr (), end_ptr ()); - if (has_allocation ()) + if (has_allocation ()) { deallocate (data_ptr (), get_capacity ()); + } set_data_ptr (new_data_ptr); set_capacity (new_capacity); swap_size (other); - } - else if (get_size () < other.get_size ()) + } else if (get_size () < other.get_size ()) { swap_elements (other); - else + } else { other.swap_elements (*this); + } // This should have no effect. alloc_interface::swap (other); @@ -4801,8 +4518,7 @@ class small_vector_base && InlineCapacity == 0>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - swap (small_vector_base& other) noexcept - { + swap (small_vector_base& other) noexcept { swap_allocation (other); alloc_interface::swap (other); } @@ -4819,33 +4535,31 @@ class small_vector_base #else && detail::small_vector_adl::is_nothrow_swappable::value #endif - ) - { - if (get_capacity () < other.get_capacity ()) - swap_default (other); - else + ) { + if (get_capacity () < other.get_capacity ()) { + swap_default (other); + } else { other.swap_default (*this); + } } template ::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR void - swap (small_vector_base& other) - { - if (get_capacity () < other.get_capacity ()) - { - if (other.allocator_ref () == allocator_ref ()) + swap (small_vector_base& other) { + if (get_capacity () < other.get_capacity ()) { + if (other.allocator_ref () == allocator_ref ()) { swap_default (other); - else + } else { swap_unequal_no_propagate (other); - } - else - { - if (other.allocator_ref () == allocator_ref ()) + } + } else { + if (other.allocator_ref () == allocator_ref ()) { other.swap_default (*this); - else + } else { other.swap_unequal_no_propagate (*this); + } } } @@ -4857,8 +4571,7 @@ class small_vector_base template static PLUMED_GCH_CPP20_CONSTEXPR InputIt - unmove_iterator (InputIt it) - { + unmove_iterator (InputIt it) { return it; } @@ -4866,8 +4579,7 @@ class small_vector_base static PLUMED_GCH_CPP20_CONSTEXPR auto unmove_iterator (std::move_iterator it) - -> decltype (unmove_iterator (it.base ())) - { + -> decltype (unmove_iterator (it.base ())) { return unmove_iterator (it.base ()); } @@ -4875,8 +4587,7 @@ class small_vector_base static PLUMED_GCH_CPP20_CONSTEXPR auto unmove_iterator (std::reverse_iterator it) - -> std::reverse_iterator - { + -> std::reverse_iterator { return std::reverse_iterator ( unmove_iterator (it.base ())); } @@ -4886,13 +4597,11 @@ class small_vector_base template PLUMED_GCH_CPP20_CONSTEXPR ptr - copy_range (InputIt first, InputIt last, ptr dest) - { + copy_range (InputIt first, InputIt last, ptr dest) { #if defined (PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED) && defined (__GLIBCXX__) if ( std::is_constant_evaluated () &&! std::is_same ())), - InputIt>::value) - { + InputIt>::value) { return std::move (unmove_iterator (first), unmove_iterator (last), dest); } #endif @@ -4905,18 +4614,17 @@ class small_vector_base is_memcpyable_iterator::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR InputIt - copy_n_return_in (InputIt first, size_ty count, ptr dest) noexcept - { + copy_n_return_in (InputIt first, size_ty count, ptr dest) noexcept { #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) - { + if (std::is_constant_evaluated ()) { std::copy_n (first, count, dest); return unchecked_next (first, count); } #endif - if (count != 0) + if (count != 0) { std::memcpy (to_address (dest), to_address (first), count * sizeof (value_ty)); + } // Note: The unsafe cast here should be proven to be safe in the caller function. return unchecked_next (first, count); } @@ -4926,8 +4634,7 @@ class small_vector_base is_memcpyable_iterator::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR std::move_iterator - copy_n_return_in (std::move_iterator first, size_ty count, ptr dest) noexcept - { + copy_n_return_in (std::move_iterator first, size_ty count, ptr dest) noexcept { return std::move_iterator (copy_n_return_in (first.base (), count, dest)); } @@ -4939,13 +4646,11 @@ class small_vector_base >::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR RandomIt - copy_n_return_in (RandomIt first, size_ty count, ptr dest) - { + copy_n_return_in (RandomIt first, size_ty count, ptr dest) { #if defined (PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED) && defined (__GLIBCXX__) if ( std::is_constant_evaluated () &&! std::is_same ())), - RandomIt>::value) - { + RandomIt>::value) { auto bfirst = unmove_iterator (first); auto blast = unchecked_next (bfirst, count); std::move (bfirst, blast, dest); @@ -4966,11 +4671,11 @@ class small_vector_base >::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR InputIt - copy_n_return_in (InputIt first, size_ty count, ptr dest) - { + copy_n_return_in (InputIt first, size_ty count, ptr dest) { - for (; count != 0; --count, static_cast (++dest), static_cast (++first)) + for (; count != 0; --count, static_cast (++dest), static_cast (++first)) { *dest = *first; + } return first; } @@ -4978,18 +4683,19 @@ class small_vector_base typename std::enable_if::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR ptr - move_left (ptr first, ptr last, ptr d_first) - { + move_left (ptr first, ptr last, ptr d_first) { // Shift initialized elements to the left. #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) + if (std::is_constant_evaluated ()) { return std::move (first, last, d_first); + } #endif const size_ty num_moved = internal_range_length (first, last); - if (num_moved != 0) + if (num_moved != 0) { std::memmove (to_address (d_first), to_address (first), num_moved * sizeof (value_ty)); + } return unchecked_next (d_first, num_moved); } @@ -4997,8 +4703,7 @@ class small_vector_base typename std::enable_if::value>::type * = nullptr> PLUMED_GCH_CPP20_CONSTEXPR ptr - move_left (ptr first, ptr last, ptr d_first) - { + move_left (ptr first, ptr last, ptr d_first) { // Shift initialized elements to the left. return std::move (first, last, d_first); } @@ -5007,19 +4712,20 @@ class small_vector_base typename std::enable_if::value, bool>::type = true> PLUMED_GCH_CPP20_CONSTEXPR ptr - move_right (ptr first, ptr last, ptr d_last) - { + move_right (ptr first, ptr last, ptr d_last) { // Move initialized elements to the right. #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) + if (std::is_constant_evaluated ()) { return std::move_backward (first, last, d_last); + } #endif const size_ty num_moved = internal_range_length (first, last); const ptr dest = unchecked_prev (d_last, num_moved); - if (num_moved != 0) + if (num_moved != 0) { std::memmove (to_address (dest), to_address (first), num_moved * sizeof (value_ty)); + } return dest; } @@ -5027,8 +4733,7 @@ class small_vector_base typename std::enable_if::value, bool>::type = false> PLUMED_GCH_CPP20_CONSTEXPR ptr - move_right (ptr first, ptr last, ptr d_last) - { + move_right (ptr first, ptr last, ptr d_last) { // move initialized elements to the right // n should not be 0 return std::move_backward (first, last, d_last); @@ -5037,126 +4742,110 @@ class small_vector_base public: PLUMED_GCH_CPP20_CONSTEXPR void - set_default (void) - { + set_default (void) { set_to_inline_storage (); set_size (0); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR ptr - data_ptr (void) noexcept - { + data_ptr (void) noexcept { return m_data.data_ptr (); } PLUMED_GCH_NODISCARD constexpr cptr - data_ptr (void) const noexcept - { + data_ptr (void) const noexcept { return m_data.data_ptr (); } PLUMED_GCH_NODISCARD constexpr size_ty - get_capacity (void) const noexcept - { + get_capacity (void) const noexcept { return m_data.capacity (); } PLUMED_GCH_NODISCARD constexpr size_ty - get_size (void) const noexcept - { + get_size (void) const noexcept { return m_data.size (); } PLUMED_GCH_NODISCARD constexpr size_ty - num_uninitialized (void) const noexcept - { + num_uninitialized (void) const noexcept { return get_capacity () - get_size (); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR ptr - begin_ptr (void) noexcept - { + begin_ptr (void) noexcept { return data_ptr (); } PLUMED_GCH_NODISCARD constexpr cptr - begin_ptr (void) const noexcept - { + begin_ptr (void) const noexcept { return data_ptr (); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR ptr - end_ptr (void) noexcept - { + end_ptr (void) noexcept { return unchecked_next (begin_ptr (), get_size ()); } PLUMED_GCH_NODISCARD constexpr cptr - end_ptr (void) const noexcept - { + end_ptr (void) const noexcept { return unchecked_next (begin_ptr (), get_size ()); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR ptr - allocation_end_ptr (void) noexcept - { + allocation_end_ptr (void) noexcept { return unchecked_next (begin_ptr (), get_capacity ()); } PLUMED_GCH_NODISCARD constexpr cptr - allocation_end_ptr (void) const noexcept - { + allocation_end_ptr (void) const noexcept { return unchecked_next (begin_ptr (), get_capacity ()); } PLUMED_GCH_NODISCARD constexpr alloc_ty - copy_allocator (void) const noexcept - { + copy_allocator (void) const noexcept { return alloc_ty (allocator_ref ()); } PLUMED_GCH_NODISCARD PLUMED_GCH_CPP14_CONSTEXPR ptr - storage_ptr (void) noexcept - { + storage_ptr (void) noexcept { return m_data.storage (); } PLUMED_GCH_NODISCARD constexpr cptr - storage_ptr (void) const noexcept - { + storage_ptr (void) const noexcept { return m_data.storage (); } PLUMED_GCH_NODISCARD constexpr bool - has_allocation (void) const noexcept - { + has_allocation (void) const noexcept { #ifdef PLUMED_GCH_LIB_IS_CONSTANT_EVALUATED - if (std::is_constant_evaluated ()) + if (std::is_constant_evaluated ()) { return true; + } #endif return InlineCapacity < get_capacity (); } PLUMED_GCH_NODISCARD constexpr bool - is_inlinable (void) const noexcept - { + is_inlinable (void) const noexcept { return get_size () <= InlineCapacity; } @@ -5171,8 +4860,7 @@ template requires concepts::small_vector::AllocatorFor #endif class small_vector -: private detail::small_vector_base -{ +: private detail::small_vector_base { using base = detail::small_vector_base; public: @@ -5253,8 +4941,7 @@ class small_vector Erasable = concepts::small_vector::Erasable; template - struct EmplaceConstructible - { + struct EmplaceConstructible { static constexpr bool value = concepts::small_vector::EmplaceConstructible::value #endif -: small_vector (init.begin (), init.end (), alloc) +: + small_vector (init.begin (), init.end (), alloc) { } template @@ -5484,8 +5178,7 @@ class small_vector #endif PLUMED_GCH_CPP20_CONSTEXPR void - assign (InputIt first, InputIt last) - { + assign (InputIt first, InputIt last) { using iterator_cat = typename std::iterator_traits::iterator_category; base::assign_with_range (first, last, iterator_cat { }); } @@ -5507,8 +5200,9 @@ class small_vector requires CopyInsertable && CopyAssignable #endif { - if (&other != this) + if (&other != this) { base::copy_assign (other); + } } template @@ -5517,8 +5211,7 @@ class small_vector #endif PLUMED_GCH_CPP20_CONSTEXPR void - assign (const small_vector& other) - { + assign (const small_vector& other) { base::copy_assign (other); } @@ -5541,8 +5234,9 @@ class small_vector requires MoveInsertable && MoveAssignable #endif { - if (&other != this) + if (&other != this) { base::move_assign (std::move (other)); + } } template @@ -5561,8 +5255,7 @@ class small_vector ) && std::is_nothrow_move_assignable::value && std::is_nothrow_move_constructible::value - ) - { + ) { base::move_assign (std::move (other)); } @@ -5622,200 +5315,179 @@ class small_vector PLUMED_GCH_CPP14_CONSTEXPR iterator - begin (void) noexcept - { + begin (void) noexcept { return iterator { base::begin_ptr () }; } constexpr const_iterator - begin (void) const noexcept - { + begin (void) const noexcept { return const_iterator { base::begin_ptr () }; } constexpr const_iterator - cbegin (void) const noexcept - { + cbegin (void) const noexcept { return begin (); } PLUMED_GCH_CPP14_CONSTEXPR iterator - end (void) noexcept - { + end (void) noexcept { return iterator { base::end_ptr () }; } constexpr const_iterator - end (void) const noexcept - { + end (void) const noexcept { return const_iterator { base::end_ptr () }; } constexpr const_iterator - cend (void) const noexcept - { + cend (void) const noexcept { return end (); } PLUMED_GCH_CPP14_CONSTEXPR reverse_iterator - rbegin (void) noexcept - { + rbegin (void) noexcept { return reverse_iterator { end () }; } constexpr const_reverse_iterator - rbegin (void) const noexcept - { + rbegin (void) const noexcept { return const_reverse_iterator { end () }; } constexpr const_reverse_iterator - crbegin (void) const noexcept - { + crbegin (void) const noexcept { return rbegin (); } PLUMED_GCH_CPP14_CONSTEXPR reverse_iterator - rend (void) noexcept - { + rend (void) noexcept { return reverse_iterator { begin () }; } constexpr const_reverse_iterator - rend (void) const noexcept - { + rend (void) const noexcept { return const_reverse_iterator { begin () }; } constexpr const_reverse_iterator - crend (void) const noexcept - { + crend (void) const noexcept { return rend (); } PLUMED_GCH_CPP14_CONSTEXPR reference - at (size_type pos) - { - if (size () <= pos) + at (size_type pos) { + if (size () <= pos) { base::throw_index_error (); + } return begin ()[static_cast (pos)]; } PLUMED_GCH_CPP14_CONSTEXPR const_reference - at (size_type pos) const - { - if (size () <= pos) + at (size_type pos) const { + if (size () <= pos) { base::throw_index_error (); + } return begin ()[static_cast (pos)]; } PLUMED_GCH_CPP14_CONSTEXPR reference - operator[] (size_type pos) - { + operator[] (size_type pos) { #ifdef _GLIBCXX_DEBUG - if (size () <= pos) base::throw_index_error (); + if (size () <= pos) { + base::throw_index_error (); + } #endif return begin ()[static_cast (pos)]; } constexpr const_reference - operator[] (size_type pos) const - { + operator[] (size_type pos) const { #ifdef _GLIBCXX_DEBUG - if (size () <= pos) base::throw_index_error (); + if (size () <= pos) { + base::throw_index_error (); + } #endif return begin ()[static_cast (pos)]; } PLUMED_GCH_CPP14_CONSTEXPR reference - front (void) - { + front (void) { return (*this)[0]; } constexpr const_reference - front (void) const - { + front (void) const { return (*this)[0]; } PLUMED_GCH_CPP14_CONSTEXPR reference - back (void) - { + back (void) { return (*this)[size () - 1]; } constexpr const_reference - back (void) const - { + back (void) const { return (*this)[size () - 1]; } PLUMED_GCH_CPP14_CONSTEXPR pointer - data (void) noexcept - { + data (void) noexcept { return base::begin_ptr (); } constexpr const_pointer - data (void) const noexcept - { + data (void) const noexcept { return base::begin_ptr (); } constexpr size_type - size (void) const noexcept - { + size (void) const noexcept { return static_cast (base::get_size ()); } PLUMED_GCH_NODISCARD constexpr bool - empty (void) const noexcept - { + empty (void) const noexcept { return size () == 0; } PLUMED_GCH_CPP14_CONSTEXPR size_type - max_size (void) const noexcept - { + max_size (void) const noexcept { return static_cast (base::get_max_size ()); } constexpr size_type - capacity (void) const noexcept - { + capacity (void) const noexcept { return static_cast (base::get_capacity ()); } constexpr allocator_type - get_allocator (void) const noexcept - { + get_allocator (void) const noexcept { return base::copy_allocator (); } @@ -5866,10 +5538,10 @@ class small_vector #endif PLUMED_GCH_CPP20_CONSTEXPR iterator - insert (const_iterator pos, InputIt first, InputIt last) - { - if (first == last) + insert (const_iterator pos, InputIt first, InputIt last) { + if (first == last) { return iterator (base::ptr_cast (pos)); + } using iterator_cat = typename std::iterator_traits::iterator_category; return iterator (base::insert_range (base::ptr_cast (pos), first, last, iterator_cat { })); @@ -5895,8 +5567,7 @@ class small_vector #endif PLUMED_GCH_CPP20_CONSTEXPR iterator - emplace (const_iterator pos, Args&&... args) - { + emplace (const_iterator pos, Args&&... args) { return iterator (base::emplace_at (base::ptr_cast (pos), std::forward (args)...)); } @@ -5953,8 +5624,7 @@ class small_vector #endif PLUMED_GCH_CPP20_CONSTEXPR reference - emplace_back (Args&&... args) - { + emplace_back (Args&&... args) { return *base::append_element (std::forward (args)...); } @@ -6021,23 +5691,20 @@ class small_vector PLUMED_GCH_NODISCARD constexpr bool - inlined (void) const noexcept - { + inlined (void) const noexcept { return ! base::has_allocation (); } PLUMED_GCH_NODISCARD constexpr bool - inlinable (void) const noexcept - { + inlinable (void) const noexcept { return base::is_inlinable (); } PLUMED_GCH_NODISCARD static PLUMED_GCH_CONSTEVAL size_type - inline_capacity (void) noexcept - { + inline_capacity (void) noexcept { return static_cast (inline_capacity_v); } @@ -6054,8 +5721,7 @@ class small_vector #endif PLUMED_GCH_CPP20_CONSTEXPR small_vector& - append (InputIt first, InputIt last) - { + append (InputIt first, InputIt last) { using policy = typename base::strong_exception_policy; using iterator_cat = typename std::iterator_traits::iterator_category; base::template append_range (first, last, iterator_cat { }); @@ -6108,8 +5774,7 @@ template & lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return lhs.size () == rhs.size () && std::equal (lhs.begin (), lhs.end (), rhs.begin ()); } @@ -6117,8 +5782,7 @@ template inline PLUMED_GCH_CPP20_CONSTEXPR bool operator== (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return lhs.size () == rhs.size () && std::equal (lhs.begin (), lhs.end (), rhs.begin ()); } @@ -6129,8 +5793,7 @@ requires std::three_way_comparable constexpr auto operator<=> (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return std::lexicographical_compare_three_way ( lhs.begin (), lhs.end (), rhs.begin (), rhs.end (), @@ -6142,8 +5805,7 @@ requires std::three_way_comparable constexpr auto operator<=> (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return std::lexicographical_compare_three_way ( lhs.begin (), lhs.end (), rhs.begin (), rhs.end (), @@ -6154,8 +5816,7 @@ template (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { constexpr auto comparison = [](const T& l, const T& r) { return (l < r) ? std::weak_ordering::less : (r < l) ? std::weak_ordering::greater @@ -6172,8 +5833,7 @@ template constexpr auto operator<=> (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { constexpr auto comparison = [](const T& l, const T& r) { return (l < r) ? std::weak_ordering::less : (r < l) ? std::weak_ordering::greater @@ -6192,8 +5852,7 @@ template & lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return ! (lhs == rhs); } @@ -6201,8 +5860,7 @@ template inline PLUMED_GCH_CPP20_CONSTEXPR bool operator!= (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return ! (lhs == rhs); } @@ -6210,8 +5868,7 @@ template & lhs, - const small_vector& rhs) -{ +const small_vector& rhs) { return std::lexicographical_compare (lhs.begin (), lhs.end (), rhs.begin (), rhs.end ()); } @@ -6219,8 +5876,7 @@ template inline PLUMED_GCH_CPP20_CONSTEXPR bool operator< (const small_vector& lhs, - const small_vector& rhs) -{ +const small_vector& rhs) { return std::lexicographical_compare (lhs.begin (), lhs.end (), rhs.begin (), rhs.end ()); } @@ -6228,8 +5884,7 @@ template = (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return ! (lhs < rhs); } @@ -6237,8 +5892,7 @@ template inline PLUMED_GCH_CPP20_CONSTEXPR bool operator>= (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return ! (lhs < rhs); } @@ -6246,8 +5900,7 @@ template (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return rhs < lhs; } @@ -6255,8 +5908,7 @@ template inline PLUMED_GCH_CPP20_CONSTEXPR bool operator> (const small_vector& lhs, - const small_vector& rhs) -{ + const small_vector& rhs) { return rhs < lhs; } @@ -6264,8 +5916,7 @@ template & lhs, - const small_vector& rhs) -{ +const small_vector& rhs) { return rhs >= lhs; } @@ -6273,8 +5924,7 @@ template inline PLUMED_GCH_CPP20_CONSTEXPR bool operator<= (const small_vector& lhs, - const small_vector& rhs) -{ +const small_vector& rhs) { return rhs >= lhs; } @@ -6306,8 +5956,7 @@ requires concepts::MoveInsertable, template inline PLUMED_GCH_CPP20_CONSTEXPR typename small_vector::size_type -erase (small_vector& v, const U& value) -{ +erase (small_vector& v, const U& value) { const auto original_size = v.size (); v.erase (std::remove (v.begin (), v.end (), value), v.end ()); return original_size - v.size (); @@ -6316,8 +5965,7 @@ erase (small_vector& v, const U& value) template inline PLUMED_GCH_CPP20_CONSTEXPR typename small_vector::size_type -erase_if (small_vector& v, Pred pred) -{ +erase_if (small_vector& v, Pred pred) { const auto original_size = v.size (); v.erase (std::remove_if (v.begin (), v.end (), pred), v.end ()); return original_size - v.size (); @@ -6326,104 +5974,91 @@ erase_if (small_vector& v, Pred pred) template constexpr typename small_vector::iterator -begin (small_vector& v) noexcept -{ +begin (small_vector& v) noexcept { return v.begin (); } template constexpr typename small_vector::const_iterator -begin (const small_vector& v) noexcept -{ +begin (const small_vector& v) noexcept { return v.begin (); } template constexpr typename small_vector::const_iterator -cbegin (const small_vector& v) noexcept -{ +cbegin (const small_vector& v) noexcept { return begin (v); } template constexpr typename small_vector::iterator -end (small_vector& v) noexcept -{ +end (small_vector& v) noexcept { return v.end (); } template constexpr typename small_vector::const_iterator -end (const small_vector& v) noexcept -{ +end (const small_vector& v) noexcept { return v.end (); } template constexpr typename small_vector::const_iterator -cend (const small_vector& v) noexcept -{ +cend (const small_vector& v) noexcept { return end (v); } template constexpr typename small_vector::reverse_iterator -rbegin (small_vector& v) noexcept -{ +rbegin (small_vector& v) noexcept { return v.rbegin (); } template constexpr typename small_vector::const_reverse_iterator -rbegin (const small_vector& v) noexcept -{ +rbegin (const small_vector& v) noexcept { return v.rbegin (); } template constexpr typename small_vector::const_reverse_iterator -crbegin (const small_vector& v) noexcept -{ +crbegin (const small_vector& v) noexcept { return rbegin (v); } template constexpr typename small_vector::reverse_iterator -rend (small_vector& v) noexcept -{ +rend (small_vector& v) noexcept { return v.rend (); } template constexpr typename small_vector::const_reverse_iterator -rend (const small_vector& v) noexcept -{ +rend (const small_vector& v) noexcept { return v.rend (); } template constexpr typename small_vector::const_reverse_iterator -crend (const small_vector& v) noexcept -{ +crend (const small_vector& v) noexcept { return rend (v); } template constexpr typename small_vector::size_type -size (const small_vector& v) noexcept -{ +size (const small_vector& v) noexcept { return v.size (); } @@ -6433,8 +6068,7 @@ typename std::common_type< std::ptrdiff_t, typename std::make_signed< typename small_vector::size_type>::type>::type -ssize (const small_vector& v) noexcept -{ +ssize (const small_vector& v) noexcept { using ret_type = typename std::common_type< std::ptrdiff_t, typename std::make_signed::type>::type; @@ -6444,24 +6078,21 @@ ssize (const small_vector& v) noexcept template PLUMED_GCH_NODISCARD constexpr bool -empty (const small_vector& v) noexcept -{ +empty (const small_vector& v) noexcept { return v.empty (); } template constexpr typename small_vector::pointer -data (small_vector& v) noexcept -{ +data (small_vector& v) noexcept { return v.data (); } template constexpr typename small_vector::const_pointer -data (const small_vector& v) noexcept -{ +data (const small_vector& v) noexcept { return v.data (); } diff --git a/src/sprint/Sprint.cpp b/src/sprint/Sprint.cpp index 89d01e5f1b..33ddc9fb9e 100644 --- a/src/sprint/Sprint.cpp +++ b/src/sprint/Sprint.cpp @@ -94,46 +94,65 @@ void Sprint::registerKeywords(Keywords& keys) { keys.add("optional","MATRIX","the matrix that you would like to perform SPRINT on"); keys.add("numbered","GROUP","specifies the list of atoms that should be assumed indistinguishable"); keys.add("numbered","SWITCH","specify the switching function to use between two sets of indistinguishable atoms"); - keys.needsAction("CONTACT_MATRIX"); keys.needsAction("DIAGONALIZE"); keys.needsAction("CUSTOM"); - keys.needsAction("SELECT_COMPONENTS"); keys.needsAction("SORT"); keys.needsAction("COMBINE"); + keys.needsAction("CONTACT_MATRIX"); + keys.needsAction("DIAGONALIZE"); + keys.needsAction("CUSTOM"); + keys.needsAction("SELECT_COMPONENTS"); + keys.needsAction("SORT"); + keys.needsAction("COMBINE"); keys.addOutputComponent("coord","default","the sprint coordinates"); } Sprint::Sprint(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - std::string matinp; parse("MATRIX",matinp); + ActionShortcut(ao) { + std::string matinp; + parse("MATRIX",matinp); if( matinp.length()==0 ) { readInputLine( getShortcutLabel() + "_jmat: CONTACT_MATRIX " + convertInputLineToString() ); matinp = getShortcutLabel() + "_jmat"; } - std::vector nin_group; unsigned ntot_atoms=0; + std::vector nin_group; + unsigned ntot_atoms=0; for(unsigned i=1;; ++i) { - std::string inum; Tools::convert( i, inum ); + std::string inum; + Tools::convert( i, inum ); ActionWithValue* av = plumed.getActionSet().selectWithLabel( matinp + inum + inum ); - if( !av ) break ; - unsigned natoms = (av->copyOutput(0))->getShape()[0]; nin_group.push_back( natoms ); ntot_atoms += natoms; + if( !av ) { + break ; + } + unsigned natoms = (av->copyOutput(0))->getShape()[0]; + nin_group.push_back( natoms ); + ntot_atoms += natoms; } // Diagonalization readInputLine( getShortcutLabel() + "_diag: DIAGONALIZE ARG=" + matinp + " VECTORS=1"); // Compute sprint coordinates as product of eigenvalue and eigenvector times square root of number of atoms in all groups - std::string str_natoms; Tools::convert( ntot_atoms, str_natoms ); + std::string str_natoms; + Tools::convert( ntot_atoms, str_natoms ); readInputLine( getShortcutLabel() + "_sp: CUSTOM ARG=" + getShortcutLabel() + "_diag.vals-1," + getShortcutLabel() + "_diag.vecs-1 FUNC=sqrt(" + str_natoms + ")*x*y PERIODIC=NO"); // Sort sprint coordinates for each group of atoms unsigned k=0, kk=0; for(unsigned j=0; j0 ) { readInputLine( getShortcutLabel() + "_mat: DISTANCE_MATRIX COMPONENTS GROUP=" + sp_str + " CUTOFF=" + rcut + pbcstr ); } else { - std::string specA, specB; parse("SPECIESA",specA); parse("SPECIESB",specB); - if( specA.length()==0 ) error("missing input atoms"); - if( specB.length()==0 ) error("missing SPECIESB keyword"); + std::string specA, specB; + parse("SPECIESA",specA); + parse("SPECIESB",specB); + if( specA.length()==0 ) { + error("missing input atoms"); + } + if( specB.length()==0 ) { + error("missing SPECIESB keyword"); + } readInputLine( getShortcutLabel() + "_mat: DISTANCE_MATRIX COMPONENTS GROUPA=" + specA + " GROUPB=" + specB + " CUTOFF=" + rcut + pbcstr ); } // Get the neighbors matrix @@ -77,7 +94,8 @@ AngularTetra::AngularTetra( const ActionOptions& ao): // Now evaluate the actual per atom CV readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_g8.g8 FUNC=(1-(3*x/8)) PERIODIC=NO"); // And get the things to do with the quantities we have computed - std::map keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); multicolvar::MultiColvarShortcuts::expandFunctions( getShortcutLabel(), getShortcutLabel(), "", keymap, this ); } diff --git a/src/symfunc/AtomicSMAC.cpp b/src/symfunc/AtomicSMAC.cpp index 6a937c52b3..3ace1070d1 100644 --- a/src/symfunc/AtomicSMAC.cpp +++ b/src/symfunc/AtomicSMAC.cpp @@ -58,35 +58,51 @@ void AtomicSMAC::registerKeywords(Keywords& keys) { keys.add("optional","SWITCH_COORD","This keyword is used to define the coordination switching function."); keys.reset_style("KERNEL","optional"); multicolvar::MultiColvarShortcuts::shortcutKeywords( keys ); - keys.needsAction("CONTACT_MATRIX"); keys.needsAction("GSYMFUNC_THREEBODY"); keys.needsAction("ONES"); + keys.needsAction("CONTACT_MATRIX"); + keys.needsAction("GSYMFUNC_THREEBODY"); + keys.needsAction("ONES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); } AtomicSMAC::AtomicSMAC(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Create the matrices - std::string sw_input; parse("SWITCH",sw_input); - std::string sp_lab, sp_laba; parse("SPECIES",sp_lab); parse("SPECIESA",sp_laba); + std::string sw_input; + parse("SWITCH",sw_input); + std::string sp_lab, sp_laba; + parse("SPECIES",sp_lab); + parse("SPECIESA",sp_laba); std::string cmap_input = getShortcutLabel() + "_cmap: CONTACT_MATRIX"; if( sp_lab.length()>0 ) { readInputLine( getShortcutLabel() + "_cmap: CONTACT_MATRIX GROUP=" + sp_lab + " COMPONENTS SWITCH={" + sw_input + "}"); } else if( sp_laba.length()>0 ) { - std::string sp_labb; parse("SPECIESB",sp_labb); + std::string sp_labb; + parse("SPECIESB",sp_labb); readInputLine( getShortcutLabel() + "_cmap: CONTACT_MATRIX GROUPA=" + sp_laba + " GROUPB=" + sp_labb + " COMPONENTS SWITCH={" + sw_input + "}"); } // Now need the Gaussians std::string mykernels; for(unsigned i=1;; ++i) { - std::string kstr_inpt, istr, kern_str; Tools::convert( i, istr ); - if( !parseNumbered("KERNEL",i,kstr_inpt ) ) { break; } + std::string kstr_inpt, istr, kern_str; + Tools::convert( i, istr ); + if( !parseNumbered("KERNEL",i,kstr_inpt ) ) { + break; + } std::vector words = Tools::getWords(kstr_inpt); - if( words[0]=="GAUSSIAN" ) kern_str="gaussian"; - else error("unknown kernel type"); - std::string center, var; Tools::parse(words,"CENTER",center); Tools::parse(words,"SIGMA",var); - if( mykernels.length()==0 ) mykernels = "exp(-(ajik-" + center + ")^2/(2*" + var + "*" + var + "))"; - else mykernels = mykernels + "+exp(-(ajik-" + center + ")^2/(2*" + var + "*" + var + "))"; + if( words[0]=="GAUSSIAN" ) { + kern_str="gaussian"; + } else { + error("unknown kernel type"); + } + std::string center, var; + Tools::parse(words,"CENTER",center); + Tools::parse(words,"SIGMA",var); + if( mykernels.length()==0 ) { + mykernels = "exp(-(ajik-" + center + ")^2/(2*" + var + "*" + var + "))"; + } else { + mykernels = mykernels + "+exp(-(ajik-" + center + ")^2/(2*" + var + "*" + var + "))"; + } } // Hard coded switching function on minimum distance here -- should be improved readInputLine( getShortcutLabel() + "_ksum: GSYMFUNC_THREEBODY WEIGHT=" + getShortcutLabel() + "_cmap.w " + @@ -95,11 +111,13 @@ AtomicSMAC::AtomicSMAC(const ActionOptions& ao): // And just the sum of the coordination numbers ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_cmap"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); readInputLine( getShortcutLabel() + "_denom: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_cmap.w," + getShortcutLabel() + "_ones"); // And the transformed switching functions - std::string swcoord_str; parse("SWITCH_COORD",swcoord_str); + std::string swcoord_str; + parse("SWITCH_COORD",swcoord_str); readInputLine( getShortcutLabel() + "_mtdenom: MORE_THAN ARG=" + getShortcutLabel() + "_denom SWITCH={" + swcoord_str +"}"); // And matheval to get the final quantity readInputLine( getShortcutLabel() + "_smac: CUSTOM ARG=" + getShortcutLabel() + "_ksum.n," + getShortcutLabel() + "_mtdenom," + getShortcutLabel() + "_ksum.d FUNC=x*y/z PERIODIC=NO"); diff --git a/src/symfunc/CoordShellVectorFunction.cpp b/src/symfunc/CoordShellVectorFunction.cpp index 8c0d92ef6c..684dd292d1 100644 --- a/src/symfunc/CoordShellVectorFunction.cpp +++ b/src/symfunc/CoordShellVectorFunction.cpp @@ -152,23 +152,37 @@ void CoordShellVectorFunction::registerKeywords( Keywords& keys ) { keys.add("compulsory","PSI","0.0","The Euler rotational angle psi"); keys.add("compulsory","ALPHA","3.0","The alpha parameter of the angular function that is used for FCCUBIC"); keys.addFlag("LOWMEM",false,"this flag does nothing and is present only to ensure back-compatibility"); - keys.needsAction("CONTACT_MATRIX"); keys.needsAction("FCCUBIC_FUNC"); keys.needsAction("CUSTOM"); - keys.needsAction("ONES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("CONTACT_MATRIX"); + keys.needsAction("FCCUBIC_FUNC"); + keys.needsAction("CUSTOM"); + keys.needsAction("ONES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); } CoordShellVectorFunction::CoordShellVectorFunction(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - std::string matlab, sp_str, specA, specB; bool lowmem; parseFlag("LOWMEM",lowmem); - if( lowmem ) warning("LOWMEM flag is deprecated and is no longer required for this action"); - parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); + ActionShortcut(ao) { + std::string matlab, sp_str, specA, specB; + bool lowmem; + parseFlag("LOWMEM",lowmem); + if( lowmem ) { + warning("LOWMEM flag is deprecated and is no longer required for this action"); + } + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); if( sp_str.length()>0 || specA.length()>0 ) { matlab = getShortcutLabel() + "_mat"; CoordinationNumbers::expandMatrix( true, getShortcutLabel(), sp_str, specA, specB, this ); - } else error("found no input atoms use SPECIES/SPECIESA"); - double phi, theta, psi; parse("PHI",phi); parse("THETA",theta); parse("PSI",psi); - std::vector rotelements(9); std::string xvec = matlab + ".x", yvec = matlab + ".y", zvec = matlab + ".z"; + } else { + error("found no input atoms use SPECIES/SPECIESA"); + } + double phi, theta, psi; + parse("PHI",phi); + parse("THETA",theta); + parse("PSI",psi); + std::vector rotelements(9); + std::string xvec = matlab + ".x", yvec = matlab + ".y", zvec = matlab + ".z"; if( phi!=0 || theta!=0 || psi!=0 ) { Tools::convert( std::cos(psi)*std::cos(phi)-std::cos(theta)*std::sin(phi)*std::sin(psi), rotelements[0] ); Tools::convert( std::cos(psi)*std::sin(phi)+std::cos(theta)*std::cos(phi)*std::sin(psi), rotelements[1] ); @@ -187,7 +201,8 @@ CoordShellVectorFunction::CoordShellVectorFunction(const ActionOptions& ao): } // Calculate FCC cubic function from bond vectors if( getName()=="FCCUBIC" ) { - std::string alpha; parse("ALPHA",alpha); + std::string alpha; + parse("ALPHA",alpha); readInputLine( getShortcutLabel() + "_vfunc: FCCUBIC_FUNC ARG=" + xvec + "," + yvec + "," + zvec+ " ALPHA=" + alpha); } else if( getName()=="TETRAHEDRAL" ) { readInputLine( getShortcutLabel() + "_r: CUSTOM ARG=" + xvec + "," + yvec + "," + zvec + " PERIODIC=NO FUNC=sqrt(x*x+y*y+z*z)"); @@ -198,18 +213,22 @@ CoordShellVectorFunction::CoordShellVectorFunction(const ActionOptions& ao): readInputLine( getShortcutLabel() + "_vfunc: CUSTOM ARG=" + xvec + "," + yvec + "," + zvec + "," + getShortcutLabel() + "_r" + " VAR=x,y,z,r PERIODIC=NO FUNC=(x^4+y^4+z^4)/(r^4)" ); } else { - std::string myfunc; parse("FUNCTION",myfunc); + std::string myfunc; + parse("FUNCTION",myfunc); if( myfunc.find("r")!=std::string::npos ) { readInputLine( getShortcutLabel() + "_r: CUSTOM ARG=" + xvec + "," + yvec + "," + zvec + " PERIODIC=NO FUNC=sqrt(x*x+y*y+z*z)"); readInputLine( getShortcutLabel() + "_vfunc: CUSTOM ARG=" + xvec + "," + yvec + "," + zvec + "," + getShortcutLabel() + "_r VAR=x,y,z,r PERIODIC=NO FUNC=" + myfunc ); - } else readInputLine( getShortcutLabel() + "_vfunc: CUSTOM ARG=" + xvec + "," + yvec + "," + zvec + " PERIODIC=NO FUNC=" + myfunc ); + } else { + readInputLine( getShortcutLabel() + "_vfunc: CUSTOM ARG=" + xvec + "," + yvec + "," + zvec + " PERIODIC=NO FUNC=" + myfunc ); + } } // Hadamard product of function above and weights readInputLine( getShortcutLabel() + "_wvfunc: CUSTOM ARG=" + getShortcutLabel() + "_vfunc," + matlab + ".w FUNC=x*y PERIODIC=NO"); // And coordination numbers ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_mat"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); readInputLine( getShortcutLabel() + ": MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_wvfunc," + getShortcutLabel() + "_ones"); std::string olab=getShortcutLabel(); @@ -221,7 +240,8 @@ CoordShellVectorFunction::CoordShellVectorFunction(const ActionOptions& ao): readInputLine( getShortcutLabel() + "_n: CUSTOM ARG=" + getShortcutLabel() + "," + getShortcutLabel() + "_denom FUNC=x/y PERIODIC=NO"); } // And expand the functions - std::map keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); multicolvar::MultiColvarShortcuts::expandFunctions( getShortcutLabel(), olab, "", keymap, this ); } diff --git a/src/symfunc/CoordinationNumbers.cpp b/src/symfunc/CoordinationNumbers.cpp index 39271e71e2..abc1497958 100644 --- a/src/symfunc/CoordinationNumbers.cpp +++ b/src/symfunc/CoordinationNumbers.cpp @@ -111,12 +111,15 @@ void CoordinationNumbers::shortcutKeywords( Keywords& keys ) { keys.add("compulsory","R_0","The r_0 parameter of the switching function"); keys.add("optional","SWITCH","the switching function that it used in the construction of the contact matrix"); multicolvar::MultiColvarShortcuts::shortcutKeywords( keys ); - keys.needsAction("CONTACT_MATRIX"); keys.needsAction("GROUP"); + keys.needsAction("CONTACT_MATRIX"); + keys.needsAction("GROUP"); } void CoordinationNumbers::expandMatrix( const bool& components, const std::string& lab, const std::string& sp_str, const std::string& spa_str, const std::string& spb_str, ActionShortcut* action ) { - if( sp_str.length()==0 && spa_str.length()==0 ) return; + if( sp_str.length()==0 && spa_str.length()==0 ) { + return; + } std::string matinp = lab + "_mat: CONTACT_MATRIX"; if( sp_str.length()>0 ) { @@ -127,16 +130,27 @@ void CoordinationNumbers::expandMatrix( const bool& components, const std::strin action->readInputLine( lab + "_grp: GROUP ATOMS=" + spa_str ); } - std::string sw_str; action->parse("SWITCH",sw_str); + std::string sw_str; + action->parse("SWITCH",sw_str); if( sw_str.length()>0 ) { matinp += " SWITCH={" + sw_str + "}"; } else { - std::string r0; action->parse("R_0",r0); std::string d0; action->parse("D_0",d0); - if( r0.length()==0 ) action->error("missing switching function parameters use SWITCH/R_0"); - std::string nn; action->parse("NN",nn); std::string mm; action->parse("MM",mm); + std::string r0; + action->parse("R_0",r0); + std::string d0; + action->parse("D_0",d0); + if( r0.length()==0 ) { + action->error("missing switching function parameters use SWITCH/R_0"); + } + std::string nn; + action->parse("NN",nn); + std::string mm; + action->parse("MM",mm); matinp += " R_0=" + r0 + " D_0=" + d0 + " NN=" + nn + " MM=" + mm; } - if( components ) matinp += " COMPONENTS"; + if( components ) { + matinp += " COMPONENTS"; + } action->readInputLine( matinp ); } @@ -146,47 +160,68 @@ void CoordinationNumbers::registerKeywords( Keywords& keys ) { keys.addFlag("LOWMEM",false,"this flag does nothing and is present only to ensure back-compatibility"); keys.add("optional","MOMENTS","the list of moments that you would like to calculate"); keys.addOutputComponent("moment","MOMENTS","the moments of the distribution"); - keys.needsAction("MATRIX_VECTOR_PRODUCT"); keys.needsAction("ONES"); keys.needsAction("MOMENTS"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("ONES"); + keys.needsAction("MOMENTS"); } CoordinationNumbers::CoordinationNumbers(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - bool lowmem; parseFlag("LOWMEM",lowmem); - if( lowmem ) warning("LOWMEM flag is deprecated and is no longer required for this action"); + ActionShortcut(ao) { + bool lowmem; + parseFlag("LOWMEM",lowmem); + if( lowmem ) { + warning("LOWMEM flag is deprecated and is no longer required for this action"); + } // Setup the contract matrix if that is what is needed std::string matlab, sp_str, specA, specB; - parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); if( sp_str.length()>0 || specA.length()>0 ) { - matlab = getShortcutLabel() + "_mat"; bool comp=false; - if( getName()=="COORDINATION_MOMENTS" ) { comp=true; matlab = getShortcutLabel() + "_mat"; } + matlab = getShortcutLabel() + "_mat"; + bool comp=false; + if( getName()=="COORDINATION_MOMENTS" ) { + comp=true; + matlab = getShortcutLabel() + "_mat"; + } expandMatrix( comp, getShortcutLabel(), sp_str, specA, specB, this ); - } else error("missing atoms input use SPECIES or SPECIESA/SPECIESB"); + } else { + error("missing atoms input use SPECIES or SPECIESA/SPECIESB"); + } ActionWithValue* mb=plumed.getActionSet().selectWithLabel( matlab ); - if( !mb ) error("could not find action with name " + matlab ); + if( !mb ) { + error("could not find action with name " + matlab ); + } Value* arg=mb->copyOutput(0); - if( arg->getRank()!=2 || arg->hasDerivatives() ) error("the input to this action should be a matrix or scalar"); + if( arg->getRank()!=2 || arg->hasDerivatives() ) { + error("the input to this action should be a matrix or scalar"); + } // Create vector of ones to multiply input matrix by - std::string nones; Tools::convert( arg->getShape()[1], nones ); + std::string nones; + Tools::convert( arg->getShape()[1], nones ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + nones ); if( getName()=="COORDINATION_MOMENTS" ) { // Calculate the lengths of the vectors - std::string r_power; parse("R_POWER",r_power); + std::string r_power; + parse("R_POWER",r_power); readInputLine( getShortcutLabel() + "_pow: CUSTOM ARG=" + matlab + ".x," + matlab + ".y," + matlab + ".z," + matlab + ".w VAR=x,y,z,w " + "PERIODIC=NO FUNC=w*(sqrt(x*x+y*y+z*z)^" + r_power +")"); matlab = getShortcutLabel() + "_pow"; } // Calcualte coordination numbers as matrix vector times vector of ones readInputLine( getShortcutLabel() + ": MATRIX_VECTOR_PRODUCT ARG=" + matlab + "," + getShortcutLabel() + "_ones"); - std::vector moments; parseVector("MOMENTS",moments); Tools::interpretRanges( moments ); + std::vector moments; + parseVector("MOMENTS",moments); + Tools::interpretRanges( moments ); readInputLine( getShortcutLabel() + "_caverage: MEAN ARG=" + getShortcutLabel() + " PERIODIC=NO"); for(unsigned i=0; i keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); multicolvar::MultiColvarShortcuts::expandFunctions( getShortcutLabel(), getShortcutLabel(), "", keymap, this ); } diff --git a/src/symfunc/CylindricalHarmonic.cpp b/src/symfunc/CylindricalHarmonic.cpp index 727f4cbcc6..ea5cd5b471 100644 --- a/src/symfunc/CylindricalHarmonic.cpp +++ b/src/symfunc/CylindricalHarmonic.cpp @@ -74,22 +74,39 @@ void CylindricalHarmonic::registerKeywords( Keywords& keys ) { void CylindricalHarmonic::read( ActionWithArguments* action ) { parse(action,"DEGREE",tmom); action->log.printf(" calculating %dth order cylindrical harmonic with %s and %s as input \n", tmom, action->getPntrToArgument(0)->getName().c_str(), action->getPntrToArgument(1)->getName().c_str() ); - if( action->getNumberOfArguments()==3 ) action->log.printf(" multiplying cylindrical harmonic by weight from %s \n", action->getPntrToArgument(2)->getName().c_str() ); + if( action->getNumberOfArguments()==3 ) { + action->log.printf(" multiplying cylindrical harmonic by weight from %s \n", action->getPntrToArgument(2)->getName().c_str() ); + } } void CylindricalHarmonic::setPeriodicityForOutputs( ActionWithValue* action ) { - action->componentIsNotPeriodic("rm"); action->componentIsNotPeriodic("im"); + action->componentIsNotPeriodic("rm"); + action->componentIsNotPeriodic("im"); } void CylindricalHarmonic::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { - double dlen2 = args[0]*args[0] + args[1]*args[1]; double dlen = sqrt( dlen2 ); double dlen3 = dlen2*dlen; - std::complex com1( args[0]/dlen,args[1]/dlen ); double weight=1; if( args.size()==3 ) weight=args[2]; - std::complex ppp = pow( com1, tmom-1 ), ii( 0, 1 ); double real_z = real( ppp*com1 ), imag_z = imag( ppp*com1 ); + double dlen2 = args[0]*args[0] + args[1]*args[1]; + double dlen = sqrt( dlen2 ); + double dlen3 = dlen2*dlen; + std::complex com1( args[0]/dlen,args[1]/dlen ); + double weight=1; + if( args.size()==3 ) { + weight=args[2]; + } + std::complex ppp = pow( com1, tmom-1 ), ii( 0, 1 ); + double real_z = real( ppp*com1 ), imag_z = imag( ppp*com1 ); std::complex dp_x = static_cast(tmom)*ppp*( (1.0/dlen)-(args[0]*args[0])/dlen3-ii*(args[0]*args[1])/dlen3 ); std::complex dp_y = static_cast(tmom)*ppp*( ii*(1.0/dlen)-(args[0]*args[1])/dlen3-ii*(args[1]*args[1])/dlen3 ); - vals[0] = weight*real_z; derivatives(0,0) = weight*real(dp_x); derivatives(0,1) = weight*real(dp_y); - vals[1] = weight*imag_z; derivatives(1,0) = weight*imag(dp_x); derivatives(1,1) = weight*imag(dp_y); - if( args.size()==3 ) { derivatives(0,2) = real_z; derivatives(1,2) = imag_z; } + vals[0] = weight*real_z; + derivatives(0,0) = weight*real(dp_x); + derivatives(0,1) = weight*real(dp_y); + vals[1] = weight*imag_z; + derivatives(1,0) = weight*imag(dp_x); + derivatives(1,1) = weight*imag(dp_y); + if( args.size()==3 ) { + derivatives(0,2) = real_z; + derivatives(1,2) = imag_z; + } } } diff --git a/src/symfunc/Fccubic.cpp b/src/symfunc/Fccubic.cpp index b680e62a8d..b5f90ee048 100644 --- a/src/symfunc/Fccubic.cpp +++ b/src/symfunc/Fccubic.cpp @@ -112,7 +112,8 @@ void Fccubic::read( ActionWithArguments* action ) { // Scaling factors such that '1' corresponds to fcc lattice // and '0' corresponds to isotropic (liquid) parse(action,"ALPHA",alpha); - a1 = 80080. / (2717. + 16*alpha); b1 = 16.*(alpha-143)/(2717+16*alpha); + a1 = 80080. / (2717. + 16*alpha); + b1 = 16.*(alpha-143)/(2717+16*alpha); action->log.printf(" setting alpha paramter equal to %f \n",alpha); } diff --git a/src/symfunc/HexaticParameter.cpp b/src/symfunc/HexaticParameter.cpp index 904e4d4d8f..f2c021ad56 100644 --- a/src/symfunc/HexaticParameter.cpp +++ b/src/symfunc/HexaticParameter.cpp @@ -62,29 +62,39 @@ void HexacticParameter::registerKeywords( Keywords& keys ) { keys.addOutputComponent("_vmean","VMEAN","the norm of the mean vector"); keys.addFlag("VSUM",false,"calculate the norm of the sum of all the vectors"); keys.addOutputComponent("_vsum","VSUM","the norm of the mean vector"); - keys.needsAction("CYLINDRICAL_HARMONIC_MATRIX"); keys.needsAction("ONES"); - keys.needsAction("MATRIX_VECTOR_PRODUCT"); keys.needsAction("CUSTOM"); - keys.needsAction("MEAN"); keys.needsAction("SUM"); keys.needsAction("COMBINE"); + keys.needsAction("CYLINDRICAL_HARMONIC_MATRIX"); + keys.needsAction("ONES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("CUSTOM"); + keys.needsAction("MEAN"); + keys.needsAction("SUM"); + keys.needsAction("COMBINE"); } HexacticParameter::HexacticParameter( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - std::string sp_str, specA, specB; parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); + ActionShortcut(ao) { + std::string sp_str, specA, specB; + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); CoordinationNumbers::expandMatrix( true, getShortcutLabel(), sp_str, specA, specB, this ); - std::string myplane; parse("PLANE",myplane); + std::string myplane; + parse("PLANE",myplane); if( myplane=="xy" ) { readInputLine( getShortcutLabel() + ": CYLINDRICAL_HARMONIC_MATRIX DEGREE=6 ARG=" + getShortcutLabel() + "_mat.x," + getShortcutLabel() + "_mat.y," + getShortcutLabel() + "_mat.w" ); } else if( myplane=="xz" ) { readInputLine( getShortcutLabel() + ": CYLINDRICAL_HARMONIC_MATRIX DEGREE=6 ARG=" + getShortcutLabel() + "_mat.x," + getShortcutLabel() + "_mat.z," + getShortcutLabel() + "_mat.w" ); } else if( myplane=="yz" ) { readInputLine( getShortcutLabel() + ": CYLINDRICAL_HARMONIC_MATRIX DEGREE=6 ARG=" + getShortcutLabel() + "_mat.y," + getShortcutLabel() + "_mat.z," + getShortcutLabel() + "_mat.w" ); - } else error("invalid input for plane -- should be xy, xz or yz"); + } else { + error("invalid input for plane -- should be xy, xz or yz"); + } // And coordination number ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_mat"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); readInputLine( getShortcutLabel() + "_rm: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + ".rm," + getShortcutLabel() + "_ones"); readInputLine( getShortcutLabel() + "_im: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + ".im," + getShortcutLabel() + "_ones"); @@ -96,7 +106,8 @@ HexacticParameter::HexacticParameter( const ActionOptions& ao): readInputLine( getShortcutLabel() + "_imn: CUSTOM ARG=" + getShortcutLabel() + "_im," + getShortcutLabel() + "_denom FUNC=x/y PERIODIC=NO"); // If we are doing VMEAN determine sum of vector components - bool do_vmean; parseFlag("VMEAN",do_vmean); + bool do_vmean; + parseFlag("VMEAN",do_vmean); if( do_vmean ) { // Real part readInputLine( getShortcutLabel() + "_rms: MEAN ARG=" + getShortcutLabel() + "_rmn PERIODIC=NO"); @@ -105,7 +116,8 @@ HexacticParameter::HexacticParameter( const ActionOptions& ao): // Now calculate the total length of the vector createVectorNormInput( getShortcutLabel(), getShortcutLabel() + "_vmean", "ms" ); } - bool do_vsum; parseFlag("VSUM",do_vsum); + bool do_vsum; + parseFlag("VSUM",do_vsum); if( do_vsum ) { // Real part readInputLine( getShortcutLabel() + "_rmz: SUM ARG=" + getShortcutLabel() + "_rmn PERIODIC=NO"); diff --git a/src/symfunc/LocalAverage.cpp b/src/symfunc/LocalAverage.cpp index 6c52ff3f4e..7ca8e1b31f 100644 --- a/src/symfunc/LocalAverage.cpp +++ b/src/symfunc/LocalAverage.cpp @@ -98,30 +98,43 @@ PLUMED_REGISTER_ACTION(LocalAverage,"LOCAL_AVERAGE") void LocalAverage::registerKeywords( Keywords& keys ) { CoordinationNumbers::shortcutKeywords( keys ); - keys.needsAction("ONES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); - keys.needsAction("VSTACK"); keys.needsAction("CUSTOM"); keys.needsAction("OUTER_PRODUCT"); + keys.needsAction("ONES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("VSTACK"); + keys.needsAction("CUSTOM"); + keys.needsAction("OUTER_PRODUCT"); } LocalAverage::LocalAverage(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - std::string sp_str, specA, specB; parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); + ActionShortcut(ao) { + std::string sp_str, specA, specB; + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); CoordinationNumbers::expandMatrix( false, getShortcutLabel(), sp_str, specA, specB, this ); - std::map keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); - if( sp_str.length()>0 ) specA=specB=sp_str; + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + if( sp_str.length()>0 ) { + specA=specB=sp_str; + } // Calculate the coordination numbers ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_mat"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); readInputLine( getShortcutLabel() + "_coord: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_mat," + getShortcutLabel() + "_ones" ); - int l=-1; std::vector shortcuts=plumed.getActionSet().select(); + int l=-1; + std::vector shortcuts=plumed.getActionSet().select(); for(unsigned i=0; igetShortcutLabel() ) { std::string sname = shortcuts[i]->getName(); - if( sname=="Q1" || sname=="Q3" || sname=="Q4" || sname=="Q6" ) { Tools::convert( sname.substr(1), l ); break; } + if( sname=="Q1" || sname=="Q3" || sname=="Q4" || sname=="Q6" ) { + Tools::convert( sname.substr(1), l ); + break; + } } } @@ -135,14 +148,21 @@ LocalAverage::LocalAverage(const ActionOptions&ao): if( !plumed.getActionSet().selectWithLabel(specB + "_imn-" + num) ) { readInputLine( specB + "_imn-" + num + ": CUSTOM ARG=" + specB + "_sp.im-" + num + "," + specB + "_denom FUNC=x/y PERIODIC=NO"); } - if( i==-l ) { vargs = "ARG=" + specB + "_rmn-" + num + "," + specB + "_imn-" + num; svargs = "ARG=" + getShortcutLabel() + "_prod." + specB + "_rmn-" + num + "," + getShortcutLabel() + "_prod." + specB + "_imn-" + num; } - else { vargs += "," + specB + "_rmn-" + num + "," + specB + "_imn-" + num; svargs += "," + getShortcutLabel() + "_prod." + specB + "_rmn-" + num + "," + getShortcutLabel() + "_prod." + specB + "_imn-" + num; } + if( i==-l ) { + vargs = "ARG=" + specB + "_rmn-" + num + "," + specB + "_imn-" + num; + svargs = "ARG=" + getShortcutLabel() + "_prod." + specB + "_rmn-" + num + "," + getShortcutLabel() + "_prod." + specB + "_imn-" + num; + } else { + vargs += "," + specB + "_rmn-" + num + "," + specB + "_imn-" + num; + svargs += "," + getShortcutLabel() + "_prod." + specB + "_rmn-" + num + "," + getShortcutLabel() + "_prod." + specB + "_imn-" + num; + } sargs += "," + specB + "_rmn-" + num + "," + specB + "_imn-" + num; } readInputLine( getShortcutLabel() + "_vstack: VSTACK " + vargs ); readInputLine( getShortcutLabel() + "_prod: MATRIX_VECTOR_PRODUCT " + sargs ); readInputLine( getShortcutLabel() + "_vpstack: VSTACK " + svargs ); - std::string twolplusone; Tools::convert( 2*(2*l+1), twolplusone ); readInputLine( getShortcutLabel() + "_lones: ONES SIZE=" + twolplusone ); + std::string twolplusone; + Tools::convert( 2*(2*l+1), twolplusone ); + readInputLine( getShortcutLabel() + "_lones: ONES SIZE=" + twolplusone ); readInputLine( getShortcutLabel() + "_unorm: OUTER_PRODUCT ARG=" + getShortcutLabel() + "_coord," + getShortcutLabel() + "_lones" ); readInputLine( getShortcutLabel() + "_av: CUSTOM ARG=" + getShortcutLabel() + "_vpstack," + getShortcutLabel() + "_vstack," + getShortcutLabel() + "_unorm FUNC=(x+y)/(1+z) PERIODIC=NO"); readInputLine( getShortcutLabel() + "_av2: CUSTOM ARG=" + getShortcutLabel() + "_av FUNC=x*x PERIODIC=NO"); @@ -157,10 +177,12 @@ LocalAverage::LocalAverage(const ActionOptions&ao): std::string LocalAverage::getMomentumSymbol( const int& m ) const { if( m<0 ) { - std::string num; Tools::convert( -1*m, num ); + std::string num; + Tools::convert( -1*m, num ); return "n" + num; } else if( m>0 ) { - std::string num; Tools::convert( m, num ); + std::string num; + Tools::convert( m, num ); return "p" + num; } return "0"; diff --git a/src/symfunc/LocalCrystalinity.cpp b/src/symfunc/LocalCrystalinity.cpp index a06d7b6433..88761a5d8f 100644 --- a/src/symfunc/LocalCrystalinity.cpp +++ b/src/symfunc/LocalCrystalinity.cpp @@ -54,29 +54,40 @@ PLUMED_REGISTER_ACTION(LocalCrystallinity,"LOCAL_CRYSTALINITY") void LocalCrystallinity::registerKeywords( Keywords& keys ) { CoordinationNumbers::shortcutKeywords( keys ); keys.add("numbered","GVECTOR","the coefficients of the linear combinations to compute for the CV"); - keys.needsAction("ONES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); - keys.needsAction("COMBINE"); keys.needsAction("CUSTOM"); + keys.needsAction("ONES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("COMBINE"); + keys.needsAction("CUSTOM"); } LocalCrystallinity::LocalCrystallinity( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // This builds an adjacency matrix - std::string sp_str, specA, specB; parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); + std::string sp_str, specA, specB; + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); CoordinationNumbers::expandMatrix( true, getShortcutLabel(), sp_str, specA, specB, this ); // Input for denominator (coord) ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_mat"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); readInputLine( getShortcutLabel() + "_denom: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_mat.w," + getShortcutLabel() + "_ones"); // Input for numerator std::string finput = ""; for(unsigned i=1;; ++i) { - std::vector gvec; std::string istr; Tools::convert( i, istr ); - if( !parseNumberedVector("GVECTOR",i,gvec) ) { break; } - if( gvec.size()!=3 ) error("gvectors should have size 3"); + std::vector gvec; + std::string istr; + Tools::convert( i, istr ); + if( !parseNumberedVector("GVECTOR",i,gvec) ) { + break; + } + if( gvec.size()!=3 ) { + error("gvectors should have size 3"); + } // This is the dot product between the input gvector and the bond vector readInputLine( getShortcutLabel() + "_dot" + istr + ": COMBINE ARG=" + getShortcutLabel() + "_mat.x," + getShortcutLabel() + "_mat.y," + getShortcutLabel() + "_mat.z " "PERIODIC=NO COEFFICIENTS=" + gvec[0] + "," + gvec[1] + "," + gvec[2] ); @@ -92,7 +103,9 @@ LocalCrystallinity::LocalCrystallinity( const ActionOptions& ao): // And work out the square modulus of this complex number readInputLine( getShortcutLabel() + "_" + istr + ": CUSTOM FUNC=x*x+y*y PERIODIC=NO ARG=" + getShortcutLabel() + "_cosmean" + istr + "," + getShortcutLabel() + "_sinmean" + istr); // These are all the kvectors that we are adding together in the final combine for the final CV - if( i>1 ) finput += ","; + if( i>1 ) { + finput += ","; + } finput += getShortcutLabel() + "_" + istr; } // This computes the final CV diff --git a/src/symfunc/LocalSteinhardt.cpp b/src/symfunc/LocalSteinhardt.cpp index 06e1800eb3..779f455696 100644 --- a/src/symfunc/LocalSteinhardt.cpp +++ b/src/symfunc/LocalSteinhardt.cpp @@ -293,25 +293,34 @@ void LocalSteinhardt::registerKeywords( Keywords& keys ) { "When this keyword is present you no longer need the NN, MM, D_0 and R_0 keywords."); keys.addFlag("LOWMEM",false,"this flag does nothing and is present only to ensure back-compatibility"); multicolvar::MultiColvarShortcuts::shortcutKeywords( keys ); - keys.needsAction("CONTACT_MATRIX"); keys.needsAction("MATRIX_PRODUCT"); keys.needsAction("GROUP"); - keys.needsAction("ONES"); keys.needsAction("OUTER_PRODUCT"); keys.needsAction("VSTACK"); - keys.needsAction("CONCATENATE"); keys.needsAction("CUSTOM"); keys.needsAction("TRANSPOSE"); + keys.needsAction("CONTACT_MATRIX"); + keys.needsAction("MATRIX_PRODUCT"); + keys.needsAction("GROUP"); + keys.needsAction("ONES"); + keys.needsAction("OUTER_PRODUCT"); + keys.needsAction("VSTACK"); + keys.needsAction("CONCATENATE"); + keys.needsAction("CUSTOM"); + keys.needsAction("TRANSPOSE"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); } std::string LocalSteinhardt::getSymbol( const int& m ) const { if( m<0 ) { - std::string num; Tools::convert( -1*m, num ); + std::string num; + Tools::convert( -1*m, num ); return "n" + num; } else if( m>0 ) { - std::string num; Tools::convert( m, num ); + std::string num; + Tools::convert( m, num ); return "p" + num; } return "0"; } std::string LocalSteinhardt::getArgsForStack( const int& l, const std::string& sp_lab ) const { - std::string numstr; Tools::convert( l, numstr ); + std::string numstr; + Tools::convert( l, numstr ); std::string data_mat = " ARG=" + sp_lab + "_sp.rm-n" + numstr + "," + sp_lab + "_sp.im-n" + numstr; for(int i=-l+1; i<=l; ++i) { numstr = getSymbol( i ); @@ -322,18 +331,24 @@ std::string LocalSteinhardt::getArgsForStack( const int& l, const std::string& s LocalSteinhardt::LocalSteinhardt(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - bool lowmem; parseFlag("LOWMEM",lowmem); - if( lowmem ) warning("LOWMEM flag is deprecated and is no longer required for this action"); + ActionShortcut(ao) { + bool lowmem; + parseFlag("LOWMEM",lowmem); + if( lowmem ) { + warning("LOWMEM flag is deprecated and is no longer required for this action"); + } // Get the Q value - int l; Tools::convert( getName().substr(7), l); + int l; + Tools::convert( getName().substr(7), l); // Create a vector filled with ones - std::string twolplusone; Tools::convert( 2*(2*l+1), twolplusone ); + std::string twolplusone; + Tools::convert( 2*(2*l+1), twolplusone ); readInputLine( getShortcutLabel() + "_uvec: ONES SIZE=" + twolplusone ); // Read in species keyword - std::string sp_str; parse("SPECIES",sp_str); - std::string spa_str; parse("SPECIESA",spa_str); + std::string sp_str; + parse("SPECIES",sp_str); + std::string spa_str; + parse("SPECIESA",spa_str); if( sp_str.length()>0 ) { // Create a group with these atoms readInputLine( getShortcutLabel() + "_grp: GROUP ATOMS=" + sp_str ); @@ -346,12 +361,15 @@ LocalSteinhardt::LocalSteinhardt(const ActionOptions& ao): readInputLine( getShortcutLabel() + "_uvecs: VSTACK" + getArgsForStack( l, sp_lab[0] ) ); } else { std::string len_vec = getShortcutLabel() + "_mags: CONCATENATE ARG=" + sp_lab[0] + "_norm"; - for(unsigned i=1; i0 ) { // Create a group with these atoms readInputLine( getShortcutLabel() + "_grp: GROUP ATOMS=" + spa_str ); - std::string spb_str; parse("SPECIESB",spb_str); - if( spb_str.length()==0 ) plumed_merror("need both SPECIESA and SPECIESB in input"); + std::string spb_str; + parse("SPECIESB",spb_str); + if( spb_str.length()==0 ) { + plumed_merror("need both SPECIESA and SPECIESB in input"); + } std::vector sp_laba = Tools::getWords(spa_str, "\t\n ,"); std::vector sp_labb = Tools::getWords(spb_str, "\t\n ,"); if( sp_laba.size()==1 ) { @@ -381,12 +404,15 @@ LocalSteinhardt::LocalSteinhardt(const ActionOptions& ao): readInputLine( getShortcutLabel() + "_uvecsA: VSTACK" + getArgsForStack( l, sp_laba[0] ) ); } else { std::string len_vec = getShortcutLabel() + "_magsA: CONCATENATE ARG=" + sp_laba[0] + "_norm"; - for(unsigned i=1; i( getShortcutLabel() + "_cmap"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); readInputLine( getShortcutLabel() + ": MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() +"_prod," + getShortcutLabel() +"_ones"); // And just the sum of the coordination numbers diff --git a/src/symfunc/RadialTetra.cpp b/src/symfunc/RadialTetra.cpp index 8b7b386474..5b23ae7ae2 100644 --- a/src/symfunc/RadialTetra.cpp +++ b/src/symfunc/RadialTetra.cpp @@ -51,26 +51,43 @@ void RadialTetra::registerKeywords( Keywords& keys ) { CoordinationNumbers::shortcutKeywords( keys ); keys.addFlag("NOPBC",false,"ignore the periodic boundary conditions when calculating distances"); keys.add("compulsory","CUTOFF","-1","ignore distances that have a value larger than this cutoff"); - keys.remove("NN"); keys.remove("MM"); keys.remove("D_0"); keys.remove("R_0"); keys.remove("SWITCH"); - keys.needsAction("DISTANCE_MATRIX"); keys.needsAction("NEIGHBORS"); - keys.needsAction("CUSTOM"); keys.needsAction("ONES"); + keys.remove("NN"); + keys.remove("MM"); + keys.remove("D_0"); + keys.remove("R_0"); + keys.remove("SWITCH"); + keys.needsAction("DISTANCE_MATRIX"); + keys.needsAction("NEIGHBORS"); + keys.needsAction("CUSTOM"); + keys.needsAction("ONES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); } RadialTetra::RadialTetra( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Read species input and create the matrix - bool nopbc; parseFlag("NOPBC",nopbc); - std::string pbcstr=""; if( nopbc ) pbcstr = " NOPBC"; - std::string sp_str, rcut; parse("SPECIES",sp_str); parse("CUTOFF",rcut); + bool nopbc; + parseFlag("NOPBC",nopbc); + std::string pbcstr=""; + if( nopbc ) { + pbcstr = " NOPBC"; + } + std::string sp_str, rcut; + parse("SPECIES",sp_str); + parse("CUTOFF",rcut); if( sp_str.length()>0 ) { readInputLine( getShortcutLabel() + "_mat: DISTANCE_MATRIX GROUP=" + sp_str + " CUTOFF=" + rcut + pbcstr ); } else { - std::string specA, specB; parse("SPECIESA",specA); parse("SPECIESB",specB); - if( specA.length()==0 ) error("missing input atoms"); - if( specB.length()==0 ) error("missing SPECIESB keyword"); + std::string specA, specB; + parse("SPECIESA",specA); + parse("SPECIESB",specB); + if( specA.length()==0 ) { + error("missing input atoms"); + } + if( specB.length()==0 ) { + error("missing SPECIESB keyword"); + } readInputLine( getShortcutLabel() + "_mat: DISTANCE_MATRIX GROUPA=" + specA + " GROUPB=" + specB + " CUTOFF=" + rcut + pbcstr); } // Get the neighbors matrix @@ -80,7 +97,8 @@ RadialTetra::RadialTetra( const ActionOptions& ao): //Now compute sum of four nearest distances ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_mat"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); readInputLine( getShortcutLabel() + "_sum4: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_near4," + getShortcutLabel() + "_ones"); // Now compute squares of four nearest distance @@ -93,7 +111,8 @@ RadialTetra::RadialTetra( const ActionOptions& ao): readInputLine( getShortcutLabel() + ": CUSTOM ARG=" + getShortcutLabel() + "_sum4," + getShortcutLabel() + "_sum4_2," + getShortcutLabel() + "_meanr " + "FUNC=(1-(y-x*z)/(12*z*z)) PERIODIC=NO"); // And get the things to do with the quantities we have computed - std::map keymap; multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); + std::map keymap; + multicolvar::MultiColvarShortcuts::readShortcutKeywords( keymap, this ); multicolvar::MultiColvarShortcuts::expandFunctions( getShortcutLabel(), getShortcutLabel(), "", keymap, this ); } diff --git a/src/symfunc/SMAC.cpp b/src/symfunc/SMAC.cpp index f988afffb5..ee89f47282 100644 --- a/src/symfunc/SMAC.cpp +++ b/src/symfunc/SMAC.cpp @@ -59,25 +59,34 @@ void SMAC::registerKeywords(Keywords& keys) { keys.add("optional","SWITCH_COORD","This keyword is used to define the coordination switching function."); keys.reset_style("KERNEL","optional"); multicolvar::MultiColvarShortcuts::shortcutKeywords( keys ); - keys.needsAction("VSTACK"); keys.needsAction("TRANSPOSE"); keys.needsAction("CONTACT_MATRIX"); - keys.needsAction("TORSIONS_MATRIX"); keys.needsAction("COMBINE"); keys.needsAction("CUSTOM"); - keys.needsAction("ONES"); keys.needsAction("MATRIX_VECTOR_PRODUCT"); keys.needsAction("MORE_THAN"); + keys.needsAction("VSTACK"); + keys.needsAction("TRANSPOSE"); + keys.needsAction("CONTACT_MATRIX"); + keys.needsAction("TORSIONS_MATRIX"); + keys.needsAction("COMBINE"); + keys.needsAction("CUSTOM"); + keys.needsAction("ONES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("MORE_THAN"); } SMAC::SMAC(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Create the matrices - std::string sw_input; parse("SWITCH",sw_input); - std::string sp_lab, sp_laba; parse("SPECIES",sp_lab); parse("SPECIESA",sp_laba); + std::string sw_input; + parse("SWITCH",sw_input); + std::string sp_lab, sp_laba; + parse("SPECIES",sp_lab); + parse("SPECIESA",sp_laba); if( sp_lab.length()>0 ) { readInputLine( getShortcutLabel() + "_vecs: VSTACK ARG=" + sp_lab + ".x," + sp_lab + ".y," + sp_lab + ".z" ); readInputLine( getShortcutLabel() + "_vecsT: TRANSPOSE ARG=" + getShortcutLabel() + "_vecs" ); readInputLine( getShortcutLabel() + "_cmap: CONTACT_MATRIX GROUP=" + sp_lab + " SWITCH={" + sw_input + "}"); readInputLine( getShortcutLabel() + "_tpmat: TORSIONS_MATRIX ARG=" + getShortcutLabel() + "_vecs," + getShortcutLabel() + "_vecsT POSITIONS1=" + sp_lab + " POSITIONS2=" + sp_lab ); } else if( sp_laba.length()>0 ) { - std::string sp_labb; parse("SPECIESB",sp_labb); + std::string sp_labb; + parse("SPECIESB",sp_labb); readInputLine( getShortcutLabel() + "_vecsa: VSTACK ARG=" + sp_laba + ".x," + sp_laba + ".y," + sp_laba + ".z" ); readInputLine( getShortcutLabel() + "_vecsb: VSTACK ARG=" + sp_labb + ".x," + sp_labb + ".y," + sp_labb + ".z" ); readInputLine( getShortcutLabel() + "_vecsbT: TRANSPOSE ARG=" + getShortcutLabel() + "_vecsb" ); @@ -87,17 +96,32 @@ SMAC::SMAC(const ActionOptions& ao): // Now need the Gaussians std::string kmap_input= getShortcutLabel() + "_ksum: COMBINE PERIODIC=NO"; for(unsigned i=1;; ++i) { - std::string kstr_inpt, istr; Tools::convert( i, istr ); - if( !parseNumbered("KERNEL",i,kstr_inpt ) ) { break; } + std::string kstr_inpt, istr; + Tools::convert( i, istr ); + if( !parseNumbered("KERNEL",i,kstr_inpt ) ) { + break; + } std::vector words = Tools::getWords(kstr_inpt); - std::string center, var; Tools::parse(words,"CENTER",center); Tools::parse(words,"SIGMA",var); - double nsig; Tools::convert( var, nsig ); std::string coeff; Tools::convert( 1/(nsig*nsig), coeff ); + std::string center, var; + Tools::parse(words,"CENTER",center); + Tools::parse(words,"SIGMA",var); + double nsig; + Tools::convert( var, nsig ); + std::string coeff; + Tools::convert( 1/(nsig*nsig), coeff ); readInputLine( getShortcutLabel() + "_kf" + istr + "_r2: COMBINE PERIODIC=NO ARG=" + getShortcutLabel() + "_tpmat COEFFICIENTS=" + coeff + " PARAMETERS=" + center + " POWERS=2"); - if( words[0]=="GAUSSIAN" ) readInputLine( getShortcutLabel() + "_kf" + istr + ": CUSTOM PERIODIC=NO FUNC=exp(-x/2) ARG=" + getShortcutLabel() + "_kf" + istr + "_r2" ); - else if( words[0]=="TRIANGULAR" ) readInputLine( getShortcutLabel() + "_kf" + istr + ": CUSTOM PERIODIC=NO FUNC=step(1-sqrt(x))*(1-sqrt(x)) ARG=" + getShortcutLabel() + "_kf" + istr + "_r2" ); - else readInputLine( getShortcutLabel() + "_kf" + istr + ": CUSTOM PERIODIC=NO FUNC=" + words[0] + " ARG=" + getShortcutLabel() + "_kf" + istr + "_r2" ); - if( i==1 ) kmap_input += " ARG=" + getShortcutLabel() + "_kf" + istr; - else kmap_input += "," + getShortcutLabel() + "_kf" + istr; + if( words[0]=="GAUSSIAN" ) { + readInputLine( getShortcutLabel() + "_kf" + istr + ": CUSTOM PERIODIC=NO FUNC=exp(-x/2) ARG=" + getShortcutLabel() + "_kf" + istr + "_r2" ); + } else if( words[0]=="TRIANGULAR" ) { + readInputLine( getShortcutLabel() + "_kf" + istr + ": CUSTOM PERIODIC=NO FUNC=step(1-sqrt(x))*(1-sqrt(x)) ARG=" + getShortcutLabel() + "_kf" + istr + "_r2" ); + } else { + readInputLine( getShortcutLabel() + "_kf" + istr + ": CUSTOM PERIODIC=NO FUNC=" + words[0] + " ARG=" + getShortcutLabel() + "_kf" + istr + "_r2" ); + } + if( i==1 ) { + kmap_input += " ARG=" + getShortcutLabel() + "_kf" + istr; + } else { + kmap_input += "," + getShortcutLabel() + "_kf" + istr; + } } readInputLine( kmap_input ); // Now create the product matrix @@ -105,13 +129,15 @@ SMAC::SMAC(const ActionOptions& ao): // Now the sum of coordination numbers times the switching functions ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_cmap"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_ones: ONES SIZE=" + size ); readInputLine( getShortcutLabel() + ": MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_prod," + getShortcutLabel() + "_ones"); // And just the sum of the coordination numbers readInputLine( getShortcutLabel() + "_denom: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_cmap," + getShortcutLabel() + "_ones"); // And the transformed switching functions - std::string swcoord_str; parse("SWITCH_COORD",swcoord_str); + std::string swcoord_str; + parse("SWITCH_COORD",swcoord_str); readInputLine( getShortcutLabel() + "_mtdenom: MORE_THAN ARG=" + getShortcutLabel() + "_denom SWITCH={" + swcoord_str +"}"); // And matheval to get the final quantity readInputLine( getShortcutLabel() + "_smac: CUSTOM ARG=" + getShortcutLabel() + "," + getShortcutLabel() + "_mtdenom," + getShortcutLabel() + "_denom FUNC=(x*y)/z PERIODIC=NO"); diff --git a/src/symfunc/SphericalHarmonic.cpp b/src/symfunc/SphericalHarmonic.cpp index 019ca7a12e..1dfac76468 100644 --- a/src/symfunc/SphericalHarmonic.cpp +++ b/src/symfunc/SphericalHarmonic.cpp @@ -83,41 +83,57 @@ unsigned SphericalHarmonic::factorial( const unsigned& n ) const { void SphericalHarmonic::read( ActionWithArguments* action ) { parse(action,"L",tmom); action->log.printf(" calculating %dth order spherical harmonic with %s, %s and %s as input \n", tmom, action->getPntrToArgument(0)->getName().c_str(), action->getPntrToArgument(1)->getName().c_str(), action->getPntrToArgument(2)->getName().c_str() ); - if( action->getNumberOfArguments()==4 ) action->log.printf(" multiplying cylindrical harmonic by weight from %s \n", action->getPntrToArgument(3)->getName().c_str() ); + if( action->getNumberOfArguments()==4 ) { + action->log.printf(" multiplying cylindrical harmonic by weight from %s \n", action->getPntrToArgument(3)->getName().c_str() ); + } normaliz.resize( tmom+1 ); for(unsigned i=0; i<=tmom; ++i) { normaliz[i] = sqrt( (2*tmom+1)*factorial(tmom-i)/(4*pi*factorial(tmom+i)) ); - if( i%2==1 ) normaliz[i]*=-1; + if( i%2==1 ) { + normaliz[i]*=-1; + } } coeff_poly.resize( tmom+1 ); if( tmom==1 ) { // Legendre polynomial coefficients of order one - coeff_poly[0]=0; coeff_poly[1]=1.0; + coeff_poly[0]=0; + coeff_poly[1]=1.0; } else if( tmom==2 ) { // Legendre polynomial coefficients of order two - coeff_poly[0]=-0.5; coeff_poly[1]=0.0; + coeff_poly[0]=-0.5; + coeff_poly[1]=0.0; coeff_poly[2]=1.5; } else if( tmom==3 ) { // Legendre polynomial coefficients of order three - coeff_poly[0]=0.0; coeff_poly[1]=-1.5; - coeff_poly[2]=0.0; coeff_poly[3]=2.5; + coeff_poly[0]=0.0; + coeff_poly[1]=-1.5; + coeff_poly[2]=0.0; + coeff_poly[3]=2.5; } else if( tmom==4 ) { // Legendre polynomial coefficients of order four - coeff_poly[0]=0.375; coeff_poly[1]=0.0; - coeff_poly[2]=-3.75; coeff_poly[3]=0.0; + coeff_poly[0]=0.375; + coeff_poly[1]=0.0; + coeff_poly[2]=-3.75; + coeff_poly[3]=0.0; coeff_poly[4]=4.375; } else if( tmom==5 ) { // Legendre polynomial coefficients of order five - coeff_poly[0]=0.0; coeff_poly[1]=1.875; - coeff_poly[2]=0.0; coeff_poly[3]=-8.75; - coeff_poly[4]=0.0; coeff_poly[5]=7.875; + coeff_poly[0]=0.0; + coeff_poly[1]=1.875; + coeff_poly[2]=0.0; + coeff_poly[3]=-8.75; + coeff_poly[4]=0.0; + coeff_poly[5]=7.875; } else if( tmom==6 ) { // Legendre polynomial coefficients of order six - coeff_poly[0]=-0.3125; coeff_poly[1]=0.0; - coeff_poly[2]=6.5625; coeff_poly[3]=0.0; - coeff_poly[4]=-19.6875; coeff_poly[5]=0.0; + coeff_poly[0]=-0.3125; + coeff_poly[1]=0.0; + coeff_poly[2]=6.5625; + coeff_poly[3]=0.0; + coeff_poly[4]=-19.6875; + coeff_poly[5]=0.0; coeff_poly[6]=14.4375; } else { action->error("Insert Legendre polynomial coefficients into SphericalHarmonics code"); @@ -125,27 +141,41 @@ void SphericalHarmonic::read( ActionWithArguments* action ) { } std::vector SphericalHarmonic::getComponentsPerLabel() const { - std::vector comp; std::string num; + std::vector comp; + std::string num; for(int i=-tmom; i<=tmom; ++i) { Tools::convert(fabs(i),num); - if( i<0 ) comp.push_back( "-n" + num ); - else if( i>0 ) comp.push_back( "-p" + num ); - else comp.push_back( "-0"); + if( i<0 ) { + comp.push_back( "-n" + num ); + } else if( i>0 ) { + comp.push_back( "-p" + num ); + } else { + comp.push_back( "-0"); + } } return comp; } void SphericalHarmonic::setPeriodicityForOutputs( ActionWithValue* action ) { std::vector comp( getComponentsPerLabel() ); - for(unsigned i=0; icomponentIsNotPeriodic("rm" + comp[i]); action->componentIsNotPeriodic("im" + comp[i]); } + for(unsigned i=0; icomponentIsNotPeriodic("rm" + comp[i]); + action->componentIsNotPeriodic("im" + comp[i]); + } } void SphericalHarmonic::calc( const ActionWithArguments* action, const std::vector& args, std::vector& vals, Matrix& derivatives ) const { - double weight=1; if( args.size()==4 ) weight = args[3]; - if( weight com1( args[0]/dlen,args[1]/dlen ), dp_x, dp_y, dp_z; - std::complex powered = std::complex(1.0,0.0); std::complex ii( 0.0, 1.0 ); + std::complex powered = std::complex(1.0,0.0); + std::complex ii( 0.0, 1.0 ); Vector myrealvec, myimagvec, real_dz, imag_dz; // Do stuff for all other m values for(unsigned m=1; m<=tmom; ++m) { @@ -179,8 +212,12 @@ void SphericalHarmonic::calc( const ActionWithArguments* action, const std::vect dp_z = md*powered*( -(args[0]*args[2])/dlen3-ii*(args[1]*args[2])/dlen3 ); // Derivatives of real and imaginary parts of above - real_dz[0] = real( dp_x ); real_dz[1] = real( dp_y ); real_dz[2] = real( dp_z ); - imag_dz[0] = imag( dp_x ); imag_dz[1] = imag( dp_y ); imag_dz[2] = imag( dp_z ); + real_dz[0] = real( dp_x ); + real_dz[1] = real( dp_y ); + real_dz[2] = real( dp_z ); + imag_dz[0] = imag( dp_x ); + imag_dz[1] = imag( dp_y ); + imag_dz[2] = imag( dp_z ); // Complete derivative of steinhardt parameter myrealvec = weight*dpoly_ass*real_z*dz + weight*poly_ass*real_dz; @@ -203,8 +240,10 @@ void SphericalHarmonic::calc( const ActionWithArguments* action, const std::vect vals[3*tmom+1-m] = -pref*weight*itq6; addVectorDerivatives( 3*tmom+1-m, -pref*myimagvec, derivatives ); if( args.size()==4 ) { - derivatives(tmom+m,3)=tq6; derivatives(3*tmom+1+m, 3)=itq6; - derivatives(tmom-m,3)=pref*tq6; derivatives(3*tmom+1-m, 3)=-pref*itq6; + derivatives(tmom+m,3)=tq6; + derivatives(3*tmom+1+m, 3)=itq6; + derivatives(tmom-m,3)=pref*tq6; + derivatives(3*tmom+1-m, 3)=-pref*itq6; } // Calculate next power of complex number powered *= com1; @@ -213,23 +252,32 @@ void SphericalHarmonic::calc( const ActionWithArguments* action, const std::vect double SphericalHarmonic::deriv_poly( const unsigned& m, const double& val, double& df ) const { double fact=1.0; - for(unsigned j=1; j<=m; ++j) fact=fact*j; + for(unsigned j=1; j<=m; ++j) { + fact=fact*j; + } double res=coeff_poly[m]*fact; - double pow=1.0, xi=val, dxi=1.0; df=0.0; + double pow=1.0, xi=val, dxi=1.0; + df=0.0; for(int i=m+1; i<=tmom; ++i) { fact=1.0; - for(unsigned j=i-m+1; j<=i; ++j) fact=fact*j; + for(unsigned j=i-m+1; j<=i; ++j) { + fact=fact*j; + } res=res+coeff_poly[i]*fact*xi; df = df + pow*coeff_poly[i]*fact*dxi; - xi=xi*val; dxi=dxi*val; pow+=1.0; + xi=xi*val; + dxi=dxi*val; + pow+=1.0; } df = df*normaliz[m]; return normaliz[m]*res; } void SphericalHarmonic::addVectorDerivatives( const unsigned& ival, const Vector& der, Matrix& derivatives ) const { - for(unsigned j=0; j<3; ++j) derivatives(ival,j) = der[j]; + for(unsigned j=0; j<3; ++j) { + derivatives(ival,j) = der[j]; + } } } diff --git a/src/symfunc/Steinhardt.cpp b/src/symfunc/Steinhardt.cpp index 3366a0f634..3212718e31 100644 --- a/src/symfunc/Steinhardt.cpp +++ b/src/symfunc/Steinhardt.cpp @@ -284,28 +284,45 @@ void Steinhardt::registerKeywords( Keywords& keys ) { keys.addOutputComponent("_vmean","VMEAN","the norm of the mean vector"); keys.addFlag("VSUM",false,"calculate the norm of the sum of all the vectors"); keys.addOutputComponent("_vsum","VSUM","the norm of the mean vector"); - keys.needsAction("GROUP"); keys.needsAction("CONTACT_MATRIX"); keys.needsAction("SPHERICAL_HARMONIC"); keys.needsAction("ONES"); - keys.needsAction("MATRIX_VECTOR_PRODUCT"); keys.needsAction("COMBINE"); keys.needsAction("CUSTOM"); keys.needsAction("MEAN"); keys.needsAction("SUM"); + keys.needsAction("GROUP"); + keys.needsAction("CONTACT_MATRIX"); + keys.needsAction("SPHERICAL_HARMONIC"); + keys.needsAction("ONES"); + keys.needsAction("MATRIX_VECTOR_PRODUCT"); + keys.needsAction("COMBINE"); + keys.needsAction("CUSTOM"); + keys.needsAction("MEAN"); + keys.needsAction("SUM"); } Steinhardt::Steinhardt( const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - bool lowmem; parseFlag("LOWMEM",lowmem); - if( lowmem ) warning("LOWMEM flag is deprecated and is no longer required for this action"); - std::string sp_str, specA, specB; parse("SPECIES",sp_str); parse("SPECIESA",specA); parse("SPECIESB",specB); - CoordinationNumbers::expandMatrix( true, getShortcutLabel(), sp_str, specA, specB, this ); int l; + ActionShortcut(ao) { + bool lowmem; + parseFlag("LOWMEM",lowmem); + if( lowmem ) { + warning("LOWMEM flag is deprecated and is no longer required for this action"); + } + std::string sp_str, specA, specB; + parse("SPECIES",sp_str); + parse("SPECIESA",specA); + parse("SPECIESB",specB); + CoordinationNumbers::expandMatrix( true, getShortcutLabel(), sp_str, specA, specB, this ); + int l; std::string sph_input = getShortcutLabel() + "_sh: SPHERICAL_HARMONIC ARG=" + getShortcutLabel() + "_mat.x," + getShortcutLabel() + "_mat.y," + getShortcutLabel() + "_mat.z," + getShortcutLabel() + "_mat.w"; if( getName()=="Q1" ) { - sph_input +=" L=1"; l=1; + sph_input +=" L=1"; + l=1; } else if( getName()=="Q3" ) { - sph_input += " L=3"; l=3; + sph_input += " L=3"; + l=3; } else if( getName()=="Q4" ) { - sph_input += " L=4"; l=4; + sph_input += " L=4"; + l=4; } else if( getName()=="Q6" ) { - sph_input += " L=6"; l=6; + sph_input += " L=6"; + l=6; } else { plumed_merror("invalid input"); } @@ -314,15 +331,18 @@ Steinhardt::Steinhardt( const ActionOptions& ao): // Input for denominator (coord) ActionWithValue* av = plumed.getActionSet().selectWithLabel( getShortcutLabel() + "_mat"); plumed_assert( av && av->getNumberOfComponents()>0 && (av->copyOutput(0))->getRank()==2 ); - std::string size; Tools::convert( (av->copyOutput(0))->getShape()[1], size ); + std::string size; + Tools::convert( (av->copyOutput(0))->getShape()[1], size ); readInputLine( getShortcutLabel() + "_denom_ones: ONES SIZE=" + size ); readInputLine( getShortcutLabel() + "_denom: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_mat.w," + getShortcutLabel() + "_denom_ones" ); readInputLine( getShortcutLabel() + "_sp: MATRIX_VECTOR_PRODUCT ARG=" + getShortcutLabel() + "_sh.*," + getShortcutLabel() + "_denom_ones"); // If we are doing VMEAN determine sum of vector components std::string snum; - bool do_vmean; parseFlag("VMEAN",do_vmean); - bool do_vsum; parseFlag("VSUM",do_vsum); + bool do_vmean; + parseFlag("VMEAN",do_vmean); + bool do_vsum; + parseFlag("VSUM",do_vsum); if( do_vmean || do_vsum ) { // Divide all components by coordination numbers for(int i=-l; i<=l; ++i) { @@ -365,7 +385,8 @@ Steinhardt::Steinhardt( const ActionOptions& ao): } void Steinhardt::createVectorNormInput( const std::string& ilab, const std::string& olab, const int& l, const std::string& sep, const std::string& vlab ) { - std::string arg_inp, norm_input = olab + "2: COMBINE PERIODIC=NO POWERS=2,2"; std::string snum = getSymbol( -l ); + std::string arg_inp, norm_input = olab + "2: COMBINE PERIODIC=NO POWERS=2,2"; + std::string snum = getSymbol( -l ); arg_inp = " ARG=" + ilab + sep + "r" + vlab + "-" + snum +"," + ilab + sep + "i" + vlab + "-" + snum; for(int i=-l+1; i<=l; ++i) { snum = getSymbol( i ); @@ -378,10 +399,12 @@ void Steinhardt::createVectorNormInput( const std::string& ilab, const std::stri std::string Steinhardt::getSymbol( const int& m ) const { if( m<0 ) { - std::string num; Tools::convert( -1*m, num ); + std::string num; + Tools::convert( -1*m, num ); return "n" + num; } else if( m>0 ) { - std::string num; Tools::convert( m, num ); + std::string num; + Tools::convert( m, num ); return "p" + num; } return "0"; diff --git a/src/symfunc/ThreeBodyGFunctions.cpp b/src/symfunc/ThreeBodyGFunctions.cpp index 9f6b3f52a0..10b38f6d05 100644 --- a/src/symfunc/ThreeBodyGFunctions.cpp +++ b/src/symfunc/ThreeBodyGFunctions.cpp @@ -51,7 +51,8 @@ class ThreeBodyGFunctions : public ActionWithVector { PLUMED_REGISTER_ACTION(ThreeBodyGFunctions,"GSYMFUNC_THREEBODY") void ThreeBodyGFunctions::registerKeywords( Keywords& keys ) { - ActionWithVector::registerKeywords( keys ); keys.use("ARG"); + ActionWithVector::registerKeywords( keys ); + keys.use("ARG"); keys.add("compulsory","WEIGHT","the matrix that contains the weights that should be used for each connection"); keys.add("numbered","FUNCTION","the parameters of the function you would like to compute"); ActionWithValue::useCustomisableComponents( keys ); @@ -59,39 +60,68 @@ void ThreeBodyGFunctions::registerKeywords( Keywords& keys ) { ThreeBodyGFunctions::ThreeBodyGFunctions(const ActionOptions&ao): Action(ao), - ActionWithVector(ao) -{ - if( getNumberOfArguments()!=3 ) error("found wrong number of arguments in input"); - std::vector wval; parseArgumentList("WEIGHT",wval); - if( wval.size()!=1 ) error("keyword WEIGHT should be provided with the label of a single action"); + ActionWithVector(ao) { + if( getNumberOfArguments()!=3 ) { + error("found wrong number of arguments in input"); + } + std::vector wval; + parseArgumentList("WEIGHT",wval); + if( wval.size()!=1 ) { + error("keyword WEIGHT should be provided with the label of a single action"); + } for(unsigned i=0; i<3; ++i) { - if( getPntrToArgument(i)->getRank()!=2 ) error("input argument should be a matrix"); - if( wval[0]->getShape()[0]!=getPntrToArgument(i)->getShape()[0] || wval[0]->getShape()[1]!=getPntrToArgument(i)->getShape()[1] ) error("mismatched shapes of matrices in input"); + if( getPntrToArgument(i)->getRank()!=2 ) { + error("input argument should be a matrix"); + } + if( wval[0]->getShape()[0]!=getPntrToArgument(i)->getShape()[0] || wval[0]->getShape()[1]!=getPntrToArgument(i)->getShape()[1] ) { + error("mismatched shapes of matrices in input"); + } } log.printf(" using bond weights from matrix labelled %s \n",wval[0]->getName().c_str() ); // Rerequest the arguments - std::vector myargs( getArguments() ); myargs.push_back( wval[0] ); requestArguments( myargs ); - for(unsigned i=0; ibuildDataStore(); - std::vector shape(1); shape[0] = getPntrToArgument(0)->getShape()[0]; + std::vector myargs( getArguments() ); + myargs.push_back( wval[0] ); + requestArguments( myargs ); + for(unsigned i=0; ibuildDataStore(); + } + std::vector shape(1); + shape[0] = getPntrToArgument(0)->getShape()[0]; // And now read the functions to compute for(int i=1;; i++) { - std::string myfunc, mystr, lab, num; Tools::convert(i,num); - if( !parseNumbered("FUNCTION",i,mystr ) ) break; + std::string myfunc, mystr, lab, num; + Tools::convert(i,num); + if( !parseNumbered("FUNCTION",i,mystr ) ) { + break; + } std::vector data=Tools::getWords(mystr); - if( !Tools::parse(data,"LABEL",lab ) ) error("found no LABEL in FUNCTION" + num + " specification"); - addComponent( lab, shape ); componentIsNotPeriodic( lab ); - if( !Tools::parse(data,"FUNC",myfunc) ) error("found no FUNC in FUNCTION" + num + " specification"); + if( !Tools::parse(data,"LABEL",lab ) ) { + error("found no LABEL in FUNCTION" + num + " specification"); + } + addComponent( lab, shape ); + componentIsNotPeriodic( lab ); + if( !Tools::parse(data,"FUNC",myfunc) ) { + error("found no FUNC in FUNCTION" + num + " specification"); + } log.printf(" component labelled %s is computed using %s \n",lab.c_str(), myfunc.c_str() ); - functions.push_back( LeptonCall() ); std::vector argnames(1); argnames[0]="ajik"; - if( myfunc.find("rij")!=std::string::npos ) argnames.push_back("rij"); + functions.push_back( LeptonCall() ); + std::vector argnames(1); + argnames[0]="ajik"; + if( myfunc.find("rij")!=std::string::npos ) { + argnames.push_back("rij"); + } if( myfunc.find("rik")!=std::string::npos ) { - if( argnames.size()<2 ) error("if you have a function of rik it must also be a function of rij -- email gareth.tribello@gmail.com if this is a problem"); + if( argnames.size()<2 ) { + error("if you have a function of rik it must also be a function of rij -- email gareth.tribello@gmail.com if this is a problem"); + } argnames.push_back("rik"); } if( myfunc.find("rjk")!=std::string::npos ) { - if( argnames.size()<2 ) error("if you have a function of rjk it must also be a function of rij and rik -- email gareth.tribello@gmail.com if this is a problem"); + if( argnames.size()<2 ) { + error("if you have a function of rjk it must also be a function of rij and rik -- email gareth.tribello@gmail.com if this is a problem"); + } argnames.push_back("rjk"); } functions[i-1].set( myfunc, argnames, this, true ); @@ -102,10 +132,13 @@ ThreeBodyGFunctions::ThreeBodyGFunctions(const ActionOptions&ao): std::string ThreeBodyGFunctions::getOutputComponentDescription( const std::string& cname, const Keywords& keys ) const { for(unsigned i=0; igetName().find(cname)!=std::string::npos ) { - std::string num; Tools::convert( i+1, num ); return "the function defined by the FUNCTION" + num + " keyword"; + std::string num; + Tools::convert( i+1, num ); + return "the function defined by the FUNCTION" + num + " keyword"; } } - plumed_error(); return ""; + plumed_error(); + return ""; } unsigned ThreeBodyGFunctions::getNumberOfDerivatives() { @@ -121,27 +154,40 @@ void ThreeBodyGFunctions::performTask( const unsigned& task_index, MultiValue& m const Value* xval = getPntrToArgument(0); const Value* yval = getPntrToArgument(1); const Value* zval = getPntrToArgument(2); - Angle angle; Vector disti, distj; unsigned matsize = wval->getNumberOfValues(); - std::vector values(4); std::vector der_i(4), der_j(4); + Angle angle; + Vector disti, distj; + unsigned matsize = wval->getNumberOfValues(); + std::vector values(4); + std::vector der_i(4), der_j(4); unsigned nbonds = wval->getRowLength( task_index ), ncols = wval->getShape()[1]; for(unsigned i=0; igetRowIndex( task_index, i ); double weighti = wval->get( ipos ); - if( weightiget( ipos ); disti[1] = yval->get( ipos ); disti[2] = zval->get( ipos ); - values[1] = disti.modulo2(); der_i[1]=2*disti; der_i[2].zero(); + values[1] = disti.modulo2(); + der_i[1]=2*disti; + der_i[2].zero(); for(unsigned j=0; jgetRowIndex( task_index, j ); double weightj = wval->get( jpos ); - if( weightjget( jpos ); distj[1] = yval->get( jpos ); distj[2] = zval->get( jpos ); - values[2] = distj.modulo2(); der_j[1].zero(); der_j[2]=2*distj; - der_i[3] = ( disti - distj ); values[3] = der_i[3].modulo2(); - der_i[3] = 2*der_i[3]; der_j[3] = -der_i[3]; + values[2] = distj.modulo2(); + der_j[1].zero(); + der_j[2]=2*distj; + der_i[3] = ( disti - distj ); + values[3] = der_i[3].modulo2(); + der_i[3] = 2*der_i[3]; + der_j[3] = -der_i[3]; // Compute angle between bonds values[0] = angle.compute( disti, distj, der_i[0], der_j[0] ); // Compute product of weights @@ -149,8 +195,11 @@ void ThreeBodyGFunctions::performTask( const unsigned& task_index, MultiValue& m // Now compute all symmetry functions for(unsigned n=0; ngetPositionInStream(); - double nonweight = functions[n].evaluate( values ); myvals.addValue( ostrn, nonweight*weightij ); - if( doNotCalculateDerivatives() ) continue; + double nonweight = functions[n].evaluate( values ); + myvals.addValue( ostrn, nonweight*weightij ); + if( doNotCalculateDerivatives() ) { + continue; + } for(unsigned m=0; mgetRowIndex( task_index, i ); double weighti = wval->get( ipos ); - if( weightigetPositionInStream(); - myvals.updateIndex( ostrn, ipos ); myvals.updateIndex( ostrn, matsize+ipos ); - myvals.updateIndex( ostrn, 2*matsize+ipos ); myvals.updateIndex( ostrn, 3*matsize+ipos ); + myvals.updateIndex( ostrn, ipos ); + myvals.updateIndex( ostrn, matsize+ipos ); + myvals.updateIndex( ostrn, 2*matsize+ipos ); + myvals.updateIndex( ostrn, 3*matsize+ipos ); } } } diff --git a/src/tools/BiasRepresentation.cpp b/src/tools/BiasRepresentation.cpp index 4e75209cad..2c241812a5 100644 --- a/src/tools/BiasRepresentation.cpp +++ b/src/tools/BiasRepresentation.cpp @@ -43,8 +43,7 @@ BiasRepresentation::BiasRepresentation(const std::vector & tmpvalues, Co /// overload the constructor: add the sigma at constructor time BiasRepresentation::BiasRepresentation(const std::vector & tmpvalues, Communicator &cc, const std::vector & sigma ): - hasgrid(false), rescaledToBias(false), histosigma(sigma),mycomm(cc) -{ + hasgrid(false), rescaledToBias(false), histosigma(sigma),mycomm(cc) { lowI_=0.0; uppI_=0.0; doInt_=false; @@ -58,8 +57,7 @@ BiasRepresentation::BiasRepresentation(const std::vector & tmpvalues, Co /// overload the constructor: add the grid at constructor time BiasRepresentation::BiasRepresentation(const std::vector & tmpvalues, Communicator &cc, const std::vector & gmin, const std::vector & gmax, const std::vector & nbin, bool doInt, double lowI, double uppI): - hasgrid(false), rescaledToBias(false), mycomm(cc) -{ + hasgrid(false), rescaledToBias(false), mycomm(cc) { ndim=tmpvalues.size(); for(int i=0; i & tmpvalues, Co /// overload the constructor with some external sigmas: needed for histogram BiasRepresentation::BiasRepresentation(const std::vector & tmpvalues, Communicator &cc, const std::vector & gmin, const std::vector & gmax, const std::vector & nbin, const std::vector & sigma): - hasgrid(false), rescaledToBias(false),histosigma(sigma),mycomm(cc) -{ + hasgrid(false), rescaledToBias(false),histosigma(sigma),mycomm(cc) { lowI_=0.0; uppI_=0.0; doInt_=false; @@ -92,14 +89,22 @@ BiasRepresentation::BiasRepresentation(const std::vector & tmpvalues, Co void BiasRepresentation::addGrid(const std::vector & gmin, const std::vector & gmax, const std::vector & nbin ) { plumed_massert(hills.size()==0,"you can set the grid before loading the hills"); plumed_massert(hasgrid==false,"to build the grid you should not having the grid in this bias representation"); - std::string ss; ss="file.free"; - std::vector vv; for(unsigned i=0; i vv; + for(unsigned i=0; i(ss,vv,gmin,gmax,nbin,false,true); hasgrid=true; } bool BiasRepresentation::hasSigmaInInput() { - if(histosigma.size()==0) {return false;} else {return true;} + if(histosigma.size()==0) { + return false; + } else { + return true; + } } void BiasRepresentation::setRescaledToBias(bool rescaled) { @@ -153,14 +158,19 @@ void BiasRepresentation::pushKernel( IFile *ifile ) { } // the bias factor is not something about the kernels but // must be stored to keep the bias/free energy duality - std::string dummy; double dummyd; + std::string dummy; + double dummyd; if(ifile->FieldExist("biasf")) { ifile->scanField("biasf",dummy); Tools::convert(dummy,dummyd); - } else {dummyd=1.0;} + } else { + dummyd=1.0; + } biasf.push_back(dummyd); // the domain does not pertain to the kernel but to the values here defined - std::string mins,maxs,minv,maxv,mini,maxi; mins="min_"; maxs="max_"; + std::string mins,maxs,minv,maxv,mini,maxi; + mins="min_"; + maxs="max_"; for(int i=0 ; iisPeriodic()) { ifile->scanField(mins+names[i],minv); @@ -177,24 +187,35 @@ void BiasRepresentation::pushKernel( IFile *ifile ) { std::vector nneighb; if(doInt_&&(kk->getCenter()[0]+kk->getContinuousSupport()[0] > uppI_ || kk->getCenter()[0]-kk->getContinuousSupport()[0] < lowI_ )) { nneighb=BiasGrid_->getNbin(); - } else nneighb=kk->getSupport(BiasGrid_->getDx()); + } else { + nneighb=kk->getSupport(BiasGrid_->getDx()); + } std::vector neighbors=BiasGrid_->getNeighbors(kk->getCenter(),nneighb); std::vector der(ndim); std::vector xx(ndim); if(mycomm.Get_size()==1) { for(unsigned i=0; igetPoint(ineigh,xx); // assign xx to a new vector of values - for(int j=0; jset(xx[j]);} + for(int j=0; jset(xx[j]); + } double bias; - if(doInt_) bias=kk->evaluate(values,der,true,doInt_,lowI_,uppI_); - else bias=kk->evaluate(values,der,true); + if(doInt_) { + bias=kk->evaluate(values,der,true,doInt_,lowI_,uppI_); + } else { + bias=kk->evaluate(values,der,true); + } if(rescaledToBias) { double f=(biasf.back()-1.)/(biasf.back()); bias*=f; - for(int j=0; jaddValueAndDerivatives(ineigh,bias,der); } @@ -207,23 +228,35 @@ void BiasRepresentation::pushKernel( IFile *ifile ) { for(unsigned i=rank; igetPoint(ineigh,xx); - for(int j=0; jset(xx[j]);} - if(doInt_) allbias[i]=kk->evaluate(values,der,true,doInt_,lowI_,uppI_); - else allbias[i]=kk->evaluate(values,der,true); + for(int j=0; jset(xx[j]); + } + if(doInt_) { + allbias[i]=kk->evaluate(values,der,true,doInt_,lowI_,uppI_); + } else { + allbias[i]=kk->evaluate(values,der,true); + } if(rescaledToBias) { double f=(biasf.back()-1.)/(biasf.back()); allbias[i]*=f; - for(int j=0; jaddValueAndDerivatives(ineigh,allbias[i],der); } } @@ -242,10 +275,14 @@ Grid* BiasRepresentation::getGridPtr() { void BiasRepresentation::getMinMaxBin(std::vector &vmin, std::vector &vmax, std::vector &vbin) { std::vector ss,cc,binsize; - vmin.clear(); vmin.resize(ndim,10.e20); - vmax.clear(); vmax.resize(ndim,-10.e20); - vbin.clear(); vbin.resize(ndim); - binsize.clear(); binsize.resize(ndim,10.e20); + vmin.clear(); + vmin.resize(ndim,10.e20); + vmax.clear(); + vmax.resize(ndim,-10.e20); + vbin.clear(); + vbin.resize(ndim); + binsize.clear(); + binsize.resize(ndim,10.e20); int ndiv=10; // adjustable parameter: division per support for(unsigned i=0; i &vmin, std::vectorvmax[j])vmax[j]=dmax; - if(ddivvmax[j]) { + vmax[j]=dmax; + } + if(ddiv &vmin, std::vectorisPeriodic()) { double minv,maxv; values[j]->getDomain(minv,maxv); - if(minv>vmin[j])vmin[j]=minv; - if(maxvvmin[j]) { + vmin[j]=minv; + } + if(maxv(std::ceil((vmax[j]-vmin[j])/binsize[j]) ); } diff --git a/src/tools/Brent1DRootSearch.h b/src/tools/Brent1DRootSearch.h index 491b9816a7..15e653e0d1 100644 --- a/src/tools/Brent1DRootSearch.h +++ b/src/tools/Brent1DRootSearch.h @@ -68,14 +68,19 @@ Brent1DRootSearch::Brent1DRootSearch( const FCLASS& pf, const double& t EXPAND(1.6), ax(0), bx(0), fa(0), fb(0), - myclass_func(pf) -{ + myclass_func(pf) { } template void Brent1DRootSearch::bracket( const double& a, const double& b, eng_pointer eng ) { - plumed_assert( a!=b ); ax=a; bx=b; fa=(myclass_func.*eng)(a); fb=(myclass_func.*eng)(b); - if ((fa > 0.0 && fb > 0.0) || (fa < 0.0 && fb < 0.0)) plumed_merror("input points do not bracket root"); + plumed_assert( a!=b ); + ax=a; + bx=b; + fa=(myclass_func.*eng)(a); + fb=(myclass_func.*eng)(b); + if ((fa > 0.0 && fb > 0.0) || (fa < 0.0 && fb < 0.0)) { + plumed_merror("input points do not bracket root"); + } bracketed=true; } @@ -85,31 +90,61 @@ double Brent1DRootSearch::search( eng_pointer eng ) { double cx=bx, d, e, min1, min2, fc=fb, p, q, r, s, tol1, xm; for(unsigned iter=0; iter0.0 && fc>0.0) || (fb<0.0 && fc<0.0) ) { cx=ax; fc=fa; e=d=bx-ax; } - if( std::fabs(fc) < std::fabs(fb) ) { ax=bx; bx=cx; cx=ax; fa=fb; fb=fc; fc=fa; } - tol1=2*EPS*std::fabs(bx)+0.5*tol; xm=0.5*(cx-bx); - if( std::fabs(xm) <= tol1 || fb == 0.0 ) return bx; + if ( (fb>0.0 && fc>0.0) || (fb<0.0 && fc<0.0) ) { + cx=ax; + fc=fa; + e=d=bx-ax; + } + if( std::fabs(fc) < std::fabs(fb) ) { + ax=bx; + bx=cx; + cx=ax; + fa=fb; + fb=fc; + fc=fa; + } + tol1=2*EPS*std::fabs(bx)+0.5*tol; + xm=0.5*(cx-bx); + if( std::fabs(xm) <= tol1 || fb == 0.0 ) { + return bx; + } if( std::fabs(e) >= tol1 && std::fabs(fa) > std::fabs(fb) ) { s=fb/fa; if( ax==cx ) { - p=2.0*xm*s; q=1.0-s; + p=2.0*xm*s; + q=1.0-s; } else { - q=fa/fc; r=fb/fc; p=s*(2.0*xm*q*(q-r)-(bx-ax)*(r-1.0)); q=(q-1.0)*(r-1.0)*(s-1.0); + q=fa/fc; + r=fb/fc; + p=s*(2.0*xm*q*(q-r)-(bx-ax)*(r-1.0)); + q=(q-1.0)*(r-1.0)*(s-1.0); } - if (p > 0.0) q = -q; - p=std::fabs(p); min1=3.0*xm*q-std::fabs(tol1*q); min2=std::fabs(e*q); + if (p > 0.0) { + q = -q; + } + p=std::fabs(p); + min1=3.0*xm*q-std::fabs(tol1*q); + min2=std::fabs(e*q); if (2.0*p < (min1 < min2 ? min1 : min2)) { - e=d; d=p/q; + e=d; + d=p/q; } else { - d=xm; e=d; + d=xm; + e=d; } } else { - d=xm; e=d; + d=xm; + e=d; + } + ax=bx; + fa=fb; + if( std::fabs(d) > tol1 ) { + bx+=d; + } else if(xm<0 ) { + bx -= std::fabs(tol1); // SIGN(tol1,xm); + } else { + bx += tol1; } - ax=bx; fa=fb; - if( std::fabs(d) > tol1 ) bx+=d; - else if(xm<0 ) bx -= std::fabs(tol1); // SIGN(tol1,xm); - else bx += tol1; fb = (myclass_func.*eng)(bx); } diff --git a/src/tools/CheckInRange.cpp b/src/tools/CheckInRange.cpp index 001fc01c81..4b53280036 100644 --- a/src/tools/CheckInRange.cpp +++ b/src/tools/CheckInRange.cpp @@ -25,27 +25,46 @@ namespace PLMD { bool CheckInRange::setBounds( const unsigned& n, const std::vector& str_lower, const std::vector& str_upper, std::string& errors ) { - if( str_upper.size()!=n && str_upper.size()>0 ) { errors="wrong number of arguments for LESS_THAN_OR_EQUAL keyword"; return false; } - if( str_lower.size()!=n && str_lower.size()>0 ) { errors="wrong number of arguments for GREATER_THAN_OR_EQUAL keyword"; return false; } + if( str_upper.size()!=n && str_upper.size()>0 ) { + errors="wrong number of arguments for LESS_THAN_OR_EQUAL keyword"; + return false; + } + if( str_lower.size()!=n && str_lower.size()>0 ) { + errors="wrong number of arguments for GREATER_THAN_OR_EQUAL keyword"; + return false; + } if( str_upper.size()>0 && str_lower.size()>0 ) { - lower.resize( str_lower.size() ); upper.resize( str_upper.size() ); + lower.resize( str_lower.size() ); + upper.resize( str_upper.size() ); for(unsigned i=0; i::max(); - else Tools::convert( str_lower[i], lower[i] ); - if( str_upper[i]=="none" ) upper[i] = std::numeric_limits::max(); - else Tools::convert( str_upper[i], upper[i] ); + if( str_lower[i]=="none" ) { + lower[i] = -std::numeric_limits::max(); + } else { + Tools::convert( str_lower[i], lower[i] ); + } + if( str_upper[i]=="none" ) { + upper[i] = std::numeric_limits::max(); + } else { + Tools::convert( str_upper[i], upper[i] ); + } } } else if( str_upper.size()>0 ) { upper.resize( str_upper.size() ); for(unsigned i=0; i::max(); - else Tools::convert( str_upper[i], upper[i] ); + if( str_upper[i]=="none" ) { + upper[i] = std::numeric_limits::max(); + } else { + Tools::convert( str_upper[i], upper[i] ); + } } } else if( str_lower.size()>0 ) { lower.resize( str_lower.size() ); for(unsigned i=0; i::max(); - else Tools::convert( str_lower[i], lower[i] ); + if( str_lower[i]=="none" ) { + lower[i] = -std::numeric_limits::max(); + } else { + Tools::convert( str_lower[i], lower[i] ); + } } } return true; @@ -57,30 +76,45 @@ bool CheckInRange::wereSet() const { std::string CheckInRange::report( const std::vector& a ) const { if( upper.size()>0 && lower.size()>0 ) { - std::string str_l, str_u; Tools::convert( upper[0], str_u ); Tools::convert( lower[0], str_l ); + std::string str_l, str_u; + Tools::convert( upper[0], str_u ); + Tools::convert( lower[0], str_l ); std::string out="only printing indices of atoms that have " + str_l + " <= " + a[0] + " <=" + str_u; for(unsigned i=1; i()); + if(val) { + Set_comm(*(const MPI_Comm*)val.get()); + } #else (void) val; plumed_merror("you are trying to use an MPI function, but PLUMED has been compiled without MPI support"); @@ -124,7 +136,9 @@ void Communicator::Abort(int errorcode) { void Communicator::Bcast(Data data,int root) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) MPI_Bcast(data.pointer,data.size,data.type,root,communicator); + if(initialized()) { + MPI_Bcast(data.pointer,data.size,data.type,root,communicator); + } #else (void) data; (void) root; @@ -133,7 +147,9 @@ void Communicator::Bcast(Data data,int root) { void Communicator::Sum(Data data) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_SUM,communicator); + if(initialized()) { + MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_SUM,communicator); + } #else (void) data; #endif @@ -141,7 +157,9 @@ void Communicator::Sum(Data data) { void Communicator::Prod(Data data) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_PROD,communicator); + if(initialized()) { + MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_PROD,communicator); + } #else (void) data; #endif @@ -149,7 +167,9 @@ void Communicator::Prod(Data data) { void Communicator::Max(Data data) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_MAX,communicator); + if(initialized()) { + MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_MAX,communicator); + } #else (void) data; #endif @@ -157,7 +177,9 @@ void Communicator::Max(Data data) { void Communicator::Min(Data data) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_MIN,communicator); + if(initialized()) { + MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_MIN,communicator); + } #else (void) data; #endif @@ -185,7 +207,9 @@ void Communicator::Allgatherv(ConstData in,Data out,const int*recvcounts,const i int*di=const_cast(displs); #if defined(__PLUMED_HAS_MPI) if(initialized()) { - if(s==NULL)s=MPI_IN_PLACE; + if(s==NULL) { + s=MPI_IN_PLACE; + } MPI_Allgatherv(s,in.size,in.type,r,rc,di,out.type,communicator); } else { plumed_assert(in.nbytes==out.nbytes); @@ -193,7 +217,9 @@ void Communicator::Allgatherv(ConstData in,Data out,const int*recvcounts,const i plumed_assert(rc); plumed_assert(rc[0]==in.size); plumed_assert(di); - if(s) std::memcpy(static_cast(r)+displs[0]*in.nbytes,s,size_t(in.size)*in.nbytes); + if(s) { + std::memcpy(static_cast(r)+displs[0]*in.nbytes,s,size_t(in.size)*in.nbytes); + } } #else plumed_assert(in.nbytes==out.nbytes); @@ -201,7 +227,9 @@ void Communicator::Allgatherv(ConstData in,Data out,const int*recvcounts,const i plumed_assert(rc); plumed_assert(rc[0]==in.size); plumed_assert(di); - if(s) std::memcpy(static_cast(r)+displs[0]*in.nbytes,s,size_t(in.size)*in.nbytes); + if(s) { + std::memcpy(static_cast(r)+displs[0]*in.nbytes,s,size_t(in.size)*in.nbytes); + } #endif } @@ -210,25 +238,34 @@ void Communicator::Allgather(ConstData in,Data out) { void*r=const_cast((const void*)out.pointer); #if defined(__PLUMED_HAS_MPI) if(initialized()) { - if(s==NULL)s=MPI_IN_PLACE; + if(s==NULL) { + s=MPI_IN_PLACE; + } MPI_Allgather(s,in.size,in.type,r,out.size/Get_size(),out.type,communicator); } else { plumed_assert(in.nbytes==out.nbytes); plumed_assert(in.size==out.size); - if(s) std::memcpy(r,s,size_t(in.size)*in.nbytes); + if(s) { + std::memcpy(r,s,size_t(in.size)*in.nbytes); + } } #else plumed_assert(in.nbytes==out.nbytes); plumed_assert(in.size==out.size); - if(s) std::memcpy(r,s,size_t(in.size)*in.nbytes); + if(s) { + std::memcpy(r,s,size_t(in.size)*in.nbytes); + } #endif } void Communicator::Recv(Data data,int source,int tag,Status&status) { #ifdef __PLUMED_HAS_MPI plumed_massert(initialized(),"you are trying to use an MPI function, but MPI is not initialized"); - if(&status==&StatusIgnore) MPI_Recv(data.pointer,data.size,data.type,source,tag,communicator,MPI_STATUS_IGNORE); - else MPI_Recv(data.pointer,data.size,data.type,source,tag,communicator,&status.s); + if(&status==&StatusIgnore) { + MPI_Recv(data.pointer,data.size,data.type,source,tag,communicator,MPI_STATUS_IGNORE); + } else { + MPI_Recv(data.pointer,data.size,data.type,source,tag,communicator,&status.s); + } #else (void) data; (void) source; @@ -240,7 +277,9 @@ void Communicator::Recv(Data data,int source,int tag,Status&status) { void Communicator::Barrier()const { #ifdef __PLUMED_HAS_MPI - if(initialized()) MPI_Barrier(communicator); + if(initialized()) { + MPI_Barrier(communicator); + } #endif } @@ -252,8 +291,11 @@ bool Communicator::initialized() { #if defined(__PLUMED_HAS_MPI) int flag=0; MPI_Initialized(&flag); - if(flag) return true; - else return false; + if(flag) { + return true; + } else { + return false; + } #endif return false; } @@ -261,8 +303,11 @@ bool Communicator::initialized() { void Communicator::Request::wait(Status&s) { #ifdef __PLUMED_HAS_MPI plumed_massert(initialized(),"you are trying to use an MPI function, but MPI is not initialized"); - if(&s==&StatusIgnore) MPI_Wait(&r,MPI_STATUS_IGNORE); - else MPI_Wait(&r,&s.s); + if(&s==&StatusIgnore) { + MPI_Wait(&r,MPI_STATUS_IGNORE); + } else { + MPI_Wait(&r,&s.s); + } #else (void) s; plumed_merror("you are trying to use an MPI function, but PLUMED has been compiled without MPI support"); @@ -270,25 +315,61 @@ void Communicator::Request::wait(Status&s) { } #ifdef __PLUMED_HAS_MPI -template<> MPI_Datatype Communicator::getMPIType() { return MPI_FLOAT;} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_DOUBLE;} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_INT;} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_CHAR;} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_UNSIGNED;} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_UNSIGNED;} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_UNSIGNED_LONG;} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_UNSIGNED_LONG_LONG;} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_LONG_DOUBLE;} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_FLOAT; +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_DOUBLE; +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_INT; +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_CHAR; +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_UNSIGNED; +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_UNSIGNED; +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_UNSIGNED_LONG; +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_UNSIGNED_LONG_LONG; +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_LONG_DOUBLE; +} #else -template<> MPI_Datatype Communicator::getMPIType() { return MPI_Datatype();} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_Datatype();} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_Datatype();} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_Datatype();} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_Datatype();} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_Datatype();} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_Datatype();} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_Datatype();} -template<> MPI_Datatype Communicator::getMPIType() { return MPI_Datatype();} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_Datatype(); +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_Datatype(); +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_Datatype(); +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_Datatype(); +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_Datatype(); +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_Datatype(); +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_Datatype(); +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_Datatype(); +} +template<> MPI_Datatype Communicator::getMPIType() { + return MPI_Datatype(); +} #endif void Communicator::Split(int color,int key,Communicator&pc)const { diff --git a/src/tools/Communicator.h b/src/tools/Communicator.h index aff4771852..16ef37ddfb 100644 --- a/src/tools/Communicator.h +++ b/src/tools/Communicator.h @@ -82,17 +82,34 @@ class Communicator { template explicit Data(TensorGeneric &p): pointer(&p), size(n*m), nbytes(sizeof(double)), type(getMPIType()) {} /// Init from reference to std::vector template explicit Data(std::vector&v) { - Data d(v.data(),v.size()); pointer=d.pointer; size=d.size; type=d.type; + Data d(v.data(),v.size()); + pointer=d.pointer; + size=d.size; + type=d.type; } /// Init from reference to PLMD::Matrix template explicit Data(Matrix&m ) { - if(m.nrows()*m.ncols()>0) { Data d(&m(0,0),m.nrows()*m.ncols()); pointer=d.pointer; size=d.size; type=d.type; } - else { pointer=NULL; size=0; } + if(m.nrows()*m.ncols()>0) { + Data d(&m(0,0),m.nrows()*m.ncols()); + pointer=d.pointer; + size=d.size; + type=d.type; + } else { + pointer=NULL; + size=0; + } } /// Init from reference to std::string explicit Data(std::string&s) { - if(s.size()>0) { Data d(&s[0],s.size()); pointer=d.pointer; size=d.size; type=d.type; } - else { pointer=NULL; size=0; } + if(s.size()>0) { + Data d(&s[0],s.size()); + pointer=d.pointer; + size=d.size; + type=d.type; + } else { + pointer=NULL; + size=0; + } } }; /// Const version of Communicator::Data @@ -109,15 +126,32 @@ class Communicator { template explicit ConstData(const TensorGeneric *p,int s): pointer(p), size(n*m*s), nbytes(sizeof(double)), type(getMPIType()) {} template explicit ConstData(const TensorGeneric &p): pointer(&p), size(n*m), nbytes(sizeof(double)), type(getMPIType()) {} template explicit ConstData(const std::vector&v) { - ConstData d(v.data(),v.size()); pointer=d.pointer; size=d.size; type=d.type; + ConstData d(v.data(),v.size()); + pointer=d.pointer; + size=d.size; + type=d.type; } template explicit ConstData(const Matrix&m ) { - if(m.nrows()*m.ncols()>0) { ConstData d(&m(0,0),m.nrows()*m.ncols()); pointer=d.pointer; size=d.size; type=d.type; } - else { pointer=NULL; size=0; } + if(m.nrows()*m.ncols()>0) { + ConstData d(&m(0,0),m.nrows()*m.ncols()); + pointer=d.pointer; + size=d.size; + type=d.type; + } else { + pointer=NULL; + size=0; + } } explicit ConstData(const std::string&s) { - if(s.size()>0) { ConstData d(&s[0],s.size()); pointer=d.pointer; size=d.size; type=d.type; } - else { pointer=NULL; size=0; } + if(s.size()>0) { + ConstData d(&s[0],s.size()); + pointer=d.pointer; + size=d.size; + type=d.type; + } else { + pointer=NULL; + size=0; + } } }; public: @@ -130,7 +164,9 @@ class Communicator { public: MPI_Status s; template - int Get_count()const {return Get_count(getMPIType());} + int Get_count()const { + return Get_count(getMPIType()); + } }; /// Special status used when status should be ignored. /// E.g. `Recv(a,0,1,Communicator::StatusIgnore);` @@ -178,41 +214,65 @@ class Communicator { /// Wrapper for MPI_Allreduce with MPI_SUM (data struct) void Sum(Data); /// Wrapper for MPI_Allreduce with MPI_SUM (pointer) - template void Sum(T*buf,int count) {Sum(Data(buf,count));} + template void Sum(T*buf,int count) { + Sum(Data(buf,count)); + } /// Wrapper for MPI_Allreduce with MPI_SUM (reference) - template void Sum(T&buf) {Sum(Data(buf));} + template void Sum(T&buf) { + Sum(Data(buf)); + } /// Wrapper for MPI_Allreduce with MPI_PROD (data struct) void Prod(Data); /// Wrapper for MPI_Allreduce with MPI_PROD (pointer) - template void Prod(T*buf,int count) {Prod(Data(buf,count));} + template void Prod(T*buf,int count) { + Prod(Data(buf,count)); + } /// Wrapper for MPI_Allreduce with MPI_PROD (reference) - template void Prod(T&buf) {Prod(Data(buf));} + template void Prod(T&buf) { + Prod(Data(buf)); + } /// Wrapper for MPI_Allreduce with MPI_MAX (data struct) void Max(Data); /// Wrapper for MPI_Allreduce with MPI_MAX (pointer) - template void Max(T*buf,int count) {Max(Data(buf,count));} + template void Max(T*buf,int count) { + Max(Data(buf,count)); + } /// Wrapper for MPI_Allreduce with MPI_MAX (reference) - template void Max(T&buf) {Max(Data(buf));} + template void Max(T&buf) { + Max(Data(buf)); + } /// Wrapper for MPI_Allreduce with MPI_MIN (data struct) void Min(Data); /// Wrapper for MPI_Allreduce with MPI_MIN (pointer) - template void Min(T*buf,int count) {Min(Data(buf,count));} + template void Min(T*buf,int count) { + Min(Data(buf,count)); + } /// Wrapper for MPI_Allreduce with MPI_MIN (reference) - template void Min(T&buf) {Min(Data(buf));} + template void Min(T&buf) { + Min(Data(buf)); + } /// Wrapper for MPI_Bcast (data struct) void Bcast(Data,int); /// Wrapper for MPI_Bcast (pointer) - template void Bcast(T*buf,int count,int root) {Bcast(Data(buf,count),root);} + template void Bcast(T*buf,int count,int root) { + Bcast(Data(buf,count),root); + } /// Wrapper for MPI_Bcast (reference) - template void Bcast(T&buf,int root) {Bcast(Data(buf),root);} + template void Bcast(T&buf,int root) { + Bcast(Data(buf),root); + } /// Wrapper for MPI_Isend (data struct) Request Isend(ConstData,int,int); /// Wrapper for MPI_Isend (pointer) - template Request Isend(const T*buf,int count,int source,int tag) {return Isend(ConstData(buf,count),source,tag);} + template Request Isend(const T*buf,int count,int source,int tag) { + return Isend(ConstData(buf,count),source,tag); + } /// Wrapper for MPI_Isend (reference) - template Request Isend(const T&buf,int source,int tag) {return Isend(ConstData(buf),source,tag);} + template Request Isend(const T&buf,int source,int tag) { + return Isend(ConstData(buf),source,tag); + } /// Wrapper for MPI_Allgatherv (data struct) void Allgatherv(ConstData in,Data out,const int*,const int*); @@ -239,9 +299,13 @@ class Communicator { /// Wrapper for MPI_Recv (data struct) void Recv(Data,int,int,Status&s=StatusIgnore); /// Wrapper for MPI_Recv (pointer) - template void Recv(T*buf,int count,int source,int tag,Status&s=StatusIgnore) {Recv(Data(buf,count),source,tag,s);} + template void Recv(T*buf,int count,int source,int tag,Status&s=StatusIgnore) { + Recv(Data(buf,count),source,tag,s); + } /// Wrapper for MPI_Recv (reference) - template void Recv(T&buf,int source,int tag,Status&s=StatusIgnore) {Recv(Data(buf),source,tag,s);} + template void Recv(T&buf,int source,int tag,Status&s=StatusIgnore) { + Recv(Data(buf),source,tag,s); + } /// Wrapper to MPI_Comm_split void Split(int,int,Communicator&)const; diff --git a/src/tools/ConjugateGradient.h b/src/tools/ConjugateGradient.h index 9b786a1783..1ecd38e70b 100644 --- a/src/tools/ConjugateGradient.h +++ b/src/tools/ConjugateGradient.h @@ -43,20 +43,34 @@ template void ConjugateGradient::minimise( const double& ftol, std::vector& p, engf_pointer myfunc ) const { std::vector xi( p.size() ), g( p.size() ), h( p.size() ); double fp = this->calcDerivatives( p, xi, myfunc ); - for(unsigned j=0; jlinemin( xi, p, myfunc ); // The exit condition - if( 2.0*std::fabs(fret-fp) <= ftol*(std::fabs(fret)+std::fabs(fp)+EPS)) { return; } - fp = fret; this->calcDerivatives( p, xi, myfunc ); + if( 2.0*std::fabs(fret-fp) <= ftol*(std::fabs(fret)+std::fabs(fp)+EPS)) { + return; + } + fp = fret; + this->calcDerivatives( p, xi, myfunc ); double ddg=0., gg=0.; - for(unsigned j=0; j & reference, const std::vecto bool ERMSD::inPair(unsigned i, unsigned j) { - if(pairs.size()==0) return true; + if(pairs.size()==0) { + return true; + } for(unsigned idx=0; idx & positions,const Pbc& pbc,\ ermsd = std::sqrt(ermsd/nresidues); double iermsd = 1.0/(ermsd*nresidues); - for(unsigned i=0; i v; int n = path.length(); @@ -53,13 +52,12 @@ std::string simplify(const std::string & path) // if ".." , we pop. if (dir == "..") { - if (!v.empty()) + if (!v.empty()) { v.pop_back(); - } - else if (dir == "." || dir == "") { + } + } else if (dir == "." || dir == "") { // do nothing (added for better understanding.) - } - else { + } else { // push the current directory into the vector. v.push_back(dir); } @@ -68,22 +66,24 @@ std::string simplify(const std::string & path) // forming the ans bool first=true; for (const auto & i : v) { - if(!first) ans += "/"; + if(!first) { + ans += "/"; + } first=false; ans += i; } // vector is empty - if (ans == "") + if (ans == "") { return "/"; + } return ans; } } -Exception::Exception() -{ +Exception::Exception() { callstack.fill(nullptr); #ifdef __PLUMED_HAS_EXECINFO callstack_n = backtrace(&callstack[0], callstack.size()-1); @@ -96,18 +96,18 @@ Exception::Exception() #endif } -Exception& Exception::operator<<(const std::string&msg) -{ +Exception& Exception::operator<<(const std::string&msg) { if(msg.length()>0) { - if(note) this->msg +="\n"; + if(note) { + this->msg +="\n"; + } this->msg +=msg; note=false; } return *this; } -Exception& Exception::operator<<(const Location&loc) -{ +Exception& Exception::operator<<(const Location&loc) { if(loc.file) { const std::size_t clinelen=1000; char cline[clinelen]; @@ -130,8 +130,7 @@ Exception& Exception::operator<<(const Location&loc) return *this; } -Exception& Exception::operator<<(const Assertion&as) -{ +Exception& Exception::operator<<(const Assertion&as) { if(as.assertion) { this->msg += "\n+++ assertion failed: "; this->msg += as.assertion; @@ -144,7 +143,10 @@ const char* Exception::stack() const { #ifdef __PLUMED_HAS_EXECINFO if(stackTrace.length()==0) { char** strs = backtrace_symbols(&callstack[0], callstack_n); - for (int i = 0; i < callstack_n; ++i) {stackTrace+=strs[i]; stackTrace+="\n";} + for (int i = 0; i < callstack_n; ++i) { + stackTrace+=strs[i]; + stackTrace+="\n"; + } free(strs); } #endif diff --git a/src/tools/Exception.h b/src/tools/Exception.h index 4b008fda12..8dafcb4137 100644 --- a/src/tools/Exception.h +++ b/src/tools/Exception.h @@ -152,8 +152,7 @@ this in all previous PLUMED versions. In case it is necessary, we can replace it later with a fixed size array placed on the stack. */ -class Exception : public std::exception -{ +class Exception : public std::exception { /// Reported message. Can be updated. std::string msg; /// Flag to remember if we have to write the `+++ message follows +++` string. @@ -220,8 +219,7 @@ class Exception : public std::exception /// Constructor compatible with PLUMED <=2.4. explicit Exception(const std::string & msg): - Exception() - { + Exception() { *this << msg; } @@ -232,8 +230,7 @@ class Exception : public std::exception note(e.note), callstack(e.callstack), callstack_n(e.callstack_n), - stackTrace(e.stackTrace) - { + stackTrace(e.stackTrace) { } /// Assignment. @@ -252,7 +249,9 @@ class Exception : public std::exception /// In case the environment variable PLUMED_STACK_TRACE was defined /// and equal to `yes` when the exception was raised, /// the error message will contain the stack trace as well. - const char* what() const noexcept override {return msg.c_str();} + const char* what() const noexcept override { + return msg.c_str(); + } /// Returns the stack trace as a string. /// This function is slow as it requires building a parsed string. @@ -260,10 +259,14 @@ class Exception : public std::exception const char* stack() const; /// Returns the callstack. - const std::array & trace() const noexcept {return callstack;} + const std::array & trace() const noexcept { + return callstack; + } /// Returns the number of elements in the trace array - int trace_n() const noexcept {return callstack_n;} + int trace_n() const noexcept { + return callstack_n; + } /// Destructor should be defined and should not throw other exceptions ~Exception() noexcept override {} diff --git a/src/tools/FileBase.cpp b/src/tools/FileBase.cpp index 3cc79af87e..3a5257e1cc 100644 --- a/src/tools/FileBase.cpp +++ b/src/tools/FileBase.cpp @@ -47,7 +47,9 @@ FileBase& FileBase::link(FILE*fp) { } FileBase& FileBase::flush() { - if(fp) fflush(fp); + if(fp) { + fflush(fp); + } return *this; } @@ -78,7 +80,11 @@ bool FileBase::FileExist(const std::string& path) { // first try with suffix FILE *ff=std::fopen(const_cast(this->path.c_str()),"r"); // call fclose when ff goes out of scope - auto deleter=[](auto f) { if(f) std::fclose(f); }; + auto deleter=[](auto f) { + if(f) { + std::fclose(f); + } + }; std::unique_ptr fp_deleter(ff,deleter); if(!ff) { @@ -87,14 +93,20 @@ bool FileBase::FileExist(const std::string& path) { ff=std::fopen(const_cast(this->path.c_str()),"r"); mode="r"; } - if(ff) do_exist=true; - if(comm) comm->Barrier(); + if(ff) { + do_exist=true; + } + if(comm) { + comm->Barrier(); + } return do_exist; } bool FileBase::isOpen() { bool isopen=false; - if(fp) isopen=true; + if(fp) { + isopen=true; + } return isopen; } @@ -102,9 +114,13 @@ void FileBase::close() { plumed_assert(!cloned); eof=false; err=false; - if(fp) std::fclose(fp); + if(fp) { + std::fclose(fp); + } #ifdef __PLUMED_HAS_ZLIB - if(gzfp) gzclose(gzFile(gzfp)); + if(gzfp) { + gzclose(gzFile(gzfp)); + } #endif fp=NULL; gzfp=NULL; @@ -120,16 +136,20 @@ FileBase::FileBase(): eof(false), err(false), heavyFlush(false), - enforcedSuffix_(false) -{ + enforcedSuffix_(false) { } -FileBase::~FileBase() -{ - if(plumed) plumed->eraseFile(*this); - if(!cloned && fp) std::fclose(fp); +FileBase::~FileBase() { + if(plumed) { + plumed->eraseFile(*this); + } + if(!cloned && fp) { + std::fclose(fp); + } #ifdef __PLUMED_HAS_ZLIB - if(!cloned && gzfp) gzclose(gzFile(gzfp)); + if(!cloned && gzfp) { + gzclose(gzFile(gzfp)); + } #endif } @@ -138,7 +158,9 @@ FileBase::operator bool()const { } std::string FileBase::appendSuffix(const std::string&path,const std::string&suffix) { - if(path=="/dev/null") return path; // do not append a suffix to /dev/null + if(path=="/dev/null") { + return path; // do not append a suffix to /dev/null + } std::string ret=path; std::string ext=Tools::extension(path); @@ -156,7 +178,9 @@ std::string FileBase::appendSuffix(const std::string&path,const std::string&suff ret.resize(l); } ret+=suffix; - if(ext.length()>0)ret+="."+ext; + if(ext.length()>0) { + ret+="."+ext; + } return ret; } @@ -167,8 +191,12 @@ FileBase& FileBase::enforceSuffix(const std::string&suffix) { } std::string FileBase::getSuffix()const { - if(enforcedSuffix_) return enforcedSuffix; - if(plumed) return plumed->getSuffix(); + if(enforcedSuffix_) { + return enforcedSuffix; + } + if(plumed) { + return plumed->getSuffix(); + } return ""; } diff --git a/src/tools/FileBase.h b/src/tools/FileBase.h index 5f148e4041..714182131c 100644 --- a/src/tools/FileBase.h +++ b/src/tools/FileBase.h @@ -113,7 +113,9 @@ class FileBase { /// Check for error/eof. operator bool () const; /// Set heavyFlush flag - void setHeavyFlush() { heavyFlush=true;} + void setHeavyFlush() { + heavyFlush=true; + } /// Opens the file virtual FileBase& open(const std::string&name)=0; /// Check if the file exists diff --git a/src/tools/ForwardDecl.h b/src/tools/ForwardDecl.h index ec1257850f..bb12014bb4 100644 --- a/src/tools/ForwardDecl.h +++ b/src/tools/ForwardDecl.h @@ -33,8 +33,7 @@ namespace PLMD { */ template class ForwardDecl: - std::unique_ptr -{ + std::unique_ptr { public: // Construction with arbitrary argument. template diff --git a/src/tools/Grid.cpp b/src/tools/Grid.cpp index f539aeb3f7..82fe6a2118 100644 --- a/src/tools/Grid.cpp +++ b/src/tools/Grid.cpp @@ -44,8 +44,7 @@ constexpr std::size_t GridBase::maxdim; template class Accelerator final: - public Grid::AcceleratorBase -{ + public Grid::AcceleratorBase { public: @@ -68,23 +67,36 @@ class Accelerator final: } neighbors.reserve(small_nbin); - for(unsigned j=0; j=static_cast(nbin_[i])) continue; - if( pbc_[i] && i0<0) i0=nbin_[i]-(-i0)%nbin_[i]; - if( pbc_[i] && i0>=static_cast(nbin_[i])) i0%=nbin_[i]; + if(!pbc_[i] && i0<0) { + continue; + } + if(!pbc_[i] && i0>=static_cast(nbin_[i])) { + continue; + } + if( pbc_[i] && i0<0) { + i0=nbin_[i]-(-i0)%nbin_[i]; + } + if( pbc_[i] && i0>=static_cast(nbin_[i])) { + i0%=nbin_[i]; + } tmp_indices[ll]=static_cast(i0); ll++; } - if(ll==dimension_) {neighbors.push_back(getIndex(grid,nbin_,&tmp_indices[0],dimension_));} + if(ll==dimension_) { + neighbors.push_back(getIndex(grid,nbin_,&tmp_indices[0],dimension_)); + } small_indices[0]++; - for(unsigned j=0; j & nbin_,const unsigned* indices,std::size_t indices_size) const override { for(unsigned int i=0; i=nbin_[i]) plumed_error() << "Looking for a value outside the grid along the " << i << " dimension (arg name: "<=nbin_[i]) { + plumed_error() << "Looking for a value outside the grid along the " << i << " dimension (arg name: "<0; --i) { index=index*nbin_[i-1]+indices[i-1]; @@ -133,22 +147,54 @@ class Accelerator final: std::unique_ptr Grid::AcceleratorBase::create(unsigned dim) { // I do this by enumeration. // Maybe can be simplified using the preprocessor, but I am not sure it's worth it - if(dim==1) return std::make_unique>(); - if(dim==2) return std::make_unique>(); - if(dim==3) return std::make_unique>(); - if(dim==4) return std::make_unique>(); - if(dim==5) return std::make_unique>(); - if(dim==6) return std::make_unique>(); - if(dim==7) return std::make_unique>(); - if(dim==8) return std::make_unique>(); - if(dim==9) return std::make_unique>(); - if(dim==10) return std::make_unique>(); - if(dim==11) return std::make_unique>(); - if(dim==12) return std::make_unique>(); - if(dim==13) return std::make_unique>(); - if(dim==14) return std::make_unique>(); - if(dim==15) return std::make_unique>(); - if(dim==16) return std::make_unique>(); + if(dim==1) { + return std::make_unique>(); + } + if(dim==2) { + return std::make_unique>(); + } + if(dim==3) { + return std::make_unique>(); + } + if(dim==4) { + return std::make_unique>(); + } + if(dim==5) { + return std::make_unique>(); + } + if(dim==6) { + return std::make_unique>(); + } + if(dim==7) { + return std::make_unique>(); + } + if(dim==8) { + return std::make_unique>(); + } + if(dim==9) { + return std::make_unique>(); + } + if(dim==10) { + return std::make_unique>(); + } + if(dim==11) { + return std::make_unique>(); + } + if(dim==12) { + return std::make_unique>(); + } + if(dim==13) { + return std::make_unique>(); + } + if(dim==14) { + return std::make_unique>(); + } + if(dim==15) { + return std::make_unique>(); + } + if(dim==16) { + return std::make_unique>(); + } // no need to go beyond this plumed_error(); } @@ -201,7 +247,8 @@ void GridBase::Init(const std::string& funcl, const std::vector &na plumed_massert(names.size()==gmax.size(),"grid dimensions in input do not match number of arguments"); dimension_=gmax.size(); accelerator=AcceleratorHandler(dimension_); - str_min_=gmin; str_max_=gmax; + str_min_=gmin; + str_max_=gmax; argnames.resize( dimension_ ); min_.resize( dimension_ ); max_.resize( dimension_ ); @@ -224,11 +271,16 @@ void GridBase::Init(const std::string& funcl, const std::vector &na nbin_=nbin; dospline_=dospline; usederiv_=usederiv; - if(dospline_) plumed_assert(dospline_==usederiv_); + if(dospline_) { + plumed_assert(dospline_==usederiv_); + } maxsize_=1; for(unsigned int i=0; i( nbin_[i] ) ); - if( !pbc_[i] ) { max_[i] += dx_[i]; nbin_[i] += 1; } + if( !pbc_[i] ) { + max_[i] += dx_[i]; + nbin_[i] += 1; + } maxsize_*=nbin_[i]; } } @@ -251,7 +303,9 @@ double GridBase::getDx(index_t j) const { double GridBase::getBinVolume() const { double vol=1.; - for(unsigned i=0; i nindices; unsigned inind; for(unsigned int i=0; iset(xx[j]); + for(unsigned j=0; jset(xx[j]); + } double newval = kernel.evaluate( vv_ptr, der, usederiv_ ); - if( usederiv_ ) addValueAndDerivatives( ineigh, newval, der ); - else addValue( ineigh, newval ); + if( usederiv_ ) { + addValueAndDerivatives( ineigh, newval, der ); + } else { + addValue( ineigh, newval ); + } } } @@ -382,7 +448,9 @@ double GridBase::getValueAndDerivatives(const std::vector & x, std::vect std::array dder; // reset value=0.0; - for(unsigned int i=0; i indices; getIndices(x, indices.data(),dimension_); @@ -400,14 +468,19 @@ double GridBase::getValueAndDerivatives(const std::vector & x, std::vect for(unsigned j=0; j & x, std::vect } for(unsigned j=0; j0 && dimension_>1 && getIndices(i)[dimension_-2]==0) ofile.printf("\n"); + if(usederiv_) { + f=getValueAndDerivatives(i,der); + } else { + f=getValue(i); + } + if(i>0 && dimension_>1 && getIndices(i)[dimension_-2]==0) { + ofile.printf("\n"); + } for(unsigned j=0; j(nbin_[j]) ); - if( pbc_[j] ) ofile.printField("periodic_" + argnames[j], "true" ); - else ofile.printField("periodic_" + argnames[j], "false" ); + if( pbc_[j] ) { + ofile.printField("periodic_" + argnames[j], "true" ); + } else { + ofile.printField("periodic_" + argnames[j], "false" ); + } + } + for(unsigned j=0; j GridBase::create(const std::string& funcl, const std:: return grid; } -std::unique_ptr GridBase::create(const std::string& funcl, const std::vector & args, IFile& ifile, bool dosparse, bool dospline, bool doder) -{ +std::unique_ptr GridBase::create(const std::string& funcl, const std::vector & args, IFile& ifile, bool dosparse, bool dospline, bool doder) { std::unique_ptr grid; - unsigned nvar=args.size(); bool hasder=false; std::string pstring; - std::vector gbin1(nvar); std::vector gbin(nvar); + unsigned nvar=args.size(); + bool hasder=false; + std::string pstring; + std::vector gbin1(nvar); + std::vector gbin(nvar); std::vector labels(nvar),gmin(nvar),gmax(nvar); - std::vector fieldnames; ifile.scanFieldList( fieldnames ); + std::vector fieldnames; + ifile.scanFieldList( fieldnames ); // Retrieve names for fields for(unsigned i=0; igetName(); bool found=false; + labels[i]=args[i]->getName(); + bool found=false; for(unsigned j=0; j GridBase::create(const std::string& funcl, const std:: if( args[i]->isPeriodic() ) { plumed_massert( pstring=="true", "input value is periodic but grid is not"); std::string pmin, pmax; - args[i]->getDomain( pmin, pmax ); gbin[i]=gbin1[i]; - if( pmin!=gmin[i] || pmax!=gmax[i] ) plumed_merror("mismatch between grid boundaries and periods of values"); + args[i]->getDomain( pmin, pmax ); + gbin[i]=gbin1[i]; + if( pmin!=gmin[i] || pmax!=gmax[i] ) { + plumed_merror("mismatch between grid boundaries and periods of values"); + } } else { gbin[i]=gbin1[i]-1; // Note header in grid file indicates one more bin that there should be when data is not periodic plumed_massert( pstring=="false", "input value is not periodic but grid is"); } hasder=ifile.FieldExist( "der_" + labels[i] ); - if( doder && !hasder ) plumed_merror("missing derivatives from grid file"); + if( doder && !hasder ) { + plumed_merror("missing derivatives from grid file"); + } for(unsigned j=0; j(funcl,args,gmin,gmax,gbin,dospline,doder);} - else {grid=Tools::make_unique(funcl,args,gmin,gmax,gbin,dospline,doder);} + if(!dosparse) { + grid=Tools::make_unique(funcl,args,gmin,gmax,gbin,dospline,doder); + } else { + grid=Tools::make_unique(funcl,args,gmin,gmax,gbin,dospline,doder); + } std::vector xx(nvar),dder(nvar); std::vector dx=grid->getDx(); double f,x; while( ifile.scanField(funcl,f) ) { for(unsigned i=0; igetIndex(xx); - if(doder) {grid->setValueAndDerivatives(index,f,dder);} - else {grid->setValue(index,f);} + if(doder) { + grid->setValueAndDerivatives(index,f,dder); + } else { + grid->setValue(index,f); + } ifile.scanField(); } return grid; @@ -597,7 +725,9 @@ double Grid::getMinValue() const { double minval; minval=DBL_MAX; for(index_t i=0; imaxval)maxval=grid_[i]; + if(grid_[i]>maxval) { + maxval=grid_[i]; + } } return maxval; } @@ -615,10 +747,14 @@ void Grid::scaleAllValuesAndDerivatives( const double& scalef ) { if(usederiv_) { for(index_t i=0; i direction( dimension_, 0 ); // Run over whole grid - npoints=0; RootFindingBase mymin( this ); + npoints=0; + RootFindingBase mymin( this ); for(unsigned i=0; i& der) { plumed_dbg_assert(index& der) { plumed_dbg_assert(indexsecond; + if(it!=map_.end()) { + value=it->second; + } return value; } double SparseGrid::getValueAndDerivatives(index_t index, double* der, std::size_t der_size)const { plumed_assert(indexsecond; + if(it!=map_.end()) { + value=it->second; + } const auto itder=der_.find(index); if(itder!=der_.end()) { const auto & second(itder->second); - for(unsigned i=0; isecond[i]; + for(unsigned i=0; isecond[i]; + } } return value; } @@ -786,7 +967,9 @@ void SparseGrid::addValueAndDerivatives(index_t index, double value, std::vector plumed_assert(index0 && dimension_>1 && getIndices(i)[dimension_-2]==0) ofile.printf("\n"); + if(usederiv_) { + f=getValueAndDerivatives(i,der); + } else { + f=getValue(i); + } + if(i>0 && dimension_>1 && getIndices(i)[dimension_-2]==0) { + ofile.printf("\n"); + } for(unsigned j=0; j(nbin_[j]) ); - if( pbc_[j] ) ofile.printField("periodic_" + argnames[j], "true" ); - else ofile.printField("periodic_" + argnames[j], "false" ); + if( pbc_[j] ) { + ofile.printField("periodic_" + argnames[j], "true" ); + } else { + ofile.printField("periodic_" + argnames[j], "false" ); + } + } + for(unsigned j=0; jmaxval) maxval=i.second; + if(i.second>maxval) { + maxval=i.second; + } } return maxval; } @@ -853,7 +1054,9 @@ void Grid::projectOnLowDimension(double &val, std::vector &vHigh, WeightBas // std::cerr< vv(vHigh.size()); - for(unsigned j=0; j & proj, WeightBase *ptr2obj ) // check if the two key methods are there WeightBase* pp = dynamic_cast(ptr2obj); - if (!pp)plumed_merror("This WeightBase is not complete: you need a projectInnerLoop and projectOuterLoop "); + if (!pp) { + plumed_merror("This WeightBase is not complete: you need a projectInnerLoop and projectOuterLoop "); + } for(unsigned j=0; j & proj, WeightBase *ptr2obj ) for(unsigned i=0; i & proj, WeightBase *ptr2obj ) std::vector v; v=smallgrid.getIndices(i); std::vector vHigh((getArgNames()).size(),-1); - for(unsigned j=0; j & proj, WeightBase *ptr2obj ) } double Grid::integrate( std::vector& npoints ) { - plumed_dbg_assert( npoints.size()==dimension_ ); plumed_assert( dospline_ ); + plumed_dbg_assert( npoints.size()==dimension_ ); + plumed_assert( dospline_ ); - unsigned ntotgrid=1; double box_vol=1.0; + unsigned ntotgrid=1; + double box_vol=1.0; std::vector ispacing( npoints.size() ); for(unsigned j=0; j& npoints ) { } else { ispacing[j] = ( max_[j] - min_[j] ) / static_cast( npoints[j] ); } - ntotgrid*=npoints[j]; box_vol*=ispacing[j]; + ntotgrid*=npoints[j]; + box_vol*=ispacing[j]; } std::vector vals( dimension_ ); - std::vector t_index( dimension_ ); double integral=0.0; + std::vector t_index( dimension_ ); + double integral=0.0; for(unsigned i=0; i=2 ) t_index[dimension_-1]=((kk-t_index[dimension_-2])/npoints[dimension_-2]); + for(unsigned j=1; j=2 ) { + t_index[dimension_-1]=((kk-t_index[dimension_-2])/npoints[dimension_-2]); + } - for(unsigned j=0; j& npoints ) { } void Grid::mpiSumValuesAndDerivatives( Communicator& comm ) { - comm.Sum( grid_ ); for(unsigned i=0; igetDimension()); + if(other.ptr) { + ptr=AcceleratorBase::create(other->getDimension()); + } } return *this; } @@ -251,7 +262,9 @@ class GridBase /// get argument names of this grid std::vector getArgNames() const; /// get if the grid has derivatives - bool hasDerivatives() const {return usederiv_;} + bool hasDerivatives() const { + return usederiv_; + } /// methods to handle grid indices void getIndices(index_t index, std::vector& rindex) const; @@ -330,17 +343,20 @@ class GridBase virtual ~GridBase() = default; /// set output format - void setOutputFmt(const std::string & ss) {fmt_=ss;} + void setOutputFmt(const std::string & ss) { + fmt_=ss; + } /// reset output format to the default %14.9f format - void resetToDefaultOutputFmt() {fmt_="%14.9f";} + void resetToDefaultOutputFmt() { + fmt_="%14.9f"; + } /// /// Find the maximum over paths of the minimum value of the gridded function along the paths /// for all paths of neighboring grid lattice points from a source point to a sink point. double findMaximalPathMinimum(const std::vector &source, const std::vector &sink); }; -class Grid : public GridBase -{ +class Grid : public GridBase { std::vector grid_; std::vector der_; double contour_location=0.0; @@ -348,20 +364,22 @@ class Grid : public GridBase Grid(const std::string& funcl, const std::vector & args, const std::vector & gmin, const std::vector & gmax, const std::vector & nbin, bool dospline, bool usederiv): - GridBase(funcl,args,gmin,gmax,nbin,dospline,usederiv) - { + GridBase(funcl,args,gmin,gmax,nbin,dospline,usederiv) { grid_.assign(maxsize_,0.0); - if(usederiv_) der_.assign(maxsize_*dimension_,0.0); + if(usederiv_) { + der_.assign(maxsize_*dimension_,0.0); + } } /// this constructor here is not Value-aware Grid(const std::string& funcl, const std::vector &names, const std::vector & gmin, const std::vector & gmax, const std::vector & nbin, bool dospline, bool usederiv, const std::vector &isperiodic, const std::vector &pmin, const std::vector &pmax ): - GridBase(funcl,names,gmin,gmax,nbin,dospline,usederiv,isperiodic,pmin,pmax) - { + GridBase(funcl,names,gmin,gmax,nbin,dospline,usederiv,isperiodic,pmin,pmax) { grid_.assign(maxsize_,0.0); - if(usederiv_) der_.assign(maxsize_*dimension_,0.0); + if(usederiv_) { + der_.assign(maxsize_*dimension_,0.0); + } } index_t getSize() const override; /// this is to access to Grid:: version of these methods (allowing overloading of virtual methods) @@ -415,8 +433,7 @@ class Grid : public GridBase }; -class SparseGrid : public GridBase -{ +class SparseGrid : public GridBase { std::map map_; std::map< index_t,std::vector > der_; @@ -499,7 +516,9 @@ void GridBase::getIndices(index_t index, unsigned* indices, std::size_t indices_ inline void GridBase::getIndices(index_t index, std::vector& indices) const { - if (indices.size()!=dimension_) indices.resize(dimension_); + if (indices.size()!=dimension_) { + indices.resize(dimension_); + } getIndices(index,indices.data(),indices.size()); } diff --git a/src/tools/HistogramBead.cpp b/src/tools/HistogramBead.cpp index eec7d7a312..0fb95191e1 100644 --- a/src/tools/HistogramBead.cpp +++ b/src/tools/HistogramBead.cpp @@ -101,8 +101,7 @@ HistogramBead::HistogramBead(): min(0.0), max(0.0), max_minus_min(0.0), - inv_max_minus_min(0.0) -{ + inv_max_minus_min(0.0) { } std::string HistogramBead::description() const { @@ -117,7 +116,9 @@ void HistogramBead::generateBins( const std::string& params, std::vector range(2); std::string smear; + unsigned nbins; + std::vector range(2); + std::string smear; bool found_nb=Tools::parse(data,"NBINS",nbins); plumed_massert(found_nb,"Number of bins in histogram not found"); bool found_r=Tools::parse(data,"LOWER",range[0]); @@ -126,9 +127,12 @@ void HistogramBead::generateBins( const std::string& params, std::vector( nbins ); + std::string lb,ub; + double delr = ( range[1]-range[0] ) / static_cast( nbins ); for(unsigned i=0; i=highb ) errormsg="Lower bound is higher than upper bound"; + if( !found_r ) { + errormsg="Upper bound has not been specified use UPPER"; + } + if( lowb>=highb ) { + errormsg="Lower bound is higher than upper bound"; + } - smear=0.5; Tools::parse(data,"SMEAR",smear); - width=smear*(highb-lowb); init=true; + smear=0.5; + Tools::parse(data,"SMEAR",smear); + width=smear*(highb-lowb); + init=true; } void HistogramBead::set( double l, double h, double w) { - init=true; lowb=l; highb=h; width=w; + init=true; + lowb=l; + highb=h; + width=w; const double DP2CUTOFF=6.25; - if( type==gaussian ) cutoff=std::sqrt(2.0*DP2CUTOFF); - else if( type==triangular ) cutoff=1.; - else plumed_error(); + if( type==gaussian ) { + cutoff=std::sqrt(2.0*DP2CUTOFF); + } else if( type==triangular ) { + cutoff=1.; + } else { + plumed_error(); + } } void HistogramBead::setKernelType( const std::string& ktype ) { - if(ktype=="gaussian") type=gaussian; - else if(ktype=="triangular") type=triangular; - else plumed_merror("cannot understand kernel type " + ktype ); + if(ktype=="gaussian") { + type=gaussian; + } else if(ktype=="triangular") { + type=triangular; + } else { + plumed_merror("cannot understand kernel type " + ktype ); + } } double HistogramBead::calculate( double x, double& df ) const { @@ -186,14 +216,26 @@ double HistogramBead::calculate( double x, double& df ) const { lowB = ( difference( x, lowb ) / width ); upperB = ( difference( x, highb ) / width ); df=0; - if( std::fabs(lowB)<1. ) df = (1 - std::fabs(lowB)) / width; - if( std::fabs(upperB)<1. ) df -= (1 - std::fabs(upperB)) / width; + if( std::fabs(lowB)<1. ) { + df = (1 - std::fabs(lowB)) / width; + } + if( std::fabs(upperB)<1. ) { + df -= (1 - std::fabs(upperB)) / width; + } if (upperB<=-1. || lowB >=1.) { f=0.; } else { double ia, ib; - if( lowB>-1.0 ) { ia=lowB; } else { ia=-1.0; } - if( upperB<1.0 ) { ib=upperB; } else { ib=1.0; } + if( lowB>-1.0 ) { + ia=lowB; + } else { + ia=-1.0; + } + if( upperB<1.0 ) { + ib=upperB; + } else { + ib=1.0; + } f = (ib*(2.-std::fabs(ib))-ia*(2.-std::fabs(ia)))*0.5; } } else { @@ -206,23 +248,40 @@ double HistogramBead::calculateWithCutoff( double x, double& df ) const { plumed_dbg_assert(init && periodicity!=unset ); double lowB, upperB, f; - lowB = difference( x, lowb ) / width ; upperB = difference( x, highb ) / width; - if( upperB<=-cutoff || lowB>=cutoff ) { df=0; return 0; } + lowB = difference( x, lowb ) / width ; + upperB = difference( x, highb ) / width; + if( upperB<=-cutoff || lowB>=cutoff ) { + df=0; + return 0; + } if( type==gaussian ) { - lowB /= std::sqrt(2.0); upperB /= std::sqrt(2.0); + lowB /= std::sqrt(2.0); + upperB /= std::sqrt(2.0); df = ( exp( -lowB*lowB ) - exp( -upperB*upperB ) ) / ( std::sqrt(2*pi)*width ); f = 0.5*( erf( upperB ) - erf( lowB ) ); } else if( type==triangular ) { df=0; - if( std::fabs(lowB)<1. ) df = (1 - std::fabs(lowB)) / width; - if( std::fabs(upperB)<1. ) df -= (1 - std::fabs(upperB)) / width; + if( std::fabs(lowB)<1. ) { + df = (1 - std::fabs(lowB)) / width; + } + if( std::fabs(upperB)<1. ) { + df -= (1 - std::fabs(upperB)) / width; + } if (upperB<=-1. || lowB >=1.) { f=0.; } else { double ia, ib; - if( lowB>-1.0 ) { ia=lowB; } else { ia=-1.0; } - if( upperB<1.0 ) { ib=upperB; } else { ib=1.0; } + if( lowB>-1.0 ) { + ia=lowB; + } else { + ia=-1.0; + } + if( upperB<1.0 ) { + ib=upperB; + } else { + ib=1.0; + } f = (ib*(2.-std::fabs(ib))-ia*(2.-std::fabs(ia)))*0.5; } } else { diff --git a/src/tools/HistogramBead.h b/src/tools/HistogramBead.h index 247ec47c52..35d3bd0ca9 100644 --- a/src/tools/HistogramBead.h +++ b/src/tools/HistogramBead.h @@ -80,20 +80,28 @@ void HistogramBead::isNotPeriodic() { inline void HistogramBead::isPeriodic( const double& mlow, const double& mhigh ) { - periodicity=periodic; min=mlow; max=mhigh; + periodicity=periodic; + min=mlow; + max=mhigh; max_minus_min=max-min; plumed_massert(max_minus_min>0, "your function has a very strange domain?"); inv_max_minus_min=1.0/max_minus_min; } inline -double HistogramBead::getlowb() const { return lowb; } +double HistogramBead::getlowb() const { + return lowb; +} inline -double HistogramBead::getbigb() const { return highb; } +double HistogramBead::getbigb() const { + return highb; +} inline -double HistogramBead::getCutoff() const { return cutoff*width; } +double HistogramBead::getCutoff() const { + return cutoff*width; +} inline double HistogramBead::difference( const double& d1, const double& d2 ) const { @@ -105,7 +113,9 @@ double HistogramBead::difference( const double& d1, const double& d2 ) const { newx=Tools::pbc(newx); newx*=max_minus_min; return d2-newx; - } else plumed_merror("periodicty was not set"); + } else { + plumed_merror("periodicty was not set"); + } return 0; } diff --git a/src/tools/IFile.cpp b/src/tools/IFile.cpp index 760400ede6..444bd69a1c 100644 --- a/src/tools/IFile.cpp +++ b/src/tools/IFile.cpp @@ -44,16 +44,24 @@ size_t IFile::llread(char*ptr,size_t s) { if(gzfp) { #ifdef __PLUMED_HAS_ZLIB int rr=gzread(gzFile(gzfp),ptr,s); - if(rr==0) eof=true; - if(rr<0) err=true; + if(rr==0) { + eof=true; + } + if(rr<0) { + err=true; + } r=rr; #else plumed_merror("file " + getPath() + ": trying to use a gz file without zlib being linked"); #endif } else { r=std::fread(ptr,1,s,fp); - if(std::feof(fp)) eof=true; - if(std::ferror(fp)) err=true; + if(std::feof(fp)) { + eof=true; + } + if(std::ferror(fp)) { + err=true; + } } return r; } @@ -65,7 +73,9 @@ IFile& IFile::advanceField() { while(!done) { getline(line); // using explicit conversion not to confuse cppcheck 1.86 - if(!bool(*this)) {return *this;} + if(!bool(*this)) { + return *this; + } std::vector words=Tools::getWords(line); if(words.size()>=2 && words[0]=="#!" && words[1]=="FIELDS") { fields.clear(); @@ -82,13 +92,18 @@ IFile& IFile::advanceField() { fields.push_back(field); } else { unsigned nf=0; - for(unsigned i=0; iinsertFile(*this); + if(plumed) { + plumed->insertFile(*this); + } return *this; } IFile& IFile::scanFieldList(std::vector&s) { - if(!inMiddleOfField) advanceField(); + if(!inMiddleOfField) { + advanceField(); + } // using explicit conversion not to confuse cppcheck 1.86 - if(!bool(*this)) return *this; + if(!bool(*this)) { + return *this; + } s.clear(); - for(unsigned i=0; i slist; scanFieldList(slist); int mycount = (int) std::count(slist.begin(), slist.end(), s); - if(mycount>0) return true; - else return false; + if(mycount>0) { + return true; + } else { + return false; + } } IFile& IFile::scanField(const std::string&name,std::string&str) { - if(!inMiddleOfField) advanceField(); + if(!inMiddleOfField) { + advanceField(); + } // using explicit conversion not to confuse cppcheck 1.86 - if(!bool(*this)) return *this; + if(!bool(*this)) { + return *this; + } unsigned i=findField(name); str=fields[i].value; fields[i].read=true; @@ -154,49 +183,63 @@ IFile& IFile::scanField(const std::string&name,std::string&str) { IFile& IFile::scanField(const std::string&name,double &x) { std::string str; scanField(name,str); - if(*this) Tools::convert(str,x); + if(*this) { + Tools::convert(str,x); + } return *this; } IFile& IFile::scanField(const std::string&name,int &x) { std::string str; scanField(name,str); - if(*this) Tools::convert(str,x); + if(*this) { + Tools::convert(str,x); + } return *this; } IFile& IFile::scanField(const std::string&name,long int &x) { std::string str; scanField(name,str); - if(*this) Tools::convert(str,x); + if(*this) { + Tools::convert(str,x); + } return *this; } IFile& IFile::scanField(const std::string&name,long long int &x) { std::string str; scanField(name,str); - if(*this) Tools::convert(str,x); + if(*this) { + Tools::convert(str,x); + } return *this; } IFile& IFile::scanField(const std::string&name,unsigned &x) { std::string str; scanField(name,str); - if(*this) Tools::convert(str,x); + if(*this) { + Tools::convert(str,x); + } return *this; } IFile& IFile::scanField(const std::string&name,long unsigned &x) { std::string str; scanField(name,str); - if(*this) Tools::convert(str,x); + if(*this) { + Tools::convert(str,x); + } return *this; } IFile& IFile::scanField(const std::string&name,long long unsigned &x) { std::string str; scanField(name,str); - if(*this) Tools::convert(str,x); + if(*this) { + Tools::convert(str,x); + } return *this; } @@ -228,12 +271,13 @@ IFile& IFile::scanField() { IFile::IFile(): inMiddleOfField(false), ignoreFields(false), - noEOL(false) -{ + noEOL(false) { } IFile::~IFile() { - if(inMiddleOfField) std::cerr<<"WARNING: IFile closed in the middle of reading. seems strange!\n"; + if(inMiddleOfField) { + std::cerr<<"WARNING: IFile closed in the middle of reading. seems strange!\n"; + } } IFile& IFile::getline(std::string &str) { @@ -249,11 +293,15 @@ IFile& IFile::getline(std::string &str) { plumed_massert(tmp=='\n',"plumed only accepts \\n (unix) or \\r\\n (dos) new lines"); } if(eof && noEOL) { - if(str.length()>0) eof=false; + if(str.length()>0) { + eof=false; + } } else if(eof || err || tmp!='\n') { eof = true; str=""; - if(!err) fsetpos(fp,&pos); + if(!err) { + fsetpos(fp,&pos); + } // there was a fsetpos here that apparently is not necessary // fsetpos(fp,&pos); // I think it was necessary to have rewind working correctly @@ -267,7 +315,10 @@ IFile& IFile::getline(std::string &str) { unsigned IFile::findField(const std::string&name)const { unsigned i; - for(i=0; i=fields.size()) { plumed_merror("file " + getPath() + ": field " + name + " cannot be found"); } @@ -277,9 +328,13 @@ unsigned IFile::findField(const std::string&name)const { void IFile::reset(bool reset) { eof = reset; err = reset; - if(!reset && fp) clearerr(fp); + if(!reset && fp) { + clearerr(fp); + } #ifdef __PLUMED_HAS_ZLIB - if(!reset && gzfp) gzclearerr(gzFile(gzfp)); + if(!reset && gzfp) { + gzclearerr(gzFile(gzfp)); + } #endif return; } diff --git a/src/tools/KernelFunctions.cpp b/src/tools/KernelFunctions.cpp index b824d7048d..ad69465590 100644 --- a/src/tools/KernelFunctions.cpp +++ b/src/tools/KernelFunctions.cpp @@ -105,26 +105,48 @@ KernelFunctions::KernelFunctions( const std::string& input ) { std::vector at; bool foundc = Tools::parseVector(data,"CENTER",at); - if(!foundc) plumed_merror("failed to find center keyword in definition of kernel"); + if(!foundc) { + plumed_merror("failed to find center keyword in definition of kernel"); + } std::vector sig; bool founds = Tools::parseVector(data,"SIGMA",sig); - if(!founds) plumed_merror("failed to find sigma keyword in definition of kernel"); + if(!founds) { + plumed_merror("failed to find sigma keyword in definition of kernel"); + } - bool multi=false; Tools::parseFlag(data,"MULTIVARIATE",multi); - bool vonmises=false; Tools::parseFlag(data,"VON-MISSES",vonmises); - if( center.size()==1 && multi ) plumed_merror("one dimensional kernel cannot be multivariate"); - if( center.size()==1 && vonmises ) plumed_merror("one dimensional kernal cannot be von-misses"); - if( center.size()==1 && sig.size()!=1 ) plumed_merror("size mismatch between center size and sigma size"); - if( multi && center.size()>1 && sig.size()!=0.5*center.size()*(center.size()-1) ) plumed_merror("size mismatch between center size and sigma size"); - if( !multi && center.size()>1 && sig.size()!=center.size() ) plumed_merror("size mismatch between center size and sigma size"); + bool multi=false; + Tools::parseFlag(data,"MULTIVARIATE",multi); + bool vonmises=false; + Tools::parseFlag(data,"VON-MISSES",vonmises); + if( center.size()==1 && multi ) { + plumed_merror("one dimensional kernel cannot be multivariate"); + } + if( center.size()==1 && vonmises ) { + plumed_merror("one dimensional kernal cannot be von-misses"); + } + if( center.size()==1 && sig.size()!=1 ) { + plumed_merror("size mismatch between center size and sigma size"); + } + if( multi && center.size()>1 && sig.size()!=0.5*center.size()*(center.size()-1) ) { + plumed_merror("size mismatch between center size and sigma size"); + } + if( !multi && center.size()>1 && sig.size()!=center.size() ) { + plumed_merror("size mismatch between center size and sigma size"); + } double h; bool foundh = Tools::parse(data,"HEIGHT",h); - if( !foundh) h=1.0; + if( !foundh) { + h=1.0; + } - if( multi ) setData( at, sig, name, "MULTIVARIATE", h ); - else if( vonmises ) setData( at, sig, name, "VON-MISSES", h ); - else setData( at, sig, name, "DIAGONAL", h ); + if( multi ) { + setData( at, sig, name, "MULTIVARIATE", h ); + } else if( vonmises ) { + setData( at, sig, name, "VON-MISSES", h ); + } else { + setData( at, sig, name, "DIAGONAL", h ); + } } KernelFunctions::KernelFunctions( const std::vector& at, const std::vector& sig, const std::string& type, const std::string& mtype, const double& w ) { @@ -142,8 +164,7 @@ KernelFunctions::KernelFunctions( const KernelFunctions* in ): ktype(in->ktype), center(in->center), width(in->width), - height(in->height) -{ + height(in->height) { if(!dp2cutoffNoStretch()) { stretchA=dp2cutoffA; stretchB=dp2cutoffB; @@ -153,12 +174,23 @@ KernelFunctions::KernelFunctions( const KernelFunctions* in ): void KernelFunctions::setData( const std::vector& at, const std::vector& sig, const std::string& type, const std::string& mtype, const double& w ) { height=w; - center.resize( at.size() ); for(unsigned i=0; i& myvals ) { double det=1.; unsigned ncv=ndim(); if(dtype==diagonal) { - for(unsigned i=0; i mymatrix( getMatrix() ), myinv( ncv, ncv ); - Invert(mymatrix,myinv); double logd; + Invert(mymatrix,myinv); + double logd; logdet( myinv, logd ); det=std::exp(logd); } @@ -199,15 +234,22 @@ void KernelFunctions::normalize( const std::vector& myvals ) { } else if( ktype==uniform || ktype==triangular ) { if( ncv%2==1 ) { double dfact=1; - for(unsigned i=1; i(i); + for(unsigned i=1; i(i); + } volume=( pow( pi, (ncv-1)/2 ) ) * ( pow( 2., (ncv+1)/2 ) ) / dfact; } else { double fact=1.; - for(unsigned i=1; i(i); + for(unsigned i=1; i(i); + } volume=pow( pi,ncv/2 ) / fact; } - if(ktype==uniform) volume*=det; - else if(ktype==triangular) volume*=det / 3.; + if(ktype==uniform) { + volume*=det; + } else if(ktype==triangular) { + volume*=det / 3.; + } } else { plumed_merror("not a valid kernel type"); } @@ -218,7 +260,9 @@ void KernelFunctions::normalize( const std::vector& myvals ) { // Now calculate determinant for aperiodic variables unsigned naper=0; for(unsigned i=0; iisPeriodic() ) naper++; + if( !myvals[i]->isPeriodic() ) { + naper++; + } } // Now construct sub matrix double volume=1; @@ -226,16 +270,23 @@ void KernelFunctions::normalize( const std::vector& myvals ) { unsigned isub=0; Matrix mymatrix( getMatrix() ), mysub( naper, naper ); for(unsigned i=0; iisPeriodic() ) continue; + if( myvals[i]->isPeriodic() ) { + continue; + } unsigned jsub=0; for(unsigned j=0; jisPeriodic() ) continue; - mysub( isub, jsub ) = mymatrix( i, j ); jsub++; + if( myvals[j]->isPeriodic() ) { + continue; + } + mysub( isub, jsub ) = mymatrix( i, j ); + jsub++; } isub++; } - Matrix myisub( naper, naper ); double logd; - Invert( mysub, myisub ); logdet( myisub, logd ); + Matrix myisub( naper, naper ); + double logd; + Invert( mysub, myisub ); + logdet( myisub, logd ); det=std::exp(logd); volume=pow( 2*pi, 0.5*ncv ) * pow( det, 0.5 ); } @@ -243,7 +294,9 @@ void KernelFunctions::normalize( const std::vector& myvals ) { // Calculate volume of periodic variables unsigned nper=0; for(unsigned i=0; iisPeriodic() ) nper++; + if( myvals[i]->isPeriodic() ) { + nper++; + } } // Now construct sub matrix @@ -251,18 +304,24 @@ void KernelFunctions::normalize( const std::vector& myvals ) { unsigned isub=0; Matrix mymatrix( getMatrix() ), mysub( nper, nper ); for(unsigned i=0; iisPeriodic() ) continue; + if( !myvals[i]->isPeriodic() ) { + continue; + } unsigned jsub=0; for(unsigned j=0; jisPeriodic() ) continue; - mysub( isub, jsub ) = mymatrix( i, j ); jsub++; + if( !myvals[j]->isPeriodic() ) { + continue; + } + mysub( isub, jsub ) = mymatrix( i, j ); + jsub++; } isub++; } Matrix eigvec( nper, nper ); std::vector eigval( nper ); diagMat( mysub, eigval, eigvec ); - unsigned iper=0; volume=1; + unsigned iper=0; + volume=1; for(unsigned i=0; iisPeriodic() ) { volume *= myvals[i]->getMaxMinusMin()*Tools::bessel0(eigval[iper])*std::exp(-eigval[iper]); @@ -275,10 +334,15 @@ void KernelFunctions::normalize( const std::vector& myvals ) { double KernelFunctions::getCutoff( const double& width ) const { const double DP2CUTOFF=6.25; - if( ktype==gaussian || ktype==truncatedgaussian || ktype==stretchedgaussian ) return std::sqrt(2.0*DP2CUTOFF)*width; - else if(ktype==triangular ) return width; - else if(ktype==uniform) return width; - else plumed_merror("No valid kernel type"); + if( ktype==gaussian || ktype==truncatedgaussian || ktype==stretchedgaussian ) { + return std::sqrt(2.0*DP2CUTOFF)*width; + } else if(ktype==triangular ) { + return width; + } else if(ktype==uniform) { + return width; + } else { + plumed_merror("No valid kernel type"); + } return 0.0; } @@ -286,16 +350,22 @@ std::vector KernelFunctions::getContinuousSupport( ) const { unsigned ncv=ndim(); std::vector support( ncv ); if(dtype==diagonal) { - for(unsigned i=0; i mymatrix( getMatrix() ), myinv( ncv,ncv ); Invert(mymatrix,myinv); - Matrix myautovec(ncv,ncv); std::vector myautoval(ncv); + Matrix myautovec(ncv,ncv); + std::vector myautoval(ncv); diagMat(myinv,myautoval,myautovec); double maxautoval=0.; unsigned ind_maxautoval=0; for (unsigned i=0; imaxautoval) {maxautoval=myautoval[i]; ind_maxautoval=i;} + if(myautoval[i]>maxautoval) { + maxautoval=myautoval[i]; + ind_maxautoval=i; + } } for(unsigned i=0; i KernelFunctions::getSupport( const std::vector& dx plumed_assert( ndim()==dx.size() ); std::vector support( dx.size() ); std::vector vv=getContinuousSupport( ); - for(unsigned i=0; i(ceil( vv[i]/dx[i] )); + for(unsigned i=0; i(ceil( vv[i]/dx[i] )); + } return support; } double KernelFunctions::evaluate( const std::vector& pos, std::vector& derivatives, bool usederiv, bool doInt, double lowI_, double uppI_) const { plumed_dbg_assert( pos.size()==ndim() && derivatives.size()==ndim() ); #ifndef NDEBUG - if( usederiv ) plumed_massert( ktype!=uniform, "step function can not be differentiated" ); + if( usederiv ) { + plumed_massert( ktype!=uniform, "step function can not be differentiated" ); + } #endif if(doInt) { plumed_dbg_assert(center.size()==1); - if(pos[0]->get()set(lowI_); - if(pos[0]->get()>uppI_) pos[0]->set(uppI_); + if(pos[0]->get()set(lowI_); + } + if(pos[0]->get()>uppI_) { + pos[0]->set(uppI_); + } } double r2=0; if(dtype==diagonal) { @@ -335,11 +413,15 @@ double KernelFunctions::evaluate( const std::vector& pos, std::vector mymatrix( getMatrix() ); for(unsigned i=0; idifference( center[i] ); for(unsigned j=0; jdifference( center[j] ); + if(i==j) { + dp_j=dp_i; + } else { + dp_j=-pos[j]->difference( center[j] ); + } derivatives[i]+=mymatrix(i,j)*dp_j; r2+=dp_i*dp_j*mymatrix(i,j); @@ -366,16 +448,23 @@ double KernelFunctions::evaluate( const std::vector& pos, std::vectorisPeriodic() ) derivatives[i] *= (2*pi/pos[i]->getMaxMinusMin()); + if( pos[i]->isPeriodic() ) { + derivatives[i] *= (2*pi/pos[i]->getMaxMinusMin()); + } + } + for(unsigned i=0; i& pos, std::vectorget() <= lowI_ || pos[0]->get() >= uppI_) && usederiv ) for(unsigned i=0; iget() <= lowI_ || pos[0]->get() >= uppI_) && usederiv ) + for(unsigned i=0; i KernelFunctions::read( IFile* ifile, const bool& cholesky, const std::vector& valnames ) { double h; - if( !ifile->scanField("height",h) ) return NULL;; - - std::string sss; ifile->scanField("multivariate",sss); - std::string ktype="stretched-gaussian"; if( ifile->FieldExist("kerneltype") ) ifile->scanField("kerneltype",ktype); + if( !ifile->scanField("height",h) ) { + return NULL; + }; + + std::string sss; + ifile->scanField("multivariate",sss); + std::string ktype="stretched-gaussian"; + if( ifile->FieldExist("kerneltype") ) { + ifile->scanField("kerneltype",ktype); + } plumed_massert( sss=="false" || sss=="true" || sss=="von-misses", "multivariate flag must be either false, true or von-misses"); // Read the position of the center std::vector cc( valnames.size() ); - for(unsigned i=0; iscanField(valnames[i],cc[i]); + for(unsigned i=0; iscanField(valnames[i],cc[i]); + } std::vector sig; if( sss=="false" ) { sig.resize( valnames.size() ); for(unsigned i=0; iscanField("sigma_"+valnames[i],sig[i]); - if( !cholesky ) sig[i]=std::sqrt(sig[i]); + if( !cholesky ) { + sig[i]=std::sqrt(sig[i]); + } } return Tools::make_unique(cc, sig, ktype, "DIAGONAL", h); } @@ -439,16 +550,24 @@ std::unique_ptr KernelFunctions::read( IFile* ifile, const bool for(unsigned i=0; iscanField("sigma_" +valnames[j+i] + "_" + valnames[j], lower(j+i,j) ); - upper(j,j+i)=lower(j+i,j); mymult(j+i,j)=mymult(j,j+i)=lower(j+i,j); + upper(j,j+i)=lower(j+i,j); + mymult(j+i,j)=mymult(j,j+i)=lower(j+i,j); } } - if( cholesky ) mult(lower,upper,mymult); + if( cholesky ) { + mult(lower,upper,mymult); + } Invert( mymult, invmatrix ); unsigned k=0; for(unsigned i=0; i(cc, sig, ktype, "MULTIVARIATE", h); } - if( sss=="true" ) return Tools::make_unique(cc, sig, ktype, "MULTIVARIATE", h); return Tools::make_unique( cc, sig, ktype, "VON-MISSES", h ); } diff --git a/src/tools/KernelFunctions.h b/src/tools/KernelFunctions.h index 7e9def564a..72b1ba9c42 100644 --- a/src/tools/KernelFunctions.h +++ b/src/tools/KernelFunctions.h @@ -73,7 +73,8 @@ class KernelFunctions { inline Matrix KernelFunctions::getMatrix() const { - unsigned k=0, ncv=ndim(); Matrix mymatrix(ncv,ncv); + unsigned k=0, ncv=ndim(); + Matrix mymatrix(ncv,ncv); for(unsigned i=0; i& kk, std::vector& std::map& cd ) const { for(unsigned i=0; i( thiskey,types.find(thiskey)->second) ); - if( (types.find(thiskey)->second).isAtomList() ) atags.insert( std::pair( thiskey,atomtags.find(thiskey)->second) ); + if( (types.find(thiskey)->second).isAtomList() ) { + atags.insert( std::pair( thiskey,atomtags.find(thiskey)->second) ); + } plumed_massert( allowmultiple.count( thiskey ), "no numbered data on keyword " + thiskey + " to copy" ); am.insert( std::pair(thiskey,allowmultiple.find(thiskey)->second) ); plumed_massert( documentation.count( thiskey ), "no documentation for keyword " + thiskey + " to copy" ); docs.insert( std::pair(thiskey,documentation.find(thiskey)->second) ); - if( booldefs.count( thiskey ) ) bools.insert( std::pair( thiskey,booldefs.find(thiskey)->second) ); - if( numdefs.count( thiskey ) ) nums.insert( std::pair( thiskey,numdefs.find(thiskey)->second) ); + if( booldefs.count( thiskey ) ) { + bools.insert( std::pair( thiskey,booldefs.find(thiskey)->second) ); + } + if( numdefs.count( thiskey ) ) { + nums.insert( std::pair( thiskey,numdefs.find(thiskey)->second) ); + } } for(unsigned i=0; i( thiskey,types.find(thiskey)->second) ); - if( (types.find(thiskey)->second).isAtomList() ) atags.insert( std::pair( thiskey,atomtags.find(thiskey)->second) ); + if( (types.find(thiskey)->second).isAtomList() ) { + atags.insert( std::pair( thiskey,atomtags.find(thiskey)->second) ); + } plumed_massert( allowmultiple.count( thiskey ), "no numbered data on keyword " + thiskey + " to copy" ); am.insert( std::pair(thiskey,allowmultiple.find(thiskey)->second) ); plumed_massert( documentation.count( thiskey ), "no documentation for keyword " + thiskey + " to copy" ); docs.insert( std::pair(thiskey,documentation.find(thiskey)->second) ); - if( booldefs.count( thiskey ) ) bools.insert( std::pair( thiskey,booldefs.find(thiskey)->second) ); - if( numdefs.count( thiskey ) ) nums.insert( std::pair( thiskey,numdefs.find(thiskey)->second) ); + if( booldefs.count( thiskey ) ) { + bools.insert( std::pair( thiskey,booldefs.find(thiskey)->second) ); + } + if( numdefs.count( thiskey ) ) { + nums.insert( std::pair( thiskey,numdefs.find(thiskey)->second) ); + } } for(unsigned i=0; i( thisnam, ckey.find(thisnam)->second) ); @@ -121,19 +143,24 @@ void Keywords::reserve( const std::string & t, const std::string & k, const std: plumed_assert( !exists(k) && !reserved(k) ); std::string fd, lowkey=k; // Convert to lower case - std::transform(lowkey.begin(),lowkey.end(),lowkey.begin(),[](unsigned char c) { return std::tolower(c); }); + std::transform(lowkey.begin(),lowkey.end(),lowkey.begin(),[](unsigned char c) { + return std::tolower(c); + }); // Remove any underscore characters for(unsigned i=0;; ++i) { std::size_t num=lowkey.find_first_of("_"); - if( num==std::string::npos ) break; + if( num==std::string::npos ) { + break; + } lowkey.erase( lowkey.begin() + num, lowkey.begin() + num + 1 ); } if( t=="vessel" ) { fd = d + " The final value can be referenced using label." + lowkey; - if(d.find("flag")==std::string::npos) fd += ". You can use multiple instances of this keyword i.e. " + - k +"1, " + k + "2, " + k + "3... The corresponding values are then " - "referenced using label."+ lowkey +"-1, label." + lowkey + - "-2, label." + lowkey + "-3..."; + if(d.find("flag")==std::string::npos) + fd += ". You can use multiple instances of this keyword i.e. " + + k +"1, " + k + "2, " + k + "3... The corresponding values are then " + "referenced using label."+ lowkey +"-1, label." + lowkey + + "-2, label." + lowkey + "-3..."; allowmultiple.insert( std::pair(k,true) ); types.insert( std::pair(k,KeyType("vessel")) ); } else if( t=="numbered" ) { @@ -142,10 +169,14 @@ void Keywords::reserve( const std::string & t, const std::string & k, const std: types.insert( std::pair(k,KeyType("optional")) ); } else { fd = d; - if( t=="atoms" && isaction ) fd = d + ". For more information on how to specify lists of atoms see \\ref Group"; + if( t=="atoms" && isaction ) { + fd = d + ". For more information on how to specify lists of atoms see \\ref Group"; + } allowmultiple.insert( std::pair(k,false) ); types.insert( std::pair(k,KeyType(t)) ); - if( (types.find(k)->second).isAtomList() ) atomtags.insert( std::pair(k,t) ); + if( (types.find(k)->second).isAtomList() ) { + atomtags.insert( std::pair(k,t) ); + } } documentation.insert( std::pair(k,fd) ); reserved_keys.push_back(k); @@ -154,9 +185,16 @@ void Keywords::reserve( const std::string & t, const std::string & k, const std: void Keywords::reserveFlag( const std::string & k, const bool def, const std::string & d ) { plumed_assert( !exists(k) && !reserved(k) ); std::string defstr; - if( def ) { defstr="( default=on ) "; } else { defstr="( default=off ) "; } + if( def ) { + defstr="( default=on ) "; + } else { + defstr="( default=off ) "; + } types.insert( std::pair(k,KeyType("flag")) ); - std::string fd,lowkey=k; std::transform(lowkey.begin(),lowkey.end(),lowkey.begin(),[](unsigned char c) { return std::tolower(c); }); + std::string fd,lowkey=k; + std::transform(lowkey.begin(),lowkey.end(),lowkey.begin(),[](unsigned char c) { + return std::tolower(c); + }); fd=defstr + d; documentation.insert( std::pair(k,fd) ); allowmultiple.insert( std::pair(k,false) ); @@ -167,16 +205,25 @@ void Keywords::reserveFlag( const std::string & k, const bool def, const std::st void Keywords::use( const std::string & k ) { plumed_massert( reserved(k), "the " + k + " keyword is not reserved"); for(unsigned i=0; isecond).setStyle(style); - if( (types.find(k)->second).isVessel() ) allowmultiple[k]=true; - if( (types.find(k)->second).isAtomList() ) atomtags.insert( std::pair(k,style) ); + if( (types.find(k)->second).isVessel() ) { + allowmultiple[k]=true; + } + if( (types.find(k)->second).isAtomList() ) { + atomtags.insert( std::pair(k,style) ); + } } void Keywords::add( const std::string & t, const std::string & k, const std::string & d ) { @@ -190,9 +237,13 @@ void Keywords::add( const std::string & t, const std::string & k, const std::str fd=d; allowmultiple.insert( std::pair(k,false) ); types.insert( std::pair(k,KeyType(t)) ); - if( (types.find(k)->second).isAtomList() ) atomtags.insert( std::pair(k,t) ); + if( (types.find(k)->second).isAtomList() ) { + atomtags.insert( std::pair(k,t) ); + } + } + if( t=="atoms" && isaction ) { + fd = d + ". For more information on how to specify lists of atoms see \\ref Group"; } - if( t=="atoms" && isaction ) fd = d + ". For more information on how to specify lists of atoms see \\ref Group"; documentation.insert( std::pair(k,fd) ); keys.push_back(k); } @@ -208,7 +259,8 @@ void Keywords::add( const std::string & t, const std::string & k, const std::str void Keywords::addFlag( const std::string & k, const bool def, const std::string & d ) { plumed_massert( !exists(k) && !reserved(k), "keyword " + k + " has already been registered"); - std::string defstr; plumed_massert( !def, "the second argument to addFlag must be false " + k ); + std::string defstr; + plumed_massert( !def, "the second argument to addFlag must be false " + k ); defstr="( default=off ) "; types.insert( std::pair(k,KeyType("flag")) ); documentation.insert( std::pair(k,defstr + d) ); @@ -218,36 +270,55 @@ void Keywords::addFlag( const std::string & k, const bool def, const std::string } void Keywords::remove( const std::string & k ) { - bool found=false; unsigned j=0, n=0; + bool found=false; + unsigned j=0, n=0; while(true) { - for(j=0; jsecond; } bool Keywords::style( const std::string & k, const std::string & t ) const { - if( getStyle(k)==t ) return true; + if( getStyle(k)==t ) { + return true; + } return false; } @@ -262,14 +333,18 @@ std::string Keywords::getKeyword( const unsigned i ) const { bool Keywords::exists( const std::string & k ) const { for(unsigned i=0; isecond).isAtomList() ) nkeys++; + if ( (types.find(keys[i])->second).isAtomList() ) { + nkeys++; + } } if( nkeys>0 ) { std::string prevtag="start"; for(unsigned i=0; isecond).isAtomList() ) { plumed_massert( atomtags.count(keys[i]), "keyword " + keys[i] + " allegedly specifies atoms but no tag has been specified. Please email Gareth Tribello"); - if( prevtag!="start" && prevtag!=atomtags.find(keys[i])->second ) break; - if( (atomtags.find(keys[i])->second).find("residues")!=std::string::npos) std::printf(" %s=", keys[i].c_str() ); - else std::printf(" %s=", keys[i].c_str() ); + if( prevtag!="start" && prevtag!=atomtags.find(keys[i])->second ) { + break; + } + if( (atomtags.find(keys[i])->second).find("residues")!=std::string::npos) { + std::printf(" %s=", keys[i].c_str() ); + } else { + std::printf(" %s=", keys[i].c_str() ); + } prevtag=atomtags.find(keys[i])->second; } } @@ -295,7 +377,9 @@ void Keywords::print_template(const std::string& actionname, bool include_option nkeys=0; for(unsigned i=0; isecond).isCompulsory() ) nkeys++; + (types.find(keys[i])->second).isCompulsory() ) { + nkeys++; + } } if( nkeys>0 ) { for(unsigned i=0; isecond).isFlag() ) { std::printf( ",flag:%s", keys[i].c_str() ); } else { - if( allowmultiple.find(keys[i])->second ) std::printf(",numbered:%s",keys[i].c_str() ); - else std::printf(",option:%s",keys[i].c_str() ); + if( allowmultiple.find(keys[i])->second ) { + std::printf(",numbered:%s",keys[i].c_str() ); + } else { + std::printf(",option:%s",keys[i].c_str() ); + } } } std::fprintf(stdout, "\n%s", getHelpString().c_str() ); @@ -334,7 +421,9 @@ void Keywords::print_html() const { if( cnames.size()>0 ) { unsigned ndef=0; for(unsigned i=0; isecond=="default") ndef++; + if(ckey.find(cnames[i])->second=="default") { + ndef++; + } } if( ndef>0 ) { @@ -345,7 +434,10 @@ void Keywords::print_html() const { unsigned nndef=0; for(unsigned i=0; isecond=="default" ); - if( ckey.find(cnames[i])->second!="default" ) { nndef++; continue; } + if( ckey.find(cnames[i])->second!="default" ) { + nndef++; + continue; + } std::printf("\n"); std::printf(" %s \n",cnames[i].c_str() ); std::printf(" %s \n",(cdocs.find(cnames[i])->second).c_str() ); @@ -371,7 +463,9 @@ void Keywords::print_html() const { } else { unsigned nregs=0; for(unsigned i=0; isecond) ) nregs++; + if( exists(ckey.find(cnames[i])->second) ) { + nregs++; + } } if( nregs>0 ) { std::cout<<"\\par Description of components\n\n"; @@ -394,22 +488,34 @@ void Keywords::print_html() const { unsigned nkeys=0; for(unsigned i=0; isecond).isAtomList() ) nkeys++; + if ( (types.find(keys[i])->second).isAtomList() ) { + nkeys++; + } } if( nkeys>0 ) { - if(isaction && isatoms) std::cout<<"\\par The atoms involved can be specified using\n\n"; - else if(isaction) std::cout<<"\\par The data to analyze can be the output from another analysis algorithm\n\n"; - else std::cout<<"\\par The input trajectory is specified using one of the following\n\n"; + if(isaction && isatoms) { + std::cout<<"\\par The atoms involved can be specified using\n\n"; + } else if(isaction) { + std::cout<<"\\par The data to analyze can be the output from another analysis algorithm\n\n"; + } else { + std::cout<<"\\par The input trajectory is specified using one of the following\n\n"; + } std::cout<<" \n"; - std::string prevtag="start"; unsigned counter=0; + std::string prevtag="start"; + unsigned counter=0; for(unsigned i=0; isecond).isAtomList() ) { plumed_massert( atomtags.count(keys[i]), "keyword " + keys[i] + " allegedly specifies atoms but no tag has been specified. Please email Gareth Tribello"); if( prevtag!="start" && prevtag!=atomtags.find(keys[i])->second && isaction ) { std::cout<<"
\n\n"; - if( isatoms ) std::cout<<"\\par Or alternatively by using\n\n"; - else if( counter==0 ) { std::cout<<"\\par Alternatively data can be collected from the trajectory using \n\n"; counter++; } - else std::cout<<"\\par Lastly data collected in a previous analysis action can be reanalyzed by using the keyword \n\n"; + if( isatoms ) { + std::cout<<"\\par Or alternatively by using\n\n"; + } else if( counter==0 ) { + std::cout<<"\\par Alternatively data can be collected from the trajectory using \n\n"; + counter++; + } else { + std::cout<<"\\par Lastly data collected in a previous analysis action can be reanalyzed by using the keyword \n\n"; + } std::cout<<" \n"; } print_html_item( keys[i] ); @@ -420,102 +526,152 @@ void Keywords::print_html() const { } nkeys=0; for(unsigned i=0; isecond).isCompulsory() ) nkeys++; + if ( (types.find(keys[i])->second).isCompulsory() ) { + nkeys++; + } } if( nkeys>0 ) { - if(isaction) std::cout<< "\\par Compulsory keywords\n\n"; - else std::cout<<"\\par The following must be present\n\n"; + if(isaction) { + std::cout<< "\\par Compulsory keywords\n\n"; + } else { + std::cout<<"\\par The following must be present\n\n"; + } std::cout<<"
\n"; for(unsigned i=0; isecond).isCompulsory() ) print_html_item( keys[i] ); + if ( (types.find(keys[i])->second).isCompulsory() ) { + print_html_item( keys[i] ); + } } std::cout<<"
\n\n"; } nkeys=0; for(unsigned i=0; isecond).isFlag() || (types.find(keys[i])->second).isOptional() || (types.find(keys[i])->second).isVessel() ) nkeys++; + if ( (types.find(keys[i])->second).isFlag() || (types.find(keys[i])->second).isOptional() || (types.find(keys[i])->second).isVessel() ) { + nkeys++; + } } if( nkeys>0 ) { - if(isaction) std::cout<<"\\par Options\n\n"; - else std::cout<<"\\par The following options are available\n\n"; + if(isaction) { + std::cout<<"\\par Options\n\n"; + } else { + std::cout<<"\\par The following options are available\n\n"; + } std::cout<<" \n"; for(unsigned i=0; isecond).isFlag() ) print_html_item( keys[i] ); + if ( (types.find(keys[i])->second).isFlag() ) { + print_html_item( keys[i] ); + } } std::cout<<"\n"; } nkeys=0; for(unsigned i=0; isecond).isOptional() || (types.find(keys[i])->second).isVessel() ) nkeys++; + if ( (types.find(keys[i])->second).isOptional() || (types.find(keys[i])->second).isVessel() ) { + nkeys++; + } } if( nkeys>0 ) { for(unsigned i=0; isecond).isOptional() || (types.find(keys[i])->second).isVessel() ) print_html_item( keys[i] ); + if ( (types.find(keys[i])->second).isOptional() || (types.find(keys[i])->second).isVessel() ) { + print_html_item( keys[i] ); + } } } std::cout<<"
\n\n"; } void Keywords::print_spelling() const { - for(unsigned i=0; isecond).find("\\f$")!=std::string::npos ); // Check for latex std::vector w=Tools::getWords( documentation.find(key)->second ); - std::stringstream sstr; sstr<60 ) { - sstr<<"\n"<second).isAtomList() ) nkeys++; + if ( (types.find(keys[i])->second).isAtomList() ) { + nkeys++; + } } if( nkeys>0 ) { helpstr += "The input trajectory can be in any of the following formats: \n\n"; for(unsigned i=0; isecond).isAtomList() ) helpstr += getKeywordDocs( keys[i] ); + if ( (types.find(keys[i])->second).isAtomList() ) { + helpstr += getKeywordDocs( keys[i] ); + } } } nkeys=0; for(unsigned i=0; isecond).isCompulsory() ) nkeys++; + if ( (types.find(keys[i])->second).isCompulsory() ) { + nkeys++; + } } unsigned ncompulsory=nkeys; if( nkeys>0 ) { helpstr += "\nThe following arguments are compulsory: \n\n"; for(unsigned i=0; isecond).isCompulsory() ) helpstr += getKeywordDocs( keys[i] ); + if ( (types.find(keys[i])->second).isCompulsory() ) { + helpstr += getKeywordDocs( keys[i] ); + } } } nkeys=0; for(unsigned i=0; isecond).isFlag() ) nkeys++; + if ( (types.find(keys[i])->second).isFlag() ) { + nkeys++; + } } if( nkeys>0 ) { - if(ncompulsory>0) helpstr += "\nIn addition you may use the following options: \n\n"; - else helpstr += "\nThe following options are available\n\n"; + if(ncompulsory>0) { + helpstr += "\nIn addition you may use the following options: \n\n"; + } else { + helpstr += "\nThe following options are available\n\n"; + } for(unsigned i=0; isecond).isFlag() ) helpstr += getKeywordDocs( keys[i] ).c_str(); + if ( (types.find(keys[i])->second).isFlag() ) { + helpstr += getKeywordDocs( keys[i] ).c_str(); + } } } nkeys=0; for(unsigned i=0; isecond).isOptional() || (types.find(keys[i])->second).isVessel() ) nkeys++; + if ( (types.find(keys[i])->second).isOptional() || (types.find(keys[i])->second).isVessel() ) { + nkeys++; + } } if( nkeys>0 ) { for(unsigned i=0; isecond).isOptional() || (types.find(keys[i])->second).isVessel() ) helpstr += getKeywordDocs( keys[i] ); + if ( (types.find(keys[i])->second).isOptional() || (types.find(keys[i])->second).isVessel() ) { + helpstr += getKeywordDocs( keys[i] ); + } } helpstr += "\n"; } @@ -531,22 +687,34 @@ void Keywords::print( FILE* out ) const { } std::string Keywords::getTooltip( const std::string& name ) const { - std::size_t dd=name.find_first_of("0123456789"); std::string kname=name.substr(0,dd); - if( !exists(kname) ) return " could not find this keyword "; + std::size_t dd=name.find_first_of("0123456789"); + std::string kname=name.substr(0,dd); + if( !exists(kname) ) { + return " could not find this keyword "; + } std::string mystring, docstr = documentation.find(kname)->second; if( types.find(kname)->second.isCompulsory() ) { mystring += "compulsory keyword "; if( docstr.find("default")!=std::string::npos ) { - std::size_t bra = docstr.find_first_of(")"); mystring += docstr.substr(0,bra+1); docstr = docstr.substr(bra+1); + std::size_t bra = docstr.find_first_of(")"); + mystring += docstr.substr(0,bra+1); + docstr = docstr.substr(bra+1); } mystring += "\n"; } - std::vector w=Tools::getWords( docstr ); unsigned nl=0; + std::vector w=Tools::getWords( docstr ); + unsigned nl=0; for(unsigned i=0; i80 ) { mystring += w[i] + "\n"; nl=0; } - else { mystring += w[i] + " "; } - if( w[i].find(".")!=std::string::npos ) break; // Only write up the the first dot + if( nl>80 ) { + mystring += w[i] + "\n"; + nl=0; + } else { + mystring += w[i] + " "; + } + if( w[i].find(".")!=std::string::npos ) { + break; // Only write up the the first dot + } } return mystring; } @@ -584,10 +752,17 @@ bool Keywords::getDefaultValue(const std::string & key, std::string& def ) const } void Keywords::destroyData() { - keys.clear(); reserved_keys.clear(); types.clear(); - allowmultiple.clear(); documentation.clear(); - booldefs.clear(); numdefs.clear(); atomtags.clear(); - ckey.clear(); cdocs.clear(); ckey.clear(); + keys.clear(); + reserved_keys.clear(); + types.clear(); + allowmultiple.clear(); + documentation.clear(); + booldefs.clear(); + numdefs.clear(); + atomtags.clear(); + ckey.clear(); + cdocs.clear(); + ckey.clear(); } void Keywords::setComponentsIntroduction( const std::string& instr ) { @@ -601,7 +776,8 @@ void Keywords::addOutputComponent( const std::string& name, const std::string& k std::size_t num2=name.find_first_of("_"); if( num2!=std::string::npos ) { - char uu = '_'; plumed_massert( std::count(name.begin(),name.end(), uu)==1, "underscore is reserved character in component names and there should only be one"); + char uu = '_'; + plumed_massert( std::count(name.begin(),name.end(), uu)==1, "underscore is reserved character in component names and there should only be one"); plumed_massert( num2==0, "underscore is reserved character in component names that has special meaning"); } if( key=="default" ) { @@ -618,9 +794,15 @@ void Keywords::addOutputComponent( const std::string& name, const std::string& k void Keywords::removeOutputComponent( const std::string& name ) { unsigned j=0; while(true) { - for(j=0; j(".#!value","default") ); cdocs.insert( std::pair(".#!value",descr) ); cnames.push_back(".#!value"); - } else cdocs[".#!value"] = descr; + } else { + cdocs[".#!value"] = descr; + } } bool Keywords::outputComponentExists( const std::string& name ) const { - if( cstring.find("customize")!=std::string::npos ) return true; + if( cstring.find("customize")!=std::string::npos ) { + return true; + } std::string sname; std::size_t num=name.find_first_of("-"); std::size_t num2=name.find_last_of("_"); - if( num2!=std::string::npos ) sname=name.substr(num2); - else if( num!=std::string::npos ) sname=name.substr(0,num); - else sname=name; + if( num2!=std::string::npos ) { + sname=name.substr(num2); + } else if( num!=std::string::npos ) { + sname=name.substr(0,num); + } else { + sname=name; + } for(unsigned i=0; isecond; @@ -675,14 +876,20 @@ void Keywords::removeComponent( const std::string& name ) { while(true) { unsigned j; - for(j=0; j Keywords::getOutputComponents() const { } std::string Keywords::getKeywordDescription( const std::string& key ) const { - plumed_assert( exists( key ) ); return documentation.find(key)->second; + plumed_assert( exists( key ) ); + return documentation.find(key)->second; } void Keywords::needsAction( const std::string& name ) { - if( std::find(neededActions.begin(), neededActions.end(), name )!=neededActions.end() ) return; + if( std::find(neededActions.begin(), neededActions.end(), name )!=neededActions.end() ) { + return; + } neededActions.push_back( name ); } @@ -704,7 +914,9 @@ const std::vector& Keywords::getNeededKeywords() const { } void Keywords::addActionNameSuffix( const std::string& suffix ) { - if( std::find(actionNameSuffixes.begin(), actionNameSuffixes.end(), suffix )!=actionNameSuffixes.end() ) return; + if( std::find(actionNameSuffixes.begin(), actionNameSuffixes.end(), suffix )!=actionNameSuffixes.end() ) { + return; + } actionNameSuffixes.push_back( suffix ); } diff --git a/src/tools/Keywords.h b/src/tools/Keywords.h index 16c0cc60fd..85873a11e6 100644 --- a/src/tools/Keywords.h +++ b/src/tools/Keywords.h @@ -40,19 +40,37 @@ class Keywords { enum {hidden,compulsory,flag,optional,atoms,vessel} style; explicit KeyType( const std::string& type ); void setStyle( const std::string& type ); - bool isCompulsory() const { return (style==compulsory); } - bool isFlag() const { return (style==flag); } - bool isOptional() const { return (style==optional); } - bool isAtomList() const { return (style==atoms); } - bool isVessel() const { return (style==vessel); } + bool isCompulsory() const { + return (style==compulsory); + } + bool isFlag() const { + return (style==flag); + } + bool isOptional() const { + return (style==optional); + } + bool isAtomList() const { + return (style==atoms); + } + bool isVessel() const { + return (style==vessel); + } std::string toString() const { - if(style==compulsory) return "compulsory"; - else if(style==optional) return "optional"; - else if(style==atoms) return "atoms"; - else if(style==flag) return "flag"; - else if(style==hidden) return "hidden"; - else if(style==vessel) return "vessel"; - else plumed_assert(0); + if(style==compulsory) { + return "compulsory"; + } else if(style==optional) { + return "optional"; + } else if(style==atoms) { + return "atoms"; + } else if(style==flag) { + return "flag"; + } else if(style==hidden) { + return "hidden"; + } else if(style==vessel) { + return "vessel"; + } else { + plumed_assert(0); + } return ""; } }; @@ -100,9 +118,13 @@ class Keywords { /// Constructor Keywords() : isaction(true), isatoms(true) {} /// - void isDriver() { isaction=false; } + void isDriver() { + isaction=false; + } /// - void isAnalysis() { isatoms=false; } + void isAnalysis() { + isatoms=false; + } /// find out whether flag key is on or off by default. bool getLogicalDefault(const std::string & key, bool& def ) const ; /// Get the value of the default for the keyword named key @@ -186,7 +208,9 @@ class Keywords { /// Remove a component with a particular name from the keywords void removeComponent( const std::string& name ); /// Reference to keys - std::vector getKeys() const { return keys; } + std::vector getKeys() const { + return keys; + } /// Get the description of a particular keyword std::string getTooltip( const std::string& name ) const ; /// Note that another actions is required to create this shortcut diff --git a/src/tools/LatticeReduction.cpp b/src/tools/LatticeReduction.cpp index c7d388161c..2893c1bcf2 100644 --- a/src/tools/LatticeReduction.cpp +++ b/src/tools/LatticeReduction.cpp @@ -34,7 +34,9 @@ void LatticeReduction::sort(Vector v[3]) { m[0]=modulo2(v[0]); m[1]=modulo2(v[1]); m[2]=modulo2(v[2]); - for(int i=0; i<3; i++) for(int j=i+1; j<3; j++) if(m[i]>m[j]) { + for(int i=0; i<3; i++) + for(int j=i+1; j<3; j++) + if(m[i]>m[j]) { std::swap(v[i],v[j]); std::swap(m[i],m[j]); } @@ -54,13 +56,17 @@ void LatticeReduction::reduce(Vector&a,Vector&b) { } a-=b*floor(dotProduct(a,b)/mb+0.5); ma=modulo2(a); - if(mb<=ma*onePlusEpsilon) break; + if(mb<=ma*onePlusEpsilon) { + break; + } counter++; if(counter%100==0) { // only test rarely since this might be expensive plumed_assert(!std::isnan(ma)); plumed_assert(!std::isnan(mb)); } - if(counter%10000==0) std::fprintf(stderr,"WARNING: LatticeReduction::reduce stuck after %u iterations\n",counter); + if(counter%10000==0) { + std::fprintf(stderr,"WARNING: LatticeReduction::reduce stuck after %u iterations\n",counter); + } } std::swap(a,b); @@ -68,32 +74,42 @@ void LatticeReduction::reduce(Vector&a,Vector&b) { void LatticeReduction::reduce2(Vector&a,Vector&b,Vector&c) { Vector v[3]; - v[0]=a; v[1]=b; v[2]=c; + v[0]=a; + v[1]=b; + v[2]=c; int iter=0; int ok=0; while(ok<3) { int i,j; if(iter%3==0) { - i=0; j=1; + i=0; + j=1; } else if(iter%3==1) { - i=0; j=2; + i=0; + j=2; } else { - i=1; j=2; + i=1; + j=2; } - if(isReduced(v[i],v[j])) ok++; - else { + if(isReduced(v[i],v[j])) { + ok++; + } else { reduce(v[i],v[j]); ok=1; } iter++; } - a=v[0]; b=v[1]; c=v[2]; + a=v[0]; + b=v[1]; + c=v[2]; } bool LatticeReduction::isReduced(const Vector&a,const Vector&b) { const int cut=5; for(int i=-cut; i<=cut; i++) { - if(modulo2(b+i*a)=modulo2(v[2])) break; + if(modulo2(best)*onePlusEpsilon>=modulo2(v[2])) { + break; + } counter++; - if(counter%10000==0) std::fprintf(stderr,"WARNING: LatticeReduction::reduceFast stuck after %u iterations\n",counter); + if(counter%10000==0) { + std::fprintf(stderr,"WARNING: LatticeReduction::reduceFast stuck after %u iterations\n",counter); + } v[2]=best; } sort(v); @@ -169,10 +189,21 @@ void LatticeReduction::reduceSlow(Tensor&t) { double e02=dotProduct(v[0],v[2]); double e12=dotProduct(v[1],v[2]); if(e01*e02*e12<0) { - int eps01=0; if(e01>0.0) eps01=1; else if(e01<0.0) eps01=-1; - int eps02=0; if(e02>0.0) eps02=1; else if(e02<0.0) eps02=-1; + int eps01=0; + if(e01>0.0) { + eps01=1; + } else if(e01<0.0) { + eps01=-1; + } + int eps02=0; + if(e02>0.0) { + eps02=1; + } else if(e02<0.0) { + eps02=-1; + } Vector n=v[0]-eps01*v[1]-eps02*v[2]; - int i=0; double mx=modulo2(v[i]); + int i=0; + double mx=modulo2(v[i]); for(int j=1; j<3; j++) { double f=modulo2(v[j]); if(f>mx) { @@ -180,7 +211,9 @@ void LatticeReduction::reduceSlow(Tensor&t) { mx=f; } } - if(modulo2(n)& var, Action* action, const bool& a ) { - unsigned nth=OpenMP::getNumThreads(); expression.resize(nth); expression_deriv.resize(var.size()); + unsigned nth=OpenMP::getNumThreads(); + expression.resize(nth); + expression_deriv.resize(var.size()); // Resize the expression for the derivatives - for(unsigned i=0; ilog<<" function as parsed by lepton: "<log<<" function as parsed by lepton: "<& v } for(auto & p : expression[0].getVariables()) { if(std::find(var.begin(),var.end(),p)==var.end()) { - if( action ) action->error("variable " + p + " is not defined"); - else plumed_merror("variable " + p + " is not defined in lepton function"); + if( action ) { + action->error("variable " + p + " is not defined"); + } else { + plumed_merror("variable " + p + " is not defined in lepton function"); + } } } - if( action ) action->log<<" derivatives as computed by lepton:\n"; + if( action ) { + action->log<<" derivatives as computed by lepton:\n"; + } lepton_ref_deriv.resize(nth*nargs*nargs,nullptr); for(unsigned i=0; ilog<<" "<log<<" "<& args ) const { plumed_dbg_assert( allow_extra_args || args.size()==nargs ); const unsigned t=OpenMP::getThreadNum(), tbas=t*nargs; for(unsigned i=0; i& args ) const { - plumed_dbg_assert( allow_extra_args || args.size()==nargs ); plumed_dbg_assert( ider& pos, const std::vector& indices, const Pbc& pbc ) { @@ -52,7 +53,8 @@ void LinkCells::buildCellLists( const std::vector& pos, const std::vecto // Setup the lists if( pos.size()!=allcells.size() ) { - allcells.resize( pos.size() ); lcell_lists.resize( pos.size() ); + allcells.resize( pos.size() ); + lcell_lists.resize( pos.size() ); } { @@ -61,22 +63,33 @@ void LinkCells::buildCellLists( const std::vector& pos, const std::vecto // This allows to use linked cells in non orthorhomic boxes Tensor reciprocal(transpose(mypbc.getInvBox())); ncells[0] = std::floor( 1.0/ reciprocal.getRow(0).modulo() / link_cutoff ); - if( ncells[0]==0 ) ncells[0]=1; + if( ncells[0]==0 ) { + ncells[0]=1; + } ncells[1] = std::floor( 1.0/ reciprocal.getRow(1).modulo() / link_cutoff ); - if( ncells[1]==0 ) ncells[1]=1; + if( ncells[1]==0 ) { + ncells[1]=1; + } ncells[2] = std::floor( 1.0/ reciprocal.getRow(2).modulo() / link_cutoff ); - if( ncells[2]==0 ) ncells[2]=1; + if( ncells[2]==0 ) { + ncells[2]=1; + } } // Setup the strides - nstride[0]=1; nstride[1]=ncells[0]; nstride[2]=ncells[0]*ncells[1]; + nstride[0]=1; + nstride[1]=ncells[0]; + nstride[2]=ncells[0]*ncells[1]; // Setup the storage for link cells unsigned ncellstot=ncells[0]*ncells[1]*ncells[2]; if( lcell_tots.size()!=ncellstot ) { - lcell_tots.resize( ncellstot ); lcell_starts.resize( ncellstot ); + lcell_tots.resize( ncellstot ); + lcell_starts.resize( ncellstot ); } // Clear nlcells - for(unsigned i=0; i& pos, const std::vecto lcell_tots[allcells[i]]++; } // And gather all this information on every node - comm.Sum( allcells ); comm.Sum( lcell_tots ); + comm.Sum( allcells ); + comm.Sum( lcell_tots ); // Now prepare the link cell lists unsigned tot=0; - for(unsigned i=0; i& celn, unsigned& int zval = celn[2] + nz; zval=LINKC_PBC(zval,ncells[2])*nstride[2]; - unsigned mybox=xval+yval+zval; bool added=false; + unsigned mybox=xval+yval+zval; + bool added=false; for(unsigned k=0; k& celn, unsigned& void LinkCells::retrieveNeighboringAtoms( const Vector& pos, std::vector& cell_list, unsigned& natomsper, std::vector& atoms ) const { - if( cell_list.size()!=getNumberOfCells() ) cell_list.resize( getNumberOfCells() ); - unsigned ncellt=0; addRequiredCells( findMyCell( pos ), ncellt, cell_list ); + if( cell_list.size()!=getNumberOfCells() ) { + cell_list.resize( getNumberOfCells() ); + } + unsigned ncellt=0; + addRequiredCells( findMyCell( pos ), ncellt, cell_list ); retrieveAtomsInCells( ncellt, cell_list, natomsper, atoms ); } @@ -174,7 +202,9 @@ unsigned LinkCells::findCell( const Vector& pos ) const { unsigned LinkCells::getMaxInCell() const { unsigned maxn = lcell_tots[0]; for(unsigned i=1; imaxn ) { maxn=lcell_tots[i]; } + if( lcell_tots[i]>maxn ) { + maxn=lcell_tots[i]; + } } return maxn; } diff --git a/src/tools/Log.h b/src/tools/Log.h index 8475822fb6..fb8ce4a1a1 100644 --- a/src/tools/Log.h +++ b/src/tools/Log.h @@ -33,8 +33,7 @@ namespace PLMD { /// lines with the "PLUMED:" prefix, useful to grep out plumed /// log from output class Log : - public OFile -{ + public OFile { }; } diff --git a/src/tools/Matrix.h b/src/tools/Matrix.h index aa55c43909..064ec604d9 100644 --- a/src/tools/Matrix.h +++ b/src/tools/Matrix.h @@ -36,21 +36,26 @@ namespace PLMD { /// Calculate the dot product between two vectors template T dotProduct( const std::vector& A, const std::vector& B ) { plumed_assert( A.size()==B.size() ); - T val; for(unsigned i=0; i T norm( const std::vector& A ) { - T val; for(unsigned i=0; i class Matrix: - public MatrixSquareBracketsAccess,T> -{ + public MatrixSquareBracketsAccess,T> { /// Multiply matrix by scalar template friend Matrix operator*(U&, const Matrix& ); /// Matrix matrix multiply @@ -90,22 +95,44 @@ class Matrix: explicit Matrix(const unsigned nr=0, const unsigned nc=0 ) : sz(nr*nc), rw(nr), cl(nc), data(nr*nc) {} Matrix(const Matrix& t) : sz(t.sz), rw(t.rw), cl(t.cl), data(t.data) {} /// Resize the matrix - void resize( const unsigned nr, const unsigned nc ) { rw=nr; cl=nc; sz=nr*nc; data.resize(sz); } + void resize( const unsigned nr, const unsigned nc ) { + rw=nr; + cl=nc; + sz=nr*nc; + data.resize(sz); + } /// Return the number of rows - inline unsigned nrows() const { return rw; } + inline unsigned nrows() const { + return rw; + } /// Return the number of columns - inline unsigned ncols() const { return cl; } + inline unsigned ncols() const { + return cl; + } /// Return the contents of the matrix as a vector of length rw*cl - inline std::vector& getVector() { return data; } + inline std::vector& getVector() { + return data; + } /// Set the matrix from a vector input - inline void setFromVector( const std::vector& vecin ) { plumed_assert( vecin.size()==sz ); for(unsigned i=0; i& vecin ) { + plumed_assert( vecin.size()==sz ); + for(unsigned i=0; i& operator=(const T& v) { - for(unsigned i=0; i& operator=(const std::vector& v) { plumed_dbg_assert( v.size()==sz ); - for(unsigned i=0; i operator+=(const T& v) { - for(unsigned i=0; i operator*=(const T& v) { - for(unsigned i=0; i operator-=(const T& v) { - for(unsigned i=0; i1.e-10 ) { sym=0; break; } + for(unsigned i=1; i1.e-10 ) { + sym=0; + break; + } return sym; } }; @@ -167,37 +209,67 @@ template Matrix operator*(T& v, const Matrix& m ) { template void mult( const Matrix& A, const Matrix& B, Matrix& C ) { plumed_assert(A.cl==B.rw); - if( A.rw !=C.rw || B.cl !=C.cl ) { C.resize( A.rw, B.cl ); } C=static_cast( 0 ); - for(unsigned i=0; i( 0 ); + for(unsigned i=0; i void mult( const Matrix& A, const std::vector& B, std::vector& C) { plumed_assert( A.cl==B.size() ); - if( C.size()!=A.rw ) { C.resize(A.rw); } - for(unsigned i=0; i( 0 ); } - for(unsigned i=0; i( 0 ); + } + for(unsigned i=0; i void mult( const std::vector& A, const Matrix& B, std::vector& C) { plumed_assert( B.rw==A.size() ); - if( C.size()!=B.cl ) {C.resize( B.cl );} - for(unsigned i=0; i( 0 ); } - for(unsigned i=0; i( 0 ); + } + for(unsigned i=0; i void transpose( const Matrix& A, Matrix& AT ) { - if( A.rw!=AT.cl || A.cl!=AT.rw ) AT.resize( A.cl, A.rw ); - for(unsigned i=0; i Log& operator<<(Log& ostr, const Matrix& mat) { - for(unsigned i=0; i void matrixOut( Log& ostr, const Matrix& mat) { for(unsigned i=0; i void matrixOut( Log& ostr, const Matrix& mat) { template int diagMat( const Matrix& A, std::vector& eigenvals, Matrix& eigenvecs ) { // Check matrix is square and symmetric - plumed_assert( A.rw==A.cl ); plumed_assert( A.isSymmetric()==1 ); + plumed_assert( A.rw==A.cl ); + plumed_assert( A.isSymmetric()==1 ); std::vector da(A.sz); unsigned k=0; std::vector evals(A.cl); // Transfer the matrix to the local array - for (unsigned i=0; i( A(j,i) ); + for (unsigned i=0; i( A(j,i) ); + } - int n=A.cl; int lwork=-1, liwork=-1, m, info, one=1; + int n=A.cl; + int lwork=-1, liwork=-1, m, info, one=1; std::vector work(A.cl); std::vector iwork(A.cl); double vl, vu, abstol=0.0; @@ -223,26 +300,38 @@ template int diagMat( const Matrix& A, std::vector& eige plumed_lapack_dsyevr("V", "I", "U", &n, da.data(), &n, &vl, &vu, &one, &n, &abstol, &m, evals.data(), evecs.data(), &n, isup.data(), work.data(), &lwork, iwork.data(), &liwork, &info); - if (info!=0) return info; + if (info!=0) { + return info; + } // Retrieve correct sizes for work and iwork then reallocate - liwork=iwork[0]; iwork.resize(liwork); - lwork=static_cast( work[0] ); work.resize(lwork); + liwork=iwork[0]; + iwork.resize(liwork); + lwork=static_cast( work[0] ); + work.resize(lwork); plumed_lapack_dsyevr("V", "I", "U", &n, da.data(), &n, &vl, &vu, &one, &n, &abstol, &m, evals.data(), evecs.data(), &n, isup.data(), work.data(), &lwork, iwork.data(), &liwork, &info); - if (info!=0) return info; + if (info!=0) { + return info; + } - if( eigenvals.size()!=A.cl ) { eigenvals.resize( A.cl ); } - if( eigenvecs.rw!=A.rw || eigenvecs.cl!=A.cl ) { eigenvecs.resize( A.rw, A.cl ); } + if( eigenvals.size()!=A.cl ) { + eigenvals.resize( A.cl ); + } + if( eigenvecs.rw!=A.rw || eigenvecs.cl!=A.cl ) { + eigenvecs.resize( A.rw, A.cl ); + } k=0; for(unsigned i=0; i int diagMat( const Matrix& A, std::vector& eige // the result reproducible for(int i=0; i1e-14) break; - if(j1e-14) { + break; + } + if(j int pseudoInvert( const Matrix& A, Matrix& pseu std::vector da(A.sz); unsigned k=0; // Transfer the matrix to the local array - for (unsigned i=0; i( A(j,i) ); + for (unsigned i=0; i( A(j,i) ); + } int nsv, info, nrows=A.rw, ncols=A.cl; - if(A.rw>A.cl) {nsv=A.cl;} else {nsv=A.rw;} + if(A.rw>A.cl) { + nsv=A.cl; + } else { + nsv=A.rw; + } // Create some containers for stuff from single value decomposition std::vector S(nsv); @@ -276,30 +379,62 @@ template int pseudoInvert( const Matrix& A, Matrix& pseu int lwork=-1; std::vector work(1); plumed_lapack_dgesdd( "A", &nrows, &ncols, da.data(), &nrows, S.data(), U.data(), &nrows, VT.data(), &ncols, work.data(), &lwork, iwork.data(), &info ); - if(info!=0) return info; + if(info!=0) { + return info; + } // Retrieve correct sizes for work and rellocate - lwork=(int) work[0]; work.resize(lwork); + lwork=(int) work[0]; + work.resize(lwork); // This does the singular value decomposition plumed_lapack_dgesdd( "A", &nrows, &ncols, da.data(), &nrows, S.data(), U.data(), &nrows, VT.data(), &ncols, work.data(), &lwork, iwork.data(), &info ); - if(info!=0) return info; + if(info!=0) { + return info; + } // Compute the tolerance on the singular values ( machine epsilon * number of singular values * maximum singular value ) - double tol; tol=S[0]; for(int i=1; itol ) { tol=S[i]; } } tol*=nsv*epsilon; + double tol; + tol=S[0]; + for(int i=1; itol ) { + tol=S[i]; + } + } + tol*=nsv*epsilon; // Get the inverses of the singlular values - Matrix Si( ncols, nrows ); Si=0.0; - for(int i=0; itol ) { Si(i,i)=1./S[i]; } else { Si(i,i)=0.0; } } + Matrix Si( ncols, nrows ); + Si=0.0; + for(int i=0; itol ) { + Si(i,i)=1./S[i]; + } else { + Si(i,i)=0.0; + } + } // Now extract matrices for pseudoinverse Matrix V( ncols, ncols ), UT( nrows, nrows ), tmp( ncols, nrows ); - k=0; for(int i=0; i int Invert( const Matrix& A, Matrix& inverse ) // GAT -- I only ever use symmetric matrices so I can invert them like this. // I choose to do this as I have had problems with the more general way of doing this that // is implemented below. - std::vector eval(A.rw); Matrix evec(A.rw,A.cl), tevec(A.rw,A.cl); - int err; err=diagMat( A, eval, evec ); - if(err!=0) return err; - for (unsigned i=0; i eval(A.rw); + Matrix evec(A.rw,A.cl), tevec(A.rw,A.cl); + int err; + err=diagMat( A, eval, evec ); + if(err!=0) { + return err; + } + for (unsigned i=0; i da(A.sz); std::vector ipiv(A.cl); - unsigned k=0; int n=A.rw, info; - for(unsigned i=0; i( A(j,i) ); + unsigned k=0; + int n=A.rw, info; + for(unsigned i=0; i( A(j,i) ); + } plumed_lapack_dgetrf(&n,&n,da.data(),&n,ipiv.data(),&info); - if(info!=0) return info; + if(info!=0) { + return info; + } int lwork=-1; std::vector work(A.cl); plumed_lapack_dgetri(&n,da.data(),&n,ipiv.data(),work.data(),&lwork,&info); - if(info!=0) return info; + if(info!=0) { + return info; + } - lwork=static_cast( work[0] ); work.resize(lwork); + lwork=static_cast( work[0] ); + work.resize(lwork); plumed_lapack_dgetri(&n,da.data(),&n,ipiv.data(),work.data(),&lwork,&info); - if(info!=0) return info; + if(info!=0) { + return info; + } - if( inverse.cl!=A.cl || inverse.rw!=A.rw ) { inverse.resize(A.rw,A.cl); } - k=0; for(unsigned i=0; i int Invert( const Matrix& A, Matrix& inverse ) template void cholesky( const Matrix& A, Matrix& B ) { plumed_assert( A.rw==A.cl && A.isSymmetric() ); - Matrix L(A.rw,A.cl); L=0.; + Matrix L(A.rw,A.cl); + L=0.; std::vector D(A.rw,0.); for(unsigned i=0; i( 1 ); for (unsigned j=0; j( 0 ); + for (unsigned k=0; k( 0 ); + } } D[i]=A(i,i); - for (unsigned k=0; k0.?std::sqrt(D[i]):0.); - if( B.rw!=A.rw || B.cl!=A.cl ) { B.resize( A.rw, A.cl); } - B=0.; for(unsigned i=0; i0.?std::sqrt(D[i]):0.); + } + if( B.rw!=A.rw || B.cl!=A.cl ) { + B.resize( A.rw, A.cl); + } + B=0.; + for(unsigned i=0; i void chol_elsolve( const Matrix& M, const std::vector& b, std::vector& y ) { plumed_assert( M.rw==M.cl && M(0,1)==0.0 && b.size()==M.rw ); - if( y.size()!=M.rw ) { y.resize( M.rw ); } + if( y.size()!=M.rw ) { + y.resize( M.rw ); + } for(unsigned i=0; i int logdet( const Matrix& M, double& ldet ) { unsigned k=0; std::vector evals(M.cl); // Transfer the matrix to the local array - for (unsigned i=0; i( M(j,i) ); + for (unsigned i=0; i( M(j,i) ); + } - int n=M.cl; int lwork=-1, liwork=-1, info, m, one=1; + int n=M.cl; + int lwork=-1, liwork=-1, info, m, one=1; std::vector work(M.rw); std::vector iwork(M.rw); double vl, vu, abstol=0.0; @@ -391,19 +575,28 @@ template int logdet( const Matrix& M, double& ldet ) { plumed_lapack_dsyevr("N", "I", "U", &n, da.data(), &n, &vl, &vu, &one, &n, &abstol, &m, evals.data(), evecs.data(), &n, isup.data(), work.data(), &lwork, iwork.data(), &liwork, &info); - if (info!=0) return info; + if (info!=0) { + return info; + } // Retrieve correct sizes for work and iwork then reallocate - lwork=static_cast( work[0] ); work.resize(lwork); - liwork=iwork[0]; iwork.resize(liwork); + lwork=static_cast( work[0] ); + work.resize(lwork); + liwork=iwork[0]; + iwork.resize(liwork); plumed_lapack_dsyevr("N", "I", "U", &n, da.data(), &n, &vl, &vu, &one, &n, &abstol, &m, evals.data(), evecs.data(), &n, isup.data(), work.data(), &lwork, iwork.data(), &liwork, &info); - if (info!=0) return info; + if (info!=0) { + return info; + } // Transfer the eigenvalues and eigenvectors to the output - ldet=0; for(unsigned i=0; i static void mergeSortedVectors(const C* const* vecs, std::size_t size, std::vector & result) { /// local class storing the range of remaining objects to be pushed - class Entry - { + class Entry { typename C::const_iterator fwdIt,endIt; public: explicit Entry(C const& v) : fwdIt(v.begin()), endIt(v.end()) {} /// check if this vector still contains something to be pushed - bool empty() const { return fwdIt == endIt; } + bool empty() const { + return fwdIt == endIt; + } /// to allow using a priority_queu, which selects the highest element. /// we here (counterintuitively) define < as > - bool operator< (Entry const& rhs) const { return top() > rhs.top(); } - const auto & top() const { return *fwdIt; } - void next() { ++fwdIt;}; + bool operator< (Entry const& rhs) const { + return top() > rhs.top(); + } + const auto & top() const { + return *fwdIt; + } + void next() { + ++fwdIt; + }; }; // preprocessing @@ -65,7 +72,9 @@ static void mergeSortedVectors(const C* const* vecs, std::size_t size, std::vect // this is just to decrease the number of reallocations on push_back result.reserve(maxsize); // if vectors are empty we are done - if(maxsize==0) return; + if(maxsize==0) { + return; + } } // start @@ -93,8 +102,11 @@ static void mergeSortedVectors(const C* const* vecs, std::size_t size, std::vect // here, we append inconditionally result.push_back(val); tmp.next(); - if(tmp.empty()) heap.pop_back(); - else std::push_heap(std::begin(heap), std::end(heap)); + if(tmp.empty()) { + heap.pop_back(); + } else { + std::push_heap(std::begin(heap), std::end(heap)); + } } while(!heap.empty()) { @@ -106,13 +118,19 @@ static void mergeSortedVectors(const C* const* vecs, std::size_t size, std::vect const auto val=tmp.top(); // if the element is larger than the current largest element, // push it to result - if(val > result.back()) result.push_back(val); + if(val > result.back()) { + result.push_back(val); + } // move forward the used entry tmp.next(); // if this entry is exhausted, remove it from the array - if(tmp.empty()) heap.pop_back(); + if(tmp.empty()) { + heap.pop_back(); + } // otherwise, sort again the array - else std::push_heap(std::begin(heap), std::end(heap)); + else { + std::push_heap(std::begin(heap), std::end(heap)); + } } } diff --git a/src/tools/Minimise1DBrent.h b/src/tools/Minimise1DBrent.h index d338c407db..dfaa38f742 100644 --- a/src/tools/Minimise1DBrent.h +++ b/src/tools/Minimise1DBrent.h @@ -83,18 +83,24 @@ Minimise1DBrent::Minimise1DBrent( const FCLASS& pf, const double& t ): ax(0),bx(0),cx(0), fa(0),fb(0),fc(0), fmin(0), - myclass_func(pf) -{ + myclass_func(pf) { } template void Minimise1DBrent::bracket( const double& a, const double& b, eng_pointer eng ) { - ax=a; bx=b; double fu; - fa=(myclass_func.*eng)(ax); fb=(myclass_func.*eng)(bx); + ax=a; + bx=b; + double fu; + fa=(myclass_func.*eng)(ax); + fb=(myclass_func.*eng)(bx); if( fb>fa ) { double tmp; - tmp=ax; ax=bx; bx=tmp; - tmp=fa; fa=fb; fb=tmp; + tmp=ax; + ax=bx; + bx=tmp; + tmp=fa; + fa=fb; + fb=tmp; } cx=bx+GOLD*(bx-ax); fc=(myclass_func.*eng)(cx); @@ -106,16 +112,29 @@ void Minimise1DBrent::bracket( const double& a, const double& b, eng_poi if((bx-u)*(u-cx) > 0.0 ) { fu=(myclass_func.*eng)(u); if( fu < fc ) { - ax=bx; bx=u; fa=fb; fb=fu; bracketed=true; return; + ax=bx; + bx=u; + fa=fb; + fb=fu; + bracketed=true; + return; } else if( fu > fb ) { - cx=u; fc=fu; bracketed=true; return; + cx=u; + fc=fu; + bracketed=true; + return; } - u=cx+GOLD*(cx-bx); fu=(myclass_func.*eng)(u); + u=cx+GOLD*(cx-bx); + fu=(myclass_func.*eng)(u); } else if((cx-u)*(u-ulim) > 0.0 ) { fu=(myclass_func.*eng)(u); if( fu= 0.0 ) { u=ulim; @@ -124,8 +143,12 @@ void Minimise1DBrent::bracket( const double& a, const double& b, eng_poi u=cx+GOLD*(cx-bx); fu=(myclass_func.*eng)(u); } - ax=bx; bx=cx; cx=u; - fa=fb; fb=fc; fc=fu; + ax=bx; + bx=cx; + cx=u; + fa=fb; + fb=fc; + fc=fu; } bracketed=true; } @@ -146,39 +169,65 @@ double Minimise1DBrent::minimise( eng_pointer eng ) { xm=0.5*(a+b); tol2=2.0*(tol1=tol*std::fabs(x)+ZEPS); if( std::fabs(x-xm) <= (tol2-0.5*(b-a))) { - fmin=fx; minimised=true; return x; + fmin=fx; + minimised=true; + return x; } if( std::fabs(e) > tol1 ) { r=(x-w)*(fx-fv); q=(x-v)*(fx-fw); p=(x-v)*q-(x-w)*r; q=2.0*(q-r); - if( q > 0.0 ) p = -p; + if( q > 0.0 ) { + p = -p; + } q=std::fabs(q); etemp=e; e=d; if( std::fabs(p) >= std::fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x) ) { d = CGOLD*(e=(x >= xm ? a-x : b-x )); } else { - d=p/q; u=x+d; - if(u-a < tol2 || b-u < tol2 ) d=(xm-x>=0?std::fabs(tol1):-std::fabs(tol1)); + d=p/q; + u=x+d; + if(u-a < tol2 || b-u < tol2 ) { + d=(xm-x>=0?std::fabs(tol1):-std::fabs(tol1)); + } } } else { d=CGOLD*(e=( x >= xm ? a-x : b-x )); } - if( std::fabs(d)>=tol1) u=x+d; else u=x+(d>=0?std::fabs(tol1):-std::fabs(tol1)); + if( std::fabs(d)>=tol1) { + u=x+d; + } else { + u=x+(d>=0?std::fabs(tol1):-std::fabs(tol1)); + } fu=(myclass_func.*eng)(u); if( fu <= fx ) { - if( u >= x ) a=x; else b=x; - v=w; fv=fw; - w=x; fw=fx; - x=u; fx=fu; + if( u >= x ) { + a=x; + } else { + b=x; + } + v=w; + fv=fw; + w=x; + fw=fx; + x=u; + fx=fu; } else { - if( u < x ) a=u; else b=u; + if( u < x ) { + a=u; + } else { + b=u; + } if( fu <=fw || w==x ) { - v=w; w=u; fv=fw; fw=fu; + v=w; + w=u; + fv=fw; + fw=fu; } else if( fu <= fv || v==x || v==w ) { - v=u; fv=fu; + v=u; + fv=fu; } } } diff --git a/src/tools/MinimiseBase.h b/src/tools/MinimiseBase.h index f8a67250cd..28cc7246a5 100644 --- a/src/tools/MinimiseBase.h +++ b/src/tools/MinimiseBase.h @@ -61,15 +61,18 @@ F1dim::F1dim( const std::vector& pp, const std::vector& fake_der(pp.size()), func(ff), calc(cc), - calc2(cc2) -{ + calc2(cc2) { plumed_assert( calc || calc2 ); } template double F1dim::getEng( const double& xt ) { - for(unsigned j=0; j*calc)(pt,fake_der); + for(unsigned j=0; j*calc)(pt,fake_der); + } return (func->*calc2)(pt,fake_der); } @@ -102,7 +105,9 @@ double MinimiseBase::linemin( const std::vector& dir, std::vecto double ax=0.0, xx=1.0; bb.bracket( ax, xx, &F1dim::getEng ); double xmin=bb.minimise( &F1dim::getEng ); - for(unsigned i=0; i tmpnum1(mypdb.getAtomsInResidue(resnum,chainid)); for(unsigned i=0; i myind( nder ); - for(unsigned i=0; i myind( nder ); - for(unsigned i=0; i myind( nder ); + for(unsigned i=0; i1000 ) return; + if( i>1000 ) { + return; + } } #endif } diff --git a/src/tools/MultiValue.h b/src/tools/MultiValue.h index 87acba096b..1e26015747 100644 --- a/src/tools/MultiValue.h +++ b/src/tools/MultiValue.h @@ -179,14 +179,18 @@ void MultiValue::addValue( const std::size_t& ival, const double& val) { inline void MultiValue::addDerivative( const std::size_t& ival, const std::size_t& jder, const double& der) { - plumed_dbg_assert( ival<=values.size() && jder& MultiValue::getFirstAtomVirialVector() { inline void MultiValue::stashMatrixElement( const unsigned& nmat, const unsigned& rowstart, const unsigned& jcol, const double& val ) { plumed_dbg_assert( jcol& MultiValue::getMatrixRowDerivativeIndices( const unsigned& nmat ) { - plumed_dbg_assert( nmattmp_vectors.size() ) tmp_vectors.resize(n); + if( n>tmp_vectors.size() ) { + tmp_vectors.resize(n); + } } inline diff --git a/src/tools/NeighborList.cpp b/src/tools/NeighborList.cpp index 58fba82a6c..0c09be76f9 100644 --- a/src/tools/NeighborList.cpp +++ b/src/tools/NeighborList.cpp @@ -119,8 +119,9 @@ void NeighborList::initialize() { } //TODO: test if this is feasible for accelerating the loop //#pragma omp parallel for default(shared) - for(unsigned int i=0; i& NeighborList::getFullAtomList() { @@ -129,11 +130,11 @@ std::vector& NeighborList::getFullAtomList() { NeighborList::pairIDs NeighborList::getIndexPair(const unsigned ipair) { pairIDs index; - if(twolists_ && do_pair_) + if(twolists_ && do_pair_) { index=pairIDs(ipair,ipair+nlist0_); - else if (twolists_ && !do_pair_) + } else if (twolists_ && !do_pair_) { index=pairIDs(ipair/nlist1_,ipair%nlist1_+nlist0_); - else if (!twolists_) { + } else if (!twolists_) { unsigned ii = nallpairs_-1-ipair; unsigned K = unsigned(std::floor((std::sqrt(double(8*ii+1))+1)/2)); unsigned jj = ii-K*(K-1)/2; @@ -187,8 +188,9 @@ void NeighborList::update(const std::vector& positions) { // find total dimension of neighborlist std::vector local_nl_size(stride, 0); local_nl_size[rank] = local_flat_nl.size(); - if(!serial_) + if(!serial_) { comm.Sum(&local_nl_size[0], stride); + } int tot_size = std::accumulate(local_nl_size.begin(), local_nl_size.end(), 0); if(tot_size==0) { setRequestList(); @@ -211,8 +213,9 @@ void NeighborList::update(const std::vector& positions) { &merge_nl[0], &local_nl_size[0], &disp[0]); - } else + } else { merge_nl = local_flat_nl; + } // resize neighbor stuff neighbors_.resize(tot_size/2); for(unsigned i=0; i NeighborList::getNeighbors(const unsigned index) { std::vector neighbors; for(unsigned int i=0; illwrite(ptr,s); + if(linked) { + return linked->llwrite(ptr,s); + } if(! (comm && comm->Get_rank()>0)) { - if(!fp) plumed_merror("writing on uninitialized File"); + if(!fp) { + plumed_merror("writing on uninitialized File"); + } if(gzfp) { #ifdef __PLUMED_HAS_ZLIB r=gzwrite(gzFile(gzfp),ptr,s); @@ -77,14 +81,15 @@ OFile::OFile(): fieldChanged(false), backstring("bck"), enforceRestart_(false), - enforceBackup_(false) -{ + enforceBackup_(false) { fmtField(); buflen=1; actual_buffer_length=0; buffer.resize(buflen); // these are set to zero to avoid valgrind errors - for(int i=0; i=buflen-actual_buffer_length) { int newlen=buflen; - while(newlen<=r+actual_buffer_length) newlen*=2; + while(newlen<=r+actual_buffer_length) { + newlen*=2; + } std::vector newbuf(newlen); std::memmove(newbuf.data(),buffer.data(),buflen); - for(int k=buflen; k0) llwrite(linePrefix.c_str(),linePrefix.length()); + if(linePrefix.length()>0) { + llwrite(linePrefix.c_str(),linePrefix.length()); + } llwrite(p1,p2-p1+1); actual_buffer_length-=(p2-p1)+1; p1=p2+1; psearch=p1; }; - if(buffer.data()!=p1) std::memmove(buffer.data(),p1,actual_buffer_length); + if(buffer.data()!=p1) { + std::memmove(buffer.data(),p1,actual_buffer_length); + } return r; } @@ -167,7 +180,9 @@ OFile& OFile::printField(const std::string&name,double v) { // When one tries to print -nan we print nan instead. // The distinction between +nan and -nan is not well defined // Always printing nan simplifies some regtest (special functions computed our of range). - if(std::isnan(v)) v=std::numeric_limits::quiet_NaN(); + if(std::isnan(v)) { + v=std::numeric_limits::quiet_NaN(); + } std::snprintf(buffer_string.data(),buffer_string.size(),fieldFmt.c_str(),v); printField(name,buffer_string.data()); return *this; @@ -211,14 +226,19 @@ OFile& OFile::printField(const std::string&name,long long unsigned v) { OFile& OFile::printField(const std::string&name,const std::string & v) { unsigned i; - for(i=0; i=const_fields.size()) { Field field; field.name=name; field.value=v; fields.push_back(field); } else { - if(const_fields[i].value!=v) fieldChanged=true; + if(const_fields[i].value!=v) { + fieldChanged=true; + } const_fields[i].value=v; } return *this; @@ -235,7 +255,8 @@ OFile& OFile::setupPrintValue( Value *val ) { OFile& OFile::printField( Value* val, const double& v ) { printField( val->getName(), v ); if( val->isPeriodic() ) { - std::string min, max; val->getDomain( min, max ); + std::string min, max; + val->getDomain( min, max ); printField( "min_" + val->getName(), min ); printField("max_" + val->getName(), max ); } @@ -246,7 +267,8 @@ OFile& OFile::printField() { bool reprint=false; if(fieldChanged || fields.size()!=previous_fields.size()) { reprint=true; - } else for(unsigned i=0; i0 && (!comm || comm->Get_rank()==0)) { FILE* ff=std::fopen(const_cast(fname.c_str()),"r"); if(ff) { @@ -306,12 +343,17 @@ void OFile::backupFile( const std::string& bstring, const std::string& fname ) { for(int i=0;; i++) { std::string num; Tools::convert(i,num); - if(i>maxbackup) plumed_merror("cannot backup file "+file+" maximum number of backup is "+num+"\n"); + if(i>maxbackup) { + plumed_merror("cannot backup file "+file+" maximum number of backup is "+num+"\n"); + } backup=directory+bstring +"."+num+"."+file; FILE* fff=std::fopen(backup.c_str(),"r"); // no exception here - if(!fff) break; - else std::fclose(fff); + if(!fff) { + break; + } else { + std::fclose(fff); + } } int check=rename(fname.c_str(),backup.c_str()); plumed_massert(check==0,"renaming "+fname+" into "+backup+" failed for reason: "+std::strerror(errno)); @@ -339,7 +381,9 @@ OFile& OFile::open(const std::string&path) { } } else { backupFile( backstring, this->path ); - if(comm)comm->Barrier(); + if(comm) { + comm->Barrier(); + } fp=std::fopen(const_cast(this->path.c_str()),"w"); mode="w"; if(Tools::extension(this->path)=="gz") { @@ -350,7 +394,9 @@ OFile& OFile::open(const std::string&path) { #endif } } - if(plumed) plumed->insertFile(*this); + if(plumed) { + plumed->insertFile(*this); + } return *this; } @@ -371,7 +417,9 @@ OFile& OFile::rewind() { plumed_massert(check==0,"renaming "+fname+" into "+backup+" failed for reason: "+std::strerror(errno)); } - if(comm) comm->Barrier(); + if(comm) { + comm->Barrier(); + } if(gzfp) { #ifdef __PLUMED_HAS_ZLIB @@ -406,18 +454,26 @@ FileBase& OFile::flush() { // for some reason flushing with Z_FINISH has problems on linux // I thus use this (incomplete) flush #ifdef __PLUMED_HAS_ZLIB - if(gzfp) gzflush(gzFile(gzfp),Z_FULL_FLUSH); + if(gzfp) { + gzflush(gzFile(gzfp),Z_FULL_FLUSH); + } #endif } return *this; } bool OFile::checkRestart()const { - if(enforceRestart_) return true; - else if(enforceBackup_) return false; - else if(action) return action->getRestart(); - else if(plumed) return plumed->getRestart(); - else return false; + if(enforceRestart_) { + return true; + } else if(enforceBackup_) { + return false; + } else if(action) { + return action->getRestart(); + } else if(plumed) { + return plumed->getRestart(); + } else { + return false; + } } OFile& OFile::enforceRestart() { diff --git a/src/tools/OpenMP.h b/src/tools/OpenMP.h index 64a5df21ae..c3fe24b8b8 100644 --- a/src/tools/OpenMP.h +++ b/src/tools/OpenMP.h @@ -62,8 +62,11 @@ unsigned getGoodNumThreads(const T* /*getTheType*/,unsigned n) { /// Get a reasonable number of threads so as to access to vector v template unsigned getGoodNumThreads(const std::vector & v) { - if(v.size()==0) return 1; - else return getGoodNumThreads(&v[0],v.size()); + if(v.size()==0) { + return 1; + } else { + return getGoodNumThreads(&v[0],v.size()); + } } }//namespace OpenMP diff --git a/src/tools/PDB.cpp b/src/tools/PDB.cpp index 92101810fb..e04129ec04 100644 --- a/src/tools/PDB.cpp +++ b/src/tools/PDB.cpp @@ -131,13 +131,20 @@ In addition, as of PLUMED 2.5, we provide a \ref pdbrenumber "command line tool" namespace PLMD { void PDB::setAtomNumbers( const std::vector& atoms ) { - positions.resize( atoms.size() ); occupancy.resize( atoms.size() ); - beta.resize( atoms.size() ); numbers.resize( atoms.size() ); - for(unsigned i=0; i& argument_names ) { - argnames.resize( argument_names.size() ); std::vector tmp(1,0); + argnames.resize( argument_names.size() ); + std::vector tmp(1,0); for(unsigned i=0; i >( argnames[i], tmp ) ); @@ -147,8 +154,12 @@ void PDB::setArgumentNames( const std::vector& argument_names ) { bool PDB::getArgumentValue( const std::string& name, std::vector& value ) const { std::map >::const_iterator it = arg_data.find(name); if( it!=arg_data.end() ) { - if( value.size()!=it->second.size() ) return false; - for(unsigned i=0; isecond[i]; + if( value.size()!=it->second.size() ) { + return false; + } + for(unsigned i=0; isecond[i]; + } return true; } return false; @@ -156,7 +167,9 @@ bool PDB::getArgumentValue( const std::string& name, std::vector& value void PDB::setAtomPositions( const std::vector& pos ) { plumed_assert( pos.size()==positions.size() ); - for(unsigned i=0; i& v1 ) { // double val; Tools::convert( sval, val ); std::vector words=Tools::getWords(sval,"\t\n ,"); std::vector val( words.size() ); - for(unsigned i=0; i >( name, val ) ); } else { flags.push_back(v1[i]); @@ -236,7 +251,9 @@ void PDB::addRemark( std::vector& v1 ) { bool PDB::hasFlag( const std::string& fname ) const { for(unsigned i=0; isecond]; + } else { + return atomsymb[p->second]; + } } unsigned PDB::getResidueNumber(AtomNumber a)const { const auto p=number2index.find(a); if(p==number2index.end()) { - std::string num; Tools::convert( a.serial(), num ); + std::string num; + Tools::convert( a.serial(), num ); plumed_merror("Residue for atom " + num + " not found" ); - } else return residue[p->second]; + } else { + return residue[p->second]; + } } std::string PDB::getResidueName(AtomNumber a) const { const auto p=number2index.find(a); if(p==number2index.end()) { - std::string num; Tools::convert( a.serial(), num ); + std::string num; + Tools::convert( a.serial(), num ); plumed_merror("Residue for atom " + num + " not found" ); - } else return residuenames[p->second]; + } else { + return residuenames[p->second]; + } } unsigned PDB::size()const { @@ -289,13 +315,18 @@ unsigned PDB::size()const { bool PDB::readFromFilepointer(FILE *fp,bool naturalUnits,double scale) { //cerr< v1; v1=Tools::getWords(line.substr(6)); + std::vector v1; + v1=Tools::getWords(line.substr(6)); addRemark( v1 ); } if(record=="CRYST1") { @@ -333,7 +374,11 @@ bool PDB::readFromFilepointer(FILE *fp,bool naturalUnits,double scale) { double cosB=std::cos(BoxABG[1]*pi/180.); double cosG=std::cos(BoxABG[2]*pi/180.); double sinG=std::sin(BoxABG[2]*pi/180.); - for (unsigned i=0; i<3; i++) {Box[i][0]=0.; Box[i][1]=0.; Box[i][2]=0.;} + for (unsigned i=0; i<3; i++) { + Box[i][0]=0.; + Box[i][1]=0.; + Box[i][2]=0.; + } Box[0][0]=BoxXYZ[0]; Box[1][0]=BoxXYZ[1]*cosG; Box[1][1]=BoxXYZ[1]*sinG; @@ -351,7 +396,9 @@ bool PDB::readFromFilepointer(FILE *fp,bool naturalUnits,double scale) { int result; auto trimmed=serial; Tools::trim(trimmed); - while(trimmed.length()<5) trimmed = std::string(" ") + trimmed; + while(trimmed.length()<5) { + trimmed = std::string(" ") + trimmed; + } const char* errmsg = h36::hy36decode(5, trimmed.c_str(),trimmed.length(), &result); if(errmsg) { std::string msg(errmsg); @@ -366,7 +413,9 @@ bool PDB::readFromFilepointer(FILE *fp,bool naturalUnits,double scale) { Tools::trim(trimmed); if(trimmed.length()>0) { int result; - while(trimmed.length()<4) trimmed = std::string(" ") + trimmed; + while(trimmed.length()<4) { + trimmed = std::string(" ") + trimmed; + } const char* errmsg = h36::hy36decode(4, trimmed.c_str(),trimmed.length(), &result); if(errmsg) { std::string msg(errmsg); @@ -396,15 +445,21 @@ bool PDB::readFromFilepointer(FILE *fp,bool naturalUnits,double scale) { residuenames.push_back(residuename); } } - if( between_ters ) block_ends.push_back( positions.size() ); + if( between_ters ) { + block_ends.push_back( positions.size() ); + } return file_is_alive; } bool PDB::read(const std::string&file,bool naturalUnits,double scale) { FILE* fp=std::fopen(file.c_str(),"r"); - if(!fp) return false; + if(!fp) { + return false; + } // call fclose when exiting this function - auto deleter=[](auto f) { std::fclose(f); }; + auto deleter=[](auto f) { + std::fclose(f); + }; std::unique_ptr fp_deleter(fp,deleter); readFromFilepointer(fp,naturalUnits,scale); return true; @@ -414,7 +469,9 @@ void PDB::getChainNames( std::vector& chains ) const { chains.resize(0); chains.push_back( chain[0] ); for(unsigned i=1; i PDB::getAtomsInResidue(const unsigned& resnum,const std::string& chainid)const { std::vector tmp; for(unsigned i=0; i PDB::getAtomsInResidue(const unsigned& resnum,const std: std::vector PDB::getAtomsInChain(const std::string& chainid)const { std::vector tmp; for(unsigned i=0; i PDB::getAtomsInChain(const std::string& chainid)const { std::string PDB::getChainID(const unsigned& resnumber) const { for(unsigned i=0; isecond]; @@ -526,14 +613,18 @@ std::string PDB::getChainID(AtomNumber a) const { bool PDB::checkForResidue( const std::string& name ) const { for(unsigned i=0; isecond]; + if(p==number2index.end()) { + plumed_merror("atom not available"); + } else { + return positions[p->second]; + } } std::vector PDB::getArgumentNames()const { @@ -570,8 +664,11 @@ std::string PDB::getMtype() const { void PDB::print( const double& lunits, GenericMolInfo* mymoldat, OFile& ofile, const std::string& fmt ) { if( argnames.size()>0 ) { ofile.printf("REMARK ARG=%s", argnames[0].c_str() ); - for(unsigned i=1; i >::iterator it=arg_data.begin(); it!=arg_data.end(); ++it) ofile.printf( descr2.c_str(),it->first.c_str(), it->second[0] ); - if( argnames.size()>0 ) ofile.printf("\n"); + for(std::map >::iterator it=arg_data.begin(); it!=arg_data.end(); ++it) { + ofile.printf( descr2.c_str(),it->first.c_str(), it->second[0] ); + } + if( argnames.size()>0 ) { + ofile.printf("\n"); + } if( !mymoldat ) { for(unsigned i=0; i at; @@ -629,127 +730,258 @@ void PDB::print( const double& lunits, GenericMolInfo* mymoldat, OFile& ofile, c bool PDB::allowedResidue( const std::string& type, const std::string& residuename ) const { if( type=="protein" ) { - if(residuename=="ALA") return true; - else if(residuename=="ARG") return true; - else if(residuename=="ASN") return true; - else if(residuename=="ASP") return true; - else if(residuename=="CYS") return true; - else if(residuename=="GLN") return true; - else if(residuename=="GLU") return true; - else if(residuename=="GLY") return true; - else if(residuename=="HIS") return true; - else if(residuename=="ILE") return true; - else if(residuename=="LEU") return true; - else if(residuename=="LYS") return true; - else if(residuename=="MET") return true; - else if(residuename=="PHE") return true; - else if(residuename=="PRO") return true; - else if(residuename=="SER") return true; - else if(residuename=="THR") return true; - else if(residuename=="TRP") return true; - else if(residuename=="TYR") return true; - else if(residuename=="VAL") return true; + if(residuename=="ALA") { + return true; + } else if(residuename=="ARG") { + return true; + } else if(residuename=="ASN") { + return true; + } else if(residuename=="ASP") { + return true; + } else if(residuename=="CYS") { + return true; + } else if(residuename=="GLN") { + return true; + } else if(residuename=="GLU") { + return true; + } else if(residuename=="GLY") { + return true; + } else if(residuename=="HIS") { + return true; + } else if(residuename=="ILE") { + return true; + } else if(residuename=="LEU") { + return true; + } else if(residuename=="LYS") { + return true; + } else if(residuename=="MET") { + return true; + } else if(residuename=="PHE") { + return true; + } else if(residuename=="PRO") { + return true; + } else if(residuename=="SER") { + return true; + } else if(residuename=="THR") { + return true; + } else if(residuename=="TRP") { + return true; + } else if(residuename=="TYR") { + return true; + } else if(residuename=="VAL") { + return true; + } // Terminal groups - else if(residuename=="ACE") return true; - else if(residuename=="NME") return true; - else if(residuename=="NH2") return true; + else if(residuename=="ACE") { + return true; + } else if(residuename=="NME") { + return true; + } else if(residuename=="NH2") { + return true; + } // Alternative residue names in common force fields - else if(residuename=="GLH") return true; // neutral GLU - else if(residuename=="ASH") return true; // neutral ASP - else if(residuename=="HID") return true; // HIS-D amber - else if(residuename=="HSD") return true; // HIS-D charmm - else if(residuename=="HIE") return true; // HIS-E amber - else if(residuename=="HSE") return true; // HIS-E charmm - else if(residuename=="HIP") return true; // HIS-P amber - else if(residuename=="HSP") return true; // HIS-P charmm - else if(residuename=="CYX") return true; // disulfide bridge CYS + else if(residuename=="GLH") { + return true; // neutral GLU + } else if(residuename=="ASH") { + return true; // neutral ASP + } else if(residuename=="HID") { + return true; // HIS-D amber + } else if(residuename=="HSD") { + return true; // HIS-D charmm + } else if(residuename=="HIE") { + return true; // HIS-E amber + } else if(residuename=="HSE") { + return true; // HIS-E charmm + } else if(residuename=="HIP") { + return true; // HIS-P amber + } else if(residuename=="HSP") { + return true; // HIS-P charmm + } else if(residuename=="CYX") { + return true; // disulfide bridge CYS + } // Weird amino acids - else if(residuename=="NLE") return true; - else if(residuename=="SFO") return true; - else return false; + else if(residuename=="NLE") { + return true; + } else if(residuename=="SFO") { + return true; + } else { + return false; + } } else if( type=="dna" ) { - if(residuename=="A") return true; - else if(residuename=="A5") return true; - else if(residuename=="A3") return true; - else if(residuename=="AN") return true; - else if(residuename=="G") return true; - else if(residuename=="G5") return true; - else if(residuename=="G3") return true; - else if(residuename=="GN") return true; - else if(residuename=="T") return true; - else if(residuename=="T5") return true; - else if(residuename=="T3") return true; - else if(residuename=="TN") return true; - else if(residuename=="C") return true; - else if(residuename=="C5") return true; - else if(residuename=="C3") return true; - else if(residuename=="CN") return true; - else if(residuename=="DA") return true; - else if(residuename=="DA5") return true; - else if(residuename=="DA3") return true; - else if(residuename=="DAN") return true; - else if(residuename=="DG") return true; - else if(residuename=="DG5") return true; - else if(residuename=="DG3") return true; - else if(residuename=="DGN") return true; - else if(residuename=="DT") return true; - else if(residuename=="DT5") return true; - else if(residuename=="DT3") return true; - else if(residuename=="DTN") return true; - else if(residuename=="DC") return true; - else if(residuename=="DC5") return true; - else if(residuename=="DC3") return true; - else if(residuename=="DCN") return true; - else return false; + if(residuename=="A") { + return true; + } else if(residuename=="A5") { + return true; + } else if(residuename=="A3") { + return true; + } else if(residuename=="AN") { + return true; + } else if(residuename=="G") { + return true; + } else if(residuename=="G5") { + return true; + } else if(residuename=="G3") { + return true; + } else if(residuename=="GN") { + return true; + } else if(residuename=="T") { + return true; + } else if(residuename=="T5") { + return true; + } else if(residuename=="T3") { + return true; + } else if(residuename=="TN") { + return true; + } else if(residuename=="C") { + return true; + } else if(residuename=="C5") { + return true; + } else if(residuename=="C3") { + return true; + } else if(residuename=="CN") { + return true; + } else if(residuename=="DA") { + return true; + } else if(residuename=="DA5") { + return true; + } else if(residuename=="DA3") { + return true; + } else if(residuename=="DAN") { + return true; + } else if(residuename=="DG") { + return true; + } else if(residuename=="DG5") { + return true; + } else if(residuename=="DG3") { + return true; + } else if(residuename=="DGN") { + return true; + } else if(residuename=="DT") { + return true; + } else if(residuename=="DT5") { + return true; + } else if(residuename=="DT3") { + return true; + } else if(residuename=="DTN") { + return true; + } else if(residuename=="DC") { + return true; + } else if(residuename=="DC5") { + return true; + } else if(residuename=="DC3") { + return true; + } else if(residuename=="DCN") { + return true; + } else { + return false; + } } else if( type=="rna" ) { - if(residuename=="A") return true; - else if(residuename=="A5") return true; - else if(residuename=="A3") return true; - else if(residuename=="AN") return true; - else if(residuename=="G") return true; - else if(residuename=="G5") return true; - else if(residuename=="G3") return true; - else if(residuename=="GN") return true; - else if(residuename=="U") return true; - else if(residuename=="U5") return true; - else if(residuename=="U3") return true; - else if(residuename=="UN") return true; - else if(residuename=="C") return true; - else if(residuename=="C5") return true; - else if(residuename=="C3") return true; - else if(residuename=="CN") return true; - else if(residuename=="RA") return true; - else if(residuename=="RA5") return true; - else if(residuename=="RA3") return true; - else if(residuename=="RAN") return true; - else if(residuename=="RG") return true; - else if(residuename=="RG5") return true; - else if(residuename=="RG3") return true; - else if(residuename=="RGN") return true; - else if(residuename=="RU") return true; - else if(residuename=="RU5") return true; - else if(residuename=="RU3") return true; - else if(residuename=="RUN") return true; - else if(residuename=="RC") return true; - else if(residuename=="RC5") return true; - else if(residuename=="RC3") return true; - else if(residuename=="RCN") return true; - else return false; + if(residuename=="A") { + return true; + } else if(residuename=="A5") { + return true; + } else if(residuename=="A3") { + return true; + } else if(residuename=="AN") { + return true; + } else if(residuename=="G") { + return true; + } else if(residuename=="G5") { + return true; + } else if(residuename=="G3") { + return true; + } else if(residuename=="GN") { + return true; + } else if(residuename=="U") { + return true; + } else if(residuename=="U5") { + return true; + } else if(residuename=="U3") { + return true; + } else if(residuename=="UN") { + return true; + } else if(residuename=="C") { + return true; + } else if(residuename=="C5") { + return true; + } else if(residuename=="C3") { + return true; + } else if(residuename=="CN") { + return true; + } else if(residuename=="RA") { + return true; + } else if(residuename=="RA5") { + return true; + } else if(residuename=="RA3") { + return true; + } else if(residuename=="RAN") { + return true; + } else if(residuename=="RG") { + return true; + } else if(residuename=="RG5") { + return true; + } else if(residuename=="RG3") { + return true; + } else if(residuename=="RGN") { + return true; + } else if(residuename=="RU") { + return true; + } else if(residuename=="RU5") { + return true; + } else if(residuename=="RU3") { + return true; + } else if(residuename=="RUN") { + return true; + } else if(residuename=="RC") { + return true; + } else if(residuename=="RC5") { + return true; + } else if(residuename=="RC3") { + return true; + } else if(residuename=="RCN") { + return true; + } else { + return false; + } } else if( type=="water" ) { - if(residuename=="SOL") return true; - if(residuename=="WAT") return true; + if(residuename=="SOL") { + return true; + } + if(residuename=="WAT") { + return true; + } return false; } else if( type=="ion" ) { - if(residuename=="IB+") return true; - if(residuename=="CA") return true; - if(residuename=="CL") return true; - if(residuename=="NA") return true; - if(residuename=="MG") return true; - if(residuename=="K") return true; - if(residuename=="RB") return true; - if(residuename=="CS") return true; - if(residuename=="LI") return true; - if(residuename=="ZN") return true; + if(residuename=="IB+") { + return true; + } + if(residuename=="CA") { + return true; + } + if(residuename=="CL") { + return true; + } + if(residuename=="NA") { + return true; + } + if(residuename=="MG") { + return true; + } + if(residuename=="K") { + return true; + } + if(residuename=="RB") { + return true; + } + if(residuename=="CS") { + return true; + } + if(residuename=="LI") { + return true; + } + if(residuename=="ZN") { + return true; + } return false; } return false; diff --git a/src/tools/Pbc.cpp b/src/tools/Pbc.cpp index 2423987a3d..f55ac8cdc3 100644 --- a/src/tools/Pbc.cpp +++ b/src/tools/Pbc.cpp @@ -30,8 +30,7 @@ namespace PLMD { Pbc::Pbc(): - type(unset) -{ + type(unset) { box.zero(); invBox.zero(); } @@ -40,11 +39,17 @@ void Pbc::buildShifts(gch::small_vector shifts[2][2][2])con const double small=1e-28; // clear all shifts - for(int i=0; i<2; i++) for(int j=0; j<2; j++) for(int k=0; k<2; k++) shifts[i][j][k].clear(); + for(int i=0; i<2; i++) + for(int j=0; j<2; j++) + for(int k=0; k<2; k++) { + shifts[i][j][k].clear(); + } // enumerate all possible shifts // since box is reduced, only 27 shifts have to be attempted - for(int l=-1; l<=1; l++) for(int m=-1; m<=1; m++) for(int n=-1; n<=1; n++) { + for(int l=-1; l<=1; l++) + for(int m=-1; m<=1; m++) + for(int n=-1; n<=1; n++) { // int/double shift vectors const int ishift[3]= {l,m,n}; @@ -52,11 +57,16 @@ void Pbc::buildShifts(gch::small_vector shifts[2][2][2])con // count how many components are != 0 unsigned count=0; - for(int s=0; s<3; s++) if(ishift[s]!=0) count++; + for(int s=0; s<3; s++) + if(ishift[s]!=0) { + count++; + } // skips trivial (0,0,0) and cases with three shifts // only 18 shifts survive past this point - if(count==0 || count==3) continue; + if(count==0 || count==3) { + continue; + } // check if that Wigner-Seitz face is perpendicular to the axis. // this allows to eliminate shifts in symmetric cells. @@ -65,24 +75,37 @@ void Pbc::buildShifts(gch::small_vector shifts[2][2][2])con Vector cosdir=matmul(reduced,transpose(reduced),dshift); double dp=dotProduct(dshift,cosdir); double ref=modulo2(dshift)*modulo2(cosdir); - if(std::fabs(ref-dp*dp)0) skip=true; - if(skip) continue; + for(int s=0; s<3; s++) + if(ishift[s]*block[s]>0) { + skip=true; + } + if(skip) { + continue; + } skip=true; for(int s=0; s<3; s++) { // check that the components of cosdir along the non-shifted directions // have the proper sign - if(((1-ishift[s]*ishift[s])*block[s])*cosdir[s]<-small) skip=false; + if(((1-ishift[s]*ishift[s])*block[s])*cosdir[s]<-small) { + skip=false; + } + } + if(skip) { + continue; } - if(skip)continue; // if we arrive to this point, shift is eligible and is added to the list shifts[i][j][k].push_back(matmul(transpose(reduced),dshift)); @@ -91,9 +114,13 @@ void Pbc::buildShifts(gch::small_vector shifts[2][2][2])con } void Pbc::fullSearch(Vector&d)const { - if(type==unset) return; + if(type==unset) { + return; + } Vector s=matmul(invReduced.transpose(),d); - for(int i=0; i<3; i++) s[i]=Tools::pbc(s[i]); + for(int i=0; i<3; i++) { + s[i]=Tools::pbc(s[i]); + } d=matmul(reduced.transpose(),s); const int smax=4; Vector a0(reduced.getRow(0)); @@ -101,7 +128,9 @@ void Pbc::fullSearch(Vector&d)const { Vector a2(reduced.getRow(2)); Vector best(d); double lbest=d.modulo2(); - for(int i=-smax; i<=smax; i++) for(int j=-smax; j<=smax; j++) for(int k=-smax; k<=smax; k++) { + for(int i=-smax; i<=smax; i++) + for(int j=-smax; j<=smax; j++) + for(int k=-smax; k<=smax; k++) { Vector trial=d+i*a0+j*a1+k*a2; double ltrial=trial.modulo2(); if(ltrial& dlist, unsigned max_index) const { @@ -160,18 +203,32 @@ void Pbc::apply(std::vector& dlist, unsigned max_index) const { } void Pbc::apply(VectorView dlist, unsigned max_index) const { - if (max_index==0) max_index=dlist.size(); + if (max_index==0) { + max_index=dlist.size(); + } if(type==unset) { // do nothing } else if(type==orthorombic) { #ifdef __PLUMED_PBC_WHILE for(unsigned k=0; khdiag[0]) dlist[k][0]-=diag[0]; - while(dlist[k][0]<=mdiag[0]) dlist[k][0]+=diag[0]; - while(dlist[k][1]>hdiag[1]) dlist[k][1]-=diag[1]; - while(dlist[k][1]<=mdiag[1]) dlist[k][1]+=diag[1]; - while(dlist[k][2]>hdiag[2]) dlist[k][2]-=diag[2]; - while(dlist[k][2]<=mdiag[2]) dlist[k][2]+=diag[2]; + while(dlist[k][0]>hdiag[0]) { + dlist[k][0]-=diag[0]; + } + while(dlist[k][0]<=mdiag[0]) { + dlist[k][0]+=diag[0]; + } + while(dlist[k][1]>hdiag[1]) { + dlist[k][1]-=diag[1]; + } + while(dlist[k][1]<=mdiag[1]) { + dlist[k][1]+=diag[1]; + } + while(dlist[k][2]>hdiag[2]) { + dlist[k][2]-=diag[2]; + } + while(dlist[k][2]<=mdiag[2]) { + dlist[k][2]+=diag[2]; + } } #else for(unsigned k=0; khdiag[i]) d[i]-=diag[i]; - while(d[i]<=mdiag[i]) d[i]+=diag[i]; + while(d[i]>hdiag[i]) { + d[i]-=diag[i]; + } + while(d[i]<=mdiag[i]) { + d[i]+=diag[i]; + } } #else - for(int i=0; i<3; i++) d[i]=Tools::pbc(d[i]*invBox(i,i))*box(i,i); + for(int i=0; i<3; i++) { + d[i]=Tools::pbc(d[i]*invBox(i,i))*box(i,i); + } #endif } else if(type==generic) { Vector s=matmul(d,invReduced); @@ -252,7 +317,9 @@ Vector Pbc::distance(const Vector&v1,const Vector&v2,int*nshifts)const { Vector best(d); double lbest(modulo2(best)); // loop over possible shifts: - if(nshifts) *nshifts+=myshifts.size(); + if(nshifts) { + *nshifts+=myshifts.size(); + } for(unsigned i=0; i operator[](size_t i) { return MemoryView(ptr_ + i * STRIDE);} + MemoryView operator[](size_t i) { + return MemoryView(ptr_ + i * STRIDE); + } }; using VectorView = mdMemoryView; diff --git a/src/tools/PlumedHandle.cpp b/src/tools/PlumedHandle.cpp index d58d13a208..5b72d617a4 100644 --- a/src/tools/PlumedHandle.cpp +++ b/src/tools/PlumedHandle.cpp @@ -38,20 +38,17 @@ #define __PLUMED_WRAPPER_CXX_ANONYMOUS_NAMESPACE_PLMD_EXCEPTIONS 1 #include "../wrapper/Plumed.h" -namespace PLMD -{ +namespace PLMD { PlumedHandle::PlumedHandle(): - local(Tools::make_unique()) -{ + local(Tools::make_unique()) { } PlumedHandle::PlumedHandle(const char* kernel) #ifdef __PLUMED_HAS_DLOPEN : - loaded(plumed_c2v(plumed_create_dlopen(kernel))) -{ + loaded(plumed_c2v(plumed_create_dlopen(kernel))) { if(!plumed_valid(plumed_v2c(loaded))) { // this is necessary to make sure loaded is properly destroyed plumed_finalize(plumed_v2c(loaded)); @@ -65,7 +62,9 @@ PlumedHandle::PlumedHandle(const char* kernel) #endif PlumedHandle::~PlumedHandle() { - if(loaded) plumed_finalize(plumed_v2c(loaded)); + if(loaded) { + plumed_finalize(plumed_v2c(loaded)); + } } PlumedHandle PlumedHandle::dlopen(const char* path) { @@ -109,19 +108,22 @@ void PlumedHandle::cmd(std::string_view key,const TypesafePtr & ptr) { plumed_cmd(plumed_v2c(loaded),key_buffer,safe); - } else plumed_error() << "should never arrive here (either one or the other should work)"; + } else { + plumed_error() << "should never arrive here (either one or the other should work)"; + } } PlumedHandle::PlumedHandle(PlumedHandle && other) noexcept: local(std::move(other.local)), - loaded(other.loaded) -{ + loaded(other.loaded) { other.loaded=nullptr; } PlumedHandle & PlumedHandle::operator=(PlumedHandle && other) noexcept { if(this!=&other) { - if(loaded) plumed_finalize(plumed_v2c(loaded)); + if(loaded) { + plumed_finalize(plumed_v2c(loaded)); + } local=std::move(other.local); loaded=other.loaded; other.loaded=nullptr; diff --git a/src/tools/PlumedHandle.h b/src/tools/PlumedHandle.h index be22d5a661..cbf5ec6bd0 100644 --- a/src/tools/PlumedHandle.h +++ b/src/tools/PlumedHandle.h @@ -26,8 +26,7 @@ #include "TypesafePtr.h" #include -namespace PLMD -{ +namespace PLMD { class PlumedMain; @@ -71,8 +70,7 @@ Thus, once constructed the object is guaranteed to be functional. */ class PlumedHandle : - public WithCmd -{ + public WithCmd { /// Pointer to PlumedMain. /// Used when using the current kernel in order to avoid unneeded indirections. std::unique_ptr local; diff --git a/src/tools/RMSD.cpp b/src/tools/RMSD.cpp index 05e787122a..bc7d5fbea7 100644 --- a/src/tools/RMSD.cpp +++ b/src/tools/RMSD.cpp @@ -54,14 +54,13 @@ void RMSD::setType(const std::string & mytype) { alignmentMethod=SIMPLE; // initialize with the simplest case: no rotation if (mytype=="SIMPLE") { alignmentMethod=SIMPLE; - } - else if (mytype=="OPTIMAL") { + } else if (mytype=="OPTIMAL") { alignmentMethod=OPTIMAL; - } - else if (mytype=="OPTIMAL-FAST") { + } else if (mytype=="OPTIMAL-FAST") { alignmentMethod=OPTIMAL_FAST; + } else { + plumed_merror("unknown RMSD type" + mytype); } - else plumed_merror("unknown RMSD type" + mytype); } @@ -80,9 +79,15 @@ void RMSD::clear() { std::string RMSD::getMethod() { std::string mystring; switch(alignmentMethod) { - case SIMPLE: mystring.assign("SIMPLE"); break; - case OPTIMAL: mystring.assign("OPTIMAL"); break; - case OPTIMAL_FAST: mystring.assign("OPTIMAL-FAST"); break; + case SIMPLE: + mystring.assign("SIMPLE"); + break; + case OPTIMAL: + mystring.assign("OPTIMAL"); + break; + case OPTIMAL_FAST: + mystring.assign("OPTIMAL-FAST"); + break; } return mystring; } @@ -97,9 +102,13 @@ void RMSD::setReference(const std::vector & reference) { plumed_massert(displace.empty(),"you should first clear() an RMSD object, then set a new reference"); align.resize(n,1.0/n); displace.resize(n,1.0/n); - for(unsigned i=0; ireference[i]*align[i]; + for(unsigned i=0; ireference[i]*align[i]; + } #pragma omp simd - for(unsigned i=0; ireference[i]-=reference_center; + for(unsigned i=0; ireference[i]-=reference_center; + } reference_center_is_calculated=true; reference_center_is_removed=true; } @@ -116,15 +125,21 @@ void RMSD::setAlign(const std::vector & align, bool normalize_weights, b if(normalize_weights) { double w=0.0; #pragma omp simd reduction(+:w) - for(unsigned i=0; ialign[i]; + for(unsigned i=0; ialign[i]; + } if(w>epsilon) { double inv=1.0/w; #pragma omp simd - for(unsigned i=0; ialign[i]*=inv; + for(unsigned i=0; ialign[i]*=inv; + } } else { double inv=1.0/n; #pragma omp simd - for(unsigned i=0; ialign[i]=inv; + for(unsigned i=0; ialign[i]=inv; + } } } // recalculate the center anyway @@ -156,15 +171,21 @@ void RMSD::setDisplace(const std::vector & displace, bool normalize_weig if(normalize_weights) { double w=0.0; #pragma omp simd reduction(+:w) - for(unsigned i=0; idisplace[i]; + for(unsigned i=0; idisplace[i]; + } if(w>epsilon) { double inv=1.0/w; #pragma omp simd - for(unsigned i=0; idisplace[i]*=inv; + for(unsigned i=0; idisplace[i]*=inv; + } } else { double inv=1.0/n; #pragma omp simd - for(unsigned i=0; idisplace[i]=inv; + for(unsigned i=0; idisplace[i]=inv; + } } } } @@ -184,16 +205,24 @@ double RMSD::calculate(const std::vector & positions,std::vector std::vector displacement( derivatives.size() ); ret=simpleAlignment(align,displace,positions,reference,derivatives,displacement,squared); break; - } case OPTIMAL_FAST : { + } + case OPTIMAL_FAST : { // this is calling the fastest option: - if(align==displace) ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); - else ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); + if(align==displace) { + ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); + } else { + ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); + } break; - } case OPTIMAL : { + } + case OPTIMAL : { // this is the fast routine but in the "safe" mode, which gives less numerical error: - if(align==displace) ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); - else ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); + if(align==displace) { + ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); + } else { + ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); + } break; } } @@ -211,12 +240,18 @@ double RMSD::calc_DDistDRef( const std::vector& positions, std::vector(align,displace,positions,reference,derivatives,DDistDRef, squared); - else ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef,squared); + if(align==displace) { + ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef, squared); + } else { + ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef,squared); + } break; case OPTIMAL: - if(align==displace) ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef,squared); - else ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef,squared); + if(align==displace) { + ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef,squared); + } else { + ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef,squared); + } break; } return ret; @@ -232,12 +267,18 @@ double RMSD::calc_SOMA( const std::vector& positions, std::vector(align,displace,positions,reference,derivatives,DDistDRef, squared); - else ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef,squared); + if(align==displace) { + ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef, squared); + } else { + ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef,squared); + } break; case OPTIMAL: - if(align==displace) ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef,squared); - else ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef,squared); + if(align==displace) { + ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef,squared); + } else { + ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef,squared); + } break; } return ret; @@ -251,12 +292,18 @@ double RMSD::calc_DDistDRef_Rot_DRotDPos( const std::vector& positions, plumed_merror("derivative of the refreence frame not implemented for SIMPLE alignmentMethod \n"); break; case OPTIMAL_FAST: - if(align==displace) ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); - else ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); + if(align==displace) { + ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); + } else { + ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); + } break; case OPTIMAL: - if(align==displace) ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); - else ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); + if(align==displace) { + ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); + } else { + ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); + } break; } return ret; @@ -269,12 +316,18 @@ double RMSD::calc_DDistDRef_Rot_DRotDPos_DRotDRef( const std::vector& po plumed_merror("derivative of the refreence frame not implemented for SIMPLE alignmentMethod \n"); break; case OPTIMAL_FAST: - if(align==displace) ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); - else ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); + if(align==displace) { + ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); + } else { + ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); + } break; case OPTIMAL: - if(align==displace) ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); - else ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); + if(align==displace) { + ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); + } else { + ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); + } break; } return ret; @@ -287,12 +340,18 @@ double RMSD::calc_Rot_DRotDRr01( const std::vector& positions, Tensor & plumed_merror("derivative of the refreence frame not implemented for SIMPLE alignmentMethod \n"); break; case OPTIMAL_FAST: - if(align==displace) ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); - else ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); + if(align==displace) { + ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); + } else { + ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); + } break; case OPTIMAL: - if(align==displace) ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); - else ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); + if(align==displace) { + ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); + } else { + ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); + } break; } return ret; @@ -305,12 +364,18 @@ double RMSD::calc_Rot( const std::vector& positions, std::vector plumed_merror("derivative of the refreence frame not implemented for SIMPLE alignmentMethod \n"); break; case OPTIMAL_FAST: - if(align==displace) ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); - else ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); + if(align==displace) { + ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); + } else { + ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); + } break; case OPTIMAL: - if(align==displace) ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); - else ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); + if(align==displace) { + ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); + } else { + ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); + } break; } return ret; @@ -323,12 +388,18 @@ double RMSD::calculateWithCloseStructure( const std::vector& positions, plumed_merror("derivative of the refreence frame not implemented for SIMPLE alignmentMethod \n"); break; case OPTIMAL_FAST: - if(align==displace) ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); - else ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); + if(align==displace) { + ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); + } else { + ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); + } break; case OPTIMAL: - if(align==displace) ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); - else ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); + if(align==displace) { + ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); + } else { + ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); + } break; } return ret; @@ -341,12 +412,18 @@ double RMSD::calc_PCAelements( const std::vector& positions, std::vector plumed_merror("derivative of the refreence frame not implemented for SIMPLE alignmentMethod \n"); break; case OPTIMAL_FAST: - if(align==displace) ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); - else ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); + if(align==displace) { + ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); + } else { + ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); + } break; case OPTIMAL: - if(align==displace) ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); - else ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); + if(align==displace) { + ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); + } else { + ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); + } break; } return ret; @@ -360,12 +437,18 @@ double RMSD::calc_FitElements( const std::vector& positions, Tensor & Ro plumed_merror("derivative of the refreence frame not implemented for SIMPLE alignmentMethod \n"); break; case OPTIMAL_FAST: - if(align==displace)ret=optimalAlignment_Fit(align,displace,positions,reference, Rotation,DRotDPos,centeredpositions,center_positions,squared); - else ret=optimalAlignment_Fit(align,displace,positions,reference, Rotation,DRotDPos,centeredpositions,center_positions,squared); + if(align==displace) { + ret=optimalAlignment_Fit(align,displace,positions,reference, Rotation,DRotDPos,centeredpositions,center_positions,squared); + } else { + ret=optimalAlignment_Fit(align,displace,positions,reference, Rotation,DRotDPos,centeredpositions,center_positions,squared); + } break; case OPTIMAL: - if(align==displace)ret=optimalAlignment_Fit(align,displace,positions,reference,Rotation,DRotDPos,centeredpositions,center_positions,squared); - else ret=optimalAlignment_Fit(align,displace,positions,reference,Rotation,DRotDPos,centeredpositions,center_positions,squared); + if(align==displace) { + ret=optimalAlignment_Fit(align,displace,positions,reference,Rotation,DRotDPos,centeredpositions,center_positions,squared); + } else { + ret=optimalAlignment_Fit(align,displace,positions,reference,Rotation,DRotDPos,centeredpositions,center_positions,squared); + } break; } return ret; @@ -412,7 +495,9 @@ double RMSD::simpleAlignment(const std::vector & align, // sqrt dist=std::sqrt(dist); ///// sqrt on derivatives - for(unsigned i=0; i & align, dist=eigenvals[0]+rr00+rr11; q=Vector4d(eigenvecs[0][0],eigenvecs[0][1],eigenvecs[0][2],eigenvecs[0][3]); double dq_dm[4][4][4]; - for(unsigned i=0; i<4; i++) for(unsigned j=0; j<4; j++) for(unsigned k=0; k<4; k++) { + for(unsigned i=0; i<4; i++) + for(unsigned j=0; j<4; j++) + for(unsigned k=0; k<4; k++) { double tmp=0.0; // perturbation theory for matrix m - for(unsigned l=1; l<4; l++) tmp+=eigenvecs[l][j]*eigenvecs[l][i]/(eigenvals[0]-eigenvals[l])*eigenvecs[0][k]; + for(unsigned l=1; l<4; l++) { + tmp+=eigenvecs[l][j]*eigenvecs[l][i]/(eigenvals[0]-eigenvals[l])*eigenvecs[0][k]; + } dq_dm[i][j][k]=tmp; } // propagation to _drr01 for(unsigned i=0; i<4; i++) { Tensor tmp; - for(unsigned j=0; j<4; j++) for(unsigned k=0; k<4; k++) { + for(unsigned j=0; j<4; j++) + for(unsigned k=0; k<4; k++) { tmp+=dq_dm[i][j][k]*dm_drr01[j][k]; } dq_drr01[i]=tmp; @@ -557,10 +647,14 @@ double RMSD::optimalAlignment(const std::vector & align, double prefactor=2.0; - if(!squared && alEqDis) prefactor*=0.5/std::sqrt(dist); + if(!squared && alEqDis) { + prefactor*=0.5/std::sqrt(dist); + } // if "safe", recompute dist here to a better accuracy - if(safe || !alEqDis) dist=0.0; + if(safe || !alEqDis) { + dist=0.0; + } // If safe is set to "false", MSD is taken from the eigenvalue of the M matrix // If safe is set to "true", MSD is recomputed from the rotational matrix @@ -576,7 +670,9 @@ double RMSD::optimalAlignment(const std::vector & align, // there is no need for derivatives of rotation and shift here as it is by construction zero // (similar to Hellman-Feynman forces) derivatives[iat]= prefactor*align[iat]*d; - if(safe) dist+=align[iat]*modulo2(d); + if(safe) { + dist+=align[iat]*modulo2(d); + } } else { // the case for align != displace is different, sob: dist+=displace[iat]*modulo2(d); @@ -591,7 +687,10 @@ double RMSD::optimalAlignment(const std::vector & align, if(!alEqDis) { Tensor ddist_drr01; - for(unsigned i=0; i<3; i++) for(unsigned j=0; j<3; j++) ddist_drr01+=ddist_drotation[i][j]*drotation_drr01[i][j]; + for(unsigned i=0; i<3; i++) + for(unsigned j=0; j<3; j++) { + ddist_drr01+=ddist_drotation[i][j]*drotation_drr01[i][j]; + } for(unsigned iat=0; iat & align, dist=std::sqrt(dist); if(!alEqDis) { double xx=0.5/dist; - for(unsigned iat=0; iat & align, // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // Perform the diagonalization and all the needed stuff cd.doCoreCalc(safe,alEqDis); @@ -655,12 +762,18 @@ double RMSD::optimalAlignment_DDistDRef(const std::vector & align, // transfer the settings for the center to let the CoreCalc deal with it // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // Perform the diagonalization and all the needed stuff cd.doCoreCalc(safe,alEqDis); @@ -686,12 +799,18 @@ double RMSD::optimalAlignment_SOMA(const std::vector & align, // transfer the settings for the center to let the CoreCalc deal with it // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // Perform the diagonalization and all the needed stuff cd.doCoreCalc(safe,alEqDis); @@ -720,12 +839,18 @@ double RMSD::optimalAlignment_DDistDRef_Rot_DRotDPos(const std::vector // transfer the settings for the center to let the CoreCalc deal with it // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // Perform the diagonalization and all the needed stuff cd.doCoreCalc(safe,alEqDis); @@ -758,12 +883,18 @@ double RMSD::optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(const std::vector // transfer the settings for the center to let the CoreCalc deal with it // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // Perform the diagonalization and all the needed stuff cd.doCoreCalc(safe,alEqDis); @@ -793,12 +924,18 @@ double RMSD::optimalAlignment_Rot_DRotDRr01(const std::vector & align, RMSDCoreData cd(align,displace,positions,reference); // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // Perform the diagonalization and all the needed stuff cd.doCoreCalc(safe,alEqDis); @@ -824,12 +961,18 @@ double RMSD::optimalAlignment_Rot(const std::vector & align, RMSDCoreData cd(align,displace,positions,reference); // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // Perform the diagonalization and all the needed stuff cd.doCoreCalc(safe,alEqDis); @@ -857,12 +1000,18 @@ double RMSD::optimalAlignmentWithCloseStructure(const std::vector & al RMSDCoreData cd(align,displace,positions,reference); // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // instead of diagonalization, approximate with saved rotation matrix cd.doCoreCalcWithCloseStructure(safe,alEqDis, rotationPosClose, rotationRefClose, drotationPosCloseDrr01); @@ -891,12 +1040,18 @@ double RMSD::optimalAlignment_PCA(const std::vector & align, RMSDCoreData cd(align,displace,positions,reference); // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // Perform the diagonalization and all the needed stuff cd.doCoreCalc(safe,alEqDis); @@ -933,12 +1088,18 @@ double RMSD::optimalAlignment_Fit(const std::vector & align, RMSDCoreData cd(align,displace,positions,reference); // transfer the settings for the center to let the CoreCalc deal with it cd.setPositionsCenterIsRemoved(positions_center_is_removed); - if(positions_center_is_calculated) {cd.setPositionsCenter(positions_center);} - else {cd.calcPositionsCenter();}; + if(positions_center_is_calculated) { + cd.setPositionsCenter(positions_center); + } else { + cd.calcPositionsCenter(); + }; cd.setReferenceCenterIsRemoved(reference_center_is_removed); - if(!reference_center_is_calculated) {cd.calcReferenceCenter();} - else {cd.setReferenceCenter(reference_center);} + if(!reference_center_is_calculated) { + cd.calcReferenceCenter(); + } else { + cd.setReferenceCenter(reference_center); + } // Perform the diagonalization and all the needed stuff cd.doCoreCalc(safe,alEqDis); @@ -979,8 +1140,16 @@ void RMSDCoreData::doCoreCalc(bool safe,bool alEqDis, bool only_rotation) { // This is positions*reference Tensor rr01; // center of mass managing: must subtract the center from the position or not? - Vector cp; cp.zero(); if(!cpositions_is_removed)cp=cpositions; - Vector cr; cr.zero(); if(!creference_is_removed)cr=creference; + Vector cp; + cp.zero(); + if(!cpositions_is_removed) { + cp=cpositions; + } + Vector cr; + cr.zero(); + if(!creference_is_removed) { + cr=creference; + } // second expensive loop: compute second moments wrt centers for(unsigned iat=0; iat here_eigenvecs; VectorGeneric<1> here_eigenvals; diagMatSym(m, here_eigenvals, here_eigenvecs ); - for(unsigned i=0; i<4; i++) eigenvecs[0][i]=here_eigenvecs[0][i]; + for(unsigned i=0; i<4; i++) { + eigenvecs[0][i]=here_eigenvecs[0][i]; + } eigenvals[0]=here_eigenvals[0]; q=Vector4d(eigenvecs[0][0],eigenvecs[0][1],eigenvecs[0][2],eigenvecs[0][3]); } @@ -1090,7 +1266,9 @@ void RMSDCoreData::doCoreCalc(bool safe,bool alEqDis, bool only_rotation) { d.resize(n); // calculate rotation matrix derivatives and components distances needed for components only when align!=displacement - if(!alEqDis)ddist_drotation.zero(); + if(!alEqDis) { + ddist_drotation.zero(); + } // This pragma leads to incorrect results with INTEL compiler. // Failures are seen in rt65-rmsd2, rt-close-structure, rt64-pca, and others. // Not really clear why. GB @@ -1102,11 +1280,15 @@ void RMSDCoreData::doCoreCalc(bool safe,bool alEqDis, bool only_rotation) { } // ddist_drotation if needed if(!alEqDis or !only_rotation) { - for (unsigned iat=0; iatalEqDis=alEqDis; @@ -1117,17 +1299,23 @@ void RMSDCoreData::doCoreCalc(bool safe,bool alEqDis, bool only_rotation) { /// just retrieve the distance already calculated double RMSDCoreData::getDistance( bool squared) { - if(!isInitialized)plumed_merror("getDistance cannot calculate the distance without being initialized first by doCoreCalc "); + if(!isInitialized) { + plumed_merror("getDistance cannot calculate the distance without being initialized first by doCoreCalc "); + } double localDist=0.0; const unsigned n=static_cast(reference.size()); - if(safe || !alEqDis) localDist=0.0; - else + if(safe || !alEqDis) { + localDist=0.0; + } else { localDist=eigenvals[0]+rr00+rr11; + } #pragma omp simd reduction(+:localDist) for(unsigned iat=0; iatalEqDis=alEqDis; this->safe=safe; @@ -1184,10 +1381,16 @@ std::vector RMSDCoreData::getDDistanceDPositions() { Vector ddist_dcpositions; derivatives.resize(n); double prefactor=1.0; - if(!distanceIsMSD) prefactor*=0.5/dist; + if(!distanceIsMSD) { + prefactor*=0.5/dist; + } plumed_massert(!retrieve_only_rotation,"You used only_rotation=true in doCoreCalc therefore you cannot retrieve this information now"); - if(!hasDistance)plumed_merror("getDPositionsDerivatives needs to calculate the distance via getDistance first !"); - if(!isInitialized)plumed_merror("getDPositionsDerivatives needs to initialize the coreData first!"); + if(!hasDistance) { + plumed_merror("getDPositionsDerivatives needs to calculate the distance via getDistance first !"); + } + if(!isInitialized) { + plumed_merror("getDPositionsDerivatives needs to initialize the coreData first!"); + } Vector csum; for(unsigned iat=0; iat RMSDCoreData::getDDistanceDPositions() { if(!alEqDis) #pragma omp simd - for(unsigned iat=0; iat RMSDCoreData::getDDistanceDReference() { Vector ddist_dcreference; derivatives.resize(n); double prefactor=1.0; - if(!distanceIsMSD) prefactor*=0.5/dist; + if(!distanceIsMSD) { + prefactor*=0.5/dist; + } Vector csum; plumed_massert(!retrieve_only_rotation,"You used only_rotation=true in doCoreCalc therefore you cannot retrieve this information now"); - if(!hasDistance)plumed_merror("getDDistanceDReference needs to calculate the distance via getDistance first !"); - if(!isInitialized)plumed_merror("getDDistanceDReference to initialize the coreData first!"); + if(!hasDistance) { + plumed_merror("getDDistanceDReference needs to calculate the distance via getDistance first !"); + } + if(!isInitialized) { + plumed_merror("getDDistanceDReference to initialize the coreData first!"); + } // get the transpose rotation Tensor t_rotation=rotation.transpose(); Tensor t_ddist_drr01=ddist_drr01.transpose(); @@ -1252,7 +1463,9 @@ std::vector RMSDCoreData::getDDistanceDReference() { if(!alEqDis) #pragma omp simd - for(unsigned iat=0; iat RMSDCoreData::getDDistanceDReferenceSOMA() { Vector ddist_dcreference; derivatives.resize(n); double prefactor=1.0; - if(!distanceIsMSD) prefactor*=0.5/dist; + if(!distanceIsMSD) { + prefactor*=0.5/dist; + } Vector csum,tmp1,tmp2; plumed_massert(!retrieve_only_rotation,"You used only_rotation=true in doCoreCalc therefore you cannot retrieve this information now"); - if(!hasDistance)plumed_merror("getDDistanceDReference needs to calculate the distance via getDistance first !"); - if(!isInitialized)plumed_merror("getDDistanceDReference to initialize the coreData first!"); + if(!hasDistance) { + plumed_merror("getDDistanceDReference needs to calculate the distance via getDistance first !"); + } + if(!isInitialized) { + plumed_merror("getDDistanceDReference to initialize the coreData first!"); + } // get the transpose rotation Tensor t_rotation=rotation.transpose(); @@ -1289,7 +1508,10 @@ std::vector RMSDCoreData::getDDistanceDReferenceSOMA() { } } - if(!alEqDis) for(unsigned iat=0; iat > RMSDCoreData::getDRotationDPositions( bool inverseTransform ) { const unsigned n=static_cast(reference.size()); plumed_massert(!retrieve_only_rotation,"You used only_rotation=true in doCoreCalc therefore you cannot retrieve this information now"); - if(!isInitialized)plumed_merror("getDRotationDPosition to initialize the coreData first!"); + if(!isInitialized) { + plumed_merror("getDRotationDPosition to initialize the coreData first!"); + } Matrix > DRotDPos=Matrix >(3,3); // remember drotation_drr01 is Tensor drotation_drr01[3][3] // (3x3 rot) (3x3 components of rr01) std::vector v(n); Vector csum; // these below could probably be calculated in the main routine - Vector cp; cp.zero(); if(!cpositions_is_removed)cp=cpositions; - Vector cr; cr.zero(); if(!creference_is_removed)cr=creference; - for(unsigned iat=0; iat > RMSDCoreData::getDRotationDReference( bool inverseTransform ) { const unsigned n=static_cast(reference.size()); plumed_massert(!retrieve_only_rotation,"You used only_rotation=true in doCoreCalc therefore you cannot retrieve this information now"); - if(!isInitialized)plumed_merror("getDRotationDPositions to initialize the coreData first!"); + if(!isInitialized) { + plumed_merror("getDRotationDPositions to initialize the coreData first!"); + } Matrix > DRotDRef=Matrix >(3,3); // remember drotation_drr01 is Tensor drotation_drr01[3][3] // (3x3 rot) (3x3 components of rr01) std::vector v(n); Vector csum; // these below could probably be calculated in the main routine - Vector cp; cp.zero(); if(!cpositions_is_removed)cp=cpositions; - Vector cr; cr.zero(); if(!creference_is_removed)cr=creference; - for(unsigned iat=0; iat RMSDCoreData::getAlignedReferenceToPositions() { std::vector alignedref; const unsigned n=static_cast(reference.size()); alignedref.resize(n); - if(!isInitialized)plumed_merror("getAlignedReferenceToPostions needs to initialize the coreData first!"); + if(!isInitialized) { + plumed_merror("getAlignedReferenceToPostions needs to initialize the coreData first!"); + } // avoid to calculate matrix element but use the sum of what you have - Vector cp; cp.zero(); if(!cpositions_is_removed)cp=cpositions; - for(unsigned iat=0; iat RMSDCoreData::getAlignedPositionsToReference() { std::vector alignedpos; - if(!isInitialized)plumed_merror("getAlignedPostionsToReference needs to initialize the coreData first!"); + if(!isInitialized) { + plumed_merror("getAlignedPostionsToReference needs to initialize the coreData first!"); + } const unsigned n=static_cast(positions.size()); alignedpos.resize(n); - Vector cp; cp.zero(); if(!cpositions_is_removed)cp=cpositions; + Vector cp; + cp.zero(); + if(!cpositions_is_removed) { + cp=cpositions; + } // avoid to calculate matrix element but use the sum of what you have - for(unsigned iat=0; iat RMSDCoreData::getCenteredPositions() { std::vector centeredpos; const unsigned n=static_cast(reference.size()); centeredpos.resize(n); - if(!isInitialized)plumed_merror("getCenteredPositions needs to initialize the coreData first!"); + if(!isInitialized) { + plumed_merror("getCenteredPositions needs to initialize the coreData first!"); + } // avoid to calculate matrix element but use the sum of what you have - for(unsigned iat=0; iat RMSDCoreData::getCenteredReference() { std::vector centeredref; const unsigned n=static_cast(reference.size()); centeredref.resize(n); - if(!isInitialized)plumed_merror("getCenteredReference needs to initialize the coreData first!"); + if(!isInitialized) { + plumed_merror("getCenteredReference needs to initialize the coreData first!"); + } // avoid to calculate matrix element but use the sum of what you have - Vector cr; cr.zero(); if(!creference_is_removed)cr=creference; - for(unsigned iat=0; iat,3> & RMSDCoreData::getDRotationDRr01() const { - if(!isInitialized)plumed_merror("getDRotationDRr01 needs to initialize the coreData first!"); + if(!isInitialized) { + plumed_merror("getDRotationDRr01 needs to initialize the coreData first!"); + } return drotation_drr01; } diff --git a/src/tools/RMSD.h b/src/tools/RMSD.h index b83524fc7b..17ad516955 100644 --- a/src/tools/RMSD.h +++ b/src/tools/RMSD.h @@ -61,8 +61,7 @@ val=rmsd.calculate(getPositions(),derivs,true); **/ -class RMSD -{ +class RMSD { enum AlignmentMethod {SIMPLE, OPTIMAL, OPTIMAL_FAST}; AlignmentMethod alignmentMethod; // Reference coordinates @@ -82,18 +81,28 @@ class RMSD // calculates the center from the position provided Vector calculateCenter(const std::vector &p,const std::vector &w) { plumed_massert(p.size()==w.size(),"mismatch in dimension of position/align arrays while calculating the center"); - unsigned n; n=p.size(); - Vector c; c.zero(); - for(unsigned i=0; i &p, const Vector &c) { - unsigned n; n=p.size(); - for(unsigned i=0; i &p, const Vector &c) {Vector cc=c*-1.; removeCenter(p,cc);}; + void addCenter(std::vector &p, const Vector &c) { + Vector cc=c*-1.; + removeCenter(p,cc); + }; public: /// Constructor @@ -250,17 +259,22 @@ class RMSD /// static convenience method to get the matrix i,a from drotdpos (which is a bit tricky) static Tensor getMatrixFromDRot(const Matrix< std::vector > &drotdpos, const unsigned &i, const unsigned &a) { Tensor t; - t[0][0]=drotdpos(0,0)[i][a]; t[0][1]=drotdpos(0,1)[i][a]; t[0][2]=drotdpos(0,2)[i][a]; - t[1][0]=drotdpos(1,0)[i][a]; t[1][1]=drotdpos(1,1)[i][a]; t[1][2]=drotdpos(1,2)[i][a]; - t[2][0]=drotdpos(2,0)[i][a]; t[2][1]=drotdpos(2,1)[i][a]; t[2][2]=drotdpos(2,2)[i][a]; + t[0][0]=drotdpos(0,0)[i][a]; + t[0][1]=drotdpos(0,1)[i][a]; + t[0][2]=drotdpos(0,2)[i][a]; + t[1][0]=drotdpos(1,0)[i][a]; + t[1][1]=drotdpos(1,1)[i][a]; + t[1][2]=drotdpos(1,2)[i][a]; + t[2][0]=drotdpos(2,0)[i][a]; + t[2][1]=drotdpos(2,1)[i][a]; + t[2][2]=drotdpos(2,2)[i][a]; return t; }; }; /// this is a class which is needed to share information across the various non-threadsafe routines /// so that the public function of rmsd are threadsafe while the inner core can safely share information -class RMSDCoreData -{ +class RMSDCoreData { private: bool alEqDis; bool distanceIsMSD; // default is RMSD but can deliver the MSD @@ -308,28 +322,54 @@ class RMSDCoreData RMSDCoreData(const std::vector &a,const std::vector &d,const std::vector &p, const std::vector &r): alEqDis(false),distanceIsMSD(false),hasDistance(false),isInitialized(false),safe(false), creference_is_calculated(false),creference_is_removed(false), - cpositions_is_calculated(false),cpositions_is_removed(false),retrieve_only_rotation(false),positions(p),reference(r),align(a),displace(d),dist(0.0),rr00(0.0),rr11(0.0) - {cpositions.zero(); creference.zero();}; + cpositions_is_calculated(false),cpositions_is_removed(false),retrieve_only_rotation(false),positions(p),reference(r),align(a),displace(d),dist(0.0),rr00(0.0),rr11(0.0) { + cpositions.zero(); + creference.zero(); + }; // set the center on the fly without subtracting void calcPositionsCenter() { plumed_massert(!cpositions_is_calculated,"the center was already calculated"); - cpositions.zero(); for(unsigned i=0; i0) idum_=-idum_; + if(idum_>0) { + idum_=-idum_; + } idum=idum_; incPrec=false; } -double Random::RandU01 () -{ - if (incPrec) +double Random::RandU01 () { + if (incPrec) { return U01d(); - else + } else { return U01(); + } } -double Random::U01d () -{ +double Random::U01d () { double u; u = U01(); u += U01() * fact; @@ -77,24 +79,36 @@ double Random::U01() { int j,k; double temp; if (idum <= 0 || !iy) { - if (-idum < 1) idum=1; - else idum = -idum; + if (-idum < 1) { + idum=1; + } else { + idum = -idum; + } for (j=NTAB+7; j>=0; j--) { k=idum/IQ; idum=IA*(idum-k*IQ)-IR*k; - if (idum < 0) idum += IM; - if (j < NTAB) iv[j] = idum; + if (idum < 0) { + idum += IM; + } + if (j < NTAB) { + iv[j] = idum; + } } iy=iv[0]; } k=idum/IQ; idum=IA*(idum-k*IQ)-IR*k; - if (idum < 0) idum += IM; + if (idum < 0) { + idum += IM; + } j=iy/NDIV; iy=iv[j]; iv[j] = idum; - if ((temp=AM*iy) > RNMX) return RNMX; - else return temp; + if ((temp=AM*iy) > RNMX) { + return RNMX; + } else { + return temp; + } } void Random::WriteStateFull(std::ostream & out)const { @@ -111,7 +125,9 @@ void Random::WriteStateFull(std::ostream & out)const { void Random::ReadStateFull (std::istream & in) { getline(in,name); in>>idum>>iy; - for (int i = 0; i < NTAB; i++) in>>iv[i]; + for (int i = 0; i < NTAB; i++) { + in>>iv[i]; + } in>>switchGaussian; in>>saveGaussian; } @@ -127,10 +143,15 @@ void Random::toString(std::string & str)const { void Random::fromString(const std::string & str) { std::string s=str; - for(unsigned i=0; i>idum>>iy; - for (int i = 0; i < NTAB; i++) istr>>iv[i]; + for (int i = 0; i < NTAB; i++) { + istr>>iv[i]; + } } // This allows to have the same stream of random numbers @@ -149,7 +170,9 @@ double Random::Gaussian() { v1=2.0*RandU01()-1.0; v2=2.0*RandU01()-1.0; rsq=v1*v1+v2*v2; - if(rsq<1.0 && rsq>0.0) break; + if(rsq<1.0 && rsq>0.0) { + break; + } } double fac=std::sqrt(-2.*std::log(rsq)/rsq); saveGaussian=v1*fac; diff --git a/src/tools/Random.h b/src/tools/Random.h index 279a8a7c3d..573e575539 100644 --- a/src/tools/Random.h +++ b/src/tools/Random.h @@ -57,13 +57,17 @@ class Random { void fromString(const std::string & str); void toString(std::string & str)const; friend std::ostream & operator<<(std::ostream & out,const Random & rng) { - rng.WriteStateFull(out); return out; + rng.WriteStateFull(out); + return out; } friend std::istream & operator>>(std::istream & in,Random & rng) { - rng.ReadStateFull(in); return in; + rng.ReadStateFull(in); + return in; } double Gaussian(); - void IncreasedPrecis(bool i) {incPrec=i;} + void IncreasedPrecis(bool i) { + incPrec=i; + } }; } diff --git a/src/tools/RootFindingBase.h b/src/tools/RootFindingBase.h index 7a097f9bfb..750b05210e 100644 --- a/src/tools/RootFindingBase.h +++ b/src/tools/RootFindingBase.h @@ -54,7 +54,9 @@ void RootFindingBase::doSearch( const std::vector& dir, std::vec double ax=0.0, xx=1.0; bb.bracket( ax, xx, &F1dim::getEng ); double xmin=bb.search( &F1dim::getEng ); - for(unsigned i=0; i diff --git a/src/tools/Stopwatch.cpp b/src/tools/Stopwatch.cpp index 84d6fa25bc..22f791ae71 100644 --- a/src/tools/Stopwatch.cpp +++ b/src/tools/Stopwatch.cpp @@ -42,7 +42,9 @@ Stopwatch::~Stopwatch() { // this is necessary e.g. to make sure the main watch present in PlumedMain // is stopped correctly. for(auto & w : watches) { - if(w.second.state==Watch::State::paused) w.second.start().stop(); + if(w.second.state==Watch::State::paused) { + w.second.start().stop(); + } } *mylog << *this; } @@ -52,11 +54,15 @@ std::ostream& Stopwatch::log(std::ostream&os)const { const std::size_t bufferlen=1000; char buffer[bufferlen]; buffer[0]=0; - for(unsigned i=0; i<40; i++) os<<" "; + for(unsigned i=0; i<40; i++) { + os<<" "; + } os<<" Cycles Total Average Minimum Maximum\n"; std::vector names; - for(const auto & it : watches) names.emplace_back(it.first); + for(const auto & it : watches) { + names.emplace_back(it.first); + } std::sort(names.begin(),names.end()); const double frac=1.0/1000000000.0; @@ -64,7 +70,9 @@ std::ostream& Stopwatch::log(std::ostream&os)const { for(const auto & name : names) { const Watch&t(watches.find(name)->second); os<start(); } inline Stopwatch::Handler::~Handler() { if(watch) { - if(stop) watch->stop(); - else watch->pause(); + if(stop) { + watch->stop(); + } else { + watch->pause(); + } } } @@ -359,8 +361,7 @@ long long int Stopwatch::getTotal(const std::string_view&name) { inline Stopwatch::Handler::Handler(Handler && handler) noexcept : watch(handler.watch), - stop(handler.stop) -{ + stop(handler.stop) { handler.watch=nullptr; } @@ -369,8 +370,11 @@ Stopwatch::Handler & Stopwatch::Handler::operator=(Handler && handler) noexcept if(this!=&handler) { if(watch) { try { - if(stop) watch->stop(); - else watch->pause(); + if(stop) { + watch->stop(); + } else { + watch->pause(); + } } catch(...) { // this is to avoid problems with cppcheck, given than this method is declared as // noexcept and stop and pause might throw in case of an internal bug @@ -398,8 +402,12 @@ Stopwatch::Watch & Stopwatch::Watch::stop() { state=State::stopped; cycles++; total+=lap; - if(lap>max)max=lap; - if(min>lap || cycles==1)min=lap; + if(lap>max) { + max=lap; + } + if(min>lap || cycles==1) { + min=lap; + } lastLap=lap; lap=0; return *this; @@ -415,7 +423,9 @@ Stopwatch::Watch & Stopwatch::Watch::pause() { running--; // notice: with exception safety the following might be converted to a plain error. // I leave it like this for now: - if(running!=0) return *this; + if(running!=0) { + return *this; + } auto t=std::chrono::duration_cast(std::chrono::high_resolution_clock::now()-lastStart); lap+=t.count(); return *this; @@ -444,8 +454,7 @@ long long int Stopwatch::Watch::getTotal() noexcept { inline Stopwatch::Stopwatch(Stopwatch&& other) noexcept: mylog(other.mylog), - watches(std::move(other.watches)) -{ + watches(std::move(other.watches)) { other.mylog=nullptr; } diff --git a/src/tools/Subprocess.cpp b/src/tools/Subprocess.cpp index f156b830af..280c32e1d9 100644 --- a/src/tools/Subprocess.cpp +++ b/src/tools/Subprocess.cpp @@ -44,19 +44,22 @@ class SubprocessPid { public: const pid_t pid; explicit SubprocessPid(pid_t pid): - pid(pid) - { + pid(pid) { plumed_assert(pid!=0 && pid!=-1); } void stop() noexcept { // Signals give problems with MPI on Travis. // I disable them for now. - if(SubprocessPidGetenvSignals()) kill(pid,SIGSTOP); + if(SubprocessPidGetenvSignals()) { + kill(pid,SIGSTOP); + } } void cont() noexcept { // Signals give problems with MPI on Travis. // I disable them for now. - if(SubprocessPidGetenvSignals()) kill(pid,SIGCONT); + if(SubprocessPidGetenvSignals()) { + kill(pid,SIGCONT); + } } ~SubprocessPid() { // the destructor implies we do not need the subprocess anymore, so SIGKILL @@ -83,30 +86,49 @@ Subprocess::Subprocess(const std::string & cmd) { }; int cp[2]; int pc[2]; - if(pipe(pc)<0) plumed_error()<<"error creating parent to child pipe"; - if(pipe(cp)<0) plumed_error()<<"error creating child to parent pipe"; + if(pipe(pc)<0) { + plumed_error()<<"error creating parent to child pipe"; + } + if(pipe(cp)<0) { + plumed_error()<<"error creating child to parent pipe"; + } pid_t pid=fork(); switch(pid) { case -1: plumed_error()<<"error forking"; break; // CHILD: - case 0: - { - if(close(1)<0) plumed_error()<<"error closing file"; - if(dup(cp[1])<0) plumed_error()<<"error duplicating file"; - if(close(0)<0) plumed_error()<<"error closing file"; - if(dup(pc[0])<0) plumed_error()<<"error duplicating file"; - if(close(pc[1])<0) plumed_error()<<"error closing file"; - if(close(cp[0])<0) plumed_error()<<"error closing file"; + case 0: { + if(close(1)<0) { + plumed_error()<<"error closing file"; + } + if(dup(cp[1])<0) { + plumed_error()<<"error duplicating file"; + } + if(close(0)<0) { + plumed_error()<<"error closing file"; + } + if(dup(pc[0])<0) { + plumed_error()<<"error duplicating file"; + } + if(close(pc[1])<0) { + plumed_error()<<"error closing file"; + } + if(close(cp[0])<0) { + plumed_error()<<"error closing file"; + } auto err=execv(arr[0],arr); plumed_error()<<"error in script file " << cmd << ", execv returned "<pid=Tools::make_unique(pid); - if(close(pc[0])<0) plumed_error()<<"error closing file"; - if(close(cp[1])<0) plumed_error()<<"error closing file"; + if(close(pc[0])<0) { + plumed_error()<<"error closing file"; + } + if(close(cp[1])<0) { + plumed_error()<<"error closing file"; + } fpc=pc[1]; fcp=cp[0]; fppc=fdopen(fpc,"w"); @@ -159,29 +181,33 @@ void Subprocess::flush() { Subprocess & Subprocess::getline(std::string & line) { child_to_parent.getline(line); - if(!child_to_parent) plumed_error() <<"error reading subprocess"; + if(!child_to_parent) { + plumed_error() <<"error reading subprocess"; + } return (*this); } Subprocess::Handler::Handler(Subprocess *sp) noexcept: - sp(sp) -{ + sp(sp) { sp->cont(); } Subprocess::Handler::~Handler() { - if(sp) sp->stop(); + if(sp) { + sp->stop(); + } } Subprocess::Handler::Handler(Handler && handler) noexcept : - sp(handler.sp) -{ + sp(handler.sp) { handler.sp=nullptr; } Subprocess::Handler & Subprocess::Handler::operator=(Handler && handler) noexcept { if(this!=&handler) { - if(sp) sp->stop(); + if(sp) { + sp->stop(); + } sp=handler.sp; handler.sp=nullptr; } diff --git a/src/tools/SwitchingFunction.cpp b/src/tools/SwitchingFunction.cpp index 99cf034a1f..a3f96b6bc0 100644 --- a/src/tools/SwitchingFunction.cpp +++ b/src/tools/SwitchingFunction.cpp @@ -221,10 +221,18 @@ double baseSwitch::calculateSqr(double distance2,double&dfunc) const { double res= calculate(std::sqrt(distance2),dfunc);//RVO! return res; } -double baseSwitch::get_d0() const {return d0;} -double baseSwitch::get_r0() const {return 1.0/invr0;} -double baseSwitch::get_dmax() const {return dmax;} -double baseSwitch::get_dmax2() const {return dmax_2;} +double baseSwitch::get_d0() const { + return d0; +} +double baseSwitch::get_r0() const { + return 1.0/invr0; +} +double baseSwitch::get_dmax() const { + return dmax; +} +double baseSwitch::get_dmax2() const { + return dmax_2; +} std::string baseSwitch::description() const { std::ostringstream ostr; ostr<::max()) { stretch=1.0; @@ -322,7 +332,13 @@ class rational : public baseSwitch { rational(double D0,double DMAX, double R0, int N, int M) :baseSwitch(D0,DMAX,R0,"rational"), nn(N), - mm([](int m,int n) {if (m==0) {return n*2;} else {return m;}}(M,N)), + mm([](int m,int n) { + if (m==0) { + return n*2; + } else { + return m; + } + }(M,N)), preRes(static_cast(nn)/mm), preDfunc(0.5*nn*(nn-mm)/static_cast(mm)), //wolfram <3:lim_(x->1) d^2/(dx^2) (1 - x^N)/(1 - x^M) = (N (M^2 - 3 M (-1 + N) + N (-3 + 2 N)))/(6 M) @@ -581,7 +597,9 @@ class nativeqSwitch: public baseSwitch { ostr<<" beta="<(d0,dmax); @@ -910,7 +931,9 @@ void SwitchingFunction::set(const std::string & definition,std::string& errormsg if( !data.empty() ) { errormsg="found the following rogue keywords in switching function input : "; - for(unsigned i=0; i::max()) { diff --git a/src/tools/Tensor.h b/src/tools/Tensor.h index a4f53c8a9b..4ed456b3d7 100644 --- a/src/tools/Tensor.h +++ b/src/tools/Tensor.h @@ -85,8 +85,7 @@ int main(){ */ template class TensorGeneric: - public MatrixSquareBracketsAccess,double> -{ + public MatrixSquareBracketsAccess,double> { std::array d; /// Auxiliary private function for constructor void auxiliaryConstructor(); @@ -212,16 +211,14 @@ void TensorGeneric::auxiliaryConstructor() template template -void TensorGeneric::auxiliaryConstructor(double first,Args... arg) -{ +void TensorGeneric::auxiliaryConstructor(double first,Args... arg) { d[n*m-(sizeof...(Args))-1]=first; auxiliaryConstructor(arg...); } template template -TensorGeneric::TensorGeneric(double first,Args... arg) -{ +TensorGeneric::TensorGeneric(double first,Args... arg) { static_assert((sizeof...(Args))+1==n*m,"you are trying to initialize a Tensor with the wrong number of arguments"); auxiliaryConstructor(first,arg...); } @@ -233,7 +230,10 @@ TensorGeneric::TensorGeneric() { template TensorGeneric::TensorGeneric(const VectorGeneric&v1,const VectorGeneric&v2) { - for(unsigned i=0; i @@ -297,27 +297,35 @@ TensorGeneric TensorGeneric::operator-()const { template TensorGeneric& TensorGeneric::setCol(unsigned j,const VectorGeneric & c) { - for(unsigned i=0; i TensorGeneric& TensorGeneric::setRow(unsigned i,const VectorGeneric & r) { - for(unsigned j=0; j VectorGeneric TensorGeneric::getCol(unsigned j)const { VectorGeneric v; - for(unsigned i=0; i VectorGeneric TensorGeneric::getRow(unsigned i)const { VectorGeneric v; - for(unsigned j=0; j inline TensorGeneric TensorGeneric::identity() { TensorGeneric t; - for(unsigned i=0; i TensorGeneric TensorGeneric::transpose()const { TensorGeneric t; - for(unsigned i=0; i TensorGeneric<3,3>::inverse()const { TensorGeneric t; double invdet=1.0/determinant(); - for(unsigned i=0; i<3; i++) for(unsigned j=0; j<3; j++) + for(unsigned i=0; i<3; i++) + for(unsigned j=0; j<3; j++) t(j,i)=invdet*( (*this)((i+1)%3,(j+1)%3)*(*this)((i+2)%3,(j+2)%3) -(*this)((i+1)%3,(j+2)%3)*(*this)((i+2)%3,(j+1)%3)); return t; @@ -393,7 +407,9 @@ TensorGeneric<3,3> TensorGeneric<3,3>::inverse()const { template TensorGeneric matmul(const TensorGeneric&a,const TensorGeneric&b) { TensorGeneric t; - for(unsigned i=0; i matmul(const TensorGeneric&a,const TensorGeneric&b) template VectorGeneric matmul(const TensorGeneric&a,const VectorGeneric&b) { VectorGeneric t; - for(unsigned i=0; i VectorGeneric matmul(const VectorGeneric&a,const TensorGeneric&b) { VectorGeneric t; - for(unsigned i=0; i dcrossDv2(const VectorGeneric<3>&v1,const VectorGeneric<3>&v2 template std::ostream & operator<<(std::ostream &os, const TensorGeneric& t) { - for(unsigned i=0; i&mat,VectorGeneric&evals,TensorGeneri TensorGenericAux::local_dsyevr("V", (n==m?"A":"I"), "U", &nn, const_cast(&mat_copy[0][0]), &nn, &vl, &vu, &one, &mm, &abstol, &mout, &evals_tmp[0], &evec[0][0], &nn, isup.data(), work.data(), &lwork, iwork.data(), &liwork, &info); - if(info!=0) plumed_error()<<"Error diagonalizing matrix\n" - <<"Matrix:\n"<1e-14) break; - if(j1e-14) { + break; + } + if(j bool Tools::convertToAny(const std::string & str,T & t) { std::istringstream istr(str.c_str()); bool ok=static_cast(istr>>t); - if(!ok) return false; + if(!ok) { + return false; + } std::string remaining; istr>>remaining; return remaining.length()==0; @@ -71,14 +73,18 @@ bool Tools::convertNoexcept(const std::string & str,AtomNumber &a) { // avoid using lepton conversions. unsigned i; bool r=convertToAny(str,i); - if(r) a.setSerial(i); + if(r) { + a.setSerial(i); + } return r; } template bool Tools::convertToInt(const std::string & str,T & t) { // First try standard conversion - if(convertToAny(str,t)) return true; + if(convertToAny(str,t)) { + return true; + } // Then use lepton try { double r=lepton::Parser::parse(str).evaluate(lepton::Constants()); @@ -87,20 +93,30 @@ bool Tools::convertToInt(const std::string & str,T & t) { // it should not overflow the requested int type: // (see https://stackoverflow.com/a/526092) - if(r>std::nextafter(std::numeric_limits::max(), 0)) return false; - if(r::min(), 0)) return false; + if(r>std::nextafter(std::numeric_limits::max(), 0)) { + return false; + } + if(r::min(), 0)) { + return false; + } // do the actual conversion auto tmp=static_cast(std::round(r)); // it should be *very close* to itself if converted back to double double diff= r-static_cast(tmp); - if(diff*diff > 1e-20) return false; + if(diff*diff > 1e-20) { + return false; + } // this is to accomodate small numerical errors and allow e.g. exp(log(7)) to be integer // it should be change if incremented or decremented by one (see https://stackoverflow.com/a/43656140) - if(r == static_cast(tmp-1)) return false; - if(r == static_cast(tmp+1)) return false; + if(r == static_cast(tmp-1)) { + return false; + } + if(r == static_cast(tmp+1)) { + return false; + } // everything is fine, then store in t t=tmp; @@ -113,11 +129,15 @@ bool Tools::convertToInt(const std::string & str,T & t) { template bool Tools::convertToReal(const std::string & str,T & t) { - if(convertToAny(str,t)) return true; + if(convertToAny(str,t)) { + return true; + } if(str=="PI" || str=="+PI" || str=="+pi" || str=="pi") { - t=pi; return true; + t=pi; + return true; } else if(str=="-PI" || str=="-pi") { - t=-pi; return true; + t=-pi; + return true; } try { t=lepton::Parser::parse(str).evaluate(lepton::Constants()); @@ -126,21 +146,33 @@ bool Tools::convertToReal(const std::string & str,T & t) { } if( str.find("PI")!=std::string::npos ) { std::size_t pi_start=str.find_first_of("PI"); - if(str.substr(pi_start)!="PI") return false; + if(str.substr(pi_start)!="PI") { + return false; + } std::istringstream nstr(str.substr(0,pi_start)); - T ff=0.0; bool ok=static_cast(nstr>>ff); - if(!ok) return false; + T ff=0.0; + bool ok=static_cast(nstr>>ff); + if(!ok) { + return false; + } t=ff*pi; - std::string remains; nstr>>remains; + std::string remains; + nstr>>remains; return remains.length()==0; } else if( str.find("pi")!=std::string::npos ) { std::size_t pi_start=str.find_first_of("pi"); - if(str.substr(pi_start)!="pi") return false; + if(str.substr(pi_start)!="pi") { + return false; + } std::istringstream nstr(str.substr(0,pi_start)); - T ff=0.0; bool ok=static_cast(nstr>>ff); - if(!ok) return false; + T ff=0.0; + bool ok=static_cast(nstr>>ff); + if(!ok) { + return false; + } t=ff*pi; - std::string remains; nstr>>remains; + std::string remains; + nstr>>remains; return remains.length()==0; } else if(str=="NAN") { t=std::numeric_limits::quiet_NaN(); @@ -170,41 +202,67 @@ std::vector Tools::getWords(std::string_view line,const char* separ plumed_massert(std::strlen(parenthesis)==1,"multiple parenthesis type not available"); plumed_massert(parenthesis[0]=='(' || parenthesis[0]=='[' || parenthesis[0]=='{', "only ( [ { allowed as parenthesis"); - if(!separators) separators=" \t\n"; + if(!separators) { + separators=" \t\n"; + } const std::string sep(separators); char openpar=parenthesis[0]; char closepar; - if(openpar=='(') closepar=')'; - if(openpar=='[') closepar=']'; - if(openpar=='{') closepar='}'; + if(openpar=='(') { + closepar=')'; + } + if(openpar=='[') { + closepar=']'; + } + if(openpar=='{') { + closepar='}'; + } std::vector words; std::string word; int parenthesisLevel=0; - if(parlevel) parenthesisLevel=*parlevel; + if(parlevel) { + parenthesisLevel=*parlevel; + } for(unsigned i=0; i=0) << "Extra closed parenthesis in '" << line << "'"; } - if(parenthesisLevel==0) for(unsigned j=0; j0) { - if(!parlevel) plumed_assert(parenthesisLevel==0) << "Unmatching parenthesis in '" << line << "'"; + if(!parlevel) { + plumed_assert(parenthesisLevel==0) << "Unmatching parenthesis in '" << line << "'"; + } words.push_back(word); word.clear(); } } if(word.length()>0) { - if(!parlevel) plumed_assert(parenthesisLevel==0) << "Unmatching parenthesis in '" << line << "'"; + if(!parlevel) { + plumed_assert(parenthesisLevel==0) << "Unmatching parenthesis in '" << line << "'"; + } words.push_back(word); } - if(parlevel) *parlevel=parenthesisLevel; + if(parlevel) { + *parlevel=parenthesisLevel; + } return words; } @@ -237,16 +295,25 @@ bool Tools::getParsedLine(IFile& ifile,std::vector & words, bool tr int parlevel=0; bool mergenext=false; while((stat=ifile.getline(line))) { - if(trimcomments) trimComments(line); + if(trimcomments) { + trimComments(line); + } trim(line); - if(line.length()==0) continue; + if(line.length()==0) { + continue; + } std::vector w=getWords(line,NULL,&parlevel,"{",trimcomments); if(!w.empty()) { if(inside && *(w.begin())=="...") { inside=false; - if(w.size()==2) plumed_massert(w[1]==words[0],"second word in terminating \"...\" "+w[1]+" line, if present, should be equal to first word of directive: "+words[0]); + if(w.size()==2) { + plumed_massert(w[1]==words[0],"second word in terminating \"...\" "+w[1]+" line, if present, should be equal to first word of directive: "+words[0]); + } plumed_massert(w.size()<=2,"terminating \"...\" lines cannot consist of more than two words"); - w.clear(); if(!trimcomments) words.push_back("..."); + w.clear(); + if(!trimcomments) { + words.push_back("..."); + } } else if(*(w.end()-1)=="...") { inside=true; w.erase(w.end()-1); @@ -256,15 +323,24 @@ bool Tools::getParsedLine(IFile& ifile,std::vector & words, bool tr words[words.size()-1]+=" "+w[0]; i0=1; } - for(unsigned i=i0; i0); - if(!inside)break; - if(!trimcomments && parlevel==0) words.push_back("@newline"); - else if(!trimcomments) words[words.size()-1] += " @newline"; + if(!inside) { + break; + } + if(!trimcomments && parlevel==0) { + words.push_back("@newline"); + } else if(!trimcomments) { + words[words.size()-1] += " @newline"; + } } plumed_massert(parlevel==0,"non matching parenthesis"); - if(words.size()>0) return true; + if(words.size()>0) { + return true; + } return stat; } @@ -274,20 +350,33 @@ bool Tools::getline(FILE* fp,std::string & line) { const int bufferlength=1024; char buffer[bufferlength]; bool ret; - for(int i=0; i0) if(buffer[ss-1]=='\n') break; + if(ss>0) + if(buffer[ss-1]=='\n') { + break; + } }; - if(line.length()>0) if(*(line.end()-1)=='\n') line.erase(line.end()-1); - if(line.length()>0) if(*(line.end()-1)=='\r') line.erase(line.end()-1); + if(line.length()>0) + if(*(line.end()-1)=='\n') { + line.erase(line.end()-1); + } + if(line.length()>0) + if(*(line.end()-1)=='\r') { + line.erase(line.end()-1); + } return ret; } void Tools::trim(std::string & s) { auto n=s.find_last_not_of(" \t"); - if(n!=std::string::npos) s.resize(n+1); + if(n!=std::string::npos) { + s.resize(n+1); + } } void Tools::ltrim(std::string & s) { @@ -300,11 +389,12 @@ void Tools::ltrim(std::string & s) { void Tools::trimComments(std::string & s) { auto n=s.find_first_of("#"); - if(n!=std::string::npos) s.resize(n); + if(n!=std::string::npos) { + s.resize(n); + } } -bool Tools::caseInSensStringCompare(const std::string & str1, const std::string &str2) -{ +bool Tools::caseInSensStringCompare(const std::string & str1, const std::string &str2) { return ((str1.size() == str2.size()) && std::equal(str1.begin(), str1.end(), str2.begin(), [](char c1, char c2) { return (c1 == c2 || std::toupper(c1) == std::toupper(c2)); })); @@ -313,10 +403,14 @@ bool Tools::caseInSensStringCompare(const std::string & str1, const std::string bool Tools::getKey(std::vector& line,const std::string & key,std::string & s,int rep) { s.clear(); for(auto p=line.begin(); p!=line.end(); ++p) { - if((*p).length()==0) continue; + if((*p).length()==0) { + continue; + } std::string x=(*p).substr(0,key.length()); if(caseInSensStringCompare(x,key)) { - if((*p).length()==key.length())return false; + if((*p).length()==key.length()) { + return false; + } std::string tmp=(*p).substr(key.length(),(*p).length()); line.erase(p); s=tmp; @@ -338,17 +432,25 @@ void Tools::interpretRanges(std::vector&s) { for(const auto & p :s) { news.push_back(p); size_t dash=p.find("-"); - if(dash==std::string::npos) continue; + if(dash==std::string::npos) { + continue; + } int first; - if(!Tools::convertToAny(p.substr(0,dash),first)) continue; + if(!Tools::convertToAny(p.substr(0,dash),first)) { + continue; + } int stride=1; int second; size_t colon=p.substr(dash+1).find(":"); if(colon!=std::string::npos) { if(!Tools::convertToAny(p.substr(dash+1).substr(0,colon),second) || - !Tools::convertToAny(p.substr(dash+1).substr(colon+1),stride)) continue; + !Tools::convertToAny(p.substr(dash+1).substr(colon+1),stride)) { + continue; + } } else { - if(!Tools::convertToAny(p.substr(dash+1),second)) continue; + if(!Tools::convertToAny(p.substr(dash+1),second)) { + continue; + } } news.resize(news.size()-1); if(first<=second) { @@ -371,10 +473,14 @@ void Tools::interpretRanges(std::vector&s) { } void Tools::interpretLabel(std::vector&s) { - if(s.size()<2)return; + if(s.size()<2) { + return; + } std::string s0=s[0]; unsigned l=s0.length(); - if(l<1) return; + if(l<1) { + return; + } if(s0[l-1]==':') { s[0]=s[1]; s[1]="LABEL="+s0.substr(0,l-1); @@ -393,7 +499,9 @@ std::vector Tools::ls(const std::string&d) { void Tools::stripLeadingAndTrailingBlanks( std::string& str ) { std::size_t first=str.find_first_not_of(' '); std::size_t last=str.find_last_not_of(' '); - if( first<=last && first!=std::string::npos) str=str.substr(first,last+1); + if( first<=last && first!=std::string::npos) { + str=str.substr(first,last+1); + } } std::string Tools::extension(const std::string&s) { @@ -401,10 +509,16 @@ std::string Tools::extension(const std::string&s) { std::string ext; if(n!=std::string::npos && n+1=s.length()) { ext=s.substr(n+1); - if(ext.find("/")!=std::string::npos) ext=""; + if(ext.find("/")!=std::string::npos) { + ext=""; + } std::string base=s.substr(0,n); - if(base.length()==0) ext=""; - if(base.length()>0 && base[base.length()-1]=='/') ext=""; + if(base.length()==0) { + ext=""; + } + if(base.length()>0 && base[base.length()-1]=='/') { + ext=""; + } } return ext; } @@ -426,16 +540,21 @@ bool Tools::startWith(const std::string & full,const std::string &start) { bool Tools::findKeyword(const std::vector&line,const std::string&key) { const std::string search(key+"="); for(const auto & p : line) { - if(startWith(p,search)) return true; + if(startWith(p,search)) { + return true; + } } return false; } Tools::DirectoryChanger::DirectoryChanger(const char*path): - path(std::filesystem::current_path()) -{ - if(!path) return; - if(std::strlen(path)==0) return; + path(std::filesystem::current_path()) { + if(!path) { + return; + } + if(std::strlen(path)==0) { + return; + } std::filesystem::current_path(path); } @@ -459,7 +578,9 @@ class process_one_exception { std::string & msg; bool first=true; void update() { - if(!first) msg+="\n\nThe above exception was the direct cause of the following exception:\n"; + if(!first) { + msg+="\n\nThe above exception was the direct cause of the following exception:\n"; + } first=false; } public: @@ -494,7 +615,9 @@ static void process_all_exceptions(T&& f) { process_all_exceptions(f); } auto d=dynamic_cast(&e); - if(d) f(*d); + if(d) { + f(*d); + } } catch(const std::exception &e) { // If not nested, we end recursion f(e); diff --git a/src/tools/Tools.h b/src/tools/Tools.h index 26e9d9eae9..84fd4d1482 100644 --- a/src/tools/Tools.h +++ b/src/tools/Tools.h @@ -237,20 +237,26 @@ class Tools { } static void set_to_zero(double*ptr,unsigned n) { - for(unsigned i=0; i static void set_to_zero(std::vector> & vec) { unsigned s=vec.size(); - if(s==0) return; + if(s==0) { + return; + } set_to_zero(&vec[0][0],s*n); } template static void set_to_zero(std::vector> & vec) { unsigned s=vec.size(); - if(s==0) return; + if(s==0) { + return; + } set_to_zero(&vec[0](0,0),s*n*m); } @@ -288,7 +294,9 @@ class Tools { T& operator[]( const std::string_view & key ) { auto f=map.find(key); - if(f!=map.end()) return f->second; + if(f!=map.end()) { + return f->second; + } keys.push_back(conv(key)); return map[keys.back().get()]; } @@ -342,8 +350,7 @@ class Tools { Key key; Handler(CriticalSectionWithKey* section,const Key& key): section(section), - key(key) - { + key(key) { section->start(key); } friend class CriticalSectionWithKey; @@ -357,14 +364,15 @@ class Tools { /// Move constructor. Handler(Handler && handler) noexcept : section(handler.section), - key(std::move(handler.key)) - { + key(std::move(handler.key)) { handler.section=nullptr; }; /// Move assignment. Handler & operator=(Handler && handler) noexcept { if(this!=&handler) { - if(section) section->stop(key); + if(section) { + section->stop(key); + } section=handler.section; key=std::move(handler.key); } @@ -373,7 +381,9 @@ class Tools { } /// Destructor ~Handler() { - if(section) section->stop(key); + if(section) { + section->stop(key); + } } }; @@ -388,15 +398,21 @@ class Tools { template bool Tools::parse(std::vector&line,const std::string&key,T&val,int rep) { std::string s; - if(!getKey(line,key+"=",s,rep)) return false; - if(s.length()>0 && !convertNoexcept(s,val))return false; + if(!getKey(line,key+"=",s,rep)) { + return false; + } + if(s.length()>0 && !convertNoexcept(s,val)) { + return false; + } return true; } template bool Tools::parseVector(std::vector&line,const std::string&key,std::vector&val,int rep) { std::string s; - if(!getKey(line,key+"=",s,rep)) return false; + if(!getKey(line,key+"=",s,rep)) { + return false; + } val.clear(); std::vector words=getWords(s,"\t\n ,"); for(unsigned i=0; i&line,const std::string&key,std: plumed_assert(rep(words.size())); s=words[rep]; } - if(!convertNoexcept(s,v))return false; + if(!convertNoexcept(s,v)) { + return false; + } val.push_back(v); } return true; } template -void Tools::removeDuplicates(std::vector& vec) -{ +void Tools::removeDuplicates(std::vector& vec) { std::sort(vec.begin(), vec.end()); vec.erase(std::unique(vec.begin(), vec.end()), vec.end()); } @@ -438,18 +455,27 @@ bool Tools::parseFlag(std::vector&line,const std::string&key,bool&v inline double Tools::pbc(double x) { #ifdef __PLUMED_PBC_WHILE - while (x>0.5) x-=1.0; - while (x<-0.5) x+=1.0; + while (x>0.5) { + x-=1.0; + } + while (x<-0.5) { + x+=1.0; + } return x; #else if constexpr (std::numeric_limits::round_style == std::round_toward_zero) { constexpr double offset=100.0; const double y=x+offset; - if(y>=0) return y-int(y+0.5); - else return y-int(y-0.5); + if(y>=0) { + return y-int(y+0.5); + } else { + return y-int(y-0.5); + } } else if constexpr (std::numeric_limits::round_style == std::round_to_nearest) { return x-int(x); - } else return x-floor(x+0.5); + } else { + return x-floor(x+0.5); + } #endif } @@ -462,17 +488,16 @@ bool Tools::convertNoexcept(T i,std::string & str) { } inline -double Tools::fastpow(double base, int exp) -{ +double Tools::fastpow(double base, int exp) { if(exp<0) { exp=-exp; base=1.0/base; } double result = 1.0; - while (exp) - { - if (exp & 1) + while (exp) { + if (exp & 1) { result *= base; + } exp >>= 1; base *= base; } @@ -503,14 +528,18 @@ inline T Tools::fastpow(T const base) { template std::vector Tools::unique2raw(const std::vector> & x) { std::vector v(x.size()); - for(unsigned i=0; i std::vector Tools::unique2raw(const std::vector> & x) { std::vector v(x.size()); - for(unsigned i=0; iisWhole()) plumed_merror("Check that reference structure in PDB file is not broken by pbc and set WHOLE in MOLINFO line"); + if(!moldat_->isWhole()) { + plumed_merror("Check that reference structure in PDB file is not broken by pbc and set WHOLE in MOLINFO line"); + } } -std::vector Tree::getTree(std::vector atoms) -{ +std::vector Tree::getTree(std::vector atoms) { // Implementation inspired from: // https://mayanknatani.wordpress.com/2013/05/31/euclidean-minimummaximum-spanning-tree-emst/ // @@ -58,7 +61,9 @@ std::vector Tree::getTree(std::vector atoms) positions.reserve(atoms.size()); tree.reserve(atoms.size()); root_.reserve(atoms.size()); - if(!moldat_->checkForAtom(atoms[0])) plumed_merror("The first atom in the list should be present in the PDB file"); + if(!moldat_->checkForAtom(atoms[0])) { + plumed_merror("The first atom in the list should be present in the PDB file"); + } // store first atom newatoms.push_back(atoms[0]); positions.push_back(moldat_->getPosition(atoms[0])); @@ -84,8 +89,9 @@ std::vector Tree::getTree(std::vector atoms) for(unsigned i=0; i=0); @@ -96,14 +102,18 @@ std::vector Tree::getTree(std::vector atoms) int iroot = -1; for(unsigned j=0; j0.0) { minroot = dist; iroot = j; } } // add to root vector - if(iroot>=0) root_.push_back(atoms[iroot]); + if(iroot>=0) { + root_.push_back(atoms[iroot]); + } } // now re-add atoms not present in the PDB @@ -116,8 +126,7 @@ std::vector Tree::getTree(std::vector atoms) return tree; } -std::vector Tree::getRoot() const -{ +std::vector Tree::getRoot() const { return root_; } diff --git a/src/tools/Tree.h b/src/tools/Tree.h index c0551e82b1..8338d5d1f1 100644 --- a/src/tools/Tree.h +++ b/src/tools/Tree.h @@ -31,8 +31,7 @@ namespace PLMD { /// \ingroup TOOLBOX -class Tree -{ +class Tree { private: GenericMolInfo* moldat_; diff --git a/src/tools/TypesafePtr.cpp b/src/tools/TypesafePtr.cpp index f019381ea8..2ec705fcf1 100644 --- a/src/tools/TypesafePtr.cpp +++ b/src/tools/TypesafePtr.cpp @@ -33,9 +33,13 @@ TypesafePtr TypesafePtr::fromSafePtr(void* safe) { TypesafePtr TypesafePtr::copy() const { auto passbyvalue=((flags>>25)&0x7)==1; - if(passbyvalue) throw ExceptionTypeError()<<"PLUMED is trying to copy the pointer of an object passed by value"; + if(passbyvalue) { + throw ExceptionTypeError()<<"PLUMED is trying to copy the pointer of an object passed by value"; + } auto forbidstore=flags&0x10000000; - if(forbidstore) throw ExceptionTypeError()<<"PLUMED is trying to copy the pointer of an object for which this was forbidden"; + if(forbidstore) { + throw ExceptionTypeError()<<"PLUMED is trying to copy the pointer of an object for which this was forbidden"; + } TypesafePtr ret; ret.ptr=ptr; ret.flags=flags; diff --git a/src/tools/TypesafePtr.h b/src/tools/TypesafePtr.h index f1545964fd..6b123da407 100644 --- a/src/tools/TypesafePtr.h +++ b/src/tools/TypesafePtr.h @@ -88,12 +88,16 @@ class TypesafePtr { unsigned i=0; for(i=0; ishape.size(); i++) { this->shape[i]=*shape; - if(*shape==0) break; + if(*shape==0) { + break; + } nelem_*=*shape; shape++; } plumed_assert(ishape.size()); // check that last element is actually zero - if(nelem==0) nelem=nelem_; + if(nelem==0) { + nelem=nelem_; + } plumed_assert(nelem==nelem_) << "Inconsistent shape/nelem"; } } @@ -105,8 +109,7 @@ class TypesafePtr { TypesafePtr(void* ptr, std::size_t nelem, const std::size_t* shape, std::size_t flags): ptr(ptr), nelem(nelem), - flags(flags) - { + flags(flags) { buffer[0]='\0'; init_shape(shape); } @@ -128,8 +131,7 @@ class TypesafePtr { buffer[0]='\0'; } - TypesafePtr(std::nullptr_t) - { + TypesafePtr(std::nullptr_t) { shape[0]=0; buffer[0]='\0'; } @@ -210,8 +212,7 @@ class TypesafePtr { ptr(other.ptr==&other.buffer[0] ? &buffer[0] : other.ptr), nelem(other.nelem), shape(other.shape), - flags(other.flags) - { + flags(other.flags) { other.ptr=nullptr; } @@ -229,12 +230,24 @@ class TypesafePtr { std::string type_str() const { auto type=(flags>>16)&0xff; - if(type==0) return "wildcard"; - if(type==1) return "void"; - if(type==2) return "integral"; - if(type==3) return "integral"; - if(type==4) return "floating point"; - if(type==5) return "FILE"; + if(type==0) { + return "wildcard"; + } + if(type==1) { + return "void"; + } + if(type==2) { + return "integral"; + } + if(type==3) { + return "integral"; + } + if(type==4) { + return "floating point"; + } + if(type==5) { + return "FILE"; + } return "unknown"; } @@ -243,9 +256,13 @@ class TypesafePtr { template T* get_priv(std::size_t nelem, const std::size_t* shape, bool byvalue) const { - if(typesafePtrSkipCheck()) return (T*) ptr; + if(typesafePtrSkipCheck()) { + return (T*) ptr; + } typedef typename std::remove_pointer::type T_noptr; - if(flags==0) return (T*) ptr; // no check + if(flags==0) { + return (T*) ptr; // no check + } auto size=flags&0xffff; auto type=(flags>>16)&0xff; // auto unsi=(flags>>24)&0x1; // ignored @@ -269,7 +286,8 @@ class TypesafePtr { throw ExceptionTypeError() << "This command expects a type with size " << typesafePtrSizeof() << ". Received type has size " << size << " instead"<::value) { - if(cons==1) throw ExceptionTypeError() << "This command expects a pointer-to-pointer. It received a value intead"<::value) { - if(cons!=4) throw ExceptionTypeError() << "This command expects a modifiable pointer-to-pointer (T**)"<::value) { - if(cons!=4 && cons!=5) throw ExceptionTypeError() << "This command expects T*const* pointer, and can only receive T** or T*const* pointers"<shape[i]==0) { throw ExceptionTypeError() << "Incorrect number of axis (requested greater than passed)"<this->shape[i])) { throw ExceptionTypeError() << "This command wants " << shape[i] << " elements on axis " << i <<" of this pointer, but " << this->shape[i] << " have been passed"<0) { nelem=1; for(unsigned i=0; ishape.size(); i++) { - if(shape[i]==0) break; + if(shape[i]==0) { + break; + } nelem*=shape[i]; } } // check number of elements - if(nelem>0 && this->nelem>0) if(!(nelem<=this->nelem)) { + if(nelem>0 && this->nelem>0) + if(!(nelem<=this->nelem)) { throw ExceptionTypeError() << "This command wants to access " << nelem << " from this pointer, but only " << this->nelem << " have been passed"<(0,nullptr,false); if(!typesafePtrSkipCheck() && this->nelem>0 && this->nelem::max()) { std::size_t i=0; - for(; inelem; i++) if(ptr[i]==0) break; - if(i==this->nelem) throw ExceptionTypeError() << "PLUMED is expecting a null terminated string, but no null character was found"; + for(; inelem; i++) + if(ptr[i]==0) { + break; + } + if(i==this->nelem) { + throw ExceptionTypeError() << "PLUMED is expecting a null terminated string, but no null character was found"; + } } return ptr; } diff --git a/src/tools/Units.cpp b/src/tools/Units.cpp index 660071c4b0..b9a9068b16 100644 --- a/src/tools/Units.cpp +++ b/src/tools/Units.cpp @@ -34,8 +34,7 @@ Units::Units(): charge(1.0), chargeString("e"), mass(1.0), - massString("amu") -{ + massString("amu") { } void Units::setEnergy(const std::string &s) { diff --git a/src/tools/Vector.h b/src/tools/Vector.h index cbebc64b21..0f585be328 100644 --- a/src/tools/Vector.h +++ b/src/tools/Vector.h @@ -160,16 +160,14 @@ void VectorGeneric::auxiliaryConstructor() template template -void VectorGeneric::auxiliaryConstructor(double first,Args... arg) -{ +void VectorGeneric::auxiliaryConstructor(double first,Args... arg) { d[n-(sizeof...(Args))-1]=first; auxiliaryConstructor(arg...); } template template -VectorGeneric::VectorGeneric(double first,Args... arg) -{ +VectorGeneric::VectorGeneric(double first,Args... arg) { static_assert((sizeof...(Args))+1==n,"you are trying to initialize a Vector with the wrong number of arguments"); auxiliaryConstructor(first,arg...); } @@ -308,7 +306,9 @@ double modulo(const VectorGeneric&v) { template std::ostream & operator<<(std::ostream &os, const VectorGeneric& v) { - for(unsigned i=0; i= digits_size) { @@ -159,7 +174,9 @@ decode_pure( value += dv; } } - if (have_minus) value = -value; + if (have_minus) { + value = -value; + } *result = value; return 0; } @@ -183,8 +200,7 @@ decode_pure( if (errmsg) throw std::runtime_error(errmsg); */ const char* -hy36encode(unsigned width, int value, char* result) -{ +hy36encode(unsigned width, int value, char* result) { int i = value; if (width == 4U) { if (i >= -999) { @@ -205,8 +221,7 @@ hy36encode(unsigned width, int value, char* result) return 0; } } - } - else if (width == 5U) { + } else if (width == 5U) { if (i >= -9999) { if (i < 100000) { encode_pure(digits_upper(), 10U, 5U, i, result); @@ -225,8 +240,7 @@ hy36encode(unsigned width, int value, char* result) return 0; } } - } - else { + } else { fill_with_stars(width, result); return unsupported_width(); } @@ -257,8 +271,7 @@ hy36encode(unsigned width, int value, char* result) if (errmsg) throw std::runtime_error(errmsg); */ const char* -hy36decode(unsigned width, const char* s, unsigned s_size, int* result) -{ +hy36decode(unsigned width, const char* s, unsigned s_size, int* result) { static const std::vector digits_values_upper_vector([]() { std::vector ret(128U,-1); for(unsigned i=0; i<36U; i++) { @@ -269,7 +282,8 @@ hy36decode(unsigned width, const char* s, unsigned s_size, int* result) ret[di] = i; } return ret; - }()); + } + ()); static const int* digits_values_upper=digits_values_upper_vector.data(); static const std::vector digits_values_lower_vector([]() { std::vector ret(128U,-1); @@ -281,7 +295,8 @@ hy36decode(unsigned width, const char* s, unsigned s_size, int* result) ret[di] = i; } return ret; - }()); + } + ()); static const int* digits_values_lower=digits_values_lower_vector.data(); int di; const char* errmsg; @@ -292,31 +307,35 @@ hy36decode(unsigned width, const char* s, unsigned s_size, int* result) errmsg = decode_pure(digits_values_upper, 36U, s, s_size, result); if (errmsg == 0) { /* result - 10*36**(width-1) + 10**width */ - if (width == 4U) (*result) -= 456560; - else if (width == 5U) (*result) -= 16696160; - else { + if (width == 4U) { + (*result) -= 456560; + } else if (width == 5U) { + (*result) -= 16696160; + } else { *result = 0; return unsupported_width(); } return 0; } - } - else if (digits_values_lower[di] >= 10) { + } else if (digits_values_lower[di] >= 10) { errmsg = decode_pure(digits_values_lower, 36U, s, s_size, result); if (errmsg == 0) { /* result + 16*36**(width-1) + 10**width */ - if (width == 4U) (*result) += 756496; - else if (width == 5U) (*result) += 26973856; - else { + if (width == 4U) { + (*result) += 756496; + } else if (width == 5U) { + (*result) += 26973856; + } else { *result = 0; return unsupported_width(); } return 0; } - } - else { + } else { errmsg = decode_pure(digits_values_upper, 10U, s, s_size, result); - if (errmsg) return errmsg; + if (errmsg) { + return errmsg; + } if (!(width == 4U || width == 5U)) { *result = 0; return unsupported_width(); diff --git a/src/valtools/Concatenate.cpp b/src/valtools/Concatenate.cpp index 8235762fdc..3073c5e0a9 100644 --- a/src/valtools/Concatenate.cpp +++ b/src/valtools/Concatenate.cpp @@ -47,7 +47,9 @@ class Concatenate : /// Constructor explicit Concatenate(const ActionOptions&); /// Get the number of derivatives - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } /// Do the calculation void calculate() override; /// @@ -57,76 +59,146 @@ class Concatenate : PLUMED_REGISTER_ACTION(Concatenate,"CONCATENATE") void Concatenate::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); ActionWithArguments::registerKeywords( keys ); keys.use("ARG"); - keys.add("numbered","MATRIX","specify the matrices that you wish to join together into a single matrix"); keys.reset_style("MATRIX","compulsory"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.use("ARG"); + keys.add("numbered","MATRIX","specify the matrices that you wish to join together into a single matrix"); + keys.reset_style("MATRIX","compulsory"); keys.setValueDescription("the concatenated vector/matrix that was constructed from the input values"); } Concatenate::Concatenate(const ActionOptions& ao): Action(ao), ActionWithValue(ao), - ActionWithArguments(ao) -{ + ActionWithArguments(ao) { if( getNumberOfArguments()>0 ) { - vectors=true; std::vector shape(1); shape[0]=0; + vectors=true; + std::vector shape(1); + shape[0]=0; for(unsigned i=0; igetRank()>1 ) error("cannot concatenate matrix with vectors"); - getPntrToArgument(i)->buildDataStore(); shape[0] += getPntrToArgument(i)->getNumberOfValues(); + if( getPntrToArgument(i)->getRank()>1 ) { + error("cannot concatenate matrix with vectors"); + } + getPntrToArgument(i)->buildDataStore(); + shape[0] += getPntrToArgument(i)->getNumberOfValues(); } log.printf(" creating vector with %d elements \n", shape[0] ); - addValue( shape ); bool period=getPntrToArgument(0)->isPeriodic(); - std::string min, max; if( period ) getPntrToArgument(0)->getDomain( min, max ); + addValue( shape ); + bool period=getPntrToArgument(0)->isPeriodic(); + std::string min, max; + if( period ) { + getPntrToArgument(0)->getDomain( min, max ); + } for(unsigned i=1; iisPeriodic() ) error("periods of input arguments should match"); + if( period!=getPntrToArgument(i)->isPeriodic() ) { + error("periods of input arguments should match"); + } if( period ) { - std::string min0, max0; getPntrToArgument(i)->getDomain( min0, max0 ); - if( min0!=min || max0!=max ) error("domains of input arguments should match"); + std::string min0, max0; + getPntrToArgument(i)->getDomain( min0, max0 ); + if( min0!=min || max0!=max ) { + error("domains of input arguments should match"); + } } } - if( period ) setPeriodic( min, max ); else setNotPeriodic(); + if( period ) { + setPeriodic( min, max ); + } else { + setNotPeriodic(); + } getPntrToComponent(0)->buildDataStore(); - if( getPntrToComponent(0)->getRank()==2 ) getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + if( getPntrToComponent(0)->getRank()==2 ) { + getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + } } else { - unsigned nrows=0, ncols=0; std::vector arglist; vectors=false; + unsigned nrows=0, ncols=0; + std::vector arglist; + vectors=false; for(unsigned i=1;; i++) { - unsigned nt_cols=0; unsigned size_b4 = arglist.size(); + unsigned nt_cols=0; + unsigned size_b4 = arglist.size(); for(unsigned j=1;; j++) { - if( j==10 ) error("cannot combine more than 9 matrices"); - std::vector argn; parseArgumentList("MATRIX", i*10+j, argn); - if( argn.size()==0 ) break; - if( argn.size()>1 ) error("should only be one argument to each matrix keyword"); - if( argn[0]->getRank()!=0 && argn[0]->getRank()!=2 ) error("input arguments for this action should be matrices"); - argn[0]->buildDataStore(); arglist.push_back( argn[0] ); nt_cols++; - if( argn[0]->getRank()==0 ) log.printf(" %d %d component of composed matrix is scalar labelled %s\n", i, j, argn[0]->getName().c_str() ); - else log.printf(" %d %d component of composed matrix is %d by %d matrix labelled %s\n", i, j, argn[0]->getShape()[0], argn[0]->getShape()[1], argn[0]->getName().c_str() ); + if( j==10 ) { + error("cannot combine more than 9 matrices"); + } + std::vector argn; + parseArgumentList("MATRIX", i*10+j, argn); + if( argn.size()==0 ) { + break; + } + if( argn.size()>1 ) { + error("should only be one argument to each matrix keyword"); + } + if( argn[0]->getRank()!=0 && argn[0]->getRank()!=2 ) { + error("input arguments for this action should be matrices"); + } + argn[0]->buildDataStore(); + arglist.push_back( argn[0] ); + nt_cols++; + if( argn[0]->getRank()==0 ) { + log.printf(" %d %d component of composed matrix is scalar labelled %s\n", i, j, argn[0]->getName().c_str() ); + } else { + log.printf(" %d %d component of composed matrix is %d by %d matrix labelled %s\n", i, j, argn[0]->getShape()[0], argn[0]->getShape()[1], argn[0]->getName().c_str() ); + } + } + if( arglist.size()==size_b4 ) { + break; + } + if( i==1 ) { + ncols=nt_cols; + } else if( nt_cols!=ncols ) { + error("should be joining same number of matrices in each row"); } - if( arglist.size()==size_b4 ) break; - if( i==1 ) ncols=nt_cols; - else if( nt_cols!=ncols ) error("should be joining same number of matrices in each row"); nrows++; } - std::vector shape(2); shape[0]=0; unsigned k=0; - row_starts.resize( arglist.size() ); col_starts.resize( arglist.size() ); + std::vector shape(2); + shape[0]=0; + unsigned k=0; + row_starts.resize( arglist.size() ); + col_starts.resize( arglist.size() ); for(unsigned i=0; igetRank()==2 ) nr=arglist[k]->getShape()[0]; + unsigned cstart = 0, nr = 1; + if( arglist[k]->getRank()==2 ) { + nr=arglist[k]->getShape()[0]; + } for(unsigned j=0; jgetRank()==0 ) { - if( nr!=1 ) error("mismatched matrix sizes"); - } else if( nrows>1 && arglist[k]->getShape()[0]!=nr ) error("mismatched matrix sizes"); - row_starts[k] = shape[0]; col_starts[k] = cstart; - if( arglist[k]->getRank()==0 ) cstart += 1; - else cstart += arglist[k]->getShape()[1]; + if( nr!=1 ) { + error("mismatched matrix sizes"); + } + } else if( nrows>1 && arglist[k]->getShape()[0]!=nr ) { + error("mismatched matrix sizes"); + } + row_starts[k] = shape[0]; + col_starts[k] = cstart; + if( arglist[k]->getRank()==0 ) { + cstart += 1; + } else { + cstart += arglist[k]->getShape()[1]; + } k++; } - if( i==0 ) shape[1]=cstart; - else if( cstart!=shape[1] ) error("mismatched matrix sizes"); - if( arglist[k-1]->getRank()==0 ) shape[0] += 1; - else shape[0] += arglist[k-1]->getShape()[0]; + if( i==0 ) { + shape[1]=cstart; + } else if( cstart!=shape[1] ) { + error("mismatched matrix sizes"); + } + if( arglist[k-1]->getRank()==0 ) { + shape[0] += 1; + } else { + shape[0] += arglist[k-1]->getShape()[0]; + } } // Now request the arguments to make sure we store things we need - requestArguments(arglist); addValue( shape ); setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); - if( getPntrToComponent(0)->getRank()==2 ) getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + requestArguments(arglist); + addValue( shape ); + setNotPeriodic(); + getPntrToComponent(0)->buildDataStore(); + if( getPntrToComponent(0)->getRank()==2 ) { + getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + } } } @@ -135,8 +207,12 @@ void Concatenate::calculate() { if( vectors ) { unsigned k=0; for(unsigned i=0; igetNumberOfValues(); - for(unsigned j=0; jset( k, myarg->get(j) ); k++; } + Value* myarg=getPntrToArgument(i); + unsigned nvals=myarg->getNumberOfValues(); + for(unsigned j=0; jset( k, myarg->get(j) ); + k++; + } } } else { // Retrieve the matrix from input @@ -146,13 +222,17 @@ void Concatenate::calculate() { if( argn->getRank()==0 ) { myval->set( ncols*row_starts[k]+col_starts[k], argn->get() ); } else { - std::vector vals; std::vector > pairs; + std::vector vals; + std::vector > pairs; bool symmetric=getPntrToArgument(k)->isSymmetric(); - unsigned nedge=0; getPntrToArgument(k)->retrieveEdgeList( nedge, pairs, vals ); + unsigned nedge=0; + getPntrToArgument(k)->retrieveEdgeList( nedge, pairs, vals ); for(unsigned l=0; lset( ncols*(row_starts[k]+i)+col_starts[k]+j, vals[l] ); - if( symmetric ) myval->set( ncols*(row_starts[k]+j)+col_starts[k]+i, vals[l] ); + if( symmetric ) { + myval->set( ncols*(row_starts[k]+j)+col_starts[k]+i, vals[l] ); + } } } } @@ -160,26 +240,35 @@ void Concatenate::calculate() { } void Concatenate::apply() { - if( doNotCalculateDerivatives() || !getPntrToComponent(0)->forcesWereAdded() ) return; + if( doNotCalculateDerivatives() || !getPntrToComponent(0)->forcesWereAdded() ) { + return; + } Value* val=getPntrToComponent(0); if( vectors ) { unsigned k=0; for(unsigned i=0; igetNumberOfValues(); - for(unsigned j=0; jaddForce( j, val->getForce(k) ); k++; } + Value* myarg=getPntrToArgument(i); + unsigned nvals=myarg->getNumberOfValues(); + for(unsigned j=0; jaddForce( j, val->getForce(k) ); + k++; + } } } else { unsigned ncols=val->getShape()[1]; for(unsigned k=0; kgetRank()==0 ) argn->addForce( 0, val->getForce(ncols*row_starts[k]+col_starts[k]) ); - else { + if( argn->getRank()==0 ) { + argn->addForce( 0, val->getForce(ncols*row_starts[k]+col_starts[k]) ); + } else { unsigned val_ncols=val->getNumberOfColumns(); unsigned arg_ncols=argn->getNumberOfColumns(); for(unsigned i=0; igetShape()[0]; ++i) { unsigned ncol = argn->getRowLength(i); - for(unsigned j=0; jaddForce( i*arg_ncols+j, val->getForce( val_ncols*(row_starts[k]+i)+col_starts[k]+argn->getRowIndex(i,j) ), false ); + for(unsigned j=0; jaddForce( i*arg_ncols+j, val->getForce( val_ncols*(row_starts[k]+i)+col_starts[k]+argn->getRowIndex(i,j) ), false ); + } } } } diff --git a/src/valtools/Flatten.cpp b/src/valtools/Flatten.cpp index d1c9f488d4..1e52e8ca81 100644 --- a/src/valtools/Flatten.cpp +++ b/src/valtools/Flatten.cpp @@ -44,7 +44,9 @@ class Flatten : /// Constructor explicit Flatten(const ActionOptions&); /// Get the number of derivatives - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } /// Do the calculation void calculate() override; /// @@ -54,41 +56,60 @@ class Flatten : PLUMED_REGISTER_ACTION(Flatten,"FLATTEN") void Flatten::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.use("ARG"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.use("ARG"); keys.setValueDescription("a vector containing all the elements of the input matrix"); } Flatten::Flatten(const ActionOptions& ao): Action(ao), ActionWithValue(ao), - ActionWithArguments(ao) -{ - if( getNumberOfArguments()!=1 ) error("should only be one argument for this action"); - if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) error("input to this action should be a matrix"); + ActionWithArguments(ao) { + if( getNumberOfArguments()!=1 ) { + error("should only be one argument for this action"); + } + if( getPntrToArgument(0)->getRank()!=2 || getPntrToArgument(0)->hasDerivatives() ) { + error("input to this action should be a matrix"); + } getPntrToArgument(0)->buildDataStore(true); std::vector inshape( getPntrToArgument(0)->getShape() ); - std::vector shape( 1 ); shape[0]=inshape[0]*inshape[1]; - addValue( shape ); setNotPeriodic(); getPntrToComponent(0)->buildDataStore(); + std::vector shape( 1 ); + shape[0]=inshape[0]*inshape[1]; + addValue( shape ); + setNotPeriodic(); + getPntrToComponent(0)->buildDataStore(); } void Flatten::calculate() { - Value* myval = getPntrToComponent(0); unsigned ss=getPntrToArgument(0)->getShape()[1]; - std::vector vals; std::vector > pairs; + Value* myval = getPntrToComponent(0); + unsigned ss=getPntrToArgument(0)->getShape()[1]; + std::vector vals; + std::vector > pairs; bool symmetric=getPntrToArgument(0)->isSymmetric(); - unsigned nedge=0; getPntrToArgument(0)->retrieveEdgeList( nedge, pairs, vals ); + unsigned nedge=0; + getPntrToArgument(0)->retrieveEdgeList( nedge, pairs, vals ); for(unsigned l=0; lset( i*ss + j, vals[l] ); - if( symmetric ) myval->set( j*ss + i, vals[l] ); + if( symmetric ) { + myval->set( j*ss + i, vals[l] ); + } } } void Flatten::apply() { - if( doNotCalculateDerivatives() || !getPntrToComponent(0)->forcesWereAdded() ) return; + if( doNotCalculateDerivatives() || !getPntrToComponent(0)->forcesWereAdded() ) { + return; + } - Value* myval=getPntrToComponent(0); Value* myarg=getPntrToArgument(0); - unsigned nvals=myval->getNumberOfValues(); for(unsigned j=0; jaddForce( j, myval->getForce(j) ); + Value* myval=getPntrToComponent(0); + Value* myarg=getPntrToArgument(0); + unsigned nvals=myval->getNumberOfValues(); + for(unsigned j=0; jaddForce( j, myval->getForce(j) ); + } } } diff --git a/src/valtools/SelectComponents.cpp b/src/valtools/SelectComponents.cpp index a421ea4ae0..d8018e2568 100644 --- a/src/valtools/SelectComponents.cpp +++ b/src/valtools/SelectComponents.cpp @@ -50,40 +50,68 @@ void SelectComponents::registerKeywords( Keywords& keys ) { ActionShortcut::registerKeywords( keys ); keys.add("compulsory","ARG","the argument we are using to build the shortcut"); keys.add("compulsory","COMPONENTS","the components in the input value that you woul like to build a new vector from"); - keys.needsAction("FLATTEN"); keys.needsAction("CONSTANT"); keys.needsAction("SELECT_WITH_MASK"); + keys.needsAction("FLATTEN"); + keys.needsAction("CONSTANT"); + keys.needsAction("SELECT_WITH_MASK"); keys.setValueDescription("a vector containing the selected components"); } SelectComponents::SelectComponents(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - std::vector argn; parseVector("ARG",argn); std::vector theargs; + ActionShortcut(ao) { + std::vector argn; + parseVector("ARG",argn); + std::vector theargs; ActionWithArguments::interpretArgumentList( argn, plumed.getActionSet(), this, theargs ); - if( theargs.size()!=1 ) error("should only be one argument input to this action"); + if( theargs.size()!=1 ) { + error("should only be one argument input to this action"); + } // Create an array that will eventually hold the mask std::vector mask( theargs[0]->getNumberOfValues(), 1 ); - std::vector elements; parseVector("COMPONENTS",elements); + std::vector elements; + parseVector("COMPONENTS",elements); if( theargs[0]->getRank()==1 ) { - for(unsigned i=0; igetRank()==2 ) { for(unsigned i=0; igetShape()[1] + jval - 1] = 0; } readInputLine( getShortcutLabel() + "_flat: FLATTEN ARG=" + theargs[0]->getName() ); - } else error("input to this argument should be a vector/matrix"); + } else { + error("input to this argument should be a vector/matrix"); + } // Now create the mask action - std::string mask_str; Tools::convert( mask[0], mask_str ); unsigned check_mask=mask[0]; - for(unsigned i=1; igetRank()==2 ) readInputLine( getShortcutLabel() + ": SELECT_WITH_MASK ARG=" + getShortcutLabel() + "_flat MASK=" + getShortcutLabel() + "_mask"); + if( theargs[0]->getRank()==1 ) { + readInputLine( getShortcutLabel() + ": SELECT_WITH_MASK ARG=" + theargs[0]->getName() + " MASK=" + getShortcutLabel() + "_mask"); + } else if( theargs[0]->getRank()==2 ) { + readInputLine( getShortcutLabel() + ": SELECT_WITH_MASK ARG=" + getShortcutLabel() + "_flat MASK=" + getShortcutLabel() + "_mask"); + } } } diff --git a/src/valtools/SelectWithMask.cpp b/src/valtools/SelectWithMask.cpp index ac480f15b7..507c811a48 100644 --- a/src/valtools/SelectWithMask.cpp +++ b/src/valtools/SelectWithMask.cpp @@ -47,7 +47,9 @@ class SelectWithMask : /// Constructor explicit SelectWithMask(const ActionOptions&); /// Get the number of derivatives - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } /// void getMatrixColumnTitles( std::vector& argnames ) const override ; /// @@ -61,8 +63,10 @@ class SelectWithMask : PLUMED_REGISTER_ACTION(SelectWithMask,"SELECT_WITH_MASK") void SelectWithMask::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.use("ARG"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.use("ARG"); keys.add("optional","ROW_MASK","an array with ones in the rows of the matrix that you want to discard"); keys.add("optional","COLUMN_MASK","an array with ones in the columns of the matrix that you want to discard"); keys.add("compulsory","MASK","an array with ones in the components that you want to discard"); @@ -72,97 +76,155 @@ void SelectWithMask::registerKeywords( Keywords& keys ) { SelectWithMask::SelectWithMask(const ActionOptions& ao): Action(ao), ActionWithValue(ao), - ActionWithArguments(ao) -{ - if( getNumberOfArguments()!=1 ) error("should only be one argument for this action"); - getPntrToArgument(0)->buildDataStore(); std::vector shape; + ActionWithArguments(ao) { + if( getNumberOfArguments()!=1 ) { + error("should only be one argument for this action"); + } + getPntrToArgument(0)->buildDataStore(); + std::vector shape; if( getPntrToArgument(0)->getRank()==1 ) { - std::vector mask; parseArgumentList("MASK",mask); - if( mask.size()!=1 ) error("should only be one input for mask"); - if( mask[0]->getNumberOfValues()!=getPntrToArgument(0)->getNumberOfValues() ) error("mismatch between size of mask and input vector"); + std::vector mask; + parseArgumentList("MASK",mask); + if( mask.size()!=1 ) { + error("should only be one input for mask"); + } + if( mask[0]->getNumberOfValues()!=getPntrToArgument(0)->getNumberOfValues() ) { + error("mismatch between size of mask and input vector"); + } log.printf(" creating vector from elements of %s who have a corresponding element in %s that is zero\n", getPntrToArgument(0)->getName().c_str(), mask[0]->getName().c_str() ); - std::vector args( getArguments() ); args.push_back( mask[0] ); requestArguments( args ); - shape.resize(1,0); if( (mask[0]->getPntrToAction())->getName()=="CONSTANT" ) shape[0]=getOutputVectorLength(mask[0]); + std::vector args( getArguments() ); + args.push_back( mask[0] ); + requestArguments( args ); + shape.resize(1,0); + if( (mask[0]->getPntrToAction())->getName()=="CONSTANT" ) { + shape[0]=getOutputVectorLength(mask[0]); + } } else if( getPntrToArgument(0)->getRank()==2 ) { - std::vector rmask, cmask; parseArgumentList("ROW_MASK",rmask); parseArgumentList("COLUMN_MASK",cmask); + std::vector rmask, cmask; + parseArgumentList("ROW_MASK",rmask); + parseArgumentList("COLUMN_MASK",cmask); if( rmask.size()==0 && cmask.size()==0 ) { error("no mask elements have been specified"); } else if( cmask.size()==0 ) { - std::string con="0"; for(unsigned i=1; igetShape()[1]; ++i) con += ",0"; - plumed.readInputLine( getLabel() + "_colmask: CONSTANT VALUES=" + con ); std::vector labs(1, getLabel() + "_colmask"); + std::string con="0"; + for(unsigned i=1; igetShape()[1]; ++i) { + con += ",0"; + } + plumed.readInputLine( getLabel() + "_colmask: CONSTANT VALUES=" + con ); + std::vector labs(1, getLabel() + "_colmask"); ActionWithArguments::interpretArgumentList( labs, plumed.getActionSet(), this, cmask ); } else if( rmask.size()==0 ) { - std::string con="0"; for(unsigned i=1; igetShape()[0]; ++i) con += ",0"; - plumed.readInputLine( getLabel() + "_rowmask: CONSTANT VALUES=" + con ); std::vector labs(1, getLabel() + "_rowmask"); + std::string con="0"; + for(unsigned i=1; igetShape()[0]; ++i) { + con += ",0"; + } + plumed.readInputLine( getLabel() + "_rowmask: CONSTANT VALUES=" + con ); + std::vector labs(1, getLabel() + "_rowmask"); ActionWithArguments::interpretArgumentList( labs, plumed.getActionSet(), this, rmask ); } shape.resize(2); - rmask[0]->buildDataStore(); shape[0] = getOutputVectorLength( rmask[0] ); - cmask[0]->buildDataStore(); shape[1] = getOutputVectorLength( cmask[0] ); - std::vector args( getArguments() ); args.push_back( rmask[0] ); - args.push_back( cmask[0] ); requestArguments( args ); - } else error("input should be vector or matrix"); + rmask[0]->buildDataStore(); + shape[0] = getOutputVectorLength( rmask[0] ); + cmask[0]->buildDataStore(); + shape[1] = getOutputVectorLength( cmask[0] ); + std::vector args( getArguments() ); + args.push_back( rmask[0] ); + args.push_back( cmask[0] ); + requestArguments( args ); + } else { + error("input should be vector or matrix"); + } - addValue( shape ); getPntrToComponent(0)->buildDataStore(); + addValue( shape ); + getPntrToComponent(0)->buildDataStore(); if( getPntrToArgument(0)->isPeriodic() ) { - std::string min, max; getPntrToArgument(0)->getDomain( min, max ); setPeriodic( min, max ); - } else setNotPeriodic(); - if( getPntrToComponent(0)->getRank()==2 ) getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + std::string min, max; + getPntrToArgument(0)->getDomain( min, max ); + setPeriodic( min, max ); + } else { + setNotPeriodic(); + } + if( getPntrToComponent(0)->getRank()==2 ) { + getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + } } unsigned SelectWithMask::getOutputVectorLength( const Value* mask ) const { unsigned l=0; for(unsigned i=0; igetNumberOfValues(); ++i) { - if( fabs(mask->get(i))>0 ) continue; + if( fabs(mask->get(i))>0 ) { + continue; + } l++; } return l; } void SelectWithMask::getMatrixColumnTitles( std::vector& argnames ) const { - std::vector alltitles; (getPntrToArgument(0)->getPntrToAction())->getMatrixColumnTitles( alltitles ); + std::vector alltitles; + (getPntrToArgument(0)->getPntrToAction())->getMatrixColumnTitles( alltitles ); for(unsigned i=0; iget(i))>0 ) continue; + if( fabs(getPntrToArgument(2)->get(i))>0 ) { + continue; + } argnames.push_back( alltitles[i] ); } } void SelectWithMask::prepare() { - Value* arg = getPntrToArgument(0); Value* out = getPntrToComponent(0); + Value* arg = getPntrToArgument(0); + Value* out = getPntrToComponent(0); if( arg->getRank()==1 ) { Value* mask = getPntrToArgument(1); - std::vector shape(1); shape[0]=getOutputVectorLength( mask ); + std::vector shape(1); + shape[0]=getOutputVectorLength( mask ); if( out->getNumberOfValues()!=shape[0] ) { - if( shape[0]==1 ) shape.resize(0); + if( shape[0]==1 ) { + shape.resize(0); + } out->setShape(shape); } } else if( arg->getRank()==2 ) { std::vector outshape(2); - Value* rmask = getPntrToArgument(1); outshape[0] = getOutputVectorLength( rmask ); - Value* cmask = getPntrToArgument(2); outshape[1] = getOutputVectorLength( cmask ); + Value* rmask = getPntrToArgument(1); + outshape[0] = getOutputVectorLength( rmask ); + Value* cmask = getPntrToArgument(2); + outshape[1] = getOutputVectorLength( cmask ); if( out->getShape()[0]!=outshape[0] || out->getShape()[1]!=outshape[1] ) { - out->setShape(outshape); out->reshapeMatrixStore( outshape[1] ); + out->setShape(outshape); + out->reshapeMatrixStore( outshape[1] ); } } } void SelectWithMask::calculate() { - Value* arg = getPntrToArgument(0); Value* out = getPntrToComponent(0); + Value* arg = getPntrToArgument(0); + Value* out = getPntrToComponent(0); if( arg->getRank()==1 ) { - Value* mask = getPntrToArgument(1); unsigned n=0; + Value* mask = getPntrToArgument(1); + unsigned n=0; for(unsigned i=0; igetNumberOfValues(); ++i) { - if( fabs(mask->get(i))>0 ) continue; - out->set(n, arg->get(i) ); n++; + if( fabs(mask->get(i))>0 ) { + continue; + } + out->set(n, arg->get(i) ); + n++; } } else if ( arg->getRank()==2 ) { std::vector outshape( out->getShape() ); - unsigned n = 0; std::vector inshape( arg->getShape() ); - Value* rmask = getPntrToArgument(1); Value* cmask = getPntrToArgument(2); + unsigned n = 0; + std::vector inshape( arg->getShape() ); + Value* rmask = getPntrToArgument(1); + Value* cmask = getPntrToArgument(2); for(unsigned i=0; iget(i))>0 ) continue; + if( fabs(rmask->get(i))>0 ) { + continue; + } unsigned m = 0; for(unsigned j=0; jget(j))>0 ) continue; + if( fabs(cmask->get(j))>0 ) { + continue; + } out->set( n*outshape[1] + m, arg->get(i*inshape[1] + j) ); m++; } @@ -172,25 +234,37 @@ void SelectWithMask::calculate() { } void SelectWithMask::apply() { - if( doNotCalculateDerivatives() || !getPntrToComponent(0)->forcesWereAdded() ) return ; + if( doNotCalculateDerivatives() || !getPntrToComponent(0)->forcesWereAdded() ) { + return ; + } - Value* arg = getPntrToArgument(0); Value* out = getPntrToComponent(0); + Value* arg = getPntrToArgument(0); + Value* out = getPntrToComponent(0); if( arg->getRank()==1 ) { - unsigned n=0; Value* mask = getPntrToArgument(1); + unsigned n=0; + Value* mask = getPntrToArgument(1); for(unsigned i=0; igetNumberOfValues(); ++i) { - if( fabs(mask->get(i))>0 ) continue; - arg->addForce(i, out->getForce(n) ); n++; + if( fabs(mask->get(i))>0 ) { + continue; + } + arg->addForce(i, out->getForce(n) ); + n++; } } else if( arg->getRank()==2 ) { unsigned n = 0; std::vector inshape( arg->getShape() ); std::vector outshape( out->getShape() ); - Value* rmask = getPntrToArgument(1); Value* cmask = getPntrToArgument(2); + Value* rmask = getPntrToArgument(1); + Value* cmask = getPntrToArgument(2); for(unsigned i=0; iget(i))>0 ) continue; + if( fabs(rmask->get(i))>0 ) { + continue; + } unsigned m = 0; for(unsigned j=0; jget(j))>0 ) continue; + if( fabs(cmask->get(j))>0 ) { + continue; + } arg->addForce( i*inshape[1] + j, out->getForce(n*outshape[1] + m) ); m++; } diff --git a/src/valtools/VStack.cpp b/src/valtools/VStack.cpp index 209e817e93..1f13c6b55c 100644 --- a/src/valtools/VStack.cpp +++ b/src/valtools/VStack.cpp @@ -42,11 +42,15 @@ class VStack : public ActionWithMatrix { /// Constructor explicit VStack(const ActionOptions&); /// Get the number of derivatives - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } /// void prepare() override ; /// - unsigned getNumberOfColumns() const override { return getNumberOfArguments(); } + unsigned getNumberOfColumns() const override { + return getNumberOfArguments(); + } /// void setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const override ; /// @@ -60,99 +64,169 @@ class VStack : public ActionWithMatrix { PLUMED_REGISTER_ACTION(VStack,"VSTACK") void VStack::registerKeywords( Keywords& keys ) { - ActionWithMatrix::registerKeywords( keys ); keys.use("ARG"); + ActionWithMatrix::registerKeywords( keys ); + keys.use("ARG"); keys.setValueDescription("a matrix that contains the input vectors in its columns"); } VStack::VStack(const ActionOptions& ao): Action(ao), - ActionWithMatrix(ao) -{ - if( getNumberOfArguments()==0 ) error("no arguments were specificed"); - if( getPntrToArgument(0)->getRank()>1 ) error("all arguments should be vectors"); - unsigned nvals=1; bool periodic=false; std::string smin, smax; - if( getPntrToArgument(0)->getRank()==1 ) nvals = getPntrToArgument(0)->getShape()[0]; - if( getPntrToArgument(0)->isPeriodic() ) { periodic=true; getPntrToArgument(0)->getDomain( smin, smax ); } + ActionWithMatrix(ao) { + if( getNumberOfArguments()==0 ) { + error("no arguments were specificed"); + } + if( getPntrToArgument(0)->getRank()>1 ) { + error("all arguments should be vectors"); + } + unsigned nvals=1; + bool periodic=false; + std::string smin, smax; + if( getPntrToArgument(0)->getRank()==1 ) { + nvals = getPntrToArgument(0)->getShape()[0]; + } + if( getPntrToArgument(0)->isPeriodic() ) { + periodic=true; + getPntrToArgument(0)->getDomain( smin, smax ); + } for(unsigned i=0; igetRank()>1 || (getPntrToArgument(i)->getRank()==1 && getPntrToArgument(i)->hasDerivatives()) ) error("all arguments should be vectors"); + if( getPntrToArgument(i)->getRank()>1 || (getPntrToArgument(i)->getRank()==1 && getPntrToArgument(i)->hasDerivatives()) ) { + error("all arguments should be vectors"); + } if( getPntrToArgument(i)->getRank()==0 ) { - if( nvals!=1 ) error("all input vector should have same number of elements"); - } else if( getPntrToArgument(i)->getShape()[0]!=nvals ) error("all input vector should have same number of elements"); + if( nvals!=1 ) { + error("all input vector should have same number of elements"); + } + } else if( getPntrToArgument(i)->getShape()[0]!=nvals ) { + error("all input vector should have same number of elements"); + } if( periodic ) { - if( !getPntrToArgument(i)->isPeriodic() ) error("one argument is periodic but " + getPntrToArgument(i)->getName() + " is not periodic"); - std::string tmin, tmax; getPntrToArgument(i)->getDomain( tmin, tmax ); - if( tmin!=smin || tmax!=smax ) error("domain of argument " + getPntrToArgument(i)->getName() + " is different from domain for all other arguments"); - } else if( getPntrToArgument(i)->isPeriodic() ) error("one argument is not periodic but " + getPntrToArgument(i)->getName() + " is periodic"); + if( !getPntrToArgument(i)->isPeriodic() ) { + error("one argument is periodic but " + getPntrToArgument(i)->getName() + " is not periodic"); + } + std::string tmin, tmax; + getPntrToArgument(i)->getDomain( tmin, tmax ); + if( tmin!=smin || tmax!=smax ) { + error("domain of argument " + getPntrToArgument(i)->getName() + " is different from domain for all other arguments"); + } + } else if( getPntrToArgument(i)->isPeriodic() ) { + error("one argument is not periodic but " + getPntrToArgument(i)->getName() + " is periodic"); + } } // And create a value to hold the matrix - std::vector shape(2); shape[0]=nvals; shape[1]=getNumberOfArguments(); addValue( shape ); - if( periodic ) setPeriodic( smin, smax ); else setNotPeriodic(); + std::vector shape(2); + shape[0]=nvals; + shape[1]=getNumberOfArguments(); + addValue( shape ); + if( periodic ) { + setPeriodic( smin, smax ); + } else { + setNotPeriodic(); + } // And store this value - getPntrToComponent(0)->buildDataStore(); getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + getPntrToComponent(0)->buildDataStore(); + getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); // Setup everything so we can build the store - done_in_chain=true; ActionWithVector* av=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); + done_in_chain=true; + ActionWithVector* av=dynamic_cast( getPntrToArgument(0)->getPntrToAction() ); if( av ) { const ActionWithVector* head0 = av->getFirstActionInChain(); for(unsigned i=0; i( getPntrToArgument(i)->getPntrToAction() ); - if( !avv ) continue; - if( head0!=avv->getFirstActionInChain() ) { done_in_chain=false; break; } + if( !avv ) { + continue; + } + if( head0!=avv->getFirstActionInChain() ) { + done_in_chain=false; + break; + } } - } else done_in_chain=false; + } else { + done_in_chain=false; + } unsigned nder = buildArgumentStore(0); // This checks which values have been stored - stored.resize( getNumberOfArguments() ); std::string headstr=getFirstActionInChain()->getLabel(); - for(unsigned i=0; iignoreStoredValue( headstr ); + stored.resize( getNumberOfArguments() ); + std::string headstr=getFirstActionInChain()->getLabel(); + for(unsigned i=0; iignoreStoredValue( headstr ); + } } void VStack::getMatrixColumnTitles( std::vector& argnames ) const { for(unsigned j=0; jgetPntrToAction())->getName()=="COLLECT" ) { ActionWithArguments* aa = dynamic_cast( getPntrToArgument(j)->getPntrToAction() ); - plumed_assert( aa && aa->getNumberOfArguments()==1 ); argnames.push_back( (aa->getPntrToArgument(0))->getName() ); - } else argnames.push_back( getPntrToArgument(j)->getName() ); + plumed_assert( aa && aa->getNumberOfArguments()==1 ); + argnames.push_back( (aa->getPntrToArgument(0))->getName() ); + } else { + argnames.push_back( getPntrToArgument(j)->getName() ); + } } } void VStack::prepare() { ActionWithVector::prepare(); - if( getPntrToArgument(0)->getRank()==0 || getPntrToArgument(0)->getShape()[0]==getPntrToComponent(0)->getShape()[0] ) return ; - std::vector shape(2); shape[0] = getPntrToArgument(0)->getShape()[0]; shape[1] = getNumberOfArguments(); - getPntrToComponent(0)->setShape(shape); getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); + if( getPntrToArgument(0)->getRank()==0 || getPntrToArgument(0)->getShape()[0]==getPntrToComponent(0)->getShape()[0] ) { + return ; + } + std::vector shape(2); + shape[0] = getPntrToArgument(0)->getShape()[0]; + shape[1] = getNumberOfArguments(); + getPntrToComponent(0)->setShape(shape); + getPntrToComponent(0)->reshapeMatrixStore( shape[1] ); } void VStack::setupForTask( const unsigned& task_index, std::vector& indices, MultiValue& myvals ) const { - unsigned nargs = getNumberOfArguments(); unsigned nvals = getConstPntrToComponent(0)->getShape()[0]; - if( indices.size()!=nargs+1 ) indices.resize( nargs+1 ); - for(unsigned i=0; igetShape()[0]; + if( indices.size()!=nargs+1 ) { + indices.resize( nargs+1 ); + } + for(unsigned i=0; i=getConstPntrToComponent(0)->getShape()[0] ) ind2 = index2 - getConstPntrToComponent(0)->getShape()[0]; + unsigned ind2 = index2; + if( index2>=getConstPntrToComponent(0)->getShape()[0] ) { + ind2 = index2 - getConstPntrToComponent(0)->getShape()[0]; + } myvals.addValue( getConstPntrToComponent(0)->getPositionInStream(), getArgumentElement( ind2, index1, myvals ) ); - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } addDerivativeOnVectorArgument( stored[ind2], 0, ind2, index1, 1.0, myvals ); } void VStack::runEndOfRowJobs( const unsigned& ival, const std::vector & indices, MultiValue& myvals ) const { - if( doNotCalculateDerivatives() || !matrixChainContinues() ) return ; + if( doNotCalculateDerivatives() || !matrixChainContinues() ) { + return ; + } unsigned nmat = getConstPntrToComponent(0)->getPositionInMatrixStash(), nmat_ind = myvals.getNumberOfMatrixRowDerivatives( nmat ); std::vector& matrix_indices( myvals.getMatrixRowDerivativeIndices( nmat ) ); plumed_assert( nmat_indgetPntrToAction(); + bool found=false; + ActionWithValue* iav = getPntrToArgument(i)->getPntrToAction(); for(unsigned j=0; jgetPntrToAction() ) { found=true; break; } + if( iav==getPntrToArgument(j)->getPntrToAction() ) { + found=true; + break; + } + } + if( found ) { + continue ; } - if( found ) continue ; unsigned istrn = getPntrToArgument(i)->getPositionInStream(); for(unsigned k=0; k xpos; parseArgumentList("XPOS",xpos); - if( xpos.size()!=1 && xpos[0]->getRank()!=0 ) error("invalid input argument for XPOS"); - std::vector ypos; parseArgumentList("YPOS",ypos); - if( ypos.size()!=1 && ypos[0]->getRank()!=0 ) error("invalid input argument for YPOS"); - std::vector zpos; parseArgumentList("ZPOS",zpos); - if( zpos.size()!=1 && zpos[0]->getRank()!=0 ) error("invalid input argument for ZPOS"); - std::vector mass; parseArgumentList("MASS",mass); - if( mass.size()!=1 && mass[0]->getRank()!=0 ) error("invalid input argument for MASS"); - std::vector charge; parseArgumentList("CHARGE",charge); - if( charge.size()!=1 && charge[0]->getRank()!=0 ) error("invalid input argument for CHARGE"); + std::vector xpos; + parseArgumentList("XPOS",xpos); + if( xpos.size()!=1 && xpos[0]->getRank()!=0 ) { + error("invalid input argument for XPOS"); + } + std::vector ypos; + parseArgumentList("YPOS",ypos); + if( ypos.size()!=1 && ypos[0]->getRank()!=0 ) { + error("invalid input argument for YPOS"); + } + std::vector zpos; + parseArgumentList("ZPOS",zpos); + if( zpos.size()!=1 && zpos[0]->getRank()!=0 ) { + error("invalid input argument for ZPOS"); + } + std::vector mass; + parseArgumentList("MASS",mass); + if( mass.size()!=1 && mass[0]->getRank()!=0 ) { + error("invalid input argument for MASS"); + } + std::vector charge; + parseArgumentList("CHARGE",charge); + if( charge.size()!=1 && charge[0]->getRank()!=0 ) { + error("invalid input argument for CHARGE"); + } // Make sure we have requested everything that we need in xpos - xpos.push_back(ypos[0]); xpos.push_back(zpos[0]); xpos.push_back(mass[0]); xpos.push_back(charge[0]); + xpos.push_back(ypos[0]); + xpos.push_back(zpos[0]); + xpos.push_back(mass[0]); + xpos.push_back(charge[0]); if( fractional ) { log.printf(" creating atom from fractional pos a=%s, b=%s and c=%s \n", xpos[0]->getName().c_str(), ypos[0]->getName().c_str(), zpos[0]->getName().c_str() ); - std::vector xbkp; parseArgumentList("XBKP",xbkp); + std::vector xbkp; + parseArgumentList("XBKP",xbkp); if( xbkp.size()>0 ) { - if( xbkp.size()!=1 && xbkp[0]->getRank()!=0 ) error("invalid input argument for XBKP"); - std::vector ybkp; parseArgumentList("YBKP",ybkp); - if( ybkp.size()!=1 && ybkp[0]->getRank()!=0 ) error("invalid input argument for YBKP"); - std::vector zbkp; parseArgumentList("ZBKP",zbkp); - if( zbkp.size()!=1 && zpos[0]->getRank()!=0 ) error("invalid input argument for ZBKP"); + if( xbkp.size()!=1 && xbkp[0]->getRank()!=0 ) { + error("invalid input argument for XBKP"); + } + std::vector ybkp; + parseArgumentList("YBKP",ybkp); + if( ybkp.size()!=1 && ybkp[0]->getRank()!=0 ) { + error("invalid input argument for YBKP"); + } + std::vector zbkp; + parseArgumentList("ZBKP",zbkp); + if( zbkp.size()!=1 && zpos[0]->getRank()!=0 ) { + error("invalid input argument for ZBKP"); + } // Store backup for NOPBC - xpos.push_back(xbkp[0]); xpos.push_back(ybkp[0]); xpos.push_back(zbkp[0]); + xpos.push_back(xbkp[0]); + xpos.push_back(ybkp[0]); + xpos.push_back(zbkp[0]); log.printf(" using x=%s, y=%s and z=%s if PBC not set \n", xbkp[0]->getName().c_str(), ybkp[0]->getName().c_str(), zbkp[0]->getName().c_str() ); } - } else log.printf(" creating atom at x=%s, y=%s and z=%s \n", xpos[0]->getName().c_str(), ypos[0]->getName().c_str(), zpos[0]->getName().c_str() ); + } else { + log.printf(" creating atom at x=%s, y=%s and z=%s \n", xpos[0]->getName().c_str(), ypos[0]->getName().c_str(), zpos[0]->getName().c_str() ); + } log.printf(" mass of atom is %s and charge is %s \n", mass[0]->getName().c_str(), charge[0]->getName().c_str() ); // Request the arguments requestArguments(xpos); // Create the components to hold the atom - addComponentWithDerivatives("x"); componentIsNotPeriodic("x"); - addComponentWithDerivatives("y"); componentIsNotPeriodic("y"); - addComponentWithDerivatives("z"); componentIsNotPeriodic("z"); - addComponent("mass"); componentIsNotPeriodic("mass"); if( mass[0]->isConstant() ) getPntrToComponent(3)->setConstant(); - addComponent("charge"); componentIsNotPeriodic("charge"); if( charge[0]->isConstant() ) getPntrToComponent(4)->setConstant(); + addComponentWithDerivatives("x"); + componentIsNotPeriodic("x"); + addComponentWithDerivatives("y"); + componentIsNotPeriodic("y"); + addComponentWithDerivatives("z"); + componentIsNotPeriodic("z"); + addComponent("mass"); + componentIsNotPeriodic("mass"); + if( mass[0]->isConstant() ) { + getPntrToComponent(3)->setConstant(); + } + addComponent("charge"); + componentIsNotPeriodic("charge"); + if( charge[0]->isConstant() ) { + getPntrToComponent(4)->setConstant(); + } pbc_action = plumed.getActionSet().selectWithLabel("Box"); - for(unsigned i=0; i<3; ++i) getPntrToComponent(i)->resizeDerivatives( getNumberOfArguments() ); + for(unsigned i=0; i<3; ++i) { + getPntrToComponent(i)->resizeDerivatives( getNumberOfArguments() ); + } } void ArgsToVatom::calculate() { if( fractional ) { if( pbc_action->getPbc().isSet() ) { // Get the position in fractional coordinates - Vector fpos; for(unsigned i=0; i<3; ++i) fpos[i] = getPntrToArgument(i)->get(); + Vector fpos; + for(unsigned i=0; i<3; ++i) { + fpos[i] = getPntrToArgument(i)->get(); + } // Convert fractioanl coordinates to cartesian coordinates - Tensor box=pbc_action->getPbc().getBox(); Vector cpos=matmul(fpos,box); + Tensor box=pbc_action->getPbc().getBox(); + Vector cpos=matmul(fpos,box); // Set the final position and derivatives for(unsigned i=0; i<3; ++i) { - Value* vv=getPntrToComponent(i); vv->set( cpos[i] ); - for(unsigned j=0; j<3; ++j) vv->addDerivative( j, box[j][i] ); + Value* vv=getPntrToComponent(i); + vv->set( cpos[i] ); + for(unsigned j=0; j<3; ++j) { + vv->addDerivative( j, box[j][i] ); + } } } else { - if( getNumberOfArguments()<8 ) error("cannot use PHASES option if box is not set"); + if( getNumberOfArguments()<8 ) { + error("cannot use PHASES option if box is not set"); + } // Set the values - for(unsigned i=0; i<3; ++i) getPntrToComponent(i)->set( getPntrToArgument(5+i)->get() ); + for(unsigned i=0; i<3; ++i) { + getPntrToComponent(i)->set( getPntrToArgument(5+i)->get() ); + } // And the derivatives - for(unsigned i=0; i<3; ++i) getPntrToComponent(i)->addDerivative( 5+i, 1.0 ); + for(unsigned i=0; i<3; ++i) { + getPntrToComponent(i)->addDerivative( 5+i, 1.0 ); + } } // Set the mass and charge - for(unsigned i=3; i<5; ++i) getPntrToComponent(i)->set( getPntrToArgument(i)->get() ); + for(unsigned i=3; i<5; ++i) { + getPntrToComponent(i)->set( getPntrToArgument(i)->get() ); + } } else { // Set the values - for(unsigned i=0; i<5; ++i) getPntrToComponent(i)->set( getPntrToArgument(i)->get() ); + for(unsigned i=0; i<5; ++i) { + getPntrToComponent(i)->set( getPntrToArgument(i)->get() ); + } // And the derivatives - for(unsigned i=0; i<3; ++i) getPntrToComponent(i)->addDerivative( i, 1.0 ); + for(unsigned i=0; i<3; ++i) { + getPntrToComponent(i)->addDerivative( i, 1.0 ); + } } } void ArgsToVatom::apply() { - if( !checkForForces() ) return ; + if( !checkForForces() ) { + return ; + } - unsigned start=0; addForcesOnArguments( 0, getForcesToApply(), start, getLabel() ); + unsigned start=0; + addForcesOnArguments( 0, getForcesToApply(), start, getLabel() ); } } diff --git a/src/vatom/Center.cpp b/src/vatom/Center.cpp index 10ce5169f8..fe03ff4ece 100644 --- a/src/vatom/Center.cpp +++ b/src/vatom/Center.cpp @@ -126,8 +126,7 @@ PRINT ARG=d1 class Center: - public ActionWithVirtualAtom -{ + public ActionWithVirtualAtom { std::vector weights; std::vector dcenter_sin; std::vector dcenter_cos; @@ -149,7 +148,9 @@ PLUMED_REGISTER_ACTION(Center,"COM") void Center::registerKeywords(Keywords& keys) { ActionWithVirtualAtom::registerKeywords(keys); - if( keys.getDisplayName()!="COM" ) keys.setDisplayName("CENTER"); + if( keys.getDisplayName()!="COM" ) { + keys.setDisplayName("CENTER"); + } keys.add("optional","WEIGHTS","Center is computed as a weighted average."); keys.add("optional","SET_CHARGE","Set the charge of the virtual atom to a given value."); keys.add("optional","SET_MASS","Set the mass of the virtual atom to a given value."); @@ -166,41 +167,64 @@ Center::Center(const ActionOptions&ao): weight_mass(false), nopbc(false), first(true), - phases(false) -{ + phases(false) { std::vector atoms; parseAtomList("ATOMS",atoms); - if(atoms.size()==0) error("at least one atom should be specified"); + if(atoms.size()==0) { + error("at least one atom should be specified"); + } parseVector("WEIGHTS",weights); parseFlag("MASS",weight_mass); parseFlag("NOPBC",nopbc); parseFlag("PHASES",phases); - double charge_=std::numeric_limits::lowest(); parse("SET_CHARGE",charge_); setCharge(charge_); - if(charge_!=std::numeric_limits::lowest()) isChargeSet_=true; - double mass_=-1; parse("SET_MASS",mass_); setMass(mass_); - if(mass_>0.) isMassSet_=true; - if(mass_==0.) error("SETMASS must be greater than 0"); - if( getName()=="COM") weight_mass=true; + double charge_=std::numeric_limits::lowest(); + parse("SET_CHARGE",charge_); + setCharge(charge_); + if(charge_!=std::numeric_limits::lowest()) { + isChargeSet_=true; + } + double mass_=-1; + parse("SET_MASS",mass_); + setMass(mass_); + if(mass_>0.) { + isMassSet_=true; + } + if(mass_==0.) { + error("SETMASS must be greater than 0"); + } + if( getName()=="COM") { + weight_mass=true; + } checkRead(); log.printf(" of atoms:"); for(unsigned i=0; i str_weights; parseVector("WEIGHTS",str_weights); + bool usemass; + parseFlag("MASS",usemass); + std::vector str_weights; + parseVector("WEIGHTS",str_weights); if( usemass || str_weights.size()==0 || str_weights.size()>1 || (str_weights.size()==1 && str_weights[0]=="@Masses") ) { - if( usemass && str_weights.size()!=0 ) error("WEIGHTS and MASS keywords cannot not be used simultaneously"); + if( usemass && str_weights.size()!=0 ) { + error("WEIGHTS and MASS keywords cannot not be used simultaneously"); + } std::string wt_str; if( str_weights.size()>0 ) { - wt_str="WEIGHTS=" + str_weights[0]; for(unsigned i=1; i0 ) { if( str_weights.size()==1 ) { - if( str_weights[0]=="@Charges" ) wlab = getShortcutLabel() + "_q"; - else wlab=str_weights[0]; + if( str_weights[0]=="@Charges" ) { + wlab = getShortcutLabel() + "_q"; + } else { + wlab=str_weights[0]; + } } else if( str_weights.size()==nat ) { - std::string vals=str_weights[0]; for(unsigned i=1; i deriv; double mass,charge; @@ -107,17 +106,20 @@ void FixedAtom::registerKeywords(Keywords& keys) { FixedAtom::FixedAtom(const ActionOptions&ao): Action(ao), - ActionWithVirtualAtom(ao) -{ + ActionWithVirtualAtom(ao) { std::vector atoms; parseAtomList("ATOMS",atoms); - if(atoms.size()!=0) error("ATOMS should be empty"); + if(atoms.size()!=0) { + error("ATOMS should be empty"); + } parseFlag("SCALED_COMPONENTS",scaled_components); std::vector at; parseVector("AT",at); - if(at.size()!=3) error("AT should be a list of three real numbers"); + if(at.size()!=3) { + error("AT should be a list of three real numbers"); + } parse("SET_MASS",mass); parse("SET_CHARGE",charge); @@ -128,7 +130,9 @@ FixedAtom::FixedAtom(const ActionOptions&ao): checkRead(); log<<" AT position "< coord; std::vector deriv; bool nopbc=false; @@ -83,20 +82,25 @@ void Ghost::registerKeywords(Keywords& keys) { Ghost::Ghost(const ActionOptions&ao): Action(ao), - ActionWithVirtualAtom(ao) -{ + ActionWithVirtualAtom(ao) { std::vector atoms; parseAtomList("ATOMS",atoms); - if(atoms.size()!=3) error("ATOMS should contain a list of three atoms"); + if(atoms.size()!=3) { + error("ATOMS should contain a list of three atoms"); + } parseVector("COORDINATES",coord); - if(coord.size()!=3) error("COORDINATES should be a list of three real numbers"); + if(coord.size()!=3) { + error("COORDINATES should be a list of three real numbers"); + } parseFlag("NOPBC",nopbc); checkRead(); log.printf(" of atoms"); - for(unsigned i=0; i basisf_labels; - parseVector("BASIS_FUNCTIONS",basisf_labels); addKeywordToList("BASIS_FUNCTIONS",basisf_labels); + parseVector("BASIS_FUNCTIONS",basisf_labels); + addKeywordToList("BASIS_FUNCTIONS",basisf_labels); if(basisf_labels.size()==1) { plumed_merror("using only one basis function in BF_COMBINED does not make sense"); } std::string error_msg = ""; basisf_pntrs_ = VesTools::getPointersFromLabels(basisf_labels,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword BASIS_FUNCTIONS of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword BASIS_FUNCTIONS of "+getName()+": "+error_msg); + } unsigned int nbasisf_total_ = 1; bool periodic = true; @@ -108,14 +110,19 @@ BF_Combined::BF_Combined(const ActionOptions&ao): if(basisf_pntrs_[i]->intervalMinStr()!=basisf_pntrs_[0]->intervalMinStr() || basisf_pntrs_[i]->intervalMaxStr()!=basisf_pntrs_[0]->intervalMaxStr()) { plumed_merror("all the basis functions to be combined should have same MINIMUM and MAXIMUM"); } - if(!basisf_pntrs_[i]->arePeriodic()) {periodic=false;} + if(!basisf_pntrs_[i]->arePeriodic()) { + periodic=false; + } } setOrder(nbasisf_total_-1); setNumberOfBasisFunctions(nbasisf_total_); setInterval(basisf_pntrs_[0]->intervalMinStr(),basisf_pntrs_[0]->intervalMaxStr()); setIntrinsicInterval("-1.0","+1.0"); - if(periodic) {setPeriodic();} - else {setNonPeriodic();} + if(periodic) { + setPeriodic(); + } else { + setNonPeriodic(); + } setIntervalBounded(); setType("combined"); setDescription("Combined"); @@ -162,7 +169,8 @@ void BF_Combined::getAllValues(const double arg, double& argT, bool& inside_rang for(unsigned int i=1; inumberOfBasisFunctions(),0.0); derivs_tmp.assign(basisf_pntrs_[i]->numberOfBasisFunctions(),0.0); - double dummy_dbl; bool dummy_bool=true; + double dummy_dbl; + bool dummy_bool=true; basisf_pntrs_[i]->getAllValues(arg,dummy_dbl,dummy_bool,values_tmp,derivs_tmp); for(unsigned int l=1; lnumberOfBasisFunctions(); l++) { values[r] = values_tmp[l]; diff --git a/src/ves/BF_Cosine.cpp b/src/ves/BF_Cosine.cpp index f7e15b547d..c9b069a3d1 100644 --- a/src/ves/BF_Cosine.cpp +++ b/src/ves/BF_Cosine.cpp @@ -100,8 +100,7 @@ void BF_Cosine::registerKeywords(Keywords& keys) { BF_Cosine::BF_Cosine(const ActionOptions&ao): - PLUMED_VES_BASISFUNCTIONS_INIT(ao) -{ + PLUMED_VES_BASISFUNCTIONS_INIT(ao) { setNumberOfBasisFunctions(getOrder()+1); setIntrinsicInterval("-pi","+pi"); setPeriodic(); @@ -128,7 +127,9 @@ void BF_Cosine::getAllValues(const double arg, double& argT, bool& inside_range, derivs[i] = -io*sin_tmp*intervalDerivf(); } if(!inside_range) { - for(unsigned int i=0; i 2) { value=0.0; deriv=0.0; - } - else if(x >= 1) { + } else if(x >= 1) { value = ((2.0-x)*(2.0-x)*(2.0-x)); deriv = dx*(-3.0*(2.0-x)*(2.0-x)); // value=((2.0-x)*(2.0-x)*(2.0-x))/6.0; // deriv=-x*x*(2.0-x)*(2.0-x); - } - else { + } else { value = 4.0-6.0*x*x+3.0*x*x*x; deriv = dx*(-12.0*x+9.0*x*x); // value=x*x*x*0.5-x*x+2.0/3.0; diff --git a/src/ves/BF_Custom.cpp b/src/ves/BF_Custom.cpp index 627736c728..87dd2a4962 100644 --- a/src/ves/BF_Custom.cpp +++ b/src/ves/BF_Custom.cpp @@ -147,28 +147,36 @@ BF_Custom::BF_Custom(const ActionOptions&ao): variable_str_("x"), transf_variable_str_("t"), do_transf_(false), - check_nan_inf_(false) -{ + check_nan_inf_(false) { std::vector bf_str; std::string str_t1="1"; bf_str.push_back(str_t1); for(int i=1;; i++) { std::string str_t2; - if(!parseNumbered("FUNC",i,str_t2)) {break;} - std::string is; Tools::convert(i,is); + if(!parseNumbered("FUNC",i,str_t2)) { + break; + } + std::string is; + Tools::convert(i,is); addKeywordToList("FUNC"+is,str_t2); bf_str.push_back(str_t2); } // - if(bf_str.size()==1) {plumed_merror(getName()+" with label "+getLabel()+": No FUNC keywords given");} + if(bf_str.size()==1) { + plumed_merror(getName()+" with label "+getLabel()+": No FUNC keywords given"); + } setOrder(bf_str.size()-1); setNumberOfBasisFunctions(getOrder()+1); setIntrinsicInterval(intervalMin(),intervalMax()); bool periodic = false; - parseFlag("PERIODIC",periodic); addKeywordToList("PERIODIC",periodic); - if(periodic) {setPeriodic();} - else {setNonPeriodic();} + parseFlag("PERIODIC",periodic); + addKeywordToList("PERIODIC",periodic); + if(periodic) { + setPeriodic(); + } else { + setNonPeriodic(); + } setIntervalBounded(); setType("custom_functions"); setDescription("Custom Functions"); @@ -184,14 +192,15 @@ BF_Custom::BF_Custom(const ActionOptions&ao): bf_derivs_lepton_ref_.resize(getNumberOfBasisFunctions()); // for(unsigned int i=1; i(intrinsic_length)}; - } - else { + } else { plumed_massert(!periodic, "TAILS_THRESHOLD can't be used with the periodic wavelet variant"); addKeywordToList("TAILS_THRESHOLD",threshold); cutoffpoints = getCutoffPoints(threshold); @@ -307,14 +309,12 @@ BF_Wavelets::BF_Wavelets(const ActionOptions& ao): if (periodic) { // this is the same value as num_shifts above + constant num_BFs = static_cast(bias_length * scale_) + 1; - } - else { + } else { num_BFs = 1; // constant one // left shifts (w/o left cutoff) + right shifts - right cutoff - 1 num_BFs += static_cast(ceil(cutoffpoints[1] + (bias_length)*scale_ - cutoffpoints[0]) - 1); } - } - else { + } else { plumed_massert(num_BFs > 0, "The number of basis functions has to be positive (NUM_BF > 0)"); // check does not work if function length was given as intrinsic length, but can't check for keyword use directly plumed_massert(function_length==bias_length,"The keywords \"NUM_BF\" and \"FUNCTION_LENGTH\" cannot be used at the same time"); @@ -322,8 +322,7 @@ BF_Wavelets::BF_Wavelets(const ActionOptions& ao): if (periodic) { // inverted num_BFs calculation from where FUNCTION_LENGTH is specified scale_ = (num_BFs - 1) / bias_length ; - } - else { + } else { double cutoff_length = cutoffpoints[1] - cutoffpoints [0]; double intrinsic_bias_length = num_BFs - cutoff_length + 1; // length of bias in intrinsic scale of wavelets scale_ = intrinsic_bias_length / bias_length; @@ -364,15 +363,19 @@ void BF_Wavelets::getAllValues(const double arg, double& argT, bool& inside_rang } if (x < 0 || x >= intrinsicIntervalMax()) { // Wavelets are 0 outside the defined range - values[i] = 0.0; derivs[i] = 0.0; - } - else { + values[i] = 0.0; + derivs[i] = 0.0; + } else { std::vector temp_deriv (1); values[i] = GridLinearInterpolation::getGridValueAndDerivativesWithLinearInterpolation(waveletGrid_.get(), {x}, temp_deriv); derivs[i] = temp_deriv[0] * scale_; // scale derivative } } - if(!inside_range) {for(auto& deriv : derivs) {deriv=0.0;}} + if(!inside_range) { + for(auto& deriv : derivs) { + deriv=0.0; + } + } } @@ -408,7 +411,8 @@ void BF_Wavelets::setupLabels() { if (arePeriodic()) { pos = pos - floor((pos-intervalMin())/intervalRange())*intervalRange(); } - std::string is; Tools::convert(pos, is); + std::string is; + Tools::convert(pos, is); setLabel(i,"i="+is); } } diff --git a/src/ves/BasisFunctions.cpp b/src/ves/BasisFunctions.cpp index 4da5223078..51d7d4a0cb 100644 --- a/src/ves/BasisFunctions.cpp +++ b/src/ves/BasisFunctions.cpp @@ -73,20 +73,22 @@ BasisFunctions::BasisFunctions(const ActionOptions&ao): nbins_(1001), uniform_integrals_(nbasis_,0.0), vesbias_pntr_(NULL), - action_pntr_(NULL) -{ + action_pntr_(NULL) { bf_keywords_.push_back(getName()); if(keywords.exists("ORDER")) { - parse("ORDER",norder_); addKeywordToList("ORDER",norder_); + parse("ORDER",norder_); + addKeywordToList("ORDER",norder_); } nbasis_=norder_+1; // - std::string str_imin; std::string str_imax; + std::string str_imin; + std::string str_imax; if(keywords.exists("MINIMUM") && keywords.exists("MAXIMUM")) { - parse("MINIMUM",str_imin); addKeywordToList("MINIMUM",str_imin); - parse("MAXIMUM",str_imax); addKeywordToList("MAXIMUM",str_imax); - } - else { + parse("MINIMUM",str_imin); + addKeywordToList("MINIMUM",str_imin); + parse("MAXIMUM",str_imax); + addKeywordToList("MAXIMUM",str_imax); + } else { str_imin = "-1.0"; str_imax = "1.0"; } @@ -98,7 +100,9 @@ BasisFunctions::BasisFunctions(const ActionOptions&ao): if(!Tools::convertNoexcept(str_imax,interval_max_)) { plumed_merror(getName()+": cannot convert the value given in MAXIMUM to a double"); } - if(interval_min_>interval_max_) {plumed_merror(getName()+": MINIMUM and MAXIMUM are not correctly defined");} + if(interval_min_>interval_max_) { + plumed_merror(getName()+": MINIMUM and MAXIMUM are not correctly defined"); + } // parseFlag("DEBUG_INFO",print_debug_info_); if(keywords.exists("NUMERICAL_INTEGRALS")) { @@ -168,7 +172,8 @@ void BasisFunctions::setupInterval() { void BasisFunctions::setupLabels() { for(unsigned int i=0; i < nbasis_; i++) { - std::string is; Tools::convert(i,is); + std::string is; + Tools::convert(i,is); bf_labels_[i]=bf_label_prefix_+is+"(s)"; } } @@ -181,32 +186,51 @@ void BasisFunctions::setupUniformIntegrals() { void BasisFunctions::setupBF() { - if(interval_intrinsic_min_>interval_intrinsic_max_) {plumed_merror("setupBF: default intervals are not correctly set");} + if(interval_intrinsic_min_>interval_intrinsic_max_) { + plumed_merror("setupBF: default intervals are not correctly set"); + } setupInterval(); setupLabels(); - if(bf_labels_.size()==1) {plumed_merror("setupBF: the labels of the basis functions are not correct.");} - if(!numerical_uniform_integrals_) {setupUniformIntegrals();} - else {numericalUniformIntegrals();} - if(uniform_integrals_.size()==1) {plumed_merror("setupBF: the integrals of the basis functions is not correct.");} - if(type_=="Undefined") {plumed_merror("setupBF: the type of the basis function is not defined.");} - if(description_=="Undefined") {plumed_merror("setupBF: the description of the basis function is not defined.");} + if(bf_labels_.size()==1) { + plumed_merror("setupBF: the labels of the basis functions are not correct."); + } + if(!numerical_uniform_integrals_) { + setupUniformIntegrals(); + } else { + numericalUniformIntegrals(); + } + if(uniform_integrals_.size()==1) { + plumed_merror("setupBF: the integrals of the basis functions is not correct."); + } + if(type_=="Undefined") { + plumed_merror("setupBF: the type of the basis function is not defined."); + } + if(description_=="Undefined") { + plumed_merror("setupBF: the description of the basis function is not defined."); + } has_been_set=true; printInfo(); } void BasisFunctions::printInfo() const { - if(!has_been_set) {plumed_merror("the basis set has not be setup correctly");} + if(!has_been_set) { + plumed_merror("the basis set has not be setup correctly"); + } log.printf(" One-dimensional basis set\n"); log.printf(" Description: %s\n",description_.c_str()); log.printf(" Type: %s\n",type_.c_str()); - if(periodic_) {log.printf(" The basis functions are periodic\n");} + if(periodic_) { + log.printf(" The basis functions are periodic\n"); + } log.printf(" Order of basis set: %u\n",norder_); log.printf(" Number of basis functions: %u\n",nbasis_); // log.printf(" Interval of basis set: %f to %f\n",interval_min_,interval_max_); log.printf(" Interval of basis set: %s to %s\n",interval_min_str_.c_str(),interval_max_str_.c_str()); log.printf(" Description of basis functions:\n"); - for(unsigned int i=0; i < nbasis_; i++) {log.printf(" %2u %10s\n",i,bf_labels_[i].c_str());} + for(unsigned int i=0; i < nbasis_; i++) { + log.printf(" %2u %10s\n",i,bf_labels_[i].c_str()); + } // if(print_debug_info_) { log.printf(" Debug information:\n"); @@ -218,8 +242,12 @@ void BasisFunctions::printInfo() const { log.printf(" Defined interval of basis set: range=%f, mean=%f\n",interval_range_,interval_mean_); log.printf(" Derivative factor due to interval translation: %f\n",argT_derivf_); log.printf(" Integral of basis functions over the interval:\n"); - if(numerical_uniform_integrals_) {log.printf(" Note: calculated numerically\n");} - for(unsigned int i=0; i < nbasis_; i++) {log.printf(" %2u %16.10f\n",i,uniform_integrals_[i]);} + if(numerical_uniform_integrals_) { + log.printf(" Note: calculated numerically\n"); + } + for(unsigned int i=0; i < nbasis_; i++) { + log.printf(" %2u %16.10f\n",i,uniform_integrals_[i]); + } log.printf(" --------------------------\n"); } } @@ -237,12 +265,19 @@ void BasisFunctions::linkAction(Action* action_pntr_in) { void BasisFunctions::numericalUniformIntegrals() { - std::vector grid_min(1); grid_min[0]=intervalMinStr(); - std::vector grid_max(1); grid_max[0]=intervalMaxStr(); - std::vector grid_bins(1); grid_bins[0]=nbins_; - std::vector> arguments(1); arguments[0]= Tools::make_unique(nullptr,"arg",false); - if(arePeriodic()) {arguments[0]->setDomain(intervalMinStr(),intervalMaxStr());} - else {arguments[0]->setNotPeriodic();} + std::vector grid_min(1); + grid_min[0]=intervalMinStr(); + std::vector grid_max(1); + grid_max[0]=intervalMaxStr(); + std::vector grid_bins(1); + grid_bins[0]=nbins_; + std::vector> arguments(1); + arguments[0]= Tools::make_unique(nullptr,"arg",false); + if(arePeriodic()) { + arguments[0]->setDomain(intervalMinStr(),intervalMaxStr()); + } else { + arguments[0]->setNotPeriodic(); + } auto uniform_grid = Tools::make_unique("uniform",Tools::unique2raw(arguments),grid_min,grid_max,grid_bins,false,false); // double inverse_normalization = 1.0/(intervalMax()-intervalMin()); @@ -282,8 +317,7 @@ std::vector BasisFunctions::numericalTargetDistributionIntegralsFromGrid std::vector BasisFunctions::getTargetDistributionIntegrals(const TargetDistribution* targetdist_pntr) const { if(targetdist_pntr==NULL) { return getUniformIntegrals(); - } - else { + } else { Grid* targetdist_grid = targetdist_pntr->getTargetDistGridPntr(); return numericalTargetDistributionIntegralsFromGrid(targetdist_grid); } @@ -292,7 +326,9 @@ std::vector BasisFunctions::getTargetDistributionIntegrals(const TargetD std::string BasisFunctions::getKeywordString() const { std::string str_keywords=bf_keywords_[0]; - for(unsigned int i=1; i& args, std::vect void BasisFunctions::writeBasisFunctionsToFile(OFile& ofile_values, OFile& ofile_derivs, const std::string& min_in, const std::string& max_in, unsigned int nbins_in, const bool ignore_periodicity, const std::string& output_fmt_values, const std::string& output_fmt_derivs, const bool numerical_deriv) const { - std::vector min(1); min[0]=min_in; - std::vector max(1); max[0]=max_in; - std::vector nbins(1); nbins[0]=nbins_in; + std::vector min(1); + min[0]=min_in; + std::vector max(1); + max[0]=max_in; + std::vector nbins(1); + nbins[0]=nbins_in; std::vector> value_pntr(1); value_pntr[0]= Tools::make_unique(nullptr,"arg",false); - if(arePeriodic() && !ignore_periodicity) {value_pntr[0]->setDomain(intervalMinStr(),intervalMaxStr());} - else {value_pntr[0]->setNotPeriodic();} + if(arePeriodic() && !ignore_periodicity) { + value_pntr[0]->setDomain(intervalMinStr(),intervalMaxStr()); + } else { + value_pntr[0]->setNotPeriodic(); + } Grid args_grid = Grid("grid",Tools::unique2raw(value_pntr),min,max,nbins,false,false); std::vector args(args_grid.getSize(),0.0); @@ -376,8 +418,7 @@ void BasisFunctions::writeBasisFunctionsToFile(OFile& ofile_values, OFile& ofile if(arePeriodic()) { ofile_values.addConstantField("periodic").printField("periodic","true"); ofile_derivs.addConstantField("periodic").printField("periodic","true"); - } - else { + } else { ofile_values.addConstantField("periodic").printField("periodic","false"); ofile_derivs.addConstantField("periodic").printField("periodic","false"); } diff --git a/src/ves/BasisFunctions.h b/src/ves/BasisFunctions.h index cb12994c45..05231e3396 100644 --- a/src/ves/BasisFunctions.h +++ b/src/ves/BasisFunctions.h @@ -47,8 +47,7 @@ class VesBias; class TargetDistribution; class BasisFunctions : - public Action -{ + public Action { private: // print extra info about the basis set bool print_debug_info_; @@ -103,7 +102,9 @@ class BasisFunctions : // setup various stuff void setupBF(); void setupInterval(); - void setNumericalIntegrationBins(const unsigned int nbins) {nbins_=nbins;} + void setNumericalIntegrationBins(const unsigned int nbins) { + nbins_=nbins; + } void numericalUniformIntegrals(); std::vector numericalTargetDistributionIntegralsFromGrid(const Grid*) const ; virtual void setupLabels(); @@ -114,24 +115,46 @@ class BasisFunctions : void addKeywordToList(const std::string&, const std::vector&); void addKeywordToList(const std::string&, const bool); // - void setPeriodic() {periodic_=true;} - void setNonPeriodic() {periodic_=false;} - void setIntervalBounded() {interval_bounded_=true;} - void setIntervalNonBounded() {interval_bounded_=false;} - void setType(const std::string& type_in) {type_=type_in;} - void setDescription(const std::string& description_in) {description_=description_in;} + void setPeriodic() { + periodic_=true; + } + void setNonPeriodic() { + periodic_=false; + } + void setIntervalBounded() { + interval_bounded_=true; + } + void setIntervalNonBounded() { + interval_bounded_=false; + } + void setType(const std::string& type_in) { + type_=type_in; + } + void setDescription(const std::string& description_in) { + description_=description_in; + } // void setNumberOfBasisFunctions(const unsigned int); - void setOrder(const unsigned int norder_in) {norder_=norder_in;} + void setOrder(const unsigned int norder_in) { + norder_=norder_in; + } void setIntrinsicInterval(const double, const double); void setIntrinsicInterval(const std::string&, const std::string&); void setInterval(const double, const double); void setInterval(const std::string&, const std::string&); // - double intrinsicIntervalMin() const {return interval_intrinsic_min_;} - double intrinsicIntervalMax() const {return interval_intrinsic_max_;} - std::string intrinsicIntervalMinStr() const {return interval_intrinsic_min_str_;} - std::string intrinsicIntervalMaxStr() const {return interval_intrinsic_max_str_;} + double intrinsicIntervalMin() const { + return interval_intrinsic_min_; + } + double intrinsicIntervalMax() const { + return interval_intrinsic_max_; + } + std::string intrinsicIntervalMinStr() const { + return interval_intrinsic_min_str_; + } + std::string intrinsicIntervalMaxStr() const { + return interval_intrinsic_max_str_; + } // void setUniformIntegral(const unsigned int, const double); void setUniformIntegrals(const std::vector&); @@ -144,30 +167,70 @@ class BasisFunctions : public: static void registerKeywords(Keywords&); explicit BasisFunctions(const ActionOptions&ao); - bool hasBeenSet() const {return has_been_set;} - std::string getType() const {return type_;} - std::string getDescription() const {return description_;} - unsigned int getOrder() const {return norder_;} - unsigned int getNumberOfBasisFunctions() const {return nbasis_;} - unsigned int numberOfBasisFunctions() const {return nbasis_;} - unsigned int getSize() const {return nbasis_;} - bool arePeriodic() const {return periodic_;} - bool intervalBounded() const {return interval_bounded_;} - double intervalMin() const {return interval_min_;} - double intervalMax() const {return interval_max_;} - double intervalRange() const {return interval_range_;} - double intervalMean() const {return interval_mean_;} - double intervalDerivf() const {return argT_derivf_;} - std::string intervalMinStr() const {return interval_min_str_;} - std::string intervalMaxStr() const {return interval_max_str_;} - std::vector getUniformIntegrals() const {return uniform_integrals_;} + bool hasBeenSet() const { + return has_been_set; + } + std::string getType() const { + return type_; + } + std::string getDescription() const { + return description_; + } + unsigned int getOrder() const { + return norder_; + } + unsigned int getNumberOfBasisFunctions() const { + return nbasis_; + } + unsigned int numberOfBasisFunctions() const { + return nbasis_; + } + unsigned int getSize() const { + return nbasis_; + } + bool arePeriodic() const { + return periodic_; + } + bool intervalBounded() const { + return interval_bounded_; + } + double intervalMin() const { + return interval_min_; + } + double intervalMax() const { + return interval_max_; + } + double intervalRange() const { + return interval_range_; + } + double intervalMean() const { + return interval_mean_; + } + double intervalDerivf() const { + return argT_derivf_; + } + std::string intervalMinStr() const { + return interval_min_str_; + } + std::string intervalMaxStr() const { + return interval_max_str_; + } + std::vector getUniformIntegrals() const { + return uniform_integrals_; + } std::vector getTargetDistributionIntegrals(const TargetDistribution*) const; // - std::vector getKeywordList() const {return bf_keywords_;} + std::vector getKeywordList() const { + return bf_keywords_; + } std::string getKeywordString() const; // - std::string getBasisFunctionLabel(const unsigned int index) const {return bf_labels_[index];} - std::vector getBasisFunctionLabels() const {return bf_labels_;} + std::string getBasisFunctionLabel(const unsigned int index) const { + return bf_labels_[index]; + } + std::vector getBasisFunctionLabels() const { + return bf_labels_; + } // void linkVesBias(VesBias*); void linkAction(Action*); @@ -257,8 +320,7 @@ double BasisFunctions::translateArgument(const double arg, bool& inside_interval if(argT < interval_intrinsic_min_) { inside_interval=false; argT=interval_intrinsic_min_; - } - else if(argT > interval_intrinsic_max_) { + } else if(argT > interval_intrinsic_max_) { inside_interval=false; argT=interval_intrinsic_max_; } @@ -273,8 +335,7 @@ double BasisFunctions::checkIfArgumentInsideInterval(const double arg, bool& ins if(arg < interval_min_) { inside_interval=false; argT=interval_min_; - } - else if(arg > interval_max_) { + } else if(arg > interval_max_) { inside_interval=false; argT=interval_max_; } @@ -307,7 +368,9 @@ void BasisFunctions::addKeywordToList(const std::string& keyword, const std::vec inline void BasisFunctions::addKeywordToList(const std::string& keyword, const bool value) { - if(value) {bf_keywords_.push_back(keyword);} + if(value) { + bf_keywords_.push_back(keyword); + } } diff --git a/src/ves/CoeffsBase.cpp b/src/ves/CoeffsBase.cpp index 05e6ad05c1..0840cb6363 100644 --- a/src/ves/CoeffsBase.cpp +++ b/src/ves/CoeffsBase.cpp @@ -66,8 +66,7 @@ CoeffsBase::CoeffsBase( field_shape_prefix_("shape_"), field_time_("time"), field_iteration_("iteration"), - output_fmt_("%30.16e") -{ + output_fmt_("%30.16e") { initializeIndices(indices_shape,dimension_labels); setAllCoeffsDescriptions(); } @@ -103,8 +102,7 @@ CoeffsBase::CoeffsBase( field_shape_prefix_("shape_"), field_time_("time"), field_iteration_("iteration"), - output_fmt_("%30.16e") -{ + output_fmt_("%30.16e") { plumed_massert(args_.size()==basisf_.size(),"CoeffsBase: number of arguments do not match number of basis functions"); std::vector dimension_labels(args_.size()); std::vector indices_shape(args_.size()); @@ -148,8 +146,7 @@ CoeffsBase::CoeffsBase( field_shape_prefix_("shape_"), field_time_("time"), field_iteration_("iteration"), - output_fmt_("%30.16e") -{ + output_fmt_("%30.16e") { plumed_massert(multicoeffs_args.size()==multicoeffs_basisf.size(),"Multi Coeffs: number of arguments vectors does not match number of basis functions vectors"); unsigned int num_args = multicoeffs_args[0].size(); unsigned int dim = num_args+1; @@ -216,8 +213,7 @@ void CoeffsBase::setupBasisFunctionsInfo() { } setCoeffDescription(i,desc); } - } - else if(coeffs_type_==MultiCoeffs_LinearBasisSet) { + } else if(coeffs_type_==MultiCoeffs_LinearBasisSet) { for(unsigned int i=0; i indices=getIndices(i); unsigned int mc_id = indices[ndimensions_-1]; @@ -298,11 +294,9 @@ std::string CoeffsBase::getTypeStr() const { std::string type_str=""; if(coeffs_type_==Generic) { type_str = "Generic"; - } - else if(coeffs_type_==LinearBasisSet) { + } else if(coeffs_type_==LinearBasisSet) { type_str = "LinearBasisSet"; - } - else if(coeffs_type_==MultiCoeffs_LinearBasisSet) { + } else if(coeffs_type_==MultiCoeffs_LinearBasisSet) { type_str = "MultiCoeffs_LinearBasisSet"; } return type_str; @@ -349,10 +343,12 @@ void CoeffsBase::setCoeffDescription(const std::vector& indices, c void CoeffsBase::setAllCoeffsDescriptions(const std::string& description_prefix) { for(size_t i=0; i indices=getIndices(i); - std::string is; Tools::convert(indices[0],is); + std::string is; + Tools::convert(indices[0],is); std::string desc=description_prefix+"("+is; for(unsigned int k=1; k shapeOfIndices() const {return indices_shape_;} - unsigned int shapeOfIndices(const unsigned int dim_index) const {return indices_shape_[dim_index];} - size_t numberOfCoeffs() const {return ncoeffs_;} - unsigned int numberOfDimensions() const {return ndimensions_;} + std::vector shapeOfIndices() const { + return indices_shape_; + } + unsigned int shapeOfIndices(const unsigned int dim_index) const { + return indices_shape_[dim_index]; + } + size_t numberOfCoeffs() const { + return ncoeffs_; + } + unsigned int numberOfDimensions() const { + return ndimensions_; + } // - bool isActive() const {return active;} - void activate() {active=true;} - void deactivate() {active=false;} + bool isActive() const { + return active; + } + void activate() { + active=true; + } + void deactivate() { + active=false; + } // size_t getIndex(const std::vector&) const; std::vector getIndices(const size_t) const; bool indicesExist(const std::vector&) const; // - std::string getCoeffDescription(const size_t index) const {return coeffs_descriptions_[index];} + std::string getCoeffDescription(const size_t index) const { + return coeffs_descriptions_[index]; + } std::string getCoeffDescription(const std::vector&) const; - std::vector getAllCoeffsDescriptions() const {return coeffs_descriptions_;} + std::vector getAllCoeffsDescriptions() const { + return coeffs_descriptions_; + } void setCoeffDescription(const size_t, const std::string&); void setCoeffDescription(const std::vector&, const std::string&); void setAllCoeffsDescriptions(const std::string& description_prefix="C"); void setAllCoeffsDescriptions(const std::vector&); // std::string getDimensionLabel(const unsigned int) const; - std::vector getAllDimensionLabels() const {return dimension_labels_;} + std::vector getAllDimensionLabels() const { + return dimension_labels_; + } void setDimensionLabel(const unsigned int, const std::string&); void setAllDimensionLabels(const std::string&); void setAllDimensionLabels(const std::vector&); @@ -161,18 +196,34 @@ class CoeffsBase void getCoeffsInfoFromFile(IFile&, const bool ignore_coeffs_info=false); void checkCoeffsInfo(const std::string&, const std::string&, const unsigned int, const size_t, const std::vector&); // - void turnOnIterationCounter() {iteration_and_time_active_=true;} - void turnOffIterationCounter() {iteration_and_time_active_=false;} - bool isIterationCounterActive() const {return iteration_and_time_active_;} + void turnOnIterationCounter() { + iteration_and_time_active_=true; + } + void turnOffIterationCounter() { + iteration_and_time_active_=false; + } + bool isIterationCounterActive() const { + return iteration_and_time_active_; + } void setIterationCounter(const unsigned int); void setTime(const double); void setIterationCounterAndTime(const unsigned int, const double); - unsigned int getIterationCounter() const {return iteration_opt;} - double getTimeValue() const {return time_md;} + unsigned int getIterationCounter() const { + return iteration_opt; + } + double getTimeValue() const { + return time_md; + } // - void setOutputFmt(const std::string& ss) { output_fmt_=ss; } - void resetOutputFmt() {output_fmt_="%30.16e";} - std::string getOutputFmt() const {return output_fmt_;} + void setOutputFmt(const std::string& ss) { + output_fmt_=ss; + } + void resetOutputFmt() { + output_fmt_="%30.16e"; + } + std::string getOutputFmt() const { + return output_fmt_; + } // void replaceLabelString(const std::string&, const std::string&); protected: diff --git a/src/ves/CoeffsMatrix.cpp b/src/ves/CoeffsMatrix.cpp index 4531e94c94..a5048ed060 100644 --- a/src/ves/CoeffsMatrix.cpp +++ b/src/ves/CoeffsMatrix.cpp @@ -57,8 +57,7 @@ CoeffsMatrix::CoeffsMatrix( diagonal_(diagonal), averaging_counter(0), averaging_exp_decay_(0), - mycomm(cc) -{ + mycomm(cc) { setupMatrix(); } @@ -78,8 +77,7 @@ CoeffsMatrix::CoeffsMatrix( diagonal_(diagonal), averaging_counter(0), averaging_exp_decay_(0), - mycomm(cc) -{ + mycomm(cc) { setupMatrix(); } @@ -100,8 +98,7 @@ CoeffsMatrix::CoeffsMatrix( diagonal_(diagonal), averaging_counter(0), averaging_exp_decay_(0), - mycomm(cc) -{ + mycomm(cc) { setupMatrix(); } @@ -119,8 +116,7 @@ CoeffsMatrix::CoeffsMatrix( diagonal_(diagonal), averaging_counter(0), averaging_exp_decay_(0), - mycomm(cc) -{ + mycomm(cc) { setLabels(label); setupMatrix(); } @@ -134,8 +130,7 @@ void CoeffsMatrix::setupMatrix() { ncolumns_=nrows_; if(diagonal_) { size_=nrows_; - } - else { + } else { size_=(nrows_*nrows_-nrows_)/2+nrows_; } clear(); @@ -204,11 +199,9 @@ size_t CoeffsMatrix::getMatrixIndex(const size_t index1, const size_t index2) co if(diagonal_) { // plumed_massert(index1==index2,"CoeffsMatrix: you trying to access a off-diagonal element of a diagonal coeffs matrix"); matrix_idx=index1; - } - else if (index1<=index2) { + } else if (index1<=index2) { matrix_idx=index2+index1*(nrows_-1)-index1*(index1-1)/2; - } - else { + } else { matrix_idx=index1+index2*(nrows_-1)-index2*(index2-1)/2; } return matrix_idx; @@ -279,8 +272,7 @@ CoeffsVector operator*(const CoeffsMatrix& coeffs_matrix, const CoeffsVector& co for(size_t i=0; i data; @@ -120,7 +119,9 @@ class CoeffsMatrix: void clear(); void setAllValuesToZero(); // - std::vector getDataAsVector() const {return data;} + std::vector getDataAsVector() const { + return data; + } // get value double getValue(const size_t, const size_t) const; double getValue(const std::vector&, const std::vector&) const; @@ -184,9 +185,15 @@ class CoeffsMatrix: // void randomizeValuesGaussian(int); // - void resetAveragingCounter() {averaging_counter=0;} - void setupExponentiallyDecayingAveraging(const unsigned int averaging_exp_decay_in) {averaging_exp_decay_=averaging_exp_decay_in;} - void turnOffExponentiallyDecayingAveraging() { averaging_exp_decay_=0;} + void resetAveragingCounter() { + averaging_counter=0; + } + void setupExponentiallyDecayingAveraging(const unsigned int averaging_exp_decay_in) { + averaging_exp_decay_=averaging_exp_decay_in; + } + void turnOffExponentiallyDecayingAveraging() { + averaging_exp_decay_=0; + } void resetAveraging(); void addToAverage(const CoeffsMatrix&); void addToAverage(const CoeffsMatrix&, const unsigned int); @@ -201,7 +208,9 @@ class CoeffsMatrix: void writeDataDiagonalToFile(OFile&); void writeDataFullToFile(OFile&); public: - Communicator& getCommunicator() const {return mycomm;} + Communicator& getCommunicator() const { + return mycomm; + } }; } diff --git a/src/ves/CoeffsVector.cpp b/src/ves/CoeffsVector.cpp index 62dde7ffa4..c3630611a1 100644 --- a/src/ves/CoeffsVector.cpp +++ b/src/ves/CoeffsVector.cpp @@ -52,8 +52,7 @@ CoeffsVector::CoeffsVector( data(0), averaging_counter(0), averaging_exp_decay_(0), - mycomm(cc) -{ + mycomm(cc) { clear(); } @@ -68,8 +67,7 @@ CoeffsVector::CoeffsVector( data(0), averaging_counter(0), averaging_exp_decay_(0), - mycomm(cc) -{ + mycomm(cc) { clear(); } @@ -85,8 +83,7 @@ CoeffsVector::CoeffsVector( data(0), averaging_counter(0), averaging_exp_decay_(0), - mycomm(cc) -{ + mycomm(cc) { clear(); } @@ -99,8 +96,7 @@ CoeffsVector::CoeffsVector( data(0), averaging_counter(0), averaging_exp_decay_(0), - mycomm(cc) -{ + mycomm(cc) { clear(); } @@ -645,7 +641,9 @@ void CoeffsVector::normalizeCoeffs() { void CoeffsVector::randomizeValuesGaussian(int randomSeed) { Random rnd; - if (randomSeed<0) {randomSeed = -randomSeed;} + if (randomSeed<0) { + randomSeed = -randomSeed; + } rnd.setSeed(-randomSeed); for(size_t i=0; igetCommunicator()); } - if(append_file) { file.enforceRestart(); } + if(append_file) { + file.enforceRestart(); + } file.open(filepath); writeToFile(file,coeffsvecSet,print_coeffs_descriptions); file.close(); @@ -785,8 +785,11 @@ void CoeffsVector::writeDataToFile(OFile& ofile, const std::vectorgetValue(i)); } - std::snprintf(s1.data(),s1.size(),int_fmt.c_str(),i); ofile.printField(field_index,s1.data()); - if(print_coeffs_descriptions) { ofile.printField(field_description," "+coeffs_descriptions[i]);} + std::snprintf(s1.data(),s1.size(),int_fmt.c_str(),i); + ofile.printField(field_index,s1.data()); + if(print_coeffs_descriptions) { + ofile.printField(field_description," "+coeffs_descriptions[i]); + } ofile.printField(); } ofile.fmtField(); @@ -801,7 +804,9 @@ size_t CoeffsVector::readFromFile(IFile& ifile, const bool ignore_missing_coeffs ifile.allowIgnoredFields(); size_t ncoeffs_read=0; while(ifile) { - if(!ignore_header) {readHeaderFromFile(ifile);} + if(!ignore_header) { + readHeaderFromFile(ifile); + } if(ifile) { ncoeffs_read=readDataFromFile(ifile,ignore_missing_coeffs); } @@ -814,8 +819,12 @@ size_t CoeffsVector::readOneSetFromFile(IFile& ifile, const bool ignore_header) ifile.allowIgnoredFields(); size_t ncoeffs_read=0; if(ifile) { - if(!ignore_header) {readHeaderFromFile(ifile);} - if(ifile) {ncoeffs_read=readDataFromFile(ifile,false);} + if(!ignore_header) { + readHeaderFromFile(ifile); + } + if(ifile) { + ncoeffs_read=readDataFromFile(ifile,false); + } } return ncoeffs_read; } @@ -867,11 +876,14 @@ size_t CoeffsVector::readDataFromFile(IFile& ifile, const bool ignore_missing_co data[getIndex(indices)] = coeff_tmp; ifile.scanField(field_index,idx_tmp); if(getIndex(indices)!=static_cast(idx_tmp)) { - std::string is1; Tools::convert(idx_tmp,is1); + std::string is1; + Tools::convert(idx_tmp,is1); std::string msg="ERROR: problem with indices at index " + is1 + " when reading coefficients from file"; plumed_merror(msg); } - if(ifile.FieldExist(field_description)) { ifile.scanField(field_description,str_tmp); } + if(ifile.FieldExist(field_description)) { + ifile.scanField(field_description,str_tmp); + } // ifile.scanField(); ncoeffs_read++; diff --git a/src/ves/CoeffsVector.h b/src/ves/CoeffsVector.h index af77ad9816..0462b80973 100644 --- a/src/ves/CoeffsVector.h +++ b/src/ves/CoeffsVector.h @@ -45,8 +45,7 @@ class CoeffsMatrix; class CoeffsVector: - public CoeffsBase -{ + public CoeffsBase { public: private: std::vector data; @@ -87,12 +86,16 @@ class CoeffsVector: // ~CoeffsVector(); // - size_t getSize() const {return numberOfCoeffs();} + size_t getSize() const { + return numberOfCoeffs(); + } // clear coeffs void clear(); void setAllValuesToZero(); // - std::vector getDataAsVector() const {return data;} + std::vector getDataAsVector() const { + return data; + } // bool sameShape(CoeffsVector&) const; bool sameShape(CoeffsMatrix&) const; @@ -191,9 +194,15 @@ class CoeffsVector: // Random values void randomizeValuesGaussian(int); // - void resetAveragingCounter() {averaging_counter=0;} - void setupExponentiallyDecayingAveraging(const unsigned int averaging_exp_decay_in) {averaging_exp_decay_=averaging_exp_decay_in;} - void turnOffExponentiallyDecayingAveraging() {averaging_exp_decay_=0;} + void resetAveragingCounter() { + averaging_counter=0; + } + void setupExponentiallyDecayingAveraging(const unsigned int averaging_exp_decay_in) { + averaging_exp_decay_=averaging_exp_decay_in; + } + void turnOffExponentiallyDecayingAveraging() { + averaging_exp_decay_=0; + } void resetAveraging(); void addToAverage(const CoeffsVector&); // @@ -216,7 +225,9 @@ class CoeffsVector: void readHeaderFromFile(IFile&, const bool ignore_coeffs_info=false); size_t readDataFromFile(IFile&, const bool ignore_missing_coeffs=false); public: - Communicator& getCommunicator() const {return mycomm;} + Communicator& getCommunicator() const { + return mycomm; + } }; diff --git a/src/ves/FermiSwitchingFunction.cpp b/src/ves/FermiSwitchingFunction.cpp index 3e0f83061f..7c6d3a50e6 100644 --- a/src/ves/FermiSwitchingFunction.cpp +++ b/src/ves/FermiSwitchingFunction.cpp @@ -47,24 +47,34 @@ void FermiSwitchingFunction::set(const std::string& definition,std::string& erro } std::string name=data[0]; data.erase(data.begin()); - if(name!="FERMI") {errormsg="only FERMI is supported";} + if(name!="FERMI") { + errormsg="only FERMI is supported"; + } type=fermi; // bool found_r0=Tools::parse(data,"R_0",r0_); - if(!found_r0) {errormsg="R_0 is required";} + if(!found_r0) { + errormsg="R_0 is required"; + } // fermi_exp_max_=std::numeric_limits::max(); Tools::parse(data,"FERMI_EXP_MAX",fermi_exp_max_); // bool found_lambda=Tools::parse(data,"FERMI_LAMBDA",fermi_lambda_); - if(!found_lambda) {errormsg="FERMI_LAMBDA is required for FERMI";} + if(!found_lambda) { + errormsg="FERMI_LAMBDA is required for FERMI"; + } if( !data.empty() ) { errormsg="found the following rogue keywords in switching function input : "; - for(unsigned i=0; i0) {init=false;} + if(errormsg.size()>0) { + init=false; + } } std::string FermiSwitchingFunction::description() const { @@ -73,8 +83,7 @@ std::string FermiSwitchingFunction::description() const { if(type==fermi) { ostr<< "fermi switching function with parameter"; ostr<< " lambda="<= fermi_exp_max_) {rdist = fermi_exp_max_;} + if(rdist >= fermi_exp_max_) { + rdist = fermi_exp_max_; + } double result = 1.0/(1.0+exp(rdist)); dfunc=-fermi_lambda_*exp(rdist)*result*result; // this is because calculate() sets dfunc to the derivative divided times the distance. @@ -101,8 +112,7 @@ FermiSwitchingFunction::FermiSwitchingFunction(): r0_(0.0), invr0_(0.0), fermi_lambda_(1.0), - fermi_exp_max_(100.0) -{ + fermi_exp_max_(100.0) { } FermiSwitchingFunction::FermiSwitchingFunction(const FermiSwitchingFunction&sf): @@ -111,8 +121,7 @@ FermiSwitchingFunction::FermiSwitchingFunction(const FermiSwitchingFunction&sf): r0_(sf.r0_), invr0_(sf.invr0_), fermi_lambda_(sf.fermi_lambda_), - fermi_exp_max_(sf.fermi_exp_max_) -{ + fermi_exp_max_(sf.fermi_exp_max_) { } void FermiSwitchingFunction::set(const double r0, const double fermi_lambda, const double fermi_exp_max) { @@ -122,8 +131,7 @@ void FermiSwitchingFunction::set(const double r0, const double fermi_lambda, con fermi_lambda_=fermi_lambda; if(fermi_exp_max>0.0) { fermi_exp_max_=fermi_exp_max; - } - else { + } else { fermi_exp_max_=100.0; } diff --git a/src/ves/GridIntegrationWeights.cpp b/src/ves/GridIntegrationWeights.cpp index dc2a832a3b..21176de20d 100644 --- a/src/ves/GridIntegrationWeights.cpp +++ b/src/ves/GridIntegrationWeights.cpp @@ -39,8 +39,7 @@ std::vector GridIntegrationWeights::getIntegrationWeights(const Grid* gr std::vector weights_tmp; if(weights_type=="trapezoidal") { weights_tmp = getOneDimensionalTrapezoidalWeights(nbins[k],dx[k],isPeriodic[k]); - } - else { + } else { plumed_merror("getIntegrationWeights: unknown weight type, the available type is trapezoidal"); } weights_perdim.push_back(weights_tmp); @@ -75,11 +74,12 @@ std::vector GridIntegrationWeights::getIntegrationWeights(const Grid* gr void GridIntegrationWeights::getOneDimensionalIntegrationPointsAndWeights(std::vector& points, std::vector& weights, const unsigned int nbins, const double min, const double max, const std::string& weights_type) { double dx = (max-min)/(static_cast(nbins)-1.0); points.resize(nbins); - for(unsigned int i=0; i GridIntegrationWeights::getOneDimensionalTrapezoidalWeights( if(!periodic) { weights_1d[0]= 0.5*dx; weights_1d[(nbins-1)]= 0.5*dx; - } - else { + } else { // as for periodic arguments the first point should be counted twice as the // grid doesn't include its periodic copy weights_1d[0]= dx; diff --git a/src/ves/GridLinearInterpolation.cpp b/src/ves/GridLinearInterpolation.cpp index 2054a6db8d..f56223907e 100644 --- a/src/ves/GridLinearInterpolation.cpp +++ b/src/ves/GridLinearInterpolation.cpp @@ -38,9 +38,12 @@ double GridLinearInterpolation::getGridValueWithLinearInterpolation_1D(GridBase* double x = arg[0]; double grid_dx = grid_pntr->getDx()[0]; - double grid_min; Tools::convert( grid_pntr->getMin()[0], grid_min); - std::vector i0(1); i0[0] = unsigned( std::floor( (x-grid_min)/grid_dx ) ); - std::vector i1(1); i1[0] = unsigned( std::ceil( (x-grid_min)/grid_dx ) ); + double grid_min; + Tools::convert( grid_pntr->getMin()[0], grid_min); + std::vector i0(1); + i0[0] = unsigned( std::floor( (x-grid_min)/grid_dx ) ); + std::vector i1(1); + i1[0] = unsigned( std::ceil( (x-grid_min)/grid_dx ) ); // double x0 = grid_pntr->getPoint(i0)[0]; double x1 = grid_pntr->getPoint(i1)[0]; @@ -122,11 +125,14 @@ double GridLinearInterpolation::getGridValueAndDerivativesWithLinearInterpolatio double x = arg[0]; double grid_dx = grid_pntr->getDx()[0]; - double grid_min; Tools::convert( grid_pntr->getMin()[0], grid_min); + double grid_min; + Tools::convert( grid_pntr->getMin()[0], grid_min); double xtoindex = (x-grid_min)/grid_dx; - std::vector i0(1); i0[0] = unsigned(std::floor(xtoindex)); - std::vector i1(1); i1[0] = unsigned(std::ceil(xtoindex)); + std::vector i0(1); + i0[0] = unsigned(std::floor(xtoindex)); + std::vector i1(1); + i1[0] = unsigned(std::ceil(xtoindex)); // std::vector d0 (1), d1 (1); double x0 = grid_pntr->getPoint(i0)[0]; @@ -169,11 +175,9 @@ double GridLinearInterpolation::getGridValueWithLinearInterpolation(GridBase* gr unsigned int dim = grid_pntr->getDimension(); if(dim==1) { return getGridValueWithLinearInterpolation_1D(grid_pntr,arg); - } - else if(dim==2) { + } else if(dim==2) { return getGridValueWithLinearInterpolation_2D(grid_pntr,arg); - } - else { + } else { return getGridValueWithLinearInterpolation_ND(grid_pntr,arg); } } @@ -197,7 +201,8 @@ std::vector> GridLinearInterpolation::getAdjacentIndices(G std::vector temp_indices(2); // double grid_dx = grid_pntr->getDx()[i]; - double grid_min; Tools::convert( grid_pntr->getMin()[i], grid_min); + double grid_min; + Tools::convert( grid_pntr->getMin()[i], grid_min); double xtoindex = (arg[i]-grid_min)/grid_dx; temp_indices[0] = static_cast(std::floor(xtoindex)); temp_indices[1] = static_cast(std::ceil(xtoindex)); diff --git a/src/ves/GridLinearInterpolation.h b/src/ves/GridLinearInterpolation.h index 0b85ef7f10..e6e0f2bcf3 100644 --- a/src/ves/GridLinearInterpolation.h +++ b/src/ves/GridLinearInterpolation.h @@ -55,8 +55,7 @@ double GridLinearInterpolation::linearInterpolation(const double x, const double // https://en.wikipedia.org/wiki/Linear_interpolation if(x1!=x0) { return y0 + (x-x0) * ((y1-y0)/(x1-x0)); - } - else { + } else { return y0; } } diff --git a/src/ves/GridProjWeights.h b/src/ves/GridProjWeights.h index be9679ce64..a1ffbbd4f1 100644 --- a/src/ves/GridProjWeights.h +++ b/src/ves/GridProjWeights.h @@ -32,16 +32,27 @@ namespace ves { class MarginalWeight:public WeightBase { public: explicit MarginalWeight() {} - double projectInnerLoop(double &input, double &v) {return input+v;} - double projectOuterLoop(double &v) {return v;} + double projectInnerLoop(double &input, double &v) { + return input+v; + } + double projectOuterLoop(double &v) { + return v; + } }; class FesWeight:public WeightBase { public: double beta,invbeta; - explicit FesWeight(double v) {beta=v; invbeta=1./beta;} - double projectInnerLoop(double &input, double &v) {return input+exp(-beta*v);} - double projectOuterLoop(double &v) {return -invbeta*std::log(v);} + explicit FesWeight(double v) { + beta=v; + invbeta=1./beta; + } + double projectInnerLoop(double &input, double &v) { + return input+exp(-beta*v); + } + double projectOuterLoop(double &v) { + return -invbeta*std::log(v); + } }; } diff --git a/src/ves/LinearBasisSetExpansion.cpp b/src/ves/LinearBasisSetExpansion.cpp index 5a1446dd6e..d0f5e5fceb 100644 --- a/src/ves/LinearBasisSetExpansion.cpp +++ b/src/ves/LinearBasisSetExpansion.cpp @@ -73,10 +73,11 @@ LinearBasisSetExpansion::LinearBasisSetExpansion( step_of_last_fesgrid_update(-1000), log_targetdist_grid_pntr_(NULL), targetdist_grid_pntr_(NULL), - targetdist_pntr_(NULL) -{ + targetdist_pntr_(NULL) { plumed_massert(args_pntrs_.size()==basisf_pntrs_.size(),"number of arguments and basis functions do not match"); - for(unsigned int k=0; kgetNumberOfBasisFunctions();} + for(unsigned int k=0; kgetNumberOfBasisFunctions(); + } // if(bias_coeffs_pntr_==NULL) { bias_coeffs_pntr_ = new CoeffsVector(label_+".coeffs",args_pntrs_,basisf_pntrs_,mycomm_,true); @@ -89,8 +90,7 @@ LinearBasisSetExpansion::LinearBasisSetExpansion( std::string targetdist_averages_label = bias_coeffs_pntr_->getLabel(); if(targetdist_averages_label.find("coeffs")!=std::string::npos) { targetdist_averages_label.replace(targetdist_averages_label.find("coeffs"), std::string("coeffs").length(), "targetdist_averages"); - } - else { + } else { targetdist_averages_label += "_targetdist_averages"; } targetdist_averages_pntr_->setLabels(targetdist_averages_label); @@ -148,7 +148,9 @@ std::unique_ptr LinearBasisSetExpansion::setupGeneralGrid(const std::strin void LinearBasisSetExpansion::setupBiasGrid(const bool usederiv) { - if(bias_grid_pntr_) {return;} + if(bias_grid_pntr_) { + return; + } bias_grid_pntr_ = setupGeneralGrid("bias",usederiv); if(biasCutoffActive()) { bias_withoutcutoff_grid_pntr_ = setupGeneralGrid("bias_withoutcutoff",usederiv); @@ -157,7 +159,9 @@ void LinearBasisSetExpansion::setupBiasGrid(const bool usederiv) { void LinearBasisSetExpansion::setupFesGrid() { - if(fes_grid_pntr_) {return;} + if(fes_grid_pntr_) { + return; + } if(!bias_grid_pntr_) { setupBiasGrid(true); } @@ -189,8 +193,7 @@ void LinearBasisSetExpansion::updateBiasGrid() { // if(bias_grid_pntr_->hasDerivatives()) { bias_grid_pntr_->setValueAndDerivatives(l,bias,forces); - } - else { + } else { bias_grid_pntr_->setValue(l,bias); } // @@ -219,8 +222,7 @@ void LinearBasisSetExpansion::updateBiasWithoutCutoffGrid() { double bias=getBiasAndForces(args,all_inside,forces); if(bias_withoutcutoff_grid_pntr_->hasDerivatives()) { bias_withoutcutoff_grid_pntr_->setValueAndDerivatives(l,bias,forces); - } - else { + } else { bias_withoutcutoff_grid_pntr_->setValue(l,bias); } } @@ -248,8 +250,7 @@ void LinearBasisSetExpansion::updateBiasWithoutCutoffGrid() { if(bias_withoutcutoff_grid_pntr_->hasDerivatives()) { std::vector zeros(nargs_,0.0); bias_withoutcutoff_grid_pntr_->addValueAndDerivatives(l,shift,zeros); - } - else { + } else { bias_withoutcutoff_grid_pntr_->addValue(l,shift); } } @@ -287,21 +288,27 @@ void LinearBasisSetExpansion::updateFesGrid() { void LinearBasisSetExpansion::writeBiasGridToFile(OFile& ofile, const bool append_file) const { plumed_massert(bias_grid_pntr_,"the bias grid is not defined"); - if(append_file) {ofile.enforceRestart();} + if(append_file) { + ofile.enforceRestart(); + } bias_grid_pntr_->writeToFile(ofile); } void LinearBasisSetExpansion::writeBiasWithoutCutoffGridToFile(OFile& ofile, const bool append_file) const { plumed_massert(bias_withoutcutoff_grid_pntr_,"the bias without cutoff grid is not defined"); - if(append_file) {ofile.enforceRestart();} + if(append_file) { + ofile.enforceRestart(); + } bias_withoutcutoff_grid_pntr_->writeToFile(ofile); } void LinearBasisSetExpansion::writeFesGridToFile(OFile& ofile, const bool append_file) const { plumed_massert(fes_grid_pntr_!=NULL,"the FES grid is not defined"); - if(append_file) {ofile.enforceRestart();} + if(append_file) { + ofile.enforceRestart(); + } fes_grid_pntr_->writeToFile(ofile); } @@ -311,44 +318,62 @@ void LinearBasisSetExpansion::writeFesProjGridToFile(const std::vector(beta_); Grid proj_grid = fes_grid_pntr_->project(proj_arg,Fw.get()); proj_grid.setMinToZero(); - if(append_file) {ofile.enforceRestart();} + if(append_file) { + ofile.enforceRestart(); + } proj_grid.writeToFile(ofile); } void LinearBasisSetExpansion::writeTargetDistGridToFile(OFile& ofile, const bool append_file) const { - if(targetdist_grid_pntr_==NULL) {return;} - if(append_file) {ofile.enforceRestart();} + if(targetdist_grid_pntr_==NULL) { + return; + } + if(append_file) { + ofile.enforceRestart(); + } targetdist_grid_pntr_->writeToFile(ofile); } void LinearBasisSetExpansion::writeLogTargetDistGridToFile(OFile& ofile, const bool append_file) const { - if(log_targetdist_grid_pntr_==NULL) {return;} - if(append_file) {ofile.enforceRestart();} + if(log_targetdist_grid_pntr_==NULL) { + return; + } + if(append_file) { + ofile.enforceRestart(); + } log_targetdist_grid_pntr_->writeToFile(ofile); } void LinearBasisSetExpansion::writeTargetDistProjGridToFile(const std::vector& proj_arg, OFile& ofile, const bool append_file) const { - if(targetdist_grid_pntr_==NULL) {return;} - if(append_file) {ofile.enforceRestart();} + if(targetdist_grid_pntr_==NULL) { + return; + } + if(append_file) { + ofile.enforceRestart(); + } Grid proj_grid = TargetDistribution::getMarginalDistributionGrid(targetdist_grid_pntr_,proj_arg); proj_grid.writeToFile(ofile); } void LinearBasisSetExpansion::writeTargetDistributionToFile(const std::string& filename) const { - OFile of1; OFile of2; + OFile of1; + OFile of2; if(action_pntr_!=NULL) { - of1.link(*action_pntr_); of2.link(*action_pntr_); + of1.link(*action_pntr_); + of2.link(*action_pntr_); } - of1.enforceBackup(); of2.enforceBackup(); + of1.enforceBackup(); + of2.enforceBackup(); of1.open(filename); of2.open(FileBase::appendSuffix(filename,".log")); writeTargetDistGridToFile(of1); writeLogTargetDistGridToFile(of2); - of1.close(); of2.close(); + of1.close(); + of2.close(); } @@ -372,14 +397,15 @@ double LinearBasisSetExpansion::getBiasAndForces(const std::vector& args bool curr_inside=true; basisf_pntrs_in[k]->getAllValues(args_values[k],args_values_trsfrm[k],curr_inside,bf_values[k],bf_derivs[k]); // inside_interval[k]=curr_inside; - if(!curr_inside) {all_inside=false;} + if(!curr_inside) { + all_inside=false; + } forces[k]=0.0; } // size_t stride=1; size_t rank=0; - if(comm_in!=NULL) - { + if(comm_in!=NULL) { stride=comm_in->Get_size(); rank=comm_in->Get_rank(); } @@ -397,8 +423,11 @@ double LinearBasisSetExpansion::getBiasAndForces(const std::vector& args for(unsigned int k=0; k& args_ // size_t stride=1; size_t rank=0; - if(comm_in!=NULL) - { + if(comm_in!=NULL) { stride=comm_in->Get_size(); rank=comm_in->Get_rank(); } @@ -531,9 +559,15 @@ void LinearBasisSetExpansion::setupTargetDistribution(TargetDistribution* target void LinearBasisSetExpansion::updateTargetDistribution() { plumed_massert(targetdist_pntr_!=NULL,"the target distribution hasn't been setup!"); plumed_massert(targetdist_pntr_->isDynamic(),"this should only be used for dynamically updated target distributions!"); - if(targetdist_pntr_->biasGridNeeded()) {updateBiasGrid();} - if(biasCutoffActive()) {updateBiasWithoutCutoffGrid();} - if(targetdist_pntr_->fesGridNeeded()) {updateFesGrid();} + if(targetdist_pntr_->biasGridNeeded()) { + updateBiasGrid(); + } + if(biasCutoffActive()) { + updateBiasWithoutCutoffGrid(); + } + if(targetdist_pntr_->fesGridNeeded()) { + updateFesGrid(); + } targetdist_pntr_->updateTargetDist(); calculateTargetDistAveragesFromGrid(targetdist_grid_pntr_); } @@ -541,14 +575,18 @@ void LinearBasisSetExpansion::updateTargetDistribution() { void LinearBasisSetExpansion::readInRestartTargetDistribution(const std::string& grid_fname) { targetdist_pntr_->readInRestartTargetDistGrid(grid_fname); - if(biasCutoffActive()) {targetdist_pntr_->clearLogTargetDistGrid();} + if(biasCutoffActive()) { + targetdist_pntr_->clearLogTargetDistGrid(); + } } void LinearBasisSetExpansion::restartTargetDistribution() { plumed_massert(targetdist_pntr_!=NULL,"the target distribution hasn't been setup!"); plumed_massert(targetdist_pntr_->isDynamic(),"this should only be used for dynamically updated target distributions!"); - if(biasCutoffActive()) {updateBiasWithoutCutoffGrid();} + if(biasCutoffActive()) { + updateBiasWithoutCutoffGrid(); + } calculateTargetDistAveragesFromGrid(targetdist_grid_pntr_); } @@ -591,8 +629,11 @@ void LinearBasisSetExpansion::setBiasMaximumToZero() { bool LinearBasisSetExpansion::biasCutoffActive() const { - if(vesbias_pntr_!=NULL) {return vesbias_pntr_->biasCutoffActive();} - else {return false;} + if(vesbias_pntr_!=NULL) { + return vesbias_pntr_->biasCutoffActive(); + } else { + return false; + } } @@ -605,7 +646,9 @@ double LinearBasisSetExpansion::calculateReweightFactor() const { for(Grid::index_t l=0; lgetSize(); l++) { sum += integration_weights[l] * targetdist_grid_pntr_->getValue(l) * exp(+beta_*bias_grid_pntr_->getValue(l)); } - if(sum==0.0) sum=std::numeric_limits::min(); + if(sum==0.0) { + sum=std::numeric_limits::min(); + } return (1.0/beta_)*std::log(sum); } diff --git a/src/ves/LinearBasisSetExpansion.h b/src/ves/LinearBasisSetExpansion.h index d57fbae044..ad8fc74e7b 100644 --- a/src/ves/LinearBasisSetExpansion.h +++ b/src/ves/LinearBasisSetExpansion.h @@ -102,20 +102,42 @@ class LinearBasisSetExpansion { public: ~LinearBasisSetExpansion(); // - std::vector getPntrsToArguments() const {return args_pntrs_;} - std::vector getPntrsToBasisFunctions() const {return basisf_pntrs_;} - CoeffsVector* getPntrToBiasCoeffs() const {return bias_coeffs_pntr_;} - Grid* getPntrToBiasGrid() const {return bias_grid_pntr_.get();}; - // - unsigned int getNumberOfArguments() const {return nargs_;}; - std::vector getNumberOfBasisFunctions() const {return nbasisf_;}; - size_t getNumberOfCoeffs() const {return ncoeffs_;}; - // - CoeffsVector& BiasCoeffs() const {return *bias_coeffs_pntr_;}; - CoeffsVector& TargetDistAverages() const {return *targetdist_averages_pntr_;}; - // - void setSerial() {serial_=true;} - void setParallel() {serial_=false;} + std::vector getPntrsToArguments() const { + return args_pntrs_; + } + std::vector getPntrsToBasisFunctions() const { + return basisf_pntrs_; + } + CoeffsVector* getPntrToBiasCoeffs() const { + return bias_coeffs_pntr_; + } + Grid* getPntrToBiasGrid() const { + return bias_grid_pntr_.get(); + }; + // + unsigned int getNumberOfArguments() const { + return nargs_; + }; + std::vector getNumberOfBasisFunctions() const { + return nbasisf_; + }; + size_t getNumberOfCoeffs() const { + return ncoeffs_; + }; + // + CoeffsVector& BiasCoeffs() const { + return *bias_coeffs_pntr_; + }; + CoeffsVector& TargetDistAverages() const { + return *targetdist_averages_pntr_; + }; + // + void setSerial() { + serial_=true; + } + void setParallel() { + serial_=false; + } // void linkVesBias(VesBias*); void linkAction(Action*); @@ -134,15 +156,27 @@ class LinearBasisSetExpansion { // Bias grid and output stuff void setupBiasGrid(const bool usederiv=false); void updateBiasGrid(); - void resetStepOfLastBiasGridUpdate() {step_of_last_biasgrid_update = -1000;} - void setStepOfLastBiasGridUpdate(long long int step) {step_of_last_biasgrid_update = step;} - long long int getStepOfLastBiasGridUpdate() const {return step_of_last_biasgrid_update;} + void resetStepOfLastBiasGridUpdate() { + step_of_last_biasgrid_update = -1000; + } + void setStepOfLastBiasGridUpdate(long long int step) { + step_of_last_biasgrid_update = step; + } + long long int getStepOfLastBiasGridUpdate() const { + return step_of_last_biasgrid_update; + } void writeBiasGridToFile(OFile&, const bool append=false) const; // void updateBiasWithoutCutoffGrid(); - void resetStepOfLastBiasWithoutCutoffGridUpdate() {step_of_last_biaswithoutcutoffgrid_update = -1000;} - void setStepOfLastBiasWithoutCutoffGridUpdate(long long int step) {step_of_last_biaswithoutcutoffgrid_update = step;} - long long int getStepOfLastBiasWithoutCutoffGridUpdate() const {return step_of_last_biaswithoutcutoffgrid_update;} + void resetStepOfLastBiasWithoutCutoffGridUpdate() { + step_of_last_biaswithoutcutoffgrid_update = -1000; + } + void setStepOfLastBiasWithoutCutoffGridUpdate(long long int step) { + step_of_last_biaswithoutcutoffgrid_update = step; + } + long long int getStepOfLastBiasWithoutCutoffGridUpdate() const { + return step_of_last_biaswithoutcutoffgrid_update; + } void writeBiasWithoutCutoffGridToFile(OFile&, const bool append=false) const; // void setBiasMinimumToZero(); @@ -150,9 +184,15 @@ class LinearBasisSetExpansion { // void setupFesGrid(); void updateFesGrid(); - void resetStepOfLastFesGridUpdate() {step_of_last_fesgrid_update = -1000;} - void setStepOfLastFesGridUpdate(long long int step) {step_of_last_fesgrid_update = step;} - long long int getStepOfLastFesGridUpdate() const {return step_of_last_fesgrid_update;} + void resetStepOfLastFesGridUpdate() { + step_of_last_fesgrid_update = -1000; + } + void setStepOfLastFesGridUpdate(long long int step) { + step_of_last_fesgrid_update = step; + } + long long int getStepOfLastFesGridUpdate() const { + return step_of_last_fesgrid_update; + } void writeFesGridToFile(OFile&, const bool append=false) const; // void setupFesProjGrid(); @@ -163,14 +203,24 @@ class LinearBasisSetExpansion { void writeTargetDistProjGridToFile(const std::vector&, OFile&, const bool append=false) const; void writeTargetDistributionToFile(const std::string&) const; // - std::vector getGridBins() const {return grid_bins_;} + std::vector getGridBins() const { + return grid_bins_; + } void setGridBins(const std::vector&); void setGridBins(const unsigned int); // - double getBeta() const {return beta_;} - double getKbT() const {return kbt_;} - double beta() const {return beta_;} - double kBT() const {return kbt_;} + double getBeta() const { + return beta_; + } + double getKbT() const { + return kbt_; + } + double beta() const { + return beta_; + } + double kBT() const { + return kbt_; + } // void setupUniformTargetDistribution(); void setupTargetDistribution(TargetDistribution*); @@ -212,8 +262,7 @@ double LinearBasisSetExpansion::getBias(const std::vector& args_values, std::vector coeffsderivs_values_dummy(ncoeffs_); if(parallel) { return getBiasAndForces(args_values,all_inside,forces_dummy,coeffsderivs_values_dummy,basisf_pntrs_, bias_coeffs_pntr_, &mycomm_); - } - else { + } else { return getBiasAndForces(args_values,all_inside,forces_dummy,coeffsderivs_values_dummy,basisf_pntrs_, bias_coeffs_pntr_, NULL); } } @@ -223,8 +272,7 @@ inline void LinearBasisSetExpansion::getBasisSetValues(const std::vector& args_values, std::vector& basisset_values, const bool parallel) { if(parallel) { getBasisSetValues(args_values,basisset_values,basisf_pntrs_, bias_coeffs_pntr_, &mycomm_); - } - else { + } else { getBasisSetValues(args_values,basisset_values,basisf_pntrs_, bias_coeffs_pntr_, NULL); } } diff --git a/src/ves/MD_LinearExpansionPES.cpp b/src/ves/MD_LinearExpansionPES.cpp index 8d2c60b244..f3c3535236 100644 --- a/src/ves/MD_LinearExpansionPES.cpp +++ b/src/ves/MD_LinearExpansionPES.cpp @@ -134,7 +134,9 @@ PRINT ARG=p.x,p.y,ene FILE=colvar.data FMT=%8.4f class MD_LinearExpansionPES : public PLMD::CLTool { public: - std::string description() const override {return "MD of a one particle on a linear expansion PES";} + std::string description() const override { + return "MD of a one particle on a linear expansion PES"; + } static void registerKeywords( Keywords& keys ); explicit MD_LinearExpansionPES( const CLToolOptions& co ); int main( FILE* in, FILE* out, PLMD::Communicator& pc) override; @@ -177,8 +179,7 @@ void MD_LinearExpansionPES::registerKeywords( Keywords& keys ) { MD_LinearExpansionPES::MD_LinearExpansionPES( const CLToolOptions& co ): CLTool(co), dim(0), - dim_string_prefix("dim") -{ + dim_string_prefix("dim") { inputdata=ifile; //commandline; } @@ -244,11 +245,9 @@ int MD_LinearExpansionPES::main( FILE* in, FILE* out, PLMD::Communicator& pc) { parseVector("temperature",temps_vec); if(temps_vec.size()==1) { temp = temps_vec[0]; - } - else if(replicas > 1 && temps_vec.size()==replicas) { + } else if(replicas > 1 && temps_vec.size()==replicas) { temp = temps_vec[inter.Get_rank()]; - } - else { + } else { error("problem with temperature keyword, you need to give either one value or a value for each replica."); } // @@ -257,11 +256,9 @@ int MD_LinearExpansionPES::main( FILE* in, FILE* out, PLMD::Communicator& pc) { parseVector("friction",frictions_vec); if(frictions_vec.size()==1) { friction = frictions_vec[0]; - } - else if(frictions_vec.size()==replicas) { + } else if(frictions_vec.size()==replicas) { friction = frictions_vec[inter.Get_rank()]; - } - else { + } else { error("problem with friction keyword, you need to give either one value or a value for each replica."); } // @@ -269,19 +266,24 @@ int MD_LinearExpansionPES::main( FILE* in, FILE* out, PLMD::Communicator& pc) { std::vector seeds_vec(0); parseVector("random_seed",seeds_vec); for(unsigned int i=0; i0) {seeds_vec[i] = -seeds_vec[i];} + if(seeds_vec[i]>0) { + seeds_vec[i] = -seeds_vec[i]; + } } if(replicas==1) { - if(seeds_vec.size()>1) {error("problem with random_seed keyword, for a single replica you should only give one value");} + if(seeds_vec.size()>1) { + error("problem with random_seed keyword, for a single replica you should only give one value"); + } seed = seeds_vec[0]; - } - else { + } else { if(seeds_vec.size()!=1 && seeds_vec.size()!=replicas) { error("problem with random_seed keyword, for multiple replicas you should give either one value or a separate value for each replica"); } if(seeds_vec.size()==1) { seeds_vec.resize(replicas); - for(unsigned int i=1; i interval_range(dim); for(unsigned int i=0; i 1 && input_coeffs_fnames.size()==replicas) { + } else if(replicas > 1 && input_coeffs_fnames.size()==replicas) { diff_input_coeffs = true; input_coeffs_fname = input_coeffs_fnames[inter.Get_rank()]; - } - else { + } else { error("problem with coeffs_file keyword, you need to give either one value or a value for each replica."); } coeffs_pntr->readFromFile(input_coeffs_fname,true,true); @@ -392,12 +393,10 @@ int MD_LinearExpansionPES::main( FILE* in, FILE* out, PLMD::Communicator& pc) { double coeffs_prefactor = 1.0; if(coeffs_prefactors.size()==1) { coeffs_prefactor = coeffs_prefactors[0]; - } - else if(replicas > 1 && coeffs_prefactors.size()==replicas) { + } else if(replicas > 1 && coeffs_prefactors.size()==replicas) { diff_input_coeffs = true; coeffs_prefactor = coeffs_prefactors[inter.Get_rank()]; - } - else { + } else { error("problem with coeffs_prefactor keyword, you need to give either one value or a value for each replica."); } coeffs_pntr->scaleAllValues(coeffs_prefactor); @@ -425,7 +424,8 @@ int MD_LinearExpansionPES::main( FILE* in, FILE* out, PLMD::Communicator& pc) { ofile_potential.close(); if(dim>1) { for(unsigned int i=0; i proj_arg(1); proj_arg[0] = dim_string_prefix+is; auto Fw = Tools::make_unique(1/temp); @@ -488,23 +488,33 @@ int MD_LinearExpansionPES::main( FILE* in, FILE* out, PLMD::Communicator& pc) { std::fprintf(out,"Number of steps %llu\n",nsteps); std::fprintf(out,"Timestep %f\n",tstep); std::fprintf(out,"Temperature %f",temps_vec[0]); - for(unsigned int i=1; icmd("setMPIComm",&pc.Get_comm()); + if(Communicator::initialized()) { + plumed->cmd("setMPIComm",&pc.Get_comm()); + } } } @@ -561,16 +573,20 @@ int MD_LinearExpansionPES::main( FILE* in, FILE* out, PLMD::Communicator& pc) { // Setup random number generator random.setSeed(seed); - double potential, therm_eng=0; std::vector masses(1,1); + double potential, therm_eng=0; + std::vector masses(1,1); std::vector positions(1), velocities(1), forces(1); for(unsigned int k=0; kinterval_max[k]) {positions[0][k]=interval_max[k];} - if(positions[0][k]interval_max[k]) { + positions[0][k]=interval_max[k]; + } + if(positions[0][k]interval_max[k]) { positions[0][k]=interval_max[k]; velocities[0][k]=-std::abs(velocities[0][k]); @@ -646,7 +662,9 @@ int MD_LinearExpansionPES::main( FILE* in, FILE* out, PLMD::Communicator& pc) { plumed->cmd("setStopFlag",&plumedWantsToStop); plumed->cmd("calc"); //if(istep%2000==0) plumed->cmd("writeCheckPointFile"); - if(plumedWantsToStop) nsteps=istep; + if(plumedWantsToStop) { + nsteps=istep; + } } // Second step of velocity verlet diff --git a/src/ves/Opt_Adam.cpp b/src/ves/Opt_Adam.cpp index 636704e9fa..07a1293c7b 100644 --- a/src/ves/Opt_Adam.cpp +++ b/src/ves/Opt_Adam.cpp @@ -66,10 +66,14 @@ class Opt_Adam: public Optimizer { }; inline -CoeffsVector& Opt_Adam::VarCoeffs(const unsigned int coeffs_id) const {return *var_coeffs_pntrs_[coeffs_id];} +CoeffsVector& Opt_Adam::VarCoeffs(const unsigned int coeffs_id) const { + return *var_coeffs_pntrs_[coeffs_id]; +} inline -CoeffsVector& Opt_Adam::VarmaxCoeffs(const unsigned int coeffs_id) const {return *varmax_coeffs_pntrs_[coeffs_id];} +CoeffsVector& Opt_Adam::VarmaxCoeffs(const unsigned int coeffs_id) const { + return *varmax_coeffs_pntrs_[coeffs_id]; +} PLUMED_REGISTER_ACTION(Opt_Adam,"OPT_ADAM") @@ -98,8 +102,7 @@ Opt_Adam::Opt_Adam(const ActionOptions&ao): one_minus_weight_decay_(1.0), amsgrad_(false), adamw_(false), - var_coeffs_pntrs_(0) -{ + var_coeffs_pntrs_(0) { // add citation and print it to log log << " Adam type stochastic gradient decent\n"; parseFlag("AMSGRAD",amsgrad_); @@ -173,8 +176,7 @@ void Opt_Adam::coeffsUpdate(const unsigned int c_id) { for (size_t i = 0; i< VarCoeffs(c_id).getSize(); ++i) { var_coeffs_sqrt.push_back(1 / (sqrt(VarCoeffs(c_id).getValue(i)) + epsilon)); } - } - else { // use VarmaxCoffs instead of VarCoeffs + } else { // use VarmaxCoffs instead of VarCoeffs for (size_t i = 0; i< VarmaxCoeffs(c_id).getSize(); ++i) { var_coeffs_sqrt.push_back(1 / (sqrt(VarmaxCoeffs(c_id).getValue(i)) + epsilon)); } diff --git a/src/ves/Opt_BachAveragedSGD.cpp b/src/ves/Opt_BachAveragedSGD.cpp index 6813729417..d015d909f7 100644 --- a/src/ves/Opt_BachAveragedSGD.cpp +++ b/src/ves/Opt_BachAveragedSGD.cpp @@ -187,7 +187,9 @@ class Opt_BachAveragedSGD : public Optimizer { std::vector> combinedgradientOFiles_; double decaying_aver_tau_; private: - CoeffsVector& CombinedGradient(const unsigned int c_id) const {return *combinedgradient_pntrs_[c_id];} + CoeffsVector& CombinedGradient(const unsigned int c_id) const { + return *combinedgradient_pntrs_[c_id]; + } double getAverDecay() const; public: static void registerKeywords(Keywords&); @@ -219,8 +221,7 @@ void Opt_BachAveragedSGD::registerKeywords(Keywords& keys) { Opt_BachAveragedSGD::Opt_BachAveragedSGD(const ActionOptions&ao): PLUMED_VES_OPTIMIZER_INIT(ao), combinedgradient_wstride_(100), - decaying_aver_tau_(0.0) -{ + decaying_aver_tau_(0.0) { log.printf(" Averaged stochastic gradient decent, see and cite "); log << plumed.cite("Bach and Moulines, NIPS 26, 773-781 (2013)"); log.printf("\n"); @@ -245,8 +246,7 @@ Opt_BachAveragedSGD::Opt_BachAveragedSGD(const ActionOptions&ao): std::string label = getGradientPntrs()[i]->getLabel(); if(label.find("gradient")!=std::string::npos) { label.replace(label.find("gradient"), std::string("gradient").length(), "combined_gradient"); - } - else { + } else { label += "_combined"; } combinedgradient_tmp->setLabels(label); @@ -258,8 +258,7 @@ Opt_BachAveragedSGD::Opt_BachAveragedSGD(const ActionOptions&ao): // if(numberOfCoeffsSets()==1) { log.printf(" Combined gradient (gradient + Hessian term) will be written out to file %s every %u iterations\n",combinedgradientOFiles_[0]->getPath().c_str(),combinedgradient_wstride_); - } - else { + } else { log.printf(" Combined gradient (gradient + Hessian term) will be written out to the following files every %u iterations:\n",combinedgradient_wstride_); for(unsigned int i=0; igetPath().c_str()); diff --git a/src/ves/Opt_Dummy.cpp b/src/ves/Opt_Dummy.cpp index 58fa53cd91..cbbab223b8 100644 --- a/src/ves/Opt_Dummy.cpp +++ b/src/ves/Opt_Dummy.cpp @@ -96,8 +96,7 @@ void Opt_Dummy::registerKeywords(Keywords& keys) { Opt_Dummy::Opt_Dummy(const ActionOptions&ao): - PLUMED_VES_OPTIMIZER_INIT(ao) -{ + PLUMED_VES_OPTIMIZER_INIT(ao) { log.printf(" fake optimizer that does not update coefficients\n"); log.printf(" can be used to monitor gradient and Hessian for debugging purposes\n"); bool monitor_hessian = false; @@ -105,8 +104,7 @@ Opt_Dummy::Opt_Dummy(const ActionOptions&ao): if(monitor_hessian) { turnOnHessian(); log.printf(" the Hessian will also be monitored\n"); - } - else { + } else { turnOffHessian(); } turnOffCoeffsOutputFiles(); diff --git a/src/ves/Opt_RobbinsMonroSGD.cpp b/src/ves/Opt_RobbinsMonroSGD.cpp index e045b4d91a..86589dace4 100644 --- a/src/ves/Opt_RobbinsMonroSGD.cpp +++ b/src/ves/Opt_RobbinsMonroSGD.cpp @@ -68,8 +68,7 @@ void Opt_RobbinsMonroSGD::registerKeywords(Keywords& keys) { Opt_RobbinsMonroSGD::Opt_RobbinsMonroSGD(const ActionOptions&ao): PLUMED_VES_OPTIMIZER_INIT(ao), - decay_constant_(1.0) -{ + decay_constant_(1.0) { parse("DECAY_CONSTANT",decay_constant_); if(decay_constant_<1.0) { plumed_merror("the value given in DECAY_CONSTANT doesn't make sense, it should be larger than 1.0"); diff --git a/src/ves/Optimizer.cpp b/src/ves/Optimizer.cpp index a34c62fa26..f3acfd3c06 100644 --- a/src/ves/Optimizer.cpp +++ b/src/ves/Optimizer.cpp @@ -82,8 +82,7 @@ Optimizer::Optimizer(const ActionOptions&ao): targetdist_output_stride_(0), targetdist_proj_output_active_(false), targetdist_proj_output_stride_(0), - isFirstStep(true) -{ + isFirstStep(true) { std::vector bias_labels(0); parseVector("BIAS",bias_labels); plumed_massert(bias_labels.size()>0,"problem with BIAS keyword"); @@ -91,7 +90,9 @@ Optimizer::Optimizer(const ActionOptions&ao): // std::string error_msg = ""; bias_pntrs_ = VesTools::getPointersFromLabels(bias_labels,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword BIAS of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword BIAS of "+getName()+": "+error_msg); + } for(unsigned int i=0; ilinkOptimizer(this); @@ -116,8 +117,7 @@ Optimizer::Optimizer(const ActionOptions&ao): std::string aux_label = pntrs_coeffs[k]->getLabel(); if(aux_label.find("coeffs")!=std::string::npos) { aux_label.replace(aux_label.find("coeffs"), std::string("coeffs").length(), "aux_coeffs"); - } - else { + } else { aux_label += "_aux"; } aux_coeffs_tmp->setLabels(aux_label); @@ -158,11 +158,13 @@ Optimizer::Optimizer(const ActionOptions&ao): log.printf(" KbT: %f\n",bias_pntrs_[0]->getKbT()); log.printf(" number of coefficients: %zu\n",coeffs_pntrs_[0]->numberOfCoeffs()); if(stepsizes_.size()>0) { - if(fixed_stepsize_) {log.printf(" using a constant step size of %f\n",stepsizes_[0]);} - else {log.printf(" using an initial step size of %f\n",stepsizes_[0]);} + if(fixed_stepsize_) { + log.printf(" using a constant step size of %f\n",stepsizes_[0]); + } else { + log.printf(" using an initial step size of %f\n",stepsizes_[0]); + } } - } - else { + } else { log.printf(" optimizing %u coefficient sets from following %u VES biases:\n",ncoeffssets_,nbiases_); for(unsigned int i=0; igetLabel().c_str(),bias_pntrs_[i]->getName().c_str(),bias_pntrs_[i]->getKbT()); @@ -173,16 +175,18 @@ Optimizer::Optimizer(const ActionOptions&ao): log.printf(" used in bias %s (type %s)\n",coeffs_pntrs_[i]->getPntrToAction()->getLabel().c_str(),coeffs_pntrs_[i]->getPntrToAction()->getName().c_str()); log.printf(" number of coefficients: %zu\n",coeffs_pntrs_[i]->numberOfCoeffs()); if(stepsizes_.size()>0) { - if(fixed_stepsize_) {log.printf(" using a constant step size of %f\n",stepsizes_[i]);} - else {log.printf(" using an initial step size of %f\n",stepsizes_[i]);} + if(fixed_stepsize_) { + log.printf(" using a constant step size of %f\n",stepsizes_[i]); + } else { + log.printf(" using an initial step size of %f\n",stepsizes_[i]); + } } tot_ncoeffs += coeffs_pntrs_[i]->numberOfCoeffs(); } log.printf(" total number of coefficients: %zu\n",tot_ncoeffs); if(identical_coeffs_shape_) { log.printf(" the indices shape is identical for all coefficient sets\n"); - } - else { + } else { log.printf(" the indices shape differs between coefficient sets\n"); } } @@ -227,7 +231,9 @@ Optimizer::Optimizer(const ActionOptions&ao): bool need_stride = false; for(unsigned int i=0; idynamicTargetDistribution(); - if(dynamic_targetdists_[i]) {need_stride = true;} + if(dynamic_targetdists_[i]) { + need_stride = true; + } } parse("TARGETDIST_STRIDE",ustride_targetdist_); if(need_stride && ustride_targetdist_==0) { @@ -239,8 +245,7 @@ Optimizer::Optimizer(const ActionOptions&ao): if(ustride_targetdist_>0) { if(nbiases_==1) { log.printf(" the target distribution will be updated very %u coefficient iterations\n",ustride_targetdist_); - } - else { + } else { log.printf(" the target distribution will be updated very %u coefficient iterations for the following biases\n ",ustride_targetdist_); for(unsigned int i=0; igetLabel().c_str()); @@ -287,8 +292,7 @@ Optimizer::Optimizer(const ActionOptions&ao): std::string aver_grad_label = aver_gradient_tmp->getLabel(); if(aver_grad_label.find("gradient")!=std::string::npos) { aver_grad_label.replace(aver_grad_label.find("gradient"), std::string("gradient").length(), "aver_gradient"); - } - else { + } else { aver_grad_label += "_aver"; } aver_gradient_tmp->setLabels(aver_grad_label); @@ -306,8 +310,7 @@ Optimizer::Optimizer(const ActionOptions&ao): if(keywords.exists("COEFFS_SET_ID_PREFIX")) { parse("COEFFS_SET_ID_PREFIX",coeffssetid_prefix_); } - } - else { + } else { coeffssetid_prefix_=""; if(keywords.exists("COEFFS_SET_ID_PREFIX")) { parse("COEFFS_SET_ID_PREFIX",coeffssetid_prefix_); @@ -345,7 +348,9 @@ Optimizer::Optimizer(const ActionOptions&ao): for(unsigned int i=0; igetIterationCounter()); log.printf(" Optimization restarted at iteration %u\n",getIterationCounter()); } @@ -398,15 +402,13 @@ Optimizer::Optimizer(const ActionOptions&ao): if(coeffs_fnames.size()>0) { if(ncoeffssets_==1) { log.printf(" Coefficients will be written out to file %s every %u iterations\n",coeffsOFiles_[0]->getPath().c_str(),coeffs_wstride_); - } - else { + } else { log.printf(" Coefficients will be written out to the following files every %u iterations:\n",coeffs_wstride_); for(unsigned int i=0; igetPath().c_str()); } } - } - else { + } else { log.printf(" Output of coefficients to file has been disabled\n"); } } @@ -432,8 +434,7 @@ Optimizer::Optimizer(const ActionOptions&ao): if(gradient_fnames.size()>0) { if(ncoeffssets_==1) { log.printf(" Gradient will be written out to file %s every %u iterations\n",gradientOFiles_[0]->getPath().c_str(),gradient_wstride_); - } - else { + } else { log.printf(" Gradient will be written out to the following files every %u iterations:\n",gradient_wstride_); for(unsigned int i=0; igetPath().c_str()); @@ -463,8 +464,7 @@ Optimizer::Optimizer(const ActionOptions&ao): if(hessian_fnames.size()>0) { if(ncoeffssets_==1) { log.printf(" Hessian will be written out to file %s every %u iterations\n",hessianOFiles_[0]->getPath().c_str(),hessian_wstride_); - } - else { + } else { log.printf(" Hessian will be written out to the following files every %u iterations:\n",hessian_wstride_); for(unsigned int i=0; igetPath().c_str()); @@ -479,8 +479,11 @@ Optimizer::Optimizer(const ActionOptions&ao): std::vector mask_fnames_in; parseVector("MASK_FILE",mask_fnames_in); if(mask_fnames_in.size()==1 && ncoeffssets_>1) { - if(identical_coeffs_shape_) {mask_fnames_in.resize(ncoeffssets_,mask_fnames_in[0]);} - else {plumed_merror("the coefficients indices shape differs between biases so you need to give a separate file for each coefficient set\n");} + if(identical_coeffs_shape_) { + mask_fnames_in.resize(ncoeffssets_,mask_fnames_in[0]); + } else { + plumed_merror("the coefficients indices shape differs between biases so you need to give a separate file for each coefficient set\n"); + } } if(mask_fnames_in.size()>0 && mask_fnames_in.size()!=ncoeffssets_) { plumed_merror("Error in MASK_FILE keyword: either give one value for all biases or a separate value for each coefficient set"); @@ -500,8 +503,7 @@ Optimizer::Optimizer(const ActionOptions&ao): log.printf(" read %zu values from mask file %s\n",nread,mask_fnames_in[0].c_str()); size_t ndeactived = coeffs_mask_pntrs_[0]->countValues(0.0); log.printf(" deactived optimization of %zu coefficients\n",ndeactived); - } - else { + } else { for(unsigned int i=0; ireadFromFile(mask_fnames_in[i],true,true); log.printf(" mask for coefficient set %u:\n",i); @@ -524,9 +526,13 @@ Optimizer::Optimizer(const ActionOptions&ao): maskOFile.enforceBackup(); if(use_mwalkers_mpi_ && mwalkers_mpi_single_files_) { unsigned int r=0; - if(comm.Get_rank()==0) {r=multi_sim_comm.Get_rank();} + if(comm.Get_rank()==0) { + r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); - if(r>0) {mask_fnames_out[i]="/dev/null";} + if(r>0) { + mask_fnames_out[i]="/dev/null"; + } maskOFile.enforceSuffix(""); } maskOFile.open(mask_fnames_out[i]); @@ -583,8 +589,7 @@ Optimizer::Optimizer(const ActionOptions&ao): if(targetdist_averages_fnames.size()>0 && targetdist_averages_wstride_ > 0) { if(ncoeffssets_==1) { log.printf(" Target distribution averages will be written out to file %s every %u iterations\n",targetdist_averagesOFiles_[0]->getPath().c_str(),targetdist_averages_wstride_); - } - else { + } else { log.printf(" Target distribution averages will be written out to the following files every %u iterations:\n",targetdist_averages_wstride_); for(unsigned int i=0; igetPath().c_str()); @@ -603,8 +608,7 @@ Optimizer::Optimizer(const ActionOptions&ao): bias_pntrs_[i]->setupBiasFileOutput(); bias_pntrs_[i]->writeBiasToFile(); } - } - else { + } else { bias_output_active_=false; bias_output_stride_=1000; } @@ -619,8 +623,7 @@ Optimizer::Optimizer(const ActionOptions&ao): bias_pntrs_[i]->setupFesFileOutput(); bias_pntrs_[i]->writeFesToFile(); } - } - else { + } else { fes_output_active_=false; fes_output_stride_=1000; } @@ -635,8 +638,7 @@ Optimizer::Optimizer(const ActionOptions&ao): bias_pntrs_[i]->setupFesProjFileOutput(); bias_pntrs_[i]->writeFesProjToFile(); } - } - else { + } else { fesproj_output_active_=false; fesproj_output_stride_=1000; } @@ -672,8 +674,7 @@ Optimizer::Optimizer(const ActionOptions&ao): bias_pntrs_[i]->writeTargetDistToFile(); } } - } - else { + } else { targetdist_output_active_=false; targetdist_output_stride_=1000; } @@ -697,8 +698,7 @@ Optimizer::Optimizer(const ActionOptions&ao): bias_pntrs_[i]->writeTargetDistProjToFile(); } } - } - else { + } else { targetdist_proj_output_active_=false; targetdist_proj_output_stride_=1000; } @@ -708,41 +708,52 @@ Optimizer::Optimizer(const ActionOptions&ao): log.printf(" Output Components:\n"); log.printf(" "); if(monitor_instantaneous_gradient_) { - addComponent("gradrms"); componentIsNotPeriodic("gradrms"); + addComponent("gradrms"); + componentIsNotPeriodic("gradrms"); log.printf(" "); - addComponent("gradmax"); componentIsNotPeriodic("gradmax"); + addComponent("gradmax"); + componentIsNotPeriodic("gradmax"); } if(aver_gradient_pntrs_.size()>0) { log.printf(" "); - addComponent("avergradrms"); componentIsNotPeriodic("avergradrms"); + addComponent("avergradrms"); + componentIsNotPeriodic("avergradrms"); log.printf(" "); - addComponent("avergradmax"); componentIsNotPeriodic("avergradmax"); + addComponent("avergradmax"); + componentIsNotPeriodic("avergradmax"); } if(!fixed_stepsize_) { log.printf(" "); - addComponent("stepsize"); componentIsNotPeriodic("stepsize"); + addComponent("stepsize"); + componentIsNotPeriodic("stepsize"); getPntrToComponent("stepsize")->set( getCurrentStepSize(0) ); } - } - else { + } else { for(unsigned int i=0; i0) { log.printf(" "); - addComponent("avergradrms"+is); componentIsNotPeriodic("avergradrms"+is); + addComponent("avergradrms"+is); + componentIsNotPeriodic("avergradrms"+is); log.printf(" "); - addComponent("avergradmax"+is); componentIsNotPeriodic("avergradmax"+is); + addComponent("avergradmax"+is); + componentIsNotPeriodic("avergradmax"+is); } if(!fixed_stepsize_) { log.printf(" "); - addComponent("stepsize"+is); componentIsNotPeriodic("stepsize"+is); + addComponent("stepsize"+is); + componentIsNotPeriodic("stepsize"+is); getPntrToComponent("stepsize"+is)->set( getCurrentStepSize(i) ); } } @@ -926,8 +937,7 @@ void Optimizer::turnOnHessian() { plumed_massert(hessian_pntrs_.size()==ncoeffssets_,"problems in linking Hessians"); if(diagonal_hessian_) { log.printf(" Optimization performed using diagonal Hessian matrix\n"); - } - else { + } else { log.printf(" Optimization performed using full Hessian matrix\n"); } // @@ -991,8 +1001,9 @@ void Optimizer::update() { bias_pntrs_[i]->updateGradientAndHessian(use_mwalkers_mpi_); } for(unsigned int i=0; iisActive()) {coeffsUpdate(i);} - else { + if(gradient_pntrs_[i]->isActive()) { + coeffsUpdate(i); + } else { std::string msg = "iteration " + getIterationCounterStr(+1) + " for " + bias_pntrs_[i]->getLabel() + " - the coefficients are not updated as CV values are outside the bias intervals"; @@ -1049,8 +1060,7 @@ void Optimizer::update() { if(isTargetDistProjOutputActive() && getIterationCounter()%getTargetDistProjOutputStride()==0) { writeTargetDistProjOutputFiles(); } - } - else { + } else { isFirstStep=false; } } @@ -1071,10 +1081,11 @@ void Optimizer::updateOutputComponents() { size_t avergradient_maxabs_idx=0; getPntrToComponent("avergradmax")->set( aver_gradient_pntrs_[0]->getMaxAbsValue(avergradient_maxabs_idx) ); } - } - else { + } else { for(unsigned int i=0; iset( getCurrentStepSize(i) ); } @@ -1105,8 +1116,7 @@ void Optimizer::writeOutputFiles(const unsigned int coeffs_id) { if(gradientOFiles_.size()>0 && iter_counter%gradient_wstride_==0) { if(aver_gradient_pntrs_.size()==0) { gradient_pntrs_[coeffs_id]->writeToFile(*gradientOFiles_[coeffs_id],false); - } - else { + } else { gradient_pntrs_[coeffs_id]->writeToFile(*gradientOFiles_[coeffs_id],aver_gradient_pntrs_[coeffs_id].get(),false); } } @@ -1127,9 +1137,13 @@ void Optimizer::setupOFiles(std::vector& fnames, std::vectorlink(*this); if(multi_sim_single_files) { unsigned int r=0; - if(comm.Get_rank()==0) {r=multi_sim_comm.Get_rank();} + if(comm.Get_rank()==0) { + r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); - if(r>0) {fnames[i]="/dev/null";} + if(r>0) { + fnames[i]="/dev/null"; + } OFiles[i]->enforceSuffix(""); } OFiles[i]->open(fnames[i]); @@ -1143,8 +1157,7 @@ void Optimizer::readCoeffsFromFiles(const std::vector& fnames, cons plumed_assert(fnames.size()==ncoeffssets_); if(ncoeffssets_==1) { log.printf(" Read in coefficients from file "); - } - else { + } else { log.printf(" Read in coefficients from files:\n"); } for(unsigned int i=0; i& fnames, cons size_t ncoeffs_read = coeffs_pntrs_[i]->readFromFile(ifile,false,false); if(ncoeffssets_==1) { log.printf("%s (read %zu of %zu values)\n", ifile.getPath().c_str(),ncoeffs_read,coeffs_pntrs_[i]->numberOfCoeffs()); - } - else { + } else { log.printf(" coefficient set %u: %s (read %zu of %zu values)\n",i,ifile.getPath().c_str(),ncoeffs_read,coeffs_pntrs_[i]->numberOfCoeffs()); } ifile.close(); @@ -1174,8 +1186,7 @@ void Optimizer::readCoeffsFromFiles(const std::vector& fnames, cons } aux_coeffs_pntrs_[i]->readFromFile(ifile,false,false); ifile.close(); - } - else { + } else { AuxCoeffs(i).setValues( Coeffs(i) ); } } @@ -1183,7 +1194,9 @@ void Optimizer::readCoeffsFromFiles(const std::vector& fnames, cons void Optimizer::addCoeffsSetIDsToFilenames(std::vector& fnames, std::string& coeffssetid_prefix) { - if(ncoeffssets_==1) {return;} + if(ncoeffssets_==1) { + return; + } // if(fnames.size()==1) { fnames.resize(ncoeffssets_,fnames[0]); @@ -1191,7 +1204,8 @@ void Optimizer::addCoeffsSetIDsToFilenames(std::vector& fnames, std plumed_assert(fnames.size()==ncoeffssets_); // for(unsigned int i=0; i getStepSizes() const; std::vector getCurrentStepSizes() const; @@ -192,62 +199,126 @@ class Optimizer : void apply() override {}; void calculate() override {}; void update() override; - unsigned int getNumberOfDerivatives() override {return 0;} + unsigned int getNumberOfDerivatives() override { + return 0; + } // - bool fixedStepSize() const {return fixed_stepsize_;} - bool dynamicStepSize() const {return !fixed_stepsize_;} + bool fixedStepSize() const { + return fixed_stepsize_; + } + bool dynamicStepSize() const { + return !fixed_stepsize_; + } // - bool useHessian() const {return use_hessian_;} - bool diagonalHessian() const {return diagonal_hessian_;} + bool useHessian() const { + return use_hessian_; + } + bool diagonalHessian() const { + return diagonal_hessian_; + } // - bool useMultipleWalkers() const {return use_mwalkers_mpi_;} + bool useMultipleWalkers() const { + return use_mwalkers_mpi_; + } // - std::vector getBiasPntrs() const {return bias_pntrs_;} - std::vector getCoeffsPntrs() const {return coeffs_pntrs_;} - std::vector getAuxCoeffsPntrs() const {return Tools::unique2raw(aux_coeffs_pntrs_);} - std::vector getGradientPntrs()const {return gradient_pntrs_;} - std::vector getHessianPntrs() const {return hessian_pntrs_;} - std::vector getCoeffsMaskPntrs() const {return Tools::unique2raw(coeffs_mask_pntrs_);} - std::vector getTargetDistAveragesPntrs() const {return targetdist_averages_pntrs_;} + std::vector getBiasPntrs() const { + return bias_pntrs_; + } + std::vector getCoeffsPntrs() const { + return coeffs_pntrs_; + } + std::vector getAuxCoeffsPntrs() const { + return Tools::unique2raw(aux_coeffs_pntrs_); + } + std::vector getGradientPntrs()const { + return gradient_pntrs_; + } + std::vector getHessianPntrs() const { + return hessian_pntrs_; + } + std::vector getCoeffsMaskPntrs() const { + return Tools::unique2raw(coeffs_mask_pntrs_); + } + std::vector getTargetDistAveragesPntrs() const { + return targetdist_averages_pntrs_; + } // - bool isBiasOutputActive() const {return bias_output_active_;} - unsigned int getBiasOutputStride() const {return bias_output_stride_;} - void setBiasOutputStride(unsigned int stride) {bias_output_stride_=stride;} + bool isBiasOutputActive() const { + return bias_output_active_; + } + unsigned int getBiasOutputStride() const { + return bias_output_stride_; + } + void setBiasOutputStride(unsigned int stride) { + bias_output_stride_=stride; + } void writeBiasOutputFiles() const; // - bool isFesOutputActive() const {return fes_output_active_;} - unsigned int getFesOutputStride() const {return fes_output_stride_;} - void setFesOutputStride(unsigned int stride) {fes_output_stride_=stride;} + bool isFesOutputActive() const { + return fes_output_active_; + } + unsigned int getFesOutputStride() const { + return fes_output_stride_; + } + void setFesOutputStride(unsigned int stride) { + fes_output_stride_=stride; + } void writeFesOutputFiles() const; // - bool isFesProjOutputActive() const {return fesproj_output_active_;} - unsigned int getFesProjOutputStride() const {return fesproj_output_stride_;} - void setFesProjOutputStride(unsigned int stride) {fesproj_output_stride_=stride;} + bool isFesProjOutputActive() const { + return fesproj_output_active_; + } + unsigned int getFesProjOutputStride() const { + return fesproj_output_stride_; + } + void setFesProjOutputStride(unsigned int stride) { + fesproj_output_stride_=stride; + } void writeFesProjOutputFiles() const; // - bool isTargetDistOutputActive() const {return targetdist_output_active_;} - unsigned int getTargetDistOutputStride() const {return targetdist_output_stride_;} - void setTargetDistOutputStride(unsigned int stride) {targetdist_output_stride_=stride;} + bool isTargetDistOutputActive() const { + return targetdist_output_active_; + } + unsigned int getTargetDistOutputStride() const { + return targetdist_output_stride_; + } + void setTargetDistOutputStride(unsigned int stride) { + targetdist_output_stride_=stride; + } void writeTargetDistOutputFiles() const; // - bool isTargetDistProjOutputActive() const {return targetdist_proj_output_active_;} - unsigned int getTargetDistProjOutputStride() const {return targetdist_proj_output_stride_;} - void setTargetDistProjOutputStride(unsigned int stride) {targetdist_proj_output_stride_=stride;} + bool isTargetDistProjOutputActive() const { + return targetdist_proj_output_active_; + } + unsigned int getTargetDistProjOutputStride() const { + return targetdist_proj_output_stride_; + } + void setTargetDistProjOutputStride(unsigned int stride) { + targetdist_proj_output_stride_=stride; + } void writeTargetDistProjOutputFiles() const; // }; inline -double Optimizer::StepSize(const unsigned int coeffs_id) const {return stepsizes_[coeffs_id];} +double Optimizer::StepSize(const unsigned int coeffs_id) const { + return stepsizes_[coeffs_id]; +} inline -CoeffsVector& Optimizer::Coeffs(const unsigned int coeffs_id) const {return *coeffs_pntrs_[coeffs_id];} +CoeffsVector& Optimizer::Coeffs(const unsigned int coeffs_id) const { + return *coeffs_pntrs_[coeffs_id]; +} inline -CoeffsVector& Optimizer::AuxCoeffs(const unsigned int coeffs_id) const {return *aux_coeffs_pntrs_[coeffs_id];} +CoeffsVector& Optimizer::AuxCoeffs(const unsigned int coeffs_id) const { + return *aux_coeffs_pntrs_[coeffs_id]; +} inline -CoeffsVector& Optimizer::Gradient(const unsigned int coeffs_id) const {return *gradient_pntrs_[coeffs_id];} +CoeffsVector& Optimizer::Gradient(const unsigned int coeffs_id) const { + return *gradient_pntrs_[coeffs_id]; +} inline CoeffsMatrix& Optimizer::Hessian(const unsigned int coeffs_id) const { @@ -256,19 +327,29 @@ CoeffsMatrix& Optimizer::Hessian(const unsigned int coeffs_id) const { } inline -CoeffsVector& Optimizer::CoeffsMask(const unsigned int coeffs_id) const {return *coeffs_mask_pntrs_[coeffs_id];} +CoeffsVector& Optimizer::CoeffsMask(const unsigned int coeffs_id) const { + return *coeffs_mask_pntrs_[coeffs_id]; +} inline -std::vector Optimizer::getStepSizes() const {return stepsizes_;} +std::vector Optimizer::getStepSizes() const { + return stepsizes_; +} inline -std::vector Optimizer::getCurrentStepSizes() const {return current_stepsizes;} +std::vector Optimizer::getCurrentStepSizes() const { + return current_stepsizes; +} inline -double Optimizer::getStepSize(const unsigned int coeffs_id) const {return stepsizes_[coeffs_id];} +double Optimizer::getStepSize(const unsigned int coeffs_id) const { + return stepsizes_[coeffs_id]; +} inline -double Optimizer::getCurrentStepSize(const unsigned int coeffs_id) const {return current_stepsizes[coeffs_id];} +double Optimizer::getCurrentStepSize(const unsigned int coeffs_id) const { + return current_stepsizes[coeffs_id]; +} inline void Optimizer::setStepSizes(const std::vector& stepsizes_in) { @@ -293,16 +374,24 @@ void Optimizer::setCurrentStepSizes(const std::vector& current_stepsizes } inline -unsigned int Optimizer::getIterationCounter() const {return iter_counter;} +unsigned int Optimizer::getIterationCounter() const { + return iter_counter; +} inline -double Optimizer::getIterationCounterDbl() const {return static_cast(iter_counter);} +double Optimizer::getIterationCounterDbl() const { + return static_cast(iter_counter); +} inline -void Optimizer::increaseIterationCounter() {iter_counter++;} +void Optimizer::increaseIterationCounter() { + iter_counter++; +} inline -void Optimizer::setIterationCounter(const unsigned int iter_counter_in) {iter_counter = iter_counter_in;} +void Optimizer::setIterationCounter(const unsigned int iter_counter_in) { + iter_counter = iter_counter_in; +} template @@ -317,7 +406,8 @@ bool Optimizer::parseMultipleValues(const std::string& keyword, std::vector& identical_values=true; } if(values.size()>0 && values.size()!=ncoeffssets_) { - std::string s1; Tools::convert(ncoeffssets_,s1); + std::string s1; + Tools::convert(ncoeffssets_,s1); plumed_merror("Error in " + keyword + " keyword: either give 1 common value for all coefficient sets or " + s1 + " separate value for each set"); } return identical_values; diff --git a/src/ves/OutputBasisFunctions.cpp b/src/ves/OutputBasisFunctions.cpp index 0a4231581d..5f47f92f5f 100644 --- a/src/ves/OutputBasisFunctions.cpp +++ b/src/ves/OutputBasisFunctions.cpp @@ -81,8 +81,7 @@ plumed driver --plumed plumed.dat --igro configuration.gro class OutputBasisFunctions : - public Action -{ + public Action { std::vector bf_pntrs; public: explicit OutputBasisFunctions(const ActionOptions&); @@ -116,15 +115,18 @@ void OutputBasisFunctions::registerKeywords(Keywords& keys) { OutputBasisFunctions::OutputBasisFunctions(const ActionOptions&ao): Action(ao), - bf_pntrs(0) -{ + bf_pntrs(0) { std::vector basisset_labels(0); parseVector("BASIS_FUNCTIONS",basisset_labels); - if(basisset_labels.size()>1) {plumed_merror("Only one basis set label allowed in keyword BASIS_FUNCTIONS of "+getName());} + if(basisset_labels.size()>1) { + plumed_merror("Only one basis set label allowed in keyword BASIS_FUNCTIONS of "+getName()); + } std::string error_msg = ""; bf_pntrs = VesTools::getPointersFromLabels(basisset_labels,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword BASIS_FUNCTIONS of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword BASIS_FUNCTIONS of "+getName()+": "+error_msg); + } unsigned int nbins = 1000; parse("GRID_BINS",nbins); @@ -163,10 +165,14 @@ OutputBasisFunctions::OutputBasisFunctions(const ActionOptions&ao): targetdist_pntrs.push_back(NULL); std::string targetdist_label=""; for(int i=1;; i++) { - if(!parseNumbered("TARGET_DISTRIBUTION",i,targetdist_label)) {break;} + if(!parseNumbered("TARGET_DISTRIBUTION",i,targetdist_label)) { + break; + } std::string error_msg = ""; TargetDistribution* pntr_tmp = VesTools::getPointerFromLabel(targetdist_label,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword TARGET_DISTRIBUTION of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword TARGET_DISTRIBUTION of "+getName()+": "+error_msg); + } targetdist_pntrs.push_back(pntr_tmp); } checkRead(); @@ -183,15 +189,17 @@ OutputBasisFunctions::OutputBasisFunctions(const ActionOptions&ao): ofile_values.close(); ofile_derivs.close(); // - std::vector grid_min(1); grid_min[0]=bf_pntrs[0]->intervalMinStr(); - std::vector grid_max(1); grid_max[0]=bf_pntrs[0]->intervalMaxStr(); - std::vector grid_bins(1); grid_bins[0]=nbins; + std::vector grid_min(1); + grid_min[0]=bf_pntrs[0]->intervalMinStr(); + std::vector grid_max(1); + grid_max[0]=bf_pntrs[0]->intervalMaxStr(); + std::vector grid_bins(1); + grid_bins[0]=nbins; std::vector> arguments(1); arguments[0]= Tools::make_unique(nullptr,"arg",false); if(bf_pntrs[0]->arePeriodic() && !ignore_periodicity) { arguments[0]->setDomain(bf_pntrs[0]->intervalMinStr(),bf_pntrs[0]->intervalMaxStr()); - } - else { + } else { arguments[0]->setNotPeriodic(); } @@ -201,7 +209,8 @@ OutputBasisFunctions::OutputBasisFunctions(const ActionOptions&ao): ofile_targetdist_aver.open(fname_targetdist_aver); for(unsigned int i=0; isetupGrids(Tools::unique2raw(arguments),grid_min,grid_max,grid_bins); @@ -212,7 +221,9 @@ OutputBasisFunctions::OutputBasisFunctions(const ActionOptions&ao): std::vector bf_integrals = bf_pntrs[0]->getTargetDistributionIntegrals(targetdist_pntrs[i]); CoeffsVector targetdist_averages = CoeffsVector("aver.targetdist-"+is,Tools::unique2raw(arguments),bf_pntrs,comm,false); targetdist_averages.setValues(bf_integrals); - if(fmt_targetdist_aver.size()>0) {targetdist_averages.setOutputFmt(fmt_targetdist_aver);} + if(fmt_targetdist_aver.size()>0) { + targetdist_averages.setOutputFmt(fmt_targetdist_aver); + } targetdist_averages.writeToFile(ofile_targetdist_aver,true); if(targetdist_pntrs[i]!=NULL) { Grid* targetdist_grid_pntr = targetdist_pntrs[i]->getTargetDistGridPntr(); diff --git a/src/ves/OutputFesBias.cpp b/src/ves/OutputFesBias.cpp index 8a4160b7e1..33ed4c64f1 100644 --- a/src/ves/OutputFesBias.cpp +++ b/src/ves/OutputFesBias.cpp @@ -121,8 +121,7 @@ void OutputFesBias::registerKeywords(Keywords& keys) { OutputFesBias::OutputFesBias(const ActionOptions&ao): - Action(ao) -{ + Action(ao) { std::vector bias_labels; parseVector("BIAS",bias_labels); @@ -132,7 +131,9 @@ OutputFesBias::OutputFesBias(const ActionOptions&ao): std::string error_msg = ""; std::vector bias_pntrs = VesTools::getPointersFromLabels(bias_labels,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword BIAS of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword BIAS of "+getName()+": "+error_msg); + } for(unsigned int i=0; inumberOfCoeffsSets()>1) { diff --git a/src/ves/OutputTargetDistribution.cpp b/src/ves/OutputTargetDistribution.cpp index 8fced37e8e..e7d3286b8c 100644 --- a/src/ves/OutputTargetDistribution.cpp +++ b/src/ves/OutputTargetDistribution.cpp @@ -79,8 +79,7 @@ plumed driver --plumed plumed.dat --igro configuration.gro class OutputTargetDistribution : - public Action -{ + public Action { public: explicit OutputTargetDistribution(const ActionOptions&); void calculate() override {} @@ -105,8 +104,7 @@ void OutputTargetDistribution::registerKeywords(Keywords& keys) { } OutputTargetDistribution::OutputTargetDistribution(const ActionOptions&ao): - Action(ao) -{ + Action(ao) { std::string targetdist_fname; parse("TARGETDIST_FILE",targetdist_fname); @@ -127,7 +125,9 @@ OutputTargetDistribution::OutputTargetDistribution(const ActionOptions&ao): std::vector grid_periodicity(nargs); parseVector("GRID_PERIODICITY",grid_periodicity); - if(grid_periodicity.size()==0) {grid_periodicity.assign(nargs,"NO");} + if(grid_periodicity.size()==0) { + grid_periodicity.assign(nargs,"NO"); + } std::string fmt_grids="%14.9f"; parse("FMT_GRIDS",fmt_grids); @@ -148,23 +148,26 @@ OutputTargetDistribution::OutputTargetDistribution(const ActionOptions&ao): // std::vector> arguments(nargs); for(unsigned int i=0; i < nargs; i++) { - std::string is; Tools::convert(i+1,is); - if(nargs==1) {is="";} + std::string is; + Tools::convert(i+1,is); + if(nargs==1) { + is=""; + } arguments[i]= Tools::make_unique(nullptr,"arg"+is,false); if(grid_periodicity[i]=="YES") { arguments[i]->setDomain(grid_min[i],grid_max[i]); - } - else if(grid_periodicity[i]=="NO") { + } else if(grid_periodicity[i]=="NO") { arguments[i]->setNotPeriodic(); - } - else { + } else { plumed_merror("wrong value given in GRID_PERIODICITY, either specify YES or NO"); } } std::string error_msg = ""; TargetDistribution* targetdist_pntr = VesTools::getPointerFromLabel(targetdist_label,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword TARGET_DISTRIBUTION of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword TARGET_DISTRIBUTION of "+getName()+": "+error_msg); + } // if(targetdist_pntr->isDynamic()) { plumed_merror(getName() + " only works for static target distributions"); diff --git a/src/ves/TD_Chi.cpp b/src/ves/TD_Chi.cpp index c28b515141..679f02fa26 100644 --- a/src/ves/TD_Chi.cpp +++ b/src/ves/TD_Chi.cpp @@ -107,28 +107,39 @@ TD_Chi::TD_Chi(const ActionOptions& ao): minima_(0), sigma_(0), kappa_(0), - normalization_(0) -{ + normalization_(0) { parseVector("MINIMUM",minima_); parseVector("SIGMA",sigma_); for(unsigned int k=0; k kappa_int(0); parseVector("KAPPA",kappa_int); - if(kappa_int.size()==0) {plumed_merror(getName()+": some problem with KAPPA keyword, should given as positive integer larger than 1");} + if(kappa_int.size()==0) { + plumed_merror(getName()+": some problem with KAPPA keyword, should given as positive integer larger than 1"); + } kappa_.resize(kappa_int.size()); for(unsigned int k=0; k(kappa_int[k]); } setDimension(minima_.size()); - if(getDimension()>1) {plumed_merror(getName()+": only defined for one dimension, for multiple dimensions it should be used in combination with the TD_PRODUCT_DISTRIBUTION action.");} - if(sigma_.size()!=getDimension()) {plumed_merror(getName()+": the SIGMA keyword does not match the given dimension in MINIMUM");} - if(kappa_.size()!=getDimension()) {plumed_merror(getName()+": the KAPPA keyword does not match the given dimension in MINIMUM");} + if(getDimension()>1) { + plumed_merror(getName()+": only defined for one dimension, for multiple dimensions it should be used in combination with the TD_PRODUCT_DISTRIBUTION action."); + } + if(sigma_.size()!=getDimension()) { + plumed_merror(getName()+": the SIGMA keyword does not match the given dimension in MINIMUM"); + } + if(kappa_.size()!=getDimension()) { + plumed_merror(getName()+": the KAPPA keyword does not match the given dimension in MINIMUM"); + } normalization_.resize(getDimension()); for(unsigned int k=0; k& argument) const { double value = 1.0; for(unsigned int k=0; k kappa_int(0); parseVector("KAPPA",kappa_int); - if(kappa_int.size()==0) {plumed_merror(getName()+": some problem with KAPPA keyword, should given as positive integer larger than 2");} + if(kappa_int.size()==0) { + plumed_merror(getName()+": some problem with KAPPA keyword, should given as positive integer larger than 2"); + } kappa_.resize(kappa_int.size()); for(unsigned int k=0; k(kappa_int[k]); } setDimension(minima_.size()); - if(getDimension()>1) {plumed_merror(getName()+": only defined for one dimension, for multiple dimensions it should be used in combination with the TD_PRODUCT_DISTRIBUTION action.");} - if(sigma_.size()!=getDimension()) {plumed_merror(getName()+": the SIGMA keyword does not match the given dimension in MINIMUM");} - if(kappa_.size()!=getDimension()) {plumed_merror(getName()+": the KAPPA keyword does not match the given dimension in MINIMUM");} + if(getDimension()>1) { + plumed_merror(getName()+": only defined for one dimension, for multiple dimensions it should be used in combination with the TD_PRODUCT_DISTRIBUTION action."); + } + if(sigma_.size()!=getDimension()) { + plumed_merror(getName()+": the SIGMA keyword does not match the given dimension in MINIMUM"); + } + if(kappa_.size()!=getDimension()) { + plumed_merror(getName()+": the KAPPA keyword does not match the given dimension in MINIMUM"); + } normalization_.resize(getDimension()); for(unsigned int k=0; k& argument) const { double value = 1.0; for(unsigned int k=0; k0) { cv_var_idx_.push_back(cv_idx-1); - } - else if(curr_var==fes_var_str_) { + } else if(curr_var==fes_var_str_) { use_fes_=true; setDynamic(); setFesGridNeeded(); - } - else if(curr_var==kbt_var_str_) { + } else if(curr_var==kbt_var_str_) { use_kbt_=true; - } - else if(curr_var==beta_var_str_) { + } else if(curr_var==beta_var_str_) { use_beta_=true; - } - else { + } else { plumed_merror(getName()+": problem with parsing formula with lepton, cannot recognise the variable "+curr_var); } } @@ -213,7 +207,8 @@ TD_Custom::TD_Custom(const ActionOptions& ao): cv_var_str_.resize(cv_var_idx_.size()); cv_var_lepton_refs_.resize(cv_var_str_.size()); for(unsigned int j=0; j integration_weights = GridIntegrationWeights::getIntegrationWeights(getTargetDistGridPntr()); @@ -269,22 +268,27 @@ void TD_Custom::updateGrid() { for(Grid::index_t l=0; l point = targetDistGrid().getPoint(l); for(unsigned int k=0; kgetValue(l);} + if(fes_var_lepton_ref_) { + *fes_var_lepton_ref_ = getFesGridPntr()->getValue(l); + } } double value = expression.evaluate(); - if(value<0.0 && !isTargetDistGridShiftedToZero()) {plumed_merror(getName()+": The target distribution function gives negative values. You should change the definition of the function used for the target distribution to avoid this. You can also use the SHIFT_TO_ZERO keyword to avoid this problem.");} + if(value<0.0 && !isTargetDistGridShiftedToZero()) { + plumed_merror(getName()+": The target distribution function gives negative values. You should change the definition of the function used for the target distribution to avoid this. You can also use the SHIFT_TO_ZERO keyword to avoid this problem."); + } targetDistGrid().setValue(l,value); norm += integration_weights[l]*value; logTargetDistGrid().setValue(l,-std::log(value)); } if(norm>0.0) { targetDistGrid().scaleAllValuesAndDerivatives(1.0/norm); - } - else if(!isTargetDistGridShiftedToZero()) { + } else if(!isTargetDistGridShiftedToZero()) { plumed_merror(getName()+": The target distribution function cannot be normalized proberly. You should change the definition of the function used for the target distribution to avoid this. You can also use the SHIFT_TO_ZERO keyword to avoid this problem."); } logTargetDistGrid().setMinToZero(); diff --git a/src/ves/TD_Exponential.cpp b/src/ves/TD_Exponential.cpp index e3b1f5107a..58920949d6 100644 --- a/src/ves/TD_Exponential.cpp +++ b/src/ves/TD_Exponential.cpp @@ -97,18 +97,23 @@ void TD_Exponential::registerKeywords(Keywords& keys) { TD_Exponential::TD_Exponential(const ActionOptions& ao): PLUMED_VES_TARGETDISTRIBUTION_INIT(ao), minima_(0), - lambda_(0) -{ + lambda_(0) { parseVector("MINIMUM",minima_); parseVector("LAMBDA",lambda_); for(unsigned int k=0; k1) {plumed_merror(getName()+": only defined for one dimension, for multiple dimensions it should be used in combination with the TD_PRODUCT_DISTRIBUTION action.");} - if(lambda_.size()!=getDimension()) {plumed_merror(getName()+": the LAMBDA keyword does not match the given dimension in MINIMUM");} + if(getDimension()>1) { + plumed_merror(getName()+": only defined for one dimension, for multiple dimensions it should be used in combination with the TD_PRODUCT_DISTRIBUTION action."); + } + if(lambda_.size()!=getDimension()) { + plumed_merror(getName()+": the LAMBDA keyword does not match the given dimension in MINIMUM"); + } checkRead(); } @@ -117,7 +122,9 @@ double TD_Exponential::getValue(const std::vector& argument) const { double value = 1.0; for(unsigned int k=0; k tmp_center; - if(!parseNumberedVector("CENTER",i,tmp_center) ) {break;} + if(!parseNumberedVector("CENTER",i,tmp_center) ) { + break; + } centers_.push_back(tmp_center); } for(unsigned int i=1;; i++) { std::vector tmp_sigma; - if(!parseNumberedVector("SIGMA",i,tmp_sigma) ) {break;} + if(!parseNumberedVector("SIGMA",i,tmp_sigma) ) { + break; + } for(unsigned int k=0; k tmp_lambda; - if(!parseNumberedVector("LAMBDA",i,tmp_lambda) ) {break;} + if(!parseNumberedVector("LAMBDA",i,tmp_lambda) ) { + break; + } for(unsigned int k=0; k tmp_center; - if(!parseNumberedVector("CENTER",i,tmp_center) ) {break;} + if(!parseNumberedVector("CENTER",i,tmp_center) ) { + break; + } centers_.push_back(tmp_center); } for(unsigned int i=1;; i++) { std::vector tmp_sigma; - if(!parseNumberedVector("SIGMA",i,tmp_sigma) ) {break;} + if(!parseNumberedVector("SIGMA",i,tmp_sigma) ) { + break; + } sigmas_.push_back(tmp_sigma); } @@ -235,8 +238,7 @@ TD_Gaussian::TD_Gaussian(const ActionOptions& ao): parseNumberedVector("CORRELATION",(i+1),corr); if(corr.size()>0) { diagonal_ = false; - } - else { + } else { corr.assign(1,0.0); } correlation_[i] = corr; @@ -257,14 +259,20 @@ TD_Gaussian::TD_Gaussian(const ActionOptions& ao): } // parseVector("WEIGHTS",weights_); - if(weights_.size()==0) {weights_.assign(centers_.size(),1.0);} + if(weights_.size()==0) { + weights_.assign(centers_.size(),1.0); + } if(centers_.size()!=weights_.size()) { plumed_merror(getName()+": there has to be as many weights given in WEIGHTS as numbered CENTER keywords"); } // double sum_weights=0.0; - for(unsigned int i=0; i& argument) const { for(unsigned int i=0; i& argument, const for(unsigned int k=0; k1) {plumed_merror(getName()+": only defined for one dimension, for multiple dimensions it should be used in combination with the TD_PRODUCT_DISTRIBUTION action.");} - if(scale_.size()!=getDimension()) {plumed_merror(getName()+": the SCALE keyword does not match the given dimension in MINIMA");} - if(shape_.size()!=getDimension()) {plumed_merror(getName()+": the SHAPE keyword does not match the given dimension in MINIMA");} + if(getDimension()>1) { + plumed_merror(getName()+": only defined for one dimension, for multiple dimensions it should be used in combination with the TD_PRODUCT_DISTRIBUTION action."); + } + if(scale_.size()!=getDimension()) { + plumed_merror(getName()+": the SCALE keyword does not match the given dimension in MINIMA"); + } + if(shape_.size()!=getDimension()) { + plumed_merror(getName()+": the SHAPE keyword does not match the given dimension in MINIMA"); + } normalization_.resize(getDimension()); for(unsigned int k=0; k& argume double arg=(argument[k]-center[k])/scale[k]; double tx; if(shape_[k]!=0.0) { - if( shape_[k]>0 && argument[k] <= (center[k]-scale[k]/shape[k]) ) {return 0.0;} - if( shape_[k]<0 && argument[k] > (center[k]-scale[k]/shape[k]) ) {return 0.0;} + if( shape_[k]>0 && argument[k] <= (center[k]-scale[k]/shape[k]) ) { + return 0.0; + } + if( shape_[k]<0 && argument[k] > (center[k]-scale[k]/shape[k]) ) { + return 0.0; + } tx = pow( (1.0+arg*shape[k]), -1.0/shape[k] ); - } - else { + } else { tx = exp(-arg); } value *= normalization[k] * pow(tx,shape[k]+1.0) * exp(-tx); diff --git a/src/ves/TD_GeneralizedNormal.cpp b/src/ves/TD_GeneralizedNormal.cpp index 29925c27ab..3b373e3dda 100644 --- a/src/ves/TD_GeneralizedNormal.cpp +++ b/src/ves/TD_GeneralizedNormal.cpp @@ -133,26 +133,35 @@ TD_GeneralizedNormal::TD_GeneralizedNormal(const ActionOptions& ao): betas_(0), normalization_(0), weights_(0), - ncenters_(0) -{ + ncenters_(0) { for(unsigned int i=1;; i++) { std::vector tmp_center; - if(!parseNumberedVector("CENTER",i,tmp_center) ) {break;} + if(!parseNumberedVector("CENTER",i,tmp_center) ) { + break; + } centers_.push_back(tmp_center); } for(unsigned int i=1;; i++) { std::vector tmp_alpha; - if(!parseNumberedVector("ALPHA",i,tmp_alpha) ) {break;} + if(!parseNumberedVector("ALPHA",i,tmp_alpha) ) { + break; + } for(unsigned int k=0; k tmp_beta; - if(!parseNumberedVector("BETA",i,tmp_beta) ) {break;} + if(!parseNumberedVector("BETA",i,tmp_beta) ) { + break; + } for(unsigned int k=0; k(nullptr,arglabels[i],false); if(argperiodic[i]) { arguments[i]->setDomain(argmin[i],argmax[i]); - } - else { + } else { arguments[i]->setNotPeriodic(); } } - IFile gridfile; gridfile.open(filename); + IFile gridfile; + gridfile.open(filename); if(has_deriv) { distGrid_=GridBase::create(gridlabel,Tools::unique2raw(arguments),gridfile,false,true,true); - } - else { + } else { distGrid_=GridBase::create(gridlabel,Tools::unique2raw(arguments),gridfile,false,false,false); } gridfile.close(); @@ -190,7 +194,9 @@ TD_Grid::TD_Grid(const ActionOptions& ao): Tools::convert(distGrid_->getMin()[i],minima_[i]); Tools::convert(distGrid_->getMax()[i],maxima_[i]); periodic_[i] = argperiodic[i]; - if(periodic_[i]) {maxima_[i]-=distGrid_->getDx()[i];} + if(periodic_[i]) { + maxima_[i]-=distGrid_->getDx()[i]; + } } } @@ -202,11 +208,9 @@ double TD_Grid::getValue(const std::vector& argument) const { for(unsigned int k=0; k maxima_[k])) { return outside; - } - else if(argument[k] < minima_[k]) { + } else if(argument[k] < minima_[k]) { arg[k] = minima_[k]; - } - else if(argument[k] > maxima_[k]) { + } else if(argument[k] > maxima_[k]) { arg[k] =maxima_[k]; } } diff --git a/src/ves/TD_LinearCombination.cpp b/src/ves/TD_LinearCombination.cpp index 3ba559433f..d9072f5add 100644 --- a/src/ves/TD_LinearCombination.cpp +++ b/src/ves/TD_LinearCombination.cpp @@ -166,35 +166,52 @@ TD_LinearCombination::TD_LinearCombination(const ActionOptions& ao): distribution_pntrs_(0), grid_pntrs_(0), weights_(0), - ndist_(0) -{ + ndist_(0) { std::vector targetdist_labels; parseVector("DISTRIBUTIONS",targetdist_labels); std::string error_msg = ""; distribution_pntrs_ = VesTools::getPointersFromLabels(targetdist_labels,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword DISTRIBUTIONS of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword DISTRIBUTIONS of "+getName()+": "+error_msg); + } for(unsigned int i=0; iisDynamic()) {setDynamic();} - if(distribution_pntrs_[i]->fesGridNeeded()) {setFesGridNeeded();} - if(distribution_pntrs_[i]->biasGridNeeded()) {setBiasGridNeeded();} + if(distribution_pntrs_[i]->isDynamic()) { + setDynamic(); + } + if(distribution_pntrs_[i]->fesGridNeeded()) { + setFesGridNeeded(); + } + if(distribution_pntrs_[i]->biasGridNeeded()) { + setBiasGridNeeded(); + } } ndist_ = distribution_pntrs_.size(); grid_pntrs_.assign(ndist_,NULL); - if(ndist_==0) {plumed_merror(getName()+ ": no distributions are given.");} - if(ndist_==1) {plumed_merror(getName()+ ": giving only one distribution does not make sense.");} + if(ndist_==0) { + plumed_merror(getName()+ ": no distributions are given."); + } + if(ndist_==1) { + plumed_merror(getName()+ ": giving only one distribution does not make sense."); + } // parseVector("WEIGHTS",weights_); - if(weights_.size()==0) {weights_.assign(distribution_pntrs_.size(),1.0);} + if(weights_.size()==0) { + weights_.assign(distribution_pntrs_.size(),1.0); + } if(distribution_pntrs_.size()!=weights_.size()) { plumed_merror(getName()+ ": there has to be as many weights given in WEIGHTS as the number of target distribution labels given in DISTRIBUTIONS"); } // double sum_weights=0.0; - for(unsigned int i=0; igetValue(l); } - if(value==0.0) value=std::numeric_limits::denorm_min(); + if(value==0.0) { + value=std::numeric_limits::denorm_min(); + } targetDistGrid().setValue(l,value); logTargetDistGrid().setValue(l,-std::log(value)); } diff --git a/src/ves/TD_Multicanonical.cpp b/src/ves/TD_Multicanonical.cpp index 823e2d37a1..bce46dcbd5 100644 --- a/src/ves/TD_Multicanonical.cpp +++ b/src/ves/TD_Multicanonical.cpp @@ -178,8 +178,7 @@ TD_Multicanonical::TD_Multicanonical(const ActionOptions& ao): sigma_(0.0), steps_temp_(20), epsilon_(10.0), - smoothening_(true) -{ + smoothening_(true) { log.printf(" Multicanonical target distribution"); log.printf("\n"); log.printf(" Please read and cite "); @@ -197,11 +196,17 @@ TD_Multicanonical::TD_Multicanonical(const ActionOptions& ao): parse("MAX_TEMP",max_temp_); log.printf(" temperatures between %f and %f will be explored \n",min_temp_,max_temp_); parseVector("SIGMA",sigma_); - if(sigma_.size()==0) smoothening_=false; - if(smoothening_ && (sigma_.size()<1 || sigma_.size()>2) ) plumed_merror(getName()+": SIGMA takes 1 or 2 values as input."); + if(sigma_.size()==0) { + smoothening_=false; + } + if(smoothening_ && (sigma_.size()<1 || sigma_.size()>2) ) { + plumed_merror(getName()+": SIGMA takes 1 or 2 values as input."); + } if (smoothening_) { log.printf(" the target distribution will be smoothed using sigma values"); - for(unsigned i=0; i& argument) const { void TD_Multicanonical::updateGrid() { if (getStep() == 0) { - if(targetDistGrid().getDimension()>2 || targetDistGrid().getDimension()<1) plumed_merror(getName()+" works only with 1 or 2 arguments, i.e. energy, or energy and CV"); - if(smoothening_ && sigma_.size()!=targetDistGrid().getDimension()) plumed_merror(getName()+": mismatch between SIGMA dimension and number of arguments"); + if(targetDistGrid().getDimension()>2 || targetDistGrid().getDimension()<1) { + plumed_merror(getName()+" works only with 1 or 2 arguments, i.e. energy, or energy and CV"); + } + if(smoothening_ && sigma_.size()!=targetDistGrid().getDimension()) { + plumed_merror(getName()+": mismatch between SIGMA dimension and number of arguments"); + } // Use uniform TD std::vector integration_weights = GridIntegrationWeights::getIntegrationWeights(getTargetDistGridPntr()); double norm = 0.0; @@ -342,14 +351,18 @@ void TD_Multicanonical::updateGrid() { double value = 1.0; double tmp; if(argument < minimum) { - if (smoothening_) tmp = GaussianSwitchingFunc(argument,minimum,sigma_[0]); - else tmp = exp(-1.0*epsilon_); - } - else if(argument > maximum) { - if (smoothening_) tmp = GaussianSwitchingFunc(argument,maximum,sigma_[0]); - else tmp = exp(-1.0*epsilon_); - } - else { + if (smoothening_) { + tmp = GaussianSwitchingFunc(argument,minimum,sigma_[0]); + } else { + tmp = exp(-1.0*epsilon_); + } + } else if(argument > maximum) { + if (smoothening_) { + tmp = GaussianSwitchingFunc(argument,maximum,sigma_[0]); + } else { + tmp = exp(-1.0*epsilon_); + } + } else { tmp = 1.0; } value *= tmp; @@ -415,16 +428,28 @@ void TD_Multicanonical::updateGrid() { deltaBin[1]=std::floor(6*sigma_[1]/dx[1]);; // For energy minBin[0]=i - deltaBin[0]; - if (minBin[0] < 0) minBin[0]=0; - if (minBin[0] > (nbin[0]-1)) minBin[0]=nbin[0]-1; + if (minBin[0] < 0) { + minBin[0]=0; + } + if (minBin[0] > (nbin[0]-1)) { + minBin[0]=nbin[0]-1; + } maxBin[0]=i + deltaBin[0]; - if (maxBin[0] > (nbin[0]-1)) maxBin[0]=nbin[0]-1; + if (maxBin[0] > (nbin[0]-1)) { + maxBin[0]=nbin[0]-1; + } // For volume minBin[1]=j - deltaBin[1]; - if (minBin[1] < 0) minBin[1]=0; - if (minBin[1] > (nbin[1]-1)) minBin[1]=nbin[1]-1; + if (minBin[1] < 0) { + minBin[1]=0; + } + if (minBin[1] > (nbin[1]-1)) { + minBin[1]=nbin[1]-1; + } maxBin[1]=j + deltaBin[1]; - if (maxBin[1] > (nbin[1]-1)) maxBin[1]=nbin[1]-1; + if (maxBin[1] > (nbin[1]-1)) { + maxBin[1]=nbin[1]-1; + } for(unsigned l=minBin[0]; l indices_prime(2); @@ -453,7 +478,9 @@ void TD_Multicanonical::updateGrid() { norm += integration_weights[l]*value; } targetDistGrid().scaleAllValuesAndDerivatives(1.0/norm); - } else plumed_merror(getName()+": Number of arguments for this target distribution must be 1 or 2"); + } else { + plumed_merror(getName()+": Number of arguments for this target distribution must be 1 or 2"); + } } updateLogTargetDistGrid(); } @@ -463,8 +490,7 @@ double TD_Multicanonical::GaussianSwitchingFunc(const double argument, const dou if(sigma>0.0) { double arg=(argument-center)/sigma; return exp(-0.5*arg*arg); - } - else { + } else { return 0.0; } } diff --git a/src/ves/TD_MultithermalMultibaric.cpp b/src/ves/TD_MultithermalMultibaric.cpp index a060c6df24..5c031eb10c 100644 --- a/src/ves/TD_MultithermalMultibaric.cpp +++ b/src/ves/TD_MultithermalMultibaric.cpp @@ -256,8 +256,7 @@ TD_MultithermalMultibaric::TD_MultithermalMultibaric(const ActionOptions& ao): epsilon_(10.0), smoothening_(true), steps_temp_(20), - steps_pressure_(20) -{ + steps_pressure_(20) { log.printf(" Multithermal-multibaric target distribution"); log.printf("\n"); @@ -282,11 +281,17 @@ TD_MultithermalMultibaric::TD_MultithermalMultibaric(const ActionOptions& ao): parse("PRESSURE",press_); log.printf(" pressure of the barostat should have been set to %f. Please check this in the MD engine \n",press_); parseVector("SIGMA",sigma_); - if(sigma_.size()==0) smoothening_=false; - if(smoothening_ && (sigma_.size()<2 || sigma_.size()>3) ) plumed_merror(getName()+": SIGMA takes 2 or 3 values as input."); + if(sigma_.size()==0) { + smoothening_=false; + } + if(smoothening_ && (sigma_.size()<2 || sigma_.size()>3) ) { + plumed_merror(getName()+": SIGMA takes 2 or 3 values as input."); + } if (smoothening_) { log.printf(" the target distribution will be smoothed using sigma values"); - for(unsigned i=0; i& argument) void TD_MultithermalMultibaric::updateGrid() { if (getStep() == 0) { - if(targetDistGrid().getDimension()>3 || targetDistGrid().getDimension()<2) plumed_merror(getName()+" works only with 2 or 3 arguments, i.e. energy and volume, or energy, volume, and CV"); - if(smoothening_ && sigma_.size()!=targetDistGrid().getDimension()) plumed_merror(getName()+": mismatch between SIGMA dimension and number of arguments"); + if(targetDistGrid().getDimension()>3 || targetDistGrid().getDimension()<2) { + plumed_merror(getName()+" works only with 2 or 3 arguments, i.e. energy and volume, or energy, volume, and CV"); + } + if(smoothening_ && sigma_.size()!=targetDistGrid().getDimension()) { + plumed_merror(getName()+": mismatch between SIGMA dimension and number of arguments"); + } // Use uniform TD std::vector integration_weights = GridIntegrationWeights::getIntegrationWeights(getTargetDistGridPntr()); double norm = 0.0; @@ -379,10 +388,16 @@ void TD_MultithermalMultibaric::updateGrid() { for(unsigned k=0; k (nbin[k]-1)) minBin[k]=nbin[k]-1; + if (minBin[k] < 0) { + minBin[k]=0; + } + if (minBin[k] > (nbin[k]-1)) { + minBin[k]=nbin[k]-1; + } maxBin[k]=indices[k] + deltaBin; - if (maxBin[k] > (nbin[k]-1)) maxBin[k]=nbin[k]-1; + if (maxBin[k] > (nbin[k]-1)) { + maxBin[k]=nbin[k]-1; + } } if (dim==2) { for(unsigned l=minBin[0]; l0.0) { double arg=(argument-center)/sigma; return exp(-0.5*arg*arg); - } - else { + } else { return 0.0; } } diff --git a/src/ves/TD_ProductCombination.cpp b/src/ves/TD_ProductCombination.cpp index 746a28d73c..0ab72722cb 100644 --- a/src/ves/TD_ProductCombination.cpp +++ b/src/ves/TD_ProductCombination.cpp @@ -152,25 +152,36 @@ TD_ProductCombination::TD_ProductCombination(const ActionOptions& ao): PLUMED_VES_TARGETDISTRIBUTION_INIT(ao), distribution_pntrs_(0), grid_pntrs_(0), - ndist_(0) -{ + ndist_(0) { std::vector targetdist_labels; parseVector("DISTRIBUTIONS",targetdist_labels); std::string error_msg = ""; distribution_pntrs_ = VesTools::getPointersFromLabels(targetdist_labels,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword DISTRIBUTIONS of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword DISTRIBUTIONS of "+getName()+": "+error_msg); + } for(unsigned int i=0; iisDynamic()) {setDynamic();} - if(distribution_pntrs_[i]->fesGridNeeded()) {setFesGridNeeded();} - if(distribution_pntrs_[i]->biasGridNeeded()) {setBiasGridNeeded();} + if(distribution_pntrs_[i]->isDynamic()) { + setDynamic(); + } + if(distribution_pntrs_[i]->fesGridNeeded()) { + setFesGridNeeded(); + } + if(distribution_pntrs_[i]->biasGridNeeded()) { + setBiasGridNeeded(); + } } ndist_ = distribution_pntrs_.size(); grid_pntrs_.assign(ndist_,NULL); - if(ndist_==0) {plumed_merror(getName()+ ": no distributions are given.");} - if(ndist_==1) {plumed_merror(getName()+ ": giving only one distribution does not make sense.");} + if(ndist_==0) { + plumed_merror(getName()+ ": no distributions are given."); + } + if(ndist_==1) { + plumed_merror(getName()+ ": giving only one distribution does not make sense."); + } // checkRead(); } @@ -204,7 +215,9 @@ void TD_ProductCombination::updateGrid() { for(unsigned int i=0; igetValue(l); } - if(value<0.0 && !isTargetDistGridShiftedToZero()) {plumed_merror(getName()+": The target distribution function gives negative values. You should change the definition of the target distribution to avoid this. You can also use the SHIFT_TO_ZERO keyword to avoid this problem.");} + if(value<0.0 && !isTargetDistGridShiftedToZero()) { + plumed_merror(getName()+": The target distribution function gives negative values. You should change the definition of the target distribution to avoid this. You can also use the SHIFT_TO_ZERO keyword to avoid this problem."); + } norm += integration_weights[l]*value; targetDistGrid().setValue(l,value); logTargetDistGrid().setValue(l,-std::log(value)); @@ -212,8 +225,7 @@ void TD_ProductCombination::updateGrid() { if(norm>0.0) { targetDistGrid().scaleAllValuesAndDerivatives(1.0/norm); - } - else if(!isTargetDistGridShiftedToZero()) { + } else if(!isTargetDistGridShiftedToZero()) { plumed_merror(getName()+": The target distribution function cannot be normalized proberly. You should change the definition of the target distribution to avoid this. You can also use the SHIFT_TO_ZERO keyword to avoid this problem."); } logTargetDistGrid().setMinToZero(); diff --git a/src/ves/TD_ProductDistribution.cpp b/src/ves/TD_ProductDistribution.cpp index 083538baa5..393c7a3b92 100644 --- a/src/ves/TD_ProductDistribution.cpp +++ b/src/ves/TD_ProductDistribution.cpp @@ -116,19 +116,26 @@ TD_ProductDistribution::TD_ProductDistribution(const ActionOptions& ao): PLUMED_VES_TARGETDISTRIBUTION_INIT(ao), distribution_pntrs_(0), grid_pntrs_(0), - ndist_(0) -{ + ndist_(0) { std::vector targetdist_labels; parseVector("DISTRIBUTIONS",targetdist_labels); std::string error_msg = ""; distribution_pntrs_ = VesTools::getPointersFromLabels(targetdist_labels,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword DISTRIBUTIONS of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword DISTRIBUTIONS of "+getName()+": "+error_msg); + } for(unsigned int i=0; iisDynamic()) {setDynamic();} - if(distribution_pntrs_[i]->fesGridNeeded()) {setFesGridNeeded();} - if(distribution_pntrs_[i]->biasGridNeeded()) {setBiasGridNeeded();} + if(distribution_pntrs_[i]->isDynamic()) { + setDynamic(); + } + if(distribution_pntrs_[i]->fesGridNeeded()) { + setFesGridNeeded(); + } + if(distribution_pntrs_[i]->biasGridNeeded()) { + setBiasGridNeeded(); + } } ndist_ = distribution_pntrs_.size(); diff --git a/src/ves/TD_Uniform.cpp b/src/ves/TD_Uniform.cpp index 8b40a63723..96373d2199 100644 --- a/src/ves/TD_Uniform.cpp +++ b/src/ves/TD_Uniform.cpp @@ -208,43 +208,53 @@ TD_Uniform::TD_Uniform(const ActionOptions& ao): minima_(0), maxima_(0), sigma_min_(0), - sigma_max_(0) -{ + sigma_max_(0) { parseVector("MINIMA",minima_); parseVector("MAXIMA",maxima_); parseVector("SIGMA_MINIMA",sigma_min_); parseVector("SIGMA_MAXIMA",sigma_max_); - if(minima_.size()==0 && sigma_min_.size()>0) {plumed_merror(getName()+": you cannot give SIGMA_MINIMA if MINIMA is not given");} - if(maxima_.size()==0 && sigma_max_.size()>0) {plumed_merror(getName()+": you cannot give SIGMA_MAXIMA if MAXIMA is not given");} + if(minima_.size()==0 && sigma_min_.size()>0) { + plumed_merror(getName()+": you cannot give SIGMA_MINIMA if MINIMA is not given"); + } + if(maxima_.size()==0 && sigma_max_.size()>0) { + plumed_merror(getName()+": you cannot give SIGMA_MAXIMA if MAXIMA is not given"); + } if(minima_.size()>0 && maxima_.size()>0) { // both MINIMA and MAXIMA given, do all checks - if(minima_.size()!=maxima_.size()) {plumed_merror(getName()+": MINIMA and MAXIMA do not have the same number of values.");} + if(minima_.size()!=maxima_.size()) { + plumed_merror(getName()+": MINIMA and MAXIMA do not have the same number of values."); + } setDimension(minima_.size()); for(unsigned int k=0; kmaxima_[k]) { plumed_merror(getName()+": error in MINIMA and MAXIMA keywords, one of the MINIMA values is larger than the corresponding MAXIMA values"); } } - } - else if(minima_.size()>0 && maxima_.size()==0) { + } else if(minima_.size()>0 && maxima_.size()==0) { // only MINIMA given, MAXIMA assigned later on. setDimension(minima_.size()); - } - else if(maxima_.size()>0 && minima_.size()==0) { + } else if(maxima_.size()>0 && minima_.size()==0) { // only MAXIMA given, MINIMA assigned later on. setDimension(maxima_.size()); - } - else if(maxima_.size()==0 && minima_.size()==0) { + } else if(maxima_.size()==0 && minima_.size()==0) { // neither MAXIMA nor MINIMA givenm, both assigned later on. setDimension(0); } - if(sigma_min_.size()==0) {sigma_min_.assign(getDimension(),0.0);} - if(sigma_max_.size()==0) {sigma_max_.assign(getDimension(),0.0);} - if(sigma_min_.size()!=getDimension()) {plumed_merror(getName()+": SIGMA_MINIMA has the wrong number of values");} - if(sigma_max_.size()!=getDimension()) {plumed_merror(getName()+": SIGMA_MAXIMA has the wrong number of values");} + if(sigma_min_.size()==0) { + sigma_min_.assign(getDimension(),0.0); + } + if(sigma_max_.size()==0) { + sigma_max_.assign(getDimension(),0.0); + } + if(sigma_min_.size()!=getDimension()) { + plumed_merror(getName()+": SIGMA_MINIMA has the wrong number of values"); + } + if(sigma_max_.size()!=getDimension()) { + plumed_merror(getName()+": SIGMA_MAXIMA has the wrong number of values"); + } // setForcedNormalization(); checkRead(); @@ -255,12 +265,16 @@ void TD_Uniform::setupAdditionalGrids(const std::vector& arguments, cons if(minima_.size()==0) { minima_.assign(getDimension(),0.0); - for(unsigned int k=0; k& argument) const { double tmp; if(argument[k] < minima_[k]) { tmp = GaussianSwitchingFunc(argument[k],minima_[k],sigma_min_[k]); - } - else if(argument[k] > maxima_[k]) { + } else if(argument[k] > maxima_[k]) { tmp = GaussianSwitchingFunc(argument[k],maxima_[k],sigma_max_[k]); - } - else { + } else { tmp = 1.0; } value *= tmp; @@ -290,8 +302,7 @@ double TD_Uniform::GaussianSwitchingFunc(const double argument, const double cen if(sigma>0.0) { double arg=(argument-center)/sigma; return exp(-0.5*arg*arg); - } - else { + } else { return 0.0; } } diff --git a/src/ves/TD_VonMises.cpp b/src/ves/TD_VonMises.cpp index d14f2d890c..dbf1ed1b18 100644 --- a/src/ves/TD_VonMises.cpp +++ b/src/ves/TD_VonMises.cpp @@ -131,16 +131,19 @@ TD_VonMises::TD_VonMises(const ActionOptions& ao): normalization_(0), weights_(0), periods_(0), - ncenters_(0) -{ + ncenters_(0) { for(unsigned int i=1;; i++) { std::vector tmp_center; - if(!parseNumberedVector("CENTER",i,tmp_center) ) {break;} + if(!parseNumberedVector("CENTER",i,tmp_center) ) { + break; + } centers_.push_back(tmp_center); } for(unsigned int i=1;; i++) { std::vector tmp_sigma; - if(!parseNumberedVector("SIGMA",i,tmp_sigma) ) {break;} + if(!parseNumberedVector("SIGMA",i,tmp_sigma) ) { + break; + } sigmas_.push_back(tmp_sigma); } // @@ -154,8 +157,12 @@ TD_VonMises::TD_VonMises(const ActionOptions& ao): // // check centers and sigmas for(unsigned int i=0; i arg(1); arg[0]= points[l]; + std::vector arg(1); + arg[0]= points[l]; sum += weights[l] * VonMisesDiagonal(arg,centers,kappas,periods,norm); } return 1.0/sum; diff --git a/src/ves/TD_WellTempered.cpp b/src/ves/TD_WellTempered.cpp index 7d921b2830..a7096eaacf 100644 --- a/src/ves/TD_WellTempered.cpp +++ b/src/ves/TD_WellTempered.cpp @@ -121,8 +121,7 @@ void TD_WellTempered::registerKeywords(Keywords& keys) { TD_WellTempered::TD_WellTempered(const ActionOptions& ao): PLUMED_VES_TARGETDISTRIBUTION_INIT(ao), - bias_factor_(0.0) -{ + bias_factor_(0.0) { log.printf(" Well-tempered target distribution, see and cite "); log << plumed.cite("Valsson and Parrinello, J. Chem. Theory Comput. 11, 1996-2002 (2015)"); log << plumed.cite("Barducci, Bussi, and Parrinello, Phys. Rev. Lett. 100, 020603 (2008)"); diff --git a/src/ves/TargetDistribution.cpp b/src/ves/TargetDistribution.cpp index 805ed5e7c1..d3ded1be13 100644 --- a/src/ves/TargetDistribution.cpp +++ b/src/ves/TargetDistribution.cpp @@ -65,8 +65,7 @@ TargetDistribution::TargetDistribution(const ActionOptions&ao): fes_grid_pntr_(NULL), static_grid_calculated(false), allow_bias_cutoff_(true), - bias_cutoff_active_(false) -{ + bias_cutoff_active_(false) { // if(keywords.exists("WELLTEMPERED_FACTOR")) { double welltempered_factor=0.0; @@ -75,8 +74,7 @@ TargetDistribution::TargetDistribution(const ActionOptions&ao): if(welltempered_factor>0.0) { auto pntr = Tools::make_unique(welltempered_factor); targetdist_modifer_pntrs_.emplace_back(std::move(pntr)); - } - else if(welltempered_factor<0.0) { + } else if(welltempered_factor<0.0) { plumed_merror(getName()+": negative value in WELLTEMPERED_FACTOR does not make sense"); } } @@ -84,7 +82,9 @@ TargetDistribution::TargetDistribution(const ActionOptions&ao): if(keywords.exists("SHIFT_TO_ZERO")) { parseFlag("SHIFT_TO_ZERO",shift_targetdist_to_zero_); if(shift_targetdist_to_zero_) { - if(bias_cutoff_active_) {plumed_merror(getName()+": using SHIFT_TO_ZERO with bias cutoff is not allowed.");} + if(bias_cutoff_active_) { + plumed_merror(getName()+": using SHIFT_TO_ZERO with bias cutoff is not allowed."); + } check_nonnegative_=false; } } @@ -93,7 +93,9 @@ TargetDistribution::TargetDistribution(const ActionOptions&ao): bool force_normalization=false; parseFlag("NORMALIZE",force_normalization); if(force_normalization) { - if(shift_targetdist_to_zero_) {plumed_merror(getName()+" with label "+getLabel()+": using NORMALIZE with SHIFT_TO_ZERO is not needed, the target distribution will be automatically normalized.");} + if(shift_targetdist_to_zero_) { + plumed_merror(getName()+" with label "+getLabel()+": using NORMALIZE with SHIFT_TO_ZERO is not needed, the target distribution will be automatically normalized."); + } setForcedNormalization(); } } @@ -175,12 +177,13 @@ void TargetDistribution::setupGrids(const std::vector& arguments, const void TargetDistribution::calculateStaticDistributionGrid() { - if(static_grid_calculated && !bias_cutoff_active_) {return;} + if(static_grid_calculated && !bias_cutoff_active_) { + return; + } // plumed_massert(isStatic(),"this should only be used for static distributions"); plumed_massert(targetdist_grid_pntr_,"the grids have not been setup using setupGrids"); plumed_massert(log_targetdist_grid_pntr_,"the grids have not been setup using setupGrids"); - for(Grid::index_t l=0; lgetSize(); l++) - { + for(Grid::index_t l=0; lgetSize(); l++) { std::vector argument = targetdist_grid_pntr_->getPoint(l); double value = getValue(argument); targetdist_grid_pntr_->setValue(l,value); @@ -216,7 +219,9 @@ Grid TargetDistribution::getMarginalDistributionGrid(Grid* grid_pntr, const std: std::vector args_index(0); for(unsigned int i=0; i 1.0+normalization_thrshold) { - std::string norm_str; Tools::convert(normalization,norm_str); + std::string norm_str; + Tools::convert(normalization,norm_str); std::string msg = "the target distribution grid is not proberly normalized, integrating over the grid gives: " + norm_str + " - You can avoid this problem by using the NORMALIZE keyword"; warning(msg); } @@ -270,13 +282,16 @@ void TargetDistribution::updateTargetDist() { const double nonnegative_thrshold = -0.02; double grid_min_value = targetdist_grid_pntr_->getMinValue(); if(grid_min_value integration_weights = GridIntegrationWeights::getIntegrationWeights(targetdist_grid_pntr_.get()); double norm = 0.0; - for(Grid::index_t l=0; lgetSize(); l++) - { + for(Grid::index_t l=0; lgetSize(); l++) { double value = targetdist_grid_pntr_->getValue(l); double bias = getBiasWithoutCutoffGridPntr()->getValue(l); double deriv_factor_swf = 0.0; @@ -315,8 +329,7 @@ void TargetDistribution::applyTargetDistModiferToGrid(TargetDistModifer* modifer // std::vector integration_weights = GridIntegrationWeights::getIntegrationWeights(targetdist_grid_pntr_.get()); double norm = 0.0; - for(Grid::index_t l=0; lgetSize(); l++) - { + for(Grid::index_t l=0; lgetSize(); l++) { double value = targetdist_grid_pntr_->getValue(l); std::vector cv_values = targetdist_grid_pntr_->getPoint(l); value = modifer_pntr->getModifedTargetDistValue(value,cv_values); @@ -330,8 +343,7 @@ void TargetDistribution::applyTargetDistModiferToGrid(TargetDistModifer* modifer void TargetDistribution::updateLogTargetDistGrid() { - for(Grid::index_t l=0; lgetSize(); l++) - { + for(Grid::index_t l=0; lgetSize(); l++) { log_targetdist_grid_pntr_->setValue(l,-std::log(targetdist_grid_pntr_->getValue(l))); } log_targetdist_grid_pntr_->setMinToZero(); @@ -366,16 +378,18 @@ void TargetDistribution::clearLogTargetDistGrid() { void TargetDistribution::checkNanAndInf() { - for(Grid::index_t l=0; lgetSize(); l++) - { + for(Grid::index_t l=0; lgetSize(); l++) { double value = targetdist_grid_pntr_->getValue(l); if(std::isnan(value) || std::isinf(value)) { - std::string vs; Tools::convert(value,vs); + std::string vs; + Tools::convert(value,vs); std::vector p = targetdist_grid_pntr_->getPoint(l); - std::string ps; Tools::convert(p[0],ps); + std::string ps; + Tools::convert(p[0],ps); ps = "(" + ps; for(unsigned int k=1; k1) { plumed_merror(getName()+" with label "+getLabel()+": multiple target distribution labels not allowed"); } - } - else if(keywords.exists("TARGET_DISTRIBUTIONS")) { + } else if(keywords.exists("TARGET_DISTRIBUTIONS")) { parseVector("TARGET_DISTRIBUTIONS",targetdist_labels); } std::string error_msg = ""; targetdist_pntrs_ = VesTools::getPointersFromLabels(targetdist_labels,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Problem with target distribution in "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Problem with target distribution in "+getName()+": "+error_msg); + } for(unsigned int i=0; ilinkVesBias(this); @@ -180,7 +180,9 @@ VesBias::VesBias(const ActionOptions&ao): if(keywords.exists("PROJ_ARG")) { std::vector proj_arg; for(int i=1;; i++) { - if(!parseNumberedVector("PROJ_ARG",i,proj_arg)) {break;} + if(!parseNumberedVector("PROJ_ARG",i,proj_arg)) { + break; + } // checks if(proj_arg.size() > (getNumberOfArguments()-1) ) { plumed_merror("PROJ_ARG must be a subset of ARG"); @@ -195,7 +197,8 @@ VesBias::VesBias(const ActionOptions&ao): } } if(!found) { - std::string s1; Tools::convert(i,s1); + std::string s1; + Tools::convert(i,s1); std::string error = "PROJ_ARG" + s1 + ": label " + proj_arg[k] + " is not among the arguments given in ARG"; plumed_merror(error); } @@ -208,7 +211,8 @@ VesBias::VesBias(const ActionOptions&ao): if(keywords.exists("CALC_REWEIGHT_FACTOR")) { parseFlag("CALC_REWEIGHT_FACTOR",calc_reweightfactor_); if(calc_reweightfactor_) { - addComponent("rct"); componentIsNotPeriodic("rct"); + addComponent("rct"); + componentIsNotPeriodic("rct"); updateReweightFactor(); } } @@ -376,8 +380,7 @@ bool VesBias::readCoeffsFromFiles() { plumed_massert(coeffs_fnames.size()==ncoeffssets_,"COEFFS keyword is of the wrong size"); if(ncoeffssets_==1) { log.printf(" Read in coefficients from file "); - } - else { + } else { log.printf(" Read in coefficients from files:\n"); } for(unsigned int i=0; isetIterationCounterAndTime(0,getTime()); if(ncoeffssets_==1) { log.printf("%s (read %zu of %zu values)\n", ifile.getPath().c_str(),ncoeffs_read,coeffs_pntrs_[i]->numberOfCoeffs()); - } - else { + } else { log.printf(" coefficient %u: %s (read %zu of %zu values)\n",i,ifile.getPath().c_str(),ncoeffs_read,coeffs_pntrs_[i]->numberOfCoeffs()); } ifile.close(); @@ -411,7 +413,9 @@ void VesBias::updateGradientAndHessian(const bool use_mwalkers_mpi) { comm.Sum(sampled_cross_averages[k]); if(use_mwalkers_mpi) { double walker_weight=1.0; - if(aver_counters[k]==0) {walker_weight=0.0;} + if(aver_counters[k]==0) { + walker_weight=0.0; + } multiSimSumAverages(k,walker_weight); } // NOTE: this assumes that all walkers have the same TargetDist, might change later on!! @@ -435,7 +439,9 @@ void VesBias::updateGradientAndHessian(const bool use_mwalkers_mpi) { // is zero unsigned int total_samples = aver_counters[k]; if(use_mwalkers_mpi) { - if(comm.Get_rank()==0) {multi_sim_comm.Sum(total_samples);} + if(comm.Get_rank()==0) { + multi_sim_comm.Sum(total_samples); + } comm.Bcast(total_samples,0); } if(total_samples==0) { @@ -468,7 +474,9 @@ void VesBias::multiSimSumAverages(const unsigned int c_id, const double walker_w multi_sim_comm.Sum(sampled_cross_averages[c_id]); double norm_weights = walker_weight; multi_sim_comm.Sum(norm_weights); - if(norm_weights>0.0) {norm_weights=1.0/norm_weights;} + if(norm_weights>0.0) { + norm_weights=1.0/norm_weights; + } for(size_t i=0; igetIterationCounter(); - } - else { + } else { iteration = getCoeffsPntrs()[0]->getIterationCounter(); } return iteration; @@ -556,8 +563,7 @@ void VesBias::linkOptimizer(Optimizer* optimizer_pntr_in) { // if(optimizer_pntr_==NULL) { optimizer_pntr_ = optimizer_pntr_in; - } - else { + } else { std::string err_msg = "VES bias " + getLabel() + " of type " + getName() + " has already been linked with optimizer " + optimizer_pntr_->getLabel() + " of type " + optimizer_pntr_->getName() + ". You cannot link two optimizer to the same VES bias."; plumed_merror(err_msg); } @@ -612,12 +618,18 @@ std::unique_ptr VesBias::getOFile(const std::string& filepath, const bool auto ofile_pntr = Tools::make_unique(); std::string fp = filepath; ofile_pntr->link(*static_cast(this)); - if(enforce_backup) {ofile_pntr->enforceBackup();} + if(enforce_backup) { + ofile_pntr->enforceBackup(); + } if(multi_sim_single_file) { unsigned int r=0; - if(comm.Get_rank()==0) {r=multi_sim_comm.Get_rank();} + if(comm.Get_rank()==0) { + r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); - if(r>0) {fp="/dev/null";} + if(r>0) { + fp="/dev/null"; + } ofile_pntr->enforceSuffix(""); } ofile_pntr->open(fp); @@ -695,9 +707,12 @@ void VesBias::setupBiasCutoff(const double bias_cutoff_value, const double fermi // double fermi_exp_max = 100.0; // - std::string str_bias_cutoff_value; VesTools::convertDbl2Str(bias_cutoff_value,str_bias_cutoff_value); - std::string str_fermi_lambda; VesTools::convertDbl2Str(fermi_lambda,str_fermi_lambda); - std::string str_fermi_exp_max; VesTools::convertDbl2Str(fermi_exp_max,str_fermi_exp_max); + std::string str_bias_cutoff_value; + VesTools::convertDbl2Str(bias_cutoff_value,str_bias_cutoff_value); + std::string str_fermi_lambda; + VesTools::convertDbl2Str(fermi_lambda,str_fermi_lambda); + std::string str_fermi_exp_max; + VesTools::convertDbl2Str(fermi_exp_max,str_fermi_exp_max); std::string swfunc_keywords = "FERMI R_0=" + str_bias_cutoff_value + " FERMI_LAMBDA=" + str_fermi_lambda + " FERMI_EXP_MAX=" + str_fermi_exp_max; // std::string swfunc_errors=""; diff --git a/src/ves/VesBias.h b/src/ves/VesBias.h index c7c0ec0ff3..5b2f891dc0 100644 --- a/src/ves/VesBias.h +++ b/src/ves/VesBias.h @@ -58,8 +58,7 @@ to include functions related to the variational approach. */ class VesBias: - public bias::Bias -{ + public bias::Bias { private: unsigned int ncoeffssets_; std::vector> coeffs_pntrs_; @@ -134,7 +133,9 @@ class VesBias: void addCoeffsSet(std::unique_ptr); // std::string getCoeffsSetLabelString(const std::string&, const unsigned int coeffs_id = 0) const; - void clearCoeffsPntrsVector() {coeffs_pntrs_.clear();} + void clearCoeffsPntrsVector() { + coeffs_pntrs_.clear(); + } void addToSampledAverages(const std::vector&, const unsigned int c_id = 0); void setTargetDistAverages(const std::vector&, const unsigned int coeffs_id = 0); void setTargetDistAverages(const CoeffsVector&, const unsigned int coeffs_id= 0); @@ -161,39 +162,83 @@ class VesBias: static void useProjectionArgKeywords(Keywords&); static void useReweightFactorKeywords(Keywords&); // - std::vector getCoeffsPntrs() const {return Tools::unique2raw(coeffs_pntrs_);} - std::vector getTargetDistAveragesPntrs() const {return Tools::unique2raw(targetdist_averages_pntrs_);} - std::vector getGradientPntrs()const {return Tools::unique2raw(gradient_pntrs_);} - std::vector getHessianPntrs() const {return Tools::unique2raw(hessian_pntrs_);} - std::vector getTargetDistributionPntrs() const {return targetdist_pntrs_;} + std::vector getCoeffsPntrs() const { + return Tools::unique2raw(coeffs_pntrs_); + } + std::vector getTargetDistAveragesPntrs() const { + return Tools::unique2raw(targetdist_averages_pntrs_); + } + std::vector getGradientPntrs()const { + return Tools::unique2raw(gradient_pntrs_); + } + std::vector getHessianPntrs() const { + return Tools::unique2raw(hessian_pntrs_); + } + std::vector getTargetDistributionPntrs() const { + return targetdist_pntrs_; + } // - CoeffsVector* getCoeffsPntr(const unsigned int coeffs_id = 0) const {return coeffs_pntrs_[coeffs_id].get();} - CoeffsVector* getTargetDistAveragesPntr(const unsigned int coeffs_id = 0) const {return targetdist_averages_pntrs_[coeffs_id].get();} - CoeffsVector* getGradientPntr(const unsigned int coeffs_id = 0)const {return gradient_pntrs_[coeffs_id].get();} - CoeffsMatrix* getHessianPntr(const unsigned int coeffs_id = 0) const {return hessian_pntrs_[coeffs_id].get();} + CoeffsVector* getCoeffsPntr(const unsigned int coeffs_id = 0) const { + return coeffs_pntrs_[coeffs_id].get(); + } + CoeffsVector* getTargetDistAveragesPntr(const unsigned int coeffs_id = 0) const { + return targetdist_averages_pntrs_[coeffs_id].get(); + } + CoeffsVector* getGradientPntr(const unsigned int coeffs_id = 0)const { + return gradient_pntrs_[coeffs_id].get(); + } + CoeffsMatrix* getHessianPntr(const unsigned int coeffs_id = 0) const { + return hessian_pntrs_[coeffs_id].get(); + } // - unsigned int getNumberOfTargetDistributionPntrs() const {return targetdist_pntrs_.size();} + unsigned int getNumberOfTargetDistributionPntrs() const { + return targetdist_pntrs_.size(); + } // - size_t numberOfCoeffs(const unsigned int coeffs_id = 0) const {return coeffs_pntrs_[coeffs_id]->numberOfCoeffs();} - size_t totalNumberOfCoeffs() const {return ncoeffs_total_;} - unsigned int numberOfCoeffsSets() const {return ncoeffssets_;} - double getKbT() const {return kbt_;} + size_t numberOfCoeffs(const unsigned int coeffs_id = 0) const { + return coeffs_pntrs_[coeffs_id]->numberOfCoeffs(); + } + size_t totalNumberOfCoeffs() const { + return ncoeffs_total_; + } + unsigned int numberOfCoeffsSets() const { + return ncoeffssets_; + } + double getKbT() const { + return kbt_; + } double getBeta() const; // - CoeffsVector& Coeffs(const unsigned int coeffs_id = 0) const {return *coeffs_pntrs_[coeffs_id];} - CoeffsVector& TargetDistAverages(const unsigned int coeffs_id = 0) const {return *targetdist_averages_pntrs_[coeffs_id];} - CoeffsVector& Gradient(const unsigned int coeffs_id = 0) const {return *gradient_pntrs_[coeffs_id];} - CoeffsMatrix& Hessian(const unsigned int coeffs_id = 0) const {return *hessian_pntrs_[coeffs_id];} + CoeffsVector& Coeffs(const unsigned int coeffs_id = 0) const { + return *coeffs_pntrs_[coeffs_id]; + } + CoeffsVector& TargetDistAverages(const unsigned int coeffs_id = 0) const { + return *targetdist_averages_pntrs_[coeffs_id]; + } + CoeffsVector& Gradient(const unsigned int coeffs_id = 0) const { + return *gradient_pntrs_[coeffs_id]; + } + CoeffsMatrix& Hessian(const unsigned int coeffs_id = 0) const { + return *hessian_pntrs_[coeffs_id]; + } // size_t getCoeffsIndex(const std::vector& indices, const unsigned int coeffs_id = 0) const; std::vector getCoeffsIndices(const size_t index, const unsigned int coeffs_id = 0) const; size_t getHessianIndex(const size_t index1, const size_t index2, const unsigned int coeffs_id = 0) const; // - bool computeHessian() const {return compute_hessian_;} - bool diagonalHessian() const {return diagonal_hessian_;} + bool computeHessian() const { + return compute_hessian_; + } + bool diagonalHessian() const { + return diagonal_hessian_; + } // - bool optimizeCoeffs() const {return optimize_coeffs_;} - Optimizer* getOptimizerPntr() const {return optimizer_pntr_;} + bool optimizeCoeffs() const { + return optimize_coeffs_; + } + Optimizer* getOptimizerPntr() const { + return optimizer_pntr_; + } bool useMultipleWalkers() const; // unsigned int getIterationCounter() const; @@ -208,66 +253,142 @@ class VesBias: void enableHessian(const bool diagonal_hessian=true); void disableHessian(); // - void enableMultipleCoeffsSets() {use_multiple_coeffssets_=true;} + void enableMultipleCoeffsSets() { + use_multiple_coeffssets_=true; + } // - void enableDynamicTargetDistribution() {dynamic_targetdist_=true;} - void disableDynamicTargetDistribution() {dynamic_targetdist_=false;} - bool dynamicTargetDistribution() const {return dynamic_targetdist_;} + void enableDynamicTargetDistribution() { + dynamic_targetdist_=true; + } + void disableDynamicTargetDistribution() { + dynamic_targetdist_=false; + } + bool dynamicTargetDistribution() const { + return dynamic_targetdist_; + } // - std::vector getGridBins() const {return grid_bins_;} + std::vector getGridBins() const { + return grid_bins_; + } void setGridBins(const std::vector&); void setGridBins(const unsigned int); - std::vector getGridMax() const {return grid_max_;} + std::vector getGridMax() const { + return grid_max_; + } void setGridMax(const std::vector&); - std::vector getGridMin() const {return grid_min_;} + std::vector getGridMin() const { + return grid_min_; + } void setGridMin(const std::vector&); // - bool filenamesIncludeIterationNumber() const {return filenames_have_iteration_number_;} - void enableIterationNumberInFilenames() {filenames_have_iteration_number_=true;} + bool filenamesIncludeIterationNumber() const { + return filenames_have_iteration_number_; + } + void enableIterationNumberInFilenames() { + filenames_have_iteration_number_=true; + } // std::string getIterationFilenameSuffix() const; std::string getCoeffsSetFilenameSuffix(const unsigned int coeffs_id) const; std::string getCurrentOutputFilename(const std::string&, const std::string& suffix="") const; - std::string getBiasOutputFilename() const {return bias_filename_;} + std::string getBiasOutputFilename() const { + return bias_filename_; + } std::string getCurrentBiasOutputFilename(const std::string& suffix="") const; - std::string getFesOutputFilename() const {return fes_filename_;} + std::string getFesOutputFilename() const { + return fes_filename_; + } std::string getCurrentFesOutputFilename(const std::string& suffix="") const; - std::string getTargetDistOutputFilename() const {return targetdist_filename_;} + std::string getTargetDistOutputFilename() const { + return targetdist_filename_; + } std::string getCurrentTargetDistOutputFilename(const std::string& suffix="") const; // - void enableBiasFileOutput() {bias_fileoutput_active_=true;} - void disableBiasFileOutput() {bias_fileoutput_active_=false;} - bool isBiasFileOutputActive() const {return bias_fileoutput_active_;} - std::string getBiasFileFmt() const {return bias_file_fmt_;} + void enableBiasFileOutput() { + bias_fileoutput_active_=true; + } + void disableBiasFileOutput() { + bias_fileoutput_active_=false; + } + bool isBiasFileOutputActive() const { + return bias_fileoutput_active_; + } + std::string getBiasFileFmt() const { + return bias_file_fmt_; + } // - void enableFesFileOutput() {fes_fileoutput_active_=true;} - void disableFesFileOutput() {fes_fileoutput_active_=false;} - bool isFesFileOutputActive() const {return fes_fileoutput_active_;} - std::string getFesFileFmt() const {return fes_file_fmt_;} + void enableFesFileOutput() { + fes_fileoutput_active_=true; + } + void disableFesFileOutput() { + fes_fileoutput_active_=false; + } + bool isFesFileOutputActive() const { + return fes_fileoutput_active_; + } + std::string getFesFileFmt() const { + return fes_file_fmt_; + } // - void enableFesProjFileOutput() {fesproj_fileoutput_active_=true;} - void disableFesFileProjOutput() {fesproj_fileoutput_active_=false;} - bool isFesProjFileOutputActive() const {return fesproj_fileoutput_active_;} + void enableFesProjFileOutput() { + fesproj_fileoutput_active_=true; + } + void disableFesFileProjOutput() { + fesproj_fileoutput_active_=false; + } + bool isFesProjFileOutputActive() const { + return fesproj_fileoutput_active_; + } // - void enableDynamicTargetDistFileOutput() {dynamic_targetdist_fileoutput_active_=true;} - void disableDynamicTargetDistFileOutput() {dynamic_targetdist_fileoutput_active_=false;} - bool isDynamicTargetDistFileOutputActive() const {return dynamic_targetdist_fileoutput_active_;} - std::string getTargetDistFileFmt() const {return targetdist_file_fmt_;} - std::string getTargetDistRestartFileFmt() const {return targetdist_restart_file_fmt_;} + void enableDynamicTargetDistFileOutput() { + dynamic_targetdist_fileoutput_active_=true; + } + void disableDynamicTargetDistFileOutput() { + dynamic_targetdist_fileoutput_active_=false; + } + bool isDynamicTargetDistFileOutputActive() const { + return dynamic_targetdist_fileoutput_active_; + } + std::string getTargetDistFileFmt() const { + return targetdist_file_fmt_; + } + std::string getTargetDistRestartFileFmt() const { + return targetdist_restart_file_fmt_; + } // - void enableStaticTargetDistFileOutput() {static_targetdist_fileoutput_active_=true;} - void disableStaticTargetDistFileOutput() {static_targetdist_fileoutput_active_=false;} - bool isStaticTargetDistFileOutputActive() const {return static_targetdist_fileoutput_active_;} + void enableStaticTargetDistFileOutput() { + static_targetdist_fileoutput_active_=true; + } + void disableStaticTargetDistFileOutput() { + static_targetdist_fileoutput_active_=false; + } + bool isStaticTargetDistFileOutputActive() const { + return static_targetdist_fileoutput_active_; + } // - std::vector< std::vector > getProjectionArguments() const {return projection_args_;} - std::vector getProjectionArgument(unsigned int i) const {return projection_args_[i];} - unsigned int getNumberOfProjectionArguments() const {return projection_args_.size();} + std::vector< std::vector > getProjectionArguments() const { + return projection_args_; + } + std::vector getProjectionArgument(unsigned int i) const { + return projection_args_[i]; + } + unsigned int getNumberOfProjectionArguments() const { + return projection_args_.size(); + } // void setupBiasCutoff(const double, const double); - bool biasCutoffActive() const {return bias_cutoff_active_;} - double getBiasCutoffValue() const {return bias_cutoff_value_;} - void setCurrentBiasMaxValue(const double max_value) {bias_current_max_value=max_value;} - double getCurrentBiasMaxValue() const {return bias_current_max_value;} + bool biasCutoffActive() const { + return bias_cutoff_active_; + } + double getBiasCutoffValue() const { + return bias_cutoff_value_; + } + void setCurrentBiasMaxValue(const double max_value) { + bias_current_max_value=max_value; + } + double getCurrentBiasMaxValue() const { + return bias_current_max_value; + } double getBiasCutoffSwitchingFunction(const double, double&) const; double getBiasCutoffSwitchingFunction(const double) const; void applyBiasCutoff(double&, std::vector&) const; @@ -297,18 +418,26 @@ class VesBias: // void updateReweightFactor(); virtual double calculateReweightFactor() const; - bool isReweightFactorCalculated() const {return calc_reweightfactor_;} + bool isReweightFactorCalculated() const { + return calc_reweightfactor_; + } }; inline -size_t VesBias::getCoeffsIndex(const std::vector& indices, const unsigned int coeffs_id) const {return coeffs_pntrs_[coeffs_id]->getIndex(indices);} +size_t VesBias::getCoeffsIndex(const std::vector& indices, const unsigned int coeffs_id) const { + return coeffs_pntrs_[coeffs_id]->getIndex(indices); +} inline -std::vector VesBias::getCoeffsIndices(const size_t index, const unsigned int coeffs_id) const {return coeffs_pntrs_[coeffs_id]->getIndices(index);} +std::vector VesBias::getCoeffsIndices(const size_t index, const unsigned int coeffs_id) const { + return coeffs_pntrs_[coeffs_id]->getIndices(index); +} inline -size_t VesBias::getHessianIndex(const size_t index1, const size_t index2, const unsigned int coeffs_id) const {return hessian_pntrs_[coeffs_id]->getMatrixIndex(index1,index2);} +size_t VesBias::getHessianIndex(const size_t index1, const size_t index2, const unsigned int coeffs_id) const { + return hessian_pntrs_[coeffs_id]->getMatrixIndex(index1,index2); +} inline @@ -392,7 +521,8 @@ bool VesBias::parseMultipleValues(const std::string& keyword, std::vector& va identical_values=true; } if(values.size()>0 && values.size()!=nvalues) { - std::string s1; Tools::convert(nvalues,s1); + std::string s1; + Tools::convert(nvalues,s1); plumed_merror("Error in " + keyword + " keyword: either give 1 common parameter value or " + s1 + " separate parameter values"); } return identical_values; diff --git a/src/ves/VesDeltaF.cpp b/src/ves/VesDeltaF.cpp index b5b19be940..854f2732fc 100644 --- a/src/ves/VesDeltaF.cpp +++ b/src/ves/VesDeltaF.cpp @@ -220,8 +220,7 @@ VesDeltaF::VesDeltaF(const ActionOptions&ao) , afterCalculate_(false) , mean_counter_(0) , av_counter_(0) - , work_(0) -{ + , work_(0) { //set beta const double Kb=getKBoltzmann(); double KbT=getkBT(); @@ -234,11 +233,11 @@ VesDeltaF::VesDeltaF(const ActionOptions&ao) std::string funcl="file.free"; //typical name given by sum_hills std::vector fes_names; - for(unsigned n=0;; n++)//NB: here we start from FILE_F0 not from FILE_F1 - { + for(unsigned n=0;; n++) { //NB: here we start from FILE_F0 not from FILE_F1 std::string filename; - if(!parseNumbered("FILE_F",n,filename)) + if(!parseNumbered("FILE_F",n,filename)) { break; + } fes_names.push_back(filename); IFile gridfile; gridfile.open(filename); @@ -257,8 +256,7 @@ VesDeltaF::VesDeltaF(const ActionOptions&ao) alpha_size_=grid_p_.size()-1; sym_alpha_size_=alpha_size_*(alpha_size_+1)/2; //useful for symmetric matrix [alpha_size_]x[alpha_size_] //check for consistency with first local free energy - for(unsigned n=1; ngetSize()==grid_p_[0]->getSize(),error_tag); plumed_massert(grid_p_[n]->getMin()==grid_p_[0]->getMin(),error_tag); @@ -268,10 +266,10 @@ VesDeltaF::VesDeltaF(const ActionOptions&ao) bool no_mintozero=false; parseFlag("NO_MINTOZERO",no_mintozero); - if(!no_mintozero) - { - for(unsigned n=0; nsetMinToZero(); + } } bool normalize=false; parseFlag("NORMALIZE",normalize); @@ -280,20 +278,18 @@ VesDeltaF::VesDeltaF(const ActionOptions&ao) //convert the FESs to probability distributions //NB: the spline interpolation will be done on the probability distributions, not on the given FESs const unsigned ncv=getNumberOfArguments(); //just for ease - for(unsigned n=0; ngetSize(); t++) - { + for(unsigned n=0; ngetSize(); t++) { std::vector der(ncv); const double val=std::exp(-beta_*grid_p_[n]->getValueAndDerivatives(t,der)); - for(unsigned s=0; ssetValueAndDerivatives(t,val,der); norm_[n]+=val; } c_norm[n]=1./beta_*std::log(norm_[n]); - if(normalize) - { + if(normalize) { grid_p_[n]->scaleAllValuesAndDerivatives(1./norm_[n]); norm_[n]=1; } @@ -303,10 +299,11 @@ VesDeltaF::VesDeltaF(const ActionOptions&ao) double biasfactor=0; parse("BIASFACTOR",biasfactor); plumed_massert(biasfactor==0 || biasfactor>1,"BIASFACTOR must be zero (for uniform target) or greater than one"); - if(biasfactor==0) + if(biasfactor==0) { inv_gamma_=0; - else + } else { inv_gamma_=1./biasfactor; + } tg_counter_=0; tg_stride_=1; parse("TG_STRIDE",tg_stride_); @@ -325,31 +322,31 @@ VesDeltaF::VesDeltaF(const ActionOptions&ao) mean_weight_tau_=0; parse("TAU_MEAN",mean_weight_tau_); - if(mean_weight_tau_!=1) //set it to 1 for basic SGD - { + if(mean_weight_tau_!=1) { //set it to 1 for basic SGD plumed_massert((mean_weight_tau_==0 || mean_weight_tau_>av_stride_),"TAU_MEAN is rescaled with AV_STRIDE, so it has to be greater"); mean_weight_tau_/=av_stride_; //this way you can look at the number of simulation steps to choose TAU_MEAN } parseVector("INITIAL_ALPHA",mean_alpha_); - if(mean_alpha_.size()>0) - { + if(mean_alpha_.size()>0) { plumed_massert(mean_alpha_.size()==alpha_size_,"provide one INITIAL_ALPHA for each basin beyond the first one"); - } - else + } else { mean_alpha_.resize(alpha_size_,0); + } inst_alpha_=mean_alpha_; exp_alpha_.resize(alpha_size_); - for(unsigned i=0; i1) //if each walker has more than one processor update them all + } + if(comm.Get_size()>1) { //if each walker has more than one processor update them all comm.Bcast(NumWalkers_,0); + } } checkRead(); //restart if needed - if(getRestart()) - { + if(getRestart()) { IFile ifile; ifile.link(*this); - if(NumWalkers_>1) + if(NumWalkers_>1) { ifile.enforceSuffix(""); - if(ifile.FileExist(alphaFileName)) - { + } + if(ifile.FileExist(alphaFileName)) { log.printf(" Restarting from: %s\n",alphaFileName.c_str()); log.printf(" all options (also PRINT_STRIDE) must be consistent!\n"); log.printf(" any INITIAL_ALPHA will be overwritten\n"); ifile.open(alphaFileName); double time; std::vector damping(alpha_size_); - while(ifile.scanField("time",time)) //room for improvements: only last line is important - { - for(unsigned i=0; i1) - { - if(comm.Get_rank()==0 && multi_sim_comm.Get_rank()>0) - alphaFileName="/dev/null"; //only first walker writes on file + if(NumWalkers_>1) { + if(comm.Get_rank()==0 && multi_sim_comm.Get_rank()>0) { + alphaFileName="/dev/null"; //only first walker writes on file + } alphaOfile_.enforceSuffix(""); } alphaOfile_.open(alphaFileName); - if(fmt.length()>0) + if(fmt.length()>0) { alphaOfile_.fmtField(" "+fmt); + } //add other output components - addComponent("rct"); componentIsNotPeriodic("rct"); - addComponent("work"); componentIsNotPeriodic("work"); + addComponent("rct"); + componentIsNotPeriodic("rct"); + addComponent("work"); + componentIsNotPeriodic("work"); //print some info log.printf(" Temperature T: %g\n",1./(Kb*beta_)); log.printf(" Beta (1/Kb*T): %g\n",beta_); log.printf(" Local free energy basins files and normalization constants:\n"); - for(unsigned n=0; n1) + if(mean_weight_tau_>1) { log.printf(" Exponentially decaying average with weight=tau/av_stride=%d\n",mean_weight_tau_); - if(mean_weight_tau_==1) + } + if(mean_weight_tau_==1) { log.printf(" +++ WARNING +++ setting TAU_MEAN=1 is equivalent to use simple SGD, without mean alpha nor hessian contribution\n"); + } log.printf(" Initial guess for alpha:\n"); - for(unsigned i=0; i1) + } + if(NumParallel_>1) { log.printf(" Using multiple threads per simulation: %d\n",NumParallel_); - if(multiple_walkers) - { + } + if(multiple_walkers) { log.printf(" -- MULTIPLE_WALKERS: multiple simulations will combine statistics for the optimization\n"); - if(NumWalkers_>1) - { + if(NumWalkers_>1) { log.printf(" number of walkers: %d\n",NumWalkers_); log.printf(" walker rank: %d\n",multi_sim_comm.Get_rank()); //only comm.Get_rank()=0 prints, so this is fine - } - else + } else { log.printf(" +++ WARNING +++ only one replica found: are you sure you are running MPI-connected simulations?\n"); + } } log.printf(" Bibliography "); log<0) + if(inv_gamma_>0) { log< cv(ncv); - for(unsigned s=0; sgetValueAndDerivatives(cv,der_prob_[n]); + } tot_prob_=prob_[0]; - for(unsigned i=0; i dV_dAlpha(alpha_size_); std::vector d2V_dAlpha2(sym_alpha_size_); - for(unsigned i=0; igetSize(); t+=NumParallel_) - { //TODO can we recycle some code? + for(Grid::index_t t=rank_; tgetSize(); t+=NumParallel_) { + //TODO can we recycle some code? std::vector prob(grid_p_.size()); - for(unsigned n=0; ngetValue(t); + } double tot_prob=prob[0]; - for(unsigned i=0; i dV_dAlpha(alpha_size_); std::vector d2V_dAlpha2(sym_alpha_size_); - for(unsigned i=0; i1) - { + if(NumParallel_>1) { comm.Sum(Z_tg); comm.Sum(tg_dV_dAlpha_); comm.Sum(tg_d2V_dAlpha2_); } - for(unsigned i=0; iset(-1./beta_*std::log(Z_tg/Z_0)); //Z_tg is the best available estimate of Z_V } -void VesDeltaF::update_alpha() -{ +void VesDeltaF::update_alpha() { //combining the averages of multiple walkers - if(NumWalkers_>1) - { - if(comm.Get_rank()==0) //sum only once: in the first rank of each walker - { + if(NumWalkers_>1) { + if(comm.Get_rank()==0) { //sum only once: in the first rank of each walker multi_sim_comm.Sum(av_dV_dAlpha_); multi_sim_comm.Sum(av_dV_dAlpha_prod_); multi_sim_comm.Sum(av_d2V_dAlpha2_); - for(unsigned i=0; i1)//if there are more ranks for each walker, everybody has to know - { + if(comm.Get_size()>1) { //if there are more ranks for each walker, everybody has to know comm.Bcast(av_dV_dAlpha_,0); comm.Bcast(av_dV_dAlpha_prod_,0); comm.Bcast(av_d2V_dAlpha2_,0); @@ -657,11 +662,9 @@ void VesDeltaF::update_alpha() //build the gradient and the Hessian of the functional std::vector grad_omega(alpha_size_); std::vector hess_omega(sym_alpha_size_); - for(unsigned i=0; i0 && mean_weight_tau_0 && mean_weight_tau_ damping(alpha_size_); - for(unsigned i=0; i basisf_labels; parseMultipleValues("BASIS_FUNCTIONS",basisf_labels,nargs_); checkRead(); std::string error_msg = ""; basisf_pntrs_ = VesTools::getPointersFromLabels(basisf_labels,plumed.getActionSet(),error_msg); - if(error_msg.size()>0) {plumed_merror("Error in keyword BASIS_FUNCTIONS of "+getName()+": "+error_msg);} + if(error_msg.size()>0) { + plumed_merror("Error in keyword BASIS_FUNCTIONS of "+getName()+": "+error_msg); + } // std::vector args_pntrs = getArguments(); @@ -358,8 +359,7 @@ VesLinearExpansion::VesLinearExpansion(const ActionOptions&ao): for(unsigned int i=0; iisPeriodic() && !(basisf_pntrs_[i]->arePeriodic()) ) { plumed_merror("argument "+args_pntrs[i]->getName()+" is periodic while the basis functions " + basisf_pntrs_[i]->getLabel()+ " are not. You need to use the COMBINE action to remove the periodicity of the argument if you want to use these basis functions"); - } - else if(!(args_pntrs[i]->isPeriodic()) && basisf_pntrs_[i]->arePeriodic() ) { + } else if(!(args_pntrs[i]->isPeriodic()) && basisf_pntrs_[i]->arePeriodic() ) { log.printf(" warning: argument %s is not periodic while the basis functions %s used for it are periodic\n",args_pntrs[i]->getName().c_str(),basisf_pntrs_[i]->getLabel().c_str()); } } @@ -381,13 +381,13 @@ VesLinearExpansion::VesLinearExpansion(const ActionOptions&ao): log.printf(" using an uniform target distribution: \n"); bias_expansion_pntr_->setupUniformTargetDistribution(); disableStaticTargetDistFileOutput(); - } - else if(getNumberOfTargetDistributionPntrs()==1) { - if(biasCutoffActive()) {getTargetDistributionPntrs()[0]->setupBiasCutoff();} + } else if(getNumberOfTargetDistributionPntrs()==1) { + if(biasCutoffActive()) { + getTargetDistributionPntrs()[0]->setupBiasCutoff(); + } bias_expansion_pntr_->setupTargetDistribution(getTargetDistributionPntrs()[0]); log.printf(" using target distribution of type %s with label %s \n",getTargetDistributionPntrs()[0]->getName().c_str(),getTargetDistributionPntrs()[0]->getLabel().c_str()); - } - else { + } else { plumed_merror("problem with the TARGET_DISTRIBUTION keyword, either give no label or just one label."); } setTargetDistAverages(bias_expansion_pntr_->TargetDistAverages()); @@ -401,7 +401,8 @@ VesLinearExpansion::VesLinearExpansion(const ActionOptions&ao): VesLinearExpansion::writeBiasToFile(); } - addComponent("force2"); componentIsNotPeriodic("force2"); + addComponent("force2"); + componentIsNotPeriodic("force2"); valueForce2_=getPntrToComponent("force2"); } diff --git a/src/ves/VesTools.cpp b/src/ves/VesTools.cpp index 8969454dc4..a126df55a5 100644 --- a/src/ves/VesTools.cpp +++ b/src/ves/VesTools.cpp @@ -46,7 +46,8 @@ void VesTools::copyGridValues(GridBase* grid_pntr_orig, GridBase* grid_pntr_copy unsigned int VesTools::getGridFileInfo(const std::string& filepath, std::string& grid_label, std::vector& arg_labels, std::vector& arg_min, std::vector& arg_max, std::vector& arg_periodic, std::vector& arg_nbins, bool& derivatives) { - IFile ifile; ifile.open(filepath); + IFile ifile; + ifile.open(filepath); std::vector fields; ifile.scanFieldList(fields); ifile.allowIgnoredFields(); @@ -58,8 +59,7 @@ unsigned int VesTools::getGridFileInfo(const std::string& filepath, std::string& derivatives = false; nargs = i-1; break; - } - else if(fields[i]=="der_"+fields[0]) { + } else if(fields[i]=="der_"+fields[0]) { derivatives = true; nargs = i-1; break; @@ -79,7 +79,9 @@ unsigned int VesTools::getGridFileInfo(const std::string& filepath, std::string& ifile.scanField("max_"+arg_labels[i],arg_max[i]); std::string str_periodic; ifile.scanField("periodic_"+arg_labels[i],str_periodic); - if(str_periodic=="true") {arg_periodic[i]=true;} + if(str_periodic=="true") { + arg_periodic[i]=true; + } int nbins; ifile.scanField("nbins_"+arg_labels[i],nbins); arg_nbins[i] = static_cast(nbins); diff --git a/src/ves/VesTools.h b/src/ves/VesTools.h index 926c641e1e..8ee52cea79 100644 --- a/src/ves/VesTools.h +++ b/src/ves/VesTools.h @@ -72,7 +72,9 @@ void VesTools::convertDbl2Str(const double value,std::string& str) { inline unsigned int log2(unsigned value) { unsigned int result = 0; - while(value >>= 1) result++; + while(value >>= 1) { + result++; + } return result; } @@ -112,10 +114,11 @@ std::vector VesTools::getPointersFromLabels(const std::vector& a if(missing.size()>0) { if(missing.size()==1) { error_msg = "label "+missing[0]+" does not exist\n"; - } - else if(missing.size()>1) { + } else if(missing.size()>1) { std::string tmp=""; - for(unsigned int j=0; j avail_action_pntrs = actionset.select(); @@ -124,8 +127,7 @@ std::vector VesTools::getPointersFromLabels(const std::vector& a for(unsigned int i=0; igetName() + " with label " + avail_action_pntrs[i]->getLabel() + "\n"; } - } - else { + } else { error_msg += " Hint! no actions defined in the input file that can be used here, they should be defined before this actions\n"; } } diff --git a/src/ves/WaveletGrid.cpp b/src/ves/WaveletGrid.cpp index 6f6b42eabf..efde4de3ae 100644 --- a/src/ves/WaveletGrid.cpp +++ b/src/ves/WaveletGrid.cpp @@ -42,7 +42,9 @@ std::unique_ptr WaveletGrid::setupGrid(const unsigned order, unsigned grid unsigned maxsupport = order*2 -1; // determine needed recursion depth for specified size unsigned recursion_number = 0; - while (maxsupport*(1U< WaveletGrid::setupGrid(const unsigned order, unsigned grid std::vector g_coeffs = getFilterCoefficients(order, false, type); g_Matvec = setupMatrices(g_coeffs); gridvarname = typeToString(type,true)+std::to_string(order)+"_psi"; - } - else { + } else { gridvarname = typeToString(type,true)+std::to_string(order)+"_phi"; } @@ -84,7 +85,8 @@ std::unique_ptr WaveletGrid::setupGrid(const unsigned order, unsigned grid std::vector> WaveletGrid::setupMatrices(const std::vector& coeffs) { Matrix M0, M1; const int N = coeffs.size() -1; - M0.resize(N,N); M1.resize(N,N); + M0.resize(N,N); + M1.resize(N,N); for (int i = 0; i < N; ++i) { for (int j = 0; j < N; ++j) { int shift = 2*i -j; @@ -133,9 +135,12 @@ std::vector WaveletGrid::getEigenvector(const Matrix &A, const d std::vector iwork(8*N); // Transfer the matrix to the local array and substract eigenvalue - for (int i=0; i( A(j,i) ); - if (i==j) da[i*N+j] -= eigenvalue; + if (i==j) { + da[i*N+j] -= eigenvalue; + } } // This optimizes the size of the work array used in lapack singular value decomposition @@ -144,14 +149,17 @@ std::vector WaveletGrid::getEigenvector(const Matrix &A, const d plumed_lapack_dgesdd( "A", &N, &N, da.data(), &N, S.data(), U.data(), &N, VT.data(), &N, work.data(), &lwork, iwork.data(), &info ); // Retrieve correct sizes for work and reallocate - lwork=static_cast(work[0]); work.resize(lwork); + lwork=static_cast(work[0]); + work.resize(lwork); // This does the singular value decomposition plumed_lapack_dgesdd( "A", &N, &N, da.data(), &N, S.data(), U.data(), &N, VT.data(), &N, work.data(), &lwork, iwork.data(), &info ); // fill eigenvector with last column of VT std::vector eigenvector(N); - for (int i=0; i>& h_Matve std::vector temp_values; // multiply matrices by 2 if derivatives are calculated (assumes ascending order) - if (derivnum != 0) for (auto& M : h_Matvec) M *= 2; + if (derivnum != 0) + for (auto& M : h_Matvec) { + M *= 2; + } if (use_mother_wavelet) { wavelet_map.reserve(bins_per_int); - if (derivnum != 0) for (auto& M : g_Matvec) M *= 2; + if (derivnum != 0) + for (auto& M : g_Matvec) { + M *= 2; + } } // fill the first two datasets by hand @@ -231,8 +245,11 @@ void WaveletGrid::fillGridFromMaps(std::unique_ptr& grid, const BinaryMap& WaveletGrid::Type WaveletGrid::stringToType(std::string& type_str) { std::unordered_map typemap = { {"DAUBECHIES", Type::db}, {"SYMLETS", Type::sym} }; - try { return typemap.at(type_str); } - catch(const std::out_of_range& e) {plumed_merror("The specified wavelet type "+type_str+" is not implemented."); } + try { + return typemap.at(type_str); + } catch(const std::out_of_range& e) { + plumed_merror("The specified wavelet type "+type_str+" is not implemented."); + } } diff --git a/src/volumes/ActionVolume.cpp b/src/volumes/ActionVolume.cpp index 9d2e955edf..296f8e6dfa 100644 --- a/src/volumes/ActionVolume.cpp +++ b/src/volumes/ActionVolume.cpp @@ -37,34 +37,55 @@ void ActionVolume::registerKeywords( Keywords& keys ) { ActionVolume::ActionVolume(const ActionOptions&ao): Action(ao), - ActionWithVector(ao) -{ - std::vector atoms; parseAtomList("ATOMS",atoms); - if( atoms.size()==0 ) error("no atoms were specified"); + ActionWithVector(ao) { + std::vector atoms; + parseAtomList("ATOMS",atoms); + if( atoms.size()==0 ) { + error("no atoms were specified"); + } log.printf(" examining positions of atoms "); - for(unsigned i=0; i shape(1); shape[0]=atoms.size(); ActionWithValue::addValue( shape ); } - setNotPeriodic(); getPntrToComponent(0)->setDerivativeIsZeroWhenValueIsZero(); + if( atoms.size()==1 ) { + ActionWithValue::addValueWithDerivatives(); + } else { + std::vector shape(1); + shape[0]=atoms.size(); + ActionWithValue::addValue( shape ); + } + setNotPeriodic(); + getPntrToComponent(0)->setDerivativeIsZeroWhenValueIsZero(); } bool ActionVolume::isInSubChain( unsigned& nder ) { - nder = 0; getFirstActionInChain()->getNumberOfStreamedDerivatives( nder, getPntrToComponent(0) ); + nder = 0; + getFirstActionInChain()->getNumberOfStreamedDerivatives( nder, getPntrToComponent(0) ); nder = nder - getNumberOfDerivatives(); return true; } void ActionVolume::requestAtoms( const std::vector & a ) { std::vector all_atoms( getAbsoluteIndexes() ); - for(unsigned i=0; igetRank()==0 ) getPntrToComponent(0)->resizeDerivatives( 3*getNumberOfAtoms()+9 ); + if( getPntrToComponent(0)->getRank()==0 ) { + getPntrToComponent(0)->resizeDerivatives( 3*getNumberOfAtoms()+9 ); + } } void ActionVolume::areAllTasksRequired( std::vector& task_reducing_actions ) { @@ -72,65 +93,110 @@ void ActionVolume::areAllTasksRequired( std::vector& task_red } void ActionVolume::getNumberOfTasks( unsigned& ntasks ) { - setupRegions(); ActionWithVector::getNumberOfTasks( ntasks ); + setupRegions(); + ActionWithVector::getNumberOfTasks( ntasks ); } int ActionVolume::checkTaskStatus( const unsigned& taskno, int& flag ) const { unsigned nref=getNumberOfAtoms()-getConstPntrToComponent(0)->getShape()[0]; - Vector wdf; Tensor vir; std::vector refders( nref ); + Vector wdf; + Tensor vir; + std::vector refders( nref ); double weight=calculateNumberInside( ActionAtomistic::getPosition(taskno), wdf, vir, refders ); - if( not_in ) weight = 1.0 - weight; - if( weight>epsilon ) return 1; + if( not_in ) { + weight = 1.0 - weight; + } + if( weight>epsilon ) { + return 1; + } return 0; } void ActionVolume::calculate() { - if( actionInChain() ) return; + if( actionInChain() ) { + return; + } if( getPntrToComponent(0)->getRank()==0 ) { - setupRegions(); unsigned nref = getNumberOfAtoms() - 1; - Vector wdf; Tensor vir; std::vector refders( nref ); + setupRegions(); + unsigned nref = getNumberOfAtoms() - 1; + Vector wdf; + Tensor vir; + std::vector refders( nref ); double weight=calculateNumberInside( ActionAtomistic::getPosition(0), wdf, vir, refders ); if( not_in ) { - weight = 1.0 - weight; wdf *= -1.; vir *=-1; - for(unsigned i=0; iset( weight ); - for(unsigned i=0; i<3; ++i ) v->addDerivative( i, wdf[i] ); + Value* v = getPntrToComponent(0); + v->set( weight ); + for(unsigned i=0; i<3; ++i ) { + v->addDerivative( i, wdf[i] ); + } // Add derivatives with respect to reference positions for(unsigned i=0; iaddDerivative( 3 + 3*i + j, refders[i][j] ); + for(unsigned j=0; j<3; ++j ) { + v->addDerivative( 3 + 3*i + j, refders[i][j] ); + } } // Add virial unsigned vbase = 3*getNumberOfAtoms(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) v->addDerivative( vbase + 3*i + j, vir(i,j) ); - } else runAllTasks(); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + v->addDerivative( vbase + 3*i + j, vir(i,j) ); + } + } else { + runAllTasks(); + } } void ActionVolume::performTask( const unsigned& curr, MultiValue& outvals ) const { unsigned nref=getNumberOfAtoms()-getConstPntrToComponent(0)->getShape()[0]; - Vector wdf; Tensor vir; std::vector refders( nref ); + Vector wdf; + Tensor vir; + std::vector refders( nref ); double weight=calculateNumberInside( ActionAtomistic::getPosition(curr), wdf, vir, refders ); if( not_in ) { - weight = 1.0 - weight; wdf *= -1.; vir *=-1; - for(unsigned i=0; igetPositionInStream(); outvals.setValue( ostrn, weight ); - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } // Atom position - for(unsigned i=0; i<3; ++i ) { outvals.addDerivative( ostrn, 3*curr+i, wdf[i] ); outvals.updateIndex( ostrn, 3*curr+i ); } + for(unsigned i=0; i<3; ++i ) { + outvals.addDerivative( ostrn, 3*curr+i, wdf[i] ); + outvals.updateIndex( ostrn, 3*curr+i ); + } // Add derivatives with respect to reference positions unsigned vbase = 3*(getNumberOfAtoms()-nref); for(unsigned i=0; igetRank()==0 ) return ActionAtomistic::getPosition( 1 + index ); + if( getConstPntrToComponent(0)->getRank()==0 ) { + return ActionAtomistic::getPosition( 1 + index ); + } return ActionAtomistic::getPosition( getConstPntrToComponent(0)->getShape()[0] + index ); } diff --git a/src/volumes/Density.cpp b/src/volumes/Density.cpp index bb6da9248b..097a1894de 100644 --- a/src/volumes/Density.cpp +++ b/src/volumes/Density.cpp @@ -49,14 +49,15 @@ void Density::registerKeywords(Keywords& keys) { ActionShortcut::registerKeywords( keys ); keys.add("compulsory","SPECIES","the atoms in the group"); keys.setValueDescription("indices for the specified group of atoms"); - keys.needsAction("ONES"); keys.needsAction("GROUP"); + keys.needsAction("ONES"); + keys.needsAction("GROUP"); } Density::Density(const ActionOptions& ao): Action(ao), - ActionShortcut(ao) -{ - std::string atoms; parse("SPECIES",atoms); + ActionShortcut(ao) { + std::string atoms; + parse("SPECIES",atoms); readInputLine( getShortcutLabel() + ": GROUP ATOMS=" + atoms); } diff --git a/src/volumes/VolumeAround.cpp b/src/volumes/VolumeAround.cpp index 84758adadc..979e9d9ebc 100644 --- a/src/volumes/VolumeAround.cpp +++ b/src/volumes/VolumeAround.cpp @@ -96,7 +96,8 @@ typedef VolumeShortcut VolumeAroundShortcut; PLUMED_REGISTER_ACTION(VolumeAroundShortcut,"AROUND") void VolumeAround::registerKeywords( Keywords& keys ) { - ActionVolume::registerKeywords( keys ); keys.setDisplayName("AROUND"); + ActionVolume::registerKeywords( keys ); + keys.setDisplayName("AROUND"); keys.add("atoms","ORIGIN","the atom whose vicinity we are interested in examining"); keys.add("atoms-2","ATOM","an alternative to ORIGIN"); keys.add("compulsory","XLOWER","0.0","the lower boundary in x relative to the x coordinate of the atom (0 indicates use full extent of box)."); @@ -109,29 +110,50 @@ void VolumeAround::registerKeywords( Keywords& keys ) { VolumeAround::VolumeAround(const ActionOptions& ao): Action(ao), - ActionVolume(ao) -{ - std::vector atom; parseAtomList("ORIGIN",atom); - if( atom.size()==0 ) parseAtomList("ATOM",atom); - if( atom.size()!=1 ) error("should only be one atom specified"); + ActionVolume(ao) { + std::vector atom; + parseAtomList("ORIGIN",atom); + if( atom.size()==0 ) { + parseAtomList("ATOM",atom); + } + if( atom.size()!=1 ) { + error("should only be one atom specified"); + } log.printf(" boundaries for region are calculated based on positions of atom : %d\n",atom[0].serial() ); - dox=true; parse("XLOWER",xlow); parse("XUPPER",xhigh); - doy=true; parse("YLOWER",ylow); parse("YUPPER",yhigh); - doz=true; parse("ZLOWER",zlow); parse("ZUPPER",zhigh); - if( xlow==0.0 && xhigh==0.0 ) dox=false; - if( ylow==0.0 && yhigh==0.0 ) doy=false; - if( zlow==0.0 && zhigh==0.0 ) doz=false; - if( !dox && !doy && !doz ) error("no subregion defined use XLOWER, XUPPER, YLOWER, YUPPER, ZLOWER, ZUPPER"); + dox=true; + parse("XLOWER",xlow); + parse("XUPPER",xhigh); + doy=true; + parse("YLOWER",ylow); + parse("YUPPER",yhigh); + doz=true; + parse("ZLOWER",zlow); + parse("ZUPPER",zhigh); + if( xlow==0.0 && xhigh==0.0 ) { + dox=false; + } + if( ylow==0.0 && yhigh==0.0 ) { + doy=false; + } + if( zlow==0.0 && zhigh==0.0 ) { + doz=false; + } + if( !dox && !doy && !doz ) { + error("no subregion defined use XLOWER, XUPPER, YLOWER, YUPPER, ZLOWER, ZUPPER"); + } log.printf(" boundaries for region (region of interest about atom) : x %f %f, y %f %f, z %f %f \n",xlow,xhigh,ylow,yhigh,zlow,zhigh); - checkRead(); requestAtoms(atom); + checkRead(); + requestAtoms(atom); } void VolumeAround::setupRegions() { } double VolumeAround::calculateNumberInside( const Vector& cpos, Vector& derivatives, Tensor& vir, std::vector& refders ) const { // Setup the histogram bead - HistogramBead bead; bead.isNotPeriodic(); bead.setKernelType( getKernelType() ); + HistogramBead bead; + bead.isNotPeriodic(); + bead.setKernelType( getKernelType() ); // Calculate position of atom wrt to origin Vector fpos=pbcDistance( getPosition(0), cpos ); @@ -140,19 +162,22 @@ double VolumeAround::calculateNumberInside( const Vector& cpos, Vector& derivati bead.set( xlow, xhigh, getSigma() ); xcontr=bead.calculate( fpos[0], xder ); } else { - xcontr=1.; xder=0.; + xcontr=1.; + xder=0.; } if( doy ) { bead.set( ylow, yhigh, getSigma() ); ycontr=bead.calculate( fpos[1], yder ); } else { - ycontr=1.; yder=0.; + ycontr=1.; + yder=0.; } if( doz ) { bead.set( zlow, zhigh, getSigma() ); zcontr=bead.calculate( fpos[2], zder ); } else { - zcontr=1.; zder=0.; + zcontr=1.; + zder=0.; } derivatives[0]=xder*ycontr*zcontr; derivatives[1]=xcontr*yder*zcontr; diff --git a/src/volumes/VolumeBetweenContours.cpp b/src/volumes/VolumeBetweenContours.cpp index ac3f249a78..4ff5982adc 100644 --- a/src/volumes/VolumeBetweenContours.cpp +++ b/src/volumes/VolumeBetweenContours.cpp @@ -92,7 +92,9 @@ typedef VolumeShortcut VolumeInEnvelopeShortcut; PLUMED_REGISTER_ACTION(VolumeInEnvelopeShortcut,"INENVELOPE") void VolumeInEnvelope::registerKeywords( Keywords& keys ) { - ActionVolume::registerKeywords( keys ); keys.remove("SIGMA"); keys.setDisplayName("INENVELOPE"); + ActionVolume::registerKeywords( keys ); + keys.remove("SIGMA"); + keys.setDisplayName("INENVELOPE"); keys.add("atoms","FIELD_ATOMS","the atom whose positions we are constructing a field from"); keys.add("compulsory","BANDWIDTH","the bandwidths for kernel density esimtation"); keys.add("compulsory","CONTOUR","a switching funciton that tells PLUMED how large the density should be"); @@ -102,59 +104,106 @@ void VolumeInEnvelope::registerKeywords( Keywords& keys ) { VolumeInEnvelope::VolumeInEnvelope(const ActionOptions& ao): Action(ao), ActionVolume(ao), - mylinks(comm) -{ - std::vector atoms; parseAtomList("FIELD_ATOMS",atoms); + mylinks(comm) { + std::vector atoms; + parseAtomList("FIELD_ATOMS",atoms); log.printf(" creating density field from atoms : "); - for(unsigned i=0; i pp(3,0.0); bandwidth.resize(3); parseVector("BANDWIDTH",bandwidth); + std::vector pp(3,0.0); + bandwidth.resize(3); + parseVector("BANDWIDTH",bandwidth); log.printf(" using %s kernel with bandwidths %f %f %f \n",getKernelType().c_str(),bandwidth[0],bandwidth[1],bandwidth[2] ); - std::string errors2; switchingFunction.set("GAUSSIAN R_0=1.0 NOSTRETCH", errors2 ); - if( errors2.length()!=0 ) error("problem reading switching function description " + errors2); - double det=1; for(unsigned i=0; imaxs ) maxs=sqrt(2*dp2cutoff)*bandwidth[j]; + if( sqrt(2*dp2cutoff)*bandwidth[j]>maxs ) { + maxs=sqrt(2*dp2cutoff)*bandwidth[j]; + } } - checkRead(); requestAtoms(atoms); mylinks.setCutoff( maxs ); + checkRead(); + requestAtoms(atoms); + mylinks.setCutoff( maxs ); } void VolumeInEnvelope::setupRegions() { - for(unsigned i=0; i& refders ) const { - unsigned ncells_required=0, natoms=1; std::vector cells_required( mylinks.getNumberOfCells() ), indices( 1 + getNumberOfAtoms() ); + unsigned ncells_required=0, natoms=1; + std::vector cells_required( mylinks.getNumberOfCells() ), indices( 1 + getNumberOfAtoms() ); mylinks.addRequiredCells( mylinks.findMyCell( cpos ), ncells_required, cells_required ); - indices[0]=getNumberOfAtoms(); mylinks.retrieveAtomsInCells( ncells_required, cells_required, natoms, indices ); - double value=0; std::vector der(3); Vector tder; + indices[0]=getNumberOfAtoms(); + mylinks.retrieveAtomsInCells( ncells_required, cells_required, natoms, indices ); + double value=0; + std::vector der(3); + Vector tder; // convert pointer once auto pos_ptr=Tools::unique2raw(pos); for(unsigned i=1; i VolumeCavityShortcut; PLUMED_REGISTER_ACTION(VolumeCavityShortcut,"CAVITY") void VolumeCavity::registerKeywords( Keywords& keys ) { - ActionVolume::registerKeywords( keys ); keys.setDisplayName("CAVITY"); + ActionVolume::registerKeywords( keys ); + keys.setDisplayName("CAVITY"); keys.add("atoms","BOX","the positions of four atoms that define spatial extent of the cavity"); keys.addFlag("PRINT_BOX",false,"write out the positions of the corners of the box to an xyz file"); keys.add("optional","FILE","the file on which to write out the box coordinates"); @@ -156,22 +157,33 @@ VolumeCavity::VolumeCavity(const ActionOptions& ao): dlperp(4), dbi(3), dcross(3), - dperp(3) -{ - std::vector atoms; parseAtomList("BOX",atoms); - if( atoms.size()!=4 ) error("number of atoms in box should be equal to four"); + dperp(3) { + std::vector atoms; + parseAtomList("BOX",atoms); + if( atoms.size()!=4 ) { + error("number of atoms in box should be equal to four"); + } log.printf(" boundaries for region are calculated based on positions of atoms : "); - for(unsigned i=0; i0 ) { - Units u; u.setLength(unitname); + Units u; + u.setLength(unitname); lenunit=getUnits().getLength()/u.getLength(); } else { unitname="nm"; @@ -206,10 +218,14 @@ void VolumeCavity::setupRegions() { d3 = pbcDistance(origin,getPosition(3)); // Create a set of unit vectors - bi = d1 / d1l; len_bi=dotProduct( d3, bi ); - cross = crossProduct( d1, d2 ); double crossmod=cross.modulo(); - cross = cross / crossmod; len_cross=dotProduct( d3, cross ); - perp = crossProduct( cross, bi ); len_perp=dotProduct( d3, perp ); + bi = d1 / d1l; + len_bi=dotProduct( d3, bi ); + cross = crossProduct( d1, d2 ); + double crossmod=cross.modulo(); + cross = cross / crossmod; + len_cross=dotProduct( d3, cross ); + perp = crossProduct( cross, bi ); + len_perp=dotProduct( d3, perp ); // Calculate derivatives of box shape with respect to atoms double d1l3=d1l*d1l*d1l; @@ -234,7 +250,9 @@ void VolumeCavity::setupRegions() { dbi[1](2,2) = ( (d1[1]*d1[1]+d1[0]*d1[0])/d1l3 ); dbi[2].zero(); - Tensor tcderiv; double cmod3=crossmod*crossmod*crossmod; Vector ucross=crossmod*cross; + Tensor tcderiv; + double cmod3=crossmod*crossmod*crossmod; + Vector ucross=crossmod*cross; tcderiv.setCol( 0, crossProduct( d1, Vector(-1.0,0.0,0.0) ) + crossProduct( Vector(-1.0,0.0,0.0), d2 ) ); tcderiv.setCol( 1, crossProduct( d1, Vector(0.0,-1.0,0.0) ) + crossProduct( Vector(0.0,-1.0,0.0), d2 ) ); tcderiv.setCol( 2, crossProduct( d1, Vector(0.0,0.0,-1.0) ) + crossProduct( Vector(0.0,0.0,-1.0), d2 ) ); @@ -288,18 +306,29 @@ void VolumeCavity::setupRegions() { // Ensure that all lengths are positive if( len_bi<0 ) { - bi=-bi; len_bi=-len_bi; - for(unsigned i=0; i<3; ++i) dbi[i]*=-1.0; + bi=-bi; + len_bi=-len_bi; + for(unsigned i=0; i<3; ++i) { + dbi[i]*=-1.0; + } } if( len_cross<0 ) { - cross=-cross; len_cross=-len_cross; - for(unsigned i=0; i<3; ++i) dcross[i]*=-1.0; + cross=-cross; + len_cross=-len_cross; + for(unsigned i=0; i<3; ++i) { + dcross[i]*=-1.0; + } } if( len_perp<0 ) { - perp=-perp; len_perp=-len_perp; - for(unsigned i=0; i<3; ++i) dperp[i]*=-1.0; + perp=-perp; + len_perp=-len_perp; + for(unsigned i=0; i<3; ++i) { + dperp[i]*=-1.0; + } + } + if( len_bi<=0 || len_cross<=0 || len_bi<=0 ) { + plumed_merror("Invalid box coordinates"); } - if( len_bi<=0 || len_cross<=0 || len_bi<=0 ) plumed_merror("Invalid box coordinates"); // Now derivatives of lengths Tensor dd3( Tensor::identity() ); @@ -320,9 +349,15 @@ void VolumeCavity::setupRegions() { // Need to calculate the jacobian Tensor jacob; - jacob(0,0)=bi[0]; jacob(1,0)=bi[1]; jacob(2,0)=bi[2]; - jacob(0,1)=cross[0]; jacob(1,1)=cross[1]; jacob(2,1)=cross[2]; - jacob(0,2)=perp[0]; jacob(1,2)=perp[1]; jacob(2,2)=perp[2]; + jacob(0,0)=bi[0]; + jacob(1,0)=bi[1]; + jacob(2,0)=bi[2]; + jacob(0,1)=cross[0]; + jacob(1,1)=cross[1]; + jacob(2,1)=cross[2]; + jacob(0,2)=perp[0]; + jacob(1,2)=perp[1]; + jacob(2,2)=perp[2]; jacob_det = fabs( jacob.determinant() ); } @@ -364,7 +399,9 @@ void VolumeCavity::update() { double VolumeCavity::calculateNumberInside( const Vector& cpos, Vector& derivatives, Tensor& vir, std::vector& rderiv ) const { // Setup the histogram bead - HistogramBead bead; bead.isNotPeriodic(); bead.setKernelType( getKernelType() ); + HistogramBead bead; + bead.isNotPeriodic(); + bead.setKernelType( getKernelType() ); // Calculate distance of atom from origin of new coordinate frame Vector datom=pbcDistance( origin, cpos ); @@ -391,15 +428,23 @@ double VolumeCavity::calculateNumberInside( const Vector& cpos, Vector& derivati double wdlen=bead.uboundDerivative( wpos ); double wder2 = bead.lboundDerivative( wpos ) - wdlen; - Vector dfd; dfd[0]=uder*vcontr*wcontr; dfd[1]=ucontr*vder*wcontr; dfd[2]=ucontr*vcontr*wder; + Vector dfd; + dfd[0]=uder*vcontr*wcontr; + dfd[1]=ucontr*vder*wcontr; + dfd[2]=ucontr*vcontr*wder; derivatives[0] = (dfd[0]*bi[0]+dfd[1]*cross[0]+dfd[2]*perp[0]); derivatives[1] = (dfd[0]*bi[1]+dfd[1]*cross[1]+dfd[2]*perp[1]); derivatives[2] = (dfd[0]*bi[2]+dfd[1]*cross[2]+dfd[2]*perp[2]); double tot = ucontr*vcontr*wcontr*jacob_det; // Add reference atom derivatives - dfd[0]=uder2*vcontr*wcontr; dfd[1]=ucontr*vder2*wcontr; dfd[2]=ucontr*vcontr*wder2; - Vector dfld; dfld[0]=udlen*vcontr*wcontr; dfld[1]=ucontr*vdlen*wcontr; dfld[2]=ucontr*vcontr*wdlen; + dfd[0]=uder2*vcontr*wcontr; + dfd[1]=ucontr*vder2*wcontr; + dfd[2]=ucontr*vcontr*wder2; + Vector dfld; + dfld[0]=udlen*vcontr*wcontr; + dfld[1]=ucontr*vdlen*wcontr; + dfld[2]=ucontr*vcontr*wdlen; rderiv[0] = dfd[0]*matmul(datom,dbi[0]) + dfd[1]*matmul(datom,dcross[0]) + dfd[2]*matmul(datom,dperp[0]) + dfld[0]*dlbi[0] + dfld[1]*dlcross[0] + dfld[2]*dlperp[0] - derivatives; rderiv[1] = dfd[0]*matmul(datom,dbi[1]) + dfd[1]*matmul(datom,dcross[1]) + dfd[2]*matmul(datom,dperp[1]) + @@ -408,7 +453,8 @@ double VolumeCavity::calculateNumberInside( const Vector& cpos, Vector& derivati dfld[0]*dlbi[2] + dfld[1]*dlcross[2] + dfld[2]*dlperp[2]; rderiv[3] = dfld[0]*dlbi[3] + dfld[1]*dlcross[3] + dfld[2]*dlperp[3]; - vir.zero(); vir-=Tensor( cpos,derivatives ); + vir.zero(); + vir-=Tensor( cpos,derivatives ); for(unsigned i=0; i<4; ++i) { vir -= Tensor( getPosition(i), rderiv[i] ); } diff --git a/src/volumes/VolumeInCylinder.cpp b/src/volumes/VolumeInCylinder.cpp index 1253007546..df439093f4 100644 --- a/src/volumes/VolumeInCylinder.cpp +++ b/src/volumes/VolumeInCylinder.cpp @@ -100,7 +100,8 @@ typedef VolumeShortcut VolumeInCylinderShortcut; PLUMED_REGISTER_ACTION(VolumeInCylinderShortcut,"INCYLINDER") void VolumeInCylinder::registerKeywords( Keywords& keys ) { - ActionVolume::registerKeywords( keys ); keys.setDisplayName("INCYLINDER"); + ActionVolume::registerKeywords( keys ); + keys.setDisplayName("INCYLINDER"); keys.add("atoms","CENTER","the atom whose vicinity we are interested in examining"); keys.add("compulsory","DIRECTION","the direction of the long axis of the cylinder. Must be x, y or z"); keys.add("compulsory","RADIUS","a switching function that gives the extent of the cylinder in the plane perpendicular to the direction"); @@ -112,35 +113,60 @@ void VolumeInCylinder::registerKeywords( Keywords& keys ) { VolumeInCylinder::VolumeInCylinder(const ActionOptions& ao): Action(ao), ActionVolume(ao), - docylinder(false) -{ + docylinder(false) { std::vector atom; parseAtomList("CENTER",atom); - if( atom.size()!=1 ) error("should only be one atom specified"); + if( atom.size()!=1 ) { + error("should only be one atom specified"); + } log.printf(" center of cylinder is at position of atom : %d\n",atom[0].serial() ); - std::string sdir; parse("DIRECTION",sdir); - if( sdir=="X") {dir.push_back(1); dir.push_back(2); dir.push_back(0); } - else if( sdir=="Y") {dir.push_back(0); dir.push_back(2); dir.push_back(1); } - else if( sdir=="Z") {dir.push_back(0); dir.push_back(1); dir.push_back(2); } - else { error(sdir + "is not a valid direction. Should be X, Y or Z"); } + std::string sdir; + parse("DIRECTION",sdir); + if( sdir=="X") { + dir.push_back(1); + dir.push_back(2); + dir.push_back(0); + } else if( sdir=="Y") { + dir.push_back(0); + dir.push_back(2); + dir.push_back(1); + } else if( sdir=="Z") { + dir.push_back(0); + dir.push_back(1); + dir.push_back(2); + } else { + error(sdir + "is not a valid direction. Should be X, Y or Z"); + } log.printf(" cylinder's long axis is along %s axis\n",sdir.c_str() ); - std::string sw, errors; parse("RADIUS",sw); - if(sw.length()==0) error("missing RADIUS keyword"); + std::string sw, errors; + parse("RADIUS",sw); + if(sw.length()==0) { + error("missing RADIUS keyword"); + } switchingFunction.set(sw,errors); - if( errors.length()!=0 ) error("problem reading RADIUS keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading RADIUS keyword : " + errors ); + } log.printf(" radius of cylinder is given by %s \n", ( switchingFunction.description() ).c_str() ); - double min, max; parse("LOWER",min); parse("UPPER",max); + double min, max; + parse("LOWER",min); + parse("UPPER",max); if( min!=0.0 || max!=0.0 ) { - if( min>max ) error("minimum of cylinder should be less than maximum"); + if( min>max ) { + error("minimum of cylinder should be less than maximum"); + } docylinder=true; log.printf(" cylinder extends from %f to %f along the %s axis\n",min,max,sdir.c_str() ); - bead.isNotPeriodic(); bead.setKernelType( getKernelType() ); bead.set( min, max, getSigma() ); + bead.isNotPeriodic(); + bead.setKernelType( getKernelType() ); + bead.set( min, max, getSigma() ); } - checkRead(); requestAtoms(atom); + checkRead(); + requestAtoms(atom); } void VolumeInCylinder::setupRegions() { } @@ -153,12 +179,14 @@ double VolumeInCylinder::calculateNumberInside( const Vector& cpos, Vector& deri if( docylinder ) { vcylinder=bead.calculate( fpos[dir[2]], dcylinder ); } else { - vcylinder=1.0; dcylinder=0.0; + vcylinder=1.0; + dcylinder=0.0; } const double dd = fpos[dir[0]]*fpos[dir[0]] + fpos[dir[1]]*fpos[dir[1]]; double dfunc, vswitch = switchingFunction.calculateSqr( dd, dfunc ); - derivatives.zero(); double value=vswitch*vcylinder; + derivatives.zero(); + double value=vswitch*vcylinder; derivatives[dir[0]]=vcylinder*dfunc*fpos[dir[0]]; derivatives[dir[1]]=vcylinder*dfunc*fpos[dir[1]]; derivatives[dir[2]]=vswitch*dcylinder; diff --git a/src/volumes/VolumeInSphere.cpp b/src/volumes/VolumeInSphere.cpp index 141ad4fbe7..91de7e5719 100644 --- a/src/volumes/VolumeInSphere.cpp +++ b/src/volumes/VolumeInSphere.cpp @@ -96,7 +96,8 @@ typedef VolumeShortcut VolumeInSphereShortcut; PLUMED_REGISTER_ACTION(VolumeInSphereShortcut,"INSPHERE") void VolumeInSphere::registerKeywords( Keywords& keys ) { - ActionVolume::registerKeywords( keys ); keys.setDisplayName("INSPHERE"); + ActionVolume::registerKeywords( keys ); + keys.setDisplayName("INSPHERE"); keys.add("atoms","CENTER","the atom whose vicinity we are interested in examining"); keys.add("atoms-2","ATOM","the atom whose vicinity we are interested in examining"); keys.add("compulsory","RADIUS","the switching function that tells us the extent of the sphereical region of interest"); @@ -105,20 +106,30 @@ void VolumeInSphere::registerKeywords( Keywords& keys ) { VolumeInSphere::VolumeInSphere(const ActionOptions& ao): Action(ao), - ActionVolume(ao) -{ - std::vector atom; parseAtomList("CENTER",atom); - if( atom.size()==0 ) parseAtomList("ATOM",atom); - if( atom.size()!=1 ) error("should only be one atom specified"); + ActionVolume(ao) { + std::vector atom; + parseAtomList("CENTER",atom); + if( atom.size()==0 ) { + parseAtomList("ATOM",atom); + } + if( atom.size()!=1 ) { + error("should only be one atom specified"); + } log.printf(" center of sphere is at position of atom : %d\n",atom[0].serial() ); - std::string sw, errors; parse("RADIUS",sw); - if(sw.length()==0) error("missing RADIUS keyword"); + std::string sw, errors; + parse("RADIUS",sw); + if(sw.length()==0) { + error("missing RADIUS keyword"); + } switchingFunction.set(sw,errors); - if( errors.length()!=0 ) error("problem reading RADIUS keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading RADIUS keyword : " + errors ); + } log.printf(" radius of sphere is given by %s \n", ( switchingFunction.description() ).c_str() ); - checkRead(); requestAtoms(atom); + checkRead(); + requestAtoms(atom); } void VolumeInSphere::setupRegions() { } @@ -127,7 +138,9 @@ double VolumeInSphere::calculateNumberInside( const Vector& cpos, Vector& deriva // Calculate position of atom wrt to origin Vector fpos=pbcDistance( getPosition(0), cpos ); double dfunc, value = switchingFunction.calculateSqr( fpos.modulo2(), dfunc ); - derivatives.zero(); derivatives = dfunc*fpos; refders[0] = -derivatives; + derivatives.zero(); + derivatives = dfunc*fpos; + refders[0] = -derivatives; // Add a virial contribution vir -= Tensor(fpos,derivatives); return value; diff --git a/src/volumes/VolumeShortcut.h b/src/volumes/VolumeShortcut.h index 2bf207d7e8..a6ed9395d3 100644 --- a/src/volumes/VolumeShortcut.h +++ b/src/volumes/VolumeShortcut.h @@ -53,36 +53,60 @@ void VolumeShortcut::registerKeywords( Keywords& keys ) { keys.addOutputComponent("sum","SUM","the sum of all the colvars weighted by the function that determines if we are in the region"); keys.addFlag("MEAN",false,"calculate the average value of the colvar inside the region of interest"); keys.addOutputComponent("mean","MEAN","the average values of the colvar in the region of interest"); - keys.addActionNameSuffix("_CALC"); keys.needsAction("LESS_THAN"); keys.needsAction("MORE_THAN"); keys.needsAction("GROUP"); - keys.needsAction("BETWEEN"); keys.needsAction("SUM"); keys.needsAction("MEAN"); keys.needsAction("CUSTOM"); + keys.addActionNameSuffix("_CALC"); + keys.needsAction("LESS_THAN"); + keys.needsAction("MORE_THAN"); + keys.needsAction("GROUP"); + keys.needsAction("BETWEEN"); + keys.needsAction("SUM"); + keys.needsAction("MEAN"); + keys.needsAction("CUSTOM"); } template VolumeShortcut::VolumeShortcut(const ActionOptions&ao): Action(ao), - ActionShortcut(ao) -{ - std::string voltype(v), mc_lab; parse("DATA",mc_lab); bool dosum; parseFlag("SUM",dosum); + ActionShortcut(ao) { + std::string voltype(v), mc_lab; + parse("DATA",mc_lab); + bool dosum; + parseFlag("SUM",dosum); if( mc_lab.length()>0 ) { Group* mygrp = plumed.getActionSet().template selectWithLabel(mc_lab); Group* mygrp2 = plumed.getActionSet().template selectWithLabel(mc_lab + "_grp"); - if( mygrp || mygrp2 ) readInputLine( getShortcutLabel() + "_grp: GROUP ATOMS=" + mc_lab ); - bool domean; parseFlag("MEAN",domean); std::string lt_input, mt_input, bt_input; - parse("LESS_THAN",lt_input); parse("MORE_THAN",mt_input); parse("BETWEEN",bt_input); - std::string atomsd; parse("ATOMS",atomsd); if( atomsd.length()==0 ) atomsd=mc_lab; + if( mygrp || mygrp2 ) { + readInputLine( getShortcutLabel() + "_grp: GROUP ATOMS=" + mc_lab ); + } + bool domean; + parseFlag("MEAN",domean); + std::string lt_input, mt_input, bt_input; + parse("LESS_THAN",lt_input); + parse("MORE_THAN",mt_input); + parse("BETWEEN",bt_input); + std::string atomsd; + parse("ATOMS",atomsd); + if( atomsd.length()==0 ) { + atomsd=mc_lab; + } // Create the apprpriate volume object readInputLine( getShortcutLabel() + ": " + voltype + "_CALC " + convertInputLineToString() + " ATOMS=" + atomsd ); // Now create input for sums if( dosum || domean ) { readInputLine( getShortcutLabel() + "_prod: CUSTOM ARG=" + mc_lab + "," + getShortcutLabel() + " FUNC=x*y PERIODIC=NO"); - std::string tlab = getShortcutLabel() + "_numer"; if( dosum ) tlab = getShortcutLabel() + "_sum:"; + std::string tlab = getShortcutLabel() + "_numer"; + if( dosum ) { + tlab = getShortcutLabel() + "_sum:"; + } readInputLine( tlab + ": SUM ARG=" + getShortcutLabel() + "_prod PERIODIC=NO"); } if( domean ) { // Calculate denominator readInputLine( getShortcutLabel() + "_norm: SUM ARG=" + getShortcutLabel() + " PERIODIC=NO"); // And calculate final quantity which is mean of these two actions - std::string arg1_lab = getShortcutLabel() + "_numer"; if( dosum ) arg1_lab = getShortcutLabel() + "_sum"; + std::string arg1_lab = getShortcutLabel() + "_numer"; + if( dosum ) { + arg1_lab = getShortcutLabel() + "_sum"; + } readInputLine( getShortcutLabel() + "_mean: CUSTOM ARG=" + arg1_lab + "," + getShortcutLabel() + "_norm FUNC=x/y PERIODIC=NO"); } if( lt_input.length()>0 ) { diff --git a/src/volumes/VolumeTetrapore.cpp b/src/volumes/VolumeTetrapore.cpp index 9037331722..a71989b37f 100644 --- a/src/volumes/VolumeTetrapore.cpp +++ b/src/volumes/VolumeTetrapore.cpp @@ -147,7 +147,8 @@ typedef VolumeShortcut VolumeTetraporeShortcut; PLUMED_REGISTER_ACTION(VolumeTetraporeShortcut,"TETRAHEDRALPORE") void VolumeTetrapore::registerKeywords( Keywords& keys ) { - ActionVolume::registerKeywords( keys ); keys.setDisplayName("TETRAHEDRALPORE"); + ActionVolume::registerKeywords( keys ); + keys.setDisplayName("TETRAHEDRALPORE"); keys.add("atoms","BOX","the positions of four atoms that define spatial extent of the cavity"); keys.addFlag("PRINT_BOX",false,"write out the positions of the corners of the box to an xyz file"); keys.add("optional","FILE","the file on which to write out the box coordinates"); @@ -164,23 +165,32 @@ VolumeTetrapore::VolumeTetrapore(const ActionOptions& ao): dlperp(4), dbi(3), dcross(3), - dperp(3) -{ + dperp(3) { std::vector atoms; parseAtomList("BOX",atoms); - if( atoms.size()!=4 ) error("number of atoms should be equal to four"); + if( atoms.size()!=4 ) { + error("number of atoms should be equal to four"); + } log.printf(" boundaries for region are calculated based on positions of atoms : "); - for(unsigned i=0; i0 ) { - Units u; u.setLength(unitname); + Units u; + u.setLength(unitname); lenunit=getUnits().getLength()/u.getLength(); } else { unitname="nm"; @@ -215,11 +225,15 @@ void VolumeTetrapore::setupRegions() { d3 = pbcDistance(origin,getPosition(3)); // Create a set of unit vectors - Vector bisector = d1 + d2; double bmod=bisector.modulo(); bisector=bisector/bmod; + Vector bisector = d1 + d2; + double bmod=bisector.modulo(); + bisector=bisector/bmod; // bi = d1 / d1l; len_bi=dotProduct( d3, bi ); - cross = crossProduct( d1, d2 ); double crossmod=cross.modulo(); - cross = cross / crossmod; len_cross=dotProduct( d3, cross ); + cross = crossProduct( d1, d2 ); + double crossmod=cross.modulo(); + cross = cross / crossmod; + len_cross=dotProduct( d3, cross ); Vector truep = crossProduct( cross, bisector ); // These are our true vectors 45 degrees from bisector @@ -227,13 +241,25 @@ void VolumeTetrapore::setupRegions() { perp = cos(pi/4.0)*bisector - sin(pi/4.0)*truep; // And the lengths of the various parts average distance to opposite corners of tetetrahedron - len_bi = dotProduct( d1, bi ); double len_bi2 = dotProduct( d2, bi ); unsigned lbi=1; - if( len_bi2>len_bi ) { len_bi=len_bi2; lbi=2; } - len_perp = dotProduct( d1, perp ); double len_perp2 = dotProduct( d2, perp ); unsigned lpi=1; - if( len_perp2>len_perp ) { len_perp=len_perp2; lpi=2; } + len_bi = dotProduct( d1, bi ); + double len_bi2 = dotProduct( d2, bi ); + unsigned lbi=1; + if( len_bi2>len_bi ) { + len_bi=len_bi2; + lbi=2; + } + len_perp = dotProduct( d1, perp ); + double len_perp2 = dotProduct( d2, perp ); + unsigned lpi=1; + if( len_perp2>len_perp ) { + len_perp=len_perp2; + lpi=2; + } plumed_assert( lbi!=lpi ); - Tensor tcderiv; double cmod3=crossmod*crossmod*crossmod; Vector ucross=crossmod*cross; + Tensor tcderiv; + double cmod3=crossmod*crossmod*crossmod; + Vector ucross=crossmod*cross; tcderiv.setCol( 0, crossProduct( d1, Vector(-1.0,0.0,0.0) ) + crossProduct( Vector(-1.0,0.0,0.0), d2 ) ); tcderiv.setCol( 1, crossProduct( d1, Vector(0.0,-1.0,0.0) ) + crossProduct( Vector(0.0,-1.0,0.0), d2 ) ); tcderiv.setCol( 2, crossProduct( d1, Vector(0.0,0.0,-1.0) ) + crossProduct( Vector(0.0,0.0,-1.0), d2 ) ); @@ -274,7 +300,8 @@ void VolumeTetrapore::setupRegions() { dcross[2](2,2)=( tcderiv(2,2)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dz/dz std::vector dbisector(3); - double bmod3=bmod*bmod*bmod; Vector ubisector=bmod*bisector; + double bmod3=bmod*bmod*bmod; + Vector ubisector=bmod*bisector; dbisector[0](0,0)= -2.0/bmod + 2*ubisector[0]*ubisector[0]/bmod3; dbisector[0](0,1)= 2*ubisector[0]*ubisector[1]/bmod3; dbisector[0](0,2)= 2*ubisector[0]*ubisector[2]/bmod3; @@ -326,22 +353,39 @@ void VolumeTetrapore::setupRegions() { // Ensure that all lengths are positive if( len_bi<0 ) { - bi=-bi; len_bi=-len_bi; - for(unsigned i=0; i<3; ++i) dbi[i]*=-1.0; + bi=-bi; + len_bi=-len_bi; + for(unsigned i=0; i<3; ++i) { + dbi[i]*=-1.0; + } } if( len_cross<0 ) { - cross=-cross; len_cross=-len_cross; - for(unsigned i=0; i<3; ++i) dcross[i]*=-1.0; + cross=-cross; + len_cross=-len_cross; + for(unsigned i=0; i<3; ++i) { + dcross[i]*=-1.0; + } } if( len_perp<0 ) { - perp=-perp; len_perp=-len_perp; - for(unsigned i=0; i<3; ++i) dperp[i]*=-1.0; + perp=-perp; + len_perp=-len_perp; + for(unsigned i=0; i<3; ++i) { + dperp[i]*=-1.0; + } + } + if( len_bi<=0 || len_cross<=0 || len_bi<=0 ) { + plumed_merror("Invalid box coordinates"); } - if( len_bi<=0 || len_cross<=0 || len_bi<=0 ) plumed_merror("Invalid box coordinates"); // Now derivatives of lengths - Tensor dd3( Tensor::identity() ); Vector ddb2=d1; if( lbi==2 ) ddb2=d2; - dlbi[1].zero(); dlbi[2].zero(); dlbi[3].zero(); + Tensor dd3( Tensor::identity() ); + Vector ddb2=d1; + if( lbi==2 ) { + ddb2=d2; + } + dlbi[1].zero(); + dlbi[2].zero(); + dlbi[3].zero(); dlbi[0] = matmul(ddb2,dbi[0]) - matmul(bi,dd3); dlbi[lbi] = matmul(ddb2,dbi[lbi]) + matmul(bi,dd3); // Derivative wrt d1 @@ -350,16 +394,27 @@ void VolumeTetrapore::setupRegions() { dlcross[2] = matmul(d3,dcross[2]); dlcross[3] = matmul(cross,dd3); - ddb2=d1; if( lpi==2 ) ddb2=d2; - dlperp[1].zero(); dlperp[2].zero(); dlperp[3].zero(); + ddb2=d1; + if( lpi==2 ) { + ddb2=d2; + } + dlperp[1].zero(); + dlperp[2].zero(); + dlperp[3].zero(); dlperp[0] = matmul(ddb2,dperp[0]) - matmul( perp, dd3 ); dlperp[lpi] = matmul(ddb2,dperp[lpi]) + matmul(perp, dd3); // Need to calculate the jacobian Tensor jacob; - jacob(0,0)=bi[0]; jacob(1,0)=bi[1]; jacob(2,0)=bi[2]; - jacob(0,1)=cross[0]; jacob(1,1)=cross[1]; jacob(2,1)=cross[2]; - jacob(0,2)=perp[0]; jacob(1,2)=perp[1]; jacob(2,2)=perp[2]; + jacob(0,0)=bi[0]; + jacob(1,0)=bi[1]; + jacob(2,0)=bi[2]; + jacob(0,1)=cross[0]; + jacob(1,1)=cross[1]; + jacob(2,1)=cross[2]; + jacob(0,2)=perp[0]; + jacob(1,2)=perp[1]; + jacob(2,2)=perp[2]; jacob_det = fabs( jacob.determinant() ); } @@ -401,7 +456,9 @@ void VolumeTetrapore::update() { double VolumeTetrapore::calculateNumberInside( const Vector& cpos, Vector& derivatives, Tensor& vir, std::vector& rderiv ) const { // Setup the histogram bead - HistogramBead bead; bead.isNotPeriodic(); bead.setKernelType( getKernelType() ); + HistogramBead bead; + bead.isNotPeriodic(); + bead.setKernelType( getKernelType() ); // Calculate distance of atom from origin of new coordinate frame Vector datom=pbcDistance( origin, cpos ); @@ -428,15 +485,23 @@ double VolumeTetrapore::calculateNumberInside( const Vector& cpos, Vector& deriv double wdlen=bead.uboundDerivative( wpos ); double wder2 = bead.lboundDerivative( wpos ) - wdlen; - Vector dfd; dfd[0]=uder*vcontr*wcontr; dfd[1]=ucontr*vder*wcontr; dfd[2]=ucontr*vcontr*wder; + Vector dfd; + dfd[0]=uder*vcontr*wcontr; + dfd[1]=ucontr*vder*wcontr; + dfd[2]=ucontr*vcontr*wder; derivatives[0] = (dfd[0]*bi[0]+dfd[1]*cross[0]+dfd[2]*perp[0]); derivatives[1] = (dfd[0]*bi[1]+dfd[1]*cross[1]+dfd[2]*perp[1]); derivatives[2] = (dfd[0]*bi[2]+dfd[1]*cross[2]+dfd[2]*perp[2]); double tot = ucontr*vcontr*wcontr*jacob_det; // Add reference atom derivatives - dfd[0]=uder2*vcontr*wcontr; dfd[1]=ucontr*vder2*wcontr; dfd[2]=ucontr*vcontr*wder2; - Vector dfld; dfld[0]=udlen*vcontr*wcontr; dfld[1]=ucontr*vdlen*wcontr; dfld[2]=ucontr*vcontr*wdlen; + dfd[0]=uder2*vcontr*wcontr; + dfd[1]=ucontr*vder2*wcontr; + dfd[2]=ucontr*vcontr*wder2; + Vector dfld; + dfld[0]=udlen*vcontr*wcontr; + dfld[1]=ucontr*vdlen*wcontr; + dfld[2]=ucontr*vcontr*wdlen; rderiv[0] = dfd[0]*matmul(datom,dbi[0]) + dfd[1]*matmul(datom,dcross[0]) + dfd[2]*matmul(datom,dperp[0]) + dfld[0]*dlbi[0] + dfld[1]*dlcross[0] + dfld[2]*dlperp[0] - derivatives; rderiv[1] = dfd[0]*matmul(datom,dbi[1]) + dfd[1]*matmul(datom,dcross[1]) + dfd[2]*matmul(datom,dperp[1]) + @@ -445,7 +510,8 @@ double VolumeTetrapore::calculateNumberInside( const Vector& cpos, Vector& deriv dfld[0]*dlbi[2] + dfld[1]*dlcross[2] + dfld[2]*dlperp[2]; rderiv[3] = dfld[0]*dlbi[3] + dfld[1]*dlcross[3] + dfld[2]*dlperp[3]; - vir.zero(); vir-=Tensor( cpos,derivatives ); + vir.zero(); + vir-=Tensor( cpos,derivatives ); for(unsigned i=0; i<4; ++i) { vir -= Tensor( getPosition(i), rderiv[i] ); } diff --git a/src/wham/Wham.cpp b/src/wham/Wham.cpp index 9ec43b7e50..7a03ac62bf 100644 --- a/src/wham/Wham.cpp +++ b/src/wham/Wham.cpp @@ -87,7 +87,9 @@ class Wham : public: static void registerKeywords(Keywords&); explicit Wham(const ActionOptions&ao); - unsigned getNumberOfDerivatives() { return 0; } + unsigned getNumberOfDerivatives() { + return 0; + } void calculate() override ; void apply() override {} }; @@ -95,8 +97,10 @@ class Wham : PLUMED_REGISTER_ACTION(Wham,"WHAM") void Wham::registerKeywords(Keywords& keys ) { - Action::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.remove("ARG"); + Action::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.remove("ARG"); keys.add("compulsory","ARG","the stored values for the bias"); keys.add("compulsory","MAXITER","1000","maximum number of iterations for WHAM algorithm"); keys.add("compulsory","WHAMTOL","1e-10","threshold for convergence of WHAM algorithm"); @@ -108,59 +112,90 @@ void Wham::registerKeywords(Keywords& keys ) { Wham::Wham(const ActionOptions&ao): Action(ao), ActionWithValue(ao), - ActionWithArguments(ao) -{ + ActionWithArguments(ao) { // Read in the temperature simtemp=getkBT(); - if(simtemp==0) error("The MD engine does not pass the temperature to plumed so you have to specify it using TEMP"); + if(simtemp==0) { + error("The MD engine does not pass the temperature to plumed so you have to specify it using TEMP"); + } // Now read in parameters of WHAM - parse("MAXITER",maxiter); parse("WHAMTOL",thresh); - if(comm.Get_rank()==0) nreplicas=multi_sim_comm.Get_size(); - comm.Bcast(nreplicas,0); addValue( getPntrToArgument(0)->getShape() ); setNotPeriodic(); + parse("MAXITER",maxiter); + parse("WHAMTOL",thresh); + if(comm.Get_rank()==0) { + nreplicas=multi_sim_comm.Get_size(); + } + comm.Bcast(nreplicas,0); + addValue( getPntrToArgument(0)->getShape() ); + setNotPeriodic(); } void Wham::calculate() { // Retrieve the values that were stored for the biase std::vector stored_biases( getPntrToArgument(0)->getNumberOfValues() ); - for(unsigned i=0; iget(i); + for(unsigned i=0; iget(i); + } // Get the minimum value of the bias double minv = *min_element(std::begin(stored_biases), std::end(stored_biases)); // Resize final weights array plumed_assert( stored_biases.size()%nreplicas==0 ); std::vector final_weights( stored_biases.size() / nreplicas, 1.0 ); if( getPntrToComponent(0)->getNumberOfValues()!=final_weights.size() ) { - std::vector shape(1); shape[0]=final_weights.size(); getPntrToComponent(0)->setShape( shape ); + std::vector shape(1); + shape[0]=final_weights.size(); + getPntrToComponent(0)->setShape( shape ); } // Offset and exponential of the bias std::vector expv( stored_biases.size() ); - for(unsigned i=0; i Z( nreplicas, 1.0 ), oldZ( nreplicas ); // Now the iterative loop to calculate the WHAM weights for(unsigned iter=0; iterset( j, final_weights[j] ); + for(unsigned j=0; jset( j, final_weights[j] ); + } return; } } diff --git a/src/wham/WhamHistogram.cpp b/src/wham/WhamHistogram.cpp index 4cbc8c0266..46e092f92a 100644 --- a/src/wham/WhamHistogram.cpp +++ b/src/wham/WhamHistogram.cpp @@ -93,18 +93,22 @@ void WhamHistogram::registerKeywords( Keywords& keys ) { keys.add("compulsory","GRID_BIN","the number of bins to use for the grid"); keys.add("optional","BANDWIDTH","the bandwidth for kernel density estimation"); keys.setValueDescription("the histogram that was generated using the WHAM weights"); - keys.needsAction("GATHER_REPLICAS"); keys.needsAction("CONCATENATE"); - keys.needsAction("COLLECT"); keys.needsAction("WHAM"); keys.needsAction("KDE"); + keys.needsAction("GATHER_REPLICAS"); + keys.needsAction("CONCATENATE"); + keys.needsAction("COLLECT"); + keys.needsAction("WHAM"); + keys.needsAction("KDE"); } WhamHistogram::WhamHistogram( const ActionOptions& ao ) : Action(ao), - ActionShortcut(ao) -{ + ActionShortcut(ao) { // Input for collection of weights for WHAM - std::string bias; parse("BIAS",bias); - std::string stride; parse("STRIDE",stride); + std::string bias; + parse("BIAS",bias); + std::string stride; + parse("STRIDE",stride); // Input for GATHER_REPLICAS readInputLine( getShortcutLabel() + "_gather: GATHER_REPLICAS ARG=" + bias ); // Put all the replicas in a single vector @@ -112,22 +116,42 @@ WhamHistogram::WhamHistogram( const ActionOptions& ao ) : // Input for COLLECT_FRAMES readInputLine( getShortcutLabel() + "_collect: COLLECT TYPE=vector ARG=" + getShortcutLabel() + "_gatherv STRIDE=" + stride); // Input for WHAM - std::string temp, tempstr=""; parse("TEMP",temp); if( temp.length()>0 ) tempstr="TEMP=" + temp; + std::string temp, tempstr=""; + parse("TEMP",temp); + if( temp.length()>0 ) { + tempstr="TEMP=" + temp; + } readInputLine( getShortcutLabel() + "_wham: WHAM ARG=" + getShortcutLabel() + "_collect " + tempstr ); // Input for COLLECT_FRAMES - std::vector args; parseVector("ARG",args); std::string argstr; + std::vector args; + parseVector("ARG",args); + std::string argstr; for(unsigned i=0; i0 ) tempstr="TEMP=" + temp; + std::string temp, tempstr=""; + parse("TEMP",temp); + if( temp.length()>0 ) { + tempstr="TEMP=" + temp; + } readInputLine( getShortcutLabel() + ": WHAM ARG=" + getShortcutLabel() + "_collect " + tempstr ); // Input for PRINT (will just output at end of calc - std::string filename, fmt; parse("FILE",filename); parse("FMT",fmt); + std::string filename, fmt; + parse("FILE",filename); + parse("FMT",fmt); readInputLine( "DUMPVECTOR STRIDE=0 ARG=" + getShortcutLabel() + " FILE=" + filename + " FMT=" + fmt ); } diff --git a/src/wrapper/Plumed.h b/src/wrapper/Plumed.h index 3ea2bc9c75..dd0aad96c2 100644 --- a/src/wrapper/Plumed.h +++ b/src/wrapper/Plumed.h @@ -930,7 +930,9 @@ __PLUMED_WRAPPER_STATIC_INLINE void plumed_error_init(plumed_error* error) __PLU /** Finalize error - should be called when an error is raised to avoid leaks */ /* cppcheck-suppress passedByValue */ __PLUMED_WRAPPER_STATIC_INLINE void plumed_error_finalize(plumed_error error) __PLUMED_WRAPPER_CXX_NOEXCEPT { - if(!error.code) return; + if(!error.code) { + return; + } if(error.nested) { plumed_error_finalize(*error.nested); plumed_free(error.nested); @@ -966,7 +968,9 @@ __PLUMED_WRAPPER_STATIC_INLINE void plumed_error_set_bad_alloc(plumed_error*erro /** Recursive merge (for internal usage) */ __PLUMED_WRAPPER_STATIC_INLINE void plumed_error_recursive_merge(plumed_error* error,char*buffer,const char*join,__PLUMED_WRAPPER_STD size_t*len) __PLUMED_WRAPPER_CXX_NOEXCEPT { - if(error->nested) plumed_error_recursive_merge(error->nested,buffer,join,len); + if(error->nested) { + plumed_error_recursive_merge(error->nested,buffer,join,len); + } __PLUMED_WRAPPER_STD strncat(buffer,plumed_error_what(*error),*len); *len -= __PLUMED_WRAPPER_STD strlen(plumed_error_what(*error)); __PLUMED_WRAPPER_STD strncat(buffer,join,*len); @@ -985,7 +989,9 @@ __PLUMED_WRAPPER_STATIC_INLINE void plumed_error_merge_with_nested(plumed_error* plumed_error*e; /* If exception is not nested, nothing to do */ - if(!error->nested) return; + if(!error->nested) { + return; + } /* Accumulate the total length of the concatenated message */ len_join=__PLUMED_WRAPPER_STD strlen(join); @@ -1015,7 +1021,9 @@ __PLUMED_WRAPPER_STATIC_INLINE void plumed_error_merge_with_nested(plumed_error* error->what=new_buffer; /* Deallocate the previous message */ - if(error->what_buffer) plumed_free(error->what_buffer); + if(error->what_buffer) { + plumed_free(error->what_buffer); + } error->what_buffer=new_buffer; /* Finalize the chain of nested exceptions */ @@ -1031,7 +1039,9 @@ __PLUMED_WRAPPER_STATIC_INLINE void plumed_error_merge_with_nested(plumed_error* /** Rethrow error (calling abort) */ __PLUMED_WRAPPER_CXX_NORETURN __PLUMED_WRAPPER_STATIC_INLINE void plumed_error_rethrow(plumed_error h) { - if(h.nested) plumed_error_merge_with_nested(&h); + if(h.nested) { + plumed_error_merge_with_nested(&h); + } __PLUMED_WRAPPER_STD fprintf(stderr,"Terminate due to exception. Code: %d\n%s\n",h.code,plumed_error_what(h)); __PLUMED_WRAPPER_STD abort(); } @@ -1823,7 +1833,9 @@ namespace wrapper { /// This is to replace c++17 std::void_t template -struct make_void { using type = void; }; +struct make_void { + using type = void; +}; template using void_t = typename make_void::type; @@ -1930,39 +1942,79 @@ class Plumed { finalize_plumed_error finalize(h); /* grab the message */ const char* msg=plumed_error_what(h); - if(h.code==1) f(Plumed::Invalid(msg)); + if(h.code==1) { + f(Plumed::Invalid(msg)); + } /* logic errors */ if(h.code>=10100 && h.code<10200) { - if(h.code>=10105 && h.code<10110) f(::std::invalid_argument(msg)); - if(h.code>=10110 && h.code<10115) f(::std::domain_error(msg)); - if(h.code>=10115 && h.code<10120) f(::std::length_error(msg)); - if(h.code>=10120 && h.code<10125) f(::std::out_of_range(msg)); + if(h.code>=10105 && h.code<10110) { + f(::std::invalid_argument(msg)); + } + if(h.code>=10110 && h.code<10115) { + f(::std::domain_error(msg)); + } + if(h.code>=10115 && h.code<10120) { + f(::std::length_error(msg)); + } + if(h.code>=10120 && h.code<10125) { + f(::std::out_of_range(msg)); + } #if __cplusplus >= 201703L && __PLUMED_WRAPPER_LIBCXX17 - if(h.code==10125) f(add_buffer_to< ::std::future_error>(::std::future_error(::std::future_errc::broken_promise),msg)); - if(h.code==10126) f(add_buffer_to< ::std::future_error>(::std::future_error(::std::future_errc::future_already_retrieved),msg)); - if(h.code==10127) f(add_buffer_to< ::std::future_error>(::std::future_error(::std::future_errc::promise_already_satisfied),msg)); - if(h.code==10128) f(add_buffer_to< ::std::future_error>(::std::future_error(::std::future_errc::no_state),msg)); + if(h.code==10125) { + f(add_buffer_to< ::std::future_error>(::std::future_error(::std::future_errc::broken_promise),msg)); + } + if(h.code==10126) { + f(add_buffer_to< ::std::future_error>(::std::future_error(::std::future_errc::future_already_retrieved),msg)); + } + if(h.code==10127) { + f(add_buffer_to< ::std::future_error>(::std::future_error(::std::future_errc::promise_already_satisfied),msg)); + } + if(h.code==10128) { + f(add_buffer_to< ::std::future_error>(::std::future_error(::std::future_errc::no_state),msg)); + } #endif f(::std::logic_error(msg)); } /* runtime errors */ if(h.code>=10200 && h.code<10300) { - if(h.code>=10205 && h.code<10210) f(::std::range_error(msg)); - if(h.code>=10210 && h.code<10215) f(::std::overflow_error(msg)); - if(h.code>=10215 && h.code<10220) f(::std::underflow_error(msg)); + if(h.code>=10205 && h.code<10210) { + f(::std::range_error(msg)); + } + if(h.code>=10210 && h.code<10215) { + f(::std::overflow_error(msg)); + } + if(h.code>=10215 && h.code<10220) { + f(::std::underflow_error(msg)); + } #if __cplusplus > 199711L && __PLUMED_WRAPPER_LIBCXX11 - if(h.code==10220) f(::std::system_error(h.error_code,::std::generic_category(),msg)); - if(h.code==10221) f(::std::system_error(h.error_code,::std::system_category(),msg)); - if(h.code==10222) f(::std::system_error(h.error_code,::std::iostream_category(),msg)); - if(h.code==10223) f(::std::system_error(h.error_code,::std::future_category(),msg)); + if(h.code==10220) { + f(::std::system_error(h.error_code,::std::generic_category(),msg)); + } + if(h.code==10221) { + f(::std::system_error(h.error_code,::std::system_category(),msg)); + } + if(h.code==10222) { + f(::std::system_error(h.error_code,::std::iostream_category(),msg)); + } + if(h.code==10223) { + f(::std::system_error(h.error_code,::std::future_category(),msg)); + } #endif #if __cplusplus >= 201703L && __PLUMED_WRAPPER_LIBCXX17 if(h.code==10229) { ::std::error_code error_code; - if(h.error_category==1) error_code=::std::error_code(h.error_code,::std::generic_category()); - if(h.error_category==2) error_code=::std::error_code(h.error_code,::std::system_category()); - if(h.error_category==3) error_code=::std::error_code(h.error_code,::std::iostream_category()); - if(h.error_category==4) error_code=::std::error_code(h.error_code,::std::future_category()); + if(h.error_category==1) { + error_code=::std::error_code(h.error_code,::std::generic_category()); + } + if(h.error_category==2) { + error_code=::std::error_code(h.error_code,::std::system_category()); + } + if(h.error_category==3) { + error_code=::std::error_code(h.error_code,::std::iostream_category()); + } + if(h.error_category==4) { + error_code=::std::error_code(h.error_code,::std::future_category()); + } if(!h.path1.ptr) { f(::std::filesystem::filesystem_error(msg,error_code)); @@ -1999,64 +2051,122 @@ class Plumed { if(h.code>=10230 && h.code<10240) { #if __cplusplus > 199711L && __PLUMED_WRAPPER_LIBCXX11 // These cases are probably useless as it looks like this should always be std::iostream_category - if(h.code==10230) f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::generic_category()))); - if(h.code==10231) f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::system_category()))); - if(h.code==10232) f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::iostream_category()))); - if(h.code==10233) f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::future_category()))); + if(h.code==10230) { + f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::generic_category()))); + } + if(h.code==10231) { + f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::system_category()))); + } + if(h.code==10232) { + f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::iostream_category()))); + } + if(h.code==10233) { + f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::future_category()))); + } #endif f(::std::ios_base::failure(msg)); } #if __cplusplus > 199711L && __PLUMED_WRAPPER_LIBCXX11 - if(h.code==10240) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_collate),msg)); - if(h.code==10241) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_ctype),msg)); - if(h.code==10242) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_escape),msg)); - if(h.code==10243) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_backref),msg)); - if(h.code==10244) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_brack),msg)); - if(h.code==10245) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_paren),msg)); - if(h.code==10246) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_brace),msg)); - if(h.code==10247) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_badbrace),msg)); - if(h.code==10248) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_range),msg)); - if(h.code==10249) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_space),msg)); - if(h.code==10250) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_badrepeat),msg)); - if(h.code==10251) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_complexity),msg)); - if(h.code==10252) f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_stack),msg)); + if(h.code==10240) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_collate),msg)); + } + if(h.code==10241) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_ctype),msg)); + } + if(h.code==10242) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_escape),msg)); + } + if(h.code==10243) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_backref),msg)); + } + if(h.code==10244) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_brack),msg)); + } + if(h.code==10245) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_paren),msg)); + } + if(h.code==10246) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_brace),msg)); + } + if(h.code==10247) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_badbrace),msg)); + } + if(h.code==10248) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_range),msg)); + } + if(h.code==10249) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_space),msg)); + } + if(h.code==10250) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_badrepeat),msg)); + } + if(h.code==10251) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_complexity),msg)); + } + if(h.code==10252) { + f(add_buffer_to< ::std::regex_error>(::std::regex_error(::std::regex_constants::error_stack),msg)); + } #endif f(::std::runtime_error(msg)); } /* "bad" errors */ /* "< ::" space required in C++ < 11 */ - if(h.code>=11000 && h.code<11100) f(add_buffer_to< ::std::bad_typeid>(msg)); + if(h.code>=11000 && h.code<11100) { + f(add_buffer_to< ::std::bad_typeid>(msg)); + } if(h.code>=11100 && h.code<11200) { #if __cplusplus >= 201703L && __PLUMED_WRAPPER_LIBCXX17 - if(h.code>=11150) f(add_buffer_to< ::std::bad_any_cast>(msg)); + if(h.code>=11150) { + f(add_buffer_to< ::std::bad_any_cast>(msg)); + } #endif f(add_buffer_to< ::std::bad_cast>(msg)); } #if __cplusplus > 199711L && __PLUMED_WRAPPER_LIBCXX11 - if(h.code>=11200 && h.code<11300) f(add_buffer_to< ::std::bad_weak_ptr>(msg)); - if(h.code>=11300 && h.code<11400) f(add_buffer_to< ::std::bad_function_call>(msg)); + if(h.code>=11200 && h.code<11300) { + f(add_buffer_to< ::std::bad_weak_ptr>(msg)); + } + if(h.code>=11300 && h.code<11400) { + f(add_buffer_to< ::std::bad_function_call>(msg)); + } #endif if(h.code>=11400 && h.code<11500) { #if __cplusplus > 199711L && __PLUMED_WRAPPER_LIBCXX11 - if(h.code>=11410 && h.code<11420) f(add_buffer_to< ::std::bad_array_new_length>(msg)); + if(h.code>=11410 && h.code<11420) { + f(add_buffer_to< ::std::bad_array_new_length>(msg)); + } #endif f(add_buffer_to< ::std::bad_alloc>(msg)); } - if(h.code>=11500 && h.code<11600) f(add_buffer_to< ::std::bad_exception>(msg)); + if(h.code>=11500 && h.code<11600) { + f(add_buffer_to< ::std::bad_exception>(msg)); + } #if __cplusplus >= 201703L && __PLUMED_WRAPPER_LIBCXX17 - if(h.code>=11600 && h.code<11700) f(add_buffer_to< ::std::bad_optional_access>(msg)); - if(h.code>=11700 && h.code<11800) f(add_buffer_to< ::std::bad_variant_access>(msg)); + if(h.code>=11600 && h.code<11700) { + f(add_buffer_to< ::std::bad_optional_access>(msg)); + } + if(h.code>=11700 && h.code<11800) { + f(add_buffer_to< ::std::bad_variant_access>(msg)); + } #endif /* lepton error */ - if(h.code>=19900 && h.code<20000) f(Plumed::LeptonException(msg)); + if(h.code>=19900 && h.code<20000) { + f(Plumed::LeptonException(msg)); + } /* plumed exceptions */ if(h.code>=20000 && h.code<30000) { /* debug - only raised with debug options */ - if(h.code>=20100 && h.code<20200) f(Plumed::ExceptionDebug(msg)); + if(h.code>=20100 && h.code<20200) { + f(Plumed::ExceptionDebug(msg)); + } /* error - runtime check */ - if(h.code>=20200 && h.code<20300) f(Plumed::ExceptionError(msg)); + if(h.code>=20200 && h.code<20300) { + f(Plumed::ExceptionError(msg)); + } /* error - type error */ - if(h.code>=20300 && h.code<20400) f(Plumed::ExceptionTypeError(msg)); + if(h.code>=20300 && h.code<20400) { + f(Plumed::ExceptionTypeError(msg)); + } f(Plumed::Exception(msg)); } /* fallback for any other exception */ @@ -2111,7 +2221,9 @@ class Plumed { When using C++11 nested exceptions, we need to rethrow recursively */ try { - if(h.nested) rethrow(*h.nested); /* recursive throw */ + if(h.nested) { + rethrow(*h.nested); /* recursive throw */ + } } catch(...) { exception_dispatch(h,rethrow_nested()); } @@ -2120,7 +2232,9 @@ class Plumed { /* When using C++<11 exceptions, we merge the message and then throw the resulting exception */ - if(h.nested) plumed_error_merge_with_nested(&h); + if(h.nested) { + plumed_error_merge_with_nested(&h); + } exception_dispatch(h,rethrow_not_nested()); #endif } @@ -2225,12 +2339,13 @@ class Plumed { Base class used to rethrow PLUMED exceptions. */ class Exception : - public ::std::exception - { + public ::std::exception { ::std::string msg; public: __PLUMED_WRAPPER_CXX_EXPLICIT Exception(const char* msg): msg(msg) {} - const char* what() const __PLUMED_WRAPPER_CXX_NOEXCEPT __PLUMED_WRAPPER_CXX_OVERRIDE {return msg.c_str();} + const char* what() const __PLUMED_WRAPPER_CXX_NOEXCEPT __PLUMED_WRAPPER_CXX_OVERRIDE { + return msg.c_str(); + } #if ! (__cplusplus > 199711L) /* Destructor should be declared in order to have the correct throw() before C++11 */ /* see https://stackoverflow.com/questions/50025862/why-is-the-stdexception-destructor-not-noexcept */ @@ -2316,12 +2431,13 @@ class Plumed { */ class LeptonException : - public ::std::exception - { + public ::std::exception { ::std::string msg; public: __PLUMED_WRAPPER_CXX_EXPLICIT LeptonException(const char* msg): msg(msg) {} - const char* what() const __PLUMED_WRAPPER_CXX_NOEXCEPT __PLUMED_WRAPPER_CXX_OVERRIDE {return msg.c_str();} + const char* what() const __PLUMED_WRAPPER_CXX_NOEXCEPT __PLUMED_WRAPPER_CXX_OVERRIDE { + return msg.c_str(); + } #if ! (__cplusplus > 199711L) /* Destructor should be declared in order to have the correct throw() before C++11 */ /* see https://stackoverflow.com/questions/50025862/why-is-the-stdexception-destructor-not-noexcept */ @@ -2341,31 +2457,32 @@ class Plumed { template class add_buffer_to: - public T - { + public T { char msg[__PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER]; void init(const char* msg) __PLUMED_WRAPPER_CXX_NOEXCEPT { this->msg[0]='\0'; __PLUMED_WRAPPER_STD strncat(this->msg,msg,__PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER-1); this->msg[__PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER-1]='\0'; - if(PlumedGetenvExceptionsDebug() && __PLUMED_WRAPPER_STD strlen(msg) > __PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER-1) __PLUMED_WRAPPER_STD fprintf(stderr,"+++ WARNING: message will be truncated\n"); + if(PlumedGetenvExceptionsDebug() && __PLUMED_WRAPPER_STD strlen(msg) > __PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER-1) { + __PLUMED_WRAPPER_STD fprintf(stderr,"+++ WARNING: message will be truncated\n"); + } } public: __PLUMED_WRAPPER_CXX_EXPLICIT add_buffer_to(const char * msg) __PLUMED_WRAPPER_CXX_NOEXCEPT { init(msg); } add_buffer_to(const T& base,const char * msg) __PLUMED_WRAPPER_CXX_NOEXCEPT: - T(base) - { + T(base) { init(msg); } add_buffer_to(const add_buffer_to & other) __PLUMED_WRAPPER_CXX_NOEXCEPT: - T(other) - { + T(other) { init(other.msg); } add_buffer_to & operator=(const add_buffer_to & other) __PLUMED_WRAPPER_CXX_NOEXCEPT { - if(this==&other) return *this; + if(this==&other) { + return *this; + } init(other.msg); return *this; } @@ -2410,8 +2527,12 @@ class Plumed { __PLUMED_WRAPPER_CXX_EXPLICIT SafePtr(const plumed_safeptr & safe,__PLUMED_WRAPPER_STD size_t nelem=0, const __PLUMED_WRAPPER_STD size_t* shape=__PLUMED_WRAPPER_CXX_NULLPTR) __PLUMED_WRAPPER_CXX_NOEXCEPT { this->safe=safe; buffer[0]='\0'; - if(nelem>0) this->safe.nelem=nelem; - if(shape) this->safe.shape=const_cast<__PLUMED_WRAPPER_STD size_t*>(shape); + if(nelem>0) { + this->safe.nelem=nelem; + } + if(shape) { + this->safe.shape=const_cast<__PLUMED_WRAPPER_STD size_t*>(shape); + } } #if __cplusplus > 199711L @@ -2712,16 +2833,14 @@ Plumed()__PLUMED_WRAPPER_CXX_NOEXCEPT : if the created object is still in scope. */ __PLUMED_WRAPPER_CXX_EXPLICIT Plumed(const char*c)__PLUMED_WRAPPER_CXX_NOEXCEPT : - main(plumed_create_reference_f(c)) - { + main(plumed_create_reference_f(c)) { } /** Create a reference from a void* pointer. Available as of PLUMED 2.5. */ __PLUMED_WRAPPER_CXX_EXPLICIT Plumed(void*v)__PLUMED_WRAPPER_CXX_NOEXCEPT : - main(plumed_create_reference_v(v)) - { + main(plumed_create_reference_v(v)) { } /** @@ -2734,8 +2853,7 @@ __PLUMED_WRAPPER_CXX_EXPLICIT Plumed(void*v)__PLUMED_WRAPPER_CXX_NOEXCEPT : if the created object is still in scope. */ __PLUMED_WRAPPER_CXX_EXPLICIT Plumed(plumed p)__PLUMED_WRAPPER_CXX_NOEXCEPT : - main(plumed_create_reference(p)) - { + main(plumed_create_reference(p)) { } /** Copy constructor. @@ -2743,8 +2861,7 @@ __PLUMED_WRAPPER_CXX_EXPLICIT Plumed(plumed p)__PLUMED_WRAPPER_CXX_NOEXCEPT : Takes a reference, incrementing the reference counter of the corresponding object. */ Plumed(const Plumed& p)__PLUMED_WRAPPER_CXX_NOEXCEPT : - main(plumed_create_reference(p.main)) - { + main(plumed_create_reference(p.main)) { } /** Assignment operator. Available as of PLUMED 2.5. @@ -2754,7 +2871,9 @@ Plumed(const Plumed& p)__PLUMED_WRAPPER_CXX_NOEXCEPT : Plumed&operator=(const Plumed&p) __PLUMED_WRAPPER_CXX_NOEXCEPT { if(this != &p) { // the check is needed to avoid calling plumed_finalize on moved objects - if(main.p) plumed_finalize(main); + if(main.p) { + plumed_finalize(main); + } main=plumed_create_reference(p.main); } return *this; @@ -2771,8 +2890,7 @@ Plumed(const Plumed& p)__PLUMED_WRAPPER_CXX_NOEXCEPT : Only if move semantics is enabled. */ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : - main(p.main) - { + main(p.main) { p.main.p=nullptr; } /** Move assignment. Available as of PLUMED 2.5. @@ -2781,7 +2899,9 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : Plumed& operator=(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT { if(this != &p) { // the check is needed to avoid calling plumed_finalize on moved objects - if(main.p) plumed_finalize(main); + if(main.p) { + plumed_finalize(main); + } main=p.main; p.main.p=nullptr; } @@ -2991,7 +3111,9 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : rethrow(); } /* plumed_error_rethrow is finalizing */ - if(!error && error_cxx.code!=0) plumed_error_rethrow_cxx(error_cxx); + if(!error && error_cxx.code!=0) { + plumed_error_rethrow_cxx(error_cxx); + } } public: @@ -3016,14 +3138,12 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : CString& operator=(CString&&) = delete; public: /// Initialize from a const char*, copying the address - CString(const char* str) noexcept - { + CString(const char* str) noexcept { this->str=str; this->static_buffer[0]='\0'; } /// Initialize from a std:string, taking the address of the corresponding c_str - CString(const std::string & str) noexcept - { + CString(const std::string & str) noexcept { this->str=str.c_str(); this->static_buffer[0]='\0'; } @@ -3057,7 +3177,9 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : /// Internal tool to convert initializer_list to shape /// This is just taking an initializer list and making a std::array std::array make_shape(std::initializer_list shape) { - if(shape.size()>4) throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + if(shape.size()>4) { + throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + } std::array shape_; unsigned j=0; for(auto i : shape) { @@ -3075,9 +3197,13 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : unsigned i; for(i=0; i<4; i++) { shape_[i]=shape[i]; - if(shape[i]==0) break; + if(shape[i]==0) { + break; + } } // one less because we need to append another number! - if(i==4) throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + if(i==4) { + throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + } shape_[i]=newindex; shape_[i+1]=0; return shape_; @@ -3118,14 +3244,18 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : // this would be strict checking // "a pointer without a specified size is meant to be pointing to a size 1 object" std::size_t shape[] { 0, 0 }; - if(val) shape[0]=1; + if(val) { + shape[0]=1; + } cmd_helper_with_shape(std::forward(key),val,shape); #else if(wrapper::is_custom_array::type>::type>::value) { // if we are passing a pointer to a fixed sized array, we make sure to retain the information related to // the rank of the array and the following (fixed) dimensions std::size_t shape[] { 0, 0 }; - if(val) shape[0]=std::numeric_limits::max(); + if(val) { + shape[0]=std::numeric_limits::max(); + } cmd_helper_with_shape(std::forward(key),val,shape); } else { // otherwise, for backward compatibility, the pointer is assumed with no shape information @@ -3157,7 +3287,9 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : template::value, int>::type = 0> void cmd_helper_with_shape(Key && key,T* val, __PLUMED_WRAPPER_STD size_t* shape,bool nocopy=false) { SafePtr s(val,0,shape); - if(nocopy) s.safe.flags |= 0x10000000; + if(nocopy) { + s.safe.flags |= 0x10000000; + } cmd_priv(main,CString(key),s); } @@ -3168,7 +3300,9 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : template::value, int>::type = 0> void cmd_with_nelem(Key && key,T* val, __PLUMED_WRAPPER_STD size_t nelem) { std::size_t shape[] { 0, 0 }; - if(val) shape[0]=nelem; + if(val) { + shape[0]=nelem; + } cmd_helper_with_shape(std::forward(key),val,shape); } @@ -3237,8 +3371,13 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : template void cmd(Key && key,T* val, __PLUMED_WRAPPER_STD size_t* shape) { unsigned i; - for(i=0; i<5; i++) if(shape[i]==0) break; - if(i==5) throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + for(i=0; i<5; i++) + if(shape[i]==0) { + break; + } + if(i==5) { + throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + } cmd_helper_with_shape(std::forward(key),val,shape); } @@ -3300,8 +3439,13 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : template void cmd(const char*key,T* val, const __PLUMED_WRAPPER_STD size_t* shape) { unsigned i; - for(i=0; i<5; i++) if(shape[i]==0) break; - if(i==5) throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + for(i=0; i<5; i++) + if(shape[i]==0) { + break; + } + if(i==5) { + throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + } plumed_cmd_cxx(main,key,val,shape); } @@ -3339,7 +3483,9 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : #endif ~Plumed() __PLUMED_WRAPPER_CXX_NOEXCEPT { // the check is needed to avoid calling plumed_finalize on moved objects - if(main.p) plumed_finalize(main); + if(main.p) { + plumed_finalize(main); + } } /** @@ -3403,8 +3549,13 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : template static void plumed_cmd_cxx(plumed p,const char*key,T* val, const __PLUMED_WRAPPER_STD size_t* shape,plumed_error* error=__PLUMED_WRAPPER_CXX_NULLPTR) { unsigned i; - for(i=0; i<5; i++) if(shape[i]==0) break; - if(i==5) throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + for(i=0; i<5; i++) + if(shape[i]==0) { + break; + } + if(i==5) { + throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + } SafePtr s(val,0,shape); cmd_priv(p,key,s,error); } @@ -3464,8 +3615,13 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : template static void plumed_gcmd_cxx(const char*key,T val, const __PLUMED_WRAPPER_STD size_t* shape,plumed_error* error=__PLUMED_WRAPPER_CXX_NULLPTR) { unsigned i; - for(i=0; i<5; i++) if(shape[i]==0) break; - if(i==5) throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + for(i=0; i<5; i++) + if(shape[i]==0) { + break; + } + if(i==5) { + throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + } plumed_cmd_cxx(plumed_global(),key,val,shape,error); } @@ -3833,14 +3989,18 @@ void* plumed_attempt_dlopen(const char*path,int mode) { } __PLUMED_WRAPPER_STD strncpy(pathcopy,path,strlenpath+1); pc=pathcopy+strlenpath-6; - while(pc>=pathcopy && __PLUMED_WRAPPER_STD memcmp(pc,"Kernel",6)) pc--; + while(pc>=pathcopy && __PLUMED_WRAPPER_STD memcmp(pc,"Kernel",6)) { + pc--; + } if(pc>=pathcopy) { __PLUMED_WRAPPER_STD memmove(pc, pc+6, __PLUMED_WRAPPER_STD strlen(pc)-5); __PLUMED_FPRINTF(stderr,"+++ This error is expected if you are trying to load a kernel <=2.4\n"); __PLUMED_FPRINTF(stderr,"+++ Trying %s +++\n",pathcopy); dlerror(); p=dlopen(pathcopy,mode); - if(!p) __PLUMED_FPRINTF(stderr,"+++ An error occurred. Message from dlopen(): %s +++\n",dlerror()); + if(!p) { + __PLUMED_FPRINTF(stderr,"+++ An error occurred. Message from dlopen(): %s +++\n",dlerror()); + } } plumed_free(pathcopy); } @@ -3893,7 +4053,9 @@ void plumed_search_symbols(void* handle, plumed_plumedmain_function_holder* f,pl */ debug=__PLUMED_GETENV("PLUMED_LOAD_DEBUG"); table_ptr=__PLUMED_WRAPPER_STATIC_CAST(plumed_symbol_table_type*, dlsym(handle,"plumed_symbol_table")); - if(table_ptr) functions=table_ptr->functions; + if(table_ptr) { + functions=table_ptr->functions; + } if(debug) { if(table_ptr) { __PLUMED_FPRINTF(stderr,"+++ plumed_symbol_table version %i found at %p +++\n",table_ptr->version,__PLUMED_WRAPPER_STATIC_CAST(void*,table_ptr)); @@ -3916,17 +4078,29 @@ void plumed_search_symbols(void* handle, plumed_plumedmain_function_holder* f,pl __PLUMED_SEARCH_FUNCTION(plumed_finalize_pointer,tmpptr,handle,functions.finalize,"plumedmain_finalize",debug); __PLUMED_SEARCH_FUNCTION(plumed_finalize_pointer,tmpptr,handle,functions.finalize,"plumed_plumedmain_finalize",debug); if(functions.create && functions.cmd && functions.finalize) { - if(debug) __PLUMED_FPRINTF(stderr,"+++ PLUMED was loaded correctly +++\n"); + if(debug) { + __PLUMED_FPRINTF(stderr,"+++ PLUMED was loaded correctly +++\n"); + } *f=functions; - if(table) *table=table_ptr; + if(table) { + *table=table_ptr; + } } else { - if(!functions.create) __PLUMED_FPRINTF(stderr,"+++ Pointer to (plumed_)plumedmain_create not found +++\n"); - if(!functions.cmd) __PLUMED_FPRINTF(stderr,"+++ Pointer to (plumed_)plumedmain_cmd not found +++\n"); - if(!functions.finalize) __PLUMED_FPRINTF(stderr,"+++ Pointer to (plumed_)plumedmain_finalize not found +++\n"); + if(!functions.create) { + __PLUMED_FPRINTF(stderr,"+++ Pointer to (plumed_)plumedmain_create not found +++\n"); + } + if(!functions.cmd) { + __PLUMED_FPRINTF(stderr,"+++ Pointer to (plumed_)plumedmain_cmd not found +++\n"); + } + if(!functions.finalize) { + __PLUMED_FPRINTF(stderr,"+++ Pointer to (plumed_)plumedmain_finalize not found +++\n"); + } f->create=__PLUMED_WRAPPER_CXX_NULLPTR; f->cmd=__PLUMED_WRAPPER_CXX_NULLPTR; f->finalize=__PLUMED_WRAPPER_CXX_NULLPTR; - if(table) *table=__PLUMED_WRAPPER_CXX_NULLPTR; + if(table) { + *table=__PLUMED_WRAPPER_CXX_NULLPTR; + } } } __PLUMED_WRAPPER_INTERNALS_END @@ -3993,18 +4167,30 @@ void plumed_retrieve_functions(plumed_plumedmain_function_holder* functions, plu This makes the symbols hardcoded and independent of a mis-set PLUMED_KERNEL variable. */ plumed_symbol_table_type* ptr=plumed_symbol_table_reexport(); - if(plumed_symbol_table_ptr) *plumed_symbol_table_ptr=ptr; - if(handle) *handle=__PLUMED_WRAPPER_CXX_NULLPTR; - if(functions) *functions=ptr->functions; + if(plumed_symbol_table_ptr) { + *plumed_symbol_table_ptr=ptr; + } + if(handle) { + *handle=__PLUMED_WRAPPER_CXX_NULLPTR; + } + if(functions) { + *functions=ptr->functions; + } #elif ! defined(__PLUMED_HAS_DLOPEN) /* When dlopen is not available, we hard code them to NULL */ __PLUMED_FPRINTF(stderr,"+++ PLUMED has been compiled without dlopen and without a static kernel +++\n"); plumed_plumedmain_function_holder g= {__PLUMED_WRAPPER_CXX_NULLPTR,__PLUMED_WRAPPER_CXX_NULLPTR,__PLUMED_WRAPPER_CXX_NULLPTR}; - if(plumed_symbol_table_ptr) *plumed_symbol_table_ptr=__PLUMED_WRAPPER_CXX_NULLPTR; - if(handle) *handle=__PLUMED_WRAPPER_CXX_NULLPTR; - if(functions) *functions=g; + if(plumed_symbol_table_ptr) { + *plumed_symbol_table_ptr=__PLUMED_WRAPPER_CXX_NULLPTR; + } + if(handle) { + *handle=__PLUMED_WRAPPER_CXX_NULLPTR; + } + if(functions) { + *functions=g; + } #else /* On the other hand, for runtime binding, we use dlsym to find the relevant functions. @@ -4022,8 +4208,12 @@ void plumed_retrieve_functions(plumed_plumedmain_function_holder* functions, plu p=__PLUMED_WRAPPER_CXX_NULLPTR; debug=__PLUMED_GETENV("PLUMED_LOAD_DEBUG"); dlopenmode=0; - if(plumed_symbol_table_ptr) *plumed_symbol_table_ptr=__PLUMED_WRAPPER_CXX_NULLPTR; - if(handle) *handle=__PLUMED_WRAPPER_CXX_NULLPTR; + if(plumed_symbol_table_ptr) { + *plumed_symbol_table_ptr=__PLUMED_WRAPPER_CXX_NULLPTR; + } + if(handle) { + *handle=__PLUMED_WRAPPER_CXX_NULLPTR; + } #ifdef __PLUMED_DEFAULT_KERNEL /* This variable allows a default path for the kernel to be hardcoded. @@ -4035,37 +4225,57 @@ void plumed_retrieve_functions(plumed_plumedmain_function_holder* functions, plu /* This is required to add quotes */ #define PLUMED_QUOTE_DIRECT(name) #name #define PLUMED_QUOTE(macro) PLUMED_QUOTE_DIRECT(macro) - if(! (path && (*path) )) path=PLUMED_QUOTE(__PLUMED_DEFAULT_KERNEL); + if(! (path && (*path) )) { + path=PLUMED_QUOTE(__PLUMED_DEFAULT_KERNEL); + } #endif #if defined(__PLUMED_PROGRAM_NAME) && defined(__PLUMED_SOEXT) - if(! (path && (*path) )) path="lib" __PLUMED_PROGRAM_NAME "Kernel." __PLUMED_SOEXT; + if(! (path && (*path) )) { + path="lib" __PLUMED_PROGRAM_NAME "Kernel." __PLUMED_SOEXT; + } #endif if(path && (*path)) { __PLUMED_FPRINTF(stderr,"+++ Loading the PLUMED kernel runtime +++\n"); __PLUMED_FPRINTF(stderr,"+++ PLUMED_KERNEL=\"%s\" +++\n",path); - if(debug) __PLUMED_FPRINTF(stderr,"+++ Loading with mode RTLD_NOW"); + if(debug) { + __PLUMED_FPRINTF(stderr,"+++ Loading with mode RTLD_NOW"); + } dlopenmode=RTLD_NOW; if(__PLUMED_GETENV("PLUMED_LOAD_NAMESPACE") && !__PLUMED_WRAPPER_STD strcmp(__PLUMED_GETENV("PLUMED_LOAD_NAMESPACE"),"GLOBAL")) { dlopenmode=dlopenmode|RTLD_GLOBAL; - if(debug) __PLUMED_FPRINTF(stderr,"|RTLD_GLOBAL"); + if(debug) { + __PLUMED_FPRINTF(stderr,"|RTLD_GLOBAL"); + } } else { dlopenmode=dlopenmode|RTLD_LOCAL; - if(debug) __PLUMED_FPRINTF(stderr,"|RTLD_LOCAL"); + if(debug) { + __PLUMED_FPRINTF(stderr,"|RTLD_LOCAL"); + } } #ifdef RTLD_DEEPBIND #if __PLUMED_WRAPPER_ENABLE_RTLD_DEEPBIND if(!__PLUMED_GETENV("PLUMED_LOAD_NODEEPBIND")) { dlopenmode=dlopenmode|RTLD_DEEPBIND; - if(debug) __PLUMED_FPRINTF(stderr,"|RTLD_DEEPBIND"); + if(debug) { + __PLUMED_FPRINTF(stderr,"|RTLD_DEEPBIND"); + } } #endif #endif - if(debug) __PLUMED_FPRINTF(stderr," +++\n"); + if(debug) { + __PLUMED_FPRINTF(stderr," +++\n"); + } p=plumed_attempt_dlopen(path,dlopenmode); - if(p) plumed_search_symbols(p,&g,plumed_symbol_table_ptr); + if(p) { + plumed_search_symbols(p,&g,plumed_symbol_table_ptr); + } + } + if(handle) { + *handle=p; + } + if(functions) { + *functions=g; } - if(handle) *handle=p; - if(functions) *functions=g; #endif } __PLUMED_WRAPPER_INTERNALS_END @@ -4136,8 +4346,12 @@ __PLUMED_WRAPPER_INTERNALS_END __PLUMED_WRAPPER_INTERNALS_BEGIN int plumed_check_pimpl(plumed_implementation*pimpl) { - if(!pimpl) return 0; - if(__PLUMED_WRAPPER_STD memcmp(pimpl->magic,"pLuMEd",6)) return 0; + if(!pimpl) { + return 0; + } + if(__PLUMED_WRAPPER_STD memcmp(pimpl->magic,"pLuMEd",6)) { + return 0; + } return 1; } __PLUMED_WRAPPER_INTERNALS_END @@ -4161,7 +4375,9 @@ plumed plumed_create(void) { #endif /* note if handle should not be dlclosed */ pimpl->dlclose=1; - if(__PLUMED_GETENV("PLUMED_LOAD_DLCLOSE") && !__PLUMED_WRAPPER_STD strcmp(__PLUMED_GETENV("PLUMED_LOAD_DLCLOSE"),"no")) pimpl->dlclose=0; + if(__PLUMED_GETENV("PLUMED_LOAD_DLCLOSE") && !__PLUMED_WRAPPER_STD strcmp(__PLUMED_GETENV("PLUMED_LOAD_DLCLOSE"),"no")) { + pimpl->dlclose=0; + } /* in case of failure, return */ /* the resulting object should be plumed_finalized, though you cannot use plumed_cmd */ if(!pimpl->functions.create) { @@ -4189,7 +4405,9 @@ plumed plumed_create_dlopen(const char*path) { dlopenmode=RTLD_NOW|RTLD_LOCAL; #ifdef RTLD_DEEPBIND #if __PLUMED_WRAPPER_ENABLE_RTLD_DEEPBIND - if(!__PLUMED_GETENV("PLUMED_LOAD_NODEEPBIND")) dlopenmode=dlopenmode|RTLD_DEEPBIND; + if(!__PLUMED_GETENV("PLUMED_LOAD_NODEEPBIND")) { + dlopenmode=dlopenmode|RTLD_DEEPBIND; + } #endif #endif #else @@ -4237,7 +4455,9 @@ plumed plumed_create_dlopen2(const char*path,int mode) { /* handler */ void* dlhandle; dlhandle=__PLUMED_WRAPPER_CXX_NULLPTR; - if(path) dlhandle=plumed_attempt_dlopen(path,mode); + if(path) { + dlhandle=plumed_attempt_dlopen(path,mode); + } /* a NULL handle implies the file could not be loaded */ if(dlhandle) { p=plumed_create_dlsym(dlhandle); @@ -4305,7 +4525,9 @@ void plumed_cmd(plumed p,const char*key,const void*val) { assert(plumed_check_pimpl(pimpl)); if(!pimpl->p) { __PLUMED_FPRINTF(stderr,"+++ ERROR: You are trying to use an invalid plumed object. +++\n"); - if(pimpl->used_plumed_kernel) __PLUMED_FPRINTF(stderr,"+++ Check your PLUMED_KERNEL environment variable. +++\n"); + if(pimpl->used_plumed_kernel) { + __PLUMED_FPRINTF(stderr,"+++ Check your PLUMED_KERNEL environment variable. +++\n"); + } __PLUMED_WRAPPER_STD abort(); } assert(pimpl->functions.create); @@ -4339,9 +4561,13 @@ void plumed_cmd_safe_nothrow(plumed p,const char*key,plumed_safeptr safe,plumed_ assert(pimpl->functions.cmd); assert(pimpl->functions.finalize); /* execute */ - if(pimpl->table && pimpl->table->version>2) (*(pimpl->table->cmd_safe_nothrow))(pimpl->p,key,safe,nothrow); - else if(pimpl->table && pimpl->table->version>1) (*(pimpl->table->cmd_nothrow))(pimpl->p,key,safe.ptr,nothrow); - else (*(pimpl->functions.cmd))(pimpl->p,key,safe.ptr); + if(pimpl->table && pimpl->table->version>2) { + (*(pimpl->table->cmd_safe_nothrow))(pimpl->p,key,safe,nothrow); + } else if(pimpl->table && pimpl->table->version>1) { + (*(pimpl->table->cmd_nothrow))(pimpl->p,key,safe.ptr,nothrow); + } else { + (*(pimpl->functions.cmd))(pimpl->p,key,safe.ptr); + } } __PLUMED_WRAPPER_C_END @@ -4365,15 +4591,20 @@ void plumed_cmd_safe(plumed p,const char*key,plumed_safeptr safe) { assert(plumed_check_pimpl(pimpl)); if(!pimpl->p) { __PLUMED_FPRINTF(stderr,"+++ ERROR: You are trying to use an invalid plumed object. +++\n"); - if(pimpl->used_plumed_kernel) __PLUMED_FPRINTF(stderr,"+++ Check your PLUMED_KERNEL environment variable. +++\n"); + if(pimpl->used_plumed_kernel) { + __PLUMED_FPRINTF(stderr,"+++ Check your PLUMED_KERNEL environment variable. +++\n"); + } __PLUMED_WRAPPER_STD abort(); } assert(pimpl->functions.create); assert(pimpl->functions.cmd); assert(pimpl->functions.finalize); /* execute */ - if(pimpl->table && pimpl->table->version>2) (*(pimpl->table->cmd_safe))(pimpl->p,key,safe); - else (*(pimpl->functions.cmd))(pimpl->p,key,safe.ptr); + if(pimpl->table && pimpl->table->version>2) { + (*(pimpl->table->cmd_safe))(pimpl->p,key,safe); + } else { + (*(pimpl->functions.cmd))(pimpl->p,key,safe.ptr); + } } __PLUMED_WRAPPER_C_END @@ -4389,9 +4620,13 @@ void plumed_finalize(plumed p) { #endif /* with PLUMED > 2.8, we can use an internal reference counter which is thread safe */ if(pimpl->p && pimpl->table && pimpl->table->version>3) { - if(pimpl->table->delete_reference(pimpl->p)>0) return; + if(pimpl->table->delete_reference(pimpl->p)>0) { + return; + } } else { - if(--pimpl->refcount>0) return; + if(--pimpl->refcount>0) { + return; + } } /* to allow finalizing an invalid plumed object, we only call finalize if the object is valid */ @@ -4405,7 +4640,9 @@ void plumed_finalize(plumed p) { #ifdef __PLUMED_HAS_DLOPEN /* dlclose library */ if(pimpl->dlhandle && pimpl->dlclose) { - if(__PLUMED_GETENV("PLUMED_LOAD_DEBUG")) __PLUMED_FPRINTF(stderr,"+++ Unloading library\n"); + if(__PLUMED_GETENV("PLUMED_LOAD_DEBUG")) { + __PLUMED_FPRINTF(stderr,"+++ Unloading library\n"); + } dlclose(pimpl->dlhandle); } #endif @@ -4423,8 +4660,11 @@ int plumed_valid(plumed p) { /* obtain pimpl */ pimpl=__PLUMED_WRAPPER_STATIC_CAST(plumed_implementation*, p.p); assert(plumed_check_pimpl(pimpl)); - if(pimpl->p) return 1; - else return 0; + if(pimpl->p) { + return 1; + } else { + return 0; + } } __PLUMED_WRAPPER_C_END @@ -4459,7 +4699,9 @@ void* plumed_malloc(__PLUMED_WRAPPER_STD size_t size) { void* ptr; ptr=__PLUMED_WRAPPER_STD malloc(size); #if __PLUMED_WRAPPER_DEBUG_REFCOUNT - if(ptr) fprintf(stderr,"plumed_malloc: %p\n",ptr); + if(ptr) { + fprintf(stderr,"plumed_malloc: %p\n",ptr); + } #endif return ptr; } @@ -4507,8 +4749,11 @@ void plumed_gfinalize(void) { } int plumed_ginitialized(void) { - if(plumed_gmain.p) return 1; - else return 0; + if(plumed_gmain.p) { + return 1; + } else { + return 0; + } } int plumed_gvalid() {