LCOV - code coverage report
Current view: top level - colvar - PathMSDBase.cpp (source / functions) Hit Total Coverage
Test: plumed test coverage Lines: 195 204 95.6 %
Date: 2026-11-12 10:48:31 Functions: 5 8 62.5 %

          Line data    Source code
       1             : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
       2             :    Copyright (c) 2012-2023 The plumed team
       3             :    (see the PEOPLE file at the root of the distribution for a list of names)
       4             : 
       5             :    See http://www.plumed.org for more information.
       6             : 
       7             :    This file is part of plumed, version 2.
       8             : 
       9             :    plumed is free software: you can redistribute it and/or modify
      10             :    it under the terms of the GNU Lesser General Public License as published by
      11             :    the Free Software Foundation, either version 3 of the License, or
      12             :    (at your option) any later version.
      13             : 
      14             :    plumed is distributed in the hope that it will be useful,
      15             :    but WITHOUT ANY WARRANTY; without even the implied warranty of
      16             :    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      17             :    GNU Lesser General Public License for more details.
      18             : 
      19             :    You should have received a copy of the GNU Lesser General Public License
      20             :    along with plumed.  If not, see <http://www.gnu.org/licenses/>.
      21             : +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
      22             : #include "PathMSDBase.h"
      23             : #include "Colvar.h"
      24             : #include "core/ActionRegister.h"
      25             : #include "core/PlumedMain.h"
      26             : #include "tools/Communicator.h"
      27             : #include "tools/PDB.h"
      28             : #include "tools/RMSD.h"
      29             : #include "tools/Tools.h"
      30             : 
      31             : #include <algorithm>
      32             : 
      33             : namespace PLMD {
      34             : namespace colvar {
      35             : 
      36          33 : void PathMSDBase::registerKeywords(Keywords& keys) {
      37          33 :   Colvar::registerKeywords(keys);
      38          66 :   keys.add("compulsory","LAMBDA","the lambda parameter is needed for smoothing, is in the units of plumed");
      39          66 :   keys.add("compulsory","REFERENCE","the pdb is needed to provide the various milestones");
      40          66 :   keys.add("optional","NEIGH_SIZE","size of the neighbor list");
      41          66 :   keys.add("optional","NEIGH_STRIDE","how often the neighbor list needs to be calculated in time units");
      42          66 :   keys.add("optional", "EPSILON", "(default=-1) the maximum distance between the close and the current structure, the positive value turn on the close structure method");
      43          66 :   keys.add("optional", "LOG_CLOSE", "(default=0) value 1 enables logging regarding the close structure");
      44          66 :   keys.add("optional", "DEBUG_CLOSE", "(default=0) value 1 enables extensive debugging info regarding the close structure, the simulation will run much slower");
      45          33 : }
      46             : 
      47          25 : PathMSDBase::PathMSDBase(const ActionOptions&ao):
      48             :   PLUMED_COLVAR_INIT(ao),
      49          25 :   nopbc(false),
      50          25 :   neigh_size(-1),
      51          25 :   neigh_stride(-1),
      52          25 :   epsilonClose(-1),
      53          25 :   debugClose(0),
      54          25 :   logClose(0),
      55          25 :   computeRefClose(false),
      56          25 :   nframes(0) {
      57          25 :   parse("LAMBDA",lambda);
      58          25 :   parse("NEIGH_SIZE",neigh_size);
      59          25 :   parse("NEIGH_STRIDE",neigh_stride);
      60          25 :   parse("REFERENCE",reference);
      61          25 :   parse("EPSILON", epsilonClose);
      62          25 :   parse("LOG_CLOSE", logClose);
      63          25 :   parse("DEBUG_CLOSE", debugClose);
      64          25 :   parseFlag("NOPBC",nopbc);
      65             : 
      66             :   // open the file
      67          25 :   if (FILE* fp=this->fopen(reference.c_str(),"r")) {
      68             : // call fclose when exiting this block
      69          25 :     auto deleter=[this](FILE* f) {
      70          25 :       this->fclose(f);
      71          25 :     };
      72             :     std::unique_ptr<FILE,decltype(deleter)> fp_deleter(fp,deleter);
      73             : 
      74             :     std::vector<AtomNumber> aaa;
      75          25 :     log<<"Opening reference file "<<reference.c_str()<<"\n";
      76             :     bool do_read=true;
      77             :     unsigned nat=0;
      78        1107 :     while (do_read) {
      79        1107 :       PDB mypdb;
      80        1107 :       RMSD mymsd;
      81        1107 :       do_read=mypdb.readFromFilepointer(fp,usingNaturalUnits(),0.1/getUnits().getLength());
      82        1107 :       if(do_read) {
      83        1082 :         nframes++;
      84        1082 :         if(mypdb.getAtomNumbers().size()==0) {
      85           0 :           error("number of atoms in a frame should be more than zero");
      86             :         }
      87        1082 :         if(nat==0) {
      88          25 :           nat=mypdb.getAtomNumbers().size();
      89             :         }
      90        1082 :         if(nat!=mypdb.getAtomNumbers().size()) {
      91           0 :           error("frames should have the same number of atoms");
      92             :         }
      93        1082 :         if(aaa.empty()) {
      94          25 :           aaa=mypdb.getAtomNumbers();
      95          25 :           log.printf("  found %zu atoms in input \n",aaa.size());
      96          25 :           log.printf("  with indices : ");
      97         346 :           for(unsigned i=0; i<aaa.size(); ++i) {
      98         321 :             if(i%25==0) {
      99          25 :               log<<"\n";
     100             :             }
     101         321 :             log.printf("%d ",aaa[i].serial());
     102             :           }
     103          25 :           log.printf("\n");
     104             :         }
     105        1082 :         if(aaa!=mypdb.getAtomNumbers()) {
     106           0 :           error("frames should contain same atoms in same order");
     107             :         }
     108        1082 :         log<<"Found PDB: "<<nframes<<" containing  "<<mypdb.getAtomNumbers().size()<<" atoms\n";
     109        1082 :         pdbv.push_back(mypdb);
     110        1082 :         derivs_s.resize(mypdb.getAtomNumbers().size());
     111        1082 :         derivs_z.resize(mypdb.getAtomNumbers().size());
     112        1082 :         mymsd.set(mypdb,"OPTIMAL");
     113        1082 :         msdv.push_back(mymsd); // the vector that stores the frames
     114             :       } else {
     115             :         break ;
     116             :       }
     117        1107 :     }
     118          25 :     log<<"Found TOTAL "<<nframes<< " PDB in the file "<<reference.c_str()<<" \n";
     119          25 :     if(nframes==0) {
     120           0 :       error("at least one frame expected");
     121             :     }
     122             :     //set up rmsdRefClose, initialize it to the first structure loaded from reference file
     123          25 :     rmsdPosClose.set(pdbv[0], "OPTIMAL");
     124          25 :     firstPosClose = true;
     125          25 :   }
     126          25 :   if(neigh_stride>0 || neigh_size>0) {
     127          14 :     if(neigh_size>int(nframes)) {
     128           0 :       log.printf(" List size required ( %d ) is too large: resizing to the maximum number of frames required: %u  \n",neigh_size,nframes);
     129           0 :       neigh_size=nframes;
     130             :     }
     131          14 :     log.printf("  Neighbor list enabled: \n");
     132          14 :     log.printf("                size   :  %d elements\n",neigh_size);
     133          14 :     log.printf("                stride :  %d timesteps \n",neigh_stride);
     134             :   } else {
     135          11 :     log.printf("  Neighbor list NOT enabled \n");
     136             :   }
     137          25 :   if (epsilonClose > 0) {
     138           2 :     log.printf(" Computing with the close structure, epsilon = %lf\n", epsilonClose);
     139           4 :     log << "  Bibliography " << plumed.cite("Pazurikova J, Krenek A, Spiwok V, Simkova M J. Chem. Phys. 146, 115101 (2017)") << "\n";
     140             :   } else {
     141          23 :     debugClose = 0;
     142          23 :     logClose = 0;
     143             :   }
     144          25 :   if (debugClose) {
     145           2 :     log.printf(" Extensive debug info regarding close structure turned on\n");
     146             :   }
     147             : 
     148          25 :   rotationRefClose.resize(nframes);
     149          25 :   savedIndices = std::vector<unsigned>(nframes);
     150             : 
     151          25 :   if(nopbc) {
     152           1 :     log.printf("  without periodic boundary conditions\n");
     153             :   } else {
     154          24 :     log.printf("  using periodic boundary conditions\n");
     155             :   }
     156             : 
     157          25 : }
     158             : 
     159          25 : PathMSDBase::~PathMSDBase() {
     160          75 : }
     161             : 
     162       11179 : void PathMSDBase::calculate() {
     163             : 
     164       11179 :   if(neigh_size>0 && getExchangeStep()) {
     165           0 :     error("Neighbor lists for this collective variable are not compatible with replica exchange, sorry for that!");
     166             :   }
     167             : 
     168             :   //log.printf("NOW CALCULATE! \n");
     169             : 
     170       11179 :   if(!nopbc) {
     171       11128 :     makeWhole();
     172             :   }
     173             : 
     174             : 
     175             :   // resize the list to full
     176       11179 :   if(imgVec.empty()) { // this is the signal that means: recalculate all
     177        7164 :     imgVec.resize(nframes);
     178             :     // No `omp simd` here: ImagePath::property is a std::vector<double>, so this body performs a
     179             :     // vector copy-assignment, i.e. it allocates. There is nothing for a SIMD unit to do.
     180      308084 :     for(unsigned i=0; i<nframes; i++) {
     181      300920 :       imgVec[i].property=indexvec[i];
     182      300920 :       imgVec[i].index=i;
     183             :     }
     184             :   }
     185             : 
     186             : // THIS IS THE HEAVY PART (RMSD STUFF)
     187       11179 :   unsigned stride=comm.Get_size();
     188       11179 :   unsigned rank=comm.Get_rank();
     189       11179 :   size_t nat=pdbv[0].size();
     190       11179 :   plumed_assert(nat>0);
     191       11179 :   plumed_assert(nframes>0);
     192       11179 :   plumed_assert(imgVec.size()>0);
     193             : 
     194       11179 :   std::vector<Tensor> tmp_rotationRefClose(nframes);
     195             : 
     196       11179 :   if (epsilonClose > 0) {
     197             :     //compute rmsd between positions and close structure, save rotation matrix, drotation_drr01
     198        1092 :     double posclose = rmsdPosClose.calc_Rot_DRotDRr01(getPositions(), rotationPosClose, drotationPosCloseDrr01, true);
     199             :     //if we compute for the first time or the existing close structure is too far from current structure
     200        1092 :     if (firstPosClose || (posclose > epsilonClose)) {
     201             :       //set the current structure as close one for a few next steps
     202          16 :       if (logClose) {
     203          16 :         log << "PLUMED_CLOSE: new close structure, rmsd pos close " << posclose << "\n";
     204             :       }
     205          16 :       rmsdPosClose.clear();
     206          16 :       rmsdPosClose.setReference(getPositions());
     207             :       //as this is a new close structure, we need to save the rotation matrices fitted to the reference structures
     208             :       // and we need to accurately recalculate for all reference structures
     209          16 :       computeRefClose = true;
     210          16 :       imgVec.resize(nframes);
     211         688 :       for(unsigned i=0; i<nframes; i++) {
     212         672 :         imgVec[i].property=indexvec[i];
     213         672 :         imgVec[i].index=i;
     214             :       }
     215          16 :       firstPosClose = false;
     216          16 :     } else {
     217             :       //the current structure is pretty close to the close structure, so we use saved rotation matrices to decrease the complexity of rmsd comuptation
     218        1076 :       if (debugClose) {
     219        1076 :         log << "PLUMED-CLOSE: old close structure, rmsd pos close " << posclose << "\n";
     220             :       }
     221        1076 :       computeRefClose = false;
     222             :     }
     223             :   }
     224             : 
     225       11179 :   std::vector<double> tmp_distances(imgVec.size(),0.0);
     226             :   std::vector<Vector> tmp_derivs;
     227             : // this array is a merge of all tmp_derivs, so as to allow a single comm.Sum below
     228       11179 :   std::vector<Vector> tmp_derivs2(imgVec.size()*nat);
     229             : 
     230             : // if imgVec.size() is less than nframes, it means that only some msd will be calculated
     231       11179 :   if (epsilonClose > 0) {
     232        1092 :     if (computeRefClose) {
     233             :       //recompute rotation matrices accurately
     234         688 :       for(unsigned i=rank; i<imgVec.size(); i+=stride) {
     235         672 :         tmp_distances[i] = msdv[imgVec[i].index].calc_Rot(getPositions(), tmp_derivs, tmp_rotationRefClose[imgVec[i].index], true);
     236         672 :         plumed_assert(tmp_derivs.size()==nat);
     237         672 :         std::copy_n(tmp_derivs.begin(), nat, tmp_derivs2.begin()+i*nat);
     238             :       }
     239             :     } else {
     240             :       //approximate distance with saved rotation matrices
     241       46268 :       for(unsigned i=rank; i<imgVec.size(); i+=stride) {
     242       45192 :         tmp_distances[i] = msdv[imgVec[i].index].calculateWithCloseStructure(getPositions(), tmp_derivs, rotationPosClose, rotationRefClose[imgVec[i].index], drotationPosCloseDrr01, true);
     243       45192 :         plumed_assert(tmp_derivs.size()==nat);
     244       45192 :         std::copy_n(tmp_derivs.begin(), nat, tmp_derivs2.begin()+i*nat);
     245       45192 :         if (debugClose) {
     246       45192 :           double withclose = tmp_distances[i];
     247       45192 :           RMSD opt;
     248       45192 :           opt.setType("OPTIMAL");
     249       45192 :           opt.setReference(msdv[imgVec[i].index].getReference());
     250             :           std::vector<Vector> ders;
     251       45192 :           double withoutclose = opt.calculate(getPositions(), ders, true);
     252       45192 :           float difference = std::abs(withoutclose-withclose);
     253       45192 :           log<<"PLUMED-CLOSE: difference original "<<withoutclose;
     254       45192 :           log<<" - with close "<<withclose<<" = "<<difference<<", step "<<getStep()<<", i "<<i<<" imgVec[i].index "<<imgVec[i].index<<"\n";
     255       45192 :         }
     256             :       }
     257             :     }
     258             :   } else {
     259             :     // store temporary local results
     260      297781 :     for(unsigned i=rank; i<imgVec.size(); i+=stride) {
     261      287694 :       tmp_distances[i]=msdv[imgVec[i].index].calculate(getPositions(),tmp_derivs,true);
     262      287694 :       plumed_assert(tmp_derivs.size()==nat);
     263      287694 :       std::copy_n(tmp_derivs.begin(), nat, tmp_derivs2.begin()+i*nat);
     264             :     }
     265             :   }
     266             : 
     267             : // reduce over all processors
     268       11179 :   comm.Sum(tmp_distances);
     269       11179 :   comm.Sum(tmp_derivs2);
     270       11179 :   if (epsilonClose > 0 && computeRefClose) {
     271          16 :     comm.Sum(tmp_rotationRefClose);
     272         688 :     for (unsigned i=0; i<nframes; i++) {
     273         672 :       rotationRefClose[i] = tmp_rotationRefClose[i];
     274             :     }
     275             :   }
     276             : // assign imgVec[i].distance and imgVec[i].distder
     277      482329 :   for(size_t i=0; i<imgVec.size(); i++) {
     278      471150 :     imgVec[i].distance=tmp_distances[i];
     279      471150 :     imgVec[i].distder.assign(&tmp_derivs2[i*nat],nat+&tmp_derivs2[i*nat]);
     280             :   }
     281             : 
     282             : // END OF THE HEAVY PART
     283             : 
     284             :   std::vector<Value*> val_s_path;
     285       11179 :   if(labels.size()>0) {
     286       18018 :     for(unsigned i=0; i<labels.size(); i++) {
     287       12012 :       val_s_path.push_back(getPntrToComponent(labels[i].c_str()));
     288             :     }
     289             :   } else {
     290        5173 :     val_s_path.push_back(getPntrToComponent("sss"));
     291             :   }
     292       22358 :   Value* val_z_path=getPntrToComponent("zzz");
     293             : 
     294       11179 :   std::vector<double> s_path(val_s_path.size());
     295       28364 :   for(unsigned i=0; i<s_path.size(); i++) {
     296       17185 :     s_path[i]=0.;
     297             :   }
     298             :   double min_distance=1e10;
     299      482329 :   for(auto & it : imgVec) {
     300      471150 :     if(it.distance < min_distance) {
     301             :       min_distance=it.distance;
     302             :     }
     303             :   }
     304             : 
     305             :   double partition=0.;
     306      482329 :   for(auto & it : imgVec) {
     307      471150 :     it.similarity=std::exp(-lambda*(it.distance - min_distance));
     308     1194552 :     for(unsigned i=0; i<s_path.size(); i++) {
     309      723402 :       s_path[i]+=(it.property[i])*it.similarity;
     310             :     }
     311      471150 :     partition+=it.similarity;
     312             :   }
     313       28364 :   for(unsigned i=0; i<s_path.size(); i++) {
     314       17185 :     s_path[i]/=partition;
     315       17185 :     val_s_path[i]->set(s_path[i]) ;
     316             :   }
     317       11179 :   val_z_path->set(-(1./lambda)*std::log(partition) + min_distance);
     318             : 
     319             :   // clean vector
     320       11179 :   Tools::set_to_zero(derivs_z);
     321             :   double tmp;
     322       28364 :   for(unsigned j=0; j<s_path.size(); j++) {
     323             :     // clean up
     324       17185 :     Tools::set_to_zero(derivs_s);
     325             :     // do the derivative
     326      740587 :     for(const auto & it : imgVec) {
     327      723402 :       double expval=it.similarity;
     328      723402 :       tmp=lambda*expval*(s_path[j]-it.property[j])/partition;
     329             :       #pragma omp simd
     330      723402 :       for(unsigned i=0; i< derivs_s.size(); i++) {
     331     9394026 :         derivs_s[i]+=tmp*it.distder[i] ;
     332             :       }
     333      723402 :       if(j==0) {
     334             :         #pragma omp simd
     335      471150 :         for(unsigned i=0; i< derivs_z.size(); i++) {
     336     6114750 :           derivs_z[i]+=it.distder[i]*expval/partition;
     337             :         }
     338             :       }
     339             :     }
     340      240386 :     for(unsigned i=0; i< derivs_s.size(); i++) {
     341      223201 :       setAtomsDerivatives (val_s_path[j],i,derivs_s[i]);
     342      223201 :       if(j==0) {
     343      145123 :         setAtomsDerivatives (val_z_path,i,derivs_z[i]);
     344             :       }
     345             :     }
     346             :   }
     347       28364 :   for(unsigned i=0; i<val_s_path.size(); ++i) {
     348       17185 :     setBoxDerivativesNoPbc(val_s_path[i]);
     349             :   }
     350       11179 :   setBoxDerivativesNoPbc(val_z_path);
     351             :   //
     352             :   //  here set next round neighbors
     353             :   //
     354       11179 :   if (neigh_size>0) {
     355             :     //if( int(getStep())%int(neigh_stride/getTimeStep())==0 ){
     356             :     // enforce consistency: the stride is in time steps
     357        7153 :     if( int(getStep())%int(neigh_stride)==0 ) {
     358             : 
     359             :       // next round do it all:empty the vector
     360        7153 :       imgVec.clear();
     361             :     }
     362             :     // time to analyze the results:
     363        7153 :     if(imgVec.size()==nframes) {
     364             :       //sort by msd
     365           0 :       sort(imgVec.begin(), imgVec.end(), imgOrderByDist());
     366             :       //resize
     367           0 :       imgVec.resize(neigh_size);
     368             :     }
     369             :   }
     370             :   //log.printf("CALCULATION DONE! \n");
     371       11179 : }
     372             : 
     373             : }
     374             : 
     375             : }

Generated by: LCOV version 1.16