2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5 * Copyright (c) 2001-2004, The GROMACS development team.
6 * Copyright (c) 2013,2014,2015, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
47 #include "gromacs/domdec/domdec.h"
48 #include "gromacs/ewald/pme.h"
49 #include "gromacs/fileio/confio.h"
50 #include "gromacs/fileio/mtxio.h"
51 #include "gromacs/fileio/trajectory_writing.h"
52 #include "gromacs/imd/imd.h"
53 #include "gromacs/legacyheaders/constr.h"
54 #include "gromacs/legacyheaders/force.h"
55 #include "gromacs/legacyheaders/gmx_omp_nthreads.h"
56 #include "gromacs/legacyheaders/macros.h"
57 #include "gromacs/legacyheaders/md_logging.h"
58 #include "gromacs/legacyheaders/md_support.h"
59 #include "gromacs/legacyheaders/mdatoms.h"
60 #include "gromacs/legacyheaders/mdebin.h"
61 #include "gromacs/legacyheaders/mdrun.h"
62 #include "gromacs/legacyheaders/names.h"
63 #include "gromacs/legacyheaders/network.h"
64 #include "gromacs/legacyheaders/nrnb.h"
65 #include "gromacs/legacyheaders/ns.h"
66 #include "gromacs/legacyheaders/sim_util.h"
67 #include "gromacs/legacyheaders/tgroup.h"
68 #include "gromacs/legacyheaders/txtdump.h"
69 #include "gromacs/legacyheaders/typedefs.h"
70 #include "gromacs/legacyheaders/update.h"
71 #include "gromacs/legacyheaders/vsite.h"
72 #include "gromacs/legacyheaders/types/commrec.h"
73 #include "gromacs/linearalgebra/sparsematrix.h"
74 #include "gromacs/listed-forces/manage-threading.h"
75 #include "gromacs/math/vec.h"
76 #include "gromacs/pbcutil/mshift.h"
77 #include "gromacs/pbcutil/pbc.h"
78 #include "gromacs/timing/wallcycle.h"
79 #include "gromacs/timing/walltime_accounting.h"
80 #include "gromacs/topology/mtop_util.h"
81 #include "gromacs/utility/cstringutil.h"
82 #include "gromacs/utility/fatalerror.h"
83 #include "gromacs/utility/smalloc.h"
94 static em_state_t *init_em_state()
100 /* does this need to be here? Should the array be declared differently (staticaly)in the state definition? */
101 snew(ems->s.lambda, efptNR);
106 static void print_em_start(FILE *fplog,
108 gmx_walltime_accounting_t walltime_accounting,
109 gmx_wallcycle_t wcycle,
112 walltime_accounting_start(walltime_accounting);
113 wallcycle_start(wcycle, ewcRUN);
114 print_start(fplog, cr, walltime_accounting, name);
116 static void em_time_end(gmx_walltime_accounting_t walltime_accounting,
117 gmx_wallcycle_t wcycle)
119 wallcycle_stop(wcycle, ewcRUN);
121 walltime_accounting_end(walltime_accounting);
124 static void sp_header(FILE *out, const char *minimizer, real ftol, int nsteps)
127 fprintf(out, "%s:\n", minimizer);
128 fprintf(out, " Tolerance (Fmax) = %12.5e\n", ftol);
129 fprintf(out, " Number of steps = %12d\n", nsteps);
132 static void warn_step(FILE *fp, real ftol, gmx_bool bLastStep, gmx_bool bConstrain)
138 "\nEnergy minimization reached the maximum number "
139 "of steps before the forces reached the requested "
140 "precision Fmax < %g.\n", ftol);
145 "\nEnergy minimization has stopped, but the forces have "
146 "not converged to the requested precision Fmax < %g (which "
147 "may not be possible for your system). It stopped "
148 "because the algorithm tried to make a new step whose size "
149 "was too small, or there was no change in the energy since "
150 "last step. Either way, we regard the minimization as "
151 "converged to within the available machine precision, "
152 "given your starting configuration and EM parameters.\n%s%s",
154 sizeof(real) < sizeof(double) ?
155 "\nDouble precision normally gives you higher accuracy, but "
156 "this is often not needed for preparing to run molecular "
160 "You might need to increase your constraint accuracy, or turn\n"
161 "off constraints altogether (set constraints = none in mdp file)\n" :
164 fputs(wrap_lines(buffer, 78, 0, FALSE), fp);
169 static void print_converged(FILE *fp, const char *alg, real ftol,
170 gmx_int64_t count, gmx_bool bDone, gmx_int64_t nsteps,
171 real epot, real fmax, int nfmax, real fnorm)
173 char buf[STEPSTRSIZE];
177 fprintf(fp, "\n%s converged to Fmax < %g in %s steps\n",
178 alg, ftol, gmx_step_str(count, buf));
180 else if (count < nsteps)
182 fprintf(fp, "\n%s converged to machine precision in %s steps,\n"
183 "but did not reach the requested Fmax < %g.\n",
184 alg, gmx_step_str(count, buf), ftol);
188 fprintf(fp, "\n%s did not converge to Fmax < %g in %s steps.\n",
189 alg, ftol, gmx_step_str(count, buf));
193 fprintf(fp, "Potential Energy = %21.14e\n", epot);
194 fprintf(fp, "Maximum force = %21.14e on atom %d\n", fmax, nfmax+1);
195 fprintf(fp, "Norm of force = %21.14e\n", fnorm);
197 fprintf(fp, "Potential Energy = %14.7e\n", epot);
198 fprintf(fp, "Maximum force = %14.7e on atom %d\n", fmax, nfmax+1);
199 fprintf(fp, "Norm of force = %14.7e\n", fnorm);
203 static void get_f_norm_max(t_commrec *cr,
204 t_grpopts *opts, t_mdatoms *mdatoms, rvec *f,
205 real *fnorm, real *fmax, int *a_fmax)
209 int la_max, a_max, start, end, i, m, gf;
211 /* This routine finds the largest force and returns it.
212 * On parallel machines the global max is taken.
218 end = mdatoms->homenr;
219 if (mdatoms->cFREEZE)
221 for (i = start; i < end; i++)
223 gf = mdatoms->cFREEZE[i];
225 for (m = 0; m < DIM; m++)
227 if (!opts->nFreeze[gf][m])
242 for (i = start; i < end; i++)
254 if (la_max >= 0 && DOMAINDECOMP(cr))
256 a_max = cr->dd->gatindex[la_max];
264 snew(sum, 2*cr->nnodes+1);
265 sum[2*cr->nodeid] = fmax2;
266 sum[2*cr->nodeid+1] = a_max;
267 sum[2*cr->nnodes] = fnorm2;
268 gmx_sumd(2*cr->nnodes+1, sum, cr);
269 fnorm2 = sum[2*cr->nnodes];
270 /* Determine the global maximum */
271 for (i = 0; i < cr->nnodes; i++)
273 if (sum[2*i] > fmax2)
276 a_max = (int)(sum[2*i+1] + 0.5);
284 *fnorm = sqrt(fnorm2);
296 static void get_state_f_norm_max(t_commrec *cr,
297 t_grpopts *opts, t_mdatoms *mdatoms,
300 get_f_norm_max(cr, opts, mdatoms, ems->f, &ems->fnorm, &ems->fmax, &ems->a_fmax);
303 void init_em(FILE *fplog, const char *title,
304 t_commrec *cr, t_inputrec *ir,
305 t_state *state_global, gmx_mtop_t *top_global,
306 em_state_t *ems, gmx_localtop_t **top,
307 rvec **f, rvec **f_global,
308 t_nrnb *nrnb, rvec mu_tot,
309 t_forcerec *fr, gmx_enerdata_t **enerd,
310 t_graph **graph, t_mdatoms *mdatoms, gmx_global_stat_t *gstat,
311 gmx_vsite_t *vsite, gmx_constr_t constr,
312 int nfile, const t_filenm fnm[],
313 gmx_mdoutf_t *outf, t_mdebin **mdebin,
314 int imdport, unsigned long gmx_unused Flags,
315 gmx_wallcycle_t wcycle)
322 fprintf(fplog, "Initiating %s\n", title);
325 state_global->ngtc = 0;
327 /* Initialize lambda variables */
328 initialize_lambdas(fplog, ir, &(state_global->fep_state), state_global->lambda, NULL);
332 /* Interactive molecular dynamics */
333 init_IMD(ir, cr, top_global, fplog, 1, state_global->x,
334 nfile, fnm, NULL, imdport, Flags);
336 if (DOMAINDECOMP(cr))
338 *top = dd_init_local_top(top_global);
340 dd_init_local_state(cr->dd, state_global, &ems->s);
344 /* Distribute the charge groups over the nodes from the master node */
345 dd_partition_system(fplog, ir->init_step, cr, TRUE, 1,
346 state_global, top_global, ir,
347 &ems->s, &ems->f, mdatoms, *top,
348 fr, vsite, NULL, constr,
350 dd_store_state(cr->dd, &ems->s);
354 snew(*f_global, top_global->natoms);
364 snew(*f, top_global->natoms);
366 /* Just copy the state */
367 ems->s = *state_global;
368 snew(ems->s.x, ems->s.nalloc);
369 snew(ems->f, ems->s.nalloc);
370 for (i = 0; i < state_global->natoms; i++)
372 copy_rvec(state_global->x[i], ems->s.x[i]);
374 copy_mat(state_global->box, ems->s.box);
376 *top = gmx_mtop_generate_local_top(top_global, ir);
379 forcerec_set_excl_load(fr, *top);
381 setup_bonded_threading(fr, &(*top)->idef);
383 if (ir->ePBC != epbcNONE && !fr->bMolPBC)
385 *graph = mk_graph(fplog, &((*top)->idef), 0, top_global->natoms, FALSE, FALSE);
392 atoms2md(top_global, ir, 0, NULL, top_global->natoms, mdatoms);
393 update_mdatoms(mdatoms, state_global->lambda[efptFEP]);
397 set_vsite_top(vsite, *top, mdatoms, cr);
403 if (ir->eConstrAlg == econtSHAKE &&
404 gmx_mtop_ftype_count(top_global, F_CONSTR) > 0)
406 gmx_fatal(FARGS, "Can not do energy minimization with %s, use %s\n",
407 econstr_names[econtSHAKE], econstr_names[econtLINCS]);
410 if (!DOMAINDECOMP(cr))
412 set_constraints(constr, *top, ir, mdatoms, cr);
415 if (!ir->bContinuation)
417 /* Constrain the starting coordinates */
419 constrain(PAR(cr) ? NULL : fplog, TRUE, TRUE, constr, &(*top)->idef,
420 ir, cr, -1, 0, 1.0, mdatoms,
421 ems->s.x, ems->s.x, NULL, fr->bMolPBC, ems->s.box,
422 ems->s.lambda[efptFEP], &dvdl_constr,
423 NULL, NULL, nrnb, econqCoord);
429 *gstat = global_stat_init(ir);
436 *outf = init_mdoutf(fplog, nfile, fnm, 0, cr, ir, top_global, NULL, wcycle);
439 init_enerdata(top_global->groups.grps[egcENER].nr, ir->fepvals->n_lambda,
444 /* Init bin for energy stuff */
445 *mdebin = init_mdebin(mdoutf_get_fp_ene(*outf), top_global, ir, NULL);
449 calc_shifts(ems->s.box, fr->shift_vec);
452 static void finish_em(t_commrec *cr, gmx_mdoutf_t outf,
453 gmx_walltime_accounting_t walltime_accounting,
454 gmx_wallcycle_t wcycle)
456 if (!(cr->duty & DUTY_PME))
458 /* Tell the PME only node to finish */
459 gmx_pme_send_finish(cr);
464 em_time_end(walltime_accounting, wcycle);
467 static void swap_em_state(em_state_t *ems1, em_state_t *ems2)
476 static void copy_em_coords(em_state_t *ems, t_state *state)
480 for (i = 0; (i < state->natoms); i++)
482 copy_rvec(ems->s.x[i], state->x[i]);
486 static void write_em_traj(FILE *fplog, t_commrec *cr,
488 gmx_bool bX, gmx_bool bF, const char *confout,
489 gmx_mtop_t *top_global,
490 t_inputrec *ir, gmx_int64_t step,
492 t_state *state_global, rvec *f_global)
495 gmx_bool bIMDout = FALSE;
498 /* Shall we do IMD output? */
501 bIMDout = do_per_step(step, IMD_get_step(ir->imd->setup));
504 if ((bX || bF || bIMDout || confout != NULL) && !DOMAINDECOMP(cr))
506 copy_em_coords(state, state_global);
513 mdof_flags |= MDOF_X;
517 mdof_flags |= MDOF_F;
520 /* If we want IMD output, set appropriate MDOF flag */
523 mdof_flags |= MDOF_IMD;
526 mdoutf_write_to_trajectory_files(fplog, cr, outf, mdof_flags,
527 top_global, step, (double)step,
528 &state->s, state_global, state->f, f_global);
530 if (confout != NULL && MASTER(cr))
532 if (ir->ePBC != epbcNONE && !ir->bPeriodicMols && DOMAINDECOMP(cr))
534 /* Make molecules whole only for confout writing */
535 do_pbc_mtop(fplog, ir->ePBC, state_global->box, top_global,
539 write_sto_conf_mtop(confout,
540 *top_global->name, top_global,
541 state_global->x, NULL, ir->ePBC, state_global->box);
545 static void do_em_step(t_commrec *cr, t_inputrec *ir, t_mdatoms *md,
547 em_state_t *ems1, real a, rvec *f, em_state_t *ems2,
548 gmx_constr_t constr, gmx_localtop_t *top,
549 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
558 int nthreads gmx_unused;
563 if (DOMAINDECOMP(cr) && s1->ddp_count != cr->dd->ddp_count)
565 gmx_incons("state mismatch in do_em_step");
568 s2->flags = s1->flags;
570 if (s2->nalloc != s1->nalloc)
572 s2->nalloc = s1->nalloc;
573 srenew(s2->x, s1->nalloc);
574 srenew(ems2->f, s1->nalloc);
575 if (s2->flags & (1<<estCGP))
577 srenew(s2->cg_p, s1->nalloc);
581 s2->natoms = s1->natoms;
582 copy_mat(s1->box, s2->box);
583 /* Copy free energy state */
584 for (i = 0; i < efptNR; i++)
586 s2->lambda[i] = s1->lambda[i];
588 copy_mat(s1->box, s2->box);
596 // cppcheck-suppress unreadVariable
597 nthreads = gmx_omp_nthreads_get(emntUpdate);
598 #pragma omp parallel num_threads(nthreads)
603 #pragma omp for schedule(static) nowait
604 for (i = start; i < end; i++)
610 for (m = 0; m < DIM; m++)
612 if (ir->opts.nFreeze[gf][m])
618 x2[i][m] = x1[i][m] + a*f[i][m];
623 if (s2->flags & (1<<estCGP))
625 /* Copy the CG p vector */
628 #pragma omp for schedule(static) nowait
629 for (i = start; i < end; i++)
631 copy_rvec(x1[i], x2[i]);
635 if (DOMAINDECOMP(cr))
637 s2->ddp_count = s1->ddp_count;
638 if (s2->cg_gl_nalloc < s1->cg_gl_nalloc)
641 s2->cg_gl_nalloc = s1->cg_gl_nalloc;
642 srenew(s2->cg_gl, s2->cg_gl_nalloc);
645 s2->ncg_gl = s1->ncg_gl;
646 #pragma omp for schedule(static) nowait
647 for (i = 0; i < s2->ncg_gl; i++)
649 s2->cg_gl[i] = s1->cg_gl[i];
651 s2->ddp_count_cg_gl = s1->ddp_count_cg_gl;
657 wallcycle_start(wcycle, ewcCONSTR);
659 constrain(NULL, TRUE, TRUE, constr, &top->idef,
660 ir, cr, count, 0, 1.0, md,
661 s1->x, s2->x, NULL, bMolPBC, s2->box,
662 s2->lambda[efptBONDED], &dvdl_constr,
663 NULL, NULL, nrnb, econqCoord);
664 wallcycle_stop(wcycle, ewcCONSTR);
668 static void em_dd_partition_system(FILE *fplog, int step, t_commrec *cr,
669 gmx_mtop_t *top_global, t_inputrec *ir,
670 em_state_t *ems, gmx_localtop_t *top,
671 t_mdatoms *mdatoms, t_forcerec *fr,
672 gmx_vsite_t *vsite, gmx_constr_t constr,
673 t_nrnb *nrnb, gmx_wallcycle_t wcycle)
675 /* Repartition the domain decomposition */
676 wallcycle_start(wcycle, ewcDOMDEC);
677 dd_partition_system(fplog, step, cr, FALSE, 1,
678 NULL, top_global, ir,
680 mdatoms, top, fr, vsite, NULL, constr,
681 nrnb, wcycle, FALSE);
682 dd_store_state(cr->dd, &ems->s);
683 wallcycle_stop(wcycle, ewcDOMDEC);
686 static void evaluate_energy(FILE *fplog, t_commrec *cr,
687 gmx_mtop_t *top_global,
688 em_state_t *ems, gmx_localtop_t *top,
689 t_inputrec *inputrec,
690 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
691 gmx_global_stat_t gstat,
692 gmx_vsite_t *vsite, gmx_constr_t constr,
694 t_graph *graph, t_mdatoms *mdatoms,
695 t_forcerec *fr, rvec mu_tot,
696 gmx_enerdata_t *enerd, tensor vir, tensor pres,
697 gmx_int64_t count, gmx_bool bFirst)
701 tensor force_vir, shake_vir, ekin;
702 real dvdl_constr, prescorr, enercorr, dvdlcorr;
705 /* Set the time to the initial time, the time does not change during EM */
706 t = inputrec->init_t;
709 (DOMAINDECOMP(cr) && ems->s.ddp_count < cr->dd->ddp_count))
711 /* This is the first state or an old state used before the last ns */
717 if (inputrec->nstlist > 0)
725 construct_vsites(vsite, ems->s.x, 1, NULL,
726 top->idef.iparams, top->idef.il,
727 fr->ePBC, fr->bMolPBC, cr, ems->s.box);
730 if (DOMAINDECOMP(cr) && bNS)
732 /* Repartition the domain decomposition */
733 em_dd_partition_system(fplog, count, cr, top_global, inputrec,
734 ems, top, mdatoms, fr, vsite, constr,
738 /* Calc force & energy on new trial position */
739 /* do_force always puts the charge groups in the box and shifts again
740 * We do not unshift, so molecules are always whole in congrad.c
742 do_force(fplog, cr, inputrec,
743 count, nrnb, wcycle, top, &top_global->groups,
744 ems->s.box, ems->s.x, &ems->s.hist,
745 ems->f, force_vir, mdatoms, enerd, fcd,
746 ems->s.lambda, graph, fr, vsite, mu_tot, t, NULL, NULL, TRUE,
747 GMX_FORCE_STATECHANGED | GMX_FORCE_ALLFORCES |
748 GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY |
749 (bNS ? GMX_FORCE_NS | GMX_FORCE_DO_LR : 0));
751 /* Clear the unused shake virial and pressure */
752 clear_mat(shake_vir);
755 /* Communicate stuff when parallel */
756 if (PAR(cr) && inputrec->eI != eiNM)
758 wallcycle_start(wcycle, ewcMoveE);
760 global_stat(fplog, gstat, cr, enerd, force_vir, shake_vir, mu_tot,
761 inputrec, NULL, NULL, NULL, 1, &terminate,
762 top_global, &ems->s, FALSE,
767 wallcycle_stop(wcycle, ewcMoveE);
770 /* Calculate long range corrections to pressure and energy */
771 calc_dispcorr(inputrec, fr, top_global->natoms, ems->s.box, ems->s.lambda[efptVDW],
772 pres, force_vir, &prescorr, &enercorr, &dvdlcorr);
773 enerd->term[F_DISPCORR] = enercorr;
774 enerd->term[F_EPOT] += enercorr;
775 enerd->term[F_PRES] += prescorr;
776 enerd->term[F_DVDL] += dvdlcorr;
778 ems->epot = enerd->term[F_EPOT];
782 /* Project out the constraint components of the force */
783 wallcycle_start(wcycle, ewcCONSTR);
785 constrain(NULL, FALSE, FALSE, constr, &top->idef,
786 inputrec, cr, count, 0, 1.0, mdatoms,
787 ems->s.x, ems->f, ems->f, fr->bMolPBC, ems->s.box,
788 ems->s.lambda[efptBONDED], &dvdl_constr,
789 NULL, &shake_vir, nrnb, econqForceDispl);
790 enerd->term[F_DVDL_CONSTR] += dvdl_constr;
791 m_add(force_vir, shake_vir, vir);
792 wallcycle_stop(wcycle, ewcCONSTR);
796 copy_mat(force_vir, vir);
800 enerd->term[F_PRES] =
801 calc_pres(fr->ePBC, inputrec->nwall, ems->s.box, ekin, vir, pres);
803 sum_dhdl(enerd, ems->s.lambda, inputrec->fepvals);
805 if (EI_ENERGY_MINIMIZATION(inputrec->eI))
807 get_state_f_norm_max(cr, &(inputrec->opts), mdatoms, ems);
811 static double reorder_partsum(t_commrec *cr, t_grpopts *opts, t_mdatoms *mdatoms,
813 em_state_t *s_min, em_state_t *s_b)
817 int ncg, *cg_gl, *index, c, cg, i, a0, a1, a, gf, m;
819 unsigned char *grpnrFREEZE;
823 fprintf(debug, "Doing reorder_partsum\n");
829 cgs_gl = dd_charge_groups_global(cr->dd);
830 index = cgs_gl->index;
832 /* Collect fm in a global vector fmg.
833 * This conflicts with the spirit of domain decomposition,
834 * but to fully optimize this a much more complicated algorithm is required.
836 snew(fmg, mtop->natoms);
838 ncg = s_min->s.ncg_gl;
839 cg_gl = s_min->s.cg_gl;
841 for (c = 0; c < ncg; c++)
846 for (a = a0; a < a1; a++)
848 copy_rvec(fm[i], fmg[a]);
852 gmx_sum(mtop->natoms*3, fmg[0], cr);
854 /* Now we will determine the part of the sum for the cgs in state s_b */
856 cg_gl = s_b->s.cg_gl;
860 grpnrFREEZE = mtop->groups.grpnr[egcFREEZE];
861 for (c = 0; c < ncg; c++)
866 for (a = a0; a < a1; a++)
868 if (mdatoms->cFREEZE && grpnrFREEZE)
872 for (m = 0; m < DIM; m++)
874 if (!opts->nFreeze[gf][m])
876 partsum += (fb[i][m] - fmg[a][m])*fb[i][m];
888 static real pr_beta(t_commrec *cr, t_grpopts *opts, t_mdatoms *mdatoms,
890 em_state_t *s_min, em_state_t *s_b)
896 /* This is just the classical Polak-Ribiere calculation of beta;
897 * it looks a bit complicated since we take freeze groups into account,
898 * and might have to sum it in parallel runs.
901 if (!DOMAINDECOMP(cr) ||
902 (s_min->s.ddp_count == cr->dd->ddp_count &&
903 s_b->s.ddp_count == cr->dd->ddp_count))
909 /* This part of code can be incorrect with DD,
910 * since the atom ordering in s_b and s_min might differ.
912 for (i = 0; i < mdatoms->homenr; i++)
914 if (mdatoms->cFREEZE)
916 gf = mdatoms->cFREEZE[i];
918 for (m = 0; m < DIM; m++)
920 if (!opts->nFreeze[gf][m])
922 sum += (fb[i][m] - fm[i][m])*fb[i][m];
929 /* We need to reorder cgs while summing */
930 sum = reorder_partsum(cr, opts, mdatoms, mtop, s_min, s_b);
934 gmx_sumd(1, &sum, cr);
937 return sum/sqr(s_min->fnorm);
940 double do_cg(FILE *fplog, t_commrec *cr,
941 int nfile, const t_filenm fnm[],
942 const output_env_t gmx_unused oenv, gmx_bool bVerbose, gmx_bool gmx_unused bCompact,
943 int gmx_unused nstglobalcomm,
944 gmx_vsite_t *vsite, gmx_constr_t constr,
945 int gmx_unused stepout,
946 t_inputrec *inputrec,
947 gmx_mtop_t *top_global, t_fcdata *fcd,
948 t_state *state_global,
950 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
951 gmx_edsam_t gmx_unused ed,
953 int gmx_unused repl_ex_nst, int gmx_unused repl_ex_nex, int gmx_unused repl_ex_seed,
954 gmx_membed_t gmx_unused membed,
955 real gmx_unused cpt_period, real gmx_unused max_hours,
957 unsigned long gmx_unused Flags,
958 gmx_walltime_accounting_t walltime_accounting)
960 const char *CG = "Polak-Ribiere Conjugate Gradients";
962 em_state_t *s_min, *s_a, *s_b, *s_c;
964 gmx_enerdata_t *enerd;
966 gmx_global_stat_t gstat;
968 rvec *f_global, *p, *sf;
969 double gpa, gpb, gpc, tmp, minstep;
972 real a, b, c, beta = 0.0;
976 gmx_bool converged, foundlower;
978 gmx_bool do_log = FALSE, do_ene = FALSE, do_x, do_f;
980 int number_steps, neval = 0, nstcg = inputrec->nstcgsteep;
982 int i, m, gf, step, nminstep;
986 s_min = init_em_state();
987 s_a = init_em_state();
988 s_b = init_em_state();
989 s_c = init_em_state();
991 /* Init em and store the local state in s_min */
992 init_em(fplog, CG, cr, inputrec,
993 state_global, top_global, s_min, &top, &f, &f_global,
994 nrnb, mu_tot, fr, &enerd, &graph, mdatoms, &gstat, vsite, constr,
995 nfile, fnm, &outf, &mdebin, imdport, Flags, wcycle);
997 /* Print to log file */
998 print_em_start(fplog, cr, walltime_accounting, wcycle, CG);
1000 /* Max number of steps */
1001 number_steps = inputrec->nsteps;
1005 sp_header(stderr, CG, inputrec->em_tol, number_steps);
1009 sp_header(fplog, CG, inputrec->em_tol, number_steps);
1012 /* Call the force routine and some auxiliary (neighboursearching etc.) */
1013 /* do_force always puts the charge groups in the box and shifts again
1014 * We do not unshift, so molecules are always whole in congrad.c
1016 evaluate_energy(fplog, cr,
1017 top_global, s_min, top,
1018 inputrec, nrnb, wcycle, gstat,
1019 vsite, constr, fcd, graph, mdatoms, fr,
1020 mu_tot, enerd, vir, pres, -1, TRUE);
1025 /* Copy stuff to the energy bin for easy printing etc. */
1026 upd_mdebin(mdebin, FALSE, FALSE, (double)step,
1027 mdatoms->tmass, enerd, &s_min->s, inputrec->fepvals, inputrec->expandedvals, s_min->s.box,
1028 NULL, NULL, vir, pres, NULL, mu_tot, constr);
1030 print_ebin_header(fplog, step, step, s_min->s.lambda[efptFEP]);
1031 print_ebin(mdoutf_get_fp_ene(outf), TRUE, FALSE, FALSE, fplog, step, step, eprNORMAL,
1032 TRUE, mdebin, fcd, &(top_global->groups), &(inputrec->opts));
1036 /* Estimate/guess the initial stepsize */
1037 stepsize = inputrec->em_stepsize/s_min->fnorm;
1041 double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));
1042 fprintf(stderr, " F-max = %12.5e on atom %d\n",
1043 s_min->fmax, s_min->a_fmax+1);
1044 fprintf(stderr, " F-Norm = %12.5e\n",
1045 s_min->fnorm/sqrtNumAtoms);
1046 fprintf(stderr, "\n");
1047 /* and copy to the log file too... */
1048 fprintf(fplog, " F-max = %12.5e on atom %d\n",
1049 s_min->fmax, s_min->a_fmax+1);
1050 fprintf(fplog, " F-Norm = %12.5e\n",
1051 s_min->fnorm/sqrtNumAtoms);
1052 fprintf(fplog, "\n");
1054 /* Start the loop over CG steps.
1055 * Each successful step is counted, and we continue until
1056 * we either converge or reach the max number of steps.
1059 for (step = 0; (number_steps < 0 || (number_steps >= 0 && step <= number_steps)) && !converged; step++)
1062 /* start taking steps in a new direction
1063 * First time we enter the routine, beta=0, and the direction is
1064 * simply the negative gradient.
1067 /* Calculate the new direction in p, and the gradient in this direction, gpa */
1072 for (i = 0; i < mdatoms->homenr; i++)
1074 if (mdatoms->cFREEZE)
1076 gf = mdatoms->cFREEZE[i];
1078 for (m = 0; m < DIM; m++)
1080 if (!inputrec->opts.nFreeze[gf][m])
1082 p[i][m] = sf[i][m] + beta*p[i][m];
1083 gpa -= p[i][m]*sf[i][m];
1084 /* f is negative gradient, thus the sign */
1093 /* Sum the gradient along the line across CPUs */
1096 gmx_sumd(1, &gpa, cr);
1099 /* Calculate the norm of the search vector */
1100 get_f_norm_max(cr, &(inputrec->opts), mdatoms, p, &pnorm, NULL, NULL);
1102 /* Just in case stepsize reaches zero due to numerical precision... */
1105 stepsize = inputrec->em_stepsize/pnorm;
1109 * Double check the value of the derivative in the search direction.
1110 * If it is positive it must be due to the old information in the
1111 * CG formula, so just remove that and start over with beta=0.
1112 * This corresponds to a steepest descent step.
1117 step--; /* Don't count this step since we are restarting */
1118 continue; /* Go back to the beginning of the big for-loop */
1121 /* Calculate minimum allowed stepsize, before the average (norm)
1122 * relative change in coordinate is smaller than precision
1125 for (i = 0; i < mdatoms->homenr; i++)
1127 for (m = 0; m < DIM; m++)
1129 tmp = fabs(s_min->s.x[i][m]);
1138 /* Add up from all CPUs */
1141 gmx_sumd(1, &minstep, cr);
1144 minstep = GMX_REAL_EPS/sqrt(minstep/(3*state_global->natoms));
1146 if (stepsize < minstep)
1152 /* Write coordinates if necessary */
1153 do_x = do_per_step(step, inputrec->nstxout);
1154 do_f = do_per_step(step, inputrec->nstfout);
1156 write_em_traj(fplog, cr, outf, do_x, do_f, NULL,
1157 top_global, inputrec, step,
1158 s_min, state_global, f_global);
1160 /* Take a step downhill.
1161 * In theory, we should minimize the function along this direction.
1162 * That is quite possible, but it turns out to take 5-10 function evaluations
1163 * for each line. However, we dont really need to find the exact minimum -
1164 * it is much better to start a new CG step in a modified direction as soon
1165 * as we are close to it. This will save a lot of energy evaluations.
1167 * In practice, we just try to take a single step.
1168 * If it worked (i.e. lowered the energy), we increase the stepsize but
1169 * the continue straight to the next CG step without trying to find any minimum.
1170 * If it didn't work (higher energy), there must be a minimum somewhere between
1171 * the old position and the new one.
1173 * Due to the finite numerical accuracy, it turns out that it is a good idea
1174 * to even accept a SMALL increase in energy, if the derivative is still downhill.
1175 * This leads to lower final energies in the tests I've done. / Erik
1177 s_a->epot = s_min->epot;
1179 c = a + stepsize; /* reference position along line is zero */
1181 if (DOMAINDECOMP(cr) && s_min->s.ddp_count < cr->dd->ddp_count)
1183 em_dd_partition_system(fplog, step, cr, top_global, inputrec,
1184 s_min, top, mdatoms, fr, vsite, constr,
1188 /* Take a trial step (new coords in s_c) */
1189 do_em_step(cr, inputrec, mdatoms, fr->bMolPBC, s_min, c, s_min->s.cg_p, s_c,
1190 constr, top, nrnb, wcycle, -1);
1193 /* Calculate energy for the trial step */
1194 evaluate_energy(fplog, cr,
1195 top_global, s_c, top,
1196 inputrec, nrnb, wcycle, gstat,
1197 vsite, constr, fcd, graph, mdatoms, fr,
1198 mu_tot, enerd, vir, pres, -1, FALSE);
1200 /* Calc derivative along line */
1204 for (i = 0; i < mdatoms->homenr; i++)
1206 for (m = 0; m < DIM; m++)
1208 gpc -= p[i][m]*sf[i][m]; /* f is negative gradient, thus the sign */
1211 /* Sum the gradient along the line across CPUs */
1214 gmx_sumd(1, &gpc, cr);
1217 /* This is the max amount of increase in energy we tolerate */
1218 tmp = sqrt(GMX_REAL_EPS)*fabs(s_a->epot);
1220 /* Accept the step if the energy is lower, or if it is not significantly higher
1221 * and the line derivative is still negative.
1223 if (s_c->epot < s_a->epot || (gpc < 0 && s_c->epot < (s_a->epot + tmp)))
1226 /* Great, we found a better energy. Increase step for next iteration
1227 * if we are still going down, decrease it otherwise
1231 stepsize *= 1.618034; /* The golden section */
1235 stepsize *= 0.618034; /* 1/golden section */
1240 /* New energy is the same or higher. We will have to do some work
1241 * to find a smaller value in the interval. Take smaller step next time!
1244 stepsize *= 0.618034;
1250 /* OK, if we didn't find a lower value we will have to locate one now - there must
1251 * be one in the interval [a=0,c].
1252 * The same thing is valid here, though: Don't spend dozens of iterations to find
1253 * the line minimum. We try to interpolate based on the derivative at the endpoints,
1254 * and only continue until we find a lower value. In most cases this means 1-2 iterations.
1256 * I also have a safeguard for potentially really pathological functions so we never
1257 * take more than 20 steps before we give up ...
1259 * If we already found a lower value we just skip this step and continue to the update.
1267 /* Select a new trial point.
1268 * If the derivatives at points a & c have different sign we interpolate to zero,
1269 * otherwise just do a bisection.
1271 if (gpa < 0 && gpc > 0)
1273 b = a + gpa*(a-c)/(gpc-gpa);
1280 /* safeguard if interpolation close to machine accuracy causes errors:
1281 * never go outside the interval
1283 if (b <= a || b >= c)
1288 if (DOMAINDECOMP(cr) && s_min->s.ddp_count != cr->dd->ddp_count)
1290 /* Reload the old state */
1291 em_dd_partition_system(fplog, -1, cr, top_global, inputrec,
1292 s_min, top, mdatoms, fr, vsite, constr,
1296 /* Take a trial step to this new point - new coords in s_b */
1297 do_em_step(cr, inputrec, mdatoms, fr->bMolPBC, s_min, b, s_min->s.cg_p, s_b,
1298 constr, top, nrnb, wcycle, -1);
1301 /* Calculate energy for the trial step */
1302 evaluate_energy(fplog, cr,
1303 top_global, s_b, top,
1304 inputrec, nrnb, wcycle, gstat,
1305 vsite, constr, fcd, graph, mdatoms, fr,
1306 mu_tot, enerd, vir, pres, -1, FALSE);
1308 /* p does not change within a step, but since the domain decomposition
1309 * might change, we have to use cg_p of s_b here.
1314 for (i = 0; i < mdatoms->homenr; i++)
1316 for (m = 0; m < DIM; m++)
1318 gpb -= p[i][m]*sf[i][m]; /* f is negative gradient, thus the sign */
1321 /* Sum the gradient along the line across CPUs */
1324 gmx_sumd(1, &gpb, cr);
1329 fprintf(debug, "CGE: EpotA %f EpotB %f EpotC %f gpb %f\n",
1330 s_a->epot, s_b->epot, s_c->epot, gpb);
1333 epot_repl = s_b->epot;
1335 /* Keep one of the intervals based on the value of the derivative at the new point */
1338 /* Replace c endpoint with b */
1339 swap_em_state(s_b, s_c);
1345 /* Replace a endpoint with b */
1346 swap_em_state(s_b, s_a);
1352 * Stop search as soon as we find a value smaller than the endpoints.
1353 * Never run more than 20 steps, no matter what.
1357 while ((epot_repl > s_a->epot || epot_repl > s_c->epot) &&
1360 if (fabs(epot_repl - s_min->epot) < fabs(s_min->epot)*GMX_REAL_EPS ||
1363 /* OK. We couldn't find a significantly lower energy.
1364 * If beta==0 this was steepest descent, and then we give up.
1365 * If not, set beta=0 and restart with steepest descent before quitting.
1375 /* Reset memory before giving up */
1381 /* Select min energy state of A & C, put the best in B.
1383 if (s_c->epot < s_a->epot)
1387 fprintf(debug, "CGE: C (%f) is lower than A (%f), moving C to B\n",
1388 s_c->epot, s_a->epot);
1390 swap_em_state(s_b, s_c);
1397 fprintf(debug, "CGE: A (%f) is lower than C (%f), moving A to B\n",
1398 s_a->epot, s_c->epot);
1400 swap_em_state(s_b, s_a);
1409 fprintf(debug, "CGE: Found a lower energy %f, moving C to B\n",
1412 swap_em_state(s_b, s_c);
1416 /* new search direction */
1417 /* beta = 0 means forget all memory and restart with steepest descents. */
1418 if (nstcg && ((step % nstcg) == 0))
1424 /* s_min->fnorm cannot be zero, because then we would have converged
1428 /* Polak-Ribiere update.
1429 * Change to fnorm2/fnorm2_old for Fletcher-Reeves
1431 beta = pr_beta(cr, &inputrec->opts, mdatoms, top_global, s_min, s_b);
1433 /* Limit beta to prevent oscillations */
1434 if (fabs(beta) > 5.0)
1440 /* update positions */
1441 swap_em_state(s_min, s_b);
1444 /* Print it if necessary */
1449 double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));
1450 fprintf(stderr, "\rStep %d, Epot=%12.6e, Fnorm=%9.3e, Fmax=%9.3e (atom %d)\n",
1451 step, s_min->epot, s_min->fnorm/sqrtNumAtoms,
1452 s_min->fmax, s_min->a_fmax+1);
1454 /* Store the new (lower) energies */
1455 upd_mdebin(mdebin, FALSE, FALSE, (double)step,
1456 mdatoms->tmass, enerd, &s_min->s, inputrec->fepvals, inputrec->expandedvals, s_min->s.box,
1457 NULL, NULL, vir, pres, NULL, mu_tot, constr);
1459 do_log = do_per_step(step, inputrec->nstlog);
1460 do_ene = do_per_step(step, inputrec->nstenergy);
1462 /* Prepare IMD energy record, if bIMD is TRUE. */
1463 IMD_fill_energy_record(inputrec->bIMD, inputrec->imd, enerd, step, TRUE);
1467 print_ebin_header(fplog, step, step, s_min->s.lambda[efptFEP]);
1469 print_ebin(mdoutf_get_fp_ene(outf), do_ene, FALSE, FALSE,
1470 do_log ? fplog : NULL, step, step, eprNORMAL,
1471 TRUE, mdebin, fcd, &(top_global->groups), &(inputrec->opts));
1474 /* Send energies and positions to the IMD client if bIMD is TRUE. */
1475 if (do_IMD(inputrec->bIMD, step, cr, TRUE, state_global->box, state_global->x, inputrec, 0, wcycle) && MASTER(cr))
1477 IMD_send_positions(inputrec->imd);
1480 /* Stop when the maximum force lies below tolerance.
1481 * If we have reached machine precision, converged is already set to true.
1483 converged = converged || (s_min->fmax < inputrec->em_tol);
1485 } /* End of the loop */
1487 /* IMD cleanup, if bIMD is TRUE. */
1488 IMD_finalize(inputrec->bIMD, inputrec->imd);
1492 step--; /* we never took that last step in this case */
1495 if (s_min->fmax > inputrec->em_tol)
1499 warn_step(stderr, inputrec->em_tol, step-1 == number_steps, FALSE);
1500 warn_step(fplog, inputrec->em_tol, step-1 == number_steps, FALSE);
1507 /* If we printed energy and/or logfile last step (which was the last step)
1508 * we don't have to do it again, but otherwise print the final values.
1512 /* Write final value to log since we didn't do anything the last step */
1513 print_ebin_header(fplog, step, step, s_min->s.lambda[efptFEP]);
1515 if (!do_ene || !do_log)
1517 /* Write final energy file entries */
1518 print_ebin(mdoutf_get_fp_ene(outf), !do_ene, FALSE, FALSE,
1519 !do_log ? fplog : NULL, step, step, eprNORMAL,
1520 TRUE, mdebin, fcd, &(top_global->groups), &(inputrec->opts));
1524 /* Print some stuff... */
1527 fprintf(stderr, "\nwriting lowest energy coordinates.\n");
1531 * For accurate normal mode calculation it is imperative that we
1532 * store the last conformation into the full precision binary trajectory.
1534 * However, we should only do it if we did NOT already write this step
1535 * above (which we did if do_x or do_f was true).
1537 do_x = !do_per_step(step, inputrec->nstxout);
1538 do_f = (inputrec->nstfout > 0 && !do_per_step(step, inputrec->nstfout));
1540 write_em_traj(fplog, cr, outf, do_x, do_f, ftp2fn(efSTO, nfile, fnm),
1541 top_global, inputrec, step,
1542 s_min, state_global, f_global);
1547 double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));
1548 fnormn = s_min->fnorm/sqrtNumAtoms;
1549 print_converged(stderr, CG, inputrec->em_tol, step, converged, number_steps,
1550 s_min->epot, s_min->fmax, s_min->a_fmax, fnormn);
1551 print_converged(fplog, CG, inputrec->em_tol, step, converged, number_steps,
1552 s_min->epot, s_min->fmax, s_min->a_fmax, fnormn);
1554 fprintf(fplog, "\nPerformed %d energy evaluations in total.\n", neval);
1557 finish_em(cr, outf, walltime_accounting, wcycle);
1559 /* To print the actual number of steps we needed somewhere */
1560 walltime_accounting_set_nsteps_done(walltime_accounting, step);
1563 } /* That's all folks */
1566 double do_lbfgs(FILE *fplog, t_commrec *cr,
1567 int nfile, const t_filenm fnm[],
1568 const output_env_t gmx_unused oenv, gmx_bool bVerbose, gmx_bool gmx_unused bCompact,
1569 int gmx_unused nstglobalcomm,
1570 gmx_vsite_t *vsite, gmx_constr_t constr,
1571 int gmx_unused stepout,
1572 t_inputrec *inputrec,
1573 gmx_mtop_t *top_global, t_fcdata *fcd,
1576 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
1577 gmx_edsam_t gmx_unused ed,
1579 int gmx_unused repl_ex_nst, int gmx_unused repl_ex_nex, int gmx_unused repl_ex_seed,
1580 gmx_membed_t gmx_unused membed,
1581 real gmx_unused cpt_period, real gmx_unused max_hours,
1583 unsigned long gmx_unused Flags,
1584 gmx_walltime_accounting_t walltime_accounting)
1586 static const char *LBFGS = "Low-Memory BFGS Minimizer";
1588 gmx_localtop_t *top;
1589 gmx_enerdata_t *enerd;
1591 gmx_global_stat_t gstat;
1594 int ncorr, nmaxcorr, point, cp, neval, nminstep;
1595 double stepsize, step_taken, gpa, gpb, gpc, tmp, minstep;
1596 real *rho, *alpha, *ff, *xx, *p, *s, *lastx, *lastf, **dx, **dg;
1597 real *xa, *xb, *xc, *fa, *fb, *fc, *xtmp, *ftmp;
1598 real a, b, c, maxdelta, delta;
1599 real diag, Epot0, Epot, EpotA, EpotB, EpotC;
1600 real dgdx, dgdg, sq, yr, beta;
1605 gmx_bool do_log, do_ene, do_x, do_f, foundlower, *frozen;
1607 int start, end, number_steps;
1609 int i, k, m, n, nfmax, gf, step;
1614 gmx_fatal(FARGS, "Cannot do parallel L-BFGS Minimization - yet.\n");
1619 gmx_fatal(FARGS, "The combination of constraints and L-BFGS minimization is not implemented. Either do not use constraints, or use another minimizer (e.g. steepest descent).");
1622 n = 3*state->natoms;
1623 nmaxcorr = inputrec->nbfgscorr;
1625 /* Allocate memory */
1626 /* Use pointers to real so we dont have to loop over both atoms and
1627 * dimensions all the time...
1628 * x/f are allocated as rvec *, so make new x0/f0 pointers-to-real
1629 * that point to the same memory.
1642 snew(rho, nmaxcorr);
1643 snew(alpha, nmaxcorr);
1646 for (i = 0; i < nmaxcorr; i++)
1652 for (i = 0; i < nmaxcorr; i++)
1661 init_em(fplog, LBFGS, cr, inputrec,
1662 state, top_global, &ems, &top, &f, &f_global,
1663 nrnb, mu_tot, fr, &enerd, &graph, mdatoms, &gstat, vsite, constr,
1664 nfile, fnm, &outf, &mdebin, imdport, Flags, wcycle);
1665 /* Do_lbfgs is not completely updated like do_steep and do_cg,
1666 * so we free some memory again.
1671 xx = (real *)state->x;
1675 end = mdatoms->homenr;
1677 /* Print to log file */
1678 print_em_start(fplog, cr, walltime_accounting, wcycle, LBFGS);
1680 do_log = do_ene = do_x = do_f = TRUE;
1682 /* Max number of steps */
1683 number_steps = inputrec->nsteps;
1685 /* Create a 3*natoms index to tell whether each degree of freedom is frozen */
1687 for (i = start; i < end; i++)
1689 if (mdatoms->cFREEZE)
1691 gf = mdatoms->cFREEZE[i];
1693 for (m = 0; m < DIM; m++)
1695 frozen[3*i+m] = inputrec->opts.nFreeze[gf][m];
1700 sp_header(stderr, LBFGS, inputrec->em_tol, number_steps);
1704 sp_header(fplog, LBFGS, inputrec->em_tol, number_steps);
1709 construct_vsites(vsite, state->x, 1, NULL,
1710 top->idef.iparams, top->idef.il,
1711 fr->ePBC, fr->bMolPBC, cr, state->box);
1714 /* Call the force routine and some auxiliary (neighboursearching etc.) */
1715 /* do_force always puts the charge groups in the box and shifts again
1716 * We do not unshift, so molecules are always whole
1721 evaluate_energy(fplog, cr,
1722 top_global, &ems, top,
1723 inputrec, nrnb, wcycle, gstat,
1724 vsite, constr, fcd, graph, mdatoms, fr,
1725 mu_tot, enerd, vir, pres, -1, TRUE);
1730 /* Copy stuff to the energy bin for easy printing etc. */
1731 upd_mdebin(mdebin, FALSE, FALSE, (double)step,
1732 mdatoms->tmass, enerd, state, inputrec->fepvals, inputrec->expandedvals, state->box,
1733 NULL, NULL, vir, pres, NULL, mu_tot, constr);
1735 print_ebin_header(fplog, step, step, state->lambda[efptFEP]);
1736 print_ebin(mdoutf_get_fp_ene(outf), TRUE, FALSE, FALSE, fplog, step, step, eprNORMAL,
1737 TRUE, mdebin, fcd, &(top_global->groups), &(inputrec->opts));
1741 /* This is the starting energy */
1742 Epot = enerd->term[F_EPOT];
1748 /* Set the initial step.
1749 * since it will be multiplied by the non-normalized search direction
1750 * vector (force vector the first time), we scale it by the
1751 * norm of the force.
1756 double sqrtNumAtoms = sqrt(static_cast<double>(state->natoms));
1757 fprintf(stderr, "Using %d BFGS correction steps.\n\n", nmaxcorr);
1758 fprintf(stderr, " F-max = %12.5e on atom %d\n", fmax, nfmax+1);
1759 fprintf(stderr, " F-Norm = %12.5e\n", fnorm/sqrtNumAtoms);
1760 fprintf(stderr, "\n");
1761 /* and copy to the log file too... */
1762 fprintf(fplog, "Using %d BFGS correction steps.\n\n", nmaxcorr);
1763 fprintf(fplog, " F-max = %12.5e on atom %d\n", fmax, nfmax+1);
1764 fprintf(fplog, " F-Norm = %12.5e\n", fnorm/sqrtNumAtoms);
1765 fprintf(fplog, "\n");
1768 // Point is an index to the memory of search directions, where 0 is the first one.
1771 // Set initial search direction to the force (-gradient), or 0 for frozen particles.
1772 for (i = 0; i < n; i++)
1776 dx[point][i] = ff[i]; /* Initial search direction */
1784 // Stepsize will be modified during the search, and actually it is not critical
1785 // (the main efficiency in the algorithm comes from changing directions), but
1786 // we still need an initial value, so estimate it as the inverse of the norm
1787 // so we take small steps where the potential fluctuates a lot.
1788 stepsize = 1.0/fnorm;
1790 /* Start the loop over BFGS steps.
1791 * Each successful step is counted, and we continue until
1792 * we either converge or reach the max number of steps.
1797 /* Set the gradient from the force */
1799 for (step = 0; (number_steps < 0 || (number_steps >= 0 && step <= number_steps)) && !converged; step++)
1802 /* Write coordinates if necessary */
1803 do_x = do_per_step(step, inputrec->nstxout);
1804 do_f = do_per_step(step, inputrec->nstfout);
1809 mdof_flags |= MDOF_X;
1814 mdof_flags |= MDOF_F;
1819 mdof_flags |= MDOF_IMD;
1822 mdoutf_write_to_trajectory_files(fplog, cr, outf, mdof_flags,
1823 top_global, step, (real)step, state, state, f, f);
1825 /* Do the linesearching in the direction dx[point][0..(n-1)] */
1827 /* make s a pointer to current search direction - point=0 first time we get here */
1830 // calculate line gradient in position A
1831 for (gpa = 0, i = 0; i < n; i++)
1836 /* Calculate minimum allowed stepsize along the line, before the average (norm)
1837 * relative change in coordinate is smaller than precision
1839 for (minstep = 0, i = 0; i < n; i++)
1849 minstep = GMX_REAL_EPS/sqrt(minstep/n);
1851 if (stepsize < minstep)
1857 // Before taking any steps along the line, store the old position
1858 for (i = 0; i < n; i++)
1865 for (i = 0; i < n; i++)
1870 /* Take a step downhill.
1871 * In theory, we should find the actual minimum of the function in this
1872 * direction, somewhere along the line.
1873 * That is quite possible, but it turns out to take 5-10 function evaluations
1874 * for each line. However, we dont really need to find the exact minimum -
1875 * it is much better to start a new BFGS step in a modified direction as soon
1876 * as we are close to it. This will save a lot of energy evaluations.
1878 * In practice, we just try to take a single step.
1879 * If it worked (i.e. lowered the energy), we increase the stepsize but
1880 * continue straight to the next BFGS step without trying to find any minimum,
1881 * i.e. we change the search direction too. If the line was smooth, it is
1882 * likely we are in a smooth region, and then it makes sense to take longer
1883 * steps in the modified search direction too.
1885 * If it didn't work (higher energy), there must be a minimum somewhere between
1886 * the old position and the new one. Then we need to start by finding a lower
1887 * value before we change search direction. Since the energy was apparently
1888 * quite rough, we need to decrease the step size.
1890 * Due to the finite numerical accuracy, it turns out that it is a good idea
1891 * to accept a SMALL increase in energy, if the derivative is still downhill.
1892 * This leads to lower final energies in the tests I've done. / Erik
1895 // State "A" is the first position along the line.
1896 // reference position along line is initially zero
1900 // Check stepsize first. We do not allow displacements
1901 // larger than emstep.
1905 // Pick a new position C by adding stepsize to A.
1908 // Calculate what the largest change in any individual coordinate
1909 // would be (translation along line * gradient along line)
1911 for (i = 0; i < n; i++)
1914 if (delta > maxdelta)
1919 // If any displacement is larger than the stepsize limit, reduce the step
1920 if (maxdelta > inputrec->em_stepsize)
1925 while (maxdelta > inputrec->em_stepsize);
1927 // Take a trial step and move the coordinate array xc[] to position C
1928 for (i = 0; i < n; i++)
1930 xc[i] = lastx[i] + c*s[i];
1934 // Calculate energy for the trial step in position C
1935 ems.s.x = (rvec *)xc;
1937 evaluate_energy(fplog, cr,
1938 top_global, &ems, top,
1939 inputrec, nrnb, wcycle, gstat,
1940 vsite, constr, fcd, graph, mdatoms, fr,
1941 mu_tot, enerd, vir, pres, step, FALSE);
1944 // Calc line gradient in position C
1945 for (gpc = 0, i = 0; i < n; i++)
1947 gpc -= s[i]*fc[i]; /* f is negative gradient, thus the sign */
1949 /* Sum the gradient along the line across CPUs */
1952 gmx_sumd(1, &gpc, cr);
1955 // This is the max amount of increase in energy we tolerate.
1956 // By allowing VERY small changes (close to numerical precision) we
1957 // frequently find even better (lower) final energies.
1958 tmp = sqrt(GMX_REAL_EPS)*fabs(EpotA);
1960 // Accept the step if the energy is lower in the new position C (compared to A),
1961 // or if it is not significantly higher and the line derivative is still negative.
1962 if (EpotC < EpotA || (gpc < 0 && EpotC < (EpotA+tmp)))
1964 // Great, we found a better energy. We no longer try to alter the
1965 // stepsize, but simply accept this new better position. The we select a new
1966 // search direction instead, which will be much more efficient than continuing
1967 // to take smaller steps along a line. Set fnorm based on the new C position,
1968 // which will be used to update the stepsize to 1/fnorm further down.
1974 // If we got here, the energy is NOT lower in point C, i.e. it will be the same
1975 // or higher than in point A. In this case it is pointless to move to point C,
1976 // so we will have to do more iterations along the same line to find a smaller
1977 // value in the interval [A=0.0,C].
1978 // Here, A is still 0.0, but that will change when we do a search in the interval
1979 // [0.0,C] below. That search we will do by interpolation or bisection rather
1980 // than with the stepsize, so no need to modify it. For the next search direction
1981 // it will be reset to 1/fnorm anyway.
1987 // OK, if we didn't find a lower value we will have to locate one now - there must
1988 // be one in the interval [a,c].
1989 // The same thing is valid here, though: Don't spend dozens of iterations to find
1990 // the line minimum. We try to interpolate based on the derivative at the endpoints,
1991 // and only continue until we find a lower value. In most cases this means 1-2 iterations.
1992 // I also have a safeguard for potentially really pathological functions so we never
1993 // take more than 20 steps before we give up.
1994 // If we already found a lower value we just skip this step and continue to the update.
1998 // Select a new trial point B in the interval [A,C].
1999 // If the derivatives at points a & c have different sign we interpolate to zero,
2000 // otherwise just do a bisection since there might be multiple minima/maxima
2001 // inside the interval.
2002 if (gpa < 0 && gpc > 0)
2004 b = a + gpa*(a-c)/(gpc-gpa);
2011 /* safeguard if interpolation close to machine accuracy causes errors:
2012 * never go outside the interval
2014 if (b <= a || b >= c)
2019 // Take a trial step to point B
2020 for (i = 0; i < n; i++)
2022 xb[i] = lastx[i] + b*s[i];
2026 // Calculate energy for the trial step in point B
2027 ems.s.x = (rvec *)xb;
2029 evaluate_energy(fplog, cr,
2030 top_global, &ems, top,
2031 inputrec, nrnb, wcycle, gstat,
2032 vsite, constr, fcd, graph, mdatoms, fr,
2033 mu_tot, enerd, vir, pres, step, FALSE);
2037 // Calculate gradient in point B
2038 for (gpb = 0, i = 0; i < n; i++)
2040 gpb -= s[i]*fb[i]; /* f is negative gradient, thus the sign */
2043 /* Sum the gradient along the line across CPUs */
2046 gmx_sumd(1, &gpb, cr);
2049 // Keep one of the intervals [A,B] or [B,C] based on the value of the derivative
2050 // at the new point B, and rename the endpoints of this new interval A and C.
2053 /* Replace c endpoint with b */
2057 /* swap coord pointers b/c */
2067 /* Replace a endpoint with b */
2071 /* swap coord pointers a/b */
2081 * Stop search as soon as we find a value smaller than the endpoints,
2082 * or if the tolerance is below machine precision.
2083 * Never run more than 20 steps, no matter what.
2087 while ((EpotB > EpotA || EpotB > EpotC) && (nminstep < 20));
2089 if (fabs(EpotB-Epot0) < GMX_REAL_EPS || nminstep >= 20)
2091 /* OK. We couldn't find a significantly lower energy.
2092 * If ncorr==0 this was steepest descent, and then we give up.
2093 * If not, reset memory to restart as steepest descent before quitting.
2105 /* Search in gradient direction */
2106 for (i = 0; i < n; i++)
2108 dx[point][i] = ff[i];
2110 /* Reset stepsize */
2111 stepsize = 1.0/fnorm;
2116 /* Select min energy state of A & C, put the best in xx/ff/Epot
2122 for (i = 0; i < n; i++)
2133 for (i = 0; i < n; i++)
2147 for (i = 0; i < n; i++)
2155 /* Update the memory information, and calculate a new
2156 * approximation of the inverse hessian
2159 /* Have new data in Epot, xx, ff */
2160 if (ncorr < nmaxcorr)
2165 for (i = 0; i < n; i++)
2167 dg[point][i] = lastf[i]-ff[i];
2168 dx[point][i] *= step_taken;
2173 for (i = 0; i < n; i++)
2175 dgdg += dg[point][i]*dg[point][i];
2176 dgdx += dg[point][i]*dx[point][i];
2181 rho[point] = 1.0/dgdx;
2184 if (point >= nmaxcorr)
2190 for (i = 0; i < n; i++)
2197 /* Recursive update. First go back over the memory points */
2198 for (k = 0; k < ncorr; k++)
2207 for (i = 0; i < n; i++)
2209 sq += dx[cp][i]*p[i];
2212 alpha[cp] = rho[cp]*sq;
2214 for (i = 0; i < n; i++)
2216 p[i] -= alpha[cp]*dg[cp][i];
2220 for (i = 0; i < n; i++)
2225 /* And then go forward again */
2226 for (k = 0; k < ncorr; k++)
2229 for (i = 0; i < n; i++)
2231 yr += p[i]*dg[cp][i];
2235 beta = alpha[cp]-beta;
2237 for (i = 0; i < n; i++)
2239 p[i] += beta*dx[cp][i];
2249 for (i = 0; i < n; i++)
2253 dx[point][i] = p[i];
2261 /* Test whether the convergence criterion is met */
2262 get_f_norm_max(cr, &(inputrec->opts), mdatoms, f, &fnorm, &fmax, &nfmax);
2264 /* Print it if necessary */
2269 double sqrtNumAtoms = sqrt(static_cast<double>(state->natoms));
2270 fprintf(stderr, "\rStep %d, Epot=%12.6e, Fnorm=%9.3e, Fmax=%9.3e (atom %d)\n",
2271 step, Epot, fnorm/sqrtNumAtoms, fmax, nfmax+1);
2273 /* Store the new (lower) energies */
2274 upd_mdebin(mdebin, FALSE, FALSE, (double)step,
2275 mdatoms->tmass, enerd, state, inputrec->fepvals, inputrec->expandedvals, state->box,
2276 NULL, NULL, vir, pres, NULL, mu_tot, constr);
2277 do_log = do_per_step(step, inputrec->nstlog);
2278 do_ene = do_per_step(step, inputrec->nstenergy);
2281 print_ebin_header(fplog, step, step, state->lambda[efptFEP]);
2283 print_ebin(mdoutf_get_fp_ene(outf), do_ene, FALSE, FALSE,
2284 do_log ? fplog : NULL, step, step, eprNORMAL,
2285 TRUE, mdebin, fcd, &(top_global->groups), &(inputrec->opts));
2288 /* Send x and E to IMD client, if bIMD is TRUE. */
2289 if (do_IMD(inputrec->bIMD, step, cr, TRUE, state->box, state->x, inputrec, 0, wcycle) && MASTER(cr))
2291 IMD_send_positions(inputrec->imd);
2294 // Reset stepsize in we are doing more iterations
2295 stepsize = 1.0/fnorm;
2297 /* Stop when the maximum force lies below tolerance.
2298 * If we have reached machine precision, converged is already set to true.
2300 converged = converged || (fmax < inputrec->em_tol);
2302 } /* End of the loop */
2304 /* IMD cleanup, if bIMD is TRUE. */
2305 IMD_finalize(inputrec->bIMD, inputrec->imd);
2309 step--; /* we never took that last step in this case */
2312 if (fmax > inputrec->em_tol)
2316 warn_step(stderr, inputrec->em_tol, step-1 == number_steps, FALSE);
2317 warn_step(fplog, inputrec->em_tol, step-1 == number_steps, FALSE);
2322 /* If we printed energy and/or logfile last step (which was the last step)
2323 * we don't have to do it again, but otherwise print the final values.
2325 if (!do_log) /* Write final value to log since we didn't do anythin last step */
2327 print_ebin_header(fplog, step, step, state->lambda[efptFEP]);
2329 if (!do_ene || !do_log) /* Write final energy file entries */
2331 print_ebin(mdoutf_get_fp_ene(outf), !do_ene, FALSE, FALSE,
2332 !do_log ? fplog : NULL, step, step, eprNORMAL,
2333 TRUE, mdebin, fcd, &(top_global->groups), &(inputrec->opts));
2336 /* Print some stuff... */
2339 fprintf(stderr, "\nwriting lowest energy coordinates.\n");
2343 * For accurate normal mode calculation it is imperative that we
2344 * store the last conformation into the full precision binary trajectory.
2346 * However, we should only do it if we did NOT already write this step
2347 * above (which we did if do_x or do_f was true).
2349 do_x = !do_per_step(step, inputrec->nstxout);
2350 do_f = !do_per_step(step, inputrec->nstfout);
2351 write_em_traj(fplog, cr, outf, do_x, do_f, ftp2fn(efSTO, nfile, fnm),
2352 top_global, inputrec, step,
2357 double sqrtNumAtoms = sqrt(static_cast<double>(state->natoms));
2358 print_converged(stderr, LBFGS, inputrec->em_tol, step, converged,
2359 number_steps, Epot, fmax, nfmax, fnorm/sqrtNumAtoms);
2360 print_converged(fplog, LBFGS, inputrec->em_tol, step, converged,
2361 number_steps, Epot, fmax, nfmax, fnorm/sqrtNumAtoms);
2363 fprintf(fplog, "\nPerformed %d energy evaluations in total.\n", neval);
2366 finish_em(cr, outf, walltime_accounting, wcycle);
2368 /* To print the actual number of steps we needed somewhere */
2369 walltime_accounting_set_nsteps_done(walltime_accounting, step);
2372 } /* That's all folks */
2375 double do_steep(FILE *fplog, t_commrec *cr,
2376 int nfile, const t_filenm fnm[],
2377 const output_env_t gmx_unused oenv, gmx_bool bVerbose, gmx_bool gmx_unused bCompact,
2378 int gmx_unused nstglobalcomm,
2379 gmx_vsite_t *vsite, gmx_constr_t constr,
2380 int gmx_unused stepout,
2381 t_inputrec *inputrec,
2382 gmx_mtop_t *top_global, t_fcdata *fcd,
2383 t_state *state_global,
2385 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
2386 gmx_edsam_t gmx_unused ed,
2388 int gmx_unused repl_ex_nst, int gmx_unused repl_ex_nex, int gmx_unused repl_ex_seed,
2389 gmx_membed_t gmx_unused membed,
2390 real gmx_unused cpt_period, real gmx_unused max_hours,
2392 unsigned long gmx_unused Flags,
2393 gmx_walltime_accounting_t walltime_accounting)
2395 const char *SD = "Steepest Descents";
2396 em_state_t *s_min, *s_try;
2398 gmx_localtop_t *top;
2399 gmx_enerdata_t *enerd;
2401 gmx_global_stat_t gstat;
2407 gmx_bool bDone, bAbort, do_x, do_f;
2412 int steps_accepted = 0;
2414 s_min = init_em_state();
2415 s_try = init_em_state();
2417 /* Init em and store the local state in s_try */
2418 init_em(fplog, SD, cr, inputrec,
2419 state_global, top_global, s_try, &top, &f, &f_global,
2420 nrnb, mu_tot, fr, &enerd, &graph, mdatoms, &gstat, vsite, constr,
2421 nfile, fnm, &outf, &mdebin, imdport, Flags, wcycle);
2423 /* Print to log file */
2424 print_em_start(fplog, cr, walltime_accounting, wcycle, SD);
2426 /* Set variables for stepsize (in nm). This is the largest
2427 * step that we are going to make in any direction.
2429 ustep = inputrec->em_stepsize;
2432 /* Max number of steps */
2433 nsteps = inputrec->nsteps;
2437 /* Print to the screen */
2438 sp_header(stderr, SD, inputrec->em_tol, nsteps);
2442 sp_header(fplog, SD, inputrec->em_tol, nsteps);
2445 /**** HERE STARTS THE LOOP ****
2446 * count is the counter for the number of steps
2447 * bDone will be TRUE when the minimization has converged
2448 * bAbort will be TRUE when nsteps steps have been performed or when
2449 * the stepsize becomes smaller than is reasonable for machine precision
2454 while (!bDone && !bAbort)
2456 bAbort = (nsteps >= 0) && (count == nsteps);
2458 /* set new coordinates, except for first step */
2461 do_em_step(cr, inputrec, mdatoms, fr->bMolPBC,
2462 s_min, stepsize, s_min->f, s_try,
2463 constr, top, nrnb, wcycle, count);
2466 evaluate_energy(fplog, cr,
2467 top_global, s_try, top,
2468 inputrec, nrnb, wcycle, gstat,
2469 vsite, constr, fcd, graph, mdatoms, fr,
2470 mu_tot, enerd, vir, pres, count, count == 0);
2474 print_ebin_header(fplog, count, count, s_try->s.lambda[efptFEP]);
2479 s_min->epot = s_try->epot;
2482 /* Print it if necessary */
2487 fprintf(stderr, "Step=%5d, Dmax= %6.1e nm, Epot= %12.5e Fmax= %11.5e, atom= %d%c",
2488 count, ustep, s_try->epot, s_try->fmax, s_try->a_fmax+1,
2489 ( (count == 0) || (s_try->epot < s_min->epot) ) ? '\n' : '\r');
2492 if ( (count == 0) || (s_try->epot < s_min->epot) )
2494 /* Store the new (lower) energies */
2495 upd_mdebin(mdebin, FALSE, FALSE, (double)count,
2496 mdatoms->tmass, enerd, &s_try->s, inputrec->fepvals, inputrec->expandedvals,
2497 s_try->s.box, NULL, NULL, vir, pres, NULL, mu_tot, constr);
2499 /* Prepare IMD energy record, if bIMD is TRUE. */
2500 IMD_fill_energy_record(inputrec->bIMD, inputrec->imd, enerd, count, TRUE);
2502 print_ebin(mdoutf_get_fp_ene(outf), TRUE,
2503 do_per_step(steps_accepted, inputrec->nstdisreout),
2504 do_per_step(steps_accepted, inputrec->nstorireout),
2505 fplog, count, count, eprNORMAL, TRUE,
2506 mdebin, fcd, &(top_global->groups), &(inputrec->opts));
2511 /* Now if the new energy is smaller than the previous...
2512 * or if this is the first step!
2513 * or if we did random steps!
2516 if ( (count == 0) || (s_try->epot < s_min->epot) )
2520 /* Test whether the convergence criterion is met... */
2521 bDone = (s_try->fmax < inputrec->em_tol);
2523 /* Copy the arrays for force, positions and energy */
2524 /* The 'Min' array always holds the coords and forces of the minimal
2526 swap_em_state(s_min, s_try);
2532 /* Write to trn, if necessary */
2533 do_x = do_per_step(steps_accepted, inputrec->nstxout);
2534 do_f = do_per_step(steps_accepted, inputrec->nstfout);
2535 write_em_traj(fplog, cr, outf, do_x, do_f, NULL,
2536 top_global, inputrec, count,
2537 s_min, state_global, f_global);
2541 /* If energy is not smaller make the step smaller... */
2544 if (DOMAINDECOMP(cr) && s_min->s.ddp_count != cr->dd->ddp_count)
2546 /* Reload the old state */
2547 em_dd_partition_system(fplog, count, cr, top_global, inputrec,
2548 s_min, top, mdatoms, fr, vsite, constr,
2553 /* Determine new step */
2554 stepsize = ustep/s_min->fmax;
2556 /* Check if stepsize is too small, with 1 nm as a characteristic length */
2558 if (count == nsteps || ustep < 1e-12)
2560 if (count == nsteps || ustep < 1e-6)
2565 warn_step(stderr, inputrec->em_tol, count == nsteps, constr != NULL);
2566 warn_step(fplog, inputrec->em_tol, count == nsteps, constr != NULL);
2571 /* Send IMD energies and positions, if bIMD is TRUE. */
2572 if (do_IMD(inputrec->bIMD, count, cr, TRUE, state_global->box, state_global->x, inputrec, 0, wcycle) && MASTER(cr))
2574 IMD_send_positions(inputrec->imd);
2578 } /* End of the loop */
2580 /* IMD cleanup, if bIMD is TRUE. */
2581 IMD_finalize(inputrec->bIMD, inputrec->imd);
2583 /* Print some data... */
2586 fprintf(stderr, "\nwriting lowest energy coordinates.\n");
2588 write_em_traj(fplog, cr, outf, TRUE, inputrec->nstfout, ftp2fn(efSTO, nfile, fnm),
2589 top_global, inputrec, count,
2590 s_min, state_global, f_global);
2594 double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));
2595 fnormn = s_min->fnorm/sqrtNumAtoms;
2597 print_converged(stderr, SD, inputrec->em_tol, count, bDone, nsteps,
2598 s_min->epot, s_min->fmax, s_min->a_fmax, fnormn);
2599 print_converged(fplog, SD, inputrec->em_tol, count, bDone, nsteps,
2600 s_min->epot, s_min->fmax, s_min->a_fmax, fnormn);
2603 finish_em(cr, outf, walltime_accounting, wcycle);
2605 /* To print the actual number of steps we needed somewhere */
2606 inputrec->nsteps = count;
2608 walltime_accounting_set_nsteps_done(walltime_accounting, count);
2611 } /* That's all folks */
2614 double do_nm(FILE *fplog, t_commrec *cr,
2615 int nfile, const t_filenm fnm[],
2616 const output_env_t gmx_unused oenv, gmx_bool bVerbose, gmx_bool gmx_unused bCompact,
2617 int gmx_unused nstglobalcomm,
2618 gmx_vsite_t *vsite, gmx_constr_t constr,
2619 int gmx_unused stepout,
2620 t_inputrec *inputrec,
2621 gmx_mtop_t *top_global, t_fcdata *fcd,
2622 t_state *state_global,
2624 t_nrnb *nrnb, gmx_wallcycle_t wcycle,
2625 gmx_edsam_t gmx_unused ed,
2627 int gmx_unused repl_ex_nst, int gmx_unused repl_ex_nex, int gmx_unused repl_ex_seed,
2628 gmx_membed_t gmx_unused membed,
2629 real gmx_unused cpt_period, real gmx_unused max_hours,
2631 unsigned long gmx_unused Flags,
2632 gmx_walltime_accounting_t walltime_accounting)
2634 const char *NM = "Normal Mode Analysis";
2636 int natoms, atom, d;
2639 gmx_localtop_t *top;
2640 gmx_enerdata_t *enerd;
2642 gmx_global_stat_t gstat;
2647 gmx_bool bSparse; /* use sparse matrix storage format */
2649 gmx_sparsematrix_t * sparse_matrix = NULL;
2650 real * full_matrix = NULL;
2651 em_state_t * state_work;
2653 /* added with respect to mdrun */
2654 int i, j, k, row, col;
2655 real der_range = 10.0*sqrt(GMX_REAL_EPS);
2657 bool bIsMaster = MASTER(cr);
2661 gmx_fatal(FARGS, "Constraints present with Normal Mode Analysis, this combination is not supported");
2664 state_work = init_em_state();
2666 /* Init em and store the local state in state_minimum */
2667 init_em(fplog, NM, cr, inputrec,
2668 state_global, top_global, state_work, &top,
2670 nrnb, mu_tot, fr, &enerd, &graph, mdatoms, &gstat, vsite, constr,
2671 nfile, fnm, &outf, NULL, imdport, Flags, wcycle);
2673 natoms = top_global->natoms;
2681 "NOTE: This version of GROMACS has been compiled in single precision,\n"
2682 " which MIGHT not be accurate enough for normal mode analysis.\n"
2683 " GROMACS now uses sparse matrix storage, so the memory requirements\n"
2684 " are fairly modest even if you recompile in double precision.\n\n");
2688 /* Check if we can/should use sparse storage format.
2690 * Sparse format is only useful when the Hessian itself is sparse, which it
2691 * will be when we use a cutoff.
2692 * For small systems (n<1000) it is easier to always use full matrix format, though.
2694 if (EEL_FULL(fr->eeltype) || fr->rlist == 0.0)
2696 md_print_info(cr, fplog, "Non-cutoff electrostatics used, forcing full Hessian format.\n");
2699 else if (top_global->natoms < 1000)
2701 md_print_info(cr, fplog, "Small system size (N=%d), using full Hessian format.\n", top_global->natoms);
2706 md_print_info(cr, fplog, "Using compressed symmetric sparse Hessian format.\n");
2712 sz = DIM*top_global->natoms;
2714 fprintf(stderr, "Allocating Hessian memory...\n\n");
2718 sparse_matrix = gmx_sparsematrix_init(sz);
2719 sparse_matrix->compressed_symmetric = TRUE;
2723 snew(full_matrix, sz*sz);
2731 /* Write start time and temperature */
2732 print_em_start(fplog, cr, walltime_accounting, wcycle, NM);
2734 /* fudge nr of steps to nr of atoms */
2735 inputrec->nsteps = natoms*2;
2739 fprintf(stderr, "starting normal mode calculation '%s'\n%d steps.\n\n",
2740 *(top_global->name), (int)inputrec->nsteps);
2743 nnodes = cr->nnodes;
2745 /* Make evaluate_energy do a single node force calculation */
2747 evaluate_energy(fplog, cr,
2748 top_global, state_work, top,
2749 inputrec, nrnb, wcycle, gstat,
2750 vsite, constr, fcd, graph, mdatoms, fr,
2751 mu_tot, enerd, vir, pres, -1, TRUE);
2752 cr->nnodes = nnodes;
2754 /* if forces are not small, warn user */
2755 get_state_f_norm_max(cr, &(inputrec->opts), mdatoms, state_work);
2757 md_print_info(cr, fplog, "Maximum force:%12.5e\n", state_work->fmax);
2758 if (state_work->fmax > 1.0e-3)
2760 md_print_info(cr, fplog,
2761 "The force is probably not small enough to "
2762 "ensure that you are at a minimum.\n"
2763 "Be aware that negative eigenvalues may occur\n"
2764 "when the resulting matrix is diagonalized.\n\n");
2767 /***********************************************************
2769 * Loop over all pairs in matrix
2771 * do_force called twice. Once with positive and
2772 * once with negative displacement
2774 ************************************************************/
2776 /* Steps are divided one by one over the nodes */
2777 for (atom = cr->nodeid; atom < natoms; atom += nnodes)
2780 for (d = 0; d < DIM; d++)
2782 x_min = state_work->s.x[atom][d];
2784 state_work->s.x[atom][d] = x_min - der_range;
2786 /* Make evaluate_energy do a single node force calculation */
2788 evaluate_energy(fplog, cr,
2789 top_global, state_work, top,
2790 inputrec, nrnb, wcycle, gstat,
2791 vsite, constr, fcd, graph, mdatoms, fr,
2792 mu_tot, enerd, vir, pres, atom*2, FALSE);
2794 for (i = 0; i < natoms; i++)
2796 copy_rvec(state_work->f[i], fneg[i]);
2799 state_work->s.x[atom][d] = x_min + der_range;
2801 evaluate_energy(fplog, cr,
2802 top_global, state_work, top,
2803 inputrec, nrnb, wcycle, gstat,
2804 vsite, constr, fcd, graph, mdatoms, fr,
2805 mu_tot, enerd, vir, pres, atom*2+1, FALSE);
2806 cr->nnodes = nnodes;
2808 /* x is restored to original */
2809 state_work->s.x[atom][d] = x_min;
2811 for (j = 0; j < natoms; j++)
2813 for (k = 0; (k < DIM); k++)
2816 -(state_work->f[j][k] - fneg[j][k])/(2*der_range);
2824 #define mpi_type MPI_DOUBLE
2826 #define mpi_type MPI_FLOAT
2828 MPI_Send(dfdx[0], natoms*DIM, mpi_type, MASTERNODE(cr), cr->nodeid,
2829 cr->mpi_comm_mygroup);
2834 for (node = 0; (node < nnodes && atom+node < natoms); node++)
2840 MPI_Recv(dfdx[0], natoms*DIM, mpi_type, node, node,
2841 cr->mpi_comm_mygroup, &stat);
2846 row = (atom + node)*DIM + d;
2848 for (j = 0; j < natoms; j++)
2850 for (k = 0; k < DIM; k++)
2856 if (col >= row && dfdx[j][k] != 0.0)
2858 gmx_sparsematrix_increment_value(sparse_matrix,
2859 row, col, dfdx[j][k]);
2864 full_matrix[row*sz+col] = dfdx[j][k];
2871 if (bVerbose && fplog)
2876 /* write progress */
2877 if (bIsMaster && bVerbose)
2879 fprintf(stderr, "\rFinished step %d out of %d",
2880 std::min(atom+nnodes, natoms), natoms);
2887 fprintf(stderr, "\n\nWriting Hessian...\n");
2888 gmx_mtxio_write(ftp2fn(efMTX, nfile, fnm), sz, sz, full_matrix, sparse_matrix);
2891 finish_em(cr, outf, walltime_accounting, wcycle);
2893 walltime_accounting_set_nsteps_done(walltime_accounting, natoms*2);