LCOV - code coverage report
Current view: top level - generic - DumpAtoms.cpp (source / functions) Hit Total Coverage
Test: plumed test coverage Lines: 142 146 97.3 %
Date: 2024-10-18 14:00:25 Functions: 10 13 76.9 %

          Line data    Source code
       1             : /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
       2             :    Copyright (c) 2011-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 "core/ActionAtomistic.h"
      23             : #include "core/ActionWithArguments.h"
      24             : #include "core/ActionPilot.h"
      25             : #include "core/ActionRegister.h"
      26             : #include "tools/Pbc.h"
      27             : #include "tools/File.h"
      28             : #include "core/PlumedMain.h"
      29             : #include "tools/Units.h"
      30             : #include "tools/CheckInRange.h"
      31             : #include <cstdio>
      32             : #include <memory>
      33             : #include "core/GenericMolInfo.h"
      34             : #include "core/ActionSet.h"
      35             : #include "xdrfile/xdrfile_xtc.h"
      36             : #include "xdrfile/xdrfile_trr.h"
      37             : 
      38             : 
      39             : namespace PLMD {
      40             : namespace generic {
      41             : 
      42             : //+PLUMEDOC PRINTANALYSIS DUMPATOMS
      43             : /*
      44             : Dump selected atoms on a file.
      45             : 
      46             : This command can be used to output the positions of a particular set of atoms.
      47             : The atoms required are output in a xyz or gro formatted file.
      48             : If PLUMED has been compiled with xdrfile support, then also xtc and trr files can be written.
      49             : To this aim one should install xdrfile library (http://www.gromacs.org/Developer_Zone/Programming_Guide/XTC_Library).
      50             : If the xdrfile library is installed properly the PLUMED configure script should be able to
      51             : detect it and enable it.
      52             : The type of file is automatically detected from the file extension, but can be also
      53             : enforced with TYPE.
      54             : Importantly, if your
      55             : input file contains actions that edit the atoms position (e.g. \ref WHOLEMOLECULES)
      56             : and the DUMPATOMS command appears after this instruction, then the edited
      57             : atom positions are output.
      58             : You can control the buffering of output using the \ref FLUSH keyword on a separate line.
      59             : 
      60             : Units of the printed file can be controlled with the UNITS keyword. By default PLUMED units as
      61             : controlled in the \ref UNITS command are used, but one can override it e.g. with UNITS=A.
      62             : Notice that gro/xtc/trr files can only contain coordinates in nm.
      63             : 
      64             : \par Examples
      65             : 
      66             : The following input instructs plumed to print out the positions of atoms
      67             : 1-10 together with the position of the center of mass of atoms 11-20 every
      68             : 10 steps to a file called file.xyz.
      69             : \plumedfile
      70             : COM ATOMS=11-20 LABEL=c1
      71             : DUMPATOMS STRIDE=10 FILE=file.xyz ATOMS=1-10,c1
      72             : \endplumedfile
      73             : Notice that the coordinates in the xyz file will be expressed in nm, since these
      74             : are the defaults units in PLUMED. If you want the xyz file to be expressed in A, you should use the
      75             : following input
      76             : \plumedfile
      77             : COM ATOMS=11-20 LABEL=c1
      78             : DUMPATOMS STRIDE=10 FILE=file.xyz ATOMS=1-10,c1 UNITS=A
      79             : \endplumedfile
      80             : As an alternative, you might want to set all the length used by PLUMED to Angstrom using the \ref UNITS
      81             : action. However, this latter choice will affect all your input and output.
      82             : 
      83             : The following input is very similar but dumps a .gro (gromacs) file,
      84             : which also contains atom and residue names.
      85             : \plumedfile
      86             : #SETTINGS MOLFILE=regtest/basic/rt32/helix.pdb
      87             : # this is required to have proper atom names:
      88             : MOLINFO STRUCTURE=reference.pdb
      89             : # if omitted, atoms will have "X" name...
      90             : 
      91             : COM ATOMS=11-20 LABEL=c1
      92             : DUMPATOMS STRIDE=10 FILE=file.gro ATOMS=1-10,c1
      93             : # notice that last atom is a virtual one and will not have
      94             : # a correct name in the resulting gro file
      95             : \endplumedfile
      96             : 
      97             : The `file.gro` will contain coordinates expressed in nm, since this is the convention for gro files.
      98             : 
      99             : In case you have compiled PLUMED with `xdrfile` library, you might even write xtc or trr files as follows
     100             : \plumedfile
     101             : COM ATOMS=11-20 LABEL=c1
     102             : DUMPATOMS STRIDE=10 FILE=file.xtc ATOMS=1-10,c1
     103             : \endplumedfile
     104             : Notice that xtc files are significantly smaller than gro and xyz files.
     105             : 
     106             : Finally, consider that gro and xtc file store coordinates with limited precision set by the
     107             : `PRECISION` keyword. Default value is 3, which means "3 digits after dot" in nm (1/1000 of a nm).
     108             : The following will write a larger xtc file with high resolution coordinates:
     109             : \plumedfile
     110             : COM ATOMS=11-20 LABEL=c1
     111             : DUMPATOMS STRIDE=10 FILE=file.xtc ATOMS=1-10,c1 PRECISION=7
     112             : \endplumedfile
     113             : 
     114             : 
     115             : 
     116             : */
     117             : //+ENDPLUMEDOC
     118             : 
     119             : class DumpAtoms:
     120             :   public ActionAtomistic,
     121             :   public ActionWithArguments,
     122             :   public ActionPilot
     123             : {
     124             :   OFile of;
     125             :   double lenunit;
     126             :   int iprecision;
     127             :   CheckInRange bounds;
     128             :   std::vector<std::string> names;
     129             :   std::vector<unsigned>    residueNumbers;
     130             :   std::vector<std::string> residueNames;
     131             :   std::string type;
     132             :   std::string fmt_gro_pos;
     133             :   std::string fmt_gro_box;
     134             :   std::string fmt_xyz;
     135             :   xdrfile::XDRFILE* xd;
     136             : public:
     137             :   explicit DumpAtoms(const ActionOptions&);
     138             :   ~DumpAtoms();
     139             :   static void registerKeywords( Keywords& keys );
     140             :   void calculateNumericalDerivatives( ActionWithValue* a=NULL ) override;
     141         194 :   bool actionHasForces() override { return false; }
     142             :   void lockRequests() override;
     143             :   void unlockRequests() override;
     144        9093 :   void calculate() override {}
     145        9093 :   void apply() override {}
     146             :   void update() override ;
     147             : };
     148             : 
     149             : PLUMED_REGISTER_ACTION(DumpAtoms,"DUMPATOMS")
     150             : 
     151         222 : void DumpAtoms::registerKeywords( Keywords& keys ) {
     152         222 :   Action::registerKeywords( keys );
     153         222 :   ActionPilot::registerKeywords( keys );
     154         222 :   ActionAtomistic::registerKeywords( keys );
     155         222 :   ActionWithArguments::registerKeywords( keys ); keys.use("ARG");
     156         444 :   keys.add("compulsory","STRIDE","1","the frequency with which the atoms should be output");
     157         444 :   keys.add("atoms", "ATOMS", "the atom indices whose positions you would like to print out");
     158         444 :   keys.add("compulsory", "FILE", "file on which to output coordinates; extension is automatically detected");
     159         444 :   keys.add("compulsory", "UNITS","PLUMED","the units in which to print out the coordinates. PLUMED means internal PLUMED units");
     160         444 :   keys.add("optional", "PRECISION","The number of digits in trajectory file");
     161         444 :   keys.add("optional", "TYPE","file type, either xyz, gro, xtc, or trr, can override an automatically detected file extension");
     162         444 :   keys.add("optional","LESS_THAN_OR_EQUAL","when printing with arguments that are vectors only print components of vectors have a value less than or equal to this value");
     163         444 :   keys.add("optional","GREATER_THAN_OR_EQUAL","when printing with arguments that are vectors only print components of vectors have a value greater than or equal to this value");
     164         222 :   keys.use("RESTART");
     165         222 :   keys.use("UPDATE_FROM");
     166         222 :   keys.use("UPDATE_UNTIL");
     167         222 : }
     168             : 
     169         220 : DumpAtoms::DumpAtoms(const ActionOptions&ao):
     170             :   Action(ao),
     171             :   ActionAtomistic(ao),
     172             :   ActionWithArguments(ao),
     173             :   ActionPilot(ao),
     174         220 :   iprecision(3)
     175             : {
     176             :   std::vector<AtomNumber> atoms;
     177             :   std::string file;
     178         440 :   parse("FILE",file);
     179         220 :   if(file.length()==0) error("name out output file was not specified");
     180         220 :   type=Tools::extension(file);
     181         220 :   log<<"  file name "<<file<<"\n";
     182         453 :   if(type=="gro" || type=="xyz" || type=="xtc" || type=="trr") {
     183         197 :     log<<"  file extension indicates a "<<type<<" file\n";
     184             :   } else {
     185          23 :     log<<"  file extension not detected, assuming xyz\n";
     186             :     type="xyz";
     187             :   }
     188             :   std::string ntype;
     189         440 :   parse("TYPE",ntype);
     190         220 :   if(ntype.length()>0) {
     191           5 :     if(ntype!="xyz" && ntype!="gro" && ntype!="xtc" && ntype!="trr"
     192           0 :       ) error("TYPE cannot be understood");
     193           2 :     log<<"  file type enforced to be "<<ntype<<"\n";
     194             :     type=ntype;
     195             :   }
     196             : 
     197             :   fmt_gro_pos="%8.3f";
     198             :   fmt_gro_box="%12.7f";
     199             :   fmt_xyz="%f";
     200             : 
     201             :   std::string precision;
     202         440 :   parse("PRECISION",precision);
     203         220 :   if(precision.length()>0) {
     204         136 :     Tools::convert(precision,iprecision);
     205         136 :     log<<"  with precision "<<iprecision<<"\n";
     206             :     std::string a,b;
     207         136 :     Tools::convert(iprecision+5,a);
     208         136 :     Tools::convert(iprecision,b);
     209         272 :     fmt_gro_pos="%"+a+"."+b+"f";
     210             :     fmt_gro_box=fmt_gro_pos;
     211             :     fmt_xyz=fmt_gro_box;
     212             :   }
     213             : 
     214         440 :   parseAtomList("ATOMS",atoms);
     215             : 
     216         440 :   std::string unitname; parse("UNITS",unitname);
     217         220 :   if(unitname!="PLUMED") {
     218          17 :     Units myunit; myunit.setLength(unitname);
     219          32 :     if(myunit.getLength()!=1.0 && type=="gro") error("gro files should be in nm");
     220          32 :     if(myunit.getLength()!=1.0 && type=="xtc") error("xtc files should be in nm");
     221          32 :     if(myunit.getLength()!=1.0 && type=="trr") error("trr files should be in nm");
     222          17 :     lenunit=getUnits().getLength()/myunit.getLength();
     223         528 :   } else if(type=="gro" || type=="xtc" || type=="trr") lenunit=getUnits().getLength();
     224         147 :   else lenunit=1.0;
     225             : 
     226         220 :   of.link(*this);
     227         220 :   of.open(file);
     228             :   std::string path=of.getPath();
     229         220 :   log<<"  Writing on file "<<path<<"\n";
     230             :   std::string mode=of.getMode();
     231         220 :   if(type=="xtc") {
     232           6 :     of.close();
     233           6 :     xd=xdrfile::xdrfile_open(path.c_str(),mode.c_str());
     234         214 :   } else if(type=="trr") {
     235           4 :     of.close();
     236           4 :     xd=xdrfile::xdrfile_open(path.c_str(),mode.c_str());
     237             :   }
     238         220 :   log.printf("  printing the following atoms in %s :", unitname.c_str() );
     239       30852 :   for(unsigned i=0; i<atoms.size(); ++i) log.printf(" %d",atoms[i].serial() );
     240         220 :   log.printf("\n");
     241             : 
     242         220 :   if( getNumberOfArguments()>0 ) {
     243          39 :     if( type!="xyz" ) error("can only print atomic properties when outputting xyz files");
     244             : 
     245             :     std::vector<std::string> argnames;
     246         119 :     for(unsigned i=0; i<getNumberOfArguments(); ++i) {
     247          80 :       if( getPntrToArgument(i)->getRank()!=1 || getPntrToArgument(i)->hasDerivatives() ) error("arguments for xyz output should be vectors");
     248          80 :       if( getPntrToArgument(i)->getNumberOfValues()!=atoms.size() ) error("number of elements in vector " + getPntrToArgument(i)->getName() + " is not equal to number of atoms output");
     249          80 :       getPntrToArgument(i)->buildDataStore(true); argnames.push_back( getPntrToArgument(i)->getName() );
     250             :     }
     251             :     std::vector<std::string> str_upper, str_lower; std::string errors;
     252         117 :     parseVector("LESS_THAN_OR_EQUAL",str_upper); parseVector("GREATER_THAN_OR_EQUAL",str_lower);
     253          39 :     if( !bounds.setBounds( getNumberOfArguments(), str_lower, str_upper, errors ) ) error( errors );
     254          52 :     if( bounds.wereSet() ) log.printf("  %s \n", bounds.report( argnames ).c_str() );
     255          39 :   }
     256             : 
     257         220 :   requestAtoms(atoms, false);
     258         220 :   auto* moldat=plumed.getActionSet().selectLatest<GenericMolInfo*>(this);
     259         220 :   if( moldat ) {
     260          56 :     log<<"  MOLINFO DATA found with label " <<moldat->getLabel()<<", using proper atom names\n";
     261          56 :     names.resize(atoms.size());
     262        5835 :     for(unsigned i=0; i<atoms.size(); i++) if(atoms[i].index()<moldat->getPDBsize()) names[i]=moldat->getAtomName(atoms[i]);
     263          56 :     residueNumbers.resize(atoms.size());
     264        5835 :     for(unsigned i=0; i<residueNumbers.size(); ++i) if(atoms[i].index()<moldat->getPDBsize()) residueNumbers[i]=moldat->getResidueNumber(atoms[i]);
     265          56 :     residueNames.resize(atoms.size());
     266        5835 :     for(unsigned i=0; i<residueNames.size(); ++i) if(atoms[i].index()<moldat->getPDBsize()) residueNames[i]=moldat->getResidueName(atoms[i]);
     267             :   }
     268         220 : }
     269             : 
     270           0 : void DumpAtoms::calculateNumericalDerivatives( ActionWithValue* a ) {
     271           0 :   plumed_merror("this should never be called");
     272             : }
     273             : 
     274        9093 : void DumpAtoms::lockRequests() {
     275             :   ActionWithArguments::lockRequests();
     276             :   ActionAtomistic::lockRequests();
     277        9093 : }
     278             : 
     279        9093 : void DumpAtoms::unlockRequests() {
     280             :   ActionWithArguments::unlockRequests();
     281             :   ActionAtomistic::unlockRequests();
     282        9093 : }
     283             : 
     284        8998 : void DumpAtoms::update() {
     285        8998 :   if(type=="xyz") {
     286        8412 :     unsigned nat=0; std::vector<double> args( getNumberOfArguments() );
     287       73985 :     for(unsigned i=0; i<getNumberOfAtoms(); ++i)  {
     288       95475 :       for(unsigned j=0; j<getNumberOfArguments(); ++j) args[j] = getPntrToArgument(j)->get(i);
     289       65573 :       if( bounds.check( args ) ) nat++;
     290             :     }
     291        8412 :     of.printf("%d\n",nat);
     292        8412 :     const Tensor & t(getPbc().getBox());
     293        8412 :     if(getPbc().isOrthorombic()) {
     294         612 :       of.printf((" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+"\n").c_str(),lenunit*t(0,0),lenunit*t(1,1),lenunit*t(2,2));
     295             :     } else {
     296       16212 :       of.printf((" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+"\n").c_str(),
     297        8106 :                 lenunit*t(0,0),lenunit*t(0,1),lenunit*t(0,2),
     298        8106 :                 lenunit*t(1,0),lenunit*t(1,1),lenunit*t(1,2),
     299        8106 :                 lenunit*t(2,0),lenunit*t(2,1),lenunit*t(2,2)
     300             :                );
     301             :     }
     302       73985 :     for(unsigned i=0; i<getNumberOfAtoms(); ++i) {
     303       95475 :       for(unsigned j=0; j<getNumberOfArguments(); ++j) args[j] = getPntrToArgument(j)->get(i);
     304       65573 :       if( !bounds.check(args) ) continue;
     305             :       const char* defname="X";
     306             :       const char* name=defname;
     307       61767 :       if(names.size()>0) if(names[i].length()>0) name=names[i].c_str();
     308      123534 :       of.printf(("%s "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz).c_str(),name,lenunit*getPosition(i)(0),lenunit*getPosition(i)(1),lenunit*getPosition(i)(2));
     309       87863 :       for(unsigned j=0; j<getNumberOfArguments(); ++j) of.printf((" "+fmt_xyz).c_str(), getPntrToArgument(j)->get(i) );
     310       61767 :       of.printf("\n");
     311             :     }
     312         586 :   } else if(type=="gro") {
     313         466 :     const Tensor & t(getPbc().getBox());
     314         466 :     of.printf("Made with PLUMED t=%f\n",getTime()/getUnits().getTime());
     315         466 :     of.printf("%d\n",getNumberOfAtoms());
     316       38404 :     for(unsigned i=0; i<getNumberOfAtoms(); ++i) {
     317             :       const char* defname="X";
     318             :       const char* name=defname;
     319             :       unsigned residueNumber=0;
     320       37938 :       if(names.size()>0) if(names[i].length()>0) name=names[i].c_str();
     321       37938 :       if(residueNumbers.size()>0) residueNumber=residueNumbers[i];
     322       37938 :       std::string resname="";
     323       37938 :       if(residueNames.size()>0) resname=residueNames[i];
     324       75876 :       of.printf(("%5u%-5s%5s%5d"+fmt_gro_pos+fmt_gro_pos+fmt_gro_pos+"\n").c_str(),
     325             :                 residueNumber%100000,resname.c_str(),name,getAbsoluteIndex(i).serial()%100000,
     326       37938 :                 lenunit*getPosition(i)(0),lenunit*getPosition(i)(1),lenunit*getPosition(i)(2));
     327             :     }
     328         932 :     of.printf((fmt_gro_box+" "+fmt_gro_box+" "+fmt_gro_box+" "+fmt_gro_box+" "+fmt_gro_box+" "+fmt_gro_box+" "+fmt_gro_box+" "+fmt_gro_box+" "+fmt_gro_box+"\n").c_str(),
     329         466 :               lenunit*t(0,0),lenunit*t(1,1),lenunit*t(2,2),
     330         466 :               lenunit*t(0,1),lenunit*t(0,2),lenunit*t(1,0),
     331         466 :               lenunit*t(1,2),lenunit*t(2,0),lenunit*t(2,1));
     332         168 :   } else if(type=="xtc" || type=="trr") {
     333             :     xdrfile::matrix box;
     334         120 :     const Tensor & t(getPbc().getBox());
     335         120 :     int natoms=getNumberOfAtoms();
     336         120 :     int step=getStep();
     337         120 :     float time=getTime()/getUnits().getTime();
     338         120 :     float precision=Tools::fastpow(10.0,iprecision);
     339        1560 :     for(int i=0; i<3; i++) for(int j=0; j<3; j++) box[i][j]=lenunit*t(i,j);
     340             : // here we cannot use a std::vector<rvec> since it does not compile.
     341             : // we thus use a std::unique_ptr<rvec[]>
     342             :     auto pos = Tools::make_unique<xdrfile::rvec[]>(natoms);
     343       25464 :     for(int i=0; i<natoms; i++) for(int j=0; j<3; j++) pos[i][j]=lenunit*getPosition(i)(j);
     344         120 :     if(type=="xtc") {
     345          72 :       write_xtc(xd,natoms,step,time,box,&pos[0],precision);
     346          48 :     } else if(type=="trr") {
     347          48 :       write_trr(xd,natoms,step,time,0.0,box,&pos[0],NULL,NULL);
     348             :     }
     349           0 :   } else plumed_merror("unknown file type "+type);
     350        8998 : }
     351             : 
     352         440 : DumpAtoms::~DumpAtoms() {
     353         220 :   if(type=="xtc") {
     354           6 :     xdrfile_close(xd);
     355         214 :   } else if(type=="trr") {
     356           4 :     xdrfile_close(xd);
     357             :   }
     358        1100 : }
     359             : 
     360             : 
     361             : }
     362             : }

Generated by: LCOV version 1.16