LCOV - code coverage report
Current view: top level - core - ActionWithArguments.cpp (source / functions) Hit Total Coverage
Test: plumed test coverage Lines: 150 164 91.5 %
Date: 2020-11-18 11:20:57 Functions: 12 13 92.3 %

          Line data    Source code
       1             : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
       2             :    Copyright (c) 2011-2019 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 "ActionWithArguments.h"
      23             : #include "ActionWithValue.h"
      24             : #include "tools/PDB.h"
      25             : #include "PlumedMain.h"
      26             : #include "ActionSet.h"
      27             : #include <iostream>
      28             : #ifdef __PLUMED_HAS_CREGEX
      29             : #include <cstring>
      30             : #include <regex.h>
      31             : #endif
      32             : 
      33             : using namespace std;
      34             : namespace PLMD {
      35             : 
      36        2011 : void ActionWithArguments::registerKeywords(Keywords& keys) {
      37        8044 :   keys.reserve("numbered","ARG","the input for this action is the scalar output from one or more other actions. The particular scalars that you will use "
      38             :                "are referenced using the label of the action. If the label appears on its own then it is assumed that the Action calculates "
      39             :                "a single scalar value.  The value of this scalar is thus used as the input to this new action.  If * or *.* appears the "
      40             :                "scalars calculated by all the proceding actions in the input file are taken.  Some actions have multi-component outputs and "
      41             :                "each component of the output has a specific label.  For example a \\ref DISTANCE action labelled dist may have three componets "
      42             :                "x, y and z.  To take just the x component you should use dist.x, if you wish to take all three components then use dist.*."
      43             :                "More information on the referencing of Actions can be found in the section of the manual on the PLUMED \\ref Syntax.  "
      44             :                "Scalar values can also be "
      45             :                "referenced using POSIX regular expressions as detailed in the section on \\ref Regex. To use this feature you you must compile "
      46             :                "PLUMED with the appropriate flag.");
      47        2011 : }
      48             : 
      49        1957 : void ActionWithArguments::parseArgumentList(const std::string&key,std::vector<Value*>&arg) {
      50        3914 :   vector<string> c; arg.clear(); parseVector(key,c);
      51        5873 :   if( c.size()==0 && (keywords.style(key,"compulsory") || keywords.style(key,"hidden")) ) {
      52           0 :     std::string def; if( keywords.getDefaultValue(key,def) ) c.push_back( def );
      53             :   }
      54        1957 :   interpretArgumentList(c,arg);
      55        1955 : }
      56             : 
      57           6 : bool ActionWithArguments::parseArgumentList(const std::string&key,int i,std::vector<Value*>&arg) {
      58           6 :   vector<string> c;
      59             :   arg.clear();
      60           6 :   if(parseNumberedVector(key,i,c)) {
      61           6 :     interpretArgumentList(c,arg);
      62             :     return true;
      63             :   } else return false;
      64             : }
      65             : 
      66        2057 : void ActionWithArguments::interpretArgumentList(const std::vector<std::string>& c, std::vector<Value*>&arg) {
      67       16783 :   for(unsigned i=0; i<c.size(); i++) {
      68             :     // is a regex? then just interpret it. The signal is ()
      69        4225 :     if(!c[i].compare(0,1,"(")) {
      70         189 :       unsigned l=c[i].length();
      71         189 :       if(!c[i].compare(l-1,1,")")) {
      72             :         // start regex parsing
      73             : #ifdef __PLUMED_HAS_CREGEX
      74             :         // take the string enclosed in quotes and put in round brackets
      75             :         std::string myregex=c[i];
      76         376 :         log.printf("  Evaluating regexp for this action: %s \n",myregex.c_str());
      77             :         int errcode;
      78         188 :         regex_t *preg = (regex_t*)malloc(sizeof(regex_t)); // pointer to the regular expression
      79             :         regmatch_t *pmatch;
      80         188 :         if ((errcode=regcomp(preg, myregex.c_str(),REG_EXTENDED|REG_NEWLINE))) {  // compile the regular expression
      81             :           char* errbuf;
      82             :           size_t errbuf_size;
      83             :           // one can check the errors asking to regerror
      84           0 :           errbuf_size = regerror(errcode, preg, NULL, 0);
      85           0 :           if (!(errbuf=(char*)malloc(errbuf_size))) {
      86           0 :             plumed_merror("cannot allocate the buffer for error detection in regexp!");
      87             :           };
      88           0 :           regerror(errcode, preg, errbuf, errbuf_size);
      89           0 :           error(errbuf);
      90             :         }
      91         188 :         plumed_massert(preg->re_nsub==1,"I can parse with only one subexpression");
      92         188 :         pmatch = (regmatch_t*)malloc(sizeof(regmatch_t)*preg->re_nsub);
      93             :         // select all the actions that have a value
      94         376 :         std::vector<ActionWithValue*> all=plumed.getActionSet().select<ActionWithValue*>();
      95         188 :         if( all.empty() ) error("your input file is not telling plumed to calculate anything");
      96        2743 :         for(unsigned j=0; j<all.size(); j++) {
      97        1578 :           std::vector<std::string> ss=all[j]->getComponentsVector();
      98      635463 :           for(unsigned  k=0; k<ss.size(); ++k) {
      99      211295 :             unsigned ll=strlen(ss[k].c_str())+1;
     100      211295 :             std::vector<char> str(ll);
     101             :             strcpy(&str[0],ss[k].c_str());
     102             :             const char *ppstr=&str[0];
     103      211295 :             if(!regexec(preg, ppstr, preg->re_nsub, pmatch, 0)) {
     104       53926 :               log.printf("  Something matched with \"%s\" : ",ss[k].c_str());
     105             :               do {
     106       26963 :                 if (pmatch[0].rm_so != -1) {    /* The regex is matching part of a string */
     107             :                   char *submatch;
     108       26963 :                   size_t matchlen = pmatch[0].rm_eo - pmatch[0].rm_so;
     109       26963 :                   submatch = (char*)malloc(matchlen+1);
     110       26963 :                   strncpy(submatch, ppstr+pmatch[0].rm_so, matchlen+1);
     111       26963 :                   submatch[matchlen]='\0';
     112       26963 :                   log.printf("  subpattern %s\n", submatch);
     113             :                   // this is the match: try to see if it is a valid action
     114       26963 :                   std::string putativeVal(submatch);
     115       26963 :                   if( all[j]->exists(putativeVal) ) {
     116       40952 :                     arg.push_back(all[j]->copyOutput(putativeVal));
     117       40952 :                     log.printf("  Action %s added! \n",putativeVal.c_str());
     118             :                   }
     119       26963 :                   free(submatch);
     120             :                 };
     121       26963 :                 ppstr += pmatch[0].rm_eo;       /* Restart from last match */
     122       26963 :               } while(!regexec(preg,ppstr,preg->re_nsub,pmatch,0));
     123             :             }
     124             :           }
     125             :         };
     126         188 :         regfree(preg);
     127         188 :         free(preg);
     128         188 :         free(pmatch);
     129             : #else
     130             :         plumed_merror("Regexp support not compiled!");
     131             : #endif
     132             :       } else {
     133           4 :         plumed_merror("did you want to use regexp to input arguments? enclose it between two round braces (...) with no spaces!");
     134             :       }
     135             :     } else {
     136             :       std::size_t dot=c[i].find_first_of('.');
     137        4036 :       string a=c[i].substr(0,dot);
     138        4036 :       string name=c[i].substr(dot+1);
     139        4036 :       if(c[i].find(".")!=string::npos) {   // if it contains a dot:
     140        1435 :         if(a=="*" && name=="*") {
     141             :           // Take all values from all actions
     142           2 :           std::vector<ActionWithValue*> all=plumed.getActionSet().select<ActionWithValue*>();
     143           1 :           if( all.empty() ) error("your input file is not telling plumed to calculate anything");
     144          26 :           for(unsigned j=0; j<all.size(); j++) {
     145          46 :             for(int k=0; k<all[j]->getNumberOfComponents(); ++k) arg.push_back(all[j]->copyOutput(k));
     146             :           }
     147        1426 :         } else if ( name=="*") {
     148             :           // Take all the values from an action with a specific name
     149         876 :           ActionWithValue* action=plumed.getActionSet().selectWithLabel<ActionWithValue*>(a);
     150         438 :           if(!action) {
     151           1 :             std::string str=" (hint! the actions with value in this ActionSet are: ";
     152           0 :             str+=plumed.getActionSet().getLabelList<ActionWithValue*>()+")";
     153           0 :             error("cannot find action named " + a + str);
     154             :           }
     155         439 :           if( action->getNumberOfComponents()==0 ) error("found " + a +".* indicating use all components calculated by action with label " + a + " but this action has no components");
     156        9677 :           for(int k=0; k<action->getNumberOfComponents(); ++k) arg.push_back(action->copyOutput(k));
     157         988 :         } else if ( a=="*" ) {
     158             :           // Take components from all actions with a specific name
     159          14 :           std::vector<ActionWithValue*> all=plumed.getActionSet().select<ActionWithValue*>();
     160           7 :           if( all.empty() ) error("your input file is not telling plumed to calculate anything");
     161             :           unsigned nval=0;
     162          86 :           for(unsigned j=0; j<all.size(); j++) {
     163          96 :             std::string flab; flab=all[j]->getLabel() + "." + name;
     164          42 :             if( all[j]->exists(flab) ) { arg.push_back(all[j]->copyOutput(flab)); nval++; }
     165             :           }
     166           7 :           if(nval==0) error("found no actions with a component called " + name );
     167             :         } else {
     168             :           // Take values with a specific name
     169        1962 :           ActionWithValue* action=plumed.getActionSet().selectWithLabel<ActionWithValue*>(a);
     170         981 :           if(!action) {
     171           1 :             std::string str=" (hint! the actions with value in this ActionSet are: ";
     172           0 :             str+=plumed.getActionSet().getLabelList<ActionWithValue*>()+")";
     173           0 :             error("cannot find action named " + a +str);
     174             :           }
     175         981 :           if( !(action->exists(c[i])) ) {
     176           1 :             std::string str=" (hint! the components in this actions are: ";
     177           0 :             str+=action->getComponentsList()+")";
     178           0 :             error("action " + a + " has no component named " + name + str);
     179             :           } ;
     180        1963 :           arg.push_back(action->copyOutput(c[i]));
     181             :         }
     182             :       } else {    // if it doesn't contain a dot
     183        2609 :         if(c[i]=="*") {
     184             :           // Take all values from all actions
     185         120 :           std::vector<ActionWithValue*> all=plumed.getActionSet().select<ActionWithValue*>();
     186          60 :           if( all.empty() ) error("your input file is not telling plumed to calculate anything");
     187        1218 :           for(unsigned j=0; j<all.size(); j++) {
     188        2118 :             for(int k=0; k<all[j]->getNumberOfComponents(); ++k) arg.push_back(all[j]->copyOutput(k));
     189             :           }
     190             :         } else {
     191        5098 :           ActionWithValue* action=plumed.getActionSet().selectWithLabel<ActionWithValue*>(c[i]);
     192        2549 :           if(!action) {
     193           2 :             std::string str=" (hint! the actions with value in this ActionSet are: ";
     194           5 :             str+=plumed.getActionSet().getLabelList<ActionWithValue*>()+")";
     195           4 :             error("cannot find action named " + c[i] + str );
     196             :           }
     197        2548 :           if( !(action->exists(c[i])) ) {
     198           1 :             std::string str=" (hint! the components in this actions are: ";
     199           0 :             str+=action->getComponentsList()+")";
     200           0 :             error("action " + c[i] + " has no component named " + c[i] +str);
     201             :           };
     202        5097 :           arg.push_back(action->copyOutput(c[i]));
     203             :         }
     204             :       }
     205             :     }
     206             :   }
     207        2055 : }
     208             : 
     209         442 : void ActionWithArguments::expandArgKeywordInPDB( PDB& pdb ) {
     210         884 :   std::vector<std::string> pdb_remark=pdb.getRemark();
     211         442 :   std::vector<std::string> arg_names;
     212         884 :   bool found=Tools::parseVector(pdb_remark,"ARG",arg_names);
     213         442 :   if( found ) {
     214             :     std::vector<Value*> arg_vals;
     215          80 :     interpretArgumentList( arg_names, arg_vals );
     216         160 :     std::string new_args="ARG=" + arg_vals[0]->getName();
     217         640 :     for(unsigned i=1; i<arg_vals.size(); ++i) new_args = new_args + "," + arg_vals[i]->getName();
     218          80 :     pdb.setArgKeyword( new_args );
     219             :   }
     220         442 : }
     221             : 
     222        3052 : void ActionWithArguments::requestArguments(const vector<Value*> &arg) {
     223        3052 :   plumed_massert(!lockRequestArguments,"requested argument list can only be changed in the prepare() method");
     224        3052 :   arguments=arg;
     225        3052 :   clearDependencies();
     226             :   std::string fullname,name;
     227       76835 :   for(unsigned i=0; i<arguments.size(); i++) {
     228       23577 :     fullname=arguments[i]->getName();
     229       23577 :     if(fullname.find(".")!=string::npos) {
     230             :       std::size_t dot=fullname.find_first_of('.');
     231       35684 :       name=fullname.substr(0,dot);
     232             :     } else {
     233             :       name=fullname;
     234             :     }
     235       47154 :     ActionWithValue* action=plumed.getActionSet().selectWithLabel<ActionWithValue*>(name);
     236       23577 :     plumed_massert(action,"cannot find action named (in requestArguments - this is weird)" + name);
     237       23577 :     addDependency(action);
     238             :   }
     239        3052 : }
     240             : 
     241        1950 : ActionWithArguments::ActionWithArguments(const ActionOptions&ao):
     242             :   Action(ao),
     243        3900 :   lockRequestArguments(false)
     244             : {
     245        5852 :   if( keywords.exists("ARG") && !keywords.exists("DATA") ) {
     246             :     vector<Value*> arg;
     247        3766 :     parseArgumentList("ARG",arg);
     248             : 
     249        1881 :     if(!arg.empty()) {
     250        1824 :       log.printf("  with arguments");
     251       86236 :       for(unsigned i=0; i<arg.size(); i++) log.printf(" %s",arg[i]->getName().c_str());
     252        1824 :       log.printf("\n");
     253             :     }
     254        1881 :     requestArguments(arg);
     255             :   }
     256        1948 : }
     257             : 
     258          58 : void ActionWithArguments::calculateNumericalDerivatives( ActionWithValue* a ) {
     259          58 :   if(!a) {
     260          58 :     a=dynamic_cast<ActionWithValue*>(this);
     261          58 :     plumed_massert(a,"cannot compute numerical derivatives for an action without values");
     262             :   }
     263             : 
     264             :   const int nval=a->getNumberOfComponents();
     265          58 :   const int npar=arguments.size();
     266          58 :   std::vector<double> value (nval*npar);
     267         264 :   for(int i=0; i<npar; i++) {
     268         206 :     double arg0=arguments[i]->get();
     269         103 :     arguments[i]->set(arg0+sqrt(epsilon));
     270         103 :     a->calculate();
     271         103 :     arguments[i]->set(arg0);
     272        2535 :     for(int j=0; j<nval; j++) {
     273        2432 :       value[i*nval+j]=a->getOutputQuantity(j);
     274             :     }
     275             :   }
     276          58 :   a->calculate();
     277          58 :   a->clearDerivatives();
     278        2230 :   for(int j=0; j<nval; j++) {
     279        1086 :     Value* v=a->copyOutput(j);
     280        1886 :     if( v->hasDerivatives() ) for(int i=0; i<npar; i++) v->addDerivative(i,(value[i*nval+j]-a->getOutputQuantity(j))/sqrt(epsilon));
     281             :   }
     282          58 : }
     283             : 
     284         261 : double ActionWithArguments::getProjection(unsigned i,unsigned j)const {
     285         522 :   plumed_massert(i<arguments.size()," making projections with an index which  is too large");
     286         261 :   plumed_massert(j<arguments.size()," making projections with an index which  is too large");
     287         261 :   const Value* v1=arguments[i];
     288         261 :   const Value* v2=arguments[j];
     289         261 :   return Value::projection(*v1,*v2);
     290             : }
     291             : 
     292         326 : void ActionWithArguments::addForcesOnArguments( const std::vector<double>& forces ) {
     293        1152 :   for(unsigned i=0; i<arguments.size(); ++i) arguments[i]->addForce( forces[i] );
     294         326 : }
     295             : 
     296        4839 : }

Generated by: LCOV version 1.13