Skip to content
Snippets Groups Projects
minimize.cpp 106 KiB
Newer Older
carlocamilloni's avatar
carlocamilloni committed
            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)
{
    double sum;

    /* This is just the classical Polak-Ribiere calculation of beta;
     * it looks a bit complicated since we take freeze groups into account,
     * and might have to sum it in parallel runs.
     */

    if (!DOMAINDECOMP(cr) ||
        (s_min->s.ddp_count == cr->dd->ddp_count &&
         s_b->s.ddp_count   == cr->dd->ddp_count))
    {
        const rvec *fm  = as_rvec_array(s_min->f.data());
        const rvec *fb  = as_rvec_array(s_b->f.data());
        sum             = 0;
        int         gf  = 0;
        /* This part of code can be incorrect with DD,
         * since the atom ordering in s_b and s_min might differ.
         */
        for (int i = 0; i < mdatoms->homenr; i++)
        {
            if (mdatoms->cFREEZE)
            {
                gf = mdatoms->cFREEZE[i];
            }
            for (int m = 0; m < DIM; m++)
            {
                if (!opts->nFreeze[gf][m])
                {
                    sum += (fb[i][m] - fm[i][m])*fb[i][m];
                }
            }
        }
    }
    else
    {
        /* We need to reorder cgs while summing */
        sum = reorder_partsum(cr, opts, mdatoms, top_global, s_min, s_b);
    }
    if (PAR(cr))
    {
        gmx_sumd(1, &sum, cr);
    }

    return sum/gmx::square(s_min->fnorm);
}

namespace gmx
{

/*! \brief Do conjugate gradients minimization
    \copydoc integrator_t(FILE *fplog, t_commrec *cr, const gmx::MDLogger &mdlog,
                           int nfile, const t_filenm fnm[],
                           const gmx_output_env_t *oenv,
                           const MdrunOptions &mdrunOptions,
                           gmx_vsite_t *vsite, gmx_constr_t constr,
                           gmx::IMDOutputProvider *outputProvider,
                           t_inputrec *inputrec,
                           gmx_mtop_t *top_global, t_fcdata *fcd,
                           t_state *state_global,
                           gmx::MDAtoms *mdAtoms,
                           t_nrnb *nrnb, gmx_wallcycle_t wcycle,
                           gmx_edsam_t ed,
                           t_forcerec *fr,
                           const ReplicaExchangeParameters &replExParams,
                           gmx_membed_t gmx_unused *membed,
                           gmx_walltime_accounting_t walltime_accounting)
 */
double do_cg(FILE *fplog, t_commrec *cr, const gmx::MDLogger gmx_unused &mdlog,
             int nfile, const t_filenm fnm[],
             const gmx_output_env_t gmx_unused *oenv,
             const MdrunOptions &mdrunOptions,
             gmx_vsite_t *vsite, gmx_constr_t constr,
             gmx::IMDOutputProvider *outputProvider,
             t_inputrec *inputrec,
             gmx_mtop_t *top_global, t_fcdata *fcd,
             t_state *state_global,
             ObservablesHistory *observablesHistory,
             gmx::MDAtoms *mdAtoms,
             t_nrnb *nrnb, gmx_wallcycle_t wcycle,
             t_forcerec *fr,
             const ReplicaExchangeParameters gmx_unused &replExParams,
             gmx_membed_t gmx_unused *membed,
             gmx_walltime_accounting_t walltime_accounting)
{
    const char       *CG = "Polak-Ribiere Conjugate Gradients";

    gmx_localtop_t   *top;
    gmx_enerdata_t   *enerd;
    gmx_global_stat_t gstat;
    t_graph          *graph;
    double            tmp, minstep;
    real              stepsize;
    real              a, b, c, beta = 0.0;
    real              epot_repl = 0;
    real              pnorm;
    t_mdebin         *mdebin;
    gmx_bool          converged, foundlower;
    rvec              mu_tot;
    gmx_bool          do_log = FALSE, do_ene = FALSE, do_x, do_f;
    tensor            vir, pres;
    int               number_steps, neval = 0, nstcg = inputrec->nstcgsteep;
    gmx_mdoutf_t      outf;
    int               m, step, nminstep;
    auto              mdatoms = mdAtoms->mdatoms();

    step = 0;

    if (MASTER(cr))
    {
        // In CG, the state is extended with a search direction
        state_global->flags |= (1<<estCGP);

        // Ensure the extra per-atom state array gets allocated
        state_change_natoms(state_global, state_global->natoms);

        // Initialize the search direction to zero
        for (RVec &cg_p : state_global->cg_p)
        {
            cg_p = { 0, 0, 0 };
        }
    }
carlocamilloni's avatar
carlocamilloni committed

    /* Create 4 states on the stack and extract pointers that we will swap */
    em_state_t  s0 {}, s1 {}, s2 {}, s3 {};
    em_state_t *s_min = &s0;
    em_state_t *s_a   = &s1;
    em_state_t *s_b   = &s2;
    em_state_t *s_c   = &s3;

    /* Init em and store the local state in s_min */
    init_em(fplog, CG, cr, outputProvider, inputrec, mdrunOptions,
            state_global, top_global, s_min, &top,
            nrnb, mu_tot, fr, &enerd, &graph, mdAtoms, &gstat,
            vsite, constr, nullptr,
            nfile, fnm, &outf, &mdebin, wcycle);

    /* Print to log file */
    print_em_start(fplog, cr, walltime_accounting, wcycle, CG);

    /* Max number of steps */
    number_steps = inputrec->nsteps;

    if (MASTER(cr))
    {
        sp_header(stderr, CG, inputrec->em_tol, number_steps);
    }
    if (fplog)
    {
        sp_header(fplog, CG, inputrec->em_tol, number_steps);
    }

    /* Call the force routine and some auxiliary (neighboursearching etc.) */
    /* 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
     */
    evaluate_energy(fplog, cr,
                    top_global, s_min, top,
                    inputrec, nrnb, wcycle, gstat,
                    vsite, constr, fcd, graph, mdAtoms, fr,
                    mu_tot, enerd, vir, pres, -1, TRUE);
    where();

    if (MASTER(cr))
    {
        /* Copy stuff to the energy bin for easy printing etc. */
        upd_mdebin(mdebin, FALSE, FALSE, (double)step,
                   mdatoms->tmass, enerd, &s_min->s, inputrec->fepvals, inputrec->expandedvals, s_min->s.box,
                   nullptr, nullptr, vir, pres, nullptr, mu_tot, constr);

        print_ebin_header(fplog, step, step);
        print_ebin(mdoutf_get_fp_ene(outf), TRUE, FALSE, FALSE, fplog, step, step, eprNORMAL,
                   mdebin, fcd, &(top_global->groups), &(inputrec->opts), nullptr);
    }
    where();

    /* Estimate/guess the initial stepsize */
    stepsize = inputrec->em_stepsize/s_min->fnorm;

    if (MASTER(cr))
    {
        double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));
        fprintf(stderr, "   F-max             = %12.5e on atom %d\n",
                s_min->fmax, s_min->a_fmax+1);
        fprintf(stderr, "   F-Norm            = %12.5e\n",
                s_min->fnorm/sqrtNumAtoms);
        fprintf(stderr, "\n");
        /* and copy to the log file too... */
        fprintf(fplog, "   F-max             = %12.5e on atom %d\n",
                s_min->fmax, s_min->a_fmax+1);
        fprintf(fplog, "   F-Norm            = %12.5e\n",
                s_min->fnorm/sqrtNumAtoms);
        fprintf(fplog, "\n");
    }
    /* Start the loop over CG steps.
     * Each successful step is counted, and we continue until
     * we either converge or reach the max number of steps.
     */
    converged = FALSE;
    for (step = 0; (number_steps < 0 || step <= number_steps) && !converged; step++)
    {

        /* start taking steps in a new direction
         * First time we enter the routine, beta=0, and the direction is
         * simply the negative gradient.
         */

        /* Calculate the new direction in p, and the gradient in this direction, gpa */
        rvec       *pm  = as_rvec_array(s_min->s.cg_p.data());
        const rvec *sfm = as_rvec_array(s_min->f.data());
        double      gpa = 0;
        int         gf  = 0;
        for (int i = 0; i < mdatoms->homenr; i++)
        {
            if (mdatoms->cFREEZE)
            {
                gf = mdatoms->cFREEZE[i];
            }
            for (m = 0; m < DIM; m++)
            {
                if (!inputrec->opts.nFreeze[gf][m])
                {
                    pm[i][m] = sfm[i][m] + beta*pm[i][m];
                    gpa     -= pm[i][m]*sfm[i][m];
                    /* f is negative gradient, thus the sign */
                }
                else
                {
                    pm[i][m] = 0;
                }
            }
        }

        /* Sum the gradient along the line across CPUs */
        if (PAR(cr))
        {
            gmx_sumd(1, &gpa, cr);
        }

        /* Calculate the norm of the search vector */
        get_f_norm_max(cr, &(inputrec->opts), mdatoms, pm, &pnorm, nullptr, nullptr);

        /* Just in case stepsize reaches zero due to numerical precision... */
        if (stepsize <= 0)
        {
            stepsize = inputrec->em_stepsize/pnorm;
        }

        /*
         * Double check the value of the derivative in the search direction.
         * If it is positive it must be due to the old information in the
         * CG formula, so just remove that and start over with beta=0.
         * This corresponds to a steepest descent step.
         */
        if (gpa > 0)
        {
            beta = 0;
            step--;   /* Don't count this step since we are restarting */
            continue; /* Go back to the beginning of the big for-loop */
        }

        /* Calculate minimum allowed stepsize, before the average (norm)
         * relative change in coordinate is smaller than precision
         */
        minstep = 0;
        for (int i = 0; i < mdatoms->homenr; i++)
        {
            for (m = 0; m < DIM; m++)
            {
                tmp = fabs(s_min->s.x[i][m]);
                if (tmp < 1.0)
                {
                    tmp = 1.0;
                }
                tmp      = pm[i][m]/tmp;
                minstep += tmp*tmp;
            }
        }
        /* Add up from all CPUs */
        if (PAR(cr))
        {
            gmx_sumd(1, &minstep, cr);
        }

        minstep = GMX_REAL_EPS/sqrt(minstep/(3*top_global->natoms));
carlocamilloni's avatar
carlocamilloni committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637

        if (stepsize < minstep)
        {
            converged = TRUE;
            break;
        }

        /* Write coordinates if necessary */
        do_x = do_per_step(step, inputrec->nstxout);
        do_f = do_per_step(step, inputrec->nstfout);

        write_em_traj(fplog, cr, outf, do_x, do_f, nullptr,
                      top_global, inputrec, step,
                      s_min, state_global, observablesHistory);

        /* Take a step downhill.
         * In theory, we should minimize the function along this direction.
         * That is quite possible, but it turns out to take 5-10 function evaluations
         * for each line. However, we dont really need to find the exact minimum -
         * it is much better to start a new CG step in a modified direction as soon
         * as we are close to it. This will save a lot of energy evaluations.
         *
         * In practice, we just try to take a single step.
         * If it worked (i.e. lowered the energy), we increase the stepsize but
         * the continue straight to the next CG step without trying to find any minimum.
         * If it didn't work (higher energy), there must be a minimum somewhere between
         * the old position and the new one.
         *
         * Due to the finite numerical accuracy, it turns out that it is a good idea
         * to even accept a SMALL increase in energy, if the derivative is still downhill.
         * This leads to lower final energies in the tests I've done. / Erik
         */
        s_a->epot = s_min->epot;
        a         = 0.0;
        c         = a + stepsize; /* reference position along line is zero */

        if (DOMAINDECOMP(cr) && s_min->s.ddp_count < cr->dd->ddp_count)
        {
            em_dd_partition_system(fplog, step, cr, top_global, inputrec,
                                   s_min, top, mdAtoms, fr, vsite, constr,
                                   nrnb, wcycle);
        }

        /* Take a trial step (new coords in s_c) */
        do_em_step(cr, inputrec, mdatoms, fr->bMolPBC, s_min, c, &s_min->s.cg_p, s_c,
                   constr, top, nrnb, wcycle, -1);

        neval++;
        /* Calculate energy for the trial step */
        evaluate_energy(fplog, cr,
                        top_global, s_c, top,
                        inputrec, nrnb, wcycle, gstat,
                        vsite, constr, fcd, graph, mdAtoms, fr,
                        mu_tot, enerd, vir, pres, -1, FALSE);

        /* Calc derivative along line */
        const rvec *pc  = as_rvec_array(s_c->s.cg_p.data());
        const rvec *sfc = as_rvec_array(s_c->f.data());
        double      gpc = 0;
        for (int i = 0; i < mdatoms->homenr; i++)
        {
            for (m = 0; m < DIM; m++)
            {
                gpc -= pc[i][m]*sfc[i][m]; /* f is negative gradient, thus the sign */
            }
        }
        /* Sum the gradient along the line across CPUs */
        if (PAR(cr))
        {
            gmx_sumd(1, &gpc, cr);
        }

        /* This is the max amount of increase in energy we tolerate */
        tmp = sqrt(GMX_REAL_EPS)*fabs(s_a->epot);

        /* Accept the step if the energy is lower, or if it is not significantly higher
         * and the line derivative is still negative.
         */
        if (s_c->epot < s_a->epot || (gpc < 0 && s_c->epot < (s_a->epot + tmp)))
        {
            foundlower = TRUE;
            /* Great, we found a better energy. Increase step for next iteration
             * if we are still going down, decrease it otherwise
             */
            if (gpc < 0)
            {
                stepsize *= 1.618034; /* The golden section */
            }
            else
            {
                stepsize *= 0.618034; /* 1/golden section */
            }
        }
        else
        {
            /* New energy is the same or higher. We will have to do some work
             * to find a smaller value in the interval. Take smaller step next time!
             */
            foundlower = FALSE;
            stepsize  *= 0.618034;
        }




        /* OK, if we didn't find a lower value we will have to locate one now - there must
         * be one in the interval [a=0,c].
         * The same thing is valid here, though: Don't spend dozens of iterations to find
         * the line minimum. We try to interpolate based on the derivative at the endpoints,
         * and only continue until we find a lower value. In most cases this means 1-2 iterations.
         *
         * I also have a safeguard for potentially really pathological functions so we never
         * take more than 20 steps before we give up ...
         *
         * If we already found a lower value we just skip this step and continue to the update.
         */
        double gpb;
        if (!foundlower)
        {
            nminstep = 0;

            do
            {
                /* Select a new trial point.
                 * If the derivatives at points a & c have different sign we interpolate to zero,
                 * otherwise just do a bisection.
                 */
                if (gpa < 0 && gpc > 0)
                {
                    b = a + gpa*(a-c)/(gpc-gpa);
                }
                else
                {
                    b = 0.5*(a+c);
                }

                /* safeguard if interpolation close to machine accuracy causes errors:
                 * never go outside the interval
                 */
                if (b <= a || b >= c)
                {
                    b = 0.5*(a+c);
                }

                if (DOMAINDECOMP(cr) && s_min->s.ddp_count != cr->dd->ddp_count)
                {
                    /* Reload the old state */
                    em_dd_partition_system(fplog, -1, cr, top_global, inputrec,
                                           s_min, top, mdAtoms, fr, vsite, constr,
                                           nrnb, wcycle);
                }

                /* Take a trial step to this new point - new coords in s_b */
                do_em_step(cr, inputrec, mdatoms, fr->bMolPBC, s_min, b, &s_min->s.cg_p, s_b,
                           constr, top, nrnb, wcycle, -1);

                neval++;
                /* Calculate energy for the trial step */
                evaluate_energy(fplog, cr,
                                top_global, s_b, top,
                                inputrec, nrnb, wcycle, gstat,
                                vsite, constr, fcd, graph, mdAtoms, fr,
                                mu_tot, enerd, vir, pres, -1, FALSE);

                /* p does not change within a step, but since the domain decomposition
                 * might change, we have to use cg_p of s_b here.
                 */
                const rvec *pb  = as_rvec_array(s_b->s.cg_p.data());
                const rvec *sfb = as_rvec_array(s_b->f.data());
                gpb             = 0;
                for (int i = 0; i < mdatoms->homenr; i++)
                {
                    for (m = 0; m < DIM; m++)
                    {
                        gpb -= pb[i][m]*sfb[i][m]; /* f is negative gradient, thus the sign */
                    }
                }
                /* Sum the gradient along the line across CPUs */
                if (PAR(cr))
                {
                    gmx_sumd(1, &gpb, cr);
                }

                if (debug)
                {
                    fprintf(debug, "CGE: EpotA %f EpotB %f EpotC %f gpb %f\n",
                            s_a->epot, s_b->epot, s_c->epot, gpb);
                }

                epot_repl = s_b->epot;

                /* Keep one of the intervals based on the value of the derivative at the new point */
                if (gpb > 0)
                {
                    /* Replace c endpoint with b */
                    swap_em_state(&s_b, &s_c);
                    c   = b;
                    gpc = gpb;
                }
                else
                {
                    /* Replace a endpoint with b */
                    swap_em_state(&s_b, &s_a);
                    a   = b;
                    gpa = gpb;
                }

                /*
                 * Stop search as soon as we find a value smaller than the endpoints.
                 * Never run more than 20 steps, no matter what.
                 */
                nminstep++;
            }
            while ((epot_repl > s_a->epot || epot_repl > s_c->epot) &&
                   (nminstep < 20));

            if (fabs(epot_repl - s_min->epot) < fabs(s_min->epot)*GMX_REAL_EPS ||
                nminstep >= 20)
            {
                /* OK. We couldn't find a significantly lower energy.
                 * If beta==0 this was steepest descent, and then we give up.
                 * If not, set beta=0 and restart with steepest descent before quitting.
                 */
                if (beta == 0.0)
                {
                    /* Converged */
                    converged = TRUE;
                    break;
                }
                else
                {
                    /* Reset memory before giving up */
                    beta = 0.0;
                    continue;
                }
            }

            /* Select min energy state of A & C, put the best in B.
             */
            if (s_c->epot < s_a->epot)
            {
                if (debug)
                {
                    fprintf(debug, "CGE: C (%f) is lower than A (%f), moving C to B\n",
                            s_c->epot, s_a->epot);
                }
                swap_em_state(&s_b, &s_c);
                gpb = gpc;
            }
            else
            {
                if (debug)
                {
                    fprintf(debug, "CGE: A (%f) is lower than C (%f), moving A to B\n",
                            s_a->epot, s_c->epot);
                }
                swap_em_state(&s_b, &s_a);
                gpb = gpa;
            }

        }
        else
        {
            if (debug)
            {
                fprintf(debug, "CGE: Found a lower energy %f, moving C to B\n",
                        s_c->epot);
            }
            swap_em_state(&s_b, &s_c);
            gpb = gpc;
        }

        /* new search direction */
        /* beta = 0 means forget all memory and restart with steepest descents. */
        if (nstcg && ((step % nstcg) == 0))
        {
            beta = 0.0;
        }
        else
        {
            /* s_min->fnorm cannot be zero, because then we would have converged
             * and broken out.
             */

            /* Polak-Ribiere update.
             * Change to fnorm2/fnorm2_old for Fletcher-Reeves
             */
            beta = pr_beta(cr, &inputrec->opts, mdatoms, top_global, s_min, s_b);
        }
        /* Limit beta to prevent oscillations */
        if (fabs(beta) > 5.0)
        {
            beta = 0.0;
        }


        /* update positions */
        swap_em_state(&s_min, &s_b);
        gpa = gpb;

        /* Print it if necessary */
        if (MASTER(cr))
        {
            if (mdrunOptions.verbose)
            {
                double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));
                fprintf(stderr, "\rStep %d, Epot=%12.6e, Fnorm=%9.3e, Fmax=%9.3e (atom %d)\n",
                        step, s_min->epot, s_min->fnorm/sqrtNumAtoms,
                        s_min->fmax, s_min->a_fmax+1);
                fflush(stderr);
            }
            /* Store the new (lower) energies */
            upd_mdebin(mdebin, FALSE, FALSE, (double)step,
                       mdatoms->tmass, enerd, &s_min->s, inputrec->fepvals, inputrec->expandedvals, s_min->s.box,
                       nullptr, nullptr, vir, pres, nullptr, mu_tot, constr);

            do_log = do_per_step(step, inputrec->nstlog);
            do_ene = do_per_step(step, inputrec->nstenergy);

            /* Prepare IMD energy record, if bIMD is TRUE. */
            IMD_fill_energy_record(inputrec->bIMD, inputrec->imd, enerd, step, TRUE);

            if (do_log)
            {
                print_ebin_header(fplog, step, step);
            }
            print_ebin(mdoutf_get_fp_ene(outf), do_ene, FALSE, FALSE,
                       do_log ? fplog : nullptr, step, step, eprNORMAL,
                       mdebin, fcd, &(top_global->groups), &(inputrec->opts), nullptr);
        }

        /* Send energies and positions to the IMD client if bIMD is TRUE. */
        if (MASTER(cr) && do_IMD(inputrec->bIMD, step, cr, TRUE, state_global->box, as_rvec_array(state_global->x.data()), inputrec, 0, wcycle))
carlocamilloni's avatar
carlocamilloni committed
        {
            IMD_send_positions(inputrec->imd);
        }

        /* Stop when the maximum force lies below tolerance.
         * If we have reached machine precision, converged is already set to true.
         */
        converged = converged || (s_min->fmax < inputrec->em_tol);

    }   /* End of the loop */

    /* IMD cleanup, if bIMD is TRUE. */
    IMD_finalize(inputrec->bIMD, inputrec->imd);

    if (converged)
    {
        step--; /* we never took that last step in this case */

    }
    if (s_min->fmax > inputrec->em_tol)
    {
        if (MASTER(cr))
        {
            warn_step(stderr, inputrec->em_tol, step-1 == number_steps, FALSE);
            warn_step(fplog, inputrec->em_tol, step-1 == number_steps, FALSE);
        }
        converged = FALSE;
    }

    if (MASTER(cr))
    {
        /* If we printed energy and/or logfile last step (which was the last step)
         * we don't have to do it again, but otherwise print the final values.
         */
        if (!do_log)
        {
            /* Write final value to log since we didn't do anything the last step */
            print_ebin_header(fplog, step, step);
        }
        if (!do_ene || !do_log)
        {
            /* Write final energy file entries */
            print_ebin(mdoutf_get_fp_ene(outf), !do_ene, FALSE, FALSE,
                       !do_log ? fplog : nullptr, step, step, eprNORMAL,
                       mdebin, fcd, &(top_global->groups), &(inputrec->opts), nullptr);
        }
    }

    /* Print some stuff... */
    if (MASTER(cr))
    {
        fprintf(stderr, "\nwriting lowest energy coordinates.\n");
    }

    /* IMPORTANT!
     * For accurate normal mode calculation it is imperative that we
     * store the last conformation into the full precision binary trajectory.
     *
     * However, we should only do it if we did NOT already write this step
     * above (which we did if do_x or do_f was true).
     */
    /* Note that with 0 < nstfout != nstxout we can end up with two frames
     * in the trajectory with the same step number.
     */
carlocamilloni's avatar
carlocamilloni committed
    do_x = !do_per_step(step, inputrec->nstxout);
    do_f = (inputrec->nstfout > 0 && !do_per_step(step, inputrec->nstfout));

    write_em_traj(fplog, cr, outf, do_x, do_f, ftp2fn(efSTO, nfile, fnm),
                  top_global, inputrec, step,
                  s_min, state_global, observablesHistory);


    if (MASTER(cr))
    {
        double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));
        print_converged(stderr, CG, inputrec->em_tol, step, converged, number_steps,
                        s_min, sqrtNumAtoms);
        print_converged(fplog, CG, inputrec->em_tol, step, converged, number_steps,
                        s_min, sqrtNumAtoms);

        fprintf(fplog, "\nPerformed %d energy evaluations in total.\n", neval);
    }

    finish_em(cr, outf, walltime_accounting, wcycle);

    /* To print the actual number of steps we needed somewhere */
    walltime_accounting_set_nsteps_done(walltime_accounting, step);

    return 0;
}   /* That's all folks */


/*! \brief Do L-BFGS conjugate gradients minimization
    \copydoc integrator_t(FILE *fplog, t_commrec *cr, const gmx::MDLogger &mdlog,
                          int nfile, const t_filenm fnm[],
                          const gmx_output_env_t *oenv,
                          const MdrunOptions &mdrunOptions,
                          gmx_vsite_t *vsite, gmx_constr_t constr,
                          gmx::IMDOutputProvider *outputProvider,
                          t_inputrec *inputrec,
                          gmx_mtop_t *top_global, t_fcdata *fcd,
                          t_state *state_global,
                          gmx::MDAtoms *mdAtoms,
                          t_nrnb *nrnb, gmx_wallcycle_t wcycle,
                          gmx_edsam_t ed,
                          t_forcerec *fr,
                          const ReplicaExchangeParameters &replExParams,
                          gmx_membed_t gmx_unused *membed,
                          gmx_walltime_accounting_t walltime_accounting)
 */
double do_lbfgs(FILE *fplog, t_commrec *cr, const gmx::MDLogger gmx_unused &mdlog,
                int nfile, const t_filenm fnm[],
                const gmx_output_env_t gmx_unused *oenv,
                const MdrunOptions &mdrunOptions,
                gmx_vsite_t *vsite, gmx_constr_t constr,
                gmx::IMDOutputProvider *outputProvider,
                t_inputrec *inputrec,
                gmx_mtop_t *top_global, t_fcdata *fcd,
                t_state *state_global,
                ObservablesHistory *observablesHistory,
                gmx::MDAtoms *mdAtoms,
                t_nrnb *nrnb, gmx_wallcycle_t wcycle,
                t_forcerec *fr,
                const ReplicaExchangeParameters gmx_unused &replExParams,
                gmx_membed_t gmx_unused *membed,
                gmx_walltime_accounting_t walltime_accounting)
{
    static const char *LBFGS = "Low-Memory BFGS Minimizer";
    em_state_t         ems;
    gmx_localtop_t    *top;
    gmx_enerdata_t    *enerd;
    gmx_global_stat_t  gstat;
    t_graph           *graph;
    int                ncorr, nmaxcorr, point, cp, neval, nminstep;
    double             stepsize, step_taken, gpa, gpb, gpc, tmp, minstep;
    real              *rho, *alpha, *p, *s, **dx, **dg;
    real               a, b, c, maxdelta, delta;
    real               diag, Epot0;
    real               dgdx, dgdg, sq, yr, beta;
    t_mdebin          *mdebin;
    gmx_bool           converged;
    rvec               mu_tot;
    gmx_bool           do_log, do_ene, do_x, do_f, foundlower, *frozen;
    tensor             vir, pres;
    int                start, end, number_steps;
    gmx_mdoutf_t       outf;
    int                i, k, m, n, gf, step;
    int                mdof_flags;
    auto               mdatoms = mdAtoms->mdatoms();

    if (PAR(cr))
    {
        gmx_fatal(FARGS, "Cannot do parallel L-BFGS Minimization - yet.\n");
    }

    if (nullptr != constr)
    {
        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).");
    }

    n        = 3*state_global->natoms;
    nmaxcorr = inputrec->nbfgscorr;

    snew(frozen, n);

    snew(p, n);
    snew(rho, nmaxcorr);
    snew(alpha, nmaxcorr);

    snew(dx, nmaxcorr);
    for (i = 0; i < nmaxcorr; i++)
    {
        snew(dx[i], n);
    }

    snew(dg, nmaxcorr);
    for (i = 0; i < nmaxcorr; i++)
    {
        snew(dg[i], n);
    }

    step  = 0;
    neval = 0;

    /* Init em */
    init_em(fplog, LBFGS, cr, outputProvider, inputrec, mdrunOptions,
            state_global, top_global, &ems, &top,
            nrnb, mu_tot, fr, &enerd, &graph, mdAtoms, &gstat,
            vsite, constr, nullptr,
            nfile, fnm, &outf, &mdebin, wcycle);

    start = 0;
    end   = mdatoms->homenr;

    /* We need 4 working states */
    em_state_t  s0 {}, s1 {}, s2 {}, s3 {};
    em_state_t *sa   = &s0;
    em_state_t *sb   = &s1;
    em_state_t *sc   = &s2;
    em_state_t *last = &s3;
    /* Initialize by copying the state from ems (we could skip x and f here) */
    *sa              = ems;
    *sb              = ems;
    *sc              = ems;

    /* Print to log file */
    print_em_start(fplog, cr, walltime_accounting, wcycle, LBFGS);

    do_log = do_ene = do_x = do_f = TRUE;

    /* Max number of steps */
    number_steps = inputrec->nsteps;

    /* Create a 3*natoms index to tell whether each degree of freedom is frozen */
    gf = 0;
    for (i = start; i < end; i++)
    {
        if (mdatoms->cFREEZE)
        {
            gf = mdatoms->cFREEZE[i];
        }
        for (m = 0; m < DIM; m++)
        {
            frozen[3*i+m] = inputrec->opts.nFreeze[gf][m];
        }
    }
    if (MASTER(cr))
    {
        sp_header(stderr, LBFGS, inputrec->em_tol, number_steps);
    }
    if (fplog)
    {
        sp_header(fplog, LBFGS, inputrec->em_tol, number_steps);
    }

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

    /* Call the force routine and some auxiliary (neighboursearching etc.) */
    /* do_force always puts the charge groups in the box and shifts again
     * We do not unshift, so molecules are always whole
     */
    neval++;
    evaluate_energy(fplog, cr,
                    top_global, &ems, top,
                    inputrec, nrnb, wcycle, gstat,
                    vsite, constr, fcd, graph, mdAtoms, fr,
                    mu_tot, enerd, vir, pres, -1, TRUE);
    where();

    if (MASTER(cr))
    {
        /* Copy stuff to the energy bin for easy printing etc. */
        upd_mdebin(mdebin, FALSE, FALSE, (double)step,
                   mdatoms->tmass, enerd, state_global, inputrec->fepvals, inputrec->expandedvals, state_global->box,
                   nullptr, nullptr, vir, pres, nullptr, mu_tot, constr);

        print_ebin_header(fplog, step, step);
        print_ebin(mdoutf_get_fp_ene(outf), TRUE, FALSE, FALSE, fplog, step, step, eprNORMAL,
                   mdebin, fcd, &(top_global->groups), &(inputrec->opts), nullptr);
    }
    where();

    /* Set the initial step.
     * since it will be multiplied by the non-normalized search direction
     * vector (force vector the first time), we scale it by the
     * norm of the force.
     */

    if (MASTER(cr))
    {
        double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));
        fprintf(stderr, "Using %d BFGS correction steps.\n\n", nmaxcorr);
        fprintf(stderr, "   F-max             = %12.5e on atom %d\n", ems.fmax, ems.a_fmax + 1);
        fprintf(stderr, "   F-Norm            = %12.5e\n", ems.fnorm/sqrtNumAtoms);
        fprintf(stderr, "\n");
        /* and copy to the log file too... */
        fprintf(fplog, "Using %d BFGS correction steps.\n\n", nmaxcorr);
        fprintf(fplog, "   F-max             = %12.5e on atom %d\n", ems.fmax, ems.a_fmax + 1);
        fprintf(fplog, "   F-Norm            = %12.5e\n", ems.fnorm/sqrtNumAtoms);
        fprintf(fplog, "\n");
    }

    // Point is an index to the memory of search directions, where 0 is the first one.
    point = 0;

    // Set initial search direction to the force (-gradient), or 0 for frozen particles.
    real *fInit = static_cast<real *>(as_rvec_array(ems.f.data())[0]);
    for (i = 0; i < n; i++)
    {
        if (!frozen[i])
        {
            dx[point][i] = fInit[i]; /* Initial search direction */
        }
        else
        {
            dx[point][i] = 0;
        }
    }

    // Stepsize will be modified during the search, and actually it is not critical
    // (the main efficiency in the algorithm comes from changing directions), but
    // we still need an initial value, so estimate it as the inverse of the norm
    // so we take small steps where the potential fluctuates a lot.
    stepsize  = 1.0/ems.fnorm;

    /* Start the loop over BFGS steps.
     * Each successful step is counted, and we continue until
     * we either converge or reach the max number of steps.
     */

    ncorr = 0;

    /* Set the gradient from the force */
    converged = FALSE;
    for (step = 0; (number_steps < 0 || step <= number_steps) && !converged; step++)
    {

        /* Write coordinates if necessary */
        do_x = do_per_step(step, inputrec->nstxout);
        do_f = do_per_step(step, inputrec->nstfout);

        mdof_flags = 0;
        if (do_x)
        {
            mdof_flags |= MDOF_X;
        }

        if (do_f)
        {
            mdof_flags |= MDOF_F;
        }

        if (inputrec->bIMD)
        {
            mdof_flags |= MDOF_IMD;
        }

        mdoutf_write_to_trajectory_files(fplog, cr, outf, mdof_flags,
                                         top_global, step, (real)step, &ems.s, state_global, observablesHistory, ems.f);

        /* Do the linesearching in the direction dx[point][0..(n-1)] */

        /* make s a pointer to current search direction - point=0 first time we get here */
        s = dx[point];

        real *xx = static_cast<real *>(as_rvec_array(ems.s.x.data())[0]);
        real *ff = static_cast<real *>(as_rvec_array(ems.f.data())[0]);

        // calculate line gradient in position A
        for (gpa = 0, i = 0; i < n; i++)
        {
            gpa -= s[i]*ff[i];
        }

        /* Calculate minimum allowed stepsize along the line, before the average (norm)
         * relative change in coordinate is smaller than precision
         */