/
Driver.cpp
1181 lines (1082 loc) · 46.7 KB
/
Driver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Copyright (c) 2012-2023 The plumed team
(see the PEOPLE file at the root of the distribution for a list of names)
See http://www.plumed.org for more information.
This file is part of plumed, version 2.
plumed is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
plumed is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with plumed. If not, see <http://www.gnu.org/licenses/>.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
#include "CLTool.h"
#include "core/CLToolRegister.h"
#include "tools/Tools.h"
#include "core/PlumedMain.h"
#include "core/ActionSet.h"
#include "core/ActionWithValue.h"
#include "core/ActionShortcut.h"
#include "tools/Communicator.h"
#include "tools/Random.h"
#include "tools/Pbc.h"
#include <cstdio>
#include <cstring>
#include <vector>
#include <map>
#include <memory>
#include "tools/Units.h"
#include "tools/PDB.h"
#include "tools/FileBase.h"
#include "tools/IFile.h"
#include "xdrfile/xdrfile_trr.h"
#include "xdrfile/xdrfile_xtc.h"
// when using molfile plugin
#ifdef __PLUMED_HAS_MOLFILE_PLUGINS
#ifndef __PLUMED_HAS_EXTERNAL_MOLFILE_PLUGINS
/* Use the internal ones. Alternatively:
* ifeq (,$(findstring __PLUMED_HAS_EXTERNAL_MOLFILE_PLUGINS,$(CPPFLAGS)))
* CPPFLAGS+=-I../molfile
*/
#include "molfile/libmolfile_plugin.h"
#include "molfile/molfile_plugin.h"
using namespace PLMD::molfile;
#else
#include <libmolfile_plugin.h>
#include <molfile_plugin.h>
#endif
#endif
namespace PLMD {
namespace cltools {
//+PLUMEDOC TOOLS driver-float
/*
Equivalent to \ref driver, but using single precision reals.
The purpose of this tool is just to test what PLUMED does when linked from
a single precision code.
\par Examples
\verbatim
plumed driver-float --plumed plumed.dat --ixyz trajectory.xyz
\endverbatim
See also examples in \ref driver
*/
//+ENDPLUMEDOC
//
//+PLUMEDOC TOOLS driver
/*
driver is a tool that allows one to to use plumed to post-process an existing trajectory.
The input to driver is specified using the command line arguments described below.
In addition, you can use the special \subpage READ command inside your plumed input
to read in colvar files that were generated during your MD simulation. The values
read in can then be treated like calculated colvars.
\warning
Notice that by default the driver has no knowledge about the masses and charges
of your atoms! Thus, if you want to compute quantities depending charges (e.g. \ref DHENERGY)
or masses (e.g. \ref COM) you should pass the proper information to the driver.
You can do it either with the --pdb option or with the --mc option. The latter
will read a file produced by \ref DUMPMASSCHARGE .
\par Examples
The following command tells plumed to post process the trajectory contained in `trajectory.xyz`
by performing the actions described in the input file `plumed.dat`. If an action that takes the
stride keyword is given a stride equal to \f$n\f$ then it will be performed only on every \f$n\f$th
frames in the trajectory file.
\verbatim
plumed driver --plumed plumed.dat --ixyz trajectory.xyz
\endverbatim
Notice that `xyz` files are expected to be in internal PLUMED units, that is by default nm.
You can change this behavior by using the `--length-units` option:
\verbatim
plumed driver --plumed plumed.dat --ixyz trajectory.xyz --length-units A
\endverbatim
The strings accepted by the `--length-units` options are the same ones accepted by the \ref UNITS action.
Other file formats typically have their default coordinates (e.g., `gro` files are always in nm)
and it thus should not be necessary to use the `--length-units` option. Additionally,
consider that the units used by the `driver` might be different by the units used in the PLUMED input
file `plumed.dat`. For instance consider the command:
\verbatim
plumed driver --plumed plumed.dat --ixyz trajectory.xyz --length-units A
\endverbatim
where `plumed.dat` is
\plumedfile
# no explicit UNITS action here
d: DISTANCE ATOMS=1,2
PRINT ARG=d FILE=colvar
\endplumedfile
In this case, the driver reads the `xyz` file assuming it to contain coordinates in Angstrom units.
However, the resulting `colvar` file contains a distance expressed in nm.
The following command tells plumed to post process the trajectory contained in trajectory.xyz.
by performing the actions described in the input file plumed.dat.
\verbatim
plumed driver --plumed plumed.dat --ixyz trajectory.xyz --trajectory-stride 100 --timestep 0.001
\endverbatim
Here though
`--trajectory-stride` is set equal to the frequency with which frames were output during the trajectory
and the `--timestep` is equal to the simulation timestep. As such the `STRIDE` parameters in the `plumed.dat`
files are referred to the original timestep and any files output resemble those that would have been generated
had we run the calculation we are running with driver when the MD simulation was running.
PLUMED can read xyz files (in PLUMED units) and gro files (in nm). In addition,
PLUMED includes by default support for a
subset of the trajectory file formats supported by VMD, e.g. xtc and dcd:
\verbatim
plumed driver --plumed plumed.dat --pdb diala.pdb --mf_xtc traj.xtc --trajectory-stride 100 --timestep 0.001
\endverbatim
where `--mf_` prefixes the extension of one of the accepted molfile plugin format.
If PLUMED has been \ref Installation "installed" with full molfile support, other formats will be available.
Just type `plumed driver --help` to see which plugins are available.
Molfile plugin require periodic cell to be triangular (i.e. first vector oriented along x and
second vector in xy plane). This is true for many MD codes. However, it could be false
if you rotate the coordinates in your trajectory before reading them in the driver.
Also notice that some formats (e.g. amber crd) do not specify atom number. In this case you can use
the `--natoms` option:
\verbatim
plumed driver --plumed plumed.dat --imf_crd trajectory.crd --natoms 128
\endverbatim
Check the available molfile plugins and limitations at [this link](http://www.ks.uiuc.edu/Research/vmd/plugins/molfile/).
Additionally, you can use the xdrfile implementation of xtc and trr. To this aim, just
download and install properly the xdrfile library (see [this link](http://www.gromacs.org/Developer_Zone/Programming_Guide/XTC_Library)).
If the xdrfile library is installed properly the PLUMED configure script should be able to
detect it and enable it.
Notice that the xdrfile implementation of xtc and trr
is more robust than the molfile one, since it provides support for generic cell shapes.
In addition, it allows \ref DUMPATOMS to write compressed xtc files.
*/
//+ENDPLUMEDOC
//
#ifdef __PLUMED_HAS_MOLFILE_PLUGINS
static std::vector<molfile_plugin_t *> plugins;
static std::map <std::string, unsigned> pluginmap;
static int register_cb(void *v, vmdplugin_t *p) {
//const char *key = p->name;
const auto ret = pluginmap.insert ( std::pair<std::string,unsigned>(std::string(p->name),plugins.size()) );
if (ret.second==false) {
//cerr<<"MOLFILE: found duplicate plugin for "<<key<<" : not inserted "<<endl;
} else {
//cerr<<"MOLFILE: loading plugin "<<key<<" number "<<plugins.size()-1<<endl;
plugins.push_back(reinterpret_cast<molfile_plugin_t *>(p));
}
return VMDPLUGIN_SUCCESS;
}
#endif
template<typename real>
class Driver : public CLTool {
public:
static void registerKeywords( Keywords& keys );
explicit Driver(const CLToolOptions& co );
int main(FILE* in,FILE*out,Communicator& pc) override;
void evaluateNumericalDerivatives( const long long int& step, PlumedMain& p, const std::vector<real>& coordinates,
const std::vector<real>& masses, const std::vector<real>& charges,
std::vector<real>& cell, const double& base, std::vector<real>& numder );
std::string description()const override;
};
template<typename real>
void Driver<real>::registerKeywords( Keywords& keys ) {
CLTool::registerKeywords( keys ); keys.isDriver();
keys.addFlag("--help-debug",false,"print special options that can be used to create regtests");
keys.add("compulsory","--plumed","plumed.dat","specify the name of the plumed input file");
keys.add("compulsory","--timestep","1.0","the timestep that was used in the calculation that produced this trajectory in picoseconds");
keys.add("compulsory","--trajectory-stride","1","the frequency with which frames were output to this trajectory during the simulation"
" (0 means that the number of the step is read from the trajectory file,"
" currently working only for xtc/trr files read with --ixtc/--trr)"
);
keys.add("compulsory","--multi","0","set number of replicas for multi environment (needs MPI)");
keys.addFlag("--noatoms",false,"don't read in a trajectory. Just use colvar files as specified in plumed.dat");
keys.addFlag("--parse-only",false,"read the plumed input file and stop");
keys.addFlag("--restart",false,"makes driver behave as if restarting");
keys.add("atoms","--ixyz","the trajectory in xyz format");
keys.add("atoms","--igro","the trajectory in gro format");
keys.add("atoms","--idlp4","the trajectory in DL_POLY_4 format");
keys.add("atoms","--ixtc","the trajectory in xtc format (xdrfile implementation)");
keys.add("atoms","--itrr","the trajectory in trr format (xdrfile implementation)");
keys.add("optional","--shortcut-ofile","the name of the file to output info on the way shortcuts have been expanded. If there are no shortcuts in your input file nothing is output");
keys.add("optional","--length-units","units for length, either as a string or a number");
keys.add("optional","--mass-units","units for mass in pdb and mc file, either as a string or a number");
keys.add("optional","--charge-units","units for charge in pdb and mc file, either as a string or a number");
keys.add("optional","--kt","set \\f$k_B T\\f$, it will not be necessary to specify temperature in input file");
keys.add("optional","--dump-forces","dump the forces on a file");
keys.add("optional","--dump-forces-fmt","( default=%%f ) the format to use to dump the forces");
keys.addFlag("--dump-full-virial",false,"with --dump-forces, it dumps the 9 components of the virial");
keys.add("optional","--pdb","provides a pdb with masses and charges");
keys.add("optional","--mc","provides a file with masses and charges as produced with DUMPMASSCHARGE");
keys.add("optional","--box","comma-separated box dimensions (3 for orthorhombic, 9 for generic)");
keys.add("optional","--natoms","provides number of atoms - only used if file format does not contain number of atoms");
keys.add("optional","--initial-step","provides a number for the initial step, default is 0");
keys.add("optional","--debug-forces","output a file containing the forces due to the bias evaluated using numerical derivatives "
"and using the analytical derivatives implemented in plumed");
keys.add("hidden","--debug-float","[yes/no] turns on the single precision version (to check float interface)");
keys.add("hidden","--debug-dd","[yes/no] use a fake domain decomposition");
keys.add("hidden","--debug-pd","[yes/no] use a fake particle decomposition");
keys.add("hidden","--debug-grex","use a fake gromacs-like replica exchange, specify exchange stride");
keys.add("hidden","--debug-grex-log","log file for debug=grex");
#ifdef __PLUMED_HAS_MOLFILE_PLUGINS
MOLFILE_INIT_ALL
MOLFILE_REGISTER_ALL(NULL, register_cb)
for(unsigned i=0; i<plugins.size(); i++) {
std::string kk="--mf_"+std::string(plugins[i]->name);
std::string mm=" molfile: the trajectory in "+std::string(plugins[i]->name)+" format " ;
keys.add("atoms",kk,mm);
}
#endif
}
template<typename real>
Driver<real>::Driver(const CLToolOptions& co ):
CLTool(co)
{
inputdata=commandline;
}
template<typename real>
std::string Driver<real>::description()const { return "analyze trajectories with plumed"; }
template<typename real>
int Driver<real>::main(FILE* in,FILE*out,Communicator& pc) {
Units units;
PDB pdb;
// Parse everything
bool printhelpdebug; parseFlag("--help-debug",printhelpdebug);
if( printhelpdebug ) {
std::fprintf(out,"%s",
"Additional options for debug (only to be used in regtest):\n"
" [--debug-float yes] : turns on the single precision version (to check float interface)\n"
" [--debug-dd yes] : use a fake domain decomposition\n"
" [--debug-pd yes] : use a fake particle decomposition\n"
);
return 0;
}
// Are we reading trajectory data
bool noatoms; parseFlag("--noatoms",noatoms);
bool parseOnly; parseFlag("--parse-only",parseOnly);
std::string full_outputfile; parse("--shortcut-ofile",full_outputfile);
bool restart; parseFlag("--restart",restart);
std::string fakein;
bool debug_float=false;
fakein="";
if(parse("--debug-float",fakein)) {
if(fakein=="yes") debug_float=true;
else if(fakein=="no") debug_float=false;
else error("--debug-float should have argument yes or no");
}
if(debug_float && sizeof(real)!=sizeof(float)) {
auto cl=cltoolRegister().create(CLToolOptions("driver-float"));
cl->setInputData(this->getInputData());
int ret=cl->main(in,out,pc);
return ret;
}
bool debug_pd=false;
fakein="";
if(parse("--debug-pd",fakein)) {
if(fakein=="yes") debug_pd=true;
else if(fakein=="no") debug_pd=false;
else error("--debug-pd should have argument yes or no");
}
if(debug_pd) std::fprintf(out,"DEBUGGING PARTICLE DECOMPOSITION\n");
bool debug_dd=false;
fakein="";
if(parse("--debug-dd",fakein)) {
if(fakein=="yes") debug_dd=true;
else if(fakein=="no") debug_dd=false;
else error("--debug-dd should have argument yes or no");
}
if(debug_dd) std::fprintf(out,"DEBUGGING DOMAIN DECOMPOSITION\n");
if( debug_pd || debug_dd ) {
if(noatoms) error("cannot debug without atoms");
}
// set up for multi replica driver:
int multi=0;
parse("--multi",multi);
Communicator intracomm;
Communicator intercomm;
if(multi) {
int ntot=pc.Get_size();
int nintra=ntot/multi;
if(multi*nintra!=ntot) error("invalid number of processes for multi environment");
pc.Split(pc.Get_rank()/nintra,pc.Get_rank(),intracomm);
pc.Split(pc.Get_rank()%nintra,pc.Get_rank(),intercomm);
} else {
intracomm.Set_comm(pc.Get_comm());
}
// set up for debug replica exchange:
bool debug_grex=parse("--debug-grex",fakein);
int grex_stride=0;
FILE*grex_log=NULL;
// call fclose when fp goes out of scope
auto deleter=[](auto f) { if(f) std::fclose(f); };
std::unique_ptr<FILE,decltype(deleter)> grex_log_deleter(grex_log,deleter);
if(debug_grex) {
if(noatoms) error("must have atoms to debug_grex");
if(multi<2) error("--debug_grex needs --multi with at least two replicas");
Tools::convert(fakein,grex_stride);
std::string n; Tools::convert(intercomm.Get_rank(),n);
std::string file;
parse("--debug-grex-log",file);
if(file.length()>0) {
file+="."+n;
grex_log=std::fopen(file.c_str(),"w");
grex_log_deleter.reset(grex_log);
}
}
// Read the plumed input file name
std::string plumedFile; parse("--plumed",plumedFile);
// the timestep
double t; parse("--timestep",t);
real timestep=real(t);
// the stride
unsigned stride; parse("--trajectory-stride",stride);
// are we writing forces
std::string dumpforces(""), debugforces(""), dumpforcesFmt("%f");;
bool dumpfullvirial=false;
if(!noatoms) {
parse("--dump-forces",dumpforces);
parse("--debug-forces",debugforces);
}
if(dumpforces!="" || debugforces!="" ) parse("--dump-forces-fmt",dumpforcesFmt);
if(dumpforces!="") parseFlag("--dump-full-virial",dumpfullvirial);
if( debugforces!="" && (debug_dd || debug_pd) ) error("cannot debug forces and domain/particle decomposition at same time");
if( debugforces!="" && sizeof(real)!=sizeof(double) ) error("cannot debug forces in single precision mode");
real kt=-1.0;
parse("--kt",kt);
std::string trajectory_fmt;
bool use_molfile=false;
molfile_plugin_t *api=NULL;
// Read in an xyz file
std::string trajectoryFile(""), pdbfile(""), mcfile("");
bool pbc_cli_given=false; std::vector<double> pbc_cli_box(9,0.0);
int command_line_natoms=-1;
if(!noatoms) {
std::string traj_xyz; parse("--ixyz",traj_xyz);
std::string traj_gro; parse("--igro",traj_gro);
std::string traj_dlp4; parse("--idlp4",traj_dlp4);
std::string traj_xtc;
std::string traj_trr;
parse("--ixtc",traj_xtc);
parse("--itrr",traj_trr);
#ifdef __PLUMED_HAS_MOLFILE_PLUGINS
for(unsigned i=0; i<plugins.size(); i++) {
std::string molfile_key="--mf_"+std::string(plugins[i]->name);
std::string traj_molfile;
parse(molfile_key,traj_molfile);
if(traj_molfile.length()>0) {
std::fprintf(out,"\nDRIVER: Found molfile format trajectory %s with name %s\n",plugins[i]->name,traj_molfile.c_str());
trajectoryFile=traj_molfile;
trajectory_fmt=std::string(plugins[i]->name);
use_molfile=true;
api = plugins[i];
}
}
#endif
{ // check that only one fmt is specified
int nn=0;
if(traj_xyz.length()>0) nn++;
if(traj_gro.length()>0) nn++;
if(traj_dlp4.length()>0) nn++;
if(traj_xtc.length()>0) nn++;
if(traj_trr.length()>0) nn++;
if(nn>1) {
std::fprintf(stderr,"ERROR: cannot provide more than one trajectory file\n");
return 1;
}
}
if(traj_xyz.length()>0 && trajectoryFile.length()==0) {
trajectoryFile=traj_xyz;
trajectory_fmt="xyz";
}
if(traj_gro.length()>0 && trajectoryFile.length()==0) {
trajectoryFile=traj_gro;
trajectory_fmt="gro";
}
if(traj_dlp4.length()>0 && trajectoryFile.length()==0) {
trajectoryFile=traj_dlp4;
trajectory_fmt="dlp4";
}
if(traj_xtc.length()>0 && trajectoryFile.length()==0) {
trajectoryFile=traj_xtc;
trajectory_fmt="xdr-xtc";
}
if(traj_trr.length()>0 && trajectoryFile.length()==0) {
trajectoryFile=traj_trr;
trajectory_fmt="xdr-trr";
}
if(trajectoryFile.length()==0&&!parseOnly) {
std::fprintf(stderr,"ERROR: missing trajectory data\n");
return 1;
}
std::string lengthUnits(""); parse("--length-units",lengthUnits);
if(lengthUnits.length()>0) units.setLength(lengthUnits);
std::string chargeUnits(""); parse("--charge-units",chargeUnits);
if(chargeUnits.length()>0) units.setCharge(chargeUnits);
std::string massUnits(""); parse("--mass-units",massUnits);
if(massUnits.length()>0) units.setMass(massUnits);
parse("--pdb",pdbfile);
if(pdbfile.length()>0) {
bool check=pdb.read(pdbfile,false,1.0);
if(!check) error("error reading pdb file");
}
parse("--mc",mcfile);
std::string pbc_cli_list; parse("--box",pbc_cli_list);
if(pbc_cli_list.length()>0) {
pbc_cli_given=true;
std::vector<std::string> words=Tools::getWords(pbc_cli_list,",");
if(words.size()==3) {
for(int i=0; i<3; i++) std::sscanf(words[i].c_str(),"%100lf",&(pbc_cli_box[4*i]));
} else if(words.size()==9) {
for(int i=0; i<9; i++) std::sscanf(words[i].c_str(),"%100lf",&(pbc_cli_box[i]));
} else {
std::string msg="ERROR: cannot parse command-line box "+pbc_cli_list;
std::fprintf(stderr,"%s\n",msg.c_str());
return 1;
}
}
parse("--natoms",command_line_natoms);
}
#ifdef __PLUMED_HAS_MOLFILE_PLUGINS
auto mf_deleter=[api](void* h_in) {
if(h_in) {
std::unique_ptr<std::lock_guard<std::mutex>> lck;
if(api->is_reentrant==VMDPLUGIN_THREADUNSAFE) lck=Tools::molfile_lock();
api->close_file_read(h_in);
}
};
void *h_in=NULL;
std::unique_ptr<void,decltype(mf_deleter)> h_in_deleter(h_in,mf_deleter);
molfile_timestep_t ts_in; // this is the structure that has the timestep
// a std::vector<float> with the same scope as ts_in
// it is necessary in order to store the pointer to ts_in.coords
std::vector<float> ts_in_coords;
ts_in.coords=ts_in_coords.data();
ts_in.velocities=NULL;
ts_in.A=-1; // we use this to check whether cell is provided or not
#endif
if(debug_dd && debug_pd) error("cannot use debug-dd and debug-pd at the same time");
if(debug_pd || debug_dd) {
if( !Communicator::initialized() ) error("needs mpi for debug-pd");
}
PlumedMain p; if( parseOnly ) p.activateParseOnlyMode();
p.cmd("setRealPrecision",(int)sizeof(real));
int checknatoms=-1;
long long int step=0;
parse("--initial-step",step);
if(restart) p.cmd("setRestart",1);
if(Communicator::initialized()) {
if(multi) {
if(intracomm.Get_rank()==0) p.cmd("GREX setMPIIntercomm",&intercomm.Get_comm());
p.cmd("GREX setMPIIntracomm",&intracomm.Get_comm());
p.cmd("GREX init");
}
p.cmd("setMPIComm",&intracomm.Get_comm());
}
p.cmd("setMDLengthUnits",units.getLength());
p.cmd("setMDChargeUnits",units.getCharge());
p.cmd("setMDMassUnits",units.getMass());
p.cmd("setMDEngine","driver");
p.cmd("setTimestep",timestep);
if( !parseOnly || full_outputfile.length()==0 ) p.cmd("setPlumedDat",plumedFile.c_str());
p.cmd("setLog",out);
int natoms;
int lvl=0;
int pb=1;
if(parseOnly) {
if(command_line_natoms<0) error("--parseOnly requires setting the number of atoms with --natoms");
natoms=command_line_natoms;
}
FILE* fp=NULL; FILE* fp_forces=NULL; OFile fp_dforces;
std::unique_ptr<FILE,decltype(deleter)> fp_deleter(fp,deleter);
std::unique_ptr<FILE,decltype(deleter)> fp_forces_deleter(fp_forces,deleter);
auto xdr_deleter=[](auto xd) { if(xd) xdrfile::xdrfile_close(xd); };
xdrfile::XDRFILE* xd=NULL;
std::unique_ptr<xdrfile::XDRFILE,decltype(xdr_deleter)> xd_deleter(xd,xdr_deleter);
if(!noatoms&&!parseOnly) {
if (trajectoryFile=="-")
fp=in;
else {
if(multi) {
std::string n;
Tools::convert(intercomm.Get_rank(),n);
std::string testfile=FileBase::appendSuffix(trajectoryFile,"."+n);
FILE* tmp_fp=std::fopen(testfile.c_str(),"r");
// no exceptions here
if(tmp_fp) { std::fclose(tmp_fp); trajectoryFile=testfile;}
}
if(use_molfile==true) {
#ifdef __PLUMED_HAS_MOLFILE_PLUGINS
std::unique_ptr<std::lock_guard<std::mutex>> lck;
if(api->is_reentrant==VMDPLUGIN_THREADUNSAFE) lck=Tools::molfile_lock();
h_in = api->open_file_read(trajectoryFile.c_str(), trajectory_fmt.c_str(), &natoms);
h_in_deleter.reset(h_in);
if(natoms==MOLFILE_NUMATOMS_UNKNOWN) {
if(command_line_natoms>=0) natoms=command_line_natoms;
else error("this file format does not provide number of atoms; use --natoms on the command line");
}
ts_in_coords.resize(3*natoms);
ts_in.coords = ts_in_coords.data();
#endif
} else if(trajectory_fmt=="xdr-xtc" || trajectory_fmt=="xdr-trr") {
xd=xdrfile::xdrfile_open(trajectoryFile.c_str(),"r");
xd_deleter.reset(xd);
if(!xd) {
std::string msg="ERROR: Error opening trajectory file "+trajectoryFile;
std::fprintf(stderr,"%s\n",msg.c_str());
return 1;
}
if(trajectory_fmt=="xdr-xtc") xdrfile::read_xtc_natoms(&trajectoryFile[0],&natoms);
if(trajectory_fmt=="xdr-trr") xdrfile::read_trr_natoms(&trajectoryFile[0],&natoms);
} else {
fp=std::fopen(trajectoryFile.c_str(),"r");
fp_deleter.reset(fp);
if(!fp) {
std::string msg="ERROR: Error opening trajectory file "+trajectoryFile;
std::fprintf(stderr,"%s\n",msg.c_str());
return 1;
}
}
}
if(dumpforces.length()>0) {
if(Communicator::initialized() && pc.Get_size()>1) {
std::string n;
Tools::convert(pc.Get_rank(),n);
dumpforces+="."+n;
}
fp_forces=std::fopen(dumpforces.c_str(),"w");
fp_forces_deleter.reset(fp_forces);
}
if(debugforces.length()>0) {
if(Communicator::initialized() && pc.Get_size()>1) {
std::string n;
Tools::convert(pc.Get_rank(),n);
debugforces+="."+n;
}
fp_dforces.open(debugforces);
}
}
std::string line;
std::vector<real> coordinates;
std::vector<real> forces;
std::vector<real> masses;
std::vector<real> charges;
std::vector<real> cell;
std::vector<real> virial;
std::vector<real> numder;
// variables to test particle decomposition
int pd_nlocal=0;
int pd_start=0;
// variables to test random decomposition (=domain decomposition)
std::vector<int> dd_gatindex;
std::vector<int> dd_g2l;
std::vector<real> dd_masses;
std::vector<real> dd_charges;
std::vector<real> dd_forces;
std::vector<real> dd_coordinates;
int dd_nlocal=0;
// random stream to choose decompositions
Random rnd;
if(trajectory_fmt=="dlp4") {
if(!Tools::getline(fp,line)) error("error reading title");
if(!Tools::getline(fp,line)) error("error reading atoms");
std::sscanf(line.c_str(),"%d %d %d",&lvl,&pb,&natoms);
}
bool lstep=true;
while(true) {
if(!noatoms&&!parseOnly) {
if(use_molfile==true) {
#ifdef __PLUMED_HAS_MOLFILE_PLUGINS
std::unique_ptr<std::lock_guard<std::mutex>> lck;
if(api->is_reentrant==VMDPLUGIN_THREADUNSAFE) lck=Tools::molfile_lock();
int rc;
rc = api->read_next_timestep(h_in, natoms, &ts_in);
if(rc==MOLFILE_EOF) {
break;
}
#endif
} else if(trajectory_fmt=="xyz" || trajectory_fmt=="gro" || trajectory_fmt=="dlp4") {
if(!Tools::getline(fp,line)) break;
}
}
bool first_step=false;
if(!noatoms&&!parseOnly) {
if(use_molfile==false && (trajectory_fmt=="xyz" || trajectory_fmt=="gro")) {
if(trajectory_fmt=="gro") if(!Tools::getline(fp,line)) error("premature end of trajectory file");
std::sscanf(line.c_str(),"%100d",&natoms);
}
if(use_molfile==false && trajectory_fmt=="dlp4") {
char xa[9];
int xb,xc,xd;
double t;
std::sscanf(line.c_str(),"%8s %lld %d %d %d %lf",xa,&step,&xb,&xc,&xd,&t);
if (lstep) {
p.cmd("setTimestep",real(t));
lstep = false;
}
}
}
if(checknatoms<0 && !noatoms) {
pd_nlocal=natoms;
pd_start=0;
first_step=true;
masses.assign(natoms,std::numeric_limits<real>::quiet_NaN());
charges.assign(natoms,std::numeric_limits<real>::quiet_NaN());
//case pdb: structure
if(pdbfile.length()>0) {
for(unsigned i=0; i<pdb.size(); ++i) {
AtomNumber an=pdb.getAtomNumbers()[i];
unsigned index=an.index();
if( index>=unsigned(natoms) ) error("atom index in pdb exceeds the number of atoms in trajectory");
masses[index]=pdb.getOccupancy()[i];
charges[index]=pdb.getBeta()[i];
}
}
if(mcfile.length()>0) {
IFile ifile;
ifile.open(mcfile);
int index; double mass; double charge;
while(ifile.scanField("index",index).scanField("mass",mass).scanField("charge",charge).scanField()) {
masses[index]=mass;
charges[index]=charge;
}
}
} else if( checknatoms<0 && noatoms ) {
natoms=0;
}
if( checknatoms<0 ) {
if(kt>=0) {
p.cmd("setKbT",kt);
}
checknatoms=natoms;
p.cmd("setNatoms",natoms);
p.cmd("init");
// Check if we have been asked to output the long version of the input and if there are shortcuts
if( parseOnly && full_outputfile.length()>0 ) {
// Read in the plumed input file and store what is in there
std::map<std::string,std::vector<std::string> > data;
IFile ifile; ifile.open(plumedFile); std::vector<std::string> words;
while( Tools::getParsedLine(ifile,words) && !p.getEndPlumed() ) {
p.readInputWords(words,false);
Action* aa=p.getActionSet()[p.getActionSet().size()-1].get();
plumed_assert(aa); // needed for following calls, see #1046
ActionWithValue* av=aa->castToActionWithValue();
if( av && aa->getDefaultString().length()>0 ) {
std::vector<std::string> def; def.push_back( "defaults " + aa->getDefaultString() );
data[ aa->getLabel() ] = def;
}
ActionShortcut* as=aa->castToActionShortcut();
if( as ) {
if( aa->getDefaultString().length()>0 ) {
std::vector<std::string> def; def.push_back( "defaults " + aa->getDefaultString() );
data[ as->getShortcutLabel() ] = def;
}
if( data.find( as->getShortcutLabel() )!=data.end() ) {
std::vector<std::string> shortcut_commands = as->getSavedInputLines();
for(unsigned i=0; i<shortcut_commands.size(); ++i) data[ as->getShortcutLabel() ].push_back( shortcut_commands[i] );
} else data[ as->getShortcutLabel() ] = as->getSavedInputLines();
}
}
ifile.close();
// Only output the full version of the input file if there are shortcuts
if( data.size()>0 ) {
OFile long_file; long_file.open( full_outputfile ); long_file.printf("{\n"); bool firstpass=true;
for(auto& x : data ) {
if( !firstpass ) long_file.printf(" },\n");
long_file.printf(" \"%s\" : {\n", x.first.c_str() );
plumed_assert( x.second.size()>0 ); unsigned sstart=0;
if( x.second[0].find("defaults")!=std::string::npos ) {
sstart=1; long_file.printf(" \"defaults\" : \"%s\"", x.second[0].substr( 9 ).c_str() );
if( x.second.size()>1 ) long_file.printf(",\n"); else long_file.printf("\n");
}
if( x.second.size()>sstart ) {
long_file.printf(" \"expansion\" : \"%s", x.second[sstart].c_str() );
for(unsigned j=sstart+1; j<x.second.size(); ++j) long_file.printf("\\n%s", x.second[j].c_str() );
long_file.printf("\"\n");
}
firstpass=false;
}
long_file.printf(" }\n}\n"); long_file.close();
}
}
if(parseOnly) break;
}
if(checknatoms!=natoms) {
std::string stepstr; Tools::convert(step,stepstr);
error("number of atoms in frame " + stepstr + " does not match number of atoms in first frame");
}
coordinates.assign(3*natoms,real(0.0));
forces.assign(3*natoms,real(0.0));
cell.assign(9,real(0.0));
virial.assign(9,real(0.0));
if( first_step || rnd.U01()>0.5) {
if(debug_pd) {
int npe=intracomm.Get_size();
std::vector<int> loc(npe,0);
std::vector<int> start(npe,0);
for(int i=0; i<npe-1; i++) {
int cc=(natoms*2*rnd.U01())/npe;
if(start[i]+cc>natoms) cc=natoms-start[i];
loc[i]=cc;
start[i+1]=start[i]+loc[i];
}
loc[npe-1]=natoms-start[npe-1];
intracomm.Bcast(loc,0);
intracomm.Bcast(start,0);
pd_nlocal=loc[intracomm.Get_rank()];
pd_start=start[intracomm.Get_rank()];
if(intracomm.Get_rank()==0) {
std::fprintf(out,"\nDRIVER: Reassigning particle decomposition\n");
std::fprintf(out,"DRIVER: "); for(int i=0; i<npe; i++) std::fprintf(out,"%d ",loc[i]); printf("\n");
std::fprintf(out,"DRIVER: "); for(int i=0; i<npe; i++) std::fprintf(out,"%d ",start[i]); printf("\n");
}
p.cmd("setAtomsNlocal",pd_nlocal);
p.cmd("setAtomsContiguous",pd_start);
} else if(debug_dd) {
int npe=intracomm.Get_size();
int rank=intracomm.Get_rank();
dd_charges.assign(natoms,0.0);
dd_masses.assign(natoms,0.0);
dd_gatindex.assign(natoms,-1);
dd_g2l.assign(natoms,-1);
dd_coordinates.assign(3*natoms,0.0);
dd_forces.assign(3*natoms,0.0);
dd_nlocal=0;
for(int i=0; i<natoms; ++i) {
double r=rnd.U01()*npe;
int n; for(n=0; n<npe; n++) if(n+1>r)break;
plumed_assert(n<npe);
if(n==rank) {
dd_gatindex[dd_nlocal]=i;
dd_g2l[i]=dd_nlocal;
dd_charges[dd_nlocal]=charges[i];
dd_masses[dd_nlocal]=masses[i];
dd_nlocal++;
}
}
if(intracomm.Get_rank()==0) {
std::fprintf(out,"\nDRIVER: Reassigning domain decomposition\n");
}
p.cmd("setAtomsNlocal",dd_nlocal);
p.cmd("setAtomsGatindex",&dd_gatindex[0],dd_nlocal);
}
}
int plumedStopCondition=0;
if(!noatoms) {
if(use_molfile) {
#ifdef __PLUMED_HAS_MOLFILE_PLUGINS
if(pbc_cli_given==false) {
if(ts_in.A>0.0) { // this is negative if molfile does not provide box
// info on the cell: convert using pbcset.tcl from pbctools in vmd distribution
real cosBC=cos(real(ts_in.alpha)*pi/180.);
//double sinBC=std::sin(ts_in.alpha*pi/180.);
real cosAC=std::cos(real(ts_in.beta)*pi/180.);
real cosAB=std::cos(real(ts_in.gamma)*pi/180.);
real sinAB=std::sin(real(ts_in.gamma)*pi/180.);
real Ax=real(ts_in.A);
real Bx=real(ts_in.B)*cosAB;
real By=real(ts_in.B)*sinAB;
real Cx=real(ts_in.C)*cosAC;
real Cy=(real(ts_in.C)*real(ts_in.B)*cosBC-Cx*Bx)/By;
real Cz=std::sqrt(real(ts_in.C)*real(ts_in.C)-Cx*Cx-Cy*Cy);
cell[0]=Ax/10.; cell[1]=0.; cell[2]=0.;
cell[3]=Bx/10.; cell[4]=By/10.; cell[5]=0.;
cell[6]=Cx/10.; cell[7]=Cy/10.; cell[8]=Cz/10.;
} else {
cell[0]=0.0; cell[1]=0.0; cell[2]=0.0;
cell[3]=0.0; cell[4]=0.0; cell[5]=0.0;
cell[6]=0.0; cell[7]=0.0; cell[8]=0.0;
}
} else {
for(unsigned i=0; i<9; i++)cell[i]=pbc_cli_box[i];
}
// info on coords
// the order is xyzxyz...
for(int i=0; i<3*natoms; i++) {
coordinates[i]=real(ts_in.coords[i])/real(10.); //convert to nm
//cerr<<"COOR "<<coordinates[i]<<endl;
}
#endif
} else if(trajectory_fmt=="xdr-xtc" || trajectory_fmt=="xdr-trr") {
int localstep;
float time;
xdrfile::matrix box;
// here we cannot use a std::vector<rvec> since it does not compile.
// we thus use a std::unique_ptr<rvec[]>
auto pos=Tools::make_unique<xdrfile::rvec[]>(natoms);
float prec,lambda;
int ret=xdrfile::exdrOK;
if(trajectory_fmt=="xdr-xtc") ret=xdrfile::read_xtc(xd,natoms,&localstep,&time,box,pos.get(),&prec);
if(trajectory_fmt=="xdr-trr") ret=xdrfile::read_trr(xd,natoms,&localstep,&time,&lambda,box,pos.get(),NULL,NULL);
if(stride==0) step=localstep;
if(ret==xdrfile::exdrENDOFFILE) break;
if(ret!=xdrfile::exdrOK) break;
for(unsigned i=0; i<3; i++) for(unsigned j=0; j<3; j++) cell[3*i+j]=box[i][j];
for(int i=0; i<natoms; i++) for(unsigned j=0; j<3; j++)
coordinates[3*i+j]=real(pos[i][j]);
} else {
if(trajectory_fmt=="xyz") {
if(!Tools::getline(fp,line)) error("premature end of trajectory file");
std::vector<double> celld(9,0.0);
if(pbc_cli_given==false) {
std::vector<std::string> words;
words=Tools::getWords(line);
if(words.size()==3) {
Tools::convert(words[0],celld[0]);
Tools::convert(words[1],celld[4]);
Tools::convert(words[2],celld[8]);
} else if(words.size()==9) {
Tools::convert(words[0],celld[0]);
Tools::convert(words[1],celld[1]);
Tools::convert(words[2],celld[2]);
Tools::convert(words[3],celld[3]);
Tools::convert(words[4],celld[4]);
Tools::convert(words[5],celld[5]);
Tools::convert(words[6],celld[6]);
Tools::convert(words[7],celld[7]);
Tools::convert(words[8],celld[8]);
} else error("needed box in second line of xyz file");
} else { // from command line
celld=pbc_cli_box;
}
for(unsigned i=0; i<9; i++)cell[i]=real(celld[i]);
}
if(trajectory_fmt=="dlp4") {
std::vector<double> celld(9,0.0);
if(pbc_cli_given==false) {
if(!Tools::getline(fp,line)) error("error reading vector a of cell");
std::sscanf(line.c_str(),"%lf %lf %lf",&celld[0],&celld[1],&celld[2]);
if(!Tools::getline(fp,line)) error("error reading vector b of cell");
std::sscanf(line.c_str(),"%lf %lf %lf",&celld[3],&celld[4],&celld[5]);
if(!Tools::getline(fp,line)) error("error reading vector c of cell");
std::sscanf(line.c_str(),"%lf %lf %lf",&celld[6],&celld[7],&celld[8]);
} else {
celld=pbc_cli_box;
}
for(auto i=0; i<9; i++)cell[i]=real(celld[i])*0.1;
}
int ddist=0;
// Read coordinates
for(int i=0; i<natoms; i++) {
bool ok=Tools::getline(fp,line);
if(!ok) error("premature end of trajectory file");
double cc[3];
if(trajectory_fmt=="xyz") {
char dummy[1000];
int ret=std::sscanf(line.c_str(),"%999s %100lf %100lf %100lf",dummy,&cc[0],&cc[1],&cc[2]);
if(ret!=4) error("cannot read line"+line);
} else if(trajectory_fmt=="gro") {
// do the gromacs way
if(!i) {
//
// calculate the distance between dots (as in gromacs gmxlib/confio.c, routine get_w_conf )
//
const char *p1, *p2, *p3;
p1 = std::strchr(line.c_str(), '.');
if (p1 == NULL) error("seems there are no coordinates in the gro file");
p2 = std::strchr(&p1[1], '.');
if (p2 == NULL) error("seems there is only one coordinates in the gro file");
ddist = p2 - p1;
p3 = std::strchr(&p2[1], '.');
if (p3 == NULL)error("seems there are only two coordinates in the gro file");
if (p3 - p2 != ddist)error("not uniform spacing in fields in the gro file");
}
Tools::convert(line.substr(20,ddist),cc[0]);
Tools::convert(line.substr(20+ddist,ddist),cc[1]);
Tools::convert(line.substr(20+ddist+ddist,ddist),cc[2]);
} else if(trajectory_fmt=="dlp4") {
char dummy[9];
int idummy;
double m,c;
std::sscanf(line.c_str(),"%8s %d %lf %lf",dummy,&idummy,&m,&c);
masses[i]=real(m);
charges[i]=real(c);
if(!Tools::getline(fp,line)) error("error reading coordinates");
std::sscanf(line.c_str(),"%lf %lf %lf",&cc[0],&cc[1],&cc[2]);
cc[0]*=0.1;
cc[1]*=0.1;
cc[2]*=0.1;
if(lvl>0) {
if(!Tools::getline(fp,line)) error("error skipping velocities");
}
if(lvl>1) {
if(!Tools::getline(fp,line)) error("error skipping forces");
}
} else plumed_error();
if(!debug_pd || ( i>=pd_start && i<pd_start+pd_nlocal) ) {
coordinates[3*i]=real(cc[0]);
coordinates[3*i+1]=real(cc[1]);
coordinates[3*i+2]=real(cc[2]);
}
}
if(trajectory_fmt=="gro") {
if(!Tools::getline(fp,line)) error("premature end of trajectory file");
std::vector<std::string> words=Tools::getWords(line);
if(words.size()<3) error("cannot understand box format");
Tools::convert(words[0],cell[0]);
Tools::convert(words[1],cell[4]);
Tools::convert(words[2],cell[8]);
if(words.size()>3) Tools::convert(words[3],cell[1]);
if(words.size()>4) Tools::convert(words[4],cell[2]);
if(words.size()>5) Tools::convert(words[5],cell[3]);
if(words.size()>6) Tools::convert(words[6],cell[5]);
if(words.size()>7) Tools::convert(words[7],cell[6]);
if(words.size()>8) Tools::convert(words[8],cell[7]);
}