From 25077afcf2d2cc0eac132c88b7ddc3e2f25a3386 Mon Sep 17 00:00:00 2001 From: Daniele Rapetti <5535617+Iximiel@users.noreply.github.com> Date: Thu, 19 Sep 2024 09:26:28 +0200 Subject: [PATCH 1/3] formatted astyle.sh + removed shellcheck warnings --- src/astyle.sh | 63 ++++++++++++++++++++++++++------------------------- 1 file changed, 32 insertions(+), 31 deletions(-) diff --git a/src/astyle.sh b/src/astyle.sh index c3239afac7..84a2394f4d 100755 --- a/src/astyle.sh +++ b/src/astyle.sh @@ -1,50 +1,51 @@ #! /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 +for dir in $DIRS; do + test -d "$dir" || continue -cd $dir + test "$dir" = lapack && continue + test "$dir" = blas && continue + test "$dir" = molfile && continue + test "$dir" = lepton && continue + test "$dir" = asmjit && continue + test "$dir" = xdrfile && continue + cd "$dir" || { + echo "Problem with 'cd $dir'" + exit 1 + } -for file in *.c *.cpp *.h *.inc.in -do + for file in *.c *.cpp *.h *.inc.in; do -test -f "$file" || continue + test -f "$file" || continue -echo -n "astyle $file" + echo -n "astyle $file" -../../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 -} + ../../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 + } -rm $file.tmp + rm "$file.tmp" -done + done -cd - + cd - || { + echo "Problem with 'cd -' from '$dir'" + exit 1 + } done - - From 33f1cb86c61c13ef7c545444113ae60f6dd628fd Mon Sep 17 00:00:00 2001 From: Daniele Rapetti Date: Fri, 4 Oct 2024 07:50:42 +0200 Subject: [PATCH 2/3] restyle v2.9 --- .astyle.options | 14 +- src/adjmat/ActionWithInputMatrix.cpp | 66 +- src/adjmat/ActionWithInputMatrix.h | 8 +- src/adjmat/AdjacencyMatrixBase.cpp | 120 ++- src/adjmat/AdjacencyMatrixBase.h | 12 +- src/adjmat/AdjacencyMatrixVessel.cpp | 95 +- src/adjmat/AlignedMatrixBase.cpp | 45 +- src/adjmat/ClusterAnalysisBase.cpp | 33 +- src/adjmat/ClusterAnalysisBase.h | 4 +- src/adjmat/ClusterDiameter.cpp | 29 +- src/adjmat/ClusterDistribution.cpp | 57 +- src/adjmat/ClusterProperties.cpp | 59 +- src/adjmat/ClusterSize.cpp | 29 +- src/adjmat/ClusterWithSurface.cpp | 57 +- src/adjmat/ClusteringBase.cpp | 34 +- src/adjmat/ContactAlignedMatrix.cpp | 26 +- src/adjmat/ContactMatrix.cpp | 29 +- src/adjmat/DFSClustering.cpp | 42 +- src/adjmat/DumpGraph.cpp | 48 +- src/adjmat/HbondMatrix.cpp | 76 +- src/adjmat/MatrixColumnSums.cpp | 50 +- src/adjmat/MatrixRowSums.cpp | 38 +- src/adjmat/OutputCluster.cpp | 113 ++- src/adjmat/SMACMatrix.cpp | 49 +- src/adjmat/Sprint.cpp | 40 +- src/adjmat/TopologyMatrix.cpp | 132 ++- src/analysis/AnalysisBase.cpp | 36 +- src/analysis/AnalysisBase.h | 15 +- src/analysis/Average.cpp | 30 +- src/analysis/AverageVessel.cpp | 21 +- src/analysis/AverageVessel.h | 4 +- src/analysis/Committor.cpp | 40 +- src/analysis/DataCollectionObject.cpp | 34 +- src/analysis/DataCollectionObject.h | 14 +- src/analysis/EuclideanDissimilarityMatrix.cpp | 59 +- src/analysis/FarthestPointSampling.cpp | 28 +- src/analysis/Histogram.cpp | 282 ++++-- src/analysis/LandmarkSelectionBase.cpp | 34 +- src/analysis/LandmarkSelectionBase.h | 4 +- src/analysis/LandmarkStaged.cpp | 40 +- src/analysis/OutputColvarFile.cpp | 76 +- src/analysis/OutputPDBFile.cpp | 43 +- src/analysis/PrintDissimilarityMatrix.cpp | 29 +- src/analysis/ReadAnalysisFrames.cpp | 106 +- src/analysis/ReadAnalysisFrames.h | 8 +- src/analysis/ReadDissimilarityMatrix.cpp | 71 +- src/analysis/ReselectLandmarks.cpp | 18 +- src/analysis/SelectRandomFrames.cpp | 6 +- src/analysis/SelectWithStride.cpp | 7 +- src/analysis/WhamHistogram.cpp | 41 +- src/analysis/WhamWeights.cpp | 26 +- src/annfunc/ANN.cpp | 33 +- src/astyle.sh | 5 +- src/bias/ABMD.cpp | 42 +- src/bias/Bias.cpp | 14 +- src/bias/Bias.h | 3 +- src/bias/BiasValue.cpp | 9 +- src/bias/ExtendedLagrangian.cpp | 31 +- src/bias/External.cpp | 33 +- src/bias/LWalls.cpp | 26 +- src/bias/MaxEnt.cpp | 146 ++- src/bias/MetaD.cpp | 926 ++++++++++++------ src/bias/MovingRestraint.cpp | 66 +- src/bias/PBMetaD.cpp | 445 ++++++--- src/bias/Restraint.cpp | 15 +- src/bias/ReweightBase.cpp | 20 +- src/bias/ReweightBase.h | 15 +- src/bias/ReweightBias.cpp | 11 +- src/bias/ReweightMetad.cpp | 11 +- src/bias/ReweightTemperaturePressure.cpp | 55 +- src/bias/ReweightWham.cpp | 80 +- src/bias/UWalls.cpp | 26 +- src/cltools/Completion.cpp | 30 +- src/cltools/Driver.cpp | 605 +++++++++--- src/cltools/DriverFloat.cpp | 4 +- src/cltools/GenExample.cpp | 348 +++++-- src/cltools/GenJson.cpp | 88 +- src/cltools/GenTemplate.cpp | 10 +- src/cltools/Info.cpp | 75 +- src/cltools/Manual.cpp | 20 +- src/cltools/PdbRenumber.cpp | 14 +- src/cltools/SimpleMD.cpp | 205 ++-- src/cltools/SumHills.cpp | 165 +++- src/cltools/kT.cpp | 15 +- src/cltools/pesmd.cpp | 132 ++- src/colvar/Angle.cpp | 25 +- src/colvar/Cell.cpp | 52 +- src/colvar/Constant.cpp | 32 +- src/colvar/ContactMap.cpp | 83 +- src/colvar/Coordination.cpp | 11 +- src/colvar/CoordinationBase.cpp | 77 +- src/colvar/DHEnergy.cpp | 7 +- src/colvar/DRMSD.cpp | 33 +- src/colvar/Dimer.cpp | 62 +- src/colvar/Dipole.cpp | 29 +- src/colvar/Distance.cpp | 42 +- src/colvar/EEFSolv.cpp | 84 +- src/colvar/ERMSD.cpp | 29 +- src/colvar/Energy.cpp | 6 +- src/colvar/ExtraCV.cpp | 6 +- src/colvar/Fake.cpp | 3 +- src/colvar/GHBFIX.cpp | 10 +- src/colvar/Gyration.cpp | 197 ++-- src/colvar/MultiRMSD.cpp | 43 +- src/colvar/PCARMSD.cpp | 97 +- src/colvar/PathMSD.cpp | 15 +- src/colvar/PathMSDBase.cpp | 116 ++- src/colvar/Position.cpp | 31 +- src/colvar/ProjectionOnAxis.cpp | 39 +- src/colvar/PropertyMap.cpp | 14 +- src/colvar/Puckering.cpp | 152 ++- src/colvar/RMSD.cpp | 42 +- src/colvar/Template.cpp | 16 +- src/colvar/Torsion.cpp | 35 +- src/colvar/Volume.cpp | 6 +- src/config/Config.inc.in | 32 +- src/core/Action.cpp | 99 +- src/core/Action.h | 77 +- src/core/ActionAnyorder.cpp | 3 +- src/core/ActionAtomistic.cpp | 194 +++- src/core/ActionAtomistic.h | 23 +- src/core/ActionPilot.cpp | 11 +- src/core/ActionPilot.h | 3 +- src/core/ActionRegister.cpp | 50 +- src/core/ActionSet.cpp | 11 +- src/core/ActionSet.h | 31 +- src/core/ActionSetup.cpp | 7 +- src/core/ActionShortcut.cpp | 32 +- src/core/ActionWithArguments.cpp | 84 +- src/core/ActionWithArguments.h | 3 +- src/core/ActionWithValue.cpp | 58 +- src/core/ActionWithValue.h | 14 +- src/core/ActionWithVirtualAtom.cpp | 20 +- src/core/ActionWithVirtualAtom.h | 3 +- src/core/Atoms.cpp | 222 +++-- src/core/Atoms.h | 67 +- src/core/CLTool.cpp | 79 +- src/core/CLTool.h | 24 +- src/core/CLToolMain.cpp | 68 +- src/core/CLToolMain.h | 3 +- src/core/CLToolRegister.cpp | 30 +- src/core/Colvar.cpp | 36 +- src/core/Colvar.h | 7 +- src/core/DataFetchingObject.cpp | 33 +- 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/MDAtoms.cpp | 74 +- src/core/MDAtoms.h | 3 +- src/core/PlumedMain.cpp | 332 +++++-- src/core/PlumedMain.h | 21 +- src/core/PlumedMainInitializer.cpp | 182 +++- src/core/TargetDist.cpp | 16 +- src/core/Value.cpp | 61 +- src/core/Value.h | 27 +- src/crystallization/BondOrientation.cpp | 36 +- src/crystallization/CubicHarmonicBase.cpp | 66 +- src/crystallization/CubicHarmonicBase.h | 4 +- src/crystallization/EnvironmentSimilarity.cpp | 121 ++- src/crystallization/Fccubic.cpp | 6 +- src/crystallization/Gradient.cpp | 106 +- src/crystallization/GradientVessel.cpp | 58 +- .../InterMolecularTorsions.cpp | 65 +- src/crystallization/LocalSteinhardt.h | 14 +- src/crystallization/MoleculeOrientation.cpp | 56 +- src/crystallization/MoleculePlane.cpp | 17 +- src/crystallization/OrientationSphere.cpp | 61 +- src/crystallization/OrientationSphere.h | 7 +- src/crystallization/PolymerAngles.cpp | 22 +- src/crystallization/Q3.cpp | 3 +- src/crystallization/Q4.cpp | 9 +- src/crystallization/Q6.cpp | 12 +- src/crystallization/SMAC.cpp | 66 +- src/crystallization/SimpleCubic.cpp | 3 +- src/crystallization/Steinhardt.cpp | 82 +- src/crystallization/Tetrahedral.cpp | 15 +- src/crystallization/VectorMean.cpp | 39 +- src/crystallization/VectorMultiColvar.cpp | 40 +- src/crystallization/VectorMultiColvar.h | 8 +- src/crystallization/VectorSum.cpp | 29 +- .../ClassicalMultiDimensionalScaling.cpp | 38 +- src/dimred/DimensionalityReductionBase.cpp | 73 +- src/dimred/DimensionalityReductionBase.h | 4 +- src/dimred/OutputPCAProjections.cpp | 54 +- src/dimred/PCA.cpp | 118 ++- src/dimred/PCA.h | 12 +- src/dimred/ProjectNonLandmarkPoints.cpp | 49 +- src/dimred/SMACOF.cpp | 59 +- src/dimred/SketchMap.cpp | 75 +- src/dimred/SketchMapBase.cpp | 81 +- src/dimred/SketchMapBase.h | 20 +- src/dimred/SketchMapConjGrad.cpp | 3 +- src/dimred/SketchMapPointwise.cpp | 52 +- src/dimred/SketchMapRead.cpp | 108 +- src/dimred/SketchMapSmacof.cpp | 29 +- src/dimred/SmacoffMDS.cpp | 10 +- src/drr/DRR.cpp | 41 +- src/drr/DRR.h | 49 +- src/drr/DynamicReferenceRestraining.cpp | 16 +- src/drr/colvar_UIestimator.h | 346 +++---- src/drr/drrtool.cpp | 18 +- src/eds/EDS.cpp | 463 ++++----- src/fisst/FISST.cpp | 101 +- src/fisst/legendre_rule_fast.cpp | 55 +- src/function/Combine.cpp | 38 +- src/function/Custom.cpp | 39 +- src/function/Ensemble.cpp | 81 +- src/function/FuncPathGeneral.cpp | 56 +- src/function/FuncPathMSD.cpp | 47 +- src/function/FuncSumHills.cpp | 262 +++-- src/function/Function.cpp | 28 +- src/function/Function.h | 3 +- src/function/LocalEnsemble.cpp | 29 +- src/function/Piecewise.cpp | 29 +- src/function/Sort.cpp | 9 +- src/function/Stats.cpp | 65 +- src/function/Target.cpp | 26 +- src/funnel/FPS.cpp | 20 +- src/funnel/Funnel.cpp | 77 +- src/generic/Debug.cpp | 42 +- src/generic/DumpAtoms.cpp | 93 +- src/generic/DumpDerivatives.cpp | 22 +- src/generic/DumpForces.cpp | 14 +- src/generic/DumpMassCharge.cpp | 29 +- src/generic/DumpProjections.cpp | 14 +- src/generic/EffectiveEnergyDrift.cpp | 48 +- src/generic/EndPlumed.cpp | 6 +- src/generic/FitToTemplate.cpp | 54 +- src/generic/Flush.cpp | 9 +- src/generic/Group.cpp | 52 +- src/generic/Include.cpp | 6 +- src/generic/Plumed.cpp | 196 +++- src/generic/Print.cpp | 14 +- src/generic/RandomExchanges.cpp | 10 +- src/generic/Read.cpp | 92 +- src/generic/ResetCell.cpp | 14 +- src/generic/Time.cpp | 10 +- src/generic/UpdateIf.cpp | 46 +- src/generic/WholeMolecules.cpp | 52 +- src/generic/WrapAround.cpp | 34 +- src/gridtools/ActionWithGrid.cpp | 67 +- src/gridtools/ActionWithInputGrid.cpp | 36 +- src/gridtools/ActionWithInputGrid.h | 9 +- src/gridtools/ActionWithIntegral.cpp | 25 +- src/gridtools/ActionWithIntegral.h | 4 +- src/gridtools/AverageOnGrid.cpp | 38 +- src/gridtools/AverageOnGrid.h | 12 +- src/gridtools/ContourFindingBase.cpp | 10 +- src/gridtools/ContourFindingBase.h | 8 +- src/gridtools/ConvertToFES.cpp | 85 +- src/gridtools/DumpCube.cpp | 30 +- src/gridtools/DumpGrid.cpp | 32 +- src/gridtools/FindContour.cpp | 115 ++- src/gridtools/FindContourSurface.cpp | 147 ++- src/gridtools/FindSphericalContour.cpp | 50 +- src/gridtools/FourierTransform.cpp | 79 +- src/gridtools/GridPrintingBase.cpp | 92 +- src/gridtools/GridSearch.h | 54 +- src/gridtools/GridToXYZ.cpp | 45 +- src/gridtools/GridVessel.cpp | 472 ++++++--- src/gridtools/GridVessel.h | 24 +- src/gridtools/HistogramOnGrid.cpp | 106 +- src/gridtools/HistogramOnGrid.h | 8 +- src/gridtools/IntegrateGrid.cpp | 10 +- src/gridtools/InterpolateGrid.cpp | 41 +- src/isdb/CS2Backbone.cpp | 840 +++++++++++----- src/isdb/Caliber.cpp | 115 ++- src/isdb/EMMI.cpp | 507 ++++++---- src/isdb/FretEfficiency.cpp | 17 +- src/isdb/Jcoupling.cpp | 49 +- src/isdb/Metainference.cpp | 613 ++++++++---- src/isdb/MetainferenceBase.cpp | 604 ++++++++---- src/isdb/MetainferenceBase.h | 66 +- src/isdb/NOE.cpp | 101 +- src/isdb/PRE.cpp | 118 ++- src/isdb/RDC.cpp | 134 ++- src/isdb/Rescale.cpp | 137 ++- src/isdb/SAXS.cpp | 884 ++++++++++++----- src/isdb/Select.cpp | 20 +- src/isdb/Selector.cpp | 6 +- src/logmfd/LogMFD.cpp | 92 +- src/main/main.cpp | 20 +- src/manyrestraints/LWalls.cpp | 3 +- src/manyrestraints/ManyRestraintsBase.cpp | 14 +- src/manyrestraints/ManyRestraintsBase.h | 15 +- src/manyrestraints/UWalls.cpp | 3 +- src/mapping/AdaptivePath.cpp | 103 +- src/mapping/Mapping.cpp | 136 ++- src/mapping/Mapping.h | 11 +- src/mapping/PCAVars.cpp | 179 +++- src/mapping/Path.cpp | 16 +- src/mapping/PathBase.cpp | 26 +- src/mapping/PathReparameterization.cpp | 77 +- src/mapping/PathTools.cpp | 158 ++- src/mapping/PropertyMap.cpp | 9 +- src/mapping/SpathVessel.cpp | 17 +- src/mapping/TrigonometricPathVessel.cpp | 165 +++- src/mapping/ZpathVessel.cpp | 9 +- 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/ActionVolume.cpp | 65 +- src/multicolvar/AlphaBeta.cpp | 23 +- src/multicolvar/Angles.cpp | 62 +- src/multicolvar/AtomValuePack.cpp | 36 +- src/multicolvar/AtomValuePack.h | 29 +- src/multicolvar/Bridge.cpp | 40 +- .../BridgedMultiColvarFunction.cpp | 55 +- src/multicolvar/BridgedMultiColvarFunction.h | 8 +- src/multicolvar/CatomPack.cpp | 3 +- src/multicolvar/CenterOfMultiColvar.cpp | 70 +- src/multicolvar/CoordinationNumbers.cpp | 52 +- src/multicolvar/Density.cpp | 29 +- src/multicolvar/DihedralCorrelation.cpp | 7 +- src/multicolvar/DistanceFromContour.cpp | 212 ++-- src/multicolvar/Distances.cpp | 48 +- src/multicolvar/DumpMultiColvar.cpp | 66 +- src/multicolvar/FilterBetween.cpp | 31 +- src/multicolvar/FilterLessThan.cpp | 26 +- src/multicolvar/FilterMoreThan.cpp | 26 +- src/multicolvar/InPlaneDistances.cpp | 53 +- src/multicolvar/LocalAverage.cpp | 90 +- src/multicolvar/MultiColvarBase.cpp | 807 +++++++++++---- src/multicolvar/MultiColvarBase.h | 19 +- src/multicolvar/MultiColvarCombine.cpp | 35 +- src/multicolvar/MultiColvarDensity.cpp | 206 ++-- src/multicolvar/MultiColvarFilter.cpp | 32 +- src/multicolvar/MultiColvarProduct.cpp | 31 +- src/multicolvar/NumberOfLinks.cpp | 40 +- src/multicolvar/Torsions.cpp | 21 +- src/multicolvar/VolumeAround.cpp | 51 +- src/multicolvar/VolumeBetweenContours.cpp | 77 +- src/multicolvar/VolumeCavity.cpp | 101 +- src/multicolvar/VolumeGradientBase.cpp | 70 +- src/multicolvar/VolumeGradientBase.h | 8 +- src/multicolvar/VolumeInCylinder.cpp | 61 +- src/multicolvar/VolumeInSphere.cpp | 25 +- src/multicolvar/VolumeTetrapore.cpp | 139 ++- src/multicolvar/XAngle.cpp | 60 +- src/multicolvar/XDistances.cpp | 48 +- src/multicolvar/XYDistances.cpp | 49 +- src/multicolvar/XYTorsion.cpp | 79 +- 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 | 132 ++- src/opes/ExpansionCVs.h | 16 +- src/opes/OPESexpanded.cpp | 448 ++++----- src/opes/OPESmetad.cpp | 902 ++++++++--------- src/pamm/HBPammHydrogens.cpp | 102 +- src/pamm/HBPammMatrix.cpp | 34 +- src/pamm/HBPammObject.cpp | 28 +- src/pamm/PAMM.cpp | 64 +- src/pamm/PammObject.cpp | 53 +- src/pamm/PammObject.h | 6 +- src/piv/PIV.cpp | 116 ++- src/pytorch/PytorchModel.cpp | 16 +- src/reference/ArgumentOnlyDistance.cpp | 15 +- src/reference/ArgumentOnlyDistance.h | 8 +- src/reference/DRMSD.cpp | 39 +- src/reference/Direction.cpp | 45 +- src/reference/Direction.h | 7 +- src/reference/DotProductDistance.cpp | 15 +- src/reference/EuclideanDistance.cpp | 3 +- src/reference/FakeFrame.h | 7 +- src/reference/IntermolecularDRMSD.cpp | 23 +- src/reference/IntramolecularDRMSD.cpp | 23 +- src/reference/MahalanobisDistance.cpp | 3 +- src/reference/MetricRegister.cpp | 11 +- src/reference/MetricRegister.h | 4 +- src/reference/MultiDomainRMSD.cpp | 161 ++- src/reference/NormalizedEuclideanDistance.cpp | 3 +- src/reference/OptimalRMSD.cpp | 89 +- src/reference/RMSDBase.cpp | 3 +- src/reference/ReferenceArguments.cpp | 112 ++- src/reference/ReferenceArguments.h | 3 +- src/reference/ReferenceAtoms.cpp | 41 +- src/reference/ReferenceAtoms.h | 3 +- src/reference/ReferenceConfiguration.cpp | 68 +- src/reference/ReferenceConfiguration.h | 12 +- src/reference/ReferenceValuePack.cpp | 39 +- src/reference/ReferenceValuePack.h | 32 +- src/reference/SimpleRMSD.cpp | 42 +- src/reference/SingleDomainRMSD.cpp | 62 +- src/s2cm/S2ContactModel.cpp | 33 +- src/sasa/sasa_HASEL.cpp | 65 +- src/sasa/sasa_LCPO.cpp | 77 +- src/secondarystructure/AlphaRMSD.cpp | 21 +- src/secondarystructure/AntibetaRMSD.cpp | 51 +- src/secondarystructure/ParabetaRMSD.cpp | 51 +- .../SecondaryStructureRMSD.cpp | 114 ++- .../SecondaryStructureRMSD.h | 7 +- src/setup/Load.cpp | 6 +- src/setup/Restart.cpp | 14 +- src/setup/Units.cpp | 56 +- src/tools/BiasRepresentation.cpp | 113 ++- src/tools/Brent1DRootSearch.h | 73 +- src/tools/Citations.cpp | 12 +- src/tools/Communicator.cpp | 165 +++- src/tools/Communicator.h | 114 ++- src/tools/ConjugateGradient.h | 26 +- src/tools/DLLoader.cpp | 8 +- src/tools/DynamicList.h | 90 +- 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 | 408 ++++++-- src/tools/Grid.h | 53 +- 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 | 406 ++++++-- src/tools/Keywords.h | 54 +- src/tools/LatticeReduction.cpp | 83 +- src/tools/LinkCells.cpp | 64 +- src/tools/Log.h | 3 +- src/tools/Matrix.h | 357 +++++-- src/tools/Minimise1DBrent.h | 99 +- src/tools/MinimiseBase.h | 15 +- src/tools/MolDataClass.cpp | 482 ++++++--- src/tools/MultiValue.cpp | 77 +- src/tools/MultiValue.h | 26 +- src/tools/NeighborList.cpp | 38 +- src/tools/NeighborList.h | 3 +- src/tools/OFile.cpp | 124 ++- src/tools/OpenMP.cpp | 8 +- src/tools/OpenMP.h | 14 +- src/tools/PDB.cpp | 563 +++++++---- src/tools/Pbc.cpp | 154 ++- 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 | 32 +- src/tools/Subprocess.cpp | 74 +- src/tools/SwitchingFunction.cpp | 116 ++- src/tools/Tensor.h | 88 +- src/tools/Tools.cpp | 270 +++-- src/tools/Tools.h | 119 ++- src/tools/Tree.cpp | 29 +- src/tools/Tree.h | 3 +- src/tools/TypesafePtr.cpp | 8 +- src/tools/TypesafePtr.h | 83 +- src/tools/Units.cpp | 3 +- src/tools/Vector.h | 10 +- src/tools/h36.cpp | 103 +- src/vatom/Center.cpp | 96 +- src/vatom/FixedAtom.cpp | 22 +- src/vatom/Ghost.cpp | 18 +- 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 | 68 +- src/ves/VesBias.h | 266 +++-- src/ves/VesDeltaF.cpp | 290 +++--- src/ves/VesLinearExpansion.cpp | 23 +- src/ves/VesTools.cpp | 10 +- src/ves/VesTools.h | 14 +- src/ves/WaveletGrid.cpp | 41 +- src/vesselbase/ActionWithAveraging.cpp | 155 ++- src/vesselbase/ActionWithAveraging.h | 19 +- src/vesselbase/ActionWithInputVessel.cpp | 20 +- src/vesselbase/ActionWithVessel.cpp | 226 +++-- src/vesselbase/ActionWithVessel.h | 24 +- src/vesselbase/AltMin.cpp | 20 +- src/vesselbase/AveragingVessel.cpp | 18 +- src/vesselbase/AveragingVessel.h | 18 +- src/vesselbase/Between.cpp | 30 +- src/vesselbase/BridgeVessel.cpp | 68 +- src/vesselbase/FunctionVessel.cpp | 37 +- src/vesselbase/Highest.cpp | 3 +- src/vesselbase/Histogram.cpp | 21 +- src/vesselbase/LessThan.cpp | 18 +- src/vesselbase/Lowest.cpp | 3 +- src/vesselbase/Max.cpp | 21 +- src/vesselbase/Mean.cpp | 10 +- src/vesselbase/Min.cpp | 20 +- src/vesselbase/Moments.cpp | 73 +- src/vesselbase/MoreThan.cpp | 18 +- src/vesselbase/OrderingVessel.cpp | 21 +- src/vesselbase/ShortcutVessel.cpp | 10 +- src/vesselbase/ShortcutVessel.h | 20 +- src/vesselbase/StoreDataVessel.cpp | 88 +- src/vesselbase/StoreDataVessel.h | 33 +- src/vesselbase/Sum.cpp | 6 +- src/vesselbase/ValueVessel.cpp | 17 +- src/vesselbase/Vessel.cpp | 44 +- src/vesselbase/Vessel.h | 25 +- src/vesselbase/VesselRegister.cpp | 14 +- src/wrapper/Plumed.h | 386 ++++++-- 566 files changed, 26830 insertions(+), 13029 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/ActionWithInputMatrix.cpp b/src/adjmat/ActionWithInputMatrix.cpp index 449240d64a..775ecec4c3 100644 --- a/src/adjmat/ActionWithInputMatrix.cpp +++ b/src/adjmat/ActionWithInputMatrix.cpp @@ -38,25 +38,38 @@ void ActionWithInputMatrix::registerKeywords( Keywords& keys ) { ActionWithInputMatrix::ActionWithInputMatrix(const ActionOptions& ao): Action(ao), MultiColvarBase(ao), - mymatrix(NULL) -{ + mymatrix(NULL) { matsums=true; if( keywords.exists("MATRIX") ) { std::vector fake_atoms; - if( !parseMultiColvarAtomList("MATRIX",-1,fake_atoms ) ) error("unable to interpret input matrix"); - if( mybasemulticolvars.size()!=1 ) error("should be exactly one matrix input"); + if( !parseMultiColvarAtomList("MATRIX",-1,fake_atoms ) ) { + error("unable to interpret input matrix"); + } + if( mybasemulticolvars.size()!=1 ) { + error("should be exactly one matrix input"); + } // Retrieve the adjacency matrix of interest for(unsigned i=0; igetNumberOfVessels(); ++i) { mymatrix = dynamic_cast( mybasemulticolvars[0]->getPntrToVessel(i) ); - if( mymatrix ) break ; + if( mymatrix ) { + break ; + } + } + if( !mymatrix ) { + error( mybasemulticolvars[0]->getLabel() + " does not calculate an adjacency matrix"); } - if( !mymatrix ) error( mybasemulticolvars[0]->getLabel() + " does not calculate an adjacency matrix"); - atom_lab.resize(0); unsigned nnodes; // Delete all the atom labels that have been created - if( mymatrix->undirectedGraph() ) nnodes = (mymatrix->function)->ablocks[0].size(); - else nnodes = (mymatrix->function)->ablocks[0].size() + (mymatrix->function)->ablocks[1].size(); - for(unsigned i=0; i( 1, i ) ); + atom_lab.resize(0); + unsigned nnodes; // Delete all the atom labels that have been created + if( mymatrix->undirectedGraph() ) { + nnodes = (mymatrix->function)->ablocks[0].size(); + } else { + nnodes = (mymatrix->function)->ablocks[0].size() + (mymatrix->function)->ablocks[1].size(); + } + for(unsigned i=0; i( 1, i ) ); + } } } @@ -77,7 +90,9 @@ AtomNumber ActionWithInputMatrix::getAbsoluteIndexOfCentralAtom(const unsigned& } double ActionWithInputMatrix::retrieveConnectionValue( const unsigned& i, const unsigned& j, std::vector& vals ) const { - if( !mymatrix->matrixElementIsActive( i, j ) ) return 0; + if( !mymatrix->matrixElementIsActive( i, j ) ) { + return 0; + } unsigned myelem = mymatrix->getStoreIndexFromMatrixIndices( i, j ); // unsigned vi; double df; @@ -87,18 +102,24 @@ double ActionWithInputMatrix::retrieveConnectionValue( const unsigned& i, const void ActionWithInputMatrix::getInputData( const unsigned& ind, const bool& normed, const multicolvar::AtomValuePack& myatoms, std::vector& orient0 ) const { if( (mymatrix->function)->mybasemulticolvars.size()==0 ) { - std::vector tvals( mymatrix->getNumberOfComponents() ); orient0.assign(orient0.size(),0); + std::vector tvals( mymatrix->getNumberOfComponents() ); + orient0.assign(orient0.size(),0); for(unsigned i=0; igetNumberOfColumns(); ++i) { - if( mymatrix->undirectedGraph() && ind==i ) continue; + if( mymatrix->undirectedGraph() && ind==i ) { + continue; + } orient0[1]+=retrieveConnectionValue( ind, i, tvals ); } - orient0[0]=1.0; return; + orient0[0]=1.0; + return; } (mymatrix->function)->getInputData( ind, normed, myatoms, orient0 ); } void ActionWithInputMatrix::addConnectionDerivatives( const unsigned& i, const unsigned& j, MultiValue& myvals, MultiValue& myvout ) const { - if( !mymatrix->matrixElementIsActive( i, j ) ) return; + if( !mymatrix->matrixElementIsActive( i, j ) ) { + return; + } unsigned myelem = mymatrix->getStoreIndexFromMatrixIndices( i, j ); // Get derivatives and add mymatrix->retrieveDerivatives( myelem, false, myvals ); @@ -117,22 +138,29 @@ MultiValue& ActionWithInputMatrix::getInputDerivatives( const unsigned& ind, con myder.clearAll(); MultiValue myvals( (mymatrix->function)->getNumberOfQuantities(), (mymatrix->function)->getNumberOfDerivatives() ); for(unsigned i=0; igetNumberOfColumns(); ++i) { - if( mymatrix->undirectedGraph() && ind==i ) continue; + if( mymatrix->undirectedGraph() && ind==i ) { + continue; + } addConnectionDerivatives( ind, i, myvals, myder ); } - myder.updateDynamicList(); return myder; + myder.updateDynamicList(); + return myder; } return (mymatrix->function)->getInputDerivatives( ind, normed, myatoms ); } unsigned ActionWithInputMatrix::getNumberOfNodeTypes() const { unsigned size = (mymatrix->function)->mybasemulticolvars.size(); - if( size==0 ) return 1; + if( size==0 ) { + return 1; + } return size; } unsigned ActionWithInputMatrix::getNumberOfQuantities() const { - if( (mymatrix->function)->mybasemulticolvars.size()==0 ) return 2; + if( (mymatrix->function)->mybasemulticolvars.size()==0 ) { + return 2; + } return (mymatrix->function)->mybasemulticolvars[0]->getNumberOfQuantities(); } diff --git a/src/adjmat/ActionWithInputMatrix.h b/src/adjmat/ActionWithInputMatrix.h index 9d5c44dcdd..e21270468b 100644 --- a/src/adjmat/ActionWithInputMatrix.h +++ b/src/adjmat/ActionWithInputMatrix.h @@ -57,12 +57,16 @@ class ActionWithInputMatrix : public multicolvar::MultiColvarBase { unsigned getNumberOfDerivatives() override; /// Get the number of rows/cols in the adjacency matrix vessel virtual unsigned getNumberOfNodes() const; - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } unsigned getNumberOfQuantities() const override; /// AtomNumber getAbsoluteIndexOfCentralAtom(const unsigned& i) const override; /// No loop over tasks for ActionWithInputMatrix - double compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const override { plumed_error(); } + double compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const override { + plumed_error(); + } /// Vector getPositionOfAtomForLinkCells( const unsigned& iatom ) const override; }; diff --git a/src/adjmat/AdjacencyMatrixBase.cpp b/src/adjmat/AdjacencyMatrixBase.cpp index 87c47ca732..775ffc4f53 100644 --- a/src/adjmat/AdjacencyMatrixBase.cpp +++ b/src/adjmat/AdjacencyMatrixBase.cpp @@ -31,7 +31,8 @@ namespace adjmat { void AdjacencyMatrixBase::registerKeywords( Keywords& keys ) { multicolvar::MultiColvarBase::registerKeywords( keys ); - keys.remove("LOWMEM"); keys.use("HIGHMEM"); + keys.remove("LOWMEM"); + keys.use("HIGHMEM"); } AdjacencyMatrixBase::AdjacencyMatrixBase(const ActionOptions& ao): @@ -39,8 +40,7 @@ AdjacencyMatrixBase::AdjacencyMatrixBase(const ActionOptions& ao): MultiColvarBase(ao), connect_id(0), no_third_dim_accum(true), - mat(NULL) -{ + mat(NULL) { log<<" Bibliography "< sw; if( !multiple ) { - sw.resize(1); parse(key,sw[0]); - if(sw[0].length()==0) error("could not find " + key + " keyword"); + sw.resize(1); + parse(key,sw[0]); + if(sw[0].length()==0) { + error("could not find " + key + " keyword"); + } } else { std::string input; for(int i=1;; i++) { - if( !parseNumbered(key, i, input ) ) break; + if( !parseNumbered(key, i, input ) ) { + break; + } sw.push_back( input ); } } setupConnector( connect_id, 0, 0, sw ); } else { - if( multiple ) error("keyword " + key + " does not work with multiple input strings"); + if( multiple ) { + error("keyword " + key + " does not work with multiple input strings"); + } unsigned nr, nc; if( nrow_t==0 ) { nr=nc=getNumberOfNodeTypes(); } else { - nr=nrow_t; nc = getNumberOfNodeTypes() - nr; + nr=nrow_t; + nc = getNumberOfNodeTypes() - nr; } for(unsigned i=0; i sw(1); parseNumbered(key,ibase+j+1,sw[0]); + std::vector sw(1); + parseNumbered(key,ibase+j+1,sw[0]); if(sw[0].length()==0) { - std::string num; Tools::convert(ibase+j+1,num); + std::string num; + Tools::convert(ibase+j+1,num); error("could not find " + key + num + " keyword. Need one " + key + " keyword for each distinct base-multicolvar-pair type"); } setupConnector( connect_id, i, j, sw ); @@ -91,18 +101,24 @@ void AdjacencyMatrixBase::parseConnectionDescriptions( const std::string& key, c } unsigned AdjacencyMatrixBase::getSizeOfInputVectors() const { - if( mybasemulticolvars.size()==0 ) return 2; + if( mybasemulticolvars.size()==0 ) { + return 2; + } unsigned nq = mybasemulticolvars[0]->getNumberOfQuantities(); for(unsigned i=1; igetNumberOfQuantities()!=nq ) error("mismatch between vectors in base colvars"); + if( mybasemulticolvars[i]->getNumberOfQuantities()!=nq ) { + error("mismatch between vectors in base colvars"); + } } return nq; } unsigned AdjacencyMatrixBase::getNumberOfNodeTypes() const { unsigned size=mybasemulticolvars.size(); - if( size==0 ) return 1; + if( size==0 ) { + return 1; + } return size; } @@ -110,57 +126,90 @@ void AdjacencyMatrixBase::retrieveTypeDimensions( unsigned& nrows, unsigned& nco bool allsame=(ablocks[0].size()==ablocks[1].size()); if( allsame ) { for(unsigned i=0; i types(1); types[0]=atom_lab[ablocks[0][0]].first; + std::vector types(1); + types[0]=atom_lab[ablocks[0][0]].first; for(unsigned i=1; i types(1); types[0]=atom_lab[ablocks[0][0]].first; + std::vector types(1); + types[0]=atom_lab[ablocks[0][0]].first; for(unsigned i=1; i& all_atoms ) { std::string param; - if( symmetric && ablocks[0].size()==ablocks[1].size() ) param="SYMMETRIC"; + if( symmetric && ablocks[0].size()==ablocks[1].size() ) { + param="SYMMETRIC"; + } if( !symmetric ) { bool usehbonds=( ablocks[0].size()==ablocks[1].size() ); if( usehbonds ) { for(unsigned i=0; i(da2); addVessel( std::move( ves ) ); @@ -168,12 +217,14 @@ void AdjacencyMatrixBase::finishMatrixSetup( const bool& symmetric, const std::v } void AdjacencyMatrixBase::readMaxTwoSpeciesMatrix( const std::string& key0, const std::string& key1, const std::string& key2, const bool& symmetric ) { - std::vector all_atoms; readTwoGroups( key0, key1, key2, all_atoms ); + std::vector all_atoms; + readTwoGroups( key0, key1, key2, all_atoms ); finishMatrixSetup( symmetric, all_atoms ); } void AdjacencyMatrixBase::readMaxThreeSpeciesMatrix( const std::string& key0, const std::string& key1, const std::string& key2, const std::string& keym, const bool& symmetric ) { - std::vector all_atoms; readGroupKeywords( key0, key1, key2, keym, true, symmetric, all_atoms ); + std::vector all_atoms; + readGroupKeywords( key0, key1, key2, keym, true, symmetric, all_atoms ); finishMatrixSetup( symmetric, all_atoms ); } @@ -185,10 +236,13 @@ void AdjacencyMatrixBase::readMaxThreeSpeciesMatrix( const std::string& key0, co // } void AdjacencyMatrixBase::recalculateMatrixElement( const unsigned& myelem, MultiValue& myvals ) { - std::vector myatoms; decodeIndexToAtoms( getTaskCode( myelem ), myatoms ); + std::vector myatoms; + decodeIndexToAtoms( getTaskCode( myelem ), myatoms ); unsigned i=myatoms[0], j=myatoms[1]; for(unsigned k=bookeeping(i,j).first; k& desc ) = 0; /// None of these things are allowed - bool isPeriodic() { return false; } - Vector getCentralAtom() { plumed_merror("cannot find central atoms for adjacency matrix actions"); } + bool isPeriodic() { + return false; + } + Vector getCentralAtom() { + plumed_merror("cannot find central atoms for adjacency matrix actions"); + } /// Get the atom number AtomNumber getAbsoluteIndexOfCentralAtom( const unsigned& i ) const ; }; @@ -86,7 +90,9 @@ AdjacencyMatrixVessel* AdjacencyMatrixBase::getAdjacencyVessel() { inline unsigned AdjacencyMatrixBase::getBaseColvarNumber( const unsigned& inum ) const { - if( atom_lab[inum].first>0 ) return atom_lab[inum].first-1; + if( atom_lab[inum].first>0 ) { + return atom_lab[inum].first-1; + } return 0; } diff --git a/src/adjmat/AdjacencyMatrixVessel.cpp b/src/adjmat/AdjacencyMatrixVessel.cpp index b4136f0f53..3e916b00ed 100644 --- a/src/adjmat/AdjacencyMatrixVessel.cpp +++ b/src/adjmat/AdjacencyMatrixVessel.cpp @@ -33,14 +33,20 @@ void AdjacencyMatrixVessel::registerKeywords( Keywords& keys ) { } AdjacencyMatrixVessel::AdjacencyMatrixVessel( const vesselbase::VesselOptions& da ): - StoreDataVessel(da) -{ + StoreDataVessel(da) { function=dynamic_cast( getAction() ); plumed_assert( function ); - parseFlag("SYMMETRIC",symmetric); parseFlag("HBONDS",hbonds); - if( symmetric && hbonds ) error("matrix should be either symmetric or hbonds"); - if( symmetric && function->ablocks[0].size()!=function->ablocks[1].size() ) error("matrix is supposed to be symmetric but nrows!=ncols"); - if( hbonds && function->ablocks[0].size()!=function->ablocks[1].size() ) error("matrix is supposed to be hbonds but nrows!=ncols"); + parseFlag("SYMMETRIC",symmetric); + parseFlag("HBONDS",hbonds); + if( symmetric && hbonds ) { + error("matrix should be either symmetric or hbonds"); + } + if( symmetric && function->ablocks[0].size()!=function->ablocks[1].size() ) { + error("matrix is supposed to be symmetric but nrows!=ncols"); + } + if( hbonds && function->ablocks[0].size()!=function->ablocks[1].size() ) { + error("matrix is supposed to be hbonds but nrows!=ncols"); + } } bool AdjacencyMatrixVessel::isSymmetric() const { @@ -64,13 +70,19 @@ bool AdjacencyMatrixVessel::matrixElementIsActive( const unsigned& ielem, const } unsigned AdjacencyMatrixVessel::getStoreIndexFromMatrixIndices( const unsigned& ielem, const unsigned& jelem ) const { - if( !symmetric && !hbonds ) return (function->ablocks[1].size())*ielem + jelem; + if( !symmetric && !hbonds ) { + return (function->ablocks[1].size())*ielem + jelem; + } if( !symmetric ) { plumed_dbg_assert( ielem!=jelem ); - if( jelemablocks[1].size()-1)*ielem + jelem; + if( jelemablocks[1].size()-1)*ielem + jelem; + } return (function->ablocks[1].size()-1)*ielem + jelem - 1; } - if( ielem>jelem ) return 0.5*ielem*(ielem-1)+jelem; + if( ielem>jelem ) { + return 0.5*ielem*(ielem-1)+jelem; + } return 0.5*jelem*(jelem-1) + ielem; } @@ -79,22 +91,33 @@ AdjacencyMatrixBase* AdjacencyMatrixVessel::getMatrixAction() { } void AdjacencyMatrixVessel::getMatrixIndices( const unsigned& code, unsigned& i, unsigned& j ) const { - std::vector myatoms; function->decodeIndexToAtoms( function->getTaskCode(code), myatoms ); - i=myatoms[0]; j=myatoms[1]; - if( !undirectedGraph() ) j -= function->ablocks[0].size(); // Have to remove number of columns as returns number in ablocks[1] + std::vector myatoms; + function->decodeIndexToAtoms( function->getTaskCode(code), myatoms ); + i=myatoms[0]; + j=myatoms[1]; + if( !undirectedGraph() ) { + j -= function->ablocks[0].size(); // Have to remove number of columns as returns number in ablocks[1] + } } void AdjacencyMatrixVessel::retrieveMatrix( DynamicList& myactive_elements, Matrix& mymatrix ) { - myactive_elements.deactivateAll(); std::vector vals( getNumberOfComponents() ); + myactive_elements.deactivateAll(); + std::vector vals( getNumberOfComponents() ); for(unsigned i=0; igetPositionInFullTaskList(i), k, j ); - - if( symmetric ) mymatrix(k,j)=mymatrix(j,k)=vals[0]*vals[1]; - else mymatrix(k,j)=vals[0]*vals[1]; + unsigned j, k; + getMatrixIndices( function->getPositionInFullTaskList(i), k, j ); + + if( symmetric ) { + mymatrix(k,j)=mymatrix(j,k)=vals[0]*vals[1]; + } else { + mymatrix(k,j)=vals[0]*vals[1]; + } } myactive_elements.updateActiveMembers(); } @@ -102,34 +125,48 @@ void AdjacencyMatrixVessel::retrieveMatrix( DynamicList& myactive_elem void AdjacencyMatrixVessel::retrieveAdjacencyLists( std::vector& nneigh, Matrix& adj_list ) { plumed_dbg_assert( undirectedGraph() ); // Currently everything has zero neighbors - for(unsigned i=0; i myvals( getNumberOfComponents() ); for(unsigned i=0; igetPositionInFullTaskList(i), k, j ); + unsigned j, k; + getMatrixIndices( function->getPositionInFullTaskList(i), k, j ); - if( nneigh[j]>=adj_list.ncols() || nneigh[k]>=adj_list.ncols() ) error("adjacency lists are not large enough, increase maxconnections"); + if( nneigh[j]>=adj_list.ncols() || nneigh[k]>=adj_list.ncols() ) { + error("adjacency lists are not large enough, increase maxconnections"); + } // Store if atoms are connected // unsigned j, k; getMatrixIndices( i, k, j ); - adj_list(k,nneigh[k])=j; nneigh[k]++; - adj_list(j,nneigh[j])=k; nneigh[j]++; + adj_list(k,nneigh[k])=j; + nneigh[k]++; + adj_list(j,nneigh[j])=k; + nneigh[j]++; } } void AdjacencyMatrixVessel::retrieveEdgeList( unsigned& nedge, std::vector >& edge_list ) { - plumed_dbg_assert( undirectedGraph() ); nedge=0; + plumed_dbg_assert( undirectedGraph() ); + nedge=0; std::vector myvals( getNumberOfComponents() ); - if( getNumberOfStoredValues()>edge_list.size() ) error("adjacency lists are not large enough, increase maxconnections"); + if( getNumberOfStoredValues()>edge_list.size() ) { + error("adjacency lists are not large enough, increase maxconnections"); + } for(unsigned i=0; igetPositionInFullTaskList(i), edge_list[nedge].first, edge_list[nedge].second ); nedge++; @@ -137,7 +174,9 @@ void AdjacencyMatrixVessel::retrieveEdgeList( unsigned& nedge, std::vector myvals( getNumberOfComponents() ); diff --git a/src/adjmat/AlignedMatrixBase.cpp b/src/adjmat/AlignedMatrixBase.cpp index 7d865e964d..a251264649 100644 --- a/src/adjmat/AlignedMatrixBase.cpp +++ b/src/adjmat/AlignedMatrixBase.cpp @@ -47,13 +47,17 @@ void AlignedMatrixBase::registerKeywords( Keywords& keys ) { AlignedMatrixBase::AlignedMatrixBase( const ActionOptions& ao ): Action(ao), - AdjacencyMatrixBase(ao) -{ + AdjacencyMatrixBase(ao) { // Read in the atomic positions readMaxTwoSpeciesMatrix( "ATOMS", "ATOMSA", "ATOMSB", true ); - unsigned nrows, ncols; retrieveTypeDimensions( nrows, ncols, ncol_t ); - if( mybasemulticolvars.size()==0 ) error("cannot use atom indices as input to this variable / input was not specified"); - if( getSizeOfInputVectors()<3 ) error("base multicolvars do not calculate an orientation"); + unsigned nrows, ncols; + retrieveTypeDimensions( nrows, ncols, ncol_t ); + if( mybasemulticolvars.size()==0 ) { + error("cannot use atom indices as input to this variable / input was not specified"); + } + if( getSizeOfInputVectors()<3 ) { + error("base multicolvars do not calculate an orientation"); + } // Read in the switching function switchingFunction.resize( nrows, ncols ); parseConnectionDescriptions("SWITCH",false,ncol_t); @@ -63,7 +67,9 @@ AlignedMatrixBase::AlignedMatrixBase( const ActionOptions& ao ): for(unsigned i=0; isfmax ) sfmax=tsf; + if( tsf>sfmax ) { + sfmax=tsf; + } } } // And set the link cell cutoff @@ -73,9 +79,15 @@ AlignedMatrixBase::AlignedMatrixBase( const ActionOptions& ao ): void AlignedMatrixBase::setupConnector( const unsigned& id, const unsigned& i, const unsigned& j, const std::vector& desc ) { plumed_assert( id<2 ); if( id==0 ) { - plumed_assert( desc.size()==1 ); std::string errors; switchingFunction(j,i).set(desc[0],errors); - if( errors.length()!=0 ) error("problem reading switching function in SWITCH keywrd description " + errors); - if( j!=i) switchingFunction(i,j).set(desc[0],errors); + plumed_assert( desc.size()==1 ); + std::string errors; + switchingFunction(j,i).set(desc[0],errors); + if( errors.length()!=0 ) { + error("problem reading switching function in SWITCH keywrd description " + errors); + } + if( j!=i) { + switchingFunction(i,j).set(desc[0],errors); + } log.printf(" %u th and %u th multicolvar groups must be within %s\n",i+1,j+1,(switchingFunction(i,j).description()).c_str() ); } else if( id==1 ) { readOrientationConnector( i, j, desc ); @@ -84,15 +96,19 @@ void AlignedMatrixBase::setupConnector( const unsigned& id, const unsigned& i, c double AlignedMatrixBase::calculateWeight( const unsigned& taskCode, const double& weight, multicolvar::AtomValuePack& myatoms ) const { Vector distance = getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); - if( distance.modulo2() orient0(ncomp), orient1(ncomp), dorient0(ncomp), dorient1(ncomp); Vector distance = getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); - getInputData( 0, true, myatoms, orient0 ); getInputData( 1, true, myatoms, orient1 ); + getInputData( 0, true, myatoms, orient0 ); + getInputData( 1, true, myatoms, orient1 ); double f_dot = computeVectorFunction( getBaseColvarNumber( myatoms.getIndex(0) ), getBaseColvarNumber( myatoms.getIndex(1) )-ncol_t, distance, orient0, orient1, ddistance, dorient0, dorient1 ); @@ -105,7 +121,10 @@ double AlignedMatrixBase::compute( const unsigned& tindex, multicolvar::AtomValu myatoms.addBoxDerivatives( 1, (-dfunc)*f_dot*Tensor(distance,distance) - sw*extProduct( distance, ddistance ) ); // Add derivatives of orientation - for(unsigned k=2; k fake_atoms; + matsums=usespecies=true; + std::vector fake_atoms; // Find what action we are taking the clusters from - if( !parseMultiColvarAtomList("CLUSTERS",-1,fake_atoms ) ) error("unable to interpret input CLUSTERS" ); - if( mybasemulticolvars.size()!=1 ) error("should be exactly one multicolvar input"); - atom_lab.resize(0); myclusters = dynamic_cast( mybasemulticolvars[0] ); - if( !myclusters ) error("input label is not that of a DFS object"); + if( !parseMultiColvarAtomList("CLUSTERS",-1,fake_atoms ) ) { + error("unable to interpret input CLUSTERS" ); + } + if( mybasemulticolvars.size()!=1 ) { + error("should be exactly one multicolvar input"); + } + atom_lab.resize(0); + myclusters = dynamic_cast( mybasemulticolvars[0] ); + if( !myclusters ) { + error("input label is not that of a DFS object"); + } // Setup the atom pack myfatoms.setNumberOfAtoms( myclusters->getNumberOfNodes() ); myfvals.getIndices().resize( myclusters->getNumberOfNodes() ); - for(unsigned i=0; igetNumberOfNodes(); ++i) myfatoms.setAtomIndex( i, i ); + for(unsigned i=0; igetNumberOfNodes(); ++i) { + myfatoms.setAtomIndex( i, i ); + } } void ClusterAnalysisBase::turnOnDerivatives() { // Check for dubious vessels for(unsigned i=0; igetName()=="MEAN" ) error("MEAN of cluster is not differentiable"); - if( getPntrToVessel(i)->getName()=="VMEAN" ) error("VMEAN of cluster is not differentiable"); + if( getPntrToVessel(i)->getName()=="MEAN" ) { + error("MEAN of cluster is not differentiable"); + } + if( getPntrToVessel(i)->getName()=="VMEAN" ) { + error("VMEAN of cluster is not differentiable"); + } } MultiColvarBase::turnOnDerivatives(); } diff --git a/src/adjmat/ClusterAnalysisBase.h b/src/adjmat/ClusterAnalysisBase.h index 97593afb5d..b43cb465cd 100644 --- a/src/adjmat/ClusterAnalysisBase.h +++ b/src/adjmat/ClusterAnalysisBase.h @@ -50,7 +50,9 @@ class ClusterAnalysisBase : public multicolvar::MultiColvarBase { void turnOnDerivatives() override; void setupActiveTaskSet( std::vector& active_tasks, const std::string& input_label ) {} Vector getPositionOfAtomForLinkCells( const unsigned& ) const override; - double compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const override { plumed_error(); } + double compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const override { + plumed_error(); + } }; } diff --git a/src/adjmat/ClusterDiameter.cpp b/src/adjmat/ClusterDiameter.cpp index aa67dce394..1879d81134 100644 --- a/src/adjmat/ClusterDiameter.cpp +++ b/src/adjmat/ClusterDiameter.cpp @@ -86,20 +86,27 @@ void ClusterDiameter::registerKeywords( Keywords& keys ) { ClusterDiameter::ClusterDiameter(const ActionOptions&ao): Action(ao), - ClusterAnalysisBase(ao) -{ + ClusterAnalysisBase(ao) { // 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>getNumberOfNodes() ) 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>getNumberOfNodes() ) { + error("cluster selected is invalid - too few atoms in system"); + } // Create the task list for(unsigned i=0; i fake_atoms; setupMultiColvarBase( fake_atoms ); + addVessel("HIGHEST", "", -1); + std::vector fake_atoms; + setupMultiColvarBase( fake_atoms ); } void ClusterDiameter::turnOnDerivatives() { @@ -108,11 +115,14 @@ void ClusterDiameter::turnOnDerivatives() { void ClusterDiameter::calculate() { // Retrieve the atoms in the largest cluster - std::vector myatoms; retrieveAtomsInCluster( clustr, myatoms ); + std::vector myatoms; + retrieveAtomsInCluster( clustr, myatoms ); // Activate the relevant tasks deactivateAllTasks(); for(unsigned i=1; i fake_atoms; setupMultiColvarBase( fake_atoms ); + std::vector fake_atoms; + setupMultiColvarBase( fake_atoms ); } void ClusterDistribution::calculate() { // Activate the relevant tasks nderivatives = getNumberOfDerivatives(); deactivateAllTasks(); - for(unsigned i=0; i myatoms; retrieveAtomsInCluster( current+1, myatoms ); + std::vector myatoms; + retrieveAtomsInCluster( current+1, myatoms ); // This deals with filters - if( myatoms.size()==1 && !nodeIsActive(myatoms[0]) ) return ; + if( myatoms.size()==1 && !nodeIsActive(myatoms[0]) ) { + return ; + } std::vector vals( getNumberOfQuantities() ); MultiValue tvals( getNumberOfQuantities(), nderivatives ); @@ -137,12 +155,16 @@ void ClusterDistribution::performTask( const unsigned& task_index, const unsigne getPropertiesOfNode( i, vals ); if( use_switch && !inverse ) { vv = 1.0 - sf.calculate( vals[1], df ); - tval += vals[0]*vv; df=-df*vals[1]; + tval += vals[0]*vv; + df=-df*vals[1]; } else if( use_switch ) { vv = sf.calculate( vals[1], df ); - tval += vals[0]*vv; df=df*vals[1]; + tval += vals[0]*vv; + df=df*vals[1]; } else { - tval += vals[0]*vals[1]; df=1.; vv=vals[1]; + tval += vals[0]*vals[1]; + df=1.; + vv=vals[1]; } if( !doNotCalculateDerivatives() ) { getNodePropertyDerivatives( i, tvals ); @@ -153,7 +175,8 @@ void ClusterDistribution::performTask( const unsigned& task_index, const unsigne tvals.clearAll(); } } - myvals.setValue( 0, 1.0 ); myvals.setValue( 1, tval ); + myvals.setValue( 0, 1.0 ); + myvals.setValue( 1, tval ); } } diff --git a/src/adjmat/ClusterProperties.cpp b/src/adjmat/ClusterProperties.cpp index 5739fd443b..d27c5ba518 100644 --- a/src/adjmat/ClusterProperties.cpp +++ b/src/adjmat/ClusterProperties.cpp @@ -76,45 +76,72 @@ PLUMED_REGISTER_ACTION(ClusterProperties,"CLUSTER_PROPERTIES") void ClusterProperties::registerKeywords( Keywords& keys ) { ClusterAnalysisBase::registerKeywords( keys ); 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.use("MEAN"); keys.use("MORE_THAN"); keys.use("LESS_THAN"); - if( keys.reserved("VMEAN") ) keys.use("VMEAN"); - if( keys.reserved("VSUM") ) keys.use("VSUM"); - keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); keys.use("ALT_MIN"); - keys.use("MIN"); keys.use("MAX"); keys.use("SUM"); keys.use("LOWEST"); keys.use("HIGHEST"); + keys.use("MEAN"); + keys.use("MORE_THAN"); + keys.use("LESS_THAN"); + if( keys.reserved("VMEAN") ) { + keys.use("VMEAN"); + } + if( keys.reserved("VSUM") ) { + keys.use("VSUM"); + } + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); + keys.use("ALT_MIN"); + keys.use("MIN"); + keys.use("MAX"); + keys.use("SUM"); + keys.use("LOWEST"); + keys.use("HIGHEST"); } ClusterProperties::ClusterProperties(const ActionOptions&ao): Action(ao), - ClusterAnalysisBase(ao) -{ + ClusterAnalysisBase(ao) { // 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>getNumberOfNodes() ) 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>getNumberOfNodes() ) { + error("cluster selected is invalid - too few atoms in system"); + } // Create all tasks by copying those from underlying DFS object (which is actually MultiColvar) - for(unsigned i=0; i fake_atoms; setupMultiColvarBase( fake_atoms ); + std::vector fake_atoms; + setupMultiColvarBase( fake_atoms ); } void ClusterProperties::calculate() { // Retrieve the atoms in the largest cluster - std::vector myatoms; retrieveAtomsInCluster( clustr, myatoms ); + std::vector myatoms; + retrieveAtomsInCluster( clustr, myatoms ); // Activate the relevant tasks deactivateAllTasks(); - for(unsigned i=0; i vals( myvals.getNumberOfValues() ); getPropertiesOfNode( current, vals ); - if( !doNotCalculateDerivatives() ) getNodePropertyDerivatives( current, myvals ); - for(unsigned k=0; k vals( myvals.getNumberOfValues() ); + getPropertiesOfNode( current, vals ); + if( !doNotCalculateDerivatives() ) { + getNodePropertyDerivatives( current, myvals ); + } + for(unsigned k=0; kgetNumberOfNodes() ) 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>getNumberOfNodes() ) { + error("cluster selected is invalid - too few atoms in system"); + } // Create all tasks by copying those from underlying DFS object (which is actually MultiColvar) - for(unsigned i=0; i fake_atoms; setupMultiColvarBase( fake_atoms ); - addValue(); setNotPeriodic(); + std::vector fake_atoms; + setupMultiColvarBase( fake_atoms ); + addValue(); + setNotPeriodic(); } void ClusterSize::turnOnDerivatives() { @@ -106,7 +115,9 @@ void ClusterSize::turnOnDerivatives() { void ClusterSize::calculate() { // Retrieve the atoms in the largest cluster - std::vector myatoms; retrieveAtomsInCluster( clustr, myatoms ); setValue( myatoms.size() ); + std::vector myatoms; + retrieveAtomsInCluster( clustr, myatoms ); + setValue( myatoms.size() ); } } diff --git a/src/adjmat/ClusterWithSurface.cpp b/src/adjmat/ClusterWithSurface.cpp index 780dd7ab95..acb7be9e16 100644 --- a/src/adjmat/ClusterWithSurface.cpp +++ b/src/adjmat/ClusterWithSurface.cpp @@ -107,19 +107,28 @@ void ClusterWithSurface::registerKeywords( Keywords& keys ) { ClusterWithSurface::ClusterWithSurface(const ActionOptions&ao): Action(ao), - ClusteringBase(ao) -{ + ClusteringBase(ao) { std::vector fake_atoms; - if( !parseMultiColvarAtomList("CLUSTERS",-1,fake_atoms ) ) error("unable to find CLUSTERS input"); - if( mybasemulticolvars.size()!=1 ) error("should be exactly one multicolvar input"); + if( !parseMultiColvarAtomList("CLUSTERS",-1,fake_atoms ) ) { + error("unable to find CLUSTERS input"); + } + if( mybasemulticolvars.size()!=1 ) { + error("should be exactly one multicolvar input"); + } // Retrieve the adjacency matrix of interest - atom_lab.resize(0); myclusters = dynamic_cast( mybasemulticolvars[0] ); - if( !myclusters ) error( mybasemulticolvars[0]->getLabel() + " does not calculate clusters"); + atom_lab.resize(0); + myclusters = dynamic_cast( mybasemulticolvars[0] ); + if( !myclusters ) { + error( mybasemulticolvars[0]->getLabel() + " does not calculate clusters"); + } // Setup switching function for surface atoms - double rcut_surf; parse("RCUT_SURF",rcut_surf); - if( rcut_surf>0 ) log.printf(" counting surface atoms that are within %f of the cluster atoms \n",rcut_surf); + double rcut_surf; + parse("RCUT_SURF",rcut_surf); + if( rcut_surf>0 ) { + log.printf(" counting surface atoms that are within %f of the cluster atoms \n",rcut_surf); + } rcut_surf2=rcut_surf*rcut_surf; // And now finish the setup of everything in the base @@ -152,35 +161,51 @@ unsigned ClusterWithSurface::getNumberOfQuantities() const { double ClusterWithSurface::getCutoffForConnection() const { double tcut = myclusters->getCutoffForConnection(); - if( tcut>std::sqrt(rcut_surf2) ) return tcut; + if( tcut>std::sqrt(rcut_surf2) ) { + return tcut; + } return std::sqrt(rcut_surf2); } void ClusterWithSurface::retrieveAtomsInCluster( const unsigned& clust, std::vector& myatoms ) const { - std::vector tmpat; myclusters->retrieveAtomsInCluster( clust, tmpat ); + std::vector tmpat; + myclusters->retrieveAtomsInCluster( clust, tmpat ); // Prevent double counting std::vector incluster( getNumberOfNodes(), false ); - for(unsigned i=0; i surface_atom( getNumberOfNodes(), false ); for(unsigned i=0; iundirectedGraph() ) error("input contact matrix is incompatible with clustering"); + cluster_sizes.resize(getNumberOfNodes()); + which_cluster.resize(getNumberOfNodes()); + if( getNumberOfNodeTypes()!=1 ) { + error("should only be running clustering with one base multicolvar in function"); + } + if( !getAdjacencyVessel()->undirectedGraph() ) { + error("input contact matrix is incompatible with clustering"); + } } if( keywords.exists("MATRIX") ) { - std::vector fake_atoms; setupMultiColvarBase( fake_atoms ); + std::vector fake_atoms; + setupMultiColvarBase( fake_atoms ); } } void ClusteringBase::turnOnDerivatives() { // Check base multicolvar isn't density probably other things shouldn't be allowed here as well if( (getAdjacencyVessel()->getMatrixAction())->getNumberOfBaseMultiColvars()>0 ) { - if( getBaseMultiColvar(0)->isDensity() ) error("DFS clustering cannot be differentiated if base multicolvar is DENSITY"); + if( getBaseMultiColvar(0)->isDensity() ) { + error("DFS clustering cannot be differentiated if base multicolvar is DENSITY"); + } } // Ensure that derivatives are turned on in base classes @@ -57,7 +64,10 @@ void ClusteringBase::turnOnDerivatives() { void ClusteringBase::calculate() { // All the clusters have zero size initially - for(unsigned i=0; i& myatoms ) const { - unsigned n=0; myatoms.resize( cluster_sizes[cluster_sizes.size() - clust].first ); + unsigned n=0; + myatoms.resize( cluster_sizes[cluster_sizes.size() - clust].first ); for(unsigned i=0; i& desc ) { - plumed_assert( desc.size()==1 ); std::string errors; sf(j,i).set(desc[0],errors); - if( j!=i ) sf(i,j).set(desc[0],errors); + plumed_assert( desc.size()==1 ); + std::string errors; + sf(j,i).set(desc[0],errors); + if( j!=i ) { + sf(i,j).set(desc[0],errors); + } log.printf(" vectors in %u th and %u th groups must have a dot product that is greater than %s \n",i+1,j+1,(sf(i,j).description()).c_str() ); } double ContactAlignedMatrix::computeVectorFunction( const unsigned& iv, const unsigned& jv, const Vector& conn, const std::vector& vec1, const std::vector& vec2, Vector& dconn, std::vector& dvec1, std::vector& dvec2 ) const { - double dot_df, dot=0; dconn.zero(); - for(unsigned k=2; ksfmax ) sfmax=tsf; + if( tsf>sfmax ) { + sfmax=tsf; + } } } // And set the link cell cutoff @@ -120,15 +123,23 @@ ContactMatrix::ContactMatrix( const ActionOptions& ao ): } void ContactMatrix::setupConnector( const unsigned& id, const unsigned& i, const unsigned& j, const std::vector& desc ) { - plumed_assert( id==0 && desc.size()==1 ); std::string errors; switchingFunction(j,i).set(desc[0],errors); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); - if( j!=i) switchingFunction(i,j).set(desc[0],errors); + plumed_assert( id==0 && desc.size()==1 ); + std::string errors; + switchingFunction(j,i).set(desc[0],errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } + if( j!=i) { + switchingFunction(i,j).set(desc[0],errors); + } log.printf(" %u th and %u th multicolvar groups must be within %s\n",i+1,j+1,(switchingFunction(i,j).description()).c_str() ); } double ContactMatrix::calculateWeight( const unsigned& taskCode, const double& weight, multicolvar::AtomValuePack& myatoms ) const { Vector distance = getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); - if( distance.modulo2()0 ) edge_list.resize( getNumberOfNodes()*maxconnections ); - else edge_list.resize(0.5*getNumberOfNodes()*(getNumberOfNodes()-1)); + if( maxconnections>0 ) { + edge_list.resize( getNumberOfNodes()*maxconnections ); + } else { + edge_list.resize(0.5*getNumberOfNodes()*(getNumberOfNodes()-1)); + } #else - nneigh.resize( getNumberOfNodes() ); color.resize(getNumberOfNodes()); - if( maxconnections>0 ) adj_list.resize(getNumberOfNodes(),maxconnections); - else adj_list.resize(getNumberOfNodes(),getNumberOfNodes()); + nneigh.resize( getNumberOfNodes() ); + color.resize(getNumberOfNodes()); + if( maxconnections>0 ) { + adj_list.resize(getNumberOfNodes(),maxconnections); + } else { + adj_list.resize(getNumberOfNodes(),getNumberOfNodes()); + } #endif } void DFSClustering::performClustering() { #ifdef __PLUMED_HAS_BOOST_GRAPH // Get the list of edges - unsigned nedges=0; getAdjacencyVessel()->retrieveEdgeList( nedges, edge_list ); + unsigned nedges=0; + getAdjacencyVessel()->retrieveEdgeList( nedges, edge_list ); // Build the graph using boost boost::adjacency_list sg(&edge_list[0],&edge_list[nedges],getNumberOfNodes()); @@ -128,15 +136,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; iretrieveAdjacencyLists( nneigh, adj_list ); // Perform clustering - number_of_cluster=-1; color.assign(color.size(),0); + number_of_cluster=-1; + color.assign(color.size(),0); for(unsigned i=0; i( mstring ); - if( !mm ) error("found no action in set with label " + mstring + " that calculates matrix"); + if( !mm ) { + error("found no action in set with label " + mstring + " that calculates matrix"); + } log.printf(" printing graph for matrix calculated by action %s\n", mm->getLabel().c_str() ); // Retrieve the adjacency matrix of interest for(unsigned i=0; igetNumberOfVessels(); ++i) { mymatrix = dynamic_cast( mm->getPntrToVessel(i) ); - if( mymatrix ) break ; + if( mymatrix ) { + break ; + } + } + if( !mymatrix ) { + error( mm->getLabel() + " does not calculate an adjacency matrix"); + } + if( !mymatrix->isSymmetric() ) { + error("input contact matrix must be symmetric"); + } + if( maxconnections==0 ) { + maxconnections=mymatrix->getNumberOfRows(); } - if( !mymatrix ) error( mm->getLabel() + " does not calculate an adjacency matrix"); - if( !mymatrix->isSymmetric() ) error("input contact matrix must be symmetric"); - if( maxconnections==0 ) maxconnections=mymatrix->getNumberOfRows(); parse("FILE",filename); log.printf(" printing graph to file named %s \n",filename.c_str() ); checkRead(); } void DumpGraph::update() { - OFile ofile; ofile.link(*this); ofile.setBackupString("graph"); - ofile.open( filename ); ofile.printf("graph G { \n"); + OFile ofile; + ofile.link(*this); + ofile.setBackupString("graph"); + ofile.open( filename ); + ofile.printf("graph G { \n"); // Print all nodes - for(unsigned i=0; igetNumberOfRows(); ++i) ofile.printf("%u [label=\"%u\"];\n",i,i); + for(unsigned i=0; igetNumberOfRows(); ++i) { + ofile.printf("%u [label=\"%u\"];\n",i,i); + } // Now retrieve connectivitives - unsigned nedge; std::vector > edge_list( mymatrix->getNumberOfRows()*maxconnections ); + unsigned nedge; + std::vector > edge_list( mymatrix->getNumberOfRows()*maxconnections ); mymatrix->retrieveEdgeList( nedge, edge_list ); - for(unsigned i=0; isfmax ) sfmax=tsf; + if( tsf>sfmax ) { + sfmax=tsf; + } } } // Set the link cell cutoff @@ -161,45 +165,70 @@ HBondMatrix::HBondMatrix( const ActionOptions& ao ): void HBondMatrix::setupConnector( const unsigned& id, const unsigned& i, const unsigned& j, const std::vector& desc ) { plumed_assert( id<3 && desc.size()==1 ); if( id==0 ) { - std::string errors; distanceOOSwitch(j,i).set(desc[0],errors); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); - if( j!=i) distanceOOSwitch(i,j).set(desc[0],errors); + std::string errors; + distanceOOSwitch(j,i).set(desc[0],errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } + if( j!=i) { + distanceOOSwitch(i,j).set(desc[0],errors); + } log.printf(" atoms of type %u and %u must be within %s\n",i+1,j+1,(distanceOOSwitch(i,j).description()).c_str() ); } else if( id==1 ) { - std::string errors; distanceOHSwitch(j,i).set(desc[0],errors); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); - if( j!=i) distanceOHSwitch(i,j).set(desc[0],errors); + std::string errors; + distanceOHSwitch(j,i).set(desc[0],errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } + if( j!=i) { + distanceOHSwitch(i,j).set(desc[0],errors); + } log.printf(" for atoms of type %u and %u the OH distance must be less than %s \n",i+1,j+1,(distanceOHSwitch(i,j).description()).c_str() ); } else if( id==2 ) { - std::string errors; angleSwitch(j,i).set(desc[0],errors); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); - if( j!=i) angleSwitch(i,j).set(desc[0],errors); + std::string errors; + angleSwitch(j,i).set(desc[0],errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } + if( j!=i) { + angleSwitch(i,j).set(desc[0],errors); + } log.printf(" for atoms of type %u and %u the OOH angle must be less than %s \n",i+1,j+1,(angleSwitch(i,j).description()).c_str() ); } } double HBondMatrix::calculateWeight( const unsigned& taskCode, const double& weight, multicolvar::AtomValuePack& myatoms ) const { // Ensure we skip diagonal elements of square matrix - if( myatoms.getIndex(0)==myatoms.getIndex(1) ) return 0.0; + if( myatoms.getIndex(0)==myatoms.getIndex(1) ) { + return 0.0; + } Vector distance = getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); - if( distance.modulo2()3 ) { - for(unsigned i=2; igetMatrixAction())->mybasemulticolvars.size()>0 ) error("matrix row sums should only be calculated when inputs are atoms"); + ActionWithInputMatrix(ao) { + if( (mymatrix->getMatrixAction())->mybasemulticolvars.size()>0 ) { + error("matrix row sums should only be calculated when inputs are atoms"); + } // Setup the tasks unsigned ncols = mymatrix->getNumberOfColumns(); - ablocks.resize(1); ablocks[0].resize( ncols ); - for(unsigned i=0; iundirectedGraph() ) { - for(unsigned i=0; igetNumberOfRows() + i; + for(unsigned i=0; igetNumberOfRows() + i; + } } - std::vector fake_atoms; setupMultiColvarBase( fake_atoms ); + std::vector fake_atoms; + setupMultiColvarBase( fake_atoms ); } double MatrixColumnSums::compute( const unsigned& tinded, multicolvar::AtomValuePack& myatoms ) const { - double sum=0.0; std::vector tvals( mymatrix->getNumberOfComponents() ); + double sum=0.0; + std::vector tvals( mymatrix->getNumberOfComponents() ); unsigned nrows = mymatrix->getNumberOfRows(); for(unsigned i=0; iundirectedGraph() && tinded==i ) continue; + if( mymatrix->undirectedGraph() && tinded==i ) { + continue; + } sum+=retrieveConnectionValue( i, tinded, tvals ); } @@ -111,7 +131,9 @@ double MatrixColumnSums::compute( const unsigned& tinded, multicolvar::AtomValue MultiValue myvals( mymatrix->getNumberOfComponents(), myatoms.getNumberOfDerivatives() ); MultiValue& myvout=myatoms.getUnderlyingMultiValue(); for(unsigned i=0; iisSymmetric() && tinded==i ) continue ; + if( mymatrix->isSymmetric() && tinded==i ) { + continue ; + } addConnectionDerivatives( i, tinded, myvals, myvout ); } } diff --git a/src/adjmat/MatrixRowSums.cpp b/src/adjmat/MatrixRowSums.cpp index 4905f9b0aa..ab0568744f 100644 --- a/src/adjmat/MatrixRowSums.cpp +++ b/src/adjmat/MatrixRowSums.cpp @@ -76,29 +76,45 @@ PLUMED_REGISTER_ACTION(MatrixRowSums,"ROWSUMS") void MatrixRowSums::registerKeywords( Keywords& keys ) { ActionWithInputMatrix::registerKeywords( keys ); - keys.use("ALT_MIN"); keys.use("LOWEST"); keys.use("HIGHEST"); - keys.use("MEAN"); keys.use("MIN"); keys.use("MAX"); keys.use("LESS_THAN"); - keys.use("MORE_THAN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); + keys.use("ALT_MIN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("MEAN"); + keys.use("MIN"); + keys.use("MAX"); + keys.use("LESS_THAN"); + keys.use("MORE_THAN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); } MatrixRowSums::MatrixRowSums(const ActionOptions& ao): Action(ao), - ActionWithInputMatrix(ao) -{ - if( (mymatrix->getMatrixAction())->mybasemulticolvars.size()>0 ) warning("matrix row may be problematic when inputs are not atoms"); + ActionWithInputMatrix(ao) { + if( (mymatrix->getMatrixAction())->mybasemulticolvars.size()>0 ) { + warning("matrix row may be problematic when inputs are not atoms"); + } // Setup the tasks unsigned nrows = mymatrix->getNumberOfRows(); - ablocks.resize(1); ablocks[0].resize( nrows ); - for(unsigned i=0; i fake_atoms; setupMultiColvarBase( fake_atoms ); + ablocks.resize(1); + ablocks[0].resize( nrows ); + for(unsigned i=0; i fake_atoms; + setupMultiColvarBase( fake_atoms ); } double MatrixRowSums::compute( const unsigned& tinded, multicolvar::AtomValuePack& myatoms ) const { std::vector tvals( mymatrix->getNumberOfComponents() ); - getInputData( tinded, false, myatoms, tvals ); double fval=tvals[1]; + getInputData( tinded, false, myatoms, tvals ); + double fval=tvals[1]; if( !doNotCalculateDerivatives() ) { - tvals.assign( tvals.size(), 0 ); tvals[1]=1.0; + tvals.assign( tvals.size(), 0 ); + tvals[1]=1.0; mergeInputDerivatives( 1, 1, 2, tinded, tvals, getInputDerivatives( tinded, false, myatoms ), myatoms ); } return fval; diff --git a/src/adjmat/OutputCluster.cpp b/src/adjmat/OutputCluster.cpp index 7fe7a3cd27..f9ae8da564 100644 --- a/src/adjmat/OutputCluster.cpp +++ b/src/adjmat/OutputCluster.cpp @@ -103,33 +103,52 @@ void OutputCluster::registerKeywords( Keywords& keys ) { OutputCluster::OutputCluster(const ActionOptions& ao): Action(ao), ActionPilot(ao), - myclusters(NULL) -{ + myclusters(NULL) { // Setup output file - ofile.link(*this); std::string file; parse("FILE",file); - if( file.length()==0 ) error("output file name was not specified"); + ofile.link(*this); + std::string file; + parse("FILE",file); + if( file.length()==0 ) { + error("output file name was not specified"); + } // Search for xyz extension output_xyz=false; if( file.find(".")!=std::string::npos ) { std::size_t dot=file.find_first_of('.'); - if( file.substr(dot+1)=="xyz" ) output_xyz=true; + if( file.substr(dot+1)=="xyz" ) { + output_xyz=true; + } } - ofile.open(file); log.printf(" on file %s \n",file.c_str()); - parseFlag("MAKE_WHOLE",makewhole); parse("MAXDEPTH",maxdepth); parse("MAXGOES",maxgoes); - if( makewhole && !output_xyz) error("MAKE_WHOLE flag is not compatible with output of non-xyz files"); + ofile.open(file); + log.printf(" on file %s \n",file.c_str()); + parseFlag("MAKE_WHOLE",makewhole); + parse("MAXDEPTH",maxdepth); + parse("MAXGOES",maxgoes); + if( makewhole && !output_xyz) { + error("MAKE_WHOLE flag is not compatible with output of non-xyz files"); + } // Find what action we are taking the clusters from - std::vector matname(1); parse("CLUSTERS",matname[0]); + std::vector matname(1); + parse("CLUSTERS",matname[0]); myclusters = plumed.getActionSet().selectWithLabel( matname[0] ); - if( !myclusters ) error( matname[0] + " does not calculate perform a clustering of the atomic positions"); + if( !myclusters ) { + error( matname[0] + " does not calculate perform a clustering of the atomic positions"); + } // N.B. the +0.3 is a fudge factor. Reconstrucing PBC doesnt work without this GAT - addDependency( myclusters ); double rcut=myclusters->getCutoffForConnection() + 0.3; rcut2=rcut*rcut; + addDependency( myclusters ); + double rcut=myclusters->getCutoffForConnection() + 0.3; + rcut2=rcut*rcut; // Read in the cluster we are calculating parse("CLUSTER",clustr); - if( clustr<1 ) error("cannot look for a cluster larger than the largest cluster"); - if( clustr>myclusters->getNumberOfNodes() ) 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>myclusters->getNumberOfNodes() ) { + error("cluster selected is invalid - too few atoms in system"); + } log.printf(" outputting atoms in %u th largest cluster found by %s \n",clustr,matname[0].c_str() ); } @@ -141,35 +160,58 @@ void OutputCluster::update() { if( makewhole ) { // Retrieve the atom positions atomsin.resize( myatoms.size() ); - for(unsigned i=0; igetPositionOfAtomForLinkCells( myatoms[i] ); + for(unsigned i=0; igetPositionOfAtomForLinkCells( myatoms[i] ); + } // Build a connectivity matrix neglecting the pbc - nneigh.resize( myatoms.size(), 0 ); adj_list.resize( myatoms.size(), myatoms.size() ); + nneigh.resize( myatoms.size(), 0 ); + adj_list.resize( myatoms.size(), myatoms.size() ); for(unsigned i=1; iareConnected( myatoms[i], myatoms[j] ) ) { adj_list(i,nneigh[i])=j; adj_list(j,nneigh[j])=i; nneigh[i]++; nneigh[j]++; } + if( myclusters->areConnected( myatoms[i], myatoms[j] ) ) { + adj_list(i,nneigh[i])=j; + adj_list(j,nneigh[j])=i; + nneigh[i]++; + nneigh[j]++; + } } } @@ -177,18 +219,24 @@ void OutputCluster::update() { for(unsigned jj=0; jjrcut2 ) { visited[j]=true; - for(unsigned depth=0; depth<=maxdepth; ++depth) explore( j, depth ); + for(unsigned depth=0; depth<=maxdepth; ++depth) { + explore( j, depth ); + } } } } } // And print final positions - for(unsigned i=0; igetPositionOfAtomForLinkCells( myatoms[i] ); @@ -198,16 +246,21 @@ void OutputCluster::update() { } else { ofile.printf("CLUSTERING RESULTS AT TIME %f : NUMBER OF ATOMS IN %u TH LARGEST CLUSTER EQUALS %u \n",getTime(),clustr,static_cast(myatoms.size()) ); ofile.printf("INDICES OF ATOMS : "); - for(unsigned i=0; igetAbsoluteIndexOfCentralAtom(myatoms[i])).index()); + for(unsigned i=0; igetAbsoluteIndexOfCentralAtom(myatoms[i])).index()); + } ofile.printf("\n"); } } void OutputCluster::explore( const unsigned& index, const unsigned& depth ) { - if( depth==0 ) return ; + if( depth==0 ) { + return ; + } for(unsigned i=0; ipbcDistance( atomsin[index], atomsin[j] ); atomsin[j] = atomsin[index] + svec; explore( j, depth-1 ); @@ -218,7 +271,9 @@ bool OutputCluster::explore_dfs( const unsigned& index ) { visited[index]=true; for(unsigned i=0; i& desc ) { for(int i=0; i& vec1, const std::vector& vec2, Vector& dconn, std::vector& dvec1, std::vector& dvec2 ) const { - unsigned nvectors = ( vec1.size() - 2 ) / 3; plumed_assert( (vec1.size()-2)%3==0 ); - std::vector dv1(nvectors), dv2(nvectors), tdconn(nvectors); Torsion t; std::vector v1(nvectors), v2(nvectors); + unsigned nvectors = ( vec1.size() - 2 ) / 3; + plumed_assert( (vec1.size()-2)%3==0 ); + std::vector dv1(nvectors), dv2(nvectors), tdconn(nvectors); + Torsion t; + std::vector v1(nvectors), v2(nvectors); std::vector> pos; - for(unsigned i=0; i() ); pos[i]->setDomain( "-pi", "pi" ); } + for(unsigned i=0; i() ); + pos[i]->setDomain( "-pi", "pi" ); + } for(unsigned j=0; jset( angle ); } - double ans=0; std::vector deriv( nvectors ), df( nvectors, 0 ); + double ans=0; + std::vector deriv( nvectors ), df( nvectors, 0 ); auto pos_ptr=Tools::unique2raw(pos); for(unsigned i=0; ihasDifferentiableOrientation() ) error("cannot use multicolvar of type " + getBaseMultiColvar(i)->getName() ); // } - if( !getAdjacencyVessel()->isSymmetric() ) error("input contact matrix is not symmetric"); - std::vector fake_atoms; setupMultiColvarBase( fake_atoms ); + if( !getAdjacencyVessel()->isSymmetric() ) { + error("input contact matrix is not symmetric"); + } + std::vector fake_atoms; + setupMultiColvarBase( fake_atoms ); // Create all the values sqrtn = std::sqrt( static_cast( getNumberOfNodes() ) ); for(unsigned i=0; iresizeDerivatives( getNumberOfDerivatives() ); @@ -145,7 +148,9 @@ Sprint::Sprint(const ActionOptions&ao): // Setup the dynamic list to hold all the tasks unsigned ntriangle = 0.5*getNumberOfNodes()*(getNumberOfNodes()-1); - for(unsigned i=0; i mymat_ders( getNumberOfComponents(), getNumberOfDerivatives() ); // std::vector catoms(2); - unsigned nval = getNumberOfNodes(); mymat_ders=0; + unsigned nval = getNumberOfNodes(); + mymat_ders=0; for(unsigned i=rank; igetMatrixIndices( active_elements[i], j, k ); + unsigned j, k; + getAdjacencyVessel()->getMatrixIndices( active_elements[i], j, k ); double tmp1 = 2 * eigenvecs(nval-1,j)*eigenvecs(nval-1,k); for(int icomp=0; icompaddDerivative( i, mymat_ders(j,i) ); + for(unsigned i=0; iaddDerivative( i, mymat_ders(j,i) ); + } } } diff --git a/src/adjmat/TopologyMatrix.cpp b/src/adjmat/TopologyMatrix.cpp index 07abbd501a..b537735cd2 100644 --- a/src/adjmat/TopologyMatrix.cpp +++ b/src/adjmat/TopologyMatrix.cpp @@ -99,21 +99,29 @@ void TopologyMatrix::registerKeywords( Keywords& keys ) { TopologyMatrix::TopologyMatrix( const ActionOptions& ao ): Action(ao), AdjacencyMatrixBase(ao), - maxbins(0) -{ + maxbins(0) { readMaxThreeSpeciesMatrix("NODES", "FAKE", "FAKE", "ATOMS", true ); - unsigned nrows, ncols, ndonor_types; retrieveTypeDimensions( nrows, ncols, ndonor_types ); - switchingFunction.resize( nrows, ncols ); parseConnectionDescriptions("SWITCH",false,ndonor_types); - cylinder_sw.resize( nrows, ncols ); parseConnectionDescriptions("RADIUS",false,ndonor_types); - low_sf.resize( nrows, ncols ); parseConnectionDescriptions("CYLINDER_SWITCH",false,ndonor_types); - binw_mat.resize( nrows, ncols ); cell_volume.resize( nrows, ncols ); + unsigned nrows, ncols, ndonor_types; + retrieveTypeDimensions( nrows, ncols, ndonor_types ); + switchingFunction.resize( nrows, ncols ); + parseConnectionDescriptions("SWITCH",false,ndonor_types); + cylinder_sw.resize( nrows, ncols ); + parseConnectionDescriptions("RADIUS",false,ndonor_types); + low_sf.resize( nrows, ncols ); + parseConnectionDescriptions("CYLINDER_SWITCH",false,ndonor_types); + binw_mat.resize( nrows, ncols ); + cell_volume.resize( nrows, ncols ); parseConnectionDescriptions("BIN_SIZE",false,ndonor_types); // Read in stuff for grid - parse("SIGMA",sigma); parse("KERNEL",kerneltype); + parse("SIGMA",sigma); + parse("KERNEL",kerneltype); // Read in threshold for density cutoff - std::string errors, thresh_sw_str; parse("DENSITY_THRESHOLD",thresh_sw_str); + std::string errors, thresh_sw_str; + parse("DENSITY_THRESHOLD",thresh_sw_str); threshold_switch.set(thresh_sw_str, errors ); - if( errors.length()>0 ) error("errors in DENSITY_THRESHOLD switching function : " + errors ); + if( errors.length()>0 ) { + error("errors in DENSITY_THRESHOLD switching function : " + errors ); + } log.printf(" threshold on density of atoms in cylinder equals %s\n",threshold_switch.description().c_str() ); for(unsigned i=0; isfmax ) sfmax=tsf; + if( tsf>sfmax ) { + sfmax=tsf; + } double rsf=cylinder_sw(i,j).get_dmax(); - if( rsf>rfmax ) rfmax=rsf; + if( rsf>rfmax ) { + rfmax=rsf; + } double lsf=low_sf(i,j).get_dmax(); - if( lsf>lsfmax ) lsfmax=lsf; + if( lsf>lsfmax ) { + lsfmax=lsf; + } } } // Get the width of the bead - HistogramBead bead; bead.isNotPeriodic(); - bead.setKernelType( kerneltype ); bead.set( 0.0, 1.0, sigma ); + HistogramBead bead; + bead.isNotPeriodic(); + bead.setKernelType( kerneltype ); + bead.set( 0.0, 1.0, sigma ); beadrad = bead.getCutoff(); // Set the link cell cutoff @@ -149,7 +165,9 @@ TopologyMatrix::TopologyMatrix( const ActionOptions& ao ): double maxsize=0; for(unsigned i=0; imaxsize ) maxsize=binw_mat(i,j); + if( binw_mat(i,j)>maxsize ) { + maxsize=binw_mat(i,j); + } } } // Set the maximum number of bins that we will need to compute @@ -166,55 +184,85 @@ unsigned TopologyMatrix::getNumberOfQuantities() const { void TopologyMatrix::setupConnector( const unsigned& id, const unsigned& i, const unsigned& j, const std::vector& desc ) { plumed_assert( id<4 ); if( id==0 ) { - std::string errors; switchingFunction(j,i).set(desc[0],errors); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); - if( j!=i) switchingFunction(i,j).set(desc[0],errors); + std::string errors; + switchingFunction(j,i).set(desc[0],errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } + if( j!=i) { + switchingFunction(i,j).set(desc[0],errors); + } log.printf(" %u th and %u th multicolvar groups must be within %s\n",i+1,j+1,(switchingFunction(i,j).description()).c_str() ); } else if( id==1 ) { - std::string errors; cylinder_sw(j,i).set(desc[0],errors); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); - if( j!=i) cylinder_sw(i,j).set(desc[0],errors); + std::string errors; + cylinder_sw(j,i).set(desc[0],errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } + if( j!=i) { + cylinder_sw(i,j).set(desc[0],errors); + } log.printf(" there must be not atoms within the cylinder connections atoms of multicolvar groups %u th and %u th. This cylinder has radius %s \n",i+1,j+1,(cylinder_sw(i,j).description()).c_str() ); } else if( id==2 ) { - std::string errors; low_sf(j,i).set(desc[0],errors); - if( errors.length()!=0 ) error("problem reading switching function description " + errors); - if( j!=i ) low_sf(i,j).set(desc[0],errors); + std::string errors; + low_sf(j,i).set(desc[0],errors); + if( errors.length()!=0 ) { + error("problem reading switching function description " + errors); + } + if( j!=i ) { + low_sf(i,j).set(desc[0],errors); + } log.printf(" %u th and %u th multicolvar groups must be further apart than %s\n",i+1,j+1,(low_sf(j,i).description()).c_str() ); } else if( id==3 ) { Tools::convert( desc[0], binw_mat(j,i) ); - if( i!=j ) binw_mat(i,j)=binw_mat(j,i); + if( i!=j ) { + binw_mat(i,j)=binw_mat(j,i); + } log.printf(" cylinder for %u th and %u th multicolvar groups is split into bins of length %f \n",i,j,binw_mat(i,j) ); } } double TopologyMatrix::calculateWeight( const unsigned& taskCode, const double& weight, multicolvar::AtomValuePack& myatoms ) const { Vector distance = getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); - if( distance.modulo2() binvals( 1+maxbins ); for(unsigned i=1;imax ) { max=myatoms.getValue(i); vout=i; } + if( myatoms.getValue(i)>max ) { + max=myatoms.getValue(i); + vout=i; + } } // Calculate value and derivative of switching function between atoms 1 and 2 double dfuncl, sw = switchingFunction( getBaseColvarNumber( myatoms.getIndex(0) ), @@ -248,12 +296,16 @@ void TopologyMatrix::calculateForThreeAtoms( const unsigned& iat, const Vector& // This tells us if we are outside the end of the cylinder double excess = proj - d1_len; // Return if we are outside of the cylinder as calculated based on excess - if( excess>low_sf( getBaseColvarNumber( myatoms.getIndex(0) ), getBaseColvarNumber( myatoms.getIndex(1) ) ).get_dmax() ) return; + if( excess>low_sf( getBaseColvarNumber( myatoms.getIndex(0) ), getBaseColvarNumber( myatoms.getIndex(1) ) ).get_dmax() ) { + return; + } // Find the length of the cylinder double binw = binw_mat( getBaseColvarNumber( myatoms.getIndex(0) ), getBaseColvarNumber( myatoms.getIndex(1) ) ); double lcylinder = (std::floor( d1_len / binw ) + 1)*binw; // Return if the projection is outside the length of interest - if( proj<-bead.getCutoff() || proj>(lcylinder+bead.getCutoff()) ) return; + if( proj<-bead.getCutoff() || proj>(lcylinder+bead.getCutoff()) ) { + return; + } // Calculate the excess swiching function double edf, eval = low_sf( getBaseColvarNumber( myatoms.getIndex(0) ), getBaseColvarNumber( myatoms.getIndex(1) ) ).calculate( excess, edf ); @@ -297,11 +349,15 @@ void TopologyMatrix::calculateForThreeAtoms( const unsigned& iat, const Vector& Vector pos1 = myatoms.getPosition(0) + d1_len*d1; Vector pos2 = myatoms.getPosition(0) + d2; - Vector g1derivf,g2derivf,lderivf; Tensor vir; + Vector g1derivf,g2derivf,lderivf; + Tensor vir; for(unsigned bin=0; binbinw*(bin+1)+bead.getCutoff() ) continue; - double der, contr=bead.calculateWithCutoff( proj, der ) / cellv; der /= cellv; + if( proj<(bin*binw-bead.getCutoff()) || proj>binw*(bin+1)+bead.getCutoff() ) { + continue; + } + double der, contr=bead.calculateWithCutoff( proj, der ) / cellv; + der /= cellv; myatoms.addValue( 2+bin, contr*val*eval ); if( !doNotCalculateDerivatives() ) { diff --git a/src/analysis/AnalysisBase.cpp b/src/analysis/AnalysisBase.cpp index f283e4dd0d..af78327f32 100644 --- a/src/analysis/AnalysisBase.cpp +++ b/src/analysis/AnalysisBase.cpp @@ -28,10 +28,16 @@ namespace PLMD { namespace analysis { void AnalysisBase::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); - ActionWithValue::registerKeywords( keys ); ActionAtomistic::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); keys.remove("NUMERICAL_DERIVATIVES"); - ActionWithVessel::registerKeywords( keys ); keys.remove("TOL"); keys.reset_style("TIMINGS","hidden"); keys.isAnalysis(); + Action::registerKeywords( keys ); + ActionPilot::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionAtomistic::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + keys.remove("NUMERICAL_DERIVATIVES"); + ActionWithVessel::registerKeywords( keys ); + keys.remove("TOL"); + keys.reset_style("TIMINGS","hidden"); + keys.isAnalysis(); keys.add("atoms-2","USE_OUTPUT_DATA_FROM","use the output of the analysis performed by this object as input to your new analysis object"); } @@ -42,16 +48,20 @@ AnalysisBase::AnalysisBase(const ActionOptions&ao): ActionAtomistic(ao), ActionWithArguments(ao), ActionWithVessel(ao), - my_input_data(NULL) -{ + my_input_data(NULL) { // We have an if statement here so that this doesn't break with READ_DISSIMILARITIES if( keywords.exists("USE_OUTPUT_DATA_FROM") ) { - std::string datastr; parse("USE_OUTPUT_DATA_FROM",datastr); - if( keywords.style("USE_OUTPUT_DATA_FROM","atoms") && datastr.length()==0 ) error("input analysis action was not specified use USE_OUTPUT_DATA_FROM"); + std::string datastr; + parse("USE_OUTPUT_DATA_FROM",datastr); + if( keywords.style("USE_OUTPUT_DATA_FROM","atoms") && datastr.length()==0 ) { + error("input analysis action was not specified use USE_OUTPUT_DATA_FROM"); + } if( datastr.length()>0 ) { my_input_data=plumed.getActionSet().selectWithLabel( datastr ); log.printf(" performing analysis on output from %s \n",datastr.c_str() ); - if( !my_input_data ) error("could not find analysis action named " + datastr ); + if( !my_input_data ) { + error("could not find analysis action named " + datastr ); + } addDependency( my_input_data ); } } @@ -68,13 +78,17 @@ std::vector AnalysisBase::getArgumentNames() { } void AnalysisBase::update() { - if( getStep()==0 || ( getStride()>0 && !onStep() ) ) return; + if( getStep()==0 || ( getStride()>0 && !onStep() ) ) { + return; + } // And do the analysis performAnalysis(); } void AnalysisBase::runFinalJobs() { - if( getStride()>0 ) return; + if( getStride()>0 ) { + return; + } performAnalysis(); } diff --git a/src/analysis/AnalysisBase.h b/src/analysis/AnalysisBase.h index db41daf97b..3f4f1bd5d7 100644 --- a/src/analysis/AnalysisBase.h +++ b/src/analysis/AnalysisBase.h @@ -47,8 +47,7 @@ class AnalysisBase : public ActionWithValue, public ActionAtomistic, public ActionWithArguments, - public vesselbase::ActionWithVessel -{ + public vesselbase::ActionWithVessel { friend class ReselectLandmarks; friend class ReadDissimilarityMatrix; protected: @@ -89,9 +88,15 @@ class AnalysisBase : /// This actually performs the analysis virtual void performAnalysis()=0; /// These overwrite things from inherited classes (this is a bit of a fudge) - bool isPeriodic() override { plumed_error(); } - unsigned getNumberOfDerivatives() override { plumed_error(); } - void calculateNumericalDerivatives( ActionWithValue* a=NULL ) override { plumed_error(); } + bool isPeriodic() override { + plumed_error(); + } + unsigned getNumberOfDerivatives() override { + plumed_error(); + } + void calculateNumericalDerivatives( ActionWithValue* a=NULL ) override { + plumed_error(); + } /// Calculate and apply do nothing all analysis is done during update step void calculate() override {} void apply() override {} diff --git a/src/analysis/Average.cpp b/src/analysis/Average.cpp index 436bb2f6ad..824984200a 100644 --- a/src/analysis/Average.cpp +++ b/src/analysis/Average.cpp @@ -99,34 +99,44 @@ class Average : public vesselbase::ActionWithAveraging { void apply() override {} void performOperations( const bool& from_update ) override; void finishAveraging() override; - bool isPeriodic() override { return false; } - void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { plumed_error(); } + bool isPeriodic() override { + return false; + } + void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { + plumed_error(); + } void accumulateAverage( MultiValue& myvals ) const override; }; PLUMED_REGISTER_ACTION(Average,"AVERAGE") void Average::registerKeywords( Keywords& keys ) { - vesselbase::ActionWithAveraging::registerKeywords( keys ); keys.use("ARG"); - keys.remove("SERIAL"); keys.remove("LOWMEM"); + vesselbase::ActionWithAveraging::registerKeywords( keys ); + keys.use("ARG"); + keys.remove("SERIAL"); + keys.remove("LOWMEM"); } Average::Average( const ActionOptions& ao ): Action(ao), - ActionWithAveraging(ao) -{ + ActionWithAveraging(ao) { addValue(); // Create a value so that we can output the average - if( getNumberOfArguments()!=1 ) error("only one quantity can be averaged at a time"); + if( getNumberOfArguments()!=1 ) { + error("only one quantity can be averaged at a time"); + } std::string instring; if( getPntrToArgument(0)->isPeriodic() ) { - std::string min, max; getPntrToArgument(0)->getDomain(min,max); - instring = "PERIODIC=" + min + "," + max; setPeriodic( min, max ); + std::string min, max; + getPntrToArgument(0)->getDomain(min,max); + instring = "PERIODIC=" + min + "," + max; + setPeriodic( min, max ); } else { setNotPeriodic(); } // Create a vessel to hold the average vesselbase::VesselOptions da("myaverage","",-1,instring,this); - Keywords keys; AverageVessel::registerKeywords( keys ); + Keywords keys; + AverageVessel::registerKeywords( keys ); vesselbase::VesselOptions dar( da, keys ); auto average=Tools::make_unique(dar); myaverage = average.get(); diff --git a/src/analysis/AverageVessel.cpp b/src/analysis/AverageVessel.cpp index 18e543689d..1bb244f656 100644 --- a/src/analysis/AverageVessel.cpp +++ b/src/analysis/AverageVessel.cpp @@ -30,28 +30,35 @@ void AverageVessel::registerKeywords( Keywords& keys ) { } AverageVessel::AverageVessel( const vesselbase::VesselOptions& da): - AveragingVessel(da) -{ + AveragingVessel(da) { parseVector("PERIODIC",domain); plumed_assert( domain.size()==2 || domain.size()==0 ); } void AverageVessel::resize() { resizeBuffer(0); - if( domain.size()==2 ) setDataSize(2); - else setDataSize(1); + if( domain.size()==2 ) { + setDataSize(2); + } else { + setDataSize(1); + } } void AverageVessel::accumulate( const double& weight, const double& val ) { if( domain.size()==2 ) { // Average with Berry Phase double tval = 2*pi*( val - domain[0] ) / ( domain[1] - domain[0] ); - addDataElement( 0, weight*std::sin(tval) ); addDataElement( 1, weight*std::cos(tval) ); - } else addDataElement( 0, weight*val ); + addDataElement( 0, weight*std::sin(tval) ); + addDataElement( 1, weight*std::cos(tval) ); + } else { + addDataElement( 0, weight*val ); + } } double AverageVessel::getAverage() const { - if( domain.size()==2 ) return domain[0] + (( domain[1] - domain[0] )*std::atan2( getDataElement(0), getDataElement(1) ) / (2*pi)); + if( domain.size()==2 ) { + return domain[0] + (( domain[1] - domain[0] )*std::atan2( getDataElement(0), getDataElement(1) ) / (2*pi)); + } return getDataElement(0); } diff --git a/src/analysis/AverageVessel.h b/src/analysis/AverageVessel.h index 304cb39246..c6e71674cc 100644 --- a/src/analysis/AverageVessel.h +++ b/src/analysis/AverageVessel.h @@ -39,7 +39,9 @@ class AverageVessel : public vesselbase::AveragingVessel { void resize() override; /// This does nothing void calculate( const unsigned& current, MultiValue& myvals, std::vector& buffer, std::vector& der_list ) const override; - std::string description() override { return ""; } + std::string description() override { + return ""; + } /// Accumulate the average void accumulate( const double& weight, const double& val ); /// Get the average value diff --git a/src/analysis/Committor.cpp b/src/analysis/Committor.cpp index 5c65db67d8..04447577b5 100644 --- a/src/analysis/Committor.cpp +++ b/src/analysis/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& ind, const std::vector& arg_names ) { - myaction=action_label; indices.resize( ind.size() ); positions.resize( indices.size() ); - for(unsigned i=0; i( arg_names[i], 0.0 ) ); + myaction=action_label; + indices.resize( ind.size() ); + positions.resize( indices.size() ); + for(unsigned i=0; i( arg_names[i], 0.0 ) ); + } } void DataCollectionObject::setAtomPositions( const std::vector& pos ) { plumed_dbg_assert( pos.size()==positions.size() && pos.size()==indices.size() ); - for(unsigned i=0; i::iterator it = args.find(name); - if( it!=args.end() ) it->second = value; - else args.insert( std::pair( name, value ) ); + if( it!=args.end() ) { + it->second = value; + } else { + args.insert( std::pair( name, value ) ); + } } bool DataCollectionObject::transferDataToPDB( PDB& mypdb ) { @@ -49,13 +60,18 @@ bool DataCollectionObject::transferDataToPDB( PDB& mypdb ) { std::map::iterator it; for(unsigned i=0; isecond ); } // Now set the atomic positions std::vector pdb_pos( mypdb.getAtomNumbers() ); - if( pdb_pos.size()==positions.size() ) mypdb.setAtomPositions( positions ); - else if( pdb_pos.size()>0 ) plumed_merror("This feature is currently not ready"); + if( pdb_pos.size()==positions.size() ) { + mypdb.setAtomPositions( positions ); + } else if( pdb_pos.size()>0 ) { + plumed_merror("This feature is currently not ready"); + } return true; } diff --git a/src/analysis/DataCollectionObject.h b/src/analysis/DataCollectionObject.h index 2828ba9b10..10fa8b9fd5 100644 --- a/src/analysis/DataCollectionObject.h +++ b/src/analysis/DataCollectionObject.h @@ -67,10 +67,16 @@ Vector DataCollectionObject::getAtomPosition( const AtomNumber& ind ) const { inline double DataCollectionObject::getArgumentValue( const std::string& name ) const { std::map::const_iterator it = args.find(name); - if( it != args.end() ) return it->second; - std::size_t dot=name.find_first_of('.'); std::string a=name.substr(0,dot); - if( a==myaction ) return args.find( name.substr(dot+1) )->second; - else plumed_merror("could not find required data in collection object"); + if( it != args.end() ) { + return it->second; + } + std::size_t dot=name.find_first_of('.'); + std::string a=name.substr(0,dot); + if( a==myaction ) { + return args.find( name.substr(dot+1) )->second; + } else { + plumed_merror("could not find required data in collection object"); + } } } diff --git a/src/analysis/EuclideanDissimilarityMatrix.cpp b/src/analysis/EuclideanDissimilarityMatrix.cpp index fff6bf51b5..5b4514c1ab 100644 --- a/src/analysis/EuclideanDissimilarityMatrix.cpp +++ b/src/analysis/EuclideanDissimilarityMatrix.cpp @@ -48,28 +48,34 @@ class EuclideanDissimilarityMatrix : public AnalysisBase { /// Do the analysis void performAnalysis() override; /// This ensures that classes that use this data know that dissimilarities were set - bool dissimilaritiesWereSet() const override { return true; } + bool dissimilaritiesWereSet() const override { + return true; + } /// Get information on how to calculate dissimilarities std::string getDissimilarityInstruction() const override; /// Get the squared dissimilarity between two reference configurations double getDissimilarity( const unsigned& i, const unsigned& j ) override; /// This is just to deal with ActionWithVessel - void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { plumed_error(); } + void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { + plumed_error(); + } }; PLUMED_REGISTER_ACTION(EuclideanDissimilarityMatrix,"EUCLIDEAN_DISSIMILARITIES") void EuclideanDissimilarityMatrix::registerKeywords( Keywords& keys ) { - AnalysisBase::registerKeywords( keys ); keys.use("ARG"); keys.reset_style("ARG","optional"); + AnalysisBase::registerKeywords( keys ); + keys.use("ARG"); + keys.reset_style("ARG","optional"); keys.add("compulsory","METRIC","EUCLIDEAN","the method that you are going to use to measure the distances between points"); keys.add("atoms","ATOMS","the list of atoms that you are going to use in the measure of distance that you are using"); } EuclideanDissimilarityMatrix::EuclideanDissimilarityMatrix( const ActionOptions& ao ): Action(ao), - AnalysisBase(ao) -{ - parse("METRIC",mtype); std::vector atoms; + AnalysisBase(ao) { + parse("METRIC",mtype); + std::vector atoms; if( my_input_data->getNumberOfAtoms()>0 ) { parseAtomList("ATOMS",atoms); if( atoms.size()!=0 ) { @@ -77,10 +83,14 @@ EuclideanDissimilarityMatrix::EuclideanDissimilarityMatrix( const ActionOptions& for(unsigned i=0; igetAtomIndexes().size(); ++j) { - if( my_input_data->getAtomIndexes()[j]==atoms[i] ) { found=true; break; } + if( my_input_data->getAtomIndexes()[j]==atoms[i] ) { + found=true; + break; + } } if( !found ) { - std::string num; Tools::convert( atoms[i].serial(), num ); + std::string num; + Tools::convert( atoms[i].serial(), num ); error("atom number " + num + " is not stored in any action that has been input"); } } @@ -88,14 +98,17 @@ EuclideanDissimilarityMatrix::EuclideanDissimilarityMatrix( const ActionOptions& } else if( getNumberOfArguments()==0 ) { mypdb.setAtomNumbers( my_input_data->getAtomIndexes() ); mypdb.addBlockEnd( my_input_data->getAtomIndexes().size() ); - if( mtype=="EUCLIDEAN" ) mtype="OPTIMAL"; + if( mtype=="EUCLIDEAN" ) { + mtype="OPTIMAL"; + } } } log.printf(" measuring distances using %s metric \n",mtype.c_str() ); if( my_input_data->getArgumentNames().size()>0 ) { if( getNumberOfArguments()==0 && atoms.size()==0 ) { std::vector argnames( my_input_data->getArgumentNames() ); - mypdb.setArgumentNames( argnames ); requestArguments( my_input_data->getArgumentList() ); + mypdb.setArgumentNames( argnames ); + requestArguments( my_input_data->getArgumentList() ); } else { std::vector myargs( getArguments() ); std::vector inargnames( my_input_data->getArgumentNames() ); @@ -104,11 +117,17 @@ EuclideanDissimilarityMatrix::EuclideanDissimilarityMatrix( const ActionOptions& argnames[i]=myargs[i]->getName(); bool found=false; for(unsigned j=0; jgetLabel() + " does not store/calculate quantity named " + argnames[i] ); } - if( !found ) error("input named " + my_input_data->getLabel() + " does not store/calculate quantity named " + argnames[i] ); } - mypdb.setArgumentNames( argnames ); requestArguments( myargs ); + mypdb.setArgumentNames( argnames ); + requestArguments( myargs ); } } } @@ -116,7 +135,8 @@ EuclideanDissimilarityMatrix::EuclideanDissimilarityMatrix( const ActionOptions& void EuclideanDissimilarityMatrix::performAnalysis() { // Resize dissimilarities matrix and set all elements to zero if( !usingLowMem() ) { - dissimilarities.resize( getNumberOfDataPoints(), getNumberOfDataPoints() ); dissimilarities=0; + dissimilarities.resize( getNumberOfDataPoints(), getNumberOfDataPoints() ); + dissimilarities=0; } } @@ -127,7 +147,9 @@ std::string EuclideanDissimilarityMatrix::getDissimilarityInstruction() const { double EuclideanDissimilarityMatrix::getDissimilarity( const unsigned& iframe, const unsigned& jframe ) { plumed_dbg_assert( iframe0. ) { return dissimilarities(iframe,jframe); } + if( dissimilarities(iframe,jframe)>0. ) { + return dissimilarities(iframe,jframe); + } } if( iframe!=jframe ) { double dd; @@ -135,8 +157,11 @@ double EuclideanDissimilarityMatrix::getDissimilarity( const unsigned& iframe, c auto myref1=metricRegister().create(mtype, mypdb); getStoredData( jframe, true ).transferDataToPDB( mypdb ); auto myref2=metricRegister().create(mtype, mypdb); - if( !usingLowMem() ) dd=dissimilarities(iframe,jframe) = dissimilarities(jframe,iframe) = distance( getPbc(), getArguments(), myref1.get(), myref2.get(), true ); - else dd=distance( getPbc(), getArguments(), myref1.get(), myref2.get(), true ); + if( !usingLowMem() ) { + dd=dissimilarities(iframe,jframe) = dissimilarities(jframe,iframe) = distance( getPbc(), getArguments(), myref1.get(), myref2.get(), true ); + } else { + dd=distance( getPbc(), getArguments(), myref1.get(), myref2.get(), true ); + } return dd; } return 0.0; diff --git a/src/analysis/FarthestPointSampling.cpp b/src/analysis/FarthestPointSampling.cpp index 80bbce30e6..fdb664ce45 100644 --- a/src/analysis/FarthestPointSampling.cpp +++ b/src/analysis/FarthestPointSampling.cpp @@ -53,9 +53,10 @@ void FarthestPointSampling::registerKeywords( Keywords& keys ) { FarthestPointSampling::FarthestPointSampling( const ActionOptions& ao ): Action(ao), - LandmarkSelectionBase(ao) -{ - if( !dissimilaritiesWereSet() ) error("dissimilarities have not been calcualted in input action"); + LandmarkSelectionBase(ao) { + if( !dissimilaritiesWereSet() ) { + error("dissimilarities have not been calcualted in input action"); + } parse("SEED",seed); } @@ -63,13 +64,17 @@ void FarthestPointSampling::selectLandmarks() { std::vector landmarks( getNumberOfDataPoints() ); // Select first point at random - Random random; random.setSeed(-seed); double rand=random.RandU01(); + Random random; + random.setSeed(-seed); + double rand=random.RandU01(); landmarks[0] = std::floor( my_input_data->getNumberOfDataPoints()*rand ); selectFrame( landmarks[0] ); // Now find distance to all other points (N.B. We can use squared distances here for speed) Matrix distances( getNumberOfDataPoints(), my_input_data->getNumberOfDataPoints() ); - for(unsigned i=0; igetNumberOfDataPoints(); ++i) distances(0,i) = my_input_data->getDissimilarity( landmarks[0], i ); + for(unsigned i=0; igetNumberOfDataPoints(); ++i) { + distances(0,i) = my_input_data->getDissimilarity( landmarks[0], i ); + } // Now find all other landmarks for(unsigned i=1; igetNumberOfDataPoints(); ++j) { double mind=distances(0,j); for(unsigned k=1; kmaxd ) { + maxd=mind; + landmarks[i]=j; } - if( mind>maxd ) { maxd=mind; landmarks[i]=j; } } selectFrame( landmarks[i] ); - for(unsigned k=0; kgetNumberOfDataPoints(); ++k) distances(i,k) = my_input_data->getDissimilarity( landmarks[i], k ); + for(unsigned k=0; kgetNumberOfDataPoints(); ++k) { + distances(i,k) = my_input_data->getDissimilarity( landmarks[i], k ); + } } } diff --git a/src/analysis/Histogram.cpp b/src/analysis/Histogram.cpp index e13b905bad..e6875f2c57 100644 --- a/src/analysis/Histogram.cpp +++ b/src/analysis/Histogram.cpp @@ -212,8 +212,12 @@ class Histogram : public gridtools::ActionWithGrid { void prepareForAveraging() override; void performOperations( const bool& from_update ) override; void finishAveraging() override; - bool threadSafe() const override { return !in_apply; } - bool isPeriodic() override { return false; } + bool threadSafe() const override { + return !in_apply; + } + bool isPeriodic() override { + return false; + } unsigned getNumberOfDerivatives() override; void turnOnDerivatives() override; void compute( const unsigned&, MultiValue& ) const override; @@ -223,7 +227,9 @@ class Histogram : public gridtools::ActionWithGrid { PLUMED_REGISTER_ACTION(Histogram,"HISTOGRAM") void Histogram::registerKeywords( Keywords& keys ) { - gridtools::ActionWithGrid::registerKeywords( keys ); keys.use("ARG"); keys.remove("NORMALIZATION"); + gridtools::ActionWithGrid::registerKeywords( keys ); + keys.use("ARG"); + keys.remove("NORMALIZATION"); 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","DATA","input data from action with vessel and compute histogram"); keys.add("optional","VECTORS","input three dimensional vectors for computing histogram"); @@ -231,7 +237,8 @@ void Histogram::registerKeywords( Keywords& keys ) { keys.add("compulsory","GRID_MAX","the upper bounds for the grid"); keys.add("optional","GRID_BIN","the number of bins for the grid"); keys.add("optional","GRID_SPACING","the approximate grid spacing (to be used as an alternative or together with GRID_BIN)"); - keys.use("UPDATE_FROM"); keys.use("UPDATE_UNTIL"); + keys.use("UPDATE_FROM"); + keys.use("UPDATE_UNTIL"); } Histogram::Histogram(const ActionOptions&ao): @@ -239,35 +246,49 @@ Histogram::Histogram(const ActionOptions&ao): ActionWithGrid(ao), ww(0.0), in_apply(false), - mvectors(false) -{ + mvectors(false) { // Read in arguments if( getNumberOfArguments()==0 ) { - std::string vlab; parse("VECTORS",vlab); + std::string vlab; + parse("VECTORS",vlab); if( vlab.length()>0 ) { ActionWithVessel* myv = plumed.getActionSet().selectWithLabel( vlab ); - if( !myv ) error("action labelled " + vlab + " does not exist or is not an ActionWithVessel"); - myvessels.push_back( myv ); stashes.push_back( myv->buildDataStashes( NULL ) ); - addDependency( myv ); mvectors=true; - if( myv->getNumberOfQuantities()!=5 ) error("can only compute histograms for three dimensional vectors"); + if( !myv ) { + error("action labelled " + vlab + " does not exist or is not an ActionWithVessel"); + } + myvessels.push_back( myv ); + stashes.push_back( myv->buildDataStashes( NULL ) ); + addDependency( myv ); + mvectors=true; + if( myv->getNumberOfQuantities()!=5 ) { + error("can only compute histograms for three dimensional vectors"); + } log.printf(" for vector quantities calculated by %s \n", vlab.c_str() ); } else { - std::vector mlab; parseVector("DATA",mlab); + std::vector mlab; + parseVector("DATA",mlab); if( mlab.size()>0 ) { for(unsigned i=0; i( mlab[i] ); - if( !myv ) error("action labelled " + mlab[i] + " does not exist or is not an ActionWithVessel"); - myvessels.push_back( myv ); stashes.push_back( myv->buildDataStashes( NULL ) ); + if( !myv ) { + error("action labelled " + mlab[i] + " does not exist or is not an ActionWithVessel"); + } + myvessels.push_back( myv ); + stashes.push_back( myv->buildDataStashes( NULL ) ); // log.printf(" for all base quantities calculated by %s \n",myvessel->getLabel().c_str() ); // Add the dependency addDependency( myv ); } unsigned nvals = myvessels[0]->getFullNumberOfTasks(); for(unsigned i=1; igetFullNumberOfTasks() ) error("mismatched number of quantities calculated by actions input to histogram"); + if( nvals!=myvessels[i]->getFullNumberOfTasks() ) { + error("mismatched number of quantities calculated by actions input to histogram"); + } } log.printf(" for all base quantities calculated by %s ", myvessels[0]->getLabel().c_str() ); - for(unsigned i=1; igetLabel().c_str() ); + for(unsigned i=1; igetLabel().c_str() ); + } log.printf("\n"); } else { error("input data is missing use ARG/VECTORS/DATA"); @@ -277,61 +298,93 @@ Histogram::Histogram(const ActionOptions&ao): // Read stuff for grid unsigned narg = getNumberOfArguments(); - if( myvessels.size()>0 ) narg=myvessels.size(); + if( myvessels.size()>0 ) { + narg=myvessels.size(); + } // Input of name and labels std::string vstring="COMPONENTS=" + getLabel(); if( mvectors ) { vstring += " COORDINATES=x,y,z PBC=F,F,F"; } else if( myvessels.size()>0 ) { vstring += " COORDINATES=" + myvessels[0]->getLabel(); - for(unsigned i=1; igetLabel(); + for(unsigned i=1; igetLabel(); + } // Input for PBC - if( myvessels[0]->isPeriodic() ) vstring+=" PBC=T"; - else vstring+=" PBC=F"; + if( myvessels[0]->isPeriodic() ) { + vstring+=" PBC=T"; + } else { + vstring+=" PBC=F"; + } for(unsigned i=1; iisPeriodic() ) vstring+=",T"; - else vstring+=",F"; + if( myvessels[i]->isPeriodic() ) { + vstring+=",T"; + } else { + vstring+=",F"; + } } } else { vstring += " COORDINATES=" + getPntrToArgument(0)->getName(); - for(unsigned i=1; igetName(); + for(unsigned i=1; igetName(); + } // Input for PBC - if( getPntrToArgument(0)->isPeriodic() ) vstring+=" PBC=T"; - else vstring+=" PBC=F"; + if( getPntrToArgument(0)->isPeriodic() ) { + vstring+=" PBC=T"; + } else { + vstring+=" PBC=F"; + } for(unsigned i=1; iisPeriodic() ) vstring+=",T"; - else vstring+=",F"; + if( getPntrToArgument(i)->isPeriodic() ) { + vstring+=",T"; + } else { + vstring+=",F"; + } } } // And create the grid auto grid=createGrid( "histogram", vstring ); // notice that createGrid also sets mygrid=grid.get() if( mygrid->getType()=="flat" ) { - if( mvectors ) error("computing histogram for three dimensional vectors but grid is not of fibonacci type - use CONCENTRATION"); + if( mvectors ) { + error("computing histogram for three dimensional vectors but grid is not of fibonacci type - use CONCENTRATION"); + } std::vector gmin( narg ), gmax( narg ); - parseVector("GRID_MIN",gmin); parseVector("GRID_MAX",gmax); - std::vector nbin; parseVector("GRID_BIN",nbin); - std::vector gspacing; parseVector("GRID_SPACING",gspacing); + parseVector("GRID_MIN",gmin); + parseVector("GRID_MAX",gmax); + std::vector nbin; + parseVector("GRID_BIN",nbin); + std::vector gspacing; + parseVector("GRID_SPACING",gspacing); if( nbin.size()!=narg && gspacing.size()!=narg ) { error("GRID_BIN or GRID_SPACING must be set"); } mygrid->setBounds( gmin, gmax, nbin, gspacing ); } else { - std::vector nbin; parseVector("GRID_BIN",nbin); - if( nbin.size()!=1 ) error("should only be one index for number of bins with spherical grid"); - if( mygrid->getType()=="fibonacci" ) mygrid->setupFibonacciGrid( nbin[0] ); + std::vector nbin; + parseVector("GRID_BIN",nbin); + if( nbin.size()!=1 ) { + error("should only be one index for number of bins with spherical grid"); + } + if( mygrid->getType()=="fibonacci" ) { + mygrid->setupFibonacciGrid( nbin[0] ); + } } myhist = dynamic_cast( mygrid ); plumed_assert( myhist ); if( myvessels.size()>0 ) { // Create a task list - for(unsigned i=0; igetFullNumberOfTasks(); ++i) addTaskToList(i); + for(unsigned i=0; igetFullNumberOfTasks(); ++i) { + addTaskToList(i); + } setAveragingAction( std::move(grid), true ); } else if( storeThenAverage() ) { setAveragingAction( std::move(grid), true ); } else { // Create a task list - for(unsigned i=0; igetNumberOfPoints(); ++i) addTaskToList(i); + for(unsigned i=0; igetNumberOfPoints(); ++i) { + addTaskToList(i); + } myhist->addOneKernelEachTimeOnly(); setAveragingAction( std::move(grid), myhist->noDiscreteKernels() ); } @@ -343,9 +396,13 @@ void Histogram::turnOnDerivatives() { std::vector all_atoms, tmp_atoms; for(unsigned i=0; i( myvessels[i] ); - if( !mbase ) error("do not know how to get histogram derivatives for actions of type " + myvessels[i]->getName() ); + if( !mbase ) { + error("do not know how to get histogram derivatives for actions of type " + myvessels[i]->getName() ); + } tmp_atoms = mbase->getAbsoluteIndexes(); - for(unsigned j=0; jresizeTemporyMultiValues( 1 ); } @@ -353,55 +410,80 @@ void Histogram::turnOnDerivatives() { finalForces.resize( 3*all_atoms.size() + 9 ); forcesToApply.resize( 3*all_atoms.size() + 9*myvessels.size() ); // And make sure we still have the dependencies which are cleared by requestAtoms - for(unsigned i=0; iresize(); in_apply=false; + in_apply=true; + mygrid->resize(); + in_apply=false; } unsigned Histogram::getNumberOfDerivatives() { if( in_apply ) { unsigned nder=0; - for(unsigned i=0; igetNumberOfDerivatives(); + for(unsigned i=0; igetNumberOfDerivatives(); + } return nder; } return getNumberOfArguments(); } unsigned Histogram::getNumberOfQuantities() const { - if( mvectors ) return myvessels[0]->getNumberOfQuantities(); - else if( myvessels.size()>0 ) return myvessels.size()+2; + if( mvectors ) { + return myvessels[0]->getNumberOfQuantities(); + } else if( myvessels.size()>0 ) { + return myvessels.size()+2; + } return ActionWithAveraging::getNumberOfQuantities(); } void Histogram::prepareForAveraging() { if( myvessels.size()>0 ) { - deactivateAllTasks(); double norm=0; + deactivateAllTasks(); + double norm=0; for(unsigned i=0; igetNumberOfStoredValues(); ++i) { std::vector cvals( myvessels[0]->getNumberOfQuantities() ); stashes[0]->retrieveSequentialValue( i, false, cvals ); - unsigned itask=myvessels[0]->getActiveTask(i); double tnorm = cvals[0]; + unsigned itask=myvessels[0]->getActiveTask(i); + double tnorm = cvals[0]; for(unsigned j=1; jgetActiveTask(i)!=itask ) error("mismatched task identities in histogram suggests histogram is meaningless"); - if( cvals.size()!=myvessels[j]->getNumberOfQuantities() ) cvals.resize( myvessels[j]->getNumberOfQuantities() ); - stashes[j]->retrieveSequentialValue( i, false, cvals ); tnorm *= cvals[0]; + if( myvessels[j]->getActiveTask(i)!=itask ) { + error("mismatched task identities in histogram suggests histogram is meaningless"); + } + if( cvals.size()!=myvessels[j]->getNumberOfQuantities() ) { + cvals.resize( myvessels[j]->getNumberOfQuantities() ); + } + stashes[j]->retrieveSequentialValue( i, false, cvals ); + tnorm *= cvals[0]; } - norm += tnorm; taskFlags[i]=1; + norm += tnorm; + taskFlags[i]=1; } lockContributors(); // Sort out normalization of histogram - if( !noNormalization() ) ww = cweight / norm; - else ww = cweight; + if( !noNormalization() ) { + ww = cweight / norm; + } else { + ww = cweight; + } } else if( !storeThenAverage() ) { // Now fetch the kernel and the active points std::vector point( getNumberOfArguments() ); - for(unsigned i=0; i neighbors(1); + for(unsigned i=0; i neighbors(1); kernel=myhist->getKernelAndNeighbors( point, num_neigh, neighbors ); if( num_neigh>1 ) { // Activate relevant tasks deactivateAllTasks(); - for(unsigned i=0; inoDiscreteKernels() ); } +void Histogram::performOperations( const bool& from_update ) { + if( myvessels.size()==0 ) { + plumed_dbg_assert( !myhist->noDiscreteKernels() ); + } +} void Histogram::finishAveraging() { - if( myvessels.size()==0 ) kernel.reset(); + if( myvessels.size()==0 ) { + kernel.reset(); + } } void Histogram::compute( const unsigned& current, MultiValue& myvals ) const { if( mvectors ) { std::vector cvals( myvessels[0]->getNumberOfQuantities() ); stashes[0]->retrieveSequentialValue( current, true, cvals ); - for(unsigned i=2; igetNumberOfQuantities(); ++i) myvals.setValue( i-1, cvals[i] ); - myvals.setValue( 0, cvals[0] ); myvals.setValue( myvessels[0]->getNumberOfQuantities() - 1, ww ); + for(unsigned i=2; igetNumberOfQuantities(); ++i) { + myvals.setValue( i-1, cvals[i] ); + } + myvals.setValue( 0, cvals[0] ); + myvals.setValue( myvessels[0]->getNumberOfQuantities() - 1, ww ); if( in_apply ) { MultiValue& tmpval = stashes[0]->getTemporyMultiValue(0); if( tmpval.getNumberOfValues()!=myvessels[0]->getNumberOfQuantities() || - tmpval.getNumberOfDerivatives()!=myvessels[0]->getNumberOfDerivatives() ) + tmpval.getNumberOfDerivatives()!=myvessels[0]->getNumberOfDerivatives() ) { tmpval.resize( myvessels[0]->getNumberOfQuantities(), myvessels[0]->getNumberOfDerivatives() ); + } stashes[0]->retrieveDerivatives( stashes[0]->getTrueIndex(current), true, tmpval ); for(unsigned j=0; jgetNumberOfQuantities(); ++i) myvals.addDerivative( i-1, jder, tmpval.getDerivative(i, jder) ); + unsigned jder=tmpval.getActiveIndex(j); + myvals.addDerivative( 0, jder, tmpval.getDerivative(0, jder) ); + for(unsigned i=2; igetNumberOfQuantities(); ++i) { + myvals.addDerivative( i-1, jder, tmpval.getDerivative(i, jder) ); + } } myvals.updateDynamicList(); } } else if( myvessels.size()>0 ) { std::vector cvals( myvessels[0]->getNumberOfQuantities() ); stashes[0]->retrieveSequentialValue( current, false, cvals ); - unsigned derbase=0; double totweight=cvals[0], tnorm = cvals[0]; myvals.setValue( 1, cvals[1] ); + unsigned derbase=0; + double totweight=cvals[0], tnorm = cvals[0]; + myvals.setValue( 1, cvals[1] ); // Get the derivatives as well if we are in apply if( in_apply ) { // This bit gets the total weight double weight0 = cvals[0]; // Store the current weight for(unsigned j=1; jretrieveSequentialValue( current, false, cvals ); totweight *= cvals[0]; + stashes[j]->retrieveSequentialValue( current, false, cvals ); + totweight *= cvals[0]; } // And this bit the derivatives MultiValue& tmpval = stashes[0]->getTemporyMultiValue(0); if( tmpval.getNumberOfValues()!=myvessels[0]->getNumberOfQuantities() || - tmpval.getNumberOfDerivatives()!=myvessels[0]->getNumberOfDerivatives() ) + tmpval.getNumberOfDerivatives()!=myvessels[0]->getNumberOfDerivatives() ) { tmpval.resize( myvessels[0]->getNumberOfQuantities(), myvessels[0]->getNumberOfDerivatives() ); + } stashes[0]->retrieveDerivatives( stashes[0]->getTrueIndex(current), false, tmpval ); for(unsigned j=0; jgetNumberOfDerivatives(); } for(unsigned i=1; igetNumberOfQuantities() ) cvals.resize( myvessels[i]->getNumberOfQuantities() ); + if( cvals.size()!=myvessels[i]->getNumberOfQuantities() ) { + cvals.resize( myvessels[i]->getNumberOfQuantities() ); + } stashes[i]->retrieveSequentialValue( current, false, cvals ); - tnorm *= cvals[0]; myvals.setValue( 1+i, cvals[1] ); + tnorm *= cvals[0]; + myvals.setValue( 1+i, cvals[1] ); // Get the derivatives as well if we are in apply if( in_apply ) { MultiValue& tmpval = stashes[0]->getTemporyMultiValue(0); if( tmpval.getNumberOfValues()!=myvessels[0]->getNumberOfQuantities() || - tmpval.getNumberOfDerivatives()!=myvessels[0]->getNumberOfDerivatives() ) + tmpval.getNumberOfDerivatives()!=myvessels[0]->getNumberOfDerivatives() ) { tmpval.resize( myvessels[0]->getNumberOfQuantities(), myvessels[0]->getNumberOfDerivatives() ); + } stashes[i]->retrieveDerivatives( stashes[i]->getTrueIndex(current), false, tmpval ); for(unsigned j=0; jgetNumberOfDerivatives(); } } - myvals.setValue( 0, tnorm ); myvals.setValue( 1+myvessels.size(), ww ); - if( in_apply ) myvals.updateDynamicList(); + myvals.setValue( 0, tnorm ); + myvals.setValue( 1+myvessels.size(), ww ); + if( in_apply ) { + myvals.updateDynamicList(); + } } else { plumed_assert( !in_apply ); std::vector> vv( myhist->getVectorOfValues() ); @@ -486,40 +592,58 @@ void Histogram::compute( const unsigned& current, MultiValue& myvals ) const { // Retrieve the location of the grid point at which we are evaluating the kernel mygrid->getGridPointCoordinates( current, val ); if( kernel ) { - for(unsigned i=0; iset( val[i] ); + for(unsigned i=0; iset( val[i] ); + } // Evaluate the histogram at the relevant grid point and set the values - double vvh = kernel->evaluate( Tools::unique2raw(vv), der,true); myvals.setValue( 1, vvh ); + double vvh = kernel->evaluate( Tools::unique2raw(vv), der,true); + myvals.setValue( 1, vvh ); } else { plumed_merror("normalisation of vectors does not work with arguments and spherical grids"); // Evalulate dot product - double dot=0; for(unsigned j=0; jvon_misses_norm)*std::exp( (myhist->von_misses_concentration)*dot ); myvals.setValue( 1, newval ); + double newval = (myhist->von_misses_norm)*std::exp( (myhist->von_misses_concentration)*dot ); + myvals.setValue( 1, newval ); // And final derivatives - for(unsigned j=0; jvon_misses_concentration)*newval; + for(unsigned j=0; jvon_misses_concentration)*newval; + } } // Set the derivatives and delete the vector of values - for(unsigned i=0; iwasForced() ) return ; + if( !myhist->wasForced() ) { + return ; + } in_apply=true; // Run the loop to calculate the forces - runAllTasks(); finishAveraging(); + runAllTasks(); + finishAveraging(); // We now need to retrieve the buffer and set the forces on the atoms myhist->applyForce( forcesToApply ); // Now make the forces make sense for the virial unsigned fbase=0, tbase=0, vbase = getNumberOfDerivatives() - myvessels.size()*9; - for(unsigned i=vbase; igetNumberOfDerivatives()-9; ++j) { finalForces[fbase + j] = forcesToApply[tbase + j]; } unsigned k=0; for(unsigned j=myvessels[i]->getNumberOfDerivatives()-9; jgetNumberOfDerivatives(); ++j) { - finalForces[vbase + k] += forcesToApply[tbase + j]; k++; + finalForces[vbase + k] += forcesToApply[tbase + j]; + k++; } fbase += myvessels[i]->getNumberOfDerivatives() - 9; tbase += myvessels[i]->getNumberOfDerivatives(); diff --git a/src/analysis/LandmarkSelectionBase.cpp b/src/analysis/LandmarkSelectionBase.cpp index e307a86428..ae32f7de30 100644 --- a/src/analysis/LandmarkSelectionBase.cpp +++ b/src/analysis/LandmarkSelectionBase.cpp @@ -34,17 +34,23 @@ void LandmarkSelectionBase::registerKeywords( Keywords& keys ) { LandmarkSelectionBase::LandmarkSelectionBase( const ActionOptions& ao ): Action(ao), AnalysisBase(ao), - nlandmarks(0) -{ - if( keywords.exists("NLANDMARKS") ) parse("NLANDMARKS",nlandmarks); + nlandmarks(0) { + if( keywords.exists("NLANDMARKS") ) { + parse("NLANDMARKS",nlandmarks); + } log.printf(" selecting %u landmark points \n",nlandmarks); lweights.resize( nlandmarks ); parseFlag("NOVORONOI",novoronoi); - if( !novoronoi && !dissimilaritiesWereSet() ) error("cannot calculate voronoi weights without dissimilarity mesaure"); + if( !novoronoi && !dissimilaritiesWereSet() ) { + error("cannot calculate voronoi weights without dissimilarity mesaure"); + } - if( !novoronoi ) log.printf(" ascribing weights to landmarks using voronoi analysis\n"); - else log.printf(" ascribing weights of original points to landmark\n"); + if( !novoronoi ) { + log.printf(" ascribing weights to landmarks using voronoi analysis\n"); + } else { + log.printf(" ascribing weights of original points to landmark\n"); + } } void LandmarkSelectionBase::selectFrame( const unsigned& iframe ) { @@ -52,16 +58,21 @@ void LandmarkSelectionBase::selectFrame( const unsigned& iframe ) { } void LandmarkSelectionBase::performAnalysis() { - landmark_indices.resize(0); selectLandmarks(); + landmark_indices.resize(0); + selectLandmarks(); plumed_dbg_assert( nlandmarks==getNumberOfDataPoints() ); - if( lweights.size()!=nlandmarks ) lweights.resize( nlandmarks ); + if( lweights.size()!=nlandmarks ) { + lweights.resize( nlandmarks ); + } if( !novoronoi ) { lweights.assign(lweights.size(),0.0); std::vector tmpass( my_input_data->getNumberOfDataPoints() ); voronoiAnalysis( landmark_indices, lweights, tmpass ); } else { - for(unsigned i=0; igetWeight( landmark_indices[i] ); + for(unsigned i=0; igetWeight( landmark_indices[i] ); + } } } @@ -74,7 +85,10 @@ void LandmarkSelectionBase::voronoiAnalysis( const std::vector& myindi double mindist=my_input_data->getDissimilarity( i, myindices[0] ); for(unsigned j=1; jgetDissimilarity( i, myindices[j] ); - if( distgetWeight(i); } diff --git a/src/analysis/LandmarkSelectionBase.h b/src/analysis/LandmarkSelectionBase.h index 79647069d1..b68d1da256 100644 --- a/src/analysis/LandmarkSelectionBase.h +++ b/src/analysis/LandmarkSelectionBase.h @@ -60,7 +60,9 @@ class LandmarkSelectionBase : public AnalysisBase { /// Get the squared dissimilarity between two reference configurations double getDissimilarity( const unsigned& i, const unsigned& j ) override; /// This does nothing - it just ensures the final class is not abstract - void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { plumed_error(); } + void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { + plumed_error(); + } }; inline diff --git a/src/analysis/LandmarkStaged.cpp b/src/analysis/LandmarkStaged.cpp index 5471c79391..8413fb4276 100644 --- a/src/analysis/LandmarkStaged.cpp +++ b/src/analysis/LandmarkStaged.cpp @@ -57,9 +57,9 @@ void LandmarkStaged::registerKeywords( Keywords& keys ) { LandmarkStaged::LandmarkStaged( const ActionOptions& ao ): Action(ao), - LandmarkSelectionBase(ao) -{ - parse("SEED",seed); parse("GAMMA",gamma); + LandmarkSelectionBase(ao) { + parse("SEED",seed); + parse("GAMMA",gamma); log.printf(" probability of selecting voronoi polyhedra equal to exp(-weight/%f) \n", gamma ); } @@ -69,7 +69,9 @@ void LandmarkStaged::selectLandmarks() { unsigned int m = static_cast( std::sqrt(n*N) ); std::vector fpslandmarks(m); // Select first point at random - Random random; random.setSeed(-seed); double rand=random.RandU01(); + Random random; + random.setSeed(-seed); + double rand=random.RandU01(); fpslandmarks[0] = std::floor( N*rand ); // using FPS we want to find m landmarks where m = sqrt(nN) @@ -86,11 +88,18 @@ void LandmarkStaged::selectLandmarks() { for(unsigned j=0; jmaxd ) { + maxd=mind; + fpslandmarks[i]=j; } - if( mind>maxd ) { maxd=mind; fpslandmarks[i]=j; } } - for(unsigned k=0; kgetDissimilarity( fpslandmarks[i], k ); + for(unsigned k=0; kgetDissimilarity( fpslandmarks[i], k ); + } } // Initial FPS selection of m landmarks completed @@ -100,9 +109,13 @@ void LandmarkStaged::selectLandmarks() { voronoiAnalysis( fpslandmarks, weights, poly_assign ); //Calculate total weight of voronoi polyhedras - double vweight=0; for(unsigned i=0; i selected(N, false); unsigned ncount=0; + std::vector selected(N, false); + unsigned ncount=0; while ( ncount=rand ) { double tweight=0; for(unsigned i=0; i=rand_poly && !selected[i] ) { - selectFrame(i); selected[i]=true; ncount++; break; + selectFrame(i); + selected[i]=true; + ncount++; + break; } else if( running_tweight>=rand_poly ) { break; } diff --git a/src/analysis/OutputColvarFile.cpp b/src/analysis/OutputColvarFile.cpp index c5f67ee37a..7e0d5a6135 100644 --- a/src/analysis/OutputColvarFile.cpp +++ b/src/analysis/OutputColvarFile.cpp @@ -53,14 +53,17 @@ class OutputColvarFile : public AnalysisBase { public: static void registerKeywords( Keywords& keys ); explicit OutputColvarFile( const ActionOptions& ); - void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { plumed_error(); } + void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { + plumed_error(); + } void performAnalysis() override; }; PLUMED_REGISTER_ACTION(OutputColvarFile,"OUTPUT_ANALYSIS_DATA_TO_COLVAR") void OutputColvarFile::registerKeywords( Keywords& keys ) { - AnalysisBase::registerKeywords( keys ); keys.use("ARG"); + AnalysisBase::registerKeywords( keys ); + keys.use("ARG"); keys.add("compulsory","FILE","the name of the file to output to"); keys.add("compulsory","REPLICA","0","the replicas for which you would like to output this information"); keys.add("compulsory","STRIDE","0","the frequency with which to perform the required analysis and to output the data. The default value of 0 tells plumed to use all the data"); @@ -71,44 +74,72 @@ OutputColvarFile::OutputColvarFile( const ActionOptions& ao ): Action(ao), AnalysisBase(ao), fmt("%f"), - output_for_all_replicas(false) -{ - parse("FILE",filename); parse("FMT",fmt); - if( !getRestart() ) { OFile ofile; ofile.link(*this); ofile.setBackupString("analysis"); ofile.backupAllFiles(filename); } + output_for_all_replicas(false) { + parse("FILE",filename); + parse("FMT",fmt); + if( !getRestart() ) { + OFile ofile; + ofile.link(*this); + ofile.setBackupString("analysis"); + ofile.backupAllFiles(filename); + } log.printf(" printing data to file named %s \n",filename.c_str() ); if( getArguments().size()==0 ) { std::vector tmp_vals( my_input_data->getArgumentNames() ); - req_vals.resize( tmp_vals.size() ); for(unsigned i=0; igetName(); + req_vals.resize( getArguments().size() ); + for(unsigned i=0; igetName(); + } } if( req_vals.size()==0 ) { log.printf(" outputting weights from input action \n"); } else { log.printf(" outputting %s", req_vals[0].c_str() ); - for(unsigned i=1; igetAtomIndexes() ); mypdb.setArgumentNames( my_input_data->getArgumentNames() ); // Find a moldata object auto* moldat=plumed.getActionSet().selectLatest(this); - if( ! moldat ) warning("PDB output files do not have atom types unless you use MOLDATA"); + if( ! moldat ) { + warning("PDB output files do not have atom types unless you use MOLDATA"); + } - parse("FILE",filename); parse("FMT",fmt); - if( !getRestart() ) { OFile ofile; ofile.link(*this); ofile.setBackupString("analysis"); ofile.backupAllFiles(filename); } + parse("FILE",filename); + parse("FMT",fmt); + if( !getRestart() ) { + OFile ofile; + ofile.link(*this); + ofile.setBackupString("analysis"); + ofile.backupAllFiles(filename); + } log.printf(" printing data to file named %s \n",filename.c_str() ); } @@ -84,14 +93,24 @@ void OutputPDBFile::performAnalysis() { // Find a moldata object auto* mymoldat=plumed.getActionSet().selectLatest(this); // Output the embedding in plumed pdb format - OFile afile; afile.link(*this); afile.setBackupString("analysis"); std::size_t psign=fmt.find("%"); - afile.open( filename ); std::string descr="REMARK WEIGHT=%-" + fmt.substr(psign+1) + "\n"; + OFile afile; + afile.link(*this); + afile.setBackupString("analysis"); + std::size_t psign=fmt.find("%"); + afile.open( filename ); + std::string descr="REMARK WEIGHT=%-" + fmt.substr(psign+1) + "\n"; for(unsigned j=0; jgetDissimilarity( i,j ) ) ); + for(unsigned j=0; jgetDissimilarity( i,j ) ) ); + } ofile.printf("\n"); } ofile.close(); diff --git a/src/analysis/ReadAnalysisFrames.cpp b/src/analysis/ReadAnalysisFrames.cpp index 4739c2df72..cd4e511eab 100644 --- a/src/analysis/ReadAnalysisFrames.cpp +++ b/src/analysis/ReadAnalysisFrames.cpp @@ -40,7 +40,9 @@ PLUMED_REGISTER_ACTION(ReadAnalysisFrames,"COLLECT_FRAMES") void ReadAnalysisFrames::registerKeywords( Keywords& keys ) { AnalysisBase::registerKeywords( keys ); - keys.remove("SERIAL"); keys.remove("USE_OUTPUT_DATA_FROM"); keys.use("ARG"); + keys.remove("SERIAL"); + keys.remove("USE_OUTPUT_DATA_FROM"); + keys.use("ARG"); keys.add("atoms-1","ATOMS","the atoms whose positions we are tracking for the purpose of analyzing the data"); keys.add("atoms-1","STRIDE","the frequency with which data should be stored for analysis. By default data is collected on every step"); keys.add("compulsory","CLEAR","0","the frequency with which data should all be deleted and restarted"); @@ -53,28 +55,39 @@ ReadAnalysisFrames::ReadAnalysisFrames( const ActionOptions& ao ): AnalysisBase(ao), clearonnextstep(false), wham_pointer(NULL), - weights_calculated(false) -{ + weights_calculated(false) { parse("CLEAR",clearstride); - if( clearstride!=0 ) log.printf(" clearing stored data every %u steps\n",clearstride); + if( clearstride!=0 ) { + log.printf(" clearing stored data every %u steps\n",clearstride); + } // Get the names of the argumes argument_names.resize( getNumberOfArguments() ); - for(unsigned i=0; igetName(); + for(unsigned i=0; igetName(); + } // Find the atom numbers to read in parseAtomList("ATOMS",atom_numbers); if( atom_numbers.size()>0 ) { log.printf(" monitoring positions of atoms "); - for(unsigned i=0; i wwstr; parseVector("LOGWEIGHTS",wwstr); - if( wwstr.size()>0 ) log.printf(" reweighting using weights from "); + std::vector wwstr; + parseVector("LOGWEIGHTS",wwstr); + if( wwstr.size()>0 ) { + log.printf(" reweighting using weights from "); + } std::vector arg( ActionWithArguments::getArguments() ); for(unsigned i=0; i(wwstr[i]); - if( !val ) error("could not find value named"); + if( !val ) { + error("could not find value named"); + } weight_vals.push_back( val->copyOutput(val->getLabel()) ); arg.push_back( val->copyOutput(val->getLabel()) ); log.printf("%s ",wwstr[i].c_str() ); @@ -82,19 +95,31 @@ ReadAnalysisFrames::ReadAnalysisFrames( const ActionOptions& ao ): if( wwstr.size()>0 ) { log.printf("\n"); wham_pointer = dynamic_cast( weight_vals[0]->getPntrToAction() ); - if( !wham_pointer ) wham_pointer = NULL; - else if( !wham_pointer->buildsWeightStore() ) wham_pointer = NULL; - if( wham_pointer && weight_vals.size()!=1 ) error("can only extract weights from one wham object"); - } else log.printf(" weights are all equal to one\n"); + if( !wham_pointer ) { + wham_pointer = NULL; + } else if( !wham_pointer->buildsWeightStore() ) { + wham_pointer = NULL; + } + if( wham_pointer && weight_vals.size()!=1 ) { + error("can only extract weights from one wham object"); + } + } else { + log.printf(" weights are all equal to one\n"); + } requestArguments( arg ); // Now add fake components to the underlying ActionWithValue for the arguments - for(unsigned i=0; i ReadAnalysisFrames::getArgumentList() { std::vector arg_vals( ActionWithArguments::getArguments() ); - for(unsigned i=0; icalculateWeights( logweights.size() ); - for(unsigned i=0; igetWeight(i); + for(unsigned i=0; igetWeight(i); + } } else { // Find the maximum weight double maxweight=logweights[0]; for(unsigned i=1; imaxweight) maxweight=logweights[i]; + if(logweights[i]>maxweight) { + maxweight=logweights[i]; + } } // Calculate weights (no memory) -- business here with maxweight is to prevent overflows - for(unsigned i=0; iclearData(); + my_data_stash.clear(); + my_data_stash.resize(0); + logweights.clear(); + logweights.resize(0); + if( wham_pointer ) { + wham_pointer->clearData(); + } clearonnextstep=false; } // Get the weight and store it in the weights array - double ww=0; for(unsigned i=0; iget(); - weights_calculated=false; logweights.push_back(ww); + double ww=0; + for(unsigned i=0; iget(); + } + weights_calculated=false; + logweights.push_back(ww); // Now create the data collection object and push it back to be stored - unsigned index = my_data_stash.size(); my_data_stash.push_back( DataCollectionObject() ); + unsigned index = my_data_stash.size(); + my_data_stash.push_back( DataCollectionObject() ); my_data_stash[index].setAtomNumbersAndArgumentNames( getLabel(), atom_numbers, argument_names ); my_data_stash[index].setAtomPositions( getPositions() ); - for(unsigned i=0; i0 ) { - if( getStep()%clearstride==0 ) clearonnextstep=true; + if( getStep()%clearstride==0 ) { + clearonnextstep=true; + } } } diff --git a/src/analysis/ReadAnalysisFrames.h b/src/analysis/ReadAnalysisFrames.h index f0b814c758..1cb22de59a 100644 --- a/src/analysis/ReadAnalysisFrames.h +++ b/src/analysis/ReadAnalysisFrames.h @@ -55,7 +55,9 @@ class ReadAnalysisFrames : public AnalysisBase { /// This does nothing void performAnalysis() override {} /// This does nothing - it just ensures the final class is not abstract - void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { plumed_error(); } + void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { + plumed_error(); + } /// Get the number of data points unsigned getNumberOfDataPoints() const override; /// Get the index of the data point @@ -91,7 +93,9 @@ bool ReadAnalysisFrames::dissimilaritiesWereSet() const { inline double ReadAnalysisFrames::getWeight( const unsigned& idat ) { - if( !weights_calculated ) calculateWeights(); + if( !weights_calculated ) { + calculateWeights(); + } return weights[idat]; } diff --git a/src/analysis/ReadDissimilarityMatrix.cpp b/src/analysis/ReadDissimilarityMatrix.cpp index 5654feb71b..8bcf2e87e3 100644 --- a/src/analysis/ReadDissimilarityMatrix.cpp +++ b/src/analysis/ReadDissimilarityMatrix.cpp @@ -58,7 +58,9 @@ class ReadDissimilarityMatrix : public AnalysisBase { /// This gives an error as if we read in the matrix we dont have the coordinates DataCollectionObject& getStoredData( const unsigned& idata, const bool& calcdist ) override; /// Tell everyone we have dissimilarities - bool dissimilaritiesWereSet() const override { return true; } + bool dissimilaritiesWereSet() const override { + return true; + } /// Get the dissimilarity between two data points double getDissimilarity( const unsigned&, const unsigned& ) override; /// Get the weight from the input file @@ -70,7 +72,9 @@ class ReadDissimilarityMatrix : public AnalysisBase { /// This does nothing void performAnalysis() override {}; /// Overwrite virtual function in base class - void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { plumed_error(); } + void performTask( const unsigned&, const unsigned&, MultiValue& ) const override { + plumed_error(); + } }; PLUMED_REGISTER_ACTION(ReadDissimilarityMatrix,"READ_DISSIMILARITY_MATRIX") @@ -85,52 +89,74 @@ void ReadDissimilarityMatrix::registerKeywords( Keywords& keys ) { ReadDissimilarityMatrix::ReadDissimilarityMatrix( const ActionOptions& ao ): Action(ao), AnalysisBase(ao), - nnodes(1) -{ + nnodes(1) { setStride(1); // Set the stride equal to one to ensure we don't get stuck in an infinite loop std::vector setupActions=plumed.getActionSet().select(); - if( my_input_data && (plumed.getActionSet().size()-setupActions.size())!=1 ) error("should only be this action and the READ_ANALYSIS_FRAMES command in the input file"); - if( !my_input_data && plumed.getActionSet().size()!=0 ) error("read dissimilarity matrix command must be at top of input file"); + if( my_input_data && (plumed.getActionSet().size()-setupActions.size())!=1 ) { + error("should only be this action and the READ_ANALYSIS_FRAMES command in the input file"); + } + if( !my_input_data && plumed.getActionSet().size()!=0 ) { + error("read dissimilarity matrix command must be at top of input file"); + } parse("FILE",fname); log.printf(" reading dissimilarity matrix from file %s \n",fname.c_str() ); parse("WFILE",wfile); - if( wfile.length()>0 ) log.printf(" reading weights of nodes from file named %s \n",wfile.c_str() ); - else log.printf(" setting weights of all nodes equal to one\n"); + if( wfile.length()>0 ) { + log.printf(" reading weights of nodes from file named %s \n",wfile.c_str() ); + } else { + log.printf(" setting weights of all nodes equal to one\n"); + } } -void ReadDissimilarityMatrix::update() { if(!my_input_data) plumed.stop(); } +void ReadDissimilarityMatrix::update() { + if(!my_input_data) { + plumed.stop(); + } +} void ReadDissimilarityMatrix::runFinalJobs() { - IFile mfile; mfile.open(fname); + IFile mfile; + mfile.open(fname); // Read in first line - std::vector words; nnodes=0; + std::vector words; + nnodes=0; while( nnodes==0 ) { Tools::getParsedLine( mfile, words ); nnodes=words.size(); } std::vector tmpdis( nnodes ); - for(unsigned j=0; j0 ) { - IFile wfilef; wfilef.open(wfile); + IFile wfilef; + wfilef.open(wfile); for(unsigned i=0; i( datastr ); - if( !mylandmarks ) error("input to LANDMARKS is not a landmark selection action"); + if( !mylandmarks ) { + error("input to LANDMARKS is not a landmark selection action"); + } nlandmarks = mylandmarks->nlandmarks; - if( (mylandmarks->my_input_data)->getNumberOfDataPoints()!=my_input_data->getNumberOfDataPoints() ) error("mismatch between amount of landmark class and base class"); + if( (mylandmarks->my_input_data)->getNumberOfDataPoints()!=my_input_data->getNumberOfDataPoints() ) { + error("mismatch between amount of landmark class and base class"); + } } void ReselectLandmarks::selectLandmarks() { - for(unsigned i=0; igetNumberOfDataPoints(); ++i) selectFrame( mylandmarks->getDataPointIndexInBase(i) ); + for(unsigned i=0; igetNumberOfDataPoints(); ++i) { + selectFrame( mylandmarks->getDataPointIndexInBase(i) ); + } } } diff --git a/src/analysis/SelectRandomFrames.cpp b/src/analysis/SelectRandomFrames.cpp index a0ab44c1fe..1345af1257 100644 --- a/src/analysis/SelectRandomFrames.cpp +++ b/src/analysis/SelectRandomFrames.cpp @@ -53,13 +53,13 @@ void SelectRandomFrames::registerKeywords( Keywords& keys ) { SelectRandomFrames::SelectRandomFrames( const ActionOptions& ao ): Action(ao), - LandmarkSelectionBase(ao) -{ + LandmarkSelectionBase(ao) { parse("SEED",seed); } void SelectRandomFrames::selectLandmarks() { - Random r; r.setSeed(-seed); + Random r; + r.setSeed(-seed); unsigned nframe=my_input_data->getNumberOfDataPoints(); unsigned nland=getNumberOfDataPoints(); diff --git a/src/analysis/SelectWithStride.cpp b/src/analysis/SelectWithStride.cpp index 3af046af6c..c5a444cfe1 100644 --- a/src/analysis/SelectWithStride.cpp +++ b/src/analysis/SelectWithStride.cpp @@ -49,13 +49,14 @@ void SelectWithStride::registerKeywords( Keywords& keys ) { SelectWithStride::SelectWithStride( const ActionOptions& ao ): Action(ao), - LandmarkSelectionBase(ao) -{ + LandmarkSelectionBase(ao) { } void SelectWithStride::selectLandmarks() { unsigned stride = std::floor( my_input_data->getNumberOfDataPoints() / getNumberOfDataPoints() ), max=stride*getNumberOfDataPoints(); - for(unsigned i=0; i 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 84a2394f4d..26a77d6568 100755 --- a/src/astyle.sh +++ b/src/astyle.sh @@ -8,6 +8,8 @@ echo "$DIRS" # shellcheck disable=SC2125 test -z "$DIRS" && DIRS=* +options=../../.astyle.options + for dir in $DIRS; do test -d "$dir" || continue @@ -29,7 +31,7 @@ for dir in $DIRS; do echo -n "astyle $file" - ../../astyle/astyle --options=../../.astyle.options <"$file" >"$file.tmp" && { + ../../astyle/astyle --options="$options" <"$file" >"$file.tmp" && { if cmp -s "$file" "$file.tmp"; then echo else @@ -42,7 +44,6 @@ for dir in $DIRS; do rm "$file.tmp" done - cd - || { echo "Problem with 'cd -' from '$dir'" exit 1 diff --git a/src/bias/ABMD.cpp b/src/bias/ABMD.cpp index dd9400ce52..83539f9830 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 0cb1d61cca..474cb0f02f 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"); @@ -76,13 +75,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 482181e10b..9de689847d 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 161385f6c5..4bf24c890e 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 caeffa71a0..1d27306073 100644 --- a/src/bias/ExtendedLagrangian.cpp +++ b/src/bias/ExtendedLagrangian.cpp @@ -156,31 +156,42 @@ 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); double temp=-1.0; parse("TEMP",temp); - if(temp>=0.0) kbt=plumed.getAtoms().getKBoltzmann()*temp; - else kbt=plumed.getAtoms().getKbT(); + if(temp>=0.0) { + kbt=plumed.getAtoms().getKBoltzmann()*temp; + } else { + kbt=plumed.getAtoms().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 436208c10b..f9e56150d8 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 dc39572687..70044f51ef 100644 --- a/src/bias/LWalls.cpp +++ b/src/bias/LWalls.cpp @@ -98,8 +98,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); @@ -109,22 +108,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=0.; parse("TEMP",simtemp); - if(simtemp>0) simtemp*=plumed.getAtoms().getKBoltzmann(); - else simtemp=plumed.getAtoms().getKbT(); + if(simtemp>0) { + simtemp*=plumed.getAtoms().getKBoltzmann(); + } else { + simtemp=plumed.getAtoms().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; @@ -321,24 +355,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(); } } @@ -346,15 +384,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(); } } @@ -363,9 +403,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)); } @@ -374,21 +414,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; + } } } } @@ -415,18 +456,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]) { @@ -437,17 +480,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() { @@ -470,13 +514,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 0f1e75533e..f9ab361d27 100644 --- a/src/bias/MetaD.cpp +++ b/src/bias/MetaD.cpp @@ -384,8 +384,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; + } } } }; @@ -629,8 +632,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; @@ -657,7 +659,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) { @@ -675,7 +679,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_); @@ -692,7 +700,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); @@ -707,25 +717,36 @@ 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"); + if( biasf_<1.0 && biasf_!=-1.0) { + error("well tempered bias factor is nonsensical"); + } parse("DAMPFACTOR",dampfactor_); double temp=0.0; parse("TEMP",temp); - if(temp>0.0) kbt_=plumed.getAtoms().getKBoltzmann()*temp; - else kbt_=plumed.getAtoms().getKbT(); + if(temp>0.0) { + kbt_=plumed.getAtoms().getKBoltzmann()*temp; + } else { + kbt_=plumed.getAtoms().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_); @@ -733,14 +754,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"); } @@ -749,53 +774,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); @@ -824,32 +891,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; @@ -861,17 +935,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_); @@ -890,13 +970,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; } @@ -934,9 +1021,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) { @@ -1002,33 +1119,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(); @@ -1040,7 +1177,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_); } @@ -1052,20 +1191,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) { @@ -1099,7 +1244,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); @@ -1108,33 +1255,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"); + } } } } @@ -1160,7 +1319,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(); } @@ -1175,22 +1335,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!"); + } } #ifdef __PLUMED_HAS_GETCWD @@ -1246,7 +1433,9 @@ MetaD::MetaD(const ActionOptions& ao): plumed_assert(ret)<<"Name of current directory too long, increase buffer size"; 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); } #endif @@ -1258,7 +1447,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; @@ -1267,7 +1457,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; @@ -1287,20 +1478,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(); @@ -1311,23 +1510,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(); @@ -1344,12 +1554,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_); } @@ -1357,14 +1573,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_) { @@ -1373,12 +1597,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"; @@ -1388,29 +1620,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); @@ -1450,20 +1701,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); @@ -1526,7 +1783,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); @@ -1541,24 +1800,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(); @@ -1581,9 +1847,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(); @@ -1624,13 +1894,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) @@ -1735,12 +2015,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]); } @@ -1775,13 +2061,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) @@ -1789,18 +2076,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; @@ -1831,11 +2126,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); @@ -1887,8 +2189,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 { @@ -1896,37 +2197,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_)); @@ -1941,22 +2259,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_) { @@ -2005,13 +2331,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); @@ -2020,15 +2352,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; } @@ -2037,16 +2375,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 @@ -2055,14 +2399,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! @@ -2078,12 +2426,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_); @@ -2100,8 +2452,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)) { @@ -2111,8 +2462,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"); } @@ -2121,7 +2474,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") { @@ -2130,9 +2485,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); @@ -2164,9 +2523,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 { @@ -2174,8 +2539,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; @@ -2205,8 +2569,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]); @@ -2239,14 +2602,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_; @@ -2254,37 +2618,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 5065d2476c..4df16e2edc 100644 --- a/src/bias/MovingRestraint.cpp +++ b/src/bias/MovingRestraint.cpp @@ -149,25 +149,33 @@ void MovingRestraint::registerKeywords( Keywords& keys ) { MovingRestraint::MovingRestraint(const ActionOptions&ao): PLUMED_BIAS_INIT(ao), - verse(getNumberOfArguments()) -{ + verse(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); comp=getPntrToArgument(i)->getName()+"_work"; // each spring has its own work - addComponent(comp); componentIsNotPeriodic(comp); + addComponent(comp); + componentIsNotPeriodic(comp); comp=getPntrToArgument(i)->getName()+"_kappa"; // each spring has its own kappa - addComponent(comp); componentIsNotPeriodic(comp); + addComponent(comp); + componentIsNotPeriodic(comp); work.push_back(0.); // initialize the work value } - addComponent("work"); componentIsNotPeriodic("work"); + addComponent("work"); + componentIsNotPeriodic("work"); tot_work=0.0; log<<" Bibliography "; @@ -223,10 +240,15 @@ void MovingRestraint::calculate() { aa=at[step.size()-1]; } else { unsigned i=0; - for(i=1; igetName()+"_cntr")->set(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]); + } getPntrToComponent(getPntrToArgument(i)->getName()+"_work")->set(work[i]); getPntrToComponent(getPntrToArgument(i)->getName()+"_kappa")->set(kk[i]); tot_work+=work[i]; diff --git a/src/bias/PBMetaD.cpp b/src/bias/PBMetaD.cpp index 8251a350d2..88da1e46fe 100644 --- a/src/bias/PBMetaD.cpp +++ b/src/bias/PBMetaD.cpp @@ -247,7 +247,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 @@ -383,8 +388,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; @@ -410,7 +414,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 << ":"; @@ -449,7 +455,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"); + } } } @@ -478,7 +486,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; i0.0) kbt_=plumed.getAtoms().getKBoltzmann()*temp; - else kbt_=plumed.getAtoms().getKbT(); + if(temp>0.0) { + kbt_=plumed.getAtoms().getKBoltzmann()*temp; + } else { + kbt_=plumed.getAtoms().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; } 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_; } @@ -540,7 +569,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_); @@ -560,8 +591,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_; @@ -570,32 +602,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 @@ -646,13 +719,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(); @@ -688,20 +775,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"; @@ -764,16 +867,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_)); } @@ -790,7 +902,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]; @@ -799,7 +912,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]; @@ -818,16 +932,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]) { @@ -874,7 +1002,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)); @@ -882,20 +1012,24 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } log<<" Bibliography "<1||walkers_mpi_) log<1||walkers_mpi_) + log< center(1); std::vector sigma(1); double height; @@ -909,14 +1043,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]); @@ -932,17 +1067,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); @@ -976,8 +1115,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) { @@ -1002,8 +1140,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_) { @@ -1013,7 +1150,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); @@ -1027,8 +1166,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 @@ -1038,8 +1176,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]); @@ -1068,11 +1211,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]; @@ -1086,7 +1230,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) { @@ -1236,7 +1400,9 @@ void PBMetaD::update() for(unsigned i=0; iisOpen())) { // check if it exists now and open it! @@ -1257,8 +1423,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]]; @@ -1267,15 +1432,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(); @@ -1285,9 +1454,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]); @@ -1297,9 +1470,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 { @@ -1308,12 +1487,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 4644fa2eae..ffe239ca0b 100644 --- a/src/bias/Restraint.cpp +++ b/src/bias/Restraint.cpp @@ -82,21 +82,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; i0) simtemp*=plumed.getAtoms().getKBoltzmann(); - else simtemp=plumed.getAtoms().getKbT(); - if(simtemp==0) error("The MD engine does not pass the temperature to plumed so you have to specify it using TEMP"); + ActionWithArguments(ao) { + simtemp=0.; + parse("TEMP",simtemp); + if(simtemp>0) { + simtemp*=plumed.getAtoms().getKBoltzmann(); + } else { + simtemp=plumed.getAtoms().getKbT(); + } + 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 6059c998ea..f7f1b4cd1e 100644 --- a/src/bias/ReweightBias.cpp +++ b/src/bias/ReweightBias.cpp @@ -78,19 +78,22 @@ 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"); } 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); @@ -223,7 +224,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"); } @@ -239,27 +242,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/plumed.getAtoms().getKBoltzmann(),rtemp_/plumed.getAtoms().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/plumed.getAtoms().getKBoltzmann(),rtemp_/plumed.getAtoms().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/plumed.getAtoms().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/plumed.getAtoms().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/plumed.getAtoms().getKBoltzmann(), press_, rtemp_/plumed.getAtoms().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/plumed.getAtoms().getKBoltzmann(), press_, rtemp_/plumed.getAtoms().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/ReweightWham.cpp b/src/bias/ReweightWham.cpp index b6628aa57d..2f14346dec 100644 --- a/src/bias/ReweightWham.cpp +++ b/src/bias/ReweightWham.cpp @@ -86,7 +86,9 @@ class ReweightWham : public ReweightBase { public: static void registerKeywords(Keywords&); explicit ReweightWham(const ActionOptions&ao); - bool buildsWeightStore() const override { return true; } + bool buildsWeightStore() const override { + return true; + } void calculateWeights( const unsigned& nframes ) override; void clearData() override; double getLogWeight() override; @@ -96,7 +98,8 @@ class ReweightWham : public ReweightBase { PLUMED_REGISTER_ACTION(ReweightWham,"REWEIGHT_WHAM") void ReweightWham::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.add("compulsory","MAXITER","1000","maximum number of iterations for WHAM algorithm"); keys.add("compulsory","WHAMTOL","1e-10","threshold for convergence of WHAM algorithm"); @@ -105,22 +108,33 @@ void ReweightWham::registerKeywords(Keywords& keys ) { ReweightWham::ReweightWham(const ActionOptions&ao): Action(ao), ReweightBase(ao), - weightsCalculated(false) -{ - parse("MAXITER",maxiter); parse("WHAMTOL",thresh); - if(comm.Get_rank()==0) nreplicas=multi_sim_comm.Get_size(); + weightsCalculated(false) { + parse("MAXITER",maxiter); + parse("WHAMTOL",thresh); + if(comm.Get_rank()==0) { + nreplicas=multi_sim_comm.Get_size(); + } comm.Bcast(nreplicas,0); } double ReweightWham::getLogWeight() { - if( getStep()==0 ) return 1.0; // This is here as first step is ignored in all analyses + if( getStep()==0 ) { + return 1.0; // This is here as first step is ignored in all analyses + } weightsCalculated=false; - double bias=0.0; for(unsigned i=0; i biases(nreplicas,0.0); - if(comm.Get_rank()==0) multi_sim_comm.Allgather(bias,biases); + if(comm.Get_rank()==0) { + multi_sim_comm.Allgather(bias,biases); + } comm.Bcast(biases,0); - for(unsigned i=0; i 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; iter 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"); @@ -257,12 +258,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) { @@ -271,7 +273,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" @@ -282,18 +285,26 @@ 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); - 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); + 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)) { @@ -306,23 +317,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: @@ -333,7 +358,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 { @@ -345,14 +372,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=[](FILE* f) { if(f) std::fclose(f); }; + auto deleter=[](FILE* 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) { @@ -363,12 +399,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; @@ -376,10 +415,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); @@ -390,13 +437,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); @@ -415,13 +466,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; @@ -451,29 +513,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()); @@ -490,7 +568,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); } }; @@ -508,22 +588,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"); } @@ -534,7 +625,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; @@ -542,43 +635,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=[](xdrfile::XDRFILE* xd) { if(xd) xdrfile::xdrfile_close(xd); }; + auto xdr_deleter=[](xdrfile::XDRFILE* 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(); @@ -591,8 +700,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); @@ -646,8 +759,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); } @@ -657,7 +774,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) { @@ -665,13 +784,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") { @@ -696,7 +820,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]; } @@ -704,7 +830,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; @@ -725,52 +853,78 @@ 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); Action* aa=p.getActionSet()[p.getActionSet().size()-1].get(); + p.readInputWords(words); + Action* aa=p.getActionSet()[p.getActionSet().size()-1].get(); ActionWithValue* av=dynamic_cast(aa); 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=dynamic_cast( aa ); 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; } if( data.find( as->getShortcutLabel() )!=data.end() ) { std::vector shortcut_commands = as->getSavedInputLines(); - for(unsigned i=0; igetShortcutLabel() ].push_back( shortcut_commands[i] ); - } else data[ as->getShortcutLabel() ] = as->getSavedInputLines(); + for(unsigned i=0; igetShortcutLabel() ].push_back( shortcut_commands[i] ); + } + } else { + data[ as->getShortcutLabel() ] = as->getSavedInputLines(); + } } } 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; j::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]; } @@ -797,8 +953,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... @@ -877,17 +1059,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) { @@ -900,36 +1099,52 @@ int Driver::main(FILE* in,FILE*out,Communicator& pc) { &celld[0], &celld[1], &celld[2], &celld[3], &celld[4], &celld[5], &celld[6], &celld[7], &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]); @@ -956,18 +1179,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]); + } } } @@ -1031,7 +1278,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"); } } @@ -1074,14 +1334,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; } @@ -1115,11 +1383,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 c660c0b92f..1c0bfad74c 100644 --- a/src/cltools/GenExample.cpp +++ b/src/cltools/GenExample.cpp @@ -59,8 +59,7 @@ plumed gen_example --plumed plumed.dat --status working //+ENDPLUMEDOC class GenExample: - public CLTool -{ + public CLTool { private: int multi; std::string status, version; @@ -92,8 +91,7 @@ GenExample::GenExample(const CLToolOptions& co ): CLTool(co), multi(0), status("nobadge"), - version("master") -{ + version("master") { inputdata=commandline; } @@ -102,32 +100,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 ) { @@ -138,11 +165,17 @@ int GenExample::main(FILE* in, FILE*out,Communicator& pc) { } ofile<<"
"; ofile<<"\"tested
"; ofile.flush(); if( hasshortcuts ) { @@ -168,107 +201,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("=");
@@ -276,22 +406,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<<""; @@ -310,31 +465,42 @@ void GenExample::printExampleInput( const std::vector > myplumed.readInputLine( myinputline ); ActionWithValue* av=dynamic_cast( 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 tname=myname.substr(dot+1); std::size_t und=tname.find_last_of("_"); std::size_t hyph=tname.find_first_of("-"); - if( und!=std::string::npos && hyph!=std::string::npos ) plumed_merror("cannot use underscore and hyphen in name"); + std::string myname = av->copyOutput(k)->getName(); + std::size_t dot=myname.find_first_of("."); + std::string tname=myname.substr(dot+1); + std::size_t und=tname.find_last_of("_"); + std::size_t hyph=tname.find_first_of("-"); + if( und!=std::string::npos && hyph!=std::string::npos ) { + plumed_merror("cannot use underscore and hyphen in name"); + } ofile<<""<"; if( und!=std::string::npos ) { ofile<"<"<( 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(); @@ -94,31 +101,55 @@ 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; i3) 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/kT.cpp b/src/cltools/kT.cpp index f8a39c8ef1..0717aa0783 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 25d18fe466..9284d586a6 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()); + } plumed->cmd("setNoVirial"); int natoms=( std::floor(dim/3) + 2 ); plumed->cmd("setNatoms",&natoms); @@ -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"); @@ -231,14 +271,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]; @@ -248,7 +292,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]; } @@ -266,12 +312,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]; } } @@ -281,7 +331,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]; @@ -291,14 +343,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/colvar/Angle.cpp b/src/colvar/Angle.cpp index 97ff219730..ca1f0107fb 100644 --- a/src/colvar/Angle.cpp +++ b/src/colvar/Angle.cpp @@ -97,8 +97,7 @@ void Angle::registerKeywords( Keywords& keys ) { Angle::Angle(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), - pbc(true) -{ + pbc(true) { std::vector atoms; parseAtomList("ATOMS",atoms); bool nopbc=!pbc; @@ -112,12 +111,18 @@ Angle::Angle(const ActionOptions&ao): atoms[2]=atoms[1]; } else if(atoms.size()==4) { log.printf(" between lines %d-%d and %d-%d\n",atoms[0].serial(),atoms[1].serial(),atoms[2].serial(),atoms[3].serial()); - } else error("Number of specified atoms should be either 3 or 4"); - - if(pbc) log.printf(" using periodic boundary conditions\n"); - else log.printf(" without periodic boundary conditions\n"); - - addValueWithDerivatives(); setNotPeriodic(); + } else { + error("Number of specified atoms should be either 3 or 4"); + } + + if(pbc) { + log.printf(" using periodic boundary conditions\n"); + } else { + log.printf(" without periodic boundary conditions\n"); + } + + addValueWithDerivatives(); + setNotPeriodic(); requestAtoms(atoms); checkRead(); } @@ -125,7 +130,9 @@ Angle::Angle(const ActionOptions&ao): // calculator void Angle::calculate() { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } Vector dij,dik; dij=delta(getPosition(2),getPosition(3)); diff --git a/src/colvar/Cell.cpp b/src/colvar/Cell.cpp index c6c447ac7e..4b8913284f 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); } @@ -95,9 +112,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/Constant.cpp b/src/colvar/Constant.cpp index ea8de35ac3..fd0c1b82f5 100644 --- a/src/colvar/Constant.cpp +++ b/src/colvar/Constant.cpp @@ -69,31 +69,43 @@ class Constant : public Colvar { PLUMED_REGISTER_ACTION(Constant,"CONSTANT") Constant::Constant(const ActionOptions&ao): - PLUMED_COLVAR_INIT(ao) -{ + PLUMED_COLVAR_INIT(ao) { bool noderiv=false; parseFlag("NODERIV",noderiv); parseVector("VALUES",values); std::vector value; parseVector("VALUE",value); - if(values.size()==0&&value.size()==0) error("One should use either VALUE or VALUES"); - if(values.size()!=0&&value.size()!=0) error("One should use either VALUE or VALUES"); - if(value.size()>1) error("VALUE cannot take more than one number"); + if(values.size()==0&&value.size()==0) { + error("One should use either VALUE or VALUES"); + } + if(values.size()!=0&&value.size()!=0) { + error("One should use either VALUE or VALUES"); + } + if(value.size()>1) { + error("VALUE cannot take more than one number"); + } if(values.size()==0) { values.resize(1); values[0]=value[0]; } checkRead(); if(values.size()==1) { - if(!noderiv) addValueWithDerivatives(); - else addValue(); + if(!noderiv) { + addValueWithDerivatives(); + } else { + addValue(); + } setNotPeriodic(); setValue(values[0]); } else if(values.size()>1) { for(unsigned i=0; iset(values[i]); diff --git a/src/colvar/ContactMap.cpp b/src/colvar/ContactMap.cpp index c82075f88f..1075d3c4d9 100644 --- a/src/colvar/ContactMap.cpp +++ b/src/colvar/ContactMap.cpp @@ -146,12 +146,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; @@ -160,39 +161,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; i( type ); drmsd_->setBoundsOnDistances( !nopbc, lcutoff, ucutoff ); drmsd_->read( pdb ); @@ -165,14 +167,19 @@ DRMSD::DRMSD(const ActionOptions&ao): requestAtoms( atoms ); // Setup the derivative pack - myvals.resize( 1, 3*atoms.size()+9 ); mypack.resize( 0, atoms.size() ); - for(unsigned i=0; icalculate(getPositions(), getPbc(), mypack, false); setValue(drmsd); - 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 5e985e3c5b..90c61545c2 100644 --- a/src/colvar/Dipole.cpp +++ b/src/colvar/Dipole.cpp @@ -81,18 +81,21 @@ void Dipole::registerKeywords(Keywords& keys) { Dipole::Dipole(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), - components(false) -{ + components(false) { parseAtomList("GROUP",ga_lista); parseFlag("COMPONENTS",components); parseFlag("NOPBC",nopbc); checkRead(); if(components) { - addComponentWithDerivatives("x"); componentIsNotPeriodic("x"); - addComponentWithDerivatives("y"); componentIsNotPeriodic("y"); - addComponentWithDerivatives("z"); componentIsNotPeriodic("z"); + addComponentWithDerivatives("x"); + componentIsNotPeriodic("x"); + addComponentWithDerivatives("y"); + componentIsNotPeriodic("y"); + addComponentWithDerivatives("z"); + componentIsNotPeriodic("z"); } else { - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); } log.printf(" of %u atoms\n",static_cast(ga_lista.size())); @@ -100,16 +103,20 @@ Dipole::Dipole(const ActionOptions&ao): log.printf(" %d", ga_lista[i].serial()); } log.printf(" \n"); - 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"); + } requestAtoms(ga_lista); } // calculator -void Dipole::calculate() -{ - if(!nopbc) makeWhole(); +void Dipole::calculate() { + if(!nopbc) { + makeWhole(); + } double ctot=0.; unsigned N=getNumberOfAtoms(); std::vector charges(N); diff --git a/src/colvar/Distance.cpp b/src/colvar/Distance.cpp index bf901435f9..94576cf3d7 100644 --- a/src/colvar/Distance.cpp +++ b/src/colvar/Distance.cpp @@ -134,12 +134,12 @@ Distance::Distance(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), components(false), scaled_components(false), - 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"); + } parseFlag("COMPONENTS",components); parseFlag("SCALED_COMPONENTS",scaled_components); bool nopbc=!pbc; @@ -148,22 +148,34 @@ Distance::Distance(const ActionOptions&ao): 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"); + } - if(components && scaled_components) error("COMPONENTS and SCALED_COMPONENTS are not compatible"); + if(components && scaled_components) { + error("COMPONENTS and SCALED_COMPONENTS are not compatible"); + } if(components) { - addComponentWithDerivatives("x"); componentIsNotPeriodic("x"); - addComponentWithDerivatives("y"); componentIsNotPeriodic("y"); - addComponentWithDerivatives("z"); componentIsNotPeriodic("z"); + addComponentWithDerivatives("x"); + componentIsNotPeriodic("x"); + addComponentWithDerivatives("y"); + componentIsNotPeriodic("y"); + addComponentWithDerivatives("z"); + componentIsNotPeriodic("z"); log<<" WARNING: components will not have the proper periodicity - see manual\n"; } else if(scaled_components) { - addComponentWithDerivatives("a"); componentIsPeriodic("a","-0.5","+0.5"); - addComponentWithDerivatives("b"); componentIsPeriodic("b","-0.5","+0.5"); - addComponentWithDerivatives("c"); componentIsPeriodic("c","-0.5","+0.5"); + addComponentWithDerivatives("a"); + componentIsPeriodic("a","-0.5","+0.5"); + addComponentWithDerivatives("b"); + componentIsPeriodic("b","-0.5","+0.5"); + addComponentWithDerivatives("c"); + componentIsPeriodic("c","-0.5","+0.5"); } else { - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); } @@ -174,7 +186,9 @@ Distance::Distance(const ActionOptions&ao): // calculator void Distance::calculate() { - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } Vector distance=delta(getPosition(0),getPosition(1)); const double value=distance.modulo(); diff --git a/src/colvar/EEFSolv.cpp b/src/colvar/EEFSolv.cpp index 7cf1a1e07e..9e752fa123 100644 --- a/src/colvar/EEFSolv.cpp +++ b/src/colvar/EEFSolv.cpp @@ -117,8 +117,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(); @@ -135,7 +134,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); @@ -157,7 +157,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; @@ -198,7 +210,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) { @@ -231,8 +245,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; @@ -240,13 +253,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; @@ -254,13 +269,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); @@ -268,23 +285,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 5ce858b23c..a67c16db49 100644 --- a/src/colvar/ERMSD.cpp +++ b/src/colvar/ERMSD.cpp @@ -126,8 +126,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; @@ -145,11 +144,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(); @@ -159,8 +165,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,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()) ) + if( !pdb.read(reference,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()) ) { error("missing input file " + reference ); + } // store target_ distance std::vector reference_positions; unsigned natoms = atoms_.size(); @@ -173,7 +180,9 @@ ERMSD::ERMSD(const ActionOptions&ao): } // shift to count from zero - for(unsigned i=0; iresizeDerivatives(1); log<<" Bibliography "; log<resizeDerivatives(1); parse("NAME",name); log<<" name: "< atoms; parseAtomList("ATOMS",atoms); diff --git a/src/colvar/GHBFIX.cpp b/src/colvar/GHBFIX.cpp index a8fea5304f..6bcb6e19e8 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) { @@ -285,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) { @@ -295,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) { @@ -305,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) { @@ -316,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 @@ -326,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)); @@ -345,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 { @@ -356,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/MultiRMSD.cpp b/src/colvar/MultiRMSD.cpp index 24e94eb5e6..20141b25bd 100644 --- a/src/colvar/MultiRMSD.cpp +++ b/src/colvar/MultiRMSD.cpp @@ -150,8 +150,7 @@ void MultiRMSD::registerKeywords(Keywords& keys) { } MultiRMSD::MultiRMSD(const ActionOptions&ao): - PLUMED_COLVAR_INIT(ao),squared(false),myvals(1,0), mypack(0,0,myvals),nopbc(false) -{ + PLUMED_COLVAR_INIT(ao),squared(false),myvals(1,0), mypack(0,0,myvals),nopbc(false) { std::string reference; parse("REFERENCE",reference); std::string type; @@ -161,46 +160,64 @@ MultiRMSD::MultiRMSD(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,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()) ) + if( !pdb.read(reference,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()) ) { error("missing input file " + reference ); + } rmsd=metricRegister().create(type,pdb); // Do not align molecule if we are doing DRMSD for domains and NOPBC has been specified in input - if( pdb.hasFlag("NOPBC") ) nopbc=true; + if( pdb.hasFlag("NOPBC") ) { + nopbc=true; + } std::vector atoms; rmsd->getAtomRequests( atoms ); requestAtoms( atoms ); - myvals.resize( 1, 3*atoms.size()+9 ); mypack.resize( 0, atoms.size() ); - for(unsigned i=0; icalculate( getPositions(), getPbc(), mypack, squared ); setValue(r); - for(unsigned i=0; i(); 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; @@ -180,25 +198,42 @@ PCARMSD::PCARMSD(const ActionOptions&ao): do_read=mypdb.readFromFilepointer(fp,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.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; @@ -228,9 +265,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 @@ -256,7 +295,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 013874eabb..acc2b8ac6c 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,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.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)); for(unsigned j=0; j atoms; parseAtomList("ATOM",atoms); - if(atoms.size()!=1) + if(atoms.size()!=1) { error("Number of specified atoms should be 1"); + } parseFlag("SCALED_COMPONENTS",scaled_components); bool nopbc=!pbc; parseFlag("NOPBC",nopbc); @@ -112,17 +112,26 @@ Position::Position(const ActionOptions&ao): checkRead(); log.printf(" for atom %d\n",atoms[0].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"); + } if(scaled_components) { - addComponentWithDerivatives("a"); componentIsPeriodic("a","-0.5","+0.5"); - addComponentWithDerivatives("b"); componentIsPeriodic("b","-0.5","+0.5"); - addComponentWithDerivatives("c"); componentIsPeriodic("c","-0.5","+0.5"); + addComponentWithDerivatives("a"); + componentIsPeriodic("a","-0.5","+0.5"); + addComponentWithDerivatives("b"); + componentIsPeriodic("b","-0.5","+0.5"); + addComponentWithDerivatives("c"); + componentIsPeriodic("c","-0.5","+0.5"); } else { - addComponentWithDerivatives("x"); componentIsNotPeriodic("x"); - addComponentWithDerivatives("y"); componentIsNotPeriodic("y"); - addComponentWithDerivatives("z"); componentIsNotPeriodic("z"); + addComponentWithDerivatives("x"); + componentIsNotPeriodic("x"); + addComponentWithDerivatives("y"); + componentIsNotPeriodic("y"); + addComponentWithDerivatives("z"); + componentIsNotPeriodic("z"); log<<" WARNING: components will not have the proper periodicity - see manual\n"; } diff --git a/src/colvar/ProjectionOnAxis.cpp b/src/colvar/ProjectionOnAxis.cpp index 705d18c8a8..4c1083b0e0 100644 --- a/src/colvar/ProjectionOnAxis.cpp +++ b/src/colvar/ProjectionOnAxis.cpp @@ -88,26 +88,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); @@ -125,8 +133,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 @@ -143,19 +153,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 2c6bde5d7b..2a97bc83ac 100644 --- a/src/colvar/PropertyMap.cpp +++ b/src/colvar/PropertyMap.cpp @@ -105,8 +105,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(); @@ -121,18 +120,21 @@ PropertyMap::PropertyMap(const ActionOptions&ao): } else { for(unsigned i=0; i labelvals; for(unsigned j=0; j 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 5aa710a5d4..67af1f0870 100644 --- a/src/colvar/RMSD.cpp +++ b/src/colvar/RMSD.cpp @@ -173,8 +173,7 @@ RMSD::RMSD(const ActionOptions&ao): myvals(1,0), mypack(0,0,myvals), squared(false), - nopbc(false) -{ + nopbc(false) { std::string reference; parse("REFERENCE",reference); std::string type; @@ -186,12 +185,14 @@ RMSD::RMSD(const ActionOptions&ao): 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,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()) ) + if( !pdb.read(reference,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()) ) { error("missing input file " + reference ); + } rmsd=metricRegister().create(type,pdb); @@ -201,33 +202,48 @@ RMSD::RMSD(const ActionOptions&ao): requestAtoms( atoms ); // Setup the derivative pack - myvals.resize( 1, 3*atoms.size()+9 ); mypack.resize( 0, atoms.size() ); - for(unsigned i=0; icalculate( getPositions(), mypack, squared ); setValue(r); - for(unsigned i=0; i 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 955c5eb5ae..9a8062691a 100644 --- a/src/colvar/Torsion.cpp +++ b/src/colvar/Torsion.cpp @@ -111,8 +111,7 @@ void Torsion::registerKeywords(Keywords& keys) { Torsion::Torsion(const ActionOptions&ao): PLUMED_COLVAR_INIT(ao), pbc(true), - do_cosine(false) -{ + do_cosine(false) { std::vector atoms,v1,v2,axis; parseAtomList("ATOMS",atoms); parseAtomList("VECTOR1",v1); @@ -127,8 +126,9 @@ Torsion::Torsion(const ActionOptions&ao): checkRead(); if(atoms.size()==4) { - if(!(v1.empty() && v2.empty() && axis.empty())) + if(!(v1.empty() && v2.empty() && axis.empty())) { error("ATOMS keyword is not compatible with VECTOR1, VECTOR2 and AXIS keywords"); + } log.printf(" between atoms %d %d %d %d\n",atoms[0].serial(),atoms[1].serial(),atoms[2].serial(),atoms[3].serial()); atoms.resize(6); atoms[5]=atoms[3]; @@ -136,8 +136,9 @@ Torsion::Torsion(const ActionOptions&ao): atoms[3]=atoms[2]; atoms[2]=atoms[1]; } else if(atoms.empty()) { - if(!(v1.size()==2 && v2.size()==2 && axis.size()==2)) + if(!(v1.size()==2 && v2.size()==2 && axis.size()==2)) { error("VECTOR1, VECTOR2 and AXIS should specify 2 atoms each"); + } 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()); atoms.resize(6); @@ -147,16 +148,26 @@ Torsion::Torsion(const ActionOptions&ao): atoms[3]=axis[1]; atoms[4]=v2[0]; atoms[5]=v2[1]; - } else error("ATOMS should specify 4 atoms"); + } else { + error("ATOMS should specify 4 atoms"); + } - 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"); + } - if(do_cosine) log.printf(" calculating cosine instead of torsion\n"); + if(do_cosine) { + log.printf(" calculating cosine instead of torsion\n"); + } addValueWithDerivatives(); - if(!do_cosine) setPeriodic("-pi","pi"); - else setNotPeriodic(); + if(!do_cosine) { + setPeriodic("-pi","pi"); + } else { + setNotPeriodic(); + } requestAtoms(atoms); } @@ -164,7 +175,9 @@ Torsion::Torsion(const ActionOptions&ao): void Torsion::calculate() { Vector d0,d1,d2; - if(pbc) makeWhole(); + if(pbc) { + makeWhole(); + } d0=delta(getPosition(1),getPosition(0)); d1=delta(getPosition(3),getPosition(2)); d2=delta(getPosition(5),getPosition(4)); diff --git a/src/colvar/Volume.cpp b/src/colvar/Volume.cpp index 9da5e497ac..956d0db351 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 9c55128e68..725b142067 100644 --- a/src/config/Config.inc.in +++ b/src/config/Config.inc.in @@ -47,11 +47,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(); @@ -73,7 +83,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) { @@ -85,7 +97,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) { @@ -97,7 +111,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/core/Action.cpp b/src/core/Action.cpp index 7fca31e000..def24f097d 100644 --- a/src/core/Action.cpp +++ b/src/core/Action.cpp @@ -35,15 +35,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 ) { @@ -66,8 +64,7 @@ Action::Action(const ActionOptions&ao): log(plumed.getLog()), comm(plumed.comm), multi_sim_comm(plumed.multi_sim_comm), - keywords(ao.keys) -{ + keywords(ao.keys) { line.erase(line.begin()); log.printf("Action %s\n",name.c_str()); @@ -76,27 +73,45 @@ Action::Action(const ActionOptions&ao): } comm.Bcast(replica_index,0); - if ( keywords.exists("LABEL") ) { parse("LABEL",label); } + if ( keywords.exists("LABEL") ) { + parse("LABEL",label); + } if(label.length()==0) { - std::string s; Tools::convert(plumed.getActionSet().size(),s); + std::string s; + Tools::convert(plumed.getActionSet().size(),s); label="@"+s; } - if( plumed.getActionSet().selectWithLabel(label) ) error("label " + label + " has been already used"); + if( plumed.getActionSet().selectWithLabel(label) ) { + error("label " + label + " has been already used"); + } log.printf(" with label %s\n",label.c_str()); - if ( keywords.exists("UPDATE_FROM") ) parse("UPDATE_FROM",update_from); - if(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(update_until!=std::numeric_limits::max()) log.printf(" only update until time %f\n",update_until); + if ( keywords.exists("UPDATE_FROM") ) { + parse("UPDATE_FROM",update_from); + } + if(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(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"); + } } } @@ -108,10 +123,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; } @@ -132,11 +153,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"); @@ -177,15 +202,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() { @@ -202,7 +233,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); @@ -248,7 +281,10 @@ void Action::calculateFromPDB( const PDB& pdb ) { activate(); for(const auto & p : after) { ActionWithValue*av=dynamic_cast(p); - if(av) { av->clearInputForces(); av->clearDerivatives(); } + if(av) { + av->clearInputForces(); + av->clearDerivatives(); + } p->readAtomsFromPDB( pdb ); p->calculate(); } @@ -267,8 +303,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 { diff --git a/src/core/Action.h b/src/core/Action.h index ffbf75cb77..94ec925f5a 100644 --- a/src/core/Action.h +++ b/src/core/Action.h @@ -254,13 +254,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 @@ -314,7 +320,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")) ) { @@ -333,10 +341,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); } @@ -344,20 +355,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 @@ -367,9 +386,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 9b409bfea5..ad3bb9f232 100644 --- a/src/core/ActionAtomistic.cpp +++ b/src/core/ActionAtomistic.cpp @@ -45,8 +45,7 @@ ActionAtomistic::ActionAtomistic(const ActionOptions&ao): lockRequestAtoms(false), donotretrieve(false), donotforce(false), - atoms(plumed.getAtoms()) -{ + atoms(plumed.getAtoms()) { atoms.add(this); // if(atoms.getNatoms()==0) error("Cannot perform calculations involving atoms without atoms"); } @@ -65,13 +64,23 @@ void ActionAtomistic::requestAtoms(const std::vector & a, const bool masses.resize(nat); charges.resize(nat); int n=atoms.positions.size(); - if(clearDep) clearDependencies(); + if(clearDep) { + clearDependencies(); + } unique.clear(); for(unsigned i=0; i=n) { std::string num; Tools::convert( indexes[i].serial(),num ); error("atom " + num + " out of range"); } - if(atoms.isVirtualAtom(indexes[i])) addDependency(atoms.getVirtualAtomsAction(indexes[i])); + if(indexes[i].index()>=n) { + std::string num; + Tools::convert( indexes[i].serial(),num ); + error("atom " + num + " out of range"); + } + if(atoms.isVirtualAtom(indexes[i])) { + addDependency(atoms.getVirtualAtomsAction(indexes[i])); + } // only real atoms are requested to lower level Atoms class - else unique.push_back(indexes[i]); + else { + unique.push_back(indexes[i]); + } } Tools::removeDuplicates(unique); updateUniqueLocal(); @@ -107,7 +116,8 @@ void ActionAtomistic::calculateAtomicNumericalDerivatives( ActionWithValue* a, c std::vector savedPositions(natoms); const double delta=std::sqrt(epsilon); - for(int i=0; icalculate(); @@ -117,17 +127,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(); @@ -136,15 +155,22 @@ 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)); + } } } } @@ -158,38 +184,54 @@ 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; + } } interpretAtomList( strings, t ); } void ActionAtomistic::interpretAtomList(std::vector& strings, std::vector &t) { - Tools::interpretRanges(strings); t.resize(0); + Tools::interpretRanges(strings); + t.resize(0); for(unsigned i=0; i(this); 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 { 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 { + error(strings[i] + " is not a label plumed knows"); + } } else { error("atoms specified using @ symbol but no MOLINFO was available"); } @@ -208,14 +250,17 @@ void ActionAtomistic::interpretAtomList(std::vector& strings, std:: const ActionSet&actionSet(plumed.getActionSet()); for(const auto & a : actionSet) { ActionWithVirtualAtom* c=dynamic_cast(a.get()); - if(c) if(c->getLabel()==strings[i]) { + if(c) + if(c->getLabel()==strings[i]) { ok=true; t.push_back(c->getIndex()); break; } } } - if(!ok) error("it was not possible to interpret atom name " + strings[i]); + if(!ok) { + error("it was not possible to interpret atom name " + strings[i]); + } // plumed_massert(ok,"it was not possible to interpret atom name " + strings[i]); } } @@ -223,49 +268,80 @@ void ActionAtomistic::interpretAtomList(std::vector& strings, std:: void ActionAtomistic::retrieveAtoms() { pbc=atoms.pbc; Colvar*cc=dynamic_cast(this); - if(cc && cc->checkIsEnergy()) energy=atoms.getEnergy(); - if(donotretrieve) return; + if(cc && cc->checkIsEnergy()) { + energy=atoms.getEnergy(); + } + if(donotretrieve) { + return; + } chargesWereSet=atoms.chargesWereSet(); const std::vector & p(atoms.positions); const std::vector & c(atoms.charges); const std::vector & m(atoms.masses); - for(unsigned j=0; j& forcesToApply, unsigned ind) { - if(donotforce) return; + if(donotforce) { + return; + } for(unsigned i=0; i& f(atoms.forces); Tensor& v(atoms.virial); - for(unsigned j=0; j0) atoms.updateExtraCVForce(extraCV,forceOnExtraCV); + if(extraCV.length()>0) { + atoms.updateExtraCVForce(extraCV,forceOnExtraCV); + } } void ActionAtomistic::clearOutputForces() { virial.zero(); - if(donotforce) return; + if(donotforce) { + return; + } Tools::set_to_zero(forces); forceOnEnergy=0.0; forceOnExtraCV=0.0; @@ -274,15 +350,25 @@ void ActionAtomistic::clearOutputForces() { void ActionAtomistic::readAtomsFromPDB(const PDB& pdb) { Colvar*cc=dynamic_cast(this); - if(cc && cc->checkIsEnergy()) error("can't read energies from pdb files"); + if(cc && cc->checkIsEnergy()) { + error("can't read energies from pdb files"); + } 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; j0) { unique_local.clear(); for(auto pp=unique.begin(); pp!=unique.end(); ++pp) { - if(atoms.g2l[pp->index()]>=0) unique_local.push_back(*pp); // already sorted + if(atoms.g2l[pp->index()]>=0) { + unique_local.push_back(*pp); // already sorted + } } } else { unique_local=unique; // copy diff --git a/src/core/ActionAtomistic.h b/src/core/ActionAtomistic.h index 714fe911c7..b83eab468a 100644 --- a/src/core/ActionAtomistic.h +++ b/src/core/ActionAtomistic.h @@ -38,8 +38,7 @@ class PDB; /// \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 { std::vector indexes; // the set of needed atoms /// unique should be an ordered set since we later create a vector containing the corresponding indexes @@ -127,7 +126,9 @@ class ActionAtomistic : /// Get a reference to force on extraCV double & modifyForceOnExtraCV(); /// 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 @@ -153,15 +154,21 @@ 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(); /// Allow calls to modifyGlobalForce() - void allowToAccessGlobalForces() {atoms.zeroallforces=true;} + void allowToAccessGlobalForces() { + atoms.zeroallforces=true; + } /// updates local unique atoms void updateUniqueLocal(); public: @@ -225,7 +232,9 @@ double ActionAtomistic::getMass(int i)const { 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/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 0eb01fdbf1..62ace3d17f 100644 --- a/src/core/ActionRegister.cpp +++ b/src/core/ActionRegister.cpp @@ -30,7 +30,9 @@ namespace PLMD { ActionRegister::~ActionRegister() { 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"; } } @@ -43,14 +45,18 @@ ActionRegister& actionRegister() { void ActionRegister::remove(creator_pointer f) { for(auto p=m.begin(); p!=m.end(); ++p) { if((*p).second==f) { - m.erase(p); break; + m.erase(p); + break; } } } void ActionRegister::add(std::string key,creator_pointer f,keywords_pointer k) { // 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"; if(m.count(key)) { m.erase(key); disabled.insert(key); @@ -64,12 +70,16 @@ void ActionRegister::add(std::string key,creator_pointer f,keywords_pointer k) { } bool ActionRegister::check(const std::string & key) { - if(m.count(key)>0 && mk.count(key)>0) return true; + if(m.count(key)>0 && mk.count(key)>0) { + return true; + } return false; } std::unique_ptr ActionRegister::create(const ActionOptions&ao) { - if(ao.line.size()<1)return NULL; + if(ao.line.size()<1) { + return NULL; + } // Create a copy of the manual locally. The manual is // then added to the ActionOptions. This allows us to // ensure during construction that all the keywords for @@ -78,7 +88,8 @@ std::unique_ptr ActionRegister::create(const ActionOptions&ao) { // in the input. std::unique_ptr action; if( check(ao.line[0]) ) { - Keywords keys; mk[ao.line[0]](keys); + Keywords keys; + mk[ao.line[0]](keys); ActionOptions nao( ao,keys ); action=m[ao.line[0]](nao); } @@ -86,15 +97,21 @@ std::unique_ptr ActionRegister::create(const ActionOptions&ao) { } bool ActionRegister::getKeywords(const std::string& action, Keywords& keys) { - if ( check(action) ) { mk[action](keys); return true; } + if ( check(action) ) { + mk[action](keys); + return true; + } return false; } 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 { @@ -108,7 +125,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; mk[action](keys); + Keywords keys; + mk[action](keys); keys.print_template(action, include_optional); return true; } else { @@ -118,21 +136,27 @@ bool ActionRegister::printTemplate(const std::string& action, bool include_optio std::vector ActionRegister::getActionNames() const { 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; } std::ostream & operator<<(std::ostream &log,const ActionRegister&ar) { std::vector s(ar.getActionNames()); - for(unsigned i=0; 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(); } diff --git a/src/core/ActionSet.h b/src/core/ActionSet.h index a6193fd100..0954fb4806 100644 --- a/src/core/ActionSet.h +++ b/src/core/ActionSet.h @@ -37,8 +37,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); @@ -85,7 +84,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; } @@ -94,7 +95,9 @@ template T ActionSet::selectWithLabel(const std::string&s)const { for(const auto & p : (*this)) { T t=dynamic_cast(p.get()); - if(t && dynamic_cast(t)->getLabel()==s) return t; + if(t && dynamic_cast(t)->getLabel()==s) { + return t; + } }; return NULL; } @@ -104,7 +107,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; } @@ -113,7 +118,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; } @@ -123,7 +130,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; } @@ -132,9 +141,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 eef278fc1f..dc5ddde1f6 100644 --- a/src/core/ActionSetup.cpp +++ b/src/core/ActionSetup.cpp @@ -28,12 +28,13 @@ 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 - if( !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."); + if( !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."); + } } } diff --git a/src/core/ActionShortcut.cpp b/src/core/ActionShortcut.cpp index da873f5c55..a35aa648f6 100644 --- a/src/core/ActionShortcut.cpp +++ b/src/core/ActionShortcut.cpp @@ -32,26 +32,38 @@ void ActionShortcut::registerKeywords( Keywords& keys ) { 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()+1,t); + std::string t; + Tools::convert(plumed.getActionSet().size()+1,t); shortcutlabel="@" + t; - } else label = ("@" + s); + } else { + label = ("@" + s); + } } void ActionShortcut::readInputLine( const std::string& input ) { - std::string f_input = input; savedInputLines.push_back( input ); + std::string f_input = input; + savedInputLines.push_back( 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; } if( keywords.exists("RESTART") ) { - if( restart ) f_input += " RESTART=YES"; - if( !restart ) f_input += " RESTART=NO"; + if( restart ) { + f_input += " RESTART=YES"; + } + if( !restart ) { + f_input += " RESTART=NO"; + } } plumed.readInputLine( f_input ); } diff --git a/src/core/ActionWithArguments.cpp b/src/core/ActionWithArguments.cpp index 56e1acc345..6f1e9b4deb 100644 --- a/src/core/ActionWithArguments.cpp +++ b/src/core/ActionWithArguments.cpp @@ -46,10 +46,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,arg); } @@ -60,7 +66,9 @@ bool ActionWithArguments::parseArgumentList(const std::string&key,int i,std::vec if(parseNumberedVector(key,i,c)) { interpretArgumentList(c,arg); return true; - } else return false; + } else { + return false; + } } void ActionWithArguments::interpretArgumentList(const std::vector& c, std::vector&arg) { @@ -87,14 +95,18 @@ void ActionWithArguments::interpretArgumentList(const std::vector& } // call regfree when reg goes out of scope - auto deleter=[](regex_t* r) { regfree(r); }; + auto deleter=[](regex_t* r) { + regfree(r); + }; std::unique_ptr reg_deleter(®,deleter); plumed_massert(reg.re_nsub==1,"I can parse with only one subexpression"); regmatch_t match; // select all the actions that have a value std::vector all=plumed.getActionSet().select(); - if( all.empty() ) error("your input file is not telling plumed to calculate anything"); + if( all.empty() ) { + error("your input file is not telling plumed to calculate anything"); + } bool found_something=false; for(unsigned j=0; j ss=all[j]->getComponentsVector(); @@ -125,7 +137,9 @@ void ActionWithArguments::interpretArgumentList(const std::vector& } } } - if(!found_something) plumed_error()<<"There isn't any action matching your regex " << myregex; + if(!found_something) { + plumed_error()<<"There isn't any action matching your regex " << myregex; + } #else plumed_merror("Regexp support not compiled!"); #endif @@ -140,9 +154,13 @@ void ActionWithArguments::interpretArgumentList(const std::vector& if(a=="*" && name=="*") { // Take all values from all actions std::vector all=plumed.getActionSet().select(); - if( all.empty() ) error("your input file is not telling plumed to calculate anything"); + if( all.empty() ) { + error("your input file is not telling plumed to calculate anything"); + } for(unsigned j=0; jgetNumberOfComponents(); ++k) arg.push_back(all[j]->copyOutput(k)); + for(int k=0; kgetNumberOfComponents(); ++k) { + arg.push_back(all[j]->copyOutput(k)); + } } } else if ( name=="*") { // Take all the values from an action with a specific name @@ -152,18 +170,30 @@ void ActionWithArguments::interpretArgumentList(const std::vector& str+=plumed.getActionSet().getLabelList()+")"; error("cannot find action named " + a + str); } - if( action->getNumberOfComponents()==0 ) 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 ) { + 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=="*" ) { // Take components from all actions with a specific name std::vector all=plumed.getActionSet().select(); - if( all.empty() ) error("your input file is not telling plumed to calculate anything"); + if( all.empty() ) { + error("your input file is not telling plumed to calculate anything"); + } 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) { + error("found no actions with a component called " + name ); } - if(nval==0) error("found no actions with a component called " + name ); } else { // Take values with a specific name ActionWithValue* action=plumed.getActionSet().selectWithLabel(a); @@ -183,9 +213,13 @@ void ActionWithArguments::interpretArgumentList(const std::vector& if(c[i]=="*") { // Take all values from all actions std::vector all=plumed.getActionSet().select(); - if( all.empty() ) error("your input file is not telling plumed to calculate anything"); + if( all.empty() ) { + error("your input file is not telling plumed to calculate anything"); + } for(unsigned j=0; jgetNumberOfComponents(); ++k) arg.push_back(all[j]->copyOutput(k)); + for(int k=0; kgetNumberOfComponents(); ++k) { + arg.push_back(all[j]->copyOutput(k)); + } } } else { ActionWithValue* action=plumed.getActionSet().selectWithLabel(c[i]); @@ -254,15 +288,16 @@ 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); if(!arg.empty()) { log.printf(" with arguments"); - for(unsigned i=0; igetName().c_str()); + for(unsigned i=0; igetName().c_str()); + } log.printf("\n"); } requestArguments(arg); @@ -291,7 +326,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)); + } } } @@ -304,7 +342,9 @@ double ActionWithArguments::getProjection(unsigned i,unsigned j)const { } void ActionWithArguments::addForcesOnArguments( const std::vector& forces ) { - for(unsigned i=0; iaddForce( forces[i] ); + for(unsigned i=0; iaddForce( forces[i] ); + } } } diff --git a/src/core/ActionWithArguments.h b/src/core/ActionWithArguments.h index 4ed915f3a7..9cc7da7f8f 100644 --- a/src/core/ActionWithArguments.h +++ b/src/core/ActionWithArguments.h @@ -40,8 +40,7 @@ This is used in PLMD::Function and PLMD::Bias */ class ActionWithArguments: - public virtual Action -{ + public virtual Action { std::vector arguments; bool lockRequestArguments; protected: diff --git a/src/core/ActionWithValue.cpp b/src/core/ActionWithValue.cpp index e29fe0928e..a6e3243fa3 100644 --- a/src/core/ActionWithValue.cpp +++ b/src/core/ActionWithValue.cpp @@ -55,10 +55,13 @@ void ActionWithValue::useCustomisableComponents(Keywords& keys) { ActionWithValue::ActionWithValue(const ActionOptions&ao): Action(ao), noderiv(true), - numericalDerivatives(false) -{ - if( keywords.exists("NUMERICAL_DERIVATIVES") ) parseFlag("NUMERICAL_DERIVATIVES",numericalDerivatives); - if(numericalDerivatives) log.printf(" using numerical derivatives\n"); + numericalDerivatives(false) { + if( keywords.exists("NUMERICAL_DERIVATIVES") ) { + parseFlag("NUMERICAL_DERIVATIVES",numericalDerivatives); + } + if(numericalDerivatives) { + log.printf(" using numerical derivatives\n"); + } } ActionWithValue::~ActionWithValue() { @@ -66,7 +69,9 @@ ActionWithValue::~ActionWithValue() { } void ActionWithValue::clearInputForces() { - for(unsigned i=0; iclearInputForce(); + for(unsigned i=0; iclearInputForce(); + } } void ActionWithValue::clearDerivatives() { @@ -74,7 +79,9 @@ void ActionWithValue::clearDerivatives() { #pragma omp parallel num_threads(nt) { #pragma omp for - for(unsigned i=0; iclearDerivatives(); + for(unsigned i=0; iclearDerivatives(); + } } } @@ -82,14 +89,18 @@ void ActionWithValue::clearDerivatives() { 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; } Value* ActionWithValue::copyOutput( const std::string& name ) const { for(unsigned i=0; iname==name) return values[i].get(); + if (values[i]->name==name) { + return values[i].get(); + } } plumed_merror("there is no pointer with name " + name); } @@ -114,7 +125,8 @@ void ActionWithValue::addValueWithDerivatives() { 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(); } @@ -137,7 +149,8 @@ void ActionWithValue::addComponent( const std::string& name ) { 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 docs."); } - 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); @@ -154,7 +167,8 @@ void ActionWithValue::addComponentWithDerivatives( const std::string& name ) { 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); @@ -168,9 +182,12 @@ void ActionWithValue::addComponentWithDerivatives( const std::string& name ) { 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); } @@ -193,7 +210,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(); } @@ -204,7 +222,9 @@ void ActionWithValue::componentIsPeriodic( const std::string& name, const std::s void ActionWithValue::setGradientsIfNeeded() { if(isOptionOn("GRADIENTS")) { - for(unsigned i=0; isetGradients(); + for(unsigned i=0; isetGradients(); + } } } @@ -212,11 +232,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; i( getDependencies()[i] ); - if(vv) vv->turnOnDerivatives(); + if(vv) { + vv->turnOnDerivatives(); + } } } diff --git a/src/core/ActionWithValue.h b/src/core/ActionWithValue.h index 7474f86704..2115a30ffb 100644 --- a/src/core/ActionWithValue.h +++ b/src/core/ActionWithValue.h @@ -64,8 +64,7 @@ PLMD::Action you should use the routines with the word component in the name */ class ActionWithValue : - public virtual Action -{ + public virtual Action { private: /// An array containing the values for this action std::vector> values; @@ -164,7 +163,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(); @@ -178,9 +179,12 @@ double ActionWithValue::getOutputQuantity(const unsigned j) const { inline double ActionWithValue::getOutputQuantity( const std::string& name ) const { - std::string thename; thename=getLabel() + "." + name; + std::string thename; + thename=getLabel() + "." + name; for(unsigned i=0; iname==thename ) return values[i]->value; + if( values[i]->name==thename ) { + return values[i]->value; + } } return 0.0; } diff --git a/src/core/ActionWithVirtualAtom.cpp b/src/core/ActionWithVirtualAtom.cpp index 72d56dd110..8a8536e8d7 100644 --- a/src/core/ActionWithVirtualAtom.cpp +++ b/src/core/ActionWithVirtualAtom.cpp @@ -33,8 +33,7 @@ void ActionWithVirtualAtom::registerKeywords(Keywords& keys) { ActionWithVirtualAtom::ActionWithVirtualAtom(const ActionOptions&ao): Action(ao), ActionAtomistic(ao), - index(atoms.addVirtualAtom(this)) -{ + index(atoms.addVirtualAtom(this)) { log<<" serial associated to this virtual atom is "< &d) { // Notice that this part alone should exactly cancel the already accumulated virial // due to forces on this atom. Vector pos=atoms.positions[index.index()]; - for(unsigned i=0; i<3; i++) for(unsigned j=0; j<3; j++) boxDerivatives[j][i][j]+=pos[i]; + for(unsigned i=0; i<3; i++) + for(unsigned j=0; j<3; j++) { + boxDerivatives[j][i][j]+=pos[i]; + } } void ActionWithVirtualAtom::setBoxDerivativesNoPbc() { std::array bd; - 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 aebbed5866..e79cba9d45 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 /// Class to add a single virtual atom to the system. /// (it might be extended to add multiple virtual atoms). class ActionWithVirtualAtom: - public ActionAtomistic -{ + public ActionAtomistic { const AtomNumber index; std::vector derivatives; std::array boxDerivatives; diff --git a/src/core/Atoms.cpp b/src/core/Atoms.cpp index a7f006b464..369bb0da15 100644 --- a/src/core/Atoms.cpp +++ b/src/core/Atoms.cpp @@ -86,8 +86,7 @@ Atoms::Atoms(PlumedMain&plumed): kbT(0.0), asyncSent(false), atomsNeeded(false), - ddStep(0) -{ + ddStep(0) { } Atoms::~Atoms() { @@ -97,39 +96,51 @@ Atoms::~Atoms() { } void Atoms::startStep() { - collectEnergy=false; energyHasBeenSet=false; positionsHaveBeenSet=0; - massesHaveBeenSet=false; chargesHaveBeenSet=false; boxHasBeenSet=false; - forcesHaveBeenSet=0; virialHasBeenSet=false; dataCanBeSet=true; + collectEnergy=false; + energyHasBeenSet=false; + positionsHaveBeenSet=0; + massesHaveBeenSet=false; + chargesHaveBeenSet=false; + boxHasBeenSet=false; + forcesHaveBeenSet=0; + virialHasBeenSet=false; + dataCanBeSet=true; resetExtraCVNeeded(); } void Atoms::setBox(const TypesafePtr & p) { mdatoms->setBox(p); - Tensor b; mdatoms->getBox(b); boxHasBeenSet=true; + Tensor b; + mdatoms->getBox(b); + boxHasBeenSet=true; } void Atoms::setPositions(const TypesafePtr & p) { plumed_massert( dataCanBeSet,"setPositions must be called after setStep in MD code interface"); plumed_massert( p || gatindex.size()==0, "NULL position pointer with non-zero local atoms"); - mdatoms->setp(p); positionsHaveBeenSet=3; + mdatoms->setp(p); + positionsHaveBeenSet=3; } void Atoms::setMasses(const TypesafePtr & p) { plumed_massert( dataCanBeSet,"setMasses must be called after setStep in MD code interface"); plumed_massert( p || gatindex.size()==0, "NULL mass pointer with non-zero local atoms"); - mdatoms->setm(p); massesHaveBeenSet=true; + mdatoms->setm(p); + massesHaveBeenSet=true; } void Atoms::setCharges(const TypesafePtr & p) { plumed_massert( dataCanBeSet, "setCharges must be called after setStep in MD code interface"); plumed_massert( p || gatindex.size()==0, "NULL charges pointer with non-zero local atoms"); - mdatoms->setc(p); chargesHaveBeenSet=true; + mdatoms->setc(p); + chargesHaveBeenSet=true; } void Atoms::setVirial(const TypesafePtr & p) { plumed_massert( dataCanBeSet,"setVirial must be called after setStep in MD code interface"); - mdatoms->setVirial(p); virialHasBeenSet=true; + mdatoms->setVirial(p); + virialHasBeenSet=true; } void Atoms::setEnergy(const TypesafePtr & p) { @@ -149,13 +160,15 @@ void Atoms::setForces(const TypesafePtr & p) { void Atoms::setPositions(const TypesafePtr & p,int i) { plumed_massert( dataCanBeSet,"setPositions must be called after setStep in MD code interface"); plumed_massert( p || gatindex.size()==0, "NULL positions pointer with non-zero local atoms"); - mdatoms->setp(p,i); positionsHaveBeenSet++; + mdatoms->setp(p,i); + positionsHaveBeenSet++; } void Atoms::setForces(const TypesafePtr & p,int i) { plumed_massert( dataCanBeSet,"setForces must be called after setStep in MD code interface"); plumed_massert( p || gatindex.size()==0, "NULL force pointer with non-zero local atoms"); - mdatoms->setf(p,i); forcesHaveBeenSet++; + mdatoms->setf(p,i); + forcesHaveBeenSet++; } void Atoms::share() { @@ -172,11 +185,16 @@ void Atoms::share() { for(unsigned i=0; iisActive()) { auto l=actions[i]->getUnique().size(); - if(l>largest) largest=l; + if(l>largest) { + largest=l; + } } } - if(largest*20) { - for(int i=0; i=0) unique.push_back(AtomNumber::index(i)); // already sorted + for(int i=0; i=0) { + unique.push_back(AtomNumber::index(i)); // already sorted + } } else { unique.resize(natoms); - for(int i=0; i& unique) { if(zeroallforces || (int(gatindex.size())==natoms && !unique_serial)) { Tools::set_to_zero(forces); } else { - for(const auto & p : unique) forces[p.index()].zero(); - for(unsigned i=getNatoms(); igetBox(box); - if(!atomsNeeded) return; + if(!atomsNeeded) { + return; + } atomsNeeded=false; if(!(int(gatindex.size())==natoms && shuffledAtoms==0)) { uniq_index.resize(unique.size()); - for(unsigned i=0; igetPositions(unique,uniq_index,positions); } else if(unique_serial) { uniq_index.resize(unique.size()); - for(unsigned i=0; igetPositions(unique,uniq_index,positions); } else { // faster version, which retrieves all atoms @@ -268,8 +303,12 @@ void Atoms::share(const std::vector& unique) { if(dd && shuffledAtoms>0) { if(dd.async) { - for(unsigned i=0; i& unique) { std::vector displ5(n); dd.Allgather(count,counts); displ[0]=0; - for(int i=1; i0) { // receive toBeReceived @@ -353,11 +402,15 @@ void Atoms::wait() { } asyncSent=false; } - if(collectEnergy) dd.Sum(energy); + if(collectEnergy) { + dd.Sum(energy); + } } // I take note that masses and charges have been set once for all // at the beginning of the simulation. - if(shareMassAndChargeOnlyAtFirstStep) massAndChargeOK=true; + if(shareMassAndChargeOnlyAtFirstStep) { + massAndChargeOK=true; + } } void Atoms::updateForces() { @@ -367,8 +420,11 @@ void Atoms::updateForces() { mdatoms->rescaleForces(gatindex,alpha); mdatoms->updateForces(gatindex,forces); } else { - if(!unique_serial && int(gatindex.size())==natoms && shuffledAtoms==0) mdatoms->updateForces(gatindex,forces); - else mdatoms->updateForces(unique,uniq_index,forces); + if(!unique_serial && int(gatindex.size())==natoms && shuffledAtoms==0) { + mdatoms->updateForces(gatindex,forces); + } else { + mdatoms->updateForces(unique,uniq_index,forces); + } } if( !plumed.novirial && dd.Get_rank()==0 ) { plumed_assert( virialHasBeenSet ); @@ -383,7 +439,9 @@ void Atoms::setNatoms(int n) { masses.resize(n); charges.resize(n); gatindex.resize(n); - for(unsigned i=0; i(gatindex.size()); ddStep=plumed.getStep(); if(fortran) { - for(unsigned i=0; iupdateUniqueLocal(); @@ -478,10 +561,12 @@ int Atoms::getRealPrecision()const { } void Atoms::MD2double(const TypesafePtr & m,double&d)const { - plumed_assert(mdatoms); mdatoms->MD2double(m,d); + plumed_assert(mdatoms); + mdatoms->MD2double(m,d); } void Atoms::double2MD(const double&d,const TypesafePtr & m)const { - plumed_assert(mdatoms); mdatoms->double2MD(d,m); + plumed_assert(mdatoms); + mdatoms->double2MD(d,m); } void Atoms::updateUnits() { @@ -516,7 +601,9 @@ void Atoms::createFullList(const TypesafePtr & n) { if(!massAndChargeOK && shareMassAndChargeOnlyAtFirstStep) { 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 Atoms::clearFullList() { @@ -609,18 +701,26 @@ void Atoms::readBinary(std::istream&i) { } double Atoms::getKBoltzmann()const { - if(naturalUnits || MDnaturalUnits) return 1.0; - else return kBoltzmann/units.getEnergy(); + if(naturalUnits || MDnaturalUnits) { + return 1.0; + } else { + return kBoltzmann/units.getEnergy(); + } } double Atoms::getMDKBoltzmann()const { - if(naturalUnits || MDnaturalUnits) return 1.0; - else return kBoltzmann/MDUnits.getEnergy(); + if(naturalUnits || MDnaturalUnits) { + return 1.0; + } else { + return kBoltzmann/MDUnits.getEnergy(); + } } void Atoms::getLocalMasses(std::vector& localMasses) { localMasses.resize(gatindex.size()); - for(unsigned i=0; i& localPositions) { @@ -630,7 +730,9 @@ void Atoms::getLocalPositions(std::vector& localPositions) { void Atoms::getLocalForces(std::vector& localForces) { localForces.resize(gatindex.size()); - for(unsigned i=0; i& localForces) { diff --git a/src/core/Atoms.h b/src/core/Atoms.h index d1b2796167..b83fc5b1a2 100644 --- a/src/core/Atoms.h +++ b/src/core/Atoms.h @@ -44,8 +44,7 @@ class Pbc; /// Class containing atom related quantities from the MD code. /// IT IS STILL UNDOCUMENTED. IT PROBABLY NEEDS A STRONG CLEANUP -class Atoms -{ +class Atoms { friend class ActionAtomistic; friend class ActionWithVirtualAtom; int natoms; @@ -117,8 +116,7 @@ class Atoms bool atomsNeeded; class DomainDecomposition: - public Communicator - { + public Communicator { public: bool on; bool async; @@ -130,7 +128,9 @@ class Atoms std::vector positionsToBeReceived; std::vector indexToBeSent; std::vector indexToBeReceived; - operator bool() const {return on;} + operator bool() const { + return on; + } DomainDecomposition(): on(false), async(false) {} @@ -176,7 +176,9 @@ class Atoms void getLocalMDForces(std::vector&); const Tensor& getVirial()const; - void setCollectEnergy(bool b) { collectEnergy=b; } + void setCollectEnergy(bool b) { + collectEnergy=b; + } void setDomainDecomposition(Communicator&); void setAtomsGatindex(const TypesafePtr &,bool); @@ -206,18 +208,39 @@ class Atoms void add(ActionAtomistic*); void remove(ActionAtomistic*); - double getEnergy()const {plumed_assert(collectEnergy && energyHasBeenSet); return energy;} - - bool isEnergyNeeded()const {return collectEnergy;} - - void setMDEnergyUnits(double d) {MDUnits.setEnergy(d);} - void setMDLengthUnits(double d) {MDUnits.setLength(d);} - void setMDTimeUnits(double d) {MDUnits.setTime(d);} - void setMDChargeUnits(double d) {MDUnits.setCharge(d);} - void setMDMassUnits(double d) {MDUnits.setMass(d);} - const Units& getMDUnits() {return MDUnits;} - void setUnits(const Units&u) {units=u;} - const Units& getUnits() {return units;} + double getEnergy()const { + plumed_assert(collectEnergy && energyHasBeenSet); + return energy; + } + + bool isEnergyNeeded()const { + return collectEnergy; + } + + void setMDEnergyUnits(double d) { + MDUnits.setEnergy(d); + } + void setMDLengthUnits(double d) { + MDUnits.setLength(d); + } + void setMDTimeUnits(double d) { + MDUnits.setTime(d); + } + void setMDChargeUnits(double d) { + MDUnits.setCharge(d); + } + void setMDMassUnits(double d) { + MDUnits.setMass(d); + } + const Units& getMDUnits() { + return MDUnits; + } + void setUnits(const Units&u) { + units=u; + } + const Units& getUnits() { + return units; + } void updateUnits(); AtomNumber addVirtualAtom(ActionWithVirtualAtom*); @@ -231,8 +254,12 @@ class Atoms double getKBoltzmann()const; double getMDKBoltzmann()const; bool usingNaturalUnits()const; - void setNaturalUnits(bool n) {naturalUnits=n;} - void setMDNaturalUnits(bool n) {MDnaturalUnits=n;} + void setNaturalUnits(bool n) { + naturalUnits=n; + } + void setMDNaturalUnits(bool n) { + MDnaturalUnits=n; + } void setExtraCV(const std::string &name,const TypesafePtr & p); void setExtraCVForce(const std::string &name,const TypesafePtr & p); diff --git a/src/core/CLTool.cpp b/src/core/CLTool.cpp index c04b7a6cfe..81ffee0640 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); @@ -80,7 +81,9 @@ void CLToolMain::cmd(const std::string& 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) { @@ -243,7 +264,9 @@ int CLToolMain::run(int argc, char **argv,FILE*in,FILE*out,Communicator& pc) { std::string cmd=config::getEnvCommand()+" \""+root+"/scripts/"+availableShell[j]+".sh\" --description"; FILE *fp=popen(cmd.c_str(),"r"); std::string line; - while(Tools::getline(fp,line))manual+=line; + while(Tools::getline(fp,line)) { + manual+=line; + } pclose(fp); #else manual="(doc not avail)"; @@ -265,7 +288,9 @@ int CLToolMain::run(int argc, char **argv,FILE*in,FILE*out,Communicator& pc) { auto cl=cltoolRegister().create(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; } @@ -274,13 +299,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; j0) { std::string names=""; - for(const auto & p : m) names+=p.first+" "; + for(const auto & p : m) { + names+=p.first+" "; + } std::cerr<<"WARNING: CLTools "+ names +" has not been properly unregistered. This might lead to memory leak!!\n"; } } @@ -44,7 +46,8 @@ CLToolRegister& cltoolRegister() { void CLToolRegister::remove(creator_pointer f) { for(auto p=m.begin(); p!=m.end(); ++p) { if((*p).second==f) { - m.erase(p); break; + m.erase(p); + break; } } } @@ -55,18 +58,23 @@ void CLToolRegister::add(std::string key,creator_pointer f,keywords_pointer kf) disabled.insert(key); } else { m.insert(std::pair(key,f)); - Keywords keys; kf(keys); + Keywords keys; + kf(keys); mk.insert(std::pair(key,keys)); }; } bool CLToolRegister::check(const std::string & key)const { - if(m.count(key)>0) return true; + if(m.count(key)>0) { + return true; + } return false; } std::unique_ptr CLToolRegister::create(const CLToolOptions&ao) { - if(ao.line.size()<1)return NULL; + if(ao.line.size()<1) { + return NULL; + } std::unique_ptr cltool; if(check(ao.line[0])) { CLToolOptions nao( ao,mk[ao.line[0]] ); @@ -78,14 +86,18 @@ std::unique_ptr CLToolRegister::create(const CLToolOptions&ao) { std::ostream & operator<<(std::ostream &log,const CLToolRegister&ar) { std::vector s(ar.list()); - for(unsigned i=0; i CLToolRegister::getKeys(const std::string& cltool)const std::vector CLToolRegister::list()const { 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; } diff --git a/src/core/Colvar.cpp b/src/core/Colvar.cpp index 8744a42848..5d6f725112 100644 --- a/src/core/Colvar.cpp +++ b/src/core/Colvar.cpp @@ -31,8 +31,7 @@ Colvar::Colvar(const ActionOptions&ao): ActionAtomistic(ao), ActionWithValue(ao), isEnergy(false), - isExtraCV(false) -{ + isExtraCV(false) { } void Colvar::registerKeywords( Keywords& keys ) { @@ -47,7 +46,9 @@ 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() { @@ -65,7 +66,9 @@ void Colvar::apply() { } unsigned nt=OpenMP::getNumThreads(); - if(nt>ncp/(4*stride)) nt=1; + if(nt>ncp/(4*stride)) { + nt=1; + } if(!isEnergy && !isExtraCV) { #pragma omp parallel num_threads(nt) @@ -94,32 +97,41 @@ void Colvar::apply() { } #pragma omp critical { - for(unsigned j=0; j4*comm.Get_size()) { - if(fsz>0) comm.Sum(&f[0][0],3*fsz); + if(fsz>0) { + comm.Sum(&f[0][0],3*fsz); + } comm.Sum(&v[0][0],9); } } else if( isEnergy ) { std::vector forces(1); - if(getPntrToComponent(0)->applyForce(forces)) modifyForceOnEnergy()+=forces[0]; + if(getPntrToComponent(0)->applyForce(forces)) { + modifyForceOnEnergy()+=forces[0]; + } } else if( isExtraCV ) { std::vector forces(1); - if(getPntrToComponent(0)->applyForce(forces)) modifyForceOnExtraCV()+=forces[0]; + if(getPntrToComponent(0)->applyForce(forces)) { + modifyForceOnExtraCV()+=forces[0]; + } } } void Colvar::setBoxDerivativesNoPbc(Value* v) { Tensor virial; unsigned nat=getNumberOfAtoms(); - 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 ba221ff4ca..2a41f67cd9 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: bool isEnergy; @@ -64,7 +63,9 @@ class Colvar : void setBoxDerivativesNoPbc(); void setBoxDerivativesNoPbc(Value*); public: - bool checkIsEnergy() {return isEnergy;} + bool checkIsEnergy() { + return isEnergy; + } explicit Colvar(const ActionOptions&); ~Colvar() {} static void registerKeywords( Keywords& keys ); diff --git a/src/core/DataFetchingObject.cpp b/src/core/DataFetchingObject.cpp index d321a81106..f5438ea924 100644 --- a/src/core/DataFetchingObject.cpp +++ b/src/core/DataFetchingObject.cpp @@ -48,24 +48,31 @@ std::unique_ptr DataFetchingObject::create(unsigned n, Plume } else if(n==sizeof(float)) { return Tools::make_unique>(p); } - 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); } DataFetchingObject::DataFetchingObject(PlumedMain&p): - plumed(p) -{ + plumed(p) { } bool DataFetchingObject::activate() const { - for(unsigned j=0; jactivate(); - if( myactions.size()>0 ) return true; + for(unsigned j=0; jactivate(); + } + if( myactions.size()>0 ) { + return true; + } return false; } ActionWithValue* DataFetchingObject::findAction( const ActionSet& a, const std::string& key ) { - std::string aname = key; std::size_t dot = key.find("."); - if( dot!=std::string::npos ) aname = key.substr(0,dot); + std::string aname = key; + std::size_t dot = key.find("."); + if( dot!=std::string::npos ) { + aname = key.substr(0,dot); + } return a.selectWithLabel( aname ); } @@ -113,8 +120,7 @@ void DataFetchingObject::get_shape( const ActionSet& a, const std::string& key, template DataFetchingObjectTyped::DataFetchingObjectTyped(PlumedMain&p): - DataFetchingObject(p) -{ + DataFetchingObject(p) { } template @@ -131,9 +137,14 @@ void DataFetchingObjectTyped::setData( const std::string& key, const std::str // Store the action if not already stored bool found=false; for(const auto & p : myactions) { - if( p->getLabel()==myv->getLabel() ) { found=true; break; } + if( p->getLabel()==myv->getLabel() ) { + found=true; + break; + } + } + if( !found ) { + myactions.push_back( myv ); } - if( !found ) myactions.push_back( myv ); // Store the value myvalues.push_back( myv->copyOutput( key ) ); } diff --git a/src/core/ExchangePatterns.cpp b/src/core/ExchangePatterns.cpp index e47afa313c..8ea743086d 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); @@ -107,7 +108,9 @@ void GREX::cmd(const std::string&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; @@ -121,7 +124,9 @@ void GREX::cmd(const std::string&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; @@ -157,7 +162,9 @@ void GREX::cmd(const std::string&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 2c3b35637c..d4a38a4ba5 100644 --- a/src/core/GREX.h +++ b/src/core/GREX.h @@ -34,8 +34,7 @@ class Atoms; 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 93d381084f..7ab75f40c7 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,plumed.getAtoms().usingNaturalUnits(),0.1/plumed.getAtoms().getUnits().getLength()))plumed_merror("missing input file " + reference ); + if( ! pdb.read(reference,plumed.getAtoms().usingNaturalUnits(),0.1/plumed.getAtoms().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()< class MDAtomsTyped: - public MDAtomsBase -{ + public MDAtomsBase { T scalep=1.0; // factor to scale positions T scalef=1.0; // factor to scale forces T scaleb=1.0; // factor to scale box @@ -112,12 +111,16 @@ class MDAtomsTyped: bool isExtraCVNeeded(const std::string &name) const override { auto search=extraCVNeeded.find(name); - if(search != extraCVNeeded.end()) return search->second; + if(search != extraCVNeeded.end()) { + return search->second; + } return false; } void resetExtraCVNeeded() override { - for(auto & i : extraCVNeeded) i.second=false; + for(auto & i : extraCVNeeded) { + i.second=false; + } } void MD2double(const TypesafePtr & m,double&d)const override { @@ -169,8 +172,13 @@ void MDAtomsTyped::setUnits(const Units& units,const Units& MDUnits) { template void MDAtomsTyped::getBox(Tensor&box)const { auto b=this->box.template get({3,3}); - if(b) for(int i=0; i<3; i++)for(int j=0; j<3; j++) box(i,j)=b[3*i+j]*scaleb; - else box.zero(); + if(b) + for(int i=0; i<3; i++) + for(int j=0; j<3; j++) { + box(i,j)=b[3*i+j]*scaleb; + } else { + box.zero(); + } } template @@ -250,21 +258,35 @@ void MDAtomsTyped::getLocalPositions(std::vector&positions)const { template void MDAtomsTyped::getMasses(const std::vector&index,std::vector&masses)const { auto mm=m.get(index.size()); - if(mm) for(unsigned i=0; i void MDAtomsTyped::getCharges(const std::vector&index,std::vector&charges)const { auto cc=c.get(index.size()); - if(cc) for(unsigned i=0; i void MDAtomsTyped::updateVirial(const Tensor&virial)const { auto v=this->virial.template get({3,3}); - if(v) for(int i=0; i<3; i++)for(int j=0; j<3; j++) v[3*i+j]+=T(virial(i,j)*scalev); + if(v) + for(int i=0; i<3; i++) + for(int j=0; j<3; j++) { + v[3*i+j]+=T(virial(i,j)*scalev); + } } template @@ -315,7 +337,11 @@ void MDAtomsTyped::rescaleForces(const std::vector&index,double factor) getPointers(f,fx,fy,fz,index.size(),ffx,ffy,ffz,stride); plumed_assert(index.size()==0 || (ffx && ffy && ffz)); auto v=virial.get({3,3}); - if(v) for(unsigned i=0; i<3; i++)for(unsigned j=0; j<3; j++) v[3*i+j]*=T(factor); + if(v) + for(unsigned i=0; i<3; i++) + for(unsigned j=0; j<3; j++) { + v[3*i+j]*=T(factor); + } #pragma omp parallel for num_threads(OpenMP::getGoodNumThreads(ffx,stride*index.size())) for(unsigned i=0; i void MDAtomsTyped::setp(const TypesafePtr & pp,int i) { p=TypesafePtr(); pp.get(); // just check type and discard pointer - if(i==0)px=pp.copy(); - if(i==1)py=pp.copy(); - if(i==2)pz=pp.copy(); + if(i==0) { + px=pp.copy(); + } + if(i==1) { + py=pp.copy(); + } + if(i==2) { + pz=pp.copy(); + } } template @@ -374,9 +406,15 @@ template void MDAtomsTyped::setf(const TypesafePtr & ff,int i) { f=TypesafePtr();; ff.get(); // just check type and discard pointer - if(i==0)fx=ff.copy(); - if(i==1)fy=ff.copy(); - if(i==2)fz=ff.copy(); + if(i==0) { + fx=ff.copy(); + } + if(i==1) { + fy=ff.copy(); + } + if(i==2) { + fz=ff.copy(); + } } template diff --git a/src/core/MDAtoms.h b/src/core/MDAtoms.h index dd69a05035..1688e31175 100644 --- a/src/core/MDAtoms.h +++ b/src/core/MDAtoms.h @@ -47,8 +47,7 @@ create(n), where n is the actual size of MD-reals e.g. std::unique_ptr mdatoms=MDAtomsBase::create(sizeof(float)); \endverbatim */ -class MDAtomsBase -{ +class MDAtomsBase { public: /// Creates an MDAtomsTyped object such that sizeof(T)==n static std::unique_ptr create(unsigned n); diff --git a/src/core/PlumedMain.cpp b/src/core/PlumedMain.cpp index 35b75222c8..0c3f5e7deb 100644 --- a/src/core/PlumedMain.cpp +++ b/src/core/PlumedMain.cpp @@ -101,28 +101,48 @@ 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); + } } #endif if(words[0]=="std::ios_base::failure") { #ifdef __PLUMED_LIBCXX11 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())); + } #endif 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; } @@ -211,8 +231,7 @@ PlumedMain::PlumedMain(): stopNow(false), novirial(false), detailedTimers(false), - gpuDeviceId(-1) -{ + gpuDeviceId(-1) { increaseReferenceCounter(); log.link(comm); log.setLinePrefix("PLUMED: "); @@ -257,7 +276,9 @@ void PlumedMain::cmd(const std::string & word,const TypesafePtr & val) { int iword=-1; double d; 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: CHECK_INIT(initialized,word); @@ -399,33 +420,50 @@ void PlumedMain::cmd(const std::string & word,const TypesafePtr & val) { break; /* ADDED WITH API==6 */ case cmd_getDataRank: - CHECK_INIT(initialized,words[0]); plumed_assert(nw==2 || nw==3); - if( nw==2 ) DataFetchingObject::get_rank( actionSet, words[1], "", val); - else DataFetchingObject::get_rank( actionSet, words[1], words[2], val); + CHECK_INIT(initialized,words[0]); + plumed_assert(nw==2 || nw==3); + if( nw==2 ) { + DataFetchingObject::get_rank( actionSet, words[1], "", val); + } else { + DataFetchingObject::get_rank( actionSet, words[1], words[2], val); + } break; /* ADDED WITH API==6 */ case cmd_getDataShape: - CHECK_INIT(initialized,words[0]); plumed_assert(nw==2 || nw==3); - if( nw==2 ) DataFetchingObject::get_shape( actionSet, words[1], "", val ); - else DataFetchingObject::get_shape( actionSet, words[1], words[2], val ); + CHECK_INIT(initialized,words[0]); + plumed_assert(nw==2 || nw==3); + if( nw==2 ) { + DataFetchingObject::get_shape( actionSet, words[1], "", val ); + } else { + DataFetchingObject::get_shape( actionSet, words[1], words[2], val ); + } break; /* ADDED WITH API==6 */ case cmd_setMemoryForData: - CHECK_INIT(initialized,words[0]); plumed_assert(nw==2 || nw==3); - if( nw==2 ) mydatafetcher->setData( words[1], "", val ); - else mydatafetcher->setData( words[1], words[2], val ); + CHECK_INIT(initialized,words[0]); + plumed_assert(nw==2 || nw==3); + if( nw==2 ) { + mydatafetcher->setData( words[1], "", val ); + } else { + mydatafetcher->setData( words[1], words[2], 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.get()); - else readInputFile("plumed.dat"); + if(val) { + readInputFile(val.get()); + } else { + readInputFile("plumed.dat"); + } break; case cmd_readInputLine: CHECK_INIT(initialized,word); @@ -536,21 +574,27 @@ void PlumedMain::cmd(const std::string & 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; @@ -559,7 +603,9 @@ void PlumedMain::cmd(const std::string & 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 */ @@ -570,8 +616,11 @@ void PlumedMain::cmd(const std::string & 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: @@ -622,8 +671,11 @@ void PlumedMain::cmd(const std::string & word,const TypesafePtr & val) { case cmd_isEnergyNeeded: CHECK_INIT(initialized,word); CHECK_NOTNULL(val,word); - if(atoms.isEnergyNeeded()) val.set(int(1)); - else val.set(int(0)); + if(atoms.isEnergyNeeded()) { + val.set(int(1)); + } else { + val.set(int(0)); + } break; case cmd_getBias: CHECK_INIT(initialized,word); @@ -649,33 +701,45 @@ void PlumedMain::cmd(const std::string & word,const TypesafePtr & val) { case cmd_isExtraCVNeeded: CHECK_NOTNULL(val,word); plumed_assert(nw==2); - if(atoms.isExtraCVNeeded(words[1])) val.set(int(1)); - else val.set(int(0)); + if(atoms.isExtraCVNeeded(words[1])) { + val.set(int(1)); + } else { + val.set(int(0)); + } 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=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; /* ADDED WITH API==7 */ - case cmd_convert: - { + case cmd_convert: { double v; plumed_assert(words.size()==2); - if(Tools::convertNoexcept(words[1],v)) atoms.double2MD(v,val); + if(Tools::convertNoexcept(words[1],v)) { + atoms.double2MD(v,val); + } } break; default: @@ -706,7 +770,9 @@ void PlumedMain::init() { // check that initialization just happens once initialized=true; atoms.init(); - if(!log.isOpen()) log.link(stdout); + if(!log.isOpen()) { + log.link(stdout); + } log<<"PLUMED is starting\n"; log<<"Version: "<0) { readInputFile(plumedDat); @@ -731,9 +799,9 @@ void PlumedMain::init() { } atoms.updateUnits(); log.printf("Timestep: %f\n",atoms.getTimeStep()); - if(atoms.getKbT()>0.0) + if(atoms.getKbT()>0.0) { log.printf("KbT: %f\n",atoms.getKbT()); - 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"); } @@ -758,14 +826,18 @@ void PlumedMain::readInputFile(const std::string & str) { void PlumedMain::readInputFile(IFile & ifile) { std::vector words; - while(Tools::getParsedLine(ifile,words) && !endPlumed) readInputWords(words); + while(Tools::getParsedLine(ifile,words) && !endPlumed) { + readInputWords(words); + } endPlumed=false; pilots=actionSet.select(); } void PlumedMain::readInputLine(const std::string & str) { plumed_assert(initialized); - if(str.empty()) return; + if(str.empty()) { + return; + } std::vector words=Tools::getWords(str); citations.clear(); readInputWords(words); @@ -778,7 +850,9 @@ void PlumedMain::readInputLine(const std::string & str) { void PlumedMain::readInputLines(const std::string & str) { plumed_assert(initialized); - if(str.empty()) return; + if(str.empty()) { + return; + } log<<"FILE: (temporary)\n"; @@ -787,7 +861,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=[](FILE* fp) { std::fclose(fp); }; + auto deleter=[](FILE* fp) { + std::fclose(fp); + }; std::unique_ptr fp_deleter(fp,deleter); auto ret=std::fputs(str.c_str(),fp); @@ -806,8 +882,9 @@ void PlumedMain::readInputLines(const std::string & str) { void PlumedMain::readInputWords(const std::vector & words) { plumed_assert(initialized); - if(words.empty())return; - else if(words[0]=="_SET_SUFFIX") { + if(words.empty()) { + return; + } else if(words[0]=="_SET_SUFFIX") { plumed_assert(words.size()==2); setSuffix(words[1]); } else { @@ -817,7 +894,9 @@ void PlumedMain::readInputWords(const std::vector & words) { 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"); + } } } @@ -890,10 +971,14 @@ void PlumedMain::prepareDependencies() { 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"); - if(atoms.getNatoms()>0) atoms.share(); + if(atoms.getNatoms()>0) { + atoms.share(); + } } void PlumedMain::performCalcNoUpdate() { @@ -916,14 +1001,20 @@ 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"); - if(atoms.getNatoms()>0) atoms.wait(); + if(atoms.getNatoms()>0) { + atoms.wait(); + } } 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; @@ -942,23 +1033,42 @@ void PlumedMain::justCalculate() { std::string actionNumberLabel; Tools::convert(iaction,actionNumberLabel); const unsigned m=actionSet.size(); - unsigned k=0; unsigned n=1; while(ngetLabel()); } ActionWithValue*av=dynamic_cast(p); ActionAtomistic*aa=dynamic_cast(p); { - if(av) av->clearInputForces(); - if(av) av->clearDerivatives(); + if(av) { + av->clearInputForces(); + } + if(av) { + av->clearDerivatives(); + } } { - if(aa) aa->clearOutputForces(); - if(aa) if(aa->isActive()) aa->retrieveAtoms(); + if(aa) { + aa->clearOutputForces(); + } + 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"); @@ -966,7 +1076,9 @@ void PlumedMain::justCalculate() { av->setGradientsIfNeeded(); } ActionWithVirtualAtom*avv=dynamic_cast(p); - if(avv)avv->setGradientsIfNeeded(); + if(avv) { + avv->setGradientsIfNeeded(); + } } } catch(...) { plumed_error_nested() << "An error happened while calculating " << p->getLabel(); @@ -981,7 +1093,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)"); @@ -997,16 +1111,25 @@ void PlumedMain::backwardPropagate() { std::string actionNumberLabel; Tools::convert(iaction,actionNumberLabel); const unsigned m=actionSet.size(); - unsigned k=0; unsigned n=1; while(ngetLabel()); } p->apply(); ActionAtomistic*a=dynamic_cast(p); // still ActionAtomistic has a special treatment, since they may need to add forces on atoms - if(a) a->applyForces(); + if(a) { + a->applyForces(); + } } iaction++; @@ -1015,13 +1138,19 @@ 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"); + } // this is updating the MD copy of the forces - if(atoms.getNatoms()>0) atoms.updateForces(); + if(atoms.getNatoms()>0) { + atoms.updateForces(); + } } void PlumedMain::update() { - if(!active)return; + if(!active) { + return; + } // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("6 Update"); @@ -1030,14 +1159,23 @@ void PlumedMain::update() { updateFlags.push(true); for(const auto & p : actionSet) { p->beforeUpdate(); - if(p->isActive() && p->checkUpdate() && updateFlagsTop()) p->update(); + if(p->isActive() && p->checkUpdate() && updateFlagsTop()) { + 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 @@ -1046,7 +1184,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(); + } } } @@ -1056,19 +1196,27 @@ void PlumedMain::load(const std::string& ss) { size_t n=s.find_last_of("."); std::string extension=""; std::string base=s; - if(n!=std::string::npos && n0) log<<" (only on master node)"; + if(comm.Get_size()>0) { + log<<" (only on master node)"; + } log<<"\n"; if(comm.Get_rank()==0) { int ret=std::system(cmd.c_str()); - if(ret!=0) plumed_error() <<"An error happened while executing command "<(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; } diff --git a/src/core/PlumedMain.h b/src/core/PlumedMain.h index c24529edea..8213d7c024 100644 --- a/src/core/PlumedMain.h +++ b/src/core/PlumedMain.h @@ -76,8 +76,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 @@ -376,7 +375,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 @@ -404,7 +405,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 @@ -421,7 +426,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); @@ -537,7 +544,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 a65225de08..91984ec7aa 100644 --- a/src/core/PlumedMainInitializer.cpp +++ b/src/core/PlumedMainInitializer.cpp @@ -109,7 +109,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)); } } @@ -126,116 +128,179 @@ 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_exception & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11500,msg,opt); #ifdef __PLUMED_LIBCXX11 } 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); #endif } catch(const std::bad_alloc & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } nothrow.handler(nothrow.ptr,11400,msg,opt); #ifdef __PLUMED_LIBCXX11 } 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); #endif } 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); // not implemented yet: std::regex_error // we do not allow regex yet due to portability problems with gcc 4.8 // as soon as we transition to using it should be straightforward to add } catch(const std::ios_base::failure & e) { - if(!msg) msg=e.what(); + if(!msg) { + msg=e.what(); + } #ifdef __PLUMED_LIBCXX11 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 #endif // 10239 represents std::ios_base::failure with default constructur nothrow.handler(nothrow.ptr,10239,msg,opt); #ifdef __PLUMED_LIBCXX11 } 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); + } #endif } 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); // not implemented yet: std::future_error // not clear how useful it would be. } 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 @@ -285,7 +350,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()) { @@ -364,33 +431,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; @@ -398,17 +473,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/TargetDist.cpp b/src/core/TargetDist.cpp index a617e99fa7..413b75018e 100644 --- a/src/core/TargetDist.cpp +++ b/src/core/TargetDist.cpp @@ -50,9 +50,14 @@ void TargetDist::read( const PDB& pdb, std::vector ar ) { void TargetDist::read( const std::vector& targ, 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; i& forces ) const { - if( !hasForce ) return false; + if( !hasForce ) { + return false; + } plumed_dbg_massert( derivatives.size()==forces.size()," forces array has wrong size" ); const unsigned N=derivatives.size(); - 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(); } @@ -127,7 +134,9 @@ void Value::getDomain(double&minout,double&maxout) const { void Value::setGradients() { // Can't do gradients if we don't have derivatives - if( !hasDeriv ) return; + if( !hasDeriv ) { + return; + } gradients.clear(); ActionAtomistic*aa=dynamic_cast(action); ActionWithArguments*aw=dynamic_cast(action); @@ -142,7 +151,9 @@ void Value::setGradients() { gradients[p.first]+=matmul(Vector(derivatives[3*j],derivatives[3*j+1],derivatives[3*j+2]),p.second); } } else { - for(unsigned i=0; i<3; i++) gradients[an][i]+=derivatives[3*j+i]; + for(unsigned i=0; i<3; i++) { + gradients[an][i]+=derivatives[3*j+i]; + } } } } else if(aw) { @@ -153,7 +164,9 @@ void Value::setGradients() { gradients[iatom]+=p.second*derivatives[j]; } } - } else plumed_error(); + } else { + plumed_error(); + } } double Value::projection(const Value& v1,const Value&v2) { @@ -177,23 +190,33 @@ ActionWithValue* Value::getPntrToAction() { void copy( const Value& val1, Value& val2 ) { unsigned nder=val1.getNumberOfDerivatives(); - if( nder!=val2.getNumberOfDerivatives() ) { val2.resizeDerivatives( nder ); } + if( nder!=val2.getNumberOfDerivatives() ) { + val2.resizeDerivatives( nder ); + } val2.clearDerivatives(); - for(unsigned i=0; igetNumberOfDerivatives() ) { val2->resizeDerivatives( nder ); } + if( nder!=val2->getNumberOfDerivatives() ) { + val2->resizeDerivatives( nder ); + } val2->clearDerivatives(); - for(unsigned i=0; iaddDerivative( i, val1.getDerivative(i) ); + for(unsigned i=0; iaddDerivative( i, val1.getDerivative(i) ); + } val2->set( val1.get() ); } void add( const Value& val1, Value* val2 ) { plumed_assert( val1.getNumberOfDerivatives()==val2->getNumberOfDerivatives() ); - for(unsigned i=0; iaddDerivative( i, val1.getDerivative(i) ); + for(unsigned i=0; iaddDerivative( i, val1.getDerivative(i) ); + } val2->set( val1.get() + val2->get() ); } diff --git a/src/core/Value.h b/src/core/Value.h index be8495116f..cd604d279d 100644 --- a/src/core/Value.h +++ b/src/core/Value.h @@ -158,14 +158,18 @@ inline void Value::applyPeriodicity() { if(periodicity==periodic) { value=min+difference(min,value); - if(valuederivatives.size()!=val1.derivatives.size() ) valout->resizeDerivatives( val1.derivatives.size() ); + if( valout->derivatives.size()!=val1.derivatives.size() ) { + valout->resizeDerivatives( val1.derivatives.size() ); + } valout->value_set=false; valout->clearDerivatives(); double u=val1.get(); @@ -187,7 +193,8 @@ void quotient( const Value& val1, const Value& val2, Value* valout ) { for(unsigned i=0; iaddDerivative(i, v*val1.getDerivative(i) - u*val2.getDerivative(i) ); } - valout->chainRule( 1/(v*v) ); valout->set( u / v ); + valout->chainRule( 1/(v*v) ); + valout->set( u / v ); } inline @@ -238,7 +245,9 @@ bool Value::hasDerivatives() const { inline void Value::resizeDerivatives(int n) { - if(hasDeriv) derivatives.resize(n); + if(hasDeriv) { + derivatives.resize(n); + } } inline @@ -255,7 +264,9 @@ void Value::setDerivative(unsigned i, double d) { inline void Value::chainRule(double df) { - for(unsigned i=0; i all_atoms; readTwoGroups( "GROUP", "GROUPA", "GROUPB", all_atoms ); - if( atom_lab.size()==0 ) readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + if( atom_lab.size()==0 ) { + readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + } setupMultiColvarBase( all_atoms ); // Read in the switching function - std::string sw, errors; parse("SWITCH",sw); + std::string sw, errors; + parse("SWITCH",sw); if(sw.length()>0) { switchingFunction.set(sw,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); } log.printf(" orientation of those bonds with lengths are less than %s\n",( switchingFunction.description() ).c_str() ); // Set the link cell cutoff setLinkCellCutoff( switchingFunction.get_dmax() ); - double rcut = switchingFunction.get_dmax(); rcut2 = rcut*rcut; + double rcut = switchingFunction.get_dmax(); + rcut2 = rcut*rcut; // Set the dimensionality of the vectors setVectorDimensionality(3); } double BondOrientation::calculateWeight( const unsigned& current, const double& weight, multicolvar::AtomValuePack& myatoms ) const { - Vector distance=getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); double distm=distance.modulo2(); - if( distm>rcut2 ) return 0.0; + Vector distance=getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); + double distm=distance.modulo2(); + if( distm>rcut2 ) { + return 0.0; + } double df, ww=switchingFunction.calculateSqr( distm, df ); // Derivatives of weights addAtomDerivatives( 0, 0, -df*weight*distance, myatoms ); diff --git a/src/crystallization/CubicHarmonicBase.cpp b/src/crystallization/CubicHarmonicBase.cpp index dd6c939a55..eae9de8f7e 100644 --- a/src/crystallization/CubicHarmonicBase.cpp +++ b/src/crystallization/CubicHarmonicBase.cpp @@ -32,7 +32,9 @@ namespace crystallization { void CubicHarmonicBase::registerKeywords( Keywords& keys ) { multicolvar::MultiColvarBase::registerKeywords( keys ); - keys.use("SPECIES"); keys.use("SPECIESA"); keys.use("SPECIESB"); + keys.use("SPECIES"); + keys.use("SPECIESA"); + keys.use("SPECIESB"); keys.add("compulsory","NN","6","The n parameter of the switching function "); keys.add("compulsory","MM","0","The m parameter of the switching function; 0 implies 2*NN"); keys.add("compulsory","D_0","0.0","The d_0 parameter of the switching function"); @@ -45,29 +47,47 @@ void CubicHarmonicBase::registerKeywords( Keywords& keys ) { keys.add("compulsory","PSI","0.0","The Euler rotational angle psi"); keys.addFlag("UNORMALIZED",false,"calculate the sum of the components of the vector rather than the mean"); // Use actionWithDistributionKeywords - keys.use("MEAN"); keys.use("MORE_THAN"); keys.use("LESS_THAN"); keys.use("MAX"); - keys.use("MIN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); - keys.use("ALT_MIN"); keys.use("LOWEST"); keys.use("HIGHEST"); + keys.use("MEAN"); + keys.use("MORE_THAN"); + keys.use("LESS_THAN"); + keys.use("MAX"); + keys.use("MIN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); + keys.use("ALT_MIN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); } CubicHarmonicBase::CubicHarmonicBase(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { // Read in the switching function - std::string sw, errors; parse("SWITCH",sw); + std::string sw, errors; + parse("SWITCH",sw); if(sw.length()>0) { 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 { - 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); } - double phi, theta, psi; parse("PHI",phi); parse("THETA",theta); parse("PSI",psi); + double phi, theta, psi; + parse("PHI",phi); + parse("THETA",theta); + parse("PSI",psi); log.printf(" creating rotation matrix with Euler angles phi=%f, theta=%f and psi=%f\n",phi,theta,psi); // Calculate the rotation matrix http://mathworld.wolfram.com/EulerAngles.html rotationmatrix[0][0]=std::cos(psi)*std::cos(phi)-std::cos(theta)*std::sin(phi)*std::sin(psi); @@ -85,20 +105,26 @@ CubicHarmonicBase::CubicHarmonicBase(const ActionOptions&ao): log.printf(" measure crystallinity around central atom. Includes those atoms within %s\n",( switchingFunction.description() ).c_str() ); parseFlag("UNORMALIZED",unormalized); - if( unormalized ) log.printf(" output sum of vector functions \n"); - else log.printf(" output mean of vector functions \n"); + if( unormalized ) { + log.printf(" output sum of vector functions \n"); + } else { + log.printf(" output mean of vector functions \n"); + } // Set the link cell cutoff rcut2 = switchingFunction.get_dmax()*switchingFunction.get_dmax(); setLinkCellCutoff( switchingFunction.get_dmax() ); // And setup the ActionWithVessel - std::vector all_atoms; setupMultiColvarBase( all_atoms ); + std::vector all_atoms; + setupMultiColvarBase( all_atoms ); } double CubicHarmonicBase::compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const { - double dfunc; Vector rotatedis; + double dfunc; + Vector rotatedis; // Calculate the coordination number - Vector myder, rotateder, fder; unsigned nat=myatoms.getNumberOfAtoms(); + Vector myder, rotateder, fder; + unsigned nat=myatoms.getNumberOfAtoms(); for(unsigned i=1; i der of... value [0], weight[1], x coord [2], y, z... [more magic] updateActiveAtoms( myatoms ); - if( !unormalized ) myatoms.getUnderlyingMultiValue().quotientRule( 1, 1 ); + if( !unormalized ) { + myatoms.getUnderlyingMultiValue().quotientRule( 1, 1 ); + } return myatoms.getValue(1); // this is equivalent to getting an "atomic" CV } diff --git a/src/crystallization/CubicHarmonicBase.h b/src/crystallization/CubicHarmonicBase.h index d1f24d8120..faf03d492b 100644 --- a/src/crystallization/CubicHarmonicBase.h +++ b/src/crystallization/CubicHarmonicBase.h @@ -43,7 +43,9 @@ class CubicHarmonicBase : public multicolvar::MultiColvarBase { double compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const ; virtual double calculateCubicHarmonic( const Vector& distance, const double& d2, Vector& myder ) const = 0; /// Returns the number of coordinates of the field - bool isPeriodic() { return false; } + bool isPeriodic() { + return false; + } }; } diff --git a/src/crystallization/EnvironmentSimilarity.cpp b/src/crystallization/EnvironmentSimilarity.cpp index 695eb45bc8..f5fa4200a9 100644 --- a/src/crystallization/EnvironmentSimilarity.cpp +++ b/src/crystallization/EnvironmentSimilarity.cpp @@ -203,7 +203,9 @@ class EnvironmentSimilarity : public multicolvar::MultiColvarBase { // active methods: virtual double compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const ; // Returns the number of coordinates of the field - bool isPeriodic() { return false; } + bool isPeriodic() { + return false; + } // Calculates maximum distance in an environment double maxDistance(std::vector environment); // Parse everything connected to the definition of the reference environments @@ -218,7 +220,9 @@ PLUMED_REGISTER_ACTION(EnvironmentSimilarity,"ENVIRONMENTSIMILARITY") void EnvironmentSimilarity::registerKeywords( Keywords& keys ) { MultiColvarBase::registerKeywords( keys ); - keys.use("SPECIES"); keys.use("SPECIESA"); keys.use("SPECIESB"); + keys.use("SPECIES"); + keys.use("SPECIESA"); + keys.use("SPECIESB"); keys.add("compulsory","SIGMA","0.1","Broadening parameter"); keys.add("compulsory","CRYSTAL_STRUCTURE","FCC","Targeted crystal structure. Options are: " "SC: simple cubic, " @@ -239,15 +243,22 @@ void EnvironmentSimilarity::registerKeywords( Keywords& keys ) { 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."); // Use actionWithDistributionKeywords - keys.use("MEAN"); keys.use("MORE_THAN"); keys.use("LESS_THAN"); keys.use("MAX"); - keys.use("MIN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); - keys.use("ALT_MIN"); keys.use("LOWEST"); keys.use("HIGHEST"); + keys.use("MEAN"); + keys.use("MORE_THAN"); + keys.use("LESS_THAN"); + keys.use("MAX"); + keys.use("MIN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); + keys.use("ALT_MIN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); } EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { log.printf(" Please read and cite "); log << plumed.cite("Piaggi and Parrinello, J. Chem. Phys. 150 (24), 244119 (2019)"); log.printf("\n"); @@ -263,7 +274,9 @@ EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): lambda_=100; parse("LAMBDA", lambda_); - if (environments_.size()>1) log.printf(" using a soft max function with lambda %f\n",lambda_); + if (environments_.size()>1) { + log.printf(" using a soft max function with lambda %f\n",lambda_); + } // Set the link cell cutoff double rcut = max_dist_ref_vector + 3*sigma; @@ -271,7 +284,9 @@ EnvironmentSimilarity::EnvironmentSimilarity(const ActionOptions&ao): rcut2_ = rcut * rcut; // And setup the ActionWithVessel - std::vector all_atoms; setupMultiColvarBase( all_atoms ); checkRead(); + std::vector all_atoms; + setupMultiColvarBase( all_atoms ); + checkRead(); plumed_massert(atomNames_.empty() || atomNames_.size()==getNumberOfAtoms(),"mismatch between atoms in SPECIES and ATOM_NAMES_FILE"); } @@ -398,7 +413,9 @@ double EnvironmentSimilarity::maxDistance( std::vector environment ) { double max_dist = 0.0; for(unsigned i=0; imax_dist) max_dist=norm; + if (norm>max_dist) { + max_dist=norm; + } } return max_dist; } @@ -410,7 +427,9 @@ void EnvironmentSimilarity::parseReferenceEnvironments( std::vector environment; std::vector environmentAtomNames; - environment.resize( natoms ); environmentAtomNames.resize( natoms); - for(unsigned i=0; i environment; + std::vector environmentAtomNames; + environment.resize( natoms ); + environmentAtomNames.resize( natoms); + for(unsigned i=0; imax_dist) max_dist=norm; + if (norm>max_dist) { + max_dist=norm; + } log.printf(" Reference environment %d : reading %d reference vectors from %s \n", i, natoms, reffile.c_str() ); } } - if (environments.size()==0) error("No environments have been found! Please specify a PDB file in the REFERENCE " - "or in the REFERENCE_1, REFERENCE_2, etc keywords"); + if (environments.size()==0) + error("No environments have been found! Please specify a PDB file in the REFERENCE " + "or in the REFERENCE_1, REFERENCE_2, etc keywords"); log.printf(" Number of reference environments is %lu\n",environments.size() ); log.printf(" Number of vectors per reference environment is %lu\n",environments[0].size() ); std::string atomNamesFile; parse("ATOM_NAMES_FILE",atomNamesFile); if (!atomNamesFile.empty()) { PDB pdb; - if( !pdb.read(atomNamesFile,plumed.getAtoms().usingNaturalUnits(),0.1/plumed.getAtoms().getUnits().getLength()) ) + if( !pdb.read(atomNamesFile,plumed.getAtoms().usingNaturalUnits(),0.1/plumed.getAtoms().getUnits().getLength()) ) { error("missing input file " + atomNamesFile); + } unsigned natoms=pdb.getPositions().size(); atomNames_.resize( natoms ); - for(unsigned i=0; i0) log.printf(" with lattice constants %f\n",lattice_constants[0]); - else log.printf("\n"); + if (lattice_constants.size()>0) { + log.printf(" with lattice constants %f\n",lattice_constants[0]); + } else { + log.printf("\n"); + } log.printf(" maximum distance in the reference environment is %f\n",max_dist); } diff --git a/src/crystallization/Fccubic.cpp b/src/crystallization/Fccubic.cpp index 8763087087..2d8062c430 100644 --- a/src/crystallization/Fccubic.cpp +++ b/src/crystallization/Fccubic.cpp @@ -90,12 +90,12 @@ void Fccubic::registerKeywords( Keywords& keys ) { Fccubic::Fccubic(const ActionOptions&ao): Action(ao), - CubicHarmonicBase(ao) -{ + CubicHarmonicBase(ao) { // Scaling factors such that '1' corresponds to fcc lattice // and '0' corresponds to isotropic (liquid) parse("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); log.printf(" setting alpha parameter equal to %f \n",alpha); // And setup the ActionWithVessel checkRead(); diff --git a/src/crystallization/Gradient.cpp b/src/crystallization/Gradient.cpp index 22ff2c7739..9da2b08b62 100644 --- a/src/crystallization/Gradient.cpp +++ b/src/crystallization/Gradient.cpp @@ -73,61 +73,103 @@ void Gradient::registerKeywords( Keywords& keys ) { Gradient::Gradient(const ActionOptions&ao): Action(ao), VolumeGradientBase(ao), - nbins(3) -{ + nbins(3) { std::vector atom; parseAtomList("ORIGIN",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(" origin is at position of atom : %d\n",atom[0].serial() ); - std::string direction; parse("DIR",direction); - std::vector tbins; parseVector("NBINS",tbins); + std::string direction; + parse("DIR",direction); + std::vector tbins; + parseVector("NBINS",tbins); for(unsigned i=0; iisDensity() ) vend=2; - else if( getPntrToMultiColvar()->getNumberOfQuantities()==2 ) vend=2; - else vend = getPntrToMultiColvar()->getNumberOfQuantities(); + if( getPntrToMultiColvar()->isDensity() ) { + vend=2; + } else if( getPntrToMultiColvar()->getNumberOfQuantities()==2 ) { + vend=2; + } else { + vend = getPntrToMultiColvar()->getNumberOfQuantities(); + } nquantities = vend + nbins[0] + nbins[1] + nbins[2]; // Output some nice information std::string functype=getPntrToMultiColvar()->getName(); - std::transform( functype.begin(), functype.end(), functype.begin(), [](unsigned char c) { return std::tolower(c); } ); + std::transform( functype.begin(), functype.end(), functype.begin(), [](unsigned char c) { + return std::tolower(c); + } ); log.printf(" calculating gradient of %s in %s direction \n",functype.c_str(), direction.c_str() ); log<<" Bibliography:"<getCentralAtomPos( curr ) ); // Note we use the pbc from base multicolvar so that we get numerical derivatives correct Vector oderiv, fpos = (getPntrToMultiColvar()->getPbc()).realToScaled( cpos ); - Vector deriv; unsigned nbase=vend; std::vector refder(1); Tensor vir; vir.zero(); + Vector deriv; + unsigned nbase=vend; + std::vector refder(1); + Tensor vir; + vir.zero(); for(unsigned idir=0; idir<3; ++idir) { deriv[0]=deriv[1]=deriv[2]=0.0; double delx = 1.0 / static_cast( nbins[idir] ); diff --git a/src/crystallization/GradientVessel.cpp b/src/crystallization/GradientVessel.cpp index 6d5389fc4f..373f4e6c0d 100644 --- a/src/crystallization/GradientVessel.cpp +++ b/src/crystallization/GradientVessel.cpp @@ -56,10 +56,10 @@ void GradientVessel::reserveKeyword( Keywords& keys ) { } GradientVessel::GradientVessel( const vesselbase::VesselOptions& da ) : - FunctionVessel(da) -{ + FunctionVessel(da) { Gradient* vg=dynamic_cast( getAction() ); - plumed_assert( vg ); isdens=(vg->getPntrToMultiColvar())->isDensity(); + plumed_assert( vg ); + isdens=(vg->getPntrToMultiColvar())->isDensity(); nweights = vg->nbins[0] + vg->nbins[1] + vg->nbins[2]; if( (vg->getPntrToMultiColvar())->getNumberOfQuantities()>2 ) { ncomponents = (vg->getPntrToMultiColvar())->getNumberOfQuantities() - 2; @@ -72,13 +72,17 @@ GradientVessel::GradientVessel( const vesselbase::VesselOptions& da ) : starts.push_back( vg->nbins[0] ); if( vg->nbins[1]>0 ) { starts.push_back( vg->nbins[0] + vg->nbins[1] ); - if( vg->nbins[2]>0 ) starts.push_back( nweights ); + if( vg->nbins[2]>0 ) { + starts.push_back( nweights ); + } } else if( vg->nbins[2]>0 ) { starts.push_back( nweights ); } } else if( vg->nbins[1]>0 ) { starts.push_back( vg->nbins[1] ); - if( vg->nbins[2]>0 ) starts.push_back( nweights ); + if( vg->nbins[2]>0 ) { + starts.push_back( nweights ); + } } else if( vg->nbins[2]>0 ) { starts.push_back( nweights ); } @@ -100,9 +104,19 @@ void GradientVessel::resize() { void GradientVessel::calculate( const unsigned& current, MultiValue& myvals, std::vector& buffer, std::vector& der_list ) const { unsigned nder; - if( getAction()->derivativesAreRequired() ) nder=getAction()->getNumberOfDerivatives(); - else nder=0; - unsigned wstart, cstart; if( ncomponents==1 ) { cstart=1; wstart=2; } else { cstart=2; wstart=2+ncomponents; } + if( getAction()->derivativesAreRequired() ) { + nder=getAction()->getNumberOfDerivatives(); + } else { + nder=0; + } + unsigned wstart, cstart; + if( ncomponents==1 ) { + cstart=1; + wstart=2; + } else { + cstart=2; + wstart=2+ncomponents; + } for(unsigned iw=0; iw& buffer ) { std::vector val_interm( ncomponents*nweights ); unsigned nder; - if( getAction()->derivativesAreRequired() ) nder=getAction()->getNumberOfDerivatives(); - else nder=0; - Matrix der_interm( ncomponents*nweights, nder ); der_interm=0; + if( getAction()->derivativesAreRequired() ) { + nder=getAction()->getNumberOfDerivatives(); + } else { + nder=0; + } + Matrix der_interm( ncomponents*nweights, nder ); + der_interm=0; if( isdens ) { for(unsigned iw=0; iwderivativesAreRequired() ) { unsigned wstart = bufstart + 2*iw*(nder+1) + 1; - for(unsigned jder=0; jderderivativesAreRequired() ) { unsigned wstart = bufstart + xx*(nder+1) + 1; for(unsigned jc=0; jc& buffer ) { for(unsigned j=0; jgetNumberOfQuantities()!=5 ) error("input multicolvar does not calculate molecular orientations"); + if( getBaseMultiColvar(i)->getNumberOfQuantities()!=5 ) { + error("input multicolvar does not calculate molecular orientations"); + } } // The weight of this does have derivatives weightHasDerivatives=true; // Read in the switching function - std::string sw, errors; parse("SWITCH",sw); + std::string sw, errors; + parse("SWITCH",sw); if(sw.length()>0) { switchingFunction.set(sw,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); } log.printf(" calculating number of links with atoms separation of %s\n",( switchingFunction.description() ).c_str() ); - std::vector all_atoms; readTwoGroups( "MOLS", "MOLSA", "MOLSB", all_atoms ); - setupMultiColvarBase( all_atoms ); setLinkCellCutoff( switchingFunction.get_dmax() ); + std::vector all_atoms; + readTwoGroups( "MOLS", "MOLSA", "MOLSB", all_atoms ); + setupMultiColvarBase( all_atoms ); + setLinkCellCutoff( switchingFunction.get_dmax() ); for(unsigned i=0; ihasDifferentiableOrientation() ) error("cannot use multicolvar of type " + getBaseMultiColvar(i)->getName() ); + if( !getBaseMultiColvar(i)->hasDifferentiableOrientation() ) { + error("cannot use multicolvar of type " + getBaseMultiColvar(i)->getName() ); + } } // Create holders for the collective variable readVesselKeywords(); plumed_assert( getNumberOfVessels()==0 ); - std::string input; addVessel( "SUM", input, -1 ); + std::string input; + addVessel( "SUM", input, -1 ); readVesselKeywords(); } @@ -169,12 +186,21 @@ double InterMolecularTorsions::compute( const unsigned& tindex, multicolvar::Ato std::vector orient0( 5 ), orient1( 5 ); getInputData( 0, true, myatoms, orient0 ); getInputData( 1, true, myatoms, orient1 ); - for(unsigned i=0; i<3; ++i) { v1[i]=orient0[2+i]; v2[i]=orient1[2+i]; } - if( getBaseMultiColvar(0)->getNumberOfQuantities()<3 ) return 1.0; + for(unsigned i=0; i<3; ++i) { + v1[i]=orient0[2+i]; + v2[i]=orient1[2+i]; + } + if( getBaseMultiColvar(0)->getNumberOfQuantities()<3 ) { + return 1.0; + } // Evaluate angle - Torsion t; double angle = t.compute( v1, conn, v2, dv1, dconn, dv2 ); - for(unsigned i=0; i<3; ++i) { orient0[i+2]=dv1[i]; orient1[i+2]=dv2[i]; } + Torsion t; + double angle = t.compute( v1, conn, v2, dv1, dconn, dv2 ); + for(unsigned i=0; i<3; ++i) { + orient0[i+2]=dv1[i]; + orient1[i+2]=dv2[i]; + } // And accumulate derivatives if( !doNotCalculateDerivatives() ) { @@ -182,7 +208,8 @@ double InterMolecularTorsions::compute( const unsigned& tindex, multicolvar::Ato mergeInputDerivatives( 1, 2, orient1.size(), 0, orient0, myder0, myatoms ); MultiValue& myder1=getInputDerivatives( 1, true, myatoms ); mergeInputDerivatives( 1, 2, orient0.size(), 1, orient1, myder1, myatoms ); - addAtomDerivatives( 1, 0, -dconn, myatoms ); addAtomDerivatives( 1, 1, dconn, myatoms ); + addAtomDerivatives( 1, 0, -dconn, myatoms ); + addAtomDerivatives( 1, 1, dconn, myatoms ); myatoms.addBoxDerivatives( 1, -extProduct( conn, dconn ) ); } diff --git a/src/crystallization/LocalSteinhardt.h b/src/crystallization/LocalSteinhardt.h index 693fcb6a8e..63942c9730 100644 --- a/src/crystallization/LocalSteinhardt.h +++ b/src/crystallization/LocalSteinhardt.h @@ -32,8 +32,7 @@ class LocalSteinhardt : public OrientationSphere { static void registerKeywords( Keywords& keys ) { OrientationSphere::registerKeywords(keys); } - explicit LocalSteinhardt(const ActionOptions& ao): Action(ao), OrientationSphere(ao) - { + explicit LocalSteinhardt(const ActionOptions& ao): Action(ao), OrientationSphere(ao) { for(unsigned i=0; i( getBaseMultiColvar(i) ); if(!mc) { @@ -42,16 +41,21 @@ class LocalSteinhardt : public OrientationSphere { } for(unsigned j=0; jgetNumberOfBaseMultiColvars(); ++j) { T* mmc=dynamic_cast( getBaseMultiColvar(i)->getBaseMultiColvar(j) ); - if( !mmc ) error("input action is not calculating the correct vectors"); + if( !mmc ) { + error("input action is not calculating the correct vectors"); + } } } } } double computeVectorFunction( const Vector& conn, const std::vector& vec1, const std::vector& vec2, Vector& dconn, std::vector& dvec1, std::vector& dvec2 ) const override { - double dot=0; dconn.zero(); + double dot=0; + dconn.zero(); for(unsigned k=2; k all_atoms; readAtomsLikeKeyword("MOL",-1,all_atoms); nvectors = std::floor( ablocks.size() / 2 ); - if( ablocks.size()%2!=0 && 2*nvectors+1!=ablocks.size() ) error("number of atoms in molecule specification is wrong. Should be two or three."); + if( ablocks.size()%2!=0 && 2*nvectors+1!=ablocks.size() ) { + error("number of atoms in molecule specification is wrong. Should be two or three."); + } - if( all_atoms.size()==0 ) error("No atoms were specified"); - setVectorDimensionality( 3*nvectors ); setupMultiColvarBase( all_atoms ); + if( all_atoms.size()==0 ) { + error("No atoms were specified"); + } + setVectorDimensionality( 3*nvectors ); + setupMultiColvarBase( all_atoms ); if( ablocks.size()==2*nvectors+1 ) { - std::vector catom_ind(ablocks.size(), false); catom_ind[ablocks.size()-1]=true; + std::vector catom_ind(ablocks.size(), false); + catom_ind[ablocks.size()-1]=true; setAtomsForCentralAtom( catom_ind ); } } @@ -98,7 +105,8 @@ AtomNumber MoleculeOrientation::getAbsoluteIndexOfCentralAtom( const unsigned& i void MoleculeOrientation::calculateVector( multicolvar::AtomValuePack& myatoms ) const { for(unsigned i=0; i& vals ) const { for(unsigned i=0; iepsilon ) inorm = 1.0 / norm; - for(unsigned j=0; j<3; ++j) vals[2+3*i+j] = inorm*vals[2+3*i+j]; + double inorm = 1.0; + if( norm>epsilon ) { + inorm = 1.0 / norm; + } + for(unsigned j=0; j<3; ++j) { + vals[2+3*i+j] = inorm*vals[2+3*i+j]; + } } } void MoleculeOrientation::normalizeVectorDerivatives( MultiValue& myvals ) const { std::vector weight( nvectors ), wdf( nvectors ); for(unsigned ivec=0; ivecepsilon ) { weight[ivec] = 1.0 / v; wdf[ivec] = 1.0 / ( v*v*v ); } + double v=0; + for(unsigned jcomp=0; jcomp<3; ++jcomp) { + v += myvals.get( 2+3*ivec+jcomp )*myvals.get( 2+3*ivec+jcomp ); + } + v=sqrt(v); + weight[ivec]=1.0; + wdf[ivec]=1.0; + if( v>epsilon ) { + weight[ivec] = 1.0 / v; + wdf[ivec] = 1.0 / ( v*v*v ); + } } for(unsigned j=0; j all_atoms; readAtomsLikeKeyword("MOL",-1,all_atoms); - if( ablocks.size()!=3 && ablocks.size()!=4 ) error("number of atoms in molecule specification is wrong. Should be three or four."); + if( ablocks.size()!=3 && ablocks.size()!=4 ) { + error("number of atoms in molecule specification is wrong. Should be three or four."); + } - if( all_atoms.size()==0 ) error("No atoms were specified"); - setVectorDimensionality( 3 ); setupMultiColvarBase( all_atoms ); + if( all_atoms.size()==0 ) { + error("No atoms were specified"); + } + setVectorDimensionality( 3 ); + setupMultiColvarBase( all_atoms ); } AtomNumber MoleculePlane::getAbsoluteIndexOfCentralAtom( const unsigned& iatom ) const { diff --git a/src/crystallization/OrientationSphere.cpp b/src/crystallization/OrientationSphere.cpp index c95493b7e4..6998e61f79 100644 --- a/src/crystallization/OrientationSphere.cpp +++ b/src/crystallization/OrientationSphere.cpp @@ -38,26 +38,41 @@ void OrientationSphere::registerKeywords( Keywords& keys ) { "The following provides information on the \\ref switchingfunction that are available. " "When this keyword is present you no longer need the NN, MM, D_0 and R_0 keywords."); // Use actionWithDistributionKeywords - keys.use("SPECIES"); keys.use("SPECIESA"); keys.use("SPECIESB"); - keys.use("MEAN"); keys.use("MORE_THAN"); keys.use("LESS_THAN"); - keys.use("MIN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); - keys.use("LOWEST"); keys.use("HIGHEST"); + keys.use("SPECIES"); + keys.use("SPECIESA"); + keys.use("SPECIESB"); + keys.use("MEAN"); + keys.use("MORE_THAN"); + keys.use("LESS_THAN"); + keys.use("MIN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); + keys.use("LOWEST"); + keys.use("HIGHEST"); } OrientationSphere::OrientationSphere(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ - if( getNumberOfBaseMultiColvars()>1 ) warning("not sure if orientation sphere works with more than one base multicolvar - check numerical derivatives"); + MultiColvarBase(ao) { + if( getNumberOfBaseMultiColvars()>1 ) { + warning("not sure if orientation sphere works with more than one base multicolvar - check numerical derivatives"); + } // Read in the switching function - std::string sw, errors; parse("SWITCH",sw); + std::string sw, errors; + parse("SWITCH",sw); if(sw.length()>0) { switchingFunction.set(sw,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); } log.printf(" degree of overlap in orientation between central molecule and those within %s\n",( switchingFunction.description() ).c_str() ); @@ -65,11 +80,13 @@ OrientationSphere::OrientationSphere(const ActionOptions&ao): // Set the link cell cutoff rcut2 = switchingFunction.get_dmax()*switchingFunction.get_dmax(); setLinkCellCutoff( switchingFunction.get_dmax() ); - std::vector all_atoms; setupMultiColvarBase( all_atoms ); + std::vector all_atoms; + setupMultiColvarBase( all_atoms ); } double OrientationSphere::compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const { - double sw, value=0, denom=0, dfunc; Vector ddistance; + double sw, value=0, denom=0, dfunc; + Vector ddistance; unsigned ncomponents=getBaseMultiColvar(0)->getNumberOfQuantities(); std::vector catom_orient( ncomponents ), this_orient( ncomponents ); std::vector this_der( ncomponents ), catom_der( ncomponents ); @@ -92,7 +109,10 @@ double OrientationSphere::compute( const unsigned& tindex, multicolvar::AtomValu double f_dot = computeVectorFunction( distance, catom_orient, this_orient, ddistance, catom_der, this_der ); if( !doNotCalculateDerivatives() ) { - for(unsigned k=2; kepsilon ) { rdenom = 1.0 / denom; } - else { plumed_assert(std::fabs(value)epsilon ) { + rdenom = 1.0 / denom; + } else { + plumed_assert(std::fabs(value)& vec1, const std::vector& vec2, Vector& dconn, std::vector& dvec1, std::vector& dvec2 ) const = 0; virtual double calculateCoordinationPrefactor( const double& coord, double& df ) const ; - bool isPeriodic() { return false; } + bool isPeriodic() { + return false; + } }; inline double OrientationSphere::calculateCoordinationPrefactor( const double& coord, double& df ) const { - df=0.0; return 1.0; + df=0.0; + return 1.0; } } diff --git a/src/crystallization/PolymerAngles.cpp b/src/crystallization/PolymerAngles.cpp index b11e90309b..df2a9c9d5e 100644 --- a/src/crystallization/PolymerAngles.cpp +++ b/src/crystallization/PolymerAngles.cpp @@ -81,11 +81,14 @@ void PolymerAngles::registerKeywords( Keywords& keys ) { PolymerAngles::PolymerAngles(const ActionOptions& ao): Action(ao), - OrientationSphere(ao) -{ - if( mybasemulticolvars.size()==0 ) error("SMAC must take multicolvar as input"); + OrientationSphere(ao) { + if( mybasemulticolvars.size()==0 ) { + error("SMAC must take multicolvar as input"); + } for(unsigned i=0; igetNumberOfQuantities()-2)%3!=0 ) error("POLYMER_ANGLES is only possible with three dimensional vectors"); + if( (mybasemulticolvars[i]->getNumberOfQuantities()-2)%3!=0 ) { + error("POLYMER_ANGLES is only possible with three dimensional vectors"); + } } } @@ -93,8 +96,15 @@ double PolymerAngles::computeVectorFunction( const Vector& conn, const std::vect Vector& dconn, std::vector& dvec1, std::vector& dvec2 ) const { plumed_assert( (vec1.size()-2)==3 ); - double dot = 0; for(unsigned k=0; k<3; ++k) dot += vec1[2+k]*vec2[2+k]; - double ans = 1.5*dot*dot - 0.5; for(unsigned k=0; k<3; ++k) { dvec1[2+k]=3*dot*vec2[2+k]; dvec2[2+k]=3*dot*vec1[2+k]; } + double dot = 0; + for(unsigned k=0; k<3; ++k) { + dot += vec1[2+k]*vec2[2+k]; + } + double ans = 1.5*dot*dot - 0.5; + for(unsigned k=0; k<3; ++k) { + dvec1[2+k]=3*dot*vec2[2+k]; + dvec2[2+k]=3*dot*vec1[2+k]; + } return ans; } diff --git a/src/crystallization/Q3.cpp b/src/crystallization/Q3.cpp index 88131cc46e..375e148e60 100644 --- a/src/crystallization/Q3.cpp +++ b/src/crystallization/Q3.cpp @@ -194,8 +194,7 @@ void Q3::registerKeywords( Keywords& keys ) { Q3::Q3(const ActionOptions& ao ): Action(ao), - Steinhardt(ao) -{ + Steinhardt(ao) { setAngularMomentum(3); // Spherical harmonics normalization: diff --git a/src/crystallization/Q4.cpp b/src/crystallization/Q4.cpp index 3f13d0201e..bb3c2737bb 100644 --- a/src/crystallization/Q4.cpp +++ b/src/crystallization/Q4.cpp @@ -193,8 +193,7 @@ void Q4::registerKeywords( Keywords& keys ) { Q4::Q4(const ActionOptions& ao ): Action(ao), - Steinhardt(ao) -{ + Steinhardt(ao) { setAngularMomentum(4); normaliz.resize( 5 ); @@ -205,8 +204,10 @@ Q4::Q4(const ActionOptions& ao ): normaliz[4] = sqrt( (9.0*1) / (4.0*pi*40320.0) ); coeff_poly.resize( 5 ); - 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; } diff --git a/src/crystallization/Q6.cpp b/src/crystallization/Q6.cpp index d66aa2cdf6..ad1d2f41c9 100644 --- a/src/crystallization/Q6.cpp +++ b/src/crystallization/Q6.cpp @@ -193,8 +193,7 @@ void Q6::registerKeywords( Keywords& keys ) { Q6::Q6(const ActionOptions& ao ): Action(ao), - Steinhardt(ao) -{ + Steinhardt(ao) { setAngularMomentum(6); normaliz.resize( 7 ); @@ -207,9 +206,12 @@ Q6::Q6(const ActionOptions& ao ): normaliz[6] = sqrt( (13.0*1) / (4.0*pi*479001600) ); coeff_poly.resize( 7 ); - 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; } diff --git a/src/crystallization/SMAC.cpp b/src/crystallization/SMAC.cpp index 585bb8e16d..d73dce7dd7 100644 --- a/src/crystallization/SMAC.cpp +++ b/src/crystallization/SMAC.cpp @@ -147,39 +147,58 @@ void SMAC::registerKeywords( Keywords& keys ) { SMAC::SMAC(const ActionOptions& ao): Action(ao), - OrientationSphere(ao) -{ - if( mybasemulticolvars.size()==0 ) error("SMAC must take multicolvar as input"); + OrientationSphere(ao) { + if( mybasemulticolvars.size()==0 ) { + error("SMAC must take multicolvar as input"); + } for(unsigned i=0; igetNumberOfQuantities()-2)%3!=0 ) error("SMAC is only possible with three dimensional vectors"); + if( (mybasemulticolvars[i]->getNumberOfQuantities()-2)%3!=0 ) { + error("SMAC is only possible with three dimensional vectors"); + } } std::string kernelinpt; for(int i=1;; i++) { - if( !parseNumbered("KERNEL",i,kernelinpt) ) break; + if( !parseNumbered("KERNEL",i,kernelinpt) ) { + break; + } KernelFunctions mykernel( kernelinpt ); kernels.push_back( mykernel ); } - if( kernels.size()==0 ) error("no kernels defined"); + if( kernels.size()==0 ) { + error("no kernels defined"); + } - std::string sw, errors; parse("SWITCH_COORD",sw); - if(sw.length()==0) error("SWITCH_COORD keyword is missing"); + std::string sw, errors; + parse("SWITCH_COORD",sw); + if(sw.length()==0) { + error("SWITCH_COORD keyword is missing"); + } coord_switch.set(sw,errors); - if(errors.length()>0) error("the following errors were found in input to SWITCH_COORD : " + errors ); + if(errors.length()>0) { + error("the following errors were found in input to SWITCH_COORD : " + errors ); + } } double SMAC::computeVectorFunction( const Vector& conn, const std::vector& vec1, const std::vector& vec2, Vector& dconn, std::vector& dvec1, std::vector& dvec2 ) const { - unsigned nvectors = ( vec1.size() - 2 ) / 3; plumed_assert( (vec1.size()-2)%3==0 ); - std::vector dv1(nvectors), dv2(nvectors), tdconn(nvectors); Torsion t; std::vector v1(nvectors), v2(nvectors); + unsigned nvectors = ( vec1.size() - 2 ) / 3; + plumed_assert( (vec1.size()-2)%3==0 ); + std::vector dv1(nvectors), dv2(nvectors), tdconn(nvectors); + Torsion t; + std::vector v1(nvectors), v2(nvectors); std::vector> pos; - for(unsigned i=0; i() ); pos[i]->setDomain( "-pi", "pi" ); } + for(unsigned i=0; i() ); + pos[i]->setDomain( "-pi", "pi" ); + } for(unsigned j=0; jset( angle ); @@ -187,20 +206,31 @@ double SMAC::computeVectorFunction( const Vector& conn, const std::vector deriv( nvectors ), df( nvectors, 0 ); + double ans=0; + std::vector deriv( nvectors ), df( nvectors, 0 ); for(unsigned i=0; i0) { switchingFunction.set(sw,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); } log.printf(" Steinhardt parameter of central atom and those within %s\n",( switchingFunction.description() ).c_str() ); log<<" Bibliography "< all_atoms; setupMultiColvarBase( all_atoms ); + rcut = switchingFunction.get_dmax(); + rcut2 = rcut*rcut; + std::vector all_atoms; + setupMultiColvarBase( all_atoms ); } void Steinhardt::setAngularMomentum( const unsigned& ang ) { - tmom=ang; setVectorDimensionality( 2*(2*ang + 1) ); + tmom=ang; + setVectorDimensionality( 2*(2*ang + 1) ); } void Steinhardt::calculateVector( multicolvar::AtomValuePack& myatoms ) const { @@ -76,7 +94,8 @@ void Steinhardt::calculateVector( multicolvar::AtomValuePack& myatoms ) const { std::complex ii( 0.0, 1.0 ), dp_x, dp_y, dp_z; unsigned ncomp=2*tmom+1; - double sw, poly_ass, dlen; std::complex powered; + double sw, poly_ass, dlen; + std::complex powered; for(unsigned i=1; i(1.,0); // else powered = std::complex(0.,0.); // Real and imaginary parts of z - real_z = real(com1*powered); imag_z = imag(com1*powered ); + real_z = real(com1*powered); + imag_z = imag(com1*powered ); // Calculate steinhardt parameter tq6=poly_ass*real_z; // Real part of steinhardt parameter @@ -124,8 +145,12 @@ void Steinhardt::calculateVector( multicolvar::AtomValuePack& myatoms ) const { dp_z = md*powered*( -(distance[0]*distance[2])/dlen3-ii*(distance[1]*distance[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 = (+sw)*dpoly_ass*real_z*dz + (+dfunc)*distance*tq6 + (+sw)*poly_ass*real_dz; @@ -151,21 +176,30 @@ void Steinhardt::calculateVector( multicolvar::AtomValuePack& myatoms ) const { // Normalize updateActiveAtoms( myatoms ); - for(unsigned i=0; iderivativesAreRequired() ) { nder=getAction()->getNumberOfDerivatives(); - resizeBuffer( (1+nder)*(ncomp+1) ); getFinalValue()->resizeDerivatives( nder ); + resizeBuffer( (1+nder)*(ncomp+1) ); + getFinalValue()->resizeDerivatives( nder ); } else { - nder=0; resizeBuffer(ncomp+1); + nder=0; + resizeBuffer(ncomp+1); } } void VectorMean::calculate( const unsigned& current, MultiValue& myvals, std::vector& buffer, std::vector& der_list ) const { unsigned ncomp=getAction()->getNumberOfQuantities()-2; - double weight=myvals.get(0); plumed_dbg_assert( weight>=getTolerance() ); + double weight=myvals.get(0); + plumed_dbg_assert( weight>=getTolerance() ); buffer[bufstart] += weight; - for(unsigned i=0; iderivativesAreRequired() ) return; + for(unsigned i=0; iderivativesAreRequired() ) { + return; + } - if( diffweight ) myvals.chainRule( 0, 0, 1, 0, 1.0, bufstart, buffer ); + if( diffweight ) { + myvals.chainRule( 0, 0, 1, 0, 1.0, bufstart, buffer ); + } for(unsigned i=0; i& buffer ) { sum+=tmp*tmp; } setOutputValue( sqrt(sum) ); - if( !getAction()->derivativesAreRequired() ) return; + if( !getAction()->derivativesAreRequired() ) { + return; + } - Value* fval=getFinalValue(); double tw = 1.0 / sqrt(sum); + Value* fval=getFinalValue(); + double tw = 1.0 / sqrt(sum); for(unsigned icomp=0; icompaddDerivative( jder, (tw*tmp/ww)*( buffer[bstart + jder] - tmp*buffer[bufstart + 1 + jder] ) ); + for(unsigned jder=0; jderaddDerivative( jder, (tw*tmp/ww)*( buffer[bstart + jder] - tmp*buffer[bufstart + 1 + jder] ) ); + } } } diff --git a/src/crystallization/VectorMultiColvar.cpp b/src/crystallization/VectorMultiColvar.cpp index 7c016ac26c..692258edd4 100644 --- a/src/crystallization/VectorMultiColvar.cpp +++ b/src/crystallization/VectorMultiColvar.cpp @@ -49,13 +49,13 @@ void VectorMultiColvar::registerKeywords( Keywords& keys ) { VectorMultiColvar::VectorMultiColvar(const ActionOptions& ao): Action(ao), MultiColvarBase(ao), - store_director(true) -{ + store_director(true) { setLowMemOption(true); } void VectorMultiColvar::setVectorDimensionality( const unsigned& ncomp ) { - ncomponents = ncomp; resizeFunctions(); // This resize needs to be here to ensure buffers are set to correct size in base + ncomponents = ncomp; + resizeFunctions(); // This resize needs to be here to ensure buffers are set to correct size in base } void VectorMultiColvar::doNotCalculateDirector() { @@ -70,17 +70,24 @@ double VectorMultiColvar::compute( const unsigned& taskIndex, multicolvar::AtomV // Now calculate the norm of the vector (this is what we return here) double norm=0; - for(unsigned i=0; i dervec( ncomponents ); - for(unsigned i=0; i dervec( ncomponents ); + for(unsigned i=0; i& vals ) const { double inorm = 1.0; - if( vals[1]>epsilon ) inorm = 1.0 / vals[1]; - for(unsigned i=2; iepsilon ) { + inorm = 1.0 / vals[1]; + } + for(unsigned i=2; i& inforces ) plumed_dbg_assert( inforces.size()==getNumberOfDerivatives() ); std::vector oldforces( getNumberOfDerivatives() ); getForcesFromVessels( oldforces ); - for(unsigned i=0; iderivativesAreRequired() ) { nder=getAction()->getNumberOfDerivatives(); - resizeBuffer( (1+nder)*ncomp ); getFinalValue()->resizeDerivatives( nder ); + resizeBuffer( (1+nder)*ncomp ); + getFinalValue()->resizeDerivatives( nder ); } else { - nder=0; resizeBuffer(ncomp); + nder=0; + resizeBuffer(ncomp); } } @@ -79,13 +80,19 @@ void VectorSum::calculate( const unsigned& current, MultiValue& myvals, std::vec double weight=myvals.get(0); plumed_dbg_assert( weight>=getTolerance() ); - for(unsigned i=0; iderivativesAreRequired() ) return; + for(unsigned i=0; iderivativesAreRequired() ) { + return; + } for(unsigned i=0; i& buffer ) { } double tw = 1.0 / sqrt(sum); setOutputValue( sqrt(sum) ); - if( !getAction()->derivativesAreRequired() ) return; + if( !getAction()->derivativesAreRequired() ) { + return; + } Value* fval=getFinalValue(); for(unsigned icomp=0; icompaddDerivative( jder, tw*tmp*buffer[bstart + jder] ); + for(unsigned jder=0; jderaddDerivative( jder, tw*tmp*buffer[bstart + jder] ); + } } } diff --git a/src/dimred/ClassicalMultiDimensionalScaling.cpp b/src/dimred/ClassicalMultiDimensionalScaling.cpp index 0135ae811e..1713b814ab 100644 --- a/src/dimred/ClassicalMultiDimensionalScaling.cpp +++ b/src/dimred/ClassicalMultiDimensionalScaling.cpp @@ -174,35 +174,51 @@ void ClassicalMultiDimensionalScaling::registerKeywords( Keywords& keys ) { ClassicalMultiDimensionalScaling::ClassicalMultiDimensionalScaling( const ActionOptions& ao): Action(ao), - DimensionalityReductionBase(ao) -{ - if( dimredbase ) error("input to CLASSICAL_MDS should not be output from dimensionality reduction object"); + DimensionalityReductionBase(ao) { + if( dimredbase ) { + error("input to CLASSICAL_MDS should not be output from dimensionality reduction object"); + } } void ClassicalMultiDimensionalScaling::calculateProjections( const Matrix& targets, Matrix& projections ) { // Retrieve the distances from the dimensionality reduction object - double half=(-0.5); Matrix distances( half*targets ); + double half=(-0.5); + Matrix distances( half*targets ); // Apply centering transtion - unsigned n=distances.nrows(); double sum; + unsigned n=distances.nrows(); + double sum; // First HM for(unsigned i=0; i eigval(n); Matrix eigvec(n,n); + std::vector eigval(n); + Matrix eigvec(n,n); diagMat( distances, eigval, eigvec ); // Pass final projections to map object for(unsigned i=0; i( my_input_data ); } @@ -52,25 +53,36 @@ DimensionalityReductionBase::DimensionalityReductionBase( const ActionOptions& a log.printf(" projecting in %u dimensional space \n",nlow); } else if( keywords.exists("NLOW_DIM") ) { parse("NLOW_DIM",nlow); - if( nlow<1 ) error("dimensionality of low dimensional space must be at least one"); + if( nlow<1 ) { + error("dimensionality of low dimensional space must be at least one"); + } log.printf(" projecting in %u dimensional space \n",nlow); } // Now add fake components to the underlying ActionWithValue for the arguments std::string num; for(unsigned i=0; i DimensionalityReductionBase::getArgumentList() { std::vector arglist( analysis::AnalysisBase::getArgumentList() ); - for(unsigned i=0; i& point, double& weight ) { - if( point.size()!=nlow ) point.resize( nlow ); - weight = getWeight(idata); for(unsigned i=0; i newp( nlow ); double w; + std::vector newp( nlow ); + double w; for(unsigned i=0; igetProjection( i, newp, w ); plumed_dbg_assert( newp.size()==nlow ); - for(unsigned j=0; jgetProjection( i, newp, w ); + plumed_dbg_assert( newp.size()==nlow ); + for(unsigned j=0; j targets( getNumberOfDataPoints(), getNumberOfDataPoints() ); targets=0; + Matrix targets( getNumberOfDataPoints(), getNumberOfDataPoints() ); + targets=0; for(unsigned i=1; i& p, std::vector& d ) { // Zero derivative and stress accumulators - for(unsigned i=0; i dtmp( p.size() ); + for(unsigned i=0; i dtmp( p.size() ); // Now accumulate total stress on system for(unsigned i=0; i& // Calculate derivatives double pref = 2.*getWeight(i) / dd; - for(unsigned j=0; j& pp, std::vector& der ); /// Overwrite virtual function in ActionWithVessel - void performTask( const unsigned&, const unsigned&, MultiValue& ) const { plumed_error(); } + void performTask( const unsigned&, const unsigned&, MultiValue& ) const { + plumed_error(); + } }; inline diff --git a/src/dimred/OutputPCAProjections.cpp b/src/dimred/OutputPCAProjections.cpp index 7b8caf60b7..cdb267bc4e 100644 --- a/src/dimred/OutputPCAProjections.cpp +++ b/src/dimred/OutputPCAProjections.cpp @@ -51,7 +51,9 @@ class OutputPCAProjection : public analysis::AnalysisBase { public: static void registerKeywords( Keywords& keys ); explicit OutputPCAProjection( const ActionOptions& ); - void performTask( const unsigned&, const unsigned&, MultiValue& ) const { plumed_error(); } + void performTask( const unsigned&, const unsigned&, MultiValue& ) const { + plumed_error(); + } void performAnalysis(); }; @@ -67,11 +69,12 @@ void OutputPCAProjection::registerKeywords( Keywords& keys ) { OutputPCAProjection::OutputPCAProjection( const ActionOptions& ao ): Action(ao), analysis::AnalysisBase(ao), - fmt("%f") -{ + fmt("%f") { // Setup the PCA object mypca = dynamic_cast( my_input_data ); - if( !mypca ) error("input must be a PCA object"); + if( !mypca ) { + error("input must be a PCA object"); + } // Get setup the pdb mypdb.setAtomNumbers( my_input_data->getAtomIndexes() ); @@ -79,10 +82,18 @@ OutputPCAProjection::OutputPCAProjection( const ActionOptions& ao ): // Find a moldata object auto* moldat=plumed.getActionSet().selectLatest(this); - if( moldat ) warning("PDB output files do not have atom types unless you use MOLDATA"); + if( moldat ) { + warning("PDB output files do not have atom types unless you use MOLDATA"); + } - parse("FILE",filename); parse("FMT",fmt); - if( !getRestart() ) { OFile ofile; ofile.link(*this); ofile.setBackupString("analysis"); ofile.backupAllFiles(filename); } + parse("FILE",filename); + parse("FMT",fmt); + if( !getRestart() ) { + OFile ofile; + ofile.link(*this); + ofile.setBackupString("analysis"); + ofile.backupAllFiles(filename); + } log.printf(" printing data to file named %s \n",filename.c_str() ); } @@ -90,20 +101,33 @@ void OutputPCAProjection::performAnalysis() { // Find a moldata object auto* mymoldat=plumed.getActionSet().selectLatest(this); // Output the embedding in plumed pdb format - OFile afile; afile.link(*this); afile.setBackupString("analysis"); + OFile afile; + afile.link(*this); + afile.setBackupString("analysis"); mypdb.setAtomPositions( (mypca->myref)->getReferencePositions() ); - for(unsigned j=0; jgetArguments().size(); ++j) mypdb.setArgumentValue( (mypca->getArguments()[j])->getName(), (mypca->myref)->getReferenceArgument(j) ); + for(unsigned j=0; jgetArguments().size(); ++j) { + mypdb.setArgumentValue( (mypca->getArguments()[j])->getName(), (mypca->myref)->getReferenceArgument(j) ); + } // And output the first frame - afile.open( filename ); afile.printf("REMARK TYPE=%s \n", mypca->mtype.c_str() ); - if( plumed.getAtoms().usingNaturalUnits() ) mypdb.print( 1.0, mymoldat, afile, fmt ); - else mypdb.print( atoms.getUnits().getLength()/0.1, mymoldat, afile, fmt ); + afile.open( filename ); + afile.printf("REMARK TYPE=%s \n", mypca->mtype.c_str() ); + if( plumed.getAtoms().usingNaturalUnits() ) { + mypdb.print( 1.0, mymoldat, afile, fmt ); + } else { + mypdb.print( atoms.getUnits().getLength()/0.1, mymoldat, afile, fmt ); + } // And now output the eigenvectors for(unsigned dim=0; dimnlow; ++dim) { afile.printf("REMARK TYPE=DIRECTION \n"); mypdb.setAtomPositions( mypca->directions[dim].getReferencePositions() ); - for(unsigned j=0; jgetArguments().size(); ++j) mypdb.setArgumentValue( (mypca->getArguments()[j])->getName(), mypca->directions[dim].getReferenceArgument(j) ); - if( plumed.getAtoms().usingNaturalUnits() ) mypdb.print( 1.0, mymoldat, afile, fmt ); - else mypdb.print( atoms.getUnits().getLength()/0.1, mymoldat, afile, fmt ); + for(unsigned j=0; jgetArguments().size(); ++j) { + mypdb.setArgumentValue( (mypca->getArguments()[j])->getName(), mypca->directions[dim].getReferenceArgument(j) ); + } + if( plumed.getAtoms().usingNaturalUnits() ) { + mypdb.print( 1.0, mymoldat, afile, fmt ); + } else { + mypdb.print( atoms.getUnits().getLength()/0.1, mymoldat, afile, fmt ); + } } afile.close(); } diff --git a/src/dimred/PCA.cpp b/src/dimred/PCA.cpp index d7bcf24191..1e9750f80d 100644 --- a/src/dimred/PCA.cpp +++ b/src/dimred/PCA.cpp @@ -100,19 +100,23 @@ namespace dimred { PLUMED_REGISTER_ACTION(PCA,"PCA") void PCA::registerKeywords( Keywords& keys ) { - DimensionalityReductionBase::registerKeywords( keys ); keys.use("ARG"); keys.reset_style("ARG","optional"); + DimensionalityReductionBase::registerKeywords( keys ); + keys.use("ARG"); + keys.reset_style("ARG","optional"); keys.add("compulsory","METRIC","EUCLIDEAN","the method that you are going to use to measure the distances between points"); keys.add("atoms","ATOMS","the list of atoms that you are going to use in the measure of distance that you are using"); } PCA::PCA(const ActionOptions&ao): Action(ao), - DimensionalityReductionBase(ao) -{ + DimensionalityReductionBase(ao) { // Get the input PDB file from the underlying ReadAnalysisFrames object analysis::ReadAnalysisFrames* myframes = dynamic_cast( my_input_data ); - if( !myframes ) error("input to PCA should be ReadAnalysisFrames object"); - parse("METRIC",mtype); std::vector atoms; + if( !myframes ) { + error("input to PCA should be ReadAnalysisFrames object"); + } + parse("METRIC",mtype); + std::vector atoms; log.printf(" performing PCA analysis using %s metric \n", mtype.c_str() ); if( my_input_data->getNumberOfAtoms()>0 ) { parseAtomList("ATOMS",atoms); @@ -121,10 +125,14 @@ PCA::PCA(const ActionOptions&ao): for(unsigned i=0; igetAtomIndexes().size(); ++j) { - if( my_input_data->getAtomIndexes()[j]==atoms[i] ) { found=true; break; } + if( my_input_data->getAtomIndexes()[j]==atoms[i] ) { + found=true; + break; + } } if( !found ) { - std::string num; Tools::convert( atoms[i].serial(), num ); + std::string num; + Tools::convert( atoms[i].serial(), num ); error("atom number " + num + " is not stored in any action that has been input"); } } @@ -132,13 +140,16 @@ PCA::PCA(const ActionOptions&ao): } else if( getNumberOfArguments()==0 ) { mypdb.setAtomNumbers( my_input_data->getAtomIndexes() ); mypdb.addBlockEnd( my_input_data->getAtomIndexes().size() ); - if( mtype=="EUCLIDEAN" ) mtype="OPTIMAL"; + if( mtype=="EUCLIDEAN" ) { + mtype="OPTIMAL"; + } } } if( my_input_data->getArgumentNames().size()>0 ) { if( getNumberOfArguments()==0 && atoms.size()==0 ) { std::vector argnames( my_input_data->getArgumentNames() ); - mypdb.setArgumentNames( argnames ); requestArguments( my_input_data->getArgumentList() ); + mypdb.setArgumentNames( argnames ); + requestArguments( my_input_data->getArgumentList() ); } else { std::vector myargs( getArguments() ); std::vector inargnames( my_input_data->getArgumentNames() ); @@ -147,14 +158,22 @@ PCA::PCA(const ActionOptions&ao): argnames[i]=myargs[i]->getName(); bool found=false; for(unsigned j=0; jgetLabel() + " does not store/calculate quantity named " + argnames[i] ); } - if( !found ) error("input named " + my_input_data->getLabel() + " does not store/calculate quantity named " + argnames[i] ); } - mypdb.setArgumentNames( argnames ); requestArguments( myargs ); + mypdb.setArgumentNames( argnames ); + requestArguments( myargs ); } } - if( nlow==0 ) error("dimensionality of output not set"); + if( nlow==0 ) { + error("dimensionality of output not set"); + } checkRead(); } @@ -164,7 +183,9 @@ void PCA::performAnalysis() { auto myconf0=metricRegister().create(mtype, mypdb); MultiValue myval( 1, myconf0->getNumberOfReferenceArguments() + 3*myconf0->getNumberOfReferencePositions() + 9 ); ReferenceValuePack mypack( myconf0->getNumberOfReferenceArguments(), myconf0->getNumberOfReferencePositions(), myval ); - for(unsigned i=0; igetNumberOfReferencePositions(); ++i) mypack.setAtomIndex( i, i ); + for(unsigned i=0; igetNumberOfReferencePositions(); ++i) { + mypack.setAtomIndex( i, i ); + } // Setup some PCA storage myconf0->setupPCAStorage ( mypack ); std::vector displace( myconf0->getNumberOfReferencePositions() ); @@ -176,30 +197,46 @@ void PCA::performAnalysis() { // Create some arrays to store the average position std::vector sarg( myconf0->getNumberOfReferenceArguments(), 0 ); std::vector spos( myconf0->getNumberOfReferencePositions() ); - for(unsigned i=0; igetNumberOfReferencePositions(); ++i) spos[i].zero(); + for(unsigned i=0; igetNumberOfReferencePositions(); ++i) { + spos[i].zero(); + } // Calculate the average displacement from the first frame - double norm=getWeight(0); std::vector args( getNumberOfArguments() ); + double norm=getWeight(0); + std::vector args( getNumberOfArguments() ); for(unsigned i=1; igetStoredData( i, false ).transferDataToPDB( mypdb ); - for(unsigned j=0; jgetName(), args[j] ); + for(unsigned j=0; jgetName(), args[j] ); + } myconf0->calc( mypdb.getPositions(), getPbc(), getArguments(), args, mypack, true ); // Accumulate average displacement of arguments (Here PBC could do fucked up things - really needs Berry Phase ) GAT - for(unsigned j=0; jgetNumberOfReferenceArguments(); ++j) sarg[j] += 0.5*getWeight(i)*mypack.getArgumentDerivative(j); + for(unsigned j=0; jgetNumberOfReferenceArguments(); ++j) { + sarg[j] += 0.5*getWeight(i)*mypack.getArgumentDerivative(j); + } // Accumulate average displacement of position - for(unsigned j=0; jgetNumberOfReferencePositions(); ++j) spos[j] += getWeight(i)*mypack.getAtomsDisplacementVector()[j] / displace[j]; + for(unsigned j=0; jgetNumberOfReferencePositions(); ++j) { + spos[j] += getWeight(i)*mypack.getAtomsDisplacementVector()[j] / displace[j]; + } norm += getWeight(i); } // Now normalise the displacements to get the average and add these to the first frame double inorm = 1.0 / norm ; - for(unsigned j=0; jgetNumberOfReferenceArguments(); ++j) sarg[j] = inorm*sarg[j] + myconf0->getReferenceArguments()[j]; - for(unsigned j=0; jgetNumberOfReferencePositions(); ++j) spos[j] = inorm*spos[j] + myconf0->getReferencePositions()[j]; + for(unsigned j=0; jgetNumberOfReferenceArguments(); ++j) { + sarg[j] = inorm*sarg[j] + myconf0->getReferenceArguments()[j]; + } + for(unsigned j=0; jgetNumberOfReferencePositions(); ++j) { + spos[j] = inorm*spos[j] + myconf0->getReferencePositions()[j]; + } // Now accumulate the covariance unsigned narg=myconf0->getNumberOfReferenceArguments(), natoms=myconf0->getNumberOfReferencePositions(); - Matrix covar( narg+3*natoms, narg+3*natoms ); covar=0; + Matrix covar( narg+3*natoms, narg+3*natoms ); + covar=0; for(unsigned i=0; igetStoredData( i, false ).transferDataToPDB( mypdb ); - for(unsigned j=0; jgetName(), args[j] ); + for(unsigned j=0; jgetName(), args[j] ); + } myconf0->calc( mypdb.getPositions(), getPbc(), getArguments(), args, mypack, true ); for(unsigned jarg=0; jarggetName(), sarg[j] ); + for(unsigned j=0; jgetName(), sarg[j] ); + } // Reset the reference configuration myref = metricRegister().create( mtype, mypdb ); @@ -242,9 +283,13 @@ void PCA::performAnalysis() { std::vector tmp_atoms( natoms ); for(unsigned dim=0; dimgetName(), eigvec(idim,i) ); + for(unsigned i=0; igetName(), eigvec(idim,i) ); + } for(unsigned i=0; i& point, double& weight ) { - if( point.size()!=nlow ) point.resize( nlow ); + if( point.size()!=nlow ) { + point.resize( nlow ); + } // Retrieve the weight weight = getWeight(idata); // Retrieve the data point @@ -262,16 +309,23 @@ void PCA::getProjection( const unsigned& idata, std::vector& point, doub } void PCA::getProjection( analysis::DataCollectionObject& myidata, std::vector& point ) { - myidata.transferDataToPDB( mypdb ); std::vector args( getArguments().size() ); - for(unsigned j=0; jgetName(), args[j] ); + myidata.transferDataToPDB( mypdb ); + std::vector args( getArguments().size() ); + for(unsigned j=0; jgetName(), args[j] ); + } // Create some storage space MultiValue myval( 1, 3*mypdb.getPositions().size() + args.size() + 9); ReferenceValuePack mypack( args.size(), mypdb.getPositions().size(), myval ); - for(unsigned i=0; isetupPCAStorage( mypack ); // And calculate myref->calculate( mypdb.getPositions(), getPbc(), getArguments(), mypack, true ); - for(unsigned i=0; iprojectDisplacementOnVector( directions[i], getArguments(), args, mypack ); + for(unsigned i=0; iprojectDisplacementOnVector( directions[i], getArguments(), args, mypack ); + } } } diff --git a/src/dimred/PCA.h b/src/dimred/PCA.h index cba38049a3..c232848c5b 100644 --- a/src/dimred/PCA.h +++ b/src/dimred/PCA.h @@ -48,9 +48,15 @@ class PCA : public DimensionalityReductionBase { void performAnalysis() override; void getProjection( const unsigned& idata, std::vector& point, double& weight ) override; void getProjection( analysis::DataCollectionObject& myidata, std::vector& point ); - void calculateProjections( const Matrix&, Matrix& ) override { plumed_error(); } - void setTargetDistance( const unsigned&, const double& ) override { plumed_error(); } - double calculateStress( const std::vector& pp, std::vector& der ) override { plumed_error(); } + void calculateProjections( const Matrix&, Matrix& ) override { + plumed_error(); + } + void setTargetDistance( const unsigned&, const double& ) override { + plumed_error(); + } + double calculateStress( const std::vector& pp, std::vector& der ) override { + plumed_error(); + } }; } diff --git a/src/dimred/ProjectNonLandmarkPoints.cpp b/src/dimred/ProjectNonLandmarkPoints.cpp index 4c71fa42a3..a17eb66768 100644 --- a/src/dimred/ProjectNonLandmarkPoints.cpp +++ b/src/dimred/ProjectNonLandmarkPoints.cpp @@ -63,7 +63,9 @@ class ProjectNonLandmarkPoints : public analysis::AnalysisBase { /// This just calls calculate stress in the underlying projection object double calculateStress( const std::vector& pp, std::vector& der ); /// Overwrite virtual function in ActionWithVessel - void performTask( const unsigned&, const unsigned&, MultiValue& ) const { plumed_error(); } + void performTask( const unsigned&, const unsigned&, MultiValue& ) const { + plumed_error(); + } }; PLUMED_REGISTER_ACTION(ProjectNonLandmarkPoints,"PROJECT_ALL_ANALYSIS_DATA") @@ -78,17 +80,22 @@ void ProjectNonLandmarkPoints::registerKeywords( Keywords& keys ) { ProjectNonLandmarkPoints::ProjectNonLandmarkPoints( const ActionOptions& ao ): Action(ao), analysis::AnalysisBase(ao), - mybase(NULL) -{ - std::string myproj; parse("PROJECTION",myproj); + mybase(NULL) { + std::string myproj; + parse("PROJECTION",myproj); mybase = plumed.getActionSet().selectWithLabel( myproj ); - if( !mybase ) error("could not find projection of data named " + myproj ); + if( !mybase ) { + error("could not find projection of data named " + myproj ); + } // Add the dependency and set the dimensionality - addDependency( mybase ); nlow = mybase->nlow; + addDependency( mybase ); + nlow = mybase->nlow; // Add fake components to the underlying ActionWithValue for the arguments std::string num; for(unsigned i=0; i ProjectNonLandmarkPoints::getArgumentList() { std::vector arglist( analysis::AnalysisBase::getArgumentList() ); - for(unsigned i=0; igetProjection( my_input_data->getStoredData(idat,false), point ); } else { ConjugateGradient myminimiser( this ); - unsigned closest=0; double mindist = std::sqrt( getDissimilarity( mybase->getDataPointIndexInBase(0), idat ) ); + unsigned closest=0; + double mindist = std::sqrt( getDissimilarity( mybase->getDataPointIndexInBase(0), idat ) ); mybase->setTargetDistance( 0, mindist ); for(unsigned i=1; igetNumberOfDataPoints(); ++i) { double dist = std::sqrt( getDissimilarity( mybase->getDataPointIndexInBase(i), idat ) ); mybase->setTargetDistance( i, dist ); - if( distprojections(closest,j) + (random.RandU01() - 0.5)*0.01; + Random random; + random.setSeed(-1234); + for(unsigned j=0; jprojections(closest,j) + (random.RandU01() - 0.5)*0.01; + } myminimiser.minimise( cgtol, point, &ProjectNonLandmarkPoints::calculateStress ); } } analysis::DataCollectionObject& ProjectNonLandmarkPoints::getStoredData( const unsigned& idat, const bool& calcdist ) { - std::vector pp(nlow); generateProjection( idat, pp ); std::string num; + std::vector pp(nlow); + generateProjection( idat, pp ); + std::string num; analysis::DataCollectionObject& myref=AnalysisBase::getStoredData(idat,calcdist); - for(unsigned i=0; i& Weights, const Matrix& Distances unsigned M = Distances.nrows(); // Calculate V - Matrix V(M,M); double totalWeight=0.; + Matrix V(M,M); + double totalWeight=0.; for(unsigned i=0; i mypseudo(M, M); pseudoInvert(V, mypseudo); - Matrix dists( M, M ); double myfirstsig = calculateSigma( Weights, Distances, InitialZ, dists ) / totalWeight; + Matrix mypseudo(M, M); + pseudoInvert(V, mypseudo); + Matrix dists( M, M ); + double myfirstsig = calculateSigma( Weights, Distances, InitialZ, dists ) / totalWeight; // 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, InitialZ.ncols() ); for(unsigned n=0; n0 ) BZ(i,j) = -Weights(i,j)*Distances(i,j) / dists(i,j); - else BZ(i,j)=0.; + 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& Weights, const Matrix& Distances, const Matrix& InitialZ, Matrix& dists ) { - unsigned M = Distances.nrows(); double sigma=0; + unsigned M = Distances.nrows(); + double sigma=0; for(unsigned i=1; i1 ) { - double smear; parse("ANNEAL_RATE", smear); double old_mix = 1.0; double new_mix = old_mix*smear; + double smear; + parse("ANNEAL_RATE", smear); + double old_mix = 1.0; + double new_mix = old_mix*smear; for(unsigned i=0; i( dimredbase ); + if( dimredbase ) { + smapbase = dynamic_cast( dimredbase ); + } // Read in the switching functions std::string linput,hinput, errors; parse("HIGH_DIM_FUNCTION",hinput); if( hinput=="as in input action" ) { - if( !smapbase ) error("high dimensional switching function has not been set - use HIGH_DIM_FUNCTION"); + if( !smapbase ) { + error("high dimensional switching function has not been set - use HIGH_DIM_FUNCTION"); + } reuse_hd=true; log.printf(" reusing high dimensional filter function defined in previous sketch-map action\n"); } else { reuse_hd=false; highdf.set(hinput,errors); - if(errors.length()>0) error(errors); + if(errors.length()>0) { + error(errors); + } log.printf(" filter function for dissimilarities in high dimensional space has cutoff %s \n",highdf.description().c_str() ); } parse("LOW_DIM_FUNCTION",linput); if( linput=="as in input action" ) { - if( !smapbase ) error("low dimensional switching function has not been set - use LOW_DIM_FUNCTION"); + if( !smapbase ) { + error("low dimensional switching function has not been set - use LOW_DIM_FUNCTION"); + } reuse_ld=true; log.printf(" reusing low dimensional filter function defined in previous sketch-map action\n"); } else { reuse_ld=false; lowdf.set(linput,errors); - if(errors.length()>0) error(errors); + if(errors.length()>0) { + error(errors); + } log.printf(" filter function for distances in low dimensionality space has cutoff %s \n",lowdf.description().c_str() ); } // Read the mixing parameter parse("MIXPARAM",mixparam); - if( mixparam<0 || mixparam>1 ) error("mixing parameter must be between 0 and 1"); + if( mixparam<0 || mixparam>1 ) { + error("mixing parameter must be between 0 and 1"); + } log.printf(" mixing %f of pure distances with %f of filtered distances \n",mixparam,1.-mixparam); } void SketchMapBase::calculateProjections( const Matrix& targets, Matrix& projections ) { if( dtargets.size()!=targets.nrows() ) { // These hold data so that we can do stress calculations - dtargets.resize( targets.nrows() ); ftargets.resize( targets.nrows() ); pweights.resize( targets.nrows() ); + dtargets.resize( targets.nrows() ); + ftargets.resize( targets.nrows() ); + pweights.resize( targets.nrows() ); // Matrices for storing input data transformed.resize( targets.nrows(), targets.ncols() ); distances.resize( targets.nrows(), targets.ncols() ); @@ -84,11 +97,16 @@ void SketchMapBase::calculateProjections( const Matrix& targets, Matrix< // Stores the weights in an array for faster access, as well as the normalization normw=0; - for(unsigned i=0; i& targets, Matrix< double SketchMapBase::calculateStress( const std::vector& p, std::vector& d ) { // Zero derivative and stress accumulators - for(unsigned i=0; i dtmp( p.size() ); + for(unsigned i=0; i dtmp( p.size() ); // Now accumulate total stress on system for(unsigned i=0; i& p, std::vector // Calculate derivatives double pref = 2.*getWeight(i) / dd ; - for(unsigned j=0; j& p, std::vector double SketchMapBase::calculateFullStress( const std::vector& p, std::vector& d ) { // Zero derivative and stress accumulators - for(unsigned i=0; i dtmp( nlow ); + for(unsigned i=0; i dtmp( nlow ); for(unsigned i=1; i& p, std::ve double jweight = pweights[j]; // Calculate distance in low dimensional space double dd=0; - for(unsigned k=0; k& p, std::ve // Calculate derivatives double pref = 2.*iweight*jweight*( (1-mixparam)*fdiff*df + mixparam*ddiff ) / dd; for(unsigned k=0; ktransformLowDimensionalDistance( val, df ); - double ans=1.0 - lowdf.calculate( val, df ); df*=-val; return ans; + if( reuse_ld ) { + return smapbase->transformLowDimensionalDistance( val, df ); + } + double ans=1.0 - lowdf.calculate( val, df ); + df*=-val; + return ans; } inline double SketchMapBase::transformHighDimensionalDistance( const double& val, double& df ) const { - if( reuse_hd ) return smapbase->transformHighDimensionalDistance( val, df ); - double ans=1.0 - highdf.calculate( val, df ); df*=-val; return ans; + if( reuse_hd ) { + return smapbase->transformHighDimensionalDistance( val, df ); + } + double ans=1.0 - highdf.calculate( val, df ); + df*=-val; + return ans; } inline void SketchMapBase::setTargetDistance( const unsigned& idata, const double& dist ) { - double df; dtargets[idata]=dist; ftargets[idata]=transformHighDimensionalDistance( dist, df ); + double df; + dtargets[idata]=dist; + ftargets[idata]=transformHighDimensionalDistance( dist, df ); } } diff --git a/src/dimred/SketchMapConjGrad.cpp b/src/dimred/SketchMapConjGrad.cpp index b336e49f1a..65192612ca 100644 --- a/src/dimred/SketchMapConjGrad.cpp +++ b/src/dimred/SketchMapConjGrad.cpp @@ -53,8 +53,7 @@ void SketchMapConjGrad::registerKeywords( Keywords& keys ) { SketchMapConjGrad::SketchMapConjGrad( const ActionOptions& ao ): Action(ao), - SketchMapBase(ao) -{ + SketchMapBase(ao) { parse("CGTOL",cgtol); log.printf(" tolerance for conjugate gradient algorithm equals %f \n",cgtol); } diff --git a/src/dimred/SketchMapPointwise.cpp b/src/dimred/SketchMapPointwise.cpp index 3cc80639d2..4bd1777741 100644 --- a/src/dimred/SketchMapPointwise.cpp +++ b/src/dimred/SketchMapPointwise.cpp @@ -62,22 +62,31 @@ SketchMapPointwise::SketchMapPointwise( const ActionOptions& ao ): Action(ao), SketchMapBase(ao), npoints(nlow), - nfgrid(nlow) -{ - parseVector("CGRID_SIZE",npoints); parse("BUFFER",gbuf); - if( npoints.size()!=nlow ) error("vector giving number of grid point in each direction has wrong size"); - parse("NCYCLES",ncycles); parse("CGTOL",cgtol); + nfgrid(nlow) { + parseVector("CGRID_SIZE",npoints); + parse("BUFFER",gbuf); + if( npoints.size()!=nlow ) { + error("vector giving number of grid point in each direction has wrong size"); + } + parse("NCYCLES",ncycles); + parse("CGTOL",cgtol); parseVector("FGRID_SIZE",nfgrid); - if( nfgrid[0]!=0 && nlow!=2 ) error("interpolation only works in two dimensions"); + if( nfgrid[0]!=0 && nlow!=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]); log.printf(" and that is %f larger than the difference between the position of the minimum and maximum projection \n",gbuf); - for(unsigned j=1; j0 ) { log.printf(" interpolating stress onto grid of points that is %u",nfgrid[0]); - for(unsigned j=1; j& projections ) { std::vector gmin( nlow ), gmax( nlow ), mypoint( nlow ); // Find the extent of the grid - for(unsigned j=0; j gmax[j] ) gmax[j] = projections(i,j); + if( projections(i,j) < gmin[j] ) { + gmin[j] = projections(i,j); + } + if( projections(i,j) > gmax[j] ) { + gmax[j] = projections(i,j); + } } } for(unsigned j=0; j& projections ) { for(unsigned i=0; i propnames; parseVector("PROPERTY",propnames); - if(propnames.size()==0) error("no properties were specified"); + SketchMapBase(ao) { + std::vector propnames; + parseVector("PROPERTY",propnames); + if(propnames.size()==0) { + error("no properties were specified"); + } nlow=propnames.size(); for(unsigned i=0; i >( propnames[i], std::vector() ) ); } log.printf(" mapped properties are %s ",propnames[0].c_str() ); - for(unsigned i=1; ifopen(ifilename.c_str(),"r"); - if(!fp) error("could not open reference file " + ifilename ); + if(!fp) { + error("could not open reference file " + ifilename ); + } // call fclose when fp goes out of scope - auto deleter=[this](FILE* f) { this->fclose(f); }; + auto deleter=[this](FILE* f) { + this->fclose(f); + }; std::unique_ptr fp_deleter(fp,deleter); // Read in the embedding - bool do_read=true; double val, ww, wnorm=0, prop; unsigned nfram=0; + bool do_read=true; + double val, ww, wnorm=0, prop; + unsigned nfram=0; while (do_read) { PDB inpdb; // Read the pdb file do_read=inpdb.readFromFilepointer(fp,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()); // Break if we are done - if( !do_read ) break ; + if( !do_read ) { + break ; + } // Check for required properties for(std::map >::iterator it=property.begin(); it!=property.end(); ++it) { - if( !inpdb.getArgumentValue( it->first, prop ) ) error("pdb input does not have contain property named " + it->first ); + if( !inpdb.getArgumentValue( it->first, prop ) ) { + error("pdb input does not have contain property named " + it->first ); + } it->second.push_back(prop); } // And read the frame ( create a measure ) myframes.emplace_back( metricRegister().create( mtype, inpdb ) ); - if( !inpdb.getArgumentValue( "WEIGHT", ww ) ) error("could not find weights in input pdb"); - weights.push_back( ww ); wnorm += ww; nfram++; + if( !inpdb.getArgumentValue( "WEIGHT", ww ) ) { + error("could not find weights in input pdb"); + } + weights.push_back( ww ); + wnorm += ww; + nfram++; // And create a data collection object - analysis::DataCollectionObject new_data; new_data.setAtomNumbersAndArgumentNames( getLabel(), inpdb.getAtomNumbers(), inpdb.getArgumentNames() ); + analysis::DataCollectionObject new_data; + new_data.setAtomNumbersAndArgumentNames( getLabel(), inpdb.getAtomNumbers(), inpdb.getArgumentNames() ); new_data.setAtomPositions( inpdb.getPositions() ); for(unsigned i=0; i atoms; std::vector args; - for(unsigned i=0; igetAtomRequests( atoms, skipchecks ); myframes[i]->getArgumentRequests( args, skipchecks ); } - requestAtoms( atoms ); std::vector req_args; std::vector fargs; + std::vector atoms; + std::vector args; + for(unsigned i=0; igetAtomRequests( atoms, skipchecks ); + myframes[i]->getArgumentRequests( args, skipchecks ); + } + requestAtoms( atoms ); + std::vector req_args; + std::vector fargs; for(unsigned i=0; i >::iterator it=property.begin(); it!=property.end(); ++it) { - if( args[i]==it->first ) { found=true; break; } + if( args[i]==it->first ) { + found=true; + break; + } + } + if( !found ) { + fargs.push_back( args[i] ); } - if( !found ) { fargs.push_back( args[i] ); } } - interpretArgumentList( fargs, req_args ); mypdb.setArgumentNames( fargs ); requestArguments( req_args ); + interpretArgumentList( fargs, req_args ); + mypdb.setArgumentNames( fargs ); + requestArguments( req_args ); - if(nfram==0 ) error("no reference configurations were specified"); + if(nfram==0 ) { + error("no reference configurations were specified"); + } log.printf(" found %u configurations in file %s\n",nfram,ifilename.c_str() ); } void SketchMapRead::minimise( Matrix& projections ) { unsigned j=0; for(std::map >::iterator it=property.begin(); it!=property.end(); ++it) { - for(unsigned i=0; isecond[i]; + for(unsigned i=0; isecond[i]; + } j++; } } @@ -169,7 +217,9 @@ unsigned SketchMapRead::getDataPointIndexInBase( const unsigned& idata ) const { std::vector SketchMapRead::getArgumentList() { std::vector arglist( ActionWithArguments::getArguments() ); - for(unsigned i=0; i& projections ) { - Matrix weights( distances.nrows(), distances.ncols() ); weights=0.; + Matrix weights( distances.nrows(), distances.ncols() ); + weights=0.; double filt = recalculateWeights( projections, weights ); for(unsigned i=0; i& projections ) { // Recalculate weights matrix and sigma double newsig = recalculateWeights( projections, weights ); // Test whether or not the algorithm has converged - if( std::fabs( newsig - filt )& projections, Matrix& weights ) { - double filt=0, totalWeight=0.;; double dr; + double filt=0, totalWeight=0.;; + double dr; for(unsigned i=1; i& projections, M double filter=transformed(i,j)-fij; double diff=distances(i,j) - dij; - if( std::fabs(diff) max) + if (x < min || x > max) { return false; - else + } else { return true; + } } bool DRRAxis::isRealPeriodic() const { @@ -79,13 +80,16 @@ void DRRForceGrid::fillTable(const vector> &in) { table.resize(ndims, vector(sampleSize, 0)); for (size_t i = 0; i < ndims; ++i) { size_t repeatAll = 1, repeatOne = 1; - for (size_t j = i + 1; j < ndims; ++j) + for (size_t j = i + 1; j < ndims; ++j) { repeatOne *= in[j].size(); - for (size_t j = 0; j < i; ++j) + } + for (size_t j = 0; j < i; ++j) { repeatAll *= in[j].size(); + } size_t in_i_sz = in[i].size(); - for (size_t l = 0; l < in_i_sz; ++l) + for (size_t l = 0; l < in_i_sz; ++l) { std::fill_n(begin(table[i]) + l * repeatOne, repeatOne, in[i][l]); + } for (size_t k = 0; k < repeatAll - 1; ++k) std::copy_n(begin(table[i]), repeatOne * in_i_sz, begin(table[i]) + repeatOne * in_i_sz * (k + 1)); @@ -115,14 +119,16 @@ DRRForceGrid::DRRForceGrid(const vector &p_dimensions, 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'; + } } headers = ss.str(); - if (initializeTable) + if (initializeTable) { fillTable(mp); + } forces.resize(sampleSize * ndims, 0.0); samples.resize(sampleSize, 0); outputunit = 1.0; @@ -141,8 +147,9 @@ DRRForceGrid::DRRForceGrid(const vector &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; } @@ -477,8 +489,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 6db4de7c4b..6c789f1ad0 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 7a500964c3..7f39752813 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'; @@ -427,9 +426,9 @@ DynamicReferenceRestraining::DynamicReferenceRestraining( withExternalFict = true; } } - if (temp >= 0.0) + if (temp >= 0.0) { kbt = plumed.getAtoms().getKBoltzmann() * temp; - else { + } else { kbt = plumed.getAtoms().getKbT(); if (kbt <= std::numeric_limits::epsilon()) { error("eABF/DRR: It seems the MD engine does not setup the temperature correctly for PLUMED." @@ -459,8 +458,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."; @@ -470,8 +470,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."; @@ -619,8 +620,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 bbc74a0b12..18ebbb1c73 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, std::vector x, std::vector y) - { + bool update(const int step, 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(9) << loop_flag[i] + 0.5 * width[i] << " "; ofile_hist << std::fixed << std::setprecision(9) << loop_flag[i] + 0.5 * width[i] << " "; ofile_count << std::fixed << std::setprecision(9) << 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(9) << grad.get_value(loop_flag)[i] << " "; ofile_hist << std::fixed << std::setprecision(9) << 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 62c574dcd3..b50589a76e 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); - string description() const { return "Extract or merge the drrstate files."; } + string description() const { + return "Extract or merge the drrstate files."; + } private: bool verbosity; @@ -161,11 +163,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); } @@ -208,9 +212,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), - [&](string s) {return s.substr(0, s.find(suffix));}); + [&](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 700b746bf7..eaf352aa5c 100644 --- a/src/eds/EDS.cpp +++ b/src/eds/EDS.cpp @@ -32,10 +32,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 /* @@ -193,8 +191,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*/ @@ -279,8 +276,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"); @@ -360,8 +356,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; @@ -370,8 +365,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); @@ -409,70 +403,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_); @@ -482,36 +466,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"); @@ -519,28 +501,24 @@ 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 { - if (temp >= 0.0) + if (temp >= 0.0) { kbt_ = plumed.getAtoms().getKBoltzmann() * temp; - else + } else { kbt_ = plumed.getAtoms().getKbT(); + } // 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."); @@ -550,19 +528,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()); @@ -570,8 +543,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 @@ -580,79 +552,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(); @@ -662,53 +623,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_); } @@ -718,11 +665,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]); @@ -732,12 +677,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); @@ -750,54 +695,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_); @@ -809,13 +753,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]); @@ -825,34 +767,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; @@ -865,17 +807,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; @@ -884,27 +823,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 @@ -912,43 +846,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]; } @@ -958,51 +890,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->modifyVirial()); 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 @@ -1020,10 +947,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]; } @@ -1032,35 +960,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]); @@ -1070,9 +998,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; } @@ -1082,59 +1008,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; } @@ -1142,15 +1060,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_++; @@ -1158,19 +1074,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/fisst/FISST.cpp b/src/fisst/FISST.cpp index 70bcfd124f..fb330b003c 100644 --- a/src/fisst/FISST.cpp +++ b/src/fisst/FISST.cpp @@ -222,14 +222,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"); @@ -260,8 +261,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; @@ -269,8 +271,9 @@ FISST::FISST(const ActionOptions&ao): readInRestart(); } else { - if(! kbt_ > 0.0) + if(! kbt_ > 0.0) { kbt_ = plumed.getAtoms().getKbT(); + } //in driver, this results in kbt of 0 if(kbt_ == 0) { @@ -288,7 +291,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(); @@ -351,11 +361,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_); } @@ -500,16 +524,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(); } } @@ -518,7 +545,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_) { @@ -559,16 +588,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 coefficients; std::vector parameters; @@ -91,7 +90,8 @@ PLUMED_REGISTER_ACTION(Combine,"COMBINE") void Combine::registerKeywords(Keywords& keys) { Function::registerKeywords(keys); - keys.use("ARG"); keys.use("PERIODIC"); + keys.use("ARG"); + keys.use("PERIODIC"); keys.add("compulsory","COEFFICIENTS","1.0","the coefficients of the arguments in your function"); keys.add("compulsory","PARAMETERS","0.0","the parameters of the arguments in your function"); keys.add("compulsory","POWERS","1.0","the powers to which you are raising each of the arguments in your function"); @@ -104,39 +104,51 @@ Combine::Combine(const ActionOptions&ao): normalize(false), coefficients(getNumberOfArguments(),1.0), parameters(getNumberOfArguments(),0.0), - powers(getNumberOfArguments(),1.0) -{ + powers(getNumberOfArguments(),1.0) { parseVector("COEFFICIENTS",coefficients); - if(coefficients.size()!=static_cast(getNumberOfArguments())) + if(coefficients.size()!=static_cast(getNumberOfArguments())) { error("Size of COEFFICIENTS array should be the same as number for arguments"); + } parseVector("PARAMETERS",parameters); - if(parameters.size()!=static_cast(getNumberOfArguments())) + if(parameters.size()!=static_cast(getNumberOfArguments())) { error("Size of PARAMETERS array should be the same as number for arguments"); + } parseVector("POWERS",powers); - if(powers.size()!=static_cast(getNumberOfArguments())) + if(powers.size()!=static_cast(getNumberOfArguments())) { error("Size of POWERS array should be the same as number for arguments"); + } parseFlag("NORMALIZE",normalize); if(normalize) { double n=0.0; - for(unsigned i=0; i expression_deriv; std::vector var; @@ -212,7 +211,8 @@ PLUMED_REGISTER_ACTION(Custom,"MATHEVAL") void Custom::registerKeywords(Keywords& keys) { Function::registerKeywords(keys); - keys.use("ARG"); keys.use("PERIODIC"); + keys.use("ARG"); + keys.use("PERIODIC"); keys.add("compulsory","FUNC","the function you wish to evaluate"); keys.add("optional","VAR","the names to give each of the arguments in the function. If you have up to three arguments in your function you can use x, y and z to refer to them. Otherwise you must use this flag to give your variables names."); } @@ -224,26 +224,35 @@ Custom::Custom(const ActionOptions&ao): values(getNumberOfArguments()), names(getNumberOfArguments()), lepton_ref(getNumberOfArguments(),nullptr), - lepton_ref_deriv(getNumberOfArguments()*getNumberOfArguments(),nullptr) -{ + lepton_ref_deriv(getNumberOfArguments()*getNumberOfArguments(),nullptr) { parseVector("VAR",var); if(var.size()==0) { var.resize(getNumberOfArguments()); - if(getNumberOfArguments()>3) + if(getNumberOfArguments()>3) { 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()>0) { + var[0]="x"; + } + if(var.size()>1) { + var[1]="y"; + } + if(var.size()>2) { + var[2]="z"; + } } - if(var.size()!=getNumberOfArguments()) + if(var.size()!=getNumberOfArguments()) { error("Size of VAR array should be the same as number of arguments"); + } parse("FUNC",func); addValueWithDerivatives(); checkRead(); log.printf(" with function : %s\n",func.c_str()); log.printf(" with variables :"); - for(unsigned i=0; i0.0) kbt=plumed.getAtoms().getKBoltzmann()*temp; - else kbt=plumed.getAtoms().getKbT(); - if(kbt==0.0) error("Unless the MD engine passes the temperature to plumed, with REWEIGHT you must specify TEMP"); + if(temp>0.0) { + kbt=plumed.getAtoms().getKBoltzmann()*temp; + } else { + kbt=plumed.getAtoms().getKbT(); + } + if(kbt==0.0) { + error("Unless the MD engine passes the temperature to plumed, with REWEIGHT you must specify TEMP"); + } } parse("MOMENT",moment); - if(moment==1) error("MOMENT can be any number but for 0 and 1"); - if(moment!=0) do_moments=true; + if(moment==1) { + error("MOMENT can be any number but for 0 and 1"); + } + if(moment!=0) { + do_moments=true; + } parseFlag("CENTRAL", do_central); - if(!do_moments&&do_central) error("To calculate a CENTRAL moment you need to define for which MOMENT"); + if(!do_moments&&do_central) { + error("To calculate a CENTRAL moment you need to define for which MOMENT"); + } parse("POWER",power); - if(power==1) error("POWER can be any number but for 0 and 1"); - if(power!=0) do_powers=true; + if(power==1) { + error("POWER can be any number but for 0 and 1"); + } + if(power!=0) { + do_powers=true; + } checkRead(); @@ -122,11 +135,15 @@ Ensemble::Ensemble(const ActionOptions&ao): } comm.Bcast(ens_dim,0); comm.Bcast(my_repl,0); - if(ens_dim<2) log.printf("WARNING: ENSEMBLE with one replica is not doing any averaging!\n"); + if(ens_dim<2) { + log.printf("WARNING: ENSEMBLE with one replica is not doing any averaging!\n"); + } // prepare output components, the number depending on reweighing or not narg = getNumberOfArguments(); - if(do_reweight) narg--; + if(do_reweight) { + narg--; + } // these are the averages for(unsigned i=0; i1) 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())); @@ -181,8 +208,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); @@ -199,7 +230,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); @@ -171,8 +172,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); @@ -181,11 +181,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"); @@ -205,8 +207,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()); @@ -218,8 +222,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.); + } } } @@ -249,8 +254,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"); @@ -261,10 +267,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; @@ -278,7 +286,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); @@ -321,15 +331,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 901fd1d869..09bb3edaae 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; } @@ -231,8 +233,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); @@ -241,10 +242,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"&&myname!="CONTACTMAP"&&myname!="DISTANCE"&&myname!="PIV") error("One or more of your arguments is not of RMSD/CONTACTMAP/DISTANCE/PIV type!!!"); + if(myname!="RMSD"&&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 @@ -260,14 +265,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 e2ec20f658..299f9c32ec 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; @@ -238,8 +250,7 @@ FuncSumHills::FuncSumHills(const ActionOptions&ao): lowI_(-1.), uppI_(-1.), beta(-1.), - fmt("%14.9f") -{ + fmt("%14.9f") { // format parse("FMT",fmt); @@ -248,44 +259,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 @@ -342,13 +385,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; @@ -416,16 +465,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); @@ -501,18 +568,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? @@ -524,17 +600,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() -{ +void Function::apply() { const unsigned noa=getNumberOfArguments(); const unsigned ncp=getNumberOfComponents(); const unsigned cgs=comm.Get_size(); @@ -86,16 +86,26 @@ void Function::apply() for(unsigned i=rank; iapplyForce(forces)) { at_least_one_forced+=1; - for(unsigned j=0; j0&&ncp>4*cgs) { comm.Sum(&f[0],noa); comm.Sum(at_least_one_forced); } + if(noa>0&&ncp>4*cgs) { + comm.Sum(&f[0],noa); + comm.Sum(at_least_one_forced); + } - if(at_least_one_forced>0) for(unsigned i=0; iaddForce(f[i]); + if(at_least_one_forced>0) + for(unsigned i=0; iaddForce(f[i]); + } } } diff --git a/src/function/Function.h b/src/function/Function.h index 51dce83612..39ebd4b532 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); diff --git a/src/function/LocalEnsemble.cpp b/src/function/LocalEnsemble.cpp index 2aa79547c6..7ffc062a27 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: @@ -97,22 +96,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"); } } @@ -129,8 +137,7 @@ LocalEnsemble::LocalEnsemble(const ActionOptions&ao): log.printf(" averaging over %u replicas.\n", ens_dim); } -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 > points; public: explicit Piecewise(const ActionOptions&); @@ -92,19 +91,25 @@ void Piecewise::registerKeywords(Keywords& keys) { Piecewise::Piecewise(const ActionOptions&ao): Action(ao), - Function(ao) -{ + Function(ao) { for(int i=0;; i++) { std::vector pp; - if(!parseNumberedVector("POINT",i,pp) ) break; - if(pp.size()!=2) error("points should be in x,y format"); + if(!parseNumberedVector("POINT",i,pp) ) { + break; + } + if(pp.size()!=2) { + 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) error("points abscissas should be monotonously increasing"); + if(i>0 && points[i].first<=points[i-1].first) { + error("points abscissas should be monotonously increasing"); + } } for(unsigned i=0; iisPeriodic()) + if(getPntrToArgument(i)->isPeriodic()) { error("Cannot use PIECEWISE on periodic arguments"); + } if(getNumberOfArguments()==1) { addValueWithDerivatives(); @@ -118,7 +123,9 @@ Piecewise::Piecewise(const ActionOptions&ao): checkRead(); log.printf(" on points:"); - for(unsigned i=0; iisPeriodic()) + if(getPntrToArgument(i)->isPeriodic()) { error("Cannot sort periodic values (check argument "+s+")"); + } addComponentWithDerivatives(s); getPntrToComponent(i)->setNotPeriodic(); } diff --git a/src/function/Stats.cpp b/src/function/Stats.cpp index 11dc0f2fa3..8a33e0941e 100644 --- a/src/function/Stats.cpp +++ b/src/function/Stats.cpp @@ -54,8 +54,7 @@ PRINT ARG=d1,d2,d3,st.* class Stats : - public Function -{ + public Function { std::vector 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/Target.cpp b/src/function/Target.cpp index 7d5985f18b..8d7cb21b13 100644 --- a/src/function/Target.cpp +++ b/src/function/Target.cpp @@ -121,13 +121,16 @@ Target::Target(const ActionOptions&ao): Action(ao), Function(ao), myvals(1,0), - mypack(0,0,myvals) -{ - std::string type; parse("TYPE",type); - std::string reference; parse("REFERENCE",reference); - checkRead(); PDB pdb; - if( !pdb.read(reference,plumed.getAtoms().usingNaturalUnits(),0.1/plumed.getAtoms().getUnits().getLength()) ) + mypack(0,0,myvals) { + std::string type; + parse("TYPE",type); + std::string reference; + parse("REFERENCE",reference); + checkRead(); + PDB pdb; + if( !pdb.read(reference,plumed.getAtoms().usingNaturalUnits(),0.1/plumed.getAtoms().getUnits().getLength()) ) { error("missing input file " + reference); + } // Use the base ActionWithArguments to expand things like a1.* expandArgKeywordInPDB( pdb ); @@ -149,12 +152,17 @@ Target::Target(const ActionOptions&ao): mypack.resize( myargs.size(), 0 ); // Create the value - addValueWithDerivatives(); setNotPeriodic(); + addValueWithDerivatives(); + setNotPeriodic(); } void Target::calculate() { - mypack.clear(); double r=target->calculate( getArguments(), mypack, false ); setValue(r); - for(unsigned i=0; icalculate( getArguments(), mypack, false ); + setValue(r); + for(unsigned i=0; i > drotdpos(3,3); diff --git a/src/funnel/Funnel.cpp b/src/funnel/Funnel.cpp index bb696f88a3..6e03d5baa0 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/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 "<(this); 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]); + } } } @@ -258,7 +281,10 @@ void DumpAtoms::update() { for(unsigned i=0; i0) 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+"\n").c_str(),name,lenunit*getPosition(i)(0),lenunit*getPosition(i)(1),lenunit*getPosition(i)(2)); } } else if(type=="gro") { @@ -269,10 +295,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)); @@ -288,17 +321,25 @@ void DumpAtoms::update() { int step=getStep(); float time=getTime()/plumed.getAtoms().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(); 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( npar!=getPntrToArgument(i)->getNumberOfDerivatives() ) error("the number of derivatives must be the same in all values being dumped"); + 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 660c44412c..4b27d3a940 100644 --- a/src/generic/DumpMassCharge.cpp +++ b/src/generic/DumpMassCharge.cpp @@ -26,8 +26,7 @@ #include "core/PlumedMain.h" #include "core/Atoms.h" -namespace PLMD -{ +namespace PLMD { namespace generic { //+PLUMEDOC PRINTANALYSIS DUMPMASSCHARGE @@ -76,8 +75,7 @@ DUMPMASSCHARGE FILE=mcfile ATOMS=solute_ions class DumpMassCharge: public ActionAtomistic, - public ActionPilot -{ + public ActionPilot { std::string file; bool first; bool second; @@ -113,11 +111,12 @@ 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); @@ -146,7 +145,9 @@ DumpMassCharge::DumpMassCharge(const ActionOptions&ao): checkRead(); log.printf(" printing the following atoms:" ); - for(unsigned i=0; i 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); @@ -250,7 +258,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 7d3e63ff4e..c5c7a1d3c5 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; @@ -195,7 +194,9 @@ class FitToTemplate: static void registerKeywords( Keywords& keys ); 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") @@ -214,8 +215,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"); @@ -229,14 +229,17 @@ 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,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()) ) + if( !pdb.read(reference,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.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 weights_measure=pdb.getBeta(); - n=0.0; for(unsigned i=0; i(); @@ -272,7 +290,8 @@ FitToTemplate::FitToTemplate(const ActionOptions&ao): log<<" Ignoring PBCs when doing alignment, make sure your molecule is whole!calc_FitElements( getPositions(), rotation, drotdpos, centeredpositions, center_positions); setValue(r); 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/Group.cpp b/src/generic/Group.cpp index 45e5288957..8fac220f81 100644 --- a/src/generic/Group.cpp +++ b/src/generic/Group.cpp @@ -129,8 +129,7 @@ DUMPATOMS ATOMS=hy FILE=hy.gro //+ENDPLUMEDOC class Group: - public ActionAtomistic -{ + public ActionAtomistic { public: explicit Group(const ActionOptions&ao); @@ -144,19 +143,25 @@ PLUMED_REGISTER_ACTION(Group,"GROUP") Group::Group(const ActionOptions&ao): Action(ao), - ActionAtomistic(ao) -{ + ActionAtomistic(ao) { std::vector atoms; parseAtomList("ATOMS",atoms); std::string ndxfile,ndxgroup; parse("NDX_FILE",ndxfile); parse("NDX_GROUP",ndxgroup); - 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 && 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) { - if(ndxgroup.size()>0) log<<" importing group '"+ndxgroup+"'"; - else log<<" importing first group"; + if(ndxgroup.size()>0) { + log<<" importing group '"+ndxgroup+"'"; + } else { + log<<" importing first group"; + } log<<" from index file "< 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; i remove; @@ -190,16 +202,22 @@ Group::Group(const ActionOptions&ao): for(unsigned i=0; i0) { log<<" the following atoms were not found:"; - for(unsigned i=0; iatoms.insertGroup(getLabel(),atoms); log.printf(" list of atoms:"); for(unsigned i=0; i3) << "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) { @@ -254,76 +254,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],9); + if(root) { + p.cmd("setBox",&box[0][0],9); + } virial.zero(); - for(int i=0; iset(bias); } @@ -407,7 +499,9 @@ void Plumed::apply() { void Plumed::update() { Tools::DirectoryChanger directoryChanger(directory.c_str()); - if(root) p.cmd("update"); + if(root) { + p.cmd("update"); + } comm.Bcast(stop,0); if(stop) { log<<" Action " << getLabel()<<" asked to stop\n"; diff --git a/src/generic/Print.cpp b/src/generic/Print.cpp index f1356646f9..644bc6cdbf 100644 --- a/src/generic/Print.cpp +++ b/src/generic/Print.cpp @@ -67,8 +67,7 @@ only when required. class Print : public ActionPilot, - public ActionWithArguments -{ + public ActionWithArguments { std::string file; OFile ofile; std::string fmt; @@ -113,8 +112,7 @@ Print::Print(const ActionOptions&ao): ActionPilot(ao), ActionWithArguments(ao), fmt("%f"), - rotate(0) -{ + rotate(0) { ofile.link(*this); parse("FILE",file); if(file.length()>0) { @@ -127,7 +125,9 @@ Print::Print(const ActionOptions&ao): parse("FMT",fmt); fmt=" "+fmt; log.printf(" with format %s\n",fmt.c_str()); - for(unsigned i=0; i0) { rotateCountdown=rotate; - for(unsigned i=0; i a(1,rotateArguments[0]); requestArguments(std::vector(1,rotateArguments[0])); rotateLast=0; 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 d90c6852e5..d4f589aafe 100644 --- a/src/generic/Read.cpp +++ b/src/generic/Read.cpp @@ -77,8 +77,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(); @@ -213,8 +241,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() { @@ -223,7 +252,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() )>plumed.getAtoms().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."); } } @@ -246,8 +277,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.getAtoms().getNatoms()==0 ) plumed.stop(); + ifile->scanField(); + double du_time; + if( !ifile->scanField("time",du_time) && plumed.getAtoms().getNatoms()==0 ) { + plumed.stop(); + } } } } diff --git a/src/generic/ResetCell.cpp b/src/generic/ResetCell.cpp index 98b76f09b8..7e05dbcaa5 100644 --- a/src/generic/ResetCell.cpp +++ b/src/generic/ResetCell.cpp @@ -91,8 +91,7 @@ END class ResetCell: public ActionPilot, - public ActionAtomistic -{ + public ActionAtomistic { std::string type; Tensor rotation,newbox; @@ -115,13 +114,14 @@ 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: "<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 c7ac2a45ae..8d0c81f3fa 100644 --- a/src/generic/WholeMolecules.cpp +++ b/src/generic/WholeMolecules.cpp @@ -102,8 +102,7 @@ WHOLEMOLECULES RESIDUES=all MOLTYPE=protein class WholeMolecules: public ActionPilot, - public ActionAtomistic -{ + public ActionAtomistic { std::vector > groups; std::vector > roots; std::vector refs; @@ -137,8 +136,7 @@ WholeMolecules::WholeMolecules(const ActionOptions&ao): Action(ao), ActionPilot(ao), ActionAtomistic(ao), - doemst(false), addref(false) -{ + doemst(false), addref(false) { // parse optional flags parseFlag("EMST", doemst); parseFlag("ADDREFERENCE", addref); @@ -147,20 +145,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 @@ -187,7 +199,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])); @@ -206,9 +222,13 @@ WholeMolecules::WholeMolecules(const ActionOptions&ao): // print out info for(unsigned i=0; i atoms; std::vector reference; @@ -178,31 +177,44 @@ WrapAround::WrapAround(const ActionOptions&ao): ActionPilot(ao), ActionAtomistic(ao), groupby(1), - pair_(false) -{ + pair_(false) { parseAtomList("ATOMS",atoms); 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 "< ActionWithGrid::createGrid( const std::string& type, const std::string& inputstr ) { // Start creating the input for the grid std::string vstring = inputstr; if( keywords.exists("KERNEL") ) { - std::string vconc; parse("CONCENTRATION",vconc); + std::string vconc; + parse("CONCENTRATION",vconc); if( vconc.length()>0 ) { vstring += " TYPE=fibonacci CONCENTRATION=" + vconc; } else { - std::string kstring; parse("KERNEL",kstring); - if( kstring=="DISCRETE" ) vstring += " KERNEL=" + kstring; - else vstring += " KERNEL=" + kstring + " " + getKeyword("BANDWIDTH"); + std::string kstring; + parse("KERNEL",kstring); + if( kstring=="DISCRETE" ) { + vstring += " KERNEL=" + kstring; + } else { + vstring += " KERNEL=" + kstring + " " + getKeyword("BANDWIDTH"); + } } } vesselbase::VesselOptions da("mygrid","",-1,vstring,this); - Keywords keys; gridtools::AverageOnGrid::registerKeywords( keys ); + Keywords keys; + gridtools::AverageOnGrid::registerKeywords( keys ); vesselbase::VesselOptions dar( da, keys ); std::unique_ptr grid; if( type=="histogram" ) { @@ -73,37 +78,59 @@ std::unique_ptr ActionWithGrid::createGrid( const std::string& type, } void ActionWithGrid::turnOnDerivatives() { - needsDerivatives(); ActionWithValue::turnOnDerivatives(); - if( getStride()==1 ) setStride(0); - else if( getStride()!=0 ) error("conflicting instructions for grid - stride was set but must be evaluated on every step for derivatives - remove STRIDE keyword"); - if( clearstride>1 ) error("conflicting instructions for grid - CLEAR was set but grid must be reset on every step for derivatives - remove CLEAR keyword" ); - if( weights.size()>0 ) error("conflicting instructions for grid - LOGWEIGHTS was set but weights are not considered when derivatives of grid are evaluated - remove LOGWEIGHTS keyword"); + needsDerivatives(); + ActionWithValue::turnOnDerivatives(); + if( getStride()==1 ) { + setStride(0); + } else if( getStride()!=0 ) { + error("conflicting instructions for grid - stride was set but must be evaluated on every step for derivatives - remove STRIDE keyword"); + } + if( clearstride>1 ) { + error("conflicting instructions for grid - CLEAR was set but grid must be reset on every step for derivatives - remove CLEAR keyword" ); + } + if( weights.size()>0 ) { + error("conflicting instructions for grid - LOGWEIGHTS was set but weights are not considered when derivatives of grid are evaluated - remove LOGWEIGHTS keyword"); + } } void ActionWithGrid::calculate() { // Do nothing if derivatives are not required - if( doNotCalculateDerivatives() ) return; + if( doNotCalculateDerivatives() ) { + return; + } // Clear on every step - if( mygrid ) clearAverage(); + if( mygrid ) { + clearAverage(); + } // Should not be any reweighting so just set these accordingly - lweight=0; cweight=1.0; + lweight=0; + cweight=1.0; // Prepare to do the averaging prepareForAveraging(); // Run all the tasks (if required - if( useRunAllTasks ) runAllTasks(); + if( useRunAllTasks ) { + runAllTasks(); + } // This the averaging if it is not done using task list - else performOperations( true ); + else { + performOperations( true ); + } // Update the norm - if( mygrid ) mygrid->setNorm( cweight ); + if( mygrid ) { + mygrid->setNorm( cweight ); + } // Finish the averaging finishAveraging(); // And reset for next step - if( mygrid ) mygrid->reset(); + if( mygrid ) { + mygrid->reset(); + } } void ActionWithGrid::runTask( const unsigned& current, MultiValue& myvals ) const { // Set the weight of this point - myvals.setValue( 0, cweight ); compute( current, myvals ); + myvals.setValue( 0, cweight ); + compute( current, myvals ); } } diff --git a/src/gridtools/ActionWithInputGrid.cpp b/src/gridtools/ActionWithInputGrid.cpp index 30d018052c..bedebe45c4 100644 --- a/src/gridtools/ActionWithInputGrid.cpp +++ b/src/gridtools/ActionWithInputGrid.cpp @@ -35,44 +35,58 @@ void ActionWithInputGrid::registerKeywords( Keywords& keys ) { ActionWithInputGrid::ActionWithInputGrid(const ActionOptions&ao): Action(ao), ActionWithGrid(ao), - ingrid(NULL) -{ - std::string mlab; parse("GRID",mlab); + ingrid(NULL) { + std::string mlab; + parse("GRID",mlab); vesselbase::ActionWithVessel* mves= plumed.getActionSet().selectWithLabel(mlab); - if(!mves) error("action labelled " + mlab + " does not exist or does not have vessels"); + if(!mves) { + error("action labelled " + mlab + " does not exist or does not have vessels"); + } addDependency(mves); for(unsigned i=0; igetNumberOfVessels(); ++i) { ingrid=dynamic_cast( mves->getPntrToVessel(i) ); - if( ingrid ) break; + if( ingrid ) { + break; + } + } + if( !ingrid ) { + error("input action does not calculate a grid"); } - if( !ingrid ) error("input action does not calculate a grid"); if( ingrid->getNumberOfComponents()==1 ) { mycomp=0; } else { - int tcomp=-1; parse("COMPONENT",tcomp); - if( tcomp<0 ) error("component of vector field was not specified - use COMPONENT keyword"); + int tcomp=-1; + parse("COMPONENT",tcomp); + if( tcomp<0 ) { + error("component of vector field was not specified - use COMPONENT keyword"); + } mycomp=tcomp; } log.printf(" using %uth component of grid calculated by action %s \n",mycomp,mves->getLabel().c_str() ); } void ActionWithInputGrid::clearAverage() { - if( mygrid->getType()=="flat" ) mygrid->setBounds( ingrid->getMin(), ingrid->getMax(), mygrid->getNbin(), mygrid->getGridSpacing() ); + if( mygrid->getType()=="flat" ) { + mygrid->setBounds( ingrid->getMin(), ingrid->getMax(), mygrid->getNbin(), mygrid->getGridSpacing() ); + } ActionWithAveraging::clearAverage(); } void ActionWithInputGrid::prepareForAveraging() { if( checkAllActive() ) { for(unsigned i=0; igetNumberOfPoints(); ++i) { - if( ingrid->inactive(i) ) error("if FIND_CONTOUR is used with BUFFER option then other actions cannot be performed with grid"); + if( ingrid->inactive(i) ) { + error("if FIND_CONTOUR is used with BUFFER option then other actions cannot be performed with grid"); + } } } } void ActionWithInputGrid::performOperations( const bool& from_update ) { - prepareForAveraging(); runAllTasks(); + prepareForAveraging(); + runAllTasks(); } } diff --git a/src/gridtools/ActionWithInputGrid.h b/src/gridtools/ActionWithInputGrid.h index 49aa7a80c4..f65faf3f73 100644 --- a/src/gridtools/ActionWithInputGrid.h +++ b/src/gridtools/ActionWithInputGrid.h @@ -42,14 +42,19 @@ class ActionWithInputGrid : public ActionWithGrid { explicit ActionWithInputGrid(const ActionOptions&ao); void clearAverage() override; void prepareForAveraging() override; - virtual bool checkAllActive() const { return true; } + virtual bool checkAllActive() const { + return true; + } void performOperations( const bool& from_update ) override; void apply() override {}; }; inline double ActionWithInputGrid::getFunctionValue( const unsigned& ipoint ) const { - unsigned dim=ingrid->getDimension(); if( ingrid->noderiv ) dim=0; + unsigned dim=ingrid->getDimension(); + if( ingrid->noderiv ) { + dim=0; + } return ingrid->getGridElement( ipoint, mycomp*(1+dim) ); } diff --git a/src/gridtools/ActionWithIntegral.cpp b/src/gridtools/ActionWithIntegral.cpp index d3097cee03..869618c82e 100644 --- a/src/gridtools/ActionWithIntegral.cpp +++ b/src/gridtools/ActionWithIntegral.cpp @@ -26,26 +26,33 @@ namespace gridtools { void ActionWithIntegral::registerKeywords( Keywords& keys ) { ActionWithInputGrid::registerKeywords( keys ); - keys.remove("KERNEL"); keys.remove("BANDWIDTH"); - keys.remove("CLEAR"); keys.add("compulsory","CLEAR","1","the frequency with which to clear all the accumulated data."); + keys.remove("KERNEL"); + keys.remove("BANDWIDTH"); + keys.remove("CLEAR"); + keys.add("compulsory","CLEAR","1","the frequency with which to clear all the accumulated data."); } ActionWithIntegral::ActionWithIntegral(const ActionOptions&ao): Action(ao), - ActionWithInputGrid(ao) -{ + ActionWithInputGrid(ao) { plumed_assert( ingrid->getNumberOfComponents()==1 ); // Retrieve the volume of the grid (for integration) volume = ingrid->getCellVolume(); // Create something that is going to calculate the sum of all the values // at the various grid points - this is going to be the integral - std::string fake_input; addVessel( "SUM", fake_input, -1 ); readVesselKeywords(); + std::string fake_input; + addVessel( "SUM", fake_input, -1 ); + readVesselKeywords(); // Now create task list - number of tasks is equal to the number of grid points // as we have to evaluate the function at each grid points - for(unsigned i=0; igetNumberOfPoints(); ++i) addTaskToList(i); + for(unsigned i=0; igetNumberOfPoints(); ++i) { + addTaskToList(i); + } // And activate all tasks deactivateAllTasks(); - for(unsigned i=0; igetNumberOfPoints(); ++i) taskFlags[i]=1; + for(unsigned i=0; igetNumberOfPoints(); ++i) { + taskFlags[i]=1; + } lockContributors(); } @@ -55,7 +62,9 @@ void ActionWithIntegral::turnOnDerivatives() { } void ActionWithIntegral::apply() { - if( getForcesFromVessels( forcesToApply ) ) ingrid->setForce( forcesToApply ); + if( getForcesFromVessels( forcesToApply ) ) { + ingrid->setForce( forcesToApply ); + } } } diff --git a/src/gridtools/ActionWithIntegral.h b/src/gridtools/ActionWithIntegral.h index f7dc3597f1..dae5659612 100644 --- a/src/gridtools/ActionWithIntegral.h +++ b/src/gridtools/ActionWithIntegral.h @@ -40,7 +40,9 @@ class ActionWithIntegral : public ActionWithInputGrid { unsigned getNumberOfDerivatives() override; void turnOnDerivatives() override; /// Unless I am mistaken an integral should never be a periodic function - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } void apply() override; }; diff --git a/src/gridtools/AverageOnGrid.cpp b/src/gridtools/AverageOnGrid.cpp index 704ad5a3c2..b8cfadddc6 100644 --- a/src/gridtools/AverageOnGrid.cpp +++ b/src/gridtools/AverageOnGrid.cpp @@ -29,11 +29,12 @@ void AverageOnGrid::registerKeywords( Keywords& keys ) { } AverageOnGrid::AverageOnGrid( const vesselbase::VesselOptions& da ): - HistogramOnGrid(da) -{ + HistogramOnGrid(da) { arg_names.push_back( "density" ); if( !discrete ) { - for(unsigned i=0; i& der, std::vector& buffer ) const { - buffer[bufstart+nper*ipoint] += weight*dens; buffer[ bufstart+nper*(ipoint+1) - (dimension+1) ] += dens; + buffer[bufstart+nper*ipoint] += weight*dens; + buffer[ bufstart+nper*(ipoint+1) - (dimension+1) ] += dens; if( der.size()>0 ) { - for(unsigned j=0; j=(nper-(dimension+1)) ) return getDataElement( nper*ipoint + jelement ); + if( jelement>=(nper-(dimension+1)) ) { + return getDataElement( nper*ipoint + jelement ); + } - if( noderiv ) return getDataElement( nper*ipoint+jelement ) / getDataElement( nper*(1+ipoint) - 1); + if( noderiv ) { + return getDataElement( nper*ipoint+jelement ) / getDataElement( nper*(1+ipoint) - 1); + } double rdenom = 1.0; - if( std::fabs(getDataElement( nper*(ipoint+1) -(dimension+1) ))>epsilon ) rdenom = 1. / getDataElement( nper*(ipoint+1) - (dimension+1) ); + if( std::fabs(getDataElement( nper*(ipoint+1) -(dimension+1) ))>epsilon ) { + rdenom = 1. / getDataElement( nper*(ipoint+1) - (dimension+1) ); + } unsigned jderiv = jelement%(1+dimension); - if( jderiv==0 ) return rdenom*getDataElement( nper*ipoint+jelement ); + if( jderiv==0 ) { + return rdenom*getDataElement( nper*ipoint+jelement ); + } unsigned jfloor = std::floor( jelement / (1+dimension) ); return rdenom*getDataElement( nper*ipoint+jelement ) - rdenom*rdenom*getDataElement(nper*ipoint+jfloor)*getDataElement(nper*(ipoint+1) - (dimension+1) + jderiv); diff --git a/src/gridtools/AverageOnGrid.h b/src/gridtools/AverageOnGrid.h index 067a0bb1ed..6796039df3 100644 --- a/src/gridtools/AverageOnGrid.h +++ b/src/gridtools/AverageOnGrid.h @@ -32,15 +32,21 @@ class AverageOnGrid : public HistogramOnGrid { static void registerKeywords( Keywords& keys ); explicit AverageOnGrid( const vesselbase::VesselOptions& da ); void accumulate( const unsigned& ipoint, const double& weight, const double& dens, const std::vector& der, std::vector& buffer ) const override; - void accumulateForce( const unsigned& ipoint, const double& weight, const std::vector& der, std::vector& intforce ) const override { plumed_error(); } + void accumulateForce( const unsigned& ipoint, const double& weight, const std::vector& der, std::vector& intforce ) const override { + plumed_error(); + } double getGridElement( const unsigned& ipoint, const unsigned& jelement ) const override; unsigned getNumberOfComponents() const override; - void getFinalForces( const std::vector& buffer, std::vector& finalForces ) override { plumed_error(); } + void getFinalForces( const std::vector& buffer, std::vector& finalForces ) override { + plumed_error(); + } }; inline unsigned AverageOnGrid::getNumberOfComponents() const { - if( noderiv ) return nper - 1; + if( noderiv ) { + return nper - 1; + } return nper / ( dimension + 1 ) - 1; } diff --git a/src/gridtools/ContourFindingBase.cpp b/src/gridtools/ContourFindingBase.cpp index 2adea414d0..d20c82f9bc 100644 --- a/src/gridtools/ContourFindingBase.cpp +++ b/src/gridtools/ContourFindingBase.cpp @@ -27,15 +27,17 @@ namespace gridtools { void ContourFindingBase::registerKeywords( Keywords& keys ) { ActionWithInputGrid::registerKeywords( keys ); keys.add("compulsory","CONTOUR","the value we would like to draw the contour at in the space"); - keys.remove("KERNEL"); keys.remove("BANDWIDTH"); + keys.remove("KERNEL"); + keys.remove("BANDWIDTH"); } ContourFindingBase::ContourFindingBase(const ActionOptions&ao): Action(ao), ActionWithInputGrid(ao), - mymin(this) -{ - if( ingrid->noDerivatives() ) error("cannot find contours if input grid has no derivatives"); + mymin(this) { + if( ingrid->noDerivatives() ) { + error("cannot find contours if input grid has no derivatives"); + } parse("CONTOUR",contour); log.printf(" calculating dividing surface along which function equals %f \n", contour); } diff --git a/src/gridtools/ContourFindingBase.h b/src/gridtools/ContourFindingBase.h index 6161709351..5ae2a7f947 100644 --- a/src/gridtools/ContourFindingBase.h +++ b/src/gridtools/ContourFindingBase.h @@ -43,9 +43,13 @@ class ContourFindingBase : public ActionWithInputGrid { /// Get the contour value double getDifferenceFromContour( const std::vector& x, std::vector& der ) const ; /// Overwrite not needed stuff - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } /// This is not periodic - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; inline diff --git a/src/gridtools/ConvertToFES.cpp b/src/gridtools/ConvertToFES.cpp index bfc45887c3..477766ea2c 100644 --- a/src/gridtools/ConvertToFES.cpp +++ b/src/gridtools/ConvertToFES.cpp @@ -68,13 +68,24 @@ class ConvertToFES : public ActionWithInputGrid { static void registerKeywords( Keywords& keys ); explicit ConvertToFES(const ActionOptions&ao); unsigned getNumberOfQuantities() const override; - bool ignoreNormalization() const override { return true; } - void prepare() override { activated=true; } - void prepareForAveraging() override { ActionWithInputGrid::prepareForAveraging(); activated=false; } + bool ignoreNormalization() const override { + return true; + } + void prepare() override { + activated=true; + } + void prepareForAveraging() override { + ActionWithInputGrid::prepareForAveraging(); + activated=false; + } void compute( const unsigned& current, MultiValue& myvals ) const override; void finishComputations( const std::vector& buffer ) override; - bool isPeriodic() override { return false; } - bool onStep() const override { return activated; } + bool isPeriodic() override { + return false; + } + bool onStep() const override { + return activated; + } void runFinalJobs() override; }; @@ -84,63 +95,91 @@ void ConvertToFES::registerKeywords( Keywords& keys ) { ActionWithInputGrid::registerKeywords( 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.remove("STRIDE"); keys.remove("KERNEL"); keys.remove("BANDWIDTH"); - keys.remove("LOGWEIGHTS"); keys.remove("CLEAR"); keys.remove("NORMALIZATION"); + keys.remove("STRIDE"); + keys.remove("KERNEL"); + keys.remove("BANDWIDTH"); + keys.remove("LOGWEIGHTS"); + keys.remove("CLEAR"); + keys.remove("NORMALIZATION"); } ConvertToFES::ConvertToFES(const ActionOptions&ao): Action(ao), ActionWithInputGrid(ao), - activated(false) -{ + activated(false) { plumed_assert( ingrid->getNumberOfComponents()==1 ); // Create a grid auto grid=createGrid( "grid", "COMPONENTS=" + getLabel() + " " + ingrid->getInputString() ); - if( ingrid->noDerivatives() ) grid->setNoDerivatives(); + if( ingrid->noDerivatives() ) { + grid->setNoDerivatives(); + } std::vector fspacing; grid->setBounds( ingrid->getMin(), ingrid->getMax(), ingrid->getNbin(), fspacing); setAveragingAction( std::move(grid), true ); - simtemp=0.; parse("TEMP",simtemp); parseFlag("MINTOZERO",mintozero); - if(simtemp>0) simtemp*=plumed.getAtoms().getKBoltzmann(); - else simtemp=plumed.getAtoms().getKbT(); - if( simtemp==0 ) error("TEMP not set - use keyword TEMP"); + simtemp=0.; + parse("TEMP",simtemp); + parseFlag("MINTOZERO",mintozero); + if(simtemp>0) { + simtemp*=plumed.getAtoms().getKBoltzmann(); + } else { + simtemp=plumed.getAtoms().getKbT(); + } + if( simtemp==0 ) { + error("TEMP not set - use keyword TEMP"); + } // Now create task list - for(unsigned i=0; igetNumberOfPoints(); ++i) addTaskToList(i); + for(unsigned i=0; igetNumberOfPoints(); ++i) { + addTaskToList(i); + } // And activate all tasks deactivateAllTasks(); - for(unsigned i=0; igetNumberOfPoints(); ++i) taskFlags[i]=1; + for(unsigned i=0; igetNumberOfPoints(); ++i) { + taskFlags[i]=1; + } lockContributors(); } unsigned ConvertToFES::getNumberOfQuantities() const { - if( mygrid->noDerivatives() ) return 2; + if( mygrid->noDerivatives() ) { + return 2; + } return 2 + mygrid->getDimension(); } void ConvertToFES::compute( const unsigned& current, MultiValue& myvals ) const { - double val=getFunctionValue( current ); myvals.setValue(1, -simtemp*std::log(val) ); + double val=getFunctionValue( current ); + myvals.setValue(1, -simtemp*std::log(val) ); if( !mygrid->noDerivatives() && val>0 ) { - for(unsigned i=0; igetDimension(); ++i) myvals.setValue( 2+i, -(simtemp/val)*ingrid->getGridElement(current,i+1) ); + for(unsigned i=0; igetDimension(); ++i) { + myvals.setValue( 2+i, -(simtemp/val)*ingrid->getGridElement(current,i+1) ); + } } } void ConvertToFES::finishComputations( const std::vector& buffer ) { ActionWithVessel::finishComputations( buffer ); - if(!mintozero) return; + if(!mintozero) { + return; + } double optval = mygrid->getGridElement( 0, 0 ); for(unsigned i=0; igetNumberOfPoints(); ++i) { double tval = mygrid->getGridElement( i, 0 ); - if( tvalgetNumberOfPoints(); ++i) { + mygrid->addToGridElement( i, 0, -optval ); } - for(unsigned i=0; igetNumberOfPoints(); ++i) mygrid->addToGridElement( i, 0, -optval ); } void ConvertToFES::runFinalJobs() { - activated=true; update(); + activated=true; + update(); } } diff --git a/src/gridtools/DumpCube.cpp b/src/gridtools/DumpCube.cpp index 071cb6414e..3d6af5d4af 100644 --- a/src/gridtools/DumpCube.cpp +++ b/src/gridtools/DumpCube.cpp @@ -79,18 +79,27 @@ void DumpCube::registerKeywords( Keywords& keys ) { DumpCube::DumpCube(const ActionOptions&ao): Action(ao), - GridPrintingBase(ao) -{ + GridPrintingBase(ao) { fmt = fmt + " "; - if( ingrid->getType()!="flat" ) error("cannot dump grid of type " + ingrid->getType() + " using DUMPCUBE"); - if( ingrid->getDimension()!=3 ) error("cannot print cube file if grid does not contain three dimensional data"); + if( ingrid->getType()!="flat" ) { + error("cannot dump grid of type " + ingrid->getType() + " using DUMPCUBE"); + } + if( ingrid->getDimension()!=3 ) { + error("cannot print cube file if grid does not contain three dimensional data"); + } if( ingrid->getNumberOfComponents()==1 ) { mycomp=0; } else { - int tcomp=-1; parse("COMPONENT",tcomp); - if( tcomp<0 ) error("component of vector field was not specified - use COMPONENT keyword"); - mycomp=tcomp*(1+ingrid->getDimension()); if( ingrid->noDerivatives() ) mycomp=tcomp; + int tcomp=-1; + parse("COMPONENT",tcomp); + if( tcomp<0 ) { + error("component of vector field was not specified - use COMPONENT keyword"); + } + mycomp=tcomp*(1+ingrid->getDimension()); + if( ingrid->noDerivatives() ) { + mycomp=tcomp; + } log.printf(" using %dth component of grid \n",tcomp ); } @@ -109,12 +118,15 @@ void DumpCube::printGrid( OFile& ofile ) const { ofile.printf(ostr.c_str(),ingrid->getNbin()[1],0.0,lunit*ingrid->getGridSpacing()[1],0.0); // shape of voxel ofile.printf(ostr.c_str(),ingrid->getNbin()[2],0.0,0.0,lunit*ingrid->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( ingrid->getNbin() ); + std::vector pp(3); + std::vector nbin( ingrid->getNbin() ); for(pp[0]=0; pp[0]getGridElement( ingrid->getIndex(pp), mycomp ) ); - if(pp[2]%6==5) ofile.printf("\n"); + if(pp[2]%6==5) { + ofile.printf("\n"); + } } ofile.printf("\n"); } diff --git a/src/gridtools/DumpGrid.cpp b/src/gridtools/DumpGrid.cpp index 3551332269..416c13edd4 100644 --- a/src/gridtools/DumpGrid.cpp +++ b/src/gridtools/DumpGrid.cpp @@ -154,10 +154,12 @@ void DumpGrid::registerKeywords( Keywords& keys ) { DumpGrid::DumpGrid(const ActionOptions&ao): Action(ao), - GridPrintingBase(ao) -{ - if( ingrid->getType()!="flat" ) error("cannot dump grid of type " + ingrid->getType() + " using DUMPGRID"); - fmt = " " + fmt; checkRead(); + GridPrintingBase(ao) { + if( ingrid->getType()!="flat" ) { + error("cannot dump grid of type " + ingrid->getType() + " using DUMPGRID"); + } + fmt = " " + fmt; + checkRead(); } void DumpGrid::printGrid( OFile& ofile ) const { @@ -173,20 +175,30 @@ void DumpGrid::printGrid( OFile& ofile ) const { std::vector ind( ingrid->getDimension() ); for(unsigned i=0; igetNumberOfPoints(); ++i) { ingrid->getIndices( i, ind ); - if(i>0 && ingrid->getDimension()==2 && ind[ingrid->getDimension()-2]==0) ofile.printf("\n"); - ofile.fmtField(fmt); ofile.printField("normalisation", ingrid->getNorm() ); + if(i>0 && ingrid->getDimension()==2 && ind[ingrid->getDimension()-2]==0) { + ofile.printf("\n"); + } + ofile.fmtField(fmt); + ofile.printField("normalisation", ingrid->getNorm() ); for(unsigned j=0; jgetDimension(); ++j) { ofile.printField("min_" + ingrid->getComponentName(j), ingrid->getMin()[j] ); ofile.printField("max_" + ingrid->getComponentName(j), ingrid->getMax()[j] ); ofile.printField("nbins_" + ingrid->getComponentName(j), static_cast(ingrid->getNbin()[j]) ); - if( ingrid->isPeriodic(j) ) ofile.printField("periodic_" + ingrid->getComponentName(j), "true" ); - else ofile.printField("periodic_" + ingrid->getComponentName(j), "false" ); + if( ingrid->isPeriodic(j) ) { + ofile.printField("periodic_" + ingrid->getComponentName(j), "true" ); + } else { + ofile.printField("periodic_" + ingrid->getComponentName(j), "false" ); + } } // Retrieve and print the grid coordinates ingrid->getGridPointCoordinates(i, xx ); - for(unsigned j=0; jgetDimension(); ++j) { ofile.fmtField(fmt); ofile.printField(ingrid->getComponentName(j),xx[j]); } + for(unsigned j=0; jgetDimension(); ++j) { + ofile.fmtField(fmt); + ofile.printField(ingrid->getComponentName(j),xx[j]); + } for(unsigned j=0; jgetNumberOfQuantities(); ++j) { - ofile.fmtField(fmt); ofile.printField(ingrid->arg_names[ingrid->dimension+j], ingrid->getGridElement( i, j ) ); + ofile.fmtField(fmt); + ofile.printField(ingrid->arg_names[ingrid->dimension+j], ingrid->getGridElement( i, j ) ); } ofile.printField(); } diff --git a/src/gridtools/FindContour.cpp b/src/gridtools/FindContour.cpp index ca74268b33..f16e758931 100644 --- a/src/gridtools/FindContour.cpp +++ b/src/gridtools/FindContour.cpp @@ -102,10 +102,16 @@ class FindContour : public ContourFindingBase { public: static void registerKeywords( Keywords& keys ); explicit FindContour(const ActionOptions&ao); - bool checkAllActive() const override { return gbuffer==0; } + bool checkAllActive() const override { + return gbuffer==0; + } void prepareForAveraging() override; - bool isPeriodic() override { return false; } - unsigned getNumberOfQuantities() const override { return 1 + ingrid->getDimension(); } + bool isPeriodic() override { + return false; + } + unsigned getNumberOfQuantities() const override { + return 1 + ingrid->getDimension(); + } void compute( const unsigned& current, MultiValue& myvals ) const override; void finishAveraging() override; }; @@ -124,75 +130,110 @@ void FindContour::registerKeywords( Keywords& keys ) { FindContour::FindContour(const ActionOptions&ao): Action(ao), ContourFindingBase(ao), - firsttime(true) -{ + firsttime(true) { 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); + } - std::string file; parse("FILE",file); - if( file.length()==0 ) error("name out output file was not specified"); + std::string file; + parse("FILE",file); + if( file.length()==0 ) { + error("name out output file was not specified"); + } std::string type=Tools::extension(file); log<<" file name "<0) { - int p; Tools::convert(precision,p); + int p; + Tools::convert(precision,p); log<<" with precision "<getDimension()*ingrid->getNumberOfPoints(); ++i) addTaskToList( i ); + for(unsigned i=0; igetDimension()*ingrid->getNumberOfPoints(); ++i) { + addTaskToList( i ); + } } - firsttime=false; deactivateAllTasks(); + firsttime=false; + deactivateAllTasks(); // We now need to identify the grid points that we need to search through std::vector nbin( ingrid->getNbin() ); std::vector ind( ingrid->getDimension() ); std::vector ones( ingrid->getDimension(), 1 ); - unsigned num_neighbours; std::vector neighbours; + unsigned num_neighbours; + std::vector neighbours; for(unsigned i=0; igetNumberOfPoints(); ++i) { // Ensure inactive grid points are ignored - if( ingrid->inactive(i) ) continue; + if( ingrid->inactive(i) ) { + continue; + } // Get the index of the current grid point ingrid->getIndices( i, ind ); ingrid->getNeighbors( ind, ones, num_neighbours, neighbours ); bool cycle=false; for(unsigned j=0; jinactive( neighbours[j]) ) { cycle=true; break; } + if( ingrid->inactive( neighbours[j]) ) { + cycle=true; + break; + } + } + if( cycle ) { + continue; } - if( cycle ) continue; // Get the value of a point on the grid double val1=getFunctionValue( i ) - contour; bool edge=false; for(unsigned j=0; jgetDimension(); ++j) { // Make sure we don't search at the edge of the grid - if( !ingrid->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( !ingrid->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=getFunctionValue( ind ) - contour; - if( val1*val2<0 ) taskFlags[ ingrid->getDimension()*i + j ] = 1; - if( ingrid->isPeriodic(j) && edge ) { edge=false; ind[j]=nbin[j]-1; } - else ind[j]-=1; + if( val1*val2<0 ) { + taskFlags[ ingrid->getDimension()*i + j ] = 1; + } + if( ingrid->isPeriodic(j) && edge ) { + edge=false; + ind[j]=nbin[j]-1; + } else { + ind[j]-=1; + } } } lockContributors(); @@ -212,13 +253,16 @@ void FindContour::compute( const unsigned& current, MultiValue& myvals ) const { // Now find the contour findContour( direction, point ); // And transfer to the store data vessel - for(unsigned i=0; igetDimension(); ++i) myvals.setValue( 1+i, point[i] ); + for(unsigned i=0; igetDimension(); ++i) { + myvals.setValue( 1+i, point[i] ); + } } void FindContour::finishAveraging() { // And update the list of active grid points if( gbuffer>0 ) { - std::vector neighbours; unsigned num_neighbours; + std::vector neighbours; + unsigned num_neighbours; std::vector ugrid_indices( ingrid->getDimension() ); std::vector active( ingrid->getNumberOfPoints(), false ); std::vector gbuffer_vec( ingrid->getDimension(), gbuffer ); @@ -229,7 +273,9 @@ void FindContour::finishAveraging() { ingrid->getIndices( ipoint, ugrid_indices ); // Now activate buffer region ingrid->getNeighbors( ugrid_indices, gbuffer_vec, num_neighbours, neighbours ); - for(unsigned n=0; nactivateThesePoints( active ); } @@ -237,8 +283,11 @@ void FindContour::finishAveraging() { of.printf("%u\n",mydata->getNumberOfStoredValues()); of.printf("Points found on isocontour\n"); for(unsigned i=0; igetNumberOfStoredValues(); ++i) { - mydata->retrieveSequentialValue( i, false, point ); of.printf("X"); - for(unsigned j=0; jgetDimension(); ++j) of.printf( (" " + fmt_xyz).c_str(), lenunit*point[1+j] ); + mydata->retrieveSequentialValue( i, false, point ); + of.printf("X"); + for(unsigned j=0; jgetDimension(); ++j) { + of.printf( (" " + fmt_xyz).c_str(), lenunit*point[1+j] ); + } of.printf("\n"); } } diff --git a/src/gridtools/FindContourSurface.cpp b/src/gridtools/FindContourSurface.cpp index cf2e375fab..2f67a23809 100644 --- a/src/gridtools/FindContourSurface.cpp +++ b/src/gridtools/FindContourSurface.cpp @@ -95,8 +95,12 @@ class FindContourSurface : public ContourFindingBase { public: static void registerKeywords( Keywords& keys ); explicit FindContourSurface(const ActionOptions&ao); - unsigned getNumberOfQuantities() const override { return 2; } - bool checkAllActive() const override { return gbuffer==0; } + unsigned getNumberOfQuantities() const override { + return 2; + } + bool checkAllActive() const override { + return gbuffer==0; + } void clearAverage() override; void prepareForAveraging() override; void compute( const unsigned& current, MultiValue& myvals ) const override; @@ -115,48 +119,72 @@ FindContourSurface::FindContourSurface(const ActionOptions&ao): Action(ao), ContourFindingBase(ao), firsttime(true), - ones(ingrid->getDimension(),1) -{ - if( ingrid->getDimension()<2 ) error("cannot find dividing surface if input grid is one dimensional"); + ones(ingrid->getDimension(),1) { + if( ingrid->getDimension()<2 ) { + error("cannot find dividing surface if input grid is one dimensional"); + } - std::string dir; parse("SEARCHDIR",dir); parse("BUFFER",gbuffer); + std::string dir; + parse("SEARCHDIR",dir); + parse("BUFFER",gbuffer); log.printf(" calculating location of contour on %d dimensional grid \n", ingrid->getDimension()-1 ); - 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(); - unsigned n=0; gdirs.resize( ingrid->getDimension()-1 ); + unsigned n=0; + gdirs.resize( ingrid->getDimension()-1 ); for(unsigned i=0; igetDimension(); ++i) { if( ingrid->getComponentName(i)==dir ) { dir_n=i; } else { - if( n==gdirs.size() ) error("could not find " + dir + " direction in input grid"); - gdirs[n]=i; n++; + if( n==gdirs.size() ) { + error("could not find " + dir + " direction in input grid"); + } + gdirs[n]=i; + n++; } } - if( n!=(ingrid->getDimension()-1) ) error("output of grid is not understood"); + if( n!=(ingrid->getDimension()-1) ) { + error("output of grid is not understood"); + } // Create the input from the old string std::string vstring = "COMPONENTS=" + getLabel() + " COORDINATES=" + ingrid->getComponentName( gdirs[0] ); - for(unsigned i=1; igetComponentName( gdirs[i] ); + for(unsigned i=1; igetComponentName( gdirs[i] ); + } vstring += " PBC="; - if( ingrid->isPeriodic(gdirs[0]) ) vstring+="T"; - else vstring+="F"; + if( ingrid->isPeriodic(gdirs[0]) ) { + vstring+="T"; + } else { + vstring+="F"; + } for(unsigned i=1; iisPeriodic(gdirs[i]) ) vstring+=",T"; else vstring+=",F"; + if( ingrid->isPeriodic(gdirs[i]) ) { + vstring+=",T"; + } else { + vstring+=",F"; + } } - auto grid=createGrid( "grid", vstring ); grid->setNoDerivatives(); + auto grid=createGrid( "grid", vstring ); + grid->setNoDerivatives(); setAveragingAction( std::move(grid), true ); } void FindContourSurface::clearAverage() { // Set the boundaries of the output grid - std::vector fspacing; std::vector snbins( ingrid->getDimension()-1 ); + std::vector fspacing; + std::vector snbins( ingrid->getDimension()-1 ); std::vector smin( ingrid->getDimension()-1 ), smax( ingrid->getDimension()-1 ); for(unsigned i=0; igetMin()[gdirs[i]]; smax[i]=ingrid->getMax()[gdirs[i]]; + smin[i]=ingrid->getMin()[gdirs[i]]; + smax[i]=ingrid->getMax()[gdirs[i]]; snbins[i]=ingrid->getNbin()[gdirs[i]]; } - mygrid->setBounds( smin, smax, snbins, fspacing); resizeFunctions(); + mygrid->setBounds( smin, smax, snbins, fspacing); + resizeFunctions(); ActionWithAveraging::clearAverage(); } @@ -166,14 +194,19 @@ void FindContourSurface::prepareForAveraging() { std::vector find( ingrid->getDimension() ); std::vector ind( mygrid->getDimension() ); for(unsigned i=0; igetNumberOfPoints(); ++i) { - find.assign( find.size(), 0 ); mygrid->getIndices( i, ind ); - for(unsigned j=0; jgetIndices( i, ind ); + for(unsigned j=0; jgetIndex(find) ); } // And prepare the task list deactivateAllTasks(); - for(unsigned i=0; igetDimension(), 0 ); @@ -188,7 +221,8 @@ void FindContourSurface::finishAveraging() { std::vector dx( ingrid->getGridSpacing() ); std::vector point( ingrid->getDimension() ); std::vector lpoint( mygrid->getDimension() ); - std::vector neighbours; unsigned num_neighbours; + std::vector neighbours; + unsigned num_neighbours; std::vector ugrid_indices( ingrid->getDimension() ); std::vector active( ingrid->getNumberOfPoints(), false ); std::vector gbuffer_vec( ingrid->getDimension(), gbuffer ); @@ -197,11 +231,15 @@ void FindContourSurface::finishAveraging() { mygrid->getGridPointCoordinates( i, lpoint ); point[dir_n] = mygrid->getGridElement( i, 0 ); // 0.5*dx added here to prevent problems with flooring of grid points - for(unsigned j=0; jgetIndices( point, ugrid_indices ); // Now activate buffer region ingrid->getNeighbors( ugrid_indices, gbuffer_vec, num_neighbours, neighbours ); - for(unsigned n=0; nactivateThesePoints( active ); } @@ -209,43 +247,69 @@ void FindContourSurface::finishAveraging() { } void FindContourSurface::compute( const unsigned& current, MultiValue& myvals ) const { - std::vector neighbours; unsigned num_neighbours; unsigned nfound=0; double minp=0; - std::vector bins_n( ingrid->getNbin() ); unsigned shiftn=current; - std::vector ind( ingrid->getDimension() ); std::vector point( ingrid->getDimension() ); + std::vector neighbours; + unsigned num_neighbours; + unsigned nfound=0; + double minp=0; + std::vector bins_n( ingrid->getNbin() ); + unsigned shiftn=current; + std::vector ind( ingrid->getDimension() ); + std::vector point( ingrid->getDimension() ); #ifndef NDEBUG - std::vector oind( mygrid->getDimension() ); mygrid->getIndices( current, oind ); + std::vector oind( mygrid->getDimension() ); + mygrid->getIndices( current, oind ); #endif for(unsigned i=0; i base_ind( ingrid->getDimension() ); ingrid->getIndices( shiftn, base_ind ); - for(unsigned j=0; j base_ind( ingrid->getDimension() ); + ingrid->getIndices( shiftn, base_ind ); + for(unsigned j=0; jinactive( shiftn ) ) { shiftn += ingrid->getStride()[dir_n]; continue; } + if( ingrid->inactive( shiftn ) ) { + shiftn += ingrid->getStride()[dir_n]; + continue; + } // Get the index of the current grid point ingrid->getIndices( shiftn, ind ); // Exit if we are at the edge of the grid if( !ingrid->isPeriodic(dir_n) && (ind[dir_n]+1)==bins_n[dir_n] ) { - shiftn += ingrid->getStride()[dir_n]; continue; + shiftn += ingrid->getStride()[dir_n]; + continue; } // Ensure points with inactive neighbours are ignored ingrid->getNeighbors( ind, ones, num_neighbours, neighbours ); bool cycle=false; for(unsigned j=0; jinactive( neighbours[j]) ) { cycle=true; break; } + if( ingrid->inactive( neighbours[j]) ) { + cycle=true; + break; + } + } + if( cycle ) { + shiftn += ingrid->getStride()[dir_n]; + continue; } - if( cycle ) { shiftn += ingrid->getStride()[dir_n]; continue; } // Now get the function value at two points - double val1=getFunctionValue( shiftn ) - contour; double val2; - if( (ind[dir_n]+1)==bins_n[dir_n] ) val2 = getFunctionValue( current ) - contour; - else val2=getFunctionValue( shiftn + ingrid->getStride()[dir_n] ) - contour; + double val1=getFunctionValue( shiftn ) - contour; + double val2; + if( (ind[dir_n]+1)==bins_n[dir_n] ) { + val2 = getFunctionValue( current ) - contour; + } else { + val2=getFunctionValue( shiftn + ingrid->getStride()[dir_n] ) - contour; + } // Check if the minimum is bracketed if( val1*val2<0 ) { - ingrid->getGridPointCoordinates( shiftn, point ); findContour( direction, point ); - minp=point[dir_n]; nfound++; break; + ingrid->getGridPointCoordinates( shiftn, point ); + findContour( direction, point ); + minp=point[dir_n]; + nfound++; + break; } @@ -253,7 +317,8 @@ void FindContourSurface::compute( const unsigned& current, MultiValue& myvals ) shiftn += ingrid->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( 1, minp ); diff --git a/src/gridtools/FindSphericalContour.cpp b/src/gridtools/FindSphericalContour.cpp index 5d51ca2274..9f2d3802dc 100644 --- a/src/gridtools/FindSphericalContour.cpp +++ b/src/gridtools/FindSphericalContour.cpp @@ -115,7 +115,9 @@ class FindSphericalContour : public ContourFindingBase { public: static void registerKeywords( Keywords& keys ); explicit FindSphericalContour(const ActionOptions&ao); - unsigned getNumberOfQuantities() const override { return 2; } + unsigned getNumberOfQuantities() const override { + return 2; + } void compute( const unsigned& current, MultiValue& myvals ) const override; }; @@ -131,27 +133,36 @@ void FindSphericalContour::registerKeywords( Keywords& keys ) { FindSphericalContour::FindSphericalContour(const ActionOptions&ao): Action(ao), - ContourFindingBase(ao) -{ - if( ingrid->getDimension()!=3 ) error("input grid must be three dimensional"); + ContourFindingBase(ao) { + if( ingrid->getDimension()!=3 ) { + error("input grid must be three dimensional"); + } - unsigned npoints; parse("NPOINTS",npoints); + unsigned npoints; + 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("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::string vstring = "TYPE=fibonacci COMPONENTS=" + getLabel() + " COORDINATES=x,y,z PBC=F,F,F"; - auto grid=createGrid( "grid", vstring ); grid->setNoDerivatives(); + auto grid=createGrid( "grid", vstring ); + grid->setNoDerivatives(); setAveragingAction( std::move(grid), true ); // use mygrid, since at this point grid has been moved mygrid->setupFibonacciGrid( npoints ); checkRead(); // Create a task list - for(unsigned i=0; igetDimension()!=2 ) error("fourier transform currently only works with two dimensional grids"); + if( ingrid->getDimension()!=2 ) { + error("fourier transform currently only works with two dimensional grids"); + } // Get the type of FT parse("FT_TYPE",output_type); @@ -118,19 +123,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]); } @@ -139,25 +151,42 @@ FourierTransform::FourierTransform(const ActionOptions&ao): // Create the input from the old string std::string vstring; if (real_output) { - if (!store_norm) vstring="COMPONENTS=" + getLabel() + "_abs"; - else vstring="COMPONENTS=" + getLabel() + "_norm"; - } else vstring="COMPONENTS=" + getLabel() + "_real," + getLabel() + "_imag"; + if (!store_norm) { + vstring="COMPONENTS=" + getLabel() + "_abs"; + } else { + vstring="COMPONENTS=" + getLabel() + "_norm"; + } + } else { + vstring="COMPONENTS=" + getLabel() + "_real," + getLabel() + "_imag"; + } // Set COORDINATES keyword vstring += " COORDINATES=" + ingrid->getComponentName( 0 ); - for(unsigned i=1; igetDimension(); ++i) vstring += "," + ingrid->getComponentName( i ); + for(unsigned i=1; igetDimension(); ++i) { + vstring += "," + ingrid->getComponentName( i ); + } // Set PBC keyword vstring += " PBC="; - if( ingrid->isPeriodic(0) ) vstring+="T"; else vstring+="F"; + if( ingrid->isPeriodic(0) ) { + vstring+="T"; + } else { + vstring+="F"; + } for(unsigned i=1; igetDimension(); ++i) { - if( ingrid->isPeriodic(i) ) vstring+=",T"; else vstring+=",F"; + if( ingrid->isPeriodic(i) ) { + vstring+=",T"; + } else { + vstring+=",F"; + } } // Create a grid on which to store the fourier transform of the input grid auto grid=createGrid( "grid", vstring ); - if( ingrid->noDerivatives() ) grid->setNoDerivatives(); + if( ingrid->noDerivatives() ) { + grid->setNoDerivatives(); + } setAveragingAction( std::move(grid), false ); checkRead(); @@ -168,9 +197,11 @@ void FourierTransform::clearAverage() { std::vector fspacing; std::vector ft_min( ingrid->getMin() ), ft_max( ingrid->getMax() ); for(unsigned i=0; igetDimension(); ++i) { - Tools::convert( 0.0, ft_min[i] ); Tools::convert( 2.0*pi*ingrid->getNbin()[i]/ ingrid->getGridExtent(i), ft_max[i] ); + Tools::convert( 0.0, ft_min[i] ); + Tools::convert( 2.0*pi*ingrid->getNbin()[i]/ ingrid->getGridExtent(i), ft_max[i] ); } - mygrid->setBounds( ft_min, ft_max, ingrid->getNbin(), fspacing); resizeFunctions(); + mygrid->setBounds( ft_min, ft_max, ingrid->getNbin(), fspacing); + resizeFunctions(); ActionWithAveraging::clearAverage(); } @@ -191,7 +222,10 @@ void FourierTransform::performOperations( const bool& from_update ) { // Get the size of the input data arrays (to allocate FFT data) size_t fft_dimension=static_cast( ingrid->getNumberOfPoints() ); std::vector N_input_data( ingrid->getNbin() ); - for(unsigned i=0; iisPeriodic(i) ) N_input_data[i]++; + for(unsigned i=0; iisPeriodic(i) ) { + N_input_data[i]++; + } // size_t fft_dimension=1; for(unsigned i=0; i( N_input_data[i] ); // FFT arrays @@ -228,8 +262,11 @@ void FourierTransform::performOperations( const bool& from_update ) { 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 mygrid->setGridElement( i, 0, ft_value ); } else { diff --git a/src/gridtools/GridPrintingBase.cpp b/src/gridtools/GridPrintingBase.cpp index 75ae61ca6b..4e227bfb6e 100644 --- a/src/gridtools/GridPrintingBase.cpp +++ b/src/gridtools/GridPrintingBase.cpp @@ -28,7 +28,8 @@ namespace PLMD { namespace gridtools { void GridPrintingBase::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); + Action::registerKeywords( keys ); + ActionPilot::registerKeywords( keys ); keys.add("compulsory","GRID","the action that creates the grid you would like to output"); keys.add("compulsory","STRIDE","0","the frequency with which the grid should be output to the file. The default " "value of 0 ensures that the grid is only output at the end of the trajectory"); @@ -41,64 +42,101 @@ GridPrintingBase::GridPrintingBase(const ActionOptions&ao): Action(ao), ActionPilot(ao), fmt("%f"), - output_for_all_replicas(false) -{ - std::string mlab; parse("GRID",mlab); + output_for_all_replicas(false) { + std::string mlab; + parse("GRID",mlab); vesselbase::ActionWithVessel* mves= plumed.getActionSet().selectWithLabel(mlab); - if(!mves) error("action labelled " + mlab + " does not exist or does not have vessels"); + if(!mves) { + error("action labelled " + mlab + " does not exist or does not have vessels"); + } addDependency(mves); for(unsigned i=0; igetNumberOfVessels(); ++i) { ingrid=dynamic_cast( mves->getPntrToVessel(i) ); - if( ingrid ) break; + if( ingrid ) { + break; + } + } + if( !ingrid ) { + error("input action does not calculate a grid"); } - if( !ingrid ) error("input action does not calculate a 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"); + } log.printf(" outputting grid calculated by action %s to file named %s",mves->getLabel().c_str(), filename.c_str() ); if( keywords.exists("FMT") ) { - parse("FMT",fmt); log.printf(" with format %s \n", fmt.c_str() ); + parse("FMT",fmt); + log.printf(" with format %s \n", fmt.c_str() ); } else { log.printf("\n"); } - std::string rep_data; parse("REPLICA",rep_data); - if( rep_data=="all" ) output_for_all_replicas=true; - else { preps.resize(1); Tools::convert( rep_data, preps[0] ); } - if( output_for_all_replicas ) log.printf(" outputting files for all replicas \n"); - else { + std::string rep_data; + parse("REPLICA",rep_data); + if( rep_data=="all" ) { + output_for_all_replicas=true; + } else { + preps.resize(1); + Tools::convert( rep_data, preps[0] ); + } + if( output_for_all_replicas ) { + log.printf(" outputting files for all replicas \n"); + } else { log.printf(" outputting data for replicas "); - for(unsigned i=0; i0 ) return; + if( getStride()>0 ) { + return; + } - OFile ofile; ofile.link(*this); - ofile.open( filename ); printGrid( ofile ); + OFile ofile; + ofile.link(*this); + ofile.open( filename ); + printGrid( ofile ); } } diff --git a/src/gridtools/GridSearch.h b/src/gridtools/GridSearch.h index 1f4276eabf..dbe0367f51 100644 --- a/src/gridtools/GridSearch.h +++ b/src/gridtools/GridSearch.h @@ -41,50 +41,74 @@ class GridSearch { std::unique_ptr myfgrid; public: GridSearch( const std::vector& mmin, const std::vector& mmax, const std::vector& ng, const std::vector& nfg, FCLASS* funcc ) : - myclass_func( funcc ) - { + myclass_func( funcc ) { // Create the grid objects std::string nstr, vstring="COMPONENTS=func COORDINATES=x1"; - for(unsigned i=1; i(dar); - if( nfg[0]>0 ) myfgrid=Tools::make_unique(dar); + if( nfg[0]>0 ) { + myfgrid=Tools::make_unique(dar); + } // Now setup the min and max values for the grid - std::vector gmin( nfg.size() ), gmax( nfg.size() ); std::vector dummy_spacing; - for(unsigned i=0; isetBounds( gmin, gmax, ng, dummy_spacing ); mygrid->resize(); - if( myfgrid ) myfgrid->setBounds( gmin, gmax, nfg, dummy_spacing ); + std::vector gmin( nfg.size() ), gmax( nfg.size() ); + std::vector dummy_spacing; + for(unsigned i=0; isetBounds( gmin, gmax, ng, dummy_spacing ); + mygrid->resize(); + if( myfgrid ) { + myfgrid->setBounds( gmin, gmax, nfg, dummy_spacing ); + } } bool minimise( std::vector& p, engf_pointer myfunc ); }; 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 ); double emin=(myclass_func->*myfunc)( coords, der ); - mygrid->setValueAndDerivatives( 0, 0, emin, der ); unsigned pmin=0; + mygrid->setValueAndDerivatives( 0, 0, emin, der ); + unsigned pmin=0; for(unsigned i=1; igetNumberOfPoints(); ++i) { mygrid->getGridPointCoordinates( i, coords ); double eng = (myclass_func->*myfunc)( coords, der ); mygrid->setValueAndDerivatives( i, 0, eng, der ); - if( engsetNorm( 1.0 ); if( myfgrid ) { - myfgrid->getGridPointCoordinates( 0, coords ); pmin=0; + myfgrid->getGridPointCoordinates( 0, coords ); + pmin=0; double emin=mygrid->getValueAndDerivatives( coords, 0, der ); for(unsigned i=1; igetNumberOfPoints(); ++i) { myfgrid->getGridPointCoordinates( i, coords ); double eng = mygrid->getValueAndDerivatives( coords, 0, der ); - if( enggetGridPointCoordinates( pmin, coords ); double checkEng = (myclass_func->*myfunc)( coords, der ); diff --git a/src/gridtools/GridToXYZ.cpp b/src/gridtools/GridToXYZ.cpp index 033f7ac68b..9b3e7595b8 100644 --- a/src/gridtools/GridToXYZ.cpp +++ b/src/gridtools/GridToXYZ.cpp @@ -59,35 +59,47 @@ void GridToXYZ::registerKeywords( Keywords& keys ) { GridToXYZ::GridToXYZ(const ActionOptions&ao): Action(ao), - GridPrintingBase(ao) -{ - if( ingrid->getDimension()!=3 ) error("cannot print grid xyz file if grid does not contain three dimensional data"); + GridPrintingBase(ao) { + if( ingrid->getDimension()!=3 ) { + error("cannot print grid xyz file if grid does not contain three dimensional data"); + } fmt = " " + fmt; if( ingrid->getNumberOfComponents()==1 ) { mycomp=0; } else { - int tcomp=-1; parse("COMPONENT",tcomp); - if( tcomp<0 ) error("component of vector field was not specified - use COMPONENT keyword"); - mycomp=tcomp*(1+ingrid->getDimension()); if( ingrid->noDerivatives() ) mycomp=tcomp; + int tcomp=-1; + parse("COMPONENT",tcomp); + if( tcomp<0 ) { + error("component of vector field was not specified - use COMPONENT keyword"); + } + mycomp=tcomp*(1+ingrid->getDimension()); + if( ingrid->noDerivatives() ) { + mycomp=tcomp; + } log.printf(" using %dth component of grid \n",tcomp ); } fmt="%f"; - std::string precision; parse("PRECISION",precision); + std::string precision; + parse("PRECISION",precision); if(precision.length()>0) { - int p; Tools::convert(precision,p); + int p; + Tools::convert(precision,p); log<<" with precision "<getGridPointCoordinates( i, point ); ofile.printf("X"); double val; - if( ingrid->getType()=="flat" ) val=1.0; - else val=ingrid->getGridElement( i, 0 ); - for(unsigned j=0; j<3; ++j) { ofile.printf( (" " + fmt).c_str(), val*lenunit*point[j] ); } + if( ingrid->getType()=="flat" ) { + val=1.0; + } else { + val=ingrid->getGridElement( i, 0 ); + } + for(unsigned j=0; j<3; ++j) { + ofile.printf( (" " + fmt).c_str(), val*lenunit*point[j] ); + } ofile.printf("\n"); } } diff --git a/src/gridtools/GridVessel.cpp b/src/gridtools/GridVessel.cpp index f51ddbecec..864481e254 100644 --- a/src/gridtools/GridVessel.cpp +++ b/src/gridtools/GridVessel.cpp @@ -41,47 +41,84 @@ GridVessel::GridVessel( const vesselbase::VesselOptions& da ): npoints(0), cube_units(1.0), wasforced(false), - noderiv(false) -{ - std::string geom; parse("TYPE",geom); - if( geom=="flat" ) gtype=flat; - else if( geom=="fibonacci" ) gtype=fibonacci; - else plumed_merror( geom + " is invalid geometry type"); - std::vector compnames; parseVector("COMPONENTS",compnames); - std::vector coordnames; parseVector("COORDINATES",coordnames); + noderiv(false) { + std::string geom; + parse("TYPE",geom); + if( geom=="flat" ) { + gtype=flat; + } else if( geom=="fibonacci" ) { + gtype=fibonacci; + } else { + plumed_merror( geom + " is invalid geometry type"); + } + std::vector compnames; + parseVector("COMPONENTS",compnames); + std::vector coordnames; + parseVector("COORDINATES",coordnames); if( gtype==flat ) { dimension=coordnames.size(); - str_min.resize( dimension); str_max.resize( dimension ); stride.resize( dimension ); - max.resize( dimension ); dx.resize( dimension ); nbin.resize( dimension ); min.resize( dimension ); + str_min.resize( dimension); + str_max.resize( dimension ); + stride.resize( dimension ); + max.resize( dimension ); + dx.resize( dimension ); + nbin.resize( dimension ); + min.resize( dimension ); } else if( gtype==fibonacci ) { - if( coordnames.size()!=3 ) error("cannot generate fibonacci grid points on surface of sphere if not 3 input coordinates"); + if( coordnames.size()!=3 ) { + error("cannot generate fibonacci grid points on surface of sphere if not 3 input coordinates"); + } dimension=3; } - unsigned n=0; nper=compnames.size()*( 1 + coordnames.size() ); + unsigned n=0; + nper=compnames.size()*( 1 + coordnames.size() ); arg_names.resize( coordnames.size() + compnames.size()*( 1 + coordnames.size() ) ); - for(unsigned i=0; i spbc( dimension ); parseVector("PBC",spbc); + std::vector spbc( dimension ); + parseVector("PBC",spbc); for(unsigned i=0; i tnames( dimension ), cnames(nper); - for(unsigned i=0; i& smin, const std::vector& smax, @@ -89,9 +126,11 @@ void GridVessel::setBounds( const std::vector& smin, const std::vec plumed_dbg_assert( smin.size()==dimension && smax.size()==dimension ); plumed_assert( gtype==flat && (spacing.size()==dimension || binsin.size()==dimension) ); - npoints=1; bounds_set=true; + npoints=1; + bounds_set=true; for(unsigned i=0; i& smin, const std::vec Tools::convertNoexcept( str_max[i], max[i] ); if( spacing.size()==dimension && binsin.size()==dimension ) { - if( spacing[i]==0 ) nbin[i] = binsin[i]; - else { - double range = max[i] - min[i]; nbin[i] = std::round( range / spacing[i]); + if( spacing[i]==0 ) { + nbin[i] = binsin[i]; + } else { + double range = max[i] - min[i]; + nbin[i] = std::round( range / spacing[i]); // This check ensures that nbins is set correctly if spacing is set the same as the number of bins - if( nbin[i]!=binsin[i] ) plumed_merror("mismatch between input spacing and input number of bins"); + if( nbin[i]!=binsin[i] ) { + plumed_merror("mismatch between input spacing and input number of bins"); + } } - } else if( binsin.size()==dimension ) nbin[i]=binsin[i]; - else if( spacing.size()==dimension ) nbin[i] = std::floor(( max[i] - min[i] ) / spacing[i]) + 1; - else plumed_error(); + } else if( binsin.size()==dimension ) { + nbin[i]=binsin[i]; + } else if( spacing.size()==dimension ) { + nbin[i] = std::floor(( max[i] - min[i] ) / spacing[i]) + 1; + } else { + plumed_error(); + } dx[i] = ( max[i] - min[i] ) / static_cast( nbin[i] ); - if( !pbc[i] ) { max[i] +=dx[i]; nbin[i]+=1; } + if( !pbc[i] ) { + max[i] +=dx[i]; + nbin[i]+=1; + } stride[i]=npoints; npoints*=nbin[i]; } @@ -117,9 +167,13 @@ void GridVessel::setBounds( const std::vector& smin, const std::vec } void GridVessel::setupFibonacciGrid( const unsigned& np ) { - bounds_set=true; root5 = std::sqrt(5); - npoints = np; golden = ( 1 + std::sqrt(5) ) / 2.0; igolden = golden - 1; - fib_increment = 2*pi*igolden; log_golden2 = std::log( golden*golden ); + bounds_set=true; + root5 = std::sqrt(5); + npoints = np; + golden = ( 1 + std::sqrt(5) ) / 2.0; + igolden = golden - 1; + fib_increment = 2*pi*igolden; + log_golden2 = std::log( golden*golden ); fib_offset = 2 / static_cast( npoints ); fib_shift = fib_offset/2 - 1; resize(); @@ -128,57 +182,85 @@ void GridVessel::setupFibonacciGrid( const unsigned& np ) { // Find minimum distance between each pair of points 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); + } } } } std::string GridVessel::description() { - if( !bounds_set ) return ""; + if( !bounds_set ) { + return ""; + } std::string des; if( gtype==flat ) { - des="grid of "; std::string num; + des="grid of "; + std::string num; for(unsigned i=0; i0, "Number of datapoints at each grid point has not been set"); - if( getAction() ) resizeBuffer( getNumberOfBufferPoints()*nper + 1 + 2*getAction()->getNumberOfDerivatives() ); - setDataSize( npoints*nper ); forces.resize( npoints ); - if( active.size()!=npoints) active.resize( npoints, true ); + if( getAction() ) { + resizeBuffer( getNumberOfBufferPoints()*nper + 1 + 2*getAction()->getNumberOfDerivatives() ); + } + setDataSize( npoints*nper ); + forces.resize( npoints ); + if( active.size()!=npoints) { + active.resize( npoints, true ); + } } unsigned GridVessel::getIndex( const std::vector& indices ) const { @@ -205,10 +292,15 @@ void GridVessel::getIndices( const std::vector& point, std::vectornbin[i] ) { - std::string pp, num; Tools::convert( point[0], pp ); - for(unsigned j=1; jnbin[i] ) { + std::string pp, num; + Tools::convert( point[0], pp ); + for(unsigned j=1; j& point, std::vector& point ) const { plumed_dbg_assert( gtype==flat && 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 ); @@ -229,34 +322,63 @@ unsigned GridVessel::getIndex( const std::vector& point ) const { unsigned GridVessel::getFibonacciIndex( const std::vector& p ) const { plumed_dbg_assert( gtype==fibonacci ); // Convert input point to coordinates on cylinder - int k=2; double phi = std::atan2( p[2], p[0] ), sinthet2 = 1 - p[1]*p[1]; + int k=2; + double phi = std::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 GridVessel::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 GridVessel::getGridPointCoordinates( const unsigned& ipoint, std::vector& tindices, std::vector& x ) const { @@ -286,32 +410,54 @@ void GridVessel::getGridPointCoordinates( const unsigned& ipoint, std::vector& 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 = std::sqrt( 1 - x[1]*x[1] ); - double phi = ipoint*fib_increment; x[0] = r*std::cos(phi); x[2] = r*std::sin(phi); - double norm=0; for(unsigned j=0; j<3; ++j) norm+=x[j]*x[j]; - norm = std::sqrt(norm); for(unsigned j=0; j<3; ++j) x[j] = x[j] / norm; + x[1] = (ipoint*fib_offset) + fib_shift; + double r = std::sqrt( 1 - x[1]*x[1] ); + double phi = ipoint*fib_increment; + x[0] = r*std::cos(phi); + x[2] = r*std::sin(phi); + double norm=0; + for(unsigned j=0; j<3; ++j) { + norm+=x[j]*x[j]; + } + norm = std::sqrt(norm); + for(unsigned j=0; j<3; ++j) { + x[j] = x[j] / norm; + } } void GridVessel::getSplineNeighbors( const unsigned& mybox, unsigned& nneighbors, std::vector& mysneigh ) const { - plumed_dbg_assert( gtype==flat ); unsigned nneigh=unsigned(pow(2.0,int(dimension))); - if( mysneigh.size()!=nneigh ) mysneigh.resize(nneigh); + plumed_dbg_assert( gtype==flat ); + unsigned nneigh=unsigned(pow(2.0,int(dimension))); + if( mysneigh.size()!=nneigh ) { + mysneigh.resize(nneigh); + } - 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& der ) { plumed_dbg_assert( !noderiv && jelement& buffer, std::vector& der_list ) const { plumed_dbg_assert( myvals.getNumberOfValues()==(nper+1) ); - for(unsigned i=0; i& buffer ) { - if( wasforced ) getFinalForces( buffer, finalForces ); - else AveragingVessel::finish( buffer ); + if( wasforced ) { + getFinalForces( buffer, finalForces ); + } else { + AveragingVessel::finish( buffer ); + } } double GridVessel::getGridElement( const std::vector& indices, const unsigned& jelement ) const { @@ -361,19 +515,24 @@ void GridVessel::setGridElement( const std::vector& indices, const uns } std::vector GridVessel::getMin() const { - plumed_dbg_assert( gtype==flat ); return str_min; + plumed_dbg_assert( gtype==flat ); + return str_min; } std::vector GridVessel::getMax() const { - plumed_dbg_assert( gtype==flat ); return str_max; + plumed_dbg_assert( gtype==flat ); + return str_max; } std::vector GridVessel::getNbin() const { plumed_dbg_assert( gtype==flat && bounds_set ); std::vector ngrid( dimension ); for(unsigned i=0; i& pp, const std::vector< if( gtype == flat ) { plumed_dbg_assert( nneigh.size()==dimension ); std::vector indices( dimension ); - for(unsigned i=0; i& indices, const std:: 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; i s_indices(dimension), t_indices(dimension); @@ -415,10 +584,18 @@ void GridVessel::getNeighbors( const std::vector& indices, const std:: 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 ) { @@ -429,23 +606,33 @@ void GridVessel::getNeighbors( const std::vector& indices, const std:: } void GridVessel::setCubeUnits( const double& units ) { - plumed_dbg_assert( gtype==flat ); cube_units=units; + plumed_dbg_assert( gtype==flat ); + cube_units=units; } double GridVessel::getCubeUnits() const { - plumed_dbg_assert( gtype==flat ); return cube_units; + plumed_dbg_assert( gtype==flat ); + return cube_units; } std::string GridVessel::getInputString() const { std::string mstring="COORDINATES="+arg_names[0]; - for(unsigned i=1; i& x, const unsigned& ind, std::vector& der ) const { plumed_dbg_assert( gtype==flat && der.size()==dimension && !noderiv && ind fd(dimension); std::vector C(dimension); std::vector D(dimension); std::vector dder(dimension); - std::vector nindices(dimension); unsigned n_neigh; - std::vector indices(dimension); getIndices( x, indices ); - std::vector neigh; getSplineNeighbors( getIndex(indices), n_neigh, neigh ); - std::vector xfloor(dimension); getFlatGridCoordinates( getIndex(x), nindices, xfloor ); + std::vector nindices(dimension); + unsigned n_neigh; + std::vector indices(dimension); + getIndices( x, indices ); + std::vector neigh; + getSplineNeighbors( getIndex(indices), n_neigh, neigh ); + std::vector xfloor(dimension); + getFlatGridCoordinates( getIndex(x), nindices, xfloor ); // loop over neighbors for(unsigned int ipoint=0; ipoint& x, const u } for(unsigned j=0; j& to_activate ) { plumed_dbg_assert( to_activate.size()==npoints ); - for(unsigned i=0; i& inforces ) { plumed_dbg_assert( inforces.size()==npoints ); - wasforced=true; for(unsigned i=0; i& fforces ) { plumed_dbg_assert( fforces.size()==finalForces.size() ); - if( !wasforced ) return false; - for(unsigned i=0; i& buffer, std::vector& finalForces ) { plumed_error(); } + virtual void getFinalForces( const std::vector& buffer, std::vector& finalForces ) { + plumed_error(); + } /// Apply the forces void setForce( const std::vector& inforces ); /// Was a force added to the grid @@ -206,14 +208,19 @@ unsigned GridVessel::getNumberOfPoints() const { inline const std::vector& GridVessel::getGridSpacing() const { - if( gtype==flat ) return dx; + if( gtype==flat ) { + return dx; + } plumed_merror("dont understand what spacing means for spherical grids"); } inline double GridVessel::getCellVolume() const { if( gtype==flat ) { - double myvol=1.0; for(unsigned i=0; i( getNumberOfPoints() ); @@ -238,7 +245,9 @@ std::string GridVessel::getComponentName( const unsigned& i ) const { inline unsigned GridVessel::getNumberOfComponents() const { - if( noderiv ) return nper; + if( noderiv ) { + return nper; + } return nper / ( dimension + 1 ); } @@ -272,8 +281,11 @@ unsigned GridVessel::getNumberOfBufferPoints() const { inline std::string GridVessel::getType() const { - if( gtype==flat ) return "flat"; - else if( gtype==fibonacci ) return "fibonacci"; + if( gtype==flat ) { + return "flat"; + } else if( gtype==fibonacci ) { + return "fibonacci"; + } plumed_error(); } diff --git a/src/gridtools/HistogramOnGrid.cpp b/src/gridtools/HistogramOnGrid.cpp index 23be915151..48881a9bf3 100644 --- a/src/gridtools/HistogramOnGrid.cpp +++ b/src/gridtools/HistogramOnGrid.cpp @@ -37,12 +37,12 @@ HistogramOnGrid::HistogramOnGrid( const vesselbase::VesselOptions& da ): neigh_tot(0), addOneKernelAtATime(false), bandwidths(dimension), - discrete(false) -{ + discrete(false) { if( getType()=="flat" ) { parse("KERNEL",kerneltype); if( kerneltype=="discrete" || kerneltype=="DISCRETE" ) { - discrete=true; setNoDerivatives(); + discrete=true; + setNoDerivatives(); } else { parseVector("BANDWIDTH",bandwidths); } @@ -65,10 +65,14 @@ void HistogramOnGrid::setBounds( const std::vector& smin, const std GridVessel::setBounds( smin, smax, nbins, spacing ); if( !discrete ) { std::vector point(dimension,0); - KernelFunctions kernel( point, bandwidths, kerneltype, "DIAGONAL", 1.0 ); neigh_tot=1; - nneigh=kernel.getSupport( dx ); std::vector support( kernel.getContinuousSupport() ); + KernelFunctions kernel( point, bandwidths, kerneltype, "DIAGONAL", 1.0 ); + neigh_tot=1; + nneigh=kernel.getSupport( dx ); + std::vector support( kernel.getContinuousSupport() ); for(unsigned i=0; igetGridExtent(i) ) error("bandwidth is too large for periodic grid"); + if( pbc[i] && 2*support[i]>getGridExtent(i) ) { + error("bandwidth is too large for periodic grid"); + } neigh_tot *= (2*nneigh[i]+1); } } @@ -77,14 +81,19 @@ void HistogramOnGrid::setBounds( const std::vector& smin, const std std::unique_ptr HistogramOnGrid::getKernelAndNeighbors( std::vector& point, unsigned& num_neigh, std::vector& neighbors ) const { if( discrete ) { plumed_assert( getType()=="flat" ); - num_neigh=1; for(unsigned i=0; i( point, bandwidths, kerneltype, "DIAGONAL", 1.0 ); // GB: Now values is destroyed when exiting this function. // I think before there was a leak std::vector> values=getVectorOfValues(); - kernel->normalize( Tools::unique2raw(values) ); getNeighbors( kernel->getCenter(), nneigh, num_neigh, neighbors ); + kernel->normalize( Tools::unique2raw(values) ); + getNeighbors( kernel->getCenter(), nneigh, num_neigh, neighbors ); return kernel; } else if( getType()=="fibonacci" ) { getNeighbors( point, nneigh, num_neigh, neighbors ); @@ -99,8 +108,11 @@ std::vector> HistogramOnGrid::getVectorOfValues() const { std::vector> vv; for(unsigned i=0; i()); - if( pbc[i] ) vv[i]->setDomain( str_min[i], str_max[i] ); - else vv[i]->setNotPeriodic(); + if( pbc[i] ) { + vv[i]->setDomain( str_min[i], str_max[i] ); + } else { + vv[i]->setNotPeriodic(); + } } return vv; } @@ -109,40 +121,59 @@ void HistogramOnGrid::calculate( const unsigned& current, MultiValue& myvals, st if( addOneKernelAtATime ) { plumed_dbg_assert( myvals.getNumberOfValues()==2 && !wasforced ); std::vector der( dimension ); - for(unsigned i=0; igetPositionInCurrentTaskList(current), myvals.get(0), myvals.get(1), der, buffer ); } else { plumed_dbg_assert( myvals.getNumberOfValues()==dimension+2 ); - std::vector point( dimension ); double weight=myvals.get(0)*myvals.get( 1+dimension ); - for(unsigned i=0; i point( dimension ); + double weight=myvals.get(0)*myvals.get( 1+dimension ); + for(unsigned i=0; i neighbors(1); + unsigned num_neigh; + std::vector neighbors(1); std::vector der( dimension ); std::unique_ptr kernel=getKernelAndNeighbors( point, num_neigh, neighbors ); if( !kernel && getType()=="flat" ) { - plumed_dbg_assert( num_neigh==1 ); der.resize(0); + plumed_dbg_assert( num_neigh==1 ); + der.resize(0); accumulate( neighbors[0], weight, 1.0, der, buffer ); } else { double totwforce=0.0; std::vector intforce( 2*dimension, 0.0 ); std::vector> vv( getVectorOfValues() ); - double newval; std::vector tindices( dimension ); std::vector xx( dimension ); + double newval; + std::vector tindices( dimension ); + std::vector xx( dimension ); for(unsigned i=0; iset(xx[j]); + for(unsigned j=0; jset(xx[j]); + } newval = kernel->evaluate( Tools::unique2raw(vv), der, true ); } else { // Evalulate dot product - double dot=0; for(unsigned j=0; jgetNumberOfDerivatives(); unsigned gridbuf = getNumberOfBufferPoints()*getNumberOfQuantities(); for(unsigned j=0; j& der, std::vector& buffer ) const { buffer[bufstart+nper*ipoint] += weight*dens; - if( der.size()>0 ) for(unsigned j=0; j0 ) + for(unsigned j=0; j& der, std::vector& intforce ) const { - for(unsigned j=0; j& buffer, std::vector& finalForces ) { - if( finalForces.size()!=getAction()->getNumberOfDerivatives() ) finalForces.resize( getAction()->getNumberOfDerivatives() ); + if( finalForces.size()!=getAction()->getNumberOfDerivatives() ) { + finalForces.resize( getAction()->getNumberOfDerivatives() ); + } // And the final force unsigned nder = getAction()->getNumberOfDerivatives(); // Derivatives due to normalization unsigned gridbuf = getNumberOfBufferPoints()*getNumberOfQuantities(); - for(unsigned i=0; i& buffer ) { if( addOneKernelAtATime ) { for(unsigned i=0; igetCurrentNumberOfActiveTasks(); ++i) { - for(unsigned j=0; jgetActiveTask(i)+j, buffer[bufstart+i*nper+j] ); + for(unsigned j=0; jgetActiveTask(i)+j, buffer[bufstart+i*nper+j] ); + } } } else { GridVessel::finish( buffer ); diff --git a/src/gridtools/HistogramOnGrid.h b/src/gridtools/HistogramOnGrid.h index a60b3080bd..7c5fd39186 100644 --- a/src/gridtools/HistogramOnGrid.h +++ b/src/gridtools/HistogramOnGrid.h @@ -54,7 +54,9 @@ class HistogramOnGrid : public GridVessel { unsigned getNumberOfBufferPoints() const override; std::unique_ptr getKernelAndNeighbors( std::vector& point, unsigned& num_neigh, std::vector& neighbors ) const; std::vector> getVectorOfValues() const ; - void addOneKernelEachTimeOnly() { addOneKernelAtATime=true; } + void addOneKernelEachTimeOnly() { + addOneKernelAtATime=true; + } void getFinalForces( const std::vector& buffer, std::vector& finalForces ) override; bool noDiscreteKernels() const ; double getFibonacciCutoff() const override; @@ -62,7 +64,9 @@ class HistogramOnGrid : public GridVessel { inline unsigned HistogramOnGrid::getNumberOfBufferPoints() const { - if( addOneKernelAtATime ) return neigh_tot; + if( addOneKernelAtATime ) { + return neigh_tot; + } return GridVessel::getNumberOfBufferPoints(); } diff --git a/src/gridtools/IntegrateGrid.cpp b/src/gridtools/IntegrateGrid.cpp index e3abba97c2..e3fa22c71e 100644 --- a/src/gridtools/IntegrateGrid.cpp +++ b/src/gridtools/IntegrateGrid.cpp @@ -49,13 +49,15 @@ void IntegrateGrid::registerKeywords( Keywords& keys ) { IntegrateGrid::IntegrateGrid(const ActionOptions&ao): Action(ao), - ActionWithIntegral(ao) -{ + ActionWithIntegral(ao) { } void IntegrateGrid::compute( const unsigned& current, MultiValue& myvals ) const { - myvals.setValue( 0, 1.0 ); myvals.setValue( 1, getVolume()*getFunctionValue( current ) ); - if( !doNotCalculateDerivatives() ) myvals.addDerivative( 1, current, getVolume() ); + myvals.setValue( 0, 1.0 ); + myvals.setValue( 1, getVolume()*getFunctionValue( current ) ); + if( !doNotCalculateDerivatives() ) { + myvals.addDerivative( 1, current, getVolume() ); + } } } diff --git a/src/gridtools/InterpolateGrid.cpp b/src/gridtools/InterpolateGrid.cpp index e0335b53ba..72a825935f 100644 --- a/src/gridtools/InterpolateGrid.cpp +++ b/src/gridtools/InterpolateGrid.cpp @@ -56,7 +56,9 @@ class InterpolateGrid : public ActionWithInputGrid { explicit InterpolateGrid(const ActionOptions&ao); unsigned getNumberOfQuantities() const override; void compute( const unsigned& current, MultiValue& myvals ) const override; - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(InterpolateGrid,"INTERPOLATE_GRID") @@ -65,21 +67,25 @@ void InterpolateGrid::registerKeywords( Keywords& keys ) { ActionWithInputGrid::registerKeywords( keys ); keys.add("optional","GRID_BIN","the number of bins for the grid"); keys.add("optional","GRID_SPACING","the approximate grid spacing (to be used as an alternative or together with GRID_BIN)"); - keys.remove("KERNEL"); keys.remove("BANDWIDTH"); + keys.remove("KERNEL"); + keys.remove("BANDWIDTH"); } InterpolateGrid::InterpolateGrid(const ActionOptions&ao): Action(ao), - ActionWithInputGrid(ao) -{ + ActionWithInputGrid(ao) { plumed_assert( ingrid->getNumberOfComponents()==1 ); - if( ingrid->noDerivatives() ) error("cannot interpolate a grid that does not have derivatives"); + if( ingrid->noDerivatives() ) { + error("cannot interpolate a grid that does not have derivatives"); + } // Create the input from the old string auto grid=createGrid( "grid", "COMPONENTS=" + getLabel() + " " + ingrid->getInputString() ); // notice that createGrid also sets mygrid=grid.get() - std::vector nbin; parseVector("GRID_BIN",nbin); - std::vector gspacing; parseVector("GRID_SPACING",gspacing); + std::vector nbin; + parseVector("GRID_BIN",nbin); + std::vector gspacing; + parseVector("GRID_SPACING",gspacing); if( nbin.size()!=ingrid->getDimension() && gspacing.size()!=ingrid->getDimension() ) { error("GRID_BIN or GRID_SPACING must be set"); } @@ -89,10 +95,14 @@ InterpolateGrid::InterpolateGrid(const ActionOptions&ao): setAveragingAction( std::move(grid), true ); // Now create task list - for(unsigned i=0; igetNumberOfPoints(); ++i) addTaskToList(i); + for(unsigned i=0; igetNumberOfPoints(); ++i) { + addTaskToList(i); + } // And activate all tasks deactivateAllTasks(); - for(unsigned i=0; igetNumberOfPoints(); ++i) taskFlags[i]=1; + for(unsigned i=0; igetNumberOfPoints(); ++i) { + taskFlags[i]=1; + } lockContributors(); } @@ -101,10 +111,15 @@ unsigned InterpolateGrid::getNumberOfQuantities() const { } void InterpolateGrid::compute( const unsigned& current, MultiValue& myvals ) const { - std::vector pos( mygrid->getDimension() ); mygrid->getGridPointCoordinates( current, pos ); - std::vector der( mygrid->getDimension() ); double val = getFunctionValueAndDerivatives( pos, der ); - myvals.setValue( 0, 1.0 ); myvals.setValue(1, val ); - for(unsigned i=0; igetDimension(); ++i) myvals.setValue( 2+i, der[i] ); + std::vector pos( mygrid->getDimension() ); + mygrid->getGridPointCoordinates( current, pos ); + std::vector der( mygrid->getDimension() ); + double val = getFunctionValueAndDerivatives( pos, der ); + myvals.setValue( 0, 1.0 ); + myvals.setValue(1, val ); + for(unsigned i=0; igetDimension(); ++i) { + myvals.setValue( 2+i, der[i] ); + } } } diff --git a/src/isdb/CS2Backbone.cpp b/src/isdb/CS2Backbone.cpp index f6e40be6b2..12b1eb4a49 100644 --- a/src/isdb/CS2Backbone.cpp +++ b/src/isdb/CS2Backbone.cpp @@ -175,160 +175,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); @@ -567,10 +608,13 @@ CS2Backbone::CS2Backbone(const ActionOptions&ao): db.parse(stringadb,scale); PDB pdb; - if( !pdb.read(stringapdb,plumed.getAtoms().usingNaturalUnits(),1./scale) ) plumed_merror("missing input file " + stringapdb); + if( !pdb.read(stringapdb,plumed.getAtoms().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); @@ -590,15 +634,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; @@ -660,42 +717,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); @@ -704,44 +792,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]); @@ -890,8 +1042,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") { @@ -949,14 +1105,21 @@ void CS2Backbone::init_rings(const PDB &pdb) } } - for(unsigned cs=0; cs camshift_sigma2(6); @@ -975,7 +1138,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(); @@ -985,7 +1150,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) @@ -1010,9 +1177,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; @@ -1109,9 +1280,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; @@ -1130,8 +1305,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; @@ -1183,7 +1362,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; @@ -1273,7 +1454,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) { @@ -1286,8 +1469,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; + } } } @@ -1391,7 +1587,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 e6e78c3331..6dca3326bf 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 bf64240334..f8d099c12c 100644 --- a/src/isdb/EMMI.cpp +++ b/src/isdb/EMMI.cpp @@ -109,8 +109,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 @@ -292,8 +291,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 @@ -329,27 +331,38 @@ 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, getNumberOfArguments() ); + if( getNumberOfAtoms()>0 ) { + setForcesOnAtoms( forcesToApply, getNumberOfArguments() ); + } } } @@ -445,8 +458,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 +475,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 @@ -508,8 +538,11 @@ EMMI::EMMI(const ActionOptions&ao): double temp=0.0; parse("TEMP",temp); // convert temp to kbt - if(temp>0.0) kbt_=plumed.getAtoms().getKBoltzmann()*temp; - else kbt_=plumed.getAtoms().getKbT(); + if(temp>0.0) { + kbt_=plumed.getAtoms().getKBoltzmann()*temp; + } else { + kbt_=plumed.getAtoms().getKbT(); + } // exponent of uncertainty prior parse("PRIOR",prior_); @@ -517,7 +550,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_); @@ -527,8 +562,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 @@ -537,13 +576,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_); @@ -551,7 +596,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(); @@ -574,11 +621,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); @@ -589,10 +645,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_); @@ -637,14 +701,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) { @@ -668,8 +738,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]); } @@ -694,7 +767,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); @@ -709,17 +784,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"); @@ -732,15 +817,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); @@ -752,16 +842,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 @@ -795,8 +888,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(); @@ -806,7 +898,8 @@ void EMMI::read_status() while(ifile->scanField("MD_time", MDtime)) { for(unsigned i=0; iscanField("s"+num, sigma_[i]); } @@ -819,8 +912,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; @@ -834,7 +926,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 @@ -922,7 +1022,9 @@ void EMMI::doMonteCarlo() } // local communication if(rank_!=0) { - for(unsigned i=0; i1) { @@ -931,12 +1033,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; @@ -952,7 +1054,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; @@ -971,8 +1074,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; @@ -996,8 +1098,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; @@ -1055,24 +1156,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(std::string GMM_file) -{ +void EMMI::get_GMM_d(std::string GMM_file) { VectorGeneric<6> cov; // open file @@ -1097,7 +1199,9 @@ void EMMI::get_GMM_d(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 @@ -1118,13 +1222,14 @@ void EMMI::get_GMM_d(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 @@ -1137,10 +1242,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]); @@ -1220,8 +1336,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; @@ -1239,12 +1354,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]; @@ -1260,12 +1377,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]; @@ -1275,8 +1394,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(); @@ -1301,7 +1419,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 @@ -1312,7 +1432,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 @@ -1322,12 +1444,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 @@ -1351,9 +1477,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 @@ -1365,8 +1492,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 @@ -1474,8 +1610,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 @@ -1484,21 +1619,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_); @@ -1513,12 +1655,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(); @@ -1553,15 +1698,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) { @@ -1611,7 +1774,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_); @@ -1669,10 +1841,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_; @@ -1684,8 +1860,7 @@ void EMMI::calculate() } -void EMMI::calculate_Gauss() -{ +void EMMI::calculate_Gauss() { // cycle on all the GMM groups for(unsigned i=0; i 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); @@ -115,8 +115,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"; @@ -130,7 +133,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 8c3bd4e6e4..0a97686da2 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 }; @@ -125,8 +124,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; @@ -181,13 +179,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.); @@ -327,7 +337,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; @@ -364,7 +376,8 @@ void JCoupling::calculate() } else { for (unsigned r=0; rset(j[r]); setAtomsDerivatives(val, a0, deriv[a0]); @@ -387,7 +400,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 c9b81317d8..9bdcb88594 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; @@ -597,9 +687,14 @@ Metainference::Metainference(const ActionOptions&ao): // get temperature double temp=0.0; parse("TEMP",temp); - if(temp>0.0) kbt_=plumed.getAtoms().getKBoltzmann()*temp; - else kbt_=plumed.getAtoms().getKbT(); - if(kbt_==0.0) error("Unless the MD engine passes the temperature to plumed, you must specify it using TEMP"); + if(temp>0.0) { + kbt_=plumed.getAtoms().getKBoltzmann()*temp; + } else { + kbt_=plumed.getAtoms().getKbT(); + } + if(kbt_==0.0) { + error("Unless the MD engine passes the temperature to plumed, you must specify it using TEMP"); + } checkRead(); @@ -637,7 +732,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_); } @@ -717,13 +820,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]); } @@ -886,7 +1016,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); @@ -908,20 +1040,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; @@ -936,22 +1072,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) @@ -965,20 +1103,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) { @@ -987,26 +1127,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]); @@ -1024,15 +1173,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; @@ -1047,15 +1199,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_; @@ -1086,8 +1241,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_) { @@ -1096,8 +1250,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; @@ -1113,8 +1271,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; @@ -1148,7 +1310,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; @@ -1175,8 +1339,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_; @@ -1199,8 +1362,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 @@ -1209,8 +1376,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]; + } } } @@ -1257,8 +1428,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.; @@ -1297,13 +1467,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; } @@ -1345,8 +1531,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; @@ -1364,14 +1549,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); @@ -1389,8 +1575,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); @@ -1408,14 +1593,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); @@ -1432,14 +1618,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); @@ -1462,14 +1649,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()); @@ -1491,8 +1681,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.); @@ -1528,15 +1717,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_); @@ -1549,12 +1739,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) { @@ -1608,13 +1814,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]; + } } } } @@ -1654,22 +1868,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; @@ -1684,14 +1905,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.; @@ -1712,7 +1934,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); @@ -1739,8 +1963,7 @@ void Metainference::calculate() setBias(ene); } -void Metainference::writeStatus() -{ +void Metainference::writeStatus() { sfile_.rewind(); sfile_.printField("time",getTimeStep()*getStep()); //nsel @@ -1797,7 +2020,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 1fb434e3a1..a6fa2c2264 100644 --- a/src/isdb/MetainferenceBase.cpp +++ b/src/isdb/MetainferenceBase.cpp @@ -126,8 +126,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; @@ -138,7 +137,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; @@ -149,18 +150,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); @@ -171,50 +183,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; @@ -324,9 +399,14 @@ MetainferenceBase::MetainferenceBase(const ActionOptions&ao): // get temperature double temp=0.0; parse("TEMP",temp); - if(temp>0.0) kbt_=plumed.getAtoms().getKBoltzmann()*temp; - else kbt_=plumed.getAtoms().getKbT(); - if(kbt_==0.0&&doscore_) error("Unless the MD engine passes the temperature to plumed, you must specify it using TEMP"); + if(temp>0.0) { + kbt_=plumed.getAtoms().getKBoltzmann()*temp; + } else { + kbt_=plumed.getAtoms().getKbT(); + } + 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; @@ -344,7 +424,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); @@ -367,24 +449,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_); } @@ -513,7 +613,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]); } @@ -583,8 +692,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: @@ -611,7 +723,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; @@ -705,22 +836,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) @@ -734,20 +867,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) { @@ -756,26 +891,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]); @@ -793,15 +937,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; @@ -816,15 +963,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_; @@ -855,8 +1005,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_) { @@ -865,8 +1014,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; @@ -882,8 +1035,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; @@ -917,7 +1074,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; @@ -944,8 +1103,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_; @@ -968,8 +1126,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 @@ -978,8 +1140,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]; + } } } @@ -1026,8 +1192,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.; @@ -1066,13 +1231,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; } @@ -1114,8 +1295,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; @@ -1133,14 +1313,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); @@ -1158,8 +1339,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); @@ -1177,14 +1357,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); @@ -1201,14 +1382,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); @@ -1231,14 +1413,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()); @@ -1260,8 +1445,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.); @@ -1297,15 +1481,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_); @@ -1317,12 +1502,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) { @@ -1376,13 +1577,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]; + } } } } @@ -1422,22 +1631,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; @@ -1452,8 +1668,7 @@ void MetainferenceBase::do_regression_zero(const std::vector &mean) } } -double MetainferenceBase::getScore() -{ +double MetainferenceBase::getScore() { /* Metainference */ /* 1) collect weights */ double weight = 0.; @@ -1474,7 +1689,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); @@ -1501,9 +1718,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 f5cdee85b1..0ad5689492 100644 --- a/src/isdb/MetainferenceBase.h +++ b/src/isdb/MetainferenceBase.h @@ -43,8 +43,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; @@ -208,62 +207,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 @@ -325,27 +322,38 @@ 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, getNumberOfArguments() ); + if( getNumberOfAtoms()>0 ) { + setForcesOnAtoms( forcesToApply, getNumberOfArguments() ); + } } } diff --git a/src/isdb/NOE.cpp b/src/isdb/NOE.cpp index cd86ed37f6..fcb30ab1d2 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; @@ -100,8 +99,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; @@ -110,21 +108,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); @@ -133,13 +143,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}); @@ -206,8 +230,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; @@ -233,7 +263,9 @@ void NOE::calculate() val->set(noe); if(!getDoScore()) { setBoxDerivatives(val, dervir); - } else setCalcData(i, noe); + } else { + setCalcData(i, noe); + } } if(getDoScore()) { @@ -246,15 +278,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)); @@ -267,7 +304,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 860cc21b2b..f241d6f390 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; @@ -111,8 +110,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; @@ -123,14 +121,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); @@ -202,20 +227,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.); @@ -257,9 +288,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; @@ -279,7 +316,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) { @@ -299,7 +338,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()) { @@ -312,15 +353,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)); @@ -333,7 +379,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 7c4deae748..5702a6b3f2 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; @@ -247,8 +246,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; @@ -256,16 +254,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]); @@ -277,38 +281,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); + } } } @@ -497,12 +537,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 e0bfb09c7c..c38090a883 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_; @@ -186,8 +185,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(); @@ -212,19 +210,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; } @@ -266,8 +272,11 @@ Rescale::Rescale(const ActionOptions&ao): // get temperature double temp=0.0; parse("TEMP",temp); - if(temp>0.0) kbt_=plumed.getAtoms().getKBoltzmann()*temp; - else kbt_=plumed.getAtoms().getKbT(); + if(temp>0.0) { + kbt_=plumed.getAtoms().getKBoltzmann()*temp; + } else { + kbt_=plumed.getAtoms().getKbT(); + } checkRead(); @@ -275,7 +284,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); @@ -333,24 +347,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_; @@ -360,14 +379,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, - std::vector args, std::vector bargs) -{ + std::vector args, std::vector bargs) { double oldB, newB; // cycle on MC steps @@ -399,7 +419,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; @@ -411,8 +433,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; @@ -437,8 +458,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_]); @@ -449,9 +469,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; @@ -459,12 +484,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) { @@ -506,7 +545,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 2664474653..9894987f2b 100644 --- a/src/isdb/SAXS.cpp +++ b/src/isdb/SAXS.cpp @@ -223,8 +223,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, @@ -349,10 +348,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); @@ -363,21 +364,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 @@ -391,34 +401,60 @@ 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"); + } - 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((!atomistic)&&(!martini)&&(!onebead)&&(!saxs)) error("External PARAMETERS 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((!atomistic)&&(!martini)&&(!onebead)&&(!saxs)) { + error("External PARAMETERS cannot be used with SANS"); + } 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 < 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,plumed.getAtoms().usingNaturalUnits(),1.) ) plumed_merror("missing input file " + template_name); + if( !pdb.read(template_name,plumed.getAtoms().usingNaturalUnits(),1.) ) { + plumed_merror("missing input file " + template_name); + } } // Here we perform the preliminary mapping for onebead representation @@ -497,10 +549,14 @@ SAXS::SAXS(const ActionOptions&ao): parameter.resize(size); ntarget=0; for(unsigned i=0; i(size)); for(unsigned i=0; i(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; } @@ -602,14 +665,24 @@ 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) { @@ -776,8 +856,7 @@ void SAXS::calcNlist(std::vector > &Nlist) } // calculates SASA according to LCPO algorithm -void SAXS::sasa_calculate(std::vector &solv_res) -{ +void SAXS::sasa_calculate(std::vector &solv_res) { unsigned natoms = getNumberOfAtoms(); std::vector > Nlist(natoms); calcNlist(Nlist); @@ -815,17 +894,22 @@ void SAXS::sasa_calculate(std::vector &solv_res) } } 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; @@ -925,10 +1009,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(); @@ -985,8 +1074,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(); @@ -1015,7 +1112,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); @@ -1043,7 +1142,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 */ @@ -1158,7 +1264,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) { @@ -1216,11 +1323,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; atoms_masses.resize(atoms.size()); @@ -1238,7 +1348,8 @@ unsigned SAXS::getOnebeadMapping(const PDB &pdb, const std::vector & Rname.erase(std::remove_if(Rname.begin(), Rname.end(), ::isspace),Rname.end()); std::vector res_atoms = pdb.getAtomsInResidue(res, chains[i]); unsigned first_time=1; - std::vector > tmp_residue_atom; tmp_residue_atom.resize(3); + std::vector > tmp_residue_atom; + tmp_residue_atom.resize(3); // cycle over atoms for(unsigned a=0; a & } else { type = Aname.at(1); } - if (type == 'H') atoms_masses[res_atoms[a].index()] = 1.008; - else if(type == 'C') atoms_masses[res_atoms[a].index()] = 12.011; - else if(type == 'N') atoms_masses[res_atoms[a].index()] = 14.007; - else if(type == 'O') atoms_masses[res_atoms[a].index()] = 15.999; - else if(type == 'S') atoms_masses[res_atoms[a].index()] = 32.065; - else if(type == 'P') atoms_masses[res_atoms[a].index()] = 30.974; - else { + if (type == 'H') { + atoms_masses[res_atoms[a].index()] = 1.008; + } else if(type == 'C') { + atoms_masses[res_atoms[a].index()] = 12.011; + } else if(type == 'N') { + atoms_masses[res_atoms[a].index()] = 14.007; + } else if(type == 'O') { + atoms_masses[res_atoms[a].index()] = 15.999; + } else if(type == 'S') { + atoms_masses[res_atoms[a].index()] = 32.065; + } else if(type == 'P') { + atoms_masses[res_atoms[a].index()] = 30.974; + } else { error("Unknown element in mass extraction\n"); } if(pdb.allowedResidue("protein",Rname)) { @@ -1296,17 +1413,25 @@ unsigned SAXS::getOnebeadMapping(const PDB &pdb, const std::vector & tmp_residue_atom[2].push_back(res_atoms[a].index()); } // 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)) { atoms_per_bead.push_back(tmp_residue_atom[0].size()); - for(unsigned tmp_i=0; tmp_i0) { atoms_per_bead.push_back(tmp_residue_atom[2].size()); - for(unsigned tmp_i=0; tmp_i & 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); @@ -2389,7 +2513,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, 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, std::vector residue_atom) { parameter_solv[TRP].push_back(60737.60249988003); parameter_solv[TRP].push_back(-77.75716755173752); @@ -3589,7 +3770,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" || @@ -3607,7 +3790,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'" || @@ -3622,7 +3807,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=="OP3" || @@ -3639,7 +3826,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" || @@ -3656,7 +3845,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'" || @@ -3670,7 +3861,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=="OP3" || @@ -3688,7 +3881,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" || @@ -3706,7 +3901,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'" || @@ -3721,7 +3918,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=="OP3" || @@ -3738,7 +3937,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" || @@ -3755,7 +3956,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'" || @@ -3769,7 +3972,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=="OP3" || @@ -3787,7 +3992,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" || @@ -3805,7 +4012,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'" || @@ -3820,7 +4029,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=="OP3" || @@ -3838,7 +4049,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" || @@ -3856,7 +4069,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'" || @@ -3871,7 +4086,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=="OP3" || @@ -3889,7 +4106,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" || @@ -3907,7 +4126,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'" || @@ -3922,7 +4143,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=="OP3" || @@ -3939,7 +4162,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" || @@ -3956,7 +4181,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'" || @@ -3970,13 +4197,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); @@ -4848,7 +5078,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" || @@ -4866,7 +5098,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'" || @@ -4881,7 +5115,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=="OP3" || @@ -4898,7 +5134,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" || @@ -4915,7 +5153,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'" || @@ -4929,7 +5169,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=="OP3" || @@ -4947,7 +5189,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" || @@ -4965,7 +5209,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'" || @@ -4980,7 +5226,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=="OP3" || @@ -4997,7 +5245,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" || @@ -5014,7 +5264,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'" || @@ -5028,7 +5280,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=="OP3" || @@ -5046,7 +5300,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" || @@ -5064,7 +5320,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'" || @@ -5079,7 +5337,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=="OP3" || @@ -5097,7 +5357,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" || @@ -5115,7 +5377,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'" || @@ -5130,7 +5394,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=="OP3" || @@ -5148,7 +5414,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" || @@ -5166,7 +5434,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'" || @@ -5181,7 +5451,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=="OP3" || @@ -5198,7 +5470,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" || @@ -5215,7 +5489,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'" || @@ -5229,13 +5505,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); @@ -5843,7 +6123,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" || @@ -5861,7 +6143,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'" || @@ -5876,7 +6160,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=="OP3" || @@ -5893,7 +6179,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" || @@ -5910,7 +6198,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'" || @@ -5924,7 +6214,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=="OP3" || @@ -5942,7 +6234,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" || @@ -5960,7 +6254,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'" || @@ -5975,7 +6271,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=="OP3" || @@ -5992,7 +6290,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" || @@ -6009,7 +6309,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'" || @@ -6023,7 +6325,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=="OP3" || @@ -6041,7 +6345,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" || @@ -6059,7 +6365,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'" || @@ -6074,7 +6382,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=="OP3" || @@ -6092,7 +6402,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" || @@ -6110,7 +6422,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'" || @@ -6125,7 +6439,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=="OP3" || @@ -6143,7 +6459,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" || @@ -6161,7 +6479,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'" || @@ -6176,7 +6496,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=="OP3" || @@ -6193,7 +6515,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" || @@ -6210,7 +6534,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'" || @@ -6224,13 +6550,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; @@ -6249,41 +6578,83 @@ double SAXS::calculateAFF(const std::vector &atoms, std::vector(this); @@ -6323,7 +6694,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; @@ -6352,13 +6724,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) @@ -7409,12 +7787,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); diff --git a/src/isdb/Select.cpp b/src/isdb/Select.cpp index 2c3f6843a6..1191bea4e1 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: @@ -85,12 +84,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()); @@ -98,15 +97,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=0.0 ) { kbt *= plumed.getAtoms().getKBoltzmann(); - } - else { + } else { kbt = plumed.getAtoms().getKbT(); } if( kbtpd>=0.0 ) { kbtpd *= plumed.getAtoms().getKBoltzmann(); - } - else { + } else { kbtpd = kbt; } @@ -655,11 +651,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; } @@ -669,23 +663,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); @@ -772,7 +774,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"); } @@ -932,7 +932,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( getDependencies()[0] ); @@ -52,9 +51,12 @@ ManyRestraintsBase::ManyRestraintsBase(const ActionOptions& ao): aves->getName().c_str(),aves->getLabel().c_str()); // Add a task list in order to avoid problems - for(unsigned i=0; igetFullNumberOfTasks(); ++i) addTaskToList( aves->getTaskCode(i) ); + for(unsigned i=0; igetFullNumberOfTasks(); ++i) { + addTaskToList( aves->getTaskCode(i) ); + } // And turn on the derivatives (note problems here because of ActionWithValue) - turnOnDerivatives(); needsDerivatives(); + turnOnDerivatives(); + needsDerivatives(); // Now create the vessel std::string fake_input="LABEL=bias"; @@ -81,7 +83,9 @@ void ManyRestraintsBase::transformBridgedDerivatives( const unsigned& current, M // Now update the outvals derivatives lists outvals.emptyActiveMembers(); - for(unsigned j=0; j& bb ) override { plumed_assert( bb.size()==0 ); } + void applyBridgeForces( const std::vector& bb ) override { + plumed_assert( bb.size()==0 ); + } }; inline diff --git a/src/manyrestraints/UWalls.cpp b/src/manyrestraints/UWalls.cpp index 0749e5e2ad..9f4fbbc7a6 100644 --- a/src/manyrestraints/UWalls.cpp +++ b/src/manyrestraints/UWalls.cpp @@ -85,8 +85,7 @@ void UWalls::registerKeywords( Keywords& keys ) { UWalls::UWalls(const ActionOptions& ao): Action(ao), - ManyRestraintsBase(ao) -{ + ManyRestraintsBase(ao) { parse("AT",at); parse("OFFSET",offset); parse("EPS",eps); diff --git a/src/mapping/AdaptivePath.cpp b/src/mapping/AdaptivePath.cpp index 8754d88f77..69f97d096d 100644 --- a/src/mapping/AdaptivePath.cpp +++ b/src/mapping/AdaptivePath.cpp @@ -105,7 +105,9 @@ class AdaptivePath : public Mapping { explicit AdaptivePath(const ActionOptions&); void calculate() override; void performTask( const unsigned&, const unsigned&, MultiValue& ) const override; - double getLambda() override { return 0.0; } + double getLambda() override { + return 0.0; + } double transformHD( const double& dist, double& df ) const override; void update() override; }; @@ -113,7 +115,8 @@ class AdaptivePath : public Mapping { PLUMED_REGISTER_ACTION(AdaptivePath,"ADAPTIVE_PATH") void AdaptivePath::registerKeywords( Keywords& keys ) { - Mapping::registerKeywords( keys ); keys.remove("PROPERTY"); + Mapping::registerKeywords( keys ); + keys.remove("PROPERTY"); keys.add("compulsory","FIXED","the positions in the list of input frames of the two path nodes whose positions remain fixed during the path optimization"); keys.add("compulsory","HALFLIFE","-1","the number of MD steps after which a previously measured path distance weighs only 50% 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","UPDATE","the frequency with which the path should be updated"); @@ -128,42 +131,64 @@ AdaptivePath::AdaptivePath(const ActionOptions& ao): Mapping(ao), fixedn(2), displacement(ReferenceConfigurationOptions("DIRECTION")), - displacement2(ReferenceConfigurationOptions("DIRECTION")) -{ - setLowMemOption( true ); parseVector("FIXED",fixedn); - if( fixedn[0]<1 || fixedn[1]>getNumberOfReferencePoints() ) error("fixed nodes must be in range from 0 to number of nodes"); - if( fixedn[0]>=fixedn[1] ) error("invalid selection for fixed nodes first index provided must be smaller than second index"); + displacement2(ReferenceConfigurationOptions("DIRECTION")) { + setLowMemOption( true ); + parseVector("FIXED",fixedn); + if( fixedn[0]<1 || fixedn[1]>getNumberOfReferencePoints() ) { + error("fixed nodes must be in range from 0 to number of nodes"); + } + if( fixedn[0]>=fixedn[1] ) { + error("invalid selection for fixed nodes first index provided must be smaller than second index"); + } log.printf(" fixing position of frames numbered %u and %u \n",fixedn[0],fixedn[1]); - fixedn[0]--; fixedn[1]--; // Set fixed notes with c++ indexing starting from zero - parse("UPDATE",update_str); if( update_str<1 ) error("update frequency for path should be greater than or equal to one"); + fixedn[0]--; + fixedn[1]--; // Set fixed notes with c++ indexing starting from zero + parse("UPDATE",update_str); + if( update_str<1 ) { + error("update frequency for path should be greater than or equal to one"); + } log.printf(" updating path every %u MD steps \n",update_str); - double halflife; parse("HALFLIFE",halflife); - if( halflife<0 ) fadefact=1.0; - else { + double halflife; + parse("HALFLIFE",halflife); + if( halflife<0 ) { + fadefact=1.0; + } else { fadefact = exp( -0.693147180559945 / static_cast(halflife) ); log.printf(" weight of contribution to frame halves every %f steps \n",halflife); } // Create the list of tasks (and reset projections of frames) - PDB mypdb; mypdb.setAtomNumbers( getAbsoluteIndexes() ); mypdb.addBlockEnd( getAbsoluteIndexes().size() ); + PDB mypdb; + mypdb.setAtomNumbers( getAbsoluteIndexes() ); + mypdb.addBlockEnd( getAbsoluteIndexes().size() ); std::vector argument_names( getNumberOfArguments() ); - for(unsigned i=0; igetName(); - if( argument_names.size()>0 ) mypdb.setArgumentNames( argument_names ); - displacement.read( mypdb ); displacement2.read( mypdb ); + for(unsigned i=0; igetName(); + } + if( argument_names.size()>0 ) { + mypdb.setArgumentNames( argument_names ); + } + displacement.read( mypdb ); + displacement2.read( mypdb ); for(int i=0; isecond[i] = static_cast( i - static_cast(fixedn[0]) ) / static_cast( fixedn[1] - fixedn[0] ); - pdisplacements[i].read( mypdb ); wsum.push_back( 0.0 ); + pdisplacements[i].read( mypdb ); + wsum.push_back( 0.0 ); } plumed_assert( getPropertyValue( fixedn[0], "spath" )==0.0 && getPropertyValue( fixedn[1], "spath" )==1.0 ); // And activate them all deactivateAllTasks(); - for(unsigned i=0; i0 ) { - wstride=0; parse("WSTRIDE",wstride); parse("FMT",ofmt); - pathfile.link(*this); pathfile.open( wfilename ); pathfile.setHeavyFlush(); - if( wstridedx; double weight1 = 1.0 + mypathv->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; } // Add projections to dispalcement accumulators ReferenceConfiguration* myref = getReferenceConfiguration( mypathv->iclose1 ); @@ -243,12 +279,17 @@ void AdaptivePath::update() { std::vector>& myconfs=getAllReferenceConfigurations(); auto* mymoldat=plumed.getActionSet().selectLatest(this); std::vector argument_names( getNumberOfArguments() ); - for(unsigned i=0; igetName(); - PDB mypdb; mypdb.setArgumentNames( argument_names ); + for(unsigned i=0; igetName(); + } + PDB mypdb; + mypdb.setArgumentNames( argument_names ); for(unsigned i=0; igetName().c_str() ); mypdb.setAtomPositions( myconfs[i]->getReferencePositions() ); - for(unsigned j=0; jgetName(), myconfs[i]->getReferenceArgument(j) ); + for(unsigned j=0; jgetName(), myconfs[i]->getReferenceArgument(j) ); + } mypdb.print( atoms.getUnits().getLength()/0.1, mymoldat, pathfile, ofmt ); } pathfile.flush(); diff --git a/src/mapping/Mapping.cpp b/src/mapping/Mapping.cpp index 95eb1fd4f5..eb1cb5e96e 100644 --- a/src/mapping/Mapping.cpp +++ b/src/mapping/Mapping.cpp @@ -50,44 +50,63 @@ Mapping::Mapping(const ActionOptions&ao): ActionAtomistic(ao), ActionWithArguments(ao), ActionWithValue(ao), - ActionWithVessel(ao) -{ + ActionWithVessel(ao) { // Read the input - std::string mtype; parse("TYPE",mtype); - bool skipchecks; parseFlag("DISABLE_CHECKS",skipchecks); + std::string mtype; + parse("TYPE",mtype); + bool skipchecks; + parseFlag("DISABLE_CHECKS",skipchecks); // Read the properties we require bool ispath=false; if( keywords.exists("PROPERTY") ) { - std::vector propnames; parseVector("PROPERTY",propnames); - if(propnames.size()==0) error("no properties were specified"); - for(unsigned i=0; i >( propnames[i], std::vector() ) ); + std::vector propnames; + parseVector("PROPERTY",propnames); + if(propnames.size()==0) { + error("no properties were specified"); + } + for(unsigned i=0; i >( propnames[i], std::vector() ) ); + } } else { - property.insert( std::pair >( "spath", std::vector() ) ); ispath=true; + property.insert( std::pair >( "spath", std::vector() ) ); + ispath=true; } // Open reference file - std::string reference; parse("REFERENCE",reference); + std::string reference; + parse("REFERENCE",reference); FILE* fp=this->fopen(reference.c_str(),"r"); - if(!fp) error("could not open reference file " + reference ); + if(!fp) { + error("could not open reference file " + reference ); + } // 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); // Read all reference configurations - bool do_read=true; unsigned nfram=0; double wnorm=0., ww; + bool do_read=true; + unsigned nfram=0; + double wnorm=0., ww; while (do_read) { // Read the pdb file - PDB mypdb; do_read=mypdb.readFromFilepointer(fp,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()); + PDB mypdb; + do_read=mypdb.readFromFilepointer(fp,plumed.getAtoms().usingNaturalUnits(),0.1/atoms.getUnits().getLength()); // Break if we are done - if( !do_read ) break ; + if( !do_read ) { + break ; + } // Check for required properties if( !ispath ) { double prop; for(std::map >::iterator it=property.begin(); it!=property.end(); ++it) { - if( !mypdb.getArgumentValue( it->first, prop ) ) error("pdb input does not have contain property named " + it->first ); + if( !mypdb.getArgumentValue( it->first, prop ) ) { + error("pdb input does not have contain property named " + it->first ); + } it->second.push_back(prop); } } else { @@ -97,26 +116,45 @@ Mapping::Mapping(const ActionOptions&ao): expandArgKeywordInPDB( mypdb ); // And read the frame myframes.emplace_back( metricRegister().create( mtype, mypdb ) ); - if( !mypdb.getArgumentValue( "WEIGHT", ww ) ) ww=1.0; - weights.push_back( ww ); wnorm+=ww; nfram++; + if( !mypdb.getArgumentValue( "WEIGHT", ww ) ) { + ww=1.0; + } + weights.push_back( ww ); + wnorm+=ww; + nfram++; } - if(nfram==0 ) error("no reference configurations were specified"); + if(nfram==0 ) { + error("no reference configurations were specified"); + } log.printf(" found %u configurations in file %s\n",nfram,reference.c_str() ); - for(unsigned i=0; i atoms; std::vector args; - for(unsigned i=0; igetAtomRequests( atoms, skipchecks ); myframes[i]->getArgumentRequests( args, skipchecks ); } - std::vector req_args; interpretArgumentList( args, req_args ); - if( req_args.size()>0 && atoms.size()>0 ) error("cannot mix atoms and arguments"); - if( req_args.size()>0 ) requestArguments( req_args ); + std::vector atoms; + std::vector args; + for(unsigned i=0; igetAtomRequests( atoms, skipchecks ); + myframes[i]->getArgumentRequests( args, skipchecks ); + } + std::vector req_args; + interpretArgumentList( args, req_args ); + if( req_args.size()>0 && atoms.size()>0 ) { + error("cannot mix atoms and arguments"); + } + if( req_args.size()>0 ) { + requestArguments( req_args ); + } if( atoms.size()>0 ) { log.printf(" found %zu atoms in input \n",atoms.size()); log.printf(" with indices : "); for(unsigned i=0; igetName(); + if( iarg < getNumberOfArguments() ) { + return getPntrToArgument(iarg)->getName(); + } unsigned iatom=iarg - getNumberOfArguments(); - std::string atnum; Tools::convert( getAbsoluteIndex(iatom).serial(),atnum); + std::string atnum; + Tools::convert( getAbsoluteIndex(iatom).serial(),atnum); unsigned icomp=iatom%3; - if(icomp==0) return "pos" + atnum + "x"; - if(icomp==1) return "pos" + atnum + "y"; + if(icomp==0) { + return "pos" + atnum + "x"; + } + if(icomp==1) { + return "pos" + atnum + "y"; + } return "pos" + atnum + "z"; } @@ -159,10 +204,15 @@ void Mapping::finishPackSetup( const unsigned& ifunc, ReferenceValuePack& mypack mypack.setValIndex(0); unsigned nargs2=myframes[ifunc]->getNumberOfReferenceArguments(); unsigned nat2=myframes[ifunc]->getNumberOfReferencePositions(); - if( mypack.getNumberOfAtoms()!=nat2 || mypack.getNumberOfArguments()!=nargs2 ) mypack.resize( nargs2, nat2 ); + if( mypack.getNumberOfAtoms()!=nat2 || mypack.getNumberOfArguments()!=nargs2 ) { + mypack.resize( nargs2, nat2 ); + } if( nat2>0 ) { - ReferenceAtoms* myat2=dynamic_cast( myframes[ifunc].get() ); plumed_dbg_assert( myat2 ); - for(unsigned i=0; igetAtomIndex(i) ); + ReferenceAtoms* myat2=dynamic_cast( myframes[ifunc].get() ); + plumed_dbg_assert( myat2 ); + for(unsigned i=0; igetAtomIndex(i) ); + } } } @@ -170,11 +220,15 @@ double Mapping::calculateDistanceFunction( const unsigned& ifunc, ReferenceValue // Calculate the distance double dd = myframes[ifunc]->calculate( getPositions(), getPbc(), getArguments(), myder, squared ); // Transform distance by whatever - double df, ff=transformHD( dd, df ); myder.scaleAllDerivatives( df ); + double df, ff=transformHD( dd, df ); + myder.scaleAllDerivatives( df ); // And the virial if( getNumberOfAtoms()>0 && !myder.virialWasSet() ) { - Tensor tvir; tvir.zero(); - for(unsigned i=0; i0 ) { Matrix save_derivatives( getNumberOfComponents(), getNumberOfArguments() ); for(int j=0; jgetDerivative(i); + for(unsigned i=0; igetDerivative(i); + } } calculateAtomicNumericalDerivatives( a, getNumberOfArguments() ); for(int j=0; jaddDerivative( i, save_derivatives(j,i) ); + for(unsigned i=0; iaddDerivative( i, save_derivatives(j,i) ); + } } } } @@ -203,7 +261,9 @@ void Mapping::calculateNumericalDerivatives( ActionWithValue* a ) { void Mapping::apply() { if( getForcesFromVessels( forcesToApply ) ) { addForcesOnArguments( forcesToApply ); - if( getNumberOfAtoms()>0 ) setForcesOnAtoms( forcesToApply, getNumberOfArguments() ); + if( getNumberOfAtoms()>0 ) { + setForcesOnAtoms( forcesToApply, getNumberOfArguments() ); + } } } diff --git a/src/mapping/Mapping.h b/src/mapping/Mapping.h index 0fdd52a564..79affd33ca 100644 --- a/src/mapping/Mapping.h +++ b/src/mapping/Mapping.h @@ -41,8 +41,7 @@ class Mapping : public ActionAtomistic, public ActionWithArguments, public ActionWithValue, - public vesselbase::ActionWithVessel -{ + public vesselbase::ActionWithVessel { friend class PropertyMap; friend class TrigonometricPathVessel; friend class AdaptivePath; @@ -81,7 +80,9 @@ class Mapping : void lockRequests() override; void unlockRequests() override; /// Distance from a point is never periodic - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } /// Get the number of derivatives for this action unsigned getNumberOfDerivatives() override; // N.B. This is replacing the virtual function in ActionWithValue /// Get the value of lambda for paths and property maps @@ -106,7 +107,9 @@ unsigned Mapping::getNumberOfReferencePoints() const { inline unsigned Mapping::getNumberOfDerivatives() { unsigned nat=getNumberOfAtoms(); - if(nat>0) return 3*nat + 9 + getNumberOfArguments(); + if(nat>0) { + return 3*nat + 9 + getNumberOfArguments(); + } return getNumberOfArguments(); } diff --git a/src/mapping/PCAVars.cpp b/src/mapping/PCAVars.cpp index 9bef5ec738..31d9059b39 100644 --- a/src/mapping/PCAVars.cpp +++ b/src/mapping/PCAVars.cpp @@ -170,8 +170,7 @@ namespace mapping { class PCAVars : public ActionWithValue, public ActionAtomistic, - public ActionWithArguments -{ + public ActionWithArguments { private: /// The holders for the derivatives MultiValue myvals; @@ -201,7 +200,8 @@ void PCAVars::registerKeywords( Keywords& keys ) { ActionWithValue::registerKeywords( keys ); ActionAtomistic::registerKeywords( keys ); ActionWithArguments::registerKeywords( keys ); - componentsAreNotOptional(keys); keys.use("ARG"); + componentsAreNotOptional(keys); + keys.use("ARG"); keys.addOutputComponent("eig","default","the projections on each eigenvalue are stored on values labeled eig-1, eig-2, ..."); keys.addOutputComponent("residual","default","the distance of the configuration from the linear subspace defined " "by the vectors, eig-1, eig2, ... that are contained in the rows of A."); @@ -217,27 +217,33 @@ PCAVars::PCAVars(const ActionOptions& ao): ActionWithArguments(ao), myvals(1,0), mypack(0,0,myvals), - nopbc(false) -{ + nopbc(false) { // What type of distance are we calculating - std::string mtype; parse("TYPE",mtype); + std::string mtype; + parse("TYPE",mtype); parseFlag("NOPBC",nopbc); // Open reference file - std::string reference; parse("REFERENCE",reference); + std::string reference; + parse("REFERENCE",reference); FILE* fp=this->fopen(reference.c_str(),"r"); - if(!fp) error("could not open reference file " + reference ); + if(!fp) { + error("could not open reference file " + reference ); + } // 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); // Read all reference configurations // MultiReferenceBase myframes( "", false ); std::vector > myframes; - bool do_read=true; unsigned nfram=0; + bool do_read=true; + unsigned nfram=0; while (do_read) { PDB mypdb; // Read the pdb file @@ -247,8 +253,12 @@ PCAVars::PCAVars(const ActionOptions& ao): if( nfram==0 ) { myref=metricRegister().create( mtype, mypdb ); Direction* tdir = dynamic_cast( myref.get() ); - if( tdir ) error("first frame should be reference configuration - not direction of vector"); - if( !myref->pcaIsEnabledForThisReference() ) error("can't do PCA with reference type " + mtype ); + if( tdir ) { + error("first frame should be reference configuration - not direction of vector"); + } + if( !myref->pcaIsEnabledForThisReference() ) { + error("can't do PCA with reference type " + mtype ); + } // std::vector remarks( mypdb.getRemark() ); std::string rtype; // bool found=Tools::parse( remarks, "TYPE", rtype ); // if(!found){ std::vector newrem(1); newrem[0]="TYPE="+mtype; mypdb.addRemark(newrem); } @@ -263,52 +273,78 @@ PCAVars::PCAVars(const ActionOptions& ao): } } - if( nfram<=1 ) error("no eigenvectors were specified"); + if( nfram<=1 ) { + error("no eigenvectors were specified"); + } log.printf(" found %u eigenvectors in file %s \n",nfram-1,reference.c_str() ); // Finish the setup of the mapping object // Get the arguments and atoms that are required - std::vector atoms; myref->getAtomRequests( atoms, false ); - std::vector args; myref->getArgumentRequests( args, false ); + std::vector atoms; + myref->getAtomRequests( atoms, false ); + std::vector args; + myref->getArgumentRequests( args, false ); if( atoms.size()>0 ) { log.printf(" found %zu atoms in input \n",atoms.size()); log.printf(" with indices : "); for(unsigned i=0; i req_args; - interpretArgumentList( args, req_args ); requestArguments( req_args ); + requestAtoms( atoms ); + std::vector req_args; + interpretArgumentList( args, req_args ); + requestArguments( req_args ); // And now check that the atoms/arguments are the same in all the eigenvalues - for(unsigned i=0; igetAtomRequests( atoms, false ); myframes[i]->getArgumentRequests( args, false ); } + for(unsigned i=0; igetAtomRequests( atoms, false ); + myframes[i]->getArgumentRequests( args, false ); + } // Setup the derivative pack - if( atoms.size()>0 ) myvals.resize( 1, args.size() + 3*atoms.size() + 9 ); - else myvals.resize( 1, args.size() ); + if( atoms.size()>0 ) { + myvals.resize( 1, args.size() + 3*atoms.size() + 9 ); + } else { + myvals.resize( 1, args.size() ); + } mypack.resize( args.size(), atoms.size() ); - for(unsigned i=0; isetupPCAStorage( mypack ); // Check there are no periodic arguments for(unsigned i=0; iisPeriodic() ) error("cannot use periodic variables in pca projections"); + if( getPntrToArgument(i)->isPeriodic() ) { + error("cannot use periodic variables in pca projections"); + } } // Work out if the user wants to normalise the input vector checkRead(); - 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"); + } // Resize the matrices that will hold our eivenvectors - PDB mypdb; mypdb.setAtomNumbers( atoms ); mypdb.addBlockEnd( atoms.size() ); - if( args.size()>0 ) mypdb.setArgumentNames( args ); + PDB mypdb; + mypdb.setAtomNumbers( atoms ); + mypdb.addBlockEnd( atoms.size() ); + if( args.size()>0 ) { + mypdb.setArgumentNames( args ); + } // Resize the matrices that will hold our eivenvectors for(unsigned i=0; iextractDisplacementVector( myref->getReferencePositions(), getArguments(), myref->getReferenceArguments(), true, directions[i] ); // Create a component to store the output - std::string num; Tools::convert( i+1, num ); - addComponentWithDerivatives("eig-"+num); componentIsNotPeriodic("eig-"+num); + std::string num; + Tools::convert( i+1, num ); + addComponentWithDerivatives("eig-"+num); + componentIsNotPeriodic("eig-"+num); } - addComponentWithDerivatives("residual"); componentIsNotPeriodic("residual"); + addComponentWithDerivatives("residual"); + componentIsNotPeriodic("residual"); // Get appropriate number of derivatives unsigned nder; @@ -331,8 +370,11 @@ PCAVars::PCAVars(const ActionOptions& ao): } // 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); + } } unsigned PCAVars::getNumberOfDerivatives() { @@ -354,7 +396,9 @@ void PCAVars::unlockRequests() { void PCAVars::calculate() { - if(!nopbc && getNumberOfAtoms()>0) makeWhole(); + if(!nopbc && getNumberOfAtoms()>0) { + makeWhole(); + } // Clear the reference value pack mypack.clear(); @@ -362,22 +406,33 @@ void PCAVars::calculate() { double dist = myref->calculate( getPositions(), getPbc(), getArguments(), mypack, true ); // Start accumulating residual by adding derivatives of distance - Value* resid=getPntrToComponent( getNumberOfComponents()-1 ); unsigned nargs=getNumberOfArguments(); - for(unsigned j=0; jaddDerivative( j, mypack.getArgumentDerivative(j) ); + Value* resid=getPntrToComponent( getNumberOfComponents()-1 ); + unsigned nargs=getNumberOfArguments(); + for(unsigned j=0; jaddDerivative( j, mypack.getArgumentDerivative(j) ); + } for(unsigned j=0; jaddDerivative( nargs +3*j+k, ader[k] ); + for(unsigned k=0; k<3; ++k) { + resid->addDerivative( nargs +3*j+k, ader[k] ); + } } // Retrieve the values of all arguments - std::vector args( getNumberOfArguments() ); for(unsigned i=0; i args( getNumberOfArguments() ); + for(unsigned i=0; iprojectDisplacementOnVector( directions[i], getArguments(), args, mypack ); // And now accumulate derivatives Value* eid=getPntrToComponent(i); - for(unsigned j=0; jaddDerivative( j, mypack.getArgumentDerivative(j) ); + for(unsigned j=0; jaddDerivative( j, mypack.getArgumentDerivative(j) ); + } if( getNumberOfAtoms()>0 ) { tvir.zero(); for(unsigned j=0; jaddDerivative( nargs + 3*getNumberOfAtoms() + 3*j + k, tvir(j,k) ); + for(unsigned k=0; k<3; ++k) { + eid->addDerivative( nargs + 3*getNumberOfAtoms() + 3*j + k, tvir(j,k) ); + } } } dist -= proj*proj; // Subtract square from total squared distance to get residual squared // Derivatives of residual - for(unsigned j=0; jaddDerivative( j, -2*proj*eid->getDerivative(j) ); + for(unsigned j=0; jaddDerivative( j, -2*proj*eid->getDerivative(j) ); + } // for(unsigned j=0;jaddDerivative( j, -2*proj*arg_eigv(i,j) ); // And set final value getPntrToComponent(i)->set( proj ); @@ -404,20 +463,29 @@ void PCAVars::calculate() { // Take square root of residual derivatives double prefactor = 0.5 / dist; - for(unsigned j=0; jsetDerivative( j, prefactor*resid->getDerivative(j) ); + for(unsigned j=0; jsetDerivative( j, prefactor*resid->getDerivative(j) ); + } for(unsigned j=0; jsetDerivative( nargs + 3*j+k, prefactor*resid->getDerivative( nargs+3*j+k ) ); + for(unsigned k=0; k<3; ++k) { + resid->setDerivative( nargs + 3*j+k, prefactor*resid->getDerivative( nargs+3*j+k ) ); + } } // And finally virial for residual if( getNumberOfAtoms()>0 ) { tvir.zero(); for(unsigned j=0; jgetDerivative( nargs + 3*j+k ); + Vector ader; + for(unsigned k=0; k<3; ++k) { + ader[k]=resid->getDerivative( nargs + 3*j+k ); + } tvir += -1.0*Tensor( getPosition(j), ader ); } for(unsigned j=0; j<3; ++j) { - for(unsigned k=0; k<3; ++k) resid->addDerivative( nargs + 3*getNumberOfAtoms() + 3*j + k, tvir(j,k) ); + for(unsigned k=0; k<3; ++k) { + resid->addDerivative( nargs + 3*getNumberOfAtoms() + 3*j + k, tvir(j,k) ); + } } } @@ -430,27 +498,36 @@ void PCAVars::calculateNumericalDerivatives( ActionWithValue* a ) { if( getNumberOfAtoms()>0 ) { Matrix save_derivatives( getNumberOfComponents(), getNumberOfArguments() ); for(int j=0; jgetDerivative(i); + for(unsigned i=0; igetDerivative(i); + } } calculateAtomicNumericalDerivatives( a, getNumberOfArguments() ); for(int j=0; jaddDerivative( i, save_derivatives(j,i) ); + for(unsigned i=0; iaddDerivative( i, save_derivatives(j,i) ); + } } } } void PCAVars::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, getNumberOfArguments() ); + if( getNumberOfAtoms()>0 ) { + setForcesOnAtoms( forcesToApply, getNumberOfArguments() ); + } } } diff --git a/src/mapping/Path.cpp b/src/mapping/Path.cpp index 345b334b27..2a1dacfe0e 100644 --- a/src/mapping/Path.cpp +++ b/src/mapping/Path.cpp @@ -139,21 +139,25 @@ class Path : public PathBase { PLUMED_REGISTER_ACTION(Path,"PATH") void Path::registerKeywords( Keywords& keys ) { - PathBase::registerKeywords( keys ); keys.remove("PROPERTY"); + PathBase::registerKeywords( keys ); + keys.remove("PROPERTY"); keys.addFlag("NOSPATH",false,"do not calculate the spath position"); - keys.remove("LOWMEM"); keys.use("GPATH"); + keys.remove("LOWMEM"); + keys.use("GPATH"); } Path::Path(const ActionOptions& ao): Action(ao), - PathBase(ao) -{ + PathBase(ao) { setLowMemOption( true ); - bool nos; parseFlag("NOSPATH",nos); + bool nos; + parseFlag("NOSPATH",nos); std::string empty; if(!nos) { - if( getLambda()==0 ) error("you must set LAMBDA parameter in order to calculate spath position. Use LAMBDA/NOSPATH keyword"); + if( getLambda()==0 ) { + error("you must set LAMBDA parameter in order to calculate spath position. Use LAMBDA/NOSPATH keyword"); + } empty="LABEL=spath"; addVessel("SPATH",empty,0); } diff --git a/src/mapping/PathBase.cpp b/src/mapping/PathBase.cpp index dbff754df5..0c2824cd25 100644 --- a/src/mapping/PathBase.cpp +++ b/src/mapping/PathBase.cpp @@ -33,23 +33,29 @@ void PathBase::registerKeywords( Keywords& keys ) { PathBase::PathBase(const ActionOptions& ao): Action(ao), - Mapping(ao) -{ + Mapping(ao) { setLowMemOption( true ); weightHasDerivatives=true; - bool noz; parseFlag("NOZPATH",noz); + bool noz; + parseFlag("NOZPATH",noz); parse("LAMBDA",lambda); // Create the list of tasks - for(unsigned i=0; igetAbsoluteIndexes() ); mypdb.addBlockEnd( pp[0]->getAbsoluteIndexes().size() ); - if( pp[0]->getArgumentNames().size()>0 ) mypdb.setArgumentNames( pp[0]->getArgumentNames() ); - mydir.read( mypdb ); mydir.zeroDirection(); pp[0]->setupPCAStorage( mypack ); + MAXCYCLES(100) { + mypdb.setAtomNumbers( pp[0]->getAbsoluteIndexes() ); + mypdb.addBlockEnd( pp[0]->getAbsoluteIndexes().size() ); + if( pp[0]->getArgumentNames().size()>0 ) { + mypdb.setArgumentNames( pp[0]->getArgumentNames() ); + } + mydir.read( mypdb ); + mydir.zeroDirection(); + pp[0]->setupPCAStorage( mypack ); } 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; } @@ -53,7 +60,10 @@ void PathReparameterization::calcCurrentPathSpacings( const int& istart, const i //printf("HELLO PATH SPACINGS ARE CURRENTLY \n"); // Get the spacings given we can go forward and backwards - int incr=1; if( istart>iend ) { 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] = mypath[i-incr]->calc( mypath[i]->getReferencePositions(), pbc, args, mypath[i]->getReferenceArguments(), mypack, false ); @@ -63,15 +73,23 @@ void PathReparameterization::calcCurrentPathSpacings( const int& istart, const i } void PathReparameterization::reparameterizePart( const int& istart, const int& iend, const double& target, const double& TOL ) { - 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 { @@ -80,18 +98,23 @@ void PathReparameterization::reparameterizePart( const int& istart, const int& i std::vector newpath; for(unsigned i=0; i( 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]; // Calculate the displacement between the appropriate points @@ -119,7 +148,9 @@ void PathReparameterization::reparameterizePart( const int& istart, const int& i // Copy the positions of the new path to the new paths for(int i=istart+incr; loopEnd(i,cfin,incr)==false; i+=incr) { mypdb.setAtomPositions( newpath[i].getReferencePositions() ); - for(unsigned j=0; jgetArgumentNames()[j], newpath[i].getReferenceArgument(j) ); + for(unsigned j=0; jgetArgumentNames()[j], newpath[i].getReferenceArgument(j) ); + } mypath[i]->read( mypdb ); } @@ -137,8 +168,12 @@ void PathReparameterization::reparameterize( const int& ifix1, const int& ifix2, double target = sumlen[ifix2] / ( ifix2 - ifix1 ); // And reparameterize the beginning and end of the path - if( ifix1>0 ) reparameterizePart( ifix1, 0, target, TOL ); - if( ifix2<(mypath.size()-1) ) reparameterizePart( ifix2, mypath.size()-1, target, TOL ); + if( ifix1>0 ) { + reparameterizePart( ifix1, 0, target, TOL ); + } + if( ifix2<(mypath.size()-1) ) { + reparameterizePart( ifix2, mypath.size()-1, target, TOL ); + } // calcCurrentPathSpacings( 0, mypath.size()-1 ); } diff --git a/src/mapping/PathTools.cpp b/src/mapping/PathTools.cpp index 9fb98d2547..40d209363f 100644 --- a/src/mapping/PathTools.cpp +++ b/src/mapping/PathTools.cpp @@ -102,8 +102,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 ); @@ -131,23 +130,31 @@ 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) { - 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::string mtype; + parse("--metric",mtype); + std::string ifilename; + parse("--path",ifilename); + std::string ofmt; + parse("--arg-fmt",ofmt); + std::string ofilename; + parse("--out",ofilename); if( ifilename.length()>0 ) { std::fprintf(out,"Reparameterising path in file named %s so that all frames are equally spaced \n",ifilename.c_str() ); FILE* fp=std::fopen(ifilename.c_str(),"r"); // call fclose when fp goes out of scope - auto deleter=[](FILE* f) { if(f) std::fclose(f); }; + auto deleter=[](FILE* f) { + if(f) { + std::fclose(f); + } + }; std::unique_ptr fp_deleter(fp,deleter); - bool do_read=true; std::vector> frames; + bool do_read=true; + std::vector> frames; while (do_read) { PDB mypdb; // Read the pdb file @@ -157,10 +164,15 @@ int PathTools::main(FILE* in, FILE*out,Communicator& pc) { frames.emplace_back( std::move(mymsd) ); } } - std::vector fixed; parseVector("--fixed",fixed); + std::vector 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]=0; fixed[1]=frames.size()-1; + if( fixed[0]!=0 ) { + error("input to --fixed should be two integers"); + } + fixed.resize(2); + fixed[0]=0; + fixed[1]=frames.size()-1; } else if( fixed.size()==2 ) { if( fixed[0]>(frames.size()-1) || fixed[1]>(frames.size()-1) ) { error("input to --fixed should be two numbers between 0 and the number of frames-1"); @@ -168,15 +180,18 @@ int PathTools::main(FILE* in, FILE*out,Communicator& pc) { } else { error("input to --fixed should be two integers"); } - std::vector atoms; std::vector arg_names; + std::vector atoms; + std::vector arg_names; for(unsigned i=0; igetAtomRequests( atoms); frames[i]->getArgumentRequests( arg_names ); } // Generate stuff to reparameterize - Pbc fake_pbc; std::vector> vals; + Pbc fake_pbc; + std::vector> vals; for(unsigned i=0; igetNumberOfReferenceArguments(); ++i) { - vals.emplace_back(Tools::make_unique()); vals[vals.size()-1]->setNotPeriodic(); + vals.emplace_back(Tools::make_unique()); + vals[vals.size()-1]->setNotPeriodic(); } // temporary pointes used to make the conversion once @@ -185,7 +200,9 @@ int PathTools::main(FILE* in, FILE*out,Communicator& pc) { // And reparameterize PathReparameterization myparam( fake_pbc, vals_ptr, frames ); // And make all points equally spaced - double tol; parse("--tolerance",tol); myparam.reparameterize( fixed[0], fixed[1], tol ); + double tol; + parse("--tolerance",tol); + myparam.reparameterize( fixed[0], fixed[1], tol ); // Output data on spacings double mean=0; @@ -199,13 +216,20 @@ int PathTools::main(FILE* in, FILE*out,Communicator& pc) { printf("SUGGESTED LAMBDA PARAMETER IS THUS %f \n",2.3/(mean/static_cast( frames.size()-1 )) ); // Delete all the frames - OFile ofile; ofile.open(ofilename); - std::vector argnames; frames[0]->getArgumentRequests( argnames ); - std::vector atindices; frames[0]->getAtomRequests( atindices ); - PDB mypdb; mypdb.setAtomNumbers( atindices ); mypdb.setArgumentNames( argnames ); + OFile ofile; + ofile.open(ofilename); + std::vector argnames; + frames[0]->getArgumentRequests( argnames ); + std::vector atindices; + frames[0]->getAtomRequests( atindices ); + PDB mypdb; + mypdb.setAtomNumbers( atindices ); + mypdb.setArgumentNames( argnames ); for(unsigned i=0; igetReferencePositions() ); - for(unsigned j=0; jgetReferenceArguments()[j] ); + for(unsigned j=0; jgetReferenceArguments()[j] ); + } ofile.printf("REMARK TYPE=%s\n",mtype.c_str() ); mypdb.print( 10, NULL, ofile, ofmt ); } @@ -216,39 +240,58 @@ int PathTools::main(FILE* in, FILE*out,Communicator& pc) { } // Read initial frame - std::string istart; parse("--start",istart); + std::string istart; + parse("--start",istart); PDB mystartpdb; { FILE* fp2=std::fopen(istart.c_str(),"r"); // call fclose when fp goes out of scope - auto deleter=[](FILE* f) { std::fclose(f); }; + auto deleter=[](FILE* f) { + std::fclose(f); + }; std::unique_ptr fp_deleter(fp2,deleter); - if( istart.length()==0 ) error("input is missing use --istart + --iend or --path"); - if( !mystartpdb.readFromFilepointer(fp2,false,0.1) ) error("could not read fila " + istart); + if( istart.length()==0 ) { + error("input is missing use --istart + --iend or --path"); + } + if( !mystartpdb.readFromFilepointer(fp2,false,0.1) ) { + error("could not read fila " + istart); + } } auto sframe=metricRegister().create( mtype, mystartpdb ); // Read final frame - std::string iend; parse("--end",iend); + std::string iend; + parse("--end",iend); PDB myendpdb; { FILE* fp1=std::fopen(iend.c_str(),"r"); // call fclose when fp goes out of scope - auto deleter=[](FILE* f) { std::fclose(f); }; + auto deleter=[](FILE* f) { + std::fclose(f); + }; std::unique_ptr fp_deleter(fp1,deleter); - if( iend.length()==0 ) error("input is missing using --istart + --iend or --path"); - if( !myendpdb.readFromFilepointer(fp1,false,0.1) ) error("could not read fila " + iend); + if( iend.length()==0 ) { + error("input is missing using --istart + --iend or --path"); + } + if( !myendpdb.readFromFilepointer(fp1,false,0.1) ) { + error("could not read fila " + iend); + } } auto eframe=metricRegister().create( mtype, myendpdb ); // Get atoms and arg requests - std::vector atoms; std::vector arg_names; - sframe->getAtomRequests( atoms); eframe->getAtomRequests( atoms); - sframe->getArgumentRequests( arg_names ); eframe->getArgumentRequests( arg_names ); + std::vector atoms; + std::vector arg_names; + sframe->getAtomRequests( atoms); + eframe->getAtomRequests( atoms); + sframe->getArgumentRequests( arg_names ); + eframe->getArgumentRequests( arg_names ); // Now read in the rest of the instructions unsigned nbefore, nbetween, nafter; - parse("--nframes-before-start",nbefore); parse("--nframes",nbetween); parse("--nframes-after-end",nafter); + parse("--nframes-before-start",nbefore); + parse("--nframes",nbetween); + parse("--nframes-after-end",nafter); nbetween++; std::fprintf(out,"Generating linear path connecting structure in file named %s to structure in file named %s \n",istart.c_str(),iend.c_str() ); std::fprintf(out,"A path consisting of %u equally-spaced frames before the initial structure, %u frames between the initial and final structures " @@ -258,7 +301,8 @@ int PathTools::main(FILE* in, FILE*out,Communicator& pc) { Pbc fpbc; std::vector> args; for(unsigned i=0; igetNumberOfReferenceArguments(); ++i) { - args.emplace_back(Tools::make_unique()); args[args.size()-1]->setNotPeriodic(); + args.emplace_back(Tools::make_unique()); + args[args.size()-1]->setNotPeriodic(); } // convert pointer once: @@ -271,40 +315,60 @@ int PathTools::main(FILE* in, FILE*out,Communicator& pc) { // And the spacing between frames double delr = 1.0 / static_cast( nbetween ); // Calculate the vector connecting the start to the end - PDB mypdb; mypdb.setAtomNumbers( sframe->getAbsoluteIndexes() ); mypdb.addBlockEnd( sframe->getAbsoluteIndexes().size() ); - if( sframe->getArgumentNames().size()>0 ) mypdb.setArgumentNames( sframe->getArgumentNames() ); - Direction mydir(ReferenceConfigurationOptions("DIRECTION")); sframe->setupPCAStorage( mypack ); mydir.read( mypdb ); mydir.zeroDirection(); + PDB mypdb; + mypdb.setAtomNumbers( sframe->getAbsoluteIndexes() ); + mypdb.addBlockEnd( sframe->getAbsoluteIndexes().size() ); + if( sframe->getArgumentNames().size()>0 ) { + mypdb.setArgumentNames( sframe->getArgumentNames() ); + } + Direction mydir(ReferenceConfigurationOptions("DIRECTION")); + sframe->setupPCAStorage( mypack ); + mydir.read( mypdb ); + mydir.zeroDirection(); sframe->extractDisplacementVector( eframe->getReferencePositions(), args_ptr, eframe->getReferenceArguments(), false, mydir ); // Now create frames - OFile ofile; ofile.open(ofilename); unsigned nframes=0; - Direction pos(ReferenceConfigurationOptions("DIRECTION")); pos.read( mypdb ); + OFile ofile; + ofile.open(ofilename); + unsigned nframes=0; + Direction pos(ReferenceConfigurationOptions("DIRECTION")); + pos.read( mypdb ); for(int i=0; igetReferencePositions(), sframe->getReferenceArguments() ); pos.displaceReferenceConfiguration( -i*delr, mydir ); mypdb.setAtomPositions( pos.getReferencePositions() ); - for(unsigned j=0; jgetArgumentNames()[j], pos.getReferenceArgument(j) ); + for(unsigned j=0; jgetArgumentNames()[j], pos.getReferenceArgument(j) ); + } ofile.printf("REMARK TYPE=%s\n",mtype.c_str() ); - mypdb.print( 10, NULL, ofile, ofmt ); nframes++; + mypdb.print( 10, NULL, ofile, ofmt ); + nframes++; } for(unsigned i=1; igetReferencePositions(), sframe->getReferenceArguments() ); pos.displaceReferenceConfiguration( i*delr, mydir ); mypdb.setAtomPositions( pos.getReferencePositions() ); - for(unsigned j=0; jgetArgumentNames()[j], pos.getReferenceArgument(j) ); + for(unsigned j=0; jgetArgumentNames()[j], pos.getReferenceArgument(j) ); + } ofile.printf("REMARK TYPE=%s\n",mtype.c_str() ); - mypdb.print( 10, NULL, ofile, ofmt ); nframes++; + mypdb.print( 10, NULL, ofile, ofmt ); + nframes++; } for(unsigned i=0; igetReferencePositions(), eframe->getReferenceArguments() ); pos.displaceReferenceConfiguration( i*delr, mydir ); mypdb.setAtomPositions( pos.getReferencePositions() ); - for(unsigned j=0; jgetArgumentNames()[j], pos.getReferenceArgument(j) ); + for(unsigned j=0; jgetArgumentNames()[j], pos.getReferenceArgument(j) ); + } ofile.printf("REMARK TYPE=%s\n",mtype.c_str() ); - mypdb.print( 10, NULL, ofile, ofmt ); nframes++; + mypdb.print( 10, NULL, ofile, ofmt ); + nframes++; } - ofile.close(); return 0; + ofile.close(); + return 0; } } // End of namespace diff --git a/src/mapping/PropertyMap.cpp b/src/mapping/PropertyMap.cpp index 2a27d8f894..f454cb75b9 100644 --- a/src/mapping/PropertyMap.cpp +++ b/src/mapping/PropertyMap.cpp @@ -111,14 +111,15 @@ void PropertyMap::registerKeywords( Keywords& keys ) { PropertyMap::PropertyMap(const ActionOptions& ao): Action(ao), - PathBase(ao) -{ - bool nos; parseFlag("NOMAPPING",nos); + PathBase(ao) { + bool nos; + parseFlag("NOMAPPING",nos); std::string empty; if(!nos) { for(std::map >::iterator it=property.begin(); it!=property.end(); ++it) { - empty="LABEL="+it->first; addVessel( "SPATH", empty, 0 ); + empty="LABEL="+it->first; + addVessel( "SPATH", empty, 0 ); } } readVesselKeywords(); diff --git a/src/mapping/SpathVessel.cpp b/src/mapping/SpathVessel.cpp index 891c7dedfa..476663ffd9 100644 --- a/src/mapping/SpathVessel.cpp +++ b/src/mapping/SpathVessel.cpp @@ -52,15 +52,17 @@ void SpathVessel::reserveKeyword( Keywords& keys ) { SpathVessel::SpathVessel( const vesselbase::VesselOptions& da ): FunctionVessel(da), - foundoneclose(false) -{ + foundoneclose(false) { mymap=dynamic_cast( getAction() ); plumed_massert( mymap, "SpathVessel can only be used with mappings"); // Retrieve the index of the property in the underlying mapping - usetol=true; norm=true; + usetol=true; + norm=true; for(unsigned i=0; igetFullNumberOfTasks(); ++i) { - if( mymap->getTaskCode(i)!=mymap->getPositionInFullTaskList(i) ) error("mismatched tasks and codes"); + if( mymap->getTaskCode(i)!=mymap->getPositionInFullTaskList(i) ) { + error("mismatched tasks and codes"); + } } } @@ -74,9 +76,12 @@ void SpathVessel::prepare() { void SpathVessel::calculate( const unsigned& current, MultiValue& myvals, std::vector& buffer, std::vector& der_index ) const { double pp=mymap->getPropertyValue( current, getLabel() ), weight=myvals.get(0); - if( weightgetNumberOfDerivatives(); - buffer[bufstart] += weight*pp; buffer[bufstart+1+nderivatives] += weight; + buffer[bufstart] += weight*pp; + buffer[bufstart+1+nderivatives] += weight; if( getAction()->derivativesAreRequired() ) { myvals.chainRule( 0, 0, 1, 0, pp, bufstart, buffer ); myvals.chainRule( 0, 1, 1, 0, 1.0, bufstart, buffer ); diff --git a/src/mapping/TrigonometricPathVessel.cpp b/src/mapping/TrigonometricPathVessel.cpp index e882f24042..5d15ac757a 100644 --- a/src/mapping/TrigonometricPathVessel.cpp +++ b/src/mapping/TrigonometricPathVessel.cpp @@ -46,40 +46,69 @@ TrigonometricPathVessel::TrigonometricPathVessel( const vesselbase::VesselOption mydpack3( 1, getAction()->getNumberOfDerivatives() ), mypack1( 0, 0, mydpack1 ), mypack2( 0, 0, mydpack2 ), - mypack3( 0, 0, mydpack3 ) -{ + mypack3( 0, 0, mydpack3 ) { mymap=dynamic_cast( getAction() ); plumed_massert( mymap, "Trigonometric path vessel can only be used with mappings"); // Retrieve the index of the property in the underlying mapping - if( mymap->getNumberOfProperties()!=1 ) error("cannot use trigonometric paths when there are multiple properties"); + if( mymap->getNumberOfProperties()!=1 ) { + error("cannot use trigonometric paths when there are multiple properties"); + } for(unsigned i=0; igetFullNumberOfTasks(); ++i) { - if( mymap->getTaskCode(i)!=mymap->getPositionInFullTaskList(i) ) error("mismatched tasks and codes"); + if( mymap->getTaskCode(i)!=mymap->getPositionInFullTaskList(i) ) { + error("mismatched tasks and codes"); + } } - mymap->addComponentWithDerivatives("gspath"); mymap->componentIsNotPeriodic("gspath"); - sp=mymap->copyOutput( mymap->getNumberOfComponents()-1 ); sp->resizeDerivatives( mymap->getNumberOfDerivatives() ); - mymap->addComponentWithDerivatives("gzpath"); mymap->componentIsNotPeriodic("gzpath"); - zp=mymap->copyOutput( mymap->getNumberOfComponents()-1 ); zp->resizeDerivatives( mymap->getNumberOfDerivatives() ); + mymap->addComponentWithDerivatives("gspath"); + mymap->componentIsNotPeriodic("gspath"); + sp=mymap->copyOutput( mymap->getNumberOfComponents()-1 ); + sp->resizeDerivatives( mymap->getNumberOfDerivatives() ); + mymap->addComponentWithDerivatives("gzpath"); + mymap->componentIsNotPeriodic("gzpath"); + zp=mymap->copyOutput( mymap->getNumberOfComponents()-1 ); + zp->resizeDerivatives( mymap->getNumberOfDerivatives() ); // Check we have PCA ReferenceConfiguration* ref0=mymap->getReferenceConfiguration(0); for(unsigned i=0; igetFullNumberOfTasks(); ++i) { - if( !(mymap->getReferenceConfiguration(i))->pcaIsEnabledForThisReference() ) error("pca must be implemented in order to use trigometric path"); - if( ref0->getName()!=(mymap->getReferenceConfiguration(i))->getName() ) error("cannot use mixed metrics"); - if( mymap->getNumberOfAtoms()!=(mymap->getReferenceConfiguration(i))->getNumberOfReferencePositions() ) error("all frames must use the same set of atoms"); - if( mymap->getNumberOfArguments()!=(mymap->getReferenceConfiguration(i))->getNumberOfReferenceArguments() ) error("all frames must use the same set of arguments"); + if( !(mymap->getReferenceConfiguration(i))->pcaIsEnabledForThisReference() ) { + error("pca must be implemented in order to use trigometric path"); + } + if( ref0->getName()!=(mymap->getReferenceConfiguration(i))->getName() ) { + error("cannot use mixed metrics"); + } + if( mymap->getNumberOfAtoms()!=(mymap->getReferenceConfiguration(i))->getNumberOfReferencePositions() ) { + error("all frames must use the same set of atoms"); + } + if( mymap->getNumberOfArguments()!=(mymap->getReferenceConfiguration(i))->getNumberOfReferenceArguments() ) { + error("all frames must use the same set of arguments"); + } } - cargs.resize( mymap->getNumberOfArguments() ); std::vector argument_names( mymap->getNumberOfArguments() ); - for(unsigned i=0; igetNumberOfArguments(); ++i) argument_names[i] = (mymap->getPntrToArgument(i))->getName(); - PDB mypdb; mypdb.setAtomNumbers( mymap->getAbsoluteIndexes() ); mypdb.addBlockEnd( mymap->getAbsoluteIndexes().size() ); - if( argument_names.size()>0 ) mypdb.setArgumentNames( argument_names ); + cargs.resize( mymap->getNumberOfArguments() ); + std::vector argument_names( mymap->getNumberOfArguments() ); + for(unsigned i=0; igetNumberOfArguments(); ++i) { + argument_names[i] = (mymap->getPntrToArgument(i))->getName(); + } + PDB mypdb; + mypdb.setAtomNumbers( mymap->getAbsoluteIndexes() ); + mypdb.addBlockEnd( mymap->getAbsoluteIndexes().size() ); + if( argument_names.size()>0 ) { + mypdb.setArgumentNames( argument_names ); + } projdir.read( mypdb ); - mypack1.resize( mymap->getNumberOfArguments(), mymap->getNumberOfAtoms() ); ref0->setupPCAStorage( mypack1 ); - mypack2.resize( mymap->getNumberOfArguments(), mymap->getNumberOfAtoms() ); ref0->setupPCAStorage( mypack2 ); + mypack1.resize( mymap->getNumberOfArguments(), mymap->getNumberOfAtoms() ); + ref0->setupPCAStorage( mypack1 ); + mypack2.resize( mymap->getNumberOfArguments(), mymap->getNumberOfAtoms() ); + ref0->setupPCAStorage( mypack2 ); mypack3.resize( mymap->getNumberOfArguments(), mymap->getNumberOfAtoms() ); - for(unsigned i=0; igetNumberOfAtoms(); ++i) { mypack1.setAtomIndex(i,i); mypack2.setAtomIndex(i,i); mypack3.setAtomIndex(i,i); } - mypack1_stashd_atoms.resize( mymap->getNumberOfAtoms() ); mypack1_stashd_args.resize( mymap->getNumberOfArguments() ); + for(unsigned i=0; igetNumberOfAtoms(); ++i) { + mypack1.setAtomIndex(i,i); + mypack2.setAtomIndex(i,i); + mypack3.setAtomIndex(i,i); + } + mypack1_stashd_atoms.resize( mymap->getNumberOfAtoms() ); + mypack1_stashd_args.resize( mymap->getNumberOfArguments() ); } std::string TrigonometricPathVessel::description() { @@ -90,7 +119,8 @@ void TrigonometricPathVessel::resize() { StoreDataVessel::resize(); if( getAction()->derivativesAreRequired() ) { unsigned nderivatives=getAction()->getNumberOfDerivatives(); - sp->resizeDerivatives( nderivatives ); zp->resizeDerivatives( nderivatives ); + sp->resizeDerivatives( nderivatives ); + zp->resizeDerivatives( nderivatives ); } } @@ -98,38 +128,54 @@ void TrigonometricPathVessel::finish( const std::vector& buffer ) { // Store the data calculated during mpi loop StoreDataVessel::finish( buffer ); // Get current value of all arguments - for(unsigned i=0; igetArgument(i); + for(unsigned i=0; igetArgument(i); + } // Determine closest and second closest point to current position double lambda=mymap->getLambda(); std::vector dist( getNumberOfComponents() ), dist2( getNumberOfComponents() );; retrieveSequentialValue( 0, false, dist ); retrieveSequentialValue( 1, false, dist2 ); - iclose1=getStoreIndex(0); iclose2=getStoreIndex(1); + iclose1=getStoreIndex(0); + iclose2=getStoreIndex(1); double mindist1=dist[0], mindist2=dist2[0]; if( lambda>0.0 ) { mindist1=-std::log( dist[0] ) / lambda; mindist2=-std::log( dist2[0] ) / lambda; } if( mindist20.0 ) ndist=-std::log( dist[0] ) / lambda; + if( lambda>0.0 ) { + ndist=-std::log( dist[0] ) / lambda; + } if( ndist1 ) isign=1; else if( isign<-1 ) isign=-1; - int iclose3 = iclose1 + isign; double v2v2; + if( isign>1 ) { + isign=1; + } else if( isign<-1 ) { + isign=-1; + } + int iclose3 = iclose1 + isign; + double v2v2; // We now have to compute vectors connecting the three closest points to the // new point double v1v1 = (mymap->getReferenceConfiguration( iclose1 ))->calculate( mymap->getPositions(), mymap->getPbc(), mymap->getArguments(), mypack1, true ); @@ -149,12 +195,15 @@ void TrigonometricPathVessel::finish( const std::vector& buffer ) { } // Stash derivatives of v1v1 - for(unsigned i=0; igetNumberOfArguments(); ++i) mypack1_stashd_args[i]=mypack1.getArgumentDerivative(i); + for(unsigned i=0; igetNumberOfArguments(); ++i) { + mypack1_stashd_args[i]=mypack1.getArgumentDerivative(i); + } if( mymap->getNumberOfAtoms()>0 ) { ReferenceAtoms* at = dynamic_cast( mymap->getReferenceConfiguration( iclose1 ) ); const std::vector & displace( at->getDisplace() ); for(unsigned i=0; igetNumberOfAtoms(); ++i) { - mypack1_stashd_atoms[i]=mypack1.getAtomDerivative(i); mypack1.getAtomsDisplacementVector()[i] /= displace[i]; + mypack1_stashd_atoms[i]=mypack1.getAtomDerivative(i); + mypack1.getAtomsDisplacementVector()[i] /= displace[i]; } } // Calculate the dot product of v1 with v2 @@ -164,7 +213,8 @@ void TrigonometricPathVessel::finish( const std::vector& buffer ) { double spacing = mymap->getPropertyValue( iclose1, (mymap->property.begin())->first ) - mymap->getPropertyValue( iclose2, (mymap->property.begin())->first ); double root = sqrt( v1v2*v1v2 - v2v2 * ( v1v1 - v3v3) ); dx = 0.5 * ( (root + v1v2) / v2v2 - 1.); - double path_s = mymap->getPropertyValue(iclose1, (mymap->property.begin())->first ) + spacing * dx; sp->set( path_s ); + double path_s = mymap->getPropertyValue(iclose1, (mymap->property.begin())->first ) + spacing * dx; + sp->set( path_s ); double fact = 0.25*spacing / v2v2; // Derivative of s wrt arguments for(unsigned i=0; igetNumberOfArguments(); ++i) { @@ -172,16 +222,24 @@ void TrigonometricPathVessel::finish( const std::vector& buffer ) { + v1v2*mypack2.getArgumentDerivative(i) )/root ) ); } // Derivative of s wrt atoms - unsigned narg=mymap->getNumberOfArguments(); Tensor vir; vir.zero(); fact = 0.5*spacing / v2v2; + unsigned narg=mymap->getNumberOfArguments(); + Tensor vir; + vir.zero(); + fact = 0.5*spacing / v2v2; if( mymap->getNumberOfAtoms()>0 ) { for(unsigned i=0; igetNumberOfAtoms(); ++i) { Vector ader = fact*(( v1v2*mypack1.getAtomDerivative(i) + 0.5*v2v2*(-mypack1_stashd_atoms[i] + mypack3.getAtomDerivative(i) ) )/root + mypack1.getAtomDerivative(i) ); - for(unsigned k=0; k<3; ++k) sp->setDerivative( narg+3*i+k, ader[k] ); + for(unsigned k=0; k<3; ++k) { + sp->setDerivative( narg+3*i+k, ader[k] ); + } vir-=Tensor( mymap->getPosition(i), ader ); } // Set the virial unsigned nbase=narg+3*mymap->getNumberOfAtoms(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) sp->setDerivative( nbase+3*i+j, vir(i,j) ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + sp->setDerivative( nbase+3*i+j, vir(i,j) ); + } } // Now compute z value ReferenceConfiguration* conf2=mymap->getReferenceConfiguration( iclose1 ); @@ -194,33 +252,50 @@ void TrigonometricPathVessel::finish( const std::vector& buffer ) { double proj = (mymap->getReferenceConfiguration(iclose1))->projectDisplacementOnVector( projdir, mymap->getArguments(), cargs, mypack1 ); double path_z = v1v1 + dx*dx*v4v4 - 2*dx*proj; // Derivatives for z path - path_z = sqrt(path_z); zp->set( path_z ); vir.zero(); - for(unsigned i=0; igetNumberOfArguments(); ++i) zp->setDerivative( i, (mypack1_stashd_args[i] - 2*dx*mypack1.getArgumentDerivative(i))/(2.0*path_z) ); + path_z = sqrt(path_z); + zp->set( path_z ); + vir.zero(); + for(unsigned i=0; igetNumberOfArguments(); ++i) { + zp->setDerivative( i, (mypack1_stashd_args[i] - 2*dx*mypack1.getArgumentDerivative(i))/(2.0*path_z) ); + } // Derivative wrt atoms if( mymap->getNumberOfAtoms()>0 ) { for(unsigned i=0; igetNumberOfAtoms(); ++i) { - Vector dxder; for(unsigned k=0; k<3; ++k) dxder[k] = ( 2*v4v4*dx - 2*proj )*spacing*sp->getDerivative( narg + 3*i+k ); + Vector dxder; + for(unsigned k=0; k<3; ++k) { + dxder[k] = ( 2*v4v4*dx - 2*proj )*spacing*sp->getDerivative( narg + 3*i+k ); + } Vector ader = ( mypack1_stashd_atoms[i] - 2.*dx*mypack1.getAtomDerivative(i) + dxder )/ (2.0*path_z); - for(unsigned k=0; k<3; ++k) zp->setDerivative( narg+3*i+k, ader[k] ); + for(unsigned k=0; k<3; ++k) { + zp->setDerivative( narg+3*i+k, ader[k] ); + } vir-=Tensor( mymap->getPosition(i), ader ); } // Set the virial unsigned nbase=narg+3*mymap->getNumberOfAtoms(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) zp->setDerivative( nbase+3*i+j, vir(i,j) ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + zp->setDerivative( nbase+3*i+j, vir(i,j) ); + } } } bool TrigonometricPathVessel::applyForce( std::vector& forces ) { std::vector tmpforce( forces.size(), 0.0 ); - forces.assign(forces.size(),0.0); bool wasforced=false; + forces.assign(forces.size(),0.0); + bool wasforced=false; if( sp->applyForce( tmpforce ) ) { wasforced=true; - for(unsigned j=0; japplyForce( tmpforce ) ) { wasforced=true; - for(unsigned j=0; j( getAction() ); plumed_massert( mymap, "ZpathVessel should only be used with mappings"); - invlambda = 1.0 / mymap->getLambda(); usetol=true; + invlambda = 1.0 / mymap->getLambda(); + usetol=true; } std::string ZpathVessel::value_descriptor() { @@ -62,7 +62,8 @@ std::string ZpathVessel::value_descriptor() { } double ZpathVessel::calcTransform( const double& val, double& dv ) const { - dv=0.0; return 1.0; + dv=0.0; + return 1.0; } double ZpathVessel::finalTransform( const double& val, double& dv ) { diff --git a/src/maze/Loss.cpp b/src/maze/Loss.cpp index 78addfada0..41ade9cd0c 100644 --- a/src/maze/Loss.cpp +++ b/src/maze/Loss.cpp @@ -72,8 +72,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 56d29ac54f..8b3565576b 100644 --- a/src/maze/Optimizer.cpp +++ b/src/maze/Optimizer.cpp @@ -145,8 +145,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")) { @@ -236,8 +235,7 @@ Optimizer::Optimizer(const ActionOptions& ao) nl_cutoff_, nl_stride_ ); - } - else { + } else { neighbor_list_=Tools::make_unique( ga_list, gb_list, @@ -248,8 +246,7 @@ Optimizer::Optimizer(const ActionOptions& ao) comm ); } - } - else { + } else { if (do_neigh) { neighbor_list_ = Tools::make_unique( ga_list, @@ -260,8 +257,7 @@ Optimizer::Optimizer(const ActionOptions& ao) nl_cutoff_, nl_stride_ ); - } - else { + } else { neighbor_list_=Tools::make_unique( ga_list, serial_, @@ -296,8 +292,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"); } @@ -395,8 +390,7 @@ void Optimizer::prepare() { validate_list_ = true; first_time_ = false; - } - else { + } else { requestAtoms(neighbor_list_->getReducedAtomList()); validate_list_ = false; @@ -432,8 +426,7 @@ double Optimizer::score() { if (pbc_) { distance = pbcDistance(getPosition(i0), getPosition(i1)); - } - else { + } else { distance = delta(getPosition(i0), getPosition(i1)); } @@ -450,8 +443,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(); @@ -466,8 +458,7 @@ double Optimizer::sampling_radius() if (pbc_) { d = pbcDistance(getPosition(i0), getPosition(i1)); - } - else { + } else { d = delta(getPosition(i0), getPosition(i1)); } @@ -493,8 +484,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 9c6b0fac24..0a6e12566d 100644 --- a/src/maze/Optimizer_Bias.cpp +++ b/src/maze/Optimizer_Bias.cpp @@ -262,8 +262,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 5fbc9367f0..dc2b988b08 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."); @@ -104,103 +100,119 @@ void fusionPoreExpansionP::registerKeywords(Keywords &keys) keys.add("optional", "YCYL", "X coordinate of the fixed cylinder, if not present this will be calculated."); } -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]); } @@ -208,8 +220,7 @@ fusionPoreExpansionP::fusionPoreExpansionP(const ActionOptions &ao) : PLUMED_COL setNotPeriodic(); requestAtoms(atoms); } -void fusionPoreExpansionP::calculate() -{ +void fusionPoreExpansionP::calculate() { /************************* * * * System * @@ -227,8 +238,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); @@ -307,48 +317,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; @@ -356,9 +354,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; @@ -372,10 +368,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]; @@ -397,13 +391,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); } @@ -466,29 +457,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)); @@ -507,8 +491,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; @@ -517,37 +500,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]; } @@ -570,8 +541,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); } @@ -583,8 +553,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]; @@ -592,8 +561,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 02569c0846..4999ed541f 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."); @@ -108,111 +104,130 @@ void fusionPoreNucleationP::registerKeywords(Keywords &keys) keys.add("optional", "YCYL", "X coordinate of the fixed cylinder, if not present this will be calculated."); } -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]); } @@ -221,8 +236,7 @@ fusionPoreNucleationP::fusionPoreNucleationP(const ActionOptions &ao) : PLUMED_C requestAtoms(atoms); } -void fusionPoreNucleationP::calculate() -{ +void fusionPoreNucleationP::calculate() { /************************* * * * System * @@ -240,8 +254,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); @@ -320,48 +333,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; @@ -369,9 +370,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; @@ -385,10 +384,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]; @@ -410,13 +407,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); } @@ -495,57 +489,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]; @@ -554,9 +535,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]; @@ -572,10 +551,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]; @@ -630,21 +607,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); } @@ -665,11 +636,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; @@ -679,10 +648,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]); @@ -710,27 +677,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]; @@ -740,16 +700,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]; @@ -769,22 +725,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]; @@ -794,8 +745,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 7e7437d9f2..b516cbe6eb 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]); } @@ -185,8 +195,7 @@ memFusionP::memFusionP(const ActionOptions &ao) : PLUMED_COLVAR_INIT(ao) requestAtoms(atoms); } -void memFusionP::calculate() -{ +void memFusionP::calculate() { /************************** * * * System * @@ -204,8 +213,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); @@ -293,49 +301,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]; @@ -344,9 +340,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]; @@ -361,10 +355,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]; @@ -386,13 +378,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); } @@ -427,21 +416,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); } @@ -465,10 +448,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; @@ -478,10 +459,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]); @@ -510,27 +489,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]; @@ -540,16 +512,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]; @@ -569,22 +537,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]; @@ -595,8 +558,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/ActionVolume.cpp b/src/multicolvar/ActionVolume.cpp index c374e4c292..ff4735e6a9 100644 --- a/src/multicolvar/ActionVolume.cpp +++ b/src/multicolvar/ActionVolume.cpp @@ -26,9 +26,15 @@ namespace multicolvar { void ActionVolume::registerKeywords( Keywords& keys ) { VolumeGradientBase::registerKeywords( keys ); - if( keys.reserved("VMEAN") ) keys.use("VMEAN"); - keys.use("MEAN"); keys.use("LESS_THAN"); keys.use("MORE_THAN"); - keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("SUM"); + if( keys.reserved("VMEAN") ) { + keys.use("VMEAN"); + } + keys.use("MEAN"); + keys.use("LESS_THAN"); + keys.use("MORE_THAN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("SUM"); keys.add("compulsory","SIGMA","the width of the function to be used for kernel density estimation"); keys.add("compulsory","KERNEL","gaussian","the type of kernel function to be used"); keys.addFlag("OUTSIDE",false,"calculate quantities for colvars that are on atoms outside the region of interest"); @@ -36,21 +42,31 @@ void ActionVolume::registerKeywords( Keywords& keys ) { ActionVolume::ActionVolume(const ActionOptions&ao): Action(ao), - VolumeGradientBase(ao) -{ + VolumeGradientBase(ao) { // Find number of quantities - if( getPntrToMultiColvar()->isDensity() ) nquantities=2; // Value + weight - else if( getPntrToMultiColvar()->getNumberOfQuantities()==2 ) nquantities=2; // Value + weight - else nquantities = 1 + getPntrToMultiColvar()->getNumberOfQuantities()-2 + 1; // Norm + vector + weight + if( getPntrToMultiColvar()->isDensity() ) { + nquantities=2; // Value + weight + } else if( getPntrToMultiColvar()->getNumberOfQuantities()==2 ) { + nquantities=2; // Value + weight + } else { + nquantities = 1 + getPntrToMultiColvar()->getNumberOfQuantities()-2 + 1; // Norm + vector + weight + } // Output some nice information std::string functype=getPntrToMultiColvar()->getName(); - std::transform( functype.begin(), functype.end(), functype.begin(), [](unsigned char c) { return std::tolower(c); } ); + std::transform( functype.begin(), functype.end(), functype.begin(), [](unsigned char c) { + return std::tolower(c); + } ); log.printf(" calculating %s inside region of insterest\n",functype.c_str() ); - parseFlag("OUTSIDE",not_in); sigma=0.0; - if( keywords.exists("SIGMA") ) parse("SIGMA",sigma); - if( keywords.exists("KERNEL") ) parse("KERNEL",kerneltype); + parseFlag("OUTSIDE",not_in); + sigma=0.0; + if( keywords.exists("SIGMA") ) { + parse("SIGMA",sigma); + } + if( keywords.exists("KERNEL") ) { + parse("KERNEL",kerneltype); + } if( getPntrToMultiColvar()->isDensity() ) { std::string input; @@ -62,21 +78,34 @@ ActionVolume::ActionVolume(const ActionOptions&ao): void ActionVolume::calculateAllVolumes( const unsigned& curr, MultiValue& outvals ) const { Vector catom_pos=getPntrToMultiColvar()->getCentralAtomPos( curr ); - double weight; Vector wdf; Tensor vir; std::vector refders( getNumberOfAtoms() ); + double weight; + Vector wdf; + Tensor vir; + std::vector refders( getNumberOfAtoms() ); weight=calculateNumberInside( catom_pos, wdf, vir, refders ); if( not_in ) { - weight = 1.0 - weight; wdf *= -1.; vir *=-1; - for(unsigned i=0; igetCentralAtomPos( curr ); - Vector wdf; Tensor vir; std::vector refders( getNumberOfAtoms() ); + Vector wdf; + Tensor vir; + std::vector refders( getNumberOfAtoms() ); double weight=calculateNumberInside( catom_pos, wdf, vir, refders ); - if( not_in ) weight = 1.0 - weight; - if( weight all_atoms; readAtomsLikeKeyword( "ATOMS", 4, all_atoms ); @@ -141,12 +142,16 @@ AlphaBeta::AlphaBeta(const ActionOptions&ao): // Read in reference values unsigned ntarget=0; for(unsigned i=0; i0 ) { use_sf=true; weightHasDerivatives=true; sf1.set(sfinput,errors); - if( errors.length()!=0 ) error("problem reading SWITCH keyword : " + errors ); + 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 ); + } log.printf(" only calculating angles for atoms separated by less than %s\n", sf1.description().c_str() ); } else { parse("SWITCHA",sfinput); @@ -149,11 +158,18 @@ Angles::Angles(const ActionOptions&ao): use_sf=true; weightHasDerivatives=true; sf1.set(sfinput,errors); - 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"); + 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 ); + } log.printf(" only calculating angles when the distance between GROUPA and GROUPB atoms is less than %s\n", sf1.description().c_str() ); log.printf(" only calculating angles when the distance between GROUPA and GROUPC atoms is less than %s\n", sf2.description().c_str() ); } @@ -161,7 +177,9 @@ Angles::Angles(const ActionOptions&ao): // Read in the atoms std::vector all_atoms; readGroupKeywords( "GROUP", "GROUPA", "GROUPB", "GROUPC", false, true, all_atoms ); - if( atom_lab.size()==0 ) readAtomsLikeKeyword( "ATOMS", 3, all_atoms ); + if( atom_lab.size()==0 ) { + readAtomsLikeKeyword( "ATOMS", 3, all_atoms ); + } setupMultiColvarBase( all_atoms ); // Set cutoff for link cells if( use_sf ) { @@ -173,12 +191,15 @@ Angles::Angles(const ActionOptions&ao): // And check everything has been read in correctly checkRead(); // Setup stuff for central atom - std::vector catom_ind(3, false); catom_ind[0]=true; + std::vector catom_ind(3, false); + catom_ind[0]=true; setAtomsForCentralAtom( catom_ind ); } double Angles::calculateWeight( const unsigned& taskCode, const double& weight, AtomValuePack& myatoms ) const { - if(!use_sf) return 1.0; + if(!use_sf) { + return 1.0; + } Vector dij=getSeparation( myatoms.getPosition(0), myatoms.getPosition(2) ); Vector dik=getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); @@ -186,12 +207,16 @@ double Angles::calculateWeight( const unsigned& taskCode, const double& weight, double ldij = dij.modulo2(), ldik = dik.modulo2(); if( use_sf ) { - if( ldij>rcut2_1 || ldik>rcut2_2 ) return 0.0; + if( ldij>rcut2_1 || ldik>rcut2_2 ) { + return 0.0; + } } w1=sf1.calculateSqr( ldij, dw1 ); w2=sf2.calculateSqr( ldik, dw2 ); - wtot=w1*w2; dw1*=weight*w2; dw2*=weight*w1; + wtot=w1*w2; + dw1*=weight*w2; + dw2*=weight*w1; addAtomDerivatives( 0, 1, dw2*dik, myatoms ); addAtomDerivatives( 0, 0, -dw1*dij - dw2*dik, myatoms ); @@ -204,7 +229,8 @@ double Angles::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { Vector dij=getSeparation( myatoms.getPosition(0), myatoms.getPosition(2) ); Vector dik=getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); - Vector ddij,ddik; PLMD::Angle a; + Vector ddij,ddik; + PLMD::Angle a; double angle=a.compute(dij,dik,ddij,ddik); // And finish the calculation diff --git a/src/multicolvar/AtomValuePack.cpp b/src/multicolvar/AtomValuePack.cpp index 605214f0b4..0cf4789984 100644 --- a/src/multicolvar/AtomValuePack.cpp +++ b/src/multicolvar/AtomValuePack.cpp @@ -32,8 +32,7 @@ AtomValuePack::AtomValuePack( MultiValue& vals, MultiColvarBase const * mcolv ): natoms(0), indices( vals.getIndices() ), sort_vector( vals.getSortIndices() ), - myatoms( vals.getAtomVector() ) -{ + myatoms( vals.getAtomVector() ) { if( indices.size()!=mcolv->getNumberOfAtoms() ) { indices.resize( mcolv->getNumberOfAtoms() ); sort_vector.resize( mcolv->getNumberOfAtoms() ); @@ -42,25 +41,40 @@ AtomValuePack::AtomValuePack( MultiValue& vals, MultiColvarBase const * mcolv ): } unsigned AtomValuePack::setupAtomsFromLinkCells( const std::vector& cind, const Vector& cpos, const LinkCells& linkcells ) { - if( cells_required.size()!=linkcells.getNumberOfCells() ) cells_required.resize( linkcells.getNumberOfCells() ); + if( cells_required.size()!=linkcells.getNumberOfCells() ) { + cells_required.resize( linkcells.getNumberOfCells() ); + } // Build the list of cells that we need - unsigned ncells_required=0; linkcells.addRequiredCells( linkcells.findMyCell( cpos ), ncells_required, cells_required ); + unsigned ncells_required=0; + linkcells.addRequiredCells( linkcells.findMyCell( cpos ), ncells_required, cells_required ); // Now build the list of atoms we need - natoms=cind.size(); for(unsigned i=0; igetPositionOfAtomForLinkCells( indices[i] ) - cpos; - if( mycolv->usesPbc() ) mycolv->applyPbc( myatoms, natoms ); + for(unsigned i=0; igetPositionOfAtomForLinkCells( indices[i] ) - cpos; + } + if( mycolv->usesPbc() ) { + mycolv->applyPbc( myatoms, natoms ); + } return natoms; } void AtomValuePack::updateUsingIndices() { - if( myvals.updateComplete() ) return; + if( myvals.updateComplete() ) { + return; + } unsigned jactive=0; for(unsigned i=0; igetNumberOfAtoms(); if( myvals.isActive( nvir ) ) { - for(unsigned i=0; i<9; ++i) myvals.putIndexInActiveArray( nvir + i ); + for(unsigned i=0; i<9; ++i) { + myvals.putIndexInActiveArray( nvir + i ); + } } myvals.completeUpdate(); } diff --git a/src/multicolvar/AtomValuePack.h b/src/multicolvar/AtomValuePack.h index e438f91d17..5c6e80275e 100644 --- a/src/multicolvar/AtomValuePack.h +++ b/src/multicolvar/AtomValuePack.h @@ -116,27 +116,32 @@ unsigned AtomValuePack::getNumberOfDerivatives() const { inline void AtomValuePack::setIndex( const unsigned& j, const unsigned& ind ) { - plumed_dbg_assert( jgetPositionOfAtomForLinkCells( ind ); + setAtomIndex( j, ind ); + myatoms[j]=mycolv->getPositionOfAtomForLinkCells( ind ); } inline unsigned AtomValuePack::getIndex( const unsigned& j ) const { - plumed_dbg_assert( jatom_lab[jatom].first>0 ) { unsigned mmc=mycolv->atom_lab[jatom].first - 1; return (mycolv->mybasemulticolvars[mmc])->getAbsoluteIndexOfCentralAtom( mycolv->atom_lab[jatom].second ); @@ -189,18 +194,26 @@ void AtomValuePack::addTemporyAtomsDerivatives( const unsigned& jder, const Vect inline void AtomValuePack::addTemporyBoxDerivatives( const Tensor& vir ) { unsigned nvir=3*mycolv->getNumberOfAtoms(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) myvals.addTemporyDerivative( nvir + 3*i+j, vir(i,j) ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + myvals.addTemporyDerivative( nvir + 3*i+j, vir(i,j) ); + } } inline void AtomValuePack::addBoxDerivatives( const unsigned& ival, const Tensor& vir ) { unsigned nvir=3*mycolv->getNumberOfAtoms(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) myvals.addDerivative( ival, nvir + 3*i+j, vir(i,j) ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + myvals.addDerivative( ival, nvir + 3*i+j, vir(i,j) ); + } } inline void AtomValuePack::updateDynamicList() { - if( myvals.updateComplete() ) return; + if( myvals.updateComplete() ) { + return; + } myvals.updateDynamicList(); } diff --git a/src/multicolvar/Bridge.cpp b/src/multicolvar/Bridge.cpp index f8a072ba1c..e6215807e3 100644 --- a/src/multicolvar/Bridge.cpp +++ b/src/multicolvar/Bridge.cpp @@ -67,7 +67,9 @@ class Bridge : public MultiColvarBase { explicit Bridge(const ActionOptions&); // active methods: double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(Bridge,"BRIDGE") @@ -87,33 +89,45 @@ void Bridge::registerKeywords( Keywords& keys ) { Bridge::Bridge(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { // Read in the atoms std::vector all_atoms; readThreeGroups("GROUPA","GROUPB","BRIDGING_ATOMS",false,true,all_atoms); // Setup the multicolvar base setupMultiColvarBase( all_atoms ); // Setup Central atom atoms - std::vector catom_ind(3, false); catom_ind[0]=true; + std::vector catom_ind(3, false); + catom_ind[0]=true; setAtomsForCentralAtom( catom_ind ); - std::string sfinput,errors; parse("SWITCH",sfinput); + std::string sfinput,errors; + parse("SWITCH",sfinput); if( sfinput.length()>0 ) { sf1.set(sfinput,errors); - if( errors.length()!=0 ) error("problem reading SWITCH keyword : " + errors ); + 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) { weightHasDerivatives=true; sf1.set(sfinput,errors); - 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"); + 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"); } @@ -125,7 +139,9 @@ Bridge::Bridge(const ActionOptions&ao): setLinkCellCutoff( sf1.get_dmax() + sf2.get_dmax() ); // And setup the ActionWithVessel - if( getNumberOfVessels()!=0 ) error("should not have vessels for this action"); + if( getNumberOfVessels()!=0 ) { + error("should not have vessels for this action"); + } std::string fake_input; addVessel( "SUM", fake_input, -1 ); // -1 here means that this value will be named getLabel() readVesselKeywords(); diff --git a/src/multicolvar/BridgedMultiColvarFunction.cpp b/src/multicolvar/BridgedMultiColvarFunction.cpp index a70eec53be..dd5fecff86 100644 --- a/src/multicolvar/BridgedMultiColvarFunction.cpp +++ b/src/multicolvar/BridgedMultiColvarFunction.cpp @@ -34,26 +34,36 @@ void BridgedMultiColvarFunction::registerKeywords( Keywords& keys ) { BridgedMultiColvarFunction::BridgedMultiColvarFunction(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ - std::string mlab; parse("DATA",mlab); + MultiColvarBase(ao) { + std::string mlab; + parse("DATA",mlab); mycolv = plumed.getActionSet().selectWithLabel(mlab); - if(!mycolv) error("action labeled " + mlab + " does not exist or is not a multicolvar"); + if(!mycolv) { + error("action labeled " + mlab + " does not exist or is not a multicolvar"); + } // When using numerical derivatives here we must use numerical derivatives // in base multicolvar - if( checkNumericalDerivatives() ) mycolv->useNumericalDerivatives(); + if( checkNumericalDerivatives() ) { + mycolv->useNumericalDerivatives(); + } - myBridgeVessel = mycolv->addBridgingVessel( this ); addDependency(mycolv); - weightHasDerivatives=true; usespecies=mycolv->usespecies; + myBridgeVessel = mycolv->addBridgingVessel( this ); + addDependency(mycolv); + weightHasDerivatives=true; + usespecies=mycolv->usespecies; // Number of tasks is the same as the number in the underlying MultiColvar - for(unsigned i=0; igetFullNumberOfTasks(); ++i) addTaskToList( mycolv->getTaskCode(i) ); + for(unsigned i=0; igetFullNumberOfTasks(); ++i) { + addTaskToList( mycolv->getTaskCode(i) ); + } } void BridgedMultiColvarFunction::turnOnDerivatives() { BridgedMultiColvarFunction* check = dynamic_cast( mycolv ); if( check ) { - if( check->getNumberOfAtoms()>0 ) error("cannot calculate required derivatives of this quantity"); + if( check->getNumberOfAtoms()>0 ) { + error("cannot calculate required derivatives of this quantity"); + } } MultiColvarBase::turnOnDerivatives(); } @@ -65,12 +75,20 @@ void BridgedMultiColvarFunction::transformBridgedDerivatives( const unsigned& cu if( derivativesAreRequired() ) { outvals.emptyActiveMembers(); if( mycolv->isDensity() ) { - for(unsigned j=0; j<3; ++j) outvals.putIndexInActiveArray( 3*current+j ); - for(unsigned j=invals.getNumberOfDerivatives()-9; jgetNumberOfDerivatives() ) { invals.resize( mycolv->getNumberOfQuantities(), mycolv->getNumberOfDerivatives() ); } - invals.clearAll(); mycolv->performTask( taskIndex, current, invals ); + invals.clearAll(); + mycolv->performTask( taskIndex, current, invals ); transformBridgedDerivatives( taskIndex, invals, myvals ); } @@ -99,11 +118,15 @@ void BridgedMultiColvarFunction::calculateNumericalDerivatives( ActionWithValue* } void BridgedMultiColvarFunction::applyBridgeForces( const std::vector& bb ) { - if( getNumberOfAtoms()==0 ) return ; + if( getNumberOfAtoms()==0 ) { + return ; + } std::vector& f( modifyForces() ); for(unsigned i=0; i& indices ); void applyBridgeForces( const std::vector& bb ) override; diff --git a/src/multicolvar/CatomPack.cpp b/src/multicolvar/CatomPack.cpp index 3f0eee8cac..dbc4f3ebd4 100644 --- a/src/multicolvar/CatomPack.cpp +++ b/src/multicolvar/CatomPack.cpp @@ -25,7 +25,8 @@ namespace PLMD { namespace multicolvar { void CatomPack::resize( const unsigned& size ) { - indices.resize(size); derivs.resize(size); + indices.resize(size); + derivs.resize(size); } } diff --git a/src/multicolvar/CenterOfMultiColvar.cpp b/src/multicolvar/CenterOfMultiColvar.cpp index f88fbcc6e8..f516880eb6 100644 --- a/src/multicolvar/CenterOfMultiColvar.cpp +++ b/src/multicolvar/CenterOfMultiColvar.cpp @@ -103,19 +103,25 @@ void CenterOfMultiColvar::registerKeywords(Keywords& keys) { CenterOfMultiColvar::CenterOfMultiColvar(const ActionOptions&ao): Action(ao), - ActionWithVirtualAtom(ao) -{ - std::string mlab; parse("DATA",mlab); + ActionWithVirtualAtom(ao) { + std::string mlab; + parse("DATA",mlab); mycolv= plumed.getActionSet().selectWithLabel(mlab); - if(!mycolv) error("action labelled " + mlab + " does not exist or does not have vessels"); + if(!mycolv) { + error("action labelled " + mlab + " does not exist or does not have vessels"); + } // Copy the atoms from the input multicolvar BridgedMultiColvarFunction* mybr=dynamic_cast( mycolv ); if( mybr ) { - requestAtoms( (mybr->getPntrToMultiColvar())->getAbsoluteIndexes() ); comp=1; + requestAtoms( (mybr->getPntrToMultiColvar())->getAbsoluteIndexes() ); + comp=1; } else { if( mycolv->getNumberOfQuantities()>5 ) { - int incomp=-1; parse("COMPONENT",incomp); - if( incomp<0 ) error("vector input but component was not specified"); + int incomp=-1; + parse("COMPONENT",incomp); + if( incomp<0 ) { + error("vector input but component was not specified"); + } comp=incomp; } else { comp=1; @@ -123,7 +129,8 @@ CenterOfMultiColvar::CenterOfMultiColvar(const ActionOptions&ao): requestAtoms( mycolv->getAbsoluteIndexes () ); } // We need the derivatives - mycolv->turnOnDerivatives(); addDependency(mycolv); + mycolv->turnOnDerivatives(); + addDependency(mycolv); mystash = mycolv->buildDataStashes( NULL ); log.printf(" building center of mass based on weights calculated in multicolvar action named %s \n",mycolv->getLabel().c_str() ); } @@ -131,16 +138,21 @@ CenterOfMultiColvar::CenterOfMultiColvar(const ActionOptions&ao): void CenterOfMultiColvar::calculate() { // Retrieve the periodic boundary conditions const Pbc& pbc=mycolv->getPbc(); - if( !pbc.isOrthorombic() ) error("Berry phase does not work for non orthorhombic cells"); + if( !pbc.isOrthorombic() ) { + error("Berry phase does not work for non orthorhombic cells"); + } // Create a multivalue to store the derivatives - MultiValue myvals( 7, mycolv->getNumberOfDerivatives() ); myvals.clearAll(); + MultiValue myvals( 7, mycolv->getNumberOfDerivatives() ); + myvals.clearAll(); MultiValue tvals( mycolv->getNumberOfQuantities(), mycolv->getNumberOfDerivatives() ); tvals.clearAll(); // Now loop over all active multicolvars Vector stmp, ctmp, scom, ccom, sder, cder; - scom.zero(); ccom.zero(); double norm=0; + scom.zero(); + ccom.zero(); + double norm=0; std::vector cvals( mycolv->getNumberOfQuantities() ); for(unsigned i=0; igetNumberOfStoredValues(); ++i) { // Retrieve value and derivatives @@ -150,8 +162,10 @@ void CenterOfMultiColvar::calculate() { Vector fpos = pbc.realToScaled( mycolv->getCentralAtomPos( mycolv->getPositionInFullTaskList(i) ) ); // Now accumulate Berry phase averages for(unsigned j=0; j<3; ++j) { - stmp[j] = std::sin( 2*pi*fpos[j] ); ctmp[j] = std::cos( 2*pi*fpos[j] ); - scom[j] += cvals[0]*cvals[comp]*stmp[j]; ccom[j] += cvals[0]*cvals[comp]*ctmp[j]; + stmp[j] = std::sin( 2*pi*fpos[j] ); + ctmp[j] = std::cos( 2*pi*fpos[j] ); + scom[j] += cvals[0]*cvals[comp]*stmp[j]; + ccom[j] += cvals[0]*cvals[comp]*ctmp[j]; double icell = 1.0 / getPbc().getBox().getRow(j).modulo(); sder[j] = 2*pi*icell*cvals[0]*cvals[comp]*std::cos( 2*pi*fpos[j] ); cder[j]=-2*pi*icell*cvals[0]*cvals[comp]*std::sin( 2*pi*fpos[j] ); @@ -168,7 +182,8 @@ void CenterOfMultiColvar::calculate() { } } // Get the central atom pack - CatomPack mypack; mycolv->getCentralAtomPack( 0, mycolv->getPositionInFullTaskList(i), mypack ); + CatomPack mypack; + mycolv->getCentralAtomPack( 0, mycolv->getPositionInFullTaskList(i), mypack ); for(unsigned j=0; j fderiv( getNumberOfAtoms() ); for(unsigned j=0; j0) { 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 { - 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); } @@ -150,7 +169,9 @@ CoordinationNumbers::CoordinationNumbers(const ActionOptions&ao): rcut2 = rcut * rcut; // And setup the ActionWithVessel - std::vector all_atoms; setupMultiColvarBase( all_atoms ); checkRead(); + std::vector all_atoms; + setupMultiColvarBase( all_atoms ); + checkRead(); } double CoordinationNumbers::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { @@ -166,7 +187,8 @@ double CoordinationNumbers::compute( const unsigned& tindex, AtomValuePack& myat sw = switchingFunction.calculateSqr( d2, dfunc ); if(r_power > 0) { - d = std::sqrt(d2); raised = std::pow( d, r_power - 1 ); + d = std::sqrt(d2); + raised = std::pow( d, r_power - 1 ); accumulateSymmetryFunction( 1, i, sw * raised * d, (dfunc * d * raised + sw * r_power * raised / d) * distance, (-dfunc * d * raised - sw * r_power * raised / d) * Tensor(distance, distance), diff --git a/src/multicolvar/Density.cpp b/src/multicolvar/Density.cpp index 679d6d91f5..510ec4eb56 100644 --- a/src/multicolvar/Density.cpp +++ b/src/multicolvar/Density.cpp @@ -55,9 +55,15 @@ class Density : public MultiColvarBase { // active methods: double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; /// Returns the number of coordinates of the field - bool isPeriodic() override { return false; } - bool isDensity() const override { return true; } - bool hasDifferentiableOrientation() const override { return true; } + bool isPeriodic() override { + return false; + } + bool isDensity() const override { + return true; + } + bool hasDifferentiableOrientation() const override { + return true; + } // void addOrientationDerivativesToBase( const unsigned& iatom, const unsigned& jstore, const unsigned& base_cv_no, // const std::vector& weight, MultiColvarFunction* func ){} void getIndexList( const unsigned& ntotal, const unsigned& jstore, const unsigned& maxder, std::vector& indices ); @@ -74,11 +80,15 @@ void Density::registerKeywords( Keywords& keys ) { Density::Density(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ - std::vector all_atoms; parseMultiColvarAtomList("SPECIES", -1, all_atoms); - ablocks.resize(1); ablocks[0].resize( atom_lab.size() ); - for(unsigned i=0; i all_atoms; + parseMultiColvarAtomList("SPECIES", -1, all_atoms); + ablocks.resize(1); + ablocks[0].resize( atom_lab.size() ); + for(unsigned i=0; i& vals ) { - plumed_dbg_assert( vals.size()==2 ); vals[0]=vals[1]=1.0; + plumed_dbg_assert( vals.size()==2 ); + vals[0]=vals[1]=1.0; } } diff --git a/src/multicolvar/DihedralCorrelation.cpp b/src/multicolvar/DihedralCorrelation.cpp index 239f128831..c4305e2ed4 100644 --- a/src/multicolvar/DihedralCorrelation.cpp +++ b/src/multicolvar/DihedralCorrelation.cpp @@ -86,7 +86,9 @@ class DihedralCorrelation : public MultiColvarBase { static void registerKeywords( Keywords& keys ); explicit DihedralCorrelation(const ActionOptions&); double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(DihedralCorrelation,"DIHCOR") @@ -103,8 +105,7 @@ void DihedralCorrelation::registerKeywords( Keywords& keys ) { DihedralCorrelation::DihedralCorrelation(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { // Read in the atoms std::vector all_atoms; readAtomsLikeKeyword( "ATOMS", 8, all_atoms ); diff --git a/src/multicolvar/DistanceFromContour.cpp b/src/multicolvar/DistanceFromContour.cpp index 18acaf1263..591db68938 100644 --- a/src/multicolvar/DistanceFromContour.cpp +++ b/src/multicolvar/DistanceFromContour.cpp @@ -87,10 +87,14 @@ class DistanceFromContour : public MultiColvarBase { public: static void registerKeywords( Keywords& keys ); explicit DistanceFromContour( const ActionOptions& ); - bool isDensity() const override { return true; } + bool isDensity() const override { + return true; + } void calculate() override; unsigned getNumberOfQuantities() const override; - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; double getDifferenceFromContour( const std::vector& x, std::vector& der ); // We need an apply action as we are using an independent value @@ -130,61 +134,104 @@ DistanceFromContour::DistanceFromContour( const ActionOptions& ao ): dirv(3,0.0), dirv2(3,0.0), perp_dirs(2), - mymin(this) -{ + mymin(this) { // Read in the multicolvar/atoms - std::vector all_atoms; parse("TOLERANCE",pbc_param); + std::vector all_atoms; + parse("TOLERANCE",pbc_param); bool read2 = parseMultiColvarAtomList("DATA", -1, all_atoms); - if( !read2 ) error("missing DATA keyword"); + if( !read2 ) { + error("missing DATA keyword"); + } bool read1 = parseMultiColvarAtomList("ATOM", -1, all_atoms); - if( !read1 ) error("missing ATOM keyword"); - if( all_atoms.size()!=1 ) error("should only be one atom specified"); + if( !read1 ) { + error("missing ATOM keyword"); + } + if( all_atoms.size()!=1 ) { + error("should only be one atom specified"); + } // Read in the center of the binding object log.printf(" computing distance of atom %d from contour \n",all_atoms[0].serial() ); - setupMultiColvarBase( all_atoms ); forces.resize( 3*getNumberOfAtoms() + 9 ); - if( getNumberOfBaseMultiColvars()!=1 ) error("should only be one input multicolvar"); + setupMultiColvarBase( all_atoms ); + forces.resize( 3*getNumberOfAtoms() + 9 ); + if( getNumberOfBaseMultiColvars()!=1 ) { + error("should only be one input multicolvar"); + } // Get the direction - std::string ldir; parse("DIR",ldir ); - if( ldir=="x" ) { dir=0; perp_dirs[0]=1; perp_dirs[1]=2; dirv[0]=1; dirv2[0]=-1; } - else if( ldir=="y" ) { dir=1; perp_dirs[0]=0; perp_dirs[1]=2; dirv[1]=1; dirv2[1]=-1; } - else if( ldir=="z" ) { dir=2; perp_dirs[0]=0; perp_dirs[1]=1; dirv[2]=1; dirv2[2]=-1; } - else error(ldir + " is not a valid direction use x, y or z"); + std::string ldir; + parse("DIR",ldir ); + if( ldir=="x" ) { + dir=0; + perp_dirs[0]=1; + perp_dirs[1]=2; + dirv[0]=1; + dirv2[0]=-1; + } else if( ldir=="y" ) { + dir=1; + perp_dirs[0]=0; + perp_dirs[1]=2; + dirv[1]=1; + dirv2[1]=-1; + } else if( ldir=="z" ) { + dir=2; + perp_dirs[0]=0; + perp_dirs[1]=1; + dirv[2]=1; + dirv2[2]=-1; + } else { + error(ldir + " is not a valid direction use x, y or z"); + } // Read in details of phase field construction - parseVector("BANDWIDTH",bw); parse("KERNEL",kerneltype); parse("CONTOUR",contour); + parseVector("BANDWIDTH",bw); + parse("KERNEL",kerneltype); + parse("CONTOUR",contour); log.printf(" searching for contour in %s direction at %f in phase field for multicolvar %s \n",ldir.c_str(), contour, mybasemulticolvars[0]->getLabel().c_str() ); log.printf(" constructing phase field using %s kernels with bandwidth (%f, %f, %f) \n",kerneltype.c_str(), bw[0], bw[1], bw[2] ); // Now create a task list - for(unsigned i=0; igetFullNumberOfTasks(); ++i) addTaskToList(i); + for(unsigned i=0; igetFullNumberOfTasks(); ++i) { + addTaskToList(i); + } // And a cutoff std::vector pp( bw.size(),0 ); KernelFunctions kernel( pp, bw, kerneltype, "DIAGONAL", 1.0 ); double rcut = kernel.getCutoff( bw[0] ); for(unsigned j=1; jrcut ) rcut=kernel.getCutoff(bw[j]); + if( kernel.getCutoff(bw[j])>rcut ) { + rcut=kernel.getCutoff(bw[j]); + } } rcut2=rcut*rcut; // Create the values - addComponent("thickness"); componentIsNotPeriodic("thickness"); - addComponent("dist1"); componentIsNotPeriodic("dist1"); - addComponent("dist2"); componentIsNotPeriodic("dist2"); - addComponentWithDerivatives("qdist"); componentIsNotPeriodic("qdist"); + addComponent("thickness"); + componentIsNotPeriodic("thickness"); + addComponent("dist1"); + componentIsNotPeriodic("dist1"); + addComponent("dist2"); + componentIsNotPeriodic("dist2"); + addComponentWithDerivatives("qdist"); + componentIsNotPeriodic("qdist"); // Create sum vessels - std::string fake_input; std::string deriv_input="COMPONENT=2"; + std::string fake_input; + std::string deriv_input="COMPONENT=2"; if( mybasemulticolvars[0]->isDensity() ) { - addVessel( "SUM", fake_input, -1 ); addVessel( "SUM", deriv_input, -1 ); + addVessel( "SUM", fake_input, -1 ); + addVessel( "SUM", deriv_input, -1 ); } else { - addVessel( "MEAN", fake_input, -1 ); addVessel( "MEAN", deriv_input, -1 ); + addVessel( "MEAN", fake_input, -1 ); + addVessel( "MEAN", deriv_input, -1 ); } // And convert to a value vessel so we can get the final value myvalue_vessel = dynamic_cast( getPntrToVessel(0) ); myderiv_vessel = dynamic_cast( getPntrToVessel(1) ); - plumed_assert( myvalue_vessel && myderiv_vessel ); resizeFunctions(); + plumed_assert( myvalue_vessel && myderiv_vessel ); + resizeFunctions(); // Create the vector of values that holds the position - for(unsigned i=0; i<3; ++i) pval.emplace_back( Tools::make_unique() ); + for(unsigned i=0; i<3; ++i) { + pval.emplace_back( Tools::make_unique() ); + } } unsigned DistanceFromContour::getNumberOfQuantities() const { @@ -193,26 +240,35 @@ unsigned DistanceFromContour::getNumberOfQuantities() const { 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 deactivateAllTasks(); - Vector myvec = getSeparation( getPosition(getNumberOfAtoms()-1), getPosition(0) ); pos2[dir]=myvec[dir]; - taskFlags[0]=1; double mindist = myvec.modulo2(); + Vector myvec = getSeparation( getPosition(getNumberOfAtoms()-1), getPosition(0) ); + pos2[dir]=myvec[dir]; + taskFlags[0]=1; + double mindist = myvec.modulo2(); for(unsigned j=1; jepsilon ) { pos2[dir]=distance[dir]; mindist = d2; } + if( d2epsilon ) { + pos2[dir]=distance[dir]; + mindist = d2; + } taskFlags[j]=1; } } - lockContributors(); derivTime=false; + lockContributors(); + derivTime=false; // pos1 position of the nanoparticle, in the first time // pos2 is the position of the closer atom in the membrane with respect the nanoparticle // fa = distance between pos1 and the contour @@ -224,8 +280,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 } } @@ -239,8 +298,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]; } @@ -248,11 +310,17 @@ void DistanceFromContour::calculate() { // Now do a search for the two contours mymin.lsearch( dirv, pos1, &DistanceFromContour::getDifferenceFromContour ); // Save the first value - Vector root1; root1.zero(); root1[dir] = pval[dir]->get(); + Vector root1; + root1.zero(); + root1[dir] = pval[dir]->get(); mymin.lsearch( dirv2, pos2, &DistanceFromContour::getDifferenceFromContour ); // Calculate the separation between the two roots using PBC - Vector root2; root2.zero(); root2[dir]=pval[dir]->get(); - Vector sep = getSeparation( root1, root2 ); double spacing = std::fabs( sep[dir] ); plumed_assert( spacing>epsilon ); + Vector root2; + root2.zero(); + root2[dir]=pval[dir]->get(); + Vector sep = getSeparation( root1, root2 ); + double spacing = std::fabs( sep[dir] ); + plumed_assert( spacing>epsilon ); getPntrToComponent("thickness")->set( spacing ); // Make sure the sign is right @@ -273,19 +341,39 @@ void DistanceFromContour::calculate() { // Now calculate the derivatives if( !doNotCalculateDerivatives() ) { - Value* ival=myvalue_vessel->getFinalValue(); ival->clearDerivatives(); - std::vector root1v(3); for(unsigned i=0; i<3; ++i) root1v[i]=root1[i]; - derivTime=true; std::vector der(3); getDifferenceFromContour( root1v, der ); double prefactor; - if( mybasemulticolvars[0]->isDensity() ) prefactor = root2[dir] / myderiv_vessel->getOutputValue(); - else plumed_error(); + Value* ival=myvalue_vessel->getFinalValue(); + ival->clearDerivatives(); + std::vector root1v(3); + for(unsigned i=0; i<3; ++i) { + root1v[i]=root1[i]; + } + derivTime=true; + std::vector der(3); + getDifferenceFromContour( root1v, der ); + double prefactor; + if( mybasemulticolvars[0]->isDensity() ) { + prefactor = root2[dir] / myderiv_vessel->getOutputValue(); + } else { + plumed_error(); + } Value* val=getPntrToComponent("qdist"); - for(unsigned i=0; igetNumberOfDerivatives(); ++i) val->setDerivative( i, -prefactor*ival->getDerivative(i) ); + for(unsigned i=0; igetNumberOfDerivatives(); ++i) { + val->setDerivative( i, -prefactor*ival->getDerivative(i) ); + } ival->clearDerivatives(); - std::vector root2v(3); for(unsigned i=0; i<3; ++i) root2v[i]=root2[i]; + std::vector root2v(3); + for(unsigned i=0; i<3; ++i) { + root2v[i]=root2[i]; + } getDifferenceFromContour( root2v, der ); - if( mybasemulticolvars[0]->isDensity() ) prefactor = root1[dir] / myderiv_vessel->getOutputValue(); - else plumed_error(); - for(unsigned i=0; igetNumberOfDerivatives(); ++i) val->addDerivative( i, -prefactor*ival->getDerivative(i) ); + if( mybasemulticolvars[0]->isDensity() ) { + prefactor = root1[dir] / myderiv_vessel->getOutputValue(); + } else { + plumed_error(); + } + for(unsigned i=0; igetNumberOfDerivatives(); ++i) { + val->addDerivative( i, -prefactor*ival->getDerivative(i) ); + } } } @@ -294,7 +382,8 @@ double DistanceFromContour::getDifferenceFromContour( const std::vector& for(unsigned j=0; j<3; ++j) { Tools::convert( -0.5*getBox()(j,j), min ); Tools::convert( +0.5*getBox()(j,j), max ); - pval[j]->setDomain( min, max ); pval[j]->set( x[j] ); + pval[j]->setDomain( min, max ); + pval[j]->set( x[j] ); } runAllTasks(); return myvalue_vessel->getOutputValue() - contour; @@ -302,27 +391,34 @@ double DistanceFromContour::getDifferenceFromContour( const std::vector& double DistanceFromContour::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { Vector distance = getSeparation( getPosition(getNumberOfAtoms()-1), myatoms.getPosition(0) ); - std::vector pp(3), der(3,0); for(unsigned j=0; j<3; ++j) pp[j] = distance[j]; + std::vector pp(3), der(3,0); + for(unsigned j=0; j<3; ++j) { + pp[j] = distance[j]; + } // convert the pointer once auto pval_ptr=Tools::unique2raw(pval); // Now create the kernel and evaluate KernelFunctions kernel( pp, bw, kerneltype, "DIAGONAL", 1.0 ); - kernel.normalize( pval_ptr ); double newval = kernel.evaluate( pval_ptr, der, true ); + kernel.normalize( pval_ptr ); + double newval = kernel.evaluate( pval_ptr, der, true ); if( mybasemulticolvars[0]->isDensity() ) { if( !doNotCalculateDerivatives() && derivTime ) { MultiValue& myvals=myatoms.getUnderlyingMultiValue(); - Vector vder; unsigned basen=myvals.getNumberOfDerivatives() - 12; + Vector vder; + unsigned basen=myvals.getNumberOfDerivatives() - 12; for(unsigned i=0; i<3; ++i) { - vder[i]=der[i]; myvals.addDerivative( 1, basen+i, vder[i] ); + vder[i]=der[i]; + myvals.addDerivative( 1, basen+i, vder[i] ); } myatoms.setValue( 2, der[dir] ); addAtomDerivatives( 1, 0, -vder, myatoms ); myatoms.addBoxDerivatives( 1, Tensor(vder,distance) ); } - myatoms.setValue( 0, 1.0 ); return newval; + myatoms.setValue( 0, 1.0 ); + return newval; } // This does the stuff for averaging @@ -335,7 +431,9 @@ double DistanceFromContour::compute( const unsigned& tindex, AtomValuePack& myat } void DistanceFromContour::apply() { - if( getPntrToComponent("qdist")->applyForce( forces ) ) setForcesOnAtoms( forces ); + if( getPntrToComponent("qdist")->applyForce( forces ) ) { + setForcesOnAtoms( forces ); + } } } diff --git a/src/multicolvar/Distances.cpp b/src/multicolvar/Distances.cpp index 624f49a66e..3465ea9539 100644 --- a/src/multicolvar/Distances.cpp +++ b/src/multicolvar/Distances.cpp @@ -129,16 +129,26 @@ class Distances : public MultiColvarBase { // active methods: double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; /// Returns the number of coordinates of the field - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(Distances,"DISTANCES") void Distances::registerKeywords( Keywords& keys ) { MultiColvarBase::registerKeywords( keys ); - keys.use("ALT_MIN"); keys.use("LOWEST"); keys.use("HIGHEST"); - keys.use("MEAN"); keys.use("MIN"); keys.use("MAX"); keys.use("LESS_THAN"); // keys.use("DHENERGY"); - keys.use("MORE_THAN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); + keys.use("ALT_MIN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("MEAN"); + keys.use("MIN"); + keys.use("MAX"); + keys.use("LESS_THAN"); // keys.use("DHENERGY"); + keys.use("MORE_THAN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); keys.add("numbered","ATOMS","the atoms involved in each of the distances you wish to calculate. " "Keywords like ATOMS1, ATOMS2, ATOMS3,... should be listed and one distance will be " "calculated for each ATOM keyword you specify (all ATOM keywords should " @@ -154,25 +164,31 @@ void Distances::registerKeywords( Keywords& keys ) { Distances::Distances(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { // Read in the atoms std::vector all_atoms; readTwoGroups( "GROUP", "GROUPA", "GROUPB", all_atoms ); - if( atom_lab.size()==0 ) readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + if( atom_lab.size()==0 ) { + readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + } setupMultiColvarBase( all_atoms ); // And check everything has been read in correctly checkRead(); // Now check if we can use link cells if( getNumberOfVessels()>0 ) { - bool use_link=false; double rcut; + bool use_link=false; + double rcut; vesselbase::LessThan* lt=dynamic_cast( getPntrToVessel(0) ); if( lt ) { - use_link=true; rcut=lt->getCutoff(); + use_link=true; + rcut=lt->getCutoff(); } else { vesselbase::Between* bt=dynamic_cast( getPntrToVessel(0) ); - if( bt ) { use_link=true; rcut=bt->getCutoff(); } + if( bt ) { + use_link=true; + rcut=bt->getCutoff(); + } } if( use_link ) { for(unsigned i=1; i( getPntrToVessel(i) ); if( lt2 ) { double tcut=lt2->getCutoff(); - if( tcut>rcut ) rcut=tcut; + if( tcut>rcut ) { + rcut=tcut; + } } else if( bt ) { double tcut=bt->getCutoff(); - if( tcut>rcut ) rcut=tcut; + if( tcut>rcut ) { + rcut=tcut; + } } else { use_link=false; } } } - if( use_link ) setLinkCellCutoff( rcut ); + if( use_link ) { + setLinkCellCutoff( rcut ); + } } } diff --git a/src/multicolvar/DumpMultiColvar.cpp b/src/multicolvar/DumpMultiColvar.cpp index d84e34a507..567ed0ece0 100644 --- a/src/multicolvar/DumpMultiColvar.cpp +++ b/src/multicolvar/DumpMultiColvar.cpp @@ -34,8 +34,7 @@ #include "vesselbase/ActionWithInputVessel.h" #include "vesselbase/StoreDataVessel.h" -namespace PLMD -{ +namespace PLMD { namespace multicolvar { //+PLUMEDOC PRINTANALYSIS DUMPMULTICOLVAR @@ -64,8 +63,7 @@ DUMPMULTICOLVAR DATA=slt FILE=MULTICOLVAR.xyz class DumpMultiColvar: public ActionPilot, public ActionAtomistic, - public vesselbase::ActionWithInputVessel -{ + public vesselbase::ActionWithInputVessel { OFile of; double lenunit; MultiColvarBase* mycolv; @@ -75,7 +73,9 @@ class DumpMultiColvar: ~DumpMultiColvar(); static void registerKeywords( Keywords& keys ); void calculate() override {} - void calculateNumericalDerivatives( ActionWithValue* vv ) override { plumed_error(); } + void calculateNumericalDerivatives( ActionWithValue* vv ) override { + plumed_error(); + } void apply() override {} void update() override; }; @@ -98,30 +98,42 @@ DumpMultiColvar::DumpMultiColvar(const ActionOptions&ao): Action(ao), ActionPilot(ao), ActionAtomistic(ao), - ActionWithInputVessel(ao) -{ + ActionWithInputVessel(ao) { readArgument("store"); mycolv = dynamic_cast( getDependencies()[0] ); plumed_assert( getDependencies().size()==1 ); - if(!mycolv) error("action labeled " + getDependencies()[0]->getLabel() + " is not a multicolvar"); + if(!mycolv) { + error("action labeled " + getDependencies()[0]->getLabel() + " is not a multicolvar"); + } log.printf(" printing colvars calculated by action %s \n",mycolv->getLabel().c_str() ); std::vector atom; parseAtomList("ORIGIN",atom); - if( atom.size()>1 ) error("should only be one atom specified"); - if( atom.size()==1 ) log.printf(" origin is at position of atom : %d\n",atom[0].serial() ); + if( atom.size()>1 ) { + error("should only be one atom specified"); + } + if( atom.size()==1 ) { + log.printf(" origin is at position of atom : %d\n",atom[0].serial() ); + } - std::string file; parse("FILE",file); - if(file.length()==0) error("name out output file was not specified"); + std::string file; + parse("FILE",file); + if(file.length()==0) { + error("name out output file was not specified"); + } std::string type=Tools::extension(file); log<<" file name "<0) { - int p; Tools::convert(precision,p); + int p; + Tools::convert(precision,p); log<<" with precision "<getCentralAtomPos( mycolv->getPositionInFullTaskList(i) ); - if( getNumberOfAtoms()>0 ) apos=pbcDistance( getPosition(0), apos ); + if( getNumberOfAtoms()>0 ) { + apos=pbcDistance( getPosition(0), apos ); + } of.printf(("%s "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz).c_str(),name,lenunit*apos[0],lenunit*apos[1],lenunit*apos[2]); stash->retrieveSequentialValue( i, true, cvals ); if( mycolv->weightWithDerivatives() ) { - for(unsigned j=0; jisPeriodic() ) { - std::string min, max; getPntrToMultiColvar()->retrieveDomain( min, max ); - double mlow, mhigh; Tools::convert( min,mlow ); Tools::convert( max, mhigh); + std::string min, max; + getPntrToMultiColvar()->retrieveDomain( min, max ); + double mlow, mhigh; + Tools::convert( min,mlow ); + Tools::convert( max, mhigh); hb.isPeriodic( mlow, mhigh ); } else { hb.isNotPeriodic(); @@ -172,13 +175,21 @@ FilterBetween::FilterBetween(const ActionOptions& ao): if(sw.length()>0) { hb.set(sw,errors); - if( errors.length()!=0 ) error("problem reading BEAD keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading BEAD keyword : " + errors ); + } } else { - double l, u, s; std::string ll, uu, ss; - parse("LOWER",l); parse("UPPER",u); parse("SMEAR",s); - Tools::convert(l,ll); Tools::convert(u,uu); Tools::convert(s,ss); + double l, u, s; + std::string ll, uu, ss; + parse("LOWER",l); + parse("UPPER",u); + parse("SMEAR",s); + Tools::convert(l,ll); + Tools::convert(u,uu); + Tools::convert(s,ss); sw="GAUSSIAN LOWER=" + ll + " UPPER=" + uu + " SMEAR=" + ss; - hb.set(sw,errors); plumed_massert(errors.length()==0,"problems with bead" + errors); + hb.set(sw,errors); + plumed_massert(errors.length()==0,"problems with bead" + errors); } log.printf(" filtering colvar values and focussing only on those values in range %s\n",( hb.description() ).c_str() ); diff --git a/src/multicolvar/FilterLessThan.cpp b/src/multicolvar/FilterLessThan.cpp index c2d9385d6c..949e13671c 100644 --- a/src/multicolvar/FilterLessThan.cpp +++ b/src/multicolvar/FilterLessThan.cpp @@ -134,18 +134,25 @@ void FilterLess::registerKeywords( Keywords& keys ) { FilterLess::FilterLess(const ActionOptions& ao): Action(ao), - MultiColvarFilter(ao) -{ + MultiColvarFilter(ao) { // Read in the switching function - std::string sw, errors; parse("SWITCH",sw); + std::string sw, errors; + parse("SWITCH",sw); if(sw.length()>0) { sf.set(sw,errors); - if( errors.length()!=0 ) error("problem reading SWITCH keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading SWITCH keyword : " + 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"); + } sf.set(nn,mm,r_0,d_0); } log.printf(" filtering colvar values and focussing only on those less than %s\n",( sf.description() ).c_str() ); @@ -154,7 +161,8 @@ FilterLess::FilterLess(const ActionOptions& ao): } double FilterLess::applyFilter( const double& val, double& df ) const { - double f = sf.calculate( val, df ); df*=val; + double f = sf.calculate( val, df ); + df*=val; return f; } diff --git a/src/multicolvar/FilterMoreThan.cpp b/src/multicolvar/FilterMoreThan.cpp index a26a570780..28b7e0379b 100644 --- a/src/multicolvar/FilterMoreThan.cpp +++ b/src/multicolvar/FilterMoreThan.cpp @@ -151,18 +151,25 @@ void FilterMore::registerKeywords( Keywords& keys ) { FilterMore::FilterMore(const ActionOptions& ao): Action(ao), - MultiColvarFilter(ao) -{ + MultiColvarFilter(ao) { // Read in the switching function - std::string sw, errors; parse("SWITCH",sw); + std::string sw, errors; + parse("SWITCH",sw); if(sw.length()>0) { sf.set(sw,errors); - if( errors.length()!=0 ) error("problem reading SWITCH keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading SWITCH keyword : " + 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"); + } sf.set(nn,mm,r_0,d_0); } log.printf(" filtering colvar values and focussing only on those more than %s\n",( sf.description() ).c_str() ); @@ -171,7 +178,8 @@ FilterMore::FilterMore(const ActionOptions& ao): } double FilterMore::applyFilter( const double& val, double& df ) const { - double f = 1.0 - sf.calculate( val, df ); df*=-val; + double f = 1.0 - sf.calculate( val, df ); + df*=-val; return f; } diff --git a/src/multicolvar/InPlaneDistances.cpp b/src/multicolvar/InPlaneDistances.cpp index 289a4ca01b..db4a395a5d 100644 --- a/src/multicolvar/InPlaneDistances.cpp +++ b/src/multicolvar/InPlaneDistances.cpp @@ -66,16 +66,26 @@ class InPlaneDistances : public MultiColvarBase { explicit InPlaneDistances(const ActionOptions&); // active methods: double compute(const unsigned& tindex, AtomValuePack& myatoms ) const override; - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(InPlaneDistances,"INPLANEDISTANCES") void InPlaneDistances::registerKeywords( Keywords& keys ) { MultiColvarBase::registerKeywords( keys ); - keys.use("ALT_MIN"); keys.use("LOWEST"); keys.use("HIGHEST"); - keys.use("MEAN"); keys.use("MIN"); keys.use("MAX"); keys.use("LESS_THAN"); - keys.use("MORE_THAN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); + keys.use("ALT_MIN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("MEAN"); + keys.use("MIN"); + keys.use("MAX"); + keys.use("LESS_THAN"); + keys.use("MORE_THAN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); keys.add("atoms","VECTORSTART","The first atom position that is used to define the normal to the plane of interest"); keys.add("atoms","VECTOREND","The second atom position that is used to define the normal to the plane of interest"); keys.add("atoms-2","GROUP","The set of atoms for which you wish to calculate the in plane distance "); @@ -83,30 +93,35 @@ void InPlaneDistances::registerKeywords( Keywords& keys ) { InPlaneDistances::InPlaneDistances(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { // Read in the atoms std::vector all_atoms; readThreeGroups("GROUP","VECTORSTART","VECTOREND",false,false,all_atoms); setupMultiColvarBase( all_atoms ); // Setup the multicolvar base - setupMultiColvarBase( all_atoms ); readVesselKeywords(); + setupMultiColvarBase( all_atoms ); + readVesselKeywords(); // Check atoms are OK - if( getFullNumberOfTasks()!=getNumberOfAtoms()-2 ) error("you should specify one atom for VECTORSTART and one atom for VECTOREND only"); + if( getFullNumberOfTasks()!=getNumberOfAtoms()-2 ) { + error("you should specify one atom for VECTORSTART and one atom for VECTOREND only"); + } // And check everything has been read in correctly checkRead(); // Now check if we can use link cells if( getNumberOfVessels()>0 ) { - bool use_link=false; double rcut; + bool use_link=false; + double rcut; vesselbase::LessThan* lt=dynamic_cast( getPntrToVessel(0) ); if( lt ) { - use_link=true; rcut=lt->getCutoff(); + use_link=true; + rcut=lt->getCutoff(); } else { vesselbase::Between* bt=dynamic_cast( getPntrToVessel(0) ); if( bt ) { - use_link=true; rcut=bt->getCutoff(); + use_link=true; + rcut=bt->getCutoff(); } } if( use_link ) { @@ -115,23 +130,31 @@ InPlaneDistances::InPlaneDistances(const ActionOptions&ao): vesselbase::Between* bt=dynamic_cast( getPntrToVessel(i) ); if( lt2 ) { double tcut=lt2->getCutoff(); - if( tcut>rcut ) rcut=tcut; + if( tcut>rcut ) { + rcut=tcut; + } } else if( bt ) { double tcut=bt->getCutoff(); - if( tcut>rcut ) rcut=tcut; + if( tcut>rcut ) { + rcut=tcut; + } } else { use_link=false; } } } - if( use_link ) setLinkCellCutoff( rcut ); + if( use_link ) { + setLinkCellCutoff( rcut ); + } } } double InPlaneDistances::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { Vector normal=getSeparation( myatoms.getPosition(1), myatoms.getPosition(2) ); Vector dir=getSeparation( myatoms.getPosition(1), myatoms.getPosition(0) ); - PLMD::Angle a; Vector ddij, ddik; double angle=a.compute(normal,dir,ddij,ddik); + PLMD::Angle a; + Vector ddij, ddik; + double angle=a.compute(normal,dir,ddij,ddik); double sangle=std::sin(angle), cangle=std::cos(angle); double dd=dir.modulo(), invdd=1.0/dd, val=dd*sangle; diff --git a/src/multicolvar/LocalAverage.cpp b/src/multicolvar/LocalAverage.cpp index 11a9eb3344..1d76d80029 100644 --- a/src/multicolvar/LocalAverage.cpp +++ b/src/multicolvar/LocalAverage.cpp @@ -97,7 +97,9 @@ class LocalAverage : public MultiColvarBase { /// We overwrite this in order to have dumpmulticolvar working for local average void normalizeVector( std::vector& vals ) const override {} /// Is the variable periodic - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(LocalAverage,"LOCAL_AVERAGE") @@ -112,34 +114,53 @@ void LocalAverage::registerKeywords( Keywords& keys ) { "The following provides information on the \\ref switchingfunction that are available. " "When this keyword is present you no longer need the NN, MM, D_0 and R_0 keywords."); // Use actionWithDistributionKeywords - keys.use("SPECIES"); keys.use("SPECIESA"); keys.use("SPECIESB"); - keys.remove("LOWMEM"); keys.use("MEAN"); keys.use("MORE_THAN"); keys.use("LESS_THAN"); - keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); + keys.use("SPECIES"); + keys.use("SPECIESA"); + keys.use("SPECIESB"); + keys.remove("LOWMEM"); + keys.use("MEAN"); + keys.use("MORE_THAN"); + keys.use("LESS_THAN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); keys.addFlag("LOWMEM",false,"lower the memory requirements"); - if( keys.reserved("VMEAN") ) keys.use("VMEAN"); - if( keys.reserved("VSUM") ) keys.use("VSUM"); + if( keys.reserved("VMEAN") ) { + keys.use("VMEAN"); + } + if( keys.reserved("VSUM") ) { + keys.use("VSUM"); + } } LocalAverage::LocalAverage(const ActionOptions& ao): Action(ao), - MultiColvarBase(ao) -{ - if( getNumberOfBaseMultiColvars()>1 ) error("local average with more than one base colvar makes no sense"); + MultiColvarBase(ao) { + if( getNumberOfBaseMultiColvars()>1 ) { + error("local average with more than one base colvar makes no sense"); + } // Read in the switching function - std::string sw, errors; parse("SWITCH",sw); + std::string sw, errors; + parse("SWITCH",sw); if(sw.length()>0) { switchingFunction.set(sw,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); } log.printf(" averaging over central molecule and those within %s\n",( switchingFunction.description() ).c_str() ); rcut2 = switchingFunction.get_dmax()*switchingFunction.get_dmax(); setLinkCellCutoff( switchingFunction.get_dmax() ); - std::vector all_atoms; setupMultiColvarBase( all_atoms ); + std::vector all_atoms; + setupMultiColvarBase( all_atoms ); } unsigned LocalAverage::getNumberOfQuantities() const { @@ -147,13 +168,16 @@ unsigned LocalAverage::getNumberOfQuantities() const { } double LocalAverage::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { - double sw, dfunc; MultiValue& myvals = myatoms.getUnderlyingMultiValue(); + double sw, dfunc; + MultiValue& myvals = myatoms.getUnderlyingMultiValue(); std::vector values( getBaseMultiColvar(0)->getNumberOfQuantities() ); getInputData( 0, false, myatoms, values ); myvals.addTemporyValue( values[0] ); if( values.size()>2 ) { - for(unsigned j=2; j0 ); + unsigned katom = myatoms.getIndex( 0 ); + plumed_dbg_assert( katom0 ); // Find base colvar - unsigned mmc=atom_lab[katom].first - 1; plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); + unsigned mmc=atom_lab[katom].first - 1; + plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); // Get start of indices for this atom - unsigned basen=0; for(unsigned i=0; igetNumberOfDerivatives() - 9; + unsigned basen=0; + for(unsigned i=0; igetNumberOfDerivatives() - 9; + } plumed_dbg_assert( basen%3==0 ); // Check the number of atoms is consistent with input derivatives unsigned virbas = myvals.getNumberOfDerivatives()-9; @@ -226,7 +256,9 @@ double LocalAverage::compute( const unsigned& tindex, AtomValuePack& myatoms ) c getInputData( i, false, myatoms, values ); if( values.size()>2 ) { - for(unsigned j=2; j0 ); + unsigned katom = myatoms.getIndex( i ); + plumed_dbg_assert( katom0 ); // Find base colvar - unsigned mmc=atom_lab[katom].first - 1; plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); + unsigned mmc=atom_lab[katom].first - 1; + plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); // Get start of indices for this atom - unsigned basen=0; for(unsigned j=0; jgetNumberOfDerivatives() - 9; + unsigned basen=0; + for(unsigned j=0; jgetNumberOfDerivatives() - 9; + } plumed_dbg_assert( basen%3==0 ); // Check the number of atoms is consistent with input derivatives unsigned virbas = myvals.getNumberOfDerivatives()-9; @@ -312,7 +350,9 @@ double LocalAverage::compute( const unsigned& tindex, AtomValuePack& myatoms ) c // Calculate length of vector norm+=myvals.get(i)*myvals.get(i); } - norm=sqrt(norm); myatoms.setValue(1, norm); double inorm = 1.0 / norm; + norm=sqrt(norm); + myatoms.setValue(1, norm); + double inorm = 1.0 / norm; for(unsigned j=0; j& all_atoms ) { plumed_assert( !usespecies ); - if( all_atoms.size()>0 ) return; + if( all_atoms.size()>0 ) { + return; + } std::vector t; for(int i=1;; ++i ) { parseAtomList(key, i, t ); - if( t.empty() ) break; + if( t.empty() ) { + break; + } log.printf(" Colvar %d is calculated from atoms : ", i); - for(unsigned j=0; j( 0, ablocks.size()*(i-1)+j ) ); } t.resize(0); } if( all_atoms.size()>0 ) { nblock=0; - for(unsigned i=0; i& t) { std::vector mlabs; - if( num<0 ) parseVector(key,mlabs); - else parseNumberedVector(key,num,mlabs); + if( num<0 ) { + parseVector(key,mlabs); + } else { + parseNumberedVector(key,num,mlabs); + } - if( mlabs.size()==0 ) return false; + if( mlabs.size()==0 ) { + return false; + } - std::string mname; unsigned found_mcolv=mlabs.size(); + std::string mname; + unsigned found_mcolv=mlabs.size(); for(unsigned i=0; i(mlabs[i]); - if(!mycolv) { found_mcolv=i; break; } + if(!mycolv) { + found_mcolv=i; + break; + } // Check all base multicolvars are of same type if( i==0 ) { mname = mycolv->getName(); - if( keywords.exists("ALL_INPUT_SAME_TYPE") && mycolv->isPeriodic() ) error("multicolvar functions don't work with this multicolvar"); + if( keywords.exists("ALL_INPUT_SAME_TYPE") && mycolv->isPeriodic() ) { + error("multicolvar functions don't work with this multicolvar"); + } } else { - if( keywords.exists("ALL_INPUT_SAME_TYPE") && mname!=mycolv->getName() ) error("All input multicolvars must be of same type"); + if( keywords.exists("ALL_INPUT_SAME_TYPE") && mname!=mycolv->getName() ) { + error("All input multicolvars must be of same type"); + } } // And track which variable stores each colvar - for(unsigned j=0; jgetFullNumberOfTasks(); ++j) atom_lab.push_back( std::pair( mybasemulticolvars.size()+1, j ) ); + for(unsigned j=0; jgetFullNumberOfTasks(); ++j) { + atom_lab.push_back( std::pair( mybasemulticolvars.size()+1, j ) ); + } // And store the multicolvar base mybasemulticolvars.push_back( mycolv ); // And create a basedata stash mybasedata.push_back( mybasemulticolvars[mybasemulticolvars.size()-1]->buildDataStashes( this ) ); // Check if weight has derivatives - if( mybasemulticolvars[ mybasemulticolvars.size()-1 ]->weightHasDerivatives ) weightHasDerivatives=true; + if( mybasemulticolvars[ mybasemulticolvars.size()-1 ]->weightHasDerivatives ) { + weightHasDerivatives=true; + } plumed_assert( mybasemulticolvars.size()==mybasedata.size() ); } // Have we conventional atoms to read in if( found_mcolv==0 ) { - std::vector tt; ActionAtomistic::interpretAtomList( mlabs, tt ); - for(unsigned i=0; i( 0, t.size() + i ) ); } + std::vector tt; + ActionAtomistic::interpretAtomList( mlabs, tt ); + for(unsigned i=0; i( 0, t.size() + i ) ); + } log.printf(" keyword %s takes atoms : ", key.c_str() ); - for(unsigned i=0; i& all_atoms ) { - plumed_dbg_assert( keywords.exists(key0) && keywords.exists(key1) && keywords.exists(key2) ); ablocks.resize( 2 ); + plumed_dbg_assert( keywords.exists(key0) && keywords.exists(key1) && keywords.exists(key2) ); + ablocks.resize( 2 ); if( parseMultiColvarAtomList(key0,-1,all_atoms) ) { - nblock=atom_lab.size(); for(unsigned i=0; i<2; ++i) ablocks[i].resize(nblock); + nblock=atom_lab.size(); + for(unsigned i=0; i<2; ++i) { + ablocks[i].resize(nblock); + } resizeBookeepingArray( nblock, nblock ); - for(unsigned i=0; iablocks[1].size() ) nblock = ablocks[0].size(); - else nblock=ablocks[1].size(); + if( ablocks[0].size()>ablocks[1].size() ) { + nblock = ablocks[0].size(); + } else { + nblock=ablocks[1].size(); + } resizeBookeepingArray( ablocks[0].size(), ablocks[1].size() ); for(unsigned i=0; i0 && atom_lab[ablocks[1][j]].first>0 ) { if( mybasemulticolvars[atom_lab[ablocks[0][i]].first-1]->getLabel()!=mybasemulticolvars[atom_lab[ablocks[1][j]].first-1]->getLabel() && - atom_lab[ablocks[0][i]].second!=atom_lab[ablocks[1][j]].second ) addTaskToList( i*nblock + j ); - } else if( all_atoms[atom_lab[ablocks[0][i]].second]!=all_atoms[atom_lab[ablocks[1][j]].second] ) addTaskToList( i*nblock + j ); + atom_lab[ablocks[0][i]].second!=atom_lab[ablocks[1][j]].second ) { + addTaskToList( i*nblock + j ); + } + } else if( all_atoms[atom_lab[ablocks[0][i]].second]!=all_atoms[atom_lab[ablocks[1][j]].second] ) { + addTaskToList( i*nblock + j ); + } bookeeping(i,j).second=getFullNumberOfTasks(); } } @@ -210,16 +271,24 @@ void MultiColvarBase::readTwoGroups( const std::string& key0, const std::string& void MultiColvarBase::readGroupKeywords( const std::string& key0, const std::string& key1, const std::string& key2, const std::string& key3, const bool& no_third_dim_accum, const bool& symmetric, std::vector& all_atoms ) { - plumed_dbg_assert( keywords.exists(key0) && keywords.exists(key1) && keywords.exists(key2) && keywords.exists(key3) ); ablocks.resize( 3 ); + plumed_dbg_assert( keywords.exists(key0) && keywords.exists(key1) && keywords.exists(key2) && keywords.exists(key3) ); + ablocks.resize( 3 ); if( parseMultiColvarAtomList(key0,-1,all_atoms) ) { if( no_third_dim_accum ) { - nblock=atom_lab.size(); ablocks[0].resize(nblock); ablocks[1].resize( nblock ); - for(unsigned i=0; i& all_atoms ) { - plumed_dbg_assert( keywords.exists(key1) && keywords.exists(key2) && keywords.exists(key3) ); ablocks.resize( 3 ); + plumed_dbg_assert( keywords.exists(key1) && keywords.exists(key2) && keywords.exists(key3) ); + ablocks.resize( 3 ); bool readkey1=parseMultiColvarAtomList(key1,-1,all_atoms); - ablocks[0].resize( atom_lab.size() ); for(unsigned i=0; iablocks[0].size() ) nblock=ablocks[1].size(); - else nblock=ablocks[0].size(); + if( ablocks[1].size()>ablocks[0].size() ) { + nblock=ablocks[1].size(); + } else { + nblock=ablocks[0].size(); + } ablocks[2].resize( ablocks[1].size() ); - for(unsigned i=0; igetLabel()!=mybasemulticolvars[atom_lab[ablocks[2][k]].first-1]->getLabel() && mybasemulticolvars[atom_lab[ablocks[1][j]].first-1]->getLabel()!=mybasemulticolvars[atom_lab[ablocks[2][k]].first-1]->getLabel() && atom_lab[ablocks[0][i]].second!=atom_lab[ablocks[1][j]].second && atom_lab[ablocks[0][i]].second!=atom_lab[ablocks[2][k]].second && - atom_lab[ablocks[1][j]].second!=atom_lab[ablocks[2][k]].second ) addTaskToList( nblock*nblock*i + nblock*j + k ); + atom_lab[ablocks[1][j]].second!=atom_lab[ablocks[2][k]].second ) { + addTaskToList( nblock*nblock*i + nblock*j + k ); + } } else if( all_atoms[atom_lab[ablocks[0][i]].second]!=all_atoms[atom_lab[ablocks[1][j]].second] && all_atoms[atom_lab[ablocks[0][i]].second]!=all_atoms[atom_lab[ablocks[2][k]].second] && - all_atoms[atom_lab[ablocks[1][j]].second]!=all_atoms[atom_lab[ablocks[2][k]].second] ) addTaskToList( nblock*nblock*i + nblock*j + k ); + all_atoms[atom_lab[ablocks[1][j]].second]!=all_atoms[atom_lab[ablocks[2][k]].second] ) { + addTaskToList( nblock*nblock*i + nblock*j + k ); + } } bookeeping(i,j).second=getFullNumberOfTasks(); } } } else { ablocks[2].resize( atom_lab.size() - ablocks[1].size() - ablocks[0].size() ); - for(unsigned i=0; iablocks[0].size() ) nblock=ablocks[1].size(); - else nblock=ablocks[0].size(); - if( ablocks[2].size()>nblock ) nblock=ablocks[2].size(); + if( ablocks[1].size()>ablocks[0].size() ) { + nblock=ablocks[1].size(); + } else { + nblock=ablocks[0].size(); + } + if( ablocks[2].size()>nblock ) { + nblock=ablocks[2].size(); + } - unsigned kcount; if( no_third_dim_accum ) kcount=1; else kcount=ablocks[2].size(); + unsigned kcount; + if( no_third_dim_accum ) { + kcount=1; + } else { + kcount=ablocks[2].size(); + } for(unsigned i=0; i0 && atom_lab[ablocks[1][j]].first>0 && atom_lab[ablocks[2][k]].first>0 ) { + if( no_third_dim_accum ) { + addTaskToList( nblock*i + j ); + } else if( atom_lab[ablocks[0][i]].first>0 && atom_lab[ablocks[1][j]].first>0 && atom_lab[ablocks[2][k]].first>0 ) { if( mybasemulticolvars[atom_lab[ablocks[0][i]].first-1]->getLabel()!=mybasemulticolvars[atom_lab[ablocks[1][j]].first-1]->getLabel() && mybasemulticolvars[atom_lab[ablocks[0][i]].first-1]->getLabel()!=mybasemulticolvars[atom_lab[ablocks[2][k]].first-1]->getLabel() && mybasemulticolvars[atom_lab[ablocks[1][j]].first-1]->getLabel()!=mybasemulticolvars[atom_lab[ablocks[2][k]].first-1]->getLabel() && atom_lab[ablocks[0][i]].second!=atom_lab[ablocks[1][j]].second && atom_lab[ablocks[0][i]].second!=atom_lab[ablocks[2][k]].second && - atom_lab[ablocks[1][j]].second!=atom_lab[ablocks[2][k]].second ) addTaskToList( nblock*nblock*i + nblock*j + k ); + atom_lab[ablocks[1][j]].second!=atom_lab[ablocks[2][k]].second ) { + addTaskToList( nblock*nblock*i + nblock*j + k ); + } } else if( all_atoms[atom_lab[ablocks[0][i]].second]!=all_atoms[atom_lab[ablocks[1][j]].second] && all_atoms[atom_lab[ablocks[0][i]].second]!=all_atoms[atom_lab[ablocks[2][k]].second] && - all_atoms[atom_lab[ablocks[1][j]].second]!=all_atoms[atom_lab[ablocks[2][k]].second] ) addTaskToList( nblock*nblock*i + nblock*j + k ); + all_atoms[atom_lab[ablocks[1][j]].second]!=all_atoms[atom_lab[ablocks[2][k]].second] ) { + addTaskToList( nblock*nblock*i + nblock*j + k ); + } } bookeeping(i,j).second=getFullNumberOfTasks(); } @@ -341,8 +464,12 @@ void MultiColvarBase::readThreeGroups( const std::string& key1, const std::strin void MultiColvarBase::buildSets() { std::vector fake_atoms; - if( !parseMultiColvarAtomList("DATA",-1,fake_atoms) ) error("missing DATA keyword"); - if( fake_atoms.size()>0 ) error("no atoms should appear in the specification for this object. Input should be other multicolvars"); + if( !parseMultiColvarAtomList("DATA",-1,fake_atoms) ) { + error("missing DATA keyword"); + } + if( fake_atoms.size()>0 ) { + error("no atoms should appear in the specification for this object. Input should be other multicolvars"); + } nblock = mybasemulticolvars[0]->getFullNumberOfTasks(); for(unsigned i=0; iresizeTemporyMultiValues( mybasemulticolvars.size() ); setupMultiColvarBase( fake_atoms ); + mybasedata[0]->resizeTemporyMultiValues( mybasemulticolvars.size() ); + setupMultiColvarBase( fake_atoms ); } void MultiColvarBase::addTaskToList( const unsigned& taskCode ) { @@ -375,17 +509,23 @@ void MultiColvarBase::addTaskToList( const unsigned& taskCode ) { void MultiColvarBase::resizeBookeepingArray( const unsigned& num1, const unsigned& num2 ) { bookeeping.resize( num1, num2 ); for(unsigned i=0; i& atoms ) { - if( !matsums && atom_lab.size()==0 ) error("No atoms have been read in"); + if( !matsums && atom_lab.size()==0 ) { + error("No atoms have been read in"); + } std::vector all_atoms; // Setup decoder array if( !usespecies && nblock>0 ) { - ncentral=ablocks.size(); use_for_central_atom.resize( ablocks.size(), true ); + ncentral=ablocks.size(); + use_for_central_atom.resize( ablocks.size(), true ); numberForCentralAtom = 1.0 / static_cast( ablocks.size() ); if( ablocks.size()==3 ) { allthirdblockintasks=uselinkforthree=true; @@ -406,55 +546,97 @@ void MultiColvarBase::setupMultiColvarBase( const std::vector& atoms } if( allthirdblockintasks ) { - decoder.resize(2); plumed_assert( ablocks.size()==3 ); + decoder.resize(2); + plumed_assert( ablocks.size()==3 ); // Check if number of atoms is too large - if( std::pow( double(nblock), 2.0 )>std::numeric_limits::max() ) error("number of atoms in groups is too big for PLUMED to handle"); + if( std::pow( double(nblock), 2.0 )>std::numeric_limits::max() ) { + error("number of atoms in groups is too big for PLUMED to handle"); + } } else { decoder.resize( ablocks.size() ); // Check if number of atoms is too large - if( std::pow( double(nblock), double(ablocks.size()) )>std::numeric_limits::max() ) error("number of atoms in groups is too big for PLUMED to handle"); + if( std::pow( double(nblock), double(ablocks.size()) )>std::numeric_limits::max() ) { + error("number of atoms in groups is too big for PLUMED to handle"); + } + } + unsigned code=1; + for(unsigned i=0; i( ablocks.size() ); } else if( keywords.exists("SPECIESA") ) { plumed_assert( atom_lab.size()==0 && all_atoms.size()==0 ); - ablocks.resize( 1 ); bool readspecies=parseMultiColvarAtomList("SPECIES", -1, all_atoms); + ablocks.resize( 1 ); + bool readspecies=parseMultiColvarAtomList("SPECIES", -1, all_atoms); if( readspecies ) { - ablocks[0].resize( atom_lab.size() ); for(unsigned i=0; i0 && atom_lab[j].first>0 ) { if( atom_lab[nat1+i].first==atom_lab[j].first && mybasemulticolvars[atom_lab[nat1+i].first-1]->getAbsoluteIndexOfCentralAtom(atom_lab[nat1+i].second)== - mybasemulticolvars[atom_lab[j].first-1]->getAbsoluteIndexOfCentralAtom(atom_lab[j].second) ) { found=true; inum=j; break; } + mybasemulticolvars[atom_lab[j].first-1]->getAbsoluteIndexOfCentralAtom(atom_lab[j].second) ) { + found=true; + inum=j; + break; + } } else if( atom_lab[nat1+i].first>0 ) { if( mybasemulticolvars[atom_lab[nat1+i].first-1]->getAbsoluteIndexOfCentralAtom(atom_lab[nat1+i].second)== - all_atoms[atom_lab[j].second] ) { found=true; inum=nat1 + i; break; } + all_atoms[atom_lab[j].second] ) { + found=true; + inum=nat1 + i; + break; + } } else if( atom_lab[j].first>0 ) { if( all_atoms[atom_lab[nat1+i].second]== - mybasemulticolvars[atom_lab[j].first-1]->getAbsoluteIndexOfCentralAtom(atom_lab[j].second) ) { found=true; inum=nat1+i; break; } - } else if( all_atoms[atom_lab[nat1+i].second]==all_atoms[atom_lab[j].second] ) { found=true; inum=j; break; } + mybasemulticolvars[atom_lab[j].first-1]->getAbsoluteIndexOfCentralAtom(atom_lab[j].second) ) { + found=true; + inum=nat1+i; + break; + } + } else if( all_atoms[atom_lab[nat1+i].second]==all_atoms[atom_lab[j].second] ) { + found=true; + inum=j; + break; + } } // This prevents mistakes being made in colvar setup - if( found ) { ablocks[0][i]=inum; } - else { ablocks[0][i]=nat1 + i; } + if( found ) { + ablocks[0][i]=inum; + } else { + ablocks[0][i]=nat1 + i; + } } } } if( mybasemulticolvars.size()>0 ) { for(unsigned i=0; iresizeTemporyMultiValues(2); mybasemulticolvars[i]->my_tmp_capacks.resize(2); + mybasedata[i]->resizeTemporyMultiValues(2); + mybasemulticolvars[i]->my_tmp_capacks.resize(2); } } @@ -462,27 +644,37 @@ void MultiColvarBase::setupMultiColvarBase( const std::vector& atoms std::vector tmp_atoms; for(unsigned i=0; igetAbsoluteIndexes(); - for(unsigned j=0; j& catom_ind ) { - unsigned nat=0; plumed_assert( catom_ind.size()==ablocks.size() ); + unsigned nat=0; + plumed_assert( catom_ind.size()==ablocks.size() ); for(unsigned i=0; i0 ); ncentral=nat; + plumed_dbg_assert( nat>0 ); + ncentral=nat; numberForCentralAtom = 1.0 / static_cast( nat ); } @@ -494,14 +686,20 @@ void MultiColvarBase::turnOnDerivatives() { void MultiColvarBase::setLinkCellCutoff( const double& lcut, double tcut ) { plumed_assert( usespecies || ablocks.size()<4 ); - if( tcut<0 ) tcut=lcut; + if( tcut<0 ) { + tcut=lcut; + } if( !linkcells.enabled() ) { linkcells.setCutoff( lcut ); threecells.setCutoff( tcut ); } else { - if( lcut>linkcells.getCutoff() ) linkcells.setCutoff( lcut ); - if( tcut>threecells.getCutoff() ) threecells.setCutoff( tcut ); + if( lcut>linkcells.getCutoff() ) { + linkcells.setCutoff( lcut ); + } + if( tcut>threecells.getCutoff() ) { + threecells.setCutoff( tcut ); + } } } @@ -510,7 +708,9 @@ double MultiColvarBase::getLinkCellCutoff() const { } void MultiColvarBase::setupLinkCells() { - if( (!usespecies && nblock==0) || !linkcells.enabled() ) return ; + if( (!usespecies && nblock==0) || !linkcells.enabled() ) { + return ; + } // Retrieve any atoms that haven't already been retrieved for(std::vector::iterator p=mybasemulticolvars.begin(); p!=mybasemulticolvars.end(); ++p) { (*p)->retrieveAtoms(); @@ -529,7 +729,9 @@ void MultiColvarBase::setupLinkCells() { // Count number of currently active atoms nactive_atoms=0; for(unsigned i=0; i0 ) { @@ -539,14 +741,18 @@ void MultiColvarBase::setupLinkCells() { nactive_atoms=0; if( usespecies ) { for(unsigned i=0; i requiredlinkcells; @@ -568,27 +776,40 @@ void MultiColvarBase::setupNonUseSpeciesLinkCells( const unsigned& my_always_act // Get some parallel info unsigned stride=comm.Get_size(); unsigned rank=comm.Get_rank(); - if( serialCalculation() ) { stride=1; rank=0; } + if( serialCalculation() ) { + stride=1; + rank=0; + } // Ensure we only do tasks where atoms are in appropriate link cells std::vector linked_atoms( 1+ablocks[1].size() ); for(unsigned i=rank; i0 ) { // Get some parallel info unsigned stride=comm.Get_size(); unsigned rank=comm.Get_rank(); - if( serialCalculation() ) { stride=1; rank=0; } + if( serialCalculation() ) { + stride=1; + rank=0; + } unsigned nactive_three=0; for(unsigned i=0; i lttmp_pos( nactive_three ); @@ -597,14 +818,18 @@ void MultiColvarBase::setupNonUseSpeciesLinkCells( const unsigned& my_always_act nactive_three=0; if( allthirdblockintasks ) { for(unsigned i=0; i linked_atoms( 1+ablocks[1].size() ); std::vector tlinked_atoms( 1+ablocks[2].size() ); for(unsigned i=rank; i& atoms ) const { plumed_dbg_assert( !usespecies && nblock>0 ); - if( atoms.size()!=decoder.size() ) atoms.resize( decoder.size() ); + if( atoms.size()!=decoder.size() ) { + atoms.resize( decoder.size() ); + } unsigned scode = taskCode; for(unsigned i=0; i task_atoms(1); task_atoms[0]=taskCode; + std::vector task_atoms(1); + task_atoms[0]=taskCode; unsigned natomsper=myatoms.setupAtomsFromLinkCells( task_atoms, getPositionOfAtomForLinkCells( taskCode ), linkcells ); return natomsper>1; } else if( matsums ) { myatoms.setNumberOfAtoms( getNumberOfAtoms() ); - for(unsigned i=0; i atoms(2); decodeIndexToAtoms( taskCode, atoms ); + plumed_dbg_assert( ablocks.size()==3 ); + std::vector atoms(2); + decodeIndexToAtoms( taskCode, atoms ); myatoms.setupAtomsFromLinkCells( atoms, getPositionOfAtomForLinkCells( atoms[0] ), threecells ); } else if( nblock>0 ) { std::vector atoms( ablocks.size() ); - decodeIndexToAtoms( taskCode, atoms ); myatoms.setNumberOfAtoms( ablocks.size() ); - for(unsigned i=0; i& active_tasks, c justVolumes=true; for(unsigned i=0; i( getPntrToVessel(i) ); - if( mys ) continue; + if( mys ) { + continue; + } vesselbase::BridgeVessel* myb=dynamic_cast( getPntrToVessel(i) ); - if( !myb ) { justVolumes=false; break; } + if( !myb ) { + justVolumes=false; + break; + } ActionVolume* myv=dynamic_cast( myb->getOutputAction() ); - if( !myv ) { justVolumes=false; break; } + if( !myv ) { + justVolumes=false; + break; + } } } deactivateAllTasks(); if( justVolumes && mydata ) { - if( mydata->getNumberOfDataUsers()==0 ) justVolumes=false; + if( mydata->getNumberOfDataUsers()==0 ) { + justVolumes=false; + } for(unsigned i=0; igetNumberOfDataUsers(); ++i) { MultiColvarBase* myu=dynamic_cast( mydata->getDataUser(i) ); if( myu ) { myu->setupActiveTaskSet( taskFlags, getLabel() ); } else { - for(unsigned i=0; i( getPntrToVessel(j) ); - if( !myb ) continue ; + if( !myb ) { + continue ; + } ActionVolume* myv=dynamic_cast( myb->getOutputAction() ); - if( !myv ) continue ; - myv->retrieveAtoms(); myv->setupRegions(); + if( !myv ) { + continue ; + } + myv->retrieveAtoms(); + myv->setupRegions(); for(unsigned i=0; iinVolumeOfInterest(i) ) taskFlags[i]=1; + if( myv->inVolumeOfInterest(i) ) { + taskFlags[i]=1; + } } } } else { - for(unsigned i=0; i& active_tasks, c if( getLabel()!=input_label ) { int input_code=-1; for(unsigned i=0; igetLabel()==input_label ) { input_code=i+1; break; } + if( mybasemulticolvars[i]->getLabel()==input_label ) { + input_code=i+1; + break; + } } MultiValue my_tvals( getNumberOfQuantities(), getNumberOfDerivatives() ); AtomValuePack mytmp_atoms( my_tvals, this ); for(unsigned i=0; i( mybasemulticolvars[i] ); - if( myfilt || mybasemulticolvars[i]->filtersUsedAsInput() ) inputAreFilters=true; + if( myfilt || mybasemulticolvars[i]->filtersUsedAsInput() ) { + inputAreFilters=true; + } } return inputAreFilters; } @@ -758,7 +1037,9 @@ void MultiColvarBase::calculate() { setupActiveTaskSet( taskFlags, getLabel() ); // Check for filters and rerun setup of link cells if there are any - if( mybasemulticolvars.size()>0 && filtersUsedAsInput() ) setupLinkCells(); + if( mybasemulticolvars.size()>0 && filtersUsedAsInput() ) { + setupLinkCells(); + } // Setup the link cells if we are not using species if( !usespecies && ablocks.size()>1 ) { @@ -766,9 +1047,11 @@ void MultiColvarBase::calculate() { // of a peculiarity in linkcells unsigned first_active=std::numeric_limits::max(); for(unsigned i=0; i0 ) plumed_merror("cannot calculate numerical derivatives for this quantity"); + if( mybasemulticolvars.size()>0 ) { + plumed_merror("cannot calculate numerical derivatives for this quantity"); + } calculateAtomicNumericalDerivatives( this, 0 ); } void MultiColvarBase::prepare() { - setup_completed=false; atomsWereRetrieved=false; + setup_completed=false; + atomsWereRetrieved=false; } void MultiColvarBase::retrieveAtoms() { - if( !atomsWereRetrieved ) { ActionAtomistic::retrieveAtoms(); atomsWereRetrieved=true; } + if( !atomsWereRetrieved ) { + ActionAtomistic::retrieveAtoms(); + atomsWereRetrieved=true; + } } void MultiColvarBase::mergeInputDerivatives( const unsigned& ival, const unsigned& start, const unsigned& end, @@ -798,11 +1087,17 @@ void MultiColvarBase::mergeInputDerivatives( const unsigned& ival, const unsigne plumed_dbg_assert( start0 ); + unsigned katom = myatoms.getIndex( jatom ); + plumed_dbg_assert( katom0 ); // Find base colvar - unsigned mmc=atom_lab[katom].first - 1; plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); + unsigned mmc=atom_lab[katom].first - 1; + plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); // Get start of indices for this atom - unsigned basen=0; for(unsigned i=0; igetNumberOfDerivatives() - 9; + unsigned basen=0; + for(unsigned i=0; igetNumberOfDerivatives() - 9; + } plumed_dbg_assert( basen%3==0 ); // Check the number of atoms is consistent with input derivatives unsigned virbas = myvals.getNumberOfDerivatives()-9; for(unsigned j=0; j0 ); + unsigned katom = myatoms.getIndex( jatom ); + plumed_dbg_assert( katom0 ); // Find base colvar - unsigned mmc=atom_lab[katom].first - 1; plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); + unsigned mmc=atom_lab[katom].first - 1; + plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); // Get start of indices for this atom - unsigned basen=0; for(unsigned i=0; igetNumberOfDerivatives() - 9; + unsigned basen=0; + for(unsigned i=0; igetNumberOfDerivatives() - 9; + } plumed_dbg_assert( basen%3==0 ); // Check the number of atoms is consistent with input derivatives unsigned virbas = myvals.getNumberOfDerivatives()-9; for(unsigned j=0; jgetNumberOfDerivatives()-9 ) { - unsigned kder=basen+jder; plumed_assert( kder(myatoms.getUnderlyingMultiValue().getNumberOfValues()) && iatom0 ); + unsigned katom = myatoms.getIndex( iatom ); + plumed_dbg_assert( atom_lab[katom].first>0 ); // Find base colvar - unsigned mmc = atom_lab[katom].first - 1; plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); - if( usespecies && iatom==0 ) { myatoms.addComDerivatives( ival, der, mybasemulticolvars[mmc]->my_tmp_capacks[0] ); return; } + unsigned mmc = atom_lab[katom].first - 1; + plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); + if( usespecies && iatom==0 ) { + myatoms.addComDerivatives( ival, der, mybasemulticolvars[mmc]->my_tmp_capacks[0] ); + return; + } // Get start of indices for this atom - unsigned basen=0; for(unsigned i=0; igetNumberOfDerivatives() - 9) / 3; + unsigned basen=0; + for(unsigned i=0; igetNumberOfDerivatives() - 9) / 3; + } mybasemulticolvars[mmc]->getCentralAtomPack( basen, atom_lab[katom].second, mybasemulticolvars[mmc]->my_tmp_capacks[1] ); myatoms.addComDerivatives( ival, der, mybasemulticolvars[mmc]->my_tmp_capacks[1] ); } @@ -870,23 +1180,34 @@ void MultiColvarBase::getInputData( const unsigned& ind, const bool& normed, const multicolvar::AtomValuePack& myatoms, std::vector& orient ) const { // Converint input atom to local index - unsigned katom = myatoms.getIndex(ind); plumed_dbg_assert( atom_lab[katom].first>0 ); + unsigned katom = myatoms.getIndex(ind); + plumed_dbg_assert( atom_lab[katom].first>0 ); // Find base colvar - unsigned mmc = atom_lab[katom].first - 1; plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); + unsigned mmc = atom_lab[katom].first - 1; + plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); // Check if orient is the correct size - if( orient.size()!=mybasemulticolvars[mmc]->getNumberOfQuantities() ) orient.resize( mybasemulticolvars[mmc]->getNumberOfQuantities() ); + if( orient.size()!=mybasemulticolvars[mmc]->getNumberOfQuantities() ) { + orient.resize( mybasemulticolvars[mmc]->getNumberOfQuantities() ); + } // Retrieve the value mybasedata[mmc]->retrieveValueWithIndex( atom_lab[katom].second, normed, orient ); } MultiValue& MultiColvarBase::getInputDerivatives( const unsigned& iatom, const bool& normed, const multicolvar::AtomValuePack& myatoms ) const { // Converint input atom to local index - unsigned katom = myatoms.getIndex(iatom); plumed_dbg_assert( atom_lab[katom].first>0 ); + unsigned katom = myatoms.getIndex(iatom); + plumed_dbg_assert( atom_lab[katom].first>0 ); // Find base colvar - unsigned mmc = atom_lab[katom].first - 1; plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); - if( usespecies && !normed && iatom==0 ) return mybasedata[mmc]->getTemporyMultiValue(0); + unsigned mmc = atom_lab[katom].first - 1; + plumed_dbg_assert( mybasemulticolvars[mmc]->taskIsCurrentlyActive( atom_lab[katom].second ) ); + if( usespecies && !normed && iatom==0 ) { + return mybasedata[mmc]->getTemporyMultiValue(0); + } - unsigned oval=0; if( iatom>0 ) oval=1; + unsigned oval=0; + if( iatom>0 ) { + oval=1; + } MultiValue& myder=mybasedata[mmc]->getTemporyMultiValue(oval); if( myder.getNumberOfValues()!=mybasemulticolvars[mmc]->getNumberOfQuantities() || myder.getNumberOfDerivatives()!=mybasemulticolvars[mmc]->getNumberOfDerivatives() ) { @@ -897,48 +1218,76 @@ MultiValue& MultiColvarBase::getInputDerivatives( const unsigned& iatom, const b } void MultiColvarBase::accumulateSymmetryFunction( const int& ival, const unsigned& iatom, const double& val, const Vector& der, const Tensor& vir, multicolvar::AtomValuePack& myatoms ) const { - plumed_dbg_assert( usespecies ); unsigned katom=myatoms.getIndex(0), jatom=myatoms.getIndex(iatom); - double weight0=1.0; if( atom_lab[katom].first>0 ) weight0=mybasedata[atom_lab[katom].first-1]->retrieveWeightWithIndex( atom_lab[katom].second ); - double weighti=1.0; if( atom_lab[jatom].first>0 ) weighti=mybasedata[atom_lab[jatom].first-1]->retrieveWeightWithIndex( atom_lab[jatom].second ); + plumed_dbg_assert( usespecies ); + unsigned katom=myatoms.getIndex(0), jatom=myatoms.getIndex(iatom); + double weight0=1.0; + if( atom_lab[katom].first>0 ) { + weight0=mybasedata[atom_lab[katom].first-1]->retrieveWeightWithIndex( atom_lab[katom].second ); + } + double weighti=1.0; + if( atom_lab[jatom].first>0 ) { + weighti=mybasedata[atom_lab[jatom].first-1]->retrieveWeightWithIndex( atom_lab[jatom].second ); + } // Accumulate the value - if( ival<0 ) myatoms.getUnderlyingMultiValue().addTemporyValue( weight0*weighti*val ); - else myatoms.addValue( ival, weight0*weighti*val ); + if( ival<0 ) { + myatoms.getUnderlyingMultiValue().addTemporyValue( weight0*weighti*val ); + } else { + myatoms.addValue( ival, weight0*weighti*val ); + } // Return if we don't need derivatives - if( doNotCalculateDerivatives() ) return ; + if( doNotCalculateDerivatives() ) { + return ; + } // And virial - if( ival<0 ) myatoms.addTemporyBoxDerivatives( weight0*weighti*vir ); - else myatoms.addBoxDerivatives( ival, weight0*weighti*vir ); + if( ival<0 ) { + myatoms.addTemporyBoxDerivatives( weight0*weighti*vir ); + } else { + myatoms.addBoxDerivatives( ival, weight0*weighti*vir ); + } // Add derivatives of central atom if( atom_lab[katom].first>0 ) { addComDerivatives( ival, 0, -weight0*weighti*der, myatoms ); std::vector tmpder( mybasemulticolvars[atom_lab[katom].first - 1]->getNumberOfQuantities(), 0. ); - tmpder[0]=weighti*val; mergeInputDerivatives( ival, 0, 1, 0, tmpder, getInputDerivatives(0, false, myatoms), myatoms ); + tmpder[0]=weighti*val; + mergeInputDerivatives( ival, 0, 1, 0, tmpder, getInputDerivatives(0, false, myatoms), myatoms ); } else { - if( ival<0 ) myatoms.addTemporyAtomsDerivatives( 0, -der ); - else myatoms.addAtomsDerivatives( ival, 0, -der ); + if( ival<0 ) { + myatoms.addTemporyAtomsDerivatives( 0, -der ); + } else { + myatoms.addAtomsDerivatives( ival, 0, -der ); + } } // Add derivatives of atom in coordination sphere if( atom_lab[jatom].first>0 ) { addComDerivatives( ival, iatom, weight0*weighti*der, myatoms ); std::vector tmpder( mybasemulticolvars[atom_lab[katom].first - 1]->getNumberOfQuantities(), 0. ); - tmpder[0]=weight0*val; mergeInputDerivatives( ival, 0, 1, iatom, tmpder, getInputDerivatives(iatom, false, myatoms), myatoms ); + tmpder[0]=weight0*val; + mergeInputDerivatives( ival, 0, 1, iatom, tmpder, getInputDerivatives(iatom, false, myatoms), myatoms ); } else { - if( ival<0 ) myatoms.addTemporyAtomsDerivatives( iatom, der ); - else myatoms.addAtomsDerivatives( ival, iatom, der ); + if( ival<0 ) { + myatoms.addTemporyAtomsDerivatives( iatom, der ); + } else { + myatoms.addAtomsDerivatives( ival, iatom, der ); + } } } void MultiColvarBase::addAtomDerivatives( const int& ival, const unsigned& iatom, const Vector& der, multicolvar::AtomValuePack& myatoms ) const { - if( doNotCalculateDerivatives() ) return ; + if( doNotCalculateDerivatives() ) { + return ; + } unsigned jatom=myatoms.getIndex(iatom); if( atom_lab[jatom].first>0 ) { addComDerivatives( ival, iatom, der, myatoms ); } else { - if( ival<0 ) myatoms.addTemporyAtomsDerivatives( iatom, der ); - else myatoms.addAtomsDerivatives( ival, iatom, der ); + if( ival<0 ) { + myatoms.addTemporyAtomsDerivatives( iatom, der ); + } else { + myatoms.addAtomsDerivatives( ival, iatom, der ); + } } } @@ -949,20 +1298,28 @@ double MultiColvarBase::calculateWeight( const unsigned& current, const double& void MultiColvarBase::performTask( const unsigned& task_index, const unsigned& current, MultiValue& myvals ) const { AtomValuePack myatoms( myvals, this ); // Retrieve the atom list - if( !setupCurrentAtomList( current, myatoms ) ) return; + if( !setupCurrentAtomList( current, myatoms ) ) { + return; + } // Get weight due to dynamic groups double weight = 1.0; if( !matsums ) { for(unsigned i=0; i1 ) break; + if( allthirdblockintasks && i>1 ) { + break; + } unsigned mmc = atom_lab[myatoms.getIndex(i)].first - 1; weight *= mybasedata[mmc]->retrieveWeightWithIndex( atom_lab[myatoms.getIndex(i)].second ); } } else if( usespecies ) { if( atom_lab[myatoms.getIndex(0)].first>0 ) { - if( mybasedata[atom_lab[myatoms.getIndex(0)].first-1]->retrieveWeightWithIndex( atom_lab[myatoms.getIndex(0)].second )retrieveWeightWithIndex( atom_lab[myatoms.getIndex(0)].second )0 ) { - MultiValue& outder=myatoms.getUnderlyingMultiValue(); MultiValue myder(0,0); + MultiValue& outder=myatoms.getUnderlyingMultiValue(); + MultiValue myder(0,0); for(unsigned i=0; iretrieveWeightWithIndex( atom_lab[myatoms.getIndex(i)].second ); // And accumulate the derivatives - for(unsigned j=0; jgetNumberOfQuantities(), mybasemulticolvars[mmc]->getNumberOfDerivatives() ); } mybasedata[mmc]->retrieveDerivatives( atom_lab[myatoms.getIndex(0)].second, false, myder ); - unsigned basen=0; for(unsigned i=0; igetNumberOfDerivatives() - 9; + unsigned basen=0; + for(unsigned i=0; igetNumberOfDerivatives() - 9; + } mybasemulticolvars[mmc]->getCentralAtomPack( basen, atom_lab[myatoms.getIndex(0)].second, mybasemulticolvars[mmc]->my_tmp_capacks[0] ); } } // Compute everything - double vv=compute( task_index, myatoms ); updateActiveAtoms( myatoms ); + double vv=compute( task_index, myatoms ); + updateActiveAtoms( myatoms ); myatoms.setValue( 1, vv ); return; } void MultiColvarBase::updateActiveAtoms( AtomValuePack& myatoms ) const { - if( mybasemulticolvars.size()==0 ) myatoms.updateUsingIndices(); - else myatoms.updateDynamicList(); + if( mybasemulticolvars.size()==0 ) { + myatoms.updateUsingIndices(); + } else { + myatoms.updateDynamicList(); + } } Vector MultiColvarBase::getCentralAtomPos( const unsigned& taskIndex ) { @@ -1025,16 +1395,23 @@ Vector MultiColvarBase::getCentralAtomPos( const unsigned& taskIndex ) { return getPositionOfAtomForLinkCells(curr); } else if( nblock>0 ) { // double factor=1.0/static_cast( ablocks.size() ); - Vector mypos; mypos.zero(); - std::vector atoms( ablocks.size() ); decodeIndexToAtoms( curr, atoms ); + Vector mypos; + mypos.zero(); + std::vector atoms( ablocks.size() ); + decodeIndexToAtoms( curr, atoms ); for(unsigned i=0; i0 ) { - if( mypack.getNumberOfAtomsWithDerivatives()!=ncentral ) mypack.resize(ncentral); + if( mypack.getNumberOfAtomsWithDerivatives()!=ncentral ) { + mypack.resize(ncentral); + } unsigned k=0; - std::vector atoms( ablocks.size() ); decodeIndexToAtoms( curr, atoms ); + std::vector atoms( ablocks.size() ); + decodeIndexToAtoms( curr, atoms ); for(unsigned i=0; i& dlist, unsigned int max_index) const { - if (usepbc) pbcApply(dlist, max_index); + if (usepbc) { + pbcApply(dlist, max_index); + } } void MultiColvarBase::apply() { - if( getForcesFromVessels( forcesToApply ) ) setForcesOnAtoms( forcesToApply ); + if( getForcesFromVessels( forcesToApply ) ) { + setForcesOnAtoms( forcesToApply ); + } } } diff --git a/src/multicolvar/MultiColvarBase.h b/src/multicolvar/MultiColvarBase.h index 5c5208c77c..365e12ea09 100644 --- a/src/multicolvar/MultiColvarBase.h +++ b/src/multicolvar/MultiColvarBase.h @@ -41,8 +41,7 @@ class ActionVolume; class MultiColvarBase : public ActionAtomistic, public ActionWithValue, - public vesselbase::ActionWithVessel -{ + public vesselbase::ActionWithVessel { friend class BridgedMultiColvarFunction; friend class VolumeGradientBase; friend class MultiColvarFilter; @@ -158,7 +157,9 @@ class MultiColvarBase : /// Apply PBCs over a set of distance vectors void applyPbc(std::vector& dlist, unsigned max_index=0) const; /// Is it safe to use multithreading - bool threadSafe() const override { return !(mybasemulticolvars.size()>0); } + bool threadSafe() const override { + return !(mybasemulticolvars.size()>0); + } /// Do some setup before the calculation void prepare() override; /// This is overwritten here in order to make sure that we do not retrieve atoms multiple times @@ -192,11 +193,15 @@ class MultiColvarBase : /// You can use this to screen contributions that are very small so we can avoid expensive (and pointless) calculations virtual double calculateWeight( const unsigned& taskCode, const double& weight, AtomValuePack& myatoms ) const ; /// Is this a density? - virtual bool isDensity() const { return false; } + virtual bool isDensity() const { + return false; + } /// Is the iatom'th stored value currently active bool storedValueIsActive( const unsigned& iatom ); /// This is true if multicolvar is calculating a vector or if the multicolvar is the density - virtual bool hasDifferentiableOrientation() const { return false; } + virtual bool hasDifferentiableOrientation() const { + return false; + } /// This makes sure we are not calculating the director when we do LocalAverage virtual void doNotCalculateDirector() {} /// Ensure that derivatives are only calculated when needed @@ -253,7 +258,9 @@ bool MultiColvarBase::usesPbc() const { inline bool MultiColvarBase::doNotCalculateDerivatives() const { - if( !dertime ) return true; + if( !dertime ) { + return true; + } return ActionWithValue::doNotCalculateDerivatives(); } diff --git a/src/multicolvar/MultiColvarCombine.cpp b/src/multicolvar/MultiColvarCombine.cpp index 7dd7b96e38..783690f35f 100644 --- a/src/multicolvar/MultiColvarCombine.cpp +++ b/src/multicolvar/MultiColvarCombine.cpp @@ -47,7 +47,9 @@ class MultiColvarCombine : public MultiColvarBase { /// Actually do the calculation double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; /// Is the variable periodic - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(MultiColvarCombine,"MCOLV_COMBINE") @@ -56,27 +58,41 @@ void MultiColvarCombine::registerKeywords( Keywords& keys ) { MultiColvarBase::registerKeywords( keys ); keys.add("compulsory","DATA","the multicolvars you are calculating linear combinations for"); keys.add("compulsory","COEFFICIENTS","1.0","the coefficients to use for the various multicolvars"); - keys.use("MEAN"); keys.use("MORE_THAN"); keys.use("SUM"); keys.use("LESS_THAN"); keys.use("HISTOGRAM"); - keys.use("MIN"); keys.use("MAX"); keys.use("LOWEST"); keys.use("HIGHEST"); keys.use("ALT_MIN"); keys.use("BETWEEN"); keys.use("MOMENTS"); + keys.use("MEAN"); + keys.use("MORE_THAN"); + keys.use("SUM"); + keys.use("LESS_THAN"); + keys.use("HISTOGRAM"); + keys.use("MIN"); + keys.use("MAX"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("ALT_MIN"); + keys.use("BETWEEN"); + keys.use("MOMENTS"); } MultiColvarCombine::MultiColvarCombine(const ActionOptions& ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { buildSets(); for(unsigned i=0; iweightWithDerivatives() ) error("cannot combine multicolvars with weights"); + if( mybasemulticolvars[i]->weightWithDerivatives() ) { + error("cannot combine multicolvars with weights"); + } } coeff.resize( getNumberOfBaseMultiColvars() ); parseVector("COEFFICIENTS",coeff); log.printf(" coefficients of multicolvars %f", coeff[0] ); - for(unsigned i=1; i tval(2); + double dot=0; + std::vector tval(2); for(unsigned i=0; i cc(2); for(unsigned i=0; i atom; parseAtomList("ORIGIN",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(" origin is at position of atom : %d\n",atom[0].serial() ); - std::string mlab; parse("DATA",mlab); + std::string mlab; + parse("DATA",mlab); mycolv = plumed.getActionSet().selectWithLabel(mlab); - if(!mycolv) error("action labelled " + mlab + " does not exist or is not a MultiColvar"); + if(!mycolv) { + error("action labelled " + mlab + " does not exist or is not a MultiColvar"); + } stash = mycolv->buildDataStashes( NULL ); parseFlag("FRACTIONAL",fractional); - std::string direction; parse("DIR",direction); + std::string direction; + parse("DIR",direction); log.printf(" calculating for %s density profile along ", mycolv->getLabel().c_str() ); if( direction=="x" ) { log.printf("x axis"); - directions.resize(1); directions[0]=0; + directions.resize(1); + directions[0]=0; } else if( direction=="y" ) { log.printf("y axis"); - directions.resize(1); directions[0]=1; + directions.resize(1); + directions[0]=1; } else if( direction=="z" ) { log.printf("z axis"); - directions.resize(1); directions[0]=2; + directions.resize(1); + directions[0]=2; } else if( direction=="xy" ) { log.printf("x and y axes"); - directions.resize(2); directions[0]=0; directions[1]=1; + directions.resize(2); + directions[0]=0; + directions[1]=1; } else if( direction=="xz" ) { log.printf("x and z axes"); - directions.resize(2); directions[0]=0; directions[1]=2; + directions.resize(2); + directions[0]=0; + directions[1]=2; } else if( direction=="yz" ) { log.printf("y and z axis"); - directions.resize(2); directions[0]=1; directions[1]=2; + directions.resize(2); + directions[0]=1; + directions[1]=2; } else if( direction=="xyz" ) { log.printf("x, y and z axes"); - directions.resize(3); directions[0]=0; directions[1]=1; directions[2]=2; + directions.resize(3); + directions[0]=0; + directions[1]=1; + directions[2]=2; } else { error( direction + " is not valid gradient direction"); } log.printf(" for colvars calculated by action %s \n",mycolv->getLabel().c_str() ); - parseVector("NBINS",nbins); parseVector("SPACING",gspacing); - if( nbins.size()!=directions.size() && gspacing.size()!=directions.size() ) error("NBINS or SPACING must be set"); + parseVector("NBINS",nbins); + parseVector("SPACING",gspacing); + if( nbins.size()!=directions.size() && gspacing.size()!=directions.size() ) { + error("NBINS or SPACING must be set"); + } - confined.resize( directions.size() ); cmin.resize( directions.size(), 0 ); cmax.resize( directions.size(), 0 ); + confined.resize( directions.size() ); + cmin.resize( directions.size(), 0 ); + cmax.resize( directions.size(), 0 ); for(unsigned i=0; igetLabel() + ".dens"; vstring +=" COORDINATES="; - if( directions[0]==0 ) vstring+="x"; - else if( directions[0]==1 ) vstring+="y"; - else if( directions[0]==2 ) vstring+="z"; + if( directions[0]==0 ) { + vstring+="x"; + } else if( directions[0]==1 ) { + vstring+="y"; + } else if( directions[0]==2 ) { + vstring+="z"; + } for(unsigned i=1; igetFullNumberOfTasks(); ++i) addTaskToList(i); + for(unsigned i=0; igetFullNumberOfTasks(); ++i) { + addTaskToList(i); + } // And create the grid std::unique_ptr grid; - if( mycolv->isDensity() ) grid=createGrid( "histogram", vstring ); - else grid=createGrid( "average", vstring ); + if( mycolv->isDensity() ) { + grid=createGrid( "histogram", vstring ); + } else { + grid=createGrid( "average", vstring ); + } // cppcheck-suppress danglingLifetime mygrid=grid.get(); // And finish the grid setup @@ -235,11 +302,15 @@ MultiColvarDensity::MultiColvarDensity(const ActionOptions&ao): // Enusre units for cube files are set correctly if( !fractional ) { - if( plumed.getAtoms().usingNaturalUnits() ) mygrid->setCubeUnits( 1.0/0.5292 ); - else mygrid->setCubeUnits( plumed.getAtoms().getUnits().getLength()/.05929 ); + if( plumed.getAtoms().usingNaturalUnits() ) { + mygrid->setCubeUnits( 1.0/0.5292 ); + } else { + mygrid->setCubeUnits( plumed.getAtoms().getUnits().getLength()/.05929 ); + } } - checkRead(); requestAtoms(atom); + checkRead(); + requestAtoms(atom); // Stupid dependencies cleared by requestAtoms - why GBussi why? That's got me so many times addDependency( mycolv ); } @@ -251,7 +322,10 @@ unsigned MultiColvarDensity::getNumberOfQuantities() const { void MultiColvarDensity::clearAverage() { std::vector min(directions.size()), max(directions.size()); std::vector gmin(directions.size()), gmax(directions.size());; - for(unsigned i=0; igetPbc().isOrthorombic() ) { error("I think that density profiles with non-orthorhombic cells don't work. If you want it have a look and see if you can work it out"); @@ -262,35 +336,55 @@ void MultiColvarDensity::clearAverage() { min[i]*=mycolv->getBox()(directions[i],directions[i]); max[i]*=mycolv->getBox()(directions[i],directions[i]); } else { - min[i]=cmin[i]; max[i]=cmax[i]; + min[i]=cmin[i]; + max[i]=cmax[i]; } } } - for(unsigned i=0; isetBounds( gmin, gmax, nbins, gspacing ); resizeFunctions(); + mygrid->setBounds( gmin, gmax, nbins, gspacing ); + resizeFunctions(); } void MultiColvarDensity::prepareForAveraging() { for(unsigned i=0; igetBox()(directions[i],directions[i]), max ); - if( max!=mygrid->getMax()[i] ) error("box size should be fixed. Use FRACTIONAL"); + if( confined[i] ) { + continue; + } + std::string max; + Tools::convert( 0.5*mycolv->getBox()(directions[i],directions[i]), max ); + if( max!=mygrid->getMax()[i] ) { + error("box size should be fixed. Use FRACTIONAL"); + } } // Ensure we only work with active multicolvars deactivateAllTasks(); - for(unsigned i=0; igetNumberOfStoredValues(); ++i) taskFlags[i]=1; + for(unsigned i=0; igetNumberOfStoredValues(); ++i) { + taskFlags[i]=1; + } lockContributors(); // Retrieve the origin origin = getPosition(0); } void MultiColvarDensity::compute( const unsigned& current, MultiValue& myvals ) const { - std::vector cvals( mycolv->getNumberOfQuantities() ); stash->retrieveSequentialValue( current, false, cvals ); + std::vector cvals( mycolv->getNumberOfQuantities() ); + stash->retrieveSequentialValue( current, false, cvals ); Vector fpos, apos = pbcDistance( origin, mycolv->getCentralAtomPos( mycolv->getPositionInFullTaskList(current) ) ); - if( fractional ) { fpos = getPbc().realToScaled( apos ); } else { fpos=apos; } + if( fractional ) { + fpos = getPbc().realToScaled( apos ); + } else { + fpos=apos; + } - myvals.setValue( 0, cweight*cvals[0] ); for(unsigned j=0; jisDensity() ) error("filtering/transforming density makes no sense"); + BridgedMultiColvarFunction(ao) { + if( getPntrToMultiColvar()->isDensity() ) { + error("filtering/transforming density makes no sense"); + } - if( getName().find("MFILTER")!=std::string::npos ) filter=true; - else { + if( getName().find("MFILTER")!=std::string::npos ) { + filter=true; + } else { plumed_assert( getName().find("MTRANSFORM")!=std::string::npos ); filter=false; } @@ -53,7 +62,9 @@ void MultiColvarFilter::doJobsRequiredBeforeTaskList() { void MultiColvarFilter::completeTask( const unsigned& curr, MultiValue& invals, MultiValue& outvals ) const { invals.copyValues( outvals ); - if( derivativesAreRequired() ) invals.copyDerivatives( outvals ); + if( derivativesAreRequired() ) { + invals.copyDerivatives( outvals ); + } // Retrieve the value of the multicolvar and apply filter double val=invals.get(1), df, weight=applyFilter( val, df ); @@ -68,7 +79,8 @@ void MultiColvarFilter::completeTask( const unsigned& curr, MultiValue& invals, } } } else if( filter ) { - double ww=outvals.get(0); outvals.setValue( 0, ww*weight ); + double ww=outvals.get(0); + outvals.setValue( 0, ww*weight ); if( derivativesAreRequired() ) { for(unsigned i=0; iweightWithDerivatives() ) error("cannot take product of multicolvars with weights"); + if( mybasemulticolvars[i]->weightWithDerivatives() ) { + error("cannot take product of multicolvars with weights"); + } } } double MultiColvarProduct::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { - double dot=1; std::vector tval(2); + double dot=1; + std::vector tval(2); for(unsigned i=0; i cc(2); for(unsigned i=0; i0) { switchingFunction.set(sw,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); } log.printf(" calculating number of links with atoms separation of %s\n",( switchingFunction.description() ).c_str() ); - std::vector all_atoms; readTwoGroups( "GROUP", "GROUPA", "GROUPB", all_atoms ); - setupMultiColvarBase( all_atoms ); setLinkCellCutoff( switchingFunction.get_dmax() ); + std::vector all_atoms; + readTwoGroups( "GROUP", "GROUPA", "GROUPB", all_atoms ); + setupMultiColvarBase( all_atoms ); + setLinkCellCutoff( switchingFunction.get_dmax() ); for(unsigned i=0; ihasDifferentiableOrientation() ) error("cannot use multicolvar of type " + getBaseMultiColvar(i)->getName() ); + if( !getBaseMultiColvar(i)->hasDifferentiableOrientation() ) { + error("cannot use multicolvar of type " + getBaseMultiColvar(i)->getName() ); + } } // Create holders for the collective variable readVesselKeywords(); plumed_assert( getNumberOfVessels()==0 ); - std::string input; addVessel( "SUM", input, -1 ); + std::string input; + addVessel( "SUM", input, -1 ); readVesselKeywords(); } @@ -148,7 +160,9 @@ double NumberOfLinks::calculateWeight( const unsigned& taskCode, const double& w } double NumberOfLinks::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { - if( getBaseMultiColvar(0)->getNumberOfQuantities()<3 ) return 1.0; + if( getBaseMultiColvar(0)->getNumberOfQuantities()<3 ) { + return 1.0; + } unsigned ncomp=getBaseMultiColvar(0)->getNumberOfQuantities(); diff --git a/src/multicolvar/Torsions.cpp b/src/multicolvar/Torsions.cpp index cd565ea73b..e8ccd2f93a 100644 --- a/src/multicolvar/Torsions.cpp +++ b/src/multicolvar/Torsions.cpp @@ -78,8 +78,13 @@ class Torsions : public MultiColvarBase { static void registerKeywords( Keywords& keys ); explicit Torsions(const ActionOptions&); double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; - bool isPeriodic() override { return true; } - void retrieveDomain( std::string& min, std::string& max ) override { min="-pi"; max="pi"; } + bool isPeriodic() override { + return true; + } + void retrieveDomain( std::string& min, std::string& max ) override { + min="-pi"; + max="pi"; + } }; PLUMED_REGISTER_ACTION(Torsions,"TORSIONS") @@ -92,15 +97,16 @@ void Torsions::registerKeywords( Keywords& keys ) { "provide the indices of four atoms). The eventual number of quantities calculated by this " "action will depend on what functions of the distribution you choose to calculate."); keys.reset_style("ATOMS","atoms"); - keys.use("BETWEEN"); keys.use("HISTOGRAM"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); } Torsions::Torsions(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { // Read in the atoms - int natoms=4; std::vector all_atoms; + int natoms=4; + std::vector all_atoms; readAtomsLikeKeyword( "ATOMS", natoms, all_atoms ); setupMultiColvarBase( all_atoms ); std::vector catom_ind(4, false); @@ -118,7 +124,8 @@ double Torsions::compute( const unsigned& tindex, AtomValuePack& myatoms ) const d1=getSeparation(myatoms.getPosition(2),myatoms.getPosition(1)); d2=getSeparation(myatoms.getPosition(3),myatoms.getPosition(2)); - Vector dd0,dd1,dd2; PLMD::Torsion t; + Vector dd0,dd1,dd2; + PLMD::Torsion t; double value = t.compute(d0,d1,d2,dd0,dd1,dd2); addAtomDerivatives(1,0,dd0,myatoms); diff --git a/src/multicolvar/VolumeAround.cpp b/src/multicolvar/VolumeAround.cpp index 6d8f7e1e09..c869886690 100644 --- a/src/multicolvar/VolumeAround.cpp +++ b/src/multicolvar/VolumeAround.cpp @@ -95,29 +95,47 @@ void VolumeAround::registerKeywords( Keywords& keys ) { VolumeAround::VolumeAround(const ActionOptions& ao): Action(ao), - ActionVolume(ao) -{ + ActionVolume(ao) { std::vector atom; parseAtomList("ATOM",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(" 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 ); @@ -126,19 +144,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/multicolvar/VolumeBetweenContours.cpp b/src/multicolvar/VolumeBetweenContours.cpp index d72e4c5937..00a23d1fc3 100644 --- a/src/multicolvar/VolumeBetweenContours.cpp +++ b/src/multicolvar/VolumeBetweenContours.cpp @@ -78,7 +78,8 @@ class VolumeInEnvelope : public ActionVolume { PLUMED_REGISTER_ACTION(VolumeInEnvelope,"INENVELOPE") void VolumeInEnvelope::registerKeywords( Keywords& keys ) { - ActionVolume::registerKeywords( keys ); keys.remove("SIGMA"); + ActionVolume::registerKeywords( keys ); + keys.remove("SIGMA"); keys.add("atoms","ATOMS","the atom whose positions we are constructing a field from"); keys.add("compulsory","BANDWIDTH","the bandwidths for kernel density estimation"); keys.add("compulsory","CONTOUR","a switching function that tells PLUMED how large the density should be"); @@ -87,58 +88,90 @@ void VolumeInEnvelope::registerKeywords( Keywords& keys ) { VolumeInEnvelope::VolumeInEnvelope(const ActionOptions& ao): Action(ao), ActionVolume(ao), - mylinks(comm) -{ - std::vector atoms; parseAtomList("ATOMS",atoms); + mylinks(comm) { + std::vector atoms; + parseAtomList("ATOMS",atoms); log.printf(" creating density field from atoms : "); - for(unsigned i=0; i pp(3,0.0), bandwidth(3); parseVector("BANDWIDTH",bandwidth); + std::vector pp(3,0.0), bandwidth(3); + parseVector("BANDWIDTH",bandwidth); log.printf(" using %s kernel with bandwidths %f %f %f \n",getKernelType().c_str(),bandwidth[0],bandwidth[1],bandwidth[2] ); kernel=Tools::make_unique( pp, bandwidth, getKernelType(), "DIAGONAL", 1.0 ); - for(unsigned i=0; i<3; ++i) { pos.emplace_back(Tools::make_unique()); pos[i]->setNotPeriodic(); } + for(unsigned i=0; i<3; ++i) { + pos.emplace_back(Tools::make_unique()); + pos[i]->setNotPeriodic(); + } std::vector csupport( kernel->getContinuousSupport() ); double maxs = csupport[0]; for(unsigned i=1; imaxs ) maxs = csupport[i]; + if( csupport[i]>maxs ) { + maxs = csupport[i]; + } } - 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; iset( dist[j] ); + for(unsigned j=0; j<3; ++j) { + pos[j]->set( dist[j] ); + } value += kernel->evaluate( pos_ptr, der, true ); for(unsigned j=0; j<3; ++j) { - derivatives[j] -= der[j]; refders[ indices[i] ][j] += der[j]; tder[j]=der[j]; + derivatives[j] -= der[j]; + refders[ indices[i] ][j] += der[j]; + tder[j]=der[j]; } vir -= Tensor( tder, dist ); } double deriv, fval = sfunc.calculate( value, deriv ); - derivatives *= -deriv*value; vir *= -deriv*value; - for(unsigned i=1; i atoms; parseAtomList("ATOMS",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=plumed.getAtoms().getUnits().getLength()/u.getLength(); } else { unitname="nm"; @@ -198,10 +207,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; @@ -226,7 +239,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 ) ); @@ -280,18 +295,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_perp<=0 ) { + plumed_merror("Invalid box coordinates"); } - if( len_bi<=0 || len_cross<=0 || len_perp<=0 ) plumed_merror("Invalid box coordinates"); // Now derivatives of lengths Tensor dd3( Tensor::identity() ); @@ -312,9 +338,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 = std::fabs( jacob.determinant() ); } @@ -356,7 +388,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 ); @@ -383,15 +417,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]) + @@ -400,7 +442,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/multicolvar/VolumeGradientBase.cpp b/src/multicolvar/VolumeGradientBase.cpp index 2c7161ceda..a0b1c5414f 100644 --- a/src/multicolvar/VolumeGradientBase.cpp +++ b/src/multicolvar/VolumeGradientBase.cpp @@ -33,20 +33,28 @@ void VolumeGradientBase::registerKeywords( Keywords& keys ) { VolumeGradientBase::VolumeGradientBase(const ActionOptions&ao): Action(ao), - BridgedMultiColvarFunction(ao) -{ + BridgedMultiColvarFunction(ao) { } void VolumeGradientBase::requestAtoms( const std::vector& atoms ) { - ActionAtomistic::requestAtoms(atoms); bridgeVariable=3*atoms.size(); + ActionAtomistic::requestAtoms(atoms); + bridgeVariable=3*atoms.size(); std::map checklabs; - for(const auto & p : getDependencies() ) checklabs.insert(std::pair(p->getLabel(),false)); + for(const auto & p : getDependencies() ) { + checklabs.insert(std::pair(p->getLabel(),false)); + } for(const auto & p : plumed.getActionSet() ) { - if( p->getLabel()==getPntrToMultiColvar()->getLabel() ) break; - if( checklabs.count(p->getLabel()) ) checklabs[p->getLabel()]=true; + if( p->getLabel()==getPntrToMultiColvar()->getLabel() ) { + break; + } + if( checklabs.count(p->getLabel()) ) { + checklabs[p->getLabel()]=true; + } } for(const auto & p : checklabs ) { - if( !p.second ) error("the input for the virtual atoms used in the input for this action must appear in the input file before the input multicolvar"); + if( !p.second ) { + error("the input for the virtual atoms used in the input for this action must appear in the input file before the input multicolvar"); + } } addDependency( getPntrToMultiColvar() ); tmpforces.resize( 3*atoms.size()+9 ); @@ -54,17 +62,21 @@ void VolumeGradientBase::requestAtoms( const std::vector& atoms ) { void VolumeGradientBase::doJobsRequiredBeforeTaskList() { ActionWithValue::clearDerivatives(); - retrieveAtoms(); setupRegions(); + retrieveAtoms(); + setupRegions(); ActionWithVessel::doJobsRequiredBeforeTaskList(); } void VolumeGradientBase::completeTask( const unsigned& curr, MultiValue& invals, MultiValue& outvals ) const { if( getPntrToMultiColvar()->isDensity() ) { - outvals.setValue(0, 1.0); outvals.setValue(1, 1.0); + outvals.setValue(0, 1.0); + outvals.setValue(1, 1.0); } else { // Copy derivatives of the colvar and the value of the colvar invals.copyValues( outvals ); - if( derivativesAreRequired() ) invals.copyDerivatives( outvals ); + if( derivativesAreRequired() ) { + invals.copyDerivatives( outvals ); + } } calculateAllVolumes( curr, outvals ); } @@ -76,7 +88,8 @@ void VolumeGradientBase::setNumberInVolume( const unsigned& ivol, const unsigned if( !mcolv->weightHasDerivatives ) { outvals.setValue(ivol, weight ); if( derivativesAreRequired() ) { - CatomPack catom; mcolv->getCentralAtomPack( 0, curr, catom ); + CatomPack catom; + mcolv->getCentralAtomPack( 0, curr, catom ); for(unsigned i=0; igetNumberOfDerivatives(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) outvals.addDerivative( ivol, nmder-9+3*i+j, virial(i,j) ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + outvals.addDerivative( ivol, nmder-9+3*i+j, virial(i,j) ); + } for(unsigned i=0; igetCentralAtomPack( 0, curr, catom ); + CatomPack catom; + mcolv->getCentralAtomPack( 0, curr, catom ); for(unsigned i=0; igetNumberOfDerivatives(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) outvals.addDerivative( ivol, nmder-9+3*i+j, ww*virial(i,j) ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + outvals.addDerivative( ivol, nmder-9+3*i+j, ww*virial(i,j) ); + } for(unsigned i=0; igetCentralAtomPack( 0, curr, catom ); + CatomPack catom; + mcolv->getCentralAtomPack( 0, curr, catom ); for(unsigned i=0; igetNumberOfDerivatives(); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) outvals.addDerivative( ivol, nmder-9+3*i+j, ww*virial(i,j) ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + outvals.addDerivative( ivol, nmder-9+3*i+j, ww*virial(i,j) ); + } for(unsigned i=0; i& bb ) { plumed_dbg_assert( bb.size()==tmpforces.size()-9 ); // Forces on local atoms - for(unsigned i=0; i(bridgeVariable)>=3*iatom && static_cast(bridgeVariable)<(iatom+1)*3 ) tmp_p[bridgeVariable%3]+=sqrt(epsilon); + if( static_cast(bridgeVariable)>=3*iatom && static_cast(bridgeVariable)<(iatom+1)*3 ) { + tmp_p[bridgeVariable%3]+=sqrt(epsilon); + } } // This makes sure that numerical derivatives of virial are calculated correctly tmp_p = ActionAtomistic::getPbc().realToScaled( tmp_p ); diff --git a/src/multicolvar/VolumeInCylinder.cpp b/src/multicolvar/VolumeInCylinder.cpp index c37ed8fda2..7134521520 100644 --- a/src/multicolvar/VolumeInCylinder.cpp +++ b/src/multicolvar/VolumeInCylinder.cpp @@ -99,35 +99,60 @@ void VolumeInCylinder::registerKeywords( Keywords& keys ) { VolumeInCylinder::VolumeInCylinder(const ActionOptions& ao): Action(ao), ActionVolume(ao), - docylinder(false) -{ + docylinder(false) { std::vector atom; parseAtomList("ATOM",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() { } @@ -140,12 +165,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/multicolvar/VolumeInSphere.cpp b/src/multicolvar/VolumeInSphere.cpp index 9de9077fc2..a79c6add0b 100644 --- a/src/multicolvar/VolumeInSphere.cpp +++ b/src/multicolvar/VolumeInSphere.cpp @@ -91,20 +91,27 @@ void VolumeInSphere::registerKeywords( Keywords& keys ) { VolumeInSphere::VolumeInSphere(const ActionOptions& ao): Action(ao), - ActionVolume(ao) -{ + ActionVolume(ao) { std::vector atom; parseAtomList("ATOM",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 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() { } @@ -113,7 +120,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/multicolvar/VolumeTetrapore.cpp b/src/multicolvar/VolumeTetrapore.cpp index ee66d158dd..97cbe507df 100644 --- a/src/multicolvar/VolumeTetrapore.cpp +++ b/src/multicolvar/VolumeTetrapore.cpp @@ -152,23 +152,32 @@ VolumeTetrapore::VolumeTetrapore(const ActionOptions& ao): dlperp(4), dbi(3), dcross(3), - dperp(3) -{ + dperp(3) { std::vector atoms; parseAtomList("ATOMS",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=plumed.getAtoms().getUnits().getLength()/u.getLength(); } else { unitname="nm"; @@ -205,11 +214,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 @@ -217,13 +230,25 @@ void VolumeTetrapore::setupRegions() { perp = std::cos(pi/4.0)*bisector - std::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 ) ); @@ -264,7 +289,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; @@ -316,22 +342,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_perp<=0 ) { + plumed_merror("Invalid box coordinates"); } - if( len_bi<=0 || len_cross<=0 || len_perp<=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 @@ -340,16 +383,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 = std::fabs( jacob.determinant() ); } @@ -391,7 +445,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 ); @@ -418,15 +474,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]) + @@ -435,7 +499,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/multicolvar/XAngle.cpp b/src/multicolvar/XAngle.cpp index e50a90b227..27c8a1dd59 100644 --- a/src/multicolvar/XAngle.cpp +++ b/src/multicolvar/XAngle.cpp @@ -93,7 +93,9 @@ class XAngles : public MultiColvarBase { double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; double calculateWeight( const unsigned& taskCode, const double& weight, AtomValuePack& ) const override; /// Returns the number of coordinates of the field - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(XAngles,"XANGLES") @@ -102,10 +104,17 @@ PLUMED_REGISTER_ACTION(XAngles,"ZANGLES") void XAngles::registerKeywords( Keywords& keys ) { MultiColvarBase::registerKeywords( keys ); - keys.use("MAX"); keys.use("ALT_MIN"); - keys.use("MEAN"); keys.use("MIN"); keys.use("LESS_THAN"); - keys.use("LOWEST"); keys.use("HIGHEST"); - keys.use("MORE_THAN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); + keys.use("MAX"); + keys.use("ALT_MIN"); + keys.use("MEAN"); + keys.use("MIN"); + keys.use("LESS_THAN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("MORE_THAN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); keys.add("numbered","ATOMS","the atoms involved in each of the angles you wish to calculate. " "Keywords like ATOMS1, ATOMS2, ATOMS3,... should be listed and one angle will be " "calculated for each ATOM keyword you specify (all ATOM keywords should " @@ -124,19 +133,27 @@ void XAngles::registerKeywords( Keywords& keys ) { XAngles::XAngles(const ActionOptions&ao): Action(ao), MultiColvarBase(ao), - use_sf(false) -{ - if( getName().find("X")!=std::string::npos) myc=0; - else if( getName().find("Y")!=std::string::npos) myc=1; - else if( getName().find("Z")!=std::string::npos) myc=2; - else plumed_error(); + use_sf(false) { + if( getName().find("X")!=std::string::npos) { + myc=0; + } else if( getName().find("Y")!=std::string::npos) { + myc=1; + } else if( getName().find("Z")!=std::string::npos) { + myc=2; + } else { + plumed_error(); + } // Read in switching function - std::string sfinput, errors; parse("SWITCH",sfinput); + std::string sfinput, errors; + parse("SWITCH",sfinput); if( sfinput.length()>0 ) { - use_sf=true; weightHasDerivatives=true; + use_sf=true; + weightHasDerivatives=true; sf1.set(sfinput,errors); - if( errors.length()!=0 ) error("problem reading SWITCH keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading SWITCH keyword : " + errors ); + } log.printf(" only calculating angles for atoms separated by less than %s\n", sf1.description().c_str() ); setLinkCellCutoff( sf1.get_dmax() ); } @@ -144,14 +161,18 @@ XAngles::XAngles(const ActionOptions&ao): // Read in the atoms std::vector all_atoms; readTwoGroups( "GROUP", "GROUPA", "GROUPB", all_atoms ); - if( atom_lab.size()==0 ) readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + if( atom_lab.size()==0 ) { + readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + } setupMultiColvarBase( all_atoms ); // And check everything has been read in correctly checkRead(); } double XAngles::calculateWeight( const unsigned& taskCode, const double& weight, AtomValuePack& myatoms ) const { - if(!use_sf) return 1.0; + if(!use_sf) { + return 1.0; + } Vector distance=getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); double dw, w = sf1.calculateSqr( distance.modulo2(), dw ); @@ -162,9 +183,12 @@ double XAngles::calculateWeight( const unsigned& taskCode, const double& weight, } double XAngles::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { - Vector ddij, ddik, axis, distance; axis.zero(); axis[myc]=1; + Vector ddij, ddik, axis, distance; + axis.zero(); + axis[myc]=1; distance=getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); - PLMD::Angle a; double angle=a.compute( distance, axis, ddij, ddik ); + PLMD::Angle a; + double angle=a.compute( distance, axis, ddij, ddik ); addAtomDerivatives( 1, 0, -ddij, myatoms ); addAtomDerivatives( 1, 1, ddij, myatoms ); diff --git a/src/multicolvar/XDistances.cpp b/src/multicolvar/XDistances.cpp index a60347eef4..4e6eecf08e 100644 --- a/src/multicolvar/XDistances.cpp +++ b/src/multicolvar/XDistances.cpp @@ -179,7 +179,9 @@ class XDistances : public MultiColvarBase { // active methods: double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; /// Returns the number of coordinates of the field - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(XDistances,"XDISTANCES") @@ -188,10 +190,17 @@ PLUMED_REGISTER_ACTION(XDistances,"ZDISTANCES") void XDistances::registerKeywords( Keywords& keys ) { MultiColvarBase::registerKeywords( keys ); - keys.use("MAX"); keys.use("ALT_MIN"); - keys.use("MEAN"); keys.use("MIN"); keys.use("LESS_THAN"); - keys.use("LOWEST"); keys.use("HIGHEST"); - keys.use("MORE_THAN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); + keys.use("MAX"); + keys.use("ALT_MIN"); + keys.use("MEAN"); + keys.use("MIN"); + keys.use("LESS_THAN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("MORE_THAN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); keys.add("numbered","ATOMS","the atoms involved in each of the distances you wish to calculate. " "Keywords like ATOMS1, ATOMS2, ATOMS3,... should be listed and one distance will be " "calculated for each ATOM keyword you specify (all ATOM keywords should " @@ -207,17 +216,23 @@ void XDistances::registerKeywords( Keywords& keys ) { XDistances::XDistances(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ - if( getName().find("X")!=std::string::npos) myc=0; - else if( getName().find("Y")!=std::string::npos) myc=1; - else if( getName().find("Z")!=std::string::npos) myc=2; - else plumed_error(); + MultiColvarBase(ao) { + if( getName().find("X")!=std::string::npos) { + myc=0; + } else if( getName().find("Y")!=std::string::npos) { + myc=1; + } else if( getName().find("Z")!=std::string::npos) { + myc=2; + } else { + plumed_error(); + } // Read in the atoms std::vector all_atoms; readTwoGroups( "GROUP", "GROUPA", "GROUPB", all_atoms ); - if( atom_lab.size()==0 ) readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + if( atom_lab.size()==0 ) { + readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + } setupMultiColvarBase( all_atoms ); // And check everything has been read in correctly checkRead(); @@ -228,10 +243,13 @@ double XDistances::compute( const unsigned& tindex, AtomValuePack& myatoms ) con distance=getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); const double value=distance[myc]; - Vector myvec; myvec.zero(); + Vector myvec; + myvec.zero(); // And finish the calculation - myvec[myc]=+1; addAtomDerivatives( 1, 1, myvec, myatoms ); - myvec[myc]=-1; addAtomDerivatives( 1, 0, myvec, myatoms ); + myvec[myc]=+1; + addAtomDerivatives( 1, 1, myvec, myatoms ); + myvec[myc]=-1; + addAtomDerivatives( 1, 0, myvec, myatoms ); myatoms.addBoxDerivatives( 1, Tensor(distance,myvec) ); return value; } diff --git a/src/multicolvar/XYDistances.cpp b/src/multicolvar/XYDistances.cpp index a01d002bab..bbafbcd4c5 100644 --- a/src/multicolvar/XYDistances.cpp +++ b/src/multicolvar/XYDistances.cpp @@ -104,7 +104,9 @@ class XYDistances : public MultiColvarBase { // active methods: double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; /// Returns the number of coordinates of the field - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(XYDistances,"XYDISTANCES") @@ -113,9 +115,17 @@ PLUMED_REGISTER_ACTION(XYDistances,"YZDISTANCES") void XYDistances::registerKeywords( Keywords& keys ) { MultiColvarBase::registerKeywords( keys ); - keys.use("MAX"); keys.use("ALT_MIN"); - keys.use("MEAN"); keys.use("MIN"); keys.use("LESS_THAN"); keys.use("LOWEST"); keys.use("HIGHEST"); - keys.use("MORE_THAN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); + keys.use("MAX"); + keys.use("ALT_MIN"); + keys.use("MEAN"); + keys.use("MIN"); + keys.use("LESS_THAN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("MORE_THAN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); keys.add("numbered","ATOMS","the atoms involved in each of the distances you wish to calculate. " "Keywords like ATOMS1, ATOMS2, ATOMS3,... should be listed and one distance will be " "calculated for each ATOM keyword you specify (all ATOM keywords should " @@ -131,20 +141,26 @@ void XYDistances::registerKeywords( Keywords& keys ) { XYDistances::XYDistances(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { if( getName().find("XY")!=std::string::npos) { - myc1=0; myc2=1; + myc1=0; + myc2=1; } else if( getName().find("XZ")!=std::string::npos) { - myc1=0; myc2=2; + myc1=0; + myc2=2; } else if( getName().find("YZ")!=std::string::npos) { - myc1=1; myc2=2; - } else plumed_error(); + myc1=1; + myc2=2; + } else { + plumed_error(); + } // Read in the atoms std::vector all_atoms; readTwoGroups( "GROUP", "GROUPA", "GROUPB", all_atoms ); - if( atom_lab.size()==0 ) readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + if( atom_lab.size()==0 ) { + readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + } setupMultiColvarBase( all_atoms ); // And check everything has been read in correctly checkRead(); @@ -156,10 +172,15 @@ double XYDistances::compute( const unsigned& tindex, AtomValuePack& myatoms ) co const double value=std::sqrt(distance[myc1]*distance[myc1] + distance[myc2]*distance[myc2] ); const double invvalue=1.0/value; - Vector myvec; myvec.zero(); + Vector myvec; + myvec.zero(); // And finish the calculation - myvec[myc1]=+invvalue*distance[myc1]; myvec[myc2]=+invvalue*distance[myc2]; addAtomDerivatives( 1, 1, myvec, myatoms ); - myvec[myc1]=-invvalue*distance[myc1]; myvec[myc2]=-invvalue*distance[myc2]; addAtomDerivatives( 1, 0, myvec, myatoms ); + myvec[myc1]=+invvalue*distance[myc1]; + myvec[myc2]=+invvalue*distance[myc2]; + addAtomDerivatives( 1, 1, myvec, myatoms ); + myvec[myc1]=-invvalue*distance[myc1]; + myvec[myc2]=-invvalue*distance[myc2]; + addAtomDerivatives( 1, 0, myvec, myatoms ); myatoms.addBoxDerivatives( 1, Tensor(distance,myvec) ); return value; } diff --git a/src/multicolvar/XYTorsion.cpp b/src/multicolvar/XYTorsion.cpp index 0d1d45c2d8..e644728686 100644 --- a/src/multicolvar/XYTorsion.cpp +++ b/src/multicolvar/XYTorsion.cpp @@ -142,8 +142,13 @@ class XYTorsion : public MultiColvarBase { double compute( const unsigned& tindex, AtomValuePack& myatoms ) const override; double calculateWeight( const unsigned& taskCode, const double& weight, AtomValuePack& ) const override; /// Returns the number of coordinates of the field - bool isPeriodic() override { return true; } - void retrieveDomain( std::string& min, std::string& max) override { min="-pi"; max="pi"; } + bool isPeriodic() override { + return true; + } + void retrieveDomain( std::string& min, std::string& max) override { + min="-pi"; + max="pi"; + } }; PLUMED_REGISTER_ACTION(XYTorsion,"XYTORSIONS") @@ -155,10 +160,15 @@ PLUMED_REGISTER_ACTION(XYTorsion,"ZYTORSIONS") void XYTorsion::registerKeywords( Keywords& keys ) { MultiColvarBase::registerKeywords( keys ); - keys.use("MAX"); keys.use("ALT_MIN"); - keys.use("MEAN"); keys.use("MIN"); - keys.use("LOWEST"); keys.use("HIGHEST"); - keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); + keys.use("MAX"); + keys.use("ALT_MIN"); + keys.use("MEAN"); + keys.use("MIN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); keys.add("numbered","ATOMS","the atoms involved in each of the torsion angles you wish to calculate. " "Keywords like ATOMS1, ATOMS2, ATOMS3,... should be listed and one torsion will be " "calculated for each ATOM keyword you specify (all ATOM keywords should " @@ -177,22 +187,39 @@ void XYTorsion::registerKeywords( Keywords& keys ) { XYTorsion::XYTorsion(const ActionOptions&ao): Action(ao), MultiColvarBase(ao), - use_sf(false) -{ - if( getName().find("XY")!=std::string::npos) { myc1=0; myc2=1; } - else if( getName().find("XZ")!=std::string::npos) { myc1=0; myc2=2; } - else if( getName().find("YX")!=std::string::npos) { myc1=1; myc2=0; } - else if( getName().find("YZ")!=std::string::npos) { myc1=1; myc2=2; } - else if( getName().find("ZX")!=std::string::npos) { myc1=2; myc2=0; } - else if( getName().find("ZY")!=std::string::npos) { myc1=2; myc2=1; } - else plumed_error(); + use_sf(false) { + if( getName().find("XY")!=std::string::npos) { + myc1=0; + myc2=1; + } else if( getName().find("XZ")!=std::string::npos) { + myc1=0; + myc2=2; + } else if( getName().find("YX")!=std::string::npos) { + myc1=1; + myc2=0; + } else if( getName().find("YZ")!=std::string::npos) { + myc1=1; + myc2=2; + } else if( getName().find("ZX")!=std::string::npos) { + myc1=2; + myc2=0; + } else if( getName().find("ZY")!=std::string::npos) { + myc1=2; + myc2=1; + } else { + plumed_error(); + } // Read in switching function - std::string sfinput, errors; parse("SWITCH",sfinput); + std::string sfinput, errors; + parse("SWITCH",sfinput); if( sfinput.length()>0 ) { - use_sf=true; weightHasDerivatives=true; + use_sf=true; + weightHasDerivatives=true; sf1.set(sfinput,errors); - if( errors.length()!=0 ) error("problem reading SWITCH keyword : " + errors ); + if( errors.length()!=0 ) { + error("problem reading SWITCH keyword : " + errors ); + } log.printf(" only calculating angles for atoms separated by less than %s\n", sf1.description().c_str() ); setLinkCellCutoff( sf1.get_dmax() ); } @@ -200,14 +227,18 @@ XYTorsion::XYTorsion(const ActionOptions&ao): // Read in the atoms std::vector all_atoms; readTwoGroups( "GROUP", "GROUPA", "GROUPB", all_atoms ); - if( atom_lab.size()==0 ) readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + if( atom_lab.size()==0 ) { + readAtomsLikeKeyword( "ATOMS", 2, all_atoms ); + } setupMultiColvarBase( all_atoms ); // And check everything has been read in correctly checkRead(); } double XYTorsion::calculateWeight( const unsigned& taskCode, const double& weight, AtomValuePack& myatoms ) const { - if(!use_sf) return 1.0; + if(!use_sf) { + return 1.0; + } Vector distance=getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); double dw, w = sf1.calculateSqr( distance.modulo2(), dw ); @@ -219,9 +250,13 @@ double XYTorsion::calculateWeight( const unsigned& taskCode, const double& weigh double XYTorsion::compute( const unsigned& tindex, AtomValuePack& myatoms ) const { Vector dd0, dd1, dd2, axis, rot, distance; - axis.zero(); rot.zero(); rot[myc1]=1; axis[myc2]=1; + axis.zero(); + rot.zero(); + rot[myc1]=1; + axis[myc2]=1; distance=getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); - PLMD::Torsion t; double torsion=t.compute( distance, rot, axis, dd0, dd1, dd2 ); + PLMD::Torsion t; + double torsion=t.compute( distance, rot, axis, dd0, dd1, dd2 ); addAtomDerivatives( 1, 0, -dd0, myatoms ); addAtomDerivatives( 1, 1, dd0, myatoms ); diff --git a/src/opes/ECVcustom.cpp b/src/opes/ECVcustom.cpp index cde45524d9..4cfb77f952 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. \\f$\\Delta U_i\\f$, 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 89e856e7f7..6bed2d1081 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. \\f$\\Delta U\\f$"); @@ -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 d714eba64e..b753374c56 100644 --- a/src/opes/ECVmultiThermal.cpp +++ b/src/opes/ECVmultiThermal.cpp @@ -80,8 +80,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_; @@ -102,8 +101,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 \\ref ENERGY colvar"); @@ -117,8 +115,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 @@ -139,31 +136,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_/plumed.getAtoms().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(); @@ -233,14 +225,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 693d19d9d2..367a40fdd9 100644 --- a/src/opes/ECVmultiThermalBaric.cpp +++ b/src/opes/ECVmultiThermalBaric.cpp @@ -74,8 +74,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_; @@ -109,8 +108,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 \\ref ENERGY and \\ref VOLUME respectively"); @@ -138,8 +136,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 @@ -174,8 +171,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"); @@ -188,10 +184,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]; @@ -313,9 +299,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); } } @@ -323,67 +307,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++; } @@ -394,22 +377,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=plumed.getAtoms().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++; } @@ -452,33 +425,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 321c29ae4d..e20eb9edc1 100644 --- a/src/opes/ExpansionCVs.cpp +++ b/src/opes/ExpansionCVs.cpp @@ -25,8 +25,7 @@ namespace PLMD { namespace opes { -void ExpansionCVs::registerKeywords(Keywords& keys) -{ +void ExpansionCVs::registerKeywords(Keywords& keys) { Action::registerKeywords(keys); ActionWithValue::registerKeywords(keys); ActionWithArguments::registerKeywords(keys); @@ -39,17 +38,16 @@ ExpansionCVs::ExpansionCVs(const ActionOptions&ao) , ActionWithValue(ao) , ActionWithArguments(ao) , isReady_(false) - , totNumECVs_(0) -{ + , totNumECVs_(0) { //set kbt_ const double kB=plumed.getAtoms().getKBoltzmann(); kbt_=plumed.getAtoms().getKbT(); double temp=-1; parse("TEMP",temp); - if(temp>0) - { - if(kbt_>0 && std::abs(kbt_-kB*temp)>1e-4) + if(temp>0) { + if(kbt_>0 && std::abs(kbt_-kB*temp)>1e-4) { log.printf(" +++ WARNING +++ using TEMP=%g while MD engine uses %g\n",temp,kbt_/kB); + } kbt_=kB*temp; } plumed_massert(kbt_>0,"your MD engine does not pass the temperature to plumed, you must specify it using TEMP"); @@ -57,104 +55,93 @@ 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"); } -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; } @@ -197,32 +180,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 3fecf96001..65a9ab6004 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_; @@ -51,10 +50,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 e5ee2cee93..bcfc60b642 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"); @@ -213,8 +212,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_); @@ -236,12 +234,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_); @@ -249,22 +250,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; } @@ -275,8 +272,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; @@ -288,38 +284,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; @@ -332,11 +323,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"); @@ -345,38 +335,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); @@ -386,42 +377,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_; @@ -429,63 +416,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"); } @@ -493,90 +482,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); } @@ -584,27 +579,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(); } @@ -646,36 +636,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; @@ -684,30 +678,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); @@ -719,12 +709,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 @@ -732,20 +722,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(); @@ -783,14 +769,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_; @@ -799,8 +784,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(); @@ -813,23 +797,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(); @@ -837,13 +820,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; @@ -251,7 +250,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") @@ -295,20 +296,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"); @@ -317,10 +320,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"); @@ -339,8 +343,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"); @@ -366,8 +371,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"); @@ -376,10 +380,10 @@ OPESmetad::OPESmetad(const ActionOptions& ao) kbt_=plumed.getAtoms().getKbT(); double temp=-1; parse("TEMP",temp); - if(temp>0) - { - if(kbt_>0 && std::abs(kbt_-kB*temp)>1e-4) + if(temp>0) { + if(kbt_>0 && std::abs(kbt_-kB*temp)>1e-4) { log.printf(" +++ WARNING +++ using TEMP=%g while MD engine uses %g\n",temp,kbt_/kB); + } kbt_=kB*temp; } plumed_massert(kbt_>0,"your MD engine does not pass the temperature to plumed, you must specify it using TEMP"); @@ -394,20 +398,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; } @@ -419,35 +420,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; @@ -467,25 +467,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"); @@ -503,8 +502,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; } @@ -518,17 +517,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 @@ -546,32 +544,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; } @@ -582,8 +579,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; @@ -593,31 +589,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"; } @@ -626,61 +616,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; @@ -689,10 +673,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; @@ -702,40 +684,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(); @@ -746,14 +728,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()); @@ -762,42 +745,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"); @@ -805,8 +791,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 @@ -847,13 +835,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"); @@ -866,116 +852,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 @@ -983,57 +982,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); } @@ -1046,90 +1043,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); @@ -1139,111 +1131,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_); @@ -1267,113 +1249,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); @@ -1500,89 +1466,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_); @@ -1591,20 +1553,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); @@ -1615,10 +1574,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"); @@ -1629,23 +1589,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); @@ -1654,8 +1608,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]); @@ -1690,69 +1639,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/HBPammHydrogens.cpp b/src/pamm/HBPammHydrogens.cpp index e4364308de..a0cbf83d9f 100644 --- a/src/pamm/HBPammHydrogens.cpp +++ b/src/pamm/HBPammHydrogens.cpp @@ -54,7 +54,9 @@ class HBPammHydrogens : public multicolvar::MultiColvarBase { // active methods: double compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const override; /// Returns the number of coordinates of the field - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(HBPammHydrogens,"HBPAMM_SH") @@ -82,44 +84,77 @@ void HBPammHydrogens::registerKeywords( Keywords& keys ) { keys.add("compulsory","REGULARISE","0.001","don't allow the denominator to be smaller then this value"); keys.reset_style("CLUSTERS","compulsory"); // Use actionWithDistributionKeywords - keys.use("MEAN"); keys.use("MORE_THAN"); keys.use("LESS_THAN"); keys.use("MAX"); - keys.use("MIN"); keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); - keys.use("ALT_MIN"); keys.use("LOWEST"); keys.use("HIGHEST"); keys.use("SUM"); + keys.use("MEAN"); + keys.use("MORE_THAN"); + keys.use("LESS_THAN"); + keys.use("MAX"); + keys.use("MIN"); + keys.use("BETWEEN"); + keys.use("HISTOGRAM"); + keys.use("MOMENTS"); + keys.use("ALT_MIN"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("SUM"); } HBPammHydrogens::HBPammHydrogens(const ActionOptions&ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { // Read in the atoms - usespecies=true; weightHasDerivatives=false; + usespecies=true; + weightHasDerivatives=false; // Read in hydrogen atom indicees - std::vector all_atoms; parseMultiColvarAtomList("HYDROGENS",-1,all_atoms); - if( atom_lab.size()==0 ) error("no hydrogens specified in input file"); + std::vector all_atoms; + parseMultiColvarAtomList("HYDROGENS",-1,all_atoms); + if( atom_lab.size()==0 ) { + error("no hydrogens specified in input file"); + } // Now create a task list - one task per hydrogen - unsigned nH = atom_lab.size(); for(unsigned i=0; inH ) { - block1upper=atom_lab.size() - nH + 1; block2lower=0; ablocks[0].resize( atom_lab.size() - nH ); - for(unsigned i=nH; i(block1upper+nH-1) || (block1upper-1)>0 ) error("no acceptor donor pairs in input specified therefore no hydrogen bonds"); - for(unsigned i=nH+block2lower-1; i(block1upper+nH-1) || (block1upper-1)>0 ) { + error("no acceptor donor pairs in input specified therefore no hydrogen bonds"); + } + for(unsigned i=nH+block2lower-1; i0 ) error( errormsg ); + if( errormsg.length()>0 ) { + error( errormsg ); + } } else { unsigned nr=nnode_t, nc=nnode_t; hbpamm_obj.resize( nr, nc ); @@ -135,14 +170,19 @@ HBPammHydrogens::HBPammHydrogens(const ActionOptions&ao): } for(unsigned j=i; j0 ) error( errormsg ); + if( errormsg.length()>0 ) { + error( errormsg ); + } } else { hbpamm_obj(i,j).setup( desc, reg, this, errormsg ); hbpamm_obj(j,i).setup( desc, reg, this, errormsg ); - if( errormsg.length()>0 ) error( errormsg ); + if( errormsg.length()>0 ) { + error( errormsg ); + } } } } @@ -153,7 +193,9 @@ HBPammHydrogens::HBPammHydrogens(const ActionOptions&ao): for(unsigned i=0; isfmax ) { sfmax=rcut; } + if( rcut>sfmax ) { + sfmax=rcut; + } } } setLinkCellCutoff( sfmax ); @@ -170,16 +212,22 @@ double HBPammHydrogens::compute( const unsigned& tindex, multicolvar::AtomValueP // Calculate the coordination number for(unsigned i=1; iblock1upper ) continue; + if( i>block1upper ) { + continue; + } for(unsigned j=1; j& myvals ) const { return !(myvals[1]>epsilon); } + bool checkForConnection( const std::vector& myvals ) const { + return !(myvals[1]>epsilon); + } }; PLUMED_REGISTER_ACTION(HBPammMatrix,"HBPAMM_MATRIX") @@ -81,18 +83,19 @@ void HBPammMatrix::registerKeywords( Keywords& keys ) { keys.add("atoms","HYDROGENS","The list of hydrogen atoms that can form part of a hydrogen bond. The atoms must be specified using a comma separated list, " "an index range or by using a \\ref GROUP"); keys.add("numbered","CLUSTERS","the name of the file that contains the definitions of all the kernels for PAMM"); - keys.reset_style("CLUSTERS","compulsory"); keys.use("SUM"); + keys.reset_style("CLUSTERS","compulsory"); + keys.use("SUM"); keys.add("compulsory","REGULARISE","0.001","don't allow the denominator to be smaller then this value"); } HBPammMatrix::HBPammMatrix(const ActionOptions& ao): Action(ao), - AdjacencyMatrixBase(ao) -{ + AdjacencyMatrixBase(ao) { readMaxThreeSpeciesMatrix("SITES", "DONORS", "ACCEPTORS", "HYDROGENS", false ); // Retrieve dimensions of hbonding matrix and resize - unsigned nrows, ncols; retrieveTypeDimensions( nrows, ncols, ndonor_types ); + unsigned nrows, ncols; + retrieveTypeDimensions( nrows, ncols, ndonor_types ); myhb_objs.resize( nrows, ncols ); // Read in the regularisation parameter parse("REGULARISE",regulariser); @@ -104,7 +107,9 @@ HBPammMatrix::HBPammMatrix(const ActionOptions& ao): for(unsigned i=0; isfmax ) { sfmax=rcut; } + if( rcut>sfmax ) { + sfmax=rcut; + } } } setLinkCellCutoff( sfmax ); @@ -112,23 +117,30 @@ HBPammMatrix::HBPammMatrix(const ActionOptions& ao): void HBPammMatrix::setupConnector( const unsigned& id, const unsigned& i, const unsigned& j, const std::vector& desc ) { log.printf(" reading definition of hydrogen bond between between type %u and %u from file %s \n",i,j,desc[0].c_str() ); - plumed_assert( desc.size()==1 ); std::string errors; + plumed_assert( desc.size()==1 ); + std::string errors; if( i==j ) { myhb_objs( i, j ).setup( desc[0], regulariser, this, errors ); } else { myhb_objs( i, j ).setup( desc[0], regulariser, this, errors ); myhb_objs( j, i ).setup( desc[0], regulariser, this, errors ); } - if( errors.length()>0 ) error( errors ); + if( errors.length()>0 ) { + error( errors ); + } } double HBPammMatrix::compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const { - Vector d_da = getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); double md_da = d_da.modulo(); // acceptor - donor + Vector d_da = getSeparation( myatoms.getPosition(0), myatoms.getPosition(1) ); + double md_da = d_da.modulo(); // acceptor - donor // Get the base colvar numbers unsigned ano, dno = getBaseColvarNumber( myatoms.getIndex(0) ); - if( ndonor_types==0 ) ano = getBaseColvarNumber( myatoms.getIndex(1) ); - else ano = getBaseColvarNumber( myatoms.getIndex(1) ) - ndonor_types; + if( ndonor_types==0 ) { + ano = getBaseColvarNumber( myatoms.getIndex(1) ); + } else { + ano = getBaseColvarNumber( myatoms.getIndex(1) ) - ndonor_types; + } double value=0; if( myatoms.getNumberOfAtoms()>3 ) { diff --git a/src/pamm/HBPammObject.cpp b/src/pamm/HBPammObject.cpp index e75f3c12b3..20b9484eab 100644 --- a/src/pamm/HBPammObject.cpp +++ b/src/pamm/HBPammObject.cpp @@ -26,9 +26,13 @@ namespace PLMD { namespace pamm { void HBPammObject::setup( const std::string& filename, const double& reg, multicolvar::MultiColvarBase* mybase, std::string& errorstr ) { - mymulti=mybase; std::vector valnames(3); - valnames[0]="ptc"; valnames[1]="ssc"; valnames[2]="adc"; - std::vector min(3), max(3); std::vector pbc(3, false); + mymulti=mybase; + std::vector valnames(3); + valnames[0]="ptc"; + valnames[1]="ssc"; + valnames[2]="adc"; + std::vector min(3), max(3); + std::vector pbc(3, false); mypamm.setup( filename, reg, valnames, pbc, min, max, errorstr ); } @@ -36,23 +40,31 @@ double HBPammObject::get_cutoff() const { double sfmax=0; for(unsigned k=0; ksfmax ) { sfmax=rcut; } + if( rcut>sfmax ) { + sfmax=rcut; + } } return sfmax; } double HBPammObject::evaluate( const unsigned& dno, const unsigned& ano, const unsigned& hno, const Vector& d_da, const double& md_da, multicolvar::AtomValuePack& myatoms ) const { - Vector d_dh = mymulti->getSeparation( myatoms.getPosition(dno), myatoms.getPosition(hno) ); double md_dh = d_dh.modulo(); // hydrogen - donor - Vector d_ah = mymulti->getSeparation( myatoms.getPosition(ano), myatoms.getPosition(hno) ); double md_ah = d_ah.modulo(); // hydrogen - acceptor + Vector d_dh = mymulti->getSeparation( myatoms.getPosition(dno), myatoms.getPosition(hno) ); + double md_dh = d_dh.modulo(); // hydrogen - donor + Vector d_ah = mymulti->getSeparation( myatoms.getPosition(ano), myatoms.getPosition(hno) ); + double md_ah = d_ah.modulo(); // hydrogen - acceptor // Create some vectors locally for pamm evaluation std::vector invals( 3 ), outvals( mypamm.getNumberOfKernels() ); std::vector > der( mypamm.getNumberOfKernels() ); - for(unsigned i=0; idoNotCalculateDerivatives() ) { diff --git a/src/pamm/PAMM.cpp b/src/pamm/PAMM.cpp index a699c11e53..8dd95be2cc 100644 --- a/src/pamm/PAMM.cpp +++ b/src/pamm/PAMM.cpp @@ -126,7 +126,9 @@ class PAMM : public multicolvar::MultiColvarBase { /// This returns the position of the central atom Vector getCentralAtom(); /// Is the variable periodic - bool isPeriodic() override { return false; } + bool isPeriodic() override { + return false; + } }; PLUMED_REGISTER_ACTION(PAMM,"PAMM") @@ -136,8 +138,18 @@ void PAMM::registerKeywords( Keywords& keys ) { keys.add("compulsory","DATA","the multicolvars from which the pamm coordinates are calculated"); keys.add("compulsory","CLUSTERS","the name of the file that contains the definitions of all the clusters"); keys.add("compulsory","REGULARISE","0.001","don't allow the denominator to be smaller then this value"); - keys.use("MEAN"); keys.use("MORE_THAN"); keys.use("SUM"); keys.use("LESS_THAN"); keys.use("HISTOGRAM"); - keys.use("MIN"); keys.use("MAX"); keys.use("LOWEST"); keys.use("HIGHEST"); keys.use("ALT_MIN"); keys.use("BETWEEN"); keys.use("MOMENTS"); + keys.use("MEAN"); + keys.use("MORE_THAN"); + keys.use("SUM"); + keys.use("LESS_THAN"); + keys.use("HISTOGRAM"); + keys.use("MIN"); + keys.use("MAX"); + keys.use("LOWEST"); + keys.use("HIGHEST"); + keys.use("ALT_MIN"); + keys.use("BETWEEN"); + keys.use("MOMENTS"); keys.setComponentsIntroduction("When the label of this action is used as the input for a second you are not referring to a scalar quantity as you are in " "regular collective variables. The label is used to reference the full set of quantities calculated by " "the action. This is usual when using \\ref multicolvarfunction. Generally when doing this the set of PAMM variables " @@ -158,13 +170,14 @@ void PAMM::registerKeywords( Keywords& keys ) { PAMM::PAMM(const ActionOptions& ao): Action(ao), - MultiColvarBase(ao) -{ + MultiColvarBase(ao) { // This builds the lists buildSets(); // Check for reasonable input for(unsigned i=0; igetNumberOfQuantities()!=2 ) error("cannot use PAMM with " + getBaseMultiColvar(i)->getName() ); + if( getBaseMultiColvar(i)->getNumberOfQuantities()!=2 ) { + error("cannot use PAMM with " + getBaseMultiColvar(i)->getName() ); + } } bool mixed=getBaseMultiColvar(0)->isPeriodic(); @@ -172,16 +185,24 @@ PAMM::PAMM(const ActionOptions& ao): std::vector valnames( getNumberOfBaseMultiColvars() ); std::vector min( getNumberOfBaseMultiColvars() ), max( getNumberOfBaseMultiColvars() ); for(unsigned i=0; iisPeriodic()!=mixed ) warning("mixing of periodic and aperiodic base variables in pamm is untested"); + if( getBaseMultiColvar(i)->isPeriodic()!=mixed ) { + warning("mixing of periodic and aperiodic base variables in pamm is untested"); + } pbc[i]=getBaseMultiColvar(i)->isPeriodic(); - if( pbc[i] ) getBaseMultiColvar(i)->retrieveDomain( min[i], max[i] ); + if( pbc[i] ) { + getBaseMultiColvar(i)->retrieveDomain( min[i], max[i] ); + } valnames[i]=getBaseMultiColvar(i)->getLabel(); } - double regulariser; parse("REGULARISE",regulariser); - std::string errorstr, filename; parse("CLUSTERS",filename); + double regulariser; + parse("REGULARISE",regulariser); + std::string errorstr, filename; + parse("CLUSTERS",filename); mypamm.setup( filename, regulariser, valnames, pbc, min, max, errorstr ); - if( errorstr.length()>0 ) error( errorstr ); + if( errorstr.length()>0 ) { + error( errorstr ); + } } unsigned PAMM::getNumberOfQuantities() const { @@ -191,9 +212,11 @@ unsigned PAMM::getNumberOfQuantities() const { void PAMM::calculateWeight( multicolvar::AtomValuePack& myatoms ) { unsigned nvars = getNumberOfBaseMultiColvars(); // Weight of point is average of weights of input colvars? - std::vector tval(2); double ww=0; + std::vector tval(2); + double ww=0; for(unsigned i=0; i( nvars ) ); @@ -213,17 +236,22 @@ void PAMM::calculateWeight( multicolvar::AtomValuePack& myatoms ) { double PAMM::compute( const unsigned& tindex, multicolvar::AtomValuePack& myatoms ) const { unsigned nvars = getNumberOfBaseMultiColvars(); std::vector > tderiv( mypamm.getNumberOfKernels() ); - for(unsigned i=0; i tval(2), invals( nvars ), vals( mypamm.getNumberOfKernels() ); for(unsigned i=0; i mypref( 1 + vals.size() ); @@ -231,7 +259,9 @@ double PAMM::compute( const unsigned& tindex, multicolvar::AtomValuePack& myatom // Get the values of the derivatives MultiValue& myder = getInputDerivatives( ivar, false, myatoms ); // And calculate the derivatives - for(unsigned i=0; i( in.kernels[i].get() ) ); + max(in.max) { + for(unsigned i=0; i( in.kernels[i].get() ) ); + } } void PammObject::setup( const std::string& filename, const double& reg, const std::vector& valnames, const std::vector& pbcin, const std::vector& imin, const std::vector& imax, std::string& errorstr ) { - IFile ifile; regulariser=reg; + IFile ifile; + regulariser=reg; if( !ifile.FileExist(filename) ) { errorstr = "could not find file named " + filename; return; @@ -54,16 +55,25 @@ void PammObject::setup( const std::string& filename, const double& reg, const st min.resize( valnames.size() ); max.resize( valnames.size() ); for(unsigned i=0; i() ); - if( !pbc[i] ) pos[i]->setNotPeriodic(); - else pos[i]->setDomain( min[i], max[i] ); + if( !pbc[i] ) { + pos[i]->setNotPeriodic(); + } else { + pos[i]->setDomain( min[i], max[i] ); + } } - ifile.open(filename); ifile.allowIgnoredFields(); kernels.resize(0); + ifile.open(filename); + ifile.allowIgnoredFields(); + kernels.resize(0); for(unsigned k=0;; ++k) { std::unique_ptr kk = KernelFunctions::read( &ifile, false, valnames ); - if( !kk ) break ; + if( !kk ) { + break ; + } kk->normalize( Tools::unique2raw( pos ) ); kernels.emplace_back( std::move(kk) ); ifile.scanField(); @@ -75,8 +85,11 @@ void PammObject::evaluate( const std::vector& invar, std::vector std::vector> pos; for(unsigned i=0; i() ); - if( !pbc[i] ) pos[i]->setNotPeriodic(); - else pos[i]->setDomain( min[i], max[i] ); + if( !pbc[i] ) { + pos[i]->setNotPeriodic(); + } else { + pos[i]->setDomain( min[i], max[i] ); + } // And set the value pos[i]->set( invar[i] ); } @@ -85,15 +98,21 @@ void PammObject::evaluate( const std::vector& invar, std::vector auto pos_ptr=Tools::unique2raw(pos); // Evaluate the set of kernels - double denom=regulariser; std::vector dderiv( der[0].size(), 0 ); + double denom=regulariser; + std::vector dderiv( der[0].size(), 0 ); for(unsigned i=0; ievaluate( pos_ptr, der[i] ); denom+=outvals[i]; - for(unsigned j=0; jevaluate( pos_ptr, der[i] ); + denom+=outvals[i]; + for(unsigned j=0; j& valnames, const std::vector& pbcin, const std::vector& imin, const std::vector& imax, diff --git a/src/piv/PIV.cpp b/src/piv/PIV.cpp index 8476f201e9..d65e8bd7e6 100644 --- a/src/piv/PIV.cpp +++ b/src/piv/PIV.cpp @@ -31,10 +31,8 @@ along with plumed. If not, see . using namespace std; -namespace PLMD -{ -namespace piv -{ +namespace PLMD { +namespace piv { //+PLUMEDOC PIVMOD_COLVAR PIV /* @@ -182,8 +180,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; @@ -233,8 +230,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." @@ -292,8 +288,7 @@ PIV::PIV(const ActionOptions&ao): doneigh(false), test(false), CompDer(false), - com(false) -{ + com(false) { log << "Starting PIV Constructor\n"; { @@ -320,7 +315,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; @@ -342,7 +339,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); @@ -362,7 +361,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); @@ -544,9 +545,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(); @@ -951,8 +973,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); @@ -1015,8 +1041,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) -{ //print pytorch version + Function(ao) { + //print pytorch version //number of inputs of the model _n_in=getNumberOfArguments(); @@ -119,8 +118,7 @@ PytorchModel::PytorchModel(const ActionOptions&ao): std::string version; ss >> version; // extract into the string. plumed_merror("Cannot load FILE: '"+fname+"'. Please check that it is a Pytorch compiled model (exported with 'torch.jit.trace' or 'torch.jit.script') and that the Pytorch version matches the LibTorch one ("+version+")."); - } - else { + } else { plumed_merror("The FILE: '"+fname+"' does not exist."); } } @@ -158,8 +156,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}); input_S.set_requires_grad(true); @@ -192,8 +191,9 @@ void PytorchModel::calculate() { 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] ); + } } } } diff --git a/src/reference/ArgumentOnlyDistance.cpp b/src/reference/ArgumentOnlyDistance.cpp index 5d3dd88f59..9671234663 100644 --- a/src/reference/ArgumentOnlyDistance.cpp +++ b/src/reference/ArgumentOnlyDistance.cpp @@ -26,8 +26,7 @@ namespace PLMD { ArgumentOnlyDistance::ArgumentOnlyDistance( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration(ro), - ReferenceArguments(ro) -{ + ReferenceArguments(ro) { } void ArgumentOnlyDistance::read( const PDB& pdb ) { @@ -36,9 +35,13 @@ void ArgumentOnlyDistance::read( const PDB& pdb ) { double ArgumentOnlyDistance::calculate( const std::vector& vals, ReferenceValuePack& myder, const bool& squared ) const { std::vector tmparg( vals.size() ); - for(unsigned i=0; iget(); + for(unsigned i=0; iget(); + } double d=calculateArgumentDistance( vals, tmparg, myder, squared ); - if( !myder.updateComplete() ) myder.updateDynamicLists(); + if( !myder.updateComplete() ) { + myder.updateDynamicLists(); + } return d; } @@ -46,7 +49,9 @@ double ArgumentOnlyDistance::calc( const std::vector& pos, const Pbc& pb ReferenceValuePack& myder, const bool& squared ) const { plumed_dbg_assert( pos.size()==0 ); double d=calculateArgumentDistance( vals, arg, myder, squared ); - if( !myder.updateComplete() ) myder.updateDynamicLists(); + if( !myder.updateComplete() ) { + myder.updateDynamicLists(); + } return d; } diff --git a/src/reference/ArgumentOnlyDistance.h b/src/reference/ArgumentOnlyDistance.h index 28ff5e0e3f..60a2eed061 100644 --- a/src/reference/ArgumentOnlyDistance.h +++ b/src/reference/ArgumentOnlyDistance.h @@ -35,8 +35,12 @@ class ArgumentOnlyDistance : public ReferenceArguments { public: explicit ArgumentOnlyDistance( const ReferenceConfigurationOptions& ro ); void read( const PDB& pdb ) override; - bool pcaIsEnabledForThisReference() override { return true; } - void setupPCAStorage( ReferenceValuePack& mypack ) override { mypack.switchOnPCAOption(); } + bool pcaIsEnabledForThisReference() override { + return true; + } + void setupPCAStorage( ReferenceValuePack& mypack ) override { + mypack.switchOnPCAOption(); + } double calc( const std::vector& pos, const Pbc& pbc, const std::vector& vals, const std::vector& arg, ReferenceValuePack& myder, const bool& squared ) const override; double calculate( const std::vector& vals, ReferenceValuePack& myder, const bool& squared ) const ; }; diff --git a/src/reference/DRMSD.cpp b/src/reference/DRMSD.cpp index 20ceaf6b8c..ce0f51d5b8 100644 --- a/src/reference/DRMSD.cpp +++ b/src/reference/DRMSD.cpp @@ -33,25 +33,35 @@ DRMSD::DRMSD( const ReferenceConfigurationOptions& ro ): nopbc(true), bounds_were_set(false), lower(0), - upper(std::numeric_limits::max( )) -{ + upper(std::numeric_limits::max( )) { } void DRMSD::setBoundsOnDistances( bool dopbc, double lbound, double ubound ) { - bounds_were_set=true; nopbc=!dopbc; - lower=lbound; upper=ubound; + bounds_were_set=true; + nopbc=!dopbc; + lower=lbound; + upper=ubound; } void DRMSD::readBounds( const PDB& pdb ) { - if( bounds_were_set ) return; - double tmp; nopbc=pdb.hasFlag("NOPBC"); - if( pdb.getArgumentValue("LOWER_CUTOFF",tmp) ) lower=tmp; - if( pdb.getArgumentValue("UPPER_CUTOFF",tmp) ) upper=tmp; + if( bounds_were_set ) { + return; + } + double tmp; + nopbc=pdb.hasFlag("NOPBC"); + if( pdb.getArgumentValue("LOWER_CUTOFF",tmp) ) { + lower=tmp; + } + if( pdb.getArgumentValue("UPPER_CUTOFF",tmp) ) { + upper=tmp; + } bounds_were_set=true; } void DRMSD::read( const PDB& pdb ) { - readAtomsFromPDB( pdb ); readBounds( pdb ); setup_targets(); + readAtomsFromPDB( pdb ); + readBounds( pdb ); + setup_targets(); } void DRMSD::setReferenceAtoms( const std::vector& conf, const std::vector& align_in, const std::vector& displace_in ) { @@ -71,7 +81,9 @@ void DRMSD::setup_targets() { } } } - if( targets.empty() ) error("drmsd will compare no distances - check upper and lower bounds are sensible"); + if( targets.empty() ) { + error("drmsd will compare no distances - check upper and lower bounds are sensible"); + } } double DRMSD::calc( const std::vector& pos, const Pbc& pbc, ReferenceValuePack& myder, const bool& squared ) const { @@ -85,8 +97,11 @@ double DRMSD::calc( const std::vector& pos, const Pbc& pbc, ReferenceVal const unsigned i=getAtomIndex( it.first.first ); const unsigned j=getAtomIndex( it.first.second ); - if(nopbc) distance=delta( pos[i], pos[j] ); - else distance=pbc.distance( pos[i], pos[j] ); + if(nopbc) { + distance=delta( pos[i], pos[j] ); + } else { + distance=pbc.distance( pos[i], pos[j] ); + } const double len = distance.modulo(); const double diff = len - it.second; diff --git a/src/reference/Direction.cpp b/src/reference/Direction.cpp index 3ef01af789..180577b766 100644 --- a/src/reference/Direction.cpp +++ b/src/reference/Direction.cpp @@ -30,8 +30,7 @@ Direction::Direction( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration(ro), ReferenceAtoms(ro), ReferenceArguments(ro), - normalized(false) -{ + normalized(false) { } void Direction::read( const PDB& pdb ) { @@ -40,22 +39,38 @@ void Direction::read( const PDB& pdb ) { } void Direction::setDirection( const std::vector& conf, const std::vector& args ) { - std::vector sigma( args.size(), 1.0 ); setReferenceArguments( args, sigma ); - - reference_atoms.resize( conf.size() ); align.resize( conf.size() ); - displace.resize( conf.size() ); atom_der_index.resize( conf.size() ); - for(unsigned i=0; i sigma( args.size(), 1.0 ); + setReferenceArguments( args, sigma ); + + reference_atoms.resize( conf.size() ); + align.resize( conf.size() ); + displace.resize( conf.size() ); + atom_der_index.resize( conf.size() ); + for(unsigned i=0; i& pos, const Pbc& pbc, const std::vector& vals, const std::vector& args, @@ -64,11 +79,15 @@ double Direction::calc( const std::vector& pos, const Pbc& pbc, const st } void Direction::extractArgumentDisplacement( const std::vector& vals, const std::vector& arg, std::vector& dirout ) const { - for(unsigned i=0; i& pos, std::vector& dirout ) const { - for(unsigned i=0; i& conf, const std::vector& args ); void addDirection( const double& weight, const Direction& dir ); - void setReferenceAtoms( const std::vector& conf, const std::vector& align_in, const std::vector& displace_in ) override { plumed_error(); } + void setReferenceAtoms( const std::vector& conf, const std::vector& align_in, const std::vector& displace_in ) override { + plumed_error(); + } /// This allows us to extract the reference positions, which are the direction in this case void extractArgumentDisplacement( const std::vector& vals, const std::vector& arg, std::vector& dirout ) const override; void extractAtomicDisplacement( const std::vector& pos, std::vector& dirout ) const override; diff --git a/src/reference/DotProductDistance.cpp b/src/reference/DotProductDistance.cpp index 8cc2becde5..545f95c5f6 100644 --- a/src/reference/DotProductDistance.cpp +++ b/src/reference/DotProductDistance.cpp @@ -37,8 +37,7 @@ PLUMED_REGISTER_METRIC(DotProductDistance,"DOTPRODUCT") DotProductDistance::DotProductDistance( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration(ro), - ArgumentOnlyDistance(ro) -{ + ArgumentOnlyDistance(ro) { } void DotProductDistance::read( const PDB& pdb ) { @@ -48,9 +47,15 @@ void DotProductDistance::read( const PDB& pdb ) { double DotProductDistance::calculateArgumentDistance( const std::vector & vals, const std::vector& arg, ReferenceValuePack& myder, const bool& squared ) const { double dot=0.0; - for (std::size_t i=0; i::min(); + for (std::size_t i=0; i::min(); + } return -log(dot); } diff --git a/src/reference/EuclideanDistance.cpp b/src/reference/EuclideanDistance.cpp index 2211b5aca8..b9f75527a6 100644 --- a/src/reference/EuclideanDistance.cpp +++ b/src/reference/EuclideanDistance.cpp @@ -33,8 +33,7 @@ PLUMED_REGISTER_METRIC(EuclideanDistance,"EUCLIDEAN") EuclideanDistance::EuclideanDistance( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration(ro), - ArgumentOnlyDistance(ro) -{ + ArgumentOnlyDistance(ro) { } } diff --git a/src/reference/FakeFrame.h b/src/reference/FakeFrame.h index ab886c0b01..99b8f82630 100644 --- a/src/reference/FakeFrame.h +++ b/src/reference/FakeFrame.h @@ -27,11 +27,12 @@ namespace PLMD { class FakeFrame : - public PLMD::ReferenceConfiguration -{ + public PLMD::ReferenceConfiguration { public: explicit FakeFrame( const ReferenceConfigurationOptions& ro ) : ReferenceConfiguration(ro) {} - void read( const PDB& ) override { plumed_merror("should not be called"); } + void read( const PDB& ) override { + plumed_merror("should not be called"); + } double calc( const std::vector& pos, const Pbc& pbc, const std::vector& vals, const std::vector& arg, ReferenceValuePack& myder, const bool& squared ) const override { plumed_merror("should not be called"); } diff --git a/src/reference/IntermolecularDRMSD.cpp b/src/reference/IntermolecularDRMSD.cpp index 3025ed4d09..f9d19f944c 100644 --- a/src/reference/IntermolecularDRMSD.cpp +++ b/src/reference/IntermolecularDRMSD.cpp @@ -39,15 +39,22 @@ PLUMED_REGISTER_METRIC(IntermolecularDRMSD,"INTER-DRMSD") IntermolecularDRMSD::IntermolecularDRMSD( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration( ro ), DRMSD( ro ), - nblocks(0) -{ + nblocks(0) { } void IntermolecularDRMSD::read( const PDB& pdb ) { - readAtomsFromPDB( pdb, true ); nblocks = pdb.getNumberOfAtomBlocks(); blocks.resize( nblocks+1 ); - if( nblocks==1 ) error("Trying to compute intermolecular rmsd but found no TERs in input PDB"); - blocks[0]=0; for(unsigned i=0; i lower ) targets[std::make_pair(iatom,jatom)] = distance; + if(distance < upper && distance > lower ) { + targets[std::make_pair(iatom,jatom)] = distance; + } } } } diff --git a/src/reference/IntramolecularDRMSD.cpp b/src/reference/IntramolecularDRMSD.cpp index 4ae85d0e7f..bc8223df0b 100644 --- a/src/reference/IntramolecularDRMSD.cpp +++ b/src/reference/IntramolecularDRMSD.cpp @@ -39,15 +39,22 @@ PLUMED_REGISTER_METRIC(IntramolecularDRMSD,"INTRA-DRMSD") IntramolecularDRMSD::IntramolecularDRMSD( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration( ro ), DRMSD( ro ), - nblocks(0) -{ + nblocks(0) { } void IntramolecularDRMSD::read( const PDB& pdb ) { - readAtomsFromPDB( pdb, true ); nblocks = pdb.getNumberOfAtomBlocks(); blocks.resize( nblocks+1 ); - if( nblocks==1 ) error("Trying to compute intramolecular rmsd but found no TERs in input PDB"); - blocks[0]=0; for(unsigned i=0; i lower ) targets[std::make_pair(iatom,jatom)] = distance; + if(distance < upper && distance > lower ) { + targets[std::make_pair(iatom,jatom)] = distance; + } } } } diff --git a/src/reference/MahalanobisDistance.cpp b/src/reference/MahalanobisDistance.cpp index 6e90183d36..75585e6e09 100644 --- a/src/reference/MahalanobisDistance.cpp +++ b/src/reference/MahalanobisDistance.cpp @@ -33,8 +33,7 @@ PLUMED_REGISTER_METRIC(MahalanobisDistance,"MAHALANOBIS") MahalanobisDistance::MahalanobisDistance( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration(ro), - ArgumentOnlyDistance(ro) -{ + ArgumentOnlyDistance(ro) { hasmetric=true; } diff --git a/src/reference/MetricRegister.cpp b/src/reference/MetricRegister.cpp index 8abaa2dbd7..506cc34f7d 100644 --- a/src/reference/MetricRegister.cpp +++ b/src/reference/MetricRegister.cpp @@ -27,7 +27,9 @@ namespace PLMD { MetricRegister::~MetricRegister() { 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: ReferenceConfiguration "+ names +" has not been properly unregistered. This might lead to memory leak!!\n"; } } @@ -40,7 +42,8 @@ MetricRegister& metricRegister() { void MetricRegister::remove(creator_pointer f) { for(auto p=m.begin(); p!=m.end(); ++p) { if((*p).second==f) { - m.erase(p); break; + m.erase(p); + break; } } } @@ -51,7 +54,9 @@ void MetricRegister::add( std::string type, creator_pointer f ) { } bool MetricRegister::check(const std::string & type) { - if( m.count(type)>0 ) return true; + if( m.count(type)>0 ) { + return true; + } return false; } diff --git a/src/reference/MetricRegister.h b/src/reference/MetricRegister.h index cd71772826..a663b90def 100644 --- a/src/reference/MetricRegister.h +++ b/src/reference/MetricRegister.h @@ -86,7 +86,9 @@ std::unique_ptr MetricRegister::create( const std::string& type ) { // if this throws, the unique_ptr conf is deleted. // Notice that with the original version of the code (2.4) an error here // would have lead to a memory leak. - if(!ptr ) plumed_merror( type + " metric is not valid in this context"); + if(!ptr ) { + plumed_merror( type + " metric is not valid in this context"); + } // release ownership in order to transfer it to returned pointer conf.release(); // notice that I should pass ptr here rather than conf.release(), diff --git a/src/reference/MultiDomainRMSD.cpp b/src/reference/MultiDomainRMSD.cpp index 760e562a49..d60282a3af 100644 --- a/src/reference/MultiDomainRMSD.cpp +++ b/src/reference/MultiDomainRMSD.cpp @@ -31,31 +31,47 @@ PLUMED_REGISTER_METRIC(MultiDomainRMSD,"MULTI") MultiDomainRMSD::MultiDomainRMSD( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration(ro), ReferenceAtoms(ro), - ftype(ro.getMultiRMSDType()) -{ + ftype(ro.getMultiRMSDType()) { } void MultiDomainRMSD::read( const PDB& pdb ) { unsigned nblocks = pdb.getNumberOfAtomBlocks(); - if( nblocks<2 ) error("multidomain RMSD only has one block of atoms"); + if( nblocks<2 ) { + error("multidomain RMSD only has one block of atoms"); + } - std::vector positions; std::vector align, displace; - std::string num; blocks.resize( nblocks+1 ); blocks[0]=0; - for(unsigned i=0; i positions; + std::vector align, displace; + std::string num; + blocks.resize( nblocks+1 ); + blocks[0]=0; + for(unsigned i=0; i::max( ); - if( pdb.getArgumentValue("LOWER_CUTOFF",tmp) ) lower=tmp; - if( pdb.getArgumentValue("UPPER_CUTOFF",tmp) ) upper=tmp; + if( pdb.getArgumentValue("LOWER_CUTOFF",tmp) ) { + lower=tmp; + } + if( pdb.getArgumentValue("UPPER_CUTOFF",tmp) ) { + upper=tmp; + } bool nopbc=pdb.hasFlag("NOPBC"); - domains.resize(0); weights.resize(0); + domains.resize(0); + weights.resize(0); for(unsigned i=1; i<=nblocks; ++i) { Tools::convert(i,num); if( ftype=="RMSD" ) { // parse("TYPE"+num, ftype ); - lower=0.0; upper=std::numeric_limits::max( ); - if( pdb.getArgumentValue("LOWER_CUTOFF"+num,tmp) ) lower=tmp; - if( pdb.getArgumentValue("UPPER_CUTOFF"+num,tmp) ) upper=tmp; + lower=0.0; + upper=std::numeric_limits::max( ); + if( pdb.getArgumentValue("LOWER_CUTOFF"+num,tmp) ) { + lower=tmp; + } + if( pdb.getArgumentValue("UPPER_CUTOFF"+num,tmp) ) { + upper=tmp; + } nopbc=pdb.hasFlag("NOPBC"); } domains.emplace_back( metricRegister().create( ftype ) ); @@ -74,12 +90,19 @@ void MultiDomainRMSD::read( const PDB& pdb ) { domains[i-1]->setupRMSDObject(); double ww=0; - if( !pdb.getArgumentValue("WEIGHT"+num,ww) ) weights.push_back( 1.0 ); - else weights.push_back( ww ); + if( !pdb.getArgumentValue("WEIGHT"+num,ww) ) { + weights.push_back( 1.0 ); + } else { + weights.push_back( ww ); + } } // And set the atom numbers for this object - indices.resize(0); atom_der_index.resize(0); - for(unsigned i=0; i& conf, const } double MultiDomainRMSD::calculate( const std::vector& pos, const Pbc& pbc, ReferenceValuePack& myder, const bool& squared ) const { - double totd=0.; Tensor tvirial; std::vector mypos; MultiValue tvals( 1, 3*pos.size()+9 ); - ReferenceValuePack tder( 0, getNumberOfAtoms(), tvals ); myder.clear(); + double totd=0.; + Tensor tvirial; + std::vector mypos; + MultiValue tvals( 1, 3*pos.size()+9 ); + ReferenceValuePack tder( 0, getNumberOfAtoms(), tvals ); + myder.clear(); for(unsigned i=0; isetupPCAStorage( tder ); - unsigned n=0; for(unsigned j=blocks[i]; jsetupPCAStorage( tder ); + } + unsigned n=0; + for(unsigned j=blocks[i]; jcalculate( mypos, pbc, tder, true ); // Now merge the derivative @@ -104,24 +140,34 @@ double MultiDomainRMSD::calculate( const std::vector& pos, const Pbc& pb // If PCA copy PCA stuff if( myder.calcUsingPCAOption() ) { unsigned n=0; - if( tder.centeredpos.size()>0 ) myder.rot[i]=tder.rot[0]; + if( tder.centeredpos.size()>0 ) { + myder.rot[i]=tder.rot[0]; + } for(unsigned j=blocks[i]; j0 ) { myder.centeredpos[j]=tder.centeredpos[n]; - for(unsigned p=0; p<3; ++p) for(unsigned q=0; q<3; ++q) myder.DRotDPos(p,q)[j]=tder.DRotDPos(p,q)[n]; + for(unsigned p=0; p<3; ++p) + for(unsigned q=0; q<3; ++q) { + myder.DRotDPos(p,q)[j]=tder.DRotDPos(p,q)[n]; + } } n++; } } // Make sure virial status is set correctly in output derivative pack // This is only done here so I do this by using class friendship - if( tder.virialWasSet() ) myder.boxWasSet=true; + if( tder.virialWasSet() ) { + myder.boxWasSet=true; + } + } + if( !myder.updateComplete() ) { + myder.updateDynamicLists(); } - if( !myder.updateComplete() ) myder.updateDynamicLists(); if( !squared ) { - totd=std::sqrt(totd); double xx=0.5/totd; + totd=std::sqrt(totd); + double xx=0.5/totd; myder.scaleAllDerivatives( xx ); } return totd; @@ -136,7 +182,9 @@ double MultiDomainRMSD::calc( const std::vector& pos, const Pbc& pbc, co bool MultiDomainRMSD::pcaIsEnabledForThisReference() { bool enabled=true; for(unsigned i=0; ipcaIsEnabledForThisReference() ) enabled=false; + if( !domains[i]->pcaIsEnabledForThisReference() ) { + enabled=false; + } } return enabled; } @@ -146,8 +194,12 @@ void MultiDomainRMSD::setupPCAStorage( ReferenceValuePack& mypack ) { mypack.switchOnPCAOption(); mypack.displacement.resize( getNumberOfAtoms() ); mypack.centeredpos.resize( getNumberOfAtoms() ); - mypack.DRotDPos.resize(3,3); mypack.rot.resize( domains.size() ); - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) mypack.DRotDPos(i,j).resize( getNumberOfAtoms() ); + mypack.DRotDPos.resize(3,3); + mypack.rot.resize( domains.size() ); + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + mypack.DRotDPos(i,j).resize( getNumberOfAtoms() ); + } } // Vector MultiDomainRMSD::getAtomicDisplacement( const unsigned& iatom ){ @@ -164,36 +216,61 @@ void MultiDomainRMSD::extractAtomicDisplacement( const std::vector& pos, std::vector mypos, mydir; for(unsigned i=0; iextractAtomicDisplacement( mypos, mydir ); // Extract the direction - n=0; for(unsigned j=blocks[i]; j& vecs, ReferenceValuePack& mypack ) const { - double totd=0.; std::vector tvecs; mypack.clear(); - MultiValue tvals( 1, mypack.getNumberOfDerivatives() ); ReferenceValuePack tder( 0, getNumberOfAtoms(), tvals ); + double totd=0.; + std::vector tvecs; + mypack.clear(); + MultiValue tvals( 1, mypack.getNumberOfDerivatives() ); + ReferenceValuePack tder( 0, getNumberOfAtoms(), tvals ); for(unsigned i=0; isetupPCAStorage( tder ); + tvecs.resize( blocks[i+1] - blocks[i] ); + domains[i]->setupPCAStorage( tder ); if( tder.centeredpos.size()>0 ) { - for(unsigned p=0; p<3; ++p) for(unsigned q=0; q<3; ++q) tder.DRotDPos(p,q).resize( tvecs.size() ); + for(unsigned p=0; p<3; ++p) + for(unsigned q=0; q<3; ++q) { + tder.DRotDPos(p,q).resize( tvecs.size() ); + } } // Extract information from storage pack and put in local pack - if( tder.centeredpos.size()>0 ) tder.rot[0]=mypack.rot[i]; + if( tder.centeredpos.size()>0 ) { + tder.rot[0]=mypack.rot[i]; + } unsigned n=0; for(unsigned j=blocks[i]; j0 ) { tder.centeredpos[n]=mypack.centeredpos[j]; - for(unsigned p=0; p<3; ++p) for(unsigned q=0; q<3; ++q) tder.DRotDPos(p,q)[n]=mypack.DRotDPos(p,q)[j]; + for(unsigned p=0; p<3; ++p) + for(unsigned q=0; q<3; ++q) { + tder.DRotDPos(p,q)[n]=mypack.DRotDPos(p,q)[j]; + } } n++; } - for(unsigned k=n; kprojectAtomicDisplacementOnVector( normalized, tvecs, tder ); @@ -201,7 +278,9 @@ double MultiDomainRMSD::projectAtomicDisplacementOnVector( const bool& normalize // And derivatives mypack.copyScaledDerivatives( 0, weights[i], tvals ); } - if( !mypack.updateComplete() ) mypack.updateDynamicLists(); + if( !mypack.updateComplete() ) { + mypack.updateDynamicLists(); + } return totd; } diff --git a/src/reference/NormalizedEuclideanDistance.cpp b/src/reference/NormalizedEuclideanDistance.cpp index 03cdcac0bc..af08099298 100644 --- a/src/reference/NormalizedEuclideanDistance.cpp +++ b/src/reference/NormalizedEuclideanDistance.cpp @@ -33,8 +33,7 @@ PLUMED_REGISTER_METRIC(NormalizedEuclideanDistance,"NORM-EUCLIDEAN") NormalizedEuclideanDistance::NormalizedEuclideanDistance( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration(ro), - ArgumentOnlyDistance(ro) -{ + ArgumentOnlyDistance(ro) { hasweights=true; } diff --git a/src/reference/OptimalRMSD.cpp b/src/reference/OptimalRMSD.cpp index f680ee9643..acf52bcf3c 100644 --- a/src/reference/OptimalRMSD.cpp +++ b/src/reference/OptimalRMSD.cpp @@ -34,13 +34,19 @@ class OptimalRMSD : public RMSDBase { explicit OptimalRMSD(const ReferenceConfigurationOptions& ro); void read( const PDB& ) override; double calc( const std::vector& pos, ReferenceValuePack& myder, const bool& squared ) const override; - bool pcaIsEnabledForThisReference() override { return true; } - void setupRMSDObject() override { myrmsd.clear(); myrmsd.set(getAlign(),getDisplace(),getReferencePositions(),"OPTIMAL"); } + bool pcaIsEnabledForThisReference() override { + return true; + } + void setupRMSDObject() override { + myrmsd.clear(); + myrmsd.set(getAlign(),getDisplace(),getReferencePositions(),"OPTIMAL"); + } void setupPCAStorage( ReferenceValuePack& mypack ) override { mypack.switchOnPCAOption(); mypack.centeredpos.resize( getNumberOfAtoms() ); mypack.displacement.resize( getNumberOfAtoms() ); - mypack.DRotDPos.resize(3,3); mypack.rot.resize(1); + mypack.DRotDPos.resize(3,3); + mypack.rot.resize(1); } void extractAtomicDisplacement( const std::vector& pos, std::vector& direction ) const override; double projectAtomicDisplacementOnVector( const bool& normalized, const std::vector& vecs, ReferenceValuePack& mypack ) const override; @@ -50,13 +56,13 @@ PLUMED_REGISTER_METRIC(OptimalRMSD,"OPTIMAL") OptimalRMSD::OptimalRMSD(const ReferenceConfigurationOptions& ro ): ReferenceConfiguration(ro), - RMSDBase(ro) -{ + RMSDBase(ro) { fast=ro.usingFastOption(); } void OptimalRMSD::read( const PDB& pdb ) { - readReference( pdb ); setupRMSDObject(); + readReference( pdb ); + setupRMSDObject(); } double OptimalRMSD::calc( const std::vector& pos, ReferenceValuePack& myder, const bool& squared ) const { @@ -65,52 +71,87 @@ double OptimalRMSD::calc( const std::vector& pos, ReferenceValuePack& my std::vector centeredreference( getNumberOfAtoms () ); d=myrmsd.calc_PCAelements(pos,myder.getAtomVector(),myder.rot[0],myder.DRotDPos,myder.getAtomsDisplacementVector(),myder.centeredpos,centeredreference,squared); unsigned nat = pos.size(); - for(unsigned i=0; i(getAlign(),getDisplace(),pos,getReferencePositions(),myder.getAtomVector(),squared); - else d=myrmsd.optimalAlignment(getAlign(),getDisplace(),pos,getReferencePositions(),myder.getAtomVector(),squared); + if( getAlign()==getDisplace() ) { + d=myrmsd.optimalAlignment(getAlign(),getDisplace(),pos,getReferencePositions(),myder.getAtomVector(),squared); + } else { + d=myrmsd.optimalAlignment(getAlign(),getDisplace(),pos,getReferencePositions(),myder.getAtomVector(),squared); + } } else { - if( getAlign()==getDisplace() ) d=myrmsd.optimalAlignment(getAlign(),getDisplace(),pos,getReferencePositions(),myder.getAtomVector(),squared); - else d=myrmsd.optimalAlignment(getAlign(),getDisplace(),pos,getReferencePositions(),myder.getAtomVector(),squared); + if( getAlign()==getDisplace() ) { + d=myrmsd.optimalAlignment(getAlign(),getDisplace(),pos,getReferencePositions(),myder.getAtomVector(),squared); + } else { + d=myrmsd.optimalAlignment(getAlign(),getDisplace(),pos,getReferencePositions(),myder.getAtomVector(),squared); + } + } + myder.clear(); + for(unsigned i=0; i& pos, std::vector& direction ) const { - std::vector rot(1); Matrix > DRotDPos( 3, 3 ); + std::vector rot(1); + Matrix > DRotDPos( 3, 3 ); std::vector centeredreference( getNumberOfAtoms() ), centeredpos( getNumberOfAtoms() ), avector( getNumberOfAtoms() ); myrmsd.calc_PCAelements(pos,avector,rot[0],DRotDPos,direction,centeredpos,centeredreference,true); - unsigned nat = pos.size(); for(unsigned i=0; i& vecs, ReferenceValuePack& mypack ) const { plumed_dbg_assert( mypack.calcUsingPCAOption() ); - double proj=0.0; mypack.clear(); + double proj=0.0; + mypack.clear(); for(unsigned i=0; i( getNumberOfAtoms() ); - for(unsigned n=0; n( getNumberOfAtoms() ); + for(unsigned n=0; n& pos, ReferenceValuePack& myder, const bool& squared ) const { diff --git a/src/reference/ReferenceArguments.cpp b/src/reference/ReferenceArguments.cpp index 15d70732c1..b9f8a41f3e 100644 --- a/src/reference/ReferenceArguments.cpp +++ b/src/reference/ReferenceArguments.cpp @@ -30,32 +30,42 @@ namespace PLMD { ReferenceArguments::ReferenceArguments( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration(ro), hasweights(false), - hasmetric(false) -{ + hasmetric(false) { } void ReferenceArguments::readArgumentsFromPDB( const PDB& pdb ) { ReferenceAtoms* aref=dynamic_cast( this ); arg_names.resize( pdb.getArgumentNames().size() ); - for(unsigned i=0; i& arg_v unsigned k=0; for(unsigned i=0; i& arg_vals ) { plumed_dbg_assert( reference_args.size()==arg_vals.size() ); - for(unsigned i=0; i& argout, bool disable_checks ) { @@ -102,19 +120,28 @@ void ReferenceArguments::getArgumentRequests( std::vector& argout, } } else { if(!disable_checks) { - if( arg_names.size()!=argout.size() ) error("mismatched numbers of arguments in pdb frames"); + if( arg_names.size()!=argout.size() ) { + error("mismatched numbers of arguments in pdb frames"); + } } for(unsigned i=0; i& argout, const std::vector& ReferenceArguments::getReferenceMetric() { if( hasmetric ) { unsigned ntot=(reference_args.size() / 2 )*(reference_args.size()+1); - if( trig_metric.size()!=ntot ) trig_metric.resize( ntot ); + if( trig_metric.size()!=ntot ) { + trig_metric.resize( ntot ); + } unsigned k=0; for(unsigned i=0; i & vals, const std::vector& arg, ReferenceValuePack& myder, const bool& squared ) const { - double r=0; std::vector arg_ders( vals.size() ); + double r=0; + std::vector arg_ders( vals.size() ); if( hasmetric ) { for(unsigned i=0; idifference( reference_args[i], arg[ik] ); for(unsigned j=0; jdifference( reference_args[j], arg[jk] ); + if(i==j) { + dp_j=dp_i; + } else { + dp_j=vals[jk]->difference( reference_args[j], arg[jk] ); + } arg_ders[ ik ]+=2.0*metric(i,j)*dp_j; // Factor of two for off diagonal terms as you have terms from ij and ji r+=dp_i*dp_j*metric(i,j); @@ -160,14 +199,20 @@ double ReferenceArguments::calculateArgumentDistance( const std::vector for(unsigned i=0; idifference( reference_args[i], arg[ik] ); - r+=weights[i]*dp_i*dp_i; arg_ders[ik]=2.0*weights[i]*dp_i; + r+=weights[i]*dp_i*dp_i; + arg_ders[ik]=2.0*weights[i]*dp_i; } } if(!squared) { - r=std::sqrt(r); double ir=1.0/(2.0*r); - for(unsigned i=0; i& plumed_error(); } else { for(unsigned j=0; jdifference( reference_args[j], arg[jk] ); + unsigned jk=arg_der_index[j]; + dirout[jk]=sqrtweight[j]*vals[jk]->difference( reference_args[j], arg[jk] ); } } } @@ -198,7 +244,9 @@ double ReferenceArguments::projectArgDisplacementOnVector( const std::vector& displace ) { plumed_dbg_assert( displace.size()==getNumberOfReferenceArguments() ); - for(unsigned i=0; i& numbers, boo } } else { if(!disable_checks) { - if( numbers.size()!=indices.size() ) error("mismatched numbers of atoms in pdb frames"); + if( numbers.size()!=indices.size() ) { + error("mismatched numbers of atoms in pdb frames"); + } } for(unsigned i=0; i& numbers, boo void ReferenceAtoms::displaceReferenceAtoms( const double& weight, const std::vector& dir ) { plumed_dbg_assert( dir.size()==reference_atoms.size() ); - for(unsigned i=0; i& pos, const Pbc& pbc, const std::vector& vals, ReferenceValuePack& myder, const bool& squared ) const { std::vector tmparg( vals.size() ); - for(unsigned i=0; iget(); + for(unsigned i=0; iget(); + } return calc( pos, pbc, vals, tmparg, myder, squared ); } void ReferenceConfiguration::displaceReferenceConfiguration( const double& weight, Direction& dir ) { ReferenceArguments* args=dynamic_cast(this); - if( args ) args->displaceReferenceArguments( weight, dir.getReferenceArguments() ); + if( args ) { + args->displaceReferenceArguments( weight, dir.getReferenceArguments() ); + } ReferenceAtoms* atoms=dynamic_cast(this); - if( atoms ) atoms->displaceReferenceAtoms( weight, dir.getReferencePositions() ); + if( atoms ) { + atoms->displaceReferenceAtoms( weight, dir.getReferencePositions() ); + } } void ReferenceConfiguration::extractDisplacementVector( const std::vector& pos, const std::vector& vals, const std::vector& arg, const bool& nflag, Direction& mydir ) const { const ReferenceAtoms* atoms=dynamic_cast( this ); - if( atoms ) atoms->extractAtomicDisplacement( pos, mydir.reference_atoms ); + if( atoms ) { + atoms->extractAtomicDisplacement( pos, mydir.reference_atoms ); + } const ReferenceArguments* args=dynamic_cast( this ); - if( args ) args->extractArgumentDisplacement( vals, arg, mydir.reference_args ); + if( args ) { + args->extractArgumentDisplacement( vals, arg, mydir.reference_args ); + } // Normalize direction if required if( nflag ) { // Calculate length of vector - double tmp, norm=0; mydir.normalized = true; + double tmp, norm=0; + mydir.normalized = true; for(unsigned i=0; i( this ); - if( atoms ) proj += atoms->projectAtomicDisplacementOnVector( mydir.normalized, mydir.getReferencePositions(), mypack ); + if( atoms ) { + proj += atoms->projectAtomicDisplacementOnVector( mydir.normalized, mydir.getReferencePositions(), mypack ); + } const ReferenceArguments* args=dynamic_cast( this ); - if( args ) proj += args->projectArgDisplacementOnVector( mydir.getReferenceArguments(), vals, arg, mypack ); + if( args ) { + proj += args->projectArgDisplacementOnVector( mydir.getReferenceArguments(), vals, arg, mypack ); + } return proj; } double distance( const Pbc& pbc, const std::vector & vals, ReferenceConfiguration* ref1, ReferenceConfiguration* ref2, const bool& squared ) { unsigned nder; - if( ref1->getReferencePositions().size()>0 ) nder=ref1->getReferenceArguments().size() + 3*ref1->getReferencePositions().size() + 9; - else nder=ref1->getReferenceArguments().size(); + if( ref1->getReferencePositions().size()>0 ) { + nder=ref1->getReferenceArguments().size() + 3*ref1->getReferencePositions().size() + 9; + } else { + nder=ref1->getReferenceArguments().size(); + } - MultiValue myvals( 1, nder ); ReferenceValuePack myder( ref1->getReferenceArguments().size(), ref1->getReferencePositions().size(), myvals ); + MultiValue myvals( 1, nder ); + ReferenceValuePack myder( ref1->getReferenceArguments().size(), ref1->getReferencePositions().size(), myvals ); double dist1=ref1->calc( ref2->getReferencePositions(), pbc, vals, ref2->getReferenceArguments(), myder, squared ); #ifndef NDEBUG // Check that A - B = B - A diff --git a/src/reference/ReferenceConfiguration.h b/src/reference/ReferenceConfiguration.h index d752ce3f63..3e064cb531 100644 --- a/src/reference/ReferenceConfiguration.h +++ b/src/reference/ReferenceConfiguration.h @@ -111,7 +111,9 @@ class ReferenceConfiguration { /// Copy derivatives from one frame to this frame void copyDerivatives( const ReferenceConfiguration* ); /// Get one of the referene arguments - virtual double getReferenceArgument( const unsigned& i ) const { plumed_error(); } + virtual double getReferenceArgument( const unsigned& i ) const { + plumed_error(); + } /// These are overwritten in ReferenceArguments and ReferenceAtoms but are required here /// to make PLMD::distance work virtual const std::vector& getReferencePositions() const ; @@ -125,11 +127,15 @@ class ReferenceConfiguration { const std::vector& arg, const bool& nflag, Direction& mydir ) const ; /// Stuff for pca - virtual bool pcaIsEnabledForThisReference() { return false; } + virtual bool pcaIsEnabledForThisReference() { + return false; + } double projectDisplacementOnVector( const Direction& mydir, const std::vector& vals, const std::vector& arg, ReferenceValuePack& mypack ) const ; /// Stuff to setup pca - virtual void setupPCAStorage( ReferenceValuePack& mypack ) { plumed_error(); } + virtual void setupPCAStorage( ReferenceValuePack& mypack ) { + plumed_error(); + } /// Move the reference configuration by an amount specified using a Direction void displaceReferenceConfiguration( const double& weight, Direction& dir ); }; diff --git a/src/reference/ReferenceValuePack.cpp b/src/reference/ReferenceValuePack.cpp index d3cacac992..ea0005992d 100644 --- a/src/reference/ReferenceValuePack.cpp +++ b/src/reference/ReferenceValuePack.cpp @@ -29,24 +29,34 @@ ReferenceValuePack::ReferenceValuePack( const unsigned& nargs, const unsigned& n oind_set(false), myvals(vals), atom_indices(myvals.getIndices()), - pca(false) -{ - if( atom_indices.size()!=natoms ) { atom_indices.resize( natoms ); myvals.getAtomVector().resize( natoms ); } - if( vals.getNumberOfValues()==1 ) { oind=0; oind_set=true; } + pca(false) { + if( atom_indices.size()!=natoms ) { + atom_indices.resize( natoms ); + myvals.getAtomVector().resize( natoms ); + } + if( vals.getNumberOfValues()==1 ) { + oind=0; + oind_set=true; + } } void ReferenceValuePack::resize( const unsigned& nargs, const unsigned& natoms ) { - numberOfArgs=nargs; atom_indices.resize( natoms ); + numberOfArgs=nargs; + atom_indices.resize( natoms ); myvals.getAtomVector().resize( natoms ); } void ReferenceValuePack::updateDynamicLists() { myvals.emptyActiveMembers(); - for(unsigned i=0; i0 ); - boxWasSet=true; unsigned nbase = myvals.getNumberOfDerivatives() - 9; - for(unsigned i=0; i<3; ++i) for(unsigned j=0; j<3; ++j) myvals.addDerivative( oind, nbase + 3*i + j, vir(i,j) ); + boxWasSet=true; + unsigned nbase = myvals.getNumberOfDerivatives() - 9; + for(unsigned i=0; i<3; ++i) + for(unsigned j=0; j<3; ++j) { + myvals.addDerivative( oind, nbase + 3*i + j, vir(i,j) ); + } } inline void ReferenceValuePack::setValIndex( const unsigned& ind ) { - oind=ind; oind_set=true; + oind=ind; + oind_set=true; } inline @@ -183,7 +191,8 @@ bool ReferenceValuePack::virialWasSet() const { inline Vector ReferenceValuePack::getAtomDerivative( const unsigned& iatom ) const { - Vector tmp; plumed_dbg_assert( oind_set && iatom& pos, ReferenceValuePack& myder, const bool& squared ) const override; - bool pcaIsEnabledForThisReference() override { return true; } + bool pcaIsEnabledForThisReference() override { + return true; + } void setupPCAStorage( ReferenceValuePack& mypack ) override { - mypack.switchOnPCAOption(); mypack.getAtomsDisplacementVector().resize( getNumberOfAtoms() ); + mypack.switchOnPCAOption(); + mypack.getAtomsDisplacementVector().resize( getNumberOfAtoms() ); } void extractAtomicDisplacement( const std::vector& pos, std::vector& direction ) const override; double projectAtomicDisplacementOnVector( const bool& normalized, const std::vector& vecs, ReferenceValuePack& mypack ) const override; @@ -44,8 +47,7 @@ PLUMED_REGISTER_METRIC(SimpleRMSD,"SIMPLE") SimpleRMSD::SimpleRMSD( const ReferenceConfigurationOptions& ro ): ReferenceConfiguration( ro ), - RMSDBase( ro ) -{ + RMSDBase( ro ) { } void SimpleRMSD::read( const PDB& pdb ) { @@ -53,33 +55,49 @@ void SimpleRMSD::read( const PDB& pdb ) { } double SimpleRMSD::calc( const std::vector& pos, ReferenceValuePack& myder, const bool& squared ) const { - if( myder.getAtomsDisplacementVector().size()!=pos.size() ) myder.getAtomsDisplacementVector().resize( pos.size() ); + if( myder.getAtomsDisplacementVector().size()!=pos.size() ) { + myder.getAtomsDisplacementVector().resize( pos.size() ); + } double d=myrmsd.simpleAlignment( getAlign(), getDisplace(), pos, getReferencePositions(), myder.getAtomVector(), myder.getAtomsDisplacementVector(), squared ); - myder.clear(); for(unsigned i=0; i& pos, std::vector& direction ) const { std::vector tder( getNumberOfAtoms() ); myrmsd.simpleAlignment( getAlign(), getDisplace(), pos, getReferencePositions(), tder, direction, true ); - for(unsigned i=0; i& vecs, ReferenceValuePack& mypack ) const { - plumed_dbg_assert( mypack.calcUsingPCAOption() ); Vector comder; comder.zero(); + plumed_dbg_assert( mypack.calcUsingPCAOption() ); + Vector comder; + comder.zero(); for(unsigned j=0; jepsilon) { double w=1.0/wa; - for(unsigned i=0; iepsilon) { double w=1.0/wd; - for(unsigned i=0; i& conf, const std::vector& align_in, const std::vector& displace_in ) { - reference_atoms.resize( conf.size() ); align.resize( conf.size() ); - displace.resize( conf.size() ); atom_der_index.resize( conf.size() ); + reference_atoms.resize( conf.size() ); + align.resize( conf.size() ); + displace.resize( conf.size() ); + atom_der_index.resize( conf.size() ); double wa=0, wd=0; - for(unsigned i=0; iepsilon) { double w=1.0/wa; - for(unsigned i=0; iepsilon) { double w=1.0/wd; - for(unsigned i=0; i(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); } @@ -201,15 +203,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; } } @@ -282,7 +289,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 3d421f9b08..1859ac9cfa 100644 --- a/src/sasa/sasa_HASEL.cpp +++ b/src/sasa/sasa_HASEL.cpp @@ -181,32 +181,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(), @@ -248,7 +258,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(); @@ -586,9 +598,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 0d5bf5d08c..a4ef8cb475 100755 --- a/src/sasa/sasa_LCPO.cpp +++ b/src/sasa/sasa_LCPO.cpp @@ -179,32 +179,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(), @@ -245,7 +255,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(); @@ -552,9 +564,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; @@ -1046,14 +1069,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; @@ -1065,7 +1092,9 @@ void SASA_LCPO::calculate() { } - for(unsigned i=0; i chains; readBackboneAtoms( "protein", chains); + std::vector chains; + readBackboneAtoms( "protein", chains); // This constructs all conceivable sections of alpha helix in the backbone of the chains - unsigned nprevious=0; std::vector nlist(30); + unsigned nprevious=0; + std::vector nlist(30); for(unsigned i=0; i chains; readBackboneAtoms( "protein", chains ); + std::vector chains; + readBackboneAtoms( "protein", chains ); bool intra_chain(false), inter_chain(false); - std::string style; parse("STYLE",style); + std::string style; + parse("STYLE",style); if( style=="all" ) { - intra_chain=true; inter_chain=true; + intra_chain=true; + inter_chain=true; } else if( style=="inter") { - intra_chain=false; inter_chain=true; + intra_chain=false; + inter_chain=true; } else if( 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"); } @@ -127,12 +131,17 @@ AntibetaRMSD::AntibetaRMSD(const ActionOptions&ao): // 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; ichain chains; readBackboneAtoms( "protein", chains ); + std::vector chains; + readBackboneAtoms( "protein", chains ); bool intra_chain(false), inter_chain(false); - std::string style; parse("STYLE",style); + std::string style; + parse("STYLE",style); if( style=="all" ) { - intra_chain=true; inter_chain=true; + intra_chain=true; + inter_chain=true; } else if( style=="inter") { - intra_chain=false; inter_chain=true; + intra_chain=false; + inter_chain=true; } else if( 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"); } @@ -128,12 +132,17 @@ ParabetaRMSD::ParabetaRMSD(const ActionOptions&ao): // 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) log.printf(" ignoring contributions from strands that are more than %f apart\n",s_cutoff); + parse("STRANDS_CUTOFF",s_cutoff); + align_strands=true; + if( s_cutoff>0) { + log.printf(" ignoring contributions from strands that are more than %f apart\n",s_cutoff); + } s_cutoff2=s_cutoff*s_cutoff; } } @@ -105,21 +113,28 @@ void SecondaryStructureRMSD::turnOnDerivatives() { } void SecondaryStructureRMSD::setAtomsFromStrands( const unsigned& atom1, const unsigned& atom2 ) { - align_atom_1=atom1; align_atom_2=atom2; + align_atom_1=atom1; + align_atom_2=atom2; } void SecondaryStructureRMSD::readBackboneAtoms( const std::string& moltype, std::vector& chain_lengths ) { auto* moldat=plumed.getActionSet().selectLatest(this); - if( ! moldat ) error("Unable to find MOLINFO in input"); + if( ! moldat ) { + error("Unable to find MOLINFO in input"); + } - std::vector resstrings; parseVector( "RESIDUES", resstrings ); + std::vector resstrings; + parseVector( "RESIDUES", resstrings ); if( !verbose_output ) { - if(resstrings.size()==0) error("residues are not defined, check the keyword RESIDUES"); - else if(resstrings[0]=="all") { + if(resstrings.size()==0) { + error("residues are not defined, check the keyword RESIDUES"); + } else if(resstrings[0]=="all") { log.printf(" examining all possible secondary structure combinations\n"); } else { log.printf(" examining secondary structure in residue positions : %s \n",resstrings[0].c_str() ); - for(unsigned i=1; i& newatoms ) { - if( colvar_atoms.size()>0 ) plumed_assert( colvar_atoms[0].size()==newatoms.size() ); + if( colvar_atoms.size()>0 ) { + plumed_assert( colvar_atoms[0].size()==newatoms.size() ); + } if( verbose_output ) { log.printf(" Secondary structure segment %u contains atoms : ", static_cast(colvar_atoms.size()+1)); - for(unsigned i=0; i& structu // Convert into correct units for(unsigned i=0; i& structu // And prepare the task list deactivateAllTasks(); - for(unsigned i=0; i pos( references[0]->getNumberOfAtoms() ); const unsigned n=pos.size(); - for(unsigned i=0; i0 ) { if( distance.modulo2()>s_cutoff2 ) { myvals.setValue( 0, 0.0 ); @@ -217,7 +254,8 @@ void SecondaryStructureRMSD::performTask( const unsigned& task_index, const unsi Vector & second (pos[i+1]); second=first+pbcDistance(first,second); } - Vector origin_old, origin_new; origin_old=pos[align_atom_2]; + Vector origin_old, origin_new; + origin_old=pos[align_atom_2]; origin_new=pos[align_atom_1]+distance; for(unsigned i=15; i<30; ++i) { pos[i]+=( origin_new - origin_old ); @@ -230,8 +268,11 @@ void SecondaryStructureRMSD::performTask( const unsigned& task_index, const unsi } } // Create a holder for the derivatives - ReferenceValuePack mypack( 0, pos.size(), myvals ); mypack.setValIndex( 1 ); - for(unsigned i=0; icalculate( pos, pbc, mypack, false ); - if( nr0 ) mypack.moveDerivatives( closest+1, 1 ); + myvals.setValue( 0, 1.0 ); + myvals.setValue( 1, r ); + if( closest>0 ) { + mypack.moveDerivatives( closest+1, 1 ); + } if( !mypack.virialWasSet() ) { Tensor vir; @@ -254,14 +301,17 @@ void SecondaryStructureRMSD::performTask( const unsigned& task_index, const unsi for(unsigned i=0; i0) 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/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/Citations.cpp b/src/tools/Citations.cpp index 25f41cf355..2f4a06ca00 100644 --- a/src/tools/Citations.cpp +++ b/src/tools/Citations.cpp @@ -28,8 +28,13 @@ namespace PLMD { std::string Citations::cite(const std::string & item) { unsigned i; - for(i=0; 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 2319f8caa9..2b060e484c 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 ) { 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 std::vector DynamicList::retrieveActiveList() { std::vector this_active(nactive); - for(unsigned k=0; k void DynamicList::clear() { all.resize(0); - onoff.resize(0); active.resize(0); + onoff.resize(0); + active.resize(0); } template @@ -237,25 +240,31 @@ unsigned DynamicList::getNumberActive() const { template void DynamicList::addIndexToList( const T & ii ) { - all.push_back(ii); active.resize( all.size() ); onoff.push_back(0); + all.push_back(ii); + active.resize( all.size() ); + onoff.push_back(0); } template void DynamicList::createIndexListFromVector( const std::vector& myind ) { - plumed_dbg_assert( all.size()==0 ); onoff.resize( myind.size(), 0 ); + plumed_dbg_assert( all.size()==0 ); + onoff.resize( myind.size(), 0 ); active.resize( myind.size() ); all.insert( all.end(), myind.begin(), myind.end() ); } template void DynamicList::setupMPICommunication( Communicator& comm ) { - nprocessors=comm.Get_size(); rank=comm.Get_rank(); + nprocessors=comm.Get_size(); + rank=comm.Get_rank(); } template int DynamicList::getIndexOfElement( const T& t ) const { for(unsigned i=0; i void DynamicList::deactivate( const T& t ) { plumed_dbg_assert( allWereActivated ); unsigned ii=getIndexOfElement( t ); - if( onoff[ii]==0 || onoff[ii]%nprocessors!=0 ) return; + if( onoff[ii]==0 || onoff[ii]%nprocessors!=0 ) { + return; + } // Deactivates the component - if( rank==0 ) onoff[ii]=nprocessors-1; - else onoff[ii]=nprocessors-rank; + if( rank==0 ) { + onoff[ii]=nprocessors-1; + } else { + onoff[ii]=nprocessors-rank; + } } template void DynamicList::deactivateAll() { - allWereDeactivated=true; allWereActivated=false; - for(unsigned i=0; i::activate( const unsigned ii ) { template void DynamicList::activateAll() { - for(unsigned i=0; i::mpi_gatherActiveMembers(Communicator& comm) { plumed_massert( comm.Get_size()==nprocessors, "error missing a call to DynamicList::setupMPICommunication"); comm.Sum(&onoff[0],onoff.size()); // When we mpi gather onoff to be on it should be active on ALL nodes - for(unsigned i=0; i0 && onoff[i]%nprocessors==0 ) { onoff[i]=nprocessors; } + for(unsigned i=0; i0 && onoff[i]%nprocessors==0 ) { + onoff[i]=nprocessors; + } updateActiveMembers(); } template void DynamicList::updateActiveMembers() { plumed_dbg_assert( allWereActivated || allWereDeactivated ); - unsigned kk=0; allWereActivated=allWereDeactivated=false; + unsigned kk=0; + allWereActivated=allWereDeactivated=false; for(unsigned i=0; i0 && onoff[i]%nprocessors==0 ) { active[kk]=i; kk++; } + if( onoff[i]>0 && onoff[i]%nprocessors==0 ) { + active[kk]=i; + kk++; + } } nactive=kk; } @@ -323,7 +353,8 @@ template void DynamicList::putIndexInActiveArray( const unsigned& ii ) { plumed_dbg_assert( allWereActivated || allWereDeactivated ); plumed_dbg_assert( onoff[ii]>0 && onoff[ii]%nprocessors==0 ); - active[nactive]=ii; nactive++; + active[nactive]=ii; + nactive++; } template @@ -341,14 +372,17 @@ void DynamicList::sortActiveList() { template bool DynamicList::updateComplete() const { - if( !allWereActivated && !allWereDeactivated ) return true; + if( !allWereActivated && !allWereDeactivated ) { + return true; + } return false; } template void mpi_gatherActiveMembers(Communicator& comm, std::vector< DynamicList >& ll ) { // Setup an array to hold all data - unsigned bufsize=0; unsigned size=comm.Get_size(); + unsigned bufsize=0; + unsigned size=comm.Get_size(); for(unsigned i=0; i >& // Gather all onoff data into a single array bufsize=0; for(unsigned i=0; i >& bufsize=0; for(unsigned i=0; i0 && buffer[bufsize]%size==0 ) ll[i].onoff[j]=size; - else ll[i].onoff[j]=size-1; + if( buffer[bufsize]>0 && buffer[bufsize]%size==0 ) { + ll[i].onoff[j]=size; + } else { + ll[i].onoff[j]=size-1; + } bufsize++; } } - for(unsigned i=0; i & 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 (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 0792da371a..439be552ec 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 9e656eb022..b8cd6ce795 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=[](FILE* f) { if(f) std::fclose(f); }; + auto deleter=[](FILE* 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 db7bbdceca..929e85ad53 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 a533715ce9..7e6e1fee09 100644 --- a/src/tools/Grid.cpp +++ b/src/tools/Grid.cpp @@ -88,7 +88,8 @@ void GridBase::Init(const std::string& funcl, const std::vector &na plumed_massert(names.size()==nbin.size(),"grid dimensions in input do not match number of arguments"); plumed_massert(names.size()==gmax.size(),"grid dimensions in input do not match number of arguments"); dimension_=gmax.size(); - str_min_=gmin; str_max_=gmax; + str_min_=gmin; + str_max_=gmax; argnames.resize( dimension_ ); min_.resize( dimension_ ); max_.resize( dimension_ ); @@ -111,11 +112,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]; } } @@ -138,7 +144,9 @@ double GridBase::getDx(index_t j) const { double GridBase::getBinVolume() const { double vol=1.; - for(unsigned i=0; i GridBase::getIndices(index_t index) const { } void GridBase::getIndices(index_t index, std::vector& indices) const { - if (indices.size()!=dimension_) indices.resize(dimension_); + if (indices.size()!=dimension_) { + indices.resize(dimension_); + } index_t kk=index; indices[0]=(index%nbin_[0]); for(unsigned int i=1; i GridBase::getIndices(const std::vector & x) const void GridBase::getIndices(const std::vector & x, std::vector& indices) const { plumed_dbg_assert(x.size()==dimension_); - if (indices.size()!=dimension_) indices.resize(dimension_); + if (indices.size()!=dimension_) { + indices.resize(dimension_); + } for(unsigned int i=0; i GridBase::getNeighbors(const std::vector=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++; } tmp_indices.resize(ll); - if(tmp_indices.size()==dimension_) {neighbors.push_back(getIndex(tmp_indices));} + if(tmp_indices.size()==dimension_) { + neighbors.push_back(getIndex(tmp_indices)); + } } return neighbors; } @@ -315,20 +337,30 @@ std::vector GridBase::getNeighbors(index_t index,const std::v void GridBase::getSplineNeighbors(const std::vector & indices, std::vector& neighbors, unsigned& nneighbors)const { plumed_dbg_assert(indices.size()==dimension_); unsigned nneigh=unsigned(std::pow(2.0,int(dimension_))); - if (neighbors.size()!=nneigh) neighbors.resize(nneigh); + if (neighbors.size()!=nneigh) { + neighbors.resize(nneigh); + } std::vector nindices(dimension_); - unsigned inind; nneighbors = 0; + unsigned inind; + nneighbors = 0; 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 ); + } } } @@ -414,13 +451,17 @@ double GridBase::getValueAndDerivatives(const std::vector & x, std::vect std::vector dder(dimension_); // reset value=0.0; - for(unsigned int i=0; i indices(dimension_); getIndices(x, indices); std::vector xfloor(dimension_); getPoint(indices, xfloor); - std::vector neigh; unsigned nneigh; getSplineNeighbors(indices, neigh, nneigh); + std::vector neigh; + unsigned nneigh; + getSplineNeighbors(indices, neigh, nneigh); // loop over neighbors std::vector nindices; @@ -431,14 +472,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(); + for(unsigned i=0; igetName(); + } // And read the stuff from the header plumed_massert( ifile.FieldExist( funcl ), "no column labelled " + funcl + " in in grid input"); for(unsigned i=0; i 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_" + args[i]->getName() ); - 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; igetName(), dder[i] ); } } + if(hasder) { + for(unsigned i=0; igetName(), dder[i] ); + } + } index_t index=grid->getIndex(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; @@ -614,7 +710,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; } @@ -632,10 +732,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) const { plumed_dbg_assert(index& 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, std::vector& der)const { plumed_assert(indexsecond; + if(it!=map_.end()) { + value=it->second; + } const auto itder=der_.find(index); - if(itder!=der_.end()) der=itder->second; + if(itder!=der_.end()) { + der=itder->second; + } return value; } @@ -801,7 +950,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; } @@ -868,7 +1037,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; i 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; @@ -218,17 +229,20 @@ class GridBase virtual ~GridBase() {} /// 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; @@ -236,20 +250,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) @@ -304,8 +320,7 @@ class Grid : public GridBase }; -class SparseGrid : public GridBase -{ +class SparseGrid : public GridBase { std::map map_; std::map< index_t,std::vector > der_; 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,15 +205,21 @@ 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 ) { @@ -189,9 +233,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); } @@ -207,7 +255,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) ); @@ -217,32 +266,49 @@ 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; } @@ -257,14 +323,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; } } @@ -290,7 +367,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() ); @@ -329,7 +411,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 ) { @@ -340,7 +424,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() ); @@ -366,7 +453,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"; @@ -389,22 +478,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] ); @@ -415,102 +516,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"; } @@ -526,22 +677,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; } @@ -579,10 +742,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 ) { @@ -595,7 +765,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"); } @@ -605,18 +776,26 @@ void Keywords::addOutputComponent( const std::string& name, const std::string& k } bool Keywords::outputComponentExists( const std::string& name, const bool& custom ) const { - if( custom && cstring.find("customize")!=std::string::npos ) return true; + if( custom && 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; } @@ -641,14 +826,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; } } diff --git a/src/tools/Keywords.h b/src/tools/Keywords.h index 976b500228..75316208f9 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 ""; } }; @@ -92,9 +110,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 @@ -174,7 +196,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 ; }; 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)& 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 ); } 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::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 34cbc177a6..cb9adf8f79 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; i& buffer ) { - if( !hasDerivatives.updateComplete() ) hasDerivatives.updateActiveMembers(); + if( !hasDerivatives.updateComplete() ) { + hasDerivatives.updateActiveMembers(); + } plumed_dbg_assert( offepsilon ) { wpref=1.0/tmpval; } - else { wpref=1.0; } + if( std::fabs(tmpval)>epsilon ) { + wpref=1.0/tmpval; + } else { + wpref=1.0; + } double pref = values[nder]*wpref*wpref; for(unsigned j=0; j& list0, const std::vect const bool& serial, const bool& do_pair, const bool& do_pbc, const Pbc& pbc, Communicator& cm, const double& distance, const unsigned& stride): reduced(false), serial_(serial), do_pair_(do_pair), do_pbc_(do_pbc), pbc_(&pbc), comm(cm), - distance_(distance), stride_(stride) -{ + distance_(distance), stride_(stride) { // store full list of atoms needed fullatomlist_=list0; fullatomlist_.insert(fullatomlist_.end(),list1.begin(),list1.end()); @@ -137,9 +136,14 @@ 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_) comm.Sum(&local_nl_size[0], stride); + 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(); return;} + if(tot_size==0) { + setRequestList(); + return; + } // merge std::vector merge_nl(tot_size, 0); // calculate vector of displacement @@ -151,8 +155,11 @@ void NeighborList::update(const std::vector& positions) { disp[i+1] = rank_size; } // Allgather neighbor list - if(comm.initialized()&&!serial_) comm.Allgatherv((!local_flat_nl.empty()?&local_flat_nl[0]:NULL), local_nl_size[rank], &merge_nl[0], &local_nl_size[0], &disp[0]); - else merge_nl = local_flat_nl; + if(comm.initialized()&&!serial_) { + comm.Allgatherv((!local_flat_nl.empty()?&local_flat_nl[0]:NULL), local_nl_size[rank], &merge_nl[0], &local_nl_size[0], &disp[0]); + } else { + merge_nl = local_flat_nl; + } // resize neighbor stuff neighbors_.resize(tot_size/2); for(unsigned i=0; i& NeighborList::getReducedAtomList() { - if(!reduced)for(unsigned int i=0; i(newindex0,newindex1); } reduced=true; @@ -216,8 +228,12 @@ std::pair NeighborList::getClosePairAtomNumber(unsigned i std::vector NeighborList::getNeighbors(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.cpp b/src/tools/OpenMP.cpp index ada29dea50..90e40417df 100644 --- a/src/tools/OpenMP.cpp +++ b/src/tools/OpenMP.cpp @@ -48,7 +48,9 @@ void OpenMP::setNumThreads(const unsigned nt) { unsigned OpenMP::getCachelineSize() { if(!getOpenMPVars().cache_set) { - if(std::getenv("PLUMED_CACHELINE_SIZE")) Tools::convert(std::getenv("PLUMED_CACHELINE_SIZE"),getOpenMPVars().cacheline_size); + if(std::getenv("PLUMED_CACHELINE_SIZE")) { + Tools::convert(std::getenv("PLUMED_CACHELINE_SIZE"),getOpenMPVars().cacheline_size); + } getOpenMPVars().cache_set = true; } return getOpenMPVars().cacheline_size; @@ -56,7 +58,9 @@ unsigned OpenMP::getCachelineSize() { unsigned OpenMP::getNumThreads() { if(!getOpenMPVars().nt_env_set) { - if(std::getenv("PLUMED_NUM_THREADS")) Tools::convert(std::getenv("PLUMED_NUM_THREADS"),getOpenMPVars().num_threads); + if(std::getenv("PLUMED_NUM_THREADS")) { + Tools::convert(std::getenv("PLUMED_NUM_THREADS"),getOpenMPVars().num_threads); + } getOpenMPVars().nt_env_set = true; } return getOpenMPVars().num_threads; diff --git a/src/tools/OpenMP.h b/src/tools/OpenMP.h index 1d727aa659..eedff96185 100644 --- a/src/tools/OpenMP.h +++ b/src/tools/OpenMP.h @@ -60,16 +60,22 @@ unsigned OpenMP::getGoodNumThreads(const T*x,unsigned n) { // to cache line boundary unsigned m=n*sizeof(T)/(2*getCachelineSize()); unsigned numThreads=getNumThreads(); - if(m>=numThreads) m=numThreads; - else m=1; + if(m>=numThreads) { + m=numThreads; + } else { + m=1; + } return m; } template unsigned OpenMP::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()); + } } diff --git a/src/tools/PDB.cpp b/src/tools/PDB.cpp index 049f1a7093..8d02835679 100644 --- a/src/tools/PDB.cpp +++ b/src/tools/PDB.cpp @@ -131,9 +131,15 @@ 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 ) { @@ -146,13 +152,18 @@ void PDB::setArgumentNames( const std::vector& argument_names ) { bool PDB::getArgumentValue( const std::string& name, double& value ) const { std::map::const_iterator it = arg_data.find(name); - if( it!=arg_data.end() ) { value = it->second; return true; } + if( it!=arg_data.end() ) { + value = it->second; + return true; + } return false; } void PDB::setAtomPositions( const std::vector& pos ) { plumed_assert( pos.size()==positions.size() ); - for(unsigned i=0; i& v1 ) { std::size_t eq=v1[i].find_first_of('='); std::string name=v1[i].substr(0,eq); std::string sval=v1[i].substr(eq+1); - double val; Tools::convert( sval, val ); + double val; + Tools::convert( sval, val ); arg_data.insert( std::pair( name, val ) ); } else { flags.push_back(v1[i]); @@ -228,7 +240,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 { @@ -281,13 +304,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") { @@ -325,7 +363,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; @@ -343,7 +385,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); @@ -358,7 +402,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); @@ -388,15 +434,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=[](FILE* f) { std::fclose(f); }; + auto deleter=[](FILE* f) { + std::fclose(f); + }; std::unique_ptr fp_deleter(fp,deleter); readFromFilepointer(fp,naturalUnits,scale); return true; @@ -406,7 +458,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]; @@ -518,14 +602,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 { @@ -562,8 +653,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 ); - 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 ); + } + if( argnames.size()>0 ) { + ofile.printf("\n"); + } if( !mymoldat ) { for(unsigned i=0; i at; @@ -621,127 +719,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 c81a913cd7..e8b84b7bf9 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(std::vector shifts[2][2][2])const { 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(std::vector shifts[2][2][2])const { // 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(std::vector shifts[2][2][2])const { 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(std::vector shifts[2][2][2])const { } 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 { - 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); @@ -199,7 +269,9 @@ Vector Pbc::distance(const Vector&v1,const Vector&v2,int*nshifts)const { // introduce a significant gain. I thus leave it out for the moment. if(true) { // bring to -0.5,+0.5 region in scaled coordinates: - 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(s,reduced); // check if shifts have to be attempted: if((std::fabs(s[0])+std::fabs(s[1])+std::fabs(s[2])>0.5)) { @@ -208,7 +280,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()) -{ + 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) { @@ -83,19 +82,22 @@ void PlumedHandle::cmd(const std::string & key,const TypesafePtr & ptr) { safe.flags=ptr.getFlags(); safe.opt=nullptr; plumed_cmd(plumed_v2c(loaded),key.c_str(),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 d3e1d5d77c..315c445c05 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 5959c2eaea..169d7bd2d8 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 ea00c8fc91..a9034724e7 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,26 +322,52 @@ 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 080ae7f855..d38ab46dca 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.push_back(it.first); + for(const auto & it : watches) { + names.push_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(); + } } } @@ -331,8 +333,7 @@ Stopwatch::Handler Stopwatch::startPause(const std::string&name) { inline Stopwatch::Handler::Handler(Handler && handler) noexcept : watch(handler.watch), - stop(handler.stop) -{ + stop(handler.stop) { handler.watch=nullptr; } @@ -341,8 +342,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 @@ -370,8 +374,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; + } lap=0; return *this; } @@ -386,7 +394,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; diff --git a/src/tools/Subprocess.cpp b/src/tools/Subprocess.cpp index 5019d97fee..2ad2ee1c8e 100644 --- a/src/tools/Subprocess.cpp +++ b/src/tools/Subprocess.cpp @@ -44,19 +44,24 @@ class SubprocessPid { public: 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()) if(pid!=0 && pid!=-1) kill(pid,SIGSTOP); + if(SubprocessPidGetenvSignals()) + if(pid!=0 && pid!=-1) { + kill(pid,SIGSTOP); + } } void cont() noexcept { // Signals give problems with MPI on Travis. // I disable them for now. - if(SubprocessPidGetenvSignals()) if(pid!=0 && pid!=-1) kill(pid,SIGCONT); + if(SubprocessPidGetenvSignals()) + if(pid!=0 && pid!=-1) { + kill(pid,SIGCONT); + } } ~SubprocessPid() { // this is apparently working also with MPI on Travis. @@ -80,30 +85,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"; + } execv(arr[0],arr); plumed_error()<<"error in script file"; } // PARENT:: default: this->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"); @@ -156,29 +180,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 58e85d7cb3..73b7c496fb 100644 --- a/src/tools/SwitchingFunction.cpp +++ b/src/tools/SwitchingFunction.cpp @@ -203,23 +203,33 @@ void SwitchingFunction::set(const std::string & definition,std::string& errormsg bool present; present=Tools::findKeyword(data,"D_0"); - if(present && !Tools::parse(data,"D_0",d0)) errormsg="could not parse D_0"; + if(present && !Tools::parse(data,"D_0",d0)) { + errormsg="could not parse D_0"; + } present=Tools::findKeyword(data,"D_MAX"); - if(present && !Tools::parse(data,"D_MAX",dmax)) errormsg="could not parse D_MAX"; - if(dmax::max())) dmax_2=dmax*dmax; + if(present && !Tools::parse(data,"D_MAX",dmax)) { + errormsg="could not parse D_MAX"; + } + if(dmax::max())) { + dmax_2=dmax*dmax; + } bool dostretch=false; Tools::parseFlag(data,"STRETCH",dostretch); // this is ignored now dostretch=true; bool dontstretch=false; Tools::parseFlag(data,"NOSTRETCH",dontstretch); // this is ignored now - if(dontstretch) dostretch=false; + if(dontstretch) { + dostretch=false; + } double r0; if(name=="CUBIC") { r0 = dmax - d0; } else { 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"; + } } invr0=1.0/r0; invr0_2=invr0*invr0; @@ -229,45 +239,66 @@ void SwitchingFunction::set(const std::string & definition,std::string& errormsg nn=6; mm=0; present=Tools::findKeyword(data,"NN"); - if(present && !Tools::parse(data,"NN",nn)) errormsg="could not parse NN"; + if(present && !Tools::parse(data,"NN",nn)) { + errormsg="could not parse NN"; + } present=Tools::findKeyword(data,"MM"); - if(present && !Tools::parse(data,"MM",mm)) errormsg="could not parse MM"; - if(mm==0) mm=2*nn; + if(present && !Tools::parse(data,"MM",mm)) { + errormsg="could not parse MM"; + } + if(mm==0) { + mm=2*nn; + } fastrational=(nn%2==0 && mm%2==0 && d0==0.0); } else if(name=="SMAP") { type=smap; present=Tools::findKeyword(data,"A"); - if(present && !Tools::parse(data,"A",a)) errormsg="could not parse A"; + if(present && !Tools::parse(data,"A",a)) { + errormsg="could not parse A"; + } present=Tools::findKeyword(data,"B"); - if(present && !Tools::parse(data,"B",b)) errormsg="could not parse B"; + if(present && !Tools::parse(data,"B",b)) { + errormsg="could not parse B"; + } c=std::pow(2., static_cast(a)/static_cast(b) ) - 1; d = -static_cast(b) / static_cast(a); - } - else if(name=="Q") { + } else if(name=="Q") { type=nativeq; beta = 50.0; // nm-1 lambda = 1.8; // unitless present=Tools::findKeyword(data,"BETA"); - if(present && !Tools::parse(data, "BETA", beta)) errormsg="could not parse BETA"; + if(present && !Tools::parse(data, "BETA", beta)) { + errormsg="could not parse BETA"; + } present=Tools::findKeyword(data,"LAMBDA"); - if(present && !Tools::parse(data, "LAMBDA", lambda)) errormsg="could not parse LAMBDA"; + if(present && !Tools::parse(data, "LAMBDA", lambda)) { + errormsg="could not parse LAMBDA"; + } bool found_ref=Tools::parse(data,"REF",ref); // nm - if(!found_ref) errormsg="REF (reference disatance) is required for native Q"; + if(!found_ref) { + errormsg="REF (reference disatance) is required for native Q"; + } - } - else if(name=="EXP") type=exponential; - else if(name=="GAUSSIAN") type=gaussian; - else if(name=="CUBIC") type=cubic; - else if(name=="TANH") type=tanh; - else if(name=="COSINUS") type=cosinus; - else if((name=="MATHEVAL" || name=="CUSTOM")) { + } else if(name=="EXP") { + type=exponential; + } else if(name=="GAUSSIAN") { + type=gaussian; + } else if(name=="CUBIC") { + type=cubic; + } else if(name=="TANH") { + type=tanh; + } else if(name=="COSINUS") { + type=cosinus; + } else if((name=="MATHEVAL" || name=="CUSTOM")) { type=leptontype; std::string func; Tools::parse(data,"FUNC",func); lepton::ParsedExpression pe=lepton::Parser::parse(func).optimize(lepton::Constants()); lepton_func=func; expression.resize(OpenMP::getNumThreads()); - for(auto & e : expression) e=pe.createCompiledExpression(); + for(auto & e : expression) { + e=pe.createCompiledExpression(); + } lepton_ref.resize(expression.size()); for(unsigned t=0; t::max()) { @@ -412,8 +450,12 @@ double SwitchingFunction::calculateSqr(double distance2,double&dfunc)const { const unsigned t=OpenMP::getThreadNum(); const double rdist_2 = distance2*invr0_2; plumed_assert(tnn=nn; this->mm=mm; this->invr0=1.0/r0; 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; @@ -75,14 +77,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()); @@ -91,20 +97,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; @@ -117,11 +133,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()); @@ -130,21 +150,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(); @@ -174,41 +206,67 @@ std::vector Tools::getWords(const std::string & line,const char* se 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_massert(parenthesisLevel==0,"Unmatching parenthesis in '" + line + "'"); + if(!parlevel) { + plumed_massert(parenthesisLevel==0,"Unmatching parenthesis in '" + line + "'"); + } words.push_back(word); word.clear(); } } if(word.length()>0) { - if(!parlevel) plumed_massert(parenthesisLevel==0,"Unmatching parenthesis in '" + line + "'"); + if(!parlevel) { + plumed_massert(parenthesisLevel==0,"Unmatching parenthesis in '" + line + "'"); + } words.push_back(word); } - if(parlevel) *parlevel=parenthesisLevel; + if(parlevel) { + *parlevel=parenthesisLevel; + } return words; } @@ -220,16 +278,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); @@ -239,15 +306,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; } @@ -257,29 +333,43 @@ 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::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)); })); @@ -288,10 +378,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; @@ -313,17 +407,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) { @@ -346,10 +448,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); @@ -371,8 +477,12 @@ std::vector Tools::ls(const std::string&d) { #else res=readdir(dir); #endif - if(!res) break; - if(std::string(res->d_name)!="." && std::string(res->d_name)!="..") result.push_back(res->d_name); + if(!res) { + break; + } + if(std::string(res->d_name)!="." && std::string(res->d_name)!="..") { + result.push_back(res->d_name); + } } closedir (dir); } @@ -382,7 +492,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) { @@ -390,10 +502,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; } @@ -415,14 +533,20 @@ 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) { - if(!path) return; - if(std::strlen(path)==0) return; + if(!path) { + return; + } + if(std::strlen(path)==0) { + return; + } #ifdef __PLUMED_HAS_GETCWD char* ret=getcwd(cwd,buffersize); plumed_assert(ret)<<"Name of current directory too long, increase buffer size"; @@ -439,11 +563,15 @@ Tools::DirectoryChanger::DirectoryChanger(const char*path) { Tools::DirectoryChanger::~DirectoryChanger() { #ifdef __PLUMED_HAS_CHDIR - if(std::strlen(cwd)==0) return; + if(std::strlen(cwd)==0) { + return; + } int ret=chdir(cwd); // we cannot put an assertion here (in a destructor) otherwise cppcheck complains // we thus just report the problem - if(ret!=0) std::fprintf(stderr,"+++ WARNING: cannot cd back to directory %s\n",cwd); + if(ret!=0) { + std::fprintf(stderr,"+++ WARNING: cannot cd back to directory %s\n",cwd); + } #endif } @@ -459,7 +587,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 +624,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 802a2f4a72..653a4bf273 100644 --- a/src/tools/Tools.h +++ b/src/tools/Tools.h @@ -240,20 +240,26 @@ class Tools { make_unique(Args&&...) = delete; 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); } @@ -269,16 +275,19 @@ class Tools { static void mergeSortedVectors(const std::vector & vecs, std::vector & result,bool priority_queue=false) { /// local class storing the range of remaining objects to be pushed - struct Entry - { + struct Entry { typename C::const_iterator fwdIt,endIt; explicit Entry(C const& v) : fwdIt(v.begin()), endIt(v.end()) {} /// check if this vector still contains something to be pushed - explicit operator bool () const { return fwdIt != endIt; } + explicit operator bool () 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 *fwdIt > *rhs.fwdIt; } + bool operator< (Entry const& rhs) const { + return *fwdIt > *rhs.fwdIt; + } }; if(priority_queue) { @@ -289,28 +298,40 @@ class Tools { { std::size_t maxsize=0; for(unsigned i=0; isize()>maxsize) maxsize=vecs[i]->size(); - if(!vecs[i]->empty())queue.push(Entry(*vecs[i])); + if(vecs[i]->size()>maxsize) { + maxsize=vecs[i]->size(); + } + if(!vecs[i]->empty()) { + queue.push(Entry(*vecs[i])); + } } // this is just to save multiple reallocations on push_back result.reserve(maxsize); } // first iteration (to avoid a if in the main loop) - if(queue.empty()) return; + if(queue.empty()) { + return; + } auto tmp=queue.top(); queue.pop(); result.push_back(*tmp.fwdIt); tmp.fwdIt++; - if(tmp) queue.push(tmp); + if(tmp) { + queue.push(tmp); + } // main loop while(!queue.empty()) { auto tmp=queue.top(); queue.pop(); - if(result.back() < *tmp.fwdIt) result.push_back(*tmp.fwdIt); + if(result.back() < *tmp.fwdIt) { + result.push_back(*tmp.fwdIt); + } tmp.fwdIt++; - if(tmp) queue.push(tmp); + if(tmp) { + queue.push(tmp); + } } } else { @@ -320,8 +341,12 @@ class Tools { { std::size_t maxsize=0; for(int i=0; isize()>maxsize) maxsize=vecs[i]->size(); - if(!vecs[i]->empty())entries.push_back(Entry(*vecs[i])); + if(vecs[i]->size()>maxsize) { + maxsize=vecs[i]->size(); + } + if(!vecs[i]->empty()) { + entries.push_back(Entry(*vecs[i])); + } } // this is just to save multiple reallocations on push_back result.reserve(maxsize); @@ -336,10 +361,15 @@ class Tools { result.push_back(minval); // fast forward vectors with elements equal to minval (to avoid duplicates) - for(auto & e : entries) while(e && *e.fwdIt==minval) ++e.fwdIt; + for(auto & e : entries) + while(e && *e.fwdIt==minval) { + ++e.fwdIt; + } // remove from the entries vector all exhausted vectors - auto erase=std::remove_if(entries.begin(),entries.end(),[](const Entry & e) {return !e;}); + auto erase=std::remove_if(entries.begin(),entries.end(),[](const Entry & e) { + return !e; + }); entries.erase(erase,entries.end()); } } @@ -354,15 +384,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()); } @@ -404,18 +441,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(std::numeric_limits::round_style == std::round_toward_zero) { const 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(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 } @@ -428,17 +474,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; } @@ -449,14 +494,18 @@ double Tools::fastpow(double base, int exp) 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/ // @@ -53,7 +56,9 @@ std::vector Tree::getTree(std::vector atoms) std::vector addtotree, addtoroot; std::vector newatoms; newatoms.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]); for(unsigned i=1; i Tree::getTree(std::vector atoms) for(unsigned i=0; i=0); @@ -89,14 +95,18 @@ std::vector Tree::getTree(std::vector atoms) int iroot = -1; for(unsigned j=0; jgetPosition(atoms[selected_vertex]), moldat_->getPosition(atoms[j])).modulo2(); - if(dist < mindist[j]) mindist[j] = dist; + if(dist < mindist[j]) { + mindist[j] = dist; + } if(dist < minroot && intree[j] && dist>0.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 @@ -109,8 +119,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 008482d4bd..ab6d43ada2 100644 --- a/src/tools/TypesafePtr.h +++ b/src/tools/TypesafePtr.h @@ -73,12 +73,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"; } } @@ -90,8 +94,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); } @@ -113,8 +116,7 @@ class TypesafePtr { buffer[0]='\0'; } - TypesafePtr(std::nullptr_t) - { + TypesafePtr(std::nullptr_t) { shape[0]=0; buffer[0]='\0'; } @@ -195,8 +197,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; } @@ -214,12 +215,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"; } @@ -228,9 +241,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 @@ -254,7 +271,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"<::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/vatom/Center.cpp b/src/vatom/Center.cpp index 461f92eb66..e27f0aa527 100644 --- a/src/vatom/Center.cpp +++ b/src/vatom/Center.cpp @@ -117,8 +117,7 @@ PRINT ARG=d1 class Center: - public ActionWithVirtualAtom -{ + public ActionWithVirtualAtom { std::vector weights; std::vector dcenter_sin; std::vector dcenter_cos; @@ -159,41 +158,60 @@ 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); parse("SET_CHARGE",charge_); - if(!std::isnan(charge_)) isChargeSet_=true; + if(!std::isnan(charge_)) { + isChargeSet_=true; + } parse("SET_MASS",mass_); - if(mass_>0.) isMassSet_=true; - if(mass_==0.) error("SETMASS must be greater than 0"); - if( getName()=="COM") weight_mass=true; + 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 deriv(getNumberOfAtoms()); - for(unsigned i=0; i 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); @@ -127,7 +129,9 @@ FixedAtom::FixedAtom(const ActionOptions&ao): checkRead(); log<<" AT position "< coord; public: explicit Ghost(const ActionOptions&ao); @@ -68,18 +67,23 @@ 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"); + } 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 302ec631f7..f5e241e636 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 a62a6ba52f..f0971d86c3 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 6434ce102b..0ae235d6fc 100644 --- a/src/ves/TD_Multicanonical.cpp +++ b/src/ves/TD_Multicanonical.cpp @@ -179,8 +179,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 "); @@ -198,11 +197,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; @@ -343,14 +352,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; @@ -416,16 +429,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); @@ -454,7 +479,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(); } @@ -464,8 +491,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 cd9ba0ffef..e034d68aa9 100644 --- a/src/ves/TD_MultithermalMultibaric.cpp +++ b/src/ves/TD_MultithermalMultibaric.cpp @@ -257,8 +257,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"); @@ -283,11 +282,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; @@ -380,10 +389,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; k0.0) { kbt_=plumed.getAtoms().getKBoltzmann()*temp; - } - else { + } else { kbt_=plumed.getAtoms().getKbT(); } if(kbt_>0.0) { @@ -115,14 +113,15 @@ VesBias::VesBias(const ActionOptions&ao): if(targetdist_labels.size()>1) { 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); @@ -188,7 +187,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"); @@ -203,7 +204,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); } @@ -216,7 +218,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(); } } @@ -384,8 +387,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(); @@ -419,7 +420,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!! @@ -443,7 +446,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) { @@ -476,7 +481,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; @@ -564,8 +570,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); } @@ -620,12 +625,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); @@ -703,9 +714,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 3e756f24e4..8226dc30a8 100644 --- a/src/ves/VesDeltaF.cpp +++ b/src/ves/VesDeltaF.cpp @@ -222,15 +222,13 @@ VesDeltaF::VesDeltaF(const ActionOptions&ao) , afterCalculate_(false) , mean_counter_(0) , av_counter_(0) - , work_(0) -{ + , work_(0) { //set beta const double Kb=plumed.getAtoms().getKBoltzmann(); double temp=0; parse("TEMP",temp); double KbT=Kb*temp; - if(KbT==0) - { + if(KbT==0) { KbT=plumed.getAtoms().getKbT(); plumed_massert(KbT>0,"your MD engine does not pass the temperature to plumed, you must specify it using TEMP"); } @@ -242,11 +240,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); @@ -264,8 +262,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); @@ -275,10 +272,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); @@ -287,20 +284,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; } @@ -310,10 +305,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_); @@ -332,31 +328,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); @@ -664,11 +668,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/vesselbase/ActionWithAveraging.cpp b/src/vesselbase/ActionWithAveraging.cpp index 0d28dbdd2c..438abb8763 100644 --- a/src/vesselbase/ActionWithAveraging.cpp +++ b/src/vesselbase/ActionWithAveraging.cpp @@ -30,8 +30,12 @@ namespace PLMD { namespace vesselbase { void ActionWithAveraging::registerKeywords( Keywords& keys ) { - Action::registerKeywords( keys ); ActionPilot::registerKeywords( keys ); ActionAtomistic::registerKeywords( keys ); - ActionWithArguments::registerKeywords( keys ); ActionWithValue::registerKeywords( keys ); ActionWithVessel::registerKeywords( keys ); + Action::registerKeywords( keys ); + ActionPilot::registerKeywords( keys ); + ActionAtomistic::registerKeywords( keys ); + ActionWithArguments::registerKeywords( keys ); + ActionWithValue::registerKeywords( keys ); + ActionWithVessel::registerKeywords( keys ); 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"); @@ -53,12 +57,13 @@ ActionWithAveraging::ActionWithAveraging( const ActionOptions& ao ): normalization(t), useRunAllTasks(false), clearstride(0), - lweight(0),cweight(0) -{ + lweight(0),cweight(0) { if( keywords.exists("CLEAR") ) { 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 grid every %u steps \n",clearstride); } } @@ -70,38 +75,59 @@ ActionWithAveraging::ActionWithAveraging( const ActionOptions& ao ): } } if( my_analysis_object ) { - if( getStride()!=1 ) error("stride should not have been set when calculating average from analysis data"); - setStride(0); addDependency( my_analysis_object ); + if( getStride()!=1 ) { + error("stride should not have been set when calculating average from analysis data"); + } + setStride(0); + addDependency( my_analysis_object ); } } if( keywords.exists("LOGWEIGHTS") ) { - std::vector wwstr; parseVector("LOGWEIGHTS",wwstr); - if( wwstr.size()>0 ) log.printf(" reweighting using weights from "); + std::vector wwstr; + parseVector("LOGWEIGHTS",wwstr); + if( wwstr.size()>0 ) { + log.printf(" reweighting using weights from "); + } std::vector arg( getArguments() ); for(unsigned i=0; i(wwstr[i]); - if( !val ) error("could not find value named"); + if( !val ) { + error("could not find value named"); + } bias::ReweightBase* iswham=dynamic_cast( val ); - if( iswham && iswham->buildsWeightStore() ) error("to use wham you must gather data using COLLECT_FRAMES"); + if( iswham && iswham->buildsWeightStore() ) { + error("to use wham you must gather data using COLLECT_FRAMES"); + } weights.push_back( val->copyOutput(val->getLabel()) ); arg.push_back( val->copyOutput(val->getLabel()) ); log.printf("%s ",wwstr[i].c_str() ); } - if( wwstr.size()>0 ) log.printf("\n"); - else log.printf(" weights are all equal to one\n"); + if( wwstr.size()>0 ) { + log.printf("\n"); + } else { + log.printf(" weights are all equal to one\n"); + } requestArguments( arg ); } if( keywords.exists("NORMALIZATION") ) { - std::string normstr; parse("NORMALIZATION",normstr); - if( normstr=="true" ) normalization=t; - else if( normstr=="false" ) normalization=f; - else if( normstr=="ndata" ) normalization=ndata; - else error("invalid instruction for NORMALIZATION flag should be true, false, or ndata"); + std::string normstr; + parse("NORMALIZATION",normstr); + if( normstr=="true" ) { + normalization=t; + } else if( normstr=="false" ) { + normalization=f; + } else if( normstr=="ndata" ) { + normalization=ndata; + } else { + error("invalid instruction for NORMALIZATION flag should be true, false, or ndata"); + } } } bool ActionWithAveraging::ignoreNormalization() const { - if( normalization==f ) return true; + if( normalization==f ) { + return true; + } return false; } @@ -109,7 +135,8 @@ void ActionWithAveraging::setAveragingAction( std::unique_ptr a // cppcheck-suppress danglingLifetime myaverage=av_vessel.get(); addVessel( std::move(av_vessel) ); - useRunAllTasks=usetasks; resizeFunctions(); + useRunAllTasks=usetasks; + resizeFunctions(); } void ActionWithAveraging::lockRequests() { @@ -123,7 +150,9 @@ void ActionWithAveraging::unlockRequests() { } unsigned ActionWithAveraging::getNumberOfQuantities() const { - if( my_analysis_object ) return getNumberOfArguments()+2; + if( my_analysis_object ) { + return getNumberOfArguments()+2; + } return 2; } @@ -132,69 +161,111 @@ void ActionWithAveraging::calculateNumericalDerivatives(PLMD::ActionWithValue*) } void ActionWithAveraging::update() { - if( (clearstride!=1 && getStep()==0) || (!onStep() && !my_analysis_object) ) return; + if( (clearstride!=1 && getStep()==0) || (!onStep() && !my_analysis_object) ) { + return; + } if( my_analysis_object ) { analysis::ReadAnalysisFrames* myfram = dynamic_cast( my_analysis_object ); - if( !activated && !myfram && !onStep() ) return ; - else if( !activated && !my_analysis_object->onStep() ) return ; + if( !activated && !myfram && !onStep() ) { + return ; + } else if( !activated && !my_analysis_object->onStep() ) { + return ; + } } // Clear if it is time to reset if( myaverage ) { - if( myaverage->wasreset() ) clearAverage(); + if( myaverage->wasreset() ) { + clearAverage(); + } } // Calculate the weight for all reweighting if ( weights.size()>0 && !my_analysis_object ) { - double sum=0; for(unsigned i=0; iget(); - lweight=sum; cweight = exp( sum ); + double sum=0; + for(unsigned i=0; iget(); + } + lweight=sum; + cweight = exp( sum ); } else { - lweight=0; cweight=1.0; + lweight=0; + cweight=1.0; } // Prepare the task list for averaging if( my_analysis_object ) { - for(unsigned i=getFullNumberOfTasks(); igetNumberOfDataPoints(); ++i) addTaskToList(i); - deactivateAllTasks(); cweight=0; + for(unsigned i=getFullNumberOfTasks(); igetNumberOfDataPoints(); ++i) { + addTaskToList(i); + } + deactivateAllTasks(); + cweight=0; for(unsigned i=0; igetNumberOfDataPoints(); ++i) { - taskFlags[i]=1; cweight += my_analysis_object->getWeight(i); + taskFlags[i]=1; + cweight += my_analysis_object->getWeight(i); } lockContributors(); } // Prepare to do the averaging prepareForAveraging(); // Run all the tasks (if required - if( my_analysis_object || useRunAllTasks ) runAllTasks(); + if( my_analysis_object || useRunAllTasks ) { + runAllTasks(); + } // This the averaging if it is not done using task list - else performOperations( true ); + else { + performOperations( true ); + } // Update the norm - double normt = cweight; if( !my_analysis_object && normalization==ndata ) normt = 1; - if( myaverage && my_analysis_object ) myaverage->setNorm( normt ); - else if( myaverage ) myaverage->setNorm( normt + myaverage->getNorm() ); + double normt = cweight; + if( !my_analysis_object && normalization==ndata ) { + normt = 1; + } + if( myaverage && my_analysis_object ) { + myaverage->setNorm( normt ); + } else if( myaverage ) { + myaverage->setNorm( normt + myaverage->getNorm() ); + } // Finish the averaging finishAveraging(); // By resetting here we are ensuring that the grid will be cleared at the start of the next step if( myaverage ) { - if( getStride()==0 || (clearstride>0 && getStep()%clearstride==0) ) myaverage->reset(); + if( getStride()==0 || (clearstride>0 && getStep()%clearstride==0) ) { + myaverage->reset(); + } } } void ActionWithAveraging::performTask( const unsigned& task_index, const unsigned& current, MultiValue& myvals ) const { if( my_analysis_object ) { const analysis::DataCollectionObject& mystore=my_analysis_object->getStoredData( current, false ); - for(unsigned i=0; igetName() ) ); + for(unsigned i=0; igetName() ) ); + } myvals.setValue( 0, my_analysis_object->getWeight(current) ); - if( normalization==f ) myvals.setValue( 1+getNumberOfArguments(), 1.0 ); else myvals.setValue( 1+getNumberOfArguments(), 1.0 / cweight ); + if( normalization==f ) { + myvals.setValue( 1+getNumberOfArguments(), 1.0 ); + } else { + myvals.setValue( 1+getNumberOfArguments(), 1.0 / cweight ); + } accumulateAverage( myvals ); } else { runTask( current, myvals ); } } -void ActionWithAveraging::clearAverage() { plumed_assert( myaverage->wasreset() ); myaverage->clear(); } +void ActionWithAveraging::clearAverage() { + plumed_assert( myaverage->wasreset() ); + myaverage->clear(); +} -void ActionWithAveraging::performOperations( const bool& from_update ) { plumed_error(); } +void ActionWithAveraging::performOperations( const bool& from_update ) { + plumed_error(); +} void ActionWithAveraging::runFinalJobs() { - if( my_analysis_object && getStride()==0 ) { activated=true; update(); } + if( my_analysis_object && getStride()==0 ) { + activated=true; + update(); + } } } diff --git a/src/vesselbase/ActionWithAveraging.h b/src/vesselbase/ActionWithAveraging.h index 1032716568..14e8da2424 100644 --- a/src/vesselbase/ActionWithAveraging.h +++ b/src/vesselbase/ActionWithAveraging.h @@ -49,8 +49,7 @@ class ActionWithAveraging : public ActionAtomistic, public ActionWithArguments, public ActionWithValue, - public ActionWithVessel -{ + public ActionWithVessel { friend class AveragingVessel; private: /// The vessel which is used to compute averages @@ -81,7 +80,9 @@ class ActionWithAveraging : void lockRequests() override; void unlockRequests() override; void calculateNumericalDerivatives(PLMD::ActionWithValue*) override; - unsigned getNumberOfDerivatives() override { return 0; } + unsigned getNumberOfDerivatives() override { + return 0; + } unsigned getNumberOfQuantities() const override; unsigned getNumberOfArguments() const override; /// Overwrite ActionWithArguments getArguments() so that we don't return the bias @@ -97,7 +98,9 @@ class ActionWithAveraging : /// Does the calculation void performTask( const unsigned& task_index, const unsigned& current, MultiValue& myvals ) const override; /// - virtual void runTask( const unsigned& current, MultiValue& myvals ) const { plumed_error(); } + virtual void runTask( const unsigned& current, MultiValue& myvals ) const { + plumed_error(); + } /// virtual void accumulateAverage( MultiValue& myvals ) const {} /// This is done once the averaging is finished @@ -116,7 +119,9 @@ unsigned ActionWithAveraging::getNumberOfArguments() const { inline std::vector ActionWithAveraging::getArguments() { std::vector arg_vals( ActionWithArguments::getArguments() ); - for(unsigned i=0; i(mlab); - if(!mves) error("action labelled " + mlab + " does not exist or does not have vessels"); + if(!mves) { + error("action labelled " + mlab + " does not exist or does not have vessels"); + } addDependency(mves); ActionWithValue* aval=dynamic_cast( this ); if(aval) { if( aval->checkNumericalDerivatives() ) { ActionWithValue* aval2=dynamic_cast( mves ); - plumed_assert( aval2 ); aval2->useNumericalDerivatives(); + plumed_assert( aval2 ); + aval2->useNumericalDerivatives(); } } if( type=="bridge" ) { ActionWithVessel* aves=dynamic_cast( this ); - plumed_assert(aves); myBridgeVessel = mves->addBridgingVessel( aves ); + plumed_assert(aves); + myBridgeVessel = mves->addBridgingVessel( aves ); arguments = dynamic_cast( myBridgeVessel ); } else if( type=="store" ) { arguments = dynamic_cast( mves->buildDataStashes( NULL ) ); @@ -81,7 +86,8 @@ void ActionWithInputVessel::calculateNumericalDerivatives( ActionWithValue* a ) } void ActionWithInputVessel::applyBridgeForces( const std::vector& bb ) { - plumed_dbg_assert( myBridgeVessel ); addBridgeForces( bb ); + plumed_dbg_assert( myBridgeVessel ); + addBridgeForces( bb ); } } diff --git a/src/vesselbase/ActionWithVessel.cpp b/src/vesselbase/ActionWithVessel.cpp index 175df0f23d..c99ae31c78 100644 --- a/src/vesselbase/ActionWithVessel.cpp +++ b/src/vesselbase/ActionWithVessel.cpp @@ -59,12 +59,17 @@ ActionWithVessel::ActionWithVessel(const ActionOptions&ao): dertime(true), contributorsAreUnlocked(false), weightHasDerivatives(false), - mydata(NULL) -{ - maxderivatives=309; parse("MAXDERIVATIVES",maxderivatives); - if( keywords.exists("SERIAL") ) parseFlag("SERIAL",serial); - else serial=true; - if(serial)log.printf(" doing calculation in serial\n"); + mydata(NULL) { + maxderivatives=309; + parse("MAXDERIVATIVES",maxderivatives); + if( keywords.exists("SERIAL") ) { + parseFlag("SERIAL",serial); + } else { + serial=true; + } + if(serial) { + log.printf(" doing calculation in serial\n"); + } if( keywords.exists("LOWMEM") ) { plumed_assert( !keywords.exists("HIGHMEM") ); parseFlag("LOWMEM",lowmem); @@ -75,21 +80,28 @@ ActionWithVessel::ActionWithVessel(const ActionOptions&ao): } if( keywords.exists("HIGHMEM") ) { plumed_assert( !keywords.exists("LOWMEM") ); - bool highmem; parseFlag("HIGHMEM",highmem); + bool highmem; + parseFlag("HIGHMEM",highmem); lowmem=!highmem; - if(!lowmem) log.printf(" increasing the memory requirements\n"); + if(!lowmem) { + log.printf(" increasing the memory requirements\n"); + } } tolerance=nl_tolerance=epsilon; - if( keywords.exists("TOL") ) parse("TOL",tolerance); + if( keywords.exists("TOL") ) { + parse("TOL",tolerance); + } if( tolerance>epsilon) { log.printf(" Ignoring contributions less than %f \n",tolerance); } parseFlag("TIMINGS",timers); - stopwatch.start(); stopwatch.pause(); + stopwatch.start(); + stopwatch.pause(); } ActionWithVessel::~ActionWithVessel() { - stopwatch.start(); stopwatch.stop(); + stopwatch.start(); + stopwatch.stop(); if(timers) { log.printf("timings for action %s with label %s \n", getName().c_str(), getLabel().c_str() ); log< vv_ptr ) { // In the original code, the dynamically casted pointer was deleted here. // Now that vv_ptr is a unique_ptr, the object will be deleted automatically when // exiting this routine. - if(dynamic_cast(vv_ptr.get())) return; + if(dynamic_cast(vv_ptr.get())) { + return; + } vv_ptr->checkRead(); StoreDataVessel* mm=dynamic_cast( vv_ptr.get() ); - if( mydata && mm ) error("cannot have more than one StoreDataVessel in one action"); - else if( mm ) mydata=mm; - else dertime_can_be_off=false; + if( mydata && mm ) { + error("cannot have more than one StoreDataVessel in one action"); + } else if( mm ) { + mydata=mm; + } else { + dertime_can_be_off=false; + } // Ownership is transferred to functions functions.emplace_back(std::move(vv_ptr)); @@ -129,7 +147,8 @@ BridgeVessel* ActionWithVessel::addBridgingVessel( ActionWithVessel* tome ) { VesselOptions da("","",0,"",this); auto bv=Tools::make_unique(da); bv->setOutputAction( tome ); - tome->actionIsBridged=true; dertime_can_be_off=false; + tome->actionIsBridged=true; + dertime_can_be_off=false; // store this pointer in order to return it later. // notice that I cannot access this with functions.tail().get() // since functions contains pointers to a different class (Vessel) @@ -141,13 +160,17 @@ BridgeVessel* ActionWithVessel::addBridgingVessel( ActionWithVessel* tome ) { StoreDataVessel* ActionWithVessel::buildDataStashes( ActionWithVessel* actionThatUses ) { if(mydata) { - if( actionThatUses ) mydata->addActionThatUses( actionThatUses ); + if( actionThatUses ) { + mydata->addActionThatUses( actionThatUses ); + } return mydata; } VesselOptions da("","",0,"",this); auto mm=Tools::make_unique(da); - if( actionThatUses ) mm->addActionThatUses( actionThatUses ); + if( actionThatUses ) { + mm->addActionThatUses( actionThatUses ); + } addVessel(std::move(mm)); // Make sure resizing of vessels is done @@ -157,30 +180,40 @@ StoreDataVessel* ActionWithVessel::buildDataStashes( ActionWithVessel* actionTha } void ActionWithVessel::addTaskToList( const unsigned& taskCode ) { - fullTaskList.push_back( taskCode ); taskFlags.push_back(0); + fullTaskList.push_back( taskCode ); + taskFlags.push_back(0); plumed_assert( fullTaskList.size()==taskFlags.size() ); } void ActionWithVessel::readVesselKeywords() { // Set maxderivatives if it is too big - if( maxderivatives>getNumberOfDerivatives() ) maxderivatives=getNumberOfDerivatives(); + if( maxderivatives>getNumberOfDerivatives() ) { + maxderivatives=getNumberOfDerivatives(); + } // Loop over all keywords find the vessels and create appropriate functions for(unsigned i=0; i0 ) resizeFunctions(); + if( functions.size()>0 ) { + resizeFunctions(); + } } void ActionWithVessel::resizeFunctions() { - for(unsigned i=0; iresize(); + for(unsigned i=0; iresize(); + } } void ActionWithVessel::needsDerivatives() { // Turn on the derivatives and resize - noderiv=false; resizeFunctions(); + noderiv=false; + resizeFunctions(); // Setting contributors unlocked here ensures that link cells are ignored - contributorsAreUnlocked=true; contributorsAreUnlocked=false; + contributorsAreUnlocked=true; + contributorsAreUnlocked=false; // And turn on the derivatives in all actions on which we are dependent for(unsigned i=0; i( getDependencies()[i] ); - if(vv) vv->needsDerivatives(); + if(vv) { + vv->needsDerivatives(); + } } } void ActionWithVessel::lockContributors() { nactive_tasks = 0; for(unsigned i=0; i0 ) nactive_tasks++; + if( taskFlags[i]>0 ) { + nactive_tasks++; + } } unsigned n=0; @@ -228,33 +271,47 @@ void ActionWithVessel::lockContributors() { plumed_dbg_assert( n==nactive_tasks ); for(unsigned i=0; i( functions[i].get() ); - if( bb ) bb->copyTaskFlags(); + if( bb ) { + bb->copyTaskFlags(); + } } // Resize mydata to accommodate all active tasks - if( mydata ) mydata->resize(); + if( mydata ) { + mydata->resize(); + } contributorsAreUnlocked=false; } void ActionWithVessel::deactivateAllTasks() { - contributorsAreUnlocked=true; nactive_tasks = 0; + contributorsAreUnlocked=true; + nactive_tasks = 0; taskFlags.assign(taskFlags.size(),0); } bool ActionWithVessel::taskIsCurrentlyActive( const unsigned& index ) const { - plumed_dbg_assert( index0); + plumed_dbg_assert( index0); } void ActionWithVessel::doJobsRequiredBeforeTaskList() { // Do any preparatory stuff for functions - for(unsigned j=0; jprepare(); + for(unsigned j=0; jprepare(); + } } unsigned ActionWithVessel::getSizeOfBuffer( unsigned& bufsize ) { - for(unsigned i=0; isetBufferStart( bufsize ); - if( buffer.size()!=bufsize ) buffer.resize( bufsize ); + for(unsigned i=0; isetBufferStart( bufsize ); + } + if( buffer.size()!=bufsize ) { + buffer.resize( bufsize ); + } if( mydata ) { unsigned dsize=mydata->getSizeOfDerivativeList(); - if( der_list.size()!=dsize ) der_list.resize( dsize ); + if( der_list.size()!=dsize ) { + der_list.resize( dsize ); + } } return bufsize; } @@ -263,32 +320,48 @@ void ActionWithVessel::runAllTasks() { plumed_massert( !contributorsAreUnlocked && functions.size()>0, "you must have a call to readVesselKeywords somewhere" ); unsigned stride=comm.Get_size(); unsigned rank=comm.Get_rank(); - if(serial) { stride=1; rank=0; } + if(serial) { + stride=1; + rank=0; + } // Make sure jobs are done - if(timers) stopwatch.start("1 Prepare Tasks"); + if(timers) { + stopwatch.start("1 Prepare Tasks"); + } doJobsRequiredBeforeTaskList(); - if(timers) stopwatch.stop("1 Prepare Tasks"); + if(timers) { + stopwatch.stop("1 Prepare Tasks"); + } // Get number of threads for OpenMP unsigned nt=OpenMP::getNumThreads(); - if( nt*stride*2>nactive_tasks || !threadSafe()) nt=1; + if( nt*stride*2>nactive_tasks || !threadSafe()) { + nt=1; + } // Get size for buffer unsigned bsize=0, bufsize=getSizeOfBuffer( bsize ); // Clear buffer buffer.assign( buffer.size(), 0.0 ); // Switch off calculation of derivatives in main loop - if( dertime_can_be_off ) dertime=false; + if( dertime_can_be_off ) { + dertime=false; + } - if(timers) stopwatch.start("2 Loop over tasks"); + if(timers) { + stopwatch.start("2 Loop over tasks"); + } #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( getNumberOfQuantities(), getNumberOfDerivatives() ); MultiValue bvals( getNumberOfQuantities(), getNumberOfDerivatives() ); - myvals.clearAll(); bvals.clearAll(); + myvals.clearAll(); + bvals.clearAll(); #pragma omp for nowait schedule(dynamic) for(unsigned i=rank; i1) for(unsigned i=0; i1) + for(unsigned i=0; i0 ) comm.Sum( buffer ); + if( !serial && buffer.size()>0 ) { + comm.Sum( buffer ); + } // MPI Gather index stores if( mydata && !lowmem && !noderiv ) { - comm.Sum( der_list ); mydata->setActiveValsAndDerivatives( der_list ); + comm.Sum( der_list ); + mydata->setActiveValsAndDerivatives( der_list ); } // Update the elements that are makign contributions to the sum here // this causes problems if we do it in prepare - if(timers) stopwatch.stop("3 MPI gather"); + if(timers) { + stopwatch.stop("3 MPI gather"); + } - if(timers) stopwatch.start("4 Finishing computations"); + if(timers) { + stopwatch.start("4 Finishing computations"); + } finishComputations( buffer ); - if(timers) stopwatch.stop("4 Finishing computations"); + if(timers) { + stopwatch.stop("4 Finishing computations"); + } } void ActionWithVessel::transformBridgedDerivatives( const unsigned& current, MultiValue& invals, MultiValue& outvals ) const { @@ -348,28 +437,38 @@ void ActionWithVessel::calculateAllVessels( const unsigned& taskCode, MultiValue // Calculate returns a bool that tells us if this particular // quantity is contributing more than the tolerance functions[j]->calculate( taskCode, functions[j]->transformDerivatives(taskCode, myvals, bvals), buffer, der_list ); - if( !actionIsBridged ) bvals.clearAll(); + if( !actionIsBridged ) { + bvals.clearAll(); + } } return; } void ActionWithVessel::finishComputations( const std::vector& buffer ) { // Set the final value of the function - for(unsigned j=0; jfinish( buffer ); + for(unsigned j=0; jfinish( buffer ); + } } bool ActionWithVessel::getForcesFromVessels( std::vector& forcesToApply ) { #ifndef NDEBUG - if( forcesToApply.size()>0 ) plumed_dbg_assert( forcesToApply.size()==getNumberOfDerivatives() ); + if( forcesToApply.size()>0 ) { + plumed_dbg_assert( forcesToApply.size()==getNumberOfDerivatives() ); + } #endif - if(tmpforces.size()!=forcesToApply.size() ) tmpforces.resize( forcesToApply.size() ); + if(tmpforces.size()!=forcesToApply.size() ) { + tmpforces.resize( forcesToApply.size() ); + } forcesToApply.assign( forcesToApply.size(),0.0 ); bool wasforced=false; for(unsigned i=0; iapplyForce( tmpforces )) ) { wasforced=true; - for(unsigned j=0; jgetName().find(mynam)!=std::string::npos ) { - if( target<0 ) target=i; - else error("found more than one " + mynam + " object in action"); + if( target<0 ) { + target=i; + } else { + error("found more than one " + mynam + " object in action"); + } } } plumed_assert(target>=0); diff --git a/src/vesselbase/ActionWithVessel.h b/src/vesselbase/ActionWithVessel.h index 32859b84b9..2c35edf446 100644 --- a/src/vesselbase/ActionWithVessel.h +++ b/src/vesselbase/ActionWithVessel.h @@ -151,7 +151,9 @@ class ActionWithVessel : public virtual Action { /// Are derivatives required for this quantity bool derivativesAreRequired() const ; /// Is this action thread safe - virtual bool threadSafe() const { return true; } + virtual bool threadSafe() const { + return true; + } /// Finish running all the calculations virtual void finishComputations( const std::vector& buffer ); /// Are the base quantities periodic @@ -183,7 +185,9 @@ class ActionWithVessel : public virtual Action { /// Ensure that data required in other vessels is stored StoreDataVessel* buildDataStashes( ActionWithVessel* actionThatUses ); /// Apply forces from bridge vessel - this is rarely used - currently only in ActionVolume - virtual void applyBridgeForces( const std::vector& bb ) { plumed_error(); } + virtual void applyBridgeForces( const std::vector& bb ) { + plumed_error(); + } /// These are overwritten in MultiColvarFunction // virtual void activateIndexes( const unsigned&, const unsigned&, const std::vector& ){} /// Return a particular named vessel @@ -193,8 +197,12 @@ class ActionWithVessel : public virtual Action { /// Return the position in the current task list unsigned getPositionInCurrentTaskList( const unsigned& myind ) const ; /// These normalizes vectors and is used in StoreDataVessel - virtual void normalizeVector( std::vector& vals ) const { plumed_error(); } - virtual void normalizeVectorDerivatives( MultiValue& myvals ) const { plumed_error(); } + virtual void normalizeVector( std::vector& vals ) const { + plumed_error(); + } + virtual void normalizeVectorDerivatives( MultiValue& myvals ) const { + plumed_error(); + } }; inline @@ -278,10 +286,14 @@ bool ActionWithVessel::weightWithDerivatives() const { inline unsigned ActionWithVessel::getPositionInCurrentTaskList( const unsigned& myind ) const { - if( nactive_tasks==fullTaskList.size() ) return myind; + if( nactive_tasks==fullTaskList.size() ) { + return myind; + } for(unsigned i=0; iisPeriodic() ) error("MIN is not a meaningful option for periodic variables"); - parse("BETA",beta); usetol=true; + FunctionVessel(da) { + if( getAction()->isPeriodic() ) { + error("MIN is not a meaningful option for periodic variables"); + } + parse("BETA",beta); + usetol=true; } std::string AltMin::value_descriptor() { - std::string str_beta; Tools::convert( beta, str_beta ); + std::string str_beta; + Tools::convert( beta, str_beta ); return "the minimum value. Beta is equal to " + str_beta; } double AltMin::calcTransform( const double& val, double& dv ) const { - double f = exp( -beta*val ); dv = -beta*f; return f; + double f = exp( -beta*val ); + dv = -beta*f; + return f; } double AltMin::finalTransform( const double& val, double& dv ) { - dv = - 1.0 /(beta*val); return -std::log( val ) / beta; + dv = - 1.0 /(beta*val); + return -std::log( val ) / beta; } } diff --git a/src/vesselbase/AveragingVessel.cpp b/src/vesselbase/AveragingVessel.cpp index 9e2cc6c26d..8bde732515 100644 --- a/src/vesselbase/AveragingVessel.cpp +++ b/src/vesselbase/AveragingVessel.cpp @@ -31,16 +31,19 @@ void AveragingVessel::registerKeywords( Keywords& keys ) { AveragingVessel::AveragingVessel( const vesselbase::VesselOptions& vo ): Vessel(vo), - wascleared(true) -{ + wascleared(true) { if( getAction() ) { ActionWithAveraging* myav = dynamic_cast( getAction() ); - plumed_assert( myav ); unormalised = myav->ignoreNormalization(); + plumed_assert( myav ); + unormalised = myav->ignoreNormalization(); } } void AveragingVessel::finish( const std::vector& buffer ) { - wascleared=false; for(unsigned i=1; i& forces ) override { return false; } + bool applyForce( std::vector& forces ) override { + return false; + } }; inline void AveragingVessel::setDataElement( const unsigned& myelem, const double& value ) { plumed_dbg_assert( myelem<1+data.size() ); - wascleared=false; data[1+myelem]=value; + wascleared=false; + data[1+myelem]=value; } inline void AveragingVessel::addDataElement( const unsigned& myelem, const double& value ) { plumed_dbg_assert( myelem<1+data.size() ); - wascleared=false; data[1+myelem]+=value; + wascleared=false; + data[1+myelem]+=value; } inline double AveragingVessel::getDataElement( const unsigned& myelem ) const { plumed_dbg_assert( myelemisPeriodic(); - double min, max; std::string str_min, str_max; + double min, max; + std::string str_min, str_max; if( isPeriodic ) { getAction()->retrieveDomain( str_min, str_max ); - Tools::convert(str_min,min); Tools::convert(str_max,max); + Tools::convert(str_min,min); + Tools::convert(str_max,max); } - parseFlag("NORM",norm); std::string errormsg; + parseFlag("NORM",norm); + std::string errormsg; hist.set( getAllInput(),errormsg ); - if( !isPeriodic ) hist.isNotPeriodic(); - else hist.isPeriodic( min, max ); - if( errormsg.size()!=0 ) error( errormsg ); + if( !isPeriodic ) { + hist.isNotPeriodic(); + } else { + hist.isPeriodic( min, max ); + } + if( errormsg.size()!=0 ) { + error( errormsg ); + } } std::string Between::value_descriptor() { - if(norm) return "the fraction of values " + hist.description(); + if(norm) { + return "the fraction of values " + hist.description(); + } return "the number of values " + hist.description(); } double Between::calcTransform( const double& val, double& dv ) const { - double f = hist.calculate(val, dv); return f; + double f = hist.calculate(val, dv); + return f; } double Between::getCutoff() { diff --git a/src/vesselbase/BridgeVessel.cpp b/src/vesselbase/BridgeVessel.cpp index 33ee559cb5..1b6d2e6636 100644 --- a/src/vesselbase/BridgeVessel.cpp +++ b/src/vesselbase/BridgeVessel.cpp @@ -33,8 +33,7 @@ BridgeVessel::BridgeVessel( const VesselOptions& da ): // in_normal_calculate(false) myOutputAction(NULL), myOutputValues(NULL), - my_tmp_val(0,0) -{ + my_tmp_val(0,0) { } void BridgeVessel::resize() { @@ -47,9 +46,12 @@ void BridgeVessel::resize() { // from a bridge if( myOutputAction->mydata ) { unsigned dsize=(myOutputAction->mydata)->getSizeOfDerivativeList(); - if( getAction()->der_list.size()!=dsize ) getAction()->der_list.resize( dsize ); + if( getAction()->der_list.size()!=dsize ) { + getAction()->der_list.resize( dsize ); + } } - unsigned tmp=0; resizeBuffer( myOutputAction->getSizeOfBuffer( tmp ) ); + unsigned tmp=0; + resizeBuffer( myOutputAction->getSizeOfBuffer( tmp ) ); } void BridgeVessel::setOutputAction( ActionWithVessel* myact ) { @@ -84,7 +86,9 @@ MultiValue& BridgeVessel::transformDerivatives( const unsigned& current, MultiVa void BridgeVessel::calculate( const unsigned& current, MultiValue& myvals, std::vector& buffer, std::vector& der_list ) const { // in_normal_calculate=true; - if( myvals.get(0)getTolerance() ) return; + if( myvals.get(0)getTolerance() ) { + return; + } myOutputAction->calculateAllVessels( current, myvals, myvals, buffer, der_list ); return; } @@ -109,22 +113,32 @@ void BridgeVessel::completeNumericalDerivatives() { Matrix tmpder( myOutputValues->getNumberOfComponents(), nextra ); ActionWithVessel* vval=dynamic_cast( myOutputAction ); for(unsigned i=0; ibridgeVariable=i; getAction()->calculate(); - for(int j=0; jgetNumberOfComponents(); ++j) tmpder(j,i) = myOutputValues->getOutputQuantity(j); + vval->bridgeVariable=i; + getAction()->calculate(); + for(int j=0; jgetNumberOfComponents(); ++j) { + tmpder(j,i) = myOutputValues->getOutputQuantity(j); + } } - vval->bridgeVariable=nextra; getAction()->calculate(); - plumed_assert( inum==mynumerical_values.size() ); inum=0; // Reset inum now that we have finished calling calculate + vval->bridgeVariable=nextra; + getAction()->calculate(); + plumed_assert( inum==mynumerical_values.size() ); + inum=0; // Reset inum now that we have finished calling calculate std::vector base( myOutputValues->getNumberOfComponents() ); - for(int j=0; jgetNumberOfComponents(); ++j) base[j] = myOutputValues->getOutputQuantity(j); + for(int j=0; jgetNumberOfComponents(); ++j) { + base[j] = myOutputValues->getOutputQuantity(j); + } const double delta=std::sqrt(epsilon); ActionAtomistic* aa=dynamic_cast( getAction() ); unsigned nvals=myOutputValues->getNumberOfComponents(); - for(unsigned j=0; jcopyOutput(j) )->clearDerivatives(); + for(unsigned j=0; jcopyOutput(j) )->clearDerivatives(); + } if( aa ) { ActionWithArguments* aarg=dynamic_cast( getAction() ); - plumed_assert( !aarg ); Tensor box=aa->getBox(); + plumed_assert( !aarg ); + Tensor box=aa->getBox(); unsigned natoms=aa->getNumberOfAtoms(); for(unsigned j=0; jcopyOutput(j) )->get(); @@ -134,11 +148,15 @@ void BridgeVessel::completeNumericalDerivatives() { ( myOutputValues->copyOutput(j) )->addDerivative(i,d); } Tensor virial; - 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++) { virial(i,k)=( mynumerical_values[ nvals*(3*natoms + 3*i + k) + j ]-ref)/delta; } virial=-matmul(box.transpose(),virial); - for(int i=0; i<3; i++) for(int k=0; k<3; k++) ( myOutputValues->copyOutput(j) )->addDerivative(3*natoms+3*k+i,virial(k,i)); + for(int i=0; i<3; i++) + for(int k=0; k<3; k++) { + ( myOutputValues->copyOutput(j) )->addDerivative(3*natoms+3*k+i,virial(k,i)); + } } } } else { @@ -157,30 +175,40 @@ void BridgeVessel::completeNumericalDerivatives() { for(unsigned j=0; jgetNumberOfDerivatives(); igetNumberOfDerivatives(); ++i) { - ( myOutputValues->copyOutput(j) )->addDerivative( i, (tmpder(j,k)-base[j])/std::sqrt(epsilon) ); k++; + ( myOutputValues->copyOutput(j) )->addDerivative( i, (tmpder(j,k)-base[j])/std::sqrt(epsilon) ); + k++; } } } bool BridgeVessel::applyForce( std::vector& outforces ) { - bool hasforce=false; outforces.assign(outforces.size(),0.0); + bool hasforce=false; + outforces.assign(outforces.size(),0.0); unsigned ndertot = myOutputAction->getNumberOfDerivatives(); unsigned nextra = ndertot - getAction()->getNumberOfDerivatives(); std::vector forces( ndertot ), eforces( nextra, 0.0 ); for(unsigned i=0; igetNumberOfVessels(); ++i) { if( ( myOutputAction->getPntrToVessel(i) )->applyForce( forces ) ) { hasforce=true; - for(unsigned j=0; japplyBridgeForces( eforces ); + if(hasforce) { + myOutputAction->applyBridgeForces( eforces ); + } return hasforce; } void BridgeVessel::copyTaskFlags() { myOutputAction->deactivateAllTasks(); - for(unsigned i=0; inactive_tasks; ++i) myOutputAction->taskFlags[ getAction()->indexOfTaskInFullList[i] ] = 1; + for(unsigned i=0; inactive_tasks; ++i) { + myOutputAction->taskFlags[ getAction()->indexOfTaskInFullList[i] ] = 1; + } myOutputAction->lockContributors(); } diff --git a/src/vesselbase/FunctionVessel.cpp b/src/vesselbase/FunctionVessel.cpp index e197155c0c..7ca5b5d03f 100644 --- a/src/vesselbase/FunctionVessel.cpp +++ b/src/vesselbase/FunctionVessel.cpp @@ -32,8 +32,7 @@ void FunctionVessel::registerKeywords( Keywords& keys ) { FunctionVessel::FunctionVessel( const VesselOptions& da ): ValueVessel(da), norm(false), - usetol(false) -{ + usetol(false) { diffweight=getAction()->weightHasDerivatives; } @@ -58,17 +57,27 @@ void FunctionVessel::calculate( const unsigned& current, MultiValue& myvals, std double dval, f=calcTransform( myvals.get(mycomp), dval ); if( norm ) { - if( usetol && weightderivativesAreRequired() && diffweight ) myvals.chainRule( 0, 1, 1, 0, 1.0, bufstart, buffer ); + if( getAction()->derivativesAreRequired() && diffweight ) { + myvals.chainRule( 0, 1, 1, 0, 1.0, bufstart, buffer ); + } } double contr=weight*f; - if( usetol && contrderivativesAreRequired() && std::fabs(dval)>0.0 ) myvals.chainRule( mycomp, 0, 1, 0, weight*dval, bufstart, buffer ); + if( diffweight ) { + myvals.chainRule( 0, 0, 1, 0, f, bufstart, buffer ); + } + if( getAction()->derivativesAreRequired() && std::fabs(dval)>0.0 ) { + myvals.chainRule( mycomp, 0, 1, 0, weight*dval, bufstart, buffer ); + } return; } @@ -88,15 +97,21 @@ void FunctionVessel::finish( const std::vector& buffer ) { } else if( norm ) { double dv, val=finalTransform( buffer[bufstart], dv), weight=buffer[bufstart+1+nderivatives]; getFinalValue()->set( val / weight ); - for(unsigned i=0; iaddDerivative( i, buffer[bufstart+1+i]/weight ); + for(unsigned i=0; iaddDerivative( i, buffer[bufstart+1+i]/weight ); + } } else { - double dv, val=finalTransform( buffer[bufstart], dv); getFinalValue()->set( val ); - for(unsigned i=0; iaddDerivative( i, dv*buffer[bufstart+1+i] ); + double dv, val=finalTransform( buffer[bufstart], dv); + getFinalValue()->set( val ); + for(unsigned i=0; iaddDerivative( i, dv*buffer[bufstart+1+i] ); + } } } double FunctionVessel::finalTransform( const double& val, double& dv ) { - dv=1.0; return val; + dv=1.0; + return val; } } diff --git a/src/vesselbase/Highest.cpp b/src/vesselbase/Highest.cpp index c75a29382b..ddef09d2b3 100644 --- a/src/vesselbase/Highest.cpp +++ b/src/vesselbase/Highest.cpp @@ -46,8 +46,7 @@ void Highest::reserveKeyword( Keywords& keys ) { } Highest::Highest( const VesselOptions& da ) : - OrderingVessel(da) -{ + OrderingVessel(da) { } std::string Highest::value_descriptor() { diff --git a/src/vesselbase/Histogram.cpp b/src/vesselbase/Histogram.cpp index eb5a0921b6..9e0020ce5d 100644 --- a/src/vesselbase/Histogram.cpp +++ b/src/vesselbase/Histogram.cpp @@ -49,14 +49,21 @@ void Histogram::reserveKeyword( Keywords& keys ) { } Histogram::Histogram( const VesselOptions& da ): - ShortcutVessel(da) -{ - bool norm; parseFlag("NORM",norm); std::string normstr=""; - if(norm) normstr=" NORM"; - std::string compstr; parse("COMPONENT",compstr); + ShortcutVessel(da) { + bool norm; + parseFlag("NORM",norm); + std::string normstr=""; + if(norm) { + normstr=" NORM"; + } + std::string compstr; + parse("COMPONENT",compstr); normstr+=" COMPONENT=" + compstr; - std::vector bins; HistogramBead::generateBins( getAllInput(), bins ); - for(unsigned i=0; i bins; + HistogramBead::generateBins( getAllInput(), bins ); + for(unsigned i=0; iisPeriodic() ) error("LESS_THAN is not a meaningful option for periodic variables"); - std::string errormsg; sf.set( getAllInput(), errormsg ); - if( errormsg.size()!=0 ) error( errormsg ); + if( getAction()->isPeriodic() ) { + error("LESS_THAN is not a meaningful option for periodic variables"); + } + std::string errormsg; + sf.set( getAllInput(), errormsg ); + if( errormsg.size()!=0 ) { + error( errormsg ); + } } std::string LessThan::value_descriptor() { @@ -55,7 +59,9 @@ std::string LessThan::value_descriptor() { } double LessThan::calcTransform( const double& val, double& dv ) const { - double f = sf.calculate(val, dv); dv*=val; return f; + double f = sf.calculate(val, dv); + dv*=val; + return f; } double LessThan::getCutoff() { diff --git a/src/vesselbase/Lowest.cpp b/src/vesselbase/Lowest.cpp index f17d9411a5..c8761c2cbc 100644 --- a/src/vesselbase/Lowest.cpp +++ b/src/vesselbase/Lowest.cpp @@ -46,8 +46,7 @@ void Lowest::reserveKeyword( Keywords& keys ) { } Lowest::Lowest( const VesselOptions& da ) : - OrderingVessel(da) -{ + OrderingVessel(da) { } std::string Lowest::value_descriptor() { diff --git a/src/vesselbase/Max.cpp b/src/vesselbase/Max.cpp index 0d6b3c886c..512dfa9395 100644 --- a/src/vesselbase/Max.cpp +++ b/src/vesselbase/Max.cpp @@ -56,26 +56,33 @@ void Max::reserveKeyword( Keywords& keys ) { } Max::Max( const VesselOptions& da ) : - FunctionVessel(da) -{ - if( getAction()->isPeriodic() ) error("max is not a meaningful option for periodic variables"); + FunctionVessel(da) { + if( getAction()->isPeriodic() ) { + error("max is not a meaningful option for periodic variables"); + } parse("BETA",beta); - if( diffweight ) error("can't calculate max if weight is differentiable"); + if( diffweight ) { + error("can't calculate max if weight is differentiable"); + } } std::string Max::value_descriptor() { - std::string str_beta; Tools::convert( beta, str_beta ); + std::string str_beta; + Tools::convert( beta, str_beta ); return "the maximum value. Beta is equal to " + str_beta; } double Max::calcTransform( const double& val, double& dv ) const { - double f = exp(val/beta); dv=f/beta; return f; + double f = exp(val/beta); + dv=f/beta; + return f; } double Max::finalTransform( const double& val, double& dv ) { double dist=beta*std::log( val ); - dv = beta/val; return dist; + dv = beta/val; + return dist; } } diff --git a/src/vesselbase/Mean.cpp b/src/vesselbase/Mean.cpp index 651123fd23..dcfae0fa31 100644 --- a/src/vesselbase/Mean.cpp +++ b/src/vesselbase/Mean.cpp @@ -48,9 +48,10 @@ void Mean::reserveKeyword( Keywords& keys ) { } Mean::Mean( const vesselbase::VesselOptions& da ) : - FunctionVessel(da) -{ - if( getAction()->isPeriodic() ) error("MEAN cannot be used with periodic variables"); + FunctionVessel(da) { + if( getAction()->isPeriodic() ) { + error("MEAN cannot be used with periodic variables"); + } norm=true; // Makes sure we calculate the average } @@ -59,7 +60,8 @@ std::string Mean::value_descriptor() { } double Mean::calcTransform( const double& val, double& dv ) const { - dv=1.0; return val; + dv=1.0; + return val; } } diff --git a/src/vesselbase/Min.cpp b/src/vesselbase/Min.cpp index a314978939..987d97f5a8 100644 --- a/src/vesselbase/Min.cpp +++ b/src/vesselbase/Min.cpp @@ -55,27 +55,33 @@ void Min::reserveKeyword( Keywords& keys ) { } Min::Min( const VesselOptions& da ) : - FunctionVessel(da) -{ - if( getAction()->isPeriodic() ) error("min is not a meaningful option for periodic variables"); + FunctionVessel(da) { + if( getAction()->isPeriodic() ) { + error("min is not a meaningful option for periodic variables"); + } parse("BETA",beta); - if( diffweight ) error("can't calculate min if weight is differentiable"); + if( diffweight ) { + error("can't calculate min if weight is differentiable"); + } } std::string Min::value_descriptor() { - std::string str_beta; Tools::convert( beta, str_beta ); + std::string str_beta; + Tools::convert( beta, str_beta ); return "the minimum value. Beta is equal to " + str_beta; } double Min::calcTransform( const double& val, double& dv ) const { - double f = exp(beta/val); dv=f/(val*val); + double f = exp(beta/val); + dv=f/(val*val); return f; } double Min::finalTransform( const double& val, double& dv ) { double dist=beta/std::log( val ); - dv = dist*dist/val; return dist; + dv = dist*dist/val; + return dist; } } diff --git a/src/vesselbase/Moments.cpp b/src/vesselbase/Moments.cpp index 2ce413a778..628e736f6a 100644 --- a/src/vesselbase/Moments.cpp +++ b/src/vesselbase/Moments.cpp @@ -71,31 +71,45 @@ void Moments::reserveKeyword( Keywords& keys ) { } Moments::Moments( const vesselbase::VesselOptions& da) : - Vessel(da) -{ + Vessel(da) { mystash = getAction()->buildDataStashes( NULL ); ActionWithValue* a=dynamic_cast( getAction() ); plumed_massert(a,"cannot create passable values as base action does not inherit from ActionWithValue"); - std::vector moments; std::string valstr = "moment-"; - parse("COMPONENT",mycomponent); parseVector("MOMENTS",moments); - if( getNumericalLabel()!=0 ) { std::string numstr; Tools::convert( mycomponent, numstr); valstr = "moment-" + numstr + "-"; } - if( moments.size()==0 ) moments=Tools::getWords(getAllInput(),"\t\n ,"); - Tools::interpretRanges(moments); unsigned nn; + std::vector moments; + std::string valstr = "moment-"; + parse("COMPONENT",mycomponent); + parseVector("MOMENTS",moments); + if( getNumericalLabel()!=0 ) { + std::string numstr; + Tools::convert( mycomponent, numstr); + valstr = "moment-" + numstr + "-"; + } + if( moments.size()==0 ) { + moments=Tools::getWords(getAllInput(),"\t\n ,"); + } + Tools::interpretRanges(moments); + unsigned nn; for(unsigned i=0; iaddComponentWithDerivatives( valstr + moments[i] ); a->componentIsNotPeriodic( valstr + moments[i] ); value_out.push_back( a->copyOutput( a->getNumberOfComponents()-1 ) ); Tools::convert( moments[i], nn ); - if( nn<2 ) error("moments are only possible for m>=2" ); - powers.push_back( nn ); std::string num; Tools::convert(powers[i],num); + if( nn<2 ) { + error("moments are only possible for m>=2" ); + } + powers.push_back( nn ); + std::string num; + Tools::convert(powers[i],num); } } void Moments::resize() { resizeBuffer(0); if( getAction()->derivativesAreRequired() ) { - for(unsigned i=0; iresizeDerivatives( getAction()->getNumberOfDerivatives() ); + for(unsigned i=0; iresizeDerivatives( getAction()->getNumberOfDerivatives() ); + } } } @@ -109,7 +123,8 @@ std::string Moments::description() { descri = descri + "\n value " + getAction()->getLabel() + "." + "moment-" + num + " contains the " + num + "th moment of the distribution"; } } else { - std::string numlab; Tools::convert( mycomponent, numlab ); + std::string numlab; + Tools::convert( mycomponent, numlab ); descri = "value " + getAction()->getLabel() + "." + "moment-" + numlab + "-" + num + " contains the " + num + "th moment for the distribution of component " + numlab; for(unsigned i=1; i& buffer ) { unsigned nvals=getAction()->getFullNumberOfTasks(); std::vector myvalues( getAction()->getNumberOfQuantities() ); - double mean=0; Value myvalue; + double mean=0; + Value myvalue; if( getAction()->isPeriodic() ) { - std::string str_min, str_max; getAction()->retrieveDomain( str_min, str_max ); - double pfactor, min, max; Tools::convert(str_min,min); Tools::convert(str_max,max); - pfactor = 2*pi / ( max-min ); myvalue.setDomain( str_min, str_max ); + std::string str_min, str_max; + getAction()->retrieveDomain( str_min, str_max ); + double pfactor, min, max; + Tools::convert(str_min,min); + Tools::convert(str_max,max); + pfactor = 2*pi / ( max-min ); + myvalue.setDomain( str_min, str_max ); double sinsum=0, cossum=0, val; for(unsigned i=0; igetNumberOfStoredValues(); ++i) { mystash->retrieveSequentialValue( i, false, myvalues ); val=pfactor*( myvalues[mycomponent] - min ); - sinsum+=std::sin(val); cossum+=std::cos(val); + sinsum+=std::sin(val); + cossum+=std::cos(val); } mean = 0.5 + std::atan2( sinsum / static_cast( nvals ), cossum / static_cast( nvals ) ) / (2*pi); mean = min + (max-min)*mean; } else { for(unsigned i=0; igetNumberOfStoredValues(); ++i) { - mystash->retrieveSequentialValue( i, false, myvalues ); mean+=myvalues[mycomponent]; + mystash->retrieveSequentialValue( i, false, myvalues ); + mean+=myvalues[mycomponent]; } - mean/=static_cast( nvals ); myvalue.setNotPeriodic(); + mean/=static_cast( nvals ); + myvalue.setNotPeriodic(); } for(unsigned npow=0; npow& buffer ) { } double moment=0; - MultiValue myvals( getAction()->getNumberOfQuantities(), getAction()->getNumberOfDerivatives() ); myvals.clearAll(); + MultiValue myvals( getAction()->getNumberOfQuantities(), getAction()->getNumberOfDerivatives() ); + myvals.clearAll(); for(unsigned i=0; igetNumberOfStoredValues(); ++i) { mystash->retrieveSequentialValue( i, false, myvalues ); double tmp=myvalue.difference( mean, myvalues[mycomponent] ); @@ -170,18 +194,23 @@ void Moments::finish( const std::vector& buffer ) { myvals.clearAll(); } } - if( value_out[npow]->getNumberOfDerivatives()>0 ) value_out[npow]->chainRule( powers[npow] / static_cast( nvals ) ); + if( value_out[npow]->getNumberOfDerivatives()>0 ) { + value_out[npow]->chainRule( powers[npow] / static_cast( nvals ) ); + } value_out[npow]->set( moment / static_cast( nvals ) ); } } bool Moments::applyForce( std::vector& forces ) { std::vector tmpforce( forces.size() ); - forces.assign(forces.size(),0.0); bool wasforced=false; + forces.assign(forces.size(),0.0); + bool wasforced=false; for(unsigned i=0; iapplyForce( tmpforce ) ) { wasforced=true; - for(unsigned j=0; jisPeriodic() ) error("more than is not a meaningful option for periodic variables"); - std::string errormsg; sf.set( getAllInput(), errormsg ); - if( errormsg.size()!=0 ) error( errormsg ); + if( getAction()->isPeriodic() ) { + error("more than is not a meaningful option for periodic variables"); + } + std::string errormsg; + sf.set( getAllInput(), errormsg ); + if( errormsg.size()!=0 ) { + error( errormsg ); + } } std::string MoreThan::value_descriptor() { @@ -69,7 +73,9 @@ std::string MoreThan::value_descriptor() { } double MoreThan::calcTransform( const double& val, double& dv ) const { - double f = 1.0 - sf.calculate(val, dv); dv*=-val; return f; + double f = 1.0 - sf.calculate(val, dv); + dv*=-val; + return f; } } diff --git a/src/vesselbase/OrderingVessel.cpp b/src/vesselbase/OrderingVessel.cpp index 26a92227cf..7981410e12 100644 --- a/src/vesselbase/OrderingVessel.cpp +++ b/src/vesselbase/OrderingVessel.cpp @@ -31,35 +31,42 @@ void OrderingVessel::registerKeywords( Keywords& keys ) { } OrderingVessel::OrderingVessel( const VesselOptions& da ) : - ValueVessel(da) -{ + ValueVessel(da) { mydata = getAction()->buildDataStashes( NULL ); for(unsigned i=0; igetNumberOfVessels(); ++i) { - if( getAction()->getPntrToVessel(i)->getName()==getName() ) + if( getAction()->getPntrToVessel(i)->getName()==getName() ) { error("calculating lowest/highest value multiple times serves no purpose"); + } } } void OrderingVessel::resize() { resizeBuffer( 0 ); - if( getAction()->derivativesAreRequired() ) getFinalValue()->resizeDerivatives( getAction()->getNumberOfDerivatives() ); + if( getAction()->derivativesAreRequired() ) { + getFinalValue()->resizeDerivatives( getAction()->getNumberOfDerivatives() ); + } } void OrderingVessel::finish( const std::vector& buffer ) { std::vector values( getAction()->getNumberOfQuantities() ); mydata->retrieveSequentialValue( 0, false, values ); - double min=values[mycomp]; unsigned mini=getAction()->getPositionInFullTaskList(0); + double min=values[mycomp]; + unsigned mini=getAction()->getPositionInFullTaskList(0); for(unsigned i=1; igetNumberOfStoredValues(); ++i) { mydata->retrieveSequentialValue( i, false, values ); double newval = values[mycomp]; - if( compare( newval, min ) ) { min=newval; mini=getAction()->getPositionInFullTaskList(i); } + if( compare( newval, min ) ) { + min=newval; + mini=getAction()->getPositionInFullTaskList(i); + } } setOutputValue( min ); if( getAction()->derivativesAreRequired() ) { MultiValue myvals( getAction()->getNumberOfQuantities(), getAction()->getNumberOfDerivatives() ); - mydata->retrieveDerivatives( mini, false, myvals ); Value* fval=getFinalValue(); + mydata->retrieveDerivatives( mini, false, myvals ); + Value* fval=getFinalValue(); for(unsigned i=0; isetDerivative( ider, myvals.getDerivative(mycomp,ider) ); diff --git a/src/vesselbase/ShortcutVessel.cpp b/src/vesselbase/ShortcutVessel.cpp index e7147f1da7..d3d411c31b 100644 --- a/src/vesselbase/ShortcutVessel.cpp +++ b/src/vesselbase/ShortcutVessel.cpp @@ -26,19 +26,21 @@ namespace PLMD { namespace vesselbase { void ShortcutVessel::registerKeywords( Keywords& keys ) { - Vessel::registerKeywords( keys ); keys.remove("LABEL"); + Vessel::registerKeywords( keys ); + keys.remove("LABEL"); plumed_assert( keys.size()==0 ); } ShortcutVessel::ShortcutVessel( const VesselOptions& da): - Vessel(da) -{ + Vessel(da) { } void ShortcutVessel::addVessel( const std::string& name, const std::string& input ) { unsigned numlab=1; for(unsigned i=0; i<(getAction()->functions).size(); ++i) { - if( (getAction()->functions[i])->getName()==name ) numlab++; + if( (getAction()->functions[i])->getName()==name ) { + numlab++; + } } getAction()->addVessel( name, input, numlab ); } diff --git a/src/vesselbase/ShortcutVessel.h b/src/vesselbase/ShortcutVessel.h index 016f0ef50f..7811ffb6a2 100644 --- a/src/vesselbase/ShortcutVessel.h +++ b/src/vesselbase/ShortcutVessel.h @@ -37,11 +37,21 @@ class ShortcutVessel : public Vessel { public: static void registerKeywords( Keywords& keys ); explicit ShortcutVessel( const VesselOptions& ); - std::string description() override { return ""; } - void resize() override { plumed_error(); } - void calculate( const unsigned& taskCode, MultiValue& myvals, std::vector& buffer, std::vector& der_index ) const override { plumed_error(); } - void finish( const std::vector& buffer ) override { plumed_error(); } - bool applyForce( std::vector& forces ) override { plumed_error(); } + std::string description() override { + return ""; + } + void resize() override { + plumed_error(); + } + void calculate( const unsigned& taskCode, MultiValue& myvals, std::vector& buffer, std::vector& der_index ) const override { + plumed_error(); + } + void finish( const std::vector& buffer ) override { + plumed_error(); + } + bool applyForce( std::vector& forces ) override { + plumed_error(); + } }; } diff --git a/src/vesselbase/StoreDataVessel.cpp b/src/vesselbase/StoreDataVessel.cpp index 956b037cc3..b8e3fb4bad 100644 --- a/src/vesselbase/StoreDataVessel.cpp +++ b/src/vesselbase/StoreDataVessel.cpp @@ -25,18 +25,21 @@ namespace PLMD { namespace vesselbase { void StoreDataVessel::registerKeywords( Keywords& keys ) { - Vessel::registerKeywords(keys); keys.remove("LABEL"); + Vessel::registerKeywords(keys); + keys.remove("LABEL"); } StoreDataVessel::StoreDataVessel( const VesselOptions& da ): Vessel(da), max_lowmem_stash(3), vecsize(0), - nspace(0) -{ + nspace(0) { ActionWithValue* myval=dynamic_cast( getAction() ); - if( !myval ) hasderiv=false; - else hasderiv=!myval->doNotCalculateDerivatives(); + if( !myval ) { + hasderiv=false; + } else { + hasderiv=!myval->doNotCalculateDerivatives(); + } } void StoreDataVessel::addActionThatUses( ActionWithVessel* actionThatUses ) { @@ -62,10 +65,12 @@ void StoreDataVessel::resize() { void StoreDataVessel::storeValues( const unsigned& myelem, MultiValue& myvals, std::vector& buffer ) const { plumed_dbg_assert( vecsize>0 ); - unsigned jelem = getAction()->getPositionInCurrentTaskList( myelem ); plumed_dbg_assert( jelemgetPositionInCurrentTaskList( myelem ); + plumed_dbg_assert( jelemgetFullNumberOfTasks()==getNumberOfStoredValues() ) { der_list[jelem]=myvals.getNumberActive(); unsigned kder = getNumberOfStoredValues() + jelem * ( nspace - 1 ); - for(unsigned j=0; j& values ) const { plumed_dbg_assert( values.size()==vecsize ); unsigned ibuf = jelem * vecsize * nspace; - for(unsigned i=0; i2 ) getAction()->normalizeVector( values ); + for(unsigned i=0; i2 ) { + getAction()->normalizeVector( values ); + } } void StoreDataVessel::retrieveValueWithIndex( const unsigned& myelem, const bool& normed, std::vector& values ) const { @@ -115,7 +136,9 @@ void StoreDataVessel::retrieveValueWithIndex( const unsigned& myelem, const bool double StoreDataVessel::retrieveWeightWithIndex( const unsigned& myelem ) const { plumed_dbg_assert( vecsize>0 ); - unsigned jelem = getStoreIndex( myelem ); unsigned ibuf = jelem * vecsize * nspace; return local_buffer[ibuf]; + unsigned jelem = getStoreIndex( myelem ); + unsigned ibuf = jelem * vecsize * nspace; + return local_buffer[ibuf]; } void StoreDataVessel::retrieveDerivatives( const unsigned& myelem, const bool& normed, MultiValue& myvals ) { @@ -124,7 +147,9 @@ void StoreDataVessel::retrieveDerivatives( const unsigned& myelem, const bool& n myvals.clearAll(); if( getAction()->lowmem ) { recalculateStoredQuantity( myelem, myvals ); - if( normed ) getAction()->normalizeVectorDerivatives( myvals ); + if( normed ) { + getAction()->normalizeVectorDerivatives( myvals ); + } } else { unsigned jelem = getAction()->getPositionInCurrentTaskList( myelem ); // Retrieve the derivatives for elements 0 and 1 - weight and norm @@ -133,14 +158,20 @@ void StoreDataVessel::retrieveDerivatives( const unsigned& myelem, const bool& n unsigned kder = getNumberOfStoredValues() + jelem * ( nspace - 1 ); for(unsigned j=0; jnormalizeVectorDerivatives( myvals ); + if( normed ) { + getAction()->normalizeVectorDerivatives( myvals ); + } // Now ensure appropriate parts of list are activated myvals.emptyActiveMembers(); unsigned kder = getNumberOfStoredValues() + jelem * ( nspace - 1 ); - for(unsigned j=0; jepsilon ) { storeValues( current, myvals, buffer ); - if( !(getAction()->lowmem) && getAction()->derivativesAreRequired() ) storeDerivatives( current, myvals, buffer, der_list ); + if( !(getAction()->lowmem) && getAction()->derivativesAreRequired() ) { + storeDerivatives( current, myvals, buffer, der_list ); + } } return; @@ -157,22 +190,29 @@ void StoreDataVessel::calculate( const unsigned& current, MultiValue& myvals, st void StoreDataVessel::finish( const std::vector& buffer ) { // Store the buffer locally - for(unsigned i=0; i& der_index ) { if( !getAction()->lowmem && getAction()->derivativesAreRequired() ) { - for(unsigned i=0; i& values ) const ; void retrieveValueWithIndex( const unsigned& myelem, const bool& normed, std::vector& values ) const ; @@ -107,7 +109,9 @@ class StoreDataVessel : public Vessel { /// Do all resizing of data void resize() override; /// - std::string description() override { return ""; } + std::string description() override { + return ""; + } /// Get the number of derivatives for the ith value unsigned getNumberOfDerivatives( const unsigned& ); /// Get the size of the derivative list @@ -123,7 +127,9 @@ class StoreDataVessel : public Vessel { /// Activate indexes (this is used at end of chain rule) virtual void activateIndices( ActionWithVessel* ) {} /// Forces on vectors should always be applied elsewhere - bool applyForce(std::vector&) override { return false; } + bool applyForce(std::vector&) override { + return false; + } /// Get the number of data users unsigned getNumberOfDataUsers() const ; /// Get one of the ith data user @@ -151,7 +157,9 @@ unsigned StoreDataVessel::getNumberOfDerivativeSpacesPerComponent() const { inline bool StoreDataVessel::storedValueIsActive( const unsigned& iatom ) const { - if( !getAction()->taskIsCurrentlyActive( iatom ) ) return false; + if( !getAction()->taskIsCurrentlyActive( iatom ) ) { + return false; + } unsigned jatom = getStoreIndex( iatom ); plumed_dbg_assert( jatomepsilon; @@ -169,16 +177,22 @@ unsigned StoreDataVessel::getNumberOfStoredValues() const { inline unsigned StoreDataVessel::getStoreIndex( const unsigned& ind ) const { - if( getAction()->nactive_tasks==getAction()->getFullNumberOfTasks() ) return ind; + if( getAction()->nactive_tasks==getAction()->getFullNumberOfTasks() ) { + return ind; + } // Binary search for required element - faster scaling than sequential search unsigned l=0, r=getAction()->nactive_tasks-1; for(unsigned i=0; inactive_tasks; ++i) { plumed_assert( l<=r ); unsigned m = std::floor( (l + r)/2 ); - if( ind==getAction()->indexOfTaskInFullList[m] ) return m; - else if( getAction()->indexOfTaskInFullList[m]indexOfTaskInFullList[m]>ind ) r=m-1; + if( ind==getAction()->indexOfTaskInFullList[m] ) { + return m; + } else if( getAction()->indexOfTaskInFullList[m]indexOfTaskInFullList[m]>ind ) { + r=m-1; + } } plumed_merror("requested task is not active"); } @@ -200,7 +214,8 @@ unsigned StoreDataVessel::getNumberOfDataUsers() const { inline ActionWithVessel* StoreDataVessel::getDataUser( const unsigned& idata ) { - plumed_dbg_assert( idata( getAction() ); plumed_massert(a,"cannot create passable values as base action does not inherit from ActionWithValue"); @@ -53,17 +52,23 @@ ValueVessel::ValueVessel( const VesselOptions& da ): } std::string ValueVessel::description() { - if( final_value->getName()==getAction()->getLabel() ) return "value " + getAction()->getLabel() + " contains " + value_descriptor(); - std::string compstr; Tools::convert(mycomp,compstr); + if( final_value->getName()==getAction()->getLabel() ) { + return "value " + getAction()->getLabel() + " contains " + value_descriptor(); + } + std::string compstr; + Tools::convert(mycomp,compstr); return "value " + getAction()->getLabel() + "." + getLabel() + " is obtained by taking the " + compstr + "th component and finding " + value_descriptor(); } bool ValueVessel::applyForce( std::vector& forces ) { std::vector tmpforce( forces.size() ); - forces.assign(forces.size(),0.0); bool wasforced=false; + forces.assign(forces.size(),0.0); + bool wasforced=false; if( final_value->applyForce( tmpforce ) ) { wasforced=true; - for(unsigned j=0; j0) { mylabel=da.mylabel; } else { - if( keywords.exists("LABEL") ) parse("LABEL",mylabel); + if( keywords.exists("LABEL") ) { + parse("LABEL",mylabel); + } if( mylabel.length()==0 && numlab>=0 ) { - mylabel=transformName( myname ); std::string nn; - if(numlab>0) { Tools::convert( numlab, nn ); mylabel = mylabel + "-" + nn; } + mylabel=transformName( myname ); + std::string nn; + if(numlab>0) { + Tools::convert( numlab, nn ); + mylabel = mylabel + "-" + nn; + } } } } @@ -100,7 +107,8 @@ std::string Vessel::getAllInput() { for(unsigned i=0; i0) msg = msg + ", "; + if(i>0) { + msg = msg + ", "; + } msg = msg + line[i]; } error(msg); } finished_read=true; std::string describe=description(); - if( describe.length()>0 && action ) action->log.printf(" %s\n", describe.c_str() ); + if( describe.length()>0 && action ) { + action->log.printf(" %s\n", describe.c_str() ); + } } [[noreturn]] void Vessel::error( const std::string& msg ) { if( action ) { action->log.printf("ERROR for keyword %s in action %s with label %s : %s \n \n",myname.c_str(), (action->getName()).c_str(), (action->getLabel()).c_str(), msg.c_str() ); - if(finished_read) keywords.print( action->log ); + if(finished_read) { + keywords.print( action->log ); + } plumed_merror("ERROR for keyword " + myname + " in action " + action->getName() + " with label " + action->getLabel() + " : " + msg ); } else { plumed_merror("ERROR: " + msg); diff --git a/src/vesselbase/Vessel.h b/src/vesselbase/Vessel.h index 04ab6b0520..42838ab6f8 100644 --- a/src/vesselbase/Vessel.h +++ b/src/vesselbase/Vessel.h @@ -158,7 +158,8 @@ void Vessel::parse(const std::string&key, T&t ) { plumed_massert(keywords.exists(key),"keyword " + key + " has not been registered"); // Now try to read the keyword - bool found=Tools::parse(line,key,t); std::string def; + bool found=Tools::parse(line,key,t); + std::string def; if ( !found && keywords.style(key,"compulsory") ) { if( keywords.getDefaultValue(key,def) ) { plumed_massert( def.length()!=0 && Tools::convertNoexcept(def,t), "default value is dubious"); @@ -172,16 +173,23 @@ template void Vessel::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 - bool found; std::string def; T val; + bool found; + std::string def; + T val; found=Tools::parseVector(line,key,t); // Check vectors size is correct (not if this is atoms or ARG) if( !keywords.style(key,"atoms") && found ) { - 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 @@ -190,7 +198,9 @@ void Vessel::parseVector(const std::string&key,std::vector&t) { if( def.length()==0 || !Tools::convertNoexcept(def,val) ) { plumed_merror("weird default value for keyword " + key ); } else { - for(unsigned i=0; i0) { std::string names=""; - for(const auto & p : m) names+=p.first+" "; + for(const auto & p : m) { + names+=p.first+" "; + } std::cerr<<"WARNING: Vessel "+ names +" has not been properly unregistered. This might lead to memory leak!!\n"; } } @@ -42,7 +44,8 @@ VesselRegister& vesselRegister() { void VesselRegister::remove(creator_pointer f) { for(auto p=m.begin(); p!=m.end(); ++p) { if((*p).second==f) { - m.erase(p); break; + m.erase(p); + break; } } } @@ -58,14 +61,17 @@ void VesselRegister::add(std::string keyword,creator_pointer f,keyword_pointer k } bool VesselRegister::check(const std::string & key) { - if( m.count(key)>0 ) return true; + if( m.count(key)>0 ) { + return true; + } return false; } std::unique_ptr VesselRegister::create(std::string keyword, const VesselOptions&da) { std::unique_ptr df; if(check(keyword)) { - Keywords keys; mk[keyword](keys); + Keywords keys; + mk[keyword](keys); VesselOptions nda( da,keys ); df=m[keyword](nda); } diff --git a/src/wrapper/Plumed.h b/src/wrapper/Plumed.h index d65d1a52e8..40691255eb 100644 --- a/src/wrapper/Plumed.h +++ b/src/wrapper/Plumed.h @@ -895,7 +895,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 */ __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); @@ -924,7 +926,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); @@ -943,7 +947,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); @@ -973,7 +979,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 */ @@ -989,7 +997,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(); } @@ -1747,33 +1757,65 @@ 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)); + } 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(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)); } @@ -1781,29 +1823,49 @@ class Plumed { } /* "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>=11100 && h.code<11200) f(add_buffer_to< ::std::bad_cast>(msg)); + if(h.code>=11000 && h.code<11100) { + f(add_buffer_to< ::std::bad_typeid>(msg)); + } + if(h.code>=11100 && h.code<11200) { + 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)); + } /* 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 */ @@ -1858,7 +1920,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()); } @@ -1867,7 +1931,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 } @@ -1972,12 +2038,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 */ @@ -2063,12 +2130,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 */ @@ -2088,27 +2156,33 @@ class Plumed { template class add_buffer_to: - public T - { - char msg[__PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER]; \ + public T { + char msg[__PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER]; + \ public: __PLUMED_WRAPPER_CXX_EXPLICIT add_buffer_to(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"); + } } add_buffer_to(const add_buffer_to & other) __PLUMED_WRAPPER_CXX_NOEXCEPT { msg[0]='\0'; __PLUMED_WRAPPER_STD memcpy(msg,other.msg,__PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER); } add_buffer_to & operator=(const add_buffer_to & other) __PLUMED_WRAPPER_CXX_NOEXCEPT { - if(this==&other) return *this; + if(this==&other) { + return *this; + } msg[0]='\0'; __PLUMED_WRAPPER_STD memcpy(msg,other.msg,__PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER); return *this; } - const char* what() const __PLUMED_WRAPPER_CXX_NOEXCEPT __PLUMED_WRAPPER_CXX_OVERRIDE {return msg;} + const char* what() const __PLUMED_WRAPPER_CXX_NOEXCEPT __PLUMED_WRAPPER_CXX_OVERRIDE { + return msg; + } #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 */ @@ -2147,8 +2221,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 @@ -2414,16 +2492,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)) { } /** @@ -2436,8 +2512,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. @@ -2445,8 +2520,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. @@ -2456,7 +2530,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; @@ -2473,8 +2549,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. @@ -2483,7 +2558,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; } @@ -2697,7 +2774,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: @@ -2756,7 +2835,9 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : */ template void cmd(const char*key,T* val, 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) { @@ -2798,7 +2879,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); + } } /** @@ -3313,7 +3396,9 @@ 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"); @@ -3327,7 +3412,9 @@ void* plumed_attempt_dlopen(const char*path,int mode) { __PLUMED_WRAPPER_STD fclose(fp); 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); } @@ -3375,7 +3462,9 @@ void plumed_search_symbols(void* handle, plumed_plumedmain_function_holder* f,pl */ debug=__PLUMED_GETENV("PLUMED_LOAD_DEBUG"); table_ptr=(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,(void*)table_ptr); @@ -3398,17 +3487,29 @@ void plumed_search_symbols(void* handle, plumed_plumedmain_function_holder* f,pl __PLUMED_SEARCH_FUNCTION(tmpptr,handle,functions.finalize,"plumedmain_finalize",debug); __PLUMED_SEARCH_FUNCTION(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 @@ -3475,18 +3576,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. @@ -3504,8 +3617,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. @@ -3517,34 +3634,52 @@ 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(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"),"LOCAL")) { dlopenmode=dlopenmode|RTLD_LOCAL; - if(debug) __PLUMED_FPRINTF(stderr,"|RTLD_LOCAL"); + if(debug) { + __PLUMED_FPRINTF(stderr,"|RTLD_LOCAL"); + } } else { dlopenmode=dlopenmode|RTLD_GLOBAL; - if(debug) __PLUMED_FPRINTF(stderr,"|RTLD_GLOBAL"); + if(debug) { + __PLUMED_FPRINTF(stderr,"|RTLD_GLOBAL"); + } } #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 @@ -3604,8 +3739,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 @@ -3629,7 +3768,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) { @@ -3657,7 +3798,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 @@ -3705,7 +3848,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); @@ -3773,7 +3918,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); @@ -3807,9 +3954,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 @@ -3833,15 +3984,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 @@ -3857,9 +4013,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 */ @@ -3873,7 +4033,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 @@ -3891,8 +4053,11 @@ int plumed_valid(plumed p) { /* obtain pimpl */ pimpl=(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 @@ -3927,7 +4092,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; } @@ -3975,8 +4142,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() { From 9464903282b556e1617e3b76f3e6fcdefe52d486 Mon Sep 17 00:00:00 2001 From: Daniele Rapetti <5535617+Iximiel@users.noreply.github.com> Date: Mon, 18 Nov 2024 15:28:11 +0100 Subject: [PATCH 3/3] added .git-blame-ignore-revs file --- .git-blame-ignore-revs | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .git-blame-ignore-revs diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000000..89eb3e7d00 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,4 @@ +# .git-blame-ignore-revs +# https://docs.github.com/en/repositories/working-with-files/using-files/viewing-a-file#ignore-commits-in-the-blame-view +# new astyle applied to v2.9 +33f1cb86c61c13ef7c545444113ae60f6dd628fd