forked from plumed/plumed2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimize.cpp
3557 lines (3206 loc) · 124 KB
/
minimize.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
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright 1991- The GROMACS Authors
* and the project initiators Erik Lindahl, Berk Hess and David van der Spoel.
* Consult the AUTHORS/COPYING files and https://www.gromacs.org for details.
*
* GROMACS 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 2.1
* of the License, or (at your option) any later version.
*
* GROMACS 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 GROMACS; if not, see
* https://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at https://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out https://www.gromacs.org.
*/
/*! \internal \file
*
* \brief This file defines integrators for energy minimization
*
* \author Berk Hess <[email protected]>
* \author Erik Lindahl <[email protected]>
* \ingroup module_mdrun
*/
#include "gmxpre.h"
#include "config.h"
#include <cmath>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <limits>
#include <vector>
#include "gromacs/commandline/filenm.h"
#include "gromacs/domdec/collect.h"
#include "gromacs/domdec/dlbtiming.h"
#include "gromacs/domdec/domdec.h"
#include "gromacs/domdec/domdec_struct.h"
#include "gromacs/domdec/mdsetup.h"
#include "gromacs/domdec/partition.h"
#include "gromacs/ewald/pme_pp.h"
#include "gromacs/fileio/confio.h"
#include "gromacs/fileio/mtxio.h"
#include "gromacs/gmxlib/network.h"
#include "gromacs/gmxlib/nrnb.h"
#include "gromacs/imd/imd.h"
#include "gromacs/linearalgebra/sparsematrix.h"
#include "gromacs/listed_forces/listed_forces.h"
#include "gromacs/math/functions.h"
#include "gromacs/math/vec.h"
#include "gromacs/mdlib/constr.h"
#include "gromacs/mdlib/coupling.h"
#include "gromacs/mdlib/dispersioncorrection.h"
#include "gromacs/mdlib/ebin.h"
#include "gromacs/mdlib/enerdata_utils.h"
#include "gromacs/mdlib/energyoutput.h"
#include "gromacs/mdlib/force.h"
#include "gromacs/mdlib/force_flags.h"
#include "gromacs/mdlib/forcerec.h"
#include "gromacs/mdlib/gmx_omp_nthreads.h"
#include "gromacs/mdlib/md_support.h"
#include "gromacs/mdlib/mdatoms.h"
#include "gromacs/mdlib/stat.h"
#include "gromacs/mdlib/tgroup.h"
#include "gromacs/mdlib/trajectory_writing.h"
#include "gromacs/mdlib/update.h"
#include "gromacs/mdlib/vsite.h"
#include "gromacs/mdrunutility/handlerestart.h"
#include "gromacs/mdrunutility/multisim.h" /*PLUMED*/
#include "gromacs/mdrunutility/printtime.h"
#include "gromacs/mdtypes/checkpointdata.h"
#include "gromacs/mdtypes/commrec.h"
#include "gromacs/mdtypes/forcebuffers.h"
#include "gromacs/mdtypes/forcerec.h"
#include "gromacs/mdtypes/inputrec.h"
#include "gromacs/mdtypes/interaction_const.h"
#include "gromacs/mdtypes/md_enums.h"
#include "gromacs/mdtypes/mdatom.h"
#include "gromacs/mdtypes/mdrunoptions.h"
#include "gromacs/mdtypes/observablesreducer.h"
#include "gromacs/mdtypes/state.h"
#include "gromacs/pbcutil/pbc.h"
#include "gromacs/timing/wallcycle.h"
#include "gromacs/timing/walltime_accounting.h"
#include "gromacs/topology/mtop_util.h"
#include "gromacs/topology/topology.h"
#include "gromacs/utility/cstringutil.h"
#include "gromacs/utility/exceptions.h"
#include "gromacs/utility/fatalerror.h"
#include "gromacs/utility/logger.h"
#include "gromacs/utility/smalloc.h"
#include "legacysimulator.h"
#include "shellfc.h"
using gmx::ArrayRef;
using gmx::MdrunScheduleWorkload;
using gmx::RVec;
using gmx::VirtualSitesHandler;
/* PLUMED */
#include "../../../Plumed.h"
extern int plumedswitch;
extern plumed plumedmain;
/* END PLUMED */
//! Utility structure for manipulating states during EM
typedef struct em_state
{
//! Copy of the global state
t_state s;
//! Force array
gmx::ForceBuffers f;
//! Potential energy
real epot;
//! Norm of the force
real fnorm;
//! Maximum force
real fmax;
//! Direction
int a_fmax;
} em_state_t;
//! Print the EM starting conditions
static void print_em_start(FILE* fplog,
const t_commrec* cr,
gmx_walltime_accounting_t walltime_accounting,
gmx_wallcycle* wcycle,
const char* name)
{
walltime_accounting_start_time(walltime_accounting);
wallcycle_start(wcycle, WallCycleCounter::Run);
print_start(fplog, cr, walltime_accounting, name);
}
//! Stop counting time for EM
static void em_time_end(gmx_walltime_accounting_t walltime_accounting, gmx_wallcycle* wcycle)
{
wallcycle_stop(wcycle, WallCycleCounter::Run);
walltime_accounting_end_time(walltime_accounting);
}
//! Printing a log file and console header
static void sp_header(FILE* out, const char* minimizer, real ftol, int nsteps)
{
fprintf(out, "\n");
fprintf(out, "%s:\n", minimizer);
fprintf(out, " Tolerance (Fmax) = %12.5e\n", ftol);
fprintf(out, " Number of steps = %12d\n", nsteps);
}
//! Print warning message
static void warn_step(FILE* fp, real ftol, real fmax, gmx_bool bLastStep, gmx_bool bConstrain)
{
constexpr bool realIsDouble = GMX_DOUBLE;
char buffer[2048];
if (!std::isfinite(fmax))
{
sprintf(buffer,
"\nEnergy minimization has stopped because the force "
"on at least one atom is not finite. This usually means "
"atoms are overlapping. Modify the input coordinates to "
"remove atom overlap or use soft-core potentials with "
"the free energy code to avoid infinite forces.\n%s",
!realIsDouble ? "You could also be lucky that switching to double precision "
"is sufficient to obtain finite forces.\n"
: "");
}
else if (bLastStep)
{
sprintf(buffer,
"\nEnergy minimization reached the maximum number "
"of steps before the forces reached the requested "
"precision Fmax < %g.\n",
ftol);
}
else
{
sprintf(buffer,
"\nEnergy minimization has stopped, but the forces have "
"not converged to the requested precision Fmax < %g (which "
"may not be possible for your system). It stopped "
"because the algorithm tried to make a new step whose size "
"was too small, or there was no change in the energy since "
"last step. Either way, we regard the minimization as "
"converged to within the available machine precision, "
"given your starting configuration and EM parameters.\n%s%s",
ftol,
!realIsDouble ? "\nDouble precision normally gives you higher accuracy, but "
"this is often not needed for preparing to run molecular "
"dynamics.\n"
: "",
bConstrain ? "You might need to increase your constraint accuracy, or turn\n"
"off constraints altogether (set constraints = none in mdp file)\n"
: "");
}
fputs(wrap_lines(buffer, 78, 0, FALSE), stderr);
fputs(wrap_lines(buffer, 78, 0, FALSE), fp);
}
//! Print message about convergence of the EM
static void print_converged(FILE* fp,
const char* alg,
real ftol,
int64_t count,
gmx_bool bDone,
int64_t nsteps,
const em_state_t* ems,
double sqrtNumAtoms)
{
char buf[STEPSTRSIZE];
if (bDone)
{
fprintf(fp, "\n%s converged to Fmax < %g in %s steps\n", alg, ftol, gmx_step_str(count, buf));
}
else if (count < nsteps)
{
fprintf(fp,
"\n%s converged to machine precision in %s steps,\n"
"but did not reach the requested Fmax < %g.\n",
alg,
gmx_step_str(count, buf),
ftol);
}
else
{
fprintf(fp, "\n%s did not converge to Fmax < %g in %s steps.\n", alg, ftol, gmx_step_str(count, buf));
}
#if GMX_DOUBLE
fprintf(fp, "Potential Energy = %21.14e\n", ems->epot);
fprintf(fp, "Maximum force = %21.14e on atom %d\n", ems->fmax, ems->a_fmax + 1);
fprintf(fp, "Norm of force = %21.14e\n", ems->fnorm / sqrtNumAtoms);
#else
fprintf(fp, "Potential Energy = %14.7e\n", ems->epot);
fprintf(fp, "Maximum force = %14.7e on atom %d\n", ems->fmax, ems->a_fmax + 1);
fprintf(fp, "Norm of force = %14.7e\n", ems->fnorm / sqrtNumAtoms);
#endif
}
//! Compute the norm and max of the force array in parallel
static void get_f_norm_max(const t_commrec* cr,
const t_grpopts* opts,
t_mdatoms* mdatoms,
gmx::ArrayRef<const gmx::RVec> f,
real* fnorm,
real* fmax,
int* a_fmax)
{
double fnorm2, *sum;
real fmax2, fam;
int la_max, a_max, start, end, i, m, gf;
/* This routine finds the largest force and returns it.
* On parallel machines the global max is taken.
*/
fnorm2 = 0;
fmax2 = 0;
la_max = -1;
start = 0;
end = mdatoms->homenr;
if (!mdatoms->cFREEZE.empty())
{
for (i = start; i < end; i++)
{
gf = mdatoms->cFREEZE[i];
fam = 0;
for (m = 0; m < DIM; m++)
{
if (!opts->nFreeze[gf][m])
{
fam += gmx::square(f[i][m]);
}
}
fnorm2 += fam;
if (fam > fmax2)
{
fmax2 = fam;
la_max = i;
}
}
}
else
{
for (i = start; i < end; i++)
{
fam = norm2(f[i]);
fnorm2 += fam;
if (fam > fmax2)
{
fmax2 = fam;
la_max = i;
}
}
}
if (la_max >= 0 && haveDDAtomOrdering(*cr))
{
a_max = cr->dd->globalAtomIndices[la_max];
}
else
{
a_max = la_max;
}
if (PAR(cr))
{
snew(sum, 2 * cr->nnodes + 1);
sum[2 * cr->nodeid] = fmax2;
sum[2 * cr->nodeid + 1] = a_max;
sum[2 * cr->nnodes] = fnorm2;
gmx_sumd(2 * cr->nnodes + 1, sum, cr);
fnorm2 = sum[2 * cr->nnodes];
/* Determine the global maximum */
for (i = 0; i < cr->nnodes; i++)
{
if (sum[2 * i] > fmax2)
{
fmax2 = sum[2 * i];
a_max = gmx::roundToInt(sum[2 * i + 1]);
}
}
sfree(sum);
}
if (fnorm)
{
*fnorm = sqrt(fnorm2);
}
if (fmax)
{
*fmax = sqrt(fmax2);
}
if (a_fmax)
{
*a_fmax = a_max;
}
}
//! Compute the norm of the force
static void get_state_f_norm_max(const t_commrec* cr, const t_grpopts* opts, t_mdatoms* mdatoms, em_state_t* ems)
{
get_f_norm_max(cr, opts, mdatoms, ems->f.view().force(), &ems->fnorm, &ems->fmax, &ems->a_fmax);
}
//! Initialize the energy minimization
static void init_em(FILE* fplog,
const gmx::MDLogger& mdlog,
const char* title,
const t_commrec* cr,
const gmx_multisim_t *ms, /* PLUMED */
const t_inputrec* ir,
gmx::ImdSession* imdSession,
pull_t* pull_work,
t_state* state_global,
const gmx_mtop_t& top_global,
em_state_t* ems,
gmx_localtop_t* top,
t_nrnb* nrnb,
t_forcerec* fr,
gmx::MDAtoms* mdAtoms,
gmx_global_stat_t* gstat,
VirtualSitesHandler* vsite,
gmx::Constraints* constr,
gmx_shellfc_t** shellfc)
{
real dvdl_constr;
if (fplog)
{
fprintf(fplog, "Initiating %s\n", title);
}
if (MAIN(cr))
{
state_global->ngtc = 0;
}
int* fep_state = MAIN(cr) ? &state_global->fep_state : nullptr;
gmx::ArrayRef<real> lambda = MAIN(cr) ? state_global->lambda : gmx::ArrayRef<real>();
initialize_lambdas(
fplog, ir->efep, ir->bSimTemp, *ir->fepvals, ir->simtempvals->temperatures, nullptr, MAIN(cr), fep_state, lambda);
if (ir->eI == IntegrationAlgorithm::NM)
{
GMX_ASSERT(shellfc != nullptr, "With NM we always support shells");
*shellfc = init_shell_flexcon(stdout,
top_global,
constr ? constr->numFlexibleConstraints() : 0,
ir->nstcalcenergy,
haveDDAtomOrdering(*cr),
thisRankHasDuty(cr, DUTY_PME));
}
else
{
GMX_ASSERT(EI_ENERGY_MINIMIZATION(ir->eI),
"This else currently only handles energy minimizers, consider if your algorithm "
"needs shell/flexible-constraint support");
/* With energy minimization, shells and flexible constraints are
* automatically minimized when treated like normal DOFS.
*/
if (shellfc != nullptr)
{
*shellfc = nullptr;
}
}
if (haveDDAtomOrdering(*cr))
{
// Local state only becomes valid now.
dd_init_local_state(*cr->dd, state_global, &ems->s);
/* Distribute the charge groups over the nodes from the main node */
dd_partition_system(fplog,
mdlog,
ir->init_step,
cr,
TRUE,
state_global,
top_global,
*ir,
imdSession,
pull_work,
&ems->s,
&ems->f,
mdAtoms,
top,
fr,
vsite,
constr,
nrnb,
nullptr,
FALSE);
dd_store_state(*cr->dd, &ems->s);
}
else
{
state_change_natoms(state_global, state_global->natoms);
/* Just copy the state */
ems->s = *state_global;
state_change_natoms(&ems->s, ems->s.natoms);
mdAlgorithmsSetupAtomData(
cr, *ir, top_global, top, fr, &ems->f, mdAtoms, constr, vsite, shellfc ? *shellfc : nullptr);
}
update_mdatoms(mdAtoms->mdatoms(), ems->s.lambda[FreeEnergyPerturbationCouplingType::Mass]);
if (constr)
{
// TODO how should this cross-module support dependency be managed?
if (ir->eConstrAlg == ConstraintAlgorithm::Shake && gmx_mtop_ftype_count(top_global, F_CONSTR) > 0)
{
gmx_fatal(FARGS,
"Can not do energy minimization with %s, use %s\n",
enumValueToString(ConstraintAlgorithm::Shake),
enumValueToString(ConstraintAlgorithm::Lincs));
}
if (!ir->bContinuation)
{
/* Constrain the starting coordinates */
bool needsLogging = true;
bool computeEnergy = true;
bool computeVirial = false;
dvdl_constr = 0;
constr->apply(needsLogging,
computeEnergy,
-1,
0,
1.0,
ems->s.x.arrayRefWithPadding(),
ems->s.x.arrayRefWithPadding(),
ArrayRef<RVec>(),
ems->s.box,
ems->s.lambda[FreeEnergyPerturbationCouplingType::Fep],
&dvdl_constr,
gmx::ArrayRefWithPadding<RVec>(),
computeVirial,
nullptr,
gmx::ConstraintVariable::Positions);
}
}
if (PAR(cr))
{
*gstat = global_stat_init(ir);
}
else
{
*gstat = nullptr;
}
calc_shifts(ems->s.box, fr->shift_vec);
/* PLUMED */
if(plumedswitch){
if(isMultiSim(ms)) {
if(MAIN(cr)) plumed_cmd(plumedmain,"GREX setMPIIntercomm",&ms->mainRanksComm_);
if(PAR(cr)){
if(haveDDAtomOrdering(*cr)) {
plumed_cmd(plumedmain,"GREX setMPIIntracomm",&cr->dd->mpi_comm_all);
}else{
plumed_cmd(plumedmain,"GREX setMPIIntracomm",&cr->mpi_comm_mysim);
}
}
plumed_cmd(plumedmain,"GREX init",nullptr);
}
if(PAR(cr)){
if(haveDDAtomOrdering(*cr)) {
plumed_cmd(plumedmain,"setMPIComm",&cr->dd->mpi_comm_all);
}else{
plumed_cmd(plumedmain,"setMPIComm",&cr->mpi_comm_mysim);
}
}
plumed_cmd(plumedmain,"setNatoms",top_global.natoms);
plumed_cmd(plumedmain,"setMDEngine","gromacs");
plumed_cmd(plumedmain,"setLog",fplog);
real real_delta_t;
real_delta_t=ir->delta_t;
plumed_cmd(plumedmain,"setTimestep",&real_delta_t);
plumed_cmd(plumedmain,"init",nullptr);
if(haveDDAtomOrdering(*cr)) {
int nat_home = dd_numHomeAtoms(*cr->dd);
plumed_cmd(plumedmain,"setAtomsNlocal",&nat_home);
plumed_cmd(plumedmain,"setAtomsGatindex",cr->dd->globalAtomIndices.data());
}
}
/* END PLUMED */
}
//! Finalize the minimization
static void finish_em(const t_commrec* cr,
gmx_mdoutf_t outf,
gmx_walltime_accounting_t walltime_accounting,
gmx_wallcycle* wcycle)
{
if (!thisRankHasDuty(cr, DUTY_PME))
{
/* Tell the PME only node to finish */
gmx_pme_send_finish(cr);
}
done_mdoutf(outf);
em_time_end(walltime_accounting, wcycle);
}
//! Swap two different EM states during minimization
static void swap_em_state(em_state_t** ems1, em_state_t** ems2)
{
em_state_t* tmp;
tmp = *ems1;
*ems1 = *ems2;
*ems2 = tmp;
}
//! Save the EM trajectory
static void write_em_traj(FILE* fplog,
const t_commrec* cr,
gmx_mdoutf_t outf,
gmx_bool bX,
gmx_bool bF,
const char* confout,
const gmx_mtop_t& top_global,
const t_inputrec* ir,
int64_t step,
em_state_t* state,
t_state* state_global,
ObservablesHistory* observablesHistory)
{
int mdof_flags = 0;
if (bX)
{
mdof_flags |= MDOF_X;
}
if (bF)
{
mdof_flags |= MDOF_F;
}
/* If we want IMD output, set appropriate MDOF flag */
if (ir->bIMD)
{
mdof_flags |= MDOF_IMD;
}
gmx::WriteCheckpointDataHolder checkpointDataHolder;
mdoutf_write_to_trajectory_files(fplog,
cr,
outf,
mdof_flags,
top_global.natoms,
step,
static_cast<double>(step),
&state->s,
state_global,
observablesHistory,
state->f.view().force(),
&checkpointDataHolder);
if (confout != nullptr)
{
if (haveDDAtomOrdering(*cr))
{
/* If bX=true, x was collected to state_global in the call above */
if (!bX)
{
auto globalXRef = MAIN(cr) ? state_global->x : gmx::ArrayRef<gmx::RVec>();
dd_collect_vec(
cr->dd, state->s.ddp_count, state->s.ddp_count_cg_gl, state->s.cg_gl, state->s.x, globalXRef);
}
}
else
{
/* Copy the local state pointer */
state_global = &state->s;
}
if (MAIN(cr))
{
if (ir->pbcType != PbcType::No && !ir->bPeriodicMols && haveDDAtomOrdering(*cr))
{
/* Make molecules whole only for confout writing */
do_pbc_mtop(ir->pbcType, state->s.box, &top_global, state_global->x.rvec_array());
}
write_sto_conf_mtop(confout,
*top_global.name,
top_global,
state_global->x.rvec_array(),
nullptr,
ir->pbcType,
state->s.box);
}
}
}
//! \brief Do one minimization step
//
// \returns true when the step succeeded, false when a constraint error occurred
static bool do_em_step(const t_commrec* cr,
const t_inputrec* ir,
t_mdatoms* md,
em_state_t* ems1,
real a,
gmx::ArrayRefWithPadding<const gmx::RVec> force,
em_state_t* ems2,
gmx::Constraints* constr,
int64_t count)
{
t_state * s1, *s2;
int start, end;
real dvdl_constr;
int nthreads gmx_unused;
bool validStep = true;
s1 = &ems1->s;
s2 = &ems2->s;
if (haveDDAtomOrdering(*cr) && s1->ddp_count != cr->dd->ddp_count)
{
gmx_incons("state mismatch in do_em_step");
}
s2->flags = s1->flags;
if (s2->natoms != s1->natoms)
{
state_change_natoms(s2, s1->natoms);
ems2->f.resize(s2->natoms);
}
if (haveDDAtomOrdering(*cr) && s2->cg_gl.size() != s1->cg_gl.size())
{
s2->cg_gl.resize(s1->cg_gl.size());
}
copy_mat(s1->box, s2->box);
/* Copy free energy state */
s2->lambda = s1->lambda;
copy_mat(s1->box, s2->box);
start = 0;
end = md->homenr;
nthreads = gmx_omp_nthreads_get(ModuleMultiThread::Update);
#pragma omp parallel num_threads(nthreads)
{
const rvec* x1 = s1->x.rvec_array();
rvec* x2 = s2->x.rvec_array();
const rvec* f = as_rvec_array(force.unpaddedArrayRef().data());
int gf = 0;
#pragma omp for schedule(static) nowait
for (int i = start; i < end; i++)
{
try
{
if (!md->cFREEZE.empty())
{
gf = md->cFREEZE[i];
}
for (int m = 0; m < DIM; m++)
{
if (ir->opts.nFreeze[gf][m])
{
x2[i][m] = x1[i][m];
}
else
{
x2[i][m] = x1[i][m] + a * f[i][m];
}
}
}
GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR
}
if (s2->flags & enumValueToBitMask(StateEntry::Cgp))
{
/* Copy the CG p vector */
const rvec* p1 = s1->cg_p.rvec_array();
rvec* p2 = s2->cg_p.rvec_array();
#pragma omp for schedule(static) nowait
for (int i = start; i < end; i++)
{
// Trivial OpenMP block that does not throw
copy_rvec(p1[i], p2[i]);
}
}
if (haveDDAtomOrdering(*cr))
{
/* OpenMP does not supported unsigned loop variables */
#pragma omp for schedule(static) nowait
for (gmx::index i = 0; i < gmx::ssize(s2->cg_gl); i++)
{
s2->cg_gl[i] = s1->cg_gl[i];
}
}
}
// Copy the DD or pair search counters
s2->ddp_count = s1->ddp_count;
s2->ddp_count_cg_gl = s1->ddp_count_cg_gl;
if (constr)
{
dvdl_constr = 0;
validStep = constr->apply(TRUE,
TRUE,
count,
0,
1.0,
s1->x.arrayRefWithPadding(),
s2->x.arrayRefWithPadding(),
ArrayRef<RVec>(),
s2->box,
s2->lambda[FreeEnergyPerturbationCouplingType::Bonded],
&dvdl_constr,
gmx::ArrayRefWithPadding<RVec>(),
false,
nullptr,
gmx::ConstraintVariable::Positions);
if (cr->nnodes > 1)
{
/* This global reduction will affect performance at high
* parallelization, but we can not really avoid it.
* But usually EM is not run at high parallelization.
*/
int reductionBuffer = static_cast<int>(!validStep);
gmx_sumi(1, &reductionBuffer, cr);
validStep = (reductionBuffer == 0);
}
// We should move this check to the different minimizers
if (!validStep && ir->eI != IntegrationAlgorithm::Steep)
{
gmx_fatal(FARGS,
"The coordinates could not be constrained. Minimizer '%s' can not handle "
"constraint failures, use minimizer '%s' before using '%s'.",
enumValueToString(ir->eI),
enumValueToString(IntegrationAlgorithm::Steep),
enumValueToString(ir->eI));
}
}
return validStep;
}
//! Prepare EM for using domain decomposition parallellization
static void em_dd_partition_system(FILE* fplog,
const gmx::MDLogger& mdlog,
int step,
const t_commrec* cr,
const gmx_mtop_t& top_global,
const t_inputrec* ir,
gmx::ImdSession* imdSession,
pull_t* pull_work,
em_state_t* ems,
gmx_localtop_t* top,
gmx::MDAtoms* mdAtoms,
t_forcerec* fr,
VirtualSitesHandler* vsite,
gmx::Constraints* constr,
t_nrnb* nrnb,
gmx_wallcycle* wcycle)
{
/* Repartition the domain decomposition */
dd_partition_system(fplog,
mdlog,
step,
cr,
FALSE,
nullptr,
top_global,
*ir,
imdSession,
pull_work,
&ems->s,
&ems->f,
mdAtoms,
top,
fr,
vsite,
constr,
nrnb,
wcycle,
FALSE);
dd_store_state(*cr->dd, &ems->s);
}
namespace
{
//! Copy coordinates, OpenMP parallelized, from \p refCoords to coords
void setCoordinates(std::vector<RVec>* coords, ArrayRef<const RVec> refCoords)
{
coords->resize(refCoords.size());
const int gmx_unused nthreads = gmx_omp_nthreads_get(ModuleMultiThread::Update);
#pragma omp parallel for num_threads(nthreads) schedule(static)
for (int i = 0; i < ssize(refCoords); i++)
{
(*coords)[i] = refCoords[i];
}
}
//! Returns the maximum difference an atom moved between two coordinate sets, over all ranks
real maxCoordinateDifference(ArrayRef<const RVec> coords1, ArrayRef<const RVec> coords2, MPI_Comm mpiCommMyGroup)
{
GMX_RELEASE_ASSERT(coords1.size() == coords2.size(), "Coordinate counts should match");
real maxDiffSquared = 0;
#ifndef _MSC_VER // Visual Studio has no support for reduction(max)
const int gmx_unused nthreads = gmx_omp_nthreads_get(ModuleMultiThread::Update);
# pragma omp parallel for reduction(max : maxDiffSquared) num_threads(nthreads) schedule(static)
#endif
for (int i = 0; i < ssize(coords1); i++)
{
maxDiffSquared = std::max(maxDiffSquared, gmx::norm2(coords1[i] - coords2[i]));
}
#if GMX_MPI
int numRanks = 1;
if (mpiCommMyGroup != MPI_COMM_NULL)
{
MPI_Comm_size(mpiCommMyGroup, &numRanks);
}
if (numRanks > 1)
{
real maxDiffSquaredReduced;
MPI_Allreduce(
&maxDiffSquared, &maxDiffSquaredReduced, 1, GMX_DOUBLE ? MPI_DOUBLE : MPI_FLOAT, MPI_MAX, mpiCommMyGroup);
maxDiffSquared = maxDiffSquaredReduced;
}
#else
GMX_UNUSED_VALUE(mpiCommMyGroup);
#endif
return std::sqrt(maxDiffSquared);
}
/*! \brief Class to handle the work of setting and doing an energy evaluation.
*
* This class is a mere aggregate of parameters to pass to evaluate an
* energy, so that future changes to names and types of them consume
* less time when refactoring other code.
*
* Aggregate initialization is used, for which the chief risk is that
* if a member is added at the end and not all initializer lists are
* updated, then the member will be value initialized, which will
* typically mean initialization to zero.
*
* Use a braced initializer list to construct one of these. */
class EnergyEvaluator
{
public:
/*! \brief Evaluates an energy on the state in \c ems.
*
* \todo In practice, the same objects mu_tot, vir, and pres
* are always passed to this function, so we would rather have
* them as data members. However, their C-array types are
* unsuited for aggregate initialization. When the types
* improve, the call signature of this method can be reduced.
*/
void run(em_state_t* ems, rvec mu_tot, tensor vir, tensor pres, int64_t count, gmx_bool bFirst, int64_t step);
//! Handles logging (deprecated).
FILE* fplog;
//! Handles logging.
const gmx::MDLogger& mdlog;
//! Handles communication.
const t_commrec* cr;
//! Coordinates multi-simulations.
const gmx_multisim_t* ms;
//! Holds the simulation topology.
const gmx_mtop_t& top_global;
//! Holds the domain topology.
gmx_localtop_t* top;
//! User input options.
const t_inputrec* inputrec;
//! The Interactive Molecular Dynamics session.
gmx::ImdSession* imdSession;
//! The pull work object.
pull_t* pull_work;
//! Manages flop accounting.
t_nrnb* nrnb;
//! Manages wall cycle accounting.
gmx_wallcycle* wcycle;
//! Legacy coordinator of global reduction.
gmx_global_stat_t gstat;
//! Coordinates reduction for observables
gmx::ObservablesReducer* observablesReducer;
//! Handles virtual sites.
VirtualSitesHandler* vsite;
//! Handles constraints.
gmx::Constraints* constr;
//! Per-atom data for this domain.
gmx::MDAtoms* mdAtoms;
//! Handles how to calculate the forces.
t_forcerec* fr;
//! Schedule of force-calculation work each step for this task.
MdrunScheduleWorkload* runScheduleWork;
//! Stores the computed energies.
gmx_enerdata_t* enerd;
//! The DD partitioning count at which the pair list was generated
int ddpCountPairSearch;
//! The local coordinates that were used for pair searching, stored for computing displacements
std::vector<RVec> pairSearchCoordinates;
};
void EnergyEvaluator::run(em_state_t* ems, rvec mu_tot, tensor vir, tensor pres, int64_t count, gmx_bool bFirst, int64_t step)
{
real t;
gmx_bool bNS;
tensor force_vir, shake_vir, ekin;
real dvdl_constr;
real terminate = 0;
/* Set the time to the initial time, the time does not change during EM */
t = inputrec->init_t;
if (vsite)
{
vsite->construct(ems->s.x, {}, ems->s.box, gmx::VSiteOperation::Positions);
}
// Compute the buffer size of the pair list
const real bufferSize = inputrec->rlist - std::max(inputrec->rcoulomb, inputrec->rvdw);