LCOV - code coverage report
Current view: top level - generic - DumpAtoms.cpp (source / functions) Hit Total Coverage
Test: plumed test coverage Lines: 143 147 97.3 %
Date: 2024-10-18 13:59:31 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 );
     156         444 :   keys.addInputKeyword("optional","ARG","vector","the labels of vectors that should be output in the xyz file. The number of elements in the vector should equal the number of atoms output");
     157         444 :   keys.add("compulsory","STRIDE","1","the frequency with which the atoms should be output");
     158         444 :   keys.add("atoms", "ATOMS", "the atom indices whose positions you would like to print out");
     159         444 :   keys.add("compulsory", "FILE", "file on which to output coordinates; extension is automatically detected");
     160         444 :   keys.add("compulsory", "UNITS","PLUMED","the units in which to print out the coordinates. PLUMED means internal PLUMED units");
     161         444 :   keys.add("optional", "PRECISION","The number of digits in trajectory file");
     162         444 :   keys.add("optional", "TYPE","file type, either xyz, gro, xtc, or trr, can override an automatically detected file extension");
     163         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");
     164         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");
     165         222 :   keys.use("RESTART");
     166         222 :   keys.use("UPDATE_FROM");
     167         222 :   keys.use("UPDATE_UNTIL");
     168         222 : }
     169             : 
     170         220 : DumpAtoms::DumpAtoms(const ActionOptions&ao):
     171             :   Action(ao),
     172             :   ActionAtomistic(ao),
     173             :   ActionWithArguments(ao),
     174             :   ActionPilot(ao),
     175         220 :   iprecision(3)
     176             : {
     177             :   std::vector<AtomNumber> atoms;
     178             :   std::string file;
     179         440 :   parse("FILE",file);
     180         220 :   if(file.length()==0) error("name out output file was not specified");
     181         220 :   type=Tools::extension(file);
     182         220 :   log<<"  file name "<<file<<"\n";
     183         453 :   if(type=="gro" || type=="xyz" || type=="xtc" || type=="trr") {
     184         197 :     log<<"  file extension indicates a "<<type<<" file\n";
     185             :   } else {
     186          23 :     log<<"  file extension not detected, assuming xyz\n";
     187             :     type="xyz";
     188             :   }
     189             :   std::string ntype;
     190         440 :   parse("TYPE",ntype);
     191         220 :   if(ntype.length()>0) {
     192           5 :     if(ntype!="xyz" && ntype!="gro" && ntype!="xtc" && ntype!="trr"
     193           0 :       ) error("TYPE cannot be understood");
     194           2 :     log<<"  file type enforced to be "<<ntype<<"\n";
     195             :     type=ntype;
     196             :   }
     197             : 
     198             :   fmt_gro_pos="%8.3f";
     199             :   fmt_gro_box="%12.7f";
     200             :   fmt_xyz="%f";
     201             : 
     202             :   std::string precision;
     203         440 :   parse("PRECISION",precision);
     204         220 :   if(precision.length()>0) {
     205         136 :     Tools::convert(precision,iprecision);
     206         136 :     log<<"  with precision "<<iprecision<<"\n";
     207             :     std::string a,b;
     208         136 :     Tools::convert(iprecision+5,a);
     209         136 :     Tools::convert(iprecision,b);
     210         272 :     fmt_gro_pos="%"+a+"."+b+"f";
     211             :     fmt_gro_box=fmt_gro_pos;
     212             :     fmt_xyz=fmt_gro_box;
     213             :   }
     214             : 
     215         440 :   parseAtomList("ATOMS",atoms);
     216             : 
     217         440 :   std::string unitname; parse("UNITS",unitname);
     218         220 :   if(unitname!="PLUMED") {
     219          17 :     Units myunit; myunit.setLength(unitname);
     220          32 :     if(myunit.getLength()!=1.0 && type=="gro") error("gro files should be in nm");
     221          32 :     if(myunit.getLength()!=1.0 && type=="xtc") error("xtc files should be in nm");
     222          32 :     if(myunit.getLength()!=1.0 && type=="trr") error("trr files should be in nm");
     223          17 :     lenunit=getUnits().getLength()/myunit.getLength();
     224         528 :   } else if(type=="gro" || type=="xtc" || type=="trr") lenunit=getUnits().getLength();
     225         147 :   else lenunit=1.0;
     226             : 
     227         220 :   of.link(*this);
     228         220 :   of.open(file);
     229             :   std::string path=of.getPath();
     230         220 :   log<<"  Writing on file "<<path<<"\n";
     231             :   std::string mode=of.getMode();
     232         220 :   if(type=="xtc") {
     233           6 :     of.close();
     234           6 :     xd=xdrfile::xdrfile_open(path.c_str(),mode.c_str());
     235         214 :   } else if(type=="trr") {
     236           4 :     of.close();
     237           4 :     xd=xdrfile::xdrfile_open(path.c_str(),mode.c_str());
     238             :   }
     239         220 :   log.printf("  printing the following atoms in %s :", unitname.c_str() );
     240       30852 :   for(unsigned i=0; i<atoms.size(); ++i) log.printf(" %d",atoms[i].serial() );
     241         220 :   log.printf("\n");
     242             : 
     243         220 :   if( getNumberOfArguments()>0 ) {
     244          39 :     if( type!="xyz" ) error("can only print atomic properties when outputting xyz files");
     245             : 
     246             :     std::vector<std::string> argnames;
     247         119 :     for(unsigned i=0; i<getNumberOfArguments(); ++i) {
     248          80 :       if( getPntrToArgument(i)->getRank()!=1 || getPntrToArgument(i)->hasDerivatives() ) error("arguments for xyz output should be vectors");
     249          80 :       if( getPntrToArgument(i)->getNumberOfValues()!=atoms.size() ) error("number of elements in vector " + getPntrToArgument(i)->getName() + " is not equal to number of atoms output");
     250          80 :       getPntrToArgument(i)->buildDataStore(true); argnames.push_back( getPntrToArgument(i)->getName() );
     251             :     }
     252             :     std::vector<std::string> str_upper, str_lower; std::string errors;
     253         117 :     parseVector("LESS_THAN_OR_EQUAL",str_upper); parseVector("GREATER_THAN_OR_EQUAL",str_lower);
     254          39 :     if( !bounds.setBounds( getNumberOfArguments(), str_lower, str_upper, errors ) ) error( errors );
     255          52 :     if( bounds.wereSet() ) log.printf("  %s \n", bounds.report( argnames ).c_str() );
     256          39 :   }
     257             : 
     258         220 :   requestAtoms(atoms, false);
     259         220 :   auto* moldat=plumed.getActionSet().selectLatest<GenericMolInfo*>(this);
     260         220 :   if( moldat ) {
     261          56 :     log<<"  MOLINFO DATA found with label " <<moldat->getLabel()<<", using proper atom names\n";
     262          56 :     names.resize(atoms.size());
     263        5835 :     for(unsigned i=0; i<atoms.size(); i++) if(atoms[i].index()<moldat->getPDBsize()) names[i]=moldat->getAtomName(atoms[i]);
     264          56 :     residueNumbers.resize(atoms.size());
     265        5835 :     for(unsigned i=0; i<residueNumbers.size(); ++i) if(atoms[i].index()<moldat->getPDBsize()) residueNumbers[i]=moldat->getResidueNumber(atoms[i]);
     266          56 :     residueNames.resize(atoms.size());
     267        5835 :     for(unsigned i=0; i<residueNames.size(); ++i) if(atoms[i].index()<moldat->getPDBsize()) residueNames[i]=moldat->getResidueName(atoms[i]);
     268             :   }
     269         220 : }
     270             : 
     271           0 : void DumpAtoms::calculateNumericalDerivatives( ActionWithValue* a ) {
     272           0 :   plumed_merror("this should never be called");
     273             : }
     274             : 
     275        9093 : void DumpAtoms::lockRequests() {
     276             :   ActionWithArguments::lockRequests();
     277             :   ActionAtomistic::lockRequests();
     278        9093 : }
     279             : 
     280        9093 : void DumpAtoms::unlockRequests() {
     281             :   ActionWithArguments::unlockRequests();
     282             :   ActionAtomistic::unlockRequests();
     283        9093 : }
     284             : 
     285        8998 : void DumpAtoms::update() {
     286        8998 :   if(type=="xyz") {
     287        8412 :     unsigned nat=0; std::vector<double> args( getNumberOfArguments() );
     288       73985 :     for(unsigned i=0; i<getNumberOfAtoms(); ++i)  {
     289       95475 :       for(unsigned j=0; j<getNumberOfArguments(); ++j) args[j] = getPntrToArgument(j)->get(i);
     290       65573 :       if( bounds.check( args ) ) nat++;
     291             :     }
     292        8412 :     of.printf("%d\n",nat);
     293        8412 :     const Tensor & t(getPbc().getBox());
     294        8412 :     if(getPbc().isOrthorombic()) {
     295         612 :       of.printf((" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+"\n").c_str(),lenunit*t(0,0),lenunit*t(1,1),lenunit*t(2,2));
     296             :     } else {
     297       16212 :       of.printf((" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+" "+fmt_xyz+"\n").c_str(),
     298        8106 :                 lenunit*t(0,0),lenunit*t(0,1),lenunit*t(0,2),
     299        8106 :                 lenunit*t(1,0),lenunit*t(1,1),lenunit*t(1,2),
     300        8106 :                 lenunit*t(2,0),lenunit*t(2,1),lenunit*t(2,2)
     301             :                );
     302             :     }
     303       73985 :     for(unsigned i=0; i<getNumberOfAtoms(); ++i) {
     304       95475 :       for(unsigned j=0; j<getNumberOfArguments(); ++j) args[j] = getPntrToArgument(j)->get(i);
     305       65573 :       if( !bounds.check(args) ) continue;
     306             :       const char* defname="X";
     307             :       const char* name=defname;
     308       61767 :       if(names.size()>0) if(names[i].length()>0) name=names[i].c_str();
     309      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));
     310       87863 :       for(unsigned j=0; j<getNumberOfArguments(); ++j) of.printf((" "+fmt_xyz).c_str(), getPntrToArgument(j)->get(i) );
     311       61767 :       of.printf("\n");
     312             :     }
     313         586 :   } else if(type=="gro") {
     314         466 :     const Tensor & t(getPbc().getBox());
     315         466 :     of.printf("Made with PLUMED t=%f\n",getTime()/getUnits().getTime());
     316         466 :     of.printf("%d\n",getNumberOfAtoms());
     317       38404 :     for(unsigned i=0; i<getNumberOfAtoms(); ++i) {
     318             :       const char* defname="X";
     319             :       const char* name=defname;
     320             :       unsigned residueNumber=0;
     321       37938 :       if(names.size()>0) if(names[i].length()>0) name=names[i].c_str();
     322       37938 :       if(residueNumbers.size()>0) residueNumber=residueNumbers[i];
     323       37938 :       std::string resname="";
     324       37938 :       if(residueNames.size()>0) resname=residueNames[i];
     325       75876 :       of.printf(("%5u%-5s%5s%5d"+fmt_gro_pos+fmt_gro_pos+fmt_gro_pos+"\n").c_str(),
     326             :                 residueNumber%100000,resname.c_str(),name,getAbsoluteIndex(i).serial()%100000,
     327       37938 :                 lenunit*getPosition(i)(0),lenunit*getPosition(i)(1),lenunit*getPosition(i)(2));
     328             :     }
     329         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(),
     330         466 :               lenunit*t(0,0),lenunit*t(1,1),lenunit*t(2,2),
     331         466 :               lenunit*t(0,1),lenunit*t(0,2),lenunit*t(1,0),
     332         466 :               lenunit*t(1,2),lenunit*t(2,0),lenunit*t(2,1));
     333         168 :   } else if(type=="xtc" || type=="trr") {
     334             :     xdrfile::matrix box;
     335         120 :     const Tensor & t(getPbc().getBox());
     336         120 :     int natoms=getNumberOfAtoms();
     337         120 :     int step=getStep();
     338         120 :     float time=getTime()/getUnits().getTime();
     339         120 :     float precision=Tools::fastpow(10.0,iprecision);
     340        1560 :     for(int i=0; i<3; i++) for(int j=0; j<3; j++) box[i][j]=lenunit*t(i,j);
     341             : // here we cannot use a std::vector<rvec> since it does not compile.
     342             : // we thus use a std::unique_ptr<rvec[]>
     343             :     auto pos = Tools::make_unique<xdrfile::rvec[]>(natoms);
     344       25464 :     for(int i=0; i<natoms; i++) for(int j=0; j<3; j++) pos[i][j]=lenunit*getPosition(i)(j);
     345         120 :     if(type=="xtc") {
     346          72 :       write_xtc(xd,natoms,step,time,box,&pos[0],precision);
     347          48 :     } else if(type=="trr") {
     348          48 :       write_trr(xd,natoms,step,time,0.0,box,&pos[0],NULL,NULL);
     349             :     }
     350           0 :   } else plumed_merror("unknown file type "+type);
     351        8998 : }
     352             : 
     353         440 : DumpAtoms::~DumpAtoms() {
     354         220 :   if(type=="xtc") {
     355           6 :     xdrfile_close(xd);
     356         214 :   } else if(type=="trr") {
     357           4 :     xdrfile_close(xd);
     358             :   }
     359        1100 : }
     360             : 
     361             : 
     362             : }
     363             : }

Generated by: LCOV version 1.16