Skip to content
Snippets Groups Projects
minimize.cpp 105 KiB
Newer Older
carlocamilloni's avatar
carlocamilloni committed
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 (c) 1991-2000, University of Groningen, The Netherlands.
 * Copyright (c) 2001-2004, The GROMACS development team.
 * Copyright (c) 2013,2014,2015,2016,2017, by the GROMACS development team, led by
 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
 * and including many others, as listed in the AUTHORS file in the
 * top-level source directory and at http://www.gromacs.org.
 *
 * 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
 * http://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 http://www.gromacs.org.
 *
 * To help us fund GROMACS development, we humbly ask that you cite
 * the research papers on the package. Check out http://www.gromacs.org.
 */
/*! \internal \file
 *
 * \brief This file defines integrators for energy minimization
 *
 * \author Berk Hess <hess@kth.se>
 * \author Erik Lindahl <erik@kth.se>
 * \ingroup module_mdlib
 */
#include "gmxpre.h"

#include "minimize.h"

#include "config.h"

#include <cmath>
#include <cstring>
#include <ctime>

#include <algorithm>
#include <vector>

#include "gromacs/commandline/filenm.h"
#include "gromacs/domdec/domdec.h"
#include "gromacs/domdec/domdec_struct.h"
#include "gromacs/ewald/pme.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/manage-threading.h"
#include "gromacs/math/functions.h"
#include "gromacs/math/vec.h"
#include "gromacs/mdlib/constr.h"
#include "gromacs/mdlib/force.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/mdebin.h"
#include "gromacs/mdlib/mdrun.h"
#include "gromacs/mdlib/mdsetup.h"
#include "gromacs/mdlib/ns.h"
#include "gromacs/mdlib/shellfc.h"
#include "gromacs/mdlib/sim_util.h"
#include "gromacs/mdlib/tgroup.h"
#include "gromacs/mdlib/trajectory_writing.h"
#include "gromacs/mdlib/update.h"
#include "gromacs/mdlib/vsite.h"
#include "gromacs/mdtypes/commrec.h"
#include "gromacs/mdtypes/inputrec.h"
#include "gromacs/mdtypes/md_enums.h"
#include "gromacs/mdtypes/state.h"
#include "gromacs/pbcutil/mshift.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"

/* PLUMED */
#include "../../../Plumed.h"
extern int    plumedswitch;
extern plumed plumedmain;
extern void(*plumedcmd)(plumed,const char*,const void*);
/* END PLUMED */

//! Utility structure for manipulating states during EM
typedef struct {
    //! Copy of the global state
    t_state          s;
    //! Force array
    PaddedRVecVector 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,
                           t_commrec                *cr,
                           gmx_walltime_accounting_t walltime_accounting,
                           gmx_wallcycle_t           wcycle,
                           const char               *name)
{
    walltime_accounting_start(walltime_accounting);
    wallcycle_start(wcycle, ewcRUN);
    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_t           wcycle)
{
    wallcycle_stop(wcycle, ewcRUN);

    walltime_accounting_end(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, gmx_bool bLastStep, gmx_bool bConstrain)
{
    char buffer[2048];
    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,
                sizeof(real) < sizeof(double) ?
                "\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), fp);
}

//! Print message about convergence of the EM
static void print_converged(FILE *fp, const char *alg, real ftol,
                            gmx_int64_t count, gmx_bool bDone, gmx_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(t_commrec *cr,
                           t_grpopts *opts, t_mdatoms *mdatoms, const 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)
    {
        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 && DOMAINDECOMP(cr))
    {
        a_max = cr->dd->gatindex[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 = (int)(sum[2*i+1] + 0.5);
            }
        }
        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(t_commrec *cr,
                                 t_grpopts *opts, t_mdatoms *mdatoms,
                                 em_state_t *ems)
{
    get_f_norm_max(cr, opts, mdatoms, as_rvec_array(ems->f.data()),
                   &ems->fnorm, &ems->fmax, &ems->a_fmax);
}

//! Initialize the energy minimization
static void init_em(FILE *fplog, const char *title,
                    t_commrec *cr, gmx::IMDOutputProvider *outputProvider,
                    t_inputrec *ir,
                    const MdrunOptions &mdrunOptions,
                    t_state *state_global, gmx_mtop_t *top_global,
                    em_state_t *ems, gmx_localtop_t **top,
                    t_nrnb *nrnb, rvec mu_tot,
                    t_forcerec *fr, gmx_enerdata_t **enerd,
                    t_graph **graph, gmx::MDAtoms *mdAtoms, gmx_global_stat_t *gstat,
                    gmx_vsite_t *vsite, gmx_constr_t constr, gmx_shellfc_t **shellfc,
                    int nfile, const t_filenm fnm[],
                    gmx_mdoutf_t *outf, t_mdebin **mdebin,
                    gmx_wallcycle_t wcycle)
{
    real dvdl_constr;

    if (fplog)
    {
        fprintf(fplog, "Initiating %s\n", title);
    }

    if (MASTER(cr))
    {
        state_global->ngtc = 0;

        /* Initialize lambda variables */
        initialize_lambdas(fplog, ir, &(state_global->fep_state), state_global->lambda, nullptr);
    }

    init_nrnb(nrnb);

    /* Interactive molecular dynamics */
    init_IMD(ir, cr, top_global, fplog, 1,
             MASTER(cr) ? as_rvec_array(state_global->x.data()) : nullptr,
             nfile, fnm, nullptr, mdrunOptions);

    if (ir->eI == eiNM)
    {
        GMX_ASSERT(shellfc != nullptr, "With NM we always support shells");

        *shellfc = init_shell_flexcon(stdout,
                                      top_global,
                                      n_flexible_constraints(constr),
                                      ir->nstcalcenergy,
                                      DOMAINDECOMP(cr));
    }
    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;
        }
    }

    auto mdatoms = mdAtoms->mdatoms();
    if (DOMAINDECOMP(cr))
    {
        *top = dd_init_local_top(top_global);

        dd_init_local_state(cr->dd, state_global, &ems->s);

        /* Distribute the charge groups over the nodes from the master node */
        dd_partition_system(fplog, ir->init_step, cr, TRUE, 1,
                            state_global, top_global, ir,
                            &ems->s, &ems->f, mdAtoms, *top,
                            fr, vsite, constr,
                            nrnb, nullptr, FALSE);
        dd_store_state(cr->dd, &ems->s);

        *graph = nullptr;
    }
    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);
        /* We need to allocate one element extra, since we might use
         * (unaligned) 4-wide SIMD loads to access rvec entries.
         */
        ems->f.resize(gmx::paddedRVecVectorSize(ems->s.natoms));

        snew(*top, 1);
        mdAlgorithmsSetupAtomData(cr, ir, top_global, *top, fr,
                                  graph, mdAtoms,
                                  vsite, shellfc ? *shellfc : nullptr);

        if (vsite)
        {
            set_vsite_top(vsite, *top, mdatoms);
        }
    }

    update_mdatoms(mdAtoms->mdatoms(), ems->s.lambda[efptMASS]);

    if (constr)
    {
        if (ir->eConstrAlg == econtSHAKE &&
            gmx_mtop_ftype_count(top_global, F_CONSTR) > 0)
        {
            gmx_fatal(FARGS, "Can not do energy minimization with %s, use %s\n",
                      econstr_names[econtSHAKE], econstr_names[econtLINCS]);
        }

        if (!DOMAINDECOMP(cr))
        {
            set_constraints(constr, *top, ir, mdatoms, cr);
        }

        if (!ir->bContinuation)
        {
            /* Constrain the starting coordinates */
            dvdl_constr = 0;
            constrain(PAR(cr) ? nullptr : fplog, TRUE, TRUE, constr, &(*top)->idef,
                      ir, cr, -1, 0, 1.0, mdatoms,
                      as_rvec_array(ems->s.x.data()),
                      as_rvec_array(ems->s.x.data()),
                      nullptr,
                      fr->bMolPBC, ems->s.box,
                      ems->s.lambda[efptFEP], &dvdl_constr,
                      nullptr, nullptr, nrnb, econqCoord);
        }
    }

    if (PAR(cr))
    {
        *gstat = global_stat_init(ir);
    }
    else
    {
        *gstat = nullptr;
    }

    *outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, ir, top_global, nullptr, wcycle);

    snew(*enerd, 1);
    init_enerdata(top_global->groups.grps[egcENER].nr, ir->fepvals->n_lambda,
                  *enerd);

    if (mdebin != nullptr)
    {
        /* Init bin for energy stuff */
        *mdebin = init_mdebin(mdoutf_get_fp_ene(*outf), top_global, ir, nullptr);
    }

    clear_rvec(mu_tot);
    calc_shifts(ems->s.box, fr->shift_vec);

    /* PLUMED */
    if(plumedswitch){
      if(cr->ms && cr->ms->nsim>1) {
        if(MASTER(cr)) (*plumedcmd) (plumedmain,"GREX setMPIIntercomm",&cr->ms->mpi_comm_masters);
        if(PAR(cr)){
          if(DOMAINDECOMP(cr)) {
            (*plumedcmd) (plumedmain,"GREX setMPIIntracomm",&cr->dd->mpi_comm_all);
          }else{
            (*plumedcmd) (plumedmain,"GREX setMPIIntracomm",&cr->mpi_comm_mysim);
          }
        }
        (*plumedcmd) (plumedmain,"GREX init",NULL);
      }
      if(PAR(cr)){
        if(DOMAINDECOMP(cr)) {
          (*plumedcmd) (plumedmain,"setMPIComm",&cr->dd->mpi_comm_all);
        }else{
          (*plumedcmd) (plumedmain,"setMPIComm",&cr->mpi_comm_mysim);
        }
      }
      (*plumedcmd) (plumedmain,"setNatoms",&top_global->natoms);
      (*plumedcmd) (plumedmain,"setMDEngine","gromacs");
      (*plumedcmd) (plumedmain,"setLog",fplog);
      real real_delta_t;
      real_delta_t=ir->delta_t;
      (*plumedcmd) (plumedmain,"setTimestep",&real_delta_t);
      (*plumedcmd) (plumedmain,"init",NULL);

      if(PAR(cr)){
        if(DOMAINDECOMP(cr)) {
          (*plumedcmd) (plumedmain,"setAtomsNlocal",&cr->dd->nat_home);
          (*plumedcmd) (plumedmain,"setAtomsGatindex",cr->dd->gatindex);
        }
      }
    }
    /* END PLUMED */
}

//! Finalize the minimization
static void finish_em(t_commrec *cr, gmx_mdoutf_t outf,
                      gmx_walltime_accounting_t walltime_accounting,
                      gmx_wallcycle_t 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, t_commrec *cr,
                          gmx_mdoutf_t outf,
                          gmx_bool bX, gmx_bool bF, const char *confout,
                          gmx_mtop_t *top_global,
                          t_inputrec *ir, gmx_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;
    }

    mdoutf_write_to_trajectory_files(fplog, cr, outf, mdof_flags,
                                     top_global, step, (double)step,
                                     &state->s, state_global, observablesHistory,
                                     state->f);

    if (confout != nullptr && MASTER(cr))
    {
        GMX_RELEASE_ASSERT(bX, "The code below assumes that (with domain decomposition), x is collected to state_global in the call above.");
        /* With domain decomposition the call above collected the state->s.x
         * into state_global->x. Without DD we copy the local state pointer.
         */
        if (!DOMAINDECOMP(cr))
        {
            state_global = &state->s;
        }

        if (ir->ePBC != epbcNONE && !ir->bPeriodicMols && DOMAINDECOMP(cr))
        {
            /* Make molecules whole only for confout writing */
            do_pbc_mtop(fplog, ir->ePBC, state->s.box, top_global,
                        as_rvec_array(state_global->x.data()));
        }

        write_sto_conf_mtop(confout,
                            *top_global->name, top_global,
                            as_rvec_array(state_global->x.data()), nullptr, ir->ePBC, 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(t_commrec *cr, t_inputrec *ir, t_mdatoms *md,
                       gmx_bool bMolPBC,
                       em_state_t *ems1, real a, const PaddedRVecVector *force,
                       em_state_t *ems2,
                       gmx_constr_t constr, gmx_localtop_t *top,
                       t_nrnb *nrnb, gmx_wallcycle_t wcycle,
                       gmx_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 (DOMAINDECOMP(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);
        /* We need to allocate one element extra, since we might use
         * (unaligned) 4-wide SIMD loads to access rvec entries.
         */
        ems2->f.resize(gmx::paddedRVecVectorSize(s2->natoms));
    }
    if (DOMAINDECOMP(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;

    // cppcheck-suppress unreadVariable
    nthreads = gmx_omp_nthreads_get(emntUpdate);
#pragma omp parallel num_threads(nthreads)
    {
        const rvec *x1 = as_rvec_array(s1->x.data());
        rvec       *x2 = as_rvec_array(s2->x.data());
        const rvec *f  = as_rvec_array(force->data());

        int         gf = 0;
#pragma omp for schedule(static) nowait
        for (int i = start; i < end; i++)
        {
            try
            {
                if (md->cFREEZE)
                {
                    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 & (1<<estCGP))
        {
            /* Copy the CG p vector */
            const rvec *p1 = as_rvec_array(s1->cg_p.data());
            rvec       *p2 = as_rvec_array(s2->cg_p.data());
#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 (DOMAINDECOMP(cr))
        {
            s2->ddp_count = s1->ddp_count;

            /* OpenMP does not supported unsigned loop variables */
#pragma omp for schedule(static) nowait
            for (int i = 0; i < static_cast<int>(s2->cg_gl.size()); i++)
            {
                s2->cg_gl[i] = s1->cg_gl[i];
            }
            s2->ddp_count_cg_gl = s1->ddp_count_cg_gl;
        }
    }

    if (constr)
    {
        wallcycle_start(wcycle, ewcCONSTR);
        dvdl_constr = 0;
        validStep   =
            constrain(nullptr, TRUE, TRUE, constr, &top->idef,
                      ir, cr, count, 0, 1.0, md,
                      as_rvec_array(s1->x.data()), as_rvec_array(s2->x.data()),
                      nullptr, bMolPBC, s2->box,
                      s2->lambda[efptBONDED], &dvdl_constr,
                      nullptr, nullptr, nrnb, econqCoord);
        wallcycle_stop(wcycle, ewcCONSTR);

        // We should move this check to the different minimizers
        if (!validStep && ir->eI != eiSteep)
        {
            gmx_fatal(FARGS, "The coordinates could not be constrained. Minimizer '%s' can not handle constraint failures, use minimizer '%s' before using '%s'.",
                      EI(ir->eI), EI(eiSteep), EI(ir->eI));
        }
    }

    return validStep;
}

//! Prepare EM for using domain decomposition parallellization
static void em_dd_partition_system(FILE *fplog, int step, t_commrec *cr,
                                   gmx_mtop_t *top_global, t_inputrec *ir,
                                   em_state_t *ems, gmx_localtop_t *top,
                                   gmx::MDAtoms *mdAtoms, t_forcerec *fr,
                                   gmx_vsite_t *vsite, gmx_constr_t constr,
                                   t_nrnb *nrnb, gmx_wallcycle_t wcycle)
{
    /* Repartition the domain decomposition */
    dd_partition_system(fplog, step, cr, FALSE, 1,
                        nullptr, top_global, ir,
                        &ems->s, &ems->f,
                        mdAtoms, top, fr, vsite, constr,
                        nrnb, wcycle, FALSE);
    dd_store_state(cr->dd, &ems->s);
}

//! De one energy evaluation
static void evaluate_energy(FILE *fplog, t_commrec *cr,
                            gmx_mtop_t *top_global,
                            em_state_t *ems, gmx_localtop_t *top,
                            t_inputrec *inputrec,
                            t_nrnb *nrnb, gmx_wallcycle_t wcycle,
                            gmx_global_stat_t gstat,
                            gmx_vsite_t *vsite, gmx_constr_t constr,
                            t_fcdata *fcd,
                            t_graph *graph, gmx::MDAtoms *mdAtoms,
                            t_forcerec *fr, rvec mu_tot,
                            gmx_enerdata_t *enerd, tensor vir, tensor pres,
                            gmx_int64_t count, gmx_bool bFirst)
{
    real     t;
    gmx_bool bNS;
    tensor   force_vir, shake_vir, ekin;
    real     dvdl_constr, prescorr, enercorr, dvdlcorr;
    real     terminate = 0;

    /* Set the time to the initial time, the time does not change during EM */
    t = inputrec->init_t;

    if (bFirst ||
        (DOMAINDECOMP(cr) && ems->s.ddp_count < cr->dd->ddp_count))
    {
        /* This is the first state or an old state used before the last ns */
        bNS = TRUE;
    }
    else
    {
        bNS = FALSE;
        if (inputrec->nstlist > 0)
        {
            bNS = TRUE;
        }
    }

    if (vsite)
    {
        construct_vsites(vsite, as_rvec_array(ems->s.x.data()), 1, nullptr,
                         top->idef.iparams, top->idef.il,
                         fr->ePBC, fr->bMolPBC, cr, ems->s.box);
    }

    if (DOMAINDECOMP(cr) && bNS)
    {
        /* Repartition the domain decomposition */
        em_dd_partition_system(fplog, count, cr, top_global, inputrec,
                               ems, top, mdAtoms, fr, vsite, constr,
                               nrnb, wcycle);
    }

    /* Calc force & energy on new trial position  */
    /* do_force always puts the charge groups in the box and shifts again
     * We do not unshift, so molecules are always whole in congrad.c
     */
    /* PLUMED */
    int plumedNeedsEnergy=0;
    matrix plumed_vir;
    if(plumedswitch){
      long int lstep=count; (*plumedcmd)(plumedmain,"setStepLong",&lstep);
      (*plumedcmd) (plumedmain,"setPositions",&ems->s.x[0][0]);
      (*plumedcmd) (plumedmain,"setMasses",&mdAtoms->mdatoms()->massT[0]);
      (*plumedcmd) (plumedmain,"setCharges",&mdAtoms->mdatoms()->chargeA[0]);
      (*plumedcmd) (plumedmain,"setBox",&ems->s.box[0][0]);
      (*plumedcmd) (plumedmain,"prepareCalc",NULL);
      (*plumedcmd) (plumedmain,"setForces",&ems->f[0][0]);
      (*plumedcmd) (plumedmain,"isEnergyNeeded",&plumedNeedsEnergy);
      clear_mat(plumed_vir);
      (*plumedcmd) (plumedmain,"setVirial",&plumed_vir[0][0]);
    }
    /* END PLUMED */

    do_force(fplog, cr, inputrec,
             count, nrnb, wcycle, top, &top_global->groups,
             ems->s.box, ems->s.x, &ems->s.hist,
             ems->f, force_vir, mdAtoms->mdatoms(), enerd, fcd,
             ems->s.lambda, graph, fr, vsite, mu_tot, t, nullptr, TRUE,
             GMX_FORCE_STATECHANGED | GMX_FORCE_ALLFORCES |
             GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY |
             (bNS ? GMX_FORCE_NS : 0),
             DOMAINDECOMP(cr) ?
             DdOpenBalanceRegionBeforeForceComputation::yes :
             DdOpenBalanceRegionBeforeForceComputation::no,
             DOMAINDECOMP(cr) ?
             DdCloseBalanceRegionAfterForceComputation::yes :
             DdCloseBalanceRegionAfterForceComputation::no);
    /* PLUMED */
    if(plumedswitch){
      if(plumedNeedsEnergy) {
        msmul(force_vir,2.0,plumed_vir);
        (*plumedcmd) (plumedmain,"setEnergy",&enerd->term[F_EPOT]);
        (*plumedcmd) (plumedmain,"performCalc",NULL);
        msmul(plumed_vir,0.5,force_vir);
      } else {
        msmul(plumed_vir,0.5,plumed_vir);
        m_add(force_vir,plumed_vir,force_vir);
      }
    }
    /* END PLUMED */

    /* Clear the unused shake virial and pressure */
    clear_mat(shake_vir);
    clear_mat(pres);

    /* Communicate stuff when parallel */
    if (PAR(cr) && inputrec->eI != eiNM)
    {
        wallcycle_start(wcycle, ewcMoveE);

        global_stat(gstat, cr, enerd, force_vir, shake_vir, mu_tot,
                    inputrec, nullptr, nullptr, nullptr, 1, &terminate,
                    nullptr, FALSE,
                    CGLO_ENERGY |
                    CGLO_PRESSURE |
                    CGLO_CONSTRAINT);

        wallcycle_stop(wcycle, ewcMoveE);
    }

    /* Calculate long range corrections to pressure and energy */
    calc_dispcorr(inputrec, fr, ems->s.box, ems->s.lambda[efptVDW],
                  pres, force_vir, &prescorr, &enercorr, &dvdlcorr);
    enerd->term[F_DISPCORR] = enercorr;
    enerd->term[F_EPOT]    += enercorr;
    enerd->term[F_PRES]    += prescorr;
    enerd->term[F_DVDL]    += dvdlcorr;

    ems->epot = enerd->term[F_EPOT];

    if (constr)
    {
        /* Project out the constraint components of the force */
        wallcycle_start(wcycle, ewcCONSTR);
        dvdl_constr = 0;
        rvec *f_rvec = as_rvec_array(ems->f.data());
        constrain(nullptr, FALSE, FALSE, constr, &top->idef,
                  inputrec, cr, count, 0, 1.0, mdAtoms->mdatoms(),
                  as_rvec_array(ems->s.x.data()), f_rvec, f_rvec,
                  fr->bMolPBC, ems->s.box,
                  ems->s.lambda[efptBONDED], &dvdl_constr,
                  nullptr, &shake_vir, nrnb, econqForceDispl);
        enerd->term[F_DVDL_CONSTR] += dvdl_constr;
        m_add(force_vir, shake_vir, vir);
        wallcycle_stop(wcycle, ewcCONSTR);
    }
    else
    {
        copy_mat(force_vir, vir);
    }

    clear_mat(ekin);
    enerd->term[F_PRES] =
        calc_pres(fr->ePBC, inputrec->nwall, ems->s.box, ekin, vir, pres);

    sum_dhdl(enerd, ems->s.lambda, inputrec->fepvals);

    if (EI_ENERGY_MINIMIZATION(inputrec->eI))
    {
        get_state_f_norm_max(cr, &(inputrec->opts), mdAtoms->mdatoms(), ems);
    }
}

//! Parallel utility summing energies and forces
static double reorder_partsum(t_commrec *cr, t_grpopts *opts, t_mdatoms *mdatoms,
                              gmx_mtop_t *top_global,
                              em_state_t *s_min, em_state_t *s_b)
{
    t_block       *cgs_gl;
    int            ncg, *cg_gl, *index, c, cg, i, a0, a1, a, gf, m;
    double         partsum;
    unsigned char *grpnrFREEZE;

    if (debug)
    {
        fprintf(debug, "Doing reorder_partsum\n");
    }

    const rvec *fm = as_rvec_array(s_min->f.data());
    const rvec *fb = as_rvec_array(s_b->f.data());

    cgs_gl = dd_charge_groups_global(cr->dd);
    index  = cgs_gl->index;

    /* Collect fm in a global vector fmg.
     * This conflicts with the spirit of domain decomposition,
     * but to fully optimize this a much more complicated algorithm is required.
     */
    rvec *fmg;
    snew(fmg, top_global->natoms);

    ncg   = s_min->s.cg_gl.size();
    cg_gl = s_min->s.cg_gl.data();
    i     = 0;
    for (c = 0; c < ncg; c++)
    {
        cg = cg_gl[c];
        a0 = index[cg];
        a1 = index[cg+1];
        for (a = a0; a < a1; a++)
        {
            copy_rvec(fm[i], fmg[a]);
            i++;
        }
    }
    gmx_sum(top_global->natoms*3, fmg[0], cr);

    /* Now we will determine the part of the sum for the cgs in state s_b */
    ncg         = s_b->s.cg_gl.size();
    cg_gl       = s_b->s.cg_gl.data();
    partsum     = 0;
    i           = 0;
    gf          = 0;
    grpnrFREEZE = top_global->groups.grpnr[egcFREEZE];
    for (c = 0; c < ncg; c++)
    {
        cg = cg_gl[c];
        a0 = index[cg];
        a1 = index[cg+1];
        for (a = a0; a < a1; a++)
        {
            if (mdatoms->cFREEZE && grpnrFREEZE)
            {
                gf = grpnrFREEZE[i];
            }
            for (m = 0; m < DIM; m++)
            {
                if (!opts->nFreeze[gf][m])
                {
                    partsum += (fb[i][m] - fmg[a][m])*fb[i][m];
                }
            }
            i++;
        }
    }

    sfree(fmg);

    return partsum;
}

//! Print some stuff, like beta, whatever that means.
static real pr_beta(t_commrec *cr, t_grpopts *opts, t_mdatoms *mdatoms,
                    gmx_mtop_t *top_global,
                    em_state_t *s_min, em_state_t *s_b)