From ebcb1cf6fe306d114465256bcba1a0cd87bd1f7c Mon Sep 17 00:00:00 2001 From: Daniele Rapetti Date: Tue, 1 Oct 2024 07:10:38 +0200 Subject: [PATCH] added "add-braces" --- .astyle.options | 3 +- src/adjmat/ActionWithInputMatrix.cpp | 39 +- src/adjmat/AdjacencyMatrixBase.cpp | 42 +- src/adjmat/AdjacencyMatrixBase.h | 3 +- src/adjmat/AdjacencyMatrixVessel.cpp | 45 +- src/adjmat/AlignedMatrixBase.cpp | 18 +- src/adjmat/ClusterAnalysisBase.cpp | 18 +- src/adjmat/ClusterDiameter.cpp | 12 +- src/adjmat/ClusterDistribution.cpp | 15 +- src/adjmat/ClusterProperties.cpp | 24 +- src/adjmat/ClusterSize.cpp | 9 +- src/adjmat/ClusterWithSurface.cpp | 27 +- src/adjmat/ClusteringBase.cpp | 9 +- src/adjmat/ContactAlignedMatrix.cpp | 6 +- src/adjmat/ContactMatrix.cpp | 12 +- src/adjmat/DFSClustering.cpp | 18 +- src/adjmat/DumpGraph.cpp | 21 +- src/adjmat/HbondMatrix.cpp | 36 +- src/adjmat/MatrixColumnSums.cpp | 18 +- src/adjmat/MatrixRowSums.cpp | 3 +- src/adjmat/OutputCluster.cpp | 42 +- src/adjmat/SMACMatrix.cpp | 12 +- src/adjmat/Sprint.cpp | 12 +- src/adjmat/TopologyMatrix.cpp | 54 +- src/analysis/AnalysisBase.cpp | 12 +- src/analysis/Average.cpp | 3 +- src/analysis/AverageVessel.cpp | 12 +- src/analysis/Committor.cpp | 21 +- src/analysis/DataCollectionObject.cpp | 24 +- src/analysis/DataCollectionObject.h | 9 +- src/analysis/EuclideanDissimilarityMatrix.cpp | 12 +- src/analysis/FarthestPointSampling.cpp | 9 +- src/analysis/Histogram.cpp | 138 +++-- src/analysis/LandmarkSelectionBase.cpp | 18 +- src/analysis/LandmarkStaged.cpp | 9 +- src/analysis/OutputColvarFile.cpp | 24 +- src/analysis/OutputPDBFile.cpp | 12 +- src/analysis/PrintDissimilarityMatrix.cpp | 6 +- src/analysis/ReadAnalysisFrames.cpp | 57 +- src/analysis/ReadAnalysisFrames.h | 3 +- src/analysis/ReadDissimilarityMatrix.cpp | 33 +- src/analysis/ReselectLandmarks.cpp | 9 +- src/analysis/SelectWithStride.cpp | 3 +- src/analysis/WhamHistogram.cpp | 6 +- src/bias/ABMD.cpp | 18 +- src/bias/Bias.cpp | 6 +- src/bias/ExtendedLagrangian.cpp | 21 +- src/bias/External.cpp | 9 +- src/bias/LWalls.cpp | 15 +- src/bias/MaxEnt.cpp | 107 ++-- src/bias/MetaD.cpp | 569 ++++++++++++------ src/bias/MovingRestraint.cpp | 33 +- src/bias/PBMetaD.cpp | 261 +++++--- src/bias/Restraint.cpp | 9 +- src/bias/ReweightBase.cpp | 9 +- src/bias/ReweightBias.cpp | 3 +- src/bias/ReweightMetad.cpp | 3 +- src/bias/ReweightTemperaturePressure.cpp | 39 +- src/bias/ReweightWham.cpp | 39 +- src/bias/UWalls.cpp | 15 +- src/colvar/Angle.cpp | 12 +- src/colvar/Cell.cpp | 3 +- src/colvar/Constant.cpp | 21 +- src/colvar/ContactMap.cpp | 33 +- src/colvar/Coordination.cpp | 6 +- src/colvar/CoordinationBase.cpp | 54 +- src/colvar/DHEnergy.cpp | 3 +- src/colvar/DRMSD.cpp | 12 +- src/colvar/Dimer.cpp | 33 +- src/colvar/Dipole.cpp | 9 +- src/colvar/Distance.cpp | 15 +- src/colvar/EEFSolv.cpp | 54 +- src/colvar/ERMSD.cpp | 15 +- src/colvar/GHBFIX.cpp | 3 +- src/colvar/Gyration.cpp | 62 +- src/colvar/MultiRMSD.cpp | 27 +- src/colvar/PCARMSD.cpp | 36 +- src/colvar/PathMSDBase.cpp | 54 +- src/colvar/Position.cpp | 9 +- src/colvar/ProjectionOnAxis.cpp | 12 +- src/colvar/Puckering.cpp | 87 ++- src/colvar/RMSD.cpp | 24 +- src/colvar/Template.cpp | 9 +- src/colvar/Torsion.cpp | 27 +- src/core/Action.cpp | 60 +- src/core/Action.h | 33 +- src/core/ActionAtomistic.cpp | 95 ++- src/core/ActionAtomistic.h | 3 +- src/core/ActionPilot.cpp | 6 +- src/core/ActionRegister.cpp | 18 +- src/core/ActionSet.cpp | 6 +- src/core/ActionSet.h | 21 +- src/core/ActionSetup.cpp | 3 +- src/core/ActionShortcut.cpp | 9 +- src/core/ActionWithArguments.cpp | 48 +- src/core/ActionWithValue.cpp | 30 +- src/core/ActionWithValue.h | 3 +- src/core/ActionWithVirtualAtom.cpp | 9 +- src/core/Atoms.cpp | 134 +++-- src/core/CLTool.cpp | 36 +- src/core/CLTool.h | 17 +- src/core/CLToolMain.cpp | 42 +- src/core/CLToolRegister.cpp | 20 +- src/core/Colvar.cpp | 18 +- src/core/DataFetchingObject.cpp | 12 +- src/core/ExchangePatterns.cpp | 6 +- src/core/FlexibleBin.cpp | 6 +- src/core/GREX.cpp | 12 +- src/core/GenericMolInfo.cpp | 75 ++- src/core/MDAtoms.cpp | 39 +- src/core/PlumedMain.cpp | 228 ++++--- src/core/PlumedMain.h | 6 +- src/core/PlumedMainInitializer.cpp | 135 +++-- src/core/TargetDist.cpp | 3 +- src/core/Value.cpp | 30 +- src/core/Value.h | 18 +- src/main/main.cpp | 15 +- src/sasa/sasa_HASEL.cpp | 36 +- src/sasa/sasa_LCPO.cpp | 42 +- src/tools/BiasRepresentation.cpp | 33 +- src/tools/Brent1DRootSearch.h | 20 +- src/tools/Citations.cpp | 9 +- src/tools/Communicator.cpp | 72 ++- src/tools/ConjugateGradient.h | 3 +- src/tools/DLLoader.cpp | 6 +- src/tools/DynamicList.h | 33 +- src/tools/ERMSD.cpp | 9 +- src/tools/Exception.cpp | 12 +- src/tools/FileBase.cpp | 44 +- src/tools/Grid.cpp | 207 ++++--- src/tools/Grid.h | 6 +- src/tools/HistogramBead.cpp | 42 +- src/tools/HistogramBead.h | 3 +- src/tools/IFile.cpp | 75 ++- src/tools/KernelFunctions.cpp | 158 +++-- src/tools/Keywords.cpp | 226 ++++--- src/tools/Keywords.h | 21 +- src/tools/LatticeReduction.cpp | 45 +- src/tools/LinkCells.cpp | 15 +- src/tools/Matrix.h | 60 +- src/tools/Minimise1DBrent.h | 24 +- src/tools/MinimiseBase.h | 9 +- src/tools/MolDataClass.cpp | 448 +++++++++----- src/tools/MultiValue.cpp | 30 +- src/tools/MultiValue.h | 6 +- src/tools/NeighborList.cpp | 15 +- src/tools/OFile.cpp | 87 ++- src/tools/OpenMP.cpp | 6 +- src/tools/OpenMP.h | 12 +- src/tools/PDB.cpp | 447 +++++++++----- src/tools/Pbc.cpp | 90 ++- src/tools/PlumedHandle.cpp | 9 +- src/tools/RMSD.cpp | 312 ++++++---- src/tools/RMSD.h | 6 +- src/tools/Random.cpp | 45 +- src/tools/RootFindingBase.h | 3 +- src/tools/Stopwatch.cpp | 12 +- src/tools/Stopwatch.h | 21 +- src/tools/Subprocess.cpp | 45 +- src/tools/SwitchingFunction.cpp | 87 ++- src/tools/Tensor.h | 30 +- src/tools/Tools.cpp | 180 ++++-- src/tools/Tools.h | 69 ++- src/tools/Tree.cpp | 18 +- src/tools/TypesafePtr.cpp | 6 +- src/tools/TypesafePtr.h | 53 +- src/tools/Vector.h | 3 +- src/tools/h36.cpp | 33 +- src/wrapper/Plumed.h | 261 +++++--- 169 files changed, 4945 insertions(+), 2489 deletions(-) diff --git a/.astyle.options b/.astyle.options index fc9513fe88..a0f9bec075 100644 --- a/.astyle.options +++ b/.astyle.options @@ -1,7 +1,8 @@ # long options can be written without the preceding '--' suffix=none #was "-n" indent=spaces=2 -break-one-line-headers #"add-braces" is too aggressive, this has the same effect, but does not add braces +break-one-line-headers +add-braces # old options #suffix=none diff --git a/src/adjmat/ActionWithInputMatrix.cpp b/src/adjmat/ActionWithInputMatrix.cpp index 41dd1d3241..c2b075ef4e 100644 --- a/src/adjmat/ActionWithInputMatrix.cpp +++ b/src/adjmat/ActionWithInputMatrix.cpp @@ -43,29 +43,36 @@ ActionWithInputMatrix::ActionWithInputMatrix(const ActionOptions& ao): matsums=true; if( keywords.exists("MATRIX") ) { std::vector fake_atoms; - if( !parseMultiColvarAtomList("MATRIX",-1,fake_atoms ) ) + if( !parseMultiColvarAtomList("MATRIX",-1,fake_atoms ) ) { error("unable to interpret input matrix"); - if( mybasemulticolvars.size()!=1 ) + } + 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 ) + if( mymatrix ) { break ; + } } - if( !mymatrix ) + if( !mymatrix ) { error( mybasemulticolvars[0]->getLabel() + " does not calculate an adjacency matrix"); + } // Delete all the atom labels that have been created atom_lab.resize(0); unsigned nnodes; - if( mymatrix->undirectedGraph() ) + if( mymatrix->undirectedGraph() ) { nnodes = (mymatrix->function)->ablocks[0].size(); - else + } + else { nnodes = (mymatrix->function)->ablocks[0].size() + (mymatrix->function)->ablocks[1].size(); - for(unsigned i=0; i( 1, i ) ); + } } } @@ -86,8 +93,9 @@ AtomNumber ActionWithInputMatrix::getAbsoluteIndexOfCentralAtom(const unsigned& } double ActionWithInputMatrix::retrieveConnectionValue( const unsigned& i, const unsigned& j, std::vector& vals ) const { - if( !mymatrix->matrixElementIsActive( i, j ) ) + if( !mymatrix->matrixElementIsActive( i, j ) ) { return 0; + } unsigned myelem = mymatrix->getStoreIndexFromMatrixIndices( i, j ); // unsigned vi; double df; @@ -100,8 +108,9 @@ void ActionWithInputMatrix::getInputData( const unsigned& ind, const bool& norme std::vector tvals( mymatrix->getNumberOfComponents() ); orient0.assign(orient0.size(),0); for(unsigned i=0; igetNumberOfColumns(); ++i) { - if( mymatrix->undirectedGraph() && ind==i ) + if( mymatrix->undirectedGraph() && ind==i ) { continue; + } orient0[1]+=retrieveConnectionValue( ind, i, tvals ); } orient0[0]=1.0; @@ -111,8 +120,9 @@ void ActionWithInputMatrix::getInputData( const unsigned& ind, const bool& norme } void ActionWithInputMatrix::addConnectionDerivatives( const unsigned& i, const unsigned& j, MultiValue& myvals, MultiValue& myvout ) const { - if( !mymatrix->matrixElementIsActive( i, j ) ) + if( !mymatrix->matrixElementIsActive( i, j ) ) { return; + } unsigned myelem = mymatrix->getStoreIndexFromMatrixIndices( i, j ); // Get derivatives and add mymatrix->retrieveDerivatives( myelem, false, myvals ); @@ -131,8 +141,9 @@ 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 ) + if( mymatrix->undirectedGraph() && ind==i ) { continue; + } addConnectionDerivatives( ind, i, myvals, myder ); } myder.updateDynamicList(); @@ -143,14 +154,16 @@ MultiValue& ActionWithInputMatrix::getInputDerivatives( const unsigned& ind, con unsigned ActionWithInputMatrix::getNumberOfNodeTypes() const { unsigned size = (mymatrix->function)->mybasemulticolvars.size(); - if( size==0 ) + if( size==0 ) { return 1; + } return size; } unsigned ActionWithInputMatrix::getNumberOfQuantities() const { - if( (mymatrix->function)->mybasemulticolvars.size()==0 ) + if( (mymatrix->function)->mybasemulticolvars.size()==0 ) { return 2; + } return (mymatrix->function)->mybasemulticolvars[0]->getNumberOfQuantities(); } diff --git a/src/adjmat/AdjacencyMatrixBase.cpp b/src/adjmat/AdjacencyMatrixBase.cpp index 5a1acaf62c..57309ea02a 100644 --- a/src/adjmat/AdjacencyMatrixBase.cpp +++ b/src/adjmat/AdjacencyMatrixBase.cpp @@ -51,20 +51,23 @@ void AdjacencyMatrixBase::parseConnectionDescriptions( const std::string& key, c if( !multiple ) { sw.resize(1); parse(key,sw[0]); - if(sw[0].length()==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 ) ) + if( !parseNumbered(key, i, input ) ) { break; + } sw.push_back( input ); } } setupConnector( connect_id, 0, 0, sw ); } else { - if( multiple ) + if( multiple ) { error("keyword " + key + " does not work with multiple input strings"); + } unsigned nr, nc; if( nrow_t==0 ) { nr=nc=getNumberOfNodeTypes(); @@ -99,21 +102,24 @@ void AdjacencyMatrixBase::parseConnectionDescriptions( const std::string& key, c } unsigned AdjacencyMatrixBase::getSizeOfInputVectors() const { - if( mybasemulticolvars.size()==0 ) + if( mybasemulticolvars.size()==0 ) { return 2; + } unsigned nq = mybasemulticolvars[0]->getNumberOfQuantities(); for(unsigned i=1; igetNumberOfQuantities()!=nq ) + 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 ) + if( size==0 ) { return 1; + } return size; } @@ -121,8 +127,9 @@ void AdjacencyMatrixBase::retrieveTypeDimensions( unsigned& nrows, unsigned& nco bool allsame=(ablocks[0].size()==ablocks[1].size()); if( allsame ) { for(unsigned i=0; i& all_atoms ) { std::string param; - if( symmetric && ablocks[0].size()==ablocks[1].size() ) + if( symmetric && ablocks[0].size()==ablocks[1].size() ) { param="SYMMETRIC"; + } if( !symmetric ) { bool usehbonds=( ablocks[0].size()==ablocks[1].size() ); if( usehbonds ) { @@ -192,8 +204,9 @@ void AdjacencyMatrixBase::finishMatrixSetup( const bool& symmetric, const std::v break; } } - if( usehbonds ) + if( usehbonds ) { param="HBONDS"; + } } } @@ -230,8 +243,9 @@ void AdjacencyMatrixBase::recalculateMatrixElement( const unsigned& myelem, Mult decodeIndexToAtoms( getTaskCode( myelem ), myatoms ); unsigned i=myatoms[0], j=myatoms[1]; for(unsigned k=bookeeping(i,j).first; k0 ) + 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 fd3b581f85..bc963c74f6 100644 --- a/src/adjmat/AdjacencyMatrixVessel.cpp +++ b/src/adjmat/AdjacencyMatrixVessel.cpp @@ -39,12 +39,15 @@ AdjacencyMatrixVessel::AdjacencyMatrixVessel( const vesselbase::VesselOptions& d plumed_assert( function ); parseFlag("SYMMETRIC",symmetric); parseFlag("HBONDS",hbonds); - if( symmetric && hbonds ) + if( symmetric && hbonds ) { error("matrix should be either symmetric or hbonds"); - if( symmetric && function->ablocks[0].size()!=function->ablocks[1].size() ) + } + 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() ) + } + if( hbonds && function->ablocks[0].size()!=function->ablocks[1].size() ) { error("matrix is supposed to be hbonds but nrows!=ncols"); + } } bool AdjacencyMatrixVessel::isSymmetric() const { @@ -68,16 +71,19 @@ bool AdjacencyMatrixVessel::matrixElementIsActive( const unsigned& ielem, const } unsigned AdjacencyMatrixVessel::getStoreIndexFromMatrixIndices( const unsigned& ielem, const unsigned& jelem ) const { - if( !symmetric && !hbonds ) + if( !symmetric && !hbonds ) { return (function->ablocks[1].size())*ielem + jelem; + } if( !symmetric ) { plumed_dbg_assert( ielem!=jelem ); - if( jelemablocks[1].size()-1)*ielem + jelem; + } return (function->ablocks[1].size()-1)*ielem + jelem - 1; } - if( ielem>jelem ) + if( ielem>jelem ) { return 0.5*ielem*(ielem-1)+jelem; + } return 0.5*jelem*(jelem-1) + ielem; } @@ -101,17 +107,20 @@ void AdjacencyMatrixVessel::retrieveMatrix( DynamicList& myactive_elem std::vector vals( getNumberOfComponents() ); for(unsigned i=0; igetPositionInFullTaskList(i), k, j ); - if( symmetric ) + if( symmetric ) { mymatrix(k,j)=mymatrix(j,k)=vals[0]*vals[1]; - else + } + else { mymatrix(k,j)=vals[0]*vals[1]; + } } myactive_elements.updateActiveMembers(); } @@ -119,22 +128,25 @@ 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 ); - if( nneigh[j]>=adj_list.ncols() || nneigh[k]>=adj_list.ncols() ) + 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; @@ -148,14 +160,16 @@ void AdjacencyMatrixVessel::retrieveEdgeList( unsigned& nedge, std::vector myvals( getNumberOfComponents() ); - if( getNumberOfStoredValues()>edge_list.size() ) + 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++; @@ -163,8 +177,9 @@ void AdjacencyMatrixVessel::retrieveEdgeList( unsigned& nedge, std::vector myvals( getNumberOfComponents() ); diff --git a/src/adjmat/AlignedMatrixBase.cpp b/src/adjmat/AlignedMatrixBase.cpp index ba8596f441..3139dc959c 100644 --- a/src/adjmat/AlignedMatrixBase.cpp +++ b/src/adjmat/AlignedMatrixBase.cpp @@ -53,10 +53,12 @@ AlignedMatrixBase::AlignedMatrixBase( const ActionOptions& ao ): readMaxTwoSpeciesMatrix( "ATOMS", "ATOMSA", "ATOMSB", true ); unsigned nrows, ncols; retrieveTypeDimensions( nrows, ncols, ncol_t ); - if( mybasemulticolvars.size()==0 ) + if( mybasemulticolvars.size()==0 ) { error("cannot use atom indices as input to this variable / input was not specified"); - if( getSizeOfInputVectors()<3 ) + } + 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); @@ -66,8 +68,9 @@ AlignedMatrixBase::AlignedMatrixBase( const ActionOptions& ao ): for(unsigned i=0; isfmax ) + if( tsf>sfmax ) { sfmax=tsf; + } } } // And set the link cell cutoff @@ -80,10 +83,12 @@ void AlignedMatrixBase::setupConnector( const unsigned& id, const unsigned& i, c plumed_assert( desc.size()==1 ); std::string errors; switchingFunction(j,i).set(desc[0],errors); - if( errors.length()!=0 ) + if( errors.length()!=0 ) { error("problem reading switching function in SWITCH keywrd description " + errors); - if( j!=i) + } + 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 ); @@ -92,8 +97,9 @@ 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() fake_atoms; // Find what action we are taking the clusters from - if( !parseMultiColvarAtomList("CLUSTERS",-1,fake_atoms ) ) + if( !parseMultiColvarAtomList("CLUSTERS",-1,fake_atoms ) ) { error("unable to interpret input CLUSTERS" ); - if( mybasemulticolvars.size()!=1 ) + } + if( mybasemulticolvars.size()!=1 ) { error("should be exactly one multicolvar input"); + } atom_lab.resize(0); myclusters = dynamic_cast( mybasemulticolvars[0] ); - if( !myclusters ) + 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) + for(unsigned i=0; igetNumberOfNodes(); ++i) { myfatoms.setAtomIndex( i, i ); + } } void ClusterAnalysisBase::turnOnDerivatives() { // Check for dubious vessels for(unsigned i=0; igetName()=="MEAN" ) + if( getPntrToVessel(i)->getName()=="MEAN" ) { error("MEAN of cluster is not differentiable"); - if( getPntrToVessel(i)->getName()=="VMEAN" ) + } + if( getPntrToVessel(i)->getName()=="VMEAN" ) { error("VMEAN of cluster is not differentiable"); + } } MultiColvarBase::turnOnDerivatives(); } diff --git a/src/adjmat/ClusterDiameter.cpp b/src/adjmat/ClusterDiameter.cpp index cedd2b4373..e4a67c905d 100644 --- a/src/adjmat/ClusterDiameter.cpp +++ b/src/adjmat/ClusterDiameter.cpp @@ -91,15 +91,18 @@ ClusterDiameter::ClusterDiameter(const ActionOptions&ao): // Find out which cluster we want parse("CLUSTER",clustr); - if( clustr<1 ) + if( clustr<1 ) { error("cannot look for a cluster larger than the largest cluster"); - if( clustr>getNumberOfNodes() ) + } + if( clustr>getNumberOfNodes() ) { error("cluster selected is invalid - too few atoms in system"); + } // Create the task list for(unsigned i=0; i fake_atoms; @@ -127,8 +130,9 @@ void ClusterDistribution::calculate() { // Activate the relevant tasks nderivatives = getNumberOfDerivatives(); deactivateAllTasks(); - for(unsigned i=0; i myatoms; retrieveAtomsInCluster( current+1, myatoms ); // This deals with filters - if( myatoms.size()==1 && !nodeIsActive(myatoms[0]) ) + if( myatoms.size()==1 && !nodeIsActive(myatoms[0]) ) { return ; + } std::vector vals( getNumberOfQuantities() ); MultiValue tvals( getNumberOfQuantities(), nderivatives ); diff --git a/src/adjmat/ClusterProperties.cpp b/src/adjmat/ClusterProperties.cpp index 860d20da21..e62e5f038c 100644 --- a/src/adjmat/ClusterProperties.cpp +++ b/src/adjmat/ClusterProperties.cpp @@ -79,10 +79,12 @@ void ClusterProperties::registerKeywords( Keywords& keys ) { keys.use("MEAN"); keys.use("MORE_THAN"); keys.use("LESS_THAN"); - if( keys.reserved("VMEAN") ) + if( keys.reserved("VMEAN") ) { keys.use("VMEAN"); - if( keys.reserved("VSUM") ) + } + if( keys.reserved("VSUM") ) { keys.use("VSUM"); + } keys.use("BETWEEN"); keys.use("HISTOGRAM"); keys.use("MOMENTS"); @@ -101,14 +103,17 @@ ClusterProperties::ClusterProperties(const ActionOptions&ao): // Find out which cluster we want parse("CLUSTER",clustr); - if( clustr<1 ) + if( clustr<1 ) { error("cannot look for a cluster larger than the largest cluster"); - if( clustr>getNumberOfNodes() ) + } + 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; @@ -121,8 +126,9 @@ void ClusterProperties::calculate() { retrieveAtomsInCluster( clustr, myatoms ); // Activate the relevant tasks deactivateAllTasks(); - for(unsigned i=0; i vals( myvals.getNumberOfValues() ); getPropertiesOfNode( current, vals ); - if( !doNotCalculateDerivatives() ) + if( !doNotCalculateDerivatives() ) { getNodePropertyDerivatives( current, myvals ); - for(unsigned k=0; kgetNumberOfNodes() ) + } + 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 ); diff --git a/src/adjmat/ClusterWithSurface.cpp b/src/adjmat/ClusterWithSurface.cpp index 5e1e6b663e..c420ff9f30 100644 --- a/src/adjmat/ClusterWithSurface.cpp +++ b/src/adjmat/ClusterWithSurface.cpp @@ -110,22 +110,26 @@ ClusterWithSurface::ClusterWithSurface(const ActionOptions&ao): ClusteringBase(ao) { std::vector fake_atoms; - if( !parseMultiColvarAtomList("CLUSTERS",-1,fake_atoms ) ) + if( !parseMultiColvarAtomList("CLUSTERS",-1,fake_atoms ) ) { error("unable to find CLUSTERS input"); - if( mybasemulticolvars.size()!=1 ) + } + 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 ) + 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 ) + 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 @@ -158,8 +162,9 @@ unsigned ClusterWithSurface::getNumberOfQuantities() const { double ClusterWithSurface::getCutoffForConnection() const { double tcut = myclusters->getCutoffForConnection(); - if( tcut>std::sqrt(rcut_surf2) ) + if( tcut>std::sqrt(rcut_surf2) ) { return tcut; + } return std::sqrt(rcut_surf2); } @@ -169,15 +174,17 @@ void ClusterWithSurface::retrieveAtomsInCluster( const unsigned& clust, std::vec // Prevent double counting std::vector incluster( getNumberOfNodes(), false ); - for(unsigned i=0; i surface_atom( getNumberOfNodes(), false ); for(unsigned i=0; iundirectedGraph() ) + } + if( !getAdjacencyVessel()->undirectedGraph() ) { error("input contact matrix is incompatible with clustering"); + } } if( keywords.exists("MATRIX") ) { std::vector fake_atoms; @@ -52,8 +54,9 @@ ClusteringBase::ClusteringBase(const ActionOptions&ao): 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() ) + if( getBaseMultiColvar(0)->isDensity() ) { error("DFS clustering cannot be differentiated if base multicolvar is DENSITY"); + } } // Ensure that derivatives are turned on in base classes diff --git a/src/adjmat/ContactAlignedMatrix.cpp b/src/adjmat/ContactAlignedMatrix.cpp index 5f8afdded2..7fd4d6df51 100644 --- a/src/adjmat/ContactAlignedMatrix.cpp +++ b/src/adjmat/ContactAlignedMatrix.cpp @@ -105,8 +105,9 @@ void ContactAlignedMatrix::readOrientationConnector( const unsigned& i, const un plumed_assert( desc.size()==1 ); std::string errors; sf(j,i).set(desc[0],errors); - if( j!=i ) + 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() ); } @@ -115,8 +116,9 @@ double ContactAlignedMatrix::computeVectorFunction( const unsigned& iv, const un Vector& dconn, std::vector& dvec1, std::vector& dvec2 ) const { double dot_df, dot=0; dconn.zero(); - for(unsigned k=2; ksfmax ) + if( tsf>sfmax ) { sfmax=tsf; + } } } // And set the link cell cutoff @@ -126,17 +127,20 @@ void ContactMatrix::setupConnector( const unsigned& id, const unsigned& i, const plumed_assert( id==0 && desc.size()==1 ); std::string errors; switchingFunction(j,i).set(desc[0],errors); - if( errors.length()!=0 ) + if( errors.length()!=0 ) { error("problem reading switching function description " + errors); - if( j!=i) + } + 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 ) + if( maxconnections>0 ) { edge_list.resize( getNumberOfNodes()*maxconnections ); - else + } + else { edge_list.resize(0.5*getNumberOfNodes()*(getNumberOfNodes()-1)); + } #else nneigh.resize( getNumberOfNodes() ); color.resize(getNumberOfNodes()); - if( maxconnections>0 ) + if( maxconnections>0 ) { adj_list.resize(getNumberOfNodes(),maxconnections); - else + } + else { adj_list.resize(getNumberOfNodes(),getNumberOfNodes()); + } #endif } @@ -135,8 +139,9 @@ 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 ); @@ -159,8 +164,9 @@ int DFSClustering::explore( const unsigned& index ) { color[index]=1; for(unsigned i=0; i( mstring ); - if( !mm ) + 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 ) + if( mymatrix ) { break ; + } } - if( !mymatrix ) + if( !mymatrix ) { error( mm->getLabel() + " does not calculate an adjacency matrix"); - if( !mymatrix->isSymmetric() ) + } + if( !mymatrix->isSymmetric() ) { error("input contact matrix must be symmetric"); - if( maxconnections==0 ) + } + if( maxconnections==0 ) { maxconnections=mymatrix->getNumberOfRows(); + } parse("FILE",filename); log.printf(" printing graph to file named %s \n",filename.c_str() ); checkRead(); @@ -112,14 +117,16 @@ void DumpGraph::update() { ofile.open( filename ); ofile.printf("graph G { \n"); // Print all nodes - for(unsigned i=0; igetNumberOfRows(); ++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 ); mymatrix->retrieveEdgeList( nedge, edge_list ); - for(unsigned i=0; isfmax ) + if( tsf>sfmax ) { sfmax=tsf; + } } } // Set the link cell cutoff @@ -167,38 +168,46 @@ void HBondMatrix::setupConnector( const unsigned& id, const unsigned& i, const u if( id==0 ) { std::string errors; distanceOOSwitch(j,i).set(desc[0],errors); - if( errors.length()!=0 ) + if( errors.length()!=0 ) { error("problem reading switching function description " + errors); - if( j!=i) + } + 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 ) + if( errors.length()!=0 ) { error("problem reading switching function description " + errors); - if( j!=i) + } + 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 ) + if( errors.length()!=0 ) { error("problem reading switching function description " + errors); - if( j!=i) + } + 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) ) + 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 ) + 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; + } } std::vector fake_atoms; setupMultiColvarBase( fake_atoms ); @@ -118,8 +122,9 @@ double MatrixColumnSums::compute( const unsigned& tinded, multicolvar::AtomValue std::vector tvals( mymatrix->getNumberOfComponents() ); unsigned nrows = mymatrix->getNumberOfRows(); for(unsigned i=0; iundirectedGraph() && tinded==i ) + if( mymatrix->undirectedGraph() && tinded==i ) { continue; + } sum+=retrieveConnectionValue( i, tinded, tvals ); } @@ -127,8 +132,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 ) + if( mymatrix->isSymmetric() && tinded==i ) { continue ; + } addConnectionDerivatives( i, tinded, myvals, myvout ); } } diff --git a/src/adjmat/MatrixRowSums.cpp b/src/adjmat/MatrixRowSums.cpp index e96943b3b4..e3f1190ba0 100644 --- a/src/adjmat/MatrixRowSums.cpp +++ b/src/adjmat/MatrixRowSums.cpp @@ -93,8 +93,9 @@ MatrixRowSums::MatrixRowSums(const ActionOptions& ao): Action(ao), ActionWithInputMatrix(ao) { - if( (mymatrix->getMatrixAction())->mybasemulticolvars.size()>0 ) + 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); diff --git a/src/adjmat/OutputCluster.cpp b/src/adjmat/OutputCluster.cpp index cb29341051..4cbf72fcd8 100644 --- a/src/adjmat/OutputCluster.cpp +++ b/src/adjmat/OutputCluster.cpp @@ -109,14 +109,16 @@ OutputCluster::OutputCluster(const ActionOptions& ao): ofile.link(*this); std::string file; parse("FILE",file); - if( file.length()==0 ) + 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" ) + if( file.substr(dot+1)=="xyz" ) { output_xyz=true; + } } ofile.open(file); @@ -124,15 +126,17 @@ OutputCluster::OutputCluster(const ActionOptions& ao): parseFlag("MAKE_WHOLE",makewhole); parse("MAXDEPTH",maxdepth); parse("MAXGOES",maxgoes); - if( makewhole && !output_xyz) + 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]); myclusters = plumed.getActionSet().selectWithLabel( matname[0] ); - if( !myclusters ) + 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; @@ -140,10 +144,12 @@ OutputCluster::OutputCluster(const ActionOptions& ao): // Read in the cluster we are calculating parse("CLUSTER",clustr); - if( clustr<1 ) + if( clustr<1 ) { error("cannot look for a cluster larger than the largest cluster"); - if( clustr>myclusters->getNumberOfNodes() ) + } + 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() ); } @@ -155,8 +161,9 @@ void OutputCluster::update() { if( makewhole ) { // Retrieve the atom positions atomsin.resize( myatoms.size() ); - 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() ); @@ -191,8 +198,9 @@ void OutputCluster::update() { // Now set visited so that only those atoms in largest cluster will be start points for PBCing visited.assign( visited.size(), false ); for(unsigned i=0; ircut2 ) { visited[j]=true; - for(unsigned depth=0; depth<=maxdepth; ++depth) + for(unsigned depth=0; depth<=maxdepth; ++depth) { explore( j, depth ); + } } } } } // And print final positions - for(unsigned i=0; igetPositionOfAtomForLinkCells( myatoms[i] ); @@ -236,15 +247,17 @@ 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()); + } ofile.printf("\n"); } } void OutputCluster::explore( const unsigned& index, const unsigned& depth ) { - if( depth==0 ) + if( depth==0 ) { return ; + } for(unsigned i=0; ihasDifferentiableOrientation() ) error("cannot use multicolvar of type " + getBaseMultiColvar(i)->getName() ); // } - if( !getAdjacencyVessel()->isSymmetric() ) + if( !getAdjacencyVessel()->isSymmetric() ) { error("input contact matrix is not symmetric"); + } std::vector fake_atoms; setupMultiColvarBase( fake_atoms ); @@ -148,8 +149,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; iaddDerivative( i, mymat_ders(j,i) ); + } } } diff --git a/src/adjmat/TopologyMatrix.cpp b/src/adjmat/TopologyMatrix.cpp index 043989ae03..e02f3d7c10 100644 --- a/src/adjmat/TopologyMatrix.cpp +++ b/src/adjmat/TopologyMatrix.cpp @@ -120,8 +120,9 @@ TopologyMatrix::TopologyMatrix( const ActionOptions& ao ): std::string errors, thresh_sw_str; parse("DENSITY_THRESHOLD",thresh_sw_str); threshold_switch.set(thresh_sw_str, errors ); - if( errors.length()>0 ) + 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 ) + if( tsf>sfmax ) { sfmax=tsf; + } double rsf=cylinder_sw(i,j).get_dmax(); - if( rsf>rfmax ) + if( rsf>rfmax ) { rfmax=rsf; + } double lsf=low_sf(i,j).get_dmax(); - if( lsf>lsfmax ) + if( lsf>lsfmax ) { lsfmax=lsf; + } } } // Get the width of the bead @@ -162,8 +166,9 @@ TopologyMatrix::TopologyMatrix( const ActionOptions& ao ): double maxsize=0; for(unsigned i=0; imaxsize ) + if( binw_mat(i,j)>maxsize ) { maxsize=binw_mat(i,j); + } } } // Set the maximum number of bins that we will need to compute @@ -182,39 +187,47 @@ void TopologyMatrix::setupConnector( const unsigned& id, const unsigned& i, cons if( id==0 ) { std::string errors; switchingFunction(j,i).set(desc[0],errors); - if( errors.length()!=0 ) + if( errors.length()!=0 ) { error("problem reading switching function description " + errors); - if( j!=i) + } + 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 ) + if( errors.length()!=0 ) { error("problem reading switching function description " + errors); - if( j!=i) + } + 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 ) + if( errors.length()!=0 ) { error("problem reading switching function description " + errors); - if( j!=i ) + } + 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 ) + 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;ilow_sf( getBaseColvarNumber( myatoms.getIndex(0) ), getBaseColvarNumber( myatoms.getIndex(1) ) ).get_dmax() ) + 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()) ) + 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 ); @@ -337,8 +354,9 @@ void TopologyMatrix::calculateForThreeAtoms( const unsigned& iat, const Vector& Tensor vir; for(unsigned bin=0; binbinw*(bin+1)+bead.getCutoff() ) + 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 ); diff --git a/src/analysis/AnalysisBase.cpp b/src/analysis/AnalysisBase.cpp index b642e00070..64b9e8e613 100644 --- a/src/analysis/AnalysisBase.cpp +++ b/src/analysis/AnalysisBase.cpp @@ -54,13 +54,15 @@ AnalysisBase::AnalysisBase(const ActionOptions&ao): 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 ) + 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 ) + if( !my_input_data ) { error("could not find analysis action named " + datastr ); + } addDependency( my_input_data ); } } @@ -77,15 +79,17 @@ std::vector AnalysisBase::getArgumentNames() { } void AnalysisBase::update() { - if( getStep()==0 || ( getStride()>0 && !onStep() ) ) + if( getStep()==0 || ( getStride()>0 && !onStep() ) ) { return; + } // And do the analysis performAnalysis(); } void AnalysisBase::runFinalJobs() { - if( getStride()>0 ) + if( getStride()>0 ) { return; + } performAnalysis(); } diff --git a/src/analysis/Average.cpp b/src/analysis/Average.cpp index 60ec4fd34d..0c95357aec 100644 --- a/src/analysis/Average.cpp +++ b/src/analysis/Average.cpp @@ -122,8 +122,9 @@ Average::Average( const ActionOptions& ao ): ActionWithAveraging(ao) { addValue(); // Create a value so that we can output the average - if( getNumberOfArguments()!=1 ) + if( getNumberOfArguments()!=1 ) { error("only one quantity can be averaged at a time"); + } std::string instring; if( getPntrToArgument(0)->isPeriodic() ) { std::string min, max; diff --git a/src/analysis/AverageVessel.cpp b/src/analysis/AverageVessel.cpp index c989f2c0c6..7358fdf072 100644 --- a/src/analysis/AverageVessel.cpp +++ b/src/analysis/AverageVessel.cpp @@ -38,10 +38,12 @@ AverageVessel::AverageVessel( const vesselbase::VesselOptions& da): void AverageVessel::resize() { resizeBuffer(0); - if( domain.size()==2 ) + if( domain.size()==2 ) { setDataSize(2); - else + } + else { setDataSize(1); + } } void AverageVessel::accumulate( const double& weight, const double& val ) { @@ -50,13 +52,15 @@ void AverageVessel::accumulate( const double& weight, const double& val ) { double tval = 2*pi*( val - domain[0] ) / ( domain[1] - domain[0] ); addDataElement( 0, weight*std::sin(tval) ); addDataElement( 1, weight*std::cos(tval) ); - } else + } else { addDataElement( 0, weight*val ); + } } double AverageVessel::getAverage() const { - if( domain.size()==2 ) + 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/Committor.cpp b/src/analysis/Committor.cpp index aafebf42cd..c1cbb24b15 100644 --- a/src/analysis/Committor.cpp +++ b/src/analysis/Committor.cpp @@ -116,12 +116,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() ) + if( tmpl.empty() && tmpu.empty() ) { break; - if( tmpl.size()!=getNumberOfArguments()) + } + 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()) + } + 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; @@ -135,16 +138,19 @@ Committor::Committor(const ActionOptions&ao): for(unsigned b=0; bupperlimits[b][i]) + 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) + if(doNotStop) { log.printf(" COMMITOR will keep track of the visited basins without stopping the simulations\n"); + } } - 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() ) + if( it!=args.end() ) { it->second = value; - else + } + else { args.insert( std::pair( name, value ) ); + } } bool DataCollectionObject::transferDataToPDB( PDB& mypdb ) { @@ -56,16 +61,19 @@ 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() ) + if( pdb_pos.size()==positions.size() ) { mypdb.setAtomPositions( positions ); - else if( pdb_pos.size()>0 ) + } + 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 78b855aae4..b2914d817c 100644 --- a/src/analysis/DataCollectionObject.h +++ b/src/analysis/DataCollectionObject.h @@ -67,14 +67,17 @@ 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() ) + 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 ) + if( a==myaction ) { return args.find( name.substr(dot+1) )->second; - else + } + else { plumed_merror("could not find required data in collection object"); + } } } diff --git a/src/analysis/EuclideanDissimilarityMatrix.cpp b/src/analysis/EuclideanDissimilarityMatrix.cpp index 443f8c51f1..6c4309e9dd 100644 --- a/src/analysis/EuclideanDissimilarityMatrix.cpp +++ b/src/analysis/EuclideanDissimilarityMatrix.cpp @@ -99,8 +99,9 @@ EuclideanDissimilarityMatrix::EuclideanDissimilarityMatrix( const ActionOptions& } else if( getNumberOfArguments()==0 ) { mypdb.setAtomNumbers( my_input_data->getAtomIndexes() ); mypdb.addBlockEnd( my_input_data->getAtomIndexes().size() ); - if( mtype=="EUCLIDEAN" ) + if( mtype=="EUCLIDEAN" ) { mtype="OPTIMAL"; + } } } log.printf(" measuring distances using %s metric \n",mtype.c_str() ); @@ -122,8 +123,9 @@ EuclideanDissimilarityMatrix::EuclideanDissimilarityMatrix( const ActionOptions& break; } } - if( !found ) + if( !found ) { error("input named " + my_input_data->getLabel() + " does not store/calculate quantity named " + argnames[i] ); + } } mypdb.setArgumentNames( argnames ); requestArguments( myargs ); @@ -156,10 +158,12 @@ 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() ) + if( !usingLowMem() ) { dd=dissimilarities(iframe,jframe) = dissimilarities(jframe,iframe) = distance( getPbc(), getArguments(), myref1.get(), myref2.get(), true ); - else + } + 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 85c70c65f4..610c2e5d90 100644 --- a/src/analysis/FarthestPointSampling.cpp +++ b/src/analysis/FarthestPointSampling.cpp @@ -55,8 +55,9 @@ FarthestPointSampling::FarthestPointSampling( const ActionOptions& ao ): Action(ao), LandmarkSelectionBase(ao) { - if( !dissimilaritiesWereSet() ) + if( !dissimilaritiesWereSet() ) { error("dissimilarities have not been calcualted in input action"); + } parse("SEED",seed); } @@ -72,8 +73,9 @@ void FarthestPointSampling::selectLandmarks() { // 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) + 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(); ++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 c088d4bd9e..47477ebbdb 100644 --- a/src/analysis/Histogram.cpp +++ b/src/analysis/Histogram.cpp @@ -254,14 +254,16 @@ Histogram::Histogram(const ActionOptions&ao): parse("VECTORS",vlab); if( vlab.length()>0 ) { ActionWithVessel* myv = plumed.getActionSet().selectWithLabel( vlab ); - if( !myv ) + 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 ) + 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; @@ -269,8 +271,9 @@ Histogram::Histogram(const ActionOptions&ao): if( mlab.size()>0 ) { for(unsigned i=0; i( mlab[i] ); - if( !myv ) + 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() ); @@ -279,12 +282,14 @@ Histogram::Histogram(const ActionOptions&ao): } unsigned nvals = myvessels[0]->getFullNumberOfTasks(); for(unsigned i=1; igetFullNumberOfTasks() ) + 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() ); + } log.printf("\n"); } else { error("input data is missing use ARG/VECTORS/DATA"); @@ -294,49 +299,61 @@ Histogram::Histogram(const ActionOptions&ao): // Read stuff for grid unsigned narg = getNumberOfArguments(); - if( myvessels.size()>0 ) + 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(); + } // Input for PBC - if( myvessels[0]->isPeriodic() ) + if( myvessels[0]->isPeriodic() ) { vstring+=" PBC=T"; - else + } + else { vstring+=" PBC=F"; + } for(unsigned i=1; iisPeriodic() ) + if( myvessels[i]->isPeriodic() ) { vstring+=",T"; - else + } + else { vstring+=",F"; + } } } else { vstring += " COORDINATES=" + getPntrToArgument(0)->getName(); - for(unsigned i=1; igetName(); + } // Input for PBC - if( getPntrToArgument(0)->isPeriodic() ) + if( getPntrToArgument(0)->isPeriodic() ) { vstring+=" PBC=T"; - else + } + else { vstring+=" PBC=F"; + } for(unsigned i=1; iisPeriodic() ) + if( getPntrToArgument(i)->isPeriodic() ) { vstring+=",T"; - else + } + 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 ) + 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); @@ -351,24 +368,28 @@ Histogram::Histogram(const ActionOptions&ao): } else { std::vector nbin; parseVector("GRID_BIN",nbin); - if( nbin.size()!=1 ) + if( nbin.size()!=1 ) { error("should only be one index for number of bins with spherical grid"); - if( mygrid->getType()=="fibonacci" ) + } + 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) + 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) + for(unsigned i=0; igetNumberOfPoints(); ++i) { addTaskToList(i); + } myhist->addOneKernelEachTimeOnly(); setAveragingAction( std::move(grid), myhist->noDiscreteKernels() ); } @@ -380,11 +401,13 @@ void Histogram::turnOnDerivatives() { std::vector all_atoms, tmp_atoms; for(unsigned i=0; i( myvessels[i] ); - if( !mbase ) + 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 ); } @@ -392,8 +415,9 @@ 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(); @@ -403,18 +427,21 @@ void Histogram::turnOnDerivatives() { unsigned Histogram::getNumberOfDerivatives() { if( in_apply ) { unsigned nder=0; - for(unsigned i=0; igetNumberOfDerivatives(); + } return nder; } return getNumberOfArguments(); } unsigned Histogram::getNumberOfQuantities() const { - if( mvectors ) + if( mvectors ) { return myvessels[0]->getNumberOfQuantities(); - else if( myvessels.size()>0 ) + } + else if( myvessels.size()>0 ) { return myvessels.size()+2; + } return ActionWithAveraging::getNumberOfQuantities(); } @@ -428,10 +455,12 @@ void Histogram::prepareForAveraging() { unsigned itask=myvessels[0]->getActiveTask(i); double tnorm = cvals[0]; for(unsigned j=1; jgetActiveTask(i)!=itask ) + if( myvessels[j]->getActiveTask(i)!=itask ) { error("mismatched task identities in histogram suggests histogram is meaningless"); - if( cvals.size()!=myvessels[j]->getNumberOfQuantities() ) + } + if( cvals.size()!=myvessels[j]->getNumberOfQuantities() ) { cvals.resize( myvessels[j]->getNumberOfQuantities() ); + } stashes[j]->retrieveSequentialValue( i, false, cvals ); tnorm *= cvals[0]; } @@ -440,15 +469,18 @@ void Histogram::prepareForAveraging() { } lockContributors(); // Sort out normalization of histogram - if( !noNormalization() ) + if( !noNormalization() ) { ww = cweight / norm; - else + } + 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); kernel=myhist->getKernelAndNeighbors( point, num_neigh, neighbors ); @@ -456,8 +488,9 @@ void Histogram::prepareForAveraging() { if( num_neigh>1 ) { // Activate relevant tasks deactivateAllTasks(); - for(unsigned i=0; inoDiscreteKernels() ); + } } void Histogram::finishAveraging() { - if( myvessels.size()==0 ) + 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) + 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) + for(unsigned i=2; igetNumberOfQuantities(); ++i) { myvals.addDerivative( i-1, jder, tmpval.getDerivative(i, jder) ); + } } myvals.updateDynamicList(); } @@ -515,8 +553,9 @@ void Histogram::compute( const unsigned& current, MultiValue& myvals ) const { // 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() ) + 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] ); @@ -535,8 +575,9 @@ void Histogram::compute( const unsigned& current, MultiValue& myvals ) const { 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; j> vv( myhist->getVectorOfValues() ); @@ -557,8 +599,9 @@ 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] ); + } // 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 ); @@ -574,8 +617,9 @@ void Histogram::compute( const unsigned& current, MultiValue& myvals ) const { 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; + } } // Set the derivatives and delete the vector of values for(unsigned i=0; iwasForced() ) + if( !myhist->wasForced() ) { return ; + } in_apply=true; // Run the loop to calculate the forces runAllTasks(); @@ -595,8 +640,9 @@ void Histogram::apply() { 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]; diff --git a/src/analysis/LandmarkSelectionBase.cpp b/src/analysis/LandmarkSelectionBase.cpp index 87b4f83761..53959fdcc9 100644 --- a/src/analysis/LandmarkSelectionBase.cpp +++ b/src/analysis/LandmarkSelectionBase.cpp @@ -36,19 +36,23 @@ LandmarkSelectionBase::LandmarkSelectionBase( const ActionOptions& ao ): AnalysisBase(ao), nlandmarks(0) { - if( keywords.exists("NLANDMARKS") ) + if( keywords.exists("NLANDMARKS") ) { parse("NLANDMARKS",nlandmarks); + } log.printf(" selecting %u landmark points \n",nlandmarks); lweights.resize( nlandmarks ); parseFlag("NOVORONOI",novoronoi); - if( !novoronoi && !dissimilaritiesWereSet() ) + if( !novoronoi && !dissimilaritiesWereSet() ) { error("cannot calculate voronoi weights without dissimilarity mesaure"); + } - if( !novoronoi ) + if( !novoronoi ) { log.printf(" ascribing weights to landmarks using voronoi analysis\n"); - else + } + else { log.printf(" ascribing weights of original points to landmark\n"); + } } void LandmarkSelectionBase::selectFrame( const unsigned& iframe ) { @@ -59,16 +63,18 @@ void LandmarkSelectionBase::performAnalysis() { landmark_indices.resize(0); selectLandmarks(); plumed_dbg_assert( nlandmarks==getNumberOfDataPoints() ); - if( lweights.size()!=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] ); + } } } diff --git a/src/analysis/LandmarkStaged.cpp b/src/analysis/LandmarkStaged.cpp index 5f7aa76d5b..d13fe49dcd 100644 --- a/src/analysis/LandmarkStaged.cpp +++ b/src/analysis/LandmarkStaged.cpp @@ -98,8 +98,9 @@ void LandmarkStaged::selectLandmarks() { fpslandmarks[i]=j; } } - for(unsigned k=0; kgetDissimilarity( fpslandmarks[i], k ); + } } // Initial FPS selection of m landmarks completed @@ -110,8 +111,9 @@ void LandmarkStaged::selectLandmarks() { //Calculate total weight of voronoi polyhedras double vweight=0; - for(unsigned i=0; i selected(N, false); unsigned ncount=0; @@ -124,8 +126,9 @@ void LandmarkStaged::selectLandmarks() { if( running_vweight>=rand ) { double tweight=0; for(unsigned i=0; i tmp_vals( my_input_data->getArgumentNames() ); req_vals.resize( tmp_vals.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; i(this); - if( ! moldat ) + if( ! moldat ) { warning("PDB output files do not have atom types unless you use MOLDATA"); + } parse("FILE",filename); parse("FMT",fmt); @@ -101,14 +102,17 @@ void OutputPDBFile::performAnalysis() { std::string descr="REMARK WEIGHT=%-" + fmt.substr(psign+1) + "\n"; 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 9c66db990b..10277e3816 100644 --- a/src/analysis/ReadAnalysisFrames.cpp +++ b/src/analysis/ReadAnalysisFrames.cpp @@ -58,18 +58,21 @@ ReadAnalysisFrames::ReadAnalysisFrames( const ActionOptions& ao ): weights_calculated(false) { parse("CLEAR",clearstride); - if( clearstride!=0 ) + 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(); + } // 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 ) + if( wwstr.size()>0 ) { log.printf(" reweighting using weights from "); + } std::vector arg( ActionWithArguments::getArguments() ); for(unsigned i=0; i(wwstr[i]); - if( !val ) + 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() ); @@ -91,14 +96,18 @@ ReadAnalysisFrames::ReadAnalysisFrames( const ActionOptions& ao ): if( wwstr.size()>0 ) { log.printf("\n"); wham_pointer = dynamic_cast( weight_vals[0]->getPntrToAction() ); - if( !wham_pointer ) + if( !wham_pointer ) { wham_pointer = NULL; - else if( !wham_pointer->buildsWeightStore() ) + } + else if( !wham_pointer->buildsWeightStore() ) { wham_pointer = NULL; - if( wham_pointer && weight_vals.size()!=1 ) + } + if( wham_pointer && weight_vals.size()!=1 ) { error("can only extract weights from one wham object"); - } else + } + } else { log.printf(" weights are all equal to one\n"); + } requestArguments( arg ); // Now add fake components to the underlying ActionWithValue for the arguments @@ -110,8 +119,9 @@ ReadAnalysisFrames::ReadAnalysisFrames( const ActionOptions& ao ): std::vector ReadAnalysisFrames::getArgumentList() { std::vector arg_vals( ActionWithArguments::getArguments() ); - for(unsigned i=0; icalculateWeights( logweights.size() ); - for(unsigned i=0; igetWeight(i); + } } else { // Find the maximum weight double maxweight=logweights[0]; for(unsigned i=1; imaxweight) + if(logweights[i]>maxweight) { maxweight=logweights[i]; + } } // Calculate weights (no memory) -- business here with maxweight is to prevent overflows - for(unsigned i=0; iclearData(); + } 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); @@ -174,12 +191,14 @@ void ReadAnalysisFrames::update() { 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 ) + if( getStep()%clearstride==0 ) { clearonnextstep=true; + } } } diff --git a/src/analysis/ReadAnalysisFrames.h b/src/analysis/ReadAnalysisFrames.h index c53ed3638f..1cb22de59a 100644 --- a/src/analysis/ReadAnalysisFrames.h +++ b/src/analysis/ReadAnalysisFrames.h @@ -93,8 +93,9 @@ bool ReadAnalysisFrames::dissimilaritiesWereSet() const { inline double ReadAnalysisFrames::getWeight( const unsigned& idat ) { - if( !weights_calculated ) + if( !weights_calculated ) { calculateWeights(); + } return weights[idat]; } diff --git a/src/analysis/ReadDissimilarityMatrix.cpp b/src/analysis/ReadDissimilarityMatrix.cpp index d4490bd310..4f245ef82c 100644 --- a/src/analysis/ReadDissimilarityMatrix.cpp +++ b/src/analysis/ReadDissimilarityMatrix.cpp @@ -93,24 +93,29 @@ ReadDissimilarityMatrix::ReadDissimilarityMatrix( const ActionOptions& ao ): { 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 ) + 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 ) + } + 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 ) + if( wfile.length()>0 ) { log.printf(" reading weights of nodes from file named %s \n",wfile.c_str() ); - else + } + else { log.printf(" setting weights of all nodes equal to one\n"); + } } void ReadDissimilarityMatrix::update() { - if(!my_input_data) + if(!my_input_data) { plumed.stop(); + } } void ReadDissimilarityMatrix::runFinalJobs() { @@ -125,23 +130,27 @@ void ReadDissimilarityMatrix::runFinalJobs() { } std::vector tmpdis( nnodes ); - for(unsigned j=0; j0 ) { @@ -158,8 +167,9 @@ void ReadDissimilarityMatrix::runFinalJobs() { } unsigned ReadDissimilarityMatrix::getNumberOfDataPoints() const { - if( my_input_data ) + if( my_input_data ) { return AnalysisBase::getNumberOfDataPoints(); + } return dissimilarities.size(); } @@ -173,8 +183,9 @@ double ReadDissimilarityMatrix::getDissimilarity( const unsigned& iframe, const DataCollectionObject& ReadDissimilarityMatrix::getStoredData( const unsigned& idata, const bool& calcdist ) { plumed_massert( !calcdist, "cannot calc dist as this data was read in from input"); - if( my_input_data ) + if( my_input_data ) { return AnalysisBase::getStoredData( idata, calcdist ); + } return fake_data[idata]; } diff --git a/src/analysis/ReselectLandmarks.cpp b/src/analysis/ReselectLandmarks.cpp index f0ed97cc03..fc6b93f1c6 100644 --- a/src/analysis/ReselectLandmarks.cpp +++ b/src/analysis/ReselectLandmarks.cpp @@ -61,17 +61,20 @@ ReselectLandmarks::ReselectLandmarks( const ActionOptions& ao ): std::string datastr; parse("LANDMARKS",datastr); mylandmarks = plumed.getActionSet().selectWithLabel( datastr ); - if( !mylandmarks ) + 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() ) + 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) + for(unsigned i=0; igetNumberOfDataPoints(); ++i) { selectFrame( mylandmarks->getDataPointIndexInBase(i) ); + } } } diff --git a/src/analysis/SelectWithStride.cpp b/src/analysis/SelectWithStride.cpp index 4f0d66c598..3f96341de2 100644 --- a/src/analysis/SelectWithStride.cpp +++ b/src/analysis/SelectWithStride.cpp @@ -55,8 +55,9 @@ SelectWithStride::SelectWithStride( const ActionOptions& ao ): void SelectWithStride::selectLandmarks() { unsigned stride = std::floor( my_input_data->getNumberOfDataPoints() / getNumberOfDataPoints() ), max=stride*getNumberOfDataPoints(); - for(unsigned i=0; igetName()+"_min"; addComponent(str_min); componentIsNotPeriodic(str_min); - if(min[i]!=-1.0) + if(min[i]!=-1.0) { getPntrToComponent(str_min)->set(min[i]); + } } for(unsigned i=0; iapplyForce(forces)) { at_least_one_forced=true; - for(unsigned j=0; j=0.0) + if(temp>=0.0) { kbt=plumed.getAtoms().getKBoltzmann()*temp; - else + } + else { kbt=plumed.getAtoms().getKbT(); + } checkRead(); log.printf(" with harmonic force constant"); - for(unsigned i=0; i0.0) + if(friction[i]>0.0) { hasFriction=true; + } } if(hasFriction) { log.printf(" with friction"); - for(unsigned i=0; igetDomain(a,b); componentIsPeriodic(comp,a,b); - } else + } 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 d2c31c8b95..37c79c0b91 100644 --- a/src/bias/External.cpp +++ b/src/bias/External.cpp @@ -134,8 +134,9 @@ External::External(const ActionOptions& ao): { std::string filename; parse("FILE",filename); - if( filename.length()==0 ) + if( filename.length()==0 ) { error("No external potential file was specified"); + } bool sparsegrid=false; parseFlag("SPARSE",sparsegrid); bool nospline=false; @@ -159,11 +160,13 @@ External::External(const ActionOptions& ao): gridfile.open(filename); std::string funcl=getLabel() + ".bias"; BiasGrid_=GridBase::create(funcl,getArguments(),gridfile,sparsegrid,spline,true); - if(BiasGrid_->getDimension()!=getNumberOfArguments()) + if(BiasGrid_->getDimension()!=getNumberOfArguments()) { error("mismatch between dimensionality of input grid and number of arguments"); + } for(unsigned i=0; iisPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) + if( getPntrToArgument(i)->isPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) { error("periodicity mismatch between arguments and input bias"); + } } } diff --git a/src/bias/LWalls.cpp b/src/bias/LWalls.cpp index 611808f7cb..c7726ced36 100644 --- a/src/bias/LWalls.cpp +++ b/src/bias/LWalls.cpp @@ -103,24 +103,29 @@ LWalls::LWalls(const ActionOptions&ao): checkRead(); log.printf(" at"); - for(unsigned i=0; i= TSTART"); + } lagmultfname=getLabel()+".LAGMULT"; parse("FILE",lagmultfname); parse("FMT",fmt); parse("PACE",pace_); - if(pace_<=0 ) + 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 ) + if(stride_<=0 ) { error("frequency for Lagrangian multipliers printing (STRIDE) is nonsensical"); + } simtemp=0.; parse("TEMP",simtemp); - if(simtemp>0) + if(simtemp>0) { simtemp*=plumed.getAtoms().getKBoltzmann(); - else + } + else { simtemp=plumed.getAtoms().getKbT(); + } parseFlag("REWEIGHT",reweight); - if(simtemp<=0 && reweight) + 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",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(); } } @@ -368,15 +387,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(); } } @@ -385,8 +406,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 { if(err_type=="LAPLACE" && sigma!=0) { return_error=-l2*sigma2/(1.0-l2*l2*sigma2/(alpha+1)); @@ -396,21 +418,26 @@ 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 { if(type=="INEQUAL>") { - if(lold>0.0) + if(lold>0.0) { return_lambda=0.0; - else + } + else { return_lambda=lold; + } } else { if(type=="INEQUAL<") { - if(lold<0.0) + if(lold<0.0) { return_lambda=0.0; - else + } + else { return_lambda=lold; + } } } } @@ -437,18 +464,22 @@ 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]) { @@ -460,16 +491,18 @@ void MaxEnt::update_lambda() { 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() { @@ -492,13 +525,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 43edc58092..16a038220c 100644 --- a/src/bias/MetaD.cpp +++ b/src/bias/MetaD.cpp @@ -384,10 +384,12 @@ 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) + if(std::abs(invsigma[i])>1.e-20) { invsigma[i]=1.0/invsigma[i] ; - else + } + else { invsigma[i]=0.0; + } } } }; @@ -659,8 +661,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() ) + 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) { @@ -699,8 +702,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) + if(stride_<=0) { error("frequency for hill addition is nonsensical"); + } current_stride_ = stride_; std::string hillsfname="HILLS"; parse("FILE",hillsfname); @@ -715,31 +719,37 @@ MetaD::MetaD(const ActionOptions& ao): parseVector("RECT",rect_biasf_); if(rect_biasf_.size()>0) { int r=0; - if(comm.Get_rank()==0) + 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) + 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) + if(temp>0.0) { kbt_=plumed.getAtoms().getKBoltzmann()*temp; - else + } + else { kbt_=plumed.getAtoms().getKbT(); + } if(biasf_>=1.0) { - if(kbt_==0.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"); + } welltemp_=true; } if(dampfactor_>0.0) { - if(kbt_==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"); + } } parseFlag("CALC_WORK",calc_work_); @@ -747,16 +757,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) + 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) ) + if (!parseNumberedVector("TRANSITIONWELL", i, tempcoords) ) { break; + } if (tempcoords.size() != getNumberOfArguments()) { error("incorrect number of coordinates for transition tempering well"); } @@ -765,73 +777,92 @@ MetaD::MetaD(const ActionOptions& ao): } parse("TARGET",targetfilename_); - if(targetfilename_.length()>0 && kbt_==0.0) + 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()) + 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_) + if(welltemp_) { tau=(kbt_*(biasf_-1.0))/height0_*getTimeStep()*stride_; - else if(dampfactor_>0.0) + } + else if(dampfactor_>0.0) { tau=(kbt_*dampfactor_)/height0_*getTimeStep()*stride_; + } } else { - if(height0_!=std::numeric_limits::max()) + if(height0_!=std::numeric_limits::max()) { error("At most one between HEIGHT and TAU should be specified"); + } if(welltemp_) { - if(biasf_!=1.0) + if(biasf_!=1.0) { height0_=(kbt_*(biasf_-1.0))/tau*getTimeStep()*stride_; - else - height0_=kbt_/tau*getTimeStep()*stride_; // special case for gamma=1 + } + else { + height0_=kbt_/tau*getTimeStep()*stride_; // special case for gamma=1 + } } - else if(dampfactor_>0.0) + else if(dampfactor_>0.0) { height0_=(kbt_*dampfactor_)/tau*getTimeStep()*stride_; - else + } + 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) + 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) + 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) + 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) + if(gspacing.size()!=getNumberOfArguments() && gspacing.size()!=0) { error("not enough values for GRID_SPACING"); - if(gmin.size()!=gmax.size()) + } + if(gmin.size()!=gmax.size()) { error("GRID_MAX and GRID_MIN should be either present or absent"); - if(gspacing.size()!=0 && gmin.size()==0) + } + 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) + } + 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) + if(gbin.size()>0) { grid_=true; + } bool sparsegrid=false; parseFlag("GRID_SPARSE",sparsegrid); @@ -865,28 +899,33 @@ MetaD::MetaD(const ActionOptions& ao): parse("GRID_WFILE",gridfilename_); parseFlag("STORE_GRIDS",storeOldGrids_); if(grid_ && gridfilename_.length()>0) { - if(wgridstride_==0 ) + if(wgridstride_==0 ) { error("frequency with which to output grid not specified use GRID_WSTRIDE"); + } } if(grid_ && wgridstride_>0) { - if(gridfilename_.length()==0) + if(gridfilename_.length()==0) { error("grid filename not specified use GRID_WFILE"); + } } std::string gridreadfilename_; parse("GRID_RFILE",gridreadfilename_); - if(!grid_&&gridfilename_.length()> 0) + if(!grid_&&gridfilename_.length()> 0) { error("To write a grid you need first to define it!"); - if(!grid_&&gridreadfilename_.length()>0) + } + 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_) + if(nlist_&&grid_) { error("NLIST and GRID cannot be combined!"); + } std::vector nlist_param; parseVector("NLIST_PARAMETERS",nlist_param); if(nlist_param.size()==0) @@ -907,20 +946,23 @@ MetaD::MetaD(const ActionOptions& ao): // Reweighting factor rct parseFlag("CALC_RCT",calc_rct_); - if (calc_rct_) + 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_) + 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_) + 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_); @@ -939,17 +981,21 @@ MetaD::MetaD(const ActionOptions& ao): // Inteval keyword std::vector tmpI(2); parseVector("INTERVAL",tmpI); - if(tmpI.size()!=2&&tmpI.size()!=0) + 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) + if(getNumberOfArguments()!=1) { error("INTERVAL limits correction works only for monodimensional metadynamics!"); - if(uppI_isPeriodic()) + } + if(getPntrToArgument(0)->isPeriodic()) { error("INTERVAL cannot be used with periodic variables!"); + } doInt_=true; } @@ -987,12 +1033,15 @@ MetaD::MetaD(const ActionOptions& ao): checkRead(); log.printf(" Gaussian width "); - if (adaptive_==FlexibleBin::diffusion) + if (adaptive_==FlexibleBin::diffusion) { log.printf(" (Note: The units of sigma are in timesteps) "); - if (adaptive_==FlexibleBin::geometry) + } + 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_) + if (welltemp_) { n_active++; - if (dampfactor_ > 0.0) + } + if (dampfactor_ > 0.0) { n_active++; - if (tt_specs_.is_active) + } + if (tt_specs_.is_active) { n_active++; + } // Find the greatest alpha. double greatest_alpha = 0.0; - if (welltemp_) + if (welltemp_) { greatest_alpha = std::max(greatest_alpha, 1.0); - if (dampfactor_ > 0.0) + } + if (dampfactor_ > 0.0) { greatest_alpha = std::max(greatest_alpha, 1.0); - if (tt_specs_.is_active) + } + 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_) + if (welltemp_) { least_alpha = std::min(least_alpha, 1.0); - if (dampfactor_ > 0.0) + } + if (dampfactor_ > 0.0) { least_alpha = std::min(least_alpha, 1.0); - if (tt_specs_.is_active) + } + 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) + 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) + } + 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) + } + 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) { @@ -1070,21 +1131,25 @@ MetaD::MetaD(const ActionOptions& ao): } } - if(doInt_) + 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; i1) { - if(walkers_mpi_) + 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_!="") + 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_!="") + 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(); @@ -1121,8 +1189,9 @@ MetaD::MetaD(const ActionOptions& ao): } if(flying_) { - if(!walkers_mpi_) + 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_); } @@ -1187,8 +1256,9 @@ MetaD::MetaD(const ActionOptions& ao): acc_rfile.scanField(); found=true; } - if(!found) + 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); @@ -1197,39 +1267,45 @@ MetaD::MetaD(const ActionOptions& ao): } if (calc_max_bias_) { - if (!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_) + 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) + if (transitionwells_[i][j] < min || transitionwells_[i][j] > max) { error(" transition well is not in grid"); + } } } } @@ -1271,13 +1347,16 @@ 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]) + 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.) + if(sigma0min_[i]<0.) { error("When using ADAPTIVE Gaussians on a grid SIGMA_MIN must be specified"); - if(mesh>0.5*sigma0min_[i]) + } + 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"; @@ -1292,10 +1371,12 @@ MetaD::MetaD(const ActionOptions& ao): for(unsigned i=0; igetDimension()!=getNumberOfArguments()) + if(BiasGrid_->getDimension()!=getNumberOfArguments()) { error("mismatch between dimensionality of input grid and number of arguments"); + } for(unsigned i=0; iisPeriodic()!=BiasGrid_->getIsPeriodic()[i] ) + 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]) + 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()) + 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) + 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_) + 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 @@ -1358,8 +1446,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) + if(comm.Get_rank()==0) { multi_sim_comm.Bcast(mw_dir_,0); + } comm.Bcast(mw_dir_,0); } #endif @@ -1402,24 +1491,28 @@ MetaD::MetaD(const ActionOptions& ao): } ifiles_[i]->reset(false); // close only the walker own hills file for later writing - if(i==mw_id_) + 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) + 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) + 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_) + if(result!=0&&result!=mpi_nw_) { error("in this WALKERS_MPI run some replica have restarted from FILE while other do not!"); + } } comm.Barrier(); @@ -1430,29 +1523,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_) + if(comm.Get_rank()==0 && walkers_mpi_) { multi_sim_comm.Barrier(); + } if(targetfilename_.length()>0) { IFile gridfile; gridfile.open(targetfilename_); std::string funcl=getLabel() + ".target"; TargetGrid_=GridBase::create(funcl,getArguments(),gridfile,false,false,true); - if(TargetGrid_->getDimension()!=getNumberOfArguments()) + if(TargetGrid_->getDimension()!=getNumberOfArguments()) { error("mismatch between dimensionality of input grid and number of arguments"); + } for(unsigned i=0; iisPeriodic()!=TargetGrid_->getIsPeriodic()[i] ) + 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_) + if(nlist_) { nlist_update_=true; + } // Calculate the Tiwary-Parrinello reweighting factor if we are restarting from previous hills - if(calc_rct_) + if(calc_rct_) { computeReweightingFactor(); + } // Calculate all special bias quantities desired if restarting with nonzero bias. if(calc_max_bias_) { max_bias_ = BiasGrid_->getMaxValue(); @@ -1469,15 +1567,18 @@ MetaD::MetaD(const ActionOptions& ao): gridfile_.link(*this); if(walkers_mpi_) { int r=0; - if(comm.Get_rank()==0) + if(comm.Get_rank()==0) { r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); - if(r>0) + if(r>0) { gridfilename_="/dev/null"; + } gridfile_.enforceSuffix(""); } - if(mw_n_>1) + if(mw_n_>1) { gridfile_.enforceSuffix(""); + } gridfile_.open(gridfilename_); } @@ -1485,18 +1586,22 @@ MetaD::MetaD(const ActionOptions& ao): hillsOfile_.link(*this); if(walkers_mpi_) { int r=0; - if(comm.Get_rank()==0) + if(comm.Get_rank()==0) { r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); - if(r>0) + if(r>0) { ifilesnames_[mw_id_]="/dev/null"; + } hillsOfile_.enforceSuffix(""); } - if(mw_n_>1) + if(mw_n_>1) { hillsOfile_.enforceSuffix(""); + } hillsOfile_.open(ifilesnames_[mw_id_]); - if(fmt_.length()>0) + if(fmt_.length()>0) { hillsOfile_.fmtField(fmt_); + } hillsOfile_.addConstantField("multivariate"); hillsOfile_.addConstantField("kerneltype"); if(doInt_) { @@ -1505,8 +1610,9 @@ MetaD::MetaD(const ActionOptions& ao): } hillsOfile_.setHeavyFlush(); // output periodicities of variables - for(unsigned i=0; i0) { if(walkers_mpi_) { log<<" You are using RECT in its 'altruistic' implementation\n"; @@ -1527,33 +1634,42 @@ MetaD::MetaD(const ActionOptions& ao): } log<<" Bibliography "<1||walkers_mpi_) + if(mw_n_>1||walkers_mpi_) { log<0) + } + if(concurrent || rect_biasf_.size()>0) { log<0 && walkers_mpi_) + } + if(rect_biasf_.size()>0 && walkers_mpi_) { log<0) { log< tmpvalues; - for(unsigned j=0; jgetName(), false ) ); + } while(scanOneHill(ifile,tmpvalues,center,sigma,height,multivariate)) { nhills++; // note that for gamma=1 we store directly -F - if(welltemp_ && biasf_>1.0) + if(welltemp_ && biasf_>1.0) { height*=(biasf_-1.0)/biasf_; + } addGaussian(Gaussian(multivariate,height,center,sigma)); } log.printf(" %d Gaussians read\n",nhills); @@ -1654,16 +1774,19 @@ void MetaD::writeGaussian(const Gaussian& hill, OFile&file) } } else { hillsOfile_.printField("multivariate","false"); - 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) + if(welltemp_ && biasf_>1.0) { height*=biasf_/(biasf_-1.0); + } file.printField("height",height).printField("biasf",biasf_); - if(mw_n_>1) + if(mw_n_>1) { file.printField("clock",int(std::time(0))); + } file.printField(); } @@ -1680,8 +1803,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); @@ -1696,24 +1820,28 @@ 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 + } else { hills_.push_back(hill); + } } std::vector MetaD::getGaussianSupport(const Gaussian& hill) @@ -1778,8 +1906,9 @@ std::vector MetaD::getGaussianSupport(const Gaussian& hill) double MetaD::getBias(const std::vector& cv) { double bias=0.0; - if(grid_) + if(grid_) { bias = BiasGrid_->getValue(cv); + } else { unsigned nt=OpenMP::getNumThreads(); unsigned stride=comm.Get_size(); @@ -1789,15 +1918,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, std::vector vder(ncv); bias=BiasGrid_->getValueAndDerivatives(cv,vder); - for(unsigned i=0; i& cv, std::vector& cv, std::vector(ncv)/2.0); @@ -1907,15 +2042,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) + if(ncv>0) { pcv=&cv[0]; + } if(doInt_) { plumed_assert(ncv==1); tmpcv[0]=cv[0]; - if(cv[0]uppI_) + } + if(cv[0]>uppI_) { tmpcv[0]=uppI_; + } pcv=&(tmpcv[0]); } @@ -1950,8 +2088,9 @@ double MetaD::evaluateGaussian(const std::vector& cv, const Gaussian& hi } double bias=0.0; - if(dp2& 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) + if(ncv>0) { pcv=&cv[0]; + } if(doInt_) { plumed_assert(ncv==1); tmpcv[0]=cv[0]; - if(cv[0]uppI_) + } + if(cv[0]>uppI_) { tmpcv[0]=uppI_; + } pcv=&(tmpcv[0]); } bool int_der=false; if(doInt_) { - if(cv[0]uppI_) + if(cv[0]uppI_) { int_der=true; + } } double dp2=0.0; @@ -2011,13 +2154,15 @@ double MetaD::evaluateGaussianAndDerivatives(const std::vector& cv, cons if(!int_der) { for(unsigned i=0; i& cv, cons if(dp2 cv(ncv); - for(unsigned i=0; i der(ncv,0.); - if(biasf_!=1.0) + if(biasf_!=1.0) { ene = getBiasAndDerivatives(cv,der); + } setBias(ene); - for(unsigned i=0; iset(work_); - if(calc_rct_) + } + if(calc_rct_) { getPntrToComponent("rbias")->set(ene - reweight_factor_); + } // calculate the acceleration factor if(acceleration_&&!isFirstStep_) { acc_ += static_cast(getStride()) * std::exp(ene/(kbt_)); @@ -2140,8 +2295,9 @@ void MetaD::update() { // adding hills criteria (could be more complex though) bool nowAddAHill; - if(getStep()%current_stride_==0 && !isFirstStep_) + if(getStep()%current_stride_==0 && !isFirstStep_) { nowAddAHill=true; + } else { nowAddAHill=false; isFirstStep_=false; @@ -2149,12 +2305,14 @@ void MetaD::update() unsigned ncv=getNumberOfArguments(); std::vector cv(ncv); - for(unsigned i=0; igetInverseMatrix(); + } // returns normal sigma - else + else { thissigma=sigma0_; + } // In case we use walkers_mpi, it is now necessary to communicate with other replicas. if(walkers_mpi_) { @@ -2205,16 +2365,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_) + if(!flying_) { writeGaussian(newhill,hillsOfile_); + } } } else { Gaussian newhill=Gaussian(multivariate,height,cv,thissigma); @@ -2223,18 +2386,21 @@ void MetaD::update() } // this is to update the hills neighbor list - if(nlist_) + 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) + if(mw_n_>1 && getStep()%mw_rstride_==0) { hillsOfile_.flush(); + } if(calc_work_) { - if(nlist_) + if(nlist_) { updateNlist(); + } double vbias1=getBias(cv); work_+=vbias1-vbias; } @@ -2243,19 +2409,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_) + 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) + if(comm.Get_rank()==0) { r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); } - if(r==0) + if(r==0) { gridfile_.rewind(); + } } BiasGrid_->writeToFile(gridfile_); // if a single grid is stored, it is necessary to flush it, otherwise @@ -2264,16 +2433,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_) + 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! @@ -2289,14 +2460,16 @@ void MetaD::update() } } // this is to update the hills neighbor list - if(nlist_) + 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) + 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_); @@ -2336,8 +2509,9 @@ bool MetaD::scanOneHill(IFile* ifile, std::vector& tmpvalues, std::vector } // scan for kerneltype std::string ktype="stretched-gaussian"; - if( ifile->FieldExist("kerneltype") ) + if( ifile->FieldExist("kerneltype") ) { ifile->scanField("kerneltype",ktype); + } if( ktype=="gaussian" ) { noStretchWarning(); } else if( ktype!="stretched-gaussian") { @@ -2346,12 +2520,15 @@ 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") + if(sss=="true") { multivariate=true; - else if(sss=="false") + } + else if(sss=="false") { multivariate=false; - else + } + else { plumed_merror("cannot parse multivariate = "+ sss); + } if(multivariate) { sigma.resize(ncv*(ncv+1)/2); Matrix upper(ncv,ncv); @@ -2383,12 +2560,15 @@ bool MetaD::scanOneHill(IFile* ifile, std::vector& tmpvalues, std::vector ifile->scanField("height",height); ifile->scanField("biasf",dummy); - if(ifile->FieldExist("clock")) + if(ifile->FieldExist("clock")) { ifile->scanField("clock",dummy); - if(ifile->FieldExist("lower_int")) + } + if(ifile->FieldExist("lower_int")) { ifile->scanField("lower_int",dummy); - if(ifile->FieldExist("upper_int")) + } + if(ifile->FieldExist("upper_int")) { ifile->scanField("upper_int",dummy); + } ifile->scanField(); return true; } else { @@ -2481,26 +2661,31 @@ void MetaD::updateFrequencyAdaptiveStride() bool MetaD::checkNeedsGradients()const { if(adaptive_==FlexibleBin::geometry) { - if(getStep()%stride_==0 && !isFirstStep_) + if(getStep()%stride_==0 && !isFirstStep_) { return true; - else + } + else { return false; - } else + } + } else { return false; + } } void MetaD::updateNlist() { // no need to check for neighbors - if(hills_.size()==0) + 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) + if(hills_.size()<2*nt) { nt=1; + } #pragma omp parallel num_threads(nt) { std::vector private_flat_nl; @@ -2513,8 +2698,9 @@ void MetaD::updateNlist() const double d=difference(i,getArgument(i),hills_[k].center[i])/hills_[k].sigma[i]; dist2+=d*d; } - if(dist2<=nlist_param_[0]*dp2cutoff) + if(dist2<=nlist_param_[0]*dp2cutoff) { private_flat_nl.push_back(hills_[k]); + } } #pragma omp critical local_flat_nl.insert(local_flat_nl.end(), private_flat_nl.begin(), private_flat_nl.end()); @@ -2522,8 +2708,9 @@ void MetaD::updateNlist() nlist_hills_ = local_flat_nl; // here we set some properties that are used to decide when to update it again - for(unsigned i=0; i dev2; dev2.resize(getNumberOfArguments(),0); for(unsigned k=0; k0.) + if(dev2[i]>0.) { nlist_dev2_[i]=dev2[i]/static_cast(nlist_hills_.size()); - else + } + 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 004b993312..29bdc3f9ad 100644 --- a/src/bias/MovingRestraint.cpp +++ b/src/bias/MovingRestraint.cpp @@ -157,22 +157,26 @@ MovingRestraint::MovingRestraint(const ActionOptions&ao): std::vector kk( getNumberOfArguments() ), aa( getNumberOfArguments() ); for(int i=0;; i++) { // Read in step - if( !parseNumberedVector("STEP",i,ss) ) + if( !parseNumberedVector("STEP",i,ss) ) { break; + } for(unsigned j=0; jgetName()+"_cntr")->set(aa[i]); const double k=kk[i]; f[i]=-k*cv; - if(verse[i]=="U" && cv<0) + if(verse[i]=="U" && cv<0) { continue; - if(verse[i]=="L" && cv>0) + } + 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()) + 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 b821face8d..61396f5f13 100644 --- a/src/bias/PBMetaD.cpp +++ b/src/bias/PBMetaD.cpp @@ -248,10 +248,12 @@ class PBMetaD : public Bias { 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) + if(std::abs(invsigma[i])>1.e-20) { invsigma[i]=1.0/invsigma[i] ; - else + } + else { invsigma[i]=0.0; + } } }; // general setup @@ -414,8 +416,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): std::vector familyargs; for(int i = 0;; i++) { parseArgumentList("PF", i, familyargs); - if (familyargs.empty()) + if (familyargs.empty()) { break; + } do_pf_ = true; log << " Identified Partitioned Family " << i << ":"; @@ -454,8 +457,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) + if (pfs_[i] == -1) { error(getPntrToArgument(i)->getName() + " was not assigned a PF"); + } } } @@ -510,8 +514,9 @@ PBMetaD::PBMetaD(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) + if(stride_<=0) { error("frequency for hill addition is nonsensical"); + } parseVector("FILE",hillsfname_); @@ -526,32 +531,40 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } parse("BIASFACTOR",biasf_); - if( biasf_<1.0 ) + if( biasf_<1.0 ) { error("well tempered bias factor is nonsensical"); + } double temp=0.0; parse("TEMP",temp); - if(temp>0.0) + if(temp>0.0) { kbt_=plumed.getAtoms().getKBoltzmann()*temp; - else + } + else { kbt_=plumed.getAtoms().getKbT(); + } if(biasf_>1.0) { - if(kbt_==0.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"); + } welltemp_=true; } double tau=0.0; parse("TAU",tau); if(tau==0.0) { - if(height0_==std::numeric_limits::max()) + 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_) + if(welltemp_) { tau=(kbt_*(biasf_-1.0))/height0_*getTimeStep()*stride_; + } } else { - if(!welltemp_) + if(!welltemp_) { error("TAU only makes sense in well-tempered metadynamics"); - if(height0_!=std::numeric_limits::max()) + } + 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_; } @@ -559,8 +572,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): // Multiple walkers parse("WALKERS_N",mw_n_); parse("WALKERS_ID",mw_id_); - if(mw_n_<=mw_id_) + 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_); @@ -580,8 +594,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_; @@ -590,44 +605,54 @@ PBMetaD::PBMetaD(const ActionOptions& ao): // Grid Stuff std::vector gmin(pf_n_); parseVector("GRID_MIN",gmin); - if(gmin.size()!=pf_n_ && gmin.size()!=0) + 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) + 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) + 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) + if(gspacing.size()!=pf_n_ && gspacing.size()!=0) { error("not enough values for GRID_SPACING"); - if(gmin.size()!=gmax.size()) + } + if(gmin.size()!=gmax.size()) { error("GRID_MAX and GRID_MIN should be either present or absent"); - if(gspacing.size()!=0 && gmin.size()==0) + } + 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) + } + 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) + 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) + if(!grid_&&gridfilenames_.size() > 0) { error("To write a grid you need first to define it!"); - if(!grid_&&gridreadfilenames_.size() > 0) + } + 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()) + 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_) + } + if(lowI_.size()!=0 && lowI_.size()!=pf_n_) { error("check number of argument of INTERVAL"); + } for(unsigned i=0; iisPeriodic()) + } + if(pfhold_[i]->isPeriodic()) { warning("INTERVAL is not used for periodic variables"); - else + } + else { doInt_[i]=true; + } } // parse selector stuff @@ -689,17 +724,21 @@ PBMetaD::PBMetaD(const ActionOptions& ao): checkRead(); log.printf(" Gaussian width "); - if (adaptive_==FlexibleBin::diffusion) + if (adaptive_==FlexibleBin::diffusion) { log.printf(" (Note: The units of sigma are in timesteps) "); - if (adaptive_==FlexibleBin::geometry) + } + if (adaptive_==FlexibleBin::geometry) { log.printf(" (Note: The units of sigma are in dist units) "); - for(unsigned i=0; i1) { - if(walkers_mpi_) + 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_!="") + 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_!="") + 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(); @@ -738,21 +780,25 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } for(unsigned i=0; i0.5*sigma0_[i]) + 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.) + 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"; @@ -824,8 +872,9 @@ 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()) + if(getRestart()) { restartedFromGrid=true; + } } else { if(!sparsegrid) { BiasGrid_=Tools::make_unique(funcl,args,gmin_t,gmax_t,gbin_t,spline,true); @@ -837,10 +886,12 @@ PBMetaD::PBMetaD(const ActionOptions& ao): std::vector actualmax=BiasGrid_->getMax(); std::string is; Tools::convert(i,is); - if(gmin_t[0]!=actualmin[0]) + 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]) + } + 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_)); } @@ -887,19 +938,22 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } ifiles_[k]->reset(false); // close only the walker own hills file for later writing - if(j==mw_id_) + 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()) + if(getRestart()) { log<<" WARNING: restart file "<0) + if(r>0) { ifilesnames_[mw_id_*hillsfname_.size()+i]="/dev/null"; + } ofile->enforceSuffix(""); } - if(mw_n_>1) + if(mw_n_>1) { ofile->enforceSuffix(""); + } ofile->open(ifilesnames_[mw_id_*hillsfname_.size()+i]); - if(fmt_.length()>0) + if(fmt_.length()>0) { ofile->fmtField(fmt_); + } ofile->addConstantField("multivariate"); ofile->addConstantField("kerneltype"); if(doInt_[i]) { @@ -950,8 +1008,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): } ofile->enforceSuffix(""); } - if(mw_n_>1) + if(mw_n_>1) { ofile->enforceSuffix(""); + } ofile->open(gridfname_tmp); ofile->setHeavyFlush(); gridfiles_.emplace_back(std::move(ofile)); @@ -968,8 +1027,9 @@ PBMetaD::PBMetaD(const ActionOptions& ao): if(adaptive_!=FlexibleBin::none) log<printField("sigma_"+pfhold_[family]->getName(),hill.sigma[0]); } double height=hill.height; - if(welltemp_) + if(welltemp_) { height *= biasf_/(biasf_-1.0); + } ofile->printField("height",height); ofile->printField("biasf",biasf_); - if(mw_n_>1) + if(mw_n_>1) { ofile->printField("clock",int(std::time(0))); + } ofile->printField(); } @@ -1100,8 +1162,9 @@ double PBMetaD::getBiasAndDerivatives(unsigned iarg, const std::vector& bias += evaluateGaussian(iarg,cv,hills_[family][i],der); } comm.Sum(bias); - if(der) + if(der) { comm.Sum(der,1); + } } else { if(der) { std::vector vder(1); @@ -1166,8 +1229,9 @@ 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()) + if(adaptive_==FlexibleBin::diffusion && getExchangeStep()) { error("ADAPTIVE=DIFF is not compatible with replica exchange"); + } std::vector cv(1); double der[1]; @@ -1181,8 +1245,9 @@ void PBMetaD::calculate() der[0] = 0.0; bias[i] = getBiasAndDerivatives(i, cv, der); deriv[i] = der[0]; - if(bias[i] < bmin) + if(bias[i] < bmin) { bmin = bias[i]; + } } double ene = 0.; for(unsigned i=0; i(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) + if(comm.Get_rank()==0) { r=multi_sim_comm.Get_rank(); + } comm.Bcast(r,0); } if(r==0) { @@ -1343,8 +1419,9 @@ void PBMetaD::update() for(unsigned i=0; iisOpen())) { // check if it exists now and open it! @@ -1385,8 +1462,9 @@ bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpva } center[0]=tmpvalues[0].get(); std::string ktype="stretched-gaussian"; - if( ifile->FieldExist("kerneltype") ) + if( ifile->FieldExist("kerneltype") ) { ifile->scanField("kerneltype",ktype); + } if( ktype=="gaussian" ) { noStretchWarning(); @@ -1396,12 +1474,15 @@ bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpva std::string sss; ifile->scanField("multivariate",sss); - if(sss=="true") + if(sss=="true") { multivariate=true; - else if(sss=="false") + } + else if(sss=="false") { multivariate=false; - else + } + else { plumed_merror("cannot parse multivariate = "+ sss); + } if(multivariate) { ifile->scanField("sigma_"+argPtr->getName()+"_"+ argPtr->getName(),sigma[0]); @@ -1411,12 +1492,15 @@ bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpva } ifile->scanField("height",height); ifile->scanField("biasf",dummy); - if(ifile->FieldExist("clock")) + if(ifile->FieldExist("clock")) { ifile->scanField("clock",dummy); - if(ifile->FieldExist("lower_int")) + } + if(ifile->FieldExist("lower_int")) { ifile->scanField("lower_int",dummy); - if(ifile->FieldExist("upper_int")) + } + if(ifile->FieldExist("upper_int")) { ifile->scanField("upper_int",dummy); + } ifile->scanField(); return true; } else { @@ -1428,12 +1512,15 @@ bool PBMetaD::scanOneHill(unsigned iarg, IFile *ifile, std::vector &tmpva bool PBMetaD::checkNeedsGradients()const { if(adaptive_==FlexibleBin::geometry) { - if(getStep()%stride_==0 && !isFirstStep_) + if(getStep()%stride_==0 && !isFirstStep_) { return true; - else + } + else { return false; - } else + } + } else { return false; + } } } diff --git a/src/bias/Restraint.cpp b/src/bias/Restraint.cpp index 51fd3dbb2a..3eb4d650d3 100644 --- a/src/bias/Restraint.cpp +++ b/src/bias/Restraint.cpp @@ -90,16 +90,19 @@ Restraint::Restraint(const ActionOptions&ao): checkRead(); log.printf(" at"); - for(unsigned i=0; i0) + if(simtemp>0) { simtemp*=plumed.getAtoms().getKBoltzmann(); - else + } + else { simtemp=plumed.getAtoms().getKbT(); - if(simtemp==0) + } + 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(); diff --git a/src/bias/ReweightBias.cpp b/src/bias/ReweightBias.cpp index a4913e2b55..63a73cefe6 100644 --- a/src/bias/ReweightBias.cpp +++ b/src/bias/ReweightBias.cpp @@ -92,8 +92,9 @@ ReweightBias::ReweightBias(const ActionOptions&ao): double ReweightBias::getLogWeight() { // Retrieve the bias double bias=0.0; - for(unsigned i=0; igetName().c_str()); + } log.printf("\n"); } //requestArguments(myenergy); @@ -224,8 +225,9 @@ ReweightTemperaturePressure::ReweightTemperaturePressure(const ActionOptions&ao) parseArgumentList("VOLUME",myvol); if(!myvol.empty()) { log.printf(" with volumes: "); - for(unsigned i=0; igetName().c_str()); + } log.printf("\n"); } @@ -241,40 +243,51 @@ 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() ) + 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() ) + 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() ) + 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 + } + 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) + 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) + 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) + 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) + 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 + } + else { return 0; + } } } diff --git a/src/bias/ReweightWham.cpp b/src/bias/ReweightWham.cpp index 2ba3f07925..b9196204e7 100644 --- a/src/bias/ReweightWham.cpp +++ b/src/bias/ReweightWham.cpp @@ -112,25 +112,30 @@ ReweightWham::ReweightWham(const ActionOptions&ao): { parse("MAXITER",maxiter); parse("WHAMTOL",thresh); - if(comm.Get_rank()==0) + if(comm.Get_rank()==0) { nreplicas=multi_sim_comm.Get_size(); + } comm.Bcast(nreplicas,0); } double ReweightWham::getLogWeight() { - if( getStep()==0 ) + 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) + 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 value; parseVector("VALUE",value); - if(values.size()==0&&value.size()==0) + if(values.size()==0&&value.size()==0) { error("One should use either VALUE or VALUES"); - if(values.size()!=0&&value.size()!=0) + } + if(values.size()!=0&&value.size()!=0) { error("One should use either VALUE or VALUES"); - if(value.size()>1) + } + 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) + if(!noderiv) { addValueWithDerivatives(); - else + } + 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 3d34d7266b..1e8f1c0dbf 100644 --- a/src/colvar/ContactMap.cpp +++ b/src/colvar/ContactMap.cpp @@ -151,8 +151,9 @@ ContactMap::ContactMap(const ActionOptions&ao): parseFlag("SERIAL",serial); parseFlag("SUM",dosum); parseFlag("CMDIST",docmdist); - if(docmdist==true&&dosum==true) + if(docmdist==true&&dosum==true) { error("You cannot use SUM and CMDIST together"); + } bool nopbc=!pbc; parseFlag("NOPBC",nopbc); pbc=!nopbc; @@ -161,8 +162,9 @@ ContactMap::ContactMap(const ActionOptions&ao): std::vector t, ga_lista, gb_lista; for(int i=1;; ++i ) { parseAtomList("ATOMS", i, t ); - if( t.empty() ) + if( t.empty() ) { break; + } if( t.size()!=2 ) { std::string ss; @@ -191,22 +193,26 @@ ContactMap::ContactMap(const ActionOptions&ao): for(unsigned i=0; i0) { switchingFunction.set(sw,errors); - if( errors.length()!=0 ) + 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) + 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 6bc006669f..f379450a2e 100644 --- a/src/colvar/CoordinationBase.cpp +++ b/src/colvar/CoordinationBase.cpp @@ -67,25 +67,31 @@ CoordinationBase::CoordinationBase(const ActionOptions&ao): parseFlag("NLIST",doneigh); if(doneigh) { parse("NL_CUTOFF",nl_cut); - if(nl_cut<=0.0) + if(nl_cut<=0.0) { error("NL_CUTOFF should be explicitly specified and positive"); + } parse("NL_STRIDE",nl_st); - if(nl_st<=0) + if(nl_st<=0) { error("NL_STRIDE should be explicitly specified and positive"); + } } addValueWithDerivatives(); setNotPeriodic(); if(gb_lista.size()>0) { - if(doneigh) + if(doneigh) { nl=Tools::make_unique(ga_lista,gb_lista,serial,dopair,pbc,getPbc(),comm,nl_cut,nl_st); - else + } + else { nl=Tools::make_unique(ga_lista,gb_lista,serial,dopair,pbc,getPbc(),comm); + } } else { - if(doneigh) + if(doneigh) { nl=Tools::make_unique(ga_lista,serial,pbc,getPbc(),comm,nl_cut,nl_st); - else + } + else { nl=Tools::make_unique(ga_lista,serial,pbc,getPbc(),comm); + } } requestAtoms(nl->getFullAtomList()); @@ -93,23 +99,28 @@ 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()) + if(getExchangeStep()) { error("Neighbor lists should be updated on exchange steps - choose a NL_STRIDE which divides the exchange stride!"); + } } - if(getExchangeStep()) + if(getExchangeStep()) { firsttime=true; + } } } @@ -161,8 +174,9 @@ void CoordinationBase::calculate() unsigned nt=OpenMP::getNumThreads(); const unsigned nn=nl->size(); - if(nt*stride*10>nn) + if(nt*stride*10>nn) { nt=1; + } const unsigned elementsPerRank = std::ceil(double(nn)/stride); const unsigned int start= rank*elementsPerRank; @@ -180,8 +194,9 @@ void CoordinationBase::calculate() const unsigned i0=nl->getClosePair(i).first; const unsigned i1=nl->getClosePair(i).second; - if(getAbsoluteIndex(i0)==getAbsoluteIndex(i1)) + if(getAbsoluteIndex(i0)==getAbsoluteIndex(i1)) { continue; + } if(pbc) { distance=pbcDistance(getPosition(i0),getPosition(i1)); @@ -207,21 +222,24 @@ void CoordinationBase::calculate() } #pragma omp critical if(nt>1) { - for(unsigned 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 b630b9f898..679eb64a6d 100644 --- a/src/colvar/Dipole.cpp +++ b/src/colvar/Dipole.cpp @@ -104,10 +104,12 @@ Dipole::Dipole(const ActionOptions&ao): log.printf(" %d", ga_lista[i].serial()); } log.printf(" \n"); - if(nopbc) + if(nopbc) { log.printf(" without periodic boundary conditions\n"); - else + } + else { log.printf(" using periodic boundary conditions\n"); + } requestAtoms(ga_lista); } @@ -115,8 +117,9 @@ Dipole::Dipole(const ActionOptions&ao): // calculator void Dipole::calculate() { - if(!nopbc) + 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 7f1e139a49..4e4b9a86b5 100644 --- a/src/colvar/Distance.cpp +++ b/src/colvar/Distance.cpp @@ -138,8 +138,9 @@ Distance::Distance(const ActionOptions&ao): { 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,13 +149,16 @@ Distance::Distance(const ActionOptions&ao): checkRead(); log.printf(" between atoms %d %d\n",atoms[0].serial(),atoms[1].serial()); - if(pbc) + if(pbc) { log.printf(" using periodic boundary conditions\n"); - else + } + else { log.printf(" without periodic boundary conditions\n"); + } - if(components && scaled_components) + if(components && scaled_components) { error("COMPONENTS and SCALED_COMPONENTS are not compatible"); + } if(components) { addComponentWithDerivatives("x"); @@ -184,8 +188,9 @@ Distance::Distance(const ActionOptions&ao): // calculator void Distance::calculate() { - if(pbc) + 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 638d644033..3c67942b6d 100644 --- a/src/colvar/EEFSolv.cpp +++ b/src/colvar/EEFSolv.cpp @@ -158,8 +158,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) + 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 + } else { nlexpo[i].push_back(false); + } } } } } void EEFSolv::calculate() { - if(pbc) + if(pbc) { makeWhole(); - if(getExchangeStep()) + } + if(getExchangeStep()) { nl_update = 0; - if(nl_update==0) + } + if(nl_update==0) { update_neighb(); + } const unsigned size=getNumberOfAtoms(); double bias = 0.0; @@ -205,8 +211,9 @@ void EEFSolv::calculate() { } unsigned nt=OpenMP::getNumThreads(); - if(nt*stride*10>size) + if(nt*stride*10>size) { nt=1; + } #pragma omp parallel num_threads(nt) { @@ -248,10 +255,12 @@ void EEFSolv::calculate() { const Vector dd = e_deriv*dist; fedensity += fact; deriv_i += dd; - if(nt>1) + if(nt>1) { deriv_omp[j] -= dd; - else + } + else { deriv[j] -= dd; + } } // j-i interaction @@ -264,10 +273,12 @@ void EEFSolv::calculate() { const Vector dd = e_deriv*dist; fedensity += fact; deriv_i += dd; - if(nt>1) + if(nt>1) { deriv_omp[j] -= dd; - else + } + else { deriv[j] -= dd; + } } } else { // i-j interaction @@ -280,31 +291,37 @@ void EEFSolv::calculate() { const Vector dd = e_deriv*dist; fedensity += fact; deriv_i += dd; - if(nt>1) + if(nt>1) { deriv_omp[j] -= dd; - else + } + else { deriv[j] -= dd; + } } } } - if(nt>1) + if(nt>1) { deriv_omp[i] += deriv_i; - else + } + else { deriv[i] += deriv_i; + } bias += 0.5*fedensity; } #pragma omp critical if(nt>1) { - for(unsigned i=0; i &atoms, std::vector > EEFSolv::setupTypeMap() { diff --git a/src/colvar/ERMSD.cpp b/src/colvar/ERMSD.cpp index bdd71bcd53..35dbacc7aa 100644 --- a/src/colvar/ERMSD.cpp +++ b/src/colvar/ERMSD.cpp @@ -148,12 +148,15 @@ ERMSD::ERMSD(const ActionOptions&ao): addValueWithDerivatives(); setNotPeriodic(); - if(atoms_.size()<6) + if(atoms_.size()<6) { error("at least six atoms should be specified"); - if(atoms_.size()%3!=0) + } + if(atoms_.size()%3!=0) { error("Atoms are not multiple of 3"); - if(pairs_.size()%2!=0) + } + if(pairs_.size()%2!=0) { error("pairs are not multiple of 2"); + } //checkRead(); @@ -163,8 +166,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(); @@ -177,8 +181,9 @@ ERMSD::ERMSD(const ActionOptions&ao): } // shift to count from zero - for(unsigned i=0; i atoms; parseAtomList("ATOMS",atoms); - if(atoms.size()==0) + if(atoms.size()==0) { error("no atoms specified"); + } parseFlag("MASS_WEIGHTED",use_masses); std::string Type; parse("TYPE",Type); @@ -114,30 +115,42 @@ Gyration::Gyration(const ActionOptions&ao): checkRead(); //shall we hastable this (with map<,>)? - if(Type=="RADIUS") + if(Type=="RADIUS") { rg_type=RADIUS; - else if(Type=="TRACE") + } + else if(Type=="TRACE") { rg_type=TRACE; - else if(Type=="GTPC_1") + } + else if(Type=="GTPC_1") { rg_type=GTPC_1; - else if(Type=="GTPC_2") + } + else if(Type=="GTPC_2") { rg_type=GTPC_2; - else if(Type=="GTPC_3") + } + else if(Type=="GTPC_3") { rg_type=GTPC_3; - else if(Type=="ASPHERICITY") + } + else if(Type=="ASPHERICITY") { rg_type=ASPHERICITY; - else if(Type=="ACYLINDRICITY") + } + else if(Type=="ACYLINDRICITY") { rg_type=ACYLINDRICITY; - else if(Type=="KAPPA2") + } + else if(Type=="KAPPA2") { rg_type=KAPPA2; - else if(Type=="RGYR_3") + } + else if(Type=="RGYR_3") { rg_type=GYRATION_3; - else if(Type=="RGYR_2") + } + else if(Type=="RGYR_2") { rg_type=GYRATION_2; - else if(Type=="RGYR_1") + } + else if(Type=="RGYR_1") { rg_type=GYRATION_1; - else + } + else { error("Unknown GYRATION type"); + } switch(rg_type) { @@ -175,13 +188,15 @@ Gyration::Gyration(const ActionOptions&ao): log.printf(" THE LARGEST PRINCIPAL RADIUS OF GYRATION (r_g1);"); break; } - if(rg_type>TRACE) + if(rg_type>TRACE) { log<<" Bibliography "<0.0001) + if(std::abs(det-1.)>0.0001) { error("Plumed Error: Cannot diagonalize gyration tensor\n"); + } switch(rg_type) { case GTPC_1: case GTPC_2: @@ -333,8 +352,9 @@ void Gyration::calculate() { 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 diff --git a/src/colvar/MultiRMSD.cpp b/src/colvar/MultiRMSD.cpp index 2f4167328d..d2d738a22e 100644 --- a/src/colvar/MultiRMSD.cpp +++ b/src/colvar/MultiRMSD.cpp @@ -166,13 +166,15 @@ MultiRMSD::MultiRMSD(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 ); + } 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") ) + if( pdb.hasFlag("NOPBC") ) { nopbc=true; + } std::vector atoms; rmsd->getAtomRequests( atoms ); @@ -180,37 +182,44 @@ MultiRMSD::MultiRMSD(const ActionOptions&ao): 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; @@ -161,16 +162,19 @@ PCARMSD::PCARMSD(const ActionOptions&ao): log.printf(" which contains %d atoms\n",getNumberOfAtoms()); log.printf(" with indices : "); for(unsigned i=0; i > drotdpos(3,3); std::vector alignedpos; @@ -286,8 +297,9 @@ void PCARMSD::calculate() { } } - for(int i=0; i(nframes); - if(nopbc) + if(nopbc) { log.printf(" without periodic boundary conditions\n"); - else + } + else { log.printf(" using periodic boundary conditions\n"); + } } @@ -154,13 +163,15 @@ PathMSDBase::~PathMSDBase() { void PathMSDBase::calculate() { - if(neigh_size>0 && getExchangeStep()) + 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) + if(!nopbc) { makeWhole(); + } // resize the list to full @@ -189,8 +200,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 @@ -205,8 +217,9 @@ void PathMSDBase::calculate() { } 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; } } @@ -224,8 +237,9 @@ 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 s_path(val_s_path.size()); - for(unsigned i=0; i 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,10 +113,12 @@ Position::Position(const ActionOptions&ao): checkRead(); log.printf(" for atom %d\n",atoms[0].serial()); - if(pbc) + if(pbc) { log.printf(" using periodic boundary conditions\n"); - else + } + else { log.printf(" without periodic boundary conditions\n"); + } if(scaled_components) { addComponentWithDerivatives("a"); diff --git a/src/colvar/ProjectionOnAxis.cpp b/src/colvar/ProjectionOnAxis.cpp index 3ef215e253..ce214cf825 100644 --- a/src/colvar/ProjectionOnAxis.cpp +++ b/src/colvar/ProjectionOnAxis.cpp @@ -92,22 +92,26 @@ ProjectionOnAxis::ProjectionOnAxis(const ActionOptions&ao): { std::vector axis_atoms; parseAtomList("AXIS_ATOMS",axis_atoms); - if( axis_atoms.size()!=2 ) + 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 ) + 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) + if(pbc) { log.printf(" using periodic boundary conditions\n"); - else + } + else { log.printf(" not using periodic boundary conditions\n"); + } // Add values to store data addComponentWithDerivatives("proj"); diff --git a/src/colvar/Puckering.cpp b/src/colvar/Puckering.cpp index b96ad61623..e3725c2397 100644 --- a/src/colvar/Puckering.cpp +++ b/src/colvar/Puckering.cpp @@ -101,16 +101,18 @@ Puckering::Puckering(const ActionOptions&ao): { std::vector atoms; parseAtomList("ATOMS",atoms); - if(atoms.size()!=5 && atoms.size()!=6) + 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 + } else { error("ATOMS should specify 5 or 6 atoms"); + } if(atoms.size()==5) { addComponentWithDerivatives("phs"); @@ -137,10 +139,12 @@ Puckering::Puckering(const ActionOptions&ao): } log<<" Bibliography "; - if(atoms.size()==5) + if(atoms.size()==5) { log<set(Zx); @@ -252,21 +262,26 @@ void Puckering::calculate5m() { void Puckering::calculate6m() { std::vector r(6); - for(unsigned i=0; i<6; 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++) + for(unsigned j=0; j<6; j++) { center+=r[j]/6.0; - for(unsigned j=0; j<6; j++) + } + for(unsigned j=0; j<6; j++) { R[j]=(r[j]-center); + } Vector Rp,Rpp; - for(unsigned j=0; j<6; 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++) + } + 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); @@ -279,25 +294,29 @@ void Puckering::calculate6m() { Tensor dnhat_dRpp=matmul(dnhat_dn,dn_dRpp); std::vector z(6); - for(unsigned j=0; j<6; j++) + 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++) + 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) + 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++) + 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++) { @@ -306,14 +325,17 @@ void Puckering::calculate6m() { } } Vector Bsum; - for(unsigned j=0; j<6; j++) + 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++) { + dB_dR[j]-=Bsum/6.0; + }; double A=0.0; - for(unsigned j=0; j<6; 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++) { @@ -322,14 +344,17 @@ void Puckering::calculate6m() { } } Vector Asum; - for(unsigned j=0; j<6; j++) + 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++) { + dA_dR[j]-=Asum/6.0; + }; double C=0.0; - for(unsigned j=0; j<6; 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++) { @@ -339,10 +364,12 @@ void Puckering::calculate6m() { } Vector Csum; - for(unsigned j=0; j<6; j++) + 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++) { + dC_dR[j]-=Csum/6.0; + }; // qx diff --git a/src/colvar/RMSD.cpp b/src/colvar/RMSD.cpp index c5b8490938..1f9393267e 100644 --- a/src/colvar/RMSD.cpp +++ b/src/colvar/RMSD.cpp @@ -191,8 +191,9 @@ RMSD::RMSD(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 ); + } rmsd=metricRegister().create(type,pdb); @@ -204,37 +205,44 @@ RMSD::RMSD(const ActionOptions&ao): // 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) + if(pbc) { log.printf(" using periodic boundary conditions\n"); - else + } + else { log.printf(" without periodic boundary conditions\n"); + } addValueWithDerivatives(); setNotPeriodic(); diff --git a/src/colvar/Torsion.cpp b/src/colvar/Torsion.cpp index 90443e99cf..c13c276107 100644 --- a/src/colvar/Torsion.cpp +++ b/src/colvar/Torsion.cpp @@ -127,8 +127,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 +137,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,22 +149,28 @@ Torsion::Torsion(const ActionOptions&ao): atoms[3]=axis[1]; atoms[4]=v2[0]; atoms[5]=v2[1]; - } else + } else { error("ATOMS should specify 4 atoms"); + } - if(pbc) + if(pbc) { log.printf(" using periodic boundary conditions\n"); - else + } + else { log.printf(" without periodic boundary conditions\n"); + } - if(do_cosine) + if(do_cosine) { log.printf(" calculating cosine instead of torsion\n"); + } addValueWithDerivatives(); - if(!do_cosine) + if(!do_cosine) { setPeriodic("-pi","pi"); - else + } + else { setNotPeriodic(); + } requestAtoms(atoms); } @@ -170,8 +178,9 @@ Torsion::Torsion(const ActionOptions&ao): void Torsion::calculate() { Vector d0,d1,d2; - if(pbc) + 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/core/Action.cpp b/src/core/Action.cpp index 685116412e..83a29e71ac 100644 --- a/src/core/Action.cpp +++ b/src/core/Action.cpp @@ -85,30 +85,39 @@ Action::Action(const ActionOptions&ao): Tools::convert(plumed.getActionSet().size(),s); label="@"+s; } - if( plumed.getActionSet().selectWithLabel(label) ) + 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") ) + if ( keywords.exists("UPDATE_FROM") ) { parse("UPDATE_FROM",update_from); - if(update_from!=std::numeric_limits::max()) + } + if(update_from!=std::numeric_limits::max()) { log.printf(" only update from time %f\n",update_from); - if ( keywords.exists("UPDATE_UNTIL") ) + } + if ( keywords.exists("UPDATE_UNTIL") ) { parse("UPDATE_UNTIL",update_until); - if(update_until!=std::numeric_limits::max()) + } + 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() ) + if( plumed.parseOnlyMode() ) { restart=false; - else if(srestart=="YES") + } + else if(srestart=="YES") { restart=true; - else if(srestart=="NO") + } + else if(srestart=="NO") { restart=false; + } else if(srestart=="AUTO") { // do nothing, this is the default - } else + } else { error("RESTART should be either YES, NO, or AUTO"); + } } } @@ -121,14 +130,17 @@ 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=='+') + if(*p=='w' || *p=='a' || *p=='+') { write=true; + } } FILE* fp; - if(write && comm.Get_rank()!=0) + if(write && comm.Get_rank()!=0) { fp=plumed.fopen("/dev/null",mode); - else + } + else { fp=plumed.fopen(path,mode); + } files.insert(fp); return fp; } @@ -149,13 +161,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 ) ) + if( Tools::getKey(line,key,outkey ) ) { return key + outkey; + } if( keywords.style(key,"compulsory") ) { if( keywords.getDefaultValue(key,outkey) ) { - if( outkey.length()==0 ) + if( outkey.length()==0 ) { error("keyword " + key + " has weird default value"); + } return key + "=" + outkey; } else { error("keyword " + key + " is compulsory for this action"); @@ -196,18 +210,21 @@ void Action::activate() { this->unlockRequests(); prepare(); this->lockRequests(); - } else + } else { return; - for(const auto & p : after) + } + 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) + for(const auto & p : after) { p->setOption(s); + } } void Action::clearOptions() { @@ -224,8 +241,9 @@ void Action::checkRead() { if(!line.empty()) { std::string msg="cannot understand the following words from the input line : "; for(unsigned i=0; i0) + if(i>0) { msg = msg + ", "; + } msg = msg + line[i]; } error(msg); @@ -296,10 +314,12 @@ bool Action::checkUpdate()const { //TODO:why not //return t::max() || t>=update_from); //? - if(t::max() || t>=update_from)) + if(t::max() || t>=update_from)) { return true; - else + } + else { return false; + } } bool Action::getCPT()const { diff --git a/src/core/Action.h b/src/core/Action.h index 8785e1f4dc..7ec21dcdf5 100644 --- a/src/core/Action.h +++ b/src/core/Action.h @@ -320,8 +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) + 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")) ) { @@ -340,8 +341,9 @@ 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) ) + if( !keywords.numbered(key) ) { error("numbered keywords are not allowed for " + key ); + } // Now try to read the keyword std::string num; @@ -356,23 +358,26 @@ void Action::parseVector(const std::string&key,std::vector&t) { unsigned size=t.size(); //bool skipcheck=size==0;? bool skipcheck=false; - if(size==0) + if(size==0) { skipcheck=true; + } // Now try to read the keyword std::string def; T val; bool present=Tools::findKeyword(line,key); bool found=Tools::parseVector(line,key,t,replica_index); - if(present && !found) + 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 ) + 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 @@ -382,11 +387,13 @@ void Action::parseVector(const std::string&key,std::vector&t) { plumed_error() <<"ERROR in action "<0) { - for(unsigned i=0; i & a, const bool masses.resize(nat); charges.resize(nat); int n=atoms.positions.size(); - if(clearDep) + if(clearDep) { clearDependencies(); + } unique.clear(); for(unsigned i=0; i=n) { @@ -74,11 +75,13 @@ void ActionAtomistic::requestAtoms(const std::vector & a, const bool Tools::convert( indexes[i].serial(),num ); error("atom " + num + " out of range"); } - if(atoms.isVirtualAtom(indexes[i])) + if(atoms.isVirtualAtom(indexes[i])) { addDependency(atoms.getVirtualAtomsAction(indexes[i])); + } // only real atoms are requested to lower level Atoms class - else + else { unique.push_back(indexes[i]); + } } Tools::removeDuplicates(unique); updateUniqueLocal(); @@ -129,19 +132,23 @@ void ActionAtomistic::calculateAtomicNumericalDerivatives( ActionWithValue* a, c 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); + } } } @@ -159,14 +166,16 @@ void ActionAtomistic::calculateAtomicNumericalDerivatives( ActionWithValue* a, c } Tensor virial; for(int i=0; i<3; i++) { - for(int k=0; k<3; k++) + 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++) + for(int k=0; k<3; k++) { v->addDerivative(startnum+3*natoms+3*k+i,virial(k,i)); + } } } } @@ -181,11 +190,13 @@ void ActionAtomistic::parseAtomList(const std::string&key,const int num, std::ve std::vector strings; if( num<0 ) { parseVector(key,strings); - if(strings.empty()) + if(strings.empty()) { return; + } } else { - if ( !parseNumberedVector(key,num,strings) ) + if ( !parseNumberedVector(key,num,strings) ) { return; + } } interpretAtomList( strings, t ); } @@ -197,22 +208,25 @@ void ActionAtomistic::interpretAtomList(std::vector& strings, std:: AtomNumber atom; // this is converting strings to AtomNumbers bool ok=Tools::convertNoexcept(strings[i],atom); - if(ok) + if(ok) { t.push_back(atom); + } // here we check if this is a special symbol for MOLINFO if( !ok && strings[i].compare(0,1,"@")==0 ) { std::string symbol=strings[i].substr(1); if(symbol=="allatoms") { const auto n=plumed.getAtoms().getNatoms() + plumed.getAtoms().getNVirtualAtoms(); t.reserve(t.size()+n); - for(unsigned i=0; i(this); @@ -253,8 +267,9 @@ void ActionAtomistic::interpretAtomList(std::vector& strings, std:: } } } - if(!ok) + 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]); } } @@ -262,25 +277,31 @@ void ActionAtomistic::interpretAtomList(std::vector& strings, std:: void ActionAtomistic::retrieveAtoms() { pbc=atoms.pbc; Colvar*cc=dynamic_cast(this); - if(cc && cc->checkIsEnergy()) + if(cc && cc->checkIsEnergy()) { energy=atoms.getEnergy(); - if(donotretrieve) + } + 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) + if(donotforce) { return; + } for(unsigned i=0; i& forcesToApply, } void ActionAtomistic::applyForces() { - if(donotforce) + if(donotforce) { return; + } std::vector& f(atoms.forces); Tensor& v(atoms.virial); - for(unsigned j=0; j0) + if(extraCV.length()>0) { atoms.updateExtraCVForce(extraCV,forceOnExtraCV); + } } void ActionAtomistic::clearOutputForces() { virial.zero(); - if(donotforce) + if(donotforce) { return; + } Tools::set_to_zero(forces); forceOnEnergy=0.0; forceOnExtraCV=0.0; @@ -334,20 +359,25 @@ void ActionAtomistic::clearOutputForces() { void ActionAtomistic::readAtomsFromPDB(const PDB& pdb) { Colvar*cc=dynamic_cast(this); - if(cc && cc->checkIsEnergy()) + if(cc && cc->checkIsEnergy()) { error("can't read energies from pdb files"); + } for(unsigned j=0; jpdb.size() ) + 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() ) + } + 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 99aa5ba709..25af11d87a 100644 --- a/src/core/ActionAtomistic.h +++ b/src/core/ActionAtomistic.h @@ -233,8 +233,9 @@ double ActionAtomistic::getMass(int i)const { inline double ActionAtomistic::getCharge(int i) const { - if( !chargesWereSet ) + 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 8811250eb8..03c879ca91 100644 --- a/src/core/ActionPilot.cpp +++ b/src/core/ActionPilot.cpp @@ -31,16 +31,18 @@ ActionPilot::ActionPilot(const ActionOptions&ao): { if( keywords.exists("STRIDE") ) { parse("STRIDE",stride); - if( !keywords.style("STRIDE","hidden") ) + if( !keywords.style("STRIDE","hidden") ) { log.printf(" with stride %d\n",stride); + } } else { stride=0; } } bool ActionPilot::onStep()const { - if( stride>0 ) + if( stride>0 ) { return getStep()%stride==0; + } return false; } diff --git a/src/core/ActionRegister.cpp b/src/core/ActionRegister.cpp index 381097c0a1..c4ad9cecc2 100644 --- a/src/core/ActionRegister.cpp +++ b/src/core/ActionRegister.cpp @@ -30,8 +30,9 @@ namespace PLMD { ActionRegister::~ActionRegister() { if(m.size()>0) { std::string names=""; - for(const auto & p : m) + 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"; } } @@ -70,14 +71,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) + 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) + 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 @@ -134,24 +137,27 @@ bool ActionRegister::printTemplate(const std::string& action, bool include_optio std::vector ActionRegister::getActionNames() const { std::vector s; - for(const auto & it : m) + 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--) + for(int i=size()-1; i>=0; i--) { (*this)[i].reset(); + } } void ActionSet::clearDelete() { - for(int i=size()-1; i>=0; i--) + 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 47aaa16ce7..d03ff33d5f 100644 --- a/src/core/ActionSet.h +++ b/src/core/ActionSet.h @@ -85,8 +85,9 @@ std::vector ActionSet::select()const { std::vector ret; for(const auto & p : (*this)) { T t=dynamic_cast(p.get()); - if(t) + if(t) { ret.push_back(t); + } }; return ret; } @@ -95,8 +96,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) + if(t && dynamic_cast(t)->getLabel()==s) { return t; + } }; return NULL; } @@ -106,8 +108,9 @@ std::vector ActionSet::selectNot()const { std::vector ret; for(const auto & p : (*this)) { T t=dynamic_cast(p); - if(!t) + if(!t) { ret.push_back(p.get()); + } }; return ret; } @@ -116,8 +119,9 @@ template std::string ActionSet::getLabelList() const { std::string outlist; for(const auto & p : (*this)) { - if(dynamic_cast(p.get())) + if(dynamic_cast(p.get())) { outlist+=p->getLabel()+" "; + } }; return outlist; } @@ -127,8 +131,9 @@ template std::vector ActionSet::getLabelVector() const { std::vector outlist; for(const auto & p : (*this)) { - if(dynamic_cast(p.get())) + if(dynamic_cast(p.get())) { outlist.push_back(p->getLabel()); + } }; return outlist; } @@ -137,11 +142,13 @@ template T ActionSet::selectLatest(const Action*action) const { T t=nullptr; for(const auto & p : (*this)) { - if(p.get()==action) + if(p.get()==action) { return t; + } T r=dynamic_cast(p.get()); - if(r) + if(r) { t=r; + } } return t; } diff --git a/src/core/ActionSetup.cpp b/src/core/ActionSetup.cpp index b6eaeba0fc..ce8042f38d 100644 --- a/src/core/ActionSetup.cpp +++ b/src/core/ActionSetup.cpp @@ -33,8 +33,9 @@ ActionSetup::ActionSetup(const ActionOptions&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()) ) + 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 4d0e5aabe7..b9807d880b 100644 --- a/src/core/ActionShortcut.cpp +++ b/src/core/ActionShortcut.cpp @@ -40,8 +40,9 @@ ActionShortcut::ActionShortcut(const ActionOptions&ao): std::string t; Tools::convert(plumed.getActionSet().size()+1,t); shortcutlabel="@" + t; - } else + } else { label = ("@" + s); + } } void ActionShortcut::readInputLine( const std::string& input ) { @@ -58,10 +59,12 @@ void ActionShortcut::readInputLine( const std::string& input ) { f_input += " UPDATE_UNTIL=" + util; } if( keywords.exists("RESTART") ) { - if( restart ) + if( restart ) { f_input += " RESTART=YES"; - if( !restart ) + } + if( !restart ) { f_input += " RESTART=NO"; + } } plumed.readInputLine( f_input ); } diff --git a/src/core/ActionWithArguments.cpp b/src/core/ActionWithArguments.cpp index 7ff777b764..3ddf039ffb 100644 --- a/src/core/ActionWithArguments.cpp +++ b/src/core/ActionWithArguments.cpp @@ -51,10 +51,12 @@ void ActionWithArguments::parseArgumentList(const std::string&key,std::vector& c, std::vector&arg) { @@ -102,8 +105,9 @@ void ActionWithArguments::interpretArgumentList(const std::vector& regmatch_t match; // select all the actions that have a value std::vector all=plumed.getActionSet().select(); - if( all.empty() ) + 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(); @@ -134,8 +138,9 @@ void ActionWithArguments::interpretArgumentList(const std::vector& } } } - if(!found_something) + if(!found_something) { plumed_error()<<"There isn't any action matching your regex " << myregex; + } #else plumed_merror("Regexp support not compiled!"); #endif @@ -150,11 +155,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() ) + if( all.empty() ) { error("your input file is not telling plumed to calculate anything"); + } for(unsigned j=0; jgetNumberOfComponents(); ++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 @@ -164,15 +171,18 @@ void ActionWithArguments::interpretArgumentList(const std::vector& str+=plumed.getActionSet().getLabelList()+")"; error("cannot find action named " + a + str); } - if( action->getNumberOfComponents()==0 ) + 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) + } + 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() ) + if( all.empty() ) { error("your input file is not telling plumed to calculate anything"); + } unsigned nval=0; for(unsigned j=0; j& nval++; } } - if(nval==0) + 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); @@ -203,11 +214,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() ) + if( all.empty() ) { error("your input file is not telling plumed to calculate anything"); + } for(unsigned j=0; jgetNumberOfComponents(); ++k) + for(int k=0; kgetNumberOfComponents(); ++k) { arg.push_back(all[j]->copyOutput(k)); + } } } else { ActionWithValue* action=plumed.getActionSet().selectWithLabel(c[i]); @@ -284,8 +297,9 @@ ActionWithArguments::ActionWithArguments(const ActionOptions&ao): if(!arg.empty()) { log.printf(" with arguments"); - for(unsigned i=0; igetName().c_str()); + } log.printf("\n"); } requestArguments(arg); @@ -315,8 +329,9 @@ void ActionWithArguments::calculateNumericalDerivatives( ActionWithValue* a ) { 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)); + } } } } @@ -330,8 +345,9 @@ double ActionWithArguments::getProjection(unsigned i,unsigned j)const { } void ActionWithArguments::addForcesOnArguments( const std::vector& forces ) { - for(unsigned i=0; iaddForce( forces[i] ); + } } } diff --git a/src/core/ActionWithValue.cpp b/src/core/ActionWithValue.cpp index 5404c45d71..2594839294 100644 --- a/src/core/ActionWithValue.cpp +++ b/src/core/ActionWithValue.cpp @@ -57,10 +57,12 @@ ActionWithValue::ActionWithValue(const ActionOptions&ao): noderiv(true), numericalDerivatives(false) { - if( keywords.exists("NUMERICAL_DERIVATIVES") ) + if( keywords.exists("NUMERICAL_DERIVATIVES") ) { parseFlag("NUMERICAL_DERIVATIVES",numericalDerivatives); - if(numericalDerivatives) + } + if(numericalDerivatives) { log.printf(" using numerical derivatives\n"); + } } ActionWithValue::~ActionWithValue() { @@ -68,8 +70,9 @@ ActionWithValue::~ActionWithValue() { } void ActionWithValue::clearInputForces() { - for(unsigned i=0; iclearInputForce(); + } } void ActionWithValue::clearDerivatives() { @@ -77,8 +80,9 @@ void ActionWithValue::clearDerivatives() { #pragma omp parallel num_threads(nt) { #pragma omp for - for(unsigned i=0; iclearDerivatives(); + } } } @@ -86,16 +90,18 @@ void ActionWithValue::clearDerivatives() { bool ActionWithValue::exists( const std::string& name ) const { for(unsigned i=0; iname==name) + if (values[i]->name==name) { return true; + } } return false; } Value* ActionWithValue::copyOutput( const std::string& name ) const { for(unsigned i=0; iname==name) + if (values[i]->name==name) { return values[i].get(); + } } plumed_merror("there is no pointer with name " + name); } @@ -180,8 +186,9 @@ int ActionWithValue::getComponent( const std::string& name ) const { std::string thename; thename=getLabel() + "." + name; for(unsigned i=0; iname==thename) + if (values[i]->name==thename) { return i; + } } plumed_merror("there is no component with name " + name); } @@ -216,8 +223,9 @@ void ActionWithValue::componentIsPeriodic( const std::string& name, const std::s void ActionWithValue::setGradientsIfNeeded() { if(isOptionOn("GRADIENTS")) { - for(unsigned i=0; isetGradients(); + } } } @@ -225,13 +233,15 @@ void ActionWithValue::turnOnDerivatives() { // Turn on the derivatives noderiv=false; // Resize the derivatives - 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) + if(vv) { vv->turnOnDerivatives(); + } } } diff --git a/src/core/ActionWithValue.h b/src/core/ActionWithValue.h index 31c5072db3..65593675fa 100644 --- a/src/core/ActionWithValue.h +++ b/src/core/ActionWithValue.h @@ -183,8 +183,9 @@ double ActionWithValue::getOutputQuantity( const std::string& name ) const { std::string thename; thename=getLabel() + "." + name; for(unsigned i=0; iname==thename ) + 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 3e26e2164b..49c9baaddf 100644 --- a/src/core/ActionWithVirtualAtom.cpp +++ b/src/core/ActionWithVirtualAtom.cpp @@ -44,11 +44,13 @@ ActionWithVirtualAtom::~ActionWithVirtualAtom() { void ActionWithVirtualAtom::apply() { Vector & f(atoms.forces[index.index()]); - for(unsigned i=0; i &d) { // 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++) + for(unsigned j=0; j<3; j++) { boxDerivatives[j][i][j]+=pos[i]; + } } } diff --git a/src/core/Atoms.cpp b/src/core/Atoms.cpp index f13c48a863..890bc56d55 100644 --- a/src/core/Atoms.cpp +++ b/src/core/Atoms.cpp @@ -186,14 +186,17 @@ void Atoms::share() { for(unsigned i=0; iisActive()) { auto l=actions[i]->getUnique().size(); - if(l>largest) + if(l>largest) { largest=l; + } } } - if(largest*2& unique) { if(zeroallforces || (int(gatindex.size())==natoms && !unique_serial)) { Tools::set_to_zero(forces); } else { - for(const auto & p : unique) + for(const auto & p : unique) { forces[p.index()].zero(); - for(unsigned i=getNatoms(); igetBox(box); - if(!atomsNeeded) + 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 @@ -297,10 +307,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 @@ -389,13 +406,15 @@ void Atoms::wait() { } asyncSent=false; } - if(collectEnergy) + 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) + if(shareMassAndChargeOnlyAtFirstStep) { massAndChargeOK=true; + } } void Atoms::updateForces() { @@ -405,10 +424,12 @@ void Atoms::updateForces() { mdatoms->rescaleForces(gatindex,alpha); mdatoms->updateForces(gatindex,forces); } else { - if(!unique_serial && int(gatindex.size())==natoms && shuffledAtoms==0) + if(!unique_serial && int(gatindex.size())==natoms && shuffledAtoms==0) { mdatoms->updateForces(gatindex,forces); - else + } + else { mdatoms->updateForces(unique,uniq_index,forces); + } } if( !plumed.novirial && dd.Get_rank()==0 ) { plumed_assert( virialHasBeenSet ); @@ -423,8 +444,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(); @@ -574,8 +608,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()) + if(!fullList.empty()) { *xx=&fullList[0]; - else + } + else { *xx=NULL; + } } void Atoms::clearFullList() { @@ -671,23 +709,28 @@ void Atoms::readBinary(std::istream&i) { } double Atoms::getKBoltzmann()const { - if(naturalUnits || MDnaturalUnits) + if(naturalUnits || MDnaturalUnits) { return 1.0; - else + } + else { return kBoltzmann/units.getEnergy(); + } } double Atoms::getMDKBoltzmann()const { - if(naturalUnits || MDnaturalUnits) + if(naturalUnits || MDnaturalUnits) { return 1.0; - else + } + else { return kBoltzmann/MDUnits.getEnergy(); + } } void Atoms::getLocalMasses(std::vector& localMasses) { localMasses.resize(gatindex.size()); - for(unsigned i=0; i& localPositions) { @@ -697,8 +740,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/CLTool.cpp b/src/core/CLTool.cpp index a3b760b94b..a2b53016cd 100644 --- a/src/core/CLTool.cpp +++ b/src/core/CLTool.cpp @@ -52,12 +52,15 @@ 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") + if( inputData[key]=="true") { t=true; - else if( inputData[key]=="false") + } + else if( inputData[key]=="false") { t=false; - else + } + else { plumed_error(); + } } bool CLTool::readInput( int argc, char**argv, FILE* in, FILE*out ) { @@ -65,10 +68,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) + if(inputdata==commandline) { return readCommandLineArgs( argc, argv, out ); - if(inputdata==ifile) + } + if(inputdata==ifile) { return readInputFile( argc, argv, in, out ); + } return true; } @@ -79,16 +84,18 @@ bool CLTool::readCommandLineArgs( int argc, char**argv, FILE*out ) { // Set all flags to default false for(unsigned k=0; k(thiskey,"false")); + } } // Read command line arguments bool printhelp=false; for(int i=1; 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) + if(inputData.count(key)==0) { error("missing data for keyword " + key); + } bool check=Tools::convertNoexcept(inputData[key],t); - if(!check) + if(!check) { error("data input for keyword " + key + " has wrong type"); + } return true; } - if( inputData.count(key)==0 ) + if( inputData.count(key)==0 ) { return false; + } Tools::convert(inputData[key],t); return true; } @@ -126,16 +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) + if(words.size()==0) { return false; + } for(unsigned i=0; isecond; + } switch(iword) { case cmd_setArgc: CHECK_NULL(val,word); @@ -81,8 +82,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]; @@ -152,16 +155,19 @@ int CLToolMain::run(int argc, char **argv,FILE*in,FILE*out,Communicator& pc) { std::string a(""); for(i=1; i0) + if(tmp[j].length()>0) { availableShell.push_back(tmp[j]); + } } } @@ -258,8 +268,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)) + while(Tools::getline(fp,line)) { manual+=line; + } pclose(fp); #else manual="(doc not avail)"; @@ -292,16 +303,19 @@ 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) + 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"; } } @@ -65,14 +66,16 @@ void CLToolRegister::add(std::string key,creator_pointer f,keywords_pointer kf) bool CLToolRegister::check(const std::string & key)const { //return m.count(key)>0;//would be simpler? - if(m.count(key)>0) + if(m.count(key)>0) { return true; + } return false; } std::unique_ptr CLToolRegister::create(const CLToolOptions&ao) { - if(ao.line.size()<1) - return NULL;//maybe nullptr? + if(ao.line.size()<1) { + return NULL; //maybe nullptr? + } std::unique_ptr cltool; if(check(ao.line[0])) { CLToolOptions nao( ao,mk[ao.line[0]] ); @@ -84,16 +87,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) + 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 6d604c71ef..1c1ce06e58 100644 --- a/src/core/Colvar.cpp +++ b/src/core/Colvar.cpp @@ -47,8 +47,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); + } } void Colvar::apply() { @@ -66,8 +67,9 @@ void Colvar::apply() { } unsigned nt=OpenMP::getNumThreads(); - if(nt>ncp/(4*stride)) + if(nt>ncp/(4*stride)) { nt=1; + } if(!isEnergy && !isExtraCV) { #pragma omp parallel num_threads(nt) @@ -96,26 +98,30 @@ void Colvar::apply() { } #pragma omp critical { - for(unsigned j=0; j4*comm.Get_size()) { - if(fsz>0) + 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)) + if(getPntrToComponent(0)->applyForce(forces)) { modifyForceOnEnergy()+=forces[0]; + } } else if( isExtraCV ) { std::vector forces(1); - if(getPntrToComponent(0)->applyForce(forces)) + if(getPntrToComponent(0)->applyForce(forces)) { modifyForceOnExtraCV()+=forces[0]; + } } } diff --git a/src/core/DataFetchingObject.cpp b/src/core/DataFetchingObject.cpp index 3d3922e4f4..447f0d81d3 100644 --- a/src/core/DataFetchingObject.cpp +++ b/src/core/DataFetchingObject.cpp @@ -59,20 +59,23 @@ DataFetchingObject::DataFetchingObject(PlumedMain&p): } bool DataFetchingObject::activate() const { - for(unsigned j=0; jactivate(); + } // return myactions.size()>0;? - if( myactions.size()>0 ) + 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 ) + if( dot!=std::string::npos ) { aname = key.substr(0,dot); + } return a.selectWithLabel( aname ); } @@ -143,8 +146,9 @@ void DataFetchingObjectTyped::setData( const std::string& key, const std::str break; } } - if( !found ) + 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 13bfeda30b..a2b1b22a23 100644 --- a/src/core/ExchangePatterns.cpp +++ b/src/core/ExchangePatterns.cpp @@ -60,15 +60,17 @@ void ExchangePatterns::getList(const TypesafePtr & ind) stat=0; iind[i] = (int) (random.U01()*NumberOfReplicas); for(int j=0; jgetArgument(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]); diff --git a/src/core/GREX.cpp b/src/core/GREX.cpp index 2652e58a76..ec40a1d92a 100644 --- a/src/core/GREX.cpp +++ b/src/core/GREX.cpp @@ -69,8 +69,9 @@ void GREX::cmd(const std::string&key,const TypesafePtr & val) { } else { int iword=-1; const auto it=word_map.find(words[0]); - if(it!=word_map.end()) + if(it!=word_map.end()) { iword=it->second; + } switch(iword) { case cmd_initialized: CHECK_NOTNULL(val,key); @@ -108,8 +109,9 @@ void GREX::cmd(const std::string&key,const TypesafePtr & val) { break; case cmd_prepare: CHECK_INIT(initialized,key); - if(intracomm.Get_rank()==0) + if(intracomm.Get_rank()==0) { return; + } intracomm.Bcast(partner,0); calculate(); break; @@ -123,8 +125,9 @@ void GREX::cmd(const std::string&key,const TypesafePtr & val) { break; case cmd_calculate: CHECK_INIT(initialized,key); - if(intracomm.Get_rank()!=0) + if(intracomm.Get_rank()!=0) { return; + } intracomm.Bcast(partner,0); calculate(); break; @@ -160,8 +163,9 @@ void GREX::cmd(const std::string&key,const TypesafePtr & val) { break; case cmd_shareAllDeltaBias: CHECK_INIT(initialized,key); - if(intracomm.Get_rank()!=0) + 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/GenericMolInfo.cpp b/src/core/GenericMolInfo.cpp index 35f0477216..200ef0ac6e 100644 --- a/src/core/GenericMolInfo.cpp +++ b/src/core/GenericMolInfo.cpp @@ -69,16 +69,18 @@ GenericMolInfo::GenericMolInfo( const ActionOptions&ao ): parseFlag("WHOLE", iswhole_); auto* moldat=plumed.getActionSet().selectLatest(this); - if( moldat ) + 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 ) + if( backbone.size()==0 ) { break; + } read_backbone.push_back(backbone); backbone.resize(0); } @@ -88,8 +90,9 @@ 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())) + 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 ); @@ -98,12 +101,14 @@ GenericMolInfo::GenericMolInfo( const ActionOptions&ao ): unsigned start,end; std::string errmsg; pdb.getResidueRange( chains[i], start, end, errmsg ); - if( errmsg.length()!=0 ) + if( errmsg.length()!=0 ) { error( errmsg ); + } AtomNumber astart,aend; pdb.getAtomRange( chains[i], astart, aend, errmsg ); - if( errmsg.length()!=0 ) + if( errmsg.length()!=0 ) { error( errmsg ); + } log.printf(" chain named %s contains residues %u to %u and atoms %u to %u \n",chains[i].c_str(),start,end,astart.serial(),aend.serial()); } @@ -120,8 +125,9 @@ GenericMolInfo::GenericMolInfo( const ActionOptions&ao ): bool sorted=true; const auto & at=pdb.getAtomNumbers(); 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 ) + if( fortype!=mytype ) { error("cannot calculate a variable designed for " + fortype + " molecules for molecule type " + mytype ); - if( MolDataClass::numberOfAtomsPerResidueInBackbone( mytype )==0 ) + } + if( MolDataClass::numberOfAtomsPerResidueInBackbone( mytype )==0 ) { error("backbone is not defined for molecule type " + mytype ); + } if( read_backbone.size()!=0 ) { - if( restrings.size()!=1 ) + if( restrings.size()!=1 ) { error("cannot interpret anything other than all for residues when using CHAIN keywords"); - if( restrings[0]!="all" ) + } + 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& restrings, const std pdb.getResidueRange( chains[i], r_start, r_end, errmsg ); if( !useter ) { std::string resname = pdb.getResidueName( r_start ); - if( MolDataClass::isTerminalGroup( mytype, resname ) ) + if( MolDataClass::isTerminalGroup( mytype, resname ) ) { r_start++; + } resname = pdb.getResidueName( r_end ); - if( MolDataClass::isTerminalGroup( mytype, resname ) ) + if( MolDataClass::isTerminalGroup( mytype, resname ) ) { r_end--; + } } Tools::convert(r_start,mm); Tools::convert(r_end,nn); - if(i==0) + if(i==0) { restrings[0] = mm + "-" + nn; - else + } + else { restrings.push_back( mm + "-" + nn ); + } } } } @@ -254,16 +269,18 @@ void GenericMolInfo::getBackbone( std::vector& restrings, const std Tools::convert( segments[i][j], num ); error("residue " + num + " appears to be a terminal group"); } - if( resname=="GLY" ) + if( resname=="GLY" ) { warning("GLY residues are achiral - assuming HA1 atom is in CB position"); + } MolDataClass::getBackboneForResidue( mytype, segments[i][j], pdb, atomnumbers ); if( atomnumbers.size()==0 ) { std::string num; Tools::convert( segments[i][j], num ); error("Could not find required backbone atom in residue number " + num ); } else { - for(unsigned k=0; kgetline(res); words=Tools::getWords(res); - if(!words.empty() && words[0]=="Error") + if(!words.empty() && words[0]=="Error") { plumed_error()<second; + } return false; } void resetExtraCVNeeded() override { - for(auto & i : extraCVNeeded) + for(auto & i : extraCVNeeded) { i.second=false; + } } void MD2double(const TypesafePtr & m,double&d)const override { @@ -178,8 +180,9 @@ void MDAtomsTyped::getBox(Tensor&box)const { } } } - else + else { box.zero(); + } } template @@ -260,11 +263,13 @@ 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::setp(const TypesafePtr & pp,int i) { p=TypesafePtr(); pp.get(); // just check type and discard pointer - if(i==0) + if(i==0) { px=pp.copy(); - if(i==1) + } + if(i==1) { py=pp.copy(); - if(i==2) + } + if(i==2) { pz=pp.copy(); + } } template @@ -408,12 +418,15 @@ template void MDAtomsTyped::setf(const TypesafePtr & ff,int i) { f=TypesafePtr(); ff.get(); // just check type and discard pointer - if(i==0) + if(i==0) { fx=ff.copy(); - if(i==1) + } + if(i==1) { fy=ff.copy(); - if(i==2) + } + if(i==2) { fz=ff.copy(); + } } template diff --git a/src/core/PlumedMain.cpp b/src/core/PlumedMain.cpp index f22c07fc9c..a2add60c54 100644 --- a/src/core/PlumedMain.cpp +++ b/src/core/PlumedMain.cpp @@ -101,38 +101,48 @@ namespace PLMD { plumed_assert(words.size()>2); int error_code; Tools::convert(words[2],error_code); - if(words[1]=="std::generic_category") + if(words[1]=="std::generic_category") { throw std::system_error(error_code,std::generic_category(),what); - if(words[1]=="std::system_category") + } + if(words[1]=="std::system_category") { throw std::system_error(error_code,std::system_category(),what); - if(words[1]=="std::iostream_category") + } + if(words[1]=="std::iostream_category") { throw std::system_error(error_code,std::iostream_category(),what); - if(words[1]=="std::future_category") + } + 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) + if(words.size()>2) { Tools::convert(words[2],error_code); - if(words.size()>1 && words[1]=="std::generic_category") + } + 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") + } + 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") + } + 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") + } + 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) + if(words.size()>1) { Tools::convert(words[1],value); + } throw value; } @@ -267,8 +277,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()) + if(it!=word_map.end()) { iword=it->second; + } switch(iword) { case cmd_setBox: CHECK_INIT(initialized,word); @@ -412,44 +423,54 @@ void PlumedMain::cmd(const std::string & word,const TypesafePtr & val) { case cmd_getDataRank: CHECK_INIT(initialized,words[0]); plumed_assert(nw==2 || nw==3); - if( nw==2 ) + if( nw==2 ) { DataFetchingObject::get_rank( actionSet, words[1], "", val); - else + } + 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 ) + if( nw==2 ) { DataFetchingObject::get_shape( actionSet, words[1], "", val ); - else + } + 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 ) + if( nw==2 ) { mydatafetcher->setData( words[1], "", val ); - else + } + else { mydatafetcher->setData( words[1], words[2], val ); + } break; /* ADDED WITH API==6 */ case cmd_setErrorHandler: { - if(val) + if(val) { error_handler=*static_cast(val.get()); - else + } + else { error_handler.handler=NULL; + } } break; case cmd_read: CHECK_INIT(initialized,word); - if(val) + if(val) { readInputFile(val.get()); - else + } + else { readInputFile("plumed.dat"); + } break; case cmd_readInputLine: CHECK_INIT(initialized,word); @@ -560,24 +581,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) + 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) + 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) + if(nt==0) { nt=1; + } OpenMP::setNumThreads(nt); } break; @@ -586,8 +610,9 @@ void PlumedMain::cmd(const std::string & word,const TypesafePtr & val) { CHECK_NOTNULL(val,word); { auto id=val.get(); - if(id>=0) + if(id>=0) { gpuDeviceId=id; + } } break; /* ADDED WITH API==6 */ @@ -598,10 +623,12 @@ 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) + if(val.get()!=0) { nestedExceptions=true; - else + } + else { nestedExceptions=false; + } break; /* STOP API */ case cmd_setMDEngine: @@ -652,10 +679,12 @@ void PlumedMain::cmd(const std::string & word,const TypesafePtr & val) { case cmd_isEnergyNeeded: CHECK_INIT(initialized,word); CHECK_NOTNULL(val,word); - if(atoms.isEnergyNeeded()) + if(atoms.isEnergyNeeded()) { val.set(int(1)); - else + } + else { val.set(int(0)); + } break; case cmd_getBias: CHECK_INIT(initialized,word); @@ -681,30 +710,36 @@ 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])) + if(atoms.isExtraCVNeeded(words[1])) { val.set(int(1)); - else + } + else { val.set(int(0)); + } break; case cmd_GREX: - if(!grex) + 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) + if(!cltool) { cltool=Tools::make_unique(); + } { std::string kk=words[1]; - for(unsigned i=2; icmd(kk.c_str(),val); } break; @@ -713,8 +748,9 @@ void PlumedMain::cmd(const std::string & word,const TypesafePtr & val) { { double v; plumed_assert(words.size()==2); - if(Tools::convertNoexcept(words[1],v)) + if(Tools::convertNoexcept(words[1],v)) { atoms.double2MD(v,val); + } } break; default: @@ -745,8 +781,9 @@ void PlumedMain::init() { // check that initialization just happens once initialized=true; atoms.init(); - if(!log.isOpen()) + if(!log.isOpen()) { log.link(stdout); + } log<<"PLUMED is starting\n"; log<<"Version: "<0) { readInputFile(plumedDat); @@ -772,8 +810,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 { log.printf("KbT has not been set by the MD engine\n"); log.printf("It should be set by hand where needed\n"); @@ -799,16 +838,18 @@ void PlumedMain::readInputFile(const std::string & str) { void PlumedMain::readInputFile(IFile & ifile) { std::vector words; - while(Tools::getParsedLine(ifile,words) && !endPlumed) + 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()) + if(str.empty()) { return; + } std::vector words=Tools::getWords(str); citations.clear(); readInputWords(words); @@ -821,8 +862,9 @@ void PlumedMain::readInputLine(const std::string & str) { void PlumedMain::readInputLines(const std::string & str) { plumed_assert(initialized); - if(str.empty()) + if(str.empty()) { return; + } log<<"FILE: (temporary)\n"; @@ -852,8 +894,9 @@ void PlumedMain::readInputLines(const std::string & str) { void PlumedMain::readInputWords(const std::vector & words) { plumed_assert(initialized); - if(words.empty()) + if(words.empty()) { return; + } else if(words[0]=="_SET_SUFFIX") { plumed_assert(words.size()==2); setSuffix(words[1]); @@ -864,8 +907,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()) + if(p->checkNeedsGradients()) { p->setOption("GRADIENTS"); + } } } @@ -939,12 +984,14 @@ void PlumedMain::prepareDependencies() { void PlumedMain::shareData() { // atom positions are shared (but only if there is something to do) - if(!active) + if(!active) { return; + } // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("2 Sharing data"); - if(atoms.getNatoms()>0) + if(atoms.getNatoms()>0) { atoms.share(); + } } void PlumedMain::performCalcNoUpdate() { @@ -967,17 +1014,20 @@ void PlumedMain::performCalc() { } void PlumedMain::waitData() { - if(!active) + if(!active) { return; + } // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("3 Waiting for data"); - if(atoms.getNatoms()>0) + if(atoms.getNatoms()>0) { atoms.wait(); + } } void PlumedMain::justCalculate() { - if(!active) + if(!active) { return; + } // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("4 Calculating (forward loop)"); bias=0.0; @@ -1003,30 +1053,37 @@ void PlumedMain::justCalculate() { k++; } const int pad=k-actionNumberLabel.length(); - for(int i=0; igetLabel()); } ActionWithValue*av=dynamic_cast(p); ActionAtomistic*aa=dynamic_cast(p); { - if(av) + if(av) { av->clearInputForces(); - if(av) + } + if(av) { av->clearDerivatives(); + } } { - if(aa) + if(aa) { aa->clearOutputForces(); + } if(aa) { - if(aa->isActive()) + if(aa->isActive()) { aa->retrieveAtoms(); + } } } - if(p->checkNumericalDerivatives()) + if(p->checkNumericalDerivatives()) { p->calculateNumericalDerivatives(); - else + } + else { p->calculate(); + } // This retrieves components called bias if(av) { bias+=av->getOutputQuantity("bias"); @@ -1034,8 +1091,9 @@ void PlumedMain::justCalculate() { av->setGradientsIfNeeded(); } ActionWithVirtualAtom*avv=dynamic_cast(p); - if(avv) + if(avv) { avv->setGradientsIfNeeded(); + } } } catch(...) { plumed_error_nested() << "An error happened while calculating " << p->getLabel(); @@ -1050,8 +1108,9 @@ void PlumedMain::justApply() { } void PlumedMain::backwardPropagate() { - if(!active) + if(!active) { return; + } int iaction=0; // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("5 Applying (backward loop)"); @@ -1075,16 +1134,18 @@ void PlumedMain::backwardPropagate() { k++; } const int pad=k-actionNumberLabel.length(); - for(int i=0; igetLabel()); } p->apply(); ActionAtomistic*a=dynamic_cast(p); // still ActionAtomistic has a special treatment, since they may need to add forces on atoms - if(a) + if(a) { a->applyForces(); + } } iaction++; @@ -1093,16 +1154,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) + if(detailedTimers) { sw1=stopwatch.startStop("5B Update forces"); + } // this is updating the MD copy of the forces - if(atoms.getNatoms()>0) + if(atoms.getNatoms()>0) { atoms.updateForces(); + } } void PlumedMain::update() { - if(!active) + if(!active) { return; + } // Stopwatch is stopped when sw goes out of scope auto sw=stopwatch.startStop("6 Update"); @@ -1111,19 +1175,24 @@ void PlumedMain::update() { updateFlags.push(true); for(const auto & p : actionSet) { p->beforeUpdate(); - if(p->isActive() && p->checkUpdate() && updateFlagsTop()) + if(p->isActive() && p->checkUpdate() && updateFlagsTop()) { p->update(); + } } - while(!updateFlags.empty()) + while(!updateFlags.empty()) { updateFlags.pop(); - if(!updateFlags.empty()) + } + 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) + if(stopFlag) { stopFlag.set(int(1)); - else + } + 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 @@ -1132,8 +1201,9 @@ void PlumedMain::update() { if(step%10000==0||doCheckPoint) { fflush(); log.flush(); - for(const auto & p : actionSet) + for(const auto & p : actionSet) { p->fflush(); + } } } @@ -1143,23 +1213,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) + 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) + if(ret!=0) { plumed_error() <<"An error happened while executing command "<(ppathsuf.c_str()),const_cast(mmode.c_str())); - if(!fp) + 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 181f37ec50..9d5e82159a 100644 --- a/src/core/PlumedMain.h +++ b/src/core/PlumedMain.h @@ -407,8 +407,9 @@ class PlumedMain: bool getRestart()const; /// Set restart flag void setRestart(bool f) { - if(!doParseOnly) + if(!doParseOnly) { restart=f; + } } /// Check if checkpointing bool getCPT()const; @@ -544,8 +545,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 + } else { return false; + } } diff --git a/src/core/PlumedMainInitializer.cpp b/src/core/PlumedMainInitializer.cpp index 0f0e4b3673..3d83beff2a 100644 --- a/src/core/PlumedMainInitializer.cpp +++ b/src/core/PlumedMainInitializer.cpp @@ -109,8 +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()) + if(getenvTypesafeDebug()) { typesafeDebug(key,safe); + } p->cmd(key,PLMD::TypesafePtr::fromSafePtr(&safe)); } } @@ -127,151 +128,186 @@ static void translate_current(plumed_nothrow_handler_x nothrow,void**nested=null // cppcheck-suppress rethrowNoCurrentException throw; } catch(const PLMD::ExceptionTypeError & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,20300,msg,opt); } catch(const PLMD::ExceptionError & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,20200,msg,opt); } catch(const PLMD::ExceptionDebug & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,20100,msg,opt); } catch(const PLMD::Exception & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,20000,msg,opt); } catch(const PLMD::lepton::Exception & e) { - if(!msg) + 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) + 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) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,11410,msg,opt); #endif } catch(const std::bad_alloc & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,11400,msg,opt); #ifdef __PLUMED_LIBCXX11 } catch(const std::bad_function_call & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,11300,msg,opt); } catch(const std::bad_weak_ptr & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,11200,msg,opt); #endif } catch(const std::bad_cast & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,11100,msg,opt); } catch(const std::bad_typeid & e) { - if(!msg) + 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) + 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()) + if(e.code().category()==std::generic_category()) { nothrow.handler(nothrow.ptr,10230,msg,opt); - else if(e.code().category()==std::system_category()) + } + else if(e.code().category()==std::system_category()) { nothrow.handler(nothrow.ptr,10231,msg,opt); - else if(e.code().category()==std::iostream_category()) + } + else if(e.code().category()==std::iostream_category()) { nothrow.handler(nothrow.ptr,10232,msg,opt); - else if(e.code().category()==std::future_category()) + } + 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) + 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()) + if(e.code().category()==std::generic_category()) { nothrow.handler(nothrow.ptr,10220,msg,opt); - else if(e.code().category()==std::system_category()) + } + else if(e.code().category()==std::system_category()) { nothrow.handler(nothrow.ptr,10221,msg,opt); - else if(e.code().category()==std::iostream_category()) + } + else if(e.code().category()==std::iostream_category()) { nothrow.handler(nothrow.ptr,10222,msg,opt); - else if(e.code().category()==std::future_category()) + } + else if(e.code().category()==std::future_category()) { nothrow.handler(nothrow.ptr,10223,msg,opt); + } // fallback to generic runtime_error - else + else { nothrow.handler(nothrow.ptr,10200,msg,opt); + } #endif } catch(const std::underflow_error &e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,10215,msg,opt); } catch(const std::overflow_error &e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,10210,msg,opt); } catch(const std::range_error &e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,10205,msg,opt); } catch(const std::runtime_error & e) { - if(!msg) + 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) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,10120,msg,opt); } catch(const std::length_error & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,10115,msg,opt); } catch(const std::domain_error & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,10110,msg,opt); } catch(const std::invalid_argument & e) { - if(!msg) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,10105,msg,opt); } catch(const std::logic_error & e) { - if(!msg) + 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) + if(!msg) { msg=e.what(); + } nothrow.handler(nothrow.ptr,10000,msg,opt); } catch(const char* m) { - if(!msg) + if(!msg) { msg=m; + } nothrow.handler(nothrow.ptr,10000,msg,opt); } catch(const std::string & s) { - if(!msg) + 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 @@ -321,8 +357,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()) + if(getenvTypesafeDebug()) { typesafeDebug(key,safe); + } p->cmd(key,PLMD::TypesafePtr::fromSafePtr(&safe)); } catch(...) { if(p->getNestedExceptions()) { @@ -405,25 +442,29 @@ class PlumedMainInitializer { { // make sure static plumed_function_pointers is initialized here plumed_symbol_table_init(); - if(debug) + 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) + 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) + 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) + 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; @@ -431,8 +472,9 @@ class PlumedMainInitializer { if(plumed_kernel_register) { std::fprintf(stderr,"+++ plumed_kernel_register found at %p +++\n",dls); } - else + else { std::fprintf(stderr,"+++ plumed_kernel_register not found +++\n"); + } } void*createp; void*cmdp; @@ -443,18 +485,21 @@ class PlumedMainInitializer { 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) + 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) + if(handle) { dlclose(handle); + } #endif } ~PlumedMainInitializer() { - if(debug) + 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 0d7172b1ea..413b75018e 100644 --- a/src/core/TargetDist.cpp +++ b/src/core/TargetDist.cpp @@ -70,8 +70,9 @@ double TargetDist::calculate( std::vector& derivs ) { dist+=tmp*tmp; } dist=std::sqrt(dist); - for(unsigned i=0; i& forces ) const { - if( !hasForce ) + 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"); + } str_max=pmax; - if( !Tools::convertNoexcept(str_max,max) ) + if( !Tools::convertNoexcept(str_max,max) ) { action->error("could not convert period string " + str_max + " to read"); + } setupPeriodicity(); } @@ -133,8 +137,9 @@ void Value::getDomain(double&minout,double&maxout) const { void Value::setGradients() { // Can't do gradients if we don't have derivatives - if( !hasDeriv ) + if( !hasDeriv ) { return; + } gradients.clear(); ActionAtomistic*aa=dynamic_cast(action); ActionWithArguments*aw=dynamic_cast(action); @@ -149,8 +154,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++) + for(unsigned i=0; i<3; i++) { gradients[an][i]+=derivatives[3*j+i]; + } } } } else if(aw) { @@ -161,8 +167,9 @@ void Value::setGradients() { gradients[iatom]+=p.second*derivatives[j]; } } - } else + } else { plumed_error(); + } } double Value::projection(const Value& v1,const Value&v2) { @@ -190,8 +197,9 @@ void copy( const Value& val1, Value& val2 ) { val2.resizeDerivatives( nder ); } val2.clearDerivatives(); - for(unsigned i=0; iresizeDerivatives( nder ); } val2->clearDerivatives(); - 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) ); + } val2->set( val1.get() + val2->get() ); } diff --git a/src/core/Value.h b/src/core/Value.h index e0a272a9e2..cd604d279d 100644 --- a/src/core/Value.h +++ b/src/core/Value.h @@ -158,16 +158,18 @@ inline void Value::applyPeriodicity() { if(periodicity==periodic) { value=min+difference(min,value); - if(valuederivatives.size()!=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(); @@ -242,8 +245,9 @@ bool Value::hasDerivatives() const { inline void Value::resizeDerivatives(int n) { - if(hasDeriv) + if(hasDeriv) { derivatives.resize(n); + } } inline @@ -260,8 +264,9 @@ void Value::setDerivative(unsigned i, double d) { inline void Value::chainRule(double df) { - for(unsigned i=0; i(this); - if( ! moldat ) + if( ! moldat ) { error("Unable to find MOLINFO in input"); + } AtomResidueName[0].clear(); AtomResidueName[1].clear(); @@ -597,11 +603,13 @@ void SASA_HASEL::readDeltaG() { } } } - if ( backboneflag == 0) + if ( backboneflag == 0) { error("Cannot find backbone value in Delta G parameters file\n"); + } } - else + else { error("Cannot open DeltaG file"); + } for(unsigned i=0; i(this); - if( ! moldat ) + 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 711252c6cb..eb3a44dd04 100755 --- a/src/sasa/sasa_LCPO.cpp +++ b/src/sasa/sasa_LCPO.cpp @@ -185,20 +185,24 @@ SASA_LCPO::SASA_LCPO(const ActionOptions&ao): parse("DELTAGFILE",DeltaGValues); parse("APPROACH", approach); parseAtomList("ATOMS",atoms); - if(atoms.size()==0) + 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") + if(Type=="TOTAL") { sasa_type=TOTAL; - else if(Type=="TRANSFER") + } + else if(Type=="TRANSFER") { sasa_type=TRANSFER; - else + } + else { error("Unknown SASA type"); + } switch(sasa_type) { @@ -212,8 +216,9 @@ SASA_LCPO::SASA_LCPO(const ActionOptions&ao): log.printf(" atoms involved : "); for(unsigned i=0; i(this); - if( ! moldat ) + if( ! moldat ) { error("Unable to find MOLINFO in input"); + } AtomResidueName[0].clear(); AtomResidueName[1].clear(); @@ -563,11 +569,13 @@ void SASA_LCPO::readDeltaG() { } } } - if ( backboneflag == 0) + if ( backboneflag == 0) { error("Cannot find backbone value in Delta G parameters file\n"); + } } - else + else { error("Cannot open DeltaG file"); + } for(unsigned i=0; i 0 ) + 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; @@ -1063,16 +1075,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 ) + 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. ) + 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; diff --git a/src/tools/BiasRepresentation.cpp b/src/tools/BiasRepresentation.cpp index 2cfc67ce98..3cfe174d63 100644 --- a/src/tools/BiasRepresentation.cpp +++ b/src/tools/BiasRepresentation.cpp @@ -95,8 +95,9 @@ void BiasRepresentation::addGrid(const std::vector & gmin, const st std::string ss; ss="file.free"; std::vector vv; - for(unsigned i=0; i(ss,vv,gmin,gmax,nbin,false,true); hasgrid=true; } @@ -191,8 +192,9 @@ 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 + } else { nneighb=kk->getSupport(BiasGrid_->getDx()); + } std::vector neighbors=BiasGrid_->getNeighbors(kk->getCenter(),nneighb); std::vector der(ndim); std::vector xx(ndim); @@ -208,10 +210,12 @@ void BiasRepresentation::pushKernel( IFile *ifile ) { values[j]->set(xx[j]); } double bias; - if(doInt_) + if(doInt_) { bias=kk->evaluate(values,der,true,doInt_,lowI_,uppI_); - else + } + else { bias=kk->evaluate(values,der,true); + } if(rescaledToBias) { double f=(biasf.back()-1.)/(biasf.back()); bias*=f; @@ -233,10 +237,12 @@ void BiasRepresentation::pushKernel( IFile *ifile ) { for(int j=0; jset(xx[j]); } - if(doInt_) + if(doInt_) { allbias[i]=kk->evaluate(values,der,true,doInt_,lowI_,uppI_); - else + } + else { allbias[i]=kk->evaluate(values,der,true); + } if(rescaledToBias) { double f=(biasf.back()-1.)/(biasf.back()); allbias[i]*=f; @@ -296,12 +302,15 @@ void BiasRepresentation::getMinMaxBin(std::vector &vmin, std::vectorvmax[j]) + } + if(dmax>vmax[j]) { vmax[j]=dmax; - if(ddiv &vmin, std::vectorisPeriodic()) { double minv,maxv; values[j]->getDomain(minv,maxv); - if(minv>vmin[j]) + if(minv>vmin[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 80b1c7e059..ab226f2caa 100644 --- a/src/tools/Brent1DRootSearch.h +++ b/src/tools/Brent1DRootSearch.h @@ -79,8 +79,9 @@ void Brent1DRootSearch::bracket( const double& a, const double& b, eng_p 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)) + if ((fa > 0.0 && fb > 0.0) || (fa < 0.0 && fb < 0.0)) { plumed_merror("input points do not bracket root"); + } bracketed=true; } @@ -105,8 +106,9 @@ double Brent1DRootSearch::search( eng_pointer eng ) { } tol1=2*EPS*std::fabs(bx)+0.5*tol; xm=0.5*(cx-bx); - if( std::fabs(xm) <= tol1 || fb == 0.0 ) + 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 ) { @@ -118,8 +120,9 @@ double Brent1DRootSearch::search( eng_pointer eng ) { 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) + if (p > 0.0) { q = -q; + } p=std::fabs(p); min1=3.0*xm*q-std::fabs(tol1*q); min2=std::fabs(e*q); @@ -136,12 +139,15 @@ double Brent1DRootSearch::search( eng_pointer eng ) { } ax=bx; fa=fb; - if( std::fabs(d) > tol1 ) + if( std::fabs(d) > tol1 ) { bx+=d; - else if(xm<0 ) - bx -= std::fabs(tol1); // SIGN(tol1,xm); - else + } + 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 1365670a19..2f4a06ca00 100644 --- a/src/tools/Citations.cpp +++ b/src/tools/Citations.cpp @@ -29,10 +29,12 @@ namespace PLMD { std::string Citations::cite(const std::string & item) { unsigned i; for(i=0; i()); + } #else (void) val; plumed_merror("you are trying to use an MPI function, but PLUMED has been compiled without MPI support"); @@ -130,8 +136,9 @@ void Communicator::Abort(int errorcode) { void Communicator::Bcast(Data data,int root) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) + if(initialized()) { MPI_Bcast(data.pointer,data.size,data.type,root,communicator); + } #else (void) data; (void) root; @@ -140,8 +147,9 @@ void Communicator::Bcast(Data data,int root) { void Communicator::Sum(Data data) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) + if(initialized()) { MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_SUM,communicator); + } #else (void) data; #endif @@ -149,8 +157,9 @@ void Communicator::Sum(Data data) { void Communicator::Prod(Data data) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) + if(initialized()) { MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_PROD,communicator); + } #else (void) data; #endif @@ -158,8 +167,9 @@ void Communicator::Prod(Data data) { void Communicator::Max(Data data) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) + if(initialized()) { MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_MAX,communicator); + } #else (void) data; #endif @@ -167,8 +177,9 @@ void Communicator::Max(Data data) { void Communicator::Min(Data data) { #if defined(__PLUMED_HAS_MPI) - if(initialized()) + if(initialized()) { MPI_Allreduce(MPI_IN_PLACE,data.pointer,data.size,data.type,MPI_MIN,communicator); + } #else (void) data; #endif @@ -196,8 +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) + 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); @@ -205,8 +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) + 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); @@ -214,8 +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) + if(s) { std::memcpy(static_cast(r)+displs[0]*in.nbytes,s,size_t(in.size)*in.nbytes); + } #endif } @@ -224,30 +238,35 @@ 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) + 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) + 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) + 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) + if(&status==&StatusIgnore) { MPI_Recv(data.pointer,data.size,data.type,source,tag,communicator,MPI_STATUS_IGNORE); - else + } + else { MPI_Recv(data.pointer,data.size,data.type,source,tag,communicator,&status.s); + } #else (void) data; (void) source; @@ -259,8 +278,9 @@ void Communicator::Recv(Data data,int source,int tag,Status&status) { void Communicator::Barrier()const { #ifdef __PLUMED_HAS_MPI - if(initialized()) + if(initialized()) { MPI_Barrier(communicator); + } #endif } @@ -272,10 +292,12 @@ bool Communicator::initialized() { #if defined(__PLUMED_HAS_MPI) int flag=0; MPI_Initialized(&flag); - if(flag) + if(flag) { return true; - else + } + else { return false; + } #endif return false; } @@ -283,10 +305,12 @@ 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) + if(&s==&StatusIgnore) { MPI_Wait(&r,MPI_STATUS_IGNORE); - else + } + 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"); diff --git a/src/tools/ConjugateGradient.h b/src/tools/ConjugateGradient.h index 0591341ba3..2b060e484c 100644 --- a/src/tools/ConjugateGradient.h +++ b/src/tools/ConjugateGradient.h @@ -62,8 +62,9 @@ void ConjugateGradient::minimise( const double& ftol, std::vector std::vector DynamicList::retrieveActiveList() { std::vector this_active(nactive); - for(unsigned k=0; k void DynamicList::deactivate( const T& t ) { plumed_dbg_assert( allWereActivated ); unsigned ii=getIndexOfElement( t ); - if( onoff[ii]==0 || onoff[ii]%nprocessors!=0 ) + if( onoff[ii]==0 || onoff[ii]%nprocessors!=0 ) { return; + } // Deactivates the component - if( rank==0 ) + if( rank==0 ) { onoff[ii]=nprocessors-1; - else + } + 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::sortActiveList() { template bool DynamicList::updateComplete() const { // return (!allWereActivated && !allWereDeactivated);? - if( !allWereActivated && !allWereDeactivated ) + if( !allWereActivated && !allWereDeactivated ) { return true; + } return false; } @@ -398,15 +406,18 @@ void mpi_gatherActiveMembers(Communicator& comm, std::vector< DynamicList >& bufsize=0; for(unsigned i=0; i0 && buffer[bufsize]%size==0 ) + if( buffer[bufsize]>0 && buffer[bufsize]%size==0 ) { ll[i].onoff[j]=size; - else + } + 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) + if(pairs.size()==0) { return true; + } for(unsigned idx=0; idx0) { - if(note) + if(note) { this->msg +="\n"; + } this->msg +=msg; note=false; } diff --git a/src/tools/FileBase.cpp b/src/tools/FileBase.cpp index 7bc423ff5b..0d47a682a9 100644 --- a/src/tools/FileBase.cpp +++ b/src/tools/FileBase.cpp @@ -47,8 +47,9 @@ FileBase& FileBase::link(FILE*fp) { } FileBase& FileBase::flush() { - if(fp) + if(fp) { fflush(fp); + } return *this; } @@ -80,8 +81,9 @@ bool FileBase::FileExist(const std::string& path) { 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) + if(f) { std::fclose(f); + } }; std::unique_ptr fp_deleter(ff,deleter); @@ -91,17 +93,20 @@ bool FileBase::FileExist(const std::string& path) { ff=std::fopen(const_cast(this->path.c_str()),"r"); mode="r"; } - if(ff) + if(ff) { do_exist=true; - if(comm) + } + if(comm) { comm->Barrier(); + } return do_exist; } bool FileBase::isOpen() { bool isopen=false; - if(fp) + if(fp) { isopen=true; + } return isopen; } @@ -109,11 +114,13 @@ void FileBase::close() { plumed_assert(!cloned); eof=false; err=false; - if(fp) + if(fp) { std::fclose(fp); + } #ifdef __PLUMED_HAS_ZLIB - if(gzfp) + if(gzfp) { gzclose(gzFile(gzfp)); + } #endif fp=NULL; gzfp=NULL; @@ -135,13 +142,16 @@ FileBase::FileBase(): FileBase::~FileBase() { - if(plumed) + if(plumed) { plumed->eraseFile(*this); - if(!cloned && fp) + } + if(!cloned && fp) { std::fclose(fp); + } #ifdef __PLUMED_HAS_ZLIB - if(!cloned && gzfp) + if(!cloned && gzfp) { gzclose(gzFile(gzfp)); + } #endif } @@ -150,8 +160,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); @@ -169,8 +180,9 @@ std::string FileBase::appendSuffix(const std::string&path,const std::string&suff ret.resize(l); } ret+=suffix; - if(ext.length()>0) + if(ext.length()>0) { ret+="."+ext; + } return ret; } @@ -181,10 +193,12 @@ FileBase& FileBase::enforceSuffix(const std::string&suffix) { } std::string FileBase::getSuffix()const { - if(enforcedSuffix_) + if(enforcedSuffix_) { return enforcedSuffix; - if(plumed) + } + if(plumed) { return plumed->getSuffix(); + } return ""; } diff --git a/src/tools/Grid.cpp b/src/tools/Grid.cpp index fd7c2433a9..c09a6025de 100644 --- a/src/tools/Grid.cpp +++ b/src/tools/Grid.cpp @@ -112,8 +112,9 @@ void GridBase::Init(const std::string& funcl, const std::vector &na nbin_=nbin; dospline_=dospline; usederiv_=usederiv; - if(dospline_) + if(dospline_) { plumed_assert(dospline_==usederiv_); + } maxsize_=1; for(unsigned int i=0; i( nbin_[i] ) ); @@ -143,8 +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_) + 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_) + if (indices.size()!=dimension_) { indices.resize(dimension_); + } for(unsigned int i=0; i GridBase::getNeighbors(const std::vector=static_cast(nbin_[i])) + } + if(!pbc_[i] && i0>=static_cast(nbin_[i])) { continue; - if( pbc_[i] && i0<0) + } + if( pbc_[i] && i0<0) { i0=nbin_[i]-(-i0)%nbin_[i]; - if( pbc_[i] && i0>=static_cast(nbin_[i])) + } + if( pbc_[i] && i0>=static_cast(nbin_[i])) { i0%=nbin_[i]; + } tmp_indices[ll]=static_cast(i0); ll++; } @@ -329,8 +337,9 @@ 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) + if (neighbors.size()!=nneigh) { neighbors.resize(nneigh); + } std::vector nindices(dimension_); unsigned inind; @@ -341,14 +350,17 @@ void GridBase::getSplineNeighbors(const std::vector & indices, std::ve for(unsigned int j=0; jset(xx[j]); + } double newval = kernel.evaluate( vv_ptr, der, usederiv_ ); - if( usederiv_ ) + if( usederiv_ ) { addValueAndDerivatives( ineigh, newval, der ); - else + } + else { addValue( ineigh, newval ); + } } } @@ -437,8 +452,9 @@ 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); @@ -457,17 +473,20 @@ 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) + if(i>0 && dimension_>1 && getIndices(i)[dimension_-2]==0) { ofile.printf("\n"); + } for(unsigned j=0; j(nbin_[j]) ); - if( pbc_[j] ) + if( pbc_[j] ) { ofile.printField("periodic_" + argnames[j], "true" ); - else + } + else { ofile.printField("periodic_" + argnames[j], "false" ); + } } for(unsigned j=0; j GridBase::create(const std::string& funcl, const std:: std::vector fieldnames; ifile.scanFieldList( fieldnames ); // Retrieve names for fields - 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:: std::string pmin, pmax; args[i]->getDomain( pmin, pmax ); gbin[i]=gbin1[i]; - if( pmin!=gmin[i] || pmax!=gmax[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 ) + if( doder && !hasder ) { plumed_merror("missing derivatives from grid file"); + } for(unsigned j=0; jmaxval) + if(grid_[i]>maxval) { maxval=grid_[i]; + } } return maxval; } @@ -705,12 +738,14 @@ void Grid::scaleAllValuesAndDerivatives( const double& scalef ) { if(usederiv_) { for(index_t i=0; i mymin( this ); for(unsigned i=0; i& der) const { plumed_dbg_assert(index& der) { plumed_dbg_assert(index& der) { plumed_dbg_assert(indexsecond; + } return value; } double SparseGrid::getValueAndDerivatives(index_t index, std::vector& der)const { plumed_assert(indexsecond; + } const auto itder=der_.find(index); - if(itder!=der_.end()) + if(itder!=der_.end()) { der=itder->second; + } return value; } @@ -904,8 +958,9 @@ void SparseGrid::addValueAndDerivatives(index_t index, double value, std::vector plumed_assert(index0 && dimension_>1 && getIndices(i)[dimension_-2]==0) + if(i>0 && dimension_>1 && getIndices(i)[dimension_-2]==0) { ofile.printf("\n"); + } for(unsigned j=0; j(nbin_[j]) ); - if( pbc_[j] ) + if( pbc_[j] ) { ofile.printField("periodic_" + argnames[j], "true" ); - else + } + else { ofile.printField("periodic_" + argnames[j], "false" ); + } } - for(unsigned j=0; jmaxval) + if(i.second>maxval) { maxval=i.second; + } } return maxval; } @@ -984,8 +1046,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) + if (!pp) { plumed_merror("This WeightBase is not complete: you need a projectInnerLoop and projectOuterLoop "); + } for(unsigned j=0; j & proj, WeightBase *ptr2obj ) break; } } - if(doappend) + if(doappend) { toBeIntegrated.push_back(i); + } } // loop over all the points in the Grid, find the corresponding fixed index, rotate over all the other ones @@ -1057,8 +1122,9 @@ Grid Grid::project(const std::vector & proj, WeightBase *ptr2obj ) std::vector v; v=smallgrid.getIndices(i); std::vector vHigh((getArgNames()).size(),-1); - for(unsigned j=0; j& npoints ) { kk=(kk-t_index[j-1])/npoints[j-1]; t_index[j]=(kk%npoints[j]); } - if( dimension_>=2 ) + if( dimension_>=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 &names, const std::vector & gmin, @@ -266,8 +267,9 @@ class Grid : public GridBase GridBase(funcl,names,gmin,gmax,nbin,dospline,usederiv,isperiodic,pmin,pmax) { grid_.assign(maxsize_,0.0); - if(usederiv_) + 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) diff --git a/src/tools/HistogramBead.cpp b/src/tools/HistogramBead.cpp index 6fd49a1f59..f3698b7783 100644 --- a/src/tools/HistogramBead.cpp +++ b/src/tools/HistogramBead.cpp @@ -159,18 +159,22 @@ void HistogramBead::set( const std::string& params, std::string& errormsg ) { type=triangular; cutoff=1.; } - else + else { plumed_merror("cannot understand kernel type " + name ); + } double smear; bool found_r=Tools::parse(data,"LOWER",lowb); - if( !found_r ) + if( !found_r ) { errormsg="Lower bound has not been specified use LOWER"; + } found_r=Tools::parse(data,"UPPER",highb); - if( !found_r ) + if( !found_r ) { errormsg="Upper bound has not been specified use UPPER"; - if( lowb>=highb ) + } + if( lowb>=highb ) { errormsg="Lower bound is higher than upper bound"; + } smear=0.5; Tools::parse(data,"SMEAR",smear); @@ -184,21 +188,27 @@ void HistogramBead::set( double l, double h, double w) { highb=h; width=w; const double DP2CUTOFF=6.25; - if( type==gaussian ) + if( type==gaussian ) { cutoff=std::sqrt(2.0*DP2CUTOFF); - else if( type==triangular ) + } + else if( type==triangular ) { cutoff=1.; - else + } + else { plumed_error(); + } } void HistogramBead::setKernelType( const std::string& ktype ) { - if(ktype=="gaussian") + if(ktype=="gaussian") { type=gaussian; - else if(ktype=="triangular") + } + else if(ktype=="triangular") { type=triangular; - else + } + else { plumed_merror("cannot understand kernel type " + ktype ); + } } double HistogramBead::calculate( double x, double& df ) const { @@ -213,10 +223,12 @@ 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. ) + if( std::fabs(lowB)<1. ) { df = (1 - std::fabs(lowB)) / width; - if( std::fabs(upperB)<1. ) + } + if( std::fabs(upperB)<1. ) { df -= (1 - std::fabs(upperB)) / width; + } if (upperB<=-1. || lowB >=1.) { f=0.; } else { @@ -257,10 +269,12 @@ double HistogramBead::calculateWithCutoff( double x, double& df ) const { f = 0.5*( erf( upperB ) - erf( lowB ) ); } else if( type==triangular ) { df=0; - if( std::fabs(lowB)<1. ) + if( std::fabs(lowB)<1. ) { df = (1 - std::fabs(lowB)) / width; - if( std::fabs(upperB)<1. ) + } + if( std::fabs(upperB)<1. ) { df -= (1 - std::fabs(upperB)) / width; + } if (upperB<=-1. || lowB >=1.) { f=0.; } else { diff --git a/src/tools/HistogramBead.h b/src/tools/HistogramBead.h index fafb309942..35d3bd0ca9 100644 --- a/src/tools/HistogramBead.h +++ b/src/tools/HistogramBead.h @@ -113,8 +113,9 @@ double HistogramBead::difference( const double& d1, const double& d2 ) const { newx=Tools::pbc(newx); newx*=max_minus_min; return d2-newx; - } else + } else { plumed_merror("periodicty was not set"); + } return 0; } diff --git a/src/tools/IFile.cpp b/src/tools/IFile.cpp index 07379ccf2c..d9f5bdfa5c 100644 --- a/src/tools/IFile.cpp +++ b/src/tools/IFile.cpp @@ -44,20 +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) + if(rr==0) { eof=true; - if(rr<0) + } + 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)) + if(std::feof(fp)) { eof=true; - if(std::ferror(fp)) + } + if(std::ferror(fp)) { err=true; + } } return r; } @@ -98,8 +102,9 @@ IFile& IFile::advanceField() { if( words.size()==nf ) { unsigned j=0; for(unsigned i=0; iinsertFile(*this); + } return *this; } IFile& IFile::scanFieldList(std::vector&s) { - if(!inMiddleOfField) + if(!inMiddleOfField) { advanceField(); + } // using explicit conversion not to confuse cppcheck 1.86 - if(!bool(*this)) + if(!bool(*this)) { return *this; + } s.clear(); - for(unsigned i=0; i0;? - if(mycount>0) + if(mycount>0) { return true; - else + } + else { return false; + } } IFile& IFile::scanField(const std::string&name,std::string&str) { - if(!inMiddleOfField) + if(!inMiddleOfField) { advanceField(); + } // using explicit conversion not to confuse cppcheck 1.86 - if(!bool(*this)) + if(!bool(*this)) { return *this; + } unsigned i=findField(name); str=fields[i].value; fields[i].read=true; @@ -173,56 +186,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) + 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) + 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) + 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) + 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) + 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) + 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) + if(*this) { Tools::convert(str,x); + } return *this; } @@ -259,8 +279,9 @@ IFile::IFile(): } IFile::~IFile() { - if(inMiddleOfField) + if(inMiddleOfField) { std::cerr<<"WARNING: IFile closed in the middle of reading. seems strange!\n"; + } } IFile& IFile::getline(std::string &str) { @@ -276,13 +297,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) + if(str.length()>0) { eof=false; + } } else if(eof || err || tmp!='\n') { eof = true; str=""; - if(!err) + 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 @@ -310,11 +333,13 @@ unsigned IFile::findField(const std::string&name)const { void IFile::reset(bool reset) { eof = reset; err = reset; - if(!reset && fp) + if(!reset && fp) { clearerr(fp); + } #ifdef __PLUMED_HAS_ZLIB - if(!reset && gzfp) + if(!reset && gzfp) { gzclearerr(gzFile(gzfp)); + } #endif return; } diff --git a/src/tools/KernelFunctions.cpp b/src/tools/KernelFunctions.cpp index 13f388a9f5..1e9b0453d8 100644 --- a/src/tools/KernelFunctions.cpp +++ b/src/tools/KernelFunctions.cpp @@ -105,39 +105,50 @@ KernelFunctions::KernelFunctions( const std::string& input ) { std::vector at; bool foundc = Tools::parseVector(data,"CENTER",at); - if(!foundc) + 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) + 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 ) + if( center.size()==1 && multi ) { plumed_merror("one dimensional kernel cannot be multivariate"); - if( center.size()==1 && vonmises ) + } + if( center.size()==1 && vonmises ) { plumed_merror("one dimensional kernal cannot be von-misses"); - if( center.size()==1 && sig.size()!=1 ) + } + 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) ) + } + 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() ) + } + 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) + if( !foundh) { h=1.0; + } - if( multi ) + if( multi ) { setData( at, sig, name, "MULTIVARIATE", h ); - else if( vonmises ) + } + else if( vonmises ) { setData( at, sig, name, "VON-MISSES", h ); - else + } + 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 ) { @@ -167,19 +178,25 @@ void KernelFunctions::setData( const std::vector& at, const std::vector< 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); @@ -222,19 +240,23 @@ 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); + } volume=( pow( pi, (ncv-1)/2 ) ) * ( pow( 2., (ncv+1)/2 ) ) / dfact; } else { double fact=1.; - for(unsigned i=1; i(i); + } volume=pow( pi,ncv/2 ) / fact; } - if(ktype==uniform) + if(ktype==uniform) { volume*=det; - else if(ktype==triangular) + } + else if(ktype==triangular) { volume*=det / 3.; + } } else { plumed_merror("not a valid kernel type"); } @@ -245,8 +267,9 @@ void KernelFunctions::normalize( const std::vector& myvals ) { // Now calculate determinant for aperiodic variables unsigned naper=0; for(unsigned i=0; iisPeriodic() ) + if( !myvals[i]->isPeriodic() ) { naper++; + } } // Now construct sub matrix double volume=1; @@ -254,12 +277,14 @@ void KernelFunctions::normalize( const std::vector& myvals ) { unsigned isub=0; Matrix mymatrix( getMatrix() ), mysub( naper, naper ); for(unsigned i=0; iisPeriodic() ) + if( myvals[i]->isPeriodic() ) { continue; + } unsigned jsub=0; for(unsigned j=0; jisPeriodic() ) + if( myvals[j]->isPeriodic() ) { continue; + } mysub( isub, jsub ) = mymatrix( i, j ); jsub++; } @@ -276,8 +301,9 @@ void KernelFunctions::normalize( const std::vector& myvals ) { // Calculate volume of periodic variables unsigned nper=0; for(unsigned i=0; iisPeriodic() ) + if( myvals[i]->isPeriodic() ) { nper++; + } } // Now construct sub matrix @@ -285,12 +311,14 @@ void KernelFunctions::normalize( const std::vector& myvals ) { unsigned isub=0; Matrix mymatrix( getMatrix() ), mysub( nper, nper ); for(unsigned i=0; iisPeriodic() ) + if( !myvals[i]->isPeriodic() ) { continue; + } unsigned jsub=0; for(unsigned j=0; jisPeriodic() ) + if( !myvals[j]->isPeriodic() ) { continue; + } mysub( isub, jsub ) = mymatrix( i, j ); jsub++; } @@ -313,14 +341,18 @@ 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 ) + if( ktype==gaussian || ktype==truncatedgaussian || ktype==stretchedgaussian ) { return std::sqrt(2.0*DP2CUTOFF)*width; - else if(ktype==triangular ) + } + else if(ktype==triangular ) { return width; - else if(ktype==uniform) + } + else if(ktype==uniform) { return width; - else + } + else { plumed_merror("No valid kernel type"); + } return 0.0; } @@ -328,8 +360,9 @@ 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); @@ -358,23 +391,27 @@ std::vector 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] )); + } 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 ) + 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()get()set(lowI_); - if(pos[0]->get()>uppI_) + } + if(pos[0]->get()>uppI_) { pos[0]->set(uppI_); + } } double r2=0; if(dtype==diagonal) { @@ -390,10 +427,12 @@ double KernelFunctions::evaluate( const std::vector& pos, std::vectordifference( center[i] ); for(unsigned j=0; jdifference( center[j] ); + } derivatives[i]+=mymatrix(i,j)*dp_j; r2+=dp_i*dp_j*mymatrix(i,j); @@ -420,15 +459,18 @@ double KernelFunctions::evaluate( const std::vector& pos, std::vectorisPeriodic() ) + if( pos[i]->isPeriodic() ) { derivatives[i] *= (2*pi/pos[i]->getMaxMinusMin()); + } } - for(unsigned i=0; i& pos, std::vector& pos, std::vectorget() <= lowI_ || pos[0]->get() >= uppI_) && usederiv ) { for(unsigned i=0; i& pos, std::vector KernelFunctions::read( IFile* ifile, const bool& cholesky, const std::vector& valnames ) { double h; - if( !ifile->scanField("height",h) ) - return NULL;; + if( !ifile->scanField("height",h) ) { + return NULL; + }; std::string sss; ifile->scanField("multivariate",sss); std::string ktype="stretched-gaussian"; - if( ifile->FieldExist("kerneltype") ) + 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]); + } std::vector sig; if( sss=="false" ) { sig.resize( valnames.size() ); for(unsigned i=0; iscanField("sigma_"+valnames[i],sig[i]); - if( !cholesky ) + if( !cholesky ) { sig[i]=std::sqrt(sig[i]); + } } return Tools::make_unique(cc, sig, ktype, "DIAGONAL", h); } @@ -517,8 +567,9 @@ std::unique_ptr KernelFunctions::read( IFile* ifile, const bool mymult(j+i,j)=mymult(j,j+i)=lower(j+i,j); } } - if( cholesky ) + if( cholesky ) { mult(lower,upper,mymult); + } Invert( mymult, invmatrix ); unsigned k=0; for(unsigned i=0; i KernelFunctions::read( IFile* ifile, const bool k++; } } - if( sss=="true" ) + 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/Keywords.cpp b/src/tools/Keywords.cpp index db8ba18b25..0ddff538fe 100644 --- a/src/tools/Keywords.cpp +++ b/src/tools/Keywords.cpp @@ -78,48 +78,59 @@ void Keywords::copyData( std::vector& kk, std::vector& std::map& cd ) const { for(unsigned i=0; i( thiskey,types.find(thiskey)->second) ); - if( (types.find(thiskey)->second).isAtomList() ) + 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 ) ) + if( booldefs.count( thiskey ) ) { bools.insert( std::pair( thiskey,booldefs.find(thiskey)->second) ); - if( numdefs.count( thiskey ) ) + } + 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() ) + 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 ) ) + if( booldefs.count( thiskey ) ) { bools.insert( std::pair( thiskey,booldefs.find(thiskey)->second) ); - if( numdefs.count( thiskey ) ) + } + if( numdefs.count( thiskey ) ) { nums.insert( std::pair( thiskey,numdefs.find(thiskey)->second) ); + } } for(unsigned i=0; i( thisnam, ckey.find(thisnam)->second) ); @@ -138,8 +149,9 @@ void Keywords::reserve( const std::string & t, const std::string & k, const std: // Remove any underscore characters for(unsigned i=0;; ++i) { std::size_t num=lowkey.find_first_of("_"); - if( num==std::string::npos ) + if( num==std::string::npos ) { break; + } lowkey.erase( lowkey.begin() + num, lowkey.begin() + num + 1 ); } if( t=="vessel" ) { @@ -158,12 +170,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 ) + 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() ) + if( (types.find(k)->second).isAtomList() ) { atomtags.insert( std::pair(k,t) ); + } } documentation.insert( std::pair(k,fd) ); reserved_keys.push_back(k); @@ -192,18 +206,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() ) + if( (types.find(k)->second).isVessel() ) { allowmultiple[k]=true; - if( (types.find(k)->second).isAtomList() ) + } + 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 ) { @@ -217,11 +234,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() ) + if( (types.find(k)->second).isAtomList() ) { atomtags.insert( std::pair(k,t) ); + } } - if( t=="atoms" && isaction ) + 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); } @@ -268,8 +287,9 @@ void Keywords::remove( const std::string & k ) { } else if(nsecond; } bool Keywords::style( const std::string & k, const std::string & t ) const { //return getStyle(k)==t;? - if( getStyle(k)==t ) + if( getStyle(k)==t ) { return true; + } return false; } @@ -308,16 +330,18 @@ bool Keywords::exists( const std::string & k ) const { // return std::any_of(keys.begin(),keys.end(),[k](const std::string& s){return s==k;}); //but needs a performance check for(unsigned i=0; isecond).isAtomList() ) + 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 ) + if( prevtag!="start" && prevtag!=atomtags.find(keys[i])->second ) { break; - if( (atomtags.find(keys[i])->second).find("residues")!=std::string::npos) + } + if( (atomtags.find(keys[i])->second).find("residues")!=std::string::npos) { std::printf(" %s=", keys[i].c_str() ); - else + } + else { std::printf(" %s=", keys[i].c_str() ); + } prevtag=atomtags.find(keys[i])->second; } } } nkeys=0; for(unsigned i=0; isecond).isCompulsory() ) + if ( include_optional || (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 ) + if( allowmultiple.find(keys[i])->second ) { std::printf(",numbered:%s",keys[i].c_str() ); - else + } + else { std::printf(",option:%s",keys[i].c_str() ); + } } } std::fprintf(stdout, "\n%s", getHelpString().c_str() ); @@ -388,8 +419,9 @@ void Keywords::print_html() const { if( cnames.size()>0 ) { unsigned ndef=0; for(unsigned i=0; isecond=="default") + if(ckey.find(cnames[i])->second=="default") { ndef++; + } } if( ndef>0 ) { @@ -429,8 +461,9 @@ void Keywords::print_html() const { } else { unsigned nregs=0; for(unsigned i=0; isecond) ) + if( exists(ckey.find(cnames[i])->second) ) { nregs++; + } } if( nregs>0 ) { std::cout<<"\\par Description of components\n\n"; @@ -453,16 +486,20 @@ void Keywords::print_html() const { unsigned nkeys=0; for(unsigned i=0; isecond).isAtomList() ) + if ( (types.find(keys[i])->second).isAtomList() ) { nkeys++; + } } if( nkeys>0 ) { - if(isaction && isatoms) + if(isaction && isatoms) { std::cout<<"\\par The atoms involved can be specified using\n\n"; - else if(isaction) + } + else if(isaction) { std::cout<<"\\par The data to analyze can be the output from another analysis algorithm\n\n"; - else + } + 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; @@ -471,14 +508,16 @@ void Keywords::print_html() const { 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 ) + 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 + 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] ); @@ -489,57 +528,69 @@ void Keywords::print_html() const { } nkeys=0; for(unsigned i=0; isecond).isCompulsory() ) + if ( (types.find(keys[i])->second).isCompulsory() ) { nkeys++; + } } if( nkeys>0 ) { - if(isaction) + if(isaction) { std::cout<< "\\par Compulsory keywords\n\n"; - else + } + else { std::cout<<"\\par The following must be present\n\n"; + } std::cout<<"
\n"; for(unsigned i=0; isecond).isCompulsory() ) + 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() ) + 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) + if(isaction) { std::cout<<"\\par Options\n\n"; - else + } + else { std::cout<<"\\par The following options are available\n\n"; + } std::cout<<" \n"; for(unsigned i=0; isecond).isFlag() ) + 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() ) + 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() ) + 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; i60 ) { sstr<<"\n"<second).isAtomList() ) + 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() ) + if ( (types.find(keys[i])->second).isAtomList() ) { helpstr += getKeywordDocs( keys[i] ); + } } } nkeys=0; for(unsigned i=0; isecond).isCompulsory() ) + 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() ) + if ( (types.find(keys[i])->second).isCompulsory() ) { helpstr += getKeywordDocs( keys[i] ); + } } } nkeys=0; for(unsigned i=0; isecond).isFlag() ) + if ( (types.find(keys[i])->second).isFlag() ) { nkeys++; + } } if( nkeys>0 ) { - if(ncompulsory>0) + if(ncompulsory>0) { helpstr += "\nIn addition you may use the following options: \n\n"; - else + } + else { helpstr += "\nThe following options are available\n\n"; + } for(unsigned i=0; isecond).isFlag() ) + 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() ) + 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() ) + if ( (types.find(keys[i])->second).isOptional() || (types.find(keys[i])->second).isVessel() ) { helpstr += getKeywordDocs( keys[i] ); + } } helpstr += "\n"; } @@ -631,8 +694,9 @@ 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) ) + 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 "; @@ -653,8 +717,9 @@ std::string Keywords::getTooltip( const std::string& name ) const { } else { mystring += w[i] + " "; } - if( w[i].find(".")!=std::string::npos ) - break; // Only write up the the first dot + if( w[i].find(".")!=std::string::npos ) { + break; // Only write up the the first dot + } } return mystring; } @@ -726,23 +791,28 @@ 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 ) + 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 ) + if( num2!=std::string::npos ) { sname=name.substr(num2); - else if( num!=std::string::npos ) + } + else if( num!=std::string::npos ) { sname=name.substr(0,num); - else + } + else { sname=name; + } for(unsigned i=0; isecond; } @@ -778,8 +851,9 @@ void Keywords::removeComponent( const std::string& name ) { if(j=modulo2(v[2])) + if(modulo2(best)*onePlusEpsilon>=modulo2(v[2])) { break; + } counter++; - if(counter%10000==0) + if(counter%10000==0) { std::fprintf(stderr,"WARNING: LatticeReduction::reduceFast stuck after %u iterations\n",counter); + } v[2]=best; } sort(v); @@ -187,15 +193,19 @@ void LatticeReduction::reduceSlow(Tensor&t) { double e12=dotProduct(v[1],v[2]); if(e01*e02*e12<0) { int eps01=0; - if(e01>0.0) + if(e01>0.0) { eps01=1; - else if(e01<0.0) + } + else if(e01<0.0) { eps01=-1; + } int eps02=0; - if(e02>0.0) + if(e02>0.0) { eps02=1; - else if(e02<0.0) + } + 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]); @@ -206,8 +216,9 @@ void LatticeReduction::reduceSlow(Tensor&t) { mx=f; } } - if(modulo2(n)& 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 ) + if( ncells[0]==0 ) { ncells[0]=1; + } ncells[1] = std::floor( 1.0/ reciprocal.getRow(1).modulo() / link_cutoff ); - if( ncells[1]==0 ) + if( ncells[1]==0 ) { ncells[1]=1; + } ncells[2] = std::floor( 1.0/ reciprocal.getRow(2).modulo() / link_cutoff ); - if( ncells[2]==0 ) + if( ncells[2]==0 ) { ncells[2]=1; + } } // Setup the strides nstride[0]=1; @@ -85,8 +88,9 @@ void LinkCells::buildCellLists( const std::vector& pos, const std::vecto lcell_starts.resize( ncellstot ); } // Clear nlcells - for(unsigned i=0; i& celn, unsigned& void LinkCells::retrieveNeighboringAtoms( const Vector& pos, std::vector& cell_list, unsigned& natomsper, std::vector& atoms ) const { - if( cell_list.size()!=getNumberOfCells() ) + 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/Matrix.h b/src/tools/Matrix.h index b8ba9ae97e..354aa4fe6c 100644 --- a/src/tools/Matrix.h +++ b/src/tools/Matrix.h @@ -117,8 +117,9 @@ class Matrix: /// Set the matrix from a vector input inline void setFromVector( const std::vector& vecin ) { plumed_assert( vecin.size()==sz ); - for(unsigned i=0; i void mult( const std::vector& A, const Matrix& B, st } template void transpose( const Matrix& A, Matrix& AT ) { - if( A.rw!=AT.cl || A.cl!=AT.rw ) + if( A.rw!=AT.cl || A.cl!=AT.rw ) { AT.resize( A.cl, A.rw ); + } for(unsigned i=0; i void transpose( const Matrix& A, Matrix& AT ) { } template Log& operator<<(Log& ostr, const Matrix& mat) { - for(unsigned i=0; i 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) + if (info!=0) { return info; + } // Retrieve correct sizes for work and iwork then reallocate liwork=iwork[0]; @@ -318,8 +322,9 @@ 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) + if (info!=0) { return info; + } if( eigenvals.size()!=A.cl ) { eigenvals.resize( A.cl ); @@ -387,8 +392,9 @@ 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) + if(info!=0) { return info; + } // Retrieve correct sizes for work and rellocate lwork=(int) work[0]; @@ -396,8 +402,9 @@ template int pseudoInvert( const Matrix& A, Matrix& pseu // 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) + if(info!=0) { return info; + } // Compute the tolerance on the singular values ( machine epsilon * number of singular values * maximum singular value ) double tol; @@ -436,8 +443,9 @@ template int pseudoInvert( const Matrix& A, Matrix& pseu } // And do matrix algebra to construct the pseudoinverse - if( pseudoinverse.rw!=ncols || pseudoinverse.cl!=nrows ) + if( pseudoinverse.rw!=ncols || pseudoinverse.cl!=nrows ) { pseudoinverse.resize( ncols, nrows ); + } mult( V, Si, tmp ); mult( tmp, UT, pseudoinverse ); @@ -454,8 +462,9 @@ template int Invert( const Matrix& A, Matrix& inverse ) Matrix evec(A.rw,A.cl), tevec(A.rw,A.cl); int err; err=diagMat( A, eval, evec ); - if(err!=0) + if(err!=0) { return err; + } for (unsigned i=0; i int Invert( const Matrix& A, Matrix& inverse ) } plumed_lapack_dgetrf(&n,&n,da.data(),&n,ipiv.data(),&info); - if(info!=0) + 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) + if(info!=0) { return info; + } lwork=static_cast( work[0] ); work.resize(lwork); plumed_lapack_dgetri(&n,da.data(),&n,ipiv.data(),work.data(),&lwork,&info); - if(info!=0) + if(info!=0) { return info; + } if( inverse.cl!=A.cl || inverse.rw!=A.rw ) { inverse.resize(A.rw,A.cl); @@ -513,21 +525,26 @@ template void cholesky( const Matrix& A, Matrix& B ) { L(i,i)=static_cast( 1 ); for (unsigned j=0; j( 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); @@ -548,8 +565,9 @@ template void chol_elsolve( const Matrix& M, const std::vector 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) + if (info!=0) { return info; + } // Retrieve correct sizes for work and iwork then reallocate lwork=static_cast( work[0] ); @@ -590,8 +609,9 @@ 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) + if (info!=0) { return info; + } // Transfer the eigenvalues and eigenvectors to the output ldet=0; diff --git a/src/tools/Minimise1DBrent.h b/src/tools/Minimise1DBrent.h index 5ed35d2cf2..3fe3099f88 100644 --- a/src/tools/Minimise1DBrent.h +++ b/src/tools/Minimise1DBrent.h @@ -179,8 +179,9 @@ double Minimise1DBrent::minimise( eng_pointer eng ) { q=(x-v)*(fx-fw); p=(x-v)*q-(x-w)*r; q=2.0*(q-r); - if( q > 0.0 ) + if( q > 0.0 ) { p = -p; + } q=std::fabs(q); etemp=e; e=d; @@ -189,22 +190,27 @@ double Minimise1DBrent::minimise( eng_pointer eng ) { } else { d=p/q; u=x+d; - if(u-a < tol2 || b-u < tol2 ) + 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) + if( std::fabs(d)>=tol1) { u=x+d; - else + } + else { u=x+(d>=0?std::fabs(tol1):-std::fabs(tol1)); + } fu=(myclass_func.*eng)(u); if( fu <= fx ) { - if( u >= x ) + if( u >= x ) { a=x; - else + } + else { b=x; + } v=w; fv=fw; w=x; @@ -212,10 +218,12 @@ double Minimise1DBrent::minimise( eng_pointer eng ) { x=u; fx=fu; } else { - if( u < x ) + if( u < x ) { a=u; - else + } + else { b=u; + } if( fu <=fw || w==x ) { v=w; w=u; diff --git a/src/tools/MinimiseBase.h b/src/tools/MinimiseBase.h index e4a7bcd4a4..af8544f076 100644 --- a/src/tools/MinimiseBase.h +++ b/src/tools/MinimiseBase.h @@ -68,10 +68,12 @@ F1dim::F1dim( const std::vector& pp, const std::vector& template double F1dim::getEng( const double& xt ) { - for(unsigned j=0; j*calc)(pt,fake_der); + } return (func->*calc2)(pt,fake_der); } @@ -104,8 +106,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& buffer ) { - if( !hasDerivatives.updateComplete() ) + if( !hasDerivatives.updateComplete() ) { hasDerivatives.updateActiveMembers(); + } plumed_dbg_assert( off& positions) { // find total dimension of neighborlist std::vector local_nl_size(stride, 0); local_nl_size[rank] = local_flat_nl.size(); - if(!serial_) + if(!serial_) { comm.Sum(&local_nl_size[0], stride); + } int tot_size = std::accumulate(local_nl_size.begin(), local_nl_size.end(), 0); if(tot_size==0) { setRequestList(); @@ -155,10 +156,12 @@ void NeighborList::update(const std::vector& positions) { disp[i+1] = rank_size; } // Allgather neighbor list - if(comm.initialized()&&!serial_) + 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 + } + else { merge_nl = local_flat_nl; + } // resize neighbor stuff neighbors_.resize(tot_size/2); for(unsigned i=0; i NeighborList::getClosePairAtomNumber(unsigned i std::vector NeighborList::getNeighbors(unsigned index) { std::vector neighbors; for(unsigned int i=0; illwrite(ptr,s); + } if(! (comm && comm->Get_rank()>0)) { - if(!fp) + if(!fp) { plumed_merror("writing on uninitialized File"); + } if(gzfp) { #ifdef __PLUMED_HAS_ZLIB r=gzwrite(gzFile(gzfp),ptr,s); @@ -86,8 +88,9 @@ OFile::OFile(): 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) + while(newlen<=r+actual_buffer_length) { newlen*=2; + } std::vector newbuf(newlen); std::memmove(newbuf.data(),buffer.data(),buflen); - for(int k=buflen; k0) + 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) + if(buffer.data()!=p1) { std::memmove(buffer.data(),p1,actual_buffer_length); + } return r; } @@ -174,8 +181,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)) + 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; @@ -220,8 +228,9 @@ 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; @@ -229,8 +238,9 @@ OFile& OFile::printField(const std::string&name,const std::string & v) { field.value=v; fields.push_back(field); } else { - if(const_fields[i].value!=v) + if(const_fields[i].value!=v) { fieldChanged=true; + } const_fields[i].value=v; } return *this; @@ -270,16 +280,18 @@ OFile& OFile::printField() { } if(reprint) { printf("#! FIELDS"); - for(unsigned i=0; i0 && (!comm || comm->Get_rank()==0)) { FILE* ff=std::fopen(const_cast(fname.c_str()),"r"); if(ff) { @@ -329,15 +346,18 @@ 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) + 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) + if(!fff) { break; - else + } + 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)); @@ -365,8 +385,9 @@ OFile& OFile::open(const std::string&path) { } } else { backupFile( backstring, this->path ); - if(comm) + if(comm) { comm->Barrier(); + } fp=std::fopen(const_cast(this->path.c_str()),"w"); mode="w"; if(Tools::extension(this->path)=="gz") { @@ -377,8 +398,9 @@ OFile& OFile::open(const std::string&path) { #endif } } - if(plumed) + if(plumed) { plumed->insertFile(*this); + } return *this; } @@ -399,8 +421,9 @@ OFile& OFile::rewind() { plumed_massert(check==0,"renaming "+fname+" into "+backup+" failed for reason: "+std::strerror(errno)); } - if(comm) + if(comm) { comm->Barrier(); + } if(gzfp) { #ifdef __PLUMED_HAS_ZLIB @@ -435,24 +458,30 @@ 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) + if(gzfp) { gzflush(gzFile(gzfp),Z_FULL_FLUSH); + } #endif } return *this; } bool OFile::checkRestart()const { - if(enforceRestart_) + if(enforceRestart_) { return true; - else if(enforceBackup_) + } + else if(enforceBackup_) { return false; - else if(action) + } + else if(action) { return action->getRestart(); - else if(plumed) + } + else if(plumed) { return plumed->getRestart(); - else + } + else { return false; + } } OFile& OFile::enforceRestart() { diff --git a/src/tools/OpenMP.cpp b/src/tools/OpenMP.cpp index ef7ccf4145..90e40417df 100644 --- a/src/tools/OpenMP.cpp +++ b/src/tools/OpenMP.cpp @@ -48,8 +48,9 @@ void OpenMP::setNumThreads(const unsigned nt) { unsigned OpenMP::getCachelineSize() { if(!getOpenMPVars().cache_set) { - if(std::getenv("PLUMED_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; @@ -57,8 +58,9 @@ unsigned OpenMP::getCachelineSize() { unsigned OpenMP::getNumThreads() { if(!getOpenMPVars().nt_env_set) { - if(std::getenv("PLUMED_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 3d90451bf3..a8e07673c3 100644 --- a/src/tools/OpenMP.h +++ b/src/tools/OpenMP.h @@ -60,20 +60,24 @@ 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) + if(m>=numThreads) { m=numThreads; - else + } + else { m=1; + } return m; } template unsigned OpenMP::getGoodNumThreads(const std::vector & v) { - if(v.size()==0) + if(v.size()==0) { return 1; - else + } + else { return getGoodNumThreads(&v[0],v.size()); + } } diff --git a/src/tools/PDB.cpp b/src/tools/PDB.cpp index 283cae9c28..14055f611e 100644 --- a/src/tools/PDB.cpp +++ b/src/tools/PDB.cpp @@ -161,8 +161,9 @@ bool PDB::getArgumentValue( const std::string& name, double& value ) const { void PDB::setAtomPositions( const std::vector& pos ) { plumed_assert( pos.size()==positions.size() ); - for(unsigned i=0; i& v1 ) { bool PDB::hasFlag( const std::string& fname ) const { for(unsigned i=0; isecond]; + } } unsigned PDB::getResidueNumber(AtomNumber a)const { @@ -278,8 +281,9 @@ unsigned PDB::getResidueNumber(AtomNumber a)const { std::string num; Tools::convert( a.serial(), num ); plumed_merror("Residue for atom " + num + " not found" ); - } else + } else { return residue[p->second]; + } } std::string PDB::getResidueName(AtomNumber a) const { @@ -288,8 +292,9 @@ std::string PDB::getResidueName(AtomNumber a) const { std::string num; Tools::convert( a.serial(), num ); plumed_merror("Residue for atom " + num + " not found" ); - } else + } else { return residuenames[p->second]; + } } unsigned PDB::size()const { @@ -299,16 +304,18 @@ unsigned PDB::size()const { bool PDB::readFromFilepointer(FILE *fp,bool naturalUnits,double scale) { //cerr<0) { int result; - while(trimmed.length()<4) + 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); @@ -425,15 +434,17 @@ bool PDB::readFromFilepointer(FILE *fp,bool naturalUnits,double scale) { residuenames.push_back(residuename); } } - if( between_ters ) + 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) + if(!fp) { return false; + } // call fclose when exiting this function auto deleter=[](FILE* f) { std::fclose(f); @@ -447,8 +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]; + } } std::vector PDB::getArgumentNames()const { @@ -627,8 +654,9 @@ 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) + 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 ) + } + if( argnames.size()>0 ) { ofile.printf("\n"); + } if( !mymoldat ) { for(unsigned i=0; i at; @@ -690,240 +720,353 @@ 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") + if(residuename=="ALA") { return true; - else if(residuename=="ARG") + } + else if(residuename=="ARG") { return true; - else if(residuename=="ASN") + } + else if(residuename=="ASN") { return true; - else if(residuename=="ASP") + } + else if(residuename=="ASP") { return true; - else if(residuename=="CYS") + } + else if(residuename=="CYS") { return true; - else if(residuename=="GLN") + } + else if(residuename=="GLN") { return true; - else if(residuename=="GLU") + } + else if(residuename=="GLU") { return true; - else if(residuename=="GLY") + } + else if(residuename=="GLY") { return true; - else if(residuename=="HIS") + } + else if(residuename=="HIS") { return true; - else if(residuename=="ILE") + } + else if(residuename=="ILE") { return true; - else if(residuename=="LEU") + } + else if(residuename=="LEU") { return true; - else if(residuename=="LYS") + } + else if(residuename=="LYS") { return true; - else if(residuename=="MET") + } + else if(residuename=="MET") { return true; - else if(residuename=="PHE") + } + else if(residuename=="PHE") { return true; - else if(residuename=="PRO") + } + else if(residuename=="PRO") { return true; - else if(residuename=="SER") + } + else if(residuename=="SER") { return true; - else if(residuename=="THR") + } + else if(residuename=="THR") { return true; - else if(residuename=="TRP") + } + else if(residuename=="TRP") { return true; - else if(residuename=="TYR") + } + else if(residuename=="TYR") { return true; - else if(residuename=="VAL") + } + else if(residuename=="VAL") { return true; + } // Terminal groups - else if(residuename=="ACE") + else if(residuename=="ACE") { return true; - else if(residuename=="NME") + } + else if(residuename=="NME") { return true; - else if(residuename=="NH2") + } + 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") + else if(residuename=="NLE") { return true; - else if(residuename=="SFO") + } + else if(residuename=="SFO") { return true; - else + } + else { return false; + } } else if( type=="dna" ) { - if(residuename=="A") + if(residuename=="A") { return true; - else if(residuename=="A5") + } + else if(residuename=="A5") { return true; - else if(residuename=="A3") + } + else if(residuename=="A3") { return true; - else if(residuename=="AN") + } + else if(residuename=="AN") { return true; - else if(residuename=="G") + } + else if(residuename=="G") { return true; - else if(residuename=="G5") + } + else if(residuename=="G5") { return true; - else if(residuename=="G3") + } + else if(residuename=="G3") { return true; - else if(residuename=="GN") + } + else if(residuename=="GN") { return true; - else if(residuename=="T") + } + else if(residuename=="T") { return true; - else if(residuename=="T5") + } + else if(residuename=="T5") { return true; - else if(residuename=="T3") + } + else if(residuename=="T3") { return true; - else if(residuename=="TN") + } + else if(residuename=="TN") { return true; - else if(residuename=="C") + } + else if(residuename=="C") { return true; - else if(residuename=="C5") + } + else if(residuename=="C5") { return true; - else if(residuename=="C3") + } + else if(residuename=="C3") { return true; - else if(residuename=="CN") + } + else if(residuename=="CN") { return true; - else if(residuename=="DA") + } + else if(residuename=="DA") { return true; - else if(residuename=="DA5") + } + else if(residuename=="DA5") { return true; - else if(residuename=="DA3") + } + else if(residuename=="DA3") { return true; - else if(residuename=="DAN") + } + else if(residuename=="DAN") { return true; - else if(residuename=="DG") + } + else if(residuename=="DG") { return true; - else if(residuename=="DG5") + } + else if(residuename=="DG5") { return true; - else if(residuename=="DG3") + } + else if(residuename=="DG3") { return true; - else if(residuename=="DGN") + } + else if(residuename=="DGN") { return true; - else if(residuename=="DT") + } + else if(residuename=="DT") { return true; - else if(residuename=="DT5") + } + else if(residuename=="DT5") { return true; - else if(residuename=="DT3") + } + else if(residuename=="DT3") { return true; - else if(residuename=="DTN") + } + else if(residuename=="DTN") { return true; - else if(residuename=="DC") + } + else if(residuename=="DC") { return true; - else if(residuename=="DC5") + } + else if(residuename=="DC5") { return true; - else if(residuename=="DC3") + } + else if(residuename=="DC3") { return true; - else if(residuename=="DCN") + } + else if(residuename=="DCN") { return true; - else + } + else { return false; + } } else if( type=="rna" ) { - if(residuename=="A") + if(residuename=="A") { return true; - else if(residuename=="A5") + } + else if(residuename=="A5") { return true; - else if(residuename=="A3") + } + else if(residuename=="A3") { return true; - else if(residuename=="AN") + } + else if(residuename=="AN") { return true; - else if(residuename=="G") + } + else if(residuename=="G") { return true; - else if(residuename=="G5") + } + else if(residuename=="G5") { return true; - else if(residuename=="G3") + } + else if(residuename=="G3") { return true; - else if(residuename=="GN") + } + else if(residuename=="GN") { return true; - else if(residuename=="U") + } + else if(residuename=="U") { return true; - else if(residuename=="U5") + } + else if(residuename=="U5") { return true; - else if(residuename=="U3") + } + else if(residuename=="U3") { return true; - else if(residuename=="UN") + } + else if(residuename=="UN") { return true; - else if(residuename=="C") + } + else if(residuename=="C") { return true; - else if(residuename=="C5") + } + else if(residuename=="C5") { return true; - else if(residuename=="C3") + } + else if(residuename=="C3") { return true; - else if(residuename=="CN") + } + else if(residuename=="CN") { return true; - else if(residuename=="RA") + } + else if(residuename=="RA") { return true; - else if(residuename=="RA5") + } + else if(residuename=="RA5") { return true; - else if(residuename=="RA3") + } + else if(residuename=="RA3") { return true; - else if(residuename=="RAN") + } + else if(residuename=="RAN") { return true; - else if(residuename=="RG") + } + else if(residuename=="RG") { return true; - else if(residuename=="RG5") + } + else if(residuename=="RG5") { return true; - else if(residuename=="RG3") + } + else if(residuename=="RG3") { return true; - else if(residuename=="RGN") + } + else if(residuename=="RGN") { return true; - else if(residuename=="RU") + } + else if(residuename=="RU") { return true; - else if(residuename=="RU5") + } + else if(residuename=="RU5") { return true; - else if(residuename=="RU3") + } + else if(residuename=="RU3") { return true; - else if(residuename=="RUN") + } + else if(residuename=="RUN") { return true; - else if(residuename=="RC") + } + else if(residuename=="RC") { return true; - else if(residuename=="RC5") + } + else if(residuename=="RC5") { return true; - else if(residuename=="RC3") + } + else if(residuename=="RC3") { return true; - else if(residuename=="RCN") + } + else if(residuename=="RCN") { return true; - else + } + else { return false; + } } else if( type=="water" ) { - if(residuename=="SOL") + if(residuename=="SOL") { return true; - if(residuename=="WAT") + } + if(residuename=="WAT") { return true; + } return false; } else if( type=="ion" ) { - if(residuename=="IB+") + if(residuename=="IB+") { return true; - if(residuename=="CA") + } + if(residuename=="CA") { return true; - if(residuename=="CL") + } + if(residuename=="CL") { return true; - if(residuename=="NA") + } + if(residuename=="NA") { return true; - if(residuename=="MG") + } + if(residuename=="MG") { return true; - if(residuename=="K") + } + if(residuename=="K") { return true; - if(residuename=="RB") + } + if(residuename=="RB") { return true; - if(residuename=="CS") + } + if(residuename=="CS") { return true; - if(residuename=="LI") + } + if(residuename=="LI") { return true; - if(residuename=="ZN") + } + if(residuename=="ZN") { return true; + } return false; } return false; diff --git a/src/tools/Pbc.cpp b/src/tools/Pbc.cpp index 3ae986df92..ac184f15ed 100644 --- a/src/tools/Pbc.cpp +++ b/src/tools/Pbc.cpp @@ -61,14 +61,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) + 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) + 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. @@ -77,8 +79,9 @@ 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) shifts[2][2][2])const { // skip cases where shift would bring too far from origin bool skip=false; for(int s=0; s<3; s++) { - if(ishift[s]*block[s]>0) + if(ishift[s]*block[s]>0) { skip=true; + } } - if(skip) + 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) + if(((1-ishift[s]*ishift[s])*block[s])*cosdir[s]<-small) { skip=false; + } } - if(skip) + 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)); @@ -116,11 +123,13 @@ void Pbc::buildShifts(std::vector shifts[2][2][2])const { } void Pbc::fullSearch(Vector&d)const { - if(type==unset) + if(type==unset) { return; + } Vector s=matmul(invReduced.transpose(),d); - for(int i=0; i<3; 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)); @@ -150,25 +159,31 @@ void Pbc::setBox(const Tensor&b) { type=unset; double det=box.determinant(); - if(det*det& dlist, unsigned max_index) const { - if (max_index==0) + 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]) + while(dlist[k][0]>hdiag[0]) { dlist[k][0]-=diag[0]; - while(dlist[k][0]<=mdiag[0]) + } + while(dlist[k][0]<=mdiag[0]) { dlist[k][0]+=diag[0]; - while(dlist[k][1]>hdiag[1]) + } + while(dlist[k][1]>hdiag[1]) { dlist[k][1]-=diag[1]; - while(dlist[k][1]<=mdiag[1]) + } + while(dlist[k][1]<=mdiag[1]) { dlist[k][1]+=diag[1]; - while(dlist[k][2]>hdiag[2]) + } + while(dlist[k][2]>hdiag[2]) { dlist[k][2]-=diag[2]; - while(dlist[k][2]<=mdiag[2]) + } + while(dlist[k][2]<=mdiag[2]) { dlist[k][2]+=diag[2]; + } } #else for(unsigned k=0; k& dlist, unsigned max_index) const { } #endif } else if(type==generic) { - for(unsigned k=0; khdiag[i]) + while(d[i]>hdiag[i]) { d[i]-=diag[i]; - while(d[i]<=mdiag[i]) + } + while(d[i]<=mdiag[i]) { d[i]+=diag[i]; + } } #else - for(int i=0; i<3; 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); @@ -255,8 +282,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++) + 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)) { @@ -265,8 +293,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) + if(nshifts) { *nshifts+=myshifts.size(); + } for(unsigned i=0; i & 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]; + } #pragma omp simd - for(unsigned i=0; ireference[i]-=reference_center; + } reference_center_is_calculated=true; reference_center_is_removed=true; } @@ -125,18 +128,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]; + } if(w>epsilon) { double inv=1.0/w; #pragma omp simd - for(unsigned i=0; ialign[i]*=inv; + } } else { double inv=1.0/n; #pragma omp simd - for(unsigned i=0; ialign[i]=inv; + } } } // recalculate the center anyway @@ -168,18 +174,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]; + } if(w>epsilon) { double inv=1.0/w; #pragma omp simd - for(unsigned i=0; idisplace[i]*=inv; + } } else { double inv=1.0/n; #pragma omp simd - for(unsigned i=0; idisplace[i]=inv; + } } } } @@ -202,19 +211,23 @@ double RMSD::calculate(const std::vector & positions,std::vector } case OPTIMAL_FAST : { // this is calling the fastest option: - if(align==displace) + if(align==displace) { ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); - else + } + else { ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); + } break; } case OPTIMAL : { // this is the fast routine but in the "safe" mode, which gives less numerical error: - if(align==displace) + if(align==displace) { ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); - else + } + else { ret=optimalAlignment(align,displace,positions,reference,derivatives,squared); + } break; } } @@ -232,16 +245,20 @@ double RMSD::calc_DDistDRef( const std::vector& positions, std::vector(align,displace,positions,reference,derivatives,DDistDRef, squared); - else + } + else { ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef,squared); + } break; case OPTIMAL: - if(align==displace) + if(align==displace) { ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef,squared); - else + } + else { ret=optimalAlignment_DDistDRef(align,displace,positions,reference,derivatives,DDistDRef,squared); + } break; } return ret; @@ -257,16 +274,20 @@ double RMSD::calc_SOMA( const std::vector& positions, std::vector(align,displace,positions,reference,derivatives,DDistDRef, squared); - else + } + else { ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef,squared); + } break; case OPTIMAL: - if(align==displace) + if(align==displace) { ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef,squared); - else + } + else { ret=optimalAlignment_SOMA(align,displace,positions,reference,derivatives,DDistDRef,squared); + } break; } return ret; @@ -280,16 +301,20 @@ 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) + if(align==displace) { ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); - else + } + else { ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); + } break; case OPTIMAL: - if(align==displace) + if(align==displace) { ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); - else + } + else { ret=optimalAlignment_DDistDRef_Rot_DRotDPos(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, squared); + } break; } return ret; @@ -302,16 +327,20 @@ 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) + if(align==displace) { ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); - else + } + else { ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); + } break; case OPTIMAL: - if(align==displace) + if(align==displace) { ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); - else + } + else { ret=optimalAlignment_DDistDRef_Rot_DRotDPos_DRotDRef(align,displace,positions,reference,derivatives,DDistDRef, Rot, DRotDPos, DRotDRef, squared); + } break; } return ret; @@ -324,16 +353,20 @@ 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) + if(align==displace) { ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); - else + } + else { ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); + } break; case OPTIMAL: - if(align==displace) + if(align==displace) { ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); - else + } + else { ret=optimalAlignment_Rot_DRotDRr01(align,displace,positions,reference, Rotation, DRotDRr01, squared); + } break; } return ret; @@ -346,16 +379,20 @@ 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) + if(align==displace) { ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); - else + } + else { ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); + } break; case OPTIMAL: - if(align==displace) + if(align==displace) { ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); - else + } + else { ret=optimalAlignment_Rot(align,displace,positions,reference,derivatives, Rotation, squared); + } break; } return ret; @@ -368,16 +405,20 @@ 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) + if(align==displace) { ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); - else + } + else { ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); + } break; case OPTIMAL: - if(align==displace) + if(align==displace) { ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); - else + } + else { ret=optimalAlignmentWithCloseStructure(align,displace,positions,reference,derivatives, rotationPosClose, rotationRefClose, drotationPosCloseDrr01, squared); + } break; } return ret; @@ -390,16 +431,20 @@ 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) + if(align==displace) { ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); - else + } + else { ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); + } break; case OPTIMAL: - if(align==displace) + if(align==displace) { ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); - else + } + else { ret=optimalAlignment_PCA(align,displace,positions,reference, alignedpositions, centeredpositions,centeredreference,Rotation,DDistDPos,DRotDPos,squared); + } break; } return ret; @@ -413,16 +458,20 @@ 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) + if(align==displace) { ret=optimalAlignment_Fit(align,displace,positions,reference, Rotation,DRotDPos,centeredpositions,center_positions,squared); - else + } + else { ret=optimalAlignment_Fit(align,displace,positions,reference, Rotation,DRotDPos,centeredpositions,center_positions,squared); + } break; case OPTIMAL: - if(align==displace) + if(align==displace) { ret=optimalAlignment_Fit(align,displace,positions,reference,Rotation,DRotDPos,centeredpositions,center_positions,squared); - else + } + else { ret=optimalAlignment_Fit(align,displace,positions,reference,Rotation,DRotDPos,centeredpositions,center_positions,squared); + } break; } return ret; @@ -568,8 +617,9 @@ double RMSD::optimalAlignment(const std::vector & align, for(unsigned k=0; k<4; k++) { double tmp=0.0; // perturbation theory for matrix m - for(unsigned l=1; l<4; l++) + 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; } } @@ -622,12 +672,14 @@ double RMSD::optimalAlignment(const std::vector & align, double prefactor=2.0; - if(!squared && alEqDis) + if(!squared && alEqDis) { prefactor*=0.5/std::sqrt(dist); + } // if "safe", recompute dist here to a better accuracy - if(safe || !alEqDis) + 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 @@ -643,8 +695,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) + if(safe) { dist+=align[iat]*modulo2(d); + } } else { // the case for align != displace is different, sob: dist+=displace[iat]*modulo2(d); @@ -675,8 +728,9 @@ double RMSD::optimalAlignment(const std::vector & align, dist=std::sqrt(dist); if(!alEqDis) { double xx=0.5/dist; - for(unsigned iat=0; iat here_eigenvecs; VectorGeneric<1> here_eigenvals; diagMatSym(m, here_eigenvals, here_eigenvecs ); - for(unsigned i=0; i<4; 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]); } @@ -1238,8 +1296,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) + 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 @@ -1251,13 +1310,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; @@ -1268,20 +1329,24 @@ void RMSDCoreData::doCoreCalc(bool safe,bool alEqDis, bool only_rotation) { /// just retrieve the distance already calculated double RMSDCoreData::getDistance( bool squared) { - if(!isInitialized) + 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) + if(safe || !alEqDis) { localDist=0.0; - else + } + else { localDist=eigenvals[0]+rr00+rr11; + } #pragma omp simd reduction(+:localDist) for(unsigned iat=0; iatalEqDis=alEqDis; this->safe=safe; @@ -1344,13 +1412,16 @@ std::vector RMSDCoreData::getDDistanceDPositions() { Vector ddist_dcpositions; derivatives.resize(n); double prefactor=1.0; - if(!distanceIsMSD) + 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) + if(!hasDistance) { plumed_merror("getDPositionsDerivatives needs to calculate the distance via getDistance first !"); - if(!isInitialized) + } + if(!isInitialized) { plumed_merror("getDPositionsDerivatives needs to initialize the coreData first!"); + } Vector csum; for(unsigned iat=0; iat RMSDCoreData::getDDistanceDReference() { Vector ddist_dcreference; derivatives.resize(n); double prefactor=1.0; - if(!distanceIsMSD) + 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) + if(!hasDistance) { plumed_merror("getDDistanceDReference needs to calculate the distance via getDistance first !"); - if(!isInitialized) + } + 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(); @@ -1434,15 +1508,18 @@ std::vector RMSDCoreData::getDDistanceDReferenceSOMA() { Vector ddist_dcreference; derivatives.resize(n); double prefactor=1.0; - if(!distanceIsMSD) + 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) + if(!hasDistance) { plumed_merror("getDDistanceDReference needs to calculate the distance via getDistance first !"); - if(!isInitialized) + } + if(!isInitialized) { plumed_merror("getDDistanceDReference to initialize the coreData first!"); + } // get the transpose rotation Tensor t_rotation=rotation.transpose(); @@ -1463,8 +1540,9 @@ 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) + 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) @@ -1490,16 +1569,20 @@ Matrix > RMSDCoreData::getDRotationDPositions( bool inverse // these below could probably be calculated in the main routine Vector cp; cp.zero(); - if(!cpositions_is_removed) + if(!cpositions_is_removed) { cp=cpositions; + } Vector cr; cr.zero(); - if(!creference_is_removed) + 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) + 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) @@ -1537,16 +1621,20 @@ Matrix > RMSDCoreData::getDRotationDReference( bool inverse // these below could probably be calculated in the main routine Vector cp; cp.zero(); - if(!cpositions_is_removed) + if(!cpositions_is_removed) { cp=cpositions; + } Vector cr; cr.zero(); - if(!creference_is_removed) + 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) + 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) + if(!cpositions_is_removed) { cp=cpositions; - for(unsigned iat=0; iat RMSDCoreData::getAlignedPositionsToReference() { std::vector alignedpos; - if(!isInitialized) + 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) + 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) + 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) + 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) + if(!creference_is_removed) { cr=creference; - for(unsigned iat=0; iat,3> & RMSDCoreData::getDRotationDRr01() const { - if(!isInitialized) + 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 29114db98b..58b1f631ca 100644 --- a/src/tools/RMSD.h +++ b/src/tools/RMSD.h @@ -86,16 +86,18 @@ class RMSD 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) { diff --git a/src/tools/Random.cpp b/src/tools/Random.cpp index b8f48f293c..e87db895ec 100644 --- a/src/tools/Random.cpp +++ b/src/tools/Random.cpp @@ -46,24 +46,28 @@ Random::Random(const std::string & name): name(&name!=&noname?name:"noname") { iy=0; - for(unsigned i=0; i0) + if(idum_>0) { idum_=-idum_; + } idum=idum_; incPrec=false; } double Random::RandU01 () { - if (incPrec) + if (incPrec) { return U01d(); - else + } + else { return U01(); + } } @@ -79,31 +83,38 @@ double Random::U01() { int j,k; double temp; if (idum <= 0 || !iy) { - if (-idum < 1) + if (-idum < 1) { idum=1; - else + } + else { idum = -idum; + } for (j=NTAB+7; j>=0; j--) { k=idum/IQ; idum=IA*(idum-k*IQ)-IR*k; - if (idum < 0) + if (idum < 0) { idum += IM; - if (j < NTAB) + } + if (j < NTAB) { iv[j] = idum; + } } iy=iv[0]; } k=idum/IQ; idum=IA*(idum-k*IQ)-IR*k; - if (idum < 0) + if (idum < 0) { idum += IM; + } j=iy/NDIV; iy=iv[j]; iv[j] = idum; - if ((temp=AM*iy) > RNMX) + if ((temp=AM*iy) > RNMX) { return RNMX; - else + } + else { return temp; + } } void Random::WriteStateFull(std::ostream & out)const { @@ -120,8 +131,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++) + for (int i = 0; i < NTAB; i++) { in>>iv[i]; + } in>>switchGaussian; in>>saveGaussian; } @@ -138,13 +150,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++) + for (int i = 0; i < NTAB; i++) { istr>>iv[i]; + } } // This allows to have the same stream of random numbers @@ -163,8 +177,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) + 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/RootFindingBase.h b/src/tools/RootFindingBase.h index 79dc2439b0..750b05210e 100644 --- a/src/tools/RootFindingBase.h +++ b/src/tools/RootFindingBase.h @@ -54,8 +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 4c59b5258a..d38ab46dca 100644 --- a/src/tools/Stopwatch.cpp +++ b/src/tools/Stopwatch.cpp @@ -42,8 +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) + if(w.second.state==Watch::State::paused) { w.second.start().stop(); + } } *mylog << *this; } @@ -53,13 +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++) + for(unsigned i=0; i<40; i++) { os<<" "; + } os<<" Cycles Total Average Minimum Maximum\n"; std::vector names; - for(const auto & it : watches) + for(const auto & it : watches) { names.push_back(it.first); + } std::sort(names.begin(),names.end()); const double frac=1.0/1000000000.0; @@ -67,8 +70,9 @@ std::ostream& Stopwatch::log(std::ostream&os)const { for(const auto & name : names) { const Watch&t(watches.find(name)->second); os<stop(); - else + } + else { watch->pause(); + } } } @@ -343,10 +345,12 @@ Stopwatch::Handler & Stopwatch::Handler::operator=(Handler && handler) noexcept if(this!=&handler) { if(watch) { try { - if(stop) + if(stop) { watch->stop(); - else + } + 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 @@ -374,10 +378,12 @@ Stopwatch::Watch & Stopwatch::Watch::stop() { state=State::stopped; cycles++; total+=lap; - if(lap>max) + if(lap>max) { max=lap; - if(min>lap || cycles==1) + } + if(min>lap || cycles==1) { min=lap; + } lap=0; return *this; } @@ -392,8 +398,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) + 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 fbdfd3236f..1c559c0777 100644 --- a/src/tools/Subprocess.cpp +++ b/src/tools/Subprocess.cpp @@ -52,15 +52,17 @@ class SubprocessPid { // Signals give problems with MPI on Travis. // I disable them for now. if(SubprocessPidGetenvSignals()) - if(pid!=0 && pid!=-1) + 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) + if(pid!=0 && pid!=-1) { kill(pid,SIGCONT); + } } ~SubprocessPid() { // this is apparently working also with MPI on Travis. @@ -84,10 +86,12 @@ Subprocess::Subprocess(const std::string & cmd) { }; int cp[2]; int pc[2]; - if(pipe(pc)<0) + if(pipe(pc)<0) { plumed_error()<<"error creating parent to child pipe"; - if(pipe(cp)<0) + } + if(pipe(cp)<0) { plumed_error()<<"error creating child to parent pipe"; + } pid_t pid=fork(); switch(pid) { case -1: @@ -96,28 +100,36 @@ Subprocess::Subprocess(const std::string & cmd) { // CHILD: case 0: { - if(close(1)<0) + if(close(1)<0) { plumed_error()<<"error closing file"; - if(dup(cp[1])<0) + } + if(dup(cp[1])<0) { plumed_error()<<"error duplicating file"; - if(close(0)<0) + } + if(close(0)<0) { plumed_error()<<"error closing file"; - if(dup(pc[0])<0) + } + if(dup(pc[0])<0) { plumed_error()<<"error duplicating file"; - if(close(pc[1])<0) + } + if(close(pc[1])<0) { plumed_error()<<"error closing file"; - if(close(cp[0])<0) + } + 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) + if(close(pc[0])<0) { plumed_error()<<"error closing file"; - if(close(cp[1])<0) + } + if(close(cp[1])<0) { plumed_error()<<"error closing file"; + } fpc=pc[1]; fcp=cp[0]; fppc=fdopen(fpc,"w"); @@ -170,8 +182,9 @@ void Subprocess::flush() { Subprocess & Subprocess::getline(std::string & line) { child_to_parent.getline(line); - if(!child_to_parent) + if(!child_to_parent) { plumed_error() <<"error reading subprocess"; + } return (*this); } @@ -182,8 +195,9 @@ Subprocess::Handler::Handler(Subprocess *sp) noexcept: } Subprocess::Handler::~Handler() { - if(sp) + if(sp) { sp->stop(); + } } Subprocess::Handler::Handler(Handler && handler) noexcept : @@ -194,8 +208,9 @@ Subprocess::Handler::Handler(Handler && handler) noexcept : Subprocess::Handler & Subprocess::Handler::operator=(Handler && handler) noexcept { if(this!=&handler) { - if(sp) + if(sp) { sp->stop(); + } sp=handler.sp; handler.sp=nullptr; } diff --git a/src/tools/SwitchingFunction.cpp b/src/tools/SwitchingFunction.cpp index 39c7941e37..f400d3a8d0 100644 --- a/src/tools/SwitchingFunction.cpp +++ b/src/tools/SwitchingFunction.cpp @@ -203,28 +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)) + 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)) + if(present && !Tools::parse(data,"D_MAX",dmax)) { errormsg="could not parse D_MAX"; - if(dmax::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) + 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) + if(!found_r0) { errormsg="R_0 is required"; + } } invr0=1.0/r0; invr0_2=invr0*invr0; @@ -234,22 +239,27 @@ 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)) + if(present && !Tools::parse(data,"NN",nn)) { errormsg="could not parse NN"; + } present=Tools::findKeyword(data,"MM"); - if(present && !Tools::parse(data,"MM",mm)) + if(present && !Tools::parse(data,"MM",mm)) { errormsg="could not parse MM"; - if(mm==0) + } + 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)) + if(present && !Tools::parse(data,"A",a)) { errormsg="could not parse A"; + } present=Tools::findKeyword(data,"B"); - if(present && !Tools::parse(data,"B",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); } @@ -258,26 +268,34 @@ void SwitchingFunction::set(const std::string & definition,std::string& errormsg beta = 50.0; // nm-1 lambda = 1.8; // unitless present=Tools::findKeyword(data,"BETA"); - if(present && !Tools::parse(data, "BETA", 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)) + if(present && !Tools::parse(data, "LAMBDA", lambda)) { errormsg="could not parse LAMBDA"; + } bool found_ref=Tools::parse(data,"REF",ref); // nm - if(!found_ref) + if(!found_ref) { errormsg="REF (reference disatance) is required for native Q"; + } } - else if(name=="EXP") + else if(name=="EXP") { type=exponential; - else if(name=="GAUSSIAN") + } + else if(name=="GAUSSIAN") { type=gaussian; - else if(name=="CUBIC") + } + else if(name=="CUBIC") { type=cubic; - else if(name=="TANH") + } + else if(name=="TANH") { type=tanh; - else if(name=="COSINUS") + } + else if(name=="COSINUS") { type=cosinus; + } else if((name=="MATHEVAL" || name=="CUSTOM")) { type=leptontype; std::string func; @@ -285,8 +303,9 @@ void SwitchingFunction::set(const std::string & definition,std::string& errormsg lepton::ParsedExpression pe=lepton::Parser::parse(func).optimize(lepton::Constants()); lepton_func=func; expression.resize(OpenMP::getNumThreads()); - for(auto & e : expression) + for(auto & e : expression) { e=pe.createCompiledExpression(); + } lepton_ref.resize(expression.size()); for(unsigned t=0; t::max()) { @@ -435,10 +458,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 3de17088ea..cafcf5078e 100644 --- a/src/tools/Tensor.h +++ b/src/tools/Tensor.h @@ -234,8 +234,9 @@ TensorGeneric::TensorGeneric() { template TensorGeneric::TensorGeneric(const VectorGeneric&v1,const VectorGeneric&v2) { for(unsigned i=0; i @@ -299,31 +300,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 std::ostream & operator<<(std::ostream &os, const TensorGeneric& t) { for(unsigned i=0; i&mat,VectorGeneric&evals,TensorGeneri <<"Info: "< bool Tools::convertToAny(const std::string & str,T & t) { std::istringstream istr(str.c_str()); bool ok=static_cast(istr>>t); - if(!ok) + if(!ok) { return false; + } std::string remaining; istr>>remaining; return remaining.length()==0; @@ -76,16 +77,18 @@ bool Tools::convertNoexcept(const std::string & str,AtomNumber &a) { // avoid using lepton conversions. unsigned i; bool r=convertToAny(str,i); - if(r) + 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)) + if(convertToAny(str,t)) { return true; + } // Then use lepton try { double r=lepton::Parser::parse(str).evaluate(lepton::Constants()); @@ -94,25 +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)) + if(r>std::nextafter(std::numeric_limits::max(), 0)) { return false; - if(r::min(), 0)) + } + 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) + 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)) + if(r == static_cast(tmp-1)) { return false; - if(r == static_cast(tmp+1)) + } + if(r == static_cast(tmp+1)) { return false; + } // everything is fine, then store in t t=tmp; @@ -125,8 +133,9 @@ bool Tools::convertToInt(const std::string & str,T & t) { template bool Tools::convertToReal(const std::string & str,T & t) { - if(convertToAny(str,t)) + if(convertToAny(str,t)) { return true; + } if(str=="PI" || str=="+PI" || str=="+pi" || str=="pi") { t=pi; return true; @@ -141,26 +150,30 @@ 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") + 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) + if(!ok) { return false; + } t=ff*pi; 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") + 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) + if(!ok) { return false; + } t=ff*pi; std::string remains; nstr>>remains; @@ -193,27 +206,33 @@ 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) + if(!separators) { separators=" \t\n"; + } const std::string sep(separators); char openpar=parenthesis[0]; char closepar; - if(openpar=='(') + if(openpar=='(') { closepar=')'; - if(openpar=='[') + } + if(openpar=='[') { closepar=']'; - if(openpar=='{') + } + if(openpar=='{') { closepar='}'; + } std::vector words; std::string word; int parenthesisLevel=0; - if(parlevel) + if(parlevel) { parenthesisLevel=*parlevel; + } for(unsigned i=0; i=0,"Extra closed parenthesis in '" + line + "'"); @@ -226,25 +245,30 @@ std::vector Tools::getWords(const std::string & line,const char* se } } // If at parenthesis level zero (outer) - if(!(parenthesisLevel==0 && (found||onParenthesis))) + if(!(parenthesisLevel==0 && (found||onParenthesis))) { word.push_back(line[i]); + } //if(onParenthesis) word.push_back(' '); - if(line[i]==openpar) + if(line[i]==openpar) { parenthesisLevel++; + } if(found && word.length()>0) { - if(!parlevel) + if(!parlevel) { plumed_massert(parenthesisLevel==0,"Unmatching parenthesis in '" + line + "'"); + } words.push_back(word); word.clear(); } } if(word.length()>0) { - if(!parlevel) + if(!parlevel) { plumed_massert(parenthesisLevel==0,"Unmatching parenthesis in '" + line + "'"); + } words.push_back(word); } - if(parlevel) + if(parlevel) { *parlevel=parenthesisLevel; + } return words; } @@ -256,21 +280,25 @@ bool Tools::getParsedLine(IFile& ifile,std::vector & words, bool tr int parlevel=0; bool mergenext=false; while((stat=ifile.getline(line))) { - if(trimcomments) + if(trimcomments) { trimComments(line); + } trim(line); - if(line.length()==0) + 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) + 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) + if(!trimcomments) { words.push_back("..."); + } } else if(*(w.end()-1)=="...") { inside=true; w.erase(w.end()-1); @@ -280,20 +308,25 @@ 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) + if(!inside) { break; - if(!trimcomments && parlevel==0) + } + if(!trimcomments && parlevel==0) { words.push_back("@newline"); - else if(!trimcomments) + } + else if(!trimcomments) { words[words.size()-1] += " @newline"; + } } plumed_massert(parlevel==0,"non matching parenthesis"); - if(words.size()>0) + if(words.size()>0) { return true; + } return stat; } @@ -303,34 +336,40 @@ 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') + if(buffer[ss-1]=='\n') { break; + } }; if(line.length()>0) - if(*(line.end()-1)=='\n') + if(*(line.end()-1)=='\n') { line.erase(line.end()-1); + } if(line.length()>0) - if(*(line.end()-1)=='\r') + 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) + 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) + if(n!=std::string::npos) { s.resize(n); + } } bool Tools::caseInSensStringCompare(const std::string & str1, const std::string &str2) @@ -343,12 +382,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) + if((*p).length()==0) { continue; + } std::string x=(*p).substr(0,key.length()); if(caseInSensStringCompare(x,key)) { - if((*p).length()==key.length()) + if((*p).length()==key.length()) { return false; + } std::string tmp=(*p).substr(key.length(),(*p).length()); line.erase(p); s=tmp; @@ -370,21 +411,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) + if(dash==std::string::npos) { continue; + } int first; - if(!Tools::convertToAny(p.substr(0,dash),first)) + 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)) + !Tools::convertToAny(p.substr(dash+1).substr(colon+1),stride)) { continue; + } } else { - if(!Tools::convertToAny(p.substr(dash+1),second)) + if(!Tools::convertToAny(p.substr(dash+1),second)) { continue; + } } news.resize(news.size()-1); if(first<=second) { @@ -407,12 +452,14 @@ void Tools::interpretRanges(std::vector&s) { } void Tools::interpretLabel(std::vector&s) { - if(s.size()<2) + if(s.size()<2) { return; + } std::string s0=s[0]; unsigned l=s0.length(); - if(l<1) + if(l<1) { return; + } if(s0[l-1]==':') { s[0]=s[1]; s[1]="LABEL="+s0.substr(0,l-1); @@ -434,10 +481,12 @@ std::vector Tools::ls(const std::string&d) { #else res=readdir(dir); #endif - if(!res) + if(!res) { break; - if(std::string(res->d_name)!="." && std::string(res->d_name)!="..") + } + if(std::string(res->d_name)!="." && std::string(res->d_name)!="..") { result.push_back(res->d_name); + } } closedir (dir); } @@ -447,8 +496,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) + if( first<=last && first!=std::string::npos) { str=str.substr(first,last+1); + } } std::string Tools::extension(const std::string&s) { @@ -456,13 +506,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) + if(ext.find("/")!=std::string::npos) { ext=""; + } std::string base=s.substr(0,n); - if(base.length()==0) + if(base.length()==0) { ext=""; - if(base.length()>0 && base[base.length()-1]=='/') + } + if(base.length()>0 && base[base.length()-1]=='/') { ext=""; + } } return ext; } @@ -484,17 +537,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)) + if(startWith(p,search)) { return true; + } } return false; } Tools::DirectoryChanger::DirectoryChanger(const char*path) { - if(!path) + if(!path) { return; - if(std::strlen(path)==0) + } + 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"; @@ -511,13 +567,15 @@ Tools::DirectoryChanger::DirectoryChanger(const char*path) { Tools::DirectoryChanger::~DirectoryChanger() { #ifdef __PLUMED_HAS_CHDIR - if(std::strlen(cwd)==0) + 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) + if(ret!=0) { std::fprintf(stderr,"+++ WARNING: cannot cd back to directory %s\n",cwd); + } #endif } @@ -533,8 +591,9 @@ class process_one_exception { std::string & msg; bool first=true; void update() { - if(!first) + if(!first) { msg+="\n\nThe above exception was the direct cause of the following exception:\n"; + } first=false; } public: @@ -569,8 +628,9 @@ static void process_all_exceptions(T&& f) { process_all_exceptions(f); } auto d=dynamic_cast(&e); - if(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 b8186bb363..3e6ce7c77d 100644 --- a/src/tools/Tools.h +++ b/src/tools/Tools.h @@ -240,23 +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) + 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) + if(s==0) { return; + } set_to_zero(&vec[0](0,0),s*n*m); } @@ -296,34 +299,40 @@ class Tools { { std::size_t maxsize=0; for(unsigned i=0; isize()>maxsize) + if(vecs[i]->size()>maxsize) { maxsize=vecs[i]->size(); - if(!vecs[i]->empty()) + } + 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()) + if(queue.empty()) { return; + } auto tmp=queue.top(); queue.pop(); result.push_back(*tmp.fwdIt); tmp.fwdIt++; - if(tmp) + if(tmp) { queue.push(tmp); + } // main loop while(!queue.empty()) { auto tmp=queue.top(); queue.pop(); - if(result.back() < *tmp.fwdIt) + if(result.back() < *tmp.fwdIt) { result.push_back(*tmp.fwdIt); + } tmp.fwdIt++; - if(tmp) + if(tmp) { queue.push(tmp); + } } } else { @@ -333,10 +342,12 @@ class Tools { { std::size_t maxsize=0; for(int i=0; isize()>maxsize) + if(vecs[i]->size()>maxsize) { maxsize=vecs[i]->size(); - if(!vecs[i]->empty()) + } + if(!vecs[i]->empty()) { entries.push_back(Entry(*vecs[i])); + } } // this is just to save multiple reallocations on push_back result.reserve(maxsize); @@ -375,18 +386,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)) + if(!getKey(line,key+"=",s,rep)) { return false; - if(s.length()>0 && !convertNoexcept(s,val)) + } + 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)) + 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)) + if(!convertNoexcept(s,v)) { return false; + } val.push_back(v); } return true; @@ -429,23 +444,28 @@ 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) + while (x>0.5) { x-=1.0; - while (x<-0.5) + } + 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) + if(y>=0) { return y-int(y+0.5); - else + } + else { return y-int(y-0.5); + } } else if(std::numeric_limits::round_style == std::round_to_nearest) { return x-int(x); - } else + } else { return x-floor(x+0.5); + } #endif } @@ -467,8 +487,9 @@ double Tools::fastpow(double base, int exp) double result = 1.0; while (exp) { - if (exp & 1) + if (exp & 1) { result *= base; + } exp >>= 1; base *= base; } @@ -479,16 +500,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()) + 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) @@ -55,8 +57,9 @@ std::vector Tree::getTree(std::vector atoms) std::vector addtotree, addtoroot; std::vector newatoms; newatoms.reserve(atoms.size()); - if(!moldat_->checkForAtom(atoms[0])) + 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); @@ -92,16 +96,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]) + 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) + if(iroot>=0) { root_.push_back(atoms[iroot]); + } } // now re-add atoms not present in the PDB diff --git a/src/tools/TypesafePtr.cpp b/src/tools/TypesafePtr.cpp index 9ca88096cd..2ec705fcf1 100644 --- a/src/tools/TypesafePtr.cpp +++ b/src/tools/TypesafePtr.cpp @@ -33,11 +33,13 @@ TypesafePtr TypesafePtr::fromSafePtr(void* safe) { TypesafePtr TypesafePtr::copy() const { auto passbyvalue=((flags>>25)&0x7)==1; - if(passbyvalue) + if(passbyvalue) { throw ExceptionTypeError()<<"PLUMED is trying to copy the pointer of an object passed by value"; + } auto forbidstore=flags&0x10000000; - if(forbidstore) + 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 b329fd2493..a9f77124ae 100644 --- a/src/tools/TypesafePtr.h +++ b/src/tools/TypesafePtr.h @@ -73,14 +73,16 @@ class TypesafePtr { unsigned i=0; for(i=0; ishape.size(); i++) { this->shape[i]=*shape; - if(*shape==0) + if(*shape==0) { break; + } nelem_*=*shape; shape++; } plumed_assert(ishape.size()); // check that last element is actually zero - if(nelem==0) + if(nelem==0) { nelem=nelem_; + } plumed_assert(nelem==nelem_) << "Inconsistent shape/nelem"; } } @@ -216,18 +218,24 @@ class TypesafePtr { std::string type_str() const { auto type=(flags>>16)&0xff; - if(type==0) + if(type==0) { return "wildcard"; - if(type==1) + } + if(type==1) { return "void"; - if(type==2) + } + if(type==2) { return "integral"; - if(type==3) + } + if(type==3) { return "integral"; - if(type==4) + } + if(type==4) { return "floating point"; - if(type==5) + } + if(type==5) { return "FILE"; + } return "unknown"; } @@ -236,11 +244,13 @@ class TypesafePtr { template T* get_priv(std::size_t nelem, const std::size_t* shape, bool byvalue) const { - if(typesafePtrSkipCheck()) + 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 @@ -290,21 +300,26 @@ class TypesafePtr { } } else { if(!std::is_const::value) { - if(cons==1) + if(cons==1) { throw ExceptionTypeError() << "This command expects a pointer-to-pointer. It received a value intead"<::value) { - if(cons!=4) + if(cons!=4) { throw ExceptionTypeError() << "This command expects a modifiable pointer-to-pointer (T**)"<::value) { - if(cons!=4 && cons!=5) + 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) + if(shape[i]==0) { break; + } nelem*=shape[i]; } } diff --git a/src/tools/Vector.h b/src/tools/Vector.h index 48b85cebfd..a2b301f6b9 100644 --- a/src/tools/Vector.h +++ b/src/tools/Vector.h @@ -308,8 +308,9 @@ double modulo(const VectorGeneric&v) { template std::ostream & operator<<(std::ostream &os, const VectorGeneric& v) { - for(unsigned i=0; inested) + 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); @@ -945,8 +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) + if(!error->nested) { return; + } /* Accumulate the total length of the concatenated message */ len_join=__PLUMED_WRAPPER_STD strlen(join); @@ -976,8 +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) + if(error->what_buffer) { plumed_free(error->what_buffer); + } error->what_buffer=new_buffer; /* Finalize the chain of nested exceptions */ @@ -993,8 +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) + 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(); } @@ -1752,49 +1757,65 @@ class Plumed { finalize_plumed_error finalize(h); /* grab the message */ const char* msg=plumed_error_what(h); - if(h.code==1) + if(h.code==1) { f(Plumed::Invalid(msg)); + } /* logic errors */ if(h.code>=10100 && h.code<10200) { - if(h.code>=10105 && h.code<10110) + if(h.code>=10105 && h.code<10110) { f(::std::invalid_argument(msg)); - if(h.code>=10110 && h.code<10115) + } + if(h.code>=10110 && h.code<10115) { f(::std::domain_error(msg)); - if(h.code>=10115 && h.code<10120) + } + if(h.code>=10115 && h.code<10120) { f(::std::length_error(msg)); - if(h.code>=10120 && h.code<10125) + } + 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) + if(h.code>=10205 && h.code<10210) { f(::std::range_error(msg)); - if(h.code>=10210 && h.code<10215) + } + if(h.code>=10210 && h.code<10215) { f(::std::overflow_error(msg)); - if(h.code>=10215 && h.code<10220) + } + if(h.code>=10215 && h.code<10220) { f(::std::underflow_error(msg)); + } #if __cplusplus > 199711L && __PLUMED_WRAPPER_LIBCXX11 - if(h.code==10220) + if(h.code==10220) { f(::std::system_error(h.error_code,::std::generic_category(),msg)); - if(h.code==10221) + } + if(h.code==10221) { f(::std::system_error(h.error_code,::std::system_category(),msg)); - if(h.code==10222) + } + if(h.code==10222) { f(::std::system_error(h.error_code,::std::iostream_category(),msg)); - if(h.code==10223) + } + 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) + if(h.code==10230) { f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::generic_category()))); - if(h.code==10231) + } + if(h.code==10231) { f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::system_category()))); - if(h.code==10232) + } + if(h.code==10232) { f(::std::ios_base::failure(msg,::std::error_code(h.error_code,::std::iostream_category()))); - if(h.code==10233) + } + 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)); } @@ -1802,39 +1823,49 @@ class Plumed { } /* "bad" errors */ /* "< ::" space required in C++ < 11 */ - if(h.code>=11000 && h.code<11100) + if(h.code>=11000 && h.code<11100) { f(add_buffer_to< ::std::bad_typeid>(msg)); - if(h.code>=11100 && h.code<11200) + } + 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) + if(h.code>=11200 && h.code<11300) { f(add_buffer_to< ::std::bad_weak_ptr>(msg)); - if(h.code>=11300 && h.code<11400) + } + 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) + 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) + if(h.code>=11500 && h.code<11600) { f(add_buffer_to< ::std::bad_exception>(msg)); + } /* lepton error */ - if(h.code>=19900 && h.code<20000) + 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) + if(h.code>=20100 && h.code<20200) { f(Plumed::ExceptionDebug(msg)); + } /* error - runtime check */ - if(h.code>=20200 && h.code<20300) + if(h.code>=20200 && h.code<20300) { f(Plumed::ExceptionError(msg)); + } /* error - type error */ - if(h.code>=20300 && h.code<20400) + if(h.code>=20300 && h.code<20400) { f(Plumed::ExceptionTypeError(msg)); + } f(Plumed::Exception(msg)); } /* fallback for any other exception */ @@ -1889,8 +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()); } @@ -1899,8 +1931,9 @@ class Plumed { /* When using C++<11 exceptions, we merge the message and then throw the resulting exception */ - if(h.nested) + if(h.nested) { plumed_error_merge_with_nested(&h); + } exception_dispatch(h,rethrow_not_nested()); #endif } @@ -2133,16 +2166,18 @@ class Plumed { 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) + 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) + if(this==&other) { return *this; + } msg[0]='\0'; __PLUMED_WRAPPER_STD memcpy(msg,other.msg,__PLUMED_WRAPPER_CXX_EXCEPTION_BUFFER); return *this; @@ -2188,10 +2223,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) + if(nelem>0) { this->safe.nelem=nelem; - if(shape) + } + if(shape) { this->safe.shape=const_cast<__PLUMED_WRAPPER_STD size_t*>(shape); + } } #if __cplusplus > 199711L @@ -2499,8 +2536,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) + if(main.p) { plumed_finalize(main); + } main=plumed_create_reference(p.main); } return *this; @@ -2527,8 +2565,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) + if(main.p) { plumed_finalize(main); + } main=p.main; p.main.p=nullptr; } @@ -2742,8 +2781,9 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : rethrow(); } /* plumed_error_rethrow is finalizing */ - if(!error && error_cxx.code!=0) + if(!error && error_cxx.code!=0) { plumed_error_rethrow_cxx(error_cxx); + } } public: @@ -2802,8 +2842,9 @@ Plumed(Plumed&&p)__PLUMED_WRAPPER_CXX_NOEXCEPT : */ template void cmd(const char*key,T* val, std::initializer_list shape) { - if(shape.size()>4) + if(shape.size()>4) { throw Plumed::ExceptionTypeError("Maximum shape size is 4"); + } std::array shape_; unsigned j=0; for(auto i : shape) { @@ -2845,8 +2886,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) + if(main.p) { plumed_finalize(main); + } } /** @@ -3361,8 +3403,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)) + 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"); @@ -3376,8 +3419,9 @@ void* plumed_attempt_dlopen(const char*path,int mode) { __PLUMED_WRAPPER_STD fclose(fp); dlerror(); p=dlopen(pathcopy,mode); - if(!p) + if(!p) { __PLUMED_FPRINTF(stderr,"+++ An error occurred. Message from dlopen(): %s +++\n",dlerror()); + } } plumed_free(pathcopy); } @@ -3425,8 +3469,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) + 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); @@ -3449,23 +3494,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) + if(debug) { __PLUMED_FPRINTF(stderr,"+++ PLUMED was loaded correctly +++\n"); + } *f=functions; - if(table) + if(table) { *table=table_ptr; + } } else { - if(!functions.create) + if(!functions.create) { __PLUMED_FPRINTF(stderr,"+++ Pointer to (plumed_)plumedmain_create not found +++\n"); - if(!functions.cmd) + } + if(!functions.cmd) { __PLUMED_FPRINTF(stderr,"+++ Pointer to (plumed_)plumedmain_cmd not found +++\n"); - if(!functions.finalize) + } + 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) + if(table) { *table=__PLUMED_WRAPPER_CXX_NULLPTR; + } } } __PLUMED_WRAPPER_INTERNALS_END @@ -3532,24 +3583,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) + if(plumed_symbol_table_ptr) { *plumed_symbol_table_ptr=ptr; - if(handle) + } + if(handle) { *handle=__PLUMED_WRAPPER_CXX_NULLPTR; - if(functions) + } + 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) + if(plumed_symbol_table_ptr) { *plumed_symbol_table_ptr=__PLUMED_WRAPPER_CXX_NULLPTR; - if(handle) + } + if(handle) { *handle=__PLUMED_WRAPPER_CXX_NULLPTR; - if(functions) + } + if(functions) { *functions=g; + } #else /* On the other hand, for runtime binding, we use dlsym to find the relevant functions. @@ -3567,10 +3624,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) + if(plumed_symbol_table_ptr) { *plumed_symbol_table_ptr=__PLUMED_WRAPPER_CXX_NULLPTR; - if(handle) + } + if(handle) { *handle=__PLUMED_WRAPPER_CXX_NULLPTR; + } #ifdef __PLUMED_DEFAULT_KERNEL /* This variable allows a default path for the kernel to be hardcoded. @@ -3582,43 +3641,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) )) + 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) + 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) + if(debug) { __PLUMED_FPRINTF(stderr,"|RTLD_LOCAL"); + } } else { dlopenmode=dlopenmode|RTLD_GLOBAL; - if(debug) + 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) + if(debug) { __PLUMED_FPRINTF(stderr,"|RTLD_DEEPBIND"); + } } #endif #endif - if(debug) + if(debug) { __PLUMED_FPRINTF(stderr," +++\n"); + } p=plumed_attempt_dlopen(path,dlopenmode); - if(p) + if(p) { plumed_search_symbols(p,&g,plumed_symbol_table_ptr); + } } - if(handle) + if(handle) { *handle=p; - if(functions) + } + if(functions) { *functions=g; + } #endif } __PLUMED_WRAPPER_INTERNALS_END @@ -3678,10 +3746,12 @@ __PLUMED_WRAPPER_INTERNALS_END __PLUMED_WRAPPER_INTERNALS_BEGIN int plumed_check_pimpl(plumed_implementation*pimpl) { - if(!pimpl) + if(!pimpl) { return 0; - if(__PLUMED_WRAPPER_STD memcmp(pimpl->magic,"pLuMEd",6)) + } + if(__PLUMED_WRAPPER_STD memcmp(pimpl->magic,"pLuMEd",6)) { return 0; + } return 1; } __PLUMED_WRAPPER_INTERNALS_END @@ -3705,8 +3775,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")) + 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) { @@ -3734,8 +3805,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")) + if(!__PLUMED_GETENV("PLUMED_LOAD_NODEEPBIND")) { dlopenmode=dlopenmode|RTLD_DEEPBIND; + } #endif #endif #else @@ -3783,8 +3855,9 @@ plumed plumed_create_dlopen2(const char*path,int mode) { /* handler */ void* dlhandle; dlhandle=__PLUMED_WRAPPER_CXX_NULLPTR; - if(path) + 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); @@ -3852,8 +3925,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) + if(pimpl->used_plumed_kernel) { __PLUMED_FPRINTF(stderr,"+++ Check your PLUMED_KERNEL environment variable. +++\n"); + } __PLUMED_WRAPPER_STD abort(); } assert(pimpl->functions.create); @@ -3887,11 +3961,15 @@ 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) + 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) + } + 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); + } + else { + (*(pimpl->functions.cmd))(pimpl->p,key,safe.ptr); + } } __PLUMED_WRAPPER_C_END @@ -3915,8 +3993,9 @@ 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) + if(pimpl->used_plumed_kernel) { __PLUMED_FPRINTF(stderr,"+++ Check your PLUMED_KERNEL environment variable. +++\n"); + } __PLUMED_WRAPPER_STD abort(); } assert(pimpl->functions.create); @@ -3943,11 +4022,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) + if(pimpl->table->delete_reference(pimpl->p)>0) { return; + } } else { - if(--pimpl->refcount>0) + if(--pimpl->refcount>0) { return; + } } /* to allow finalizing an invalid plumed object, we only call finalize if the object is valid */ @@ -3961,8 +4042,9 @@ void plumed_finalize(plumed p) { #ifdef __PLUMED_HAS_DLOPEN /* dlclose library */ if(pimpl->dlhandle && pimpl->dlclose) { - if(__PLUMED_GETENV("PLUMED_LOAD_DEBUG")) + if(__PLUMED_GETENV("PLUMED_LOAD_DEBUG")) { __PLUMED_FPRINTF(stderr,"+++ Unloading library\n"); + } dlclose(pimpl->dlhandle); } #endif @@ -3980,10 +4062,12 @@ int plumed_valid(plumed p) { /* obtain pimpl */ pimpl=(plumed_implementation*) p.p; assert(plumed_check_pimpl(pimpl)); - if(pimpl->p) + if(pimpl->p) { return 1; - else + } + else { return 0; + } } __PLUMED_WRAPPER_C_END @@ -4018,8 +4102,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) + if(ptr) { fprintf(stderr,"plumed_malloc: %p\n",ptr); + } #endif return ptr; } @@ -4067,10 +4152,12 @@ void plumed_gfinalize(void) { } int plumed_ginitialized(void) { - if(plumed_gmain.p) + if(plumed_gmain.p) { return 1; - else + } + else { return 0; + } } int plumed_gvalid() {