Skip to content
Snippets Groups Projects
minimize.cpp 106 KiB
Newer Older
carlocamilloni's avatar
carlocamilloni committed
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
        for (minstep = 0, i = 0; i < n; i++)
        {
            tmp = fabs(xx[i]);
            if (tmp < 1.0)
            {
                tmp = 1.0;
            }
            tmp      = s[i]/tmp;
            minstep += tmp*tmp;
        }
        minstep = GMX_REAL_EPS/sqrt(minstep/n);

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

        // Before taking any steps along the line, store the old position
        *last       = ems;
        real *lastx = static_cast<real *>(as_rvec_array(last->s.x.data())[0]);
        real *lastf = static_cast<real *>(as_rvec_array(last->f.data())[0]);
        Epot0       = ems.epot;

        *sa         = ems;

        /* Take a step downhill.
         * In theory, we should find the actual minimum of the function in this
         * direction, somewhere along the line.
         * 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 BFGS 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
         * continue straight to the next BFGS step without trying to find any minimum,
         * i.e. we change the search direction too. If the line was smooth, it is
         * likely we are in a smooth region, and then it makes sense to take longer
         * steps in the modified search direction too.
         *
         * If it didn't work (higher energy), there must be a minimum somewhere between
         * the old position and the new one. Then we need to start by finding a lower
         * value before we change search direction. Since the energy was apparently
         * quite rough, we need to decrease the step size.
         *
         * Due to the finite numerical accuracy, it turns out that it is a good idea
         * to 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
         */

        // State "A" is the first position along the line.
        // reference position along line is initially zero
        a          = 0.0;

        // Check stepsize first. We do not allow displacements
        // larger than emstep.
        //
        do
        {
            // Pick a new position C by adding stepsize to A.
            c        = a + stepsize;

            // Calculate what the largest change in any individual coordinate
            // would be (translation along line * gradient along line)
            maxdelta = 0;
            for (i = 0; i < n; i++)
            {
                delta = c*s[i];
                if (delta > maxdelta)
                {
                    maxdelta = delta;
                }
            }
            // If any displacement is larger than the stepsize limit, reduce the step
            if (maxdelta > inputrec->em_stepsize)
            {
                stepsize *= 0.1;
            }
        }
        while (maxdelta > inputrec->em_stepsize);

        // Take a trial step and move the coordinate array xc[] to position C
        real *xc = static_cast<real *>(as_rvec_array(sc->s.x.data())[0]);
        for (i = 0; i < n; i++)
        {
            xc[i] = lastx[i] + c*s[i];
        }

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

        // Calc line gradient in position C
        real *fc = static_cast<real *>(as_rvec_array(sc->f.data())[0]);
        for (gpc = 0, i = 0; i < n; i++)
        {
            gpc -= s[i]*fc[i]; /* 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.
        // By allowing VERY small changes (close to numerical precision) we
        // frequently find even better (lower) final energies.
        tmp = sqrt(GMX_REAL_EPS)*fabs(sa->epot);

        // Accept the step if the energy is lower in the new position C (compared to A),
        // or if it is not significantly higher and the line derivative is still negative.
        if (sc->epot < sa->epot || (gpc < 0 && sc->epot < (sa->epot + tmp)))
        {
            // Great, we found a better energy. We no longer try to alter the
            // stepsize, but simply accept this new better position. The we select a new
            // search direction instead, which will be much more efficient than continuing
            // to take smaller steps along a line. Set fnorm based on the new C position,
            // which will be used to update the stepsize to 1/fnorm further down.
            foundlower = TRUE;
        }
        else
        {
            // If we got here, the energy is NOT lower in point C, i.e. it will be the same
            // or higher than in point A. In this case it is pointless to move to point C,
            // so we will have to do more iterations along the same line to find a smaller
            // value in the interval [A=0.0,C].
            // Here, A is still 0.0, but that will change when we do a search in the interval
            // [0.0,C] below. That search we will do by interpolation or bisection rather
            // than with the stepsize, so no need to modify it. For the next search direction
            // it will be reset to 1/fnorm anyway.
            foundlower = FALSE;
        }

        if (!foundlower)
        {
            // OK, if we didn't find a lower value we will have to locate one now - there must
            // be one in the interval [a,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.
            real fnorm = 0;
            nminstep   = 0;
            do
            {
                // Select a new trial point B in the interval [A,C].
                // If the derivatives at points a & c have different sign we interpolate to zero,
                // otherwise just do a bisection since there might be multiple minima/maxima
                // inside the interval.
                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);
                }

                // Take a trial step to point B
                real *xb = static_cast<real *>(as_rvec_array(sb->s.x.data())[0]);
                for (i = 0; i < n; i++)
                {
                    xb[i] = lastx[i] + b*s[i];
                }

                neval++;
                // Calculate energy for the trial step in point B
                evaluate_energy(fplog, cr,
                                top_global, sb, top,
                                inputrec, nrnb, wcycle, gstat,
                                vsite, constr, fcd, graph, mdAtoms, fr,
                                mu_tot, enerd, vir, pres, step, FALSE);
                fnorm = sb->fnorm;

                // Calculate gradient in point B
                real *fb = static_cast<real *>(as_rvec_array(sb->f.data())[0]);
                for (gpb = 0, i = 0; i < n; i++)
                {
                    gpb -= s[i]*fb[i]; /* f is negative gradient, thus the sign */

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

                // Keep one of the intervals [A,B] or [B,C] based on the value of the derivative
                // at the new point B, and rename the endpoints of this new interval A and C.
                if (gpb > 0)
                {
                    /* Replace c endpoint with b */
                    c   = b;
                    /* swap states b and c */
                    swap_em_state(&sb, &sc);
                }
                else
                {
                    /* Replace a endpoint with b */
                    a   = b;
                    /* swap states a and b */
                    swap_em_state(&sa, &sb);
                }

                /*
                 * Stop search as soon as we find a value smaller than the endpoints,
                 * or if the tolerance is below machine precision.
                 * Never run more than 20 steps, no matter what.
                 */
                nminstep++;
            }
            while ((sb->epot > sa->epot || sb->epot > sc->epot) && (nminstep < 20));

            if (fabs(sb->epot - Epot0) < GMX_REAL_EPS || nminstep >= 20)
            {
                /* OK. We couldn't find a significantly lower energy.
                 * If ncorr==0 this was steepest descent, and then we give up.
                 * If not, reset memory to restart as steepest descent before quitting.
                 */
                if (ncorr == 0)
                {
                    /* Converged */
                    converged = TRUE;
                    break;
                }
                else
                {
                    /* Reset memory */
                    ncorr = 0;
                    /* Search in gradient direction */
                    for (i = 0; i < n; i++)
                    {
                        dx[point][i] = ff[i];
                    }
                    /* Reset stepsize */
                    stepsize = 1.0/fnorm;
                    continue;
                }
            }

            /* Select min energy state of A & C, put the best in xx/ff/Epot
             */
            if (sc->epot < sa->epot)
            {
                /* Use state C */
                ems        = *sc;
                step_taken = c;
            }
            else
            {
                /* Use state A */
                ems        = *sa;
                step_taken = a;
            }

        }
        else
        {
            /* found lower */
            /* Use state C */
            ems        = *sc;
            step_taken = c;
        }

        /* Update the memory information, and calculate a new
         * approximation of the inverse hessian
         */

        /* Have new data in Epot, xx, ff */
        if (ncorr < nmaxcorr)
        {
            ncorr++;
        }

        for (i = 0; i < n; i++)
        {
            dg[point][i]  = lastf[i]-ff[i];
            dx[point][i] *= step_taken;
        }

        dgdg = 0;
        dgdx = 0;
        for (i = 0; i < n; i++)
        {
            dgdg += dg[point][i]*dg[point][i];
            dgdx += dg[point][i]*dx[point][i];
        }

        diag = dgdx/dgdg;

        rho[point] = 1.0/dgdx;
        point++;

        if (point >= nmaxcorr)
        {
            point = 0;
        }

        /* Update */
        for (i = 0; i < n; i++)
        {
            p[i] = ff[i];
        }

        cp = point;

        /* Recursive update. First go back over the memory points */
        for (k = 0; k < ncorr; k++)
        {
            cp--;
            if (cp < 0)
            {
                cp = ncorr-1;
            }

            sq = 0;
            for (i = 0; i < n; i++)
            {
                sq += dx[cp][i]*p[i];
            }

            alpha[cp] = rho[cp]*sq;

            for (i = 0; i < n; i++)
            {
                p[i] -= alpha[cp]*dg[cp][i];
            }
        }

        for (i = 0; i < n; i++)
        {
            p[i] *= diag;
        }

        /* And then go forward again */
        for (k = 0; k < ncorr; k++)
        {
            yr = 0;
            for (i = 0; i < n; i++)
            {
                yr += p[i]*dg[cp][i];
            }

            beta = rho[cp]*yr;
            beta = alpha[cp]-beta;

            for (i = 0; i < n; i++)
            {
                p[i] += beta*dx[cp][i];
            }

            cp++;
            if (cp >= ncorr)
            {
                cp = 0;
            }
        }

        for (i = 0; i < n; i++)
        {
            if (!frozen[i])
            {
                dx[point][i] = p[i];
            }
            else
            {
                dx[point][i] = 0;
            }
        }

        /* 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, ems.epot, ems.fnorm/sqrtNumAtoms, ems.fmax, ems.a_fmax + 1);
                fflush(stderr);
            }
            /* Store the new (lower) energies */
            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);
            do_log = do_per_step(step, inputrec->nstlog);
            do_ene = do_per_step(step, inputrec->nstenergy);
            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 x and E to IMD client, if bIMD is TRUE. */
        if (do_IMD(inputrec->bIMD, step, cr, TRUE, state_global->box, as_rvec_array(state_global->x.data()), inputrec, 0, wcycle) && MASTER(cr))
        {
            IMD_send_positions(inputrec->imd);
        }

        // Reset stepsize in we are doing more iterations
        stepsize = 1.0/ems.fnorm;

        /* Stop when the maximum force lies below tolerance.
         * If we have reached machine precision, converged is already set to true.
         */
        converged = converged || (ems.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 (ems.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 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 anythin 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).
     */
    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, ftp2fn(efSTO, nfile, fnm),
                  top_global, inputrec, step,
                  &ems, state_global, observablesHistory);

    if (MASTER(cr))
    {
        double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));
        print_converged(stderr, LBFGS, inputrec->em_tol, step, converged,
                        number_steps, &ems, sqrtNumAtoms);
        print_converged(fplog, LBFGS, inputrec->em_tol, step, converged,
                        number_steps, &ems, 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 steepest descents 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_walltime_accounting_t walltime_accounting)
 */
double do_steep(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       *SD = "Steepest Descents";
    gmx_localtop_t   *top;
    gmx_enerdata_t   *enerd;
    gmx_global_stat_t gstat;
    t_graph          *graph;
    real              stepsize;
    real              ustep;
    gmx_mdoutf_t      outf;
    t_mdebin         *mdebin;
    gmx_bool          bDone, bAbort, do_x, do_f;
    tensor            vir, pres;
    rvec              mu_tot;
    int               nsteps;
    int               count          = 0;
    int               steps_accepted = 0;
    auto              mdatoms        = mdAtoms->mdatoms();

    /* Create 2 states on the stack and extract pointers that we will swap */
    em_state_t  s0 {}, s1 {};
    em_state_t *s_min = &s0;
    em_state_t *s_try = &s1;

    /* Init em and store the local state in s_try */
    init_em(fplog, SD, cr, outputProvider, inputrec, mdrunOptions,
            state_global, top_global, s_try, &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, SD);

    /* Set variables for stepsize (in nm). This is the largest
     * step that we are going to make in any direction.
     */
    ustep    = inputrec->em_stepsize;
    stepsize = 0;

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

    if (MASTER(cr))
    {
        /* Print to the screen  */
        sp_header(stderr, SD, inputrec->em_tol, nsteps);
    }
    if (fplog)
    {
        sp_header(fplog, SD, inputrec->em_tol, nsteps);
    }

    /**** HERE STARTS THE LOOP ****
     * count is the counter for the number of steps
     * bDone will be TRUE when the minimization has converged
     * bAbort will be TRUE when nsteps steps have been performed or when
     * the stepsize becomes smaller than is reasonable for machine precision
     */
    count  = 0;
    bDone  = FALSE;
    bAbort = FALSE;
    while (!bDone && !bAbort)
    {
        bAbort = (nsteps >= 0) && (count == nsteps);

        /* set new coordinates, except for first step */
        bool validStep = true;
        if (count > 0)
        {
            validStep =
                do_em_step(cr, inputrec, mdatoms, fr->bMolPBC,
                           s_min, stepsize, &s_min->f, s_try,
                           constr, top, nrnb, wcycle, count);
        }

        if (validStep)
        {
            evaluate_energy(fplog, cr,
                            top_global, s_try, top,
                            inputrec, nrnb, wcycle, gstat,
                            vsite, constr, fcd, graph, mdAtoms, fr,
                            mu_tot, enerd, vir, pres, count, count == 0);
        }
        else
        {
            // Signal constraint error during stepping with energy=inf
            s_try->epot = std::numeric_limits<real>::infinity();
        }

        if (MASTER(cr))
        {
            print_ebin_header(fplog, count, count);
        }

        if (count == 0)
        {
            s_min->epot = s_try->epot;
        }

        /* Print it if necessary  */
        if (MASTER(cr))
        {
            if (mdrunOptions.verbose)
            {
                fprintf(stderr, "Step=%5d, Dmax= %6.1e nm, Epot= %12.5e Fmax= %11.5e, atom= %d%c",
                        count, ustep, s_try->epot, s_try->fmax, s_try->a_fmax+1,
                        ( (count == 0) || (s_try->epot < s_min->epot) ) ? '\n' : '\r');
                fflush(stderr);
            }

            if ( (count == 0) || (s_try->epot < s_min->epot) )
            {
                /* Store the new (lower) energies  */
                upd_mdebin(mdebin, FALSE, FALSE, (double)count,
                           mdatoms->tmass, enerd, &s_try->s, inputrec->fepvals, inputrec->expandedvals,
                           s_try->s.box, nullptr, nullptr, vir, pres, nullptr, mu_tot, constr);

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

                print_ebin(mdoutf_get_fp_ene(outf), TRUE,
                           do_per_step(steps_accepted, inputrec->nstdisreout),
                           do_per_step(steps_accepted, inputrec->nstorireout),
                           fplog, count, count, eprNORMAL,
                           mdebin, fcd, &(top_global->groups), &(inputrec->opts), nullptr);
                fflush(fplog);
            }
        }

        /* Now if the new energy is smaller than the previous...
         * or if this is the first step!
         * or if we did random steps!
         */

        if ( (count == 0) || (s_try->epot < s_min->epot) )
        {
            steps_accepted++;

            /* Test whether the convergence criterion is met...  */
            bDone = (s_try->fmax < inputrec->em_tol);

            /* Copy the arrays for force, positions and energy  */
            /* The 'Min' array always holds the coords and forces of the minimal
               sampled energy  */
            swap_em_state(&s_min, &s_try);
            if (count > 0)
            {
                ustep *= 1.2;
            }

            /* Write to trn, if necessary */
            do_x = do_per_step(steps_accepted, inputrec->nstxout);
            do_f = do_per_step(steps_accepted, inputrec->nstfout);
            write_em_traj(fplog, cr, outf, do_x, do_f, nullptr,
                          top_global, inputrec, count,
                          s_min, state_global, observablesHistory);
        }
        else
        {
            /* If energy is not smaller make the step smaller...  */
            ustep *= 0.5;

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

        /* Determine new step  */
        stepsize = ustep/s_min->fmax;

        /* Check if stepsize is too small, with 1 nm as a characteristic length */
#if GMX_DOUBLE
        if (count == nsteps || ustep < 1e-12)
#else
        if (count == nsteps || ustep < 1e-6)
#endif
        {
            if (MASTER(cr))
            {
                warn_step(stderr, inputrec->em_tol, count == nsteps, constr != nullptr);
                warn_step(fplog, inputrec->em_tol, count == nsteps, constr != nullptr);
            }
            bAbort = TRUE;
        }

        /* Send IMD energies and positions, if bIMD is TRUE. */
        if (do_IMD(inputrec->bIMD, count, cr, TRUE, state_global->box,
                   MASTER(cr) ? as_rvec_array(state_global->x.data()) : nullptr,
                   inputrec, 0, wcycle) &&
            MASTER(cr))
        {
            IMD_send_positions(inputrec->imd);
        }

        count++;
    }   /* End of the loop  */

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

    /* Print some data...  */
    if (MASTER(cr))
    {
        fprintf(stderr, "\nwriting lowest energy coordinates.\n");
    }
    write_em_traj(fplog, cr, outf, TRUE, inputrec->nstfout, ftp2fn(efSTO, nfile, fnm),
                  top_global, inputrec, count,
                  s_min, state_global, observablesHistory);

    if (MASTER(cr))
    {
        double sqrtNumAtoms = sqrt(static_cast<double>(state_global->natoms));

        print_converged(stderr, SD, inputrec->em_tol, count, bDone, nsteps,
                        s_min, sqrtNumAtoms);
        print_converged(fplog, SD, inputrec->em_tol, count, bDone, nsteps,
                        s_min, sqrtNumAtoms);
    }

    finish_em(cr, outf, walltime_accounting, wcycle);

    /* To print the actual number of steps we needed somewhere */
    inputrec->nsteps = count;

    walltime_accounting_set_nsteps_done(walltime_accounting, count);

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

/*! \brief Do normal modes analysis
    \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_walltime_accounting_t walltime_accounting)
 */
double do_nm(FILE *fplog, t_commrec *cr, const gmx::MDLogger &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 gmx_unused *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          *NM = "Normal Mode Analysis";
    gmx_mdoutf_t         outf;
    int                  nnodes, node;
    gmx_localtop_t      *top;
    gmx_enerdata_t      *enerd;
    gmx_global_stat_t    gstat;
    t_graph             *graph;
    tensor               vir, pres;
    rvec                 mu_tot;
    rvec                *fneg, *dfdx;
    gmx_bool             bSparse; /* use sparse matrix storage format */
    size_t               sz;
    gmx_sparsematrix_t * sparse_matrix           = nullptr;
    real           *     full_matrix             = nullptr;

    /* added with respect to mdrun */
    int                       row, col;
    real                      der_range = 10.0*sqrt(GMX_REAL_EPS);
    real                      x_min;
    bool                      bIsMaster = MASTER(cr);
    auto                      mdatoms   = mdAtoms->mdatoms();

    if (constr != nullptr)
    {
        gmx_fatal(FARGS, "Constraints present with Normal Mode Analysis, this combination is not supported");
    }

    gmx_shellfc_t *shellfc;

    em_state_t     state_work {};

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

    std::vector<size_t> atom_index = get_atom_index(top_global);
    snew(fneg, atom_index.size());
    snew(dfdx, atom_index.size());

#if !GMX_DOUBLE
    if (bIsMaster)
    {
        fprintf(stderr,
                "NOTE: This version of GROMACS has been compiled in single precision,\n"
                "      which MIGHT not be accurate enough for normal mode analysis.\n"
                "      GROMACS now uses sparse matrix storage, so the memory requirements\n"
                "      are fairly modest even if you recompile in double precision.\n\n");
    }
#endif

    /* Check if we can/should use sparse storage format.
     *
     * Sparse format is only useful when the Hessian itself is sparse, which it
     * will be when we use a cutoff.
     * For small systems (n<1000) it is easier to always use full matrix format, though.
     */
    if (EEL_FULL(fr->ic->eeltype) || fr->rlist == 0.0)
    {
        GMX_LOG(mdlog.warning).appendText("Non-cutoff electrostatics used, forcing full Hessian format.");
        bSparse = FALSE;
    }
    else if (atom_index.size() < 1000)
    {
        GMX_LOG(mdlog.warning).appendTextFormatted("Small system size (N=%d), using full Hessian format.",
                                                   atom_index.size());
        bSparse = FALSE;
    }
    else
    {
        GMX_LOG(mdlog.warning).appendText("Using compressed symmetric sparse Hessian format.");
        bSparse = TRUE;
    }

    /* Number of dimensions, based on real atoms, that is not vsites or shell */
    sz = DIM*atom_index.size();

    fprintf(stderr, "Allocating Hessian memory...\n\n");

    if (bSparse)
    {
        sparse_matrix = gmx_sparsematrix_init(sz);
        sparse_matrix->compressed_symmetric = TRUE;
    }
    else
    {
        snew(full_matrix, sz*sz);
    }

    init_nrnb(nrnb);

    where();

    /* Write start time and temperature */
    print_em_start(fplog, cr, walltime_accounting, wcycle, NM);

    /* fudge nr of steps to nr of atoms */
    inputrec->nsteps = atom_index.size()*2;

    if (bIsMaster)
    {
        fprintf(stderr, "starting normal mode calculation '%s'\n%d steps.\n\n",
                *(top_global->name), (int)inputrec->nsteps);
    }

    nnodes = cr->nnodes;

    /* Make evaluate_energy do a single node force calculation */
    cr->nnodes = 1;
    evaluate_energy(fplog, cr,
                    top_global, &state_work, top,
                    inputrec, nrnb, wcycle, gstat,
                    vsite, constr, fcd, graph, mdAtoms, fr,
                    mu_tot, enerd, vir, pres, -1, TRUE);
    cr->nnodes = nnodes;

    /* if forces are not small, warn user */
    get_state_f_norm_max(cr, &(inputrec->opts), mdatoms, &state_work);

    GMX_LOG(mdlog.warning).appendTextFormatted("Maximum force:%12.5e", state_work.fmax);
    if (state_work.fmax > 1.0e-3)
    {
        GMX_LOG(mdlog.warning).appendText(
                "The force is probably not small enough to "
                "ensure that you are at a minimum.\n"
                "Be aware that negative eigenvalues may occur\n"
                "when the resulting matrix is diagonalized.");
    }

    /***********************************************************
     *
     *      Loop over all pairs in matrix
     *
     *      do_force called twice. Once with positive and
     *      once with negative displacement
     *
     ************************************************************/

    /* Steps are divided one by one over the nodes */
    bool bNS = true;
    for (unsigned int aid = cr->nodeid; aid < atom_index.size(); aid += nnodes)
    {
        size_t atom = atom_index[aid];
        for (size_t d = 0; d < DIM; d++)
        {
            gmx_bool    bBornRadii  = FALSE;
            gmx_int64_t step        = 0;
            int         force_flags = GMX_FORCE_STATECHANGED | GMX_FORCE_ALLFORCES;
            double      t           = 0;

            x_min = state_work.s.x[atom][d];

            for (unsigned int dx = 0; (dx < 2); dx++)
            {
                if (dx == 0)
                {
                    state_work.s.x[atom][d] = x_min - der_range;
                }
                else
                {
                    state_work.s.x[atom][d] = x_min + der_range;
                }

                /* Make evaluate_energy do a single node force calculation */
                cr->nnodes = 1;
                if (shellfc)
                {
                    /* Now is the time to relax the shells */
                    (void) relax_shell_flexcon(fplog, cr, mdrunOptions.verbose, step,
                                               inputrec, bNS, force_flags,
                                               top,
                                               constr, enerd, fcd,
                                               &state_work.s, &state_work.f, vir, mdatoms,
                                               nrnb, wcycle, graph, &top_global->groups,
                                               shellfc, fr, bBornRadii, t, mu_tot,
                                               vsite,
                                               DdOpenBalanceRegionBeforeForceComputation::no,
                                               DdCloseBalanceRegionAfterForceComputation::no);
                    bNS = false;
                    step++;
                }
                else
                {
                    evaluate_energy(fplog, cr,
                                    top_global, &state_work, top,
                                    inputrec, nrnb, wcycle, gstat,
                                    vsite, constr, fcd, graph, mdAtoms, fr,
carlocamilloni's avatar
carlocamilloni committed
                                    mu_tot, enerd, vir, pres, aid*2+dx, FALSE);
carlocamilloni's avatar
carlocamilloni committed
                }

                cr->nnodes = nnodes;

                if (dx == 0)
                {
                    for (size_t i = 0; i < atom_index.size(); i++)
                    {
                        copy_rvec(state_work.f[atom_index[i]], fneg[i]);
                    }
                }
            }

            /* x is restored to original */